diff --git a/.claude/agents/model.md b/.claude/agents/model.md index 7752058..b953ed1 100644 --- a/.claude/agents/model.md +++ b/.claude/agents/model.md @@ -30,10 +30,10 @@ Do not stop and report — diagnose, fix, and re-evaluate in the same session un | Phase | Classes | Stages Active | |-------|---------|---------------| -| 1 | AND, OR, NOT | 1 only | -| 2 | All 12: + NAND, NOR, XOR, XNOR, Switch, Input, Output, LED, Junction | 1 only | -| 3 | All 12 | 1 + 2 + 3 | -| 4 | All 12 | 1 + 2 + 3 + 4 | +| 1 | NMOS, PMOS, VDD, GND | 1 only | +| 2 | All 14 tier A (see `ml/classes.yaml`): + INPUT_PORT, OUTPUT_PORT, JUNCTION, AND, OR, NOT, NAND, NOR, XOR, XNOR | 1 only | +| 3 | All 14 | 1 + 2 + 3 | +| 4 | All 14 | 1 + 2 + 3 + 4 | Current phase tracked in `ml/experiments/current_phase.txt`. diff --git a/README.md b/README.md index 3a86704..8e23bce 100644 --- a/README.md +++ b/README.md @@ -145,10 +145,10 @@ What is true today: AND, OR, NOT, NAND, NOR, XOR, XNOR, Switch, Input, Output, LED, Junction). It does not recognise NMOS/PMOS transistors or supply symbols, and it detects nothing useful on transistor-level schematics. -- **Retraining on transistor-level classes is in progress.** It needs a new - class schema, a synthetic transistor-level generator, real hand-drawn data - (see [Data and licences](#-data-and-licences)), a GPU training run and - net tracing that no longer assumes left-to-right gates. Until that lands, +- **Retraining on transistor-level classes is in progress.** The class schema + (`ml/classes.yaml`) is in place; it still needs a synthetic transistor-level + generator, real hand-drawn data (see [Data and licences](#-data-and-licences)), + a GPU training run and net tracing that no longer assumes left-to-right gates. Until that lands, treat detection results on transistor schematics as unsupported. - **Training is transfer learning only** (pretrained COCO weights, never random init), with the gate: F1 >= 0.95 and accuracy >= 0.95 per class before a phase diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index 8447655..54dde54 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -15,16 +15,36 @@ Image → [Stage 1: YOLO Detection] → [Stage 2: OpenCV Wire Extraction] | 3 | `backend/pipeline/graph_builder.py` | NetworkX DiGraph | Directed circuit graph | | 4 | `backend/pipeline/circuit_exporter.py` | JSON serialization | DigiSim-importable JSON | +## Class Vocabulary +Single source of truth: `ml/classes.yaml` (name, tier, YOLO id, frontend node type, terminals, default size, legacy aliases). +Never hand-edit the generated files; after editing the YAML run `cd ml && uv run python class_schema.py generate` +(`check` verifies nothing is stale; pytest `backend/test_class_schema.py` and Jest `yoloClassMap.test.ts` assert the backend and frontend maps equal the YAML). + +| Tier | Classes (YOLO ids in file order) | +|------|----------------------------------| +| A (required, 14) | `NMOS PMOS VDD GND INPUT_PORT OUTPUT_PORT JUNCTION AND OR NOT NAND NOR XOR XNOR` | +| B (next, analog) | `RESISTOR CAPACITOR INDUCTOR BJT_NPN BJT_PNP CLOCK` | + +Generated: `backend/pipeline/class_map.py` (`CLASS_TO_NODE_TYPE`, re-exported by `detector.py`), +`frontend/src/logic/vision/yoloClassMap.generated.ts` (`YOLO_CLASS_MAP`), dataset `data.yaml` +(`class_schema.py data-yaml --path DIR`, tier A by default; `screenshot_pipeline.py` uses the same renderer). + +Legacy aliases (old 12-class gate-era weights): `SWITCH`, `INPUT` -> `INPUT_PORT`; `OUTPUT`, `LED` -> `OUTPUT_PORT`; +the gate names and `JUNCTION` are unchanged. Old weights emit these names upper-case, matching the alias keys. +Legacy ids differ from the canonical ids, so the frontend ONNX decoder uses `legacy_order` from `classes.yaml` +(AND=0 ... JUNCTION=11) when the model output has exactly 12 classes, and the canonical order otherwise. +The backend is unaffected because it reads class names from the model weights. + ## Training Phases | Phase | Classes Active | Stages Active | Threshold | |-------|---------------|---------------|-----------| -| 1 | AND, OR, NOT | 1 only | F1 ≥ 0.95, acc ≥ 0.95 per class | -| 2 | All 12 | 1 only | same | -| 3 | All 12 | 1 + 2 + 3 | same | -| 4 | All 12 | 1 + 2 + 3 + 4 | same | +| 1 | NMOS, PMOS, VDD, GND | 1 only | F1 >= 0.95, acc >= 0.95 per class | +| 2 | All 14 tier A | 1 only | same on synthetic held-out-style test; real held-out set F1 >= 0.85 per class with >= 30 test instances; JUNCTION recall >= 0.90 | +| 3 | All 14 tier A | 1 + 2 + 3 | same | +| 4 | All 14 tier A | 1 + 2 + 3 + 4 | same | -All 12 classes: `AND OR NOT NAND NOR XOR XNOR Switch Input Output LED Junction` +Tier B classes are trained after phase 4. Current phase: `ml/experiments/current_phase.txt` diff --git a/backend/data_gen/screenshot_pipeline.py b/backend/data_gen/screenshot_pipeline.py index e270040..92322ed 100644 --- a/backend/data_gen/screenshot_pipeline.py +++ b/backend/data_gen/screenshot_pipeline.py @@ -24,9 +24,11 @@ from data_gen.symbols import ( # noqa: E402 CLASS_NAMES, CLASS_TO_ID, + SCHEMA, DrawnSymbol, draw_symbol, hand_stroke, + render_data_yaml, ) REPO_ROOT = Path(__file__).resolve().parents[2] @@ -145,7 +147,7 @@ def place(name: str, cx: float, cy: float, s: float) -> DrawnSymbol: """Draw one symbol, record its annotation, and return it.""" sym = draw_symbol(img, name, cx, cy, s * rng.uniform(0.88, 1.12), color, thickness, rng) symbols.append(sym) - counts[name] += 1 + counts[CLASS_NAMES[CLASS_TO_ID[name]]] += 1 return sym # Sources on the left: INPUT boxes or SWITCH symbols. @@ -253,7 +255,7 @@ def _write_yolo_label( def _convert_roboflow_split(split_src: str, split_dst: str, out_dir: Path, counts: Counter) -> int: """ Copy one Roboflow split into the merged dataset, converting polygon labels - to bounding boxes and remapping class ids to the canonical 12-class list. + to bounding boxes and remapping class ids to the canonical class list (ml/classes.yaml). Args: split_src: Roboflow split directory name ('train', 'valid', 'test'). @@ -343,8 +345,7 @@ def build_dataset(out_dir: Path, count: int, seed: int) -> None: print(f"roboflow {split}: {n} images merged") counts.update(rf_counts) - yaml_text = f"path: {out_dir.resolve()}\ntrain: images/train\nval: images/valid\ntest: images/test\nnc: {len(CLASS_NAMES)}\nnames: {CLASS_NAMES}\n" - (out_dir / "data.yaml").write_text(yaml_text) + (out_dir / "data.yaml").write_text(render_data_yaml(SCHEMA, out_dir)) total = sum(counts.values()) max_count = max(counts.values()) diff --git a/backend/data_gen/symbols.py b/backend/data_gen/symbols.py index 4af048c..41203d2 100644 --- a/backend/data_gen/symbols.py +++ b/backend/data_gen/symbols.py @@ -6,28 +6,27 @@ screenshot pipeline can auto-generate YOLO labels and route wires. """ +import sys from dataclasses import dataclass, field +from pathlib import Path import cv2 import numpy as np -# Canonical class list for the whole ML pipeline (ids are the YOLO class ids). -CLASS_NAMES: list[str] = [ - "AND", - "OR", - "NOT", - "NAND", - "NOR", - "XOR", - "XNOR", - "SWITCH", - "INPUT", - "OUTPUT", - "LED", - "JUNCTION", -] - -CLASS_TO_ID: dict[str, int] = {name: i for i, name in enumerate(CLASS_NAMES)} +# Canonical class list for the whole ML pipeline, loaded from ml/classes.yaml (the single +# source of truth). CLASS_NAMES index == YOLO class id (tier A only); CLASS_TO_ID also +# resolves legacy gate-era names (SWITCH, INPUT, OUTPUT, LED) to their canonical class id, +# because this renderer still draws those symbols. +_ML_DIR = Path(__file__).resolve().parents[2] / "ml" +if str(_ML_DIR) not in sys.path: + sys.path.insert(0, str(_ML_DIR)) + +from class_schema import load_schema, render_data_yaml # noqa: E402,F401 (render_data_yaml re-exported) + +SCHEMA = load_schema() +CLASS_NAMES: list[str] = [c.name for c in SCHEMA.classes_up_to("A")] +CLASS_TO_ID: dict[str, int] = {name: i for i, name in enumerate(SCHEMA.names)} +CLASS_TO_ID.update({alias: CLASS_TO_ID[canonical] for alias, canonical in SCHEMA.aliases.items()}) @dataclass diff --git a/backend/pipeline/class_map.py b/backend/pipeline/class_map.py new file mode 100644 index 0000000..260afe2 --- /dev/null +++ b/backend/pipeline/class_map.py @@ -0,0 +1,67 @@ +""" +Module: class_map.py +Purpose: AUTO-GENERATED from ml/classes.yaml by ml/class_schema.py - do not edit by hand. + Class vocabulary data for the detector: canonical names by YOLO id, legacy aliases + that old weights still predict, and the class-to-frontend-node-type map. + Regenerate with `cd ml && uv run python class_schema.py generate`. +""" + +# Canonical class names; the index is the YOLO class id. +CLASS_NAMES: tuple[str, ...] = ( + "NMOS", + "PMOS", + "VDD", + "GND", + "INPUT_PORT", + "OUTPUT_PORT", + "JUNCTION", + "AND", + "OR", + "NOT", + "NAND", + "NOR", + "XOR", + "XNOR", + "RESISTOR", + "CAPACITOR", + "INDUCTOR", + "BJT_NPN", + "BJT_PNP", + "CLOCK", +) + +# Legacy (gate-era) class names -> canonical class, so old weights keep resolving. +CLASS_ALIASES: dict[str, str] = { + "SWITCH": "INPUT_PORT", + "INPUT": "INPUT_PORT", + "OUTPUT": "OUTPUT_PORT", + "LED": "OUTPUT_PORT", +} + +# Class name (canonical and legacy) -> ReactFlow node type used by the frontend. +CLASS_TO_NODE_TYPE: dict[str, str] = { + "NMOS": "nmos", + "PMOS": "pmos", + "VDD": "vsource", + "GND": "ground", + "INPUT_PORT": "input", + "OUTPUT_PORT": "output", + "JUNCTION": "junction", + "AND": "andGate", + "OR": "orGate", + "NOT": "notGate", + "NAND": "nandGate", + "NOR": "norGate", + "XOR": "xorGate", + "XNOR": "xnorGate", + "RESISTOR": "resistor", + "CAPACITOR": "capacitor", + "INDUCTOR": "inductor", + "BJT_NPN": "bjtNpn", + "BJT_PNP": "bjtPnp", + "CLOCK": "clockSource", + "SWITCH": "input", + "INPUT": "input", + "OUTPUT": "output", + "LED": "output", +} diff --git a/backend/pipeline/detector.py b/backend/pipeline/detector.py index 09d27a1..9eca31d 100644 --- a/backend/pipeline/detector.py +++ b/backend/pipeline/detector.py @@ -1,8 +1,10 @@ """ Module: detector.py -Purpose: YOLOv8 gate detection stage — takes a circuit image and returns bounding boxes - with class labels for all detected logic gates. Runs fully local inference - with the transfer-learned weights produced by ml/train.py. +Purpose: YOLOv8 symbol detection stage — takes a circuit image and returns bounding boxes + with class labels for all detected circuit symbols (transistors, supplies, ports, + gates, junctions). Runs fully local inference with the transfer-learned weights + produced by ml/train.py. The class vocabulary comes from ml/classes.yaml via the + generated pipeline/class_map.py; legacy gate-era names stay resolvable as aliases. """ from dataclasses import dataclass @@ -10,10 +12,20 @@ from ultralytics import YOLO +from pipeline.class_map import CLASS_ALIASES, CLASS_NAMES, CLASS_TO_NODE_TYPE + +__all__ = [ + "CLASS_ALIASES", + "CLASS_NAMES", + "CLASS_TO_NODE_TYPE", + "Detection", + "GateDetector", +] + @dataclass class Detection: - """A single gate detection result from the YOLO model.""" + """A single symbol detection result from the YOLO model.""" class_name: str confidence: float @@ -38,24 +50,6 @@ def box(self) -> tuple[float, float, float, float]: ) -# Canonical model class names → ReactFlow node types used by the frontend. -# SWITCH acts as a toggleable input; LED acts as an output indicator. -CLASS_TO_NODE_TYPE: dict[str, str] = { - "AND": "andGate", - "OR": "orGate", - "NOT": "notGate", - "NAND": "nandGate", - "NOR": "norGate", - "XOR": "xorGate", - "XNOR": "xnorGate", - "SWITCH": "input", - "INPUT": "input", - "OUTPUT": "output", - "LED": "output", - "JUNCTION": "junction", -} - - class GateDetector: """Runs local YOLOv8 inference to detect logic gates in a circuit image.""" diff --git a/backend/pyproject.toml b/backend/pyproject.toml index d9018a1..202df94 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -21,6 +21,7 @@ dependencies = [ "onnxslim>=0.1.96", "pytest>=9.1.1", "google-generativeai>=0.8.6", + "pyyaml>=6.0", ] [dependency-groups] diff --git a/backend/test_class_schema.py b/backend/test_class_schema.py new file mode 100644 index 0000000..e3ad67e --- /dev/null +++ b/backend/test_class_schema.py @@ -0,0 +1,90 @@ +""" +Module: test_class_schema.py +Purpose: Contract tests tying the backend detector class map to ml/classes.yaml, the single + source of truth for the detector vocabulary. Also verifies the generated files are + not stale and that legacy gate-era class names still resolve for old weights. +""" + +import importlib.util +import sys +from pathlib import Path + +import yaml + +REPO_ROOT = Path(__file__).resolve().parent.parent +SCHEMA_PATH = REPO_ROOT / "ml" / "classes.yaml" + +from pipeline import detector # noqa: E402 +from pipeline.class_map import CLASS_ALIASES, CLASS_NAMES, CLASS_TO_NODE_TYPE # noqa: E402 + + +def _load_class_schema_module(): + """ + Import ml/class_schema.py (not on the backend path) as a module. + + Returns: + The imported class_schema module. + """ + spec = importlib.util.spec_from_file_location("class_schema", REPO_ROOT / "ml" / "class_schema.py") + module = importlib.util.module_from_spec(spec) + sys.modules["class_schema"] = module + spec.loader.exec_module(module) + return module + + +def _yaml_doc() -> dict: + """ + Parse ml/classes.yaml directly, independent of the generator. + + Returns: + The parsed YAML document. + """ + return yaml.safe_load(SCHEMA_PATH.read_text()) + + +def test_backend_map_equals_yaml(): + """CLASS_TO_NODE_TYPE holds exactly the YAML classes plus legacy aliases.""" + doc = _yaml_doc() + expected = {c["name"]: c["node_type"] for c in doc["classes"]} + for alias, canonical in doc["aliases"].items(): + expected[alias] = expected[canonical] + assert CLASS_TO_NODE_TYPE == expected + assert detector.CLASS_TO_NODE_TYPE is CLASS_TO_NODE_TYPE + + +def test_class_names_follow_yolo_ids(): + """CLASS_NAMES is ordered so that index equals the YOLO class id from the YAML.""" + doc = _yaml_doc() + assert list(CLASS_NAMES) == [c["name"] for c in sorted(doc["classes"], key=lambda c: c["id"])] + assert [c["id"] for c in doc["classes"]] == list(range(len(doc["classes"]))) + assert CLASS_ALIASES == doc["aliases"] + + +def test_generated_files_are_fresh(): + """Generated backend and frontend files match what the generator renders from the YAML.""" + schema_mod = _load_class_schema_module() + assert schema_mod.stale_files(schema_mod.load_schema()) == [] + + +def test_legacy_names_resolve_for_old_weights(): + """The 12 upper-case gate-era names an old model predicts keep their node types.""" + legacy = ["AND", "OR", "NOT", "NAND", "NOR", "XOR", "XNOR", "SWITCH", "INPUT", "OUTPUT", "LED", "JUNCTION"] + assert all(n in CLASS_TO_NODE_TYPE for n in legacy) + assert CLASS_TO_NODE_TYPE["AND"] == "andGate" + assert CLASS_TO_NODE_TYPE["SWITCH"] == "input" + assert CLASS_TO_NODE_TYPE["INPUT"] == "input" + assert CLASS_TO_NODE_TYPE["OUTPUT"] == "output" + assert CLASS_TO_NODE_TYPE["LED"] == "output" + assert CLASS_TO_NODE_TYPE["JUNCTION"] == "junction" + + +def test_data_yaml_uses_tier_a_by_default(tmp_path): + """The generated data.yaml lists tier A classes in id order and widens with tier B.""" + schema_mod = _load_class_schema_module() + schema = schema_mod.load_schema() + doc = yaml.safe_load(schema_mod.render_data_yaml(schema, tmp_path)) + tier_a = [c["name"] for c in _yaml_doc()["classes"] if c["tier"] == "A"] + assert doc["names"] == tier_a + assert doc["nc"] == len(tier_a) + wide = yaml.safe_load(schema_mod.render_data_yaml(schema, tmp_path, "B")) + assert wide["names"] == list(CLASS_NAMES) diff --git a/backend/uv.lock b/backend/uv.lock index 162c733..29c5d39 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -1,20 +1,20 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", - "python_full_version < '3.12' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.13.*' and sys_platform == 'darwin'", - "python_full_version == '3.12.*' and sys_platform == 'darwin'", "python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux'", - "python_full_version == '3.13.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", - "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", "(python_full_version >= '3.14' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'darwin'", + "python_full_version == '3.13.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", "(python_full_version == '3.13.*' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version == '3.13.*' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'darwin'", + "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", "(python_full_version == '3.12.*' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version == '3.12.*' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')", + "python_full_version < '3.12' and sys_platform == 'win32'", "python_full_version < '3.12' and sys_platform == 'darwin'", "python_full_version < '3.12' and platform_machine == 'aarch64' and sys_platform == 'linux'", "(python_full_version < '3.12' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version < '3.12' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')", @@ -739,6 +739,7 @@ dependencies = [ { name = "pyjwt" }, { name = "pytest" }, { name = "python-dotenv" }, + { name = "pyyaml" }, { name = "rapidfuzz" }, { name = "rapidocr-onnxruntime" }, { name = "requests" }, @@ -766,6 +767,7 @@ requires-dist = [ { name = "pyjwt", specifier = ">=2.13.0" }, { name = "pytest", specifier = ">=9.1.1" }, { name = "python-dotenv", specifier = ">=1.0" }, + { name = "pyyaml", specifier = ">=6.0" }, { name = "rapidfuzz", specifier = ">=3.14.5" }, { name = "rapidocr-onnxruntime", specifier = ">=1.4.4" }, { name = "requests", specifier = ">=2.31" }, @@ -2932,16 +2934,16 @@ version = "1.18.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", - "python_full_version == '3.13.*' and sys_platform == 'win32'", - "python_full_version == '3.12.*' and sys_platform == 'win32'", "python_full_version >= '3.14' and sys_platform == 'darwin'", - "python_full_version == '3.13.*' and sys_platform == 'darwin'", - "python_full_version == '3.12.*' and sys_platform == 'darwin'", "python_full_version >= '3.14' and platform_machine == 'aarch64' and sys_platform == 'linux'", - "python_full_version == '3.13.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", - "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", "(python_full_version >= '3.14' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'darwin'", + "python_full_version == '3.13.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", "(python_full_version == '3.13.*' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version == '3.13.*' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'darwin'", + "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux'", "(python_full_version == '3.12.*' and platform_machine != 'aarch64' and sys_platform == 'linux') or (python_full_version == '3.12.*' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')", ] dependencies = [ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index e0635e2..d0ed19d 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -21,9 +21,11 @@ }, "devDependencies": { "@types/jest": "^30.0.0", + "@types/js-yaml": "^4.0.9", "@types/node": "^26.1.0", "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", + "js-yaml": "^4.3.2", "typescript": "^5.9.3" } }, @@ -2438,24 +2440,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/@eslint/eslintrc/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "license": "Python-2.0" - }, - "node_modules/@eslint/eslintrc/node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/@eslint/js": { "version": "8.57.1", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", @@ -2606,6 +2590,15 @@ "node": ">=8" } }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, "node_modules/@istanbuljs/load-nyc-config/node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -2615,6 +2608,19 @@ "node": ">=6" } }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/@istanbuljs/schema": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", @@ -4424,6 +4430,13 @@ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, + "node_modules/@types/js-yaml": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz", + "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -5288,13 +5301,10 @@ "license": "MIT" }, "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "license": "MIT", - "dependencies": { - "sprintf-js": "~1.0.2" - } + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" }, "node_modules/aria-query": { "version": "5.3.0", @@ -8446,12 +8456,6 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, - "node_modules/eslint/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "license": "Python-2.0" - }, "node_modules/eslint/node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -8468,18 +8472,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint/node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/eslint/node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -11684,13 +11676,22 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" @@ -16648,6 +16649,15 @@ "node": ">=4" } }, + "node_modules/svgo/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, "node_modules/svgo/node_modules/chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -16745,6 +16755,19 @@ "node": ">=4" } }, + "node_modules/svgo/node_modules/js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/svgo/node_modules/nth-check": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz", diff --git a/frontend/package.json b/frontend/package.json index ab7ae37..ce20f3d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -40,9 +40,11 @@ }, "devDependencies": { "@types/jest": "^30.0.0", + "@types/js-yaml": "^4.0.9", "@types/node": "^26.1.0", "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", + "js-yaml": "^4.3.2", "typescript": "^5.9.3" } } diff --git a/frontend/src/logic/vision/yoloClassMap.generated.ts b/frontend/src/logic/vision/yoloClassMap.generated.ts new file mode 100644 index 0000000..baa9a2d --- /dev/null +++ b/frontend/src/logic/vision/yoloClassMap.generated.ts @@ -0,0 +1,84 @@ +/** + * @file yoloClassMap.generated.ts + * @description AUTO-GENERATED from ml/classes.yaml by ml/class_schema.py - do not edit by hand. + * Detector class vocabulary: canonical names by YOLO id, legacy aliases that old weights still + * predict, and the class-to-node-type map. Regenerate with `cd ml && uv run python class_schema.py generate`. + */ + +import type { YoloNodeType } from '../../types'; + +/** Canonical class names; the index is the YOLO class id. */ +export const YOLO_CLASS_NAMES: readonly string[] = [ + 'NMOS', + 'PMOS', + 'VDD', + 'GND', + 'INPUT_PORT', + 'OUTPUT_PORT', + 'JUNCTION', + 'AND', + 'OR', + 'NOT', + 'NAND', + 'NOR', + 'XOR', + 'XNOR', + 'RESISTOR', + 'CAPACITOR', + 'INDUCTOR', + 'BJT_NPN', + 'BJT_PNP', + 'CLOCK', +]; + +/** Class order of the 12-class gate-era weights; the index is their YOLO class id. */ +export const YOLO_LEGACY_CLASS_NAMES: readonly string[] = [ + 'AND', + 'OR', + 'NOT', + 'NAND', + 'NOR', + 'XOR', + 'XNOR', + 'SWITCH', + 'INPUT', + 'OUTPUT', + 'LED', + 'JUNCTION', +]; + +/** Legacy (gate-era) class names mapped to their canonical class. */ +export const YOLO_CLASS_ALIASES: Record = { + SWITCH: 'INPUT_PORT', + INPUT: 'INPUT_PORT', + OUTPUT: 'OUTPUT_PORT', + LED: 'OUTPUT_PORT', +}; + +/** Class name (canonical and legacy) mapped to the DigiSim ReactFlow node type. */ +export const YOLO_CLASS_MAP: Record = { + NMOS: 'nmos', + PMOS: 'pmos', + VDD: 'vsource', + GND: 'ground', + INPUT_PORT: 'input', + OUTPUT_PORT: 'output', + JUNCTION: 'junction', + AND: 'andGate', + OR: 'orGate', + NOT: 'notGate', + NAND: 'nandGate', + NOR: 'norGate', + XOR: 'xorGate', + XNOR: 'xnorGate', + RESISTOR: 'resistor', + CAPACITOR: 'capacitor', + INDUCTOR: 'inductor', + BJT_NPN: 'bjtNpn', + BJT_PNP: 'bjtPnp', + CLOCK: 'clockSource', + SWITCH: 'input', + INPUT: 'input', + OUTPUT: 'output', + LED: 'output', +}; diff --git a/frontend/src/logic/vision/yoloClassMap.test.ts b/frontend/src/logic/vision/yoloClassMap.test.ts new file mode 100644 index 0000000..3accb0f --- /dev/null +++ b/frontend/src/logic/vision/yoloClassMap.test.ts @@ -0,0 +1,84 @@ +/** + * @file yoloClassMap.test.ts + * @description Contract test: the generated frontend YOLO class map must equal ml/classes.yaml, + * the single source of truth shared with the backend detector. + */ + +import fs from 'fs'; +import path from 'path'; +import yaml from 'js-yaml'; +import { + YOLO_CLASS_ALIASES, + YOLO_CLASS_MAP, + YOLO_CLASS_NAMES, + YOLO_LEGACY_CLASS_NAMES, +} from './yoloDetector'; + +interface SchemaClass { + name: string; + id: number; + tier: string; + node_type: string; +} + +interface Schema { + classes: SchemaClass[]; + aliases: Record; + legacy_order: string[]; +} + +/** + * Load and parse ml/classes.yaml from the repo root. + * @returns The parsed schema document + */ +function loadSchema(): Schema { + const file = path.resolve(__dirname, '../../../../ml/classes.yaml'); + return yaml.load(fs.readFileSync(file, 'utf8')) as Schema; +} + +describe('YOLO class map matches ml/classes.yaml', () => { + const schema = loadSchema(); + + it('lists canonical class names in YOLO id order', () => { + const ordered = [...schema.classes].sort((a, b) => a.id - b.id).map((c) => c.name); + expect([...YOLO_CLASS_NAMES]).toEqual(ordered); + schema.classes.forEach((c) => expect(YOLO_CLASS_NAMES[c.id]).toBe(c.name)); + }); + + it('maps every canonical class and every legacy alias to the YAML node type', () => { + const expected: Record = {}; + schema.classes.forEach((c) => { + expected[c.name] = c.node_type; + }); + Object.entries(schema.aliases).forEach(([alias, canonical]) => { + expected[alias] = expected[canonical]; + }); + expect(YOLO_CLASS_MAP).toEqual(expected); + }); + + it('keeps the legacy aliases from the YAML', () => { + expect(YOLO_CLASS_ALIASES).toEqual(schema.aliases); + }); + + it('keeps the legacy class order from the YAML', () => { + expect([...YOLO_LEGACY_CLASS_NAMES]).toEqual(schema.legacy_order); + }); + + it('keeps every legacy gate-era class name resolvable to its node type', () => { + const legacy = ['AND', 'OR', 'NOT', 'NAND', 'NOR', 'XOR', 'XNOR', 'SWITCH', 'INPUT', 'OUTPUT', 'LED', 'JUNCTION']; + legacy.forEach((n) => expect(YOLO_CLASS_MAP[n]).toBeDefined()); + expect(YOLO_CLASS_MAP.AND).toBe('andGate'); + expect(YOLO_CLASS_MAP.SWITCH).toBe('input'); + expect(YOLO_CLASS_MAP.INPUT).toBe('input'); + expect(YOLO_CLASS_MAP.OUTPUT).toBe('output'); + expect(YOLO_CLASS_MAP.LED).toBe('output'); + expect(YOLO_CLASS_MAP.JUNCTION).toBe('junction'); + }); + + it('covers the transistor-first vocabulary', () => { + expect(YOLO_CLASS_MAP.NMOS).toBe('nmos'); + expect(YOLO_CLASS_MAP.PMOS).toBe('pmos'); + expect(YOLO_CLASS_MAP.VDD).toBe('vsource'); + expect(YOLO_CLASS_MAP.GND).toBe('ground'); + }); +}); diff --git a/frontend/src/logic/vision/yoloDetector.test.ts b/frontend/src/logic/vision/yoloDetector.test.ts index 2943486..9d6084d 100644 --- a/frontend/src/logic/vision/yoloDetector.test.ts +++ b/frontend/src/logic/vision/yoloDetector.test.ts @@ -1,4 +1,5 @@ -import { applyNMS, YoloCircuitDetector, YOLO_CLASS_MAP } from './yoloDetector'; +import * as ort from 'onnxruntime-web'; +import { applyNMS, decodeYoloOutput, YoloCircuitDetector, YOLO_CLASS_MAP } from './yoloDetector'; import type { YoloDetection } from './yoloDetector'; describe('yoloDetector', () => { @@ -68,4 +69,42 @@ describe('yoloDetector', () => { expect(detections[0]).toHaveProperty('confidence'); expect(detections[0]).toHaveProperty('nodeType'); }); + + describe('decodeYoloOutput class tables', () => { + /** + * Build a [1, 4 + numClasses, 1] output tensor with a single box scoring 0.9 for one class. + * @param numClasses - Number of classes in the fake model + * @param classIdx - Class id that scores highest + * @returns The ONNX tensor + */ + function singleBoxTensor(numClasses: number, classIdx: number): ort.Tensor { + const data = new Float32Array(4 + numClasses); + data.set([320, 320, 100, 80], 0); + data[4 + classIdx] = 0.9; + return new ort.Tensor('float32', data, [1, 4 + numClasses, 1]); + } + + it('decodes a legacy 12-class model with the gate-era class order', () => { + const legacy = ['AND', 'OR', 'NOT', 'NAND', 'NOR', 'XOR', 'XNOR', 'SWITCH', 'INPUT', 'OUTPUT', 'LED', 'JUNCTION']; + legacy.forEach((name, idx) => { + const [det] = decodeYoloOutput(singleBoxTensor(12, idx), 640, 640, 0.5); + expect(det.className).toBe(name); + expect(det.nodeType).toBe(YOLO_CLASS_MAP[name]); + }); + }); + + it('decodes a 20-class model with the canonical class order', () => { + const [nmos] = decodeYoloOutput(singleBoxTensor(20, 0), 640, 640, 0.5); + expect(nmos.className).toBe('NMOS'); + expect(nmos.nodeType).toBe('nmos'); + const [and] = decodeYoloOutput(singleBoxTensor(20, 7), 640, 640, 0.5); + expect(and.className).toBe('AND'); + expect(and.nodeType).toBe('andGate'); + }); + + it('computes box corners from the box center and size', () => { + const [det] = decodeYoloOutput(singleBoxTensor(20, 0), 640, 640, 0.5); + expect([det.x1, det.y1, det.x2, det.y2]).toEqual([270, 280, 370, 360]); + }); + }); }); diff --git a/frontend/src/logic/vision/yoloDetector.ts b/frontend/src/logic/vision/yoloDetector.ts index e4395f2..03fddd6 100644 --- a/frontend/src/logic/vision/yoloDetector.ts +++ b/frontend/src/logic/vision/yoloDetector.ts @@ -6,11 +6,17 @@ */ import * as ort from 'onnxruntime-web'; -import type { CircuitNodeType } from '../../types'; +import type { YoloNodeType } from '../../types'; +import { + YOLO_CLASS_ALIASES, + YOLO_CLASS_MAP, + YOLO_CLASS_NAMES, + YOLO_LEGACY_CLASS_NAMES, +} from './yoloClassMap.generated'; export interface YoloDetection { className: string; - nodeType: CircuitNodeType; + nodeType: YoloNodeType; confidence: number; x: number; // Bounding box center X (image space) y: number; // Bounding box center Y (image space) @@ -22,31 +28,17 @@ export interface YoloDetection { y2: number; // Box bottom-right Y } -/** Class mapping from YOLO labels to DigiSim ReactFlow node types. */ -export const YOLO_CLASS_MAP: Record = { - AND: 'andGate', - OR: 'orGate', - NOT: 'notGate', - NAND: 'nandGate', - NOR: 'norGate', - XOR: 'xorGate', - XNOR: 'xnorGate', - SWITCH: 'input', - INPUT: 'input', - OUTPUT: 'output', - LED: 'output', - and: 'andGate', - or: 'orGate', - not: 'notGate', - nand: 'nandGate', - nor: 'norGate', - xor: 'xorGate', - xnor: 'xnorGate', - switch: 'input', - input: 'input', - output: 'output', - led: 'output', -}; +export { YOLO_CLASS_ALIASES, YOLO_CLASS_MAP, YOLO_CLASS_NAMES, YOLO_LEGACY_CLASS_NAMES }; + +/** + * Pick the class-name table (index = YOLO class id) for a model with the given class count. + * Legacy 12-class gate-era weights use their own id order; every other model uses the canonical order. + * @param numClasses - Number of classes in the model output + * @returns The class names indexed by YOLO class id + */ +export function classNamesForModel(numClasses: number): readonly string[] { + return numClasses === YOLO_LEGACY_CLASS_NAMES.length ? YOLO_LEGACY_CLASS_NAMES : YOLO_CLASS_NAMES; +} const DEFAULT_MODEL_URL = '/models/yolo_circuit.onnx'; @@ -151,6 +143,74 @@ export function preprocessImage( return { tensor, originalWidth: origWidth, originalHeight: origHeight }; } +/** + * Decode a raw YOLO output tensor ([1, 4 + numClasses, numBoxes]) into NMS-filtered detections. + * @param outputTensor - Raw model output tensor + * @param origW - Original image width in pixels + * @param origH - Original image height in pixels + * @param confidenceThreshold - Minimum class score to keep a box + * @returns Detections in original image space + */ +export function decodeYoloOutput( + outputTensor: ort.Tensor, + origW: number, + origH: number, + confidenceThreshold: number +): YoloDetection[] { + const rawData = outputTensor.data as Float32Array; + const dims = outputTensor.dims; + + const rawDetections: YoloDetection[] = []; + + if (dims.length === 3) { + const numCols = dims[2]; + const numChannels = dims[1]; + const classNames = classNamesForModel(numChannels - 4); + + const scaleX = origW / 640; + const scaleY = origH / 640; + + for (let i = 0; i < numCols; i++) { + const cx = rawData[0 * numCols + i] * scaleX; + const cy = rawData[1 * numCols + i] * scaleY; + const w = rawData[2 * numCols + i] * scaleX; + const h = rawData[3 * numCols + i] * scaleY; + + let maxScore = 0; + let maxClassIdx = 0; + + for (let c = 4; c < numChannels; c++) { + const score = rawData[c * numCols + i]; + if (score > maxScore) { + maxScore = score; + maxClassIdx = c - 4; + } + } + + if (maxScore >= confidenceThreshold) { + const className = classNames[maxClassIdx] ?? 'AND'; + const nodeType = YOLO_CLASS_MAP[className] ?? 'andGate'; + + rawDetections.push({ + className, + nodeType, + confidence: maxScore, + x: cx, + y: cy, + width: w, + height: h, + x1: cx - w / 2, + y1: cy - h / 2, + x2: cx + w / 2, + y2: cy + h / 2, + }); + } + } + } + + return applyNMS(rawDetections, 0.45); +} + /** YOLO Circuit Detector instance. */ export class YoloCircuitDetector { private session: ort.InferenceSession | null = null; @@ -247,58 +307,7 @@ export class YoloCircuitDetector { origH: number, confidenceThreshold: number ): YoloDetection[] { - const rawData = outputTensor.data as Float32Array; - const dims = outputTensor.dims; - - const rawDetections: YoloDetection[] = []; - - if (dims.length === 3) { - const numCols = dims[2]; - const numChannels = dims[1]; - - const scaleX = origW / 640; - const scaleY = origH / 640; - - for (let i = 0; i < numCols; i++) { - const cx = rawData[0 * numCols + i] * scaleX; - const cy = rawData[1 * numCols + i] * scaleY; - const w = rawData[2 * numCols + i] * scaleX; - const h = rawData[3 * numCols + i] * scaleY; - - let maxScore = 0; - let maxClassIdx = 0; - - for (let c = 4; c < numChannels; c++) { - const score = rawData[c * numCols + i]; - if (score > maxScore) { - maxScore = score; - maxClassIdx = c - 4; - } - } - - if (maxScore >= confidenceThreshold) { - const classNames = Object.keys(YOLO_CLASS_MAP); - const className = classNames[maxClassIdx % classNames.length] || 'AND'; - const nodeType = YOLO_CLASS_MAP[className] || 'andGate'; - - rawDetections.push({ - className, - nodeType, - confidence: maxScore, - x: cx, - y: cy, - width: w, - height: h, - x1: cx - w / 2, - y1: cy - h / 2, - x2: cx + w / 2, - y2: cx + h / 2, - }); - } - } - } - - return applyNMS(rawDetections, 0.45); + return decodeYoloOutput(outputTensor, origW, origH, confidenceThreshold); } /** Generates realistic mock detections when ONNX WASM model file is absent. */ diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index de33017..9db288b 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -15,7 +15,23 @@ export type CircuitNodeType = | 'nandGate' | 'norGate' | 'xorGate' - | 'xnorGate'; + | 'xnorGate' + | 'nmos' + | 'pmos' + | 'vsource' + | 'ground' + | 'resistor' + | 'capacitor' + | 'inductor' + | 'bjtNpn' + | 'bjtPnp' + | 'clockSource'; + +/** + * Node type a detector class maps to: a canvas node type, or 'junction' (a wire dot that + * merges nets and never becomes a canvas node). Generated into YOLO_CLASS_MAP from ml/classes.yaml. + */ +export type YoloNodeType = CircuitNodeType | 'junction'; /** One detected component placed on the canvas. */ export interface CircuitComponent { diff --git a/ml/class_schema.py b/ml/class_schema.py new file mode 100644 index 0000000..f6f55b7 --- /dev/null +++ b/ml/class_schema.py @@ -0,0 +1,339 @@ +""" +Module: class_schema.py +Purpose: Loads and validates ml/classes.yaml (the single source of truth for the detector + class vocabulary) and generates everything derived from it: the backend + CLASS_TO_NODE_TYPE map, the frontend YOLO_CLASS_MAP, and YOLO dataset data.yaml + files. Also exposes a `check` mode so contract tests and CI can verify that the + generated files on disk are not stale. + +Usage: + cd ml + uv run python class_schema.py generate # rewrite the generated backend + frontend files + uv run python class_schema.py check # exit 1 if a generated file is stale + uv run python class_schema.py data-yaml --path DIR # print a YOLO data.yaml (tier A by default) +""" + +import argparse +import sys +from dataclasses import dataclass +from pathlib import Path + +import yaml + +ML_DIR = Path(__file__).resolve().parent +REPO_ROOT = ML_DIR.parent +SCHEMA_PATH = ML_DIR / "classes.yaml" +BACKEND_MAP_PATH = REPO_ROOT / "backend" / "pipeline" / "class_map.py" +FRONTEND_MAP_PATH = REPO_ROOT / "frontend" / "src" / "logic" / "vision" / "yoloClassMap.generated.ts" + +TIER_ORDER: tuple[str, ...] = ("A", "B") +SCHEMA_VERSION = 1 + + +@dataclass(frozen=True) +class ClassSpec: + """One detector class as declared in classes.yaml.""" + + name: str + id: int + tier: str + node_type: str + terminals: tuple[str, ...] + default_size: tuple[int, int] + + +@dataclass(frozen=True) +class ClassSchema: + """The validated class vocabulary: ordered classes plus legacy aliases.""" + + classes: tuple[ClassSpec, ...] + aliases: dict[str, str] + legacy_order: tuple[str, ...] + + @property + def names(self) -> tuple[str, ...]: + """ + Canonical class names ordered by YOLO id. + + Returns: + Tuple of class names where index equals the YOLO class id. + """ + return tuple(c.name for c in self.classes) + + def node_type_map(self) -> dict[str, str]: + """ + Class name to frontend node type, canonical names first, then legacy aliases. + + Returns: + Ordered dict covering every canonical name and every alias. + """ + by_name = {c.name: c.node_type for c in self.classes} + mapping = dict(by_name) + for alias, canonical in self.aliases.items(): + mapping[alias] = by_name[canonical] + return mapping + + def classes_up_to(self, max_tier: str) -> tuple[ClassSpec, ...]: + """ + Classes whose tier is at or below max_tier. + + Args: + max_tier: Highest tier to include ('A' or 'B'). + Returns: + Classes in YOLO id order; ids stay contiguous from 0 because tiers are id-ordered. + Raises: + ValueError: If max_tier is not a known tier. + """ + if max_tier not in TIER_ORDER: + raise ValueError(f"Unknown tier {max_tier!r}; expected one of {TIER_ORDER}") + limit = TIER_ORDER.index(max_tier) + return tuple(c for c in self.classes if TIER_ORDER.index(c.tier) <= limit) + + +def load_schema(path: Path = SCHEMA_PATH) -> ClassSchema: + """ + Load and validate the class schema. + + Args: + path: Path to classes.yaml. + Returns: + The validated ClassSchema. + Raises: + FileNotFoundError: If the schema file does not exist. + ValueError: If the schema is malformed (duplicate names or ids, non-contiguous ids, + tiers out of order, bad terminals or size, aliases that do not resolve). + """ + if not path.exists(): + raise FileNotFoundError(f"Class schema not found: {path}") + raw = yaml.safe_load(path.read_text()) + if not isinstance(raw, dict) or raw.get("version") != SCHEMA_VERSION: + raise ValueError(f"{path}: expected a mapping with version: {SCHEMA_VERSION}") + + classes: list[ClassSpec] = [] + for entry in raw.get("classes") or []: + try: + size = tuple(int(v) for v in entry["default_size"]) + spec = ClassSpec( + name=str(entry["name"]), + id=int(entry["id"]), + tier=str(entry["tier"]), + node_type=str(entry["node_type"]), + terminals=tuple(str(t) for t in entry["terminals"]), + default_size=(size[0], size[1]), + ) + except (KeyError, TypeError, ValueError, IndexError) as exc: + raise ValueError(f"{path}: malformed class entry {entry!r}: {exc}") from exc + classes.append(spec) + + aliases = {str(k): str(v) for k, v in (raw.get("aliases") or {}).items()} + legacy_order = tuple(str(n) for n in raw.get("legacy_order") or []) + schema = ClassSchema(classes=tuple(classes), aliases=aliases, legacy_order=legacy_order) + _validate(schema) + return schema + + +def _validate(schema: ClassSchema) -> None: + """ + Enforce the schema invariants. + + Args: + schema: Schema to check. + Raises: + ValueError: On the first violated invariant. + """ + if not schema.classes: + raise ValueError("classes.yaml declares no classes") + names = schema.names + if len(set(names)) != len(names): + raise ValueError("Duplicate class names in classes.yaml") + if [c.id for c in schema.classes] != list(range(len(schema.classes))): + raise ValueError("Class ids must be contiguous from 0 and listed in id order") + tier_ranks = [TIER_ORDER.index(c.tier) if c.tier in TIER_ORDER else -1 for c in schema.classes] + if -1 in tier_ranks: + raise ValueError(f"Every class tier must be one of {TIER_ORDER}") + if tier_ranks != sorted(tier_ranks): + raise ValueError("Classes must be ordered by tier so a tier prefix has contiguous ids") + for c in schema.classes: + if not c.node_type or not c.terminals or any(v <= 0 for v in c.default_size): + raise ValueError(f"Class {c.name}: node_type, terminals and a positive default_size are required") + upper_names = {n.upper() for n in names} + for alias, canonical in schema.aliases.items(): + if canonical not in names: + raise ValueError(f"Alias {alias} points at unknown class {canonical}") + if alias.upper() in upper_names: + raise ValueError(f"Alias {alias} collides with a canonical class name") + known = set(names) | set(schema.aliases) + if len(set(schema.legacy_order)) != len(schema.legacy_order): + raise ValueError("Duplicate names in legacy_order") + for name in schema.legacy_order: + if name not in known: + raise ValueError(f"legacy_order entry {name} is neither a class nor an alias") + + +def render_backend_map(schema: ClassSchema) -> str: + """ + Render backend/pipeline/class_map.py (ruff-format clean). + + Args: + schema: Validated schema. + Returns: + Full file text. + """ + lines = [ + '"""', + "Module: class_map.py", + "Purpose: AUTO-GENERATED from ml/classes.yaml by ml/class_schema.py - do not edit by hand.", + " Class vocabulary data for the detector: canonical names by YOLO id, legacy aliases", + " that old weights still predict, and the class-to-frontend-node-type map.", + " Regenerate with `cd ml && uv run python class_schema.py generate`.", + '"""', + "", + "# Canonical class names; the index is the YOLO class id.", + "CLASS_NAMES: tuple[str, ...] = (", + *[f' "{n}",' for n in schema.names], + ")", + "", + "# Legacy (gate-era) class names -> canonical class, so old weights keep resolving.", + "CLASS_ALIASES: dict[str, str] = {", + *[f' "{a}": "{c}",' for a, c in schema.aliases.items()], + "}", + "", + "# Class name (canonical and legacy) -> ReactFlow node type used by the frontend.", + "CLASS_TO_NODE_TYPE: dict[str, str] = {", + *[f' "{n}": "{t}",' for n, t in schema.node_type_map().items()], + "}", + "", + ] + return "\n".join(lines) + + +def render_frontend_map(schema: ClassSchema) -> str: + """ + Render frontend/src/logic/vision/yoloClassMap.generated.ts. + + Args: + schema: Validated schema. + Returns: + Full file text. + """ + lines = [ + "/**", + " * @file yoloClassMap.generated.ts", + " * @description AUTO-GENERATED from ml/classes.yaml by ml/class_schema.py - do not edit by hand.", + " * Detector class vocabulary: canonical names by YOLO id, legacy aliases that old weights still", + " * predict, and the class-to-node-type map. Regenerate with `cd ml && uv run python class_schema.py generate`.", + " */", + "", + "import type { YoloNodeType } from '../../types';", + "", + "/** Canonical class names; the index is the YOLO class id. */", + "export const YOLO_CLASS_NAMES: readonly string[] = [", + *[f" '{n}'," for n in schema.names], + "];", + "", + "/** Class order of the 12-class gate-era weights; the index is their YOLO class id. */", + "export const YOLO_LEGACY_CLASS_NAMES: readonly string[] = [", + *[f" '{n}'," for n in schema.legacy_order], + "];", + "", + "/** Legacy (gate-era) class names mapped to their canonical class. */", + "export const YOLO_CLASS_ALIASES: Record = {", + *[f" {a}: '{c}'," for a, c in schema.aliases.items()], + "};", + "", + "/** Class name (canonical and legacy) mapped to the DigiSim ReactFlow node type. */", + "export const YOLO_CLASS_MAP: Record = {", + *[f" {n}: '{t}'," for n, t in schema.node_type_map().items()], + "};", + "", + ] + return "\n".join(lines) + + +def render_data_yaml(schema: ClassSchema, dataset_root: Path, max_tier: str = "A") -> str: + """ + Render a YOLO dataset data.yaml for the classes up to max_tier. + + Args: + schema: Validated schema. + dataset_root: Dataset root directory written into the `path:` key. + max_tier: Highest tier to include ('A' or 'B'). + Returns: + YAML text with train/val/test split dirs, nc and id-ordered names. + Raises: + ValueError: If max_tier is unknown. + """ + selected = schema.classes_up_to(max_tier) + doc = { + "path": str(dataset_root.resolve()), + "train": "images/train", + "val": "images/valid", + "test": "images/test", + "nc": len(selected), + "names": [c.name for c in selected], + } + return yaml.safe_dump(doc, sort_keys=False) + + +def generated_files(schema: ClassSchema) -> dict[Path, str]: + """ + Every generated file and its expected content. + + Args: + schema: Validated schema. + Returns: + Mapping of absolute path to the text it must contain. + """ + return { + BACKEND_MAP_PATH: render_backend_map(schema), + FRONTEND_MAP_PATH: render_frontend_map(schema), + } + + +def stale_files(schema: ClassSchema) -> list[Path]: + """ + Generated files whose on-disk content differs from the schema. + + Args: + schema: Validated schema. + Returns: + Paths that are missing or out of date. + """ + return [p for p, text in generated_files(schema).items() if not p.exists() or p.read_text() != text] + + +def main(argv: list[str] | None = None) -> int: + """ + CLI entry point. + + Args: + argv: Argument list (defaults to sys.argv[1:]). + Returns: + Process exit code: 0 on success, 1 when `check` finds stale files. + """ + parser = argparse.ArgumentParser(description="DigiSim class schema tooling") + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("generate", help="rewrite the generated backend and frontend files") + sub.add_parser("check", help="exit 1 if a generated file is stale") + dy = sub.add_parser("data-yaml", help="print a YOLO data.yaml") + dy.add_argument("--path", type=Path, required=True, help="dataset root directory") + dy.add_argument("--tier", default="A", choices=TIER_ORDER, help="highest tier to include") + args = parser.parse_args(argv) + + schema = load_schema() + if args.command == "generate": + for path, text in generated_files(schema).items(): + path.write_text(text) + print(f"wrote {path.relative_to(REPO_ROOT)}") + return 0 + if args.command == "check": + stale = stale_files(schema) + for path in stale: + print(f"stale: {path.relative_to(REPO_ROOT)} (run: cd ml && uv run python class_schema.py generate)") + return 1 if stale else 0 + sys.stdout.write(render_data_yaml(schema, args.path, args.tier)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ml/classes.yaml b/ml/classes.yaml new file mode 100644 index 0000000..8748ba1 --- /dev/null +++ b/ml/classes.yaml @@ -0,0 +1,59 @@ +# DigiSim detector class schema - the single source of truth for the symbol vocabulary. +# +# Everything that names a detector class is generated from or checked against this file: +# - backend/pipeline/class_map.py (CLASS_TO_NODE_TYPE, re-exported by detector.py) +# - frontend/src/logic/vision/yoloClassMap.generated.ts (YOLO_CLASS_MAP) +# - the YOLO dataset data.yaml (python ml/class_schema.py data-yaml) +# Regenerate after editing: cd ml && uv run python class_schema.py generate +# CI-style check (also run by the pytest and Jest contract tests): uv run python class_schema.py check +# +# Fields per class: +# name canonical class name emitted by the detector (upper snake case, unique) +# id YOLO class id; contiguous from 0 and ordered by tier (all tier A before tier B) +# tier A = required for the transistor-first app, B = next (analog parts) +# node_type frontend ReactFlow node type the class maps to ("junction" is not a canvas node: it merges nets) +# terminals terminal names, in the handle naming used by the frontend (analog nodes: t: / s:; +# gates: inputs a, b and the default output handle "out") +# default_size [width, height] in canvas px, a layout hint for the importer +# +# Tier B terminal names are provisional until those nodes get a final handle layout. + +version: 1 + +classes: + # ---- Tier A: transistor-level symbols and supplies ---- + - {name: NMOS, id: 0, tier: A, node_type: nmos, terminals: [d, g, s, b], default_size: [80, 100]} + - {name: PMOS, id: 1, tier: A, node_type: pmos, terminals: [s, g, d, b], default_size: [80, 100]} + - {name: VDD, id: 2, tier: A, node_type: vsource, terminals: [pos, neg], default_size: [60, 60]} + - {name: GND, id: 3, tier: A, node_type: ground, terminals: [gnd], default_size: [40, 40]} + - {name: INPUT_PORT, id: 4, tier: A, node_type: input, terminals: [out], default_size: [70, 50]} + - {name: OUTPUT_PORT, id: 5, tier: A, node_type: output, terminals: [a], default_size: [70, 50]} + - {name: JUNCTION, id: 6, tier: A, node_type: junction, terminals: [net], default_size: [12, 12]} + # ---- Tier A: gate-level symbols (hidden legacy nodes until T9 maps them to library cells) ---- + - {name: AND, id: 7, tier: A, node_type: andGate, terminals: [a, b, out], default_size: [120, 90]} + - {name: OR, id: 8, tier: A, node_type: orGate, terminals: [a, b, out], default_size: [120, 90]} + - {name: NOT, id: 9, tier: A, node_type: notGate, terminals: [a, out], default_size: [100, 70]} + - {name: NAND, id: 10, tier: A, node_type: nandGate, terminals: [a, b, out], default_size: [120, 90]} + - {name: NOR, id: 11, tier: A, node_type: norGate, terminals: [a, b, out], default_size: [120, 90]} + - {name: XOR, id: 12, tier: A, node_type: xorGate, terminals: [a, b, out], default_size: [120, 90]} + - {name: XNOR, id: 13, tier: A, node_type: xnorGate, terminals: [a, b, out], default_size: [120, 90]} + # ---- Tier B: analog parts that already exist as palette nodes ---- + - {name: RESISTOR, id: 14, tier: B, node_type: resistor, terminals: [a, b], default_size: [100, 40]} + - {name: CAPACITOR, id: 15, tier: B, node_type: capacitor, terminals: [a, b], default_size: [100, 40]} + - {name: INDUCTOR, id: 16, tier: B, node_type: inductor, terminals: [a, b], default_size: [100, 40]} + - {name: BJT_NPN, id: 17, tier: B, node_type: bjtNpn, terminals: [c, b, e], default_size: [80, 100]} + - {name: BJT_PNP, id: 18, tier: B, node_type: bjtPnp, terminals: [c, b, e], default_size: [80, 100]} + - {name: CLOCK, id: 19, tier: B, node_type: clockSource, terminals: [out], default_size: [70, 50]} + +# Legacy class names -> canonical class. The 12-class gate-era weights (AND OR NOT NAND NOR XOR XNOR +# SWITCH INPUT OUTPUT LED JUNCTION) predict these names, so they must keep resolving. Old weights +# emit these names upper-case, matching the keys here. A SWITCH acts as a toggleable input and an LED as an output indicator. +aliases: + SWITCH: INPUT_PORT + INPUT: INPUT_PORT + OUTPUT: OUTPUT_PORT + LED: OUTPUT_PORT + +# Class order of the 12-class gate-era weights (index = their YOLO id). A model whose output has +# exactly this many classes is decoded with this table instead of the canonical id order above. +legacy_order: [AND, OR, NOT, NAND, NOR, XOR, XNOR, SWITCH, INPUT, OUTPUT, LED, JUNCTION] diff --git a/testing.md b/testing.md index 8587e8e..40950d5 100644 --- a/testing.md +++ b/testing.md @@ -48,18 +48,16 @@ Reviewer agent runs this checklist before approving anything. ## ML — Phase Completion Criteria -### Phase 1 (AND, OR, NOT) -- [ ] `evaluate.py` reports F1 ≥ 0.95 for AND individually -- [ ] `evaluate.py` reports F1 ≥ 0.95 for OR individually -- [ ] `evaluate.py` reports F1 ≥ 0.95 for NOT individually +### Phase 1 (NMOS, PMOS, VDD, GND) +- [ ] `evaluate.py` reports F1 ≥ 0.95 for NMOS, PMOS, VDD and GND individually - [ ] mAP@0.5 ≥ 0.90 overall - [ ] Inference on 5 unseen images completes in under 3 seconds on CPU - [ ] `/detect_circuit` returns valid JSON matching `CircuitExportJSON` - [ ] Training run logged in `ml/experiments/run_YYYYMMDD_HHMM/` - [ ] `ml/experiments/current_phase.txt` updated to `2` -### Phase 2 (All 12 classes) -- [ ] F1 ≥ 0.95 for every class individually (all 12) +### Phase 2 (All 14 tier A classes, `ml/classes.yaml`) +- [ ] F1 ≥ 0.95 for every class individually (all 14) - [ ] mAP@0.5 ≥ 0.90 overall - [ ] No class under 10% in confusion matrix - [ ] Training run logged