File size: 3,252 Bytes
166c438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""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}")