自動車・データ実務

まず試験 CSV の時間軸と単位を確認する

合成の demonstration data で units、missing values、finite numbers、duplicate または reversed timestamps を確認し、その後 check results と chart を保存します。

目次を表示

この翻訳はAIで作成しました。コード、単位、数値は原文と併せて確認してください。各言語のネイティブ話者による校閲は、まだ完了していません。 English

対象読者Python で初めて vehicle test CSV を読むエンジニアと初学者向けです。

準備するもの
  • Python 3.12 と terminal を用意します。python --version で version を確認してください。
  • ダウンロードした ZIP 全体を展開し、example.py がある folder で terminal を開きます。
  • まず付属の practice data で始め、その後 results を original files と比較します。
  • 付属の synthetic_test.csv は synthetic demonstration data です。time には s、speed には km/h を使用しています。

01chart を作る前に確認する4つのこと

まず synthetic demonstration data の file structure, numbers, units, time order を確認します。values を読めることだけでは、units が正しいことや times が正しいことは分かりません。この例では、すべての input row に s と km/h が記載されていることと、original row order で time が増加していることを確認します。

02input CSV を読む

Column含まれる値と意味
dataset_noteSynthetic demonstration data
time0.0 から 1.0 までの elapsed time
time_units
speed0 から 22 までの speed values
speed_unitkm/h

numeric cells に unit strings を付けないでください。units は別の column に記録します。time は negative にできず、少なくとも2 samples が必要です。この code では speed の physically normal range は定義しません。

03files を準備して example を実行する

  1. ZIP を展開し、README.txt に記載された input file が example.py と同じ folder にあることを確認します。ZIP archive 内から example を実行しないでください。
  2. example.py がある folder で、以下の commands を1行ずつ実行します。Windows で python が使えず py が使える場合は、各 command の python を py -3.12 に置き換えます。
  3. completion message が表示されたら、新しい outputs folder を開きます。outputs がすでに存在する場合は、previous results を保持するため先に rename してから example を再実行します。
bash
python --version
python -m pip install -r requirements.txt
python example.py

installation には internet connection が必要です。code 内の BASE は current terminal folder ではなく example.py を基準に input と output paths を設定します。

04完全な code と停止条件

CSV の各 row を読むときに missing values と units を確認します。math.isfinite は NaN と infinity を拒否します。current time が previous time 以下の場合は停止するため、sort して問題を隠したり、duplicate samples を任意に削除したりしません。outputs は input check が完了した後にだけ作成されます。

example.py
"""Check time order and declared units in explanatory synthetic test data.

This demonstrates file checks only. It makes no vehicle safety assessment.
"""
import csv
import json
import math
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

BASE = Path(__file__).resolve().parent
HEADERS = ["dataset_note", "time", "time_unit", "speed", "speed_unit"]
NOTE = "설명용 합성 데이터"


def read_samples():
    samples = []
    with (BASE / "synthetic_test.csv").open(encoding="utf-8-sig", newline="") as file:
        reader = csv.DictReader(file)
        if reader.fieldnames != HEADERS:
            raise ValueError(f"Expected headers: {HEADERS}")
        for line, row in enumerate(reader, start=2):
            if None in row or any(value is None or not value.strip() for value in row.values()):
                raise ValueError(f"Row {line}: missing or extra field.")
            if row["dataset_note"] != NOTE:
                raise ValueError(f"Row {line}: explanatory synthetic-data label is required.")
            if row["time_unit"] != "s" or row["speed_unit"] != "km/h":
                raise ValueError(f"Row {line}: expected units s and km/h; no automatic conversion.")
            time, speed = float(row["time"]), float(row["speed"])
            if not math.isfinite(time) or not math.isfinite(speed):
                raise ValueError(f"Row {line}: NaN and infinite values are not supported.")
            if time < 0:
                raise ValueError(f"Row {line}: elapsed time must be nonnegative.")
            if samples and time <= samples[-1][0]:
                raise ValueError(f"Row {line}: duplicate or decreasing time; check the source.")
            samples.append((time, speed))
    if len(samples) < 2:
        raise ValueError("At least two samples are required.")
    return samples


