#!/usr/bin/env python3 import argparse import json import os import re import time from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path import numpy as np TRIAL_RE = re.compile(r"trial_(\d+)\.npy$") def trial_id_from_path(p: Path) -> int: m = TRIAL_RE.search(p.name) return int(m.group(1)) if m else -1 def _convert_one_class(class_dir_s: str, out_root_s: str, target_len: int, out_dtype: str, verbose_every: int): class_dir = Path(class_dir_s) out_root = Path(out_root_s) paths = sorted(class_dir.glob("trial_*.npy"), key=trial_id_from_path) if not paths: return { "class_name": class_dir.name, "num_traces": 0, "target_len": int(target_len), "dtype": out_dtype, "elapsed_sec": 0.0, "source_length_histogram": {}, } cls_out = out_root / class_dir.name cls_out.mkdir(parents=True, exist_ok=True) dtype = np.float16 if out_dtype == "float16" else np.float32 n = len(paths) traces_out = cls_out / "traces.npy" ids_out = cls_out / "trial_ids.npy" mm = np.lib.format.open_memmap(traces_out, mode="w+", dtype=dtype, shape=(n, int(target_len))) ids = np.empty((n,), dtype=np.int32) length_hist = {} cache = {} t0 = time.time() for i, p in enumerate(paths, start=1): x = np.load(p).astype(np.float32, copy=False) src_len = int(len(x)) length_hist[src_len] = int(length_hist.get(src_len, 0)) + 1 if src_len == int(target_len): y = x else: cached = cache.get(src_len) if cached is None: src_idx = np.arange(src_len, dtype=np.float32) dst_idx = np.linspace(0, max(0, src_len - 1), int(target_len), dtype=np.float32) cached = (src_idx, dst_idx) cache[src_len] = cached src_idx, dst_idx = cached y = np.interp(dst_idx, src_idx, x).astype(np.float32, copy=False) if dtype == np.float16: mm[i - 1] = y.astype(np.float16, copy=False) else: mm[i - 1] = y ids[i - 1] = int(trial_id_from_path(p)) if verbose_every > 0 and (i % int(verbose_every) == 0): print("[{}] {}/{}".format(class_dir.name, i, n), flush=True) mm.flush() np.save(ids_out, ids) meta = { "class_name": class_dir.name, "num_traces": int(n), "target_len": int(target_len), "dtype": out_dtype, "elapsed_sec": float(time.time() - t0), "source_length_histogram": {str(k): int(v) for k, v in sorted(length_hist.items())}, } with open(cls_out / "meta.json", "w") as f: json.dump(meta, f, indent=2) return meta def main(): p = argparse.ArgumentParser(description="Downsample raw trace files to fixed length") p.add_argument("--source-traces", required=True, help="Path to source traces root (contains expert_* dirs)") p.add_argument("--output-root", required=True, help="Path to output dataset root") p.add_argument("--target-len", type=int, default=16384) p.add_argument("--dtype", choices=["float32", "float16"], default="float32") p.add_argument("--workers", type=int, default=max(1, min(8, (os.cpu_count() or 4)))) p.add_argument("--verbose-every", type=int, default=1000) args = p.parse_args() src = Path(os.path.expanduser(args.source_traces)).resolve() out_root = Path(os.path.expanduser(args.output_root)).resolve() out_root.mkdir(parents=True, exist_ok=True) class_dirs = sorted([d for d in src.iterdir() if d.is_dir()]) if not class_dirs: raise RuntimeError("No class directories found under {}".format(src)) run_t0 = time.time() # Copy capture metadata if present parent = src.parent cap_meta = parent / "capture_meta.json" if cap_meta.exists(): with open(cap_meta, "rb") as fin, open(out_root / "capture_meta.json", "wb") as fout: fout.write(fin.read()) print("[info] classes={} target_len={} dtype={} workers={}".format(len(class_dirs), args.target_len, args.dtype, args.workers), flush=True) results = [] if int(args.workers) <= 1: for d in class_dirs: print("[start] {}".format(d.name), flush=True) r = _convert_one_class(str(d), str(out_root), int(args.target_len), str(args.dtype), int(args.verbose_every)) print("[done] {} traces={} elapsed={:.1f}s".format(d.name, r["num_traces"], r["elapsed_sec"]), flush=True) results.append(r) else: with ProcessPoolExecutor(max_workers=int(args.workers)) as ex: futs = { ex.submit( _convert_one_class, str(d), str(out_root), int(args.target_len), str(args.dtype), int(args.verbose_every), ): d.name for d in class_dirs } for fut in as_completed(futs): name = futs[fut] r = fut.result() print("[done] {} traces={} elapsed={:.1f}s".format(name, r["num_traces"], r["elapsed_sec"]), flush=True) results.append(r) results = sorted(results, key=lambda x: x["class_name"]) total_traces = int(sum(r["num_traces"] for r in results)) summary = { "source_traces": str(src), "output_root": str(out_root), "target_len": int(args.target_len), "dtype": str(args.dtype), "workers": int(args.workers), "classes": [r["class_name"] for r in results], "class_count": int(len(results)), "total_traces": total_traces, "runtime_sec": float(time.time() - run_t0), "per_class": results, } with open(out_root / "downsample_summary.json", "w") as f: json.dump(summary, f, indent=2) print("[all-done] total_traces={} runtime={:.1f}s".format(total_traces, summary["runtime_sec"]), flush=True) if __name__ == "__main__": main()