From 5a2802aaab41fe351f0a34ac1920f51f30589e1f Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 01:08:32 +0530 Subject: [PATCH 1/5] feat(ml): evaluation harness v2 with per-domain Wilson-CI metrics, frozen test hash and end-to-end netlist metrics Extend ml/evaluate.py: per-class and per-domain P/R/F1/accuracy with Wilson CIs, confusion matrix, small-object (junction) recall, one JSON and one Markdown report per run, and a legacy ultralytics block that reproduces the old eval_test.json exactly. Runs refuse to start when the frozen test split hash differs from ml/frozen_sets.json. End-to-end metrics (--gt-netlists/--pred-netlists): net precision/recall/F1 over pin pairs, netlist exact-match rate and truth-table equivalence via DigiSim's own simulate() (ml/sim_bridge). Commits the gate12 baseline (ml/baselines/gate12.json) and the gate12_test frozen-set entry; weights and images stay out of git. --- agent_docs/ml-pipeline.md | 16 + ml/baselines/gate12.json | 1987 +++++++++++++++++++++++++++++++++ ml/eval_frozen.py | 194 ++++ ml/eval_metrics.py | 337 ++++++ ml/eval_netlist.py | 552 +++++++++ ml/eval_report.py | 275 +++++ ml/evaluate.py | 451 +++++++- ml/frozen_sets.json | 24 + ml/pyproject.toml | 5 + ml/sim_bridge/truth_table.cjs | 93 ++ ml/tests/conftest.py | 61 + ml/tests/test_baselines.py | 47 + ml/tests/test_eval_frozen.py | 81 ++ ml/tests/test_eval_metrics.py | 110 ++ ml/tests/test_eval_netlist.py | 176 +++ ml/tests/test_evaluate.py | 104 ++ ml/uv.lock | 96 +- 17 files changed, 4556 insertions(+), 53 deletions(-) create mode 100644 ml/baselines/gate12.json create mode 100644 ml/eval_frozen.py create mode 100644 ml/eval_metrics.py create mode 100644 ml/eval_netlist.py create mode 100644 ml/eval_report.py create mode 100644 ml/frozen_sets.json create mode 100644 ml/sim_bridge/truth_table.cjs create mode 100644 ml/tests/conftest.py create mode 100644 ml/tests/test_baselines.py create mode 100644 ml/tests/test_eval_frozen.py create mode 100644 ml/tests/test_eval_metrics.py create mode 100644 ml/tests/test_eval_netlist.py create mode 100644 ml/tests/test_evaluate.py diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index 54dde54..505e279 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -48,6 +48,22 @@ Tier B classes are trained after phase 4. Current phase: `ml/experiments/current_phase.txt` +## Evaluation (harness v2) +`cd ml && uv run python evaluate.py --weights W.pt --data DATASET/data.yaml --frozen-name NAME` writes one JSON and one Markdown report +(`ml/experiments/eval/.json|.md`, gitignored) with: +- **Detection:** per-class and per-domain precision / recall / F1 / accuracy with Wilson 95% CIs, confusion matrix, small-object (junction) recall, + at one operating confidence (default 0.35). "accuracy" = TP / GT instances of the class (the phase-gate number). Domains come from the image file + name prefix (`syn_` synthetic, `rf_` roboflow_real, `cghd_` cghd_real, `dss_` digisim_screenshot; add more with `--domain-rule PREFIX=name`). + Classes with fewer than 30 GT instances are labelled `low n` instead of judged. Models are scored in the dataset's vocabulary: predictions map by + class name, then by legacy alias (`ml/classes.yaml`); predictions with no counterpart are counted as `unmapped`. +- **Legacy block:** the original ultralytics validation numbers (mAP, max-F1 per class, confusion-matrix accuracy); `--reproduce OLD_eval_test.json` checks them. +- **End-to-end (optional):** `--gt-netlists DIR --pred-netlists DIR` (files `.json`, schema in `ml/eval_netlist.py`; T2 emits the ground truth, + T8 must emit predictions in it) gives net precision/recall/F1 over pin pairs (MOSFET bulk pins unscored), netlist exact-match rate, and truth-table + equivalence of the rebuilt circuit under DigiSim's own `simulate()` (`ml/sim_bridge/truth_table.cjs`; needs `cd frontend && npm install`; `--no-truth-table` skips it). +- **Frozen sets:** the test split's SHA-256 (images, labels, netlists, class names) must equal the entry in `ml/frozen_sets.json`, otherwise the run exits 3 and writes nothing. + Register a new set once with `--freeze --frozen-name NAME --freeze-note "..."`; tooling never overwrites an entry. +- **Baselines:** `ml/baselines/gate12.json` is the old 12-class model on the gate-era test split (`gate12_test`); compare a new run with `--baseline ml/baselines/gate12.json`. + ## Dataset - **Source:** Synthetic screenshots from DigiSim (primary) + hand-drawn images (supplement) - **Generation:** `backend/data_gen/screenshot_pipeline.py` diff --git a/ml/baselines/gate12.json b/ml/baselines/gate12.json new file mode 100644 index 0000000..d6ef033 --- /dev/null +++ b/ml/baselines/gate12.json @@ -0,0 +1,1987 @@ +{ + "schema": "digisim.eval/2", + "run": { + "name": "gate12", + "generated_at": "2026-11-17T19:36:59+00:00", + "weights": { + "name": "best.pt", + "sha256": "bc2e0c3313b4b973d738c51efb72a17cf4141d82ae563cff14bd75ef6cfa322f" + }, + "dataset": { + "frozen_name": "gate12_test", + "split": "test", + "images": 78, + "labels": 78, + "netlists": 0, + "sha256": "c261f9d325c708eceb1d54978d611685ed6be8464b3068926c100208025b83ca", + "classes": [ + "AND", + "OR", + "NOT", + "NAND", + "NOR", + "XOR", + "XNOR", + "SWITCH", + "INPUT", + "OUTPUT", + "LED", + "JUNCTION" + ] + }, + "params": { + "imgsz": 640, + "conf": 0.35, + "iou": 0.5, + "small_px": 24.0, + "device": "cpu" + } + }, + "detection": { + "conf": 0.35, + "iou_threshold": 0.5, + "model_classes": [ + "AND", + "OR", + "NOT", + "NAND", + "NOR", + "XOR", + "XNOR", + "SWITCH", + "INPUT", + "OUTPUT", + "LED", + "JUNCTION" + ], + "class_map": { + "AND": "AND", + "OR": "OR", + "NOT": "NOT", + "NAND": "NAND", + "NOR": "NOR", + "XOR": "XOR", + "XNOR": "XNOR", + "SWITCH": "SWITCH", + "INPUT": "INPUT", + "OUTPUT": "OUTPUT", + "LED": "LED", + "JUNCTION": "JUNCTION" + }, + "overall": { + "images": 78, + "gt": 569, + "tp": 562, + "fp": 4, + "fn": 7, + "precision": { + "value": 0.9929328621908127, + "ci95": [ + 0.981971, + 0.997248 + ], + "n": 566 + }, + "recall": { + "value": 0.9876977152899824, + "ci95": [ + 0.974826, + 0.994028 + ], + "n": 569 + }, + "f1": { + "value": 0.9903083700440528, + "ci95": [ + 0.982729, + 0.99458 + ], + "n": 1135 + }, + "unmapped_predictions": 0, + "small_object": { + "max_side_px": 24.0, + "recall": { + "value": 0.8888888888888888, + "ci95": [ + 0.564994, + 0.98011 + ], + "n": 9 + } + } + }, + "per_class": { + "AND": { + "gt": 36, + "tp": 36, + "fp": 1, + "fn": 0, + "precision": { + "value": 0.972972972972973, + "ci95": [ + 0.861756, + 0.995213 + ], + "n": 37 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.903578, + 1.0 + ], + "n": 36 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.903578, + 1.0 + ], + "n": 36 + }, + "f1": { + "value": 0.9863013698630136, + "ci95": [ + 0.926401, + 0.997578 + ], + "n": 73 + }, + "low_support": false + }, + "OR": { + "gt": 35, + "tp": 34, + "fp": 2, + "fn": 1, + "precision": { + "value": 0.9444444444444444, + "ci95": [ + 0.81855, + 0.98463 + ], + "n": 36 + }, + "recall": { + "value": 0.9714285714285714, + "ci95": [ + 0.854666, + 0.994939 + ], + "n": 35 + }, + "accuracy": { + "value": 0.9714285714285714, + "ci95": [ + 0.854666, + 0.994939 + ], + "n": 35 + }, + "f1": { + "value": 0.9577464788732394, + "ci95": [ + 0.882974, + 0.985527 + ], + "n": 71 + }, + "low_support": false + }, + "NOT": { + "gt": 32, + "tp": 32, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.892817, + 1.0 + ], + "n": 32 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.892817, + 1.0 + ], + "n": 32 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.892817, + 1.0 + ], + "n": 32 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.943374, + 1.0 + ], + "n": 64 + }, + "low_support": false + }, + "NAND": { + "gt": 32, + "tp": 31, + "fp": 0, + "fn": 1, + "precision": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "recall": { + "value": 0.96875, + "ci95": [ + 0.842554, + 0.994462 + ], + "n": 32 + }, + "accuracy": { + "value": 0.96875, + "ci95": [ + 0.842554, + 0.994462 + ], + "n": 32 + }, + "f1": { + "value": 0.9841269841269841, + "ci95": [ + 0.915413, + 0.997193 + ], + "n": 63 + }, + "low_support": false + }, + "NOR": { + "gt": 30, + "tp": 29, + "fp": 1, + "fn": 1, + "precision": { + "value": 0.9666666666666667, + "ci95": [ + 0.833292, + 0.994092 + ], + "n": 30 + }, + "recall": { + "value": 0.9666666666666667, + "ci95": [ + 0.833292, + 0.994092 + ], + "n": 30 + }, + "accuracy": { + "value": 0.9666666666666667, + "ci95": [ + 0.833292, + 0.994092 + ], + "n": 30 + }, + "f1": { + "value": 0.9666666666666667, + "ci95": [ + 0.88636, + 0.990811 + ], + "n": 60 + }, + "low_support": false + }, + "XOR": { + "gt": 32, + "tp": 31, + "fp": 0, + "fn": 1, + "precision": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "recall": { + "value": 0.96875, + "ci95": [ + 0.842554, + 0.994462 + ], + "n": 32 + }, + "accuracy": { + "value": 0.96875, + "ci95": [ + 0.842554, + 0.994462 + ], + "n": 32 + }, + "f1": { + "value": 0.9841269841269841, + "ci95": [ + 0.915413, + 0.997193 + ], + "n": 63 + }, + "low_support": false + }, + "XNOR": { + "gt": 28, + "tp": 28, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.879353, + 1.0 + ], + "n": 28 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.879353, + 1.0 + ], + "n": 28 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.879353, + 1.0 + ], + "n": 28 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.935804, + 1.0 + ], + "n": 56 + }, + "low_support": true + }, + "SWITCH": { + "gt": 68, + "tp": 68, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.946527, + 1.0 + ], + "n": 68 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.946527, + 1.0 + ], + "n": 68 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.946527, + 1.0 + ], + "n": 68 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.972529, + 1.0 + ], + "n": 136 + }, + "low_support": false + }, + "INPUT": { + "gt": 154, + "tp": 154, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.975662, + 1.0 + ], + "n": 154 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.975662, + 1.0 + ], + "n": 154 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.975662, + 1.0 + ], + "n": 154 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.987681, + 1.0 + ], + "n": 308 + }, + "low_support": false + }, + "OUTPUT": { + "gt": 50, + "tp": 49, + "fp": 0, + "fn": 1, + "precision": { + "value": 1.0, + "ci95": [ + 0.9273, + 1.0 + ], + "n": 49 + }, + "recall": { + "value": 0.98, + "ci95": [ + 0.895043, + 0.996461 + ], + "n": 50 + }, + "accuracy": { + "value": 0.98, + "ci95": [ + 0.895043, + 0.996461 + ], + "n": 50 + }, + "f1": { + "value": 0.98989898989899, + "ci95": [ + 0.944983, + 0.998215 + ], + "n": 99 + }, + "low_support": false + }, + "LED": { + "gt": 25, + "tp": 25, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.866804, + 1.0 + ], + "n": 25 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.866804, + 1.0 + ], + "n": 25 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.866804, + 1.0 + ], + "n": 25 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.92865, + 1.0 + ], + "n": 50 + }, + "low_support": true + }, + "JUNCTION": { + "gt": 47, + "tp": 45, + "fp": 0, + "fn": 2, + "precision": { + "value": 1.0, + "ci95": [ + 0.921346, + 1.0 + ], + "n": 45 + }, + "recall": { + "value": 0.9574468085106383, + "ci95": [ + 0.857512, + 0.988252 + ], + "n": 47 + }, + "accuracy": { + "value": 0.9574468085106383, + "ci95": [ + 0.857512, + 0.988252 + ], + "n": 47 + }, + "f1": { + "value": 0.9782608695652174, + "ci95": [ + 0.924164, + 0.994018 + ], + "n": 92 + }, + "low_support": false + } + }, + "per_domain": { + "roboflow_real": { + "overall": { + "images": 3, + "gt": 13, + "tp": 9, + "fp": 4, + "fn": 4, + "precision": { + "value": 0.6923076923076923, + "ci95": [ + 0.423689, + 0.873195 + ], + "n": 13 + }, + "recall": { + "value": 0.6923076923076923, + "ci95": [ + 0.423689, + 0.873195 + ], + "n": 13 + }, + "f1": { + "value": 0.6923076923076923, + "ci95": [ + 0.500114, + 0.834989 + ], + "n": 26 + }, + "unmapped_predictions": 0, + "small_object": { + "max_side_px": 24.0, + "recall": { + "value": null, + "ci95": null, + "n": 0 + } + } + }, + "per_class": { + "AND": { + "gt": 5, + "tp": 5, + "fp": 1, + "fn": 0, + "precision": { + "value": 0.8333333333333334, + "ci95": [ + 0.436491, + 0.969947 + ], + "n": 6 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.565509, + 1.0 + ], + "n": 5 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.565509, + 1.0 + ], + "n": 5 + }, + "f1": { + "value": 0.9090909090909091, + "ci95": [ + 0.622635, + 0.983768 + ], + "n": 11 + }, + "low_support": true + }, + "OR": { + "gt": 3, + "tp": 2, + "fp": 2, + "fn": 1, + "precision": { + "value": 0.5, + "ci95": [ + 0.150036, + 0.849964 + ], + "n": 4 + }, + "recall": { + "value": 0.6666666666666666, + "ci95": [ + 0.207655, + 0.93851 + ], + "n": 3 + }, + "accuracy": { + "value": 0.6666666666666666, + "ci95": [ + 0.207655, + 0.93851 + ], + "n": 3 + }, + "f1": { + "value": 0.5714285714285714, + "ci95": [ + 0.250454, + 0.841783 + ], + "n": 7 + }, + "low_support": true + }, + "NOT": { + "gt": 2, + "tp": 2, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.342372, + 1.0 + ], + "n": 2 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.342372, + 1.0 + ], + "n": 2 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.342372, + 1.0 + ], + "n": 2 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.5101, + 1.0 + ], + "n": 4 + }, + "low_support": true + }, + "NAND": { + "gt": 1, + "tp": 0, + "fp": 0, + "fn": 1, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "accuracy": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "f1": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "low_support": true + }, + "NOR": { + "gt": 1, + "tp": 0, + "fp": 1, + "fn": 1, + "precision": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "recall": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "accuracy": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "f1": { + "value": 0.0, + "ci95": [ + 0.0, + 0.657628 + ], + "n": 2 + }, + "low_support": true + }, + "XOR": { + "gt": 1, + "tp": 0, + "fp": 0, + "fn": 1, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "accuracy": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "f1": { + "value": 0.0, + "ci95": [ + 0.0, + 0.793457 + ], + "n": 1 + }, + "low_support": true + }, + "XNOR": { + "gt": 0, + "tp": 0, + "fp": 0, + "fn": 0, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": null, + "ci95": null, + "n": 0 + }, + "accuracy": { + "value": null, + "ci95": null, + "n": 0 + }, + "f1": { + "value": null, + "ci95": null, + "n": 0 + }, + "low_support": true + }, + "SWITCH": { + "gt": 0, + "tp": 0, + "fp": 0, + "fn": 0, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": null, + "ci95": null, + "n": 0 + }, + "accuracy": { + "value": null, + "ci95": null, + "n": 0 + }, + "f1": { + "value": null, + "ci95": null, + "n": 0 + }, + "low_support": true + }, + "INPUT": { + "gt": 0, + "tp": 0, + "fp": 0, + "fn": 0, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": null, + "ci95": null, + "n": 0 + }, + "accuracy": { + "value": null, + "ci95": null, + "n": 0 + }, + "f1": { + "value": null, + "ci95": null, + "n": 0 + }, + "low_support": true + }, + "OUTPUT": { + "gt": 0, + "tp": 0, + "fp": 0, + "fn": 0, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": null, + "ci95": null, + "n": 0 + }, + "accuracy": { + "value": null, + "ci95": null, + "n": 0 + }, + "f1": { + "value": null, + "ci95": null, + "n": 0 + }, + "low_support": true + }, + "LED": { + "gt": 0, + "tp": 0, + "fp": 0, + "fn": 0, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": null, + "ci95": null, + "n": 0 + }, + "accuracy": { + "value": null, + "ci95": null, + "n": 0 + }, + "f1": { + "value": null, + "ci95": null, + "n": 0 + }, + "low_support": true + }, + "JUNCTION": { + "gt": 0, + "tp": 0, + "fp": 0, + "fn": 0, + "precision": { + "value": null, + "ci95": null, + "n": 0 + }, + "recall": { + "value": null, + "ci95": null, + "n": 0 + }, + "accuracy": { + "value": null, + "ci95": null, + "n": 0 + }, + "f1": { + "value": null, + "ci95": null, + "n": 0 + }, + "low_support": true + } + } + }, + "synthetic": { + "overall": { + "images": 75, + "gt": 556, + "tp": 553, + "fp": 0, + "fn": 3, + "precision": { + "value": 1.0, + "ci95": [ + 0.993101, + 1.0 + ], + "n": 553 + }, + "recall": { + "value": 0.9946043165467626, + "ci95": [ + 0.984257, + 0.998163 + ], + "n": 556 + }, + "f1": { + "value": 0.9972948602344455, + "ci95": [ + 0.992077, + 0.99908 + ], + "n": 1109 + }, + "unmapped_predictions": 0, + "small_object": { + "max_side_px": 24.0, + "recall": { + "value": 0.8888888888888888, + "ci95": [ + 0.564994, + 0.98011 + ], + "n": 9 + } + } + }, + "per_class": { + "AND": { + "gt": 31, + "tp": 31, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.941654, + 1.0 + ], + "n": 62 + }, + "low_support": false + }, + "OR": { + "gt": 32, + "tp": 32, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.892817, + 1.0 + ], + "n": 32 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.892817, + 1.0 + ], + "n": 32 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.892817, + 1.0 + ], + "n": 32 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.943374, + 1.0 + ], + "n": 64 + }, + "low_support": false + }, + "NOT": { + "gt": 30, + "tp": 30, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.886483, + 1.0 + ], + "n": 30 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.886483, + 1.0 + ], + "n": 30 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.886483, + 1.0 + ], + "n": 30 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.939826, + 1.0 + ], + "n": 60 + }, + "low_support": false + }, + "NAND": { + "gt": 31, + "tp": 31, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.941654, + 1.0 + ], + "n": 62 + }, + "low_support": false + }, + "NOR": { + "gt": 29, + "tp": 29, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.883026, + 1.0 + ], + "n": 29 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.883026, + 1.0 + ], + "n": 29 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.883026, + 1.0 + ], + "n": 29 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.93788, + 1.0 + ], + "n": 58 + }, + "low_support": true + }, + "XOR": { + "gt": 31, + "tp": 31, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.889741, + 1.0 + ], + "n": 31 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.941654, + 1.0 + ], + "n": 62 + }, + "low_support": false + }, + "XNOR": { + "gt": 28, + "tp": 28, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.879353, + 1.0 + ], + "n": 28 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.879353, + 1.0 + ], + "n": 28 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.879353, + 1.0 + ], + "n": 28 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.935804, + 1.0 + ], + "n": 56 + }, + "low_support": true + }, + "SWITCH": { + "gt": 68, + "tp": 68, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.946527, + 1.0 + ], + "n": 68 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.946527, + 1.0 + ], + "n": 68 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.946527, + 1.0 + ], + "n": 68 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.972529, + 1.0 + ], + "n": 136 + }, + "low_support": false + }, + "INPUT": { + "gt": 154, + "tp": 154, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.975662, + 1.0 + ], + "n": 154 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.975662, + 1.0 + ], + "n": 154 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.975662, + 1.0 + ], + "n": 154 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.987681, + 1.0 + ], + "n": 308 + }, + "low_support": false + }, + "OUTPUT": { + "gt": 50, + "tp": 49, + "fp": 0, + "fn": 1, + "precision": { + "value": 1.0, + "ci95": [ + 0.9273, + 1.0 + ], + "n": 49 + }, + "recall": { + "value": 0.98, + "ci95": [ + 0.895043, + 0.996461 + ], + "n": 50 + }, + "accuracy": { + "value": 0.98, + "ci95": [ + 0.895043, + 0.996461 + ], + "n": 50 + }, + "f1": { + "value": 0.98989898989899, + "ci95": [ + 0.944983, + 0.998215 + ], + "n": 99 + }, + "low_support": false + }, + "LED": { + "gt": 25, + "tp": 25, + "fp": 0, + "fn": 0, + "precision": { + "value": 1.0, + "ci95": [ + 0.866804, + 1.0 + ], + "n": 25 + }, + "recall": { + "value": 1.0, + "ci95": [ + 0.866804, + 1.0 + ], + "n": 25 + }, + "accuracy": { + "value": 1.0, + "ci95": [ + 0.866804, + 1.0 + ], + "n": 25 + }, + "f1": { + "value": 1.0, + "ci95": [ + 0.92865, + 1.0 + ], + "n": 50 + }, + "low_support": true + }, + "JUNCTION": { + "gt": 47, + "tp": 45, + "fp": 0, + "fn": 2, + "precision": { + "value": 1.0, + "ci95": [ + 0.921346, + 1.0 + ], + "n": 45 + }, + "recall": { + "value": 0.9574468085106383, + "ci95": [ + 0.857512, + 0.988252 + ], + "n": 47 + }, + "accuracy": { + "value": 0.9574468085106383, + "ci95": [ + 0.857512, + 0.988252 + ], + "n": 47 + }, + "f1": { + "value": 0.9782608695652174, + "ci95": [ + 0.924164, + 0.994018 + ], + "n": 92 + }, + "low_support": false + } + } + } + }, + "confusion_matrix": { + "labels": [ + "AND", + "OR", + "NOT", + "NAND", + "NOR", + "XOR", + "XNOR", + "SWITCH", + "INPUT", + "OUTPUT", + "LED", + "JUNCTION", + "background" + ], + "rows": "predicted", + "columns": "ground_truth", + "matrix": [ + [ + 36, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 34, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 32, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 31, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 29, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1 + ], + [ + 0, + 0, + 0, + 0, + 0, + 31, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 28, + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 68, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 154, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 49, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 25, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 45, + 0 + ], + [ + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 2, + 0 + ] + ] + }, + "junction_recall": { + "value": 0.9574468085106383, + "ci95": [ + 0.857512, + 0.988252 + ], + "n": 47 + } + }, + "legacy": { + "split": "test", + "map50": 0.9921107927469747, + "map50_95": 0.9493556299956223, + "per_class": { + "AND": { + "f1": 0.9769255139495461, + "accuracy": 1.0 + }, + "OR": { + "f1": 0.9608146464016857, + "accuracy": 0.9714285714285714 + }, + "NOT": { + "f1": 0.9915914021061303, + "accuracy": 1.0 + }, + "NAND": { + "f1": 0.974301394895826, + "accuracy": 0.96875 + }, + "NOR": { + "f1": 0.9510496527237545, + "accuracy": 0.9666666666666667 + }, + "XOR": { + "f1": 0.9985330823729923, + "accuracy": 0.96875 + }, + "XNOR": { + "f1": 0.9889459269105559, + "accuracy": 1.0 + }, + "SWITCH": { + "f1": 0.9956153712677703, + "accuracy": 1.0 + }, + "INPUT": { + "f1": 0.9980431836272996, + "accuracy": 1.0 + }, + "OUTPUT": { + "f1": 0.9963330131391387, + "accuracy": 0.98 + }, + "LED": { + "f1": 0.9882367942891848, + "accuracy": 1.0 + }, + "JUNCTION": { + "f1": 0.9776970433928199, + "accuracy": 0.9574468085106383 + } + } + }, + "reproduction": { + "reference": "eval_test.json", + "tolerance": 0.02, + "rows": [ + { + "metric": "map50", + "reference": 0.9921107927469747, + "value": 0.9921107927469747, + "delta": 0.0 + }, + { + "metric": "map50_95", + "reference": 0.9493556299956223, + "value": 0.9493556299956223, + "delta": 0.0 + }, + { + "metric": "AND.f1", + "reference": 0.9769255139495461, + "value": 0.9769255139495461, + "delta": 0.0 + }, + { + "metric": "AND.accuracy", + "reference": 1.0, + "value": 1.0, + "delta": 0.0 + }, + { + "metric": "OR.f1", + "reference": 0.9608146464016857, + "value": 0.9608146464016857, + "delta": 0.0 + }, + { + "metric": "OR.accuracy", + "reference": 0.9714285714285714, + "value": 0.9714285714285714, + "delta": 0.0 + }, + { + "metric": "NOT.f1", + "reference": 0.9915914021061303, + "value": 0.9915914021061303, + "delta": 0.0 + }, + { + "metric": "NOT.accuracy", + "reference": 1.0, + "value": 1.0, + "delta": 0.0 + }, + { + "metric": "NAND.f1", + "reference": 0.974301394895826, + "value": 0.974301394895826, + "delta": 0.0 + }, + { + "metric": "NAND.accuracy", + "reference": 0.96875, + "value": 0.96875, + "delta": 0.0 + }, + { + "metric": "NOR.f1", + "reference": 0.9510496527237545, + "value": 0.9510496527237545, + "delta": 0.0 + }, + { + "metric": "NOR.accuracy", + "reference": 0.9666666666666667, + "value": 0.9666666666666667, + "delta": 0.0 + }, + { + "metric": "XOR.f1", + "reference": 0.9985330823729923, + "value": 0.9985330823729923, + "delta": 0.0 + }, + { + "metric": "XOR.accuracy", + "reference": 0.96875, + "value": 0.96875, + "delta": 0.0 + }, + { + "metric": "XNOR.f1", + "reference": 0.9889459269105559, + "value": 0.9889459269105559, + "delta": 0.0 + }, + { + "metric": "XNOR.accuracy", + "reference": 1.0, + "value": 1.0, + "delta": 0.0 + }, + { + "metric": "SWITCH.f1", + "reference": 0.9956153712677703, + "value": 0.9956153712677703, + "delta": 0.0 + }, + { + "metric": "SWITCH.accuracy", + "reference": 1.0, + "value": 1.0, + "delta": 0.0 + }, + { + "metric": "INPUT.f1", + "reference": 0.9980431836272996, + "value": 0.9980431836272996, + "delta": 0.0 + }, + { + "metric": "INPUT.accuracy", + "reference": 1.0, + "value": 1.0, + "delta": 0.0 + }, + { + "metric": "OUTPUT.f1", + "reference": 0.9963330131391387, + "value": 0.9963330131391387, + "delta": 0.0 + }, + { + "metric": "OUTPUT.accuracy", + "reference": 0.98, + "value": 0.98, + "delta": 0.0 + }, + { + "metric": "LED.f1", + "reference": 0.9882367942891848, + "value": 0.9882367942891848, + "delta": 0.0 + }, + { + "metric": "LED.accuracy", + "reference": 1.0, + "value": 1.0, + "delta": 0.0 + }, + { + "metric": "JUNCTION.f1", + "reference": 0.9776970433928199, + "value": 0.9776970433928199, + "delta": 0.0 + }, + { + "metric": "JUNCTION.accuracy", + "reference": 0.9574468085106383, + "value": 0.9574468085106383, + "delta": 0.0 + } + ], + "max_abs_delta": 0.0, + "missing": [], + "ok": true + }, + "baseline": { + "model": "gate12 - YOLOv8n, 12 gate-era classes (AND OR NOT NAND NOR XOR XNOR SWITCH INPUT OUTPUT LED JUNCTION), trained 2026-07-03 (run_20260703_2028)", + "weights": "not committed (gitignored); sha256 above identifies them", + "what_it_is": "Baseline row for the old gate-era detector on its own frozen test split (frozen set gate12_test). Every later model is compared against this file with: evaluate.py --baseline baselines/gate12.json", + "regenerate": "cd ml && uv run python evaluate.py --weights --data /data.yaml --frozen-name gate12_test --run-name gate12 --reproduce ", + "reproduces_old_numbers": true + } +} diff --git a/ml/eval_frozen.py b/ml/eval_frozen.py new file mode 100644 index 0000000..6156d86 --- /dev/null +++ b/ml/eval_frozen.py @@ -0,0 +1,194 @@ +""" +Module: eval_frozen.py +Purpose: Frozen-test-set integrity for the evaluation harness. Computes a deterministic SHA-256 + over a dataset split (every image, label and optional ground-truth netlist file plus the + class names) and compares it with the registry in ml/frozen_sets.json, so an evaluation + refuses to run when the frozen test set was edited, regenerated or re-labelled. + +Registry format (ml/frozen_sets.json): + {"": {"sha256": "...", "split": "test", "images": 78, "labels": 78, "netlists": 0, + "classes": [...], "note": "..."}} +""" + +import hashlib +import json +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path + +ML_DIR = Path(__file__).resolve().parent +DEFAULT_REGISTRY = ML_DIR / "frozen_sets.json" +IMAGE_SUFFIXES = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"}) + + +class FrozenSetError(RuntimeError): + """Raised when a frozen set is missing from the registry or its hash no longer matches.""" + + +@dataclass(frozen=True) +class SplitDigest: + """The digest of one dataset split and the file counts that went into it.""" + + sha256: str + images: int + labels: int + netlists: int + classes: tuple[str, ...] + + +def file_sha256(path: Path) -> str: + """ + SHA-256 of a file's bytes. + + Args: + path: File to hash. + Returns: + Lower-case hex digest. + """ + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def split_dirs(dataset_root: Path, split: str) -> tuple[Path, Path, Path]: + """ + The image, label and netlist directories of a split. + + Args: + dataset_root: Dataset root (the `path:` of data.yaml). + split: Split name such as 'test'. + Returns: + (images/, labels/, netlists/); the netlist directory may not exist. + """ + return dataset_root / "images" / split, dataset_root / "labels" / split, dataset_root / "netlists" / split + + +def hash_split(dataset_root: Path, split: str, class_names: Sequence[str]) -> SplitDigest: + """ + Deterministic digest of a dataset split. + + Args: + dataset_root: Dataset root directory. + split: Split name. + class_names: Class names in id order (label ids are meaningless without them). + Returns: + The SplitDigest. Only *.txt labels, image files and *.json netlists count; caches are ignored. + Raises: + FileNotFoundError: If the image or label directory does not exist. + """ + images_dir, labels_dir, netlists_dir = split_dirs(dataset_root, split) + for required in (images_dir, labels_dir): + if not required.is_dir(): + raise FileNotFoundError(f"Split directory missing: {required}") + entries: list[tuple[str, str]] = [] + counts = {"images": 0, "labels": 0, "netlists": 0} + for kind, folder, keep in ( + ("images", images_dir, lambda p: p.suffix.lower() in IMAGE_SUFFIXES), + ("labels", labels_dir, lambda p: p.suffix == ".txt"), + ("netlists", netlists_dir, lambda p: p.suffix == ".json"), + ): + if not folder.is_dir(): + continue + for path in sorted(folder.iterdir()): + if path.is_file() and keep(path): + entries.append((f"{kind}/{path.name}", file_sha256(path))) + counts[kind] += 1 + digest = hashlib.sha256() + digest.update(("classes\t" + json.dumps(list(class_names)) + "\n").encode()) + for rel, file_hash in sorted(entries): + digest.update(f"{rel}\t{file_hash}\n".encode()) + return SplitDigest( + sha256=digest.hexdigest(), + images=counts["images"], + labels=counts["labels"], + netlists=counts["netlists"], + classes=tuple(class_names), + ) + + +def load_registry(path: Path = DEFAULT_REGISTRY) -> dict[str, dict[str, object]]: + """ + Load the frozen-set registry. + + Args: + path: Registry JSON path. + Returns: + Mapping frozen name -> entry; empty when the file does not exist. + Raises: + ValueError: If the file is not a JSON object. + """ + if not path.exists(): + return {} + raw = json.loads(path.read_text()) + if not isinstance(raw, dict): + raise ValueError(f"{path}: expected a JSON object of frozen sets") + return raw + + +def infer_frozen_name(split: str, class_names: Sequence[str], registry_path: Path = DEFAULT_REGISTRY) -> str | None: + """ + The frozen set a run should be checked against when --frozen-name is omitted. + + Args: + split: Split being evaluated. + class_names: Class names of the dataset, in id order. + registry_path: Registry JSON path. + Returns: + The registry name when exactly one entry has this split and class list, otherwise None + (no match or an ambiguous match: the caller must ask for an explicit name). + """ + matches = [name for name, entry in load_registry(registry_path).items() if entry.get("split") == split and entry.get("classes") == list(class_names)] + return matches[0] if len(matches) == 1 else None + + +def verify_frozen(name: str, digest: SplitDigest, registry_path: Path = DEFAULT_REGISTRY) -> None: + """ + Refuse (raise) unless the split digest equals the registered frozen hash. + + Args: + name: Frozen set name in the registry. + digest: Digest computed from the dataset on disk. + registry_path: Registry JSON path. + Raises: + FrozenSetError: If the name is unregistered or the hash differs from the registered one. + """ + registry = load_registry(registry_path) + entry = registry.get(name) + if entry is None: + raise FrozenSetError(f"Frozen set {name!r} is not registered in {registry_path}; freeze it first with --freeze (deliberate, reviewed change)") + expected = str(entry.get("sha256", "")) + if expected != digest.sha256: + raise FrozenSetError( + f"Frozen set {name!r} changed: registered sha256 {expected[:16]}... but the dataset on disk hashes to {digest.sha256[:16]}... " + "The frozen test set must never be edited; refusing to evaluate." + ) + + +def freeze(name: str, digest: SplitDigest, split: str, note: str, registry_path: Path = DEFAULT_REGISTRY) -> None: + """ + Register a new frozen set. + + Args: + name: Frozen set name. + digest: Digest of the split to freeze. + split: Split the digest was computed from. + note: Free-text provenance (what the set is, where it came from). + registry_path: Registry JSON path. + Raises: + FrozenSetError: If the name is already registered (frozen sets are never overwritten by tooling). + """ + registry = load_registry(registry_path) + if name in registry: + raise FrozenSetError(f"Frozen set {name!r} already registered in {registry_path}; refusing to overwrite it") + registry[name] = { + "sha256": digest.sha256, + "split": split, + "images": digest.images, + "labels": digest.labels, + "netlists": digest.netlists, + "classes": list(digest.classes), + "note": note, + } + registry_path.write_text(json.dumps(registry, indent=2, sort_keys=True) + "\n") diff --git a/ml/eval_metrics.py b/ml/eval_metrics.py new file mode 100644 index 0000000..7cb4bd9 --- /dev/null +++ b/ml/eval_metrics.py @@ -0,0 +1,337 @@ +""" +Module: eval_metrics.py +Purpose: Pure (model-free) detection metrics for the evaluation harness: Wilson confidence + intervals, greedy IoU matching of predictions to ground truth, a confusion matrix + accumulator, per-class precision/recall/F1/accuracy records, per-domain splits and + small-object (junction) recall. Kept free of ultralytics/torch so it is unit-testable. + +Conventions: + - Boxes are pixel xyxy. Ground truth rows are [cls, x1, y1, x2, y2]; prediction rows are + [cls, conf, x1, y1, x2, y2]. A prediction class of -1 means "not in the dataset vocabulary". + - The confusion matrix has rows = predicted class and columns = ground-truth class, with the + extra last index meaning background: [background, gt] is a miss (false negative) and + [pred, background] is a spurious detection (false positive). This matches ultralytics. + - "accuracy" keeps the repo's definition (TP / ground-truth instances of the class), the + number the phase gate in agent_docs/ml-pipeline.md uses; it equals recall. +""" + +import math +import re +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field + +import numpy as np + +# Rows with fewer ground-truth instances than this are flagged "low support" in reports. +LOW_SUPPORT_N = 30 +# Default longest-side threshold (original-image pixels) below which a GT box counts as small. +# Junction dots are 10-17 px at ~1000 px width (agent_docs/ml-pipeline.md / run notes). +DEFAULT_SMALL_PX = 24.0 +IOU_MATCH_THRESHOLD = 0.5 + +# Filename-prefix rules mapping an image to its data domain. First match wins. +DEFAULT_DOMAIN_RULES: tuple[tuple[str, str], ...] = ( + ("syn_", "synthetic"), + ("rf_", "roboflow_real"), + ("cghd_", "cghd_real"), + ("dss_", "digisim_screenshot"), +) +UNKNOWN_DOMAIN = "unknown" + + +def wilson_interval(successes: int, total: int, z: float = 1.96) -> tuple[float, float] | None: + """ + Wilson score interval for a binomial proportion. + + Args: + successes: Number of successes (0 <= successes <= total). + total: Number of trials. + z: Normal quantile (1.96 for a 95% interval). + Returns: + (low, high) bounds in [0, 1], or None when total is 0. + Raises: + ValueError: If successes is outside [0, total]. + """ + if total < 0 or successes < 0 or successes > total: + raise ValueError(f"Invalid counts: {successes}/{total}") + if total == 0: + return None + p = successes / total + denom = 1.0 + z * z / total + centre = (p + z * z / (2 * total)) / denom + half = z * math.sqrt(p * (1 - p) / total + z * z / (4 * total * total)) / denom + return (max(0.0, centre - half), min(1.0, centre + half)) + + +def rate(successes: int, total: int) -> dict[str, object]: + """ + A proportion with its Wilson 95% interval, JSON-ready. + + Args: + successes: Numerator. + total: Denominator. + Returns: + Dict with value (None when total is 0), ci95 ([low, high] or None) and n (the denominator). + """ + ci = wilson_interval(successes, total) + return { + "value": successes / total if total else None, + "ci95": [round(ci[0], 6), round(ci[1], 6)] if ci else None, + "n": total, + } + + +def domain_for(image_name: str, rules: Sequence[tuple[str, str]] = DEFAULT_DOMAIN_RULES) -> str: + """ + Resolve an image file name to its data domain by filename prefix. + + Args: + image_name: Image file name (or stem). + rules: Ordered (prefix, domain) pairs; first match wins. + Returns: + The domain name, or UNKNOWN_DOMAIN when no prefix matches. + """ + for prefix, domain in rules: + if image_name.startswith(prefix): + return domain + return UNKNOWN_DOMAIN + + +def parse_domain_rule(text: str) -> tuple[str, str]: + """ + Parse a CLI `PREFIX=DOMAIN` rule. + + Args: + text: The raw argument, e.g. "cghd_=cghd_real". + Returns: + (prefix, domain). + Raises: + ValueError: If the text is not of the form PREFIX=DOMAIN with both parts non-empty. + """ + prefix, sep, domain = text.partition("=") + if not sep or not prefix or not re.fullmatch(r"[A-Za-z0-9_.-]+", domain): + raise ValueError(f"Domain rule must look like PREFIX=domain_name, got {text!r}") + return prefix, domain + + +def box_iou(a: np.ndarray, b: np.ndarray) -> np.ndarray: + """ + Pairwise IoU between two sets of xyxy boxes. + + Args: + a: (n, 4) array of boxes. + b: (m, 4) array of boxes. + Returns: + (n, m) IoU matrix (0 where the union is empty). + """ + if len(a) == 0 or len(b) == 0: + return np.zeros((len(a), len(b)), dtype=np.float64) + a = a.astype(np.float64) + b = b.astype(np.float64) + ix1 = np.maximum(a[:, None, 0], b[None, :, 0]) + iy1 = np.maximum(a[:, None, 1], b[None, :, 1]) + ix2 = np.minimum(a[:, None, 2], b[None, :, 2]) + iy2 = np.minimum(a[:, None, 3], b[None, :, 3]) + inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None) + area_a = (a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]) + area_b = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1]) + union = area_a[:, None] + area_b[None, :] - inter + return np.where(union > 0, inter / np.where(union > 0, union, 1.0), 0.0) + + +def match_boxes(gt: np.ndarray, pred: np.ndarray, iou_threshold: float = IOU_MATCH_THRESHOLD) -> list[tuple[int, int]]: + """ + One-to-one greedy matching of predictions to ground truth by descending IoU (class-agnostic). + + Args: + gt: (n, 5) rows [cls, x1, y1, x2, y2]. + pred: (m, 6) rows [cls, conf, x1, y1, x2, y2]. + iou_threshold: Minimum IoU for a pair to be considered. + Returns: + List of (gt_index, pred_index) pairs. + """ + if len(gt) == 0 or len(pred) == 0: + return [] + iou = box_iou(gt[:, 1:5], pred[:, 2:6]) + gi, pi = np.nonzero(iou >= iou_threshold) + if len(gi) == 0: + return [] + # Highest IoU first; ties broken by higher prediction confidence. + order = np.lexsort((-pred[pi, 1], -iou[gi, pi])) + used_gt: set[int] = set() + used_pred: set[int] = set() + pairs: list[tuple[int, int]] = [] + for k in order: + g, p = int(gi[k]), int(pi[k]) + if g in used_gt or p in used_pred: + continue + used_gt.add(g) + used_pred.add(p) + pairs.append((g, p)) + return pairs + + +@dataclass +class DetectionAccumulator: + """Accumulates the confusion matrix and small-object counters over many images.""" + + n_classes: int + small_px: float = DEFAULT_SMALL_PX + iou_threshold: float = IOU_MATCH_THRESHOLD + matrix: np.ndarray = field(init=False) + n_images: int = 0 + small_total: int = 0 + small_hits: int = 0 + unmapped_predictions: int = 0 + + def __post_init__(self) -> None: + """ + Allocate the (n_classes + 1) square confusion matrix. + """ + self.matrix = np.zeros((self.n_classes + 1, self.n_classes + 1), dtype=np.int64) + + def add_image(self, gt: np.ndarray, pred: np.ndarray) -> None: + """ + Match one image's predictions to its ground truth and update every counter. + + Args: + gt: (n, 5) rows [cls, x1, y1, x2, y2] (cls in [0, n_classes)). + pred: (m, 6) rows [cls, conf, x1, y1, x2, y2] already filtered by the operating confidence; + cls of -1 marks a class outside the dataset vocabulary. + Raises: + ValueError: If a ground-truth class id is out of range. + """ + bg = self.n_classes + self.n_images += 1 + if len(gt) and (gt[:, 0].min() < 0 or gt[:, 0].max() >= bg): + raise ValueError("Ground-truth class id out of range for this vocabulary") + pairs = match_boxes(gt, pred, self.iou_threshold) + matched_gt = {g for g, _ in pairs} + matched_pred = {p for _, p in pairs} + small = (np.maximum(gt[:, 3] - gt[:, 1], gt[:, 4] - gt[:, 2]) <= self.small_px) if len(gt) else np.zeros(0, dtype=bool) + for g, p in pairs: + gcls, pcls = int(gt[g, 0]), int(pred[p, 0]) + if pcls < 0: + self.matrix[bg, gcls] += 1 # matched by an out-of-vocabulary prediction: the GT is missed + else: + self.matrix[pcls, gcls] += 1 + if small[g] and pcls == gcls: + self.small_hits += 1 + for g in range(len(gt)): + if g not in matched_gt: + self.matrix[bg, int(gt[g, 0])] += 1 + for p in range(len(pred)): + if p in matched_pred: + continue + pcls = int(pred[p, 0]) + if pcls < 0: + self.unmapped_predictions += 1 + else: + self.matrix[pcls, bg] += 1 + self.small_total += int(small.sum()) + + def per_class(self, names: Sequence[str]) -> dict[str, dict[str, object]]: + """ + Per-class counts and metrics with Wilson CIs. + + Args: + names: Class names ordered by class id. + Returns: + Mapping class name -> record with gt, tp, fp, fn, precision, recall, accuracy, f1, low_support. + """ + out: dict[str, dict[str, object]] = {} + for c, name in enumerate(names): + tp = int(self.matrix[c, c]) + fp = int(self.matrix[c, :].sum()) - tp + gt_n = int(self.matrix[:, c].sum()) + fn = gt_n - tp + out[name] = { + "gt": gt_n, + "tp": tp, + "fp": fp, + "fn": fn, + "precision": rate(tp, tp + fp), + "recall": rate(tp, gt_n), + "accuracy": rate(tp, gt_n), + "f1": f1_record(tp, fp, fn), + "low_support": gt_n < LOW_SUPPORT_N, + } + return out + + def overall(self) -> dict[str, object]: + """ + Micro-averaged metrics over all classes plus the small-object recall. + + Returns: + Record with images, gt, tp, fp, fn, precision, recall, f1 and small_object. + """ + bg = self.n_classes + tp = int(np.trace(self.matrix[:bg, :bg])) + fp = int(self.matrix[:bg, :].sum()) - tp + gt_n = int(self.matrix[:, :bg].sum()) + fn = gt_n - tp + return { + "images": self.n_images, + "gt": gt_n, + "tp": tp, + "fp": fp, + "fn": fn, + "precision": rate(tp, tp + fp), + "recall": rate(tp, gt_n), + "f1": f1_record(tp, fp, fn), + "unmapped_predictions": self.unmapped_predictions, + "small_object": { + "max_side_px": self.small_px, + "recall": rate(self.small_hits, self.small_total), + }, + } + + def confusion(self, names: Sequence[str]) -> dict[str, object]: + """ + The confusion matrix with labels, rows = predicted, columns = ground truth. + + Args: + names: Class names ordered by class id. + Returns: + Dict with labels (names + "background"), axes description and the integer matrix. + """ + return { + "labels": [*names, "background"], + "rows": "predicted", + "columns": "ground_truth", + "matrix": self.matrix.tolist(), + } + + +def f1_record(tp: int, fp: int, fn: int) -> dict[str, object]: + """ + F1 with an approximate Wilson interval. + + F1 = 2TP / (2TP + FP + FN) is treated as a proportion over 2TP + FP + FN pseudo-trials, so the + interval is a heuristic (it ignores the correlation between precision and recall) but it shrinks + with support the same way the other intervals do. + + Args: + tp: True positives. + fp: False positives. + fn: False negatives. + Returns: + Dict with value, ci95 and n (as in rate()). + """ + return rate(2 * tp, 2 * tp + fp + fn) + + +def split_by_domain(image_names: Iterable[str], rules: Sequence[tuple[str, str]] = DEFAULT_DOMAIN_RULES) -> dict[str, list[str]]: + """ + Group image names by their domain. + + Args: + image_names: Image file names. + rules: Ordered (prefix, domain) rules. + Returns: + Mapping domain -> image names, domains in first-seen order. + """ + groups: dict[str, list[str]] = {} + for name in image_names: + groups.setdefault(domain_for(name, rules), []).append(name) + return groups diff --git a/ml/eval_netlist.py b/ml/eval_netlist.py new file mode 100644 index 0000000..86d5a5f --- /dev/null +++ b/ml/eval_netlist.py @@ -0,0 +1,552 @@ +""" +Module: eval_netlist.py +Purpose: End-to-end (image -> circuit) metrics for the evaluation harness. Compares a predicted + netlist with the ground-truth netlist of the same image: net precision/recall/F1 over + pin-pair connectivity, netlist exact-match rate, and truth-table equivalence after the + predicted circuit is rebuilt as a DigiSim canvas and simulated by DigiSim's own simulator + (frontend/src/logic/simulation, driven through ml/sim_bridge/truth_table.cjs). + +Netlist JSON schema (ground truth and predictions use the same shape; T2 emits it, T8 will emit it): + { + "components": [{"id": "MP1", "type": "pmos", "bbox": [x1, y1, x2, y2]}, ...], + "nets": [["MP1:d", "MN1:d", "Y:a"], ["IN:out", "MP1:g", "MN1:g"], ...] + } + - type is a frontend node type from ml/classes.yaml (nmos, pmos, vsource, ground, input, output, + andGate, ...). bbox is optional and, when present on every component of both sides, is used to + pair predicted components with ground-truth ones (same type, greedy IoU >= 0.5); otherwise + components are paired by identical id and type. + - A pin is ":" with the terminal names declared in ml/classes.yaml. + - A net is the set of pins that are electrically connected; nets sharing a pin are merged and + nets with fewer than two scored pins are ignored. MOSFET bulk pins are not scored by default + (the switch-level solver ignores them and 3-terminal symbols omit them). +""" + +import itertools +import json +import subprocess +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path + +import numpy as np + +from class_schema import load_schema +from eval_metrics import IOU_MATCH_THRESHOLD, LOW_SUPPORT_N, box_iou, domain_for, rate + +ML_DIR = Path(__file__).resolve().parent +BRIDGE_SCRIPT = ML_DIR / "sim_bridge" / "truth_table.cjs" +BRIDGE_TIMEOUT_S = 300 + +GATE_TYPES = frozenset({"andGate", "orGate", "notGate", "nandGate", "norGate", "xorGate", "xnorGate"}) +HANDLE_PREFIX_TYPES = frozenset({"nmos", "pmos", "vsource", "ground", "clockSource"}) +BULK_TERMINALS: frozenset[tuple[str, str]] = frozenset({("nmos", "b"), ("pmos", "b")}) +DEFAULT_SUPPLY_VOLTS = 5 + + +class NetlistError(ValueError): + """Raised when a netlist file or dict violates the schema.""" + + +class BridgeError(RuntimeError): + """Raised when the Node simulator bridge cannot run (node or frontend dependencies missing).""" + + +@dataclass(frozen=True) +class Component: + """One circuit component of a netlist.""" + + id: str + type: str + bbox: tuple[float, float, float, float] | None = None + + +@dataclass +class Netlist: + """A circuit as components plus nets (sets of pins ":").""" + + components: dict[str, Component] = field(default_factory=dict) + nets: list[frozenset[str]] = field(default_factory=list) + + +def node_terminals() -> dict[str, tuple[str, ...]]: + """ + Terminal names per frontend node type, from ml/classes.yaml. + + Returns: + Mapping node type -> terminals (the non-canvas 'junction' type is excluded). + """ + return {c.node_type: c.terminals for c in load_schema().classes if c.node_type != "junction"} + + +def parse_netlist(raw: Mapping[str, object], terminals: Mapping[str, Sequence[str]] | None = None) -> Netlist: + """ + Validate a netlist dict and normalise its nets. + + Args: + raw: Parsed netlist JSON. + terminals: Node type -> allowed terminals (defaults to the classes.yaml vocabulary). + Returns: + The Netlist, with nets that share a pin merged (duplicates and singletons are kept; scoring drops them). + Raises: + NetlistError: On unknown types, duplicate ids, malformed pins, or pins on unknown components/terminals. + """ + terms = terminals if terminals is not None else node_terminals() + comps_raw = raw.get("components") + nets_raw = raw.get("nets") + if not isinstance(comps_raw, list) or not isinstance(nets_raw, list): + raise NetlistError("netlist needs 'components' and 'nets' lists") + components: dict[str, Component] = {} + for entry in comps_raw: + if not isinstance(entry, dict) or not isinstance(entry.get("id"), str) or not isinstance(entry.get("type"), str): + raise NetlistError(f"malformed component {entry!r}") + cid, ctype = entry["id"], entry["type"] + if ctype not in terms: + raise NetlistError(f"component {cid}: unknown type {ctype!r}") + if cid in components or ":" in cid: + raise NetlistError(f"component id {cid!r} is duplicated or contains ':'") + bbox_raw = entry.get("bbox") + bbox: tuple[float, float, float, float] | None = None + if bbox_raw is not None: + if not isinstance(bbox_raw, list) or len(bbox_raw) != 4: + raise NetlistError(f"component {cid}: bbox must be [x1, y1, x2, y2]") + bbox = (float(bbox_raw[0]), float(bbox_raw[1]), float(bbox_raw[2]), float(bbox_raw[3])) + components[cid] = Component(cid, ctype, bbox) + parent: dict[str, str] = {} + + def find(pin: str) -> str: + """Union-find root of a pin.""" + parent.setdefault(pin, pin) + while parent[pin] != pin: + parent[pin] = parent[parent[pin]] + pin = parent[pin] + return pin + + for net in nets_raw: + if not isinstance(net, list) or not all(isinstance(p, str) for p in net): + raise NetlistError(f"malformed net {net!r}") + for pin in net: + cid, _, term = pin.partition(":") + if cid not in components or term not in terms[components[cid].type]: + raise NetlistError(f"pin {pin!r} does not name a terminal of a declared component") + find(pin) + for other in net[1:]: + parent[find(other)] = find(net[0]) + groups: dict[str, set[str]] = {} + for pin in parent: + groups.setdefault(find(pin), set()).add(pin) + return Netlist(components, [frozenset(g) for g in sorted(groups.values(), key=lambda s: sorted(s))]) + + +def load_netlist(path: Path) -> Netlist: + """ + Read and validate a netlist JSON file. + + Args: + path: Netlist JSON file. + Returns: + The parsed Netlist. + Raises: + NetlistError: If the file is not valid JSON or violates the schema. + FileNotFoundError: If the file does not exist. + """ + try: + raw = json.loads(path.read_text()) + except json.JSONDecodeError as exc: + raise NetlistError(f"{path}: invalid JSON: {exc}") from exc + if not isinstance(raw, dict): + raise NetlistError(f"{path}: expected a JSON object") + return parse_netlist(raw) + + +def match_components(gt: Netlist, pred: Netlist, mode: str = "auto", iou_threshold: float = IOU_MATCH_THRESHOLD) -> dict[str, str]: + """ + Pair predicted components with ground-truth components. + + Args: + gt: Ground-truth netlist. + pred: Predicted netlist. + mode: 'bbox' (IoU, same type), 'id' (same id and type) or 'auto' (bbox when every component of both + sides has one, otherwise id). + iou_threshold: Minimum IoU for bbox pairing. + Returns: + Mapping predicted component id -> ground-truth component id (one-to-one). + Raises: + ValueError: If mode is unknown, or 'bbox' is requested but a component has no bbox. + """ + if mode not in {"auto", "bbox", "id"}: + raise ValueError(f"Unknown match mode {mode!r}") + have_boxes = all(c.bbox for c in gt.components.values()) and all(c.bbox for c in pred.components.values()) + if mode == "bbox" and not have_boxes: + raise ValueError("bbox matching needs a bbox on every component of both netlists") + if mode == "id" or (mode == "auto" and not have_boxes): + return {pid: pid for pid, c in pred.components.items() if pid in gt.components and gt.components[pid].type == c.type} + gids, pids = list(gt.components), list(pred.components) + if not gids or not pids: + return {} + iou = box_iou( + _as_array([gt.components[g].bbox for g in gids]), + _as_array([pred.components[p].bbox for p in pids]), + ) + candidates = sorted( + ((float(iou[i, j]), i, j) for i in range(len(gids)) for j in range(len(pids)) if iou[i, j] >= iou_threshold and gt.components[gids[i]].type == pred.components[pids[j]].type), + reverse=True, + ) + mapping: dict[str, str] = {} + used_gt: set[str] = set() + for _, i, j in candidates: + if gids[i] in used_gt or pids[j] in mapping: + continue + used_gt.add(gids[i]) + mapping[pids[j]] = gids[i] + return mapping + + +def _as_array(boxes: Sequence[tuple[float, float, float, float] | None]) -> np.ndarray: + """ + Stack bboxes into an (n, 4) float array. + + Args: + boxes: Boxes (all non-None). + Returns: + numpy array of shape (n, 4). + """ + return np.asarray([b for b in boxes], dtype=np.float64).reshape(-1, 4) + + +def scored_nets(netlist: Netlist, score_bulk: bool = False) -> list[frozenset[str]]: + """ + Nets reduced to scored pins, dropping nets with fewer than two pins. + + Args: + netlist: Netlist to reduce. + score_bulk: Keep MOSFET bulk pins when True. + Returns: + List of pin sets with at least two pins. + """ + kept: list[frozenset[str]] = [] + for net in netlist.nets: + pins = frozenset(p for p in net if score_bulk or (netlist.components[p.partition(":")[0]].type, p.partition(":")[2]) not in BULK_TERMINALS) + if len(pins) >= 2: + kept.append(pins) + return kept + + +def remap_pins(nets: Sequence[frozenset[str]], mapping: Mapping[str, str]) -> list[frozenset[str]]: + """ + Rename predicted pins into ground-truth component ids; unmatched components get a 'pred~' prefix. + + Args: + nets: Predicted nets. + mapping: Predicted component id -> ground-truth component id. + Returns: + Nets expressed over ground-truth ids (unmatched pins can never equal a ground-truth pin). + """ + + def rename(pin: str) -> str: + """Rename one pin.""" + cid, _, term = pin.partition(":") + return f"{mapping[cid]}:{term}" if cid in mapping else f"pred~{cid}:{term}" + + return [frozenset(rename(p) for p in net) for net in nets] + + +def pin_pairs(nets: Sequence[frozenset[str]]) -> set[frozenset[str]]: + """ + Every unordered pin pair that shares a net. + + Args: + nets: Pin sets. + Returns: + Set of 2-element frozensets. + """ + return {frozenset(pair) for net in nets for pair in itertools.combinations(sorted(net), 2)} + + +def connectivity_scores(gt_pairs: set[frozenset[str]], pred_pairs: set[frozenset[str]]) -> dict[str, int]: + """ + Pin-pair counts behind net precision/recall. + + Args: + gt_pairs: Ground-truth connected pin pairs. + pred_pairs: Predicted connected pin pairs (already in ground-truth ids). + Returns: + Dict with tp, fp, fn. + """ + tp = len(gt_pairs & pred_pairs) + return {"tp": tp, "fp": len(pred_pairs) - tp, "fn": len(gt_pairs) - tp} + + +def prf(tp: int, fp: int, fn: int) -> dict[str, float | None]: + """ + Precision, recall and F1 from counts. + + Args: + tp: True positives. + fp: False positives. + fn: False negatives. + Returns: + Dict with precision, recall, f1 (None where the denominator is 0). + """ + p = tp / (tp + fp) if tp + fp else None + r = tp / (tp + fn) if tp + fn else None + f1 = 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else None + return {"precision": p, "recall": r, "f1": f1} + + +def to_digisim(netlist: Netlist, id_map: Mapping[str, str] | None = None) -> dict[str, list[dict[str, object]]]: + """ + Rebuild a netlist as a DigiSim (ReactFlow) canvas: nodes plus edges using the app's handle ids. + + Each net becomes a star of edges from one root pin to every other pin; the switch-level solver + unions edge endpoints, and gate-level evaluation follows driver -> consumer edges, so a driver + (gate `out` or `input` pin) is preferred as the root. + + Args: + netlist: Netlist to convert. + id_map: Optional component id renaming (used to put a prediction in ground-truth ids). + Returns: + Dict with 'nodes' and 'edges' lists. + """ + rename = id_map or {} + nodes = [] + for comp in netlist.components.values(): + nid = rename.get(comp.id, comp.id) + data: dict[str, object] = {"label": nid} + if comp.type == "input": + data["value"] = 0 + elif comp.type == "output": + data["value"] = 0 + elif comp.type == "vsource": + data["param"] = DEFAULT_SUPPLY_VOLTS + nodes.append({"id": nid, "type": comp.type, "position": {"x": 0, "y": 0}, "data": data}) + + def split(pin: str) -> tuple[str, str, str]: + """Return (node id, node type, terminal) of a pin.""" + cid, _, term = pin.partition(":") + return rename.get(cid, cid), netlist.components[cid].type, term + + def is_driver(pin: str) -> bool: + """True for a pin that drives a net in gate-level evaluation.""" + _, ntype, term = split(pin) + return (ntype == "input" and term == "out") or (ntype in GATE_TYPES and term == "out") + + def source_handle(pin: str) -> str | None: + """Source handle id for a pin.""" + _, ntype, term = split(pin) + return f"s:{term}" if ntype in HANDLE_PREFIX_TYPES else None + + def target_handle(pin: str) -> str | None: + """Target handle id for a pin.""" + _, ntype, term = split(pin) + if ntype in HANDLE_PREFIX_TYPES: + return f"t:{term}" + return term if ntype in GATE_TYPES else None + + edges = [] + for net in netlist.nets: + pins = sorted(net) + if len(pins) < 2: + continue + root = next((p for p in pins if is_driver(p)), None) or next((p for p in pins if split(p)[1] != "output"), pins[0]) + for pin in pins: + if pin == root: + continue + edges.append( + { + "id": f"e{len(edges)}", + "source": split(root)[0], + "sourceHandle": source_handle(root), + "target": split(pin)[0], + "targetHandle": target_handle(pin), + } + ) + return {"nodes": nodes, "edges": edges} + + +def run_truth_tables(circuits: Mapping[str, dict[str, list[dict[str, object]]]]) -> dict[str, dict[str, object]]: + """ + Simulate circuits with DigiSim's simulator (one Node process for the whole batch). + + Args: + circuits: Mapping circuit id -> {'nodes', 'edges'} as built by to_digisim(). + Returns: + Mapping circuit id -> {'inputs', 'outputs', 'rows'} or {'error': message}. + Raises: + BridgeError: If node or the frontend dependencies are unavailable, or the bridge crashes. + """ + payload = json.dumps({"circuits": [{"id": cid, **graph} for cid, graph in circuits.items()]}) + try: + proc = subprocess.run(["node", str(BRIDGE_SCRIPT)], input=payload, capture_output=True, text=True, timeout=BRIDGE_TIMEOUT_S, check=False) + except (FileNotFoundError, subprocess.TimeoutExpired) as exc: + raise BridgeError(f"cannot run the simulator bridge: {exc}") from exc + if proc.returncode != 0: + raise BridgeError(f"simulator bridge failed (is `cd frontend && npm install` done?): {proc.stderr.strip()[-500:]}") + try: + return json.loads(proc.stdout) + except json.JSONDecodeError as exc: + raise BridgeError(f"simulator bridge returned invalid JSON: {exc}") from exc + + +def tables_equivalent(gt_table: Mapping[str, object], pred_table: Mapping[str, object]) -> bool: + """ + Whether two truth tables are identical (same inputs, outputs and every row). + + Args: + gt_table: Ground-truth table from the bridge. + pred_table: Predicted table from the bridge. + Returns: + True when inputs, outputs and rows all match; False if either side errored. + """ + if "error" in gt_table or "error" in pred_table: + return False + return all(gt_table.get(k) == pred_table.get(k) for k in ("inputs", "outputs", "rows")) + + +@dataclass +class CircuitResult: + """Per-circuit end-to-end outcome (pin-pair counts, exact match, truth-table status).""" + + stem: str + domain: str + gt_components: int + pred_components: int + matched_components: int + tp: int + fp: int + fn: int + exact_match: bool + pred_error: str | None = None + # 'equivalent' | 'different' | 'gt_unsimulatable' | None (truth table not requested) + truth_table: str | None = None + truth_table_detail: str | None = None + + def to_dict(self) -> dict[str, object]: + """ + JSON-ready form of the record. + + Returns: + Dict with components, pairs, exact_match, pred_error and truth_table. + """ + return { + "domain": self.domain, + "components": {"gt": self.gt_components, "pred": self.pred_components, "matched": self.matched_components}, + "pairs": {"tp": self.tp, "fp": self.fp, "fn": self.fn}, + "exact_match": self.exact_match, + "pred_error": self.pred_error, + "truth_table": None if self.truth_table is None else {"status": self.truth_table, "detail": self.truth_table_detail}, + } + + +def evaluate_netlists( + gt_dir: Path, + pred_dir: Path, + truth_table: bool = True, + match_mode: str = "auto", + score_bulk: bool = False, +) -> dict[str, object]: + """ + End-to-end metrics over every ground-truth netlist in gt_dir. + + A missing or malformed prediction scores as an empty circuit (zero recall, no equivalence). + + Args: + gt_dir: Directory of ground-truth netlists named .json. + pred_dir: Directory of predicted netlists with the same stems. + truth_table: Also compute truth-table equivalence with DigiSim's simulator. + match_mode: Component pairing mode (see match_components). + score_bulk: Score MOSFET bulk pins too. + Returns: + Dict with per-circuit records, micro/macro net P/R/F1, exact-match rate and truth-table equivalence + rate (with Wilson CIs), overall and per domain. + Raises: + FileNotFoundError: If gt_dir does not exist or holds no netlists. + NetlistError: If a ground-truth netlist is malformed. + BridgeError: If truth-table equivalence is requested but the simulator bridge cannot run. + """ + gt_files = sorted(gt_dir.glob("*.json")) + if not gt_dir.is_dir() or not gt_files: + raise FileNotFoundError(f"No ground-truth netlists in {gt_dir}") + records: dict[str, CircuitResult] = {} + sim_inputs: dict[str, dict[str, list[dict[str, object]]]] = {} + for gt_file in gt_files: + stem = gt_file.stem + gt = load_netlist(gt_file) + pred_file = pred_dir / gt_file.name + pred_error: str | None = None + pred = Netlist() + if not pred_file.exists(): + pred_error = "missing prediction" + else: + try: + pred = load_netlist(pred_file) + except NetlistError as exc: + pred_error = str(exc) + mapping = match_components(gt, pred, match_mode) + gt_nets = scored_nets(gt, score_bulk) + pred_nets = remap_pins(scored_nets(pred, score_bulk), mapping) + counts = connectivity_scores(pin_pairs(gt_nets), pin_pairs(pred_nets)) + comps_ok = len(pred.components) == len(gt.components) == len(mapping) + records[stem] = CircuitResult( + stem=stem, + domain=domain_for(stem), + gt_components=len(gt.components), + pred_components=len(pred.components), + matched_components=len(mapping), + tp=counts["tp"], + fp=counts["fp"], + fn=counts["fn"], + exact_match=comps_ok and set(gt_nets) == set(pred_nets), + pred_error=pred_error, + ) + if truth_table: + sim_inputs[f"gt::{stem}"] = to_digisim(gt) + sim_inputs[f"pred::{stem}"] = to_digisim(pred, {pid: mapping.get(pid, f"pred~{pid}") for pid in pred.components}) + if truth_table: + tables = run_truth_tables(sim_inputs) + for stem, rec in records.items(): + gt_t, pred_t = tables[f"gt::{stem}"], tables[f"pred::{stem}"] + if "error" in gt_t: + rec.truth_table, rec.truth_table_detail = "gt_unsimulatable", str(gt_t["error"]) + else: + rec.truth_table = "equivalent" if tables_equivalent(gt_t, pred_t) else "different" + rec.truth_table_detail = str(pred_t["error"]) if "error" in pred_t else None + domains = sorted({r.domain for r in records.values()}) + return { + "settings": {"match_mode": match_mode, "score_bulk": score_bulk, "truth_table": truth_table, "iou": IOU_MATCH_THRESHOLD}, + "overall": aggregate(list(records.values())), + "per_domain": {d: aggregate([r for r in records.values() if r.domain == d]) for d in domains}, + "circuits": {stem: r.to_dict() for stem, r in records.items()}, + } + + +def aggregate(records: Sequence[CircuitResult]) -> dict[str, object]: + """ + Aggregate per-circuit results into end-to-end metrics. + + Args: + records: Per-circuit results. + Returns: + Dict with circuits, low_support, micro/macro net scores, exact_match and truth_table rates. + """ + tp = sum(r.tp for r in records) + fp = sum(r.fp for r in records) + fn = sum(r.fn for r in records) + per_circuit = [prf(r.tp, r.fp, r.fn) for r in records] + macro: dict[str, float | None] = {} + for key in ("precision", "recall", "f1"): + vals = [m[key] for m in per_circuit if m[key] is not None] + macro[key] = sum(vals) / len(vals) if vals else None + n = len(records) + exact = sum(1 for r in records if r.exact_match) + requested = [r for r in records if r.truth_table is not None] + simulatable = [r for r in requested if r.truth_table != "gt_unsimulatable"] + equivalent = sum(1 for r in simulatable if r.truth_table == "equivalent") + return { + "circuits": n, + "low_support": n < LOW_SUPPORT_N, + "net_micro": {**prf(tp, fp, fn), "pairs_tp": tp, "pairs_fp": fp, "pairs_fn": fn}, + "net_macro": macro, + "net_f1_micro_ci95": rate(2 * tp, 2 * tp + fp + fn)["ci95"], + "exact_match": rate(exact, n), + "truth_table": {**rate(equivalent, len(simulatable)), "gt_unsimulatable": len(requested) - len(simulatable)}, + } diff --git a/ml/eval_report.py b/ml/eval_report.py new file mode 100644 index 0000000..acc6745 --- /dev/null +++ b/ml/eval_report.py @@ -0,0 +1,275 @@ +""" +Module: eval_report.py +Purpose: Renders an evaluation run (the JSON produced by evaluate.py) as one Markdown document: + run header, overall/per-class/per-domain detection tables with Wilson CIs, confusion + matrix, small-object recall, end-to-end netlist metrics, the legacy ultralytics numbers + and the reproduction check, with optional deltas against a committed baseline run. +""" + +from collections.abc import Mapping, Sequence +from typing import Any + +# Parsed JSON document (reports are plain nested dicts/lists). +JsonDict = dict[str, Any] + +F1_GATE = 0.95 +ACC_GATE = 0.95 +REAL_F1_GATE = 0.85 +JUNCTION_RECALL_GATE = 0.90 + + +def fmt_rate(rec: JsonDict | None, digits: int = 3) -> str: + """ + Format a rate record as `value [lo, hi]`. + + Args: + rec: Record with value and ci95 (see eval_metrics.rate), or None. + digits: Decimal places. + Returns: + The formatted cell, or "n/a" when the value is undefined. + """ + if not rec or rec.get("value") is None: + return "n/a" + value = float(rec["value"]) + ci = rec.get("ci95") + if not ci: + return f"{value:.{digits}f}" + lo, hi = ci + return f"{value:.{digits}f} [{lo:.{digits}f}, {hi:.{digits}f}]" + + +def _value(rec: JsonDict | None) -> float | None: + """ + The numeric value of a rate record. + + Args: + rec: Rate record or None. + Returns: + The value, or None when absent. + """ + if not rec or rec.get("value") is None: + return None + return float(rec["value"]) + + +def verdict(record: JsonDict, domain: str | None) -> str: + """ + Pass/fail verdict for one class record under the phase gate. + + Synthetic and overall rows need F1 >= 0.95 and accuracy >= 0.95; real-image domains need F1 >= 0.85 + (agent_docs/ml-pipeline.md, phase 2). Classes with too little support are labelled instead of judged. + + Args: + record: Per-class record from DetectionAccumulator.per_class(). + domain: Domain name, or None for the overall table. + Returns: + 'PASS', 'FAIL', 'no GT' (no ground-truth instances) or 'low n' (verdict not trustworthy). + """ + if int(record["gt"]) == 0: + return "no GT" + f1, acc = _value(record["f1"]), _value(record["accuracy"]) + real = bool(domain and domain.endswith("_real")) + ok = f1 is not None and acc is not None and f1 >= (REAL_F1_GATE if real else F1_GATE) and (real or acc >= ACC_GATE) + if record["low_support"]: + return f"low n ({'pass' if ok else 'fail'})" + return "PASS" if ok else "FAIL" + + +def _num(value: float | None, signed: bool = False) -> str: + """ + Format an optional number to four decimals. + + Args: + value: Number or None. + signed: Always show the sign. + Returns: + The formatted number, or 'missing' for None. + """ + if value is None: + return "missing" + return f"{value:+.4f}" if signed else f"{value:.4f}" + + +def _table(headers: Sequence[str], rows: Sequence[Sequence[str]]) -> list[str]: + """ + A GitHub-flavoured Markdown table. + + Args: + headers: Column headers. + rows: Row cells. + Returns: + Lines of the table. + """ + lines = ["| " + " | ".join(headers) + " |", "|" + "|".join("---" for _ in headers) + "|"] + lines += ["| " + " | ".join(r) + " |" for r in rows] + return lines + + +def _delta(current: float | None, base: float | None) -> str: + """ + Signed difference against a baseline value. + + Args: + current: Current value. + base: Baseline value. + Returns: + Like "+0.012", or "-" when either side is missing. + """ + if current is None or base is None: + return "-" + return f"{current - base:+.3f}" + + +def _class_table(per_class: Mapping[str, JsonDict], domain: str | None, base: Mapping[str, JsonDict] | None) -> list[str]: + """ + Per-class metric table. + + Args: + per_class: Class name -> record. + domain: Domain name or None for overall. + base: Baseline per-class records for the same scope, or None. + Returns: + Table lines. + """ + headers = ["class", "GT", "TP", "FP", "FN", "precision", "recall = accuracy", "F1", "verdict"] + if base is not None: + headers.append("dF1 vs baseline") + rows = [] + for name, rec in per_class.items(): + row = [ + name, + str(rec["gt"]), + str(rec["tp"]), + str(rec["fp"]), + str(rec["fn"]), + fmt_rate(rec["precision"]), + fmt_rate(rec["recall"]), + fmt_rate(rec["f1"]), + verdict(rec, domain), + ] + if base is not None: + row.append(_delta(_value(rec["f1"]), _value(base.get(name, {}).get("f1")))) + rows.append(row) + return _table(headers, rows) + + +def _confusion_table(conf: JsonDict) -> list[str]: + """ + Confusion matrix as a table (rows = predicted, columns = ground truth). + + Args: + conf: Confusion record from DetectionAccumulator.confusion(). + Returns: + Table lines. + """ + labels = [str(x) for x in conf["labels"]] + matrix = conf["matrix"] + rows = [[f"**{labels[i]}**", *[str(v) if v else "." for v in matrix[i]]] for i in range(len(labels))] + return _table(["pred \\ GT", *labels], rows) + + +def _e2e_rows(label: str, rec: JsonDict) -> list[str]: + """ + One end-to-end summary row. + + Args: + label: Row label (scope name). + rec: Aggregate record from eval_netlist.aggregate(). + Returns: + Table cells. + """ + micro, macro = rec["net_micro"], rec["net_macro"] + f = lambda v: "n/a" if v is None else f"{v:.3f}" # noqa: E731 + return [ + label, + str(rec["circuits"]), + f(micro["precision"]), + f(micro["recall"]), + f(micro["f1"]), + f(macro["f1"]), + fmt_rate(rec["exact_match"]), + fmt_rate(rec["truth_table"]), + ] + + +def render_markdown(report: JsonDict, baseline: JsonDict | None = None) -> str: + """ + Render a whole evaluation report as Markdown. + + Args: + report: The evaluate.py JSON report. + baseline: A previous report to show deltas against (same schema), or None. + Returns: + The Markdown text. + """ + run = report["run"] + lines = [f"# DigiSim evaluation - {run['name']}", ""] + lines += [ + f"- generated: {run['generated_at']}", + f"- weights: `{run['weights']['name']}` sha256 `{str(run['weights']['sha256'])[:16]}...`" if run.get("weights") else "- weights: none (end-to-end only)", + f"- dataset: `{run['dataset']['frozen_name']}` split `{run['dataset']['split']}`, {run['dataset']['images']} images, frozen sha256 `{str(run['dataset']['sha256'])[:16]}...` (verified)", + f"- params: {run['params']}", + "", + ] + det = report.get("detection") + if det: + base_det = (baseline or {}).get("detection") + ov = det["overall"] + lines += ["## Detection - overall", ""] + lines += _table( + ["images", "GT", "precision", "recall", "F1", "small-object recall", "unmapped preds"], + [ + [ + str(ov["images"]), + str(ov["gt"]), + fmt_rate(ov["precision"]), + fmt_rate(ov["recall"]), + fmt_rate(ov["f1"]), + fmt_rate(ov["small_object"]["recall"]) + f" (side <= {ov['small_object']['max_side_px']:g}px)", + str(ov["unmapped_predictions"]), + ] + ], + ) + lines += [ + "", + f"Operating point: conf >= {det['conf']}, IoU >= {det['iou_threshold']}.", + f"Verdicts: F1 >= {F1_GATE} and accuracy >= {ACC_GATE} (synthetic / overall), F1 >= {REAL_F1_GATE} (real domains); `low n` = fewer than 30 GT instances.", + "", + ] + jr = det.get("junction_recall") + if jr: + lines += [f"JUNCTION recall: {fmt_rate(jr)} (gate: >= {JUNCTION_RECALL_GATE})", ""] + lines += ["## Detection - per class (all domains)", ""] + lines += _class_table(det["per_class"], None, base_det["per_class"] if base_det else None) + for domain, drec in det["per_domain"].items(): + lines += ["", f"## Detection - domain `{domain}` ({drec['overall']['images']} images, {drec['overall']['gt']} GT)", ""] + base_dom = ((base_det or {}).get("per_domain") or {}).get(domain) + lines += _class_table(drec["per_class"], domain, base_dom["per_class"] if base_dom else None) + lines += ["", "## Confusion matrix (all domains)", ""] + lines += _confusion_table(det["confusion_matrix"]) + e2e = report.get("end_to_end") + if e2e: + lines += ["", "## End-to-end (netlist)", ""] + rows = [_e2e_rows("overall", e2e["overall"])] + rows += [_e2e_rows(d, rec) for d, rec in e2e["per_domain"].items()] + lines += _table(["scope", "circuits", "net P (micro)", "net R (micro)", "net F1 (micro)", "net F1 (macro)", "exact match", "truth-table equiv."], rows) + lines += ["", "Net P/R/F1 are over pin-pair connectivity (micro = pooled pairs, macro = mean per circuit). Intervals are Wilson 95%.", ""] + legacy = report.get("legacy") + if legacy: + lines += ["", "## Legacy ultralytics validation (phase-gate numbers)", "", f"mAP@0.5 = {legacy['map50']:.4f}, mAP@0.5:0.95 = {legacy['map50_95']:.4f}", ""] + lines += _table( + ["class", "F1 (max-F1 conf)", "accuracy (confusion matrix)"], + [[n, f"{m.get('f1', float('nan')):.4f}", f"{m.get('accuracy', float('nan')):.4f}"] for n, m in legacy["per_class"].items()], + ) + repro = report.get("reproduction") + if repro: + lines += [ + "", + "## Reproduction of the reference numbers", + "", + f"Reference: `{repro['reference']}`; tolerance {repro['tolerance']}; max abs delta {_num(repro['max_abs_delta'])}.", + f"Result: **{'OK' if repro['ok'] else 'OUT OF TOLERANCE'}**", + "", + ] + lines += _table(["metric", "reference", "this run", "delta"], [[r["metric"], f"{r['reference']:.4f}", _num(r["value"]), _num(r["delta"], signed=True)] for r in repro["rows"]]) + return "\n".join(lines) + "\n" diff --git a/ml/evaluate.py b/ml/evaluate.py index 84207d7..40f6421 100644 --- a/ml/evaluate.py +++ b/ml/evaluate.py @@ -1,46 +1,277 @@ """ Module: evaluate.py -Purpose: Evaluates the trained gate detector on the test split and prints - per-class F1 and accuracy plus overall mAP@0.5 — the numbers that gate - phase advancement (F1 ≥ 0.95 and accuracy ≥ 0.95 per class). Accuracy - is computed from the confusion matrix as TP / total ground truth of the - class (misses and misclassifications both count against it). +Purpose: Evaluation harness v2 for the DigiSim symbol detector and the image -> circuit pipeline. + One run writes one JSON and one Markdown report containing: + - detection: per-class and per-domain precision / recall / F1 / accuracy with Wilson 95% CIs, + a confusion matrix, small-object (junction) recall; + - end-to-end (optional): net precision/recall/F1 over pin pairs, netlist exact-match rate and + truth-table equivalence of the reconstructed circuit under DigiSim's simulator; + - legacy: the ultralytics-validation numbers the original phase gate used (mAP, max-F1 per + class, confusion-matrix accuracy), so old results stay reproducible; + - a frozen-set integrity check: the run refuses to start when the test split's SHA-256 no + longer matches ml/frozen_sets.json. + "accuracy" is TP / ground-truth instances of the class (misses and misclassifications both count + against it), the number the F1 >= 0.95 / accuracy >= 0.95 phase gate uses. Usage: - cd ml && uv run python evaluate.py [--weights ../backend/model/weights/best.pt] + cd ml + uv run python evaluate.py --weights W.pt --data DATASET/data.yaml --frozen-name gate12_test + uv run python evaluate.py ... --freeze --freeze-note "what this set is" # register a new frozen set (reviewed change) + uv run python evaluate.py ... --gt-netlists DIR --pred-netlists DIR # add end-to-end metrics + uv run python evaluate.py ... --reproduce eval_test.json --baseline baselines/gate12.json +Exit codes: 0 ok, 3 frozen-set check failed, 4 reproduction out of tolerance. """ import argparse import json +import os +import subprocess +import sys +from dataclasses import dataclass +from datetime import UTC, datetime from pathlib import Path +from typing import Any import numpy as np -from ultralytics import YOLO + +from class_schema import load_schema +from eval_frozen import DEFAULT_REGISTRY, FrozenSetError, SplitDigest, file_sha256, freeze, hash_split, infer_frozen_name, verify_frozen +from eval_metrics import ( + DEFAULT_DOMAIN_RULES, + DEFAULT_SMALL_PX, + IOU_MATCH_THRESHOLD, + DetectionAccumulator, + domain_for, + parse_domain_rule, +) +from eval_netlist import evaluate_netlists +from eval_report import render_markdown ML_DIR = Path(__file__).resolve().parent REPO_ROOT = ML_DIR.parent DEFAULT_WEIGHTS = REPO_ROOT / "backend" / "model" / "weights" / "best.pt" DEFAULT_DATA = ML_DIR / "dataset" / "data.yaml" +DEFAULT_OUT_DIR = ML_DIR / "experiments" / "eval" F1_THRESHOLD = 0.95 ACC_THRESHOLD = 0.95 +# Predictions are generated once at this floor so any operating confidence can be derived from them. +PREDICT_CONF_FLOOR = 0.001 +DEFAULT_OPERATING_CONF = 0.35 # production DETECTION_CONFIDENCE_THRESHOLD (backend/pipeline/detector.py) +DEFAULT_TOLERANCE = 0.02 +IMAGE_SUFFIXES = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".webp"}) +EXIT_FROZEN = 3 +EXIT_REPRODUCTION = 4 + + +@dataclass(frozen=True) +class DatasetInfo: + """A YOLO dataset resolved from its data.yaml.""" + + root: Path + names: tuple[str, ...] + images_dir: Path + labels_dir: Path + + +def load_dataset_info(data: Path, split: str) -> DatasetInfo: + """ + Resolve dataset root, class names and the split's image/label directories from data.yaml. + + Args: + data: Path to a YOLO data.yaml. + split: Split key ('test', 'val', ...), resolved through the yaml like ultralytics does. + Returns: + The DatasetInfo. + Raises: + FileNotFoundError: If the yaml or the split directory does not exist. + ValueError: If the yaml has no class names or no entry for the split. + """ + import yaml + + if not data.exists(): + raise FileNotFoundError(f"Dataset yaml not found: {data}") + doc = yaml.safe_load(data.read_text()) + raw_names = doc.get("names") + names = tuple(raw_names[i] for i in sorted(raw_names)) if isinstance(raw_names, dict) else tuple(raw_names or ()) + if not names: + raise ValueError(f"{data}: no class names") + key = "val" if split == "valid" and "valid" not in doc else split + if key not in doc: + raise ValueError(f"{data}: no entry for split {split!r}") + root = Path(doc.get("path", data.parent)) + if not root.is_absolute(): + root = (data.parent / root).resolve() + images_dir = root / str(doc[key]) + labels_dir = root / str(doc[key]).replace("images", "labels", 1) + if not images_dir.is_dir(): + raise FileNotFoundError(f"Split images directory missing: {images_dir}") + return DatasetInfo(root=root, names=names, images_dir=images_dir, labels_dir=labels_dir) + + +def read_labels(label_file: Path, width: int, height: int) -> np.ndarray: + """ + Read a YOLO label file into pixel-space ground-truth rows. + + Args: + label_file: YOLO .txt (class xc yc w h, or class x1 y1 x2 y2 ... polygon, all normalised); may not exist. + width: Image width in pixels. + height: Image height in pixels. + Returns: + (n, 5) float array of [cls, x1, y1, x2, y2] in pixels (empty when the file is missing or empty). + Raises: + ValueError: If a line is malformed. + """ + rows: list[list[float]] = [] + if label_file.exists(): + for line in label_file.read_text().splitlines(): + parts = line.split() + if not parts: + continue + vals = [float(v) for v in parts] + if len(vals) == 5: + cx, cy, w, h = vals[1:] + x1, y1, x2, y2 = cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2 + elif len(vals) >= 7 and len(vals) % 2 == 1: + xs, ys = vals[1::2], vals[2::2] + x1, y1, x2, y2 = min(xs), min(ys), max(xs), max(ys) + else: + raise ValueError(f"{label_file}: malformed label line {line!r}") + rows.append([vals[0], x1 * width, y1 * height, x2 * width, y2 * height]) + return np.asarray(rows, dtype=np.float64).reshape(-1, 5) + + +def build_class_map(model_names: dict[int, str], dataset_names: tuple[str, ...], aliases: dict[str, str]) -> list[int]: + """ + Map each model class id to a dataset class id by name, then by legacy alias. + + Args: + model_names: Model class id -> name (as stored in the weights). + dataset_names: Dataset class names ordered by id. + aliases: Legacy alias -> canonical class name (ml/classes.yaml). + Returns: + List indexed by model class id giving the dataset class id, or -1 when the model class has no + counterpart in the dataset vocabulary (such predictions are counted as unmapped). + """ + index = {name: i for i, name in enumerate(dataset_names)} + mapping = [] + for cls_id in range(max(model_names) + 1 if model_names else 0): + name = model_names.get(cls_id, "") + canonical = aliases.get(name, aliases.get(name.upper(), name)) + mapping.append(index.get(name, index.get(canonical, -1))) + return mapping + + +def predict_split(weights: Path, image_paths: list[Path], imgsz: int, device: str) -> tuple[dict[int, str], dict[str, tuple[np.ndarray, tuple[int, int]]]]: + """ + Run the detector once over a list of images at a very low confidence floor. + + Args: + weights: Trained .pt weights. + image_paths: Images to run. + imgsz: Inference image size. + device: Torch device string ('cpu', '0', ...). + Returns: + (model class names, mapping image name -> (predictions [cls, conf, x1, y1, x2, y2], (height, width))). + Raises: + FileNotFoundError: If the weights do not exist. + """ + from ultralytics import YOLO + + if not weights.exists(): + raise FileNotFoundError(f"Weights not found: {weights} - train first") + model = YOLO(str(weights)) + out: dict[str, tuple[np.ndarray, tuple[int, int]]] = {} + for path, result in zip(image_paths, model.predict(source=[str(p) for p in image_paths], imgsz=imgsz, conf=PREDICT_CONF_FLOOR, device=device, stream=True, verbose=False), strict=True): + boxes = result.boxes + xyxy = boxes.xyxy.cpu().numpy() + conf = boxes.conf.cpu().numpy() + cls = boxes.cls.cpu().numpy() + preds = np.column_stack([cls, conf, xyxy]) if len(cls) else np.zeros((0, 6)) + out[path.name] = (preds, (int(result.orig_shape[0]), int(result.orig_shape[1]))) + return {int(k): str(v) for k, v in model.names.items()}, out + + +def evaluate_detection( + info: DatasetInfo, + weights: Path, + imgsz: int, + conf: float, + iou: float, + small_px: float, + device: str, + domain_rules: tuple[tuple[str, str], ...], +) -> dict[str, Any]: + """ + Per-class and per-domain detection metrics at one operating confidence. + + Args: + info: Resolved dataset. + weights: Trained .pt weights. + imgsz: Inference image size. + conf: Operating confidence threshold applied to the raw predictions. + iou: IoU threshold for prediction-to-GT matching. + small_px: Longest-side threshold (pixels) for the small-object recall. + device: Torch device string. + domain_rules: (filename prefix, domain) rules. + Returns: + Dict with overall, per_class, per_domain, confusion_matrix, junction_recall and operating-point settings. + Raises: + FileNotFoundError: If the weights are missing or the split holds no images. + """ + images = sorted(p for p in info.images_dir.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES) + if not images: + raise FileNotFoundError(f"No images in {info.images_dir}") + model_names, predictions = predict_split(weights, images, imgsz, device) + class_map = np.asarray(build_class_map(model_names, info.names, load_schema().aliases), dtype=np.int64) + n = len(info.names) + overall = DetectionAccumulator(n, small_px, iou) + per_domain: dict[str, DetectionAccumulator] = {} + for path in images: + preds, (height, width) = predictions[path.name] + preds = preds[preds[:, 1] >= conf] if len(preds) else preds + if len(preds): + preds = preds.copy() + preds[:, 0] = class_map[preds[:, 0].astype(int)] + gt = read_labels(info.labels_dir / f"{path.stem}.txt", width, height) + overall.add_image(gt, preds) + per_domain.setdefault(domain_for(path.name, domain_rules), DetectionAccumulator(n, small_px, iou)).add_image(gt, preds) + per_class = overall.per_class(info.names) + return { + "conf": conf, + "iou_threshold": iou, + "model_classes": [model_names[i] for i in sorted(model_names)], + "class_map": {model_names.get(i, str(i)): (info.names[c] if c >= 0 else None) for i, c in enumerate(class_map.tolist())}, + "overall": overall.overall(), + "per_class": per_class, + "per_domain": {d: {"overall": acc.overall(), "per_class": acc.per_class(info.names)} for d, acc in sorted(per_domain.items())}, + "confusion_matrix": overall.confusion(info.names), + "junction_recall": per_class["JUNCTION"]["recall"] if "JUNCTION" in per_class else None, + } -def evaluate(weights: Path, data: Path, split: str) -> dict: +def evaluate(weights: Path, data: Path, split: str, imgsz: int = 640, project: Path | None = None, device: str = "cpu") -> dict[str, Any]: """ - Run validation and assemble per-class metrics. + Legacy ultralytics validation: mAP plus max-F1 per class and confusion-matrix accuracy. + + This is exactly what the original phase gate used; it stays so old numbers remain reproducible. Args: weights: Path to trained .pt weights. data: Dataset yaml path. split: Dataset split to evaluate ('test' or 'val'). + imgsz: Validation image size. + project: Directory for ultralytics' validation artefacts (defaults to ml/experiments/eval). + device: Torch device string. Returns: - Dict with per-class metrics and overall mAP. + Dict with split, map50, map50_95 and per_class {f1, accuracy}. Raises: FileNotFoundError: If weights or dataset yaml are missing. """ + from ultralytics import YOLO + if not weights.exists(): - raise FileNotFoundError(f"Weights not found: {weights} — train first") + raise FileNotFoundError(f"Weights not found: {weights} - train first") if not data.exists(): raise FileNotFoundError(f"Dataset yaml not found: {data}") @@ -50,9 +281,11 @@ def evaluate(weights: Path, data: Path, split: str) -> dict: metrics = model.val( data=str(data), split=split, - device="cpu", + imgsz=imgsz, + device=device, + workers=0, plots=True, - project=str(ML_DIR / "experiments" / "eval"), + project=str(project or DEFAULT_OUT_DIR), name=split, exist_ok=True, ) @@ -82,19 +315,19 @@ def evaluate(weights: Path, data: Path, split: str) -> dict: } -def print_report(report: dict) -> bool: +def print_report(report: dict[str, Any]) -> bool: """ - Print the per-class metric table and threshold verdicts. + Print the legacy per-class metric table and threshold verdicts. Args: report: Output of evaluate(). Returns: True when every reported class passes both thresholds. """ - print(f"\n=== DigiSim gate detector — split: {report['split']} ===") + print(f"\n=== DigiSim detector (ultralytics validation) - split: {report['split']} ===") print(f"mAP@0.5 : {report['map50']:.4f}") print(f"mAP@0.5:0.95 : {report['map50_95']:.4f}\n") - print(f"{'class':<10} {'F1':>7} {'acc':>7} verdict") + print(f"{'class':<12} {'F1':>7} {'acc':>7} verdict") all_pass = True for name, m in report["per_class"].items(): @@ -102,32 +335,184 @@ def print_report(report: dict) -> bool: acc = m.get("accuracy", float("nan")) ok = f1 >= F1_THRESHOLD and acc >= ACC_THRESHOLD all_pass = all_pass and ok - print(f"{name:<10} {f1:>7.4f} {acc:>7.4f} {'PASS' if ok else 'FAIL'}") + print(f"{name:<12} {f1:>7.4f} {acc:>7.4f} {'PASS' if ok else 'FAIL'}") verdict = "ALL CLASSES PASS" if all_pass else "THRESHOLD NOT MET" - print(f"\n{verdict} (need F1 ≥ {F1_THRESHOLD} and acc ≥ {ACC_THRESHOLD})") + print(f"\n{verdict} (need F1 >= {F1_THRESHOLD} and acc >= {ACC_THRESHOLD})") return all_pass -def main() -> None: +def reproduction_check(legacy: dict[str, Any], reference: dict[str, Any], tolerance: float, reference_name: str) -> dict[str, Any]: + """ + Compare a legacy validation block with a reference (e.g. the old eval_test.json). + + Args: + legacy: Output of evaluate(). + reference: Reference report with map50, map50_95 and per_class {f1, accuracy}. + tolerance: Maximum allowed absolute difference per metric. + reference_name: Name recorded in the report. + Returns: + Dict with reference, tolerance, rows (metric, reference, value, delta), max_abs_delta and ok. + """ + rows: list[dict[str, Any]] = [] + + def add(metric: str, ref_value: float, value: float | None) -> None: + """Append one comparison row; a metric absent from the run has value/delta None and fails the check.""" + rows.append({"metric": metric, "reference": float(ref_value), "value": value, "delta": None if value is None else value - float(ref_value)}) + + for key in ("map50", "map50_95"): + if key in reference: + add(key, reference[key], float(legacy[key]) if key in legacy else None) + for name, ref in reference.get("per_class", {}).items(): + for key in ("f1", "accuracy"): + if key in ref: + got = legacy["per_class"].get(name, {}).get(key) + add(f"{name}.{key}", ref[key], None if got is None else float(got)) + missing = [r["metric"] for r in rows if r["delta"] is None] + deltas = [abs(r["delta"]) for r in rows if r["delta"] is not None] + worst = max(deltas) if deltas else None + ok = bool(rows) and not missing and worst is not None and worst <= tolerance + return {"reference": reference_name, "tolerance": tolerance, "rows": rows, "max_abs_delta": worst, "missing": missing, "ok": ok} + + +def git_commit() -> str | None: + """ + The current git commit of the repository, for provenance. + + Returns: + The commit hash, or None if git is unavailable. + """ + try: + proc = subprocess.run(["git", "-C", str(REPO_ROOT), "rev-parse", "HEAD"], capture_output=True, text=True, check=True) + except (FileNotFoundError, subprocess.CalledProcessError): + return None + return proc.stdout.strip() + + +def build_parser() -> argparse.ArgumentParser: + """ + The command-line parser. + + Returns: + Configured ArgumentParser. + """ + p = argparse.ArgumentParser(description="DigiSim evaluation harness v2") + p.add_argument("--weights", type=Path, default=DEFAULT_WEIGHTS) + p.add_argument("--data", type=Path, default=DEFAULT_DATA) + p.add_argument("--split", default="test") + p.add_argument("--frozen-name", help="Frozen set to verify (inferred from the registry when one entry has this split and class list; required for the test split otherwise)") + p.add_argument("--registry", type=Path, default=DEFAULT_REGISTRY) + p.add_argument("--freeze", action="store_true", help="Register the split as a new frozen set, then exit") + p.add_argument("--freeze-note", default="", help="Provenance note stored with --freeze") + p.add_argument("--imgsz", type=int, default=640) + p.add_argument("--conf", type=float, default=DEFAULT_OPERATING_CONF, help="Operating confidence for P/R/F1") + p.add_argument("--iou", type=float, default=IOU_MATCH_THRESHOLD) + p.add_argument("--small-px", type=float, default=DEFAULT_SMALL_PX, help="GT boxes with longest side <= this are 'small objects'") + p.add_argument("--device", default="cpu") + p.add_argument("--threads", type=int, default=4, help="CPU threads for torch/OpenMP") + p.add_argument("--domain-rule", action="append", default=[], metavar="PREFIX=NAME", help="Extra filename-prefix domain rule (repeatable)") + p.add_argument("--skip-detection", action="store_true", help="Only run the end-to-end metrics") + p.add_argument("--skip-legacy", action="store_true", help="Skip the ultralytics validation block") + p.add_argument("--gt-netlists", type=Path, help="Directory of ground-truth netlists (.json)") + p.add_argument("--pred-netlists", type=Path, help="Directory of predicted netlists (.json)") + p.add_argument("--match-mode", choices=["auto", "bbox", "id"], default="auto") + p.add_argument("--score-bulk", action="store_true", help="Also score MOSFET bulk pins") + p.add_argument("--no-truth-table", action="store_true", help="Skip simulator-based truth-table equivalence") + p.add_argument("--reproduce", type=Path, help="Reference eval JSON (e.g. the old eval_test.json) the legacy block must match") + p.add_argument("--tolerance", type=float, default=DEFAULT_TOLERANCE) + p.add_argument("--baseline", type=Path, help="Earlier report JSON to show deltas against") + p.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR) + p.add_argument("--run-name", help="Output file stem (default: the frozen set name, else _)") + return p + + +def main(argv: list[str] | None = None) -> int: """ - CLI entry point — prints the report and writes it next to the weights. + CLI entry point: verify the frozen set, run the requested evaluations, write the JSON and Markdown. + Args: + argv: Argument list (defaults to sys.argv[1:]). + Returns: + Process exit code (0 ok, 3 frozen-set failure, 4 reproduction out of tolerance). Raises: - SystemExit: On argparse errors. + SystemExit: On argparse errors or invalid options. """ - parser = argparse.ArgumentParser(description="Evaluate DigiSim gate detector") - parser.add_argument("--weights", type=Path, default=DEFAULT_WEIGHTS) - parser.add_argument("--data", type=Path, default=DEFAULT_DATA) - parser.add_argument("--split", default="test") - args = parser.parse_args() + parser = build_parser() + args = parser.parse_args(argv) + os.environ.setdefault("OMP_NUM_THREADS", str(args.threads)) + try: + rules = (*(parse_domain_rule(r) for r in args.domain_rule), *DEFAULT_DOMAIN_RULES) + except ValueError as exc: + parser.error(str(exc)) + if bool(args.gt_netlists) != bool(args.pred_netlists): + parser.error("--gt-netlists and --pred-netlists go together") + + info = load_dataset_info(args.data, args.split) + digest: SplitDigest = hash_split(info.root, args.split, info.names) + if not args.freeze and not args.frozen_name: + args.frozen_name = infer_frozen_name(args.split, info.names, args.registry) + if args.split == "test" and not args.frozen_name: + parser.error("the test split must be hash-verified: pass --frozen-name (no single registered frozen set has this split and class list)") + if args.freeze: + if not args.frozen_name: + parser.error("--freeze needs --frozen-name") + try: + freeze(args.frozen_name, digest, args.split, args.freeze_note, args.registry) + except FrozenSetError as exc: + print(f"error: {exc}", file=sys.stderr) + return EXIT_FROZEN + print(f"froze {args.frozen_name}: sha256 {digest.sha256} ({digest.images} images, {digest.labels} labels, {digest.netlists} netlists)") + return 0 + if args.frozen_name: + try: + verify_frozen(args.frozen_name, digest, args.registry) + except FrozenSetError as exc: + print(f"error: {exc}", file=sys.stderr) + return EXIT_FROZEN + + report: dict[str, Any] = { + "schema": "digisim.eval/2", + "run": { + "name": args.run_name or args.frozen_name or f"{info.root.name}_{args.split}", + "generated_at": datetime.now(UTC).isoformat(timespec="seconds"), + "git_commit": git_commit(), + "weights": None if args.skip_detection else {"name": args.weights.name, "sha256": file_sha256(args.weights) if args.weights.exists() else None}, + "dataset": { + "frozen_name": args.frozen_name, + "split": args.split, + "images": digest.images, + "labels": digest.labels, + "netlists": digest.netlists, + "sha256": digest.sha256, + "classes": list(info.names), + }, + "params": {"imgsz": args.imgsz, "conf": args.conf, "iou": args.iou, "small_px": args.small_px, "device": args.device}, + }, + } + status = 0 + if not args.skip_detection: + report["detection"] = evaluate_detection(info, args.weights, args.imgsz, args.conf, args.iou, args.small_px, args.device, rules) + if not args.skip_legacy: + report["legacy"] = evaluate(args.weights, args.data, args.split, args.imgsz, args.out_dir / "ultralytics_val", args.device) + print_report(report["legacy"]) + if args.reproduce: + repro = reproduction_check(report["legacy"], json.loads(args.reproduce.read_text()), args.tolerance, args.reproduce.name) + report["reproduction"] = repro + if not repro["ok"]: + status = EXIT_REPRODUCTION + elif args.reproduce: + parser.error("--reproduce needs the legacy block (drop --skip-legacy)") + if args.gt_netlists: + report["end_to_end"] = evaluate_netlists(args.gt_netlists, args.pred_netlists, not args.no_truth_table, args.match_mode, args.score_bulk) - report = evaluate(args.weights, args.data, args.split) - print_report(report) - out = args.weights.parent / f"eval_{args.split}.json" - out.write_text(json.dumps(report, indent=2)) - print(f"Report written to {out}") + args.out_dir.mkdir(parents=True, exist_ok=True) + stem = report["run"]["name"] + baseline = json.loads(args.baseline.read_text()) if args.baseline else None + (args.out_dir / f"{stem}.json").write_text(json.dumps(report, indent=2) + "\n") + (args.out_dir / f"{stem}.md").write_text(render_markdown(report, baseline)) + print(f"Wrote {args.out_dir / (stem + '.json')} and {args.out_dir / (stem + '.md')}") + return status if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/ml/frozen_sets.json b/ml/frozen_sets.json new file mode 100644 index 0000000..c25d88b --- /dev/null +++ b/ml/frozen_sets.json @@ -0,0 +1,24 @@ +{ + "gate12_test": { + "classes": [ + "AND", + "OR", + "NOT", + "NAND", + "NOR", + "XOR", + "XNOR", + "SWITCH", + "INPUT", + "OUTPUT", + "LED", + "JUNCTION" + ], + "images": 78, + "labels": 78, + "netlists": 0, + "note": "Legacy 12-class gate-era test split (75 synthetic + 3 Roboflow real images), copied from the pre-T1 checkout; the split the old weights' reported numbers came from.", + "sha256": "c261f9d325c708eceb1d54978d611685ed6be8464b3068926c100208025b83ca", + "split": "test" + } +} diff --git a/ml/pyproject.toml b/ml/pyproject.toml index e6d0731..8016e2d 100644 --- a/ml/pyproject.toml +++ b/ml/pyproject.toml @@ -11,6 +11,7 @@ dependencies = [ [dependency-groups] dev = [ + "pytest>=8.0", "ruff>=0.4", ] @@ -20,3 +21,7 @@ target-version = "py311" [tool.ruff.lint] select = ["E", "F", "I"] + +[tool.pytest.ini_options] +pythonpath = ["."] +testpaths = ["tests"] diff --git a/ml/sim_bridge/truth_table.cjs b/ml/sim_bridge/truth_table.cjs new file mode 100644 index 0000000..8199ef5 --- /dev/null +++ b/ml/sim_bridge/truth_table.cjs @@ -0,0 +1,93 @@ +/** + * @file truth_table.cjs + * @description Node bridge from the Python evaluation harness (ml/eval_netlist.py) to DigiSim's own + * simulator. Reads {"circuits": [{"id", "nodes", "edges"}]} as JSON on stdin (ReactFlow-shaped nodes and + * edges), enumerates every combination of the circuit's `input` nodes, runs simulate() from + * frontend/src/logic/simulation for each one, and writes {"": {"inputs", "outputs", "rows"} | {"error"}} + * to stdout. It contains no simulation logic itself (that lives only in src/logic/simulation/); it is a + * driver. Needs `cd frontend && npm install` first (uses the transpiler bundled with react-scripts). + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const FRONTEND_DIR = path.resolve(__dirname, '..', '..', 'frontend'); +const MAX_INPUTS = 10; + +/** Minimal in-memory localStorage: simulation modules read custom components from it. */ +const memoryStorage = (() => { + const store = new Map(); + return { + getItem: (key) => (store.has(key) ? store.get(key) : null), + setItem: (key, value) => { store.set(key, String(value)); }, + removeItem: (key) => { store.delete(key); }, + clear: () => { store.clear(); }, + }; +})(); + +/** + * Load the simulation entry point by transpiling the TypeScript sources on the fly. + * @returns {Function} simulate(nodes, edges, timeSeconds) + */ +function loadSimulate() { + global.localStorage = memoryStorage; + const sucraseRegister = require.resolve('sucrase/register', { paths: [FRONTEND_DIR] }); + require(sucraseRegister); + return require(path.join(FRONTEND_DIR, 'src', 'logic', 'simulation', 'index.ts')).simulate; +} + +/** + * Truth table of one circuit, enumerating every assignment of its `input` nodes. + * @param {Function} simulate - DigiSim simulate() + * @param {{nodes: object[], edges: object[]}} circuit - ReactFlow-shaped circuit + * @returns {{inputs: string[], outputs: string[], rows: Array>} | {error: string}} + */ +function truthTable(simulate, circuit) { + const inputs = circuit.nodes.filter((n) => n.type === 'input').map((n) => n.id).sort(); + const outputs = circuit.nodes.filter((n) => n.type === 'output').map((n) => n.id).sort(); + if (inputs.length === 0 || outputs.length === 0) return { error: 'circuit needs at least one input and one output' }; + if (inputs.length > MAX_INPUTS) return { error: `more than ${MAX_INPUTS} inputs` }; + const rows = []; + for (let mask = 0; mask < (1 << inputs.length); mask++) { + const nodes = circuit.nodes.map((n) => { + const bit = inputs.indexOf(n.id); + const data = { ...(n.data || {}) }; + if (bit >= 0) data.value = (mask >> (inputs.length - 1 - bit)) & 1; + return { ...n, position: n.position || { x: 0, y: 0 }, data }; + }); + const solved = simulate(nodes, circuit.edges); + const byId = new Map(solved.map((n) => [n.id, n])); + const bits = inputs.map((_, i) => (mask >> (inputs.length - 1 - i)) & 1); + const outs = outputs.map((id) => { + const v = byId.get(id) && byId.get(id).data.value; + return v === undefined || v === null ? 'Z' : v; + }); + rows.push([...bits, ...outs]); + } + return { inputs, outputs, rows }; +} + +/** + * Entry point: stdin JSON in, stdout JSON out. + * @returns {void} + */ +function main() { + const payload = JSON.parse(fs.readFileSync(0, 'utf8')); + const warn = console.warn; + console.warn = () => {}; + const simulate = loadSimulate(); + const result = {}; + for (const circuit of payload.circuits) { + try { + result[circuit.id] = truthTable(simulate, circuit); + } catch (err) { + result[circuit.id] = { error: String(err && err.message ? err.message : err) }; + } + } + console.warn = warn; + process.stdout.write(JSON.stringify(result)); +} + +main(); diff --git a/ml/tests/conftest.py b/ml/tests/conftest.py new file mode 100644 index 0000000..ea8b8cd --- /dev/null +++ b/ml/tests/conftest.py @@ -0,0 +1,61 @@ +""" +Module: conftest.py +Purpose: Shared pytest fixtures for the ml/ evaluation-harness tests: small hand-built CMOS netlists + (inverter, NAND) in the netlist JSON schema of ml/eval_netlist.py and helpers to write them to disk. +""" + +import json +from pathlib import Path + +import pytest + + +def nand_netlist(with_boxes: bool = False, prefix: str = "", shift: float = 0.0) -> dict: + """ + A 2-input CMOS NAND as a netlist dict. + + Args: + with_boxes: Attach a bbox to every component. + prefix: Prepended to every component id (to test id-independent matching). + shift: Added to every bbox coordinate (to test IoU tolerance). + Returns: + Netlist dict with components and nets. + """ + names = {"A": "input", "B": "input", "VDD": "vsource", "GND": "ground", "MP1": "pmos", "MP2": "pmos", "MN1": "nmos", "MN2": "nmos", "Y": "output"} + comps = [] + for i, (cid, ctype) in enumerate(names.items()): + comp = {"id": f"{prefix}{cid}", "type": ctype} + if with_boxes: + x = 100.0 * i + shift + comp["bbox"] = [x, 10 + shift, x + 60, 90 + shift] + comps.append(comp) + p = prefix + nets = [ + [f"{p}A:out", f"{p}MP1:g", f"{p}MN1:g"], + [f"{p}B:out", f"{p}MP2:g", f"{p}MN2:g"], + [f"{p}VDD:pos", f"{p}MP1:s", f"{p}MP2:s"], + [f"{p}MP1:d", f"{p}MP2:d", f"{p}MN1:d", f"{p}Y:a"], + [f"{p}MN1:s", f"{p}MN2:d"], + [f"{p}MN2:s", f"{p}GND:gnd"], + ] + return {"components": comps, "nets": nets} + + +@pytest.fixture +def write_netlist(tmp_path: Path): + """ + Factory that writes a netlist dict to //.json. + + Args: + tmp_path: pytest temporary directory. + Returns: + Callable (directory name, stem, netlist dict) -> directory path. + """ + + def _write(directory: str, stem: str, netlist: dict) -> Path: + folder = tmp_path / directory + folder.mkdir(exist_ok=True) + (folder / f"{stem}.json").write_text(json.dumps(netlist)) + return folder + + return _write diff --git a/ml/tests/test_baselines.py b/ml/tests/test_baselines.py new file mode 100644 index 0000000..631accb --- /dev/null +++ b/ml/tests/test_baselines.py @@ -0,0 +1,47 @@ +""" +Module: test_baselines.py +Purpose: Guards the committed evaluation baselines: ml/baselines/gate12.json must reference a frozen set + that is registered in ml/frozen_sets.json with the same hash and class list, must have reproduced + the old numbers within tolerance, and must carry the per-class and per-domain detection blocks + later runs are compared against. +""" + +import json +from pathlib import Path + +import pytest + +ML_DIR = Path(__file__).resolve().parents[1] +BASELINE = ML_DIR / "baselines" / "gate12.json" + + +@pytest.fixture(scope="module") +def baseline() -> dict: + """ + The committed gate12 baseline report. + + Returns: + Parsed JSON. + """ + return json.loads(BASELINE.read_text()) + + +def test_gate12_baseline_matches_the_frozen_registry(baseline: dict) -> None: + """The baseline's dataset hash and classes are exactly what ml/frozen_sets.json froze.""" + registry = json.loads((ML_DIR / "frozen_sets.json").read_text()) + dataset = baseline["run"]["dataset"] + entry = registry[dataset["frozen_name"]] + assert entry["sha256"] == dataset["sha256"] + assert entry["classes"] == dataset["classes"] + assert entry["images"] == dataset["images"] == 78 + + +def test_gate12_baseline_reproduced_the_old_numbers(baseline: dict) -> None: + """The old validation numbers were reproduced within tolerance, and the new blocks are present.""" + assert baseline["reproduction"]["ok"] is True + assert baseline["reproduction"]["max_abs_delta"] <= baseline["reproduction"]["tolerance"] + detection = baseline["detection"] + assert set(detection["per_class"]) == set(baseline["run"]["dataset"]["classes"]) + assert {"synthetic", "roboflow_real"} <= set(detection["per_domain"]) + assert detection["junction_recall"]["value"] == pytest.approx(0.957, abs=0.001) + assert baseline["run"]["weights"]["sha256"] and baseline["baseline"]["weights"].startswith("not committed") diff --git a/ml/tests/test_eval_frozen.py b/ml/tests/test_eval_frozen.py new file mode 100644 index 0000000..fff95b8 --- /dev/null +++ b/ml/tests/test_eval_frozen.py @@ -0,0 +1,81 @@ +""" +Module: test_eval_frozen.py +Purpose: Unit tests for ml/eval_frozen.py - the frozen test-set hash is deterministic, sensitive to + any image/label/netlist/class change, ignores caches, and the registry refuses unknown, + changed and re-frozen sets. +""" + +from pathlib import Path + +import pytest + +from eval_frozen import FrozenSetError, freeze, hash_split, verify_frozen + +NAMES = ["A", "B"] + + +def make_dataset(root: Path) -> Path: + """ + Create a tiny dataset with a test split. + + Args: + root: Dataset root to populate. + Returns: + The root. + """ + (root / "images" / "test").mkdir(parents=True) + (root / "labels" / "test").mkdir(parents=True) + (root / "images" / "test" / "syn_0.jpg").write_bytes(b"image-bytes") + (root / "labels" / "test" / "syn_0.txt").write_text("0 0.5 0.5 0.1 0.1\n") + return root + + +def test_hash_is_deterministic_and_ignores_caches(tmp_path: Path) -> None: + """Same bytes -> same hash; a label cache file does not change it.""" + root = make_dataset(tmp_path / "d") + first = hash_split(root, "test", NAMES) + (root / "labels" / "test.cache").write_bytes(b"cache") + again = hash_split(root, "test", NAMES) + assert first == again and first.images == 1 and first.labels == 1 and first.netlists == 0 + + +@pytest.mark.parametrize("change", ["label", "image", "classes", "extra_label", "netlist"]) +def test_hash_changes_when_anything_changes(tmp_path: Path, change: str) -> None: + """Editing a label or image, reordering classes, adding a file or a netlist all change the hash.""" + root = make_dataset(tmp_path / "d") + before = hash_split(root, "test", NAMES).sha256 + names = NAMES + if change == "label": + (root / "labels" / "test" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") + elif change == "image": + (root / "images" / "test" / "syn_0.jpg").write_bytes(b"other") + elif change == "classes": + names = ["B", "A"] + elif change == "extra_label": + (root / "labels" / "test" / "syn_1.txt").write_text("") + else: + (root / "netlists" / "test").mkdir(parents=True) + (root / "netlists" / "test" / "syn_0.json").write_text("{}") + assert hash_split(root, "test", names).sha256 != before + + +def test_registry_refuses_unknown_changed_and_refrozen(tmp_path: Path) -> None: + """verify_frozen raises for unregistered and modified sets; freeze never overwrites.""" + root = make_dataset(tmp_path / "d") + registry = tmp_path / "frozen.json" + digest = hash_split(root, "test", NAMES) + with pytest.raises(FrozenSetError, match="not registered"): + verify_frozen("t", digest, registry) + freeze("t", digest, "test", "note", registry) + verify_frozen("t", digest, registry) + with pytest.raises(FrozenSetError, match="already registered"): + freeze("t", digest, "test", "note", registry) + (root / "labels" / "test" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") + with pytest.raises(FrozenSetError, match="changed"): + verify_frozen("t", hash_split(root, "test", NAMES), registry) + + +def test_missing_split_directory_raises(tmp_path: Path) -> None: + """A dataset without the requested split cannot be hashed.""" + with pytest.raises(FileNotFoundError): + hash_split(tmp_path, "test", NAMES) diff --git a/ml/tests/test_eval_metrics.py b/ml/tests/test_eval_metrics.py new file mode 100644 index 0000000..8061ec2 --- /dev/null +++ b/ml/tests/test_eval_metrics.py @@ -0,0 +1,110 @@ +""" +Module: test_eval_metrics.py +Purpose: Unit tests for ml/eval_metrics.py - Wilson intervals, IoU matching, the confusion matrix + accumulator, per-class records, small-object recall and domain resolution. +""" + +import numpy as np +import pytest + +from eval_metrics import DetectionAccumulator, box_iou, domain_for, match_boxes, parse_domain_rule, rate, wilson_interval + + +def gt_rows(*rows: tuple[int, float, float, float, float]) -> np.ndarray: + """ + Build a ground-truth array. + + Args: + rows: (cls, x1, y1, x2, y2) tuples. + Returns: + (n, 5) float array. + """ + return np.asarray(rows, dtype=float).reshape(-1, 5) + + +def pred_rows(*rows: tuple[int, float, float, float, float, float]) -> np.ndarray: + """ + Build a prediction array. + + Args: + rows: (cls, conf, x1, y1, x2, y2) tuples. + Returns: + (m, 6) float array. + """ + return np.asarray(rows, dtype=float).reshape(-1, 6) + + +def test_wilson_matches_reference_values() -> None: + """Known Wilson 95% intervals: 8/10, 0/10, 10/10.""" + lo, hi = wilson_interval(8, 10) + assert lo == pytest.approx(0.4902, abs=1e-3) and hi == pytest.approx(0.9433, abs=1e-3) + lo, hi = wilson_interval(0, 10) + assert lo == 0.0 and hi == pytest.approx(0.2775, abs=1e-3) + lo, hi = wilson_interval(10, 10) + assert hi == 1.0 and lo == pytest.approx(0.7225, abs=1e-3) + + +def test_wilson_edge_cases() -> None: + """Empty denominators give no interval; invalid counts raise.""" + assert wilson_interval(0, 0) is None + assert rate(0, 0) == {"value": None, "ci95": None, "n": 0} + with pytest.raises(ValueError): + wilson_interval(5, 3) + + +def test_box_iou_and_match_is_one_to_one() -> None: + """Identical boxes have IoU 1; a duplicate prediction cannot match the same GT twice.""" + a = np.array([[0, 0, 10, 10]], dtype=float) + assert box_iou(a, a)[0, 0] == pytest.approx(1.0) + gt = gt_rows((0, 0, 0, 10, 10)) + preds = pred_rows((0, 0.9, 0, 0, 10, 10), (0, 0.8, 1, 1, 10, 10)) + assert match_boxes(gt, preds) == [(0, 0)] + assert match_boxes(gt, pred_rows()) == [] + + +def test_accumulator_counts_hits_misses_confusions_and_spurious() -> None: + """One TP, one misclassification, one miss and one spurious detection land in the right cells.""" + acc = DetectionAccumulator(n_classes=2) + gt = gt_rows((0, 0, 0, 20, 20), (1, 100, 100, 140, 140), (1, 200, 200, 240, 240)) + preds = pred_rows( + (0, 0.9, 0, 0, 20, 20), # correct class 0 + (0, 0.8, 100, 100, 140, 140), # class 1 object predicted as 0 + (1, 0.7, 400, 400, 440, 440), # spurious class 1 + ) + acc.add_image(gt, preds) + # rows = predicted (0, 1, background), cols = ground truth (0, 1, background) + assert acc.matrix.tolist() == [[1, 1, 0], [0, 0, 1], [0, 1, 0]] + per_class = acc.per_class(["A", "B"]) + assert per_class["A"]["tp"] == 1 and per_class["A"]["fp"] == 1 and per_class["A"]["fn"] == 0 + assert per_class["B"]["gt"] == 2 and per_class["B"]["fn"] == 2 and per_class["B"]["fp"] == 1 + assert per_class["B"]["recall"]["value"] == 0.0 and per_class["B"]["accuracy"]["value"] == 0.0 + assert per_class["A"]["low_support"] is True + + +def test_small_object_recall_and_unmapped_predictions() -> None: + """Only boxes with longest side <= small_px count as small; class -1 predictions are tracked, not scored as a class.""" + acc = DetectionAccumulator(n_classes=1, small_px=12) + gt = gt_rows((0, 0, 0, 10, 10), (0, 50, 50, 90, 90)) + preds = pred_rows((0, 0.9, 0, 0, 10, 10), (-1, 0.9, 50, 50, 90, 90), (-1, 0.5, 300, 300, 320, 320)) + acc.add_image(gt, preds) + overall = acc.overall() + assert overall["small_object"]["recall"]["n"] == 1 and overall["small_object"]["recall"]["value"] == 1.0 + assert overall["unmapped_predictions"] == 1 # the unmatched one + assert acc.per_class(["A"])["A"]["fn"] == 1 # the big box was "matched" by an out-of-vocabulary prediction: still a miss + + +def test_out_of_range_ground_truth_class_raises() -> None: + """A GT class id outside the vocabulary is a data error.""" + acc = DetectionAccumulator(n_classes=2) + with pytest.raises(ValueError): + acc.add_image(gt_rows((5, 0, 0, 1, 1)), pred_rows()) + + +def test_domains() -> None: + """Prefix rules resolve domains; custom rules parse and malformed ones are rejected.""" + assert domain_for("syn_test_00001.jpg") == "synthetic" + assert domain_for("rf_x.jpg") == "roboflow_real" + assert domain_for("mystery.jpg") == "unknown" + assert parse_domain_rule("cghd_=cghd_real") == ("cghd_", "cghd_real") + with pytest.raises(ValueError): + parse_domain_rule("nonsense") diff --git a/ml/tests/test_eval_netlist.py b/ml/tests/test_eval_netlist.py new file mode 100644 index 0000000..ee3c794 --- /dev/null +++ b/ml/tests/test_eval_netlist.py @@ -0,0 +1,176 @@ +""" +Module: test_eval_netlist.py +Purpose: Tests for ml/eval_netlist.py - netlist validation, component matching (by bbox and by id), + pin-pair net precision/recall, exact match, bulk-pin handling, conversion to a DigiSim + canvas, and truth-table equivalence through DigiSim's real simulator (skipped when node or + the frontend dependencies are unavailable). +""" + +import copy +import json +from pathlib import Path + +import pytest +from conftest import nand_netlist + +from eval_netlist import ( + BridgeError, + NetlistError, + evaluate_netlists, + match_components, + parse_netlist, + pin_pairs, + remap_pins, + run_truth_tables, + scored_nets, + to_digisim, +) + + +def simulator_available() -> bool: + """ + Whether the Node simulator bridge can run here. + + Returns: + True when a trivial circuit simulates. + """ + try: + run_truth_tables({"probe": to_digisim(parse_netlist(nand_netlist()))}) + except BridgeError: + return False + return True + + +needs_simulator = pytest.mark.skipif(not simulator_available(), reason="node and `cd frontend && npm install` are required for truth-table tests") + + +def test_parse_rejects_bad_netlists() -> None: + """Unknown types, duplicate ids, bad pins and unknown terminals are errors.""" + ok = nand_netlist() + bad_type = copy.deepcopy(ok) + bad_type["components"][0]["type"] = "flux_capacitor" + bad_pin = copy.deepcopy(ok) + bad_pin["nets"][0].append("MP1:zzz") + dup = copy.deepcopy(ok) + dup["components"].append(dict(dup["components"][0])) + for broken in (bad_type, bad_pin, dup, {"components": []}): + with pytest.raises(NetlistError): + parse_netlist(broken) + + +def test_nets_sharing_a_pin_are_merged() -> None: + """Two listed nets that share a pin are one net.""" + raw = nand_netlist() + raw["nets"] = [["A:out", "MP1:g"], ["MP1:g", "MN1:g"]] + net = parse_netlist(raw).nets + assert net == [frozenset({"A:out", "MP1:g", "MN1:g"})] + + +def test_bulk_pins_are_not_scored_by_default() -> None: + """A bulk connection is ignored unless score_bulk is set.""" + raw = nand_netlist() + raw["nets"][2].append("MP1:b") + netlist = parse_netlist(raw) + assert all("MP1:b" not in net for net in scored_nets(netlist)) + assert any("MP1:b" in net for net in scored_nets(netlist, score_bulk=True)) + + +def test_match_by_bbox_survives_renamed_ids_and_small_shifts() -> None: + """Predicted components are paired with ground truth by IoU and type, not id.""" + gt = parse_netlist(nand_netlist(with_boxes=True)) + pred = parse_netlist(nand_netlist(with_boxes=True, prefix="p_", shift=2.0)) + mapping = match_components(gt, pred) + assert mapping == {f"p_{c}": c for c in gt.components} + assert pin_pairs(remap_pins(scored_nets(pred), mapping)) == pin_pairs(scored_nets(gt)) + with pytest.raises(ValueError): + match_components(parse_netlist(nand_netlist()), pred, "bbox") + + +def run_one(tmp_path: Path, pred: dict | None, gt: dict | None = None, **kwargs) -> dict: + """ + Evaluate a single prediction against a ground truth (default: a boxed NAND). + + Args: + tmp_path: Temporary directory. + pred: Predicted netlist dict. + gt: Ground-truth netlist dict. + **kwargs: Extra evaluate_netlists arguments. + Returns: + The overall end-to-end record. + """ + (tmp_path / "gt").mkdir(exist_ok=True) + (tmp_path / "pred").mkdir(exist_ok=True) + (tmp_path / "gt" / "syn_0.json").write_text(json.dumps(gt or nand_netlist(with_boxes=True))) + if pred is not None: + (tmp_path / "pred" / "syn_0.json").write_text(json.dumps(pred)) + return evaluate_netlists(tmp_path / "gt", tmp_path / "pred", **kwargs) + + +def test_perfect_prediction_scores_one(tmp_path: Path) -> None: + """Same circuit under renamed ids: P = R = F1 = 1 and exact match.""" + result = run_one(tmp_path, nand_netlist(with_boxes=True, prefix="p_", shift=1.0), truth_table=False) + overall = result["overall"] + assert overall["net_micro"]["f1"] == 1.0 and overall["exact_match"]["value"] == 1.0 + assert result["circuits"]["syn_0"]["domain"] == "synthetic" + + +def test_missing_wire_lowers_recall_only(tmp_path: Path) -> None: + """Dropping a pin from a net removes true pairs (recall down, precision still 1) and breaks exact match.""" + pred = nand_netlist(with_boxes=True) + pred["nets"][3].remove("MN1:d") + overall = run_one(tmp_path, pred, truth_table=False)["overall"] + assert overall["net_micro"]["precision"] == 1.0 + assert overall["net_micro"]["recall"] < 1.0 + assert overall["exact_match"]["value"] == 0.0 + + +def test_spurious_component_breaks_exact_match_but_not_recall(tmp_path: Path) -> None: + """An extra predicted component with a spurious wire adds false pairs and fails exact match.""" + pred = nand_netlist(with_boxes=True) + pred["components"].append({"id": "X", "type": "nmos", "bbox": [5000, 5000, 5060, 5090]}) + pred["nets"].append(["X:d", "GND:gnd"]) + overall = run_one(tmp_path, pred, truth_table=False)["overall"] + assert overall["net_micro"]["recall"] == 1.0 and overall["net_micro"]["precision"] < 1.0 + assert overall["exact_match"]["value"] == 0.0 + + +def test_missing_and_malformed_predictions_score_zero(tmp_path: Path) -> None: + """No prediction file, or an invalid one, is an empty circuit with the error recorded.""" + missing = run_one(tmp_path, None, truth_table=False)["circuits"]["syn_0"] + assert missing["pred_error"] == "missing prediction" and missing["pairs"]["tp"] == 0 and missing["exact_match"] is False + broken = nand_netlist(with_boxes=True) + broken["nets"][0].append("NOPE:g") + bad = run_one(tmp_path, broken, truth_table=False)["circuits"]["syn_0"] + assert bad["pred_error"] and bad["pairs"]["tp"] == 0 + + +def test_to_digisim_uses_app_handle_ids() -> None: + """Transistor pins become t:/s: handles, gate inputs plain handles, and drivers root their nets.""" + graph = to_digisim(parse_netlist(nand_netlist())) + edges = {(e["source"], e["sourceHandle"], e["target"], e["targetHandle"]) for e in graph["edges"]} + assert ("A", None, "MP1", "t:g") in edges # input drives a transistor gate + assert ("MN1", "s:d", "Y", None) in edges # transistor drain into the output node (root = first non-output pin) + gate = parse_netlist({"components": [{"id": "G", "type": "andGate"}, {"id": "I", "type": "input"}], "nets": [["I:out", "G:a"]]}) + assert [(e["source"], e["target"], e["targetHandle"]) for e in to_digisim(gate)["edges"]] == [("I", "G", "a")] + + +@needs_simulator +def test_truth_table_equivalence_with_digisim_simulator(tmp_path: Path) -> None: + """A correct NAND is equivalent under renamed ids; a NAND with its NMOS stack in parallel (a different function) is not.""" + good = run_one(tmp_path, nand_netlist(with_boxes=True, prefix="p_", shift=1.0))["overall"] + assert good["truth_table"]["value"] == 1.0 and good["truth_table"]["n"] == 1 + wrong = nand_netlist(with_boxes=True) + wrong["nets"][4] = ["MN1:s", "GND:gnd"] # both NMOS now sink straight to ground: parallel, i.e. NOR-like pull-down + wrong["nets"][5] = ["MN2:s", "GND:gnd", "MN1:s"] + wrong["nets"][3] = ["MP1:d", "MP2:d", "MN1:d", "MN2:d", "Y:a"] + result = run_one(tmp_path, wrong)["overall"] + assert result["truth_table"]["value"] == 0.0 + assert result["net_micro"]["f1"] > 0.6 # structurally close, functionally wrong: why both metrics exist + + +@needs_simulator +def test_truth_table_of_ground_truth_nand_is_correct() -> None: + """The simulator returns the NAND truth table for the fixture (A, B -> Y).""" + table = run_truth_tables({"nand": to_digisim(parse_netlist(nand_netlist()))})["nand"] + assert table["inputs"] == ["A", "B"] and table["outputs"] == ["Y"] + assert table["rows"] == [[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 0]] diff --git a/ml/tests/test_evaluate.py b/ml/tests/test_evaluate.py new file mode 100644 index 0000000..a9408e2 --- /dev/null +++ b/ml/tests/test_evaluate.py @@ -0,0 +1,104 @@ +""" +Module: test_evaluate.py +Purpose: Tests for ml/evaluate.py helpers and CLI behaviour that need no trained weights: label + parsing, class-name mapping (incl. legacy aliases), the reproduction check, the markdown + renderer, and the refusal to run when the frozen test set changed. +""" + +import json +from pathlib import Path + +import numpy as np +import pytest +from conftest import nand_netlist +from test_eval_frozen import make_dataset + +from eval_report import render_markdown +from evaluate import build_class_map, main, read_labels, reproduction_check + + +def test_read_labels_handles_boxes_polygons_and_missing_files(tmp_path: Path) -> None: + """YOLO boxes and polygons become pixel xyxy; a missing file is empty ground truth.""" + label = tmp_path / "a.txt" + label.write_text("2 0.5 0.5 0.2 0.4\n1 0.1 0.1 0.3 0.1 0.3 0.5 0.1 0.5\n\n") + rows = read_labels(label, 100, 200) + assert rows.shape == (2, 5) + assert rows[0].tolist() == pytest.approx([2, 40, 60, 60, 140]) + assert rows[1].tolist() == pytest.approx([1, 10, 20, 30, 100]) + assert read_labels(tmp_path / "none.txt", 10, 10).shape == (0, 5) + label.write_text("1 0.1 0.2\n") + with pytest.raises(ValueError): + read_labels(label, 10, 10) + + +def test_class_map_by_name_then_alias() -> None: + """Names match directly; legacy aliases resolve to the canonical dataset class; unknown classes map to -1.""" + aliases = {"SWITCH": "INPUT_PORT", "LED": "OUTPUT_PORT"} + mapping = build_class_map({0: "NMOS", 1: "SWITCH", 2: "LED", 3: "mystery"}, ("NMOS", "INPUT_PORT", "OUTPUT_PORT"), aliases) + assert mapping == [0, 1, 2, -1] + assert build_class_map({0: "SWITCH"}, ("SWITCH", "INPUT_PORT"), aliases) == [0] # an exact name beats the alias + + +def test_reproduction_check_tolerance() -> None: + """Within tolerance passes, beyond it fails, and a metric missing from the run counts as a failure.""" + legacy = {"map50": 0.99, "map50_95": 0.95, "per_class": {"A": {"f1": 0.97, "accuracy": 0.96}}} + ref = {"map50": 0.992, "map50_95": 0.949, "per_class": {"A": {"f1": 0.9705, "accuracy": 0.96}}} + assert reproduction_check(legacy, ref, 0.01, "ref")["ok"] is True + assert reproduction_check(legacy, ref, 0.0001, "ref")["ok"] is False + ref["per_class"]["B"] = {"f1": 0.9} + assert reproduction_check(legacy, ref, 0.5, "ref")["ok"] is False + + +def write_yaml(root: Path) -> Path: + """ + Write a data.yaml for the tiny test dataset. + + Args: + root: Dataset root. + Returns: + The yaml path. + """ + data = root / "data.yaml" + data.write_text(f"path: {root}\ntrain: images/test\nval: images/test\ntest: images/test\nnames: [A, B]\n") + return data + + +def test_cli_refuses_changed_frozen_set_and_requires_a_name(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """freeze -> verified run works; editing a label makes the run exit 3 with no report; the test split needs --frozen-name.""" + root = make_dataset(tmp_path / "d") + data = write_yaml(root) + registry = tmp_path / "frozen.json" + out = tmp_path / "out" + common = ["--data", str(data), "--registry", str(registry), "--out-dir", str(out), "--skip-detection"] + with pytest.raises(SystemExit): + main([*common]) # test split without --frozen-name + assert main([*common, "--frozen-name", "t", "--freeze", "--freeze-note", "tiny"]) == 0 + assert main([*common, "--frozen-name", "t"]) == 0 + assert main(common) == 0 # name inferred: one registered set has this split and class list + report = json.loads((out / "t.json").read_text()) + assert report["run"]["dataset"]["sha256"] == json.loads(registry.read_text())["t"]["sha256"] + (out / "t.json").unlink() + (root / "labels" / "test" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") + assert main([*common, "--frozen-name", "t"]) == 3 + assert not (out / "t.json").exists() + assert "refusing to evaluate" in capsys.readouterr().err + + +def test_end_to_end_report_renders_markdown(tmp_path: Path) -> None: + """An end-to-end-only run writes JSON plus a Markdown table with the three headline metrics.""" + root = make_dataset(tmp_path / "d") + (root / "netlists" / "test").mkdir(parents=True) + (root / "netlists" / "test" / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True))) + pred = tmp_path / "pred" + pred.mkdir() + (pred / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True, prefix="p_", shift=1.0))) + data, out = write_yaml(root), tmp_path / "out" + args = ["--data", str(data), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-detection", "--frozen-name", "t"] + assert main([*args, "--freeze"]) == 0 + assert main([*args, "--gt-netlists", str(root / "netlists" / "test"), "--pred-netlists", str(pred), "--no-truth-table"]) == 0 + markdown = (out / "t.md").read_text() + assert "End-to-end (netlist)" in markdown and "exact match" in markdown + report = json.loads((out / "t.json").read_text()) + assert report["end_to_end"]["overall"]["net_micro"]["f1"] == 1.0 + assert render_markdown(report, report).count("# DigiSim evaluation") == 1 + assert np.isclose(report["end_to_end"]["overall"]["exact_match"]["value"], 1.0) diff --git a/ml/uv.lock b/ml/uv.lock index b2f7248..260f0be 100644 --- a/ml/uv.lock +++ b/ml/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.12' and sys_platform == 'win32'", @@ -106,6 +106,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/db/8f/61959034484a4a7c527811f4721e75d02d653a35afb0b6054474d8185d4c/charset_normalizer-3.4.7-py3-none-any.whl", hash = "sha256:3dce51d0f5e7951f8bb4900c257dad282f49190fdbebecd4ba99bcc41fef404d", size = 61958, upload-time = "2026-04-02T09:28:37.794Z" }, ] +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + [[package]] name = "contourpy" version = "1.3.3" @@ -194,7 +203,7 @@ name = "cuda-bindings" version = "13.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder", marker = "sys_platform != 'win32'" }, + { name = "cuda-pathfinder" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/51/6b/457ca12dad3ee9bfcc9a545cfd6b64b359ba49de40f776f6e028e678f262/cuda_bindings-13.3.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5879712accf6e14bb01aa5e67440eb84998b8d104b509cc7a6dc0b8f656a474", size = 6053539, upload-time = "2026-05-29T23:11:43.19Z" }, @@ -227,34 +236,34 @@ wheels = [ [package.optional-dependencies] cudart = [ - { name = "nvidia-cuda-runtime", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-runtime" }, ] cufft = [ - { name = "nvidia-cufft", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufft" }, ] cufile = [ - { name = "nvidia-cufile", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cufile" }, ] cupti = [ - { name = "nvidia-cuda-cupti", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-cupti" }, ] curand = [ - { name = "nvidia-curand", marker = "sys_platform == 'linux'" }, + { name = "nvidia-curand" }, ] cusolver = [ - { name = "nvidia-cusolver", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusolver" }, ] cusparse = [ - { name = "nvidia-cusparse", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusparse" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvjitlink" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cuda-nvrtc" }, ] nvtx = [ - { name = "nvidia-nvtx", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvtx" }, ] [[package]] @@ -280,6 +289,7 @@ dependencies = [ [package.dev-dependencies] dev = [ + { name = "pytest" }, { name = "ruff" }, ] @@ -292,7 +302,10 @@ requires-dist = [ ] [package.metadata.requires-dev] -dev = [{ name = "ruff", specifier = ">=0.4" }] +dev = [ + { name = "pytest", specifier = ">=8.0" }, + { name = "ruff", specifier = ">=0.4" }, +] [[package]] name = "filelock" @@ -370,6 +383,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/1e/5e/d4e9f1a599fb8e573b7b87160658329fbf28d19eac2718f51fc3def3aa5a/idna-3.18-py3-none-any.whl", hash = "sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2", size = 65455, upload-time = "2026-06-02T14:34:06.319Z" }, ] +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + [[package]] name = "jinja2" version = "3.1.6" @@ -788,7 +810,7 @@ name = "nvidia-cublas" version = "13.1.1.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cuda-nvrtc", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cuda-nvrtc" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, @@ -827,7 +849,7 @@ name = "nvidia-cudnn-cu13" version = "9.20.0.48" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cublas" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" }, @@ -839,7 +861,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "sys_platform != 'win32'" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, @@ -869,9 +891,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas", marker = "sys_platform != 'win32'" }, - { name = "nvidia-cusparse", marker = "sys_platform != 'win32'" }, - { name = "nvidia-nvjitlink", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cublas" }, + { name = "nvidia-cusparse" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, @@ -883,7 +905,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink", marker = "sys_platform != 'win32'" }, + { name = "nvidia-nvjitlink" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, @@ -1078,6 +1100,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" }, ] +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + [[package]] name = "polars" version = "1.42.1" @@ -1134,6 +1165,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, ] +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + [[package]] name = "pyparsing" version = "3.3.2" @@ -1143,6 +1183,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, ] +[[package]] +name = "pytest" +version = "9.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, +] + [[package]] name = "python-dateutil" version = "2.9.0.post0" From d9704ddf5ed6216ee7ecd635f35d39b2c1cfec8f Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 01:17:36 +0530 Subject: [PATCH 2/5] no-mistakes(review): Hash resolved split dirs; pass domain rules to netlist eval --- ml/eval_frozen.py | 23 ++++----------- ml/eval_netlist.py | 6 ++-- ml/evaluate.py | 8 ++++-- ml/tests/test_eval_frozen.py | 40 ++++++++++++++++++++------ ml/tests/test_evaluate.py | 56 +++++++++++++++++++++++++++++++++++- 5 files changed, 101 insertions(+), 32 deletions(-) diff --git a/ml/eval_frozen.py b/ml/eval_frozen.py index 6156d86..d56e675 100644 --- a/ml/eval_frozen.py +++ b/ml/eval_frozen.py @@ -52,33 +52,20 @@ def file_sha256(path: Path) -> str: return digest.hexdigest() -def split_dirs(dataset_root: Path, split: str) -> tuple[Path, Path, Path]: +def hash_split(images_dir: Path, labels_dir: Path, netlists_dir: Path, class_names: Sequence[str]) -> SplitDigest: """ - The image, label and netlist directories of a split. + Deterministic digest of a dataset split, over exactly the directories an evaluation reads. Args: - dataset_root: Dataset root (the `path:` of data.yaml). - split: Split name such as 'test'. - Returns: - (images/, labels/, netlists/); the netlist directory may not exist. - """ - return dataset_root / "images" / split, dataset_root / "labels" / split, dataset_root / "netlists" / split - - -def hash_split(dataset_root: Path, split: str, class_names: Sequence[str]) -> SplitDigest: - """ - Deterministic digest of a dataset split. - - Args: - dataset_root: Dataset root directory. - split: Split name. + images_dir: Directory holding the split's images. + labels_dir: Directory holding the split's YOLO label files. + netlists_dir: Directory holding the split's ground-truth netlists (may not exist). class_names: Class names in id order (label ids are meaningless without them). Returns: The SplitDigest. Only *.txt labels, image files and *.json netlists count; caches are ignored. Raises: FileNotFoundError: If the image or label directory does not exist. """ - images_dir, labels_dir, netlists_dir = split_dirs(dataset_root, split) for required in (images_dir, labels_dir): if not required.is_dir(): raise FileNotFoundError(f"Split directory missing: {required}") diff --git a/ml/eval_netlist.py b/ml/eval_netlist.py index 86d5a5f..ec431fa 100644 --- a/ml/eval_netlist.py +++ b/ml/eval_netlist.py @@ -31,7 +31,7 @@ import numpy as np from class_schema import load_schema -from eval_metrics import IOU_MATCH_THRESHOLD, LOW_SUPPORT_N, box_iou, domain_for, rate +from eval_metrics import DEFAULT_DOMAIN_RULES, IOU_MATCH_THRESHOLD, LOW_SUPPORT_N, box_iou, domain_for, rate ML_DIR = Path(__file__).resolve().parent BRIDGE_SCRIPT = ML_DIR / "sim_bridge" / "truth_table.cjs" @@ -443,6 +443,7 @@ def evaluate_netlists( truth_table: bool = True, match_mode: str = "auto", score_bulk: bool = False, + domain_rules: Sequence[tuple[str, str]] = DEFAULT_DOMAIN_RULES, ) -> dict[str, object]: """ End-to-end metrics over every ground-truth netlist in gt_dir. @@ -455,6 +456,7 @@ def evaluate_netlists( truth_table: Also compute truth-table equivalence with DigiSim's simulator. match_mode: Component pairing mode (see match_components). score_bulk: Score MOSFET bulk pins too. + domain_rules: (filename prefix, domain) rules used to group circuits per domain. Returns: Dict with per-circuit records, micro/macro net P/R/F1, exact-match rate and truth-table equivalence rate (with Wilson CIs), overall and per domain. @@ -488,7 +490,7 @@ def evaluate_netlists( comps_ok = len(pred.components) == len(gt.components) == len(mapping) records[stem] = CircuitResult( stem=stem, - domain=domain_for(stem), + domain=domain_for(stem, domain_rules), gt_components=len(gt.components), pred_components=len(pred.components), matched_components=len(mapping), diff --git a/ml/evaluate.py b/ml/evaluate.py index 40f6421..a0c836d 100644 --- a/ml/evaluate.py +++ b/ml/evaluate.py @@ -72,6 +72,7 @@ class DatasetInfo: names: tuple[str, ...] images_dir: Path labels_dir: Path + netlists_dir: Path def load_dataset_info(data: Path, split: str) -> DatasetInfo: @@ -104,9 +105,10 @@ def load_dataset_info(data: Path, split: str) -> DatasetInfo: root = (data.parent / root).resolve() images_dir = root / str(doc[key]) labels_dir = root / str(doc[key]).replace("images", "labels", 1) + netlists_dir = root / str(doc[key]).replace("images", "netlists", 1) if not images_dir.is_dir(): raise FileNotFoundError(f"Split images directory missing: {images_dir}") - return DatasetInfo(root=root, names=names, images_dir=images_dir, labels_dir=labels_dir) + return DatasetInfo(root=root, names=names, images_dir=images_dir, labels_dir=labels_dir, netlists_dir=netlists_dir) def read_labels(label_file: Path, width: int, height: int) -> np.ndarray: @@ -448,7 +450,7 @@ def main(argv: list[str] | None = None) -> int: parser.error("--gt-netlists and --pred-netlists go together") info = load_dataset_info(args.data, args.split) - digest: SplitDigest = hash_split(info.root, args.split, info.names) + digest: SplitDigest = hash_split(info.images_dir, info.labels_dir, args.gt_netlists or info.netlists_dir, info.names) if not args.freeze and not args.frozen_name: args.frozen_name = infer_frozen_name(args.split, info.names, args.registry) if args.split == "test" and not args.frozen_name: @@ -503,7 +505,7 @@ def main(argv: list[str] | None = None) -> int: elif args.reproduce: parser.error("--reproduce needs the legacy block (drop --skip-legacy)") if args.gt_netlists: - report["end_to_end"] = evaluate_netlists(args.gt_netlists, args.pred_netlists, not args.no_truth_table, args.match_mode, args.score_bulk) + report["end_to_end"] = evaluate_netlists(args.gt_netlists, args.pred_netlists, not args.no_truth_table, args.match_mode, args.score_bulk, rules) args.out_dir.mkdir(parents=True, exist_ok=True) stem = report["run"]["name"] diff --git a/ml/tests/test_eval_frozen.py b/ml/tests/test_eval_frozen.py index fff95b8..311b344 100644 --- a/ml/tests/test_eval_frozen.py +++ b/ml/tests/test_eval_frozen.py @@ -9,7 +9,7 @@ import pytest -from eval_frozen import FrozenSetError, freeze, hash_split, verify_frozen +from eval_frozen import FrozenSetError, SplitDigest, freeze, hash_split, verify_frozen NAMES = ["A", "B"] @@ -30,12 +30,25 @@ def make_dataset(root: Path) -> Path: return root +def hash_test_split(root: Path, names: list[str]) -> SplitDigest: + """ + Hash the conventional images/test, labels/test and netlists/test directories of a dataset. + + Args: + root: Dataset root. + names: Class names in id order. + Returns: + The split digest. + """ + return hash_split(root / "images" / "test", root / "labels" / "test", root / "netlists" / "test", names) + + def test_hash_is_deterministic_and_ignores_caches(tmp_path: Path) -> None: """Same bytes -> same hash; a label cache file does not change it.""" root = make_dataset(tmp_path / "d") - first = hash_split(root, "test", NAMES) + first = hash_test_split(root, NAMES) (root / "labels" / "test.cache").write_bytes(b"cache") - again = hash_split(root, "test", NAMES) + again = hash_test_split(root, NAMES) assert first == again and first.images == 1 and first.labels == 1 and first.netlists == 0 @@ -43,7 +56,7 @@ def test_hash_is_deterministic_and_ignores_caches(tmp_path: Path) -> None: def test_hash_changes_when_anything_changes(tmp_path: Path, change: str) -> None: """Editing a label or image, reordering classes, adding a file or a netlist all change the hash.""" root = make_dataset(tmp_path / "d") - before = hash_split(root, "test", NAMES).sha256 + before = hash_test_split(root, NAMES).sha256 names = NAMES if change == "label": (root / "labels" / "test" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") @@ -56,14 +69,14 @@ def test_hash_changes_when_anything_changes(tmp_path: Path, change: str) -> None else: (root / "netlists" / "test").mkdir(parents=True) (root / "netlists" / "test" / "syn_0.json").write_text("{}") - assert hash_split(root, "test", names).sha256 != before + assert hash_test_split(root, names).sha256 != before def test_registry_refuses_unknown_changed_and_refrozen(tmp_path: Path) -> None: """verify_frozen raises for unregistered and modified sets; freeze never overwrites.""" root = make_dataset(tmp_path / "d") registry = tmp_path / "frozen.json" - digest = hash_split(root, "test", NAMES) + digest = hash_test_split(root, NAMES) with pytest.raises(FrozenSetError, match="not registered"): verify_frozen("t", digest, registry) freeze("t", digest, "test", "note", registry) @@ -72,10 +85,21 @@ def test_registry_refuses_unknown_changed_and_refrozen(tmp_path: Path) -> None: freeze("t", digest, "test", "note", registry) (root / "labels" / "test" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") with pytest.raises(FrozenSetError, match="changed"): - verify_frozen("t", hash_split(root, "test", NAMES), registry) + verify_frozen("t", hash_test_split(root, NAMES), registry) def test_missing_split_directory_raises(tmp_path: Path) -> None: """A dataset without the requested split cannot be hashed.""" with pytest.raises(FileNotFoundError): - hash_split(tmp_path, "test", NAMES) + hash_test_split(tmp_path, NAMES) + + +def test_hash_follows_the_directories_it_is_given(tmp_path: Path) -> None: + """The digest depends on the directories passed in, not on a split name: identical bytes elsewhere hash the same.""" + root = make_dataset(tmp_path / "d") + other = tmp_path / "other" + (other / "pics").mkdir(parents=True) + (other / "tags").mkdir() + (other / "pics" / "syn_0.jpg").write_bytes(b"image-bytes") + (other / "tags" / "syn_0.txt").write_text("0 0.5 0.5 0.1 0.1\n") + assert hash_split(other / "pics", other / "tags", other / "none", NAMES).sha256 == hash_test_split(root, NAMES).sha256 diff --git a/ml/tests/test_evaluate.py b/ml/tests/test_evaluate.py index a9408e2..77451d6 100644 --- a/ml/tests/test_evaluate.py +++ b/ml/tests/test_evaluate.py @@ -14,7 +14,7 @@ from test_eval_frozen import make_dataset from eval_report import render_markdown -from evaluate import build_class_map, main, read_labels, reproduction_check +from evaluate import build_class_map, load_dataset_info, main, read_labels, reproduction_check def test_read_labels_handles_boxes_polygons_and_missing_files(tmp_path: Path) -> None: @@ -102,3 +102,57 @@ def test_end_to_end_report_renders_markdown(tmp_path: Path) -> None: assert report["end_to_end"]["overall"]["net_micro"]["f1"] == 1.0 assert render_markdown(report, report).count("# DigiSim evaluation") == 1 assert np.isclose(report["end_to_end"]["overall"]["exact_match"]["value"], 1.0) + + +def test_frozen_hash_covers_the_directories_data_yaml_names(tmp_path: Path) -> None: + """A split entry that is not images/ is hashed where it points: editing that directory is refused.""" + root = tmp_path / "d" + (root / "images" / "test_v2").mkdir(parents=True) + (root / "labels" / "test_v2").mkdir(parents=True) + (root / "images" / "test_v2" / "syn_0.jpg").write_bytes(b"image-bytes") + (root / "labels" / "test_v2" / "syn_0.txt").write_text("0 0.5 0.5 0.1 0.1\n") + data = root / "data.yaml" + data.write_text(f"path: {root}\ntrain: images/test_v2\nval: images/test_v2\ntest: images/test_v2\nnames: [A, B]\n") + info = load_dataset_info(data, "test") + assert info.netlists_dir == root / "netlists" / "test_v2" + registry = tmp_path / "frozen.json" + common = ["--data", str(data), "--registry", str(registry), "--out-dir", str(tmp_path / "out"), "--skip-detection", "--frozen-name", "t"] + assert main([*common, "--freeze"]) == 0 + assert main(common) == 0 + (root / "labels" / "test_v2" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") + assert main(common) == 3 + + +def test_frozen_hash_covers_the_scored_ground_truth_netlists(tmp_path: Path) -> None: + """--gt-netlists pointing outside the dataset is hashed too: a different ground truth is refused.""" + root = make_dataset(tmp_path / "d") + gt = tmp_path / "gt" + gt.mkdir() + (gt / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True))) + pred = tmp_path / "pred" + pred.mkdir() + (pred / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True))) + data, out = write_yaml(root), tmp_path / "out" + base = ["--data", str(data), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-detection", "--frozen-name", "t"] + scored = [*base, "--gt-netlists", str(gt), "--pred-netlists", str(pred), "--no-truth-table"] + assert main([*scored, "--freeze"]) == 0 + assert main(scored) == 0 + (gt / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True, shift=2.0))) + assert main(scored) == 3 + + +def test_end_to_end_domains_follow_cli_domain_rules(tmp_path: Path) -> None: + """--domain-rule groups the end-to-end per-domain block, not only the detection one.""" + root = make_dataset(tmp_path / "d") + gt, pred = tmp_path / "gt", tmp_path / "pred" + for folder in (gt, pred): + folder.mkdir() + for stem in ("syn_0", "foo_1"): + (folder / f"{stem}.json").write_text(json.dumps(nand_netlist(with_boxes=True))) + out = tmp_path / "out" + args = ["--data", str(write_yaml(root)), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-detection", "--frozen-name", "t"] + scored = [*args, "--gt-netlists", str(gt), "--pred-netlists", str(pred), "--no-truth-table", "--domain-rule", "foo_=bar"] + assert main([*scored, "--freeze"]) == 0 + assert main(scored) == 0 + report = json.loads((out / "t.json").read_text()) + assert set(report["end_to_end"]["per_domain"]) == {"synthetic", "bar"} From 00926fbf72f68fc868b17fe240e2653674200eb6 Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 01:21:15 +0530 Subject: [PATCH 3/5] no-mistakes(document): Align frozen-hash doc with resolved split directories --- agent_docs/ml-pipeline.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index 505e279..00c829f 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -60,7 +60,7 @@ Current phase: `ml/experiments/current_phase.txt` - **End-to-end (optional):** `--gt-netlists DIR --pred-netlists DIR` (files `.json`, schema in `ml/eval_netlist.py`; T2 emits the ground truth, T8 must emit predictions in it) gives net precision/recall/F1 over pin pairs (MOSFET bulk pins unscored), netlist exact-match rate, and truth-table equivalence of the rebuilt circuit under DigiSim's own `simulate()` (`ml/sim_bridge/truth_table.cjs`; needs `cd frontend && npm install`; `--no-truth-table` skips it). -- **Frozen sets:** the test split's SHA-256 (images, labels, netlists, class names) must equal the entry in `ml/frozen_sets.json`, otherwise the run exits 3 and writes nothing. +- **Frozen sets:** the SHA-256 of the split's images and labels directories as resolved from `data.yaml`, its netlists directory (`--gt-netlists` when given) and class names must equal the entry in `ml/frozen_sets.json`, otherwise the run exits 3 and writes nothing. Register a new set once with `--freeze --frozen-name NAME --freeze-note "..."`; tooling never overwrites an entry. - **Baselines:** `ml/baselines/gate12.json` is the old 12-class model on the gate-era test split (`gate12_test`); compare a new run with `--baseline ml/baselines/gate12.json`. From a1d8ba0298603022deb4866c00ddf7ce2f01131b Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 01:28:03 +0530 Subject: [PATCH 4/5] no-mistakes(review): Drop extra eval flags, label unverified runs, share image rules --- agent_docs/ml-pipeline.md | 3 +- ml/eval_netlist.py | 34 +++++-------- ml/eval_report.py | 6 ++- ml/evaluate.py | 60 ++++++++++++++--------- ml/tests/test_eval_netlist.py | 11 +++-- ml/tests/test_evaluate.py | 91 ++++++++++++++++++++++++++++++++--- 6 files changed, 142 insertions(+), 63 deletions(-) diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index 00c829f..b2ca01c 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -61,7 +61,8 @@ Current phase: `ml/experiments/current_phase.txt` T8 must emit predictions in it) gives net precision/recall/F1 over pin pairs (MOSFET bulk pins unscored), netlist exact-match rate, and truth-table equivalence of the rebuilt circuit under DigiSim's own `simulate()` (`ml/sim_bridge/truth_table.cjs`; needs `cd frontend && npm install`; `--no-truth-table` skips it). - **Frozen sets:** the SHA-256 of the split's images and labels directories as resolved from `data.yaml`, its netlists directory (`--gt-netlists` when given) and class names must equal the entry in `ml/frozen_sets.json`, otherwise the run exits 3 and writes nothing. - Register a new set once with `--freeze --frozen-name NAME --freeze-note "..."`; tooling never overwrites an entry. + Register a new set once with `--freeze --frozen-name NAME --freeze-note "..."`; tooling never overwrites an entry. `--freeze` exists because the hash check needs a + recorded hash to compare against, and every later dataset task (T4 onwards) registers its frozen entry this way. A split with no registered set runs unchecked and the report says "(not frozen - unverified)". - **Baselines:** `ml/baselines/gate12.json` is the old 12-class model on the gate-era test split (`gate12_test`); compare a new run with `--baseline ml/baselines/gate12.json`. ## Dataset diff --git a/ml/eval_netlist.py b/ml/eval_netlist.py index ec431fa..01a5787 100644 --- a/ml/eval_netlist.py +++ b/ml/eval_netlist.py @@ -158,27 +158,20 @@ def load_netlist(path: Path) -> Netlist: return parse_netlist(raw) -def match_components(gt: Netlist, pred: Netlist, mode: str = "auto", iou_threshold: float = IOU_MATCH_THRESHOLD) -> dict[str, str]: +def match_components(gt: Netlist, pred: Netlist, iou_threshold: float = IOU_MATCH_THRESHOLD) -> dict[str, str]: """ Pair predicted components with ground-truth components. Args: gt: Ground-truth netlist. pred: Predicted netlist. - mode: 'bbox' (IoU, same type), 'id' (same id and type) or 'auto' (bbox when every component of both - sides has one, otherwise id). iou_threshold: Minimum IoU for bbox pairing. Returns: - Mapping predicted component id -> ground-truth component id (one-to-one). - Raises: - ValueError: If mode is unknown, or 'bbox' is requested but a component has no bbox. + Mapping predicted component id -> ground-truth component id (one-to-one). Components are paired by IoU + and type when every component of both sides has a bbox, otherwise by id and type. """ - if mode not in {"auto", "bbox", "id"}: - raise ValueError(f"Unknown match mode {mode!r}") have_boxes = all(c.bbox for c in gt.components.values()) and all(c.bbox for c in pred.components.values()) - if mode == "bbox" and not have_boxes: - raise ValueError("bbox matching needs a bbox on every component of both netlists") - if mode == "id" or (mode == "auto" and not have_boxes): + if not have_boxes: return {pid: pid for pid, c in pred.components.items() if pid in gt.components and gt.components[pid].type == c.type} gids, pids = list(gt.components), list(pred.components) if not gids or not pids: @@ -213,19 +206,18 @@ def _as_array(boxes: Sequence[tuple[float, float, float, float] | None]) -> np.n return np.asarray([b for b in boxes], dtype=np.float64).reshape(-1, 4) -def scored_nets(netlist: Netlist, score_bulk: bool = False) -> list[frozenset[str]]: +def scored_nets(netlist: Netlist) -> list[frozenset[str]]: """ - Nets reduced to scored pins, dropping nets with fewer than two pins. + Nets reduced to scored pins (MOSFET bulk pins are unscored), dropping nets with fewer than two pins. Args: netlist: Netlist to reduce. - score_bulk: Keep MOSFET bulk pins when True. Returns: List of pin sets with at least two pins. """ kept: list[frozenset[str]] = [] for net in netlist.nets: - pins = frozenset(p for p in net if score_bulk or (netlist.components[p.partition(":")[0]].type, p.partition(":")[2]) not in BULK_TERMINALS) + pins = frozenset(p for p in net if (netlist.components[p.partition(":")[0]].type, p.partition(":")[2]) not in BULK_TERMINALS) if len(pins) >= 2: kept.append(pins) return kept @@ -441,8 +433,6 @@ def evaluate_netlists( gt_dir: Path, pred_dir: Path, truth_table: bool = True, - match_mode: str = "auto", - score_bulk: bool = False, domain_rules: Sequence[tuple[str, str]] = DEFAULT_DOMAIN_RULES, ) -> dict[str, object]: """ @@ -454,8 +444,6 @@ def evaluate_netlists( gt_dir: Directory of ground-truth netlists named .json. pred_dir: Directory of predicted netlists with the same stems. truth_table: Also compute truth-table equivalence with DigiSim's simulator. - match_mode: Component pairing mode (see match_components). - score_bulk: Score MOSFET bulk pins too. domain_rules: (filename prefix, domain) rules used to group circuits per domain. Returns: Dict with per-circuit records, micro/macro net P/R/F1, exact-match rate and truth-table equivalence @@ -483,9 +471,9 @@ def evaluate_netlists( pred = load_netlist(pred_file) except NetlistError as exc: pred_error = str(exc) - mapping = match_components(gt, pred, match_mode) - gt_nets = scored_nets(gt, score_bulk) - pred_nets = remap_pins(scored_nets(pred, score_bulk), mapping) + mapping = match_components(gt, pred) + gt_nets = scored_nets(gt) + pred_nets = remap_pins(scored_nets(pred), mapping) counts = connectivity_scores(pin_pairs(gt_nets), pin_pairs(pred_nets)) comps_ok = len(pred.components) == len(gt.components) == len(mapping) records[stem] = CircuitResult( @@ -514,7 +502,7 @@ def evaluate_netlists( rec.truth_table_detail = str(pred_t["error"]) if "error" in pred_t else None domains = sorted({r.domain for r in records.values()}) return { - "settings": {"match_mode": match_mode, "score_bulk": score_bulk, "truth_table": truth_table, "iou": IOU_MATCH_THRESHOLD}, + "settings": {"truth_table": truth_table, "iou": IOU_MATCH_THRESHOLD}, "overall": aggregate(list(records.values())), "per_domain": {d: aggregate([r for r in records.values() if r.domain == d]) for d in domains}, "circuits": {stem: r.to_dict() for stem, r in records.items()}, diff --git a/ml/eval_report.py b/ml/eval_report.py index acc6745..3a196ae 100644 --- a/ml/eval_report.py +++ b/ml/eval_report.py @@ -203,11 +203,13 @@ def render_markdown(report: JsonDict, baseline: JsonDict | None = None) -> str: The Markdown text. """ run = report["run"] + ds = run["dataset"] + status = "(verified)" if ds["frozen_name"] else "(not frozen - unverified)" lines = [f"# DigiSim evaluation - {run['name']}", ""] lines += [ f"- generated: {run['generated_at']}", - f"- weights: `{run['weights']['name']}` sha256 `{str(run['weights']['sha256'])[:16]}...`" if run.get("weights") else "- weights: none (end-to-end only)", - f"- dataset: `{run['dataset']['frozen_name']}` split `{run['dataset']['split']}`, {run['dataset']['images']} images, frozen sha256 `{str(run['dataset']['sha256'])[:16]}...` (verified)", + f"- weights: `{run['weights']['name']}` sha256 `{str(run['weights']['sha256'])[:16]}...`", + f"- dataset: `{ds['frozen_name'] or 'unregistered'}` split `{ds['split']}`, {ds['images']} images, sha256 `{str(ds['sha256'])[:16]}...` {status}", f"- params: {run['params']}", "", ] diff --git a/ml/evaluate.py b/ml/evaluate.py index a0c836d..c95e877 100644 --- a/ml/evaluate.py +++ b/ml/evaluate.py @@ -35,7 +35,7 @@ import numpy as np from class_schema import load_schema -from eval_frozen import DEFAULT_REGISTRY, FrozenSetError, SplitDigest, file_sha256, freeze, hash_split, infer_frozen_name, verify_frozen +from eval_frozen import DEFAULT_REGISTRY, IMAGE_SUFFIXES, FrozenSetError, SplitDigest, file_sha256, freeze, hash_split, infer_frozen_name, verify_frozen from eval_metrics import ( DEFAULT_DOMAIN_RULES, DEFAULT_SMALL_PX, @@ -59,7 +59,7 @@ PREDICT_CONF_FLOOR = 0.001 DEFAULT_OPERATING_CONF = 0.35 # production DETECTION_CONFIDENCE_THRESHOLD (backend/pipeline/detector.py) DEFAULT_TOLERANCE = 0.02 -IMAGE_SUFFIXES = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".webp"}) +OMP_THREADS = "4" EXIT_FROZEN = 3 EXIT_REPRODUCTION = 4 @@ -104,11 +104,28 @@ def load_dataset_info(data: Path, split: str) -> DatasetInfo: if not root.is_absolute(): root = (data.parent / root).resolve() images_dir = root / str(doc[key]) - labels_dir = root / str(doc[key]).replace("images", "labels", 1) - netlists_dir = root / str(doc[key]).replace("images", "netlists", 1) if not images_dir.is_dir(): raise FileNotFoundError(f"Split images directory missing: {images_dir}") - return DatasetInfo(root=root, names=names, images_dir=images_dir, labels_dir=labels_dir, netlists_dir=netlists_dir) + return DatasetInfo(root=root, names=names, images_dir=images_dir, labels_dir=sibling_dir(images_dir, "labels"), netlists_dir=sibling_dir(images_dir, "netlists")) + + +def sibling_dir(images_dir: Path, name: str) -> Path: + """ + The directory beside a split's images, found the way ultralytics finds labels: the last 'images' path component is swapped. + + Args: + images_dir: The split's images directory. + name: Replacement component ('labels', 'netlists'). + Returns: + The sibling directory path. + Raises: + ValueError: If images_dir has no 'images' path component. + """ + parts = list(images_dir.parts) + if "images" not in parts: + raise ValueError(f"{images_dir}: the split directory must have an 'images' path component") + parts[len(parts) - 1 - parts[::-1].index("images")] = name + return Path(*parts) def read_labels(label_file: Path, width: int, height: int) -> np.ndarray: @@ -411,14 +428,10 @@ def build_parser() -> argparse.ArgumentParser: p.add_argument("--iou", type=float, default=IOU_MATCH_THRESHOLD) p.add_argument("--small-px", type=float, default=DEFAULT_SMALL_PX, help="GT boxes with longest side <= this are 'small objects'") p.add_argument("--device", default="cpu") - p.add_argument("--threads", type=int, default=4, help="CPU threads for torch/OpenMP") p.add_argument("--domain-rule", action="append", default=[], metavar="PREFIX=NAME", help="Extra filename-prefix domain rule (repeatable)") - p.add_argument("--skip-detection", action="store_true", help="Only run the end-to-end metrics") p.add_argument("--skip-legacy", action="store_true", help="Skip the ultralytics validation block") p.add_argument("--gt-netlists", type=Path, help="Directory of ground-truth netlists (.json)") p.add_argument("--pred-netlists", type=Path, help="Directory of predicted netlists (.json)") - p.add_argument("--match-mode", choices=["auto", "bbox", "id"], default="auto") - p.add_argument("--score-bulk", action="store_true", help="Also score MOSFET bulk pins") p.add_argument("--no-truth-table", action="store_true", help="Skip simulator-based truth-table equivalence") p.add_argument("--reproduce", type=Path, help="Reference eval JSON (e.g. the old eval_test.json) the legacy block must match") p.add_argument("--tolerance", type=float, default=DEFAULT_TOLERANCE) @@ -441,7 +454,7 @@ def main(argv: list[str] | None = None) -> int: """ parser = build_parser() args = parser.parse_args(argv) - os.environ.setdefault("OMP_NUM_THREADS", str(args.threads)) + os.environ.setdefault("OMP_NUM_THREADS", OMP_THREADS) try: rules = (*(parse_domain_rule(r) for r in args.domain_rule), *DEFAULT_DOMAIN_RULES) except ValueError as exc: @@ -478,7 +491,7 @@ def main(argv: list[str] | None = None) -> int: "name": args.run_name or args.frozen_name or f"{info.root.name}_{args.split}", "generated_at": datetime.now(UTC).isoformat(timespec="seconds"), "git_commit": git_commit(), - "weights": None if args.skip_detection else {"name": args.weights.name, "sha256": file_sha256(args.weights) if args.weights.exists() else None}, + "weights": {"name": args.weights.name, "sha256": file_sha256(args.weights) if args.weights.exists() else None}, "dataset": { "frozen_name": args.frozen_name, "split": args.split, @@ -492,20 +505,19 @@ def main(argv: list[str] | None = None) -> int: }, } status = 0 - if not args.skip_detection: - report["detection"] = evaluate_detection(info, args.weights, args.imgsz, args.conf, args.iou, args.small_px, args.device, rules) - if not args.skip_legacy: - report["legacy"] = evaluate(args.weights, args.data, args.split, args.imgsz, args.out_dir / "ultralytics_val", args.device) - print_report(report["legacy"]) - if args.reproduce: - repro = reproduction_check(report["legacy"], json.loads(args.reproduce.read_text()), args.tolerance, args.reproduce.name) - report["reproduction"] = repro - if not repro["ok"]: - status = EXIT_REPRODUCTION - elif args.reproduce: - parser.error("--reproduce needs the legacy block (drop --skip-legacy)") + report["detection"] = evaluate_detection(info, args.weights, args.imgsz, args.conf, args.iou, args.small_px, args.device, rules) + if not args.skip_legacy: + report["legacy"] = evaluate(args.weights, args.data, args.split, args.imgsz, args.out_dir / "ultralytics_val", args.device) + print_report(report["legacy"]) + if args.reproduce: + repro = reproduction_check(report["legacy"], json.loads(args.reproduce.read_text()), args.tolerance, args.reproduce.name) + report["reproduction"] = repro + if not repro["ok"]: + status = EXIT_REPRODUCTION + elif args.reproduce: + parser.error("--reproduce needs the legacy block (drop --skip-legacy)") if args.gt_netlists: - report["end_to_end"] = evaluate_netlists(args.gt_netlists, args.pred_netlists, not args.no_truth_table, args.match_mode, args.score_bulk, rules) + report["end_to_end"] = evaluate_netlists(args.gt_netlists, args.pred_netlists, not args.no_truth_table, rules) args.out_dir.mkdir(parents=True, exist_ok=True) stem = report["run"]["name"] diff --git a/ml/tests/test_eval_netlist.py b/ml/tests/test_eval_netlist.py index ee3c794..0c2db7f 100644 --- a/ml/tests/test_eval_netlist.py +++ b/ml/tests/test_eval_netlist.py @@ -66,13 +66,13 @@ def test_nets_sharing_a_pin_are_merged() -> None: assert net == [frozenset({"A:out", "MP1:g", "MN1:g"})] -def test_bulk_pins_are_not_scored_by_default() -> None: - """A bulk connection is ignored unless score_bulk is set.""" +def test_bulk_pins_are_not_scored() -> None: + """A MOSFET bulk connection is ignored when nets are reduced to scored pins.""" raw = nand_netlist() raw["nets"][2].append("MP1:b") netlist = parse_netlist(raw) + assert any("MP1:b" in net for net in netlist.nets) assert all("MP1:b" not in net for net in scored_nets(netlist)) - assert any("MP1:b" in net for net in scored_nets(netlist, score_bulk=True)) def test_match_by_bbox_survives_renamed_ids_and_small_shifts() -> None: @@ -82,8 +82,9 @@ def test_match_by_bbox_survives_renamed_ids_and_small_shifts() -> None: mapping = match_components(gt, pred) assert mapping == {f"p_{c}": c for c in gt.components} assert pin_pairs(remap_pins(scored_nets(pred), mapping)) == pin_pairs(scored_nets(gt)) - with pytest.raises(ValueError): - match_components(parse_netlist(nand_netlist()), pred, "bbox") + unboxed = parse_netlist(nand_netlist()) + assert match_components(unboxed, parse_netlist(nand_netlist())) == {c: c for c in unboxed.components} + assert match_components(unboxed, pred) == {} def run_one(tmp_path: Path, pred: dict | None, gt: dict | None = None, **kwargs) -> dict: diff --git a/ml/tests/test_evaluate.py b/ml/tests/test_evaluate.py index 77451d6..46de0c8 100644 --- a/ml/tests/test_evaluate.py +++ b/ml/tests/test_evaluate.py @@ -2,7 +2,9 @@ Module: test_evaluate.py Purpose: Tests for ml/evaluate.py helpers and CLI behaviour that need no trained weights: label parsing, class-name mapping (incl. legacy aliases), the reproduction check, the markdown - renderer, and the refusal to run when the frozen test set changed. + renderer, and the refusal to run when the frozen test set changed. The CLI runs use a stub + detector (no weights, no ultralytics) and --skip-legacy; the frozen check, netlist scoring and + report writing around it are the real code. """ import json @@ -13,8 +15,51 @@ from conftest import nand_netlist from test_eval_frozen import make_dataset +import evaluate +from eval_metrics import DetectionAccumulator from eval_report import render_markdown -from evaluate import build_class_map, load_dataset_info, main, read_labels, reproduction_check +from evaluate import DatasetInfo, build_class_map, load_dataset_info, main, read_labels, reproduction_check, sibling_dir + +DETECTOR_CALLS: list[Path] = [] + + +def stub_detection(info: DatasetInfo, weights: Path, imgsz: int, conf: float, iou: float, small_px: float, device: str, domain_rules: tuple[tuple[str, str], ...]) -> dict: + """ + Stand-in for evaluate_detection: an empty but schema-complete detection block, recording that it ran. + + Args: + info: Resolved dataset. + weights: Weights path (unused). + imgsz: Inference size (unused). + conf: Operating confidence. + iou: IoU threshold. + small_px: Small-object threshold. + device: Device (unused). + domain_rules: Domain rules (unused). + Returns: + A detection dict with no ground truth and no predictions. + """ + DETECTOR_CALLS.append(weights) + acc = DetectionAccumulator(len(info.names), small_px, iou) + per_class = acc.per_class(info.names) + return { + "conf": conf, + "iou_threshold": iou, + "model_classes": list(info.names), + "class_map": {}, + "overall": acc.overall(), + "per_class": per_class, + "per_domain": {}, + "confusion_matrix": acc.confusion(info.names), + "junction_recall": None, + } + + +@pytest.fixture(autouse=True) +def stub_detector(monkeypatch: pytest.MonkeyPatch) -> None: + """Replace the model-backed detector so CLI runs need no weights.""" + DETECTOR_CALLS.clear() + monkeypatch.setattr(evaluate, "evaluate_detection", stub_detection) def test_read_labels_handles_boxes_polygons_and_missing_files(tmp_path: Path) -> None: @@ -69,7 +114,7 @@ def test_cli_refuses_changed_frozen_set_and_requires_a_name(tmp_path: Path, caps data = write_yaml(root) registry = tmp_path / "frozen.json" out = tmp_path / "out" - common = ["--data", str(data), "--registry", str(registry), "--out-dir", str(out), "--skip-detection"] + common = ["--data", str(data), "--registry", str(registry), "--out-dir", str(out), "--skip-legacy"] with pytest.raises(SystemExit): main([*common]) # test split without --frozen-name assert main([*common, "--frozen-name", "t", "--freeze", "--freeze-note", "tiny"]) == 0 @@ -79,13 +124,15 @@ def test_cli_refuses_changed_frozen_set_and_requires_a_name(tmp_path: Path, caps assert report["run"]["dataset"]["sha256"] == json.loads(registry.read_text())["t"]["sha256"] (out / "t.json").unlink() (root / "labels" / "test" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") + detector_runs = len(DETECTOR_CALLS) assert main([*common, "--frozen-name", "t"]) == 3 + assert len(DETECTOR_CALLS) == detector_runs assert not (out / "t.json").exists() assert "refusing to evaluate" in capsys.readouterr().err def test_end_to_end_report_renders_markdown(tmp_path: Path) -> None: - """An end-to-end-only run writes JSON plus a Markdown table with the three headline metrics.""" + """A run with netlists writes JSON plus a Markdown table with the three end-to-end headline metrics.""" root = make_dataset(tmp_path / "d") (root / "netlists" / "test").mkdir(parents=True) (root / "netlists" / "test" / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True))) @@ -93,7 +140,7 @@ def test_end_to_end_report_renders_markdown(tmp_path: Path) -> None: pred.mkdir() (pred / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True, prefix="p_", shift=1.0))) data, out = write_yaml(root), tmp_path / "out" - args = ["--data", str(data), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-detection", "--frozen-name", "t"] + args = ["--data", str(data), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-legacy", "--frozen-name", "t"] assert main([*args, "--freeze"]) == 0 assert main([*args, "--gt-netlists", str(root / "netlists" / "test"), "--pred-netlists", str(pred), "--no-truth-table"]) == 0 markdown = (out / "t.md").read_text() @@ -116,7 +163,7 @@ def test_frozen_hash_covers_the_directories_data_yaml_names(tmp_path: Path) -> N info = load_dataset_info(data, "test") assert info.netlists_dir == root / "netlists" / "test_v2" registry = tmp_path / "frozen.json" - common = ["--data", str(data), "--registry", str(registry), "--out-dir", str(tmp_path / "out"), "--skip-detection", "--frozen-name", "t"] + common = ["--data", str(data), "--registry", str(registry), "--out-dir", str(tmp_path / "out"), "--skip-legacy", "--frozen-name", "t"] assert main([*common, "--freeze"]) == 0 assert main(common) == 0 (root / "labels" / "test_v2" / "syn_0.txt").write_text("1 0.5 0.5 0.1 0.1\n") @@ -133,7 +180,7 @@ def test_frozen_hash_covers_the_scored_ground_truth_netlists(tmp_path: Path) -> pred.mkdir() (pred / "syn_0.json").write_text(json.dumps(nand_netlist(with_boxes=True))) data, out = write_yaml(root), tmp_path / "out" - base = ["--data", str(data), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-detection", "--frozen-name", "t"] + base = ["--data", str(data), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-legacy", "--frozen-name", "t"] scored = [*base, "--gt-netlists", str(gt), "--pred-netlists", str(pred), "--no-truth-table"] assert main([*scored, "--freeze"]) == 0 assert main(scored) == 0 @@ -150,9 +197,37 @@ def test_end_to_end_domains_follow_cli_domain_rules(tmp_path: Path) -> None: for stem in ("syn_0", "foo_1"): (folder / f"{stem}.json").write_text(json.dumps(nand_netlist(with_boxes=True))) out = tmp_path / "out" - args = ["--data", str(write_yaml(root)), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-detection", "--frozen-name", "t"] + args = ["--data", str(write_yaml(root)), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-legacy", "--frozen-name", "t"] scored = [*args, "--gt-netlists", str(gt), "--pred-netlists", str(pred), "--no-truth-table", "--domain-rule", "foo_=bar"] assert main([*scored, "--freeze"]) == 0 assert main(scored) == 0 report = json.loads((out / "t.json").read_text()) assert set(report["end_to_end"]["per_domain"]) == {"synthetic", "bar"} + + +def test_report_marks_an_unfrozen_split_unverified(tmp_path: Path) -> None: + """A split with no registered frozen set runs unchecked, and the Markdown says so instead of claiming verification.""" + root = make_dataset(tmp_path / "d") + out = tmp_path / "out" + unfrozen = ["--data", str(write_yaml(root)), "--registry", str(tmp_path / "f.json"), "--out-dir", str(out), "--skip-legacy", "--split", "val"] + assert main(unfrozen) == 0 + assert "(not frozen - unverified)" in (out / "d_val.md").read_text() + assert "(verified)" not in (out / "d_val.md").read_text() + frozen = [*unfrozen[:-2], "--frozen-name", "t"] + assert main([*frozen, "--freeze"]) == 0 + assert main(frozen) == 0 + assert "(verified)" in (out / "t.md").read_text() + + +def test_labels_and_netlists_dirs_swap_the_last_images_component(tmp_path: Path) -> None: + """Like ultralytics, only the last 'images' path component is replaced, so an 'images' earlier in the path stays.""" + assert sibling_dir(Path("/a/images/ds/images/test"), "labels") == Path("/a/images/ds/labels/test") + root = tmp_path / "my_images" + (root / "images" / "test").mkdir(parents=True) + data = root / "data.yaml" + data.write_text(f"path: {root}\ntest: images/test\nnames: [A, B]\n") + info = load_dataset_info(data, "test") + assert info.labels_dir == root / "labels" / "test" + assert info.netlists_dir == root / "netlists" / "test" + with pytest.raises(ValueError): + sibling_dir(Path("/data/test"), "labels") From 5d7ab71ab42c2139baf47989d2f7f341394fde93 Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 01:30:55 +0530 Subject: [PATCH 5/5] no-mistakes(review): Remove unused split_by_domain helper --- ml/eval_metrics.py | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/ml/eval_metrics.py b/ml/eval_metrics.py index 7cb4bd9..8e988d8 100644 --- a/ml/eval_metrics.py +++ b/ml/eval_metrics.py @@ -17,7 +17,7 @@ import math import re -from collections.abc import Iterable, Sequence +from collections.abc import Sequence from dataclasses import dataclass, field import numpy as np @@ -319,19 +319,3 @@ def f1_record(tp: int, fp: int, fn: int) -> dict[str, object]: Dict with value, ci95 and n (as in rate()). """ return rate(2 * tp, 2 * tp + fp + fn) - - -def split_by_domain(image_names: Iterable[str], rules: Sequence[tuple[str, str]] = DEFAULT_DOMAIN_RULES) -> dict[str, list[str]]: - """ - Group image names by their domain. - - Args: - image_names: Image file names. - rules: Ordered (prefix, domain) rules. - Returns: - Mapping domain -> image names, domains in first-seen order. - """ - groups: dict[str, list[str]] = {} - for name in image_names: - groups.setdefault(domain_for(name, rules), []).append(name) - return groups