def main():
    destination = BASE / "outputs"
    if destination.exists():
        raise ValueError("outputs already exists; rename it before running again.")
    samples = read_samples()
    times, speeds = zip(*samples)
    intervals = [right - left for left, right in zip(times, times[1:])]
    report = {
        "dataset_note": NOTE,
        "scope": "File structure and numeric checks only; no vehicle safety assessment.",
        "sample_count": len(samples), "time_unit": "s", "speed_unit": "km/h",
        "start_time": times[0], "end_time": times[-1],
        "min_interval_s": min(intervals), "max_interval_s": max(intervals),
        "min_speed_kmh": min(speeds), "max_speed_kmh": max(speeds),
        "time_strictly_increasing": True,
    }
    figure, axis = plt.subplots(figsize=(8, 4.6), layout="constrained")
    axis.plot(times, speeds, "o-", color="#2B6578", linewidth=2)
    axis.set(title="Speed trace | Explanatory synthetic data", xlabel="Elapsed time (s)", ylabel="Speed (km/h)")
    axis.spines[["top", "right"]].set_visible(False)
    axis.grid(alpha=0.2)
    destination.mkdir(exist_ok=False)
    with (destination / "data_check.json").open("x", encoding="utf-8") as file:
        json.dump(report, file, ensure_ascii=False, indent=2)
    figure.savefig(destination / "synthetic_speed.png", dpi=160)
    plt.close(figure)
    print(f"Explanatory synthetic data: {len(samples)} samples, {times[0]:g}-{times[-1]:g} s.")
    print(f"Sample interval: {min(intervals):g}-{max(intervals):g} s; units: s, km/h.")
    print("Created outputs/data_check.json and outputs/synthetic_speed.png.")


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, csv.Error) as error:
        raise SystemExit(f"Stopped: {error}") from error

05results と chart を確認する

outputs/data_check.json には units, number of samples, time range, minimum and maximum sampling interval が記録されます。outputs/synthetic_speed.png は同じ synthetic demonstration data の chart です。

項目付属 synthetic demonstration data の結果
Samples6
Time range0.0~1.0 s
Sampling intervalAbout 0.2 s
Speed minimum / maximum0 / 22 km/h
Time increasingtrue
Speed curve of synthetic demonstration data. Time 0–1 s, speed 0–22 km/h.
Speed curve of synthetic demonstration data. Time 0–1 s, speed 0–22 km/h.

floating-point representation のため、JSON の sampling interval が 0.19999999999999996 と表示される場合があります。これは input values や measurement resolution に追加の precision があると主張する数値ではありません。

06自分で errors を入れてテストする

  1. normal result の sample_count が 6、time_unit が s であることを確認します。
  2. 新しく展開した practice folder で、3つ目の data row の time を previous value と同じ 0.2 に変更します。実行すると duplicate or decreasing time message で停止するはずです。
  3. 別の fresh copy で speed_unit の1つを m/s に変更します。expected units message が表示され、outputs が作成されないことを確認します。
  4. original input file は保持し、error experiments は copies だけで行います。

07check が停止したときに確認すること

Messageoriginal で確認すること
expected units s and km/hexport settings が各 row の units と一致しているか確認します。code は自動変換しません。
duplicate or decreasing timerestart, duplicate samples, file merging の途中で time order が変わっていないか確認します。
NaN and infinite valuesoriginal に missing samples や calculation errors がないか確認します。
synthetic-data label is requiredこの tutorial 専用の synthetic demonstration data であることを示す label を保持します。
missing or extra fieldcommas の数、blank cells、column names を確認します。

08check に合格した後も必要な確認

  • time interval が一定であるという rule は強制しません。min_interval_s と max_interval_s が異なる場合は、original の sampling period を別途確認してください。
  • filtering, interpolation, unit conversion, sensor calibration, time synchronization, noise judgments は行いません。
  • unit columns の notation だけを確認します。actual values が本当にその unit で測定されたか、sensor が正しい channel にあるかは確認できません。
  • これは付属 data に限定した file-handling practice です。実際の vehicle test procedures や safety judgments に使用できる validation tool と解釈しないでください。

実行・検証の記録

Windows 11 (10.0.26200), CPython 3.12.14 (64-bit). openpyxl 3.1.5, Matplotlib 3.10.8. 各 example で使用する libraries は requirements.txt に固定されています。

  • synthetic demonstration data 6 samples、time range、units、intervals を確認しました
  • unit mismatch, duplicate or reversed times, NaN, missing values の errors を確認しました
  • original hash が変更されないこと、existing results が拒否されること、PNG が作成されることを確認しました
検証範囲の限界
  • synthetic demonstration data だけを確認しました。real measurement data と vehicle safety は評価していません。

サイト全体の執筆・検証方針

自分で実行するためのサンプルファイル

コード、入力データ、実行手順が含まれています。展開して、まずREADME.txtを読んでください。

サンプルZIPをダウンロード

サンプルコード、ファイル名、入力キーは原文のままです。翻訳本文のコマンドと確認手順も併せて参照してください。

独自に作成した練習用資料 · 元のファイルを別に保管してから実行してください。

参考資料

説明と例は独自に作成しました。関連する動作や概念は、以下の公式資料で確認できます。