Compare multiple test conditions on the same time axis
Validate three synthetic demonstration CSV files, then overlay curves that share the same time samples and acceleration units on one chart.
Check units, missing values, finite numbers, and duplicate or reversed timestamps in synthetic demonstration data, then save the check results and a chart.
This translation was generated by AI. Check the code, units, and numbers against the original. Native-speaker review has not yet been completed for each language. 한국어
Who this is forEngineers and beginners reading a vehicle test CSV with Python for the first time
First check the file structure, numbers, units, and time order of the synthetic demonstration data. Being able to read the values does not tell you that the units are right or the times are correct. This example checks that s and km/h are stated in every input row and that time increases in the original row order.
| Column | Included values and meaning |
|---|---|
| dataset_note | Synthetic demonstration data |
| time | Elapsed time from 0.0 to 1.0 |
| time_unit | s |
| speed | Speed values from 0 to 22 |
| speed_unit | km/h |
Do not attach unit strings to numeric cells. Record units in a separate column. time cannot be negative, and at least two samples are required. This code does not define a physically normal range for speed.
python --version
python -m pip install -r requirements.txt
python example.pyInstallation requires an internet connection. BASE in the code sets the input and output paths relative to example.py, not the current terminal folder.
While reading each row of the CSV, it checks for missing values and units. math.isfinite rejects NaN and infinity. If the current time is less than or equal to the previous time, it stops, so it does not hide problems by sorting or arbitrarily delete duplicate samples. outputs is created only after the input check is finished.
"""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
outputs/data_check.json records the units, number of samples, time range, and the minimum and maximum sampling interval. outputs/synthetic_speed.png is a chart of the same synthetic demonstration data.
| Item | Results for the included synthetic demonstration data |
|---|---|
| Samples | 6 |
| Time range | 0.0~1.0 s |
| Sampling interval | About 0.2 s |
| Speed minimum / maximum | 0 / 22 km/h |
| Time increasing | true |

Because of floating-point representation, the sampling interval in the JSON may appear as 0.19999999999999996. It is not a number that claims any additional precision of the input values or measurement resolution.
| Message | What to check in the original |
|---|---|
| expected units s and km/h | Check that the export settings match the units in each row. The code does not convert automatically. |
| duplicate or decreasing time | Check whether the time order changed during a restart, duplicate samples, or file merging. |
| NaN and infinite values | Check the original for missing samples or calculation errors. |
| synthetic-data label is required | Keep the label marking it as synthetic demonstration data for this tutorial only. |
| missing or extra field | Check the number of commas, blank cells, and column names. |
Windows 11 (10.0.26200), CPython 3.12.14 (64-bit). openpyxl 3.1.5, Matplotlib 3.10.8. The libraries used by each example are pinned in requirements.txt.
Includes code, input data, and instructions. Extract the ZIP and read README.txt first.
Download example ZIPExample code, filenames, and input keys remain unchanged. Refer to the commands and checking steps in the translated article as well.
The explanations and examples were written for this site. See the official sources below for the related behavior and concepts.