File size: 10,309 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""Seeded exact dense-bin sampling and the author's pooled sparse-bin grouping."""
from collections import Counter, defaultdict
import json
from pathlib import Path
import shutil
import sqlite3
import tempfile
import numpy as np
import pandas as pd
from _common import numeric, output_path, parser, unique, preflight_outputs

INPUT_COLUMNS = ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "x_local", "y_local", "v_rel", "cangle"]
OUTPUT_COLUMNS = INPUT_COLUMNS + ["round_v", "Sample_Group_ID"]


def read_chunks(path, chunksize):
    last_frame, boundary = None, set()
    with pd.read_csv(path, usecols=INPUT_COLUMNS, chunksize=chunksize) as reader:
        for chunk in reader:
            numeric(chunk, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID", "cangle"], integer=True)
            numeric(chunk, ["x_local", "y_local", "v_rel"])
            unique(chunk, ["Frame", "EV_Vehicle_ID", "POV_Vehicle_ID"])
            if not len(chunk):
                continue
            if not chunk.Frame.is_monotonic_increasing or (last_frame is not None and chunk.Frame.iloc[0] < last_frame):
                raise ValueError("Candidate CSV must be sorted by Frame")
            if last_frame is not None:
                keys = set(map(tuple, chunk.loc[chunk.Frame.eq(last_frame), ["EV_Vehicle_ID", "POV_Vehicle_ID"]].to_numpy()))
                if boundary & keys:
                    raise ValueError("Duplicate pair/frame across CSV chunks")
            tail = set(map(tuple, chunk.loc[chunk.Frame.eq(chunk.Frame.iloc[-1]), ["EV_Vehicle_ID", "POV_Vehicle_ID"]].to_numpy()))
            boundary = boundary | tail if last_frame == chunk.Frame.iloc[-1] else tail
            last_frame = chunk.Frame.iloc[-1]
            if not chunk.cangle.isin([0, 1]).all() or chunk.v_rel.le(0).any() or chunk.EV_Vehicle_ID.eq(chunk.POV_Vehicle_ID).any():
                raise ValueError("Require binary cangle, positive relative speed, and distinct vehicle IDs")
            yield chunk


def balance(input_path, output, audit_path, target=50000, max_relative_speed=30., seed=42, chunksize=500000, work_dir=None):
    if target < 1 or int(target) != target or chunksize < 1 or not np.isfinite(max_relative_speed) or max_relative_speed <= 0:
        raise ValueError("Require positive integer target/chunksize and finite positive maximum speed")
    preflight_outputs(output, audit_path)
    if Path(output).resolve() == Path(audit_path).resolve() or Path(audit_path).exists():
        raise FileExistsError("Choose distinct new output and audit filenames")
    source = Path(input_path)
    initial_stat = (source.stat().st_size, source.stat().st_mtime_ns)
    counts, input_rows, excluded = Counter(), 0, 0
    for chunk in read_chunks(source, chunksize):
        input_rows += len(chunk)
        excluded += int(chunk.v_rel.gt(max_relative_speed).sum())
        chunk = chunk.loc[chunk.v_rel.le(max_relative_speed)].copy()
        chunk["round_v"] = np.round(chunk.v_rel, 1)
        counts.update({(int(c), float(v)): int(n) for (c, v), n in chunk.groupby(["cangle", "round_v"]).size().items()})
    if not counts:
        raise ValueError("No eligible candidate records at or below the maximum relative speed")
    if not any(n >= target for n in counts.values()) and not any(sum(n for (c, _), n in counts.items() if c == category) >= target for category in (0, 1)):
        raise ValueError("Insufficient observations to form any complete fitting group; no balanced CSV written")
    rng = np.random.default_rng(seed)
    selected = {key: np.sort(rng.choice(count, target, replace=False)) for key, count in sorted(counts.items()) if count >= target}
    offsets = defaultdict(int)
    groups, dropped_sparse = [], {}
    dense_rows = 0
    if work_dir is not None:
        Path(work_dir).mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix="pair_balance_", dir=work_dir) as temporary_dir:
        dense_path = Path(temporary_dir) / "dense.csv"
        con = sqlite3.connect(Path(temporary_dir) / "sparse.sqlite")
        try:
            con.execute("CREATE TABLE sparse (ordinal INTEGER PRIMARY KEY, Frame INTEGER, EV_Vehicle_ID INTEGER, POV_Vehicle_ID INTEGER, x_local REAL, y_local REAL, v_rel REAL, cangle INTEGER)")
            ordinal = 0
            for chunk in read_chunks(source, chunksize):
                chunk = chunk.loc[chunk.v_rel.le(max_relative_speed)].copy()
                chunk["round_v"] = np.round(chunk.v_rel, 1)
                for key, group in chunk.groupby(["cangle", "round_v"], sort=True):
                    key = int(key[0]), float(key[1])
                    if key in selected:
                        start, stop = offsets[key], offsets[key] + len(group)
                        choice = selected[key]
                        local = choice[(choice >= start) & (choice < stop)] - start
                        part = group.iloc[local].copy()
                        part["Sample_Group_ID"] = f"dense_{key[0]}_{int(round(key[1] * 10))}"
                        if len(part):
                            part[OUTPUT_COLUMNS].to_csv(dense_path, mode="a", header=not dense_path.exists(), index=False)
                            dense_rows += len(part)
                        offsets[key] = stop
                    else:
                        records = [(ordinal + i, int(r.Frame), int(r.EV_Vehicle_ID), int(r.POV_Vehicle_ID), float(r.x_local), float(r.y_local), float(r.v_rel), int(r.cangle)) for i, r in enumerate(group[INPUT_COLUMNS].itertuples(index=False))]
                        con.executemany("INSERT INTO sparse VALUES (?,?,?,?,?,?,?,?)", records)
                        ordinal += len(records)
                con.commit()
            if (source.stat().st_size, source.stat().st_mtime_ns) != initial_stat:
                raise ValueError("Input changed between sampling passes")
            if any(offsets[key] != counts[key] for key in selected) or dense_rows != len(selected) * target:
                raise RuntimeError("Sampling counts changed; refusing an incomplete dense sample")
            for (cangle, speed), size in sorted(counts.items()):
                if (cangle, speed) in selected:
                    groups.append({"Sample_Group_ID": f"dense_{cangle}_{int(round(speed * 10))}", "cangle": cangle, "round_v": speed,
                                   "kind": "dense_rounded_bin", "input_count": size, "output_count": target})
            con.execute("CREATE INDEX sparse_speed ON sparse(cangle,v_rel,ordinal)")
            with output_path(output) as temporary:
                if dense_path.exists():
                    shutil.copyfile(dense_path, temporary)
                else:
                    pd.DataFrame(columns=OUTPUT_COLUMNS).to_csv(temporary, index=False)
                for category in (0, 1):
                    cursor = con.execute("SELECT Frame,EV_Vehicle_ID,POV_Vehicle_ID,x_local,y_local,v_rel,cangle FROM sparse WHERE cangle=? ORDER BY v_rel,ordinal", (category,))
                    index = 0
                    while True:
                        records = cursor.fetchmany(target)
                        if len(records) < target:
                            dropped_sparse[str(category)] = len(records)
                            break
                        group = pd.DataFrame.from_records(records, columns=INPUT_COLUMNS)
                        group["round_v"] = float(np.round(group.v_rel.mean(), 1))
                        group["Sample_Group_ID"] = f"sparse_{category}_{index}"
                        group[OUTPUT_COLUMNS].to_csv(temporary, mode="a", header=False, index=False)
                        groups.append({"Sample_Group_ID": f"sparse_{category}_{index}", "cangle": category, "round_v": float(group.round_v.iloc[0]),
                                       "kind": "pooled_sparse_sorted_block", "input_count": target, "output_count": target,
                                       "v_min": float(group.v_rel.min()), "v_max": float(group.v_rel.max())})
                        index += 1
        finally:
            con.close()
    keys = Counter((g["cangle"], g["round_v"]) for g in groups)
    audit = {"input_rows": input_rows, "input_bytes": initial_stat[0], "excluded_above_max_relative_speed": excluded,
             "max_relative_speed_mps": max_relative_speed, "target_samples": target, "seed": seed,
             "dense_sampling": "Exact uniform sampling without replacement; RNG PCG64; deterministic for this row order and seed",
             "sparse_grouping": "Pool nondense bins within category; sort by v_rel then original order; full target-sized blocks; drop final remainder",
             "sparse_remainder_discarded": dropped_sparse, "groups": groups, "output_rows": len(groups) * target,
             "representative_key_collisions": [{"cangle": c, "round_v": v, "group_count": n} for (c, v), n in keys.items() if n > 1],
             "historical_sample_identity": "Original script had no seed. This seeded sample cannot be claimed identical to historical samples."}
    with output_path(audit_path) as temporary:
        Path(temporary).write_text(json.dumps(audit, indent=2, allow_nan=False), encoding="utf-8")
    return audit


def main():
    p = parser(__doc__)
    p.add_argument("--input", required=True, help="Frame-sorted full candidate-pair CSV")
    p.add_argument("--output", required=True, help="New balanced sample CSV; use only for fitting")
    p.add_argument("--audit", required=True, help="New JSON group counts, discarded remainders and key collisions")
    p.add_argument("--target-samples", type=int, default=50000, help="Original production value: 50000")
    p.add_argument("--max-relative-speed", type=float, default=30., help="Original fitting cutoff in m/s; not the annotation cutoff")
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--chunksize", type=int, default=500000)
    p.add_argument("--work-dir", help="Writable scratch directory for sparse rows; needs disk capacity")
    a = p.parse_args()
    balance(a.input, a.output, a.audit, a.target_samples, a.max_relative_speed, a.seed, a.chunksize, a.work_dir)


if __name__ == "__main__":
    main()