"""Shared CSV validation and non-overwriting output helpers.""" import argparse import os from contextlib import contextmanager from pathlib import Path import tempfile import numpy as np import pandas as pd def parser(description): return argparse.ArgumentParser(description=description) def require(df, columns): missing = set(columns) - set(df.columns) if missing: raise ValueError(f"Missing columns: {sorted(missing)}") def numeric(df, columns, integer=False): require(df, columns) for col in columns: values = pd.to_numeric(df[col], errors="raise") if not np.isfinite(values.to_numpy(dtype=float)).all(): raise ValueError(f"Non-finite values in {col}") if integer: if not (values == np.floor(values)).all(): raise ValueError(f"Non-integer values in {col}") values = values.astype("int64") df[col] = values def unique(df, keys): require(df, keys) if df[keys].isna().any().any() or df.duplicated(keys).any(): raise ValueError(f"Missing or duplicate keys: {keys}") def lane_direction(df, allow_missing=False): """Validate lane indices and direction labels; reconstruction may fill missing observations.""" require(df, ["Lane number", "Direction"]) lanes = pd.to_numeric(df["Lane number"], errors="raise") observed = lanes.dropna().to_numpy(dtype=float) if not np.isfinite(observed).all() or np.any(observed <= 0) or np.any(observed != np.floor(observed)): raise ValueError("Lane number must be a positive integer") if not df.Direction.dropna().isin(["Left", "Right"]).all(): raise ValueError("Direction must be Left or Right") if not allow_missing and (lanes.isna().any() or df.Direction.isna().any()): raise ValueError("Lane and Direction cannot be missing") df["Lane number"] = lanes def read_csv(path): df = pd.read_csv(path, encoding="utf-8-sig") if df.empty: raise ValueError(f"Empty input: {path}") return df def preflight_outputs(*paths): """Reject colliding or existing destinations before a multi-output run.""" resolved = [Path(path).resolve() for path in paths] if len(set(resolved)) != len(resolved): raise ValueError("Output destinations must be distinct") for path in resolved: if path.exists(): raise FileExistsError(f"Output exists; choose a new filename: {path}") @contextmanager def output_path(path): path = Path(path) if path.exists(): raise FileExistsError(f"Output exists; choose a new filename: {path}") path.parent.mkdir(parents=True, exist_ok=True) handle, temporary = tempfile.mkstemp(prefix=path.name + ".", dir=path.parent) os.close(handle) try: yield temporary if path.exists(): raise FileExistsError(path) os.replace(temporary, path) finally: if os.path.exists(temporary): os.unlink(temporary) def save_csv(df, path): with output_path(path) as temporary: df.to_csv(temporary, index=False, encoding="utf-8-sig") print(f"Saved {len(df):,} rows: {path}")