From fa1cc6193e595a4a020503d20788f1f7047eff56 Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 02:44:57 +0530 Subject: [PATCH 1/4] feat(backend): net tracing v2 with skeleton nets, junction vs crossover, pin assignment and schema 2 exporter Replace the Hough segment extractor and the left/right-of-box gate heuristics with a classical net tracer: background-normalised ink, symbol erasure with size-relative margins, skeleton graph with junction-dot vs crossover rules, pin assignment from detector keypoints or a geometry fallback with an orientation estimate, global supply nets, and OCR of port and supply labels. The graph is now an undirected component/net multigraph and the exporter emits schema 2 (pins, nets, ReactFlow edges, library cells) while keeping the legacy gate-level connections for the current importer. bench_tracing.py drives the tracer from perturbed T2 ground truth and scores it with the T6 evaluator, which now also reads T2 pin-map netlists and net objects. Scores: on 300 held-out T2 samples (seed 1) the tracer reaches net F1 0.9995 and exact match 99.3% on clean renders, net F1 0.9989 and exact match 98.7% on hand-drawn-style renders, truth-table equivalence 99.0%, p95 runtime 0.29 s per image. These scores come from perturbed ground-truth detections (box and keypoint jitter, dropped junction dots): no trained detector for the new classes exists yet, so the numbers bound the tracer, not the end-to-end photo pipeline. The T3 round-trip truth-table criterion waits for T3. --- .claude/agents/model.md | 13 +- README.md | 8 +- agent_docs/ml-pipeline.md | 31 +- backend/app.py | 20 +- backend/bench_tracing.py | 362 ++++++++++++++++++ backend/pipeline/circuit_exporter.py | 198 ++++++++-- backend/pipeline/class_map.py | 27 +- backend/pipeline/detector.py | 59 ++- backend/pipeline/graph_builder.py | 248 ++---------- backend/pipeline/ink.py | 87 +++++ backend/pipeline/label_attach.py | 257 +++++++++++++ backend/pipeline/net_tracer.py | 544 +++++++++++++++++++++++++++ backend/pipeline/pin_assignment.py | 430 +++++++++++++++++++++ backend/pipeline/skeleton_graph.py | 309 +++++++++++++++ backend/pipeline/trace_types.py | 94 +++++ backend/pipeline/wire_extractor.py | 152 -------- backend/pyproject.toml | 1 + backend/test_class_schema.py | 8 +- backend/test_net_tracer.py | 505 +++++++++++++++++++++++++ backend/uv.lock | 139 +++++++ frontend/src/types/api.ts | 60 ++- ml/class_schema.py | 21 +- ml/eval_netlist.py | 48 ++- ml/tests/test_eval_netlist.py | 28 +- 24 files changed, 3213 insertions(+), 436 deletions(-) create mode 100644 backend/bench_tracing.py create mode 100644 backend/pipeline/ink.py create mode 100644 backend/pipeline/label_attach.py create mode 100644 backend/pipeline/net_tracer.py create mode 100644 backend/pipeline/pin_assignment.py create mode 100644 backend/pipeline/skeleton_graph.py create mode 100644 backend/pipeline/trace_types.py delete mode 100644 backend/pipeline/wire_extractor.py create mode 100644 backend/test_net_tracer.py diff --git a/.claude/agents/model.md b/.claude/agents/model.md index b953ed1..45f217b 100644 --- a/.claude/agents/model.md +++ b/.claude/agents/model.md @@ -14,17 +14,12 @@ Do not stop and report — diagnose, fix, and re-evaluate in the same session un | Stage | Input | Method | Output | |-------|-------|--------|--------| | 1 — Detection | Circuit image | YOLOv8 (transfer learning) | Bounding boxes + class labels | -| 2 — Wire Extraction | Image | OpenCV only — no neural net | Wire segments as pixel coordinate pairs | -| 3 — Graph | Detections + wires | NetworkX DiGraph | Directed circuit graph | +| 2 - Wire Extraction (net tracing) | Image + detections | OpenCV only, no neural net | Components with pins + undirected nets | +| 3 - Graph | Net trace | NetworkX component/net MultiGraph | Net-based circuit graph | | 4 — Export | Graph | JSON serialization | DigiSim-importable JSON | -**Stage 4 output format:** -```json -{ - "components": [{ "id": "gate_0", "type": "AND", "x": 120, "y": 80 }], - "connections": [{ "from": "gate_0", "to": "gate_1", "fromPort": "output", "toPort": "input_a" }] -} -``` +**Stage 4 output format:** schema 2 (components with pins, undirected `nets`, ReactFlow `edges`, legacy gate-level +`connections`), documented in the `backend/pipeline/circuit_exporter.py` module docstring. ## Training Phases (do not advance without hitting threshold) diff --git a/README.md b/README.md index 56d08cc..57dbd34 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ should use the seeded cells or package their own. - **🔍 ⌘K Component Search**: Instant search and filtering across the entire component palette. - **⚙️ Real-time Simulation Engine**: Relaxation-based digital gate evaluation, a switch-level CMOS solver (NMOS/PMOS + supplies resolve to correct truth tables), and Modified Nodal Analysis (MNA) solver for analog nodes with live signal propagation (HIGH/LOW/Z/X). - **📸 ML Image-to-Circuit Detection**: - - **YOLOv8 Schematic Detection**: Detects schematic symbols and uses OpenCV line transforms (Hough) to extract wire paths into a NetworkX graph. See [Machine learning status](#-machine-learning-status) for what the detector currently recognises. + - **YOLOv8 Schematic Detection**: Detects schematic symbols, then traces wires classically (OpenCV skeleton nets, junction vs crossover, pin assignment) into a net-based NetworkX graph. See [Machine learning status](#-machine-learning-status) for what the detector currently recognises. - **DINOv2 Physical Board Analysis**: Physical board photo component recognition using DINOv2 embeddings and OCR. - **📄 Human & LLM-Parsable Netlist JSON Schema**: Export and import circuits using an intuitive, semantic JSON format (`input_A.out -> and_1.a`) with 100% loss-free round-trip reconstruction. @@ -133,8 +133,8 @@ deploy steps and required secrets: [`docs/deploy-vercel-render.md`](docs/deploy- ## 🧠 Machine Learning Status The image-to-circuit pipeline is four strictly sequential stages: YOLOv8 detection -(`backend/pipeline/detector.py`), classical OpenCV wire extraction -(`wire_extractor.py`, no neural network), NetworkX graph building +(`backend/pipeline/detector.py`), classical OpenCV net tracing +(`net_tracer.py`, no neural network), net-based NetworkX graph building (`graph_builder.py`) and DigiSim JSON export (`circuit_exporter.py`). Details: [`agent_docs/ml-pipeline.md`](agent_docs/ml-pipeline.md). @@ -149,7 +149,7 @@ What is true today: (`ml/classes.yaml`) and a synthetic transistor and gate generator (`backend/data_gen/generate_v2.py`, see [`docs/synth_v2/README.md`](docs/synth_v2/README.md)) are in place; it still needs 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, + and a GPU training run (net tracing for transistor-level schematics is in place). 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 67c9e5f..0d76e37 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -4,16 +4,31 @@ Photo of a circuit → structured JSON → DigiSim recreates the circuit automatically. ## 4 Stages (strictly sequential) -Image → [Stage 1: YOLO Detection] → [Stage 2: OpenCV Wire Extraction] +Image → [Stage 1: YOLO Detection] → [Stage 2: OpenCV Net Tracing (wire extraction)] -→ [Stage 3: NetworkX Graph] → [Stage 4: DigiSim JSON Export] +→ [Stage 3: NetworkX Net Graph] → [Stage 4: DigiSim JSON Export] | Stage | File | Method | Output | |-------|------|--------|--------| -| 1 | `backend/pipeline/detector.py` | YOLOv8 transfer learning | Bounding boxes + class labels | -| 2 | `backend/pipeline/wire_extractor.py` | OpenCV only — no neural net | Wire segments as pixel pairs | -| 3 | `backend/pipeline/graph_builder.py` | NetworkX DiGraph | Directed circuit graph | -| 4 | `backend/pipeline/circuit_exporter.py` | JSON serialization | DigiSim-importable JSON | +| 1 | `backend/pipeline/detector.py` | YOLOv8 transfer learning | Boxes + class labels (+ optional per-terminal keypoints) | +| 2 | `backend/pipeline/net_tracer.py` (+ `ink.py`, `skeleton_graph.py`, `pin_assignment.py`, `label_attach.py`) | OpenCV/scikit-image only, no neural net | Components with resolved pins, undirected nets, labels | +| 3 | `backend/pipeline/graph_builder.py` | NetworkX bipartite component/net MultiGraph | Net-based circuit graph | +| 4 | `backend/pipeline/circuit_exporter.py` | JSON serialization | Schema 2 JSON (components with pins, nets, ReactFlow edges, legacy `connections`) | + +## Net Tracing (stage 2) +- Ink is binarised against a morphological paper-background estimate; symbol boxes are erased (plus a margin), junction dots are kept; + the wire ink is skeletonised into edges and branch clusters. A cluster whose centre lies in a `JUNCTION` box connects all its wires; + a dotless 4-way cluster is a crossover (straight-through pairs only); any other branch point connects. VDD symbols share one global net, + GND symbols another. Every threshold scales with the measured stroke width and the median symbol size (`TraceConfig`). +- Pins: wire ends at a symbol box are its contacts. With detector keypoints (`Detection.keypoints`: keypoint i = terminal i of the class in + `ml/classes.yaml`, the contract for a T7 pose head) contacts are matched to keypoints; without them a classical rule set assigns terminals + (MOSFET drain/source by electrical distance to the supply, gates by input side) and estimates the 8-way orientation. +- Labels: names beside ports and supplies are cropped and read with RapidOCR's recogniser; nets take their port's name. +- Bench: `cd backend && uv run python data_gen/generate_v2.py --count 300 --seed 1 --out DIR && uv run python bench_tracing.py --data DIR --truth-table` + drives the tracer from perturbed ground-truth detections and scores it with `ml/eval_netlist.py` per render style (clean = cad/textbook, + hand_drawn = hand/photo); it exits 1 unless net F1 >= 0.90 for both styles, exact match >= 70% clean / >= 50% hand-drawn, and p95 runtime < 2 s. +- Not yet: the T3 screenshot round-trip check, and the frontend importer (T9) still reads only the legacy `connections` (gate-level); wiring + transistor-level imports means consuming `nets`/`edges` (handles `t:`/`s:` + terminal) and `library_cell` in `App.tsx importCircuit`. ## Class Vocabulary Single source of truth: `ml/classes.yaml` (name, tier, YOLO id, frontend node type, terminals, default size, legacy aliases). @@ -57,8 +72,8 @@ Current phase: `ml/experiments/current_phase.txt` 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 +- **End-to-end (optional):** `--gt-netlists DIR --pred-netlists DIR` (files `.json`, schema in `ml/eval_netlist.py`; the T2 generator's + pin-map netlists are read as ground truth directly, and the stage 4 exporter output is a valid prediction) 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. `--freeze` exists because the hash check needs a diff --git a/backend/app.py b/backend/app.py index cdcf5b8..47d2961 100644 --- a/backend/app.py +++ b/backend/app.py @@ -8,6 +8,7 @@ import tempfile from pathlib import Path +import cv2 from dotenv import load_dotenv from flask import Flask, jsonify, request from flask_cors import CORS @@ -19,7 +20,8 @@ from pipeline.circuit_exporter import CircuitExporter from pipeline.detector import GateDetector from pipeline.graph_builder import GraphBuilder -from pipeline.wire_extractor import WireExtractor +from pipeline.label_attach import rapidocr_recognizer +from pipeline.net_tracer import NetTracer from projects import projects_bp from recognition import recognition_bp @@ -116,11 +118,12 @@ def detect_gates() -> tuple: @require_auth def detect_circuit() -> tuple: """ - Run the full local pipeline: detection → wire extraction → graph → JSON export. + Run the full local pipeline: detection → net tracing → net graph → JSON export. Returns: - JSON with 'components' and 'connections' (CircuitExportJSON) on success, - 503 while model weights are missing, or an 'error' key on failure. + JSON in the exporter's schema_version 2 (components with pins, nets, edges, plus the legacy + 'connections' list CircuitExportJSON reads) on success, 503 while model weights are missing, + or an 'error' key on failure. Raises: 400: When no image file is included in the request. 500: When any pipeline stage fails. @@ -149,10 +152,11 @@ def detect_circuit() -> tuple: temp_path = Path(tmp.name) detections = detector.detect(temp_path) - gate_boxes = [d.box for d in detections if d.class_name != "JUNCTION"] - wires = WireExtractor().extract(temp_path, exclude_boxes=gate_boxes) - graph = GraphBuilder().build(detections, wires) - payload = CircuitExporter().export(graph) + image = cv2.imread(str(temp_path)) + if image is None: + return jsonify({"error": "Could not decode the uploaded image"}), 400 + trace = NetTracer(ocr=rapidocr_recognizer).trace(image, detections) + payload = CircuitExporter().export(GraphBuilder().build(trace)) payload["status"] = "ok" payload["detections"] = [ { diff --git a/backend/bench_tracing.py b/backend/bench_tracing.py new file mode 100644 index 0000000..ca83672 --- /dev/null +++ b/backend/bench_tracing.py @@ -0,0 +1,362 @@ +""" +Module: bench_tracing.py +Purpose: Benchmark for net tracing v2 (T8). Runs the classical net tracer on synthetic samples + from the T2 generator (backend/data_gen/generate_v2.py) driven by ground-truth + detections with realistic perturbation (box jitter, keypoint jitter, missed junction + dots), then scores the exported netlists with the T6 evaluation harness + (ml/eval_netlist.py): net precision/recall/F1 over pin pairs and netlist exact match, + split into clean renders (cad, textbook) and hand-drawn-style renders (hand, photo). + Also reports per-image runtime, orientation-head accuracy, MOSFET drain/source accuracy + and port-label accuracy (over ports whose name is drawn in the image). No trained weights are needed; the same tracer runs unchanged + on real detector output (T7). + +Usage: + cd backend + uv run python data_gen/generate_v2.py --count 300 --seed 1 --out /tmp/synth300 + uv run python bench_tracing.py --data /tmp/synth300 --count 300 --out /tmp/bench --mode both +Exit code: 0 when the acceptance gates pass (net F1 >= 0.90 on both styles, exact match >= 70% clean +and >= 50% hand-drawn) for every evaluated pin mode, 1 otherwise. +""" + +from __future__ import annotations + +import argparse +import json +import shutil +import sys +import time +from collections import Counter +from dataclasses import dataclass +from pathlib import Path + +import cv2 +import numpy as np + +BACKEND_DIR = Path(__file__).resolve().parent +sys.path.insert(0, str(BACKEND_DIR)) +sys.path.insert(0, str(BACKEND_DIR.parent / "ml")) + +from eval_netlist import evaluate_netlists # noqa: E402 + +from pipeline.circuit_exporter import CircuitExporter # noqa: E402 +from pipeline.detector import Detection # noqa: E402 +from pipeline.graph_builder import GraphBuilder # noqa: E402 +from pipeline.label_attach import rapidocr_recognizer # noqa: E402 +from pipeline.net_tracer import NetTracer # noqa: E402 +from pipeline.pin_assignment import CANONICAL_PINS, orient_vector # noqa: E402 +from pipeline.trace_types import Orientation, TextBox # noqa: E402 + +CLEAN_MODES = ("cad", "textbook") +HAND_MODES = ("hand", "photo") +DOMAIN_RULES: tuple[tuple[str, str], ...] = (("cad_", "clean"), ("textbook_", "clean"), ("hand_", "hand_drawn"), ("photo_", "hand_drawn")) +GATES = {"clean": {"net_f1": 0.90, "exact_match": 0.70}, "hand_drawn": {"net_f1": 0.90, "exact_match": 0.50}} +RUNTIME_LIMIT_S = 2.0 +MIRROR_SYMMETRIC = frozenset({"VDD", "GND", "INPUT_PORT", "OUTPUT_PORT", "NOT"}) + + +@dataclass(frozen=True) +class Perturbation: + """How ground-truth detections are degraded to look like detector output.""" + + box_sigma: float = 0.03 # each box edge moves by N(0, sigma * box side) + keypoint_sigma: float = 0.03 # keypoints move by N(0, sigma * short box side) per axis + junction_miss: float = 0.02 # probability a junction dot is not detected + junction_sigma: float = 0.1 # junction box edges move by N(0, sigma * dot diameter) + + +def perturb_detections(annotation: dict, rng: np.random.Generator, p: Perturbation, keypoints: bool) -> list[Detection]: + """ + Build detector-like detections from a T2 annotation. + + Args: + annotation: T2 annotation (symbols with bbox/pins, junctions with bbox). + rng: Random generator. + p: Perturbation settings. + keypoints: Attach (jittered) pin keypoints, as a pose head would. + Returns: + Detections: symbols first (annotation order), then the junctions that were not dropped. + """ + dets: list[Detection] = [] + for sym in annotation["symbols"]: + x1, y1, x2, y2 = sym["bbox"] + w, h = x2 - x1, y2 - y1 + x1, x2 = x1 + rng.normal(0, p.box_sigma * w), x2 + rng.normal(0, p.box_sigma * w) + y1, y2 = y1 + rng.normal(0, p.box_sigma * h), y2 + rng.normal(0, p.box_sigma * h) + kps = None + if keypoints: + s = p.keypoint_sigma * min(w, h) + kps = {t: (float(xy[0] + rng.normal(0, s)), float(xy[1] + rng.normal(0, s))) for t, xy in sym["pins"].items()} + dets.append(Detection(sym["class"], float(rng.uniform(0.6, 0.99)), (x1 + x2) / 2, (y1 + y2) / 2, abs(x2 - x1), abs(y2 - y1), keypoints=kps)) + for j in annotation["junctions"]: + if rng.random() < p.junction_miss: + continue + x1, y1, x2, y2 = j["bbox"] + d = p.junction_sigma * j["diameter"] + x1, x2, y1, y2 = (v + rng.normal(0, d) for v in (x1, x2, y1, y2)) + dets.append(Detection("JUNCTION", float(rng.uniform(0.6, 0.99)), (x1 + x2) / 2, (y1 + y2) / 2, abs(x2 - x1), abs(y2 - y1))) + return dets + + +def ground_truth_netlist(netlist: dict, annotation: dict) -> dict: + """ + T2 netlist in the evaluator's nets-of-pins schema, with ground-truth boxes for component pairing. + + Args: + netlist: T2 netlist.json. + annotation: T2 annotation (symbol boxes by id). + Returns: + {"components": [{"id", "type", "bbox"}], "nets": [[pins]]}. + """ + boxes = {s["id"]: s["bbox"] for s in annotation["symbols"]} + by_net: dict[str, list[str]] = {} + comps = [] + for c in netlist["components"]: + comps.append({"id": c["id"], "type": c["node_type"], "bbox": boxes[c["id"]]}) + for t, n in c["pins"].items(): + by_net.setdefault(n, []).append(f"{c['id']}:{t}") + return {"components": comps, "nets": [sorted(v) for _, v in sorted(by_net.items())]} + + +def _orientation_ok(cls: str, pred: dict | None, truth: dict) -> bool: + """ + Whether a predicted orientation matches ground truth, modulo the symbol's own symmetry. + + Args: + cls: Class name. + pred: Exported orientation dict or None. + truth: Annotation orientation {"rotation", "mirror"}. + Returns: + True when the orientations are equivalent for this symbol. + """ + if pred is None: + return False + if cls in MIRROR_SYMMETRIC: + # A mirror-symmetric symbol is fixed by the direction of its pin axis alone. + return _pin_axis(cls, pred) == _pin_axis(cls, truth) + return pred["rotation"] == truth["rotation"] and pred["mirror"] == truth["mirror"] + + +def _pin_axis(cls: str, o: dict) -> tuple[int, int]: + """ + Screen direction of a mirror-symmetric symbol's canonical pin axis under an orientation. + + Args: + cls: Class name. + o: Orientation {"rotation", "mirror"}. + Returns: + Rounded unit direction (dx, dy). + """ + v = orient_vector(CANONICAL_PINS[cls][next(iter(CANONICAL_PINS[cls]))], Orientation(int(o["rotation"]), bool(o["mirror"]))) + return (int(np.sign(round(v[0], 6))), int(np.sign(round(v[1], 6)))) + + +def run_mode(samples: list[dict], data: Path, out: Path, mode: str, perturb: Perturbation, seed: int, ocr: str, truth_table: bool) -> dict: + """ + Trace every sample in one pin mode and score it. + + Args: + samples: Manifest entries. + data: T2 dataset root. + out: Output directory for this mode (gt/, pred/, report). + mode: "keypoints" or "geometry". + perturb: Perturbation settings. + seed: Perturbation seed. + ocr: "gt" (annotation texts), "rapidocr" or "none". + truth_table: Also run truth-table equivalence through DigiSim's simulator. + Returns: + Summary dict. + """ + gt_dir, pred_dir = out / "gt", out / "pred" + for d in (gt_dir, pred_dir): + shutil.rmtree(d, ignore_errors=True) + d.mkdir(parents=True) + tracer = NetTracer(ocr=rapidocr_recognizer if ocr == "rapidocr" else None) + times: list[float] = [] + orient = {"ok": 0, "n": 0} + ds = {"ok": 0, "n": 0} + labels = {"ok": 0, "n": 0} + per_sample: dict[str, dict] = {} + for entry in samples: + ann = json.loads((data / entry["files"]["annotation"]["path"]).read_text()) + net = json.loads((data / entry["files"]["netlist"]["path"]).read_text()) + image = cv2.imread(str(data / entry["files"]["image"]["path"])) + rng = np.random.default_rng([seed, int(entry["id"])]) + dets = perturb_detections(ann, rng, perturb, keypoints=(mode == "keypoints")) + texts = [TextBox(t["text"], tuple(t["bbox"])) for t in ann["texts"]] if ocr == "gt" else None + t0 = time.perf_counter() + trace = tracer.trace(image, dets, texts=texts) + payload = CircuitExporter().export(GraphBuilder().build(trace)) + times.append(time.perf_counter() - t0) + stem = f"{ann['render_style']['mode']}_{entry['id']}" + (gt_dir / f"{stem}.json").write_text(json.dumps(ground_truth_netlist(net, ann))) + (pred_dir / f"{stem}.json").write_text(json.dumps(payload)) + per_sample[stem] = {"seconds": round(times[-1], 4), "diagnostics": trace.diagnostics.__dict__} + id_map = {comp["id"]: sym["id"] for sym, comp in zip(ann["symbols"], payload["components"])} + gt_pin_net = {f"{sym['id']}:{t}": n for sym in ann["symbols"] for t, n in sym["nets"].items()} + pred_net_pins = {n["id"]: n["pins"] for n in payload["nets"]} + drawn = {t["text"] for t in ann["texts"]} + for sym, comp in zip(ann["symbols"], payload["components"]): + ok = _orientation_ok(sym["class"], comp["orientation"], sym["orientation"]) + orient["n"] += 1 + orient["ok"] += int(ok) + if sym["class"] in ("NMOS", "PMOS") and all(comp["pins"].get(t, {}).get("net") for t in ("d", "s")): + ds["n"] += 1 + own = {f"{comp['id']}:d", f"{comp['id']}:s"} + got = {t: _majority_gt_net(pred_net_pins[comp["pins"][t]["net"]], own, id_map, gt_pin_net) for t in ("d", "s")} + ds["ok"] += int(got["d"] == sym["nets"]["d"] and got["s"] == sym["nets"]["s"]) + name = next(iter(sym["nets"].values())) + if sym["class"] in ("INPUT_PORT", "OUTPUT_PORT") and name in drawn: + labels["n"] += 1 + labels["ok"] += int(comp["label"] == name) + report = evaluate_netlists(gt_dir, pred_dir, truth_table=truth_table, domain_rules=DOMAIN_RULES) + arr = np.array(times) + summary = { + "mode": mode, + "samples": len(samples), + "runtime_s": {"mean": round(float(arr.mean()), 4), "p95": round(float(np.percentile(arr, 95)), 4), "max": round(float(arr.max()), 4)}, + "orientation_accuracy": round(orient["ok"] / orient["n"], 4) if orient["n"] else None, + "mosfet_ds_accuracy": round(ds["ok"] / ds["n"], 4) if ds["n"] else None, + "port_label_accuracy": round(labels["ok"] / labels["n"], 4) if labels["n"] and ocr != "none" else None, + "overall": report["overall"], + "per_domain": report["per_domain"], + "per_render_mode": _per_render_mode(report["circuits"]), + } + (out / "report.json").write_text(json.dumps({"summary": summary, "evaluation": report, "per_sample": per_sample}, indent=1, default=str)) + return summary + + +def _majority_gt_net(pins: list[str], exclude: set[str], id_map: dict[str, str], gt_pin_net: dict[str, str]) -> str | None: + """ + Ground-truth net most of a predicted net's pins belong to. + + Args: + pins: Pins of the predicted net (predicted component ids). + exclude: Pins to ignore (the transistor's own channel pins). + id_map: Predicted component id -> ground-truth component id. + gt_pin_net: Ground-truth ":" -> net name. + Returns: + The majority ground-truth net name, or None when no pin maps. + """ + votes = Counter(gt_pin_net.get(f"{id_map[p.partition(':')[0]]}:{p.partition(':')[2]}") for p in pins if p not in exclude) + votes.pop(None, None) + return votes.most_common(1)[0][0] if votes else None + + +def _per_render_mode(circuits: dict[str, dict]) -> dict[str, dict]: + """ + Net F1 and exact-match rate per render mode, from the evaluator's per-circuit records. + + Args: + circuits: evaluate_netlists()["circuits"]. + Returns: + Mode -> {circuits, net_f1, exact_match}. + """ + acc: dict[str, dict[str, float]] = {} + for stem, rec in circuits.items(): + m = stem.split("_")[0] + a = acc.setdefault(m, {"n": 0, "tp": 0, "fp": 0, "fn": 0, "exact": 0}) + a["n"] += 1 + a["exact"] += int(rec["exact_match"]) + for k in ("tp", "fp", "fn"): + a[k] += rec["pairs"][k] + return { + m: { + "circuits": int(a["n"]), + "net_f1": round(2 * a["tp"] / max(1, 2 * a["tp"] + a["fp"] + a["fn"]), 4), + "exact_match": round(a["exact"] / a["n"], 4), + } + for m, a in sorted(acc.items()) + } + + +def gates_pass(summary: dict) -> bool: + """ + Whether a mode's summary meets the T8 acceptance gates. + + Args: + summary: run_mode() summary. + Returns: + True when every domain gate and the runtime limit pass. + """ + for domain, gate in GATES.items(): + d = summary["per_domain"].get(domain) + if d is None or (d["net_micro"]["f1"] or 0.0) < gate["net_f1"] or d["exact_match"]["value"] < gate["exact_match"]: + return False + return summary["runtime_s"]["p95"] < RUNTIME_LIMIT_S + + +def markdown(summaries: list[dict], perturb: Perturbation) -> str: + """ + Markdown table of the bench results. + + Args: + summaries: Per-mode summaries. + perturb: Perturbation used. + Returns: + Markdown text. + """ + lines = [ + "# Net tracing v2 bench", + "", + f"Perturbation: {perturb}", + "", + "| pin mode | domain | circuits | net P | net R | net F1 | exact match | truth-table equiv. | gate |", + "|---|---|---|---|---|---|---|---|---|", + ] + for s in summaries: + for domain, d in sorted(s["per_domain"].items()): + nm = d["net_micro"] + gate = GATES.get(domain, {}) + ok = (nm["f1"] or 0) >= gate.get("net_f1", 0) and d["exact_match"]["value"] >= gate.get("exact_match", 0) + tt = d["truth_table"]["value"] + tt_text = "n/a" if tt is None else f"{tt:.3f}" + lines.append( + f"| {s['mode']} | {domain} | {d['circuits']} | {nm['precision']:.4f} | {nm['recall']:.4f} | {nm['f1']:.4f} | {d['exact_match']['value']:.3f} | {tt_text} | {'pass' if ok else 'FAIL'} |" + ) + lines += ["", "| pin mode | render mode | circuits | net F1 | exact match |", "|---|---|---|---|---|"] + for s in summaries: + for m, d in s["per_render_mode"].items(): + lines.append(f"| {s['mode']} | {m} | {d['circuits']} | {d['net_f1']:.4f} | {d['exact_match']:.3f} |") + lines += ["", "| pin mode | runtime mean / p95 / max (s) | orientation acc | MOSFET d/s acc | port label acc |", "|---|---|---|---|---|"] + for s in summaries: + r = s["runtime_s"] + lines.append(f"| {s['mode']} | {r['mean']} / {r['p95']} / {r['max']} | {s['orientation_accuracy']} | {s['mosfet_ds_accuracy']} | {s['port_label_accuracy']} |") + return "\n".join(lines) + "\n" + + +def main(argv: list[str] | None = None) -> int: + """ + CLI entry point. + + Args: + argv: Arguments (defaults to sys.argv). + Returns: + 0 when every evaluated mode passes the gates, else 1. + """ + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--data", type=Path, required=True, help="T2 dataset root (has manifest.json)") + parser.add_argument("--count", type=int, default=300, help="samples to evaluate (first N of the manifest)") + parser.add_argument("--out", type=Path, default=BACKEND_DIR.parent / "ml" / "experiments" / "trace_bench") + parser.add_argument("--mode", choices=("keypoints", "geometry", "both"), default="both") + parser.add_argument("--seed", type=int, default=0, help="perturbation seed") + parser.add_argument("--ocr", choices=("gt", "rapidocr", "none"), default="gt", help="text source for label attachment") + parser.add_argument("--truth-table", action="store_true", help="also check truth-table equivalence (needs node + frontend deps)") + parser.add_argument("--box-sigma", type=float, default=Perturbation.box_sigma) + parser.add_argument("--keypoint-sigma", type=float, default=Perturbation.keypoint_sigma) + parser.add_argument("--junction-miss", type=float, default=Perturbation.junction_miss) + args = parser.parse_args(argv) + cv2.setNumThreads(1) + manifest = json.loads((args.data / "manifest.json").read_text()) + samples = sorted(manifest["samples"], key=lambda e: e["id"])[: args.count] + perturb = Perturbation(box_sigma=args.box_sigma, keypoint_sigma=args.keypoint_sigma, junction_miss=args.junction_miss) + modes = ("keypoints", "geometry") if args.mode == "both" else (args.mode,) + summaries = [run_mode(samples, args.data, args.out / m, m, perturb, args.seed, args.ocr, args.truth_table) for m in modes] + md = markdown(summaries, perturb) + args.out.mkdir(parents=True, exist_ok=True) + (args.out / "report.md").write_text(md) + print(md) + return 0 if all(gates_pass(s) for s in summaries) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/pipeline/circuit_exporter.py b/backend/pipeline/circuit_exporter.py index f38bfdf..7c74ca3 100644 --- a/backend/pipeline/circuit_exporter.py +++ b/backend/pipeline/circuit_exporter.py @@ -1,24 +1,60 @@ """ Module: circuit_exporter.py -Purpose: JSON export stage — serialises a circuit graph into DigiSim-importable JSON. - This is Stage 4 (final stage) of the detection pipeline. +Purpose: JSON export stage - serialises the net-based circuit graph into DigiSim-importable + JSON. This is Stage 4 (final stage) of the detection pipeline. -Output format (matches CircuitExportJSON in frontend/src/types/api.ts): +Output (schema_version 2): { - "components": [ - {"id": "comp_0", "type": "andGate", "label": "AND Gate", - "x": 120, "y": 80} - ], - "connections": [ - {"from": "comp_0", "to": "comp_1", - "fromPort": "output", "toPort": "a"} - ] + "schema_version": 2, + "image": {"width": 1024, "height": 768}, + "components": [ + {"id": "MP1", "type": "pmos", "class": "PMOS", "label": "MP1", + "x": 262.3, "y": 194.3, "width": 42.0, "height": 74.4, "bbox": [x1, y1, x2, y2], + "confidence": 0.93, "orientation": {"rotation": 0, "mirror": true}, "pin_source": "keypoints", + "pins": {"s": {"x": 265.7, "y": 196.3, "net": "n2"}, "g": {...}, "d": {...}}, + "library_cell": null}, + {"id": "U1", "type": "nandGate", ..., "library_cell": {"id": "std-nand", "pins": {"a": "a", "b": "b", "out": "out"}}} + ], + "nets": [{"id": "n2", "label": "VDD", "pins": ["MP1:s", "VDD1:pos"]}, ...], + "edges": [{"id": "e0", "source": "VDD1", "sourceHandle": "s:pos", "target": "MP1", "targetHandle": "t:s"}, ...], + "connections": [{"from": "IN1", "to": "U1", "fromPort": "output", "toPort": "a"}, ...], + "warnings": [] } + - components[].type is a frontend node type from ml/classes.yaml: nmos, pmos, vsource, ground, input, + output (the transistor-first palette), the legacy gate node types, or tier-B analog types. Gate symbols + also name the seeded standard cell (frontend/src/logic/library/standardCells.ts) they map to, with the + detector terminal -> cell pin id map; XNOR has no seeded cell and stays a legacy gate (library_cell null). + - nets are undirected sets of ":" pins - the same shape ml/eval_netlist.py scores. + - edges realise every net as ReactFlow edges with the app's handle ids (t:/s: prefixed for transistor-level + nodes, a/b for gate inputs, null for single-handle nodes), rooted at the net's driver when it has one; + this is what the transistor-first importer (T9) consumes. + - connections is the legacy (schema 1) directed gate-level list, kept so the current importer + (App.tsx importCircuit, CircuitExportJSON) still wires gate-level circuits; it only lists links between + input/output/gate components. """ +from __future__ import annotations + import networkx as nx -# Human-readable labels for ReactFlow node types. +SCHEMA_VERSION = 2 + +GATE_TYPES = frozenset({"andGate", "orGate", "notGate", "nandGate", "norGate", "xorGate", "xnorGate"}) +# Node types whose handles carry a t:/s: prefix (target/source variants of each terminal). +HANDLE_PREFIX_TYPES = frozenset({"nmos", "pmos", "vsource", "ground", "clockSource", "resistor", "capacitor", "inductor", "bjtNpn", "bjtPnp"}) +LEGACY_TYPES = GATE_TYPES | {"input", "output"} + +# Gate node type -> seeded standard cell and the detector-terminal -> cell-pin-id map. +LIBRARY_CELLS: dict[str, dict[str, object]] = { + "notGate": {"id": "std-not", "pins": {"a": "in", "out": "out"}}, + "nandGate": {"id": "std-nand", "pins": {"a": "a", "b": "b", "out": "out"}}, + "norGate": {"id": "std-nor", "pins": {"a": "a", "b": "b", "out": "out"}}, + "andGate": {"id": "std-and", "pins": {"a": "a", "b": "b", "out": "out"}}, + "orGate": {"id": "std-or", "pins": {"a": "a", "b": "b", "out": "out"}}, + "xorGate": {"id": "std-xor", "pins": {"a": "a", "b": "b", "out": "out"}}, +} + +# Human-readable fallback labels for ReactFlow node types. NODE_TYPE_LABELS: dict[str, str] = { "andGate": "AND Gate", "orGate": "OR Gate", @@ -29,45 +65,137 @@ "xnorGate": "XNOR Gate", "input": "Input", "output": "Output", + "nmos": "NMOS", + "pmos": "PMOS", + "vsource": "VDD", + "ground": "GND", } +def _is_driver(node_type: str, terminal: str) -> bool: + """ + Whether a pin drives its net in gate-level evaluation. + + Args: + node_type: Frontend node type. + terminal: Terminal name. + Returns: + True for an input port output and a gate output. + """ + return terminal == "out" and (node_type == "input" or node_type in GATE_TYPES) + + +def source_handle(node_type: str, terminal: str) -> str | None: + """ + ReactFlow source handle id of a pin. + + Args: + node_type: Frontend node type. + terminal: Terminal name. + Returns: + "s:" for prefixed node types, None for single/default-output nodes. + """ + return f"s:{terminal}" if node_type in HANDLE_PREFIX_TYPES else None + + +def target_handle(node_type: str, terminal: str) -> str | None: + """ + ReactFlow target handle id of a pin. + + Args: + node_type: Frontend node type. + terminal: Terminal name. + Returns: + "t:" for prefixed node types, the input id for gates, None for single-handle nodes. + """ + if node_type in HANDLE_PREFIX_TYPES: + return f"t:{terminal}" + return terminal if node_type in GATE_TYPES else None + + class CircuitExporter: - """Serialises a NetworkX circuit graph to DigiSim JSON format.""" + """Serialises the net-based circuit graph to DigiSim JSON (schema_version 2, plus legacy connections).""" - def export(self, graph: nx.DiGraph) -> dict: + def export(self, graph: nx.MultiGraph) -> dict[str, object]: """ Convert a circuit graph into a DigiSim-importable JSON dict. Args: - graph: A networkx.DiGraph produced by GraphBuilder. + graph: A networkx.MultiGraph produced by GraphBuilder.build. Returns: - Dict with 'components' and 'connections' keys matching - CircuitExportJSON. + Dict with schema_version, image, components, nets, edges, connections and warnings (see module docstring). """ + comps = {n: a for n, a in graph.nodes(data=True) if a.get("kind") == "component"} + nets = {n: a for n, a in graph.nodes(data=True) if a.get("kind") == "net"} + net_pins: dict[str, list[tuple[str, str]]] = {n: [] for n in nets} + pin_net: dict[tuple[str, str], str] = {} + for u, v, terminal in graph.edges(keys=True): + comp, net = (u, v) if u in comps else (v, u) + net_pins[net].append((comp, terminal)) + pin_net[(comp, terminal)] = nets[net]["net_id"] + components = [] - for node_id, attrs in graph.nodes(data=True): - node_type = attrs.get("node_type", "input") + for cid, a in comps.items(): + x1, y1, x2, y2 = a["box"] + o = a.get("orientation") + pins = { + t: {"x": None if p is None else round(float(p[0]), 1), "y": None if p is None else round(float(p[1]), 1), "net": pin_net.get((cid, t))} for t, p in sorted(a.get("pins", {}).items()) + } components.append( { - "id": node_id, - "type": node_type, - "label": NODE_TYPE_LABELS.get(node_type, attrs.get("class_name", "Component")), - "x": round(float(attrs.get("x", 0.0)), 1), - "y": round(float(attrs.get("y", 0.0)), 1), - "confidence": round(float(attrs.get("confidence", 0.0)), 3), + "id": cid, + "type": a["node_type"], + "class": a["class_name"], + "label": a.get("label") or NODE_TYPE_LABELS.get(a["node_type"], a["class_name"]), + "x": round(float(x1), 1), + "y": round(float(y1), 1), + "width": round(float(x2 - x1), 1), + "height": round(float(y2 - y1), 1), + "bbox": [round(float(v), 1) for v in (x1, y1, x2, y2)], + "confidence": round(float(a.get("confidence", 0.0)), 3), + "orientation": None if o is None else {"rotation": o.rotation, "mirror": o.mirror}, + "pin_source": a.get("pin_source"), + "pins": pins, + "library_cell": LIBRARY_CELLS.get(a["node_type"]), } ) + net_list = [] + edges = [] connections = [] - for src, dst, attrs in graph.edges(data=True): - connections.append( - { - "from": src, - "to": dst, - "fromPort": attrs.get("fromPort", "output"), - "toPort": attrs.get("toPort"), - } - ) + for net, members in sorted(net_pins.items(), key=lambda kv: nets[kv[0]]["net_id"]): + pins = sorted(f"{c}:{t}" for c, t in members) + net_list.append({"id": nets[net]["net_id"], "label": nets[net].get("label"), "pins": pins}) + if len(members) < 2: + continue + ordered = sorted(members) + root = next((m for m in ordered if _is_driver(comps[m[0]]["node_type"], m[1])), None) + root = root or next((m for m in ordered if comps[m[0]]["node_type"] != "output"), ordered[0]) + rtype = comps[root[0]]["node_type"] + for comp, terminal in ordered: + if (comp, terminal) == root: + continue + ctype = comps[comp]["node_type"] + edges.append( + { + "id": f"e{len(edges)}", + "source": root[0], + "sourceHandle": source_handle(rtype, root[1]), + "target": comp, + "targetHandle": target_handle(ctype, terminal), + } + ) + if _is_driver(rtype, root[1]) and ctype in LEGACY_TYPES and ctype != "input" and comp != root[0]: + connections.append({"from": root[0], "to": comp, "fromPort": "output", "toPort": target_handle(ctype, terminal)}) - return {"components": components, "connections": connections} + diagnostics = graph.graph.get("diagnostics") + width, height = graph.graph.get("image_size", (0, 0)) + return { + "schema_version": SCHEMA_VERSION, + "image": {"width": width, "height": height}, + "components": components, + "nets": net_list, + "edges": edges, + "connections": connections, + "warnings": list(getattr(diagnostics, "warnings", [])), + } diff --git a/backend/pipeline/class_map.py b/backend/pipeline/class_map.py index 260afe2..553a5ee 100644 --- a/backend/pipeline/class_map.py +++ b/backend/pipeline/class_map.py @@ -2,7 +2,8 @@ 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. + that old weights still predict, the class-to-frontend-node-type map and the + terminal names of each class (the net tracer's pin vocabulary). Regenerate with `cd ml && uv run python class_schema.py generate`. """ @@ -65,3 +66,27 @@ "OUTPUT": "output", "LED": "output", } + +# Canonical class name -> terminal names, in the frontend handle naming (t: / s:). +CLASS_TERMINALS: dict[str, tuple[str, ...]] = { + "NMOS": ("d", "g", "s", "b"), + "PMOS": ("s", "g", "d", "b"), + "VDD": ("pos", "neg"), + "GND": ("gnd",), + "INPUT_PORT": ("out",), + "OUTPUT_PORT": ("a",), + "JUNCTION": ("net",), + "AND": ("a", "b", "out"), + "OR": ("a", "b", "out"), + "NOT": ("a", "out"), + "NAND": ("a", "b", "out"), + "NOR": ("a", "b", "out"), + "XOR": ("a", "b", "out"), + "XNOR": ("a", "b", "out"), + "RESISTOR": ("a", "b"), + "CAPACITOR": ("a", "b"), + "INDUCTOR": ("a", "b"), + "BJT_NPN": ("c", "b", "e"), + "BJT_PNP": ("c", "b", "e"), + "CLOCK": ("out",), +} diff --git a/backend/pipeline/detector.py b/backend/pipeline/detector.py index 9eca31d..8cae602 100644 --- a/backend/pipeline/detector.py +++ b/backend/pipeline/detector.py @@ -5,23 +5,45 @@ 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. + +Detector -> tracer contract (pipeline/net_tracer.py): + Each Detection carries its class name, confidence and box. Optionally it carries per-terminal + pin points (`keypoints`): a pose/keypoint model (T7) predicts keypoint i of a detection as the + point of terminal i of its class, in the terminal order of ml/classes.yaml (CLASS_TERMINALS); + keypoints with visibility < KEYPOINT_MIN_VISIBILITY are dropped. Without keypoints the tracer + falls back to its classical geometry pin assignment. """ from dataclasses import dataclass from pathlib import Path -from ultralytics import YOLO - -from pipeline.class_map import CLASS_ALIASES, CLASS_NAMES, CLASS_TO_NODE_TYPE +from pipeline.class_map import CLASS_ALIASES, CLASS_NAMES, CLASS_TERMINALS, CLASS_TO_NODE_TYPE __all__ = [ "CLASS_ALIASES", "CLASS_NAMES", + "CLASS_TERMINALS", "CLASS_TO_NODE_TYPE", "Detection", "GateDetector", + "canonical_class", ] +KEYPOINT_MIN_VISIBILITY = 0.5 + + +def canonical_class(name: str) -> str: + """ + Resolve a detector class name (canonical or legacy alias, any case) to its canonical name. + + Args: + name: Class name as predicted by the weights. + Returns: + Canonical class name (unchanged when it is not a known alias). + """ + upper = name.upper() + return CLASS_ALIASES.get(upper, upper) + @dataclass class Detection: @@ -33,6 +55,8 @@ class Detection: y: float width: float height: float + # Terminal name -> pin point in image pixels, from a keypoint head (None when the model has none). + keypoints: dict[str, tuple[float, float]] | None = None @property def box(self) -> tuple[float, float, float, float]: @@ -65,6 +89,8 @@ def __init__(self, weights_path: Path, confidence_threshold: float = 0.5) -> Non """ if not weights_path.exists(): raise FileNotFoundError(f"Model weights not found: {weights_path}") + from ultralytics import YOLO # deferred: torch is only needed when a model is actually loaded + self.weights_path = weights_path self.confidence_threshold = confidence_threshold self._model = YOLO(str(weights_path)) @@ -93,16 +119,39 @@ def detect(self, image_path: Path) -> list[Detection]: detections: list[Detection] = [] for result in results: names = result.names - for box in result.boxes: + keypoints = getattr(result, "keypoints", None) + for i, box in enumerate(result.boxes): cx, cy, w, h = (float(v) for v in box.xywh[0]) + class_name = names[int(box.cls[0])] detections.append( Detection( - class_name=names[int(box.cls[0])], + class_name=class_name, confidence=float(box.conf[0]), x=cx, y=cy, width=w, height=h, + keypoints=_terminal_keypoints(class_name, keypoints, i), ) ) return detections + + +def _terminal_keypoints(class_name: str, keypoints: object, index: int) -> dict[str, tuple[float, float]] | None: + """ + Map a pose model's keypoints for one detection onto the class's terminal names. + + Args: + class_name: Predicted class name. + keypoints: ultralytics Keypoints object of the result (None for a plain detection model). + index: Detection index inside the result. + Returns: + Terminal -> (x, y) for visible keypoints, or None when the model predicts no keypoints. + """ + if keypoints is None: + return None + xy = keypoints.xy[index].tolist() + conf = keypoints.conf[index].tolist() if keypoints.conf is not None else [1.0] * len(xy) + terminals = CLASS_TERMINALS.get(canonical_class(class_name), ()) + points = {t: (float(p[0]), float(p[1])) for t, p, c in zip(terminals, xy, conf) if c >= KEYPOINT_MIN_VISIBILITY} + return points or None diff --git a/backend/pipeline/graph_builder.py b/backend/pipeline/graph_builder.py index 08d0d0f..a441444 100644 --- a/backend/pipeline/graph_builder.py +++ b/backend/pipeline/graph_builder.py @@ -1,236 +1,66 @@ """ Module: graph_builder.py -Purpose: Graph construction stage — converts gate detections and wire segments into a - directed NetworkX graph representing the circuit topology. - -Approach: - 1. Wire segments are clustered into electrical nets with union-find: two - segments join the same net when any of their endpoints are close. - 2. A net touches a gate when one of its endpoints falls inside the gate's - inflated bounding box; touching the right half of the box means the - gate drives the net (output), the left half means the net feeds it. - 3. Each net becomes directed edges source-gate → target-gate(s). Junction - detections are ignored as nodes — the dot ink already keeps nets whole. +Purpose: Graph construction stage - turns a net trace into an undirected, net-based NetworkX + graph: a bipartite multigraph with one node per component and one node per electrical + net, and one edge per wired pin (component -- net, keyed by terminal name). Nets are + undirected on purpose: a MOSFET's drain and source have no signal direction and a + supply rail is shared by many devices, so no driver/consumer guess is made here (the + old left/right-of-box gate heuristics are gone). """ -from dataclasses import dataclass +from __future__ import annotations import networkx as nx -from pipeline.detector import CLASS_TO_NODE_TYPE, Detection -from pipeline.wire_extractor import WireSegment - -NET_JOIN_DISTANCE = 16.0 # px — endpoints closer than this share a net -BOX_INFLATE = 16.0 # px — contact tolerance around gate boxes - - -@dataclass -class CircuitNode: - """A single circuit component node in the graph.""" - - id: str - node_type: str - x: float - y: float - - -class _UnionFind: - """Minimal union-find over integer indices for net clustering.""" - - def __init__(self, n: int) -> None: - """ - Initialise n singleton sets. - - Args: - n: Number of elements. - """ - self.parent = list(range(n)) - - def find(self, a: int) -> int: - """ - Find the set root of element a with path compression. +from pipeline.trace_types import TraceResult - Args: - a: Element index. - Returns: - Root index of a's set. - """ - while self.parent[a] != a: - self.parent[a] = self.parent[self.parent[a]] - a = self.parent[a] - return a +NET_PREFIX = "net:" - def union(self, a: int, b: int) -> None: - """ - Merge the sets containing a and b. - Args: - a: First element index. - b: Second element index. - """ - self.parent[self.find(a)] = self.find(b) - - -def _endpoint_distance(s1: WireSegment, s2: WireSegment) -> float: +def net_node(net_id: str) -> str: """ - Smallest distance between any endpoint pair of two segments. + Graph node id of a net. Args: - s1: First segment. - s2: Second segment. + net_id: Net id from the trace (n0, n1, ...). Returns: - Minimum endpoint-to-endpoint distance in pixels. + Graph node id ("net:"), distinct from every component id. """ - best = float("inf") - for p in s1.endpoints: - for q in s2.endpoints: - d = ((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) ** 0.5 - best = min(best, d) - return best + return f"{NET_PREFIX}{net_id}" class GraphBuilder: - """Builds a directed circuit graph from detections and wire segments.""" + """Builds the net-based circuit graph from a TraceResult.""" - def build( - self, - detections: list[Detection], - wire_segments: list[WireSegment], - ) -> nx.DiGraph: + def build(self, trace: TraceResult) -> nx.MultiGraph: """ - Construct a NetworkX DiGraph from gate detections and wire segments. + Construct the component/net bipartite multigraph. Args: - detections: Gate detections from the detector stage. - wire_segments: Wire segments from the wire extractor stage. + trace: Output of NetTracer.trace. Returns: - A networkx.DiGraph where nodes are gates and edges are wire - connections carrying 'fromPort'/'toPort' attributes. + nx.MultiGraph. Component nodes carry kind="component", node_type, class_name, box, confidence, + orientation, label and pins (terminal -> point); net nodes carry kind="net" and label; each edge + (component, net, key=terminal) carries terminal. """ - graph = nx.DiGraph() - - components = [d for d in detections if d.class_name != "JUNCTION"] - for i, det in enumerate(components): - x1, y1, _, _ = det.box + graph = nx.MultiGraph(image_size=trace.image_size, diagnostics=trace.diagnostics) + for comp in trace.components: graph.add_node( - f"comp_{i}", - node_type=CLASS_TO_NODE_TYPE.get(det.class_name, "input"), - class_name=det.class_name, - confidence=det.confidence, - x=float(x1), - y=float(y1), + comp.id, + kind="component", + node_type=comp.node_type, + class_name=comp.class_name, + box=comp.box, + confidence=comp.confidence, + orientation=comp.orientation, + label=comp.label, + pin_source=comp.pin_source, + pins={t: p.point for t, p in comp.pins.items()}, ) - - nets = self._cluster_nets(wire_segments) - for net in nets: - contacts = self._net_contacts(net, components) - if len({gate for gate, _, _ in contacts}) < 2: - continue - self._add_net_edges(graph, contacts, components) + for net in trace.nets: + graph.add_node(net_node(net.id), kind="net", net_id=net.id, label=net.label) + for comp in trace.components: + for terminal, pin in comp.pins.items(): + if pin.net is not None: + graph.add_edge(comp.id, net_node(pin.net), key=terminal, terminal=terminal) return graph - - def _cluster_nets(self, segments: list[WireSegment]) -> list[list[WireSegment]]: - """ - Group wire segments into electrical nets. - - Args: - segments: All extracted wire segments. - Returns: - List of nets, each a list of segments. - """ - uf = _UnionFind(len(segments)) - for i in range(len(segments)): - for j in range(i + 1, len(segments)): - if _endpoint_distance(segments[i], segments[j]) <= NET_JOIN_DISTANCE: - uf.union(i, j) - nets: dict[int, list[WireSegment]] = {} - for i, seg in enumerate(segments): - nets.setdefault(uf.find(i), []).append(seg) - return list(nets.values()) - - def _net_contacts(self, net: list[WireSegment], components: list[Detection]) -> list[tuple[int, str, tuple[float, float]]]: - """ - Find which components a net touches and on which side. - - Args: - net: Segments belonging to one electrical net. - components: Non-junction detections in node order. - Returns: - List of (component index, 'left'|'right', contact point). - """ - contacts: list[tuple[int, str, tuple[float, float]]] = [] - seen: set[tuple[int, str, str]] = set() - for seg in net: - for px, py in seg.endpoints: - for idx, det in enumerate(components): - x1, y1, x2, y2 = det.box - if x1 - BOX_INFLATE <= px <= x2 + BOX_INFLATE and y1 - BOX_INFLATE <= py <= y2 + BOX_INFLATE: - side = "right" if px >= det.x else "left" - # Keep one contact per box quadrant so a gate's two - # input ports (top/bottom halves) both survive dedup. - half = "top" if py < det.y else "bottom" - if (idx, side, half) not in seen: - seen.add((idx, side, half)) - contacts.append((idx, side, (float(px), float(py)))) - return contacts - - def _add_net_edges( - self, - graph: nx.DiGraph, - contacts: list[tuple[int, str, tuple[float, float]]], - components: list[Detection], - ) -> None: - """ - Convert one net's gate contacts into directed edges. - - Args: - graph: Graph mutated in place. - contacts: Output of _net_contacts for this net. - components: Non-junction detections in node order. - """ - - def node_type(idx: int) -> str: - """Return the ReactFlow node type of component idx.""" - return CLASS_TO_NODE_TYPE.get(components[idx].class_name, "input") - - # Drivers: gates contacted on their output (right) side. Output-style - # nodes cannot drive a net. - sources = [c for c in contacts if c[1] == "right" and node_type(c[0]) != "output"] - if not sources: - # Fallback: the leftmost touched component drives the net. - leftmost = min(contacts, key=lambda c: components[c[0]].x) - sources = [leftmost] - - source_ids = {c[0] for c in sources} - # Consumers: contacted on their input (left) side. Input-style nodes - # have no input handles and can never be targets. - targets = [c for c in contacts if c[0] not in source_ids and node_type(c[0]) != "input"] - - for tgt_idx, _, tgt_point in targets: - # When bad segment merging yields several drivers on one net, - # pick the driver whose contact runs at the closest height. - src = min(sources, key=lambda c: abs(c[2][1] - tgt_point[1])) - to_port = self._input_port(components[tgt_idx], tgt_point) - graph.add_edge( - f"comp_{src[0]}", - f"comp_{tgt_idx}", - fromPort="output", - toPort=to_port, - ) - - def _input_port(self, det: Detection, contact: tuple[float, float]) -> str | None: - """ - Choose the frontend input handle id for a connection. - - Args: - det: Target component detection. - contact: Wire contact point in pixels. - Returns: - 'a'/'b' for gates, None for output-style single-handle nodes. - """ - node_type = CLASS_TO_NODE_TYPE.get(det.class_name, "input") - if node_type in ("output", "input"): - return None - if node_type == "notGate": - return "a" - return "a" if contact[1] < det.y else "b" diff --git a/backend/pipeline/ink.py b/backend/pipeline/ink.py new file mode 100644 index 0000000..045746d --- /dev/null +++ b/backend/pipeline/ink.py @@ -0,0 +1,87 @@ +""" +Module: ink.py +Purpose: Ink binarisation and scale estimation for the net tracer (classical OpenCV, no neural + networks). Normalises uneven lighting against a morphological background estimate so + faint ruled-paper lines and photo shading drop out while pen and pencil strokes stay, + and measures the stroke width that every size-relative tracing threshold scales with. +""" + +from __future__ import annotations + +import cv2 +import numpy as np + +# A pixel is ink when it is darker than this fraction of the local paper brightness. Ruled-paper +# lines blend to about 0.85 of the paper, pencil strokes to about 0.55, pen ink to under 0.3. +INK_RATIO = 0.72 +# Background kernel as a fraction of the longer image side (must exceed the largest junction dot). +BACKGROUND_KERNEL_FRACTION = 0.03 +MIN_BACKGROUND_KERNEL = 15 + + +def _odd(n: float) -> int: + """ + Round to the nearest odd integer >= 3. + + Args: + n: Size. + Returns: + Odd kernel size. + """ + k = max(3, int(round(n))) + return k if k % 2 else k + 1 + + +def to_gray(image: np.ndarray) -> np.ndarray: + """ + Convert an image to single-channel float32 grayscale. + + Args: + image: BGR, BGRA or grayscale uint8 image. + Returns: + HxW float32 array in [0, 255]. + """ + if image.ndim == 2: + return image.astype(np.float32) + code = cv2.COLOR_BGRA2GRAY if image.shape[2] == 4 else cv2.COLOR_BGR2GRAY + return cv2.cvtColor(image, code).astype(np.float32) + + +def ink_mask(image: np.ndarray) -> np.ndarray: + """ + Binarise pen/pencil ink against an estimated paper background. + + Args: + image: BGR (or grayscale) uint8 image. + Returns: + HxW bool mask, True on ink pixels. + """ + gray = to_gray(image) + h, w = gray.shape + k = _odd(max(MIN_BACKGROUND_KERNEL, BACKGROUND_KERNEL_FRACTION * max(h, w))) + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k)) + background = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel) + background = cv2.blur(background, (k, k)) + ratio = gray / np.maximum(background, 1.0) + return ratio < INK_RATIO + + +def stroke_width(mask: np.ndarray) -> float: + """ + Typical stroke width from the median distance-to-background d along stroke centre lines (2d - 1, since the + centre pixel itself counts once). + + Centre lines are the ridge pixels of the distance transform (local maxima), so filled shapes + such as junction dots and arrow heads contribute only a few pixels and do not skew the estimate. + + Args: + mask: Bool ink mask. + Returns: + Stroke width in pixels (at least 1.0). + """ + if not mask.any(): + return 1.0 + dist = cv2.distanceTransform(mask.astype(np.uint8), cv2.DIST_L2, cv2.DIST_MASK_PRECISE) + ridge = (dist > 0) & (dist >= cv2.dilate(dist, np.ones((3, 3), np.uint8))) + values = dist[ridge] if ridge.any() else dist[dist > 0] + return max(1.0, float(2.0 * np.median(values) - 1.0)) diff --git a/backend/pipeline/label_attach.py b/backend/pipeline/label_attach.py new file mode 100644 index 0000000..eb7954e --- /dev/null +++ b/backend/pipeline/label_attach.py @@ -0,0 +1,257 @@ +""" +Module: label_attach.py +Purpose: OCR label attachment for the net tracer. Port and supply names are read where they + are written - beside the symbol, on the side away from its wire: the isolated glyphs + there are cropped tightly and passed to RapidOCR's recogniser alone (already a backend + dependency, CPU ONNX; whole-page detection merges one-letter names with arrow heads + and is several times slower). Text boxes, read or supplied, attach to the nearest port, + supply or device symbol, or else to the nearest net. A net takes the name of the port + on it when it has no text of its own. The recogniser is injectable for tests. +""" + +from __future__ import annotations + +from collections.abc import Callable + +import cv2 +import numpy as np + +from pipeline.trace_types import Box, TextBox, TracedComponent, TracedNet + +TextRecognizer = Callable[[np.ndarray], tuple[str, float] | None] + +MIN_TEXT_CONFIDENCE = 0.5 +PORT_CLASSES = frozenset({"INPUT_PORT", "OUTPUT_PORT"}) +SUPPLY_CLASSES = frozenset({"VDD", "GND"}) +LABELLED_CLASSES = PORT_CLASSES | SUPPLY_CLASSES +# Label search window beside a symbol, in multiples of the symbol's short side. +LABEL_REACH = 4.0 +LABEL_HALF_HEIGHT = 0.9 +# Glyphs of one label are at most this many short sides apart. +GLYPH_GAP = 0.6 + +_engine: object | None = None +_engine_error: str | None = None + + +def _rapidocr() -> object | None: + """ + Lazily construct the shared RapidOCR engine. + + Returns: + The RapidOCR instance, or None when it cannot be initialised (labels are then skipped). + """ + global _engine, _engine_error + if _engine is None and _engine_error is None: + try: + from rapidocr_onnxruntime import RapidOCR + + _engine = RapidOCR() + except (ImportError, OSError, RuntimeError, ValueError) as exc: + _engine_error = str(exc) + return _engine + + +def rapidocr_recognizer(crop: np.ndarray) -> tuple[str, float] | None: + """ + Recognise the text of one tight text crop with RapidOCR's recogniser (no detection stage). + + Args: + crop: BGR uint8 crop holding one label. + Returns: + (text, confidence) when legible with confidence >= MIN_TEXT_CONFIDENCE, else None (also when OCR is unavailable). + """ + engine = _rapidocr() + if engine is None or crop.size == 0: + return None + try: + result, _elapsed = engine(crop, use_det=False, use_cls=False, use_rec=True) + except (RuntimeError, ValueError, cv2.error): + return None + if not result: + return None + text, conf = str(result[0][0]).strip(), float(result[0][1]) + return (text, conf) if text and conf >= MIN_TEXT_CONFIDENCE else None + + +def _label_window(comp: TracedComponent, width: int, height: int) -> tuple[int, int, int, int] | None: + """ + Window beside a port or supply symbol where its name is written: on the side away from its wire. + + Args: + comp: Component with at least one resolved pin point. + width: Image width. + height: Image height. + Returns: + (xa, ya, xb, yb) pixel window, or None when the symbol has no pin to orient by. + """ + points = [p.point for p in comp.pins.values() if p.point is not None] + if not points: + return None + x1, y1, x2, y2 = comp.box + cx, cy = (x1 + x2) / 2, (y1 + y2) / 2 + px, py = points[0] + short = max(4.0, min(x2 - x1, y2 - y1)) + reach, half = LABEL_REACH * short, LABEL_HALF_HEIGHT * short + if abs(px - cx) >= abs(py - cy): + xa, xb = (x2, x2 + reach) if px < cx else (x1 - reach, x1) + ya, yb = cy - half, cy + half + else: + ya, yb = (y2, y2 + reach) if py < cy else (y1 - reach, y1) + xa, xb = cx - reach / 2, cx + reach / 2 + xa, ya = max(0, int(xa)), max(0, int(ya)) + xb, yb = min(width, int(np.ceil(xb))), min(height, int(np.ceil(yb))) + return (xa, ya, xb, yb) if xb - xa > 2 and yb - ya > 2 else None + + +def _text_box(ink: np.ndarray, window: tuple[int, int, int, int], anchor: Box, short: float) -> Box | None: + """ + Tight box of the label glyphs in a window: ink blobs not touching the window border (wires do), grown + from the blob nearest the symbol through neighbours closer than GLYPH_GAP short sides. + + Args: + ink: Bool ink mask of the whole image. + window: Search window (xa, ya, xb, yb). + anchor: The symbol's box (glyph growth starts next to it). + short: The symbol's short side in pixels. + Returns: + Text box in image pixels, or None when the window holds no isolated glyphs. + """ + xa, ya, xb, yb = window + crop = ink[ya:yb, xa:xb].astype(np.uint8) + n, _, stats, _ = cv2.connectedComponentsWithStats(crop, connectivity=8) + h, w = crop.shape + blobs = [] + for i in range(1, n): + x, y, bw, bh, area = (int(v) for v in stats[i]) + if x == 0 or y == 0 or x + bw >= w or y + bh >= h or area < 3: + continue + blobs.append((x + xa, y + ya, x + xa + bw, y + ya + bh)) + if not blobs: + return None + remaining = sorted(blobs, key=lambda b: box_distance(b, anchor)) + group = [remaining.pop(0)] + grown = True + while grown: + grown = False + for b in list(remaining): + if min(box_distance(b, g) for g in group) <= GLYPH_GAP * short: + group.append(b) + remaining.remove(b) + grown = True + return (min(b[0] for b in group), min(b[1] for b in group), max(b[2] for b in group), max(b[3] for b in group)) + + +def read_labels(image: np.ndarray, ink: np.ndarray, components: list[TracedComponent], recognizer: TextRecognizer) -> list[TextBox]: + """ + Read the names written beside port and supply symbols. + + Args: + image: BGR uint8 image. + ink: Bool ink mask of the image. + components: Traced components (pins resolved). + recognizer: Recogniser for one tight text crop. + Returns: + Text boxes in image pixels. + """ + height, width = ink.shape + texts: list[TextBox] = [] + for comp in components: + if comp.class_name not in LABELLED_CLASSES: + continue + window = _label_window(comp, width, height) + if window is None: + continue + short = max(4.0, min(comp.box[2] - comp.box[0], comp.box[3] - comp.box[1])) + box = _text_box(ink, window, comp.box, short) + if box is None: + continue + pad = max(2, int(0.15 * (box[3] - box[1]))) + xa, ya = max(0, int(box[0]) - pad), max(0, int(box[1]) - pad) + xb, yb = min(width, int(box[2]) + pad), min(height, int(box[3]) + pad) + read = recognizer(image[ya:yb, xa:xb]) + if read is not None: + texts.append(TextBox(text=read[0], box=box, confidence=read[1])) + return texts + + +def box_distance(a: Box, b: Box) -> float: + """ + Gap between two axis-aligned boxes (0 when they overlap). + + Args: + a: First box. + b: Second box. + Returns: + Euclidean gap in pixels. + """ + dx = max(0.0, max(a[0], b[0]) - min(a[2], b[2])) + dy = max(0.0, max(a[1], b[1]) - min(a[3], b[3])) + return float(np.hypot(dx, dy)) + + +def _net_distance(box: Box, pixels: np.ndarray) -> float: + """ + Distance from a text box to the nearest wire pixel of a net. + + Args: + box: Text box. + pixels: (n, 2) wire pixels (x, y) of the net. + Returns: + Distance in pixels (inf for an empty net). + """ + if pixels.size == 0: + return float("inf") + dx = np.maximum(0.0, np.maximum(box[0] - pixels[:, 0], pixels[:, 0] - box[2])) + dy = np.maximum(0.0, np.maximum(box[1] - pixels[:, 1], pixels[:, 1] - box[3])) + return float(np.sqrt(dx * dx + dy * dy).min()) + + +def attach_labels(texts: list[TextBox], components: list[TracedComponent], nets: list[TracedNet], net_pixels: dict[str, np.ndarray], reach: float) -> None: + """ + Attach text to components and nets in place. + + Args: + texts: OCR text boxes. + components: Traced components (labels are set on ports, supplies and devices). + nets: Traced nets (labels are set on nets). + net_pixels: Net id -> wire pixels (x, y), for text that labels a wire directly. + reach: Largest text-to-symbol (or text-to-wire) gap that still counts as labelling it. + """ + best_for_component: dict[str, tuple[float, str]] = {} + best_for_net: dict[str, tuple[float, str]] = {} + for t in texts: + scored = [(box_distance(t.box, c.box) * (0.7 if c.class_name in PORT_CLASSES else 1.0), c) for c in components if c.class_name != "JUNCTION"] + scored = [(d, c) for d, c in scored if d <= reach] + if scored: + d, comp = min(scored, key=lambda dc: dc[0]) + prev = best_for_component.get(comp.id) + if prev is None or d < prev[0]: + best_for_component[comp.id] = (d, t.text) + continue + dists = [(_net_distance(t.box, net_pixels.get(n.id, np.empty((0, 2)))), n) for n in nets] + dists = [(d, n) for d, n in dists if d <= reach] + if dists: + d, net = min(dists, key=lambda dn: dn[0]) + prev = best_for_net.get(net.id) + if prev is None or d < prev[0]: + best_for_net[net.id] = (d, t.text) + for comp in components: + if comp.id in best_for_component: + comp.label = best_for_component[comp.id][1] + by_id = {c.id: c for c in components} + for net in nets: + if net.id in best_for_net: + net.label = best_for_net[net.id][1] + continue + for pin in net.pins: + comp = by_id[pin.partition(":")[0]] + if comp.class_name in PORT_CLASSES and comp.label: + net.label = comp.label + break + else: + for pin in net.pins: + comp = by_id[pin.partition(":")[0]] + if comp.class_name in SUPPLY_CLASSES: + net.label = comp.label or ("VDD" if comp.class_name == "VDD" else "GND") + break diff --git a/backend/pipeline/net_tracer.py b/backend/pipeline/net_tracer.py new file mode 100644 index 0000000..3011741 --- /dev/null +++ b/backend/pipeline/net_tracer.py @@ -0,0 +1,544 @@ +""" +Module: net_tracer.py +Purpose: Net tracing v2 - the wire extraction stage of the image-to-circuit pipeline. Classical + CV only (no neural networks, per AGENTS.md). Turns a schematic image plus symbol + detections into components with resolved pins and undirected electrical nets: + 1. binarise ink against the paper background (pipeline/ink.py); + 2. erase every symbol body (box plus a size-relative margin), keep junction dots; + 3. skeletonise the remaining wire ink into a pixel graph and resolve it into nets: + junction dots connect, dotless 4-way crossings are crossovers (straight-through + wires only), every other branch point connects (pipeline/skeleton_graph.py); + 4. wire ends stopping at a symbol box are its contacts; contacts become terminals via + the detector's pin keypoints, or the classical geometry rules and orientation + head when there are none (pipeline/pin_assignment.py); + 5. OCR text attaches to ports, supplies, devices and nets (pipeline/label_attach.py). + Every threshold scales with the measured stroke width and the median symbol size, so + the same settings work from 500 px to 2000 px images. +""" + +from __future__ import annotations + +import itertools +import time +from collections.abc import Callable +from dataclasses import dataclass + +import cv2 +import numpy as np + +from pipeline.class_map import CLASS_TERMINALS, CLASS_TO_NODE_TYPE +from pipeline.detector import Detection, canonical_class +from pipeline.ink import ink_mask, stroke_width +from pipeline.label_attach import TextRecognizer, attach_labels, read_labels +from pipeline.pin_assignment import ( + DS_UNRESOLVED, + MOSFET_CLASSES, + Contact, + assign_by_geometry, + assign_by_keypoints, + estimate_orientation, + resolve_drain_source, +) +from pipeline.skeleton_graph import SkeletonGraph, UnionFind, build_skeleton_graph, edge_length, resolve_connectivity +from pipeline.trace_types import Box, Point, TextBox, TracedComponent, TraceDiagnostics, TracedNet, TracedPin, TraceResult + +# Designator prefix per frontend node type, numbered in reading order (top-to-bottom, left-to-right). +DESIGNATOR_PREFIX: dict[str, str] = { + "nmos": "MN", + "pmos": "MP", + "vsource": "VDD", + "ground": "GND", + "input": "IN", + "output": "OUT", + "resistor": "R", + "capacitor": "C", + "inductor": "L", + "bjtNpn": "Q", + "bjtPnp": "Q", + "clockSource": "CLK", +} +GATE_DESIGNATOR = "U" +# Share of samples along a pin-to-pin segment that must be ink for a direct link. +DIRECT_LINK_MIN_INK = 0.8 +# Supply classes and the terminal their symbol draws; all symbols of one class share a global net. +SUPPLY_TERMINAL: dict[str, str] = {"VDD": "pos", "GND": "gnd"} + + +@dataclass(frozen=True) +class TraceConfig: + """Size-relative tracing thresholds (multiples of the stroke width s and the median symbol size).""" + + erase_margin_stroke: float = 1.0 # symbol erase margin = a*s + b*symbol size + erase_margin_symbol: float = 0.06 + contact_stroke: float = 1.5 # a wire end within c*s + 2 px of an erased box is a contact + merge_radius_stroke: float = 0.5 # branch pixels within this many strokes are one cluster + reach_stroke: float = 4.0 # wire directions are measured over this many strokes + spur_stroke: float = 3.0 # dangling runs shorter than this many strokes are spurs + junction_pad_stroke: float = 0.5 # junction boxes grow by this many strokes + pass_through_cos: float = 0.85 # leftover contacts this collinear and opposite are one wire + label_reach_symbol: float = 0.8 # text within this many symbol sizes labels a symbol or net + close_symbol: float = 0.1 # closing kernel for the wire mask, as a fraction of the symbol size + min_blob_strokes: float = 1.0 # ink specks spanning less than k*s px either way are noise + direct_link_strokes: float = 6.0 # unwired facing pins closer than 2*margin + k*s, joined by ink, connect + + +def _inflate(box: Box, margin: float, width: int, height: int) -> tuple[int, int, int, int]: + """ + Integer pixel window of a box grown by a margin and clipped to the image. + + Args: + box: (x1, y1, x2, y2). + margin: Growth on every side in pixels. + width: Image width. + height: Image height. + Returns: + (xa, ya, xb, yb) half-open pixel window. + """ + return ( + max(0, int(np.floor(box[0] - margin))), + max(0, int(np.floor(box[1] - margin))), + min(width, int(np.ceil(box[2] + margin)) + 1), + min(height, int(np.ceil(box[3] + margin)) + 1), + ) + + +def _rect_distances(point: Point, rects: np.ndarray) -> np.ndarray: + """ + Distance from a point to each rectangle (0 inside). + + Args: + point: (x, y). + rects: (n, 4) array of (xa, ya, xb, yb). + Returns: + (n,) distances. + """ + dx = np.maximum(0.0, np.maximum(rects[:, 0] - point[0], point[0] - (rects[:, 2] - 1))) + dy = np.maximum(0.0, np.maximum(rects[:, 1] - point[1], point[1] - (rects[:, 3] - 1))) + return np.hypot(dx, dy) + + +def _ink_fraction(ink: np.ndarray, a: Point, b: Point) -> float: + """ + Fraction of points along a segment that fall on ink (a one-pixel tolerance band). + + Args: + ink: Bool ink mask. + a: Segment start (x, y). + b: Segment end (x, y). + Returns: + Share in [0, 1]. + """ + h, w = ink.shape + n = max(2, int(np.hypot(b[0] - a[0], b[1] - a[1]))) + xs = np.clip(np.round(np.linspace(a[0], b[0], n)).astype(int), 0, w - 1) + ys = np.clip(np.round(np.linspace(a[1], b[1], n)).astype(int), 0, h - 1) + near = np.zeros(n, dtype=bool) + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + near |= ink[np.clip(ys + dy, 0, h - 1), np.clip(xs + dx, 0, w - 1)] + return float(near.mean()) + + +def _remove_small_blobs(mask: np.ndarray, min_extent: float) -> np.ndarray: + """ + Drop connected ink specks whose bounding box is shorter than min_extent on both sides. + + Args: + mask: Bool mask. + min_extent: Smallest kept bounding-box side in pixels (short wire stubs are long in one direction). + Returns: + Cleaned bool mask. + """ + n, labels, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8) + keep = np.zeros(n, dtype=bool) + keep[1:] = np.maximum(stats[1:, cv2.CC_STAT_WIDTH], stats[1:, cv2.CC_STAT_HEIGHT]) >= min_extent + return keep[labels] + + +class NetTracer: + """Classical net tracer: image + symbol detections -> components with pins and nets.""" + + def __init__(self, config: TraceConfig | None = None, ocr: TextRecognizer | None = None) -> None: + """ + Create a tracer. + + Args: + config: Thresholds (defaults to TraceConfig()). + ocr: Recogniser for label crops (None skips OCR; pass label_attach.rapidocr_recognizer for real OCR). + """ + self.config = config or TraceConfig() + self.ocr = ocr + + def trace(self, image: np.ndarray, detections: list[Detection], texts: list[TextBox] | None = None) -> TraceResult: + """ + Trace nets and assign pins for one schematic image. + + Args: + image: BGR uint8 image. + detections: Symbol detections (any class of ml/classes.yaml, legacy aliases accepted). + texts: Pre-read text boxes; when None the configured recogniser (if any) reads the port and supply labels. + Returns: + TraceResult with components (ids are designators like MN1, MP2, VDD1, U3), nets and diagnostics. + """ + start = time.perf_counter() + cfg = self.config + diag = TraceDiagnostics() + height, width = image.shape[:2] + + symbols: list[tuple[str, Detection]] = [] + junction_boxes: list[Box] = [] + for det in detections: + cls = canonical_class(det.class_name) + if cls == "JUNCTION": + junction_boxes.append(det.box) + elif cls in CLASS_TERMINALS: + symbols.append((cls, det)) + else: + diag.warnings.append(f"unknown class {det.class_name!r} ignored") + + ink = ink_mask(image) + s = stroke_width(ink) + sizes = [min(d.width, d.height) for _, d in symbols] + scale = float(np.median(sizes)) if sizes else 0.03 * max(width, height) + margin = cfg.erase_margin_stroke * s + cfg.erase_margin_symbol * scale + diag.stroke_width, diag.symbol_scale, diag.erase_margin = round(s, 3), round(scale, 3), round(margin, 3) + + wire = ink.copy() + rects = np.array([_inflate(d.box, margin, width, height) for _, d in symbols], dtype=np.float64).reshape(-1, 4) + for xa, ya, xb, yb in rects.astype(int): + wire[ya:yb, xa:xb] = False + # Close small gaps and merge the doubled passes of sketchy strokes into one stroke before thinning. + k = max(3, int(round(cfg.close_symbol * scale)) | 1) + wire = cv2.morphologyEx(wire.astype(np.uint8), cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k))).astype(bool) + for xa, ya, xb, yb in rects.astype(int): + wire[ya:yb, xa:xb] = False + wire = _remove_small_blobs(wire, cfg.min_blob_strokes * s) + + pad = cfg.junction_pad_stroke * s + jboxes = [(b[0] - pad, b[1] - pad, b[2] + pad, b[3] + pad) for b in junction_boxes] + reach = cfg.reach_stroke * s + graph = build_skeleton_graph(wire, jboxes, merge_radius=max(1.5, cfg.merge_radius_stroke * s), reach=reach) + diag.skeleton_edges, diag.clusters = graph.n_edges, graph.n_clusters + + contacts = self._contacts(graph, rects, cfg.contact_stroke * s + 2.0) + spurs = self._spurs(graph, contacts, cfg.spur_stroke * s) + uf, diag.crossovers_split, diag.junction_merges = resolve_connectivity(graph, spurs, reach) + + by_symbol: dict[int, list[Contact]] = {} + for c in contacts: + by_symbol.setdefault(c.symbol, []).append(c) + + components = self._components(symbols) + assigned: list[dict[str, Contact]] = [] + for k, (cls, det) in enumerate(symbols): + comp = components[k] + mine = by_symbol.get(k, []) + if det.keypoints: + kps = {t: p for t, p in det.keypoints.items() if t in CLASS_TERMINALS[cls]} + terms = assign_by_keypoints(kps, mine, det.box, margin, s) + for t, p in kps.items(): + if t not in terms: + found = self._nearest_wire(graph, p, rects[k], margin + 3.0 * s + 0.3 * min(det.width, det.height)) + if found is not None: + terms[t] = Contact(k, p, found, (0.0, 0.0)) + comp.pin_source = "keypoints" + else: + terms = assign_by_geometry(cls, CLASS_TERMINALS[cls], mine, det.box, ink) + comp.pin_source = "geometry" + assigned.append(terms) + used = {id(c) for c in terms.values()} + leftovers = [c for c in mine if id(c) not in used] + diag.unassigned_contacts += len(leftovers) + diag.pass_through_repairs += self._repair_pass_through(leftovers, uf, cfg.pass_through_cos) + + net_of_root: dict[int, str] = {} + counter = itertools.count() + + def fresh_net() -> str: + """A new, unused net id.""" + return f"n{next(counter)}" + + def net_for(edge: int) -> str: + """Stable net id for the union-find root of an edge.""" + root = uf.find(edge) + if root not in net_of_root: + net_of_root[root] = fresh_net() + return net_of_root[root] + + for k, (cls, det) in enumerate(symbols): + comp = components[k] + for t, c in assigned[k].items(): + point = det.keypoints.get(t, c.point) if det.keypoints else c.point + comp.pins[t] = TracedPin(terminal=t, point=(round(float(point[0]), 2), round(float(point[1]), 2)), net=net_for(c.edge)) + for k, (cls, det) in enumerate(symbols): + comp = components[k] + for t in CLASS_TERMINALS[cls]: + if t not in comp.pins and det.keypoints and t in det.keypoints: + comp.pins[t] = TracedPin(terminal=t, point=det.keypoints[t], net=None) + diag.direct_links = self._link_facing_pins(components, ink, 2.0 * margin + cfg.direct_link_strokes * s, fresh_net) + self._merge_supplies(symbols, components) + self._resolve_mosfets(symbols, components) + for k, (cls, det) in enumerate(symbols): + comp = components[k] + comp.orientation = estimate_orientation(cls, det.box, {t: p.point for t, p in comp.pins.items() if p.point is not None}) + diag.unconnected_pins += sum(1 for p in comp.pins.values() if p.net is None) + + nets, renamed = self._nets(components) + if texts is None and self.ocr is not None: + texts = read_labels(image, ink, components, self.ocr) + texts = texts or [] + pixels = {renamed[n]: px for n, px in self._net_pixels(graph, uf, net_of_root).items() if n in renamed} if texts else {} + attach_labels(texts, components, nets, pixels, cfg.label_reach_symbol * scale) + diag.seconds = round(time.perf_counter() - start, 4) + return TraceResult(image_size=(width, height), components=components, nets=nets, texts=texts, diagnostics=diag) + + @staticmethod + def _contacts(graph: SkeletonGraph, rects: np.ndarray, reach: float) -> list[Contact]: + """ + Wire ends that stop at an erased symbol box. + + Args: + graph: Skeleton graph. + rects: (n, 4) erased symbol windows. + reach: Largest end-to-box distance of a contact. + Returns: + Contacts (each end belongs to its nearest box only). + """ + if len(rects) == 0: + return [] + out: list[Contact] = [] + for ep in graph.endpoints: + d = _rect_distances(ep.point, rects) + k = int(np.argmin(d)) + if d[k] <= reach: + out.append(Contact(symbol=k, point=ep.point, edge=ep.edge, direction=ep.direction, length=edge_length(graph, ep.edge))) + return out + + @staticmethod + def _spurs(graph: SkeletonGraph, contacts: list[Contact], max_len: float) -> set[int]: + """ + Short dangling edges that are thinning artefacts, not wires. + + Args: + graph: Skeleton graph. + contacts: Contacts (their edges are never spurs). + max_len: Longest spur in pixels. + Returns: + Edge ids to ignore when counting a cluster's wires. + """ + contact_edges = {c.edge for c in contacts} + dangling = {ep.edge for ep in graph.endpoints} + return {e for e in dangling if e not in contact_edges and edge_length(graph, e) < max_len} + + @staticmethod + def _nearest_wire(graph: SkeletonGraph, point: Point, rect: np.ndarray, radius: float) -> int | None: + """ + Edge whose skeleton passes closest to a keypoint, outside the symbol's erased window. + + Args: + graph: Skeleton graph. + point: Keypoint (x, y). + rect: The symbol's erased window (xa, ya, xb, yb). + radius: Search radius in pixels. + Returns: + Edge id, or None when no wire is within the radius. + """ + h, w = graph.edge_labels.shape + r = int(np.ceil(radius)) + xa, ya = max(0, int(point[0]) - r), max(0, int(point[1]) - r) + xb, yb = min(w, int(point[0]) + r + 1), min(h, int(point[1]) + r + 1) + window = graph.edge_labels[ya:yb, xa:xb] + ys, xs = np.nonzero(window) + if ys.size == 0: + return None + xs, ys = xs + xa, ys + ya + d = np.hypot(xs - point[0], ys - point[1]) + inside = (xs >= rect[0]) & (xs < rect[2]) & (ys >= rect[1]) & (ys < rect[3]) + d[inside] = np.inf + i = int(np.argmin(d)) + return int(graph.edge_labels[ys[i], xs[i]]) if d[i] <= radius else None + + @staticmethod + def _repair_pass_through(leftovers: list[Contact], uf: UnionFind, min_cos: float) -> int: + """ + Reconnect a wire that runs past a symbol and was cut by its erased box (two collinear, opposite leftover ends). + + Args: + leftovers: Contacts of one symbol not used by any terminal. + uf: Edge union-find (mutated). + min_cos: Required collinearity (|cos| of the directions and of the gap line). + Returns: + Number of repairs made. + """ + repairs = 0 + used: set[int] = set() + for i in range(len(leftovers)): + for j in range(i + 1, len(leftovers)): + if i in used or j in used: + continue + a, b = leftovers[i], leftovers[j] + facing = a.direction[0] * b.direction[0] + a.direction[1] * b.direction[1] + gap = np.array(b.point) - np.array(a.point) + n = float(np.hypot(*gap)) + if n < 1e-6 or facing > -min_cos: + continue + along = abs(gap[0] * a.direction[0] + gap[1] * a.direction[1]) / n + if along >= min_cos: + uf.union(a.edge, b.edge) + used.update((i, j)) + repairs += 1 + return repairs + + @staticmethod + def _components(symbols: list[tuple[str, Detection]]) -> list[TracedComponent]: + """ + Create components with designator ids in reading order. + + Args: + symbols: (canonical class, detection) per non-junction symbol. + Returns: + Components in the same order as symbols. + """ + order = sorted(range(len(symbols)), key=lambda k: (round(symbols[k][1].box[1] / 8.0), symbols[k][1].box[0])) + counters: dict[str, int] = {} + ids: dict[int, str] = {} + for k in order: + node_type = CLASS_TO_NODE_TYPE[symbols[k][0]] + prefix = DESIGNATOR_PREFIX.get(node_type, GATE_DESIGNATOR) + counters[prefix] = counters.get(prefix, 0) + 1 + ids[k] = f"{prefix}{counters[prefix]}" + return [ + TracedComponent( + id=ids[k], + class_name=cls, + node_type=CLASS_TO_NODE_TYPE[cls], + box=tuple(round(float(v), 2) for v in det.box), + confidence=round(float(det.confidence), 4), + ) + for k, (cls, det) in enumerate(symbols) + ] + + @staticmethod + def _link_facing_pins(components: list[TracedComponent], ink: np.ndarray, max_gap: float, fresh_net: Callable[[], str]) -> int: + """ + Connect two unwired pins of different symbols that face each other across a tiny gap drawn in ink. + + Stacked transistors are often joined by a wire shorter than the two erase margins, so no skeleton is + left between them; the keypoints still sit on either end of that stub. + + Args: + components: Components with pins (pin nets are set in place). + ink: Bool ink mask before symbol erasure. + max_gap: Largest pin-to-pin distance linked. + fresh_net: Allocator for new net ids. + Returns: + Number of links made. + """ + loose = [(c, p) for c in components for p in c.pins.values() if p.net is None and p.point is not None] + links = 0 + taken: set[int] = set() + pairs = sorted( + ((float(np.hypot(a[1].point[0] - b[1].point[0], a[1].point[1] - b[1].point[1])), i, j) for i, a in enumerate(loose) for j, b in enumerate(loose) if i < j and a[0] is not b[0]), + ) + for gap, i, j in pairs: + if gap > max_gap or i in taken or j in taken: + continue + if _ink_fraction(ink, loose[i][1].point, loose[j][1].point) < DIRECT_LINK_MIN_INK: + continue + net = fresh_net() + loose[i][1].net = loose[j][1].net = net + taken.update((i, j)) + links += 1 + return links + + @staticmethod + def _merge_supplies(symbols: list[tuple[str, Detection]], components: list[TracedComponent]) -> None: + """ + Supply symbols are global: every VDD symbol is one net and every GND symbol is one net, wired or not. + + Args: + symbols: (canonical class, detection) per symbol. + components: Components with pins (pin nets are rewritten in place). + """ + for cls, terminal in SUPPLY_TERMINAL.items(): + pins = [comp.pins[terminal] for (c, _), comp in zip(symbols, components) if c == cls and terminal in comp.pins] + nets = sorted({p.net for p in pins if p.net is not None}, key=lambda n: int(n[1:])) + target = nets[0] if nets else f"n_{cls.lower()}" + merged = set(nets) + for comp in components: + for pin in comp.pins.values(): + if pin.net in merged: + pin.net = target + for pin in pins: + pin.net = target + + @staticmethod + def _resolve_mosfets(symbols: list[tuple[str, Detection]], components: list[TracedComponent]) -> None: + """ + Rename geometry-mode MOSFET channel placeholders (ds0/ds1) to drain/source electrically. + + Args: + symbols: (canonical class, detection) per symbol. + components: Components with pins (mutated). + """ + pending = [] + supply: dict[str, set[str]] = {"NMOS": set(), "PMOS": set()} + for (cls, _), comp in zip(symbols, components): + for pin in comp.pins.values(): + if pin.net and cls == "GND": + supply["NMOS"].add(pin.net) + if pin.net and cls == "VDD": + supply["PMOS"].add(pin.net) + if cls in MOSFET_CLASSES and DS_UNRESOLVED[0] in comp.pins: + p0, p1 = comp.pins[DS_UNRESOLVED[0]], comp.pins[DS_UNRESOLVED[1]] + pending.append((comp.id, cls, p0.net, p1.net, p0.point, p1.point)) + inputs = {p.net for (cls, _), comp in zip(symbols, components) if cls == "INPUT_PORT" for p in comp.pins.values() if p.net} + decisions = resolve_drain_source(pending, supply, inputs) + for comp in components: + if comp.id in decisions: + t0, t1 = decisions[comp.id] + p0, p1 = comp.pins.pop(DS_UNRESOLVED[0]), comp.pins.pop(DS_UNRESOLVED[1]) + p0.terminal, p1.terminal = t0, t1 + comp.pins[t0], comp.pins[t1] = p0, p1 + + @staticmethod + def _nets(components: list[TracedComponent]) -> tuple[list[TracedNet], dict[str, str]]: + """ + Collect nets from component pins, renumbered n0.. by their first pin. + + Args: + components: Components with pins (pin nets are renamed in place). + Returns: + (nets with sorted pin lists, old net id -> new net id). + """ + groups: dict[str, list[str]] = {} + for comp in components: + for t, pin in sorted(comp.pins.items()): + if pin.net is not None: + groups.setdefault(pin.net, []).append(f"{comp.id}:{t}") + ordered = sorted(groups.items(), key=lambda kv: sorted(kv[1])[0]) + rename = {old: f"n{i}" for i, (old, _) in enumerate(ordered)} + for comp in components: + for pin in comp.pins.values(): + if pin.net is not None: + pin.net = rename[pin.net] + return [TracedNet(id=rename[old], pins=sorted(pins)) for old, pins in ordered], rename + + @staticmethod + def _net_pixels(graph: SkeletonGraph, uf: UnionFind, net_of_root: dict[int, str]) -> dict[str, np.ndarray]: + """ + Wire pixels per (pre-renumbering) net id, for text-to-net attachment. + + Args: + graph: Skeleton graph. + uf: Edge union-find. + net_of_root: Union-find root -> net id assigned during pin resolution. + Returns: + Net id -> (n, 2) pixels. + """ + acc: dict[str, list[np.ndarray]] = {} + for e, pixels in graph.edge_pixels.items(): + net = net_of_root.get(uf.find(e)) + if net is not None: + acc.setdefault(net, []).append(pixels) + return {n: np.concatenate(p, axis=0) for n, p in acc.items()} diff --git a/backend/pipeline/pin_assignment.py b/backend/pipeline/pin_assignment.py new file mode 100644 index 0000000..f882442 --- /dev/null +++ b/backend/pipeline/pin_assignment.py @@ -0,0 +1,430 @@ +""" +Module: pin_assignment.py +Purpose: Pin assignment for the net tracer. A symbol's "contacts" are the wire ends that stop + at its (erased) box; this module decides which terminal each contact is: + - keypoint mode: the detector (a T7 pose/keypoint head, or ground truth in the bench) + supplies one image point per terminal and contacts are matched to them by an + optimal assignment with a size-relative distance gate; + - geometry mode (classical fallback, no keypoints): terminals follow from the symbol + family's contact layout (MOSFET: drain/source are the farthest-apart pair and the + gate is the remaining contact farther from that line; gates: inputs share a side, + the output is opposite; single-pin symbols take their one wire). MOSFET drain vs + source is settled afterwards electrically (resolve_drain_source). + Also estimates each symbol's orientation (4 rotations x mirror, the generator's + convention) from its resolved pin points: the classical orientation head. +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass +from itertools import combinations + +import numpy as np +from scipy.optimize import linear_sum_assignment + +from pipeline.trace_types import Box, Orientation, Point + +MOSFET_CLASSES = frozenset({"NMOS", "PMOS"}) +GATE_CLASSES = frozenset({"AND", "OR", "NOT", "NAND", "NOR", "XOR", "XNOR"}) +# Single-wire symbols and the terminal their one drawn lead is (VDD draws only its positive pin). +SINGLE_PIN: dict[str, str] = {"VDD": "pos", "GND": "gnd", "INPUT_PORT": "out", "OUTPUT_PORT": "a", "CLOCK": "out"} +# Placeholder terminals for a MOSFET channel pair whose drain/source order is not known yet. +DS_UNRESOLVED = ("ds0", "ds1") + +# Canonical pin offsets from the symbol centre (y down), in the generator's canonical orientation +# (backend/data_gen/synth_v2/symbols.py): MOSFET gate left and channel vertical, gates facing right, +# VDD lead down, GND lead up, input port driving right, output port fed from the left. +CANONICAL_PINS: dict[str, dict[str, Point]] = { + "NMOS": {"d": (1.0, -2.0), "g": (-1.0, 0.0), "s": (1.0, 2.0), "b": (2.0, 0.0)}, + "PMOS": {"s": (1.0, -2.0), "g": (-1.0, 0.0), "d": (1.0, 2.0), "b": (2.0, 0.0)}, + "AND": {"a": (-2.5, -1.0), "b": (-2.5, 1.0), "out": (2.5, 0.0)}, + "NOT": {"a": (-2.0, 0.0), "out": (2.0, 0.0)}, + "VDD": {"pos": (0.0, 1.0)}, + "GND": {"gnd": (0.0, -1.0)}, + "INPUT_PORT": {"out": (1.0, 0.0)}, + "OUTPUT_PORT": {"a": (-1.0, 0.0)}, +} +for _gate in ("OR", "NAND", "NOR", "XOR", "XNOR"): + CANONICAL_PINS[_gate] = CANONICAL_PINS["AND"] + + +@dataclass +class Contact: + """A wire end stopping at a symbol's erased box.""" + + symbol: int + point: Point + edge: int + direction: Point # unit vector from the contact along the wire, away from the symbol + length: int = 0 # skeleton pixels of the wire run the contact belongs to + + +def orient_vector(v: Point, orientation: Orientation) -> Point: + """ + Apply an orientation to a vector: mirror x first, then rotate clockwise on screen (y down). + + Args: + v: Vector (x, y). + orientation: Orientation to apply. + Returns: + Transformed vector. + """ + x, y = (-v[0], v[1]) if orientation.mirror else v + for _ in range((orientation.rotation // 90) % 4): + x, y = -y, x + return (x, y) + + +ALL_ORIENTATIONS: tuple[Orientation, ...] = tuple(Orientation(r, m) for m in (False, True) for r in (0, 90, 180, 270)) + + +def _unit(v: Point) -> Point: + """ + Normalise a vector. + + Args: + v: Vector. + Returns: + Unit vector, or (0, 0) for a zero vector. + """ + n = float(np.hypot(v[0], v[1])) + return (v[0] / n, v[1] / n) if n > 1e-9 else (0.0, 0.0) + + +def estimate_orientation(class_name: str, box: Box, pins: dict[str, Point]) -> Orientation | None: + """ + Classical orientation head: the orientation whose canonical pin directions best match the observed pins. + + Args: + class_name: Canonical class name. + box: Symbol box (x1, y1, x2, y2). + pins: Terminal -> resolved image point (only wired/known terminals). + Returns: + The best Orientation, or None when the class has no template or no usable pins. Single-pin symbols + are mirror-symmetric, so their mirror flag is reported as False. + """ + template = CANONICAL_PINS.get(class_name) + if template is None: + return None + usable = {t: p for t, p in pins.items() if t in template} + if not usable: + return None + cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 + observed = {t: _unit((p[0] - cx, p[1] - cy)) for t, p in usable.items()} + candidates = ALL_ORIENTATIONS if len(usable) > 1 else ALL_ORIENTATIONS[:4] + best: tuple[float, Orientation] | None = None + for o in candidates: + score = 0.0 + for t, v in observed.items(): + c = _unit(orient_vector(template[t], o)) + score += c[0] * v[0] + c[1] * v[1] + if best is None or score > best[0] + 1e-9: + best = (score, o) + return best[1] if best else None + + +def _gate_distance(box: Box, margin: float, stroke: float) -> float: + """ + Largest allowed distance between a keypoint and the contact it is matched to. + + Args: + box: Symbol box. + margin: Erase margin around symbol boxes. + stroke: Stroke width. + Returns: + Distance gate in pixels. + """ + short_side = min(box[2] - box[0], box[3] - box[1]) + return margin + 3.0 * stroke + 0.3 * short_side + + +def assign_by_keypoints(keypoints: dict[str, Point], contacts: list[Contact], box: Box, margin: float, stroke: float) -> dict[str, Contact]: + """ + Match contacts to keypoint terminals with a gated optimal assignment. + + Args: + keypoints: Terminal -> keypoint (image pixels). + contacts: Contacts of this symbol. + box: Symbol box. + margin: Erase margin. + stroke: Stroke width. + Returns: + Terminal -> matched Contact (terminals without a contact within the gate are left out). + """ + terms = list(keypoints) + if not terms or not contacts: + return {} + cost = np.array([[float(np.hypot(keypoints[t][0] - c.point[0], keypoints[t][1] - c.point[1])) for c in contacts] for t in terms]) + gate = _gate_distance(box, margin, stroke) + big = 1e6 + rows, cols = linear_sum_assignment(np.where(cost <= gate, cost, big)) + return {terms[r]: contacts[c] for r, c in zip(rows, cols) if cost[r, c] <= gate} + + +def _side(contact: Contact, box: Box) -> str: + """ + Box side a contact's wire leaves from: the dominant axis of its direction, else the nearest box edge. + + Args: + contact: Contact (a wire entering at a box corner is still classified by where it heads). + box: Box (x1, y1, x2, y2). + Returns: + "left", "right", "top" or "bottom". + """ + dx, dy = contact.direction + if abs(dx) > 1.5 * abs(dy): + return "left" if dx < 0 else "right" + if abs(dy) > 1.5 * abs(dx): + return "top" if dy < 0 else "bottom" + x, y = contact.point + gaps = {"left": abs(x - box[0]), "right": abs(x - box[2]), "top": abs(y - box[1]), "bottom": abs(y - box[3])} + return min(gaps, key=gaps.get) + + +_OPPOSITE = {"left": "right", "right": "left", "top": "bottom", "bottom": "top"} +_SIDE_NORMAL: dict[str, Point] = {"left": (-1.0, 0.0), "right": (1.0, 0.0), "top": (0.0, -1.0), "bottom": (0.0, 1.0)} + + +def _wider_side(ink: np.ndarray, box: Box, side_a: str) -> bool: + """ + Whether the gate body is wider near side_a than near its opposite side. + + A gate body is widest at its input side (flat back, triangle base) and narrows toward the output + (curved front, triangle tip, bubble). The body's cross-axis ink extent is compared over the second and + third quarters of the axis between the two sides (the outer quarters hold mostly the leads). + + Args: + ink: Bool ink mask of the whole image (before symbol erasure). + box: Gate box. + side_a: Side to compare against its opposite. + Returns: + True when the body is at least as wide near side_a. + """ + h, w = ink.shape + x1, y1 = max(0, int(box[0])), max(0, int(box[1])) + x2, y2 = min(w, int(np.ceil(box[2]))), min(h, int(np.ceil(box[3]))) + crop = ink[y1:y2, x1:x2] + if crop.size == 0: + return True + if side_a in ("top", "bottom"): + crop = crop.T + if side_a in ("right", "bottom"): + crop = crop[:, ::-1] + n = crop.shape[1] + + def extent(lo: float, hi: float) -> float: + """Mean cross-axis ink extent over a slice of the axis.""" + spans = [] + for col in crop[:, int(lo * n) : max(int(lo * n) + 1, int(hi * n))].T: + rows = np.flatnonzero(col) + spans.append(float(rows[-1] - rows[0]) if rows.size else 0.0) + return float(np.mean(spans)) if spans else 0.0 + + return extent(0.25, 0.5) >= extent(0.5, 0.75) + + +def _assign_gate(class_name: str, contacts: list[Contact], box: Box, ink: np.ndarray) -> dict[str, Contact]: + """ + Geometry-mode terminals of a logic gate: inputs share a side, the output is on the opposite side. + + Args: + class_name: Gate class. + contacts: Contacts of this gate. + box: Gate box. + ink: Bool ink mask (for the input-side test when the contact layout is ambiguous). + Returns: + Terminal -> Contact. + """ + sides: dict[str, list[Contact]] = {} + for c in contacts: + sides.setdefault(_side(c, box), []).append(c) + n_inputs = 1 if class_name == "NOT" else 2 + crowded = max(sides, key=lambda s: len(sides[s])) + if len(sides[crowded]) >= 2 and _OPPOSITE[crowded] in sides: + in_side = crowded + else: + candidates = [s for s in sides if _OPPOSITE[s] in sides] or list(sides) + s0 = candidates[0] + in_side = s0 if _wider_side(ink, box, s0) else _OPPOSITE[s0] + out_side = _OPPOSITE[in_side] + result: dict[str, Contact] = {} + cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 + if out_side in sides: + result["out"] = min(sides[out_side], key=lambda c: abs(c.point[1] - cy) if out_side in ("left", "right") else abs(c.point[0] - cx)) + inputs = sides.get(in_side, []) + if n_inputs == 1: + if inputs: + result["a"] = min(inputs, key=lambda c: abs(c.point[1] - cy) if in_side in ("left", "right") else abs(c.point[0] - cx)) + return result + # Input "a" sits counter-clockwise of the output direction (above it for a right-facing gate). + dx, dy = _SIDE_NORMAL[out_side] + left_hand = (dy, -dx) + ranked = sorted(inputs, key=lambda c: -((c.point[0] - cx) * left_hand[0] + (c.point[1] - cy) * left_hand[1])) + for term, c in zip(("a", "b"), (ranked[0], ranked[-1]) if len(ranked) >= 2 else ranked[:1]): + result[term] = c + return result + + +def _assign_mosfet(contacts: list[Contact]) -> dict[str, Contact]: + """ + Geometry-mode terminals of a MOSFET: drain/source are the farthest-apart contacts, the gate is + the remaining contact farthest from the drain-source line, the body (if any) the one after it. + + Args: + contacts: Contacts of this transistor. + Returns: + Terminal -> Contact, with the channel pair under the placeholders DS_UNRESOLVED. + """ + if len(contacts) < 2: + return {"g": contacts[0]} if contacts else {} + pts = [np.asarray(c.point) for c in contacts] + i, j = max(combinations(range(len(contacts)), 2), key=lambda ij: float(np.hypot(*(pts[ij[0]] - pts[ij[1]])))) + if len(contacts) == 2: + # Both wires on opposite ends: a channel pair with the gate unwired. + return {DS_UNRESOLVED[0]: contacts[i], DS_UNRESOLVED[1]: contacts[j]} + a, b = pts[i], pts[j] + axis = b - a + norm = float(np.hypot(*axis)) or 1.0 + + def line_distance(k: int) -> float: + """Distance of contact k from the drain-source line.""" + d = pts[k] - a + return abs(float(axis[0] * d[1] - axis[1] * d[0])) / norm + + rest = sorted((k for k in range(len(contacts)) if k not in (i, j)), key=line_distance, reverse=True) + result = {DS_UNRESOLVED[0]: contacts[i], DS_UNRESOLVED[1]: contacts[j], "g": contacts[rest[0]]} + if len(rest) > 1: + result["b"] = contacts[rest[1]] + return result + + +def _assign_generic(terminals: tuple[str, ...], contacts: list[Contact], box: Box) -> dict[str, Contact]: + """ + Fallback for classes without a layout rule: terminals in declared order around the box (clockwise from the left). + + Args: + terminals: Terminal names of the class. + contacts: Contacts of this symbol. + box: Symbol box. + Returns: + Terminal -> Contact. + """ + cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 + ordered = sorted(contacts, key=lambda c: (np.arctan2(c.point[1] - cy, c.point[0] - cx) + np.pi) % (2 * np.pi)) + return dict(zip(terminals, ordered)) + + +def assign_by_geometry(class_name: str, terminals: tuple[str, ...], contacts: list[Contact], box: Box, ink: np.ndarray) -> dict[str, Contact]: + """ + Classical pin assignment when the detector gives no keypoints. + + Args: + class_name: Canonical class name. + terminals: Terminal names of the class. + contacts: Contacts of this symbol. + box: Symbol box. + ink: Bool ink mask (before symbol erasure). + Returns: + Terminal -> Contact (MOSFET channel pairs use the DS_UNRESOLVED placeholders). + """ + if not contacts: + return {} + if class_name in MOSFET_CLASSES: + return _assign_mosfet(contacts) + if class_name in GATE_CLASSES: + return _assign_gate(class_name, contacts, box, ink) + if class_name in SINGLE_PIN: + return {SINGLE_PIN[class_name]: max(contacts, key=lambda c: c.length)} + return _assign_generic(terminals, contacts, box) + + +def _hops(sources: set[str], adjacency: dict[str, set[str]]) -> dict[str, int]: + """ + Breadth-first channel-hop distance from a set of nets. + + Args: + sources: Start nets (distance 0). + adjacency: Net -> nets reachable through one transistor channel. + Returns: + Net -> hop count for every reachable net. + """ + dist: dict[str, int] = {n: 0 for n in sources} + queue = deque(dist) + while queue: + n = queue.popleft() + for m in adjacency.get(n, ()): + if m not in dist: + dist[m] = dist[n] + 1 + queue.append(m) + return dist + + +def _closer(n0: str | None, n1: str | None, dist: dict[str, int]) -> int | None: + """ + Which of two nets is strictly closer under a distance map. + + Args: + n0: First net. + n1: Second net. + dist: Net -> distance. + Returns: + 0 or 1 for the strictly closer net, None on a tie or when neither is reachable. + """ + d0 = dist.get(n0) if n0 else None + d1 = dist.get(n1) if n1 else None + if d0 is not None and (d1 is None or d0 < d1): + return 0 + if d1 is not None and (d0 is None or d1 < d0): + return 1 + return None + + +def resolve_drain_source( + mosfets: list[tuple[str, str, str | None, str | None, Point | None, Point | None]], + supply_nets: dict[str, set[str]], + input_nets: set[str] | None = None, +) -> dict[str, tuple[str, str]]: + """ + Electrical drain/source rule: an NMOS source is the channel end closer (through NMOS channels) to a + ground net, a PMOS source the end closer (through PMOS channels) to a VDD net. A pass transistor that + reaches no supply (transmission gates) takes its source at the end closer to an input port, through any + channel. Remaining ties fall back to the upright-drawing convention (NMOS source below, PMOS above). + + Args: + mosfets: (component id, class, net of ds0, net of ds1, point of ds0, point of ds1) per unresolved MOSFET. + supply_nets: {"NMOS": ground nets, "PMOS": VDD nets}. + input_nets: Nets driven by input ports. + Returns: + Component id -> (terminal for ds0, terminal for ds1), each "d" or "s". + """ + result: dict[str, tuple[str, str]] = {} + every: dict[str, set[str]] = {} + for _, _, n0, n1, _, _ in mosfets: + if n0 and n1 and n0 != n1: + every.setdefault(n0, set()).add(n1) + every.setdefault(n1, set()).add(n0) + from_inputs = _hops(input_nets or set(), every) + for polarity in ("NMOS", "PMOS"): + adjacency: dict[str, set[str]] = {} + for _, cls, n0, n1, _, _ in mosfets: + if cls == polarity and n0 and n1 and n0 != n1: + adjacency.setdefault(n0, set()).add(n1) + adjacency.setdefault(n1, set()).add(n0) + dist = _hops(supply_nets.get(polarity, set()), adjacency) + for cid, cls, n0, n1, p0, p1 in mosfets: + if cls != polarity: + continue + closer = _closer(n0, n1, dist) + if closer is None and not (dist.get(n0 or "") is not None or dist.get(n1 or "") is not None): + closer = _closer(n0, n1, from_inputs) + if closer == 0: + result[cid] = ("s", "d") + elif closer == 1: + result[cid] = ("d", "s") + else: + lower_first = p0 is not None and p1 is not None and p0[1] > p1[1] + # NMOS source drawn below its drain, PMOS source above. + first_is_source = lower_first if polarity == "NMOS" else not lower_first + result[cid] = ("s", "d") if first_is_source else ("d", "s") + return result diff --git a/backend/pipeline/skeleton_graph.py b/backend/pipeline/skeleton_graph.py new file mode 100644 index 0000000..bb65226 --- /dev/null +++ b/backend/pipeline/skeleton_graph.py @@ -0,0 +1,309 @@ +""" +Module: skeleton_graph.py +Purpose: Turns the wire ink (symbol bodies already erased) into a pixel graph and resolves it + into electrical connectivity, classical CV only. The skeleton is split into node + clusters (groups of nearby branch points) and edges (the wire runs between them). + A cluster touching a detected junction dot box is a forced connection; clusters are + never grown to the dot's extent, so a crossover drawn just beside a dot stays one. Connectivity rules at a cluster: + - a cluster under a JUNCTION detection always connects all its wires; + - a 4-way cluster without a junction is a crossover: the wires are paired by + straightness and only the straight-through pairs connect; + - any other cluster (T, L, kink) connects all its wires. + Short dangling spurs (thinning artefacts of dots and blobs) are ignored when counting + a cluster's wires. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from itertools import combinations + +import cv2 +import numpy as np +from skimage.morphology import skeletonize + +from pipeline.trace_types import Box, Point + +_NEIGHBOUR_KERNEL = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]], dtype=np.float32) +_OFFSETS: tuple[tuple[int, int], ...] = tuple((dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1) if dy or dx) +# Both wire pairs of a crossover must be at least this straight (cosine of the pair angle <= -value). +CROSSOVER_MIN_STRAIGHTNESS = 0.6 + + +class UnionFind: + """Union-find over integer ids with path halving.""" + + def __init__(self, n: int) -> None: + """ + Create n singleton sets. + + Args: + n: Number of elements. + """ + self.parent = list(range(n)) + + def find(self, a: int) -> int: + """ + Root of a's set. + + Args: + a: Element. + Returns: + Root element. + """ + while self.parent[a] != a: + self.parent[a] = self.parent[self.parent[a]] + a = self.parent[a] + return a + + def union(self, a: int, b: int) -> None: + """ + Merge the sets of a and b. + + Args: + a: First element. + b: Second element. + """ + ra, rb = self.find(a), self.find(b) + if ra != rb: + self.parent[max(ra, rb)] = min(ra, rb) + + +@dataclass +class Endpoint: + """A free end of the skeleton (degree-1 pixel) and the wire leaving it.""" + + point: Point # (x, y) + edge: int + direction: Point # unit vector from the endpoint along its wire + + +@dataclass +class SkeletonGraph: + """Skeleton split into edges (wire runs) and clusters (branch points and junction dots).""" + + skeleton: np.ndarray + edge_labels: np.ndarray # int32, 0 = not an edge pixel, edge ids start at 1 + n_edges: int + cluster_labels: np.ndarray # int32, 0 = not a cluster pixel, cluster ids start at 1 + n_clusters: int + cluster_forced: set[int] # clusters under a detected junction dot + incidence: dict[int, list[int]] # cluster id -> incident edge ids (with multiplicity for loops) + edge_pixels: dict[int, np.ndarray] # edge id -> (n, 2) array of (x, y) + cluster_centroids: dict[int, Point] + endpoints: list[Endpoint] = field(default_factory=list) + junction_groups: list[set[int]] = field(default_factory=list) # cluster ids under each junction box + + +def skeleton_of(mask: np.ndarray) -> np.ndarray: + """ + One-pixel-wide skeleton of a binary mask. + + Args: + mask: Bool mask. + Returns: + Bool skeleton. + """ + return skeletonize(mask) + + +def _group_pixels(labels: np.ndarray) -> dict[int, np.ndarray]: + """ + Pixel coordinates per label. + + Args: + labels: int32 label image (0 = background). + Returns: + Mapping label -> (n, 2) array of (x, y). + """ + ys, xs = np.nonzero(labels) + if ys.size == 0: + return {} + labs = labels[ys, xs] + order = np.argsort(labs, kind="stable") + labs, xs, ys = labs[order], xs[order], ys[order] + bounds = np.flatnonzero(np.diff(labs)) + 1 + groups: dict[int, np.ndarray] = {} + for chunk_l, chunk_x, chunk_y in zip(np.split(labs, bounds), np.split(xs, bounds), np.split(ys, bounds)): + groups[int(chunk_l[0])] = np.stack([chunk_x, chunk_y], axis=1) + return groups + + +def _neighbour_pairs(src: np.ndarray, dst: np.ndarray) -> set[tuple[int, int]]: + """ + Label pairs (src label, dst label) of 8-adjacent pixels. + + Args: + src: int32 label image. + dst: int32 label image of the same shape. + Returns: + Set of (src label, dst label) with both labels > 0. + """ + h, w = src.shape + padded = np.pad(dst, 1) + ys, xs = np.nonzero(src) + pairs: set[tuple[int, int]] = set() + if ys.size == 0: + return pairs + s = src[ys, xs] + for dy, dx in _OFFSETS: + d = padded[ys + 1 + dy, xs + 1 + dx] + hit = d > 0 + if hit.any(): + pairs.update(zip(s[hit].tolist(), d[hit].tolist())) + return pairs + + +def _direction(pixels: np.ndarray, origin: Point, reach: float) -> Point: + """ + Unit direction from an origin toward the nearby part of a pixel run. + + Args: + pixels: (n, 2) array of (x, y) pixels of one edge. + origin: Reference point (cluster centroid or endpoint). + reach: Only pixels within this distance are averaged (the nearest few when none are). + Returns: + Unit vector (dx, dy); (0, 0) when undefined. + """ + d = np.hypot(pixels[:, 0] - origin[0], pixels[:, 1] - origin[1]) + near = pixels[d <= reach] + if len(near) < 2: + near = pixels[np.argsort(d)[: max(2, min(len(pixels), 6))]] + v = near.mean(axis=0) - np.asarray(origin) + n = float(np.hypot(v[0], v[1])) + return (float(v[0] / n), float(v[1] / n)) if n > 1e-6 else (0.0, 0.0) + + +def build_skeleton_graph(mask: np.ndarray, junction_boxes: list[Box], merge_radius: float, reach: float) -> SkeletonGraph: + """ + Skeletonise wire ink and split it into edges and node clusters. + + Args: + mask: Bool wire-ink mask (symbol bodies erased). + junction_boxes: Detected junction dot boxes (x1, y1, x2, y2); branch clusters touching one are forced + connections, and several clusters under one box are joined. + merge_radius: Branch pixels closer than this form one cluster (absorbs the short bridges of thick crossings). + reach: Distance over which wire directions are measured. + Returns: + The SkeletonGraph. + """ + skel = skeleton_of(mask) + sk8 = skel.astype(np.uint8) + nb = cv2.filter2D(sk8, cv2.CV_16S, _NEIGHBOUR_KERNEL, borderType=cv2.BORDER_CONSTANT) + branch = skel & (nb >= 3) + ends = skel & (nb == 1) + h, w = skel.shape + cluster_mask = np.zeros_like(skel) + if branch.any(): + r = max(1, int(round(merge_radius))) + region = cv2.dilate(branch.astype(np.uint8), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * r + 1, 2 * r + 1))) + cluster_mask |= skel & region.astype(bool) + n_c, cluster_labels = cv2.connectedComponents(cluster_mask.astype(np.uint8), connectivity=8) + edge_mask = skel & ~cluster_mask + n_e, edge_labels = cv2.connectedComponents(edge_mask.astype(np.uint8), connectivity=8) + cluster_labels = cluster_labels.astype(np.int32) + edge_labels = edge_labels.astype(np.int32) + edge_pixels = _group_pixels(edge_labels) + cluster_pixels = _group_pixels(cluster_labels) + centroids = {c: (float(p[:, 0].mean()), float(p[:, 1].mean())) for c, p in cluster_pixels.items()} + # A cluster is under a dot when its centre is inside the dot box; touching the box is not enough, since + # crossovers are often drawn within a dot diameter of a junction. + groups: list[set[int]] = [] + for x1, y1, x2, y2 in junction_boxes: + groups.append({c for c, (cx, cy) in centroids.items() if x1 <= cx <= x2 and y1 <= cy <= y2}) + forced = set().union(*groups) if groups else set() + incidence: dict[int, list[int]] = {c: [] for c in cluster_pixels} + for e, c in sorted(_neighbour_pairs(edge_labels, cluster_labels)): + incidence[c].append(e) + + endpoints: list[Endpoint] = [] + eys, exs = np.nonzero(ends & edge_mask) + for y, x in zip(eys.tolist(), exs.tolist()): + e = int(edge_labels[y, x]) + endpoints.append(Endpoint(point=(float(x), float(y)), edge=e, direction=_direction(edge_pixels[e], (float(x), float(y)), reach))) + return SkeletonGraph( + skeleton=skel, + edge_labels=edge_labels, + n_edges=int(n_e - 1), + cluster_labels=cluster_labels, + n_clusters=int(n_c - 1), + cluster_forced=forced, + incidence=incidence, + edge_pixels=edge_pixels, + cluster_centroids=centroids, + endpoints=endpoints, + junction_groups=[g for g in groups if len(g) > 1], + ) + + +def crossover_pairing(directions: list[Point]) -> tuple[tuple[int, int], tuple[int, int]] | None: + """ + Pair four wire directions into two straight-through runs. + + Args: + directions: Four unit vectors pointing from the crossing outward along each wire. + Returns: + The two index pairs of the straightest pairing, or None when either pair bends more than + CROSSOVER_MIN_STRAIGHTNESS allows (then the cluster is not a clean crossover). + """ + best: tuple[float, tuple[tuple[int, int], tuple[int, int]]] | None = None + for first in ((0, 1), (0, 2), (0, 3)): + second = tuple(i for i in range(4) if i not in first) + cos_a = directions[first[0]][0] * directions[first[1]][0] + directions[first[0]][1] * directions[first[1]][1] + cos_b = directions[second[0]][0] * directions[second[1]][0] + directions[second[0]][1] * directions[second[1]][1] + worst = max(cos_a, cos_b) + if best is None or worst < best[0]: + best = (worst, (first, (second[0], second[1]))) + if best is None or best[0] > -CROSSOVER_MIN_STRAIGHTNESS: + return None + return best[1] + + +def resolve_connectivity(graph: SkeletonGraph, spurs: set[int], reach: float) -> tuple[UnionFind, int, int]: + """ + Union skeleton edges into nets with the junction / crossover rules. + + Args: + graph: Skeleton graph. + spurs: Edge ids to ignore when counting a cluster's wires (short dangling artefacts). + reach: Distance over which wire directions at a cluster are measured. + Returns: + (union-find over edge ids 0..n_edges, number of crossovers split, number of forced junction merges). + """ + uf = UnionFind(graph.n_edges + 1) + crossovers = 0 + junction_merges = 0 + for c, edges in graph.incidence.items(): + wires = [e for e in edges if e not in spurs] + if c not in graph.cluster_forced and len(wires) == 4 and len(set(wires)) == 4: + centre = graph.cluster_centroids[c] + dirs = [_direction(graph.edge_pixels[e], centre, reach) for e in wires] + pairing = crossover_pairing(dirs) + if pairing is not None: + for i, j in pairing: + uf.union(wires[i], wires[j]) + crossovers += 1 + continue + if c in graph.cluster_forced and len(set(wires)) > 1: + junction_merges += 1 + for a, b in combinations(sorted(set(edges)), 2): + uf.union(a, b) + for group in graph.junction_groups: + edges = sorted({e for c in group for e in graph.incidence.get(c, [])}) + for e in edges[1:]: + uf.union(edges[0], e) + return uf, crossovers, junction_merges + + +def edge_length(graph: SkeletonGraph, edge: int) -> int: + """ + Pixel count of an edge. + + Args: + graph: Skeleton graph. + edge: Edge id. + Returns: + Number of skeleton pixels in the edge. + """ + pixels = graph.edge_pixels.get(edge) + return 0 if pixels is None else int(len(pixels)) diff --git a/backend/pipeline/trace_types.py b/backend/pipeline/trace_types.py new file mode 100644 index 0000000..d1898b8 --- /dev/null +++ b/backend/pipeline/trace_types.py @@ -0,0 +1,94 @@ +""" +Module: trace_types.py +Purpose: Data types shared by the net tracing stage (net_tracer.py and its helpers), the + net-based graph builder and the exporter: traced components with resolved pins, + electrical nets, OCR text boxes and the trace result with its diagnostics. + Kept in one module so every stage speaks the same vocabulary. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +Point = tuple[float, float] +Box = tuple[float, float, float, float] + + +@dataclass(frozen=True) +class Orientation: + """Symbol orientation: mirror (x -> -x) applied first, then `rotation` degrees clockwise on screen.""" + + rotation: int + mirror: bool + + +@dataclass +class TracedPin: + """One terminal of a traced component, resolved to an image point and (when wired) a net.""" + + terminal: str + point: Point | None + net: str | None = None + + +@dataclass +class TracedComponent: + """A detected symbol after pin assignment.""" + + id: str + class_name: str + node_type: str + box: Box + confidence: float + pins: dict[str, TracedPin] = field(default_factory=dict) + orientation: Orientation | None = None + label: str | None = None + pin_source: str = "keypoints" # "keypoints" (detector/pose head) or "geometry" (classical fallback) + + +@dataclass +class TracedNet: + """An electrical net: the set of component pins it connects (":").""" + + id: str + pins: list[str] = field(default_factory=list) + label: str | None = None + + +@dataclass(frozen=True) +class TextBox: + """One OCR text fragment in image pixels.""" + + text: str + box: Box + confidence: float = 1.0 + + +@dataclass +class TraceDiagnostics: + """Measurements and counters describing how a trace went (for logs, the API and the bench).""" + + stroke_width: float = 0.0 + symbol_scale: float = 0.0 + erase_margin: float = 0.0 + skeleton_edges: int = 0 + clusters: int = 0 + crossovers_split: int = 0 + junction_merges: int = 0 + unassigned_contacts: int = 0 + unconnected_pins: int = 0 + pass_through_repairs: int = 0 + direct_links: int = 0 + seconds: float = 0.0 + warnings: list[str] = field(default_factory=list) + + +@dataclass +class TraceResult: + """Output of the net tracing stage: components with pins, nets and diagnostics.""" + + image_size: tuple[int, int] # (width, height) + components: list[TracedComponent] + nets: list[TracedNet] + texts: list[TextBox] = field(default_factory=list) + diagnostics: TraceDiagnostics = field(default_factory=TraceDiagnostics) diff --git a/backend/pipeline/wire_extractor.py b/backend/pipeline/wire_extractor.py deleted file mode 100644 index 515e4c4..0000000 --- a/backend/pipeline/wire_extractor.py +++ /dev/null @@ -1,152 +0,0 @@ -""" -Module: wire_extractor.py -Purpose: Classical OpenCV wire extraction stage — traces wire segments between gates - using pixel-level line detection. No neural networks used here. - -Approach: - 1. Adaptive threshold isolates dark pen ink from the paper background. - 2. Detected gate boxes are erased so only wires (and stray text) remain. - Junction dots are intentionally NOT erased — they keep branching nets - connected as single ink components. - 3. Small compact components (handwritten text) are removed; elongated or - large components are kept as wire ink. - 4. Probabilistic Hough transform converts wire ink into line segments. -""" - -from dataclasses import dataclass -from pathlib import Path - -import cv2 -import numpy as np - - -@dataclass -class WireSegment: - """A single wire segment expressed as pixel start/end coordinates.""" - - x1: int - y1: int - x2: int - y2: int - - @property - def endpoints(self) -> tuple[tuple[int, int], tuple[int, int]]: - """ - Segment endpoints. - - Returns: - ((x1, y1), (x2, y2)) tuple pair. - """ - return ((self.x1, self.y1), (self.x2, self.y2)) - - -class WireExtractor: - """Extracts wire connections from a circuit image via classical CV (OpenCV only).""" - - def __init__( - self, - min_line_length: int = 22, - max_line_gap: int = 14, - min_component_diag: float = 45.0, - ) -> None: - """ - Initialise the extractor. - - Args: - min_line_length: Minimum Hough segment length in pixels. - max_line_gap: Maximum gap bridged inside one Hough segment. - min_component_diag: Ink components with a smaller bounding-box - diagonal are treated as text/noise and discarded. - """ - self.min_line_length = min_line_length - self.max_line_gap = max_line_gap - self.min_component_diag = min_component_diag - - def _ink_mask(self, image: np.ndarray) -> np.ndarray: - """ - Binarise the image so pen ink is white on black. - - Args: - image: BGR input image. - Returns: - uint8 binary mask of ink pixels. - """ - gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) - gray = cv2.GaussianBlur(gray, (3, 3), 0) - return cv2.adaptiveThreshold( - gray, - 255, - cv2.ADAPTIVE_THRESH_MEAN_C, - cv2.THRESH_BINARY_INV, - 35, - 12, - ) - - def _remove_text_noise(self, mask: np.ndarray) -> np.ndarray: - """ - Drop compact ink blobs (handwritten labels, specks) from the mask. - - Args: - mask: Binary ink mask (modified copy is returned). - Returns: - Cleaned binary mask containing only wire-like components. - """ - n, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8) - cleaned = np.zeros_like(mask) - for i in range(1, n): - x, y, w, h, area = stats[i] - diag = float(np.hypot(w, h)) - elongation = max(w, h) / max(1, min(w, h)) - # Wires are long/thin or span large extents; text blobs are compact. - if diag >= self.min_component_diag and (elongation >= 2.2 or diag > 140): - cleaned[labels == i] = 255 - return cleaned - - def extract( - self, - image_path: Path, - exclude_boxes: list[tuple[float, float, float, float]] | None = None, - ) -> list[WireSegment]: - """ - Detect wire segments in a circuit image. - - Args: - image_path: Path to the input circuit image. - exclude_boxes: Gate bounding boxes (x1, y1, x2, y2) to erase before - tracing so gate bodies are not mistaken for wires. Junction - boxes must not be included here. - Returns: - List of WireSegment objects representing detected wire paths. - Raises: - FileNotFoundError: If image_path does not exist. - ValueError: If the image cannot be decoded. - """ - if not image_path.exists(): - raise FileNotFoundError(f"Image not found: {image_path}") - image = cv2.imread(str(image_path)) - if image is None: - raise ValueError(f"Could not decode image: {image_path}") - - mask = self._ink_mask(image) - - h, w = mask.shape - for x1, y1, x2, y2 in exclude_boxes or []: - xa, ya = max(0, int(x1)), max(0, int(y1)) - xb, yb = min(w, int(x2)), min(h, int(y2)) - mask[ya:yb, xa:xb] = 0 - - mask = self._remove_text_noise(mask) - # Bridge small breaks left by erasing boxes over wire endpoints. - mask = cv2.dilate(mask, np.ones((3, 3), np.uint8), iterations=1) - - lines = cv2.HoughLinesP( - mask, - rho=1, - theta=np.pi / 180, - threshold=28, - minLineLength=self.min_line_length, - maxLineGap=self.max_line_gap, - ) - if lines is None: - return [] - return [WireSegment(int(x1), int(y1), int(x2), int(y2)) for x1, y1, x2, y2 in lines[:, 0]] diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 202df94..a9a57c7 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -22,6 +22,7 @@ dependencies = [ "pytest>=9.1.1", "google-generativeai>=0.8.6", "pyyaml>=6.0", + "scikit-image>=0.24", ] [dependency-groups] diff --git a/backend/test_class_schema.py b/backend/test_class_schema.py index e3ad67e..fc94f63 100644 --- a/backend/test_class_schema.py +++ b/backend/test_class_schema.py @@ -15,7 +15,7 @@ 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 +from pipeline.class_map import CLASS_ALIASES, CLASS_NAMES, CLASS_TERMINALS, CLASS_TO_NODE_TYPE # noqa: E402 def _load_class_schema_module(): @@ -60,6 +60,12 @@ def test_class_names_follow_yolo_ids(): assert CLASS_ALIASES == doc["aliases"] +def test_class_terminals_equal_yaml(): + """CLASS_TERMINALS (the net tracer's pin vocabulary) lists every canonical class's YAML terminals in order.""" + doc = _yaml_doc() + assert CLASS_TERMINALS == {c["name"]: tuple(c["terminals"]) for c in doc["classes"]} + + 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() diff --git a/backend/test_net_tracer.py b/backend/test_net_tracer.py new file mode 100644 index 0000000..4258a64 --- /dev/null +++ b/backend/test_net_tracer.py @@ -0,0 +1,505 @@ +""" +Module: test_net_tracer.py +Purpose: Tests for net tracing v2 (pipeline/net_tracer.py and helpers) and the schema-2 exporter on + small hand-built schematics drawn with the T2 generator's symbol geometry: crossovers with + and without a junction dot, a branching supply rail, every transistor rotation and mirror, + 3- vs 4-terminal MOSFET symbols, global supply nets, stacked transistors, label reading, + ruled paper, and the exported nets/edges/legacy connections. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +import cv2 +import numpy as np +import pytest + +from data_gen.synth_v2.symbols import orient_points, symbol_geometry +from pipeline.circuit_exporter import CircuitExporter +from pipeline.detector import Detection +from pipeline.graph_builder import GraphBuilder +from pipeline.ink import ink_mask, stroke_width +from pipeline.net_tracer import NetTracer +from pipeline.pin_assignment import ALL_ORIENTATIONS, orient_vector +from pipeline.trace_types import Orientation, TraceResult + +PITCH = 20.0 +THICK = 2 + + +@dataclass +class Placed: + """A symbol placed in a test scene (grid anchor, orientation) with its drawn pixel extent and pins.""" + + name: str + cls: str + variant: str + box: tuple[float, float, float, float] + pins: dict[str, tuple[float, float]] + + +@dataclass +class Scene: + """A test schematic: a white canvas, symbols, wires and junction dots, drawn like the T2 renderer.""" + + width: int = 640 + height: int = 480 + symbols: list[Placed] = field(default_factory=list) + dots: list[tuple[float, float]] = field(default_factory=list) + + def __post_init__(self) -> None: + """Create the canvas.""" + self.mask = np.zeros((self.height, self.width), dtype=np.uint8) + + @staticmethod + def px(pts: np.ndarray) -> np.ndarray: + """ + Grid units to pixels. + + Args: + pts: (n, 2) grid points. + Returns: + (n, 2) pixel points. + """ + return (np.asarray(pts, dtype=np.float64) + 0.5) * PITCH + + def _poly(self, pts: np.ndarray) -> None: + """ + Draw an anti-aliased polyline in pixels. + + Args: + pts: (n, 2) pixel points. + """ + cv2.polylines(self.mask, [np.round(pts * 16).astype(np.int32)], False, 255, THICK, cv2.LINE_AA, shift=4) + + def symbol(self, name: str, cls: str, variant: str, anchor: tuple[int, int], rotation: int = 0, mirror: bool = False) -> Placed: + """ + Draw a symbol and record its box and pin points. + + Args: + name: Test id. + cls: Class name. + variant: Symbol variant. + anchor: Grid anchor. + rotation: Clockwise rotation in degrees. + mirror: Mirror x before rotating. + Returns: + The placed symbol. + """ + geom = symbol_geometry(cls, variant) + shift = np.array(anchor, dtype=np.float64) + drawn = [] + for stroke in geom.strokes: + pts = self.px(orient_points(stroke, rotation, mirror) + shift) + self._poly(pts) + drawn.append(pts) + for fill in geom.fills: + pts = self.px(orient_points(fill, rotation, mirror) + shift) + cv2.fillPoly(self.mask, [np.round(pts * 16).astype(np.int32)], 255, cv2.LINE_AA, shift=4) + drawn.append(pts) + allpts = np.concatenate(drawn) + pad = THICK / 2 + 1 + box = (float(allpts[:, 0].min() - pad), float(allpts[:, 1].min() - pad), float(allpts[:, 0].max() + pad), float(allpts[:, 1].max() + pad)) + pins = {t: tuple(float(v) for v in self.px(orient_points(np.array([p], dtype=np.float64), rotation, mirror) + shift)[0]) for t, p in geom.pins.items()} + placed = Placed(name, cls, variant, box, pins) + self.symbols.append(placed) + return placed + + def wire(self, *grid_pts: tuple[float, float]) -> None: + """ + Draw a wire through grid points. + + Args: + grid_pts: Polyline vertices in grid units. + """ + self._poly(self.px(np.array(grid_pts, dtype=np.float64))) + + def dot(self, grid_pt: tuple[float, float], diameter: float = 9.0) -> None: + """ + Draw a filled junction dot. + + Args: + grid_pt: Centre in grid units. + diameter: Dot diameter in pixels. + """ + c = self.px(np.array([grid_pt]))[0] + cv2.circle(self.mask, (int(round(c[0] * 16)), int(round(c[1] * 16))), int(round(diameter / 2 * 16)), 255, -1, cv2.LINE_AA, shift=4) + self.dots.append((float(c[0]), float(c[1]))) + + def image(self) -> np.ndarray: + """ + Render black ink on white paper. + + Returns: + BGR uint8 image. + """ + gray = 255 - (self.mask.astype(np.float32) * (235.0 / 255.0)) + return cv2.cvtColor(gray.astype(np.uint8), cv2.COLOR_GRAY2BGR) + + def detections(self, keypoints: bool = True, dots: bool = True) -> list[Detection]: + """ + Ground-truth detections of the scene. + + Args: + keypoints: Attach pin keypoints. + dots: Include junction detections. + Returns: + Detections in symbol order, then junctions. + """ + dets = [] + for s in self.symbols: + x1, y1, x2, y2 = s.box + dets.append(Detection(s.cls, 0.9, (x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1, keypoints=dict(s.pins) if keypoints else None)) + if dots: + for x, y in self.dots: + dets.append(Detection("JUNCTION", 0.9, x, y, 11.0, 11.0)) + return dets + + +def trace(scene: Scene, keypoints: bool = True, dots: bool = True) -> tuple[TraceResult, dict[str, str]]: + """ + Trace a scene and map traced component ids back to scene names. + + Args: + scene: Test scene. + keypoints: Give the tracer pin keypoints. + dots: Give the tracer junction detections. + Returns: + (trace result, traced id -> scene name). + """ + result = NetTracer().trace(scene.image(), scene.detections(keypoints, dots), texts=[]) + return result, {c.id: s.name for c, s in zip(result.components, scene.symbols)} + + +def nets_by_name(result: TraceResult, names: dict[str, str]) -> set[frozenset[str]]: + """ + Traced nets with at least two pins, in scene names. + + Args: + result: Trace result. + names: Traced id -> scene name. + Returns: + Set of frozensets of ":". + """ + out = set() + for net in result.nets: + pins = frozenset(f"{names[p.partition(':')[0]]}:{p.partition(':')[2]}" for p in net.pins) + if len(pins) >= 2: + out.add(pins) + return out + + +def crossing_scene(with_dot: bool) -> Scene: + """ + Two wires crossing at (14, 11): IN1 -> OUT1 horizontally and IN2 -> OUT2 vertically. + + Args: + with_dot: Draw a junction dot at the crossing. + Returns: + The scene. + """ + sc = Scene() + sc.symbol("IN1", "INPUT_PORT", "tag", (4, 11)) + sc.symbol("OUT1", "OUTPUT_PORT", "tag", (24, 11)) + sc.symbol("IN2", "INPUT_PORT", "tag", (6, 4)) + sc.symbol("OUT2", "OUTPUT_PORT", "tag", (24, 18)) + sc.wire((4, 11), (24, 11)) + sc.wire((6, 4), (14, 4), (14, 18), (24, 18)) + if with_dot: + sc.dot((14, 11)) + return sc + + +@pytest.mark.parametrize("keypoints", [True, False]) +def test_crossover_without_dot_keeps_nets_separate(keypoints: bool) -> None: + """A dotless 4-way crossing is a crossover: the two wires stay two nets.""" + result, names = trace(crossing_scene(with_dot=False), keypoints=keypoints) + assert nets_by_name(result, names) == {frozenset({"IN1:out", "OUT1:a"}), frozenset({"IN2:out", "OUT2:a"})} + assert result.diagnostics.crossovers_split == 1 + + +@pytest.mark.parametrize("keypoints", [True, False]) +def test_crossing_with_dot_is_one_net(keypoints: bool) -> None: + """A detected junction dot on a 4-way crossing joins all four wires.""" + result, names = trace(crossing_scene(with_dot=True), keypoints=keypoints) + assert nets_by_name(result, names) == {frozenset({"IN1:out", "OUT1:a", "IN2:out", "OUT2:a"})} + + +def test_crossing_with_undetected_dot_falls_back_to_crossover() -> None: + """Without the JUNCTION detection the dot is ink only, so the 4-way rule decides (crossover).""" + result, names = trace(crossing_scene(with_dot=True), dots=False) + assert len(nets_by_name(result, names)) == 2 + + +def test_crossover_beside_a_dot_stays_a_crossover() -> None: + """A crossover drawn one grid step from a T-junction dot is not swallowed by the dot.""" + sc2 = Scene() + sc2.symbol("IN1", "INPUT_PORT", "tag", (4, 10)) + sc2.symbol("OUT1", "OUTPUT_PORT", "tag", (26, 10)) + sc2.symbol("OUT2", "OUTPUT_PORT", "tag", (26, 16)) + sc2.symbol("IN2", "INPUT_PORT", "tag", (4, 12)) + sc2.symbol("OUT3", "OUTPUT_PORT", "tag", (26, 13)) + sc2.wire((4, 10), (26, 10)) + sc2.wire((15, 10), (15, 16), (26, 16)) + sc2.dot((15, 10)) + sc2.wire((4, 12), (12, 12), (12, 11), (18, 11), (18, 13), (26, 13)) + result, names = trace(sc2) + assert nets_by_name(result, names) == {frozenset({"IN1:out", "OUT1:a", "OUT2:a"}), frozenset({"IN2:out", "OUT3:a"})} + + +def supply_rail_scene() -> Scene: + """ + A VDD rail branching (with dots) to three PMOS sources, crossed by a dotless input wire. + + Returns: + The scene. + """ + sc = Scene(width=800) + sc.symbol("VDD", "VDD", "bar", (6, 4)) + for i, x in enumerate((12, 18, 24)): + sc.symbol(f"P{i}", "PMOS", "bubble3", (x, 9)) + sc.symbol(f"Y{i}", "OUTPUT_PORT", "tag", (x + 3, 15)) + sc.wire((x, 11), (x, 15), (x + 3, 15)) + sc.symbol(f"A{i}", "INPUT_PORT", "tag", (x - 4, 18 + i)) + sc.wire((x - 4, 18 + i), (x - 3, 18 + i), (x - 3, 9), (x - 2, 9)) + sc.wire((6, 4), (6, 5), (33, 5)) + for x in (12, 18, 24): + sc.wire((x, 5), (x, 7)) + sc.dot((x, 5)) + # A signal wire crossing the rail without a dot. + sc.symbol("CLK", "INPUT_PORT", "tag", (29, 1)) + sc.symbol("CLKO", "OUTPUT_PORT", "tag", (33, 22)) + sc.wire((29, 1), (31, 1), (31, 22), (33, 22)) + return sc + + +@pytest.mark.parametrize("keypoints", [True, False]) +def test_branching_supply_rail(keypoints: bool) -> None: + """One VDD net holds the supply pin and every branched source; a wire crossing the rail stays separate.""" + result, names = trace(supply_rail_scene(), keypoints=keypoints) + nets = nets_by_name(result, names) + assert frozenset({"VDD:pos", "P0:s", "P1:s", "P2:s"}) in nets + assert frozenset({"CLK:out", "CLKO:a"}) in nets + for i in range(3): + assert frozenset({f"P{i}:d", f"Y{i}:a"}) in nets + assert frozenset({f"A{i}:out", f"P{i}:g"}) in nets + + +def transistor_scene(rotation: int, mirror: bool, variant: str = "plain3", cls: str = "NMOS") -> Scene: + """ + One MOSFET whose terminals each run straight out to a port or supply, in a given orientation. + + Args: + rotation: Clockwise rotation. + mirror: Mirror flag. + variant: Symbol variant. + cls: NMOS or PMOS. + Returns: + The scene (drain -> OUT, gate <- IN, source -> GND for NMOS / VDD for PMOS, body -> BODY port). + """ + sc = Scene() + anchor = (16, 12) + placed = sc.symbol("M", cls, variant, anchor, rotation, mirror) + o = Orientation(rotation, mirror) + supply = ("GND", "GND", "gnd") if cls == "NMOS" else ("VDD", "VDD", "pos") + ends = {"d": ("OUT", "OUTPUT_PORT", "a"), "g": ("IN", "INPUT_PORT", "out"), "s": supply, "b": ("BODY", "OUTPUT_PORT", "a")} + canonical = {"d": (0, -2), "g": (-2, 0), "s": (0, 2), "b": (1, 0)} if cls == "NMOS" else {"s": (0, -2), "g": (-2, 0), "d": (0, 2), "b": (1, 0)} + for term in placed.pins: + dx, dy = (int(round(v)) for v in orient_vector(canonical[term], o)) + unit = (int(np.sign(dx)), int(np.sign(dy))) + start = (anchor[0] + dx, anchor[1] + dy) + end = (start[0] + 4 * unit[0], start[1] + 4 * unit[1]) + sc.wire(start, end) + name, ecls, _ = ends[term] + # Rotate each end symbol so its pin faces the wire. + if ecls in ("VDD", "GND"): + facing = {(0, 1): 0, (-1, 0): 90, (0, -1): 180, (1, 0): 270} if ecls == "VDD" else {(0, -1): 0, (1, 0): 90, (0, 1): 180, (-1, 0): 270} + sc.symbol(name, ecls, "bar" if ecls == "VDD" else "bars", end, facing[(-unit[0], -unit[1])]) + else: + base = (1, 0) if ecls == "INPUT_PORT" else (-1, 0) + rot = next(r for r in (0, 90, 180, 270) if tuple(int(round(v)) for v in orient_vector(base, Orientation(r, False))) == (-unit[0], -unit[1])) + sc.symbol(name, ecls, "tag", end, rot) + return sc + + +@pytest.mark.parametrize("orientation", ALL_ORIENTATIONS, ids=lambda o: f"r{o.rotation}{'m' if o.mirror else ''}") +@pytest.mark.parametrize("keypoints", [True, False]) +def test_rotated_mirrored_transistor(orientation: Orientation, keypoints: bool) -> None: + """Every rotation and mirror of an NMOS resolves gate, drain and source; keypoint mode also recovers the orientation.""" + sc = transistor_scene(orientation.rotation, orientation.mirror) + result, names = trace(sc, keypoints=keypoints) + assert nets_by_name(result, names) == {frozenset({"M:d", "OUT:a"}), frozenset({"M:g", "IN:out"}), frozenset({"M:s", "GND:gnd"})} + mos = result.components[0] + assert mos.orientation == orientation + + +@pytest.mark.parametrize( + ("cls", "variant", "four"), + [ + ("NMOS", "plain3", False), + ("NMOS", "arrow3", False), + ("NMOS", "dashed3", False), + ("NMOS", "body4", True), + ("PMOS", "bubble3", False), + ("PMOS", "arrow3", False), + ("PMOS", "bubble4", True), + ("PMOS", "body4", True), + ], +) +@pytest.mark.parametrize("keypoints", [True, False]) +def test_three_vs_four_terminal_symbols(cls: str, variant: str, four: bool, keypoints: bool) -> None: + """3-terminal symbols get d/g/s; 4-terminal symbols also get the body pin on its own net.""" + sc = transistor_scene(90, False, variant, cls) + result, names = trace(sc, keypoints=keypoints) + nets = nets_by_name(result, names) + supply = "GND:gnd" if cls == "NMOS" else "VDD:pos" + assert frozenset({"M:s", supply}) in nets + assert frozenset({"M:d", "OUT:a"}) in nets + assert frozenset({"M:g", "IN:out"}) in nets + assert (frozenset({"M:b", "BODY:a"}) in nets) == four + assert ("b" in result.components[0].pins) == four + + +def test_separate_supply_symbols_share_one_net() -> None: + """Two unconnected GND symbols are one global ground net.""" + sc = Scene() + sc.symbol("IN1", "INPUT_PORT", "tag", (6, 6)) + sc.symbol("G1", "GND", "bars", (10, 8)) + sc.wire((6, 6), (10, 6), (10, 8)) + sc.symbol("IN2", "INPUT_PORT", "tag", (16, 14)) + sc.symbol("G2", "GND", "triangle", (20, 16)) + sc.wire((16, 14), (20, 14), (20, 16)) + result, names = trace(sc) + assert nets_by_name(result, names) == {frozenset({"IN1:out", "G1:gnd", "IN2:out", "G2:gnd"})} + + +def test_stacked_transistors_with_tiny_link() -> None: + """Two series NMOS whose shared wire is shorter than the erase margins still connect drain to source.""" + sc = Scene() + sc.symbol("M1", "NMOS", "plain3", (16, 8)) + sc.symbol("M2", "NMOS", "plain3", (16, 12.3)) + sc.wire((16, 10), (16, 10.3)) + sc.symbol("OUT", "OUTPUT_PORT", "tag", (20, 4)) + sc.wire((16, 6), (16, 4), (20, 4)) + sc.symbol("GND", "GND", "bars", (16, 17)) + sc.wire((16, 14.3), (16, 17)) + for name, y in (("A", 8), ("B", 12.3)): + sc.symbol(name, "INPUT_PORT", "tag", (10, y)) + sc.wire((10, y), (14, y)) + result, names = trace(sc) + assert frozenset({"M1:s", "M2:d"}) in nets_by_name(result, names) + + +def test_ink_ignores_ruled_paper_lines() -> None: + """Faint ruled-paper lines are not ink; pen strokes are, and the stroke width is measured.""" + img = np.full((200, 300, 3), (238, 242, 245), dtype=np.uint8) + for y in range(10, 200, 25): + cv2.line(img, (0, y), (299, y), (205, 185, 165), 1) + cv2.line(img, (20, 100), (280, 100), (25, 25, 25), 3) + mask = ink_mask(img) + assert mask[100, 150] and not mask[35, 150] + assert abs(stroke_width(mask) - int(mask[:, 150].sum())) <= 1.0 + + +def test_reads_port_labels_beside_symbols() -> None: + """The label window beside each port is cropped and recognised; nets take their port's name.""" + sc = crossing_scene(with_dot=False) + img = sc.image() + cv2.putText(img, "A", (int(sc.symbols[0].box[0]) - 26, int(sc.symbols[0].box[3]) - 2), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (20, 20, 20), 2) + seen: list[tuple[int, int]] = [] + + def fake_ocr(crop: np.ndarray) -> tuple[str, float]: + """Recogniser stub that records crop sizes.""" + seen.append(crop.shape[:2]) + return ("A", 0.99) + + result = NetTracer(ocr=fake_ocr).trace(img, sc.detections(), texts=None) + in1 = result.components[0] + assert in1.label == "A" + assert len(seen) == 1 and seen[0][0] < 40 + net = next(n for n in result.nets if f"{in1.id}:out" in n.pins) + assert net.label == "A" + + +def test_export_schema_v2_for_cmos_inverter() -> None: + """The exporter emits typed components with pins, undirected nets and ReactFlow edges with t:/s: handles.""" + sc = Scene() + sc.symbol("VDD", "VDD", "bar", (16, 3)) + sc.symbol("MP", "PMOS", "bubble3", (16, 7)) + sc.symbol("MN", "NMOS", "plain3", (16, 13)) + sc.symbol("GND", "GND", "bars", (16, 17)) + sc.symbol("A", "INPUT_PORT", "tag", (8, 10)) + sc.symbol("Y", "OUTPUT_PORT", "tag", (22, 10)) + sc.wire((16, 3), (16, 5)) + sc.wire((16, 9), (16, 11)) + sc.wire((16, 15), (16, 17)) + sc.wire((16, 10), (22, 10)) + sc.dot((16, 10)) + sc.wire((8, 10), (11, 10), (11, 7), (14, 7)) + sc.wire((11, 10), (11, 13), (14, 13)) + sc.dot((11, 10)) + result, names = trace(sc) + payload = CircuitExporter().export(GraphBuilder().build(result)) + assert payload["schema_version"] == 2 + types = {names[c["id"]]: c["type"] for c in payload["components"]} + assert types == {"VDD": "vsource", "MP": "pmos", "MN": "nmos", "GND": "ground", "A": "input", "Y": "output"} + by_name = {names[c["id"]]: c for c in payload["components"]} + assert set(by_name["MN"]["pins"]) == {"d", "g", "s"} + nets = {frozenset(f"{names[p.split(':')[0]]}:{p.split(':')[1]}" for p in n["pins"]) for n in payload["nets"]} + assert nets == { + frozenset({"VDD:pos", "MP:s"}), + frozenset({"MP:d", "MN:d", "Y:a"}), + frozenset({"A:out", "MP:g", "MN:g"}), + frozenset({"MN:s", "GND:gnd"}), + } + ids = {v: k for k, v in names.items()} + gate_edges = [e for e in payload["edges"] if e["source"] == ids["A"]] + assert {(e["target"], e["targetHandle"]) for e in gate_edges} == {(ids["MP"], "t:g"), (ids["MN"], "t:g")} + assert all(e["sourceHandle"] is None for e in gate_edges) + supply_edge = next(e for e in payload["edges"] if ids["VDD"] in (e["source"], e["target"])) + assert {supply_edge["sourceHandle"], supply_edge["targetHandle"]} == {"s:pos", "t:s"} or {supply_edge["sourceHandle"], supply_edge["targetHandle"]} == {"s:s", "t:pos"} + assert payload["connections"] == [] + assert all(c["library_cell"] is None for c in payload["components"]) + + +def test_export_gate_circuit_keeps_legacy_connections() -> None: + """Gate-level circuits still produce the schema-1 directed connections the current importer reads.""" + sc = Scene() + sc.symbol("U", "NAND", "ansi", (14, 10)) + sc.symbol("A", "INPUT_PORT", "tag", (6, 9)) + sc.symbol("B", "INPUT_PORT", "tag", (6, 11)) + sc.symbol("Y", "OUTPUT_PORT", "tag", (22, 10)) + sc.wire((6, 9), (13, 9)) + sc.wire((6, 11), (13, 11)) + sc.wire((18, 10), (22, 10)) + for keypoints in (True, False): + result, names = trace(sc, keypoints=keypoints) + payload = CircuitExporter().export(GraphBuilder().build(result)) + ids = {v: k for k, v in names.items()} + conns = {(names[c["from"]], names[c["to"]], c["fromPort"], c["toPort"]) for c in payload["connections"]} + assert conns == {("A", "U", "output", "a"), ("B", "U", "output", "b"), ("U", "Y", "output", None)} + nand = next(c for c in payload["components"] if c["id"] == ids["U"]) + assert nand["library_cell"] == {"id": "std-nand", "pins": {"a": "a", "b": "b", "out": "out"}} + + +def test_legacy_alias_classes_are_traced() -> None: + """Old gate-era class names (SWITCH, LED) resolve through the aliases.""" + sc = Scene() + sc.symbol("S", "INPUT_PORT", "tag", (6, 8)) + sc.symbol("L", "OUTPUT_PORT", "tag", (16, 8)) + sc.wire((6, 8), (16, 8)) + dets = sc.detections() + dets[0].class_name, dets[1].class_name = "SWITCH", "LED" + result = NetTracer().trace(sc.image(), dets, texts=[]) + assert [c.node_type for c in result.components] == ["input", "output"] + assert len(result.nets) == 1 and len(result.nets[0].pins) == 2 + + +def test_unknown_class_is_reported_not_traced() -> None: + """A class outside ml/classes.yaml is skipped with a warning.""" + sc = crossing_scene(with_dot=False) + dets = sc.detections() + [Detection("TOASTER", 0.9, 50, 50, 10, 10)] + result = NetTracer().trace(sc.image(), dets, texts=[]) + assert any("TOASTER" in w for w in result.diagnostics.warnings) + assert len(result.components) == 4 diff --git a/backend/uv.lock b/backend/uv.lock index 29c5d39..5cb3ed1 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -743,6 +743,7 @@ dependencies = [ { name = "rapidfuzz" }, { name = "rapidocr-onnxruntime" }, { name = "requests" }, + { name = "scikit-image" }, { name = "ultralytics" }, ] @@ -771,6 +772,7 @@ requires-dist = [ { name = "rapidfuzz", specifier = ">=3.14.5" }, { name = "rapidocr-onnxruntime", specifier = ">=1.4.4" }, { name = "requests", specifier = ">=2.31" }, + { name = "scikit-image", specifier = ">=0.24" }, { name = "ultralytics", specifier = ">=8.0" }, ] @@ -1204,6 +1206,19 @@ 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 = "imageio" +version = "2.38.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "pillow" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/be/027f866037034c8ccc1791a3df6d630d2e454233f7ba09fbff76ce5aed81/imageio-2.38.2.tar.gz", hash = "sha256:62e338ea5c19a5547521b3b590a8a9ed1177e5d6c3fd1df076029053eacc73ca", size = 404125, upload-time = "2026-11-16T08:43:45.488Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/30/34/7fb055831d4dd5aa9994cc296b61e341f4cd5221c8119b15b0617c721c61/imageio-2.38.2-py3-none-any.whl", hash = "sha256:d71174e7af8369a4f73525c5b1c0d2621eb2827ed3cfd7327560be02ac1b4084", size = 328689, upload-time = "2026-11-16T08:43:43.569Z" }, +] + [[package]] name = "inference-sdk" version = "1.3.1" @@ -1359,6 +1374,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0a/dd/8050c947d435c8d4bc94e3252f4d8bb8a76cfb424f043a8680be637a57f1/kiwisolver-1.5.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:59cd8683f575d96df5bb48f6add94afc055012c29e28124fcae2b63661b9efb1", size = 73558, upload-time = "2026-03-09T13:15:52.112Z" }, ] +[[package]] +name = "lazy-loader" +version = "0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/8c/0f2ff2a8b7513e68871a74740c17a504b0488c679b379e6445ebb7bd78dc/lazy_loader-0.6.tar.gz", hash = "sha256:2f4b7824d6401958639008a0cae20c776b61dff619accd6890693e2de8260167", size = 18438, upload-time = "2026-09-21T21:31:32.982Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/93/4e45e37f26c820216704b36b8e67cc55c490a7abd287a78a26a2c0e21386/lazy_loader-0.6-py3-none-any.whl", hash = "sha256:77253be3391b06124a0e16105bd663b6c54470af1a9ca8e1cf026f38d58ed056", size = 8791, upload-time = "2026-09-21T21:31:31.632Z" }, +] + [[package]] name = "markupsafe" version = "3.0.3" @@ -2851,6 +2878,74 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/29/4c/67bb45e41609eb4726f1bfeb59e083cf91d14c696d4bd14c234a980be93d/ruff-0.15.18-py3-none-win_arm64.whl", hash = "sha256:b2c9257fcbd4a3e5b977a1904e6facca016bafe2edc17df24db67cfaee03b4e4", size = 11329958, upload-time = "2026-06-18T18:25:43.686Z" }, ] +[[package]] +name = "scikit-image" +version = "0.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "imageio" }, + { name = "lazy-loader" }, + { name = "networkx" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "tifffile", version = "2026.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "tifffile", version = "2026.11.16", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/b4/2528bb43c67d48053a7a649a9666432dc307d66ba02e3a6d5c40f46655df/scikit_image-0.26.0.tar.gz", hash = "sha256:f5f970ab04efad85c24714321fcc91613fcb64ef2a892a13167df2f3e59199fa", size = 22729739, upload-time = "2025-12-20T17:12:21.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/16/8a407688b607f86f81f8c649bf0d68a2a6d67375f18c2d660aba20f5b648/scikit_image-0.26.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b1ede33a0fb3731457eaf53af6361e73dd510f449dac437ab54573b26788baf0", size = 12355510, upload-time = "2025-12-20T17:10:31.628Z" }, + { url = "https://files.pythonhosted.org/packages/6b/f9/7efc088ececb6f6868fd4475e16cfafc11f242ce9ab5fc3557d78b5da0d4/scikit_image-0.26.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7af7aa331c6846bd03fa28b164c18d0c3fd419dbb888fb05e958ac4257a78fdd", size = 12056334, upload-time = "2025-12-20T17:10:34.559Z" }, + { url = "https://files.pythonhosted.org/packages/9f/1e/bc7fb91fb5ff65ef42346c8b7ee8b09b04eabf89235ab7dbfdfd96cbd1ea/scikit_image-0.26.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9ea6207d9e9d21c3f464efe733121c0504e494dbdc7728649ff3e23c3c5a4953", size = 13297768, upload-time = "2025-12-20T17:10:37.733Z" }, + { url = "https://files.pythonhosted.org/packages/a5/2a/e71c1a7d90e70da67b88ccc609bd6ae54798d5847369b15d3a8052232f9d/scikit_image-0.26.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74aa5518ccea28121f57a95374581d3b979839adc25bb03f289b1bc9b99c58af", size = 13711217, upload-time = "2025-12-20T17:10:40.935Z" }, + { url = "https://files.pythonhosted.org/packages/d4/59/9637ee12c23726266b91296791465218973ce1ad3e4c56fc81e4d8e7d6e1/scikit_image-0.26.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d5c244656de905e195a904e36dbc18585e06ecf67d90f0482cbde63d7f9ad59d", size = 14337782, upload-time = "2025-12-20T17:10:43.452Z" }, + { url = "https://files.pythonhosted.org/packages/e7/5c/a3e1e0860f9294663f540c117e4bf83d55e5b47c281d475cc06227e88411/scikit_image-0.26.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:21a818ee6ca2f2131b9e04d8eb7637b5c18773ebe7b399ad23dcc5afaa226d2d", size = 14805997, upload-time = "2025-12-20T17:10:45.93Z" }, + { url = "https://files.pythonhosted.org/packages/d3/c6/2eeacf173da041a9e388975f54e5c49df750757fcfc3ee293cdbbae1ea0a/scikit_image-0.26.0-cp311-cp311-win_amd64.whl", hash = "sha256:9490360c8d3f9a7e85c8de87daf7c0c66507960cf4947bb9610d1751928721c7", size = 11878486, upload-time = "2025-12-20T17:10:48.246Z" }, + { url = "https://files.pythonhosted.org/packages/c3/a4/a852c4949b9058d585e762a66bf7e9a2cd3be4795cd940413dfbfbb0ce79/scikit_image-0.26.0-cp311-cp311-win_arm64.whl", hash = "sha256:0baa0108d2d027f34d748e84e592b78acc23e965a5de0e4bb03cf371de5c0581", size = 11346518, upload-time = "2025-12-20T17:10:50.575Z" }, + { url = "https://files.pythonhosted.org/packages/99/e8/e13757982264b33a1621628f86b587e9a73a13f5256dad49b19ba7dc9083/scikit_image-0.26.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d454b93a6fa770ac5ae2d33570f8e7a321bb80d29511ce4b6b78058ebe176e8c", size = 12376452, upload-time = "2025-12-20T17:10:52.796Z" }, + { url = "https://files.pythonhosted.org/packages/e3/be/f8dd17d0510f9911f9f17ba301f7455328bf13dae416560126d428de9568/scikit_image-0.26.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3409e89d66eff5734cd2b672d1c48d2759360057e714e1d92a11df82c87cba37", size = 12061567, upload-time = "2025-12-20T17:10:55.207Z" }, + { url = "https://files.pythonhosted.org/packages/b3/2b/c70120a6880579fb42b91567ad79feb4772f7be72e8d52fec403a3dde0c6/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4c717490cec9e276afb0438dd165b7c3072d6c416709cc0f9f5a4c1070d23a44", size = 13084214, upload-time = "2025-12-20T17:10:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/f4/a2/70401a107d6d7466d64b466927e6b96fcefa99d57494b972608e2f8be50f/scikit_image-0.26.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7df650e79031634ac90b11e64a9eedaf5a5e06fcd09bcd03a34be01745744466", size = 13561683, upload-time = "2025-12-20T17:10:59.49Z" }, + { url = "https://files.pythonhosted.org/packages/13/a5/48bdfd92794c5002d664e0910a349d0a1504671ef5ad358150f21643c79a/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cefd85033e66d4ea35b525bb0937d7f42d4cdcfed2d1888e1570d5ce450d3932", size = 14112147, upload-time = "2025-12-20T17:11:02.083Z" }, + { url = "https://files.pythonhosted.org/packages/ee/b5/ac71694da92f5def5953ca99f18a10fe98eac2dd0a34079389b70b4d0394/scikit_image-0.26.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3f5bf622d7c0435884e1e141ebbe4b2804e16b2dd23ae4c6183e2ea99233be70", size = 14661625, upload-time = "2025-12-20T17:11:04.528Z" }, + { url = "https://files.pythonhosted.org/packages/23/4d/a3cc1e96f080e253dad2251bfae7587cf2b7912bcd76fd43fd366ff35a87/scikit_image-0.26.0-cp312-cp312-win_amd64.whl", hash = "sha256:abed017474593cd3056ae0fe948d07d0747b27a085e92df5474f4955dd65aec0", size = 11911059, upload-time = "2025-12-20T17:11:06.61Z" }, + { url = "https://files.pythonhosted.org/packages/35/8a/d1b8055f584acc937478abf4550d122936f420352422a1a625eef2c605d8/scikit_image-0.26.0-cp312-cp312-win_arm64.whl", hash = "sha256:4d57e39ef67a95d26860c8caf9b14b8fb130f83b34c6656a77f191fa6d1d04d8", size = 11348740, upload-time = "2025-12-20T17:11:09.118Z" }, + { url = "https://files.pythonhosted.org/packages/4f/48/02357ffb2cca35640f33f2cfe054a4d6d5d7a229b88880a64f1e45c11f4e/scikit_image-0.26.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a2e852eccf41d2d322b8e60144e124802873a92b8d43a6f96331aa42888491c7", size = 12346329, upload-time = "2025-12-20T17:11:11.599Z" }, + { url = "https://files.pythonhosted.org/packages/67/b9/b792c577cea2c1e94cda83b135a656924fc57c428e8a6d302cd69aac1b60/scikit_image-0.26.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:98329aab3bc87db352b9887f64ce8cdb8e75f7c2daa19927f2e121b797b678d5", size = 12031726, upload-time = "2025-12-20T17:11:13.871Z" }, + { url = "https://files.pythonhosted.org/packages/07/a9/9564250dfd65cb20404a611016db52afc6268b2b371cd19c7538ea47580f/scikit_image-0.26.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:915bb3ba66455cf8adac00dc8fdf18a4cd29656aec7ddd38cb4dda90289a6f21", size = 13094910, upload-time = "2025-12-20T17:11:16.2Z" }, + { url = "https://files.pythonhosted.org/packages/a3/b8/0d8eeb5a9fd7d34ba84f8a55753a0a3e2b5b51b2a5a0ade648a8db4a62f7/scikit_image-0.26.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b36ab5e778bf50af5ff386c3ac508027dc3aaeccf2161bdf96bde6848f44d21b", size = 13660939, upload-time = "2025-12-20T17:11:18.464Z" }, + { url = "https://files.pythonhosted.org/packages/2f/d6/91d8973584d4793d4c1a847d388e34ef1218d835eeddecfc9108d735b467/scikit_image-0.26.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:09bad6a5d5949c7896c8347424c4cca899f1d11668030e5548813ab9c2865dcb", size = 14138938, upload-time = "2025-12-20T17:11:20.919Z" }, + { url = "https://files.pythonhosted.org/packages/39/9a/7e15d8dc10d6bbf212195fb39bdeb7f226c46dd53f9c63c312e111e2e175/scikit_image-0.26.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:aeb14db1ed09ad4bee4ceb9e635547a8d5f3549be67fc6c768c7f923e027e6cd", size = 14752243, upload-time = "2025-12-20T17:11:23.347Z" }, + { url = "https://files.pythonhosted.org/packages/8f/58/2b11b933097bc427e42b4a8b15f7de8f24f2bac1fd2779d2aea1431b2c31/scikit_image-0.26.0-cp313-cp313-win_amd64.whl", hash = "sha256:ac529eb9dbd5954f9aaa2e3fe9a3fd9661bfe24e134c688587d811a0233127f1", size = 11906770, upload-time = "2025-12-20T17:11:25.297Z" }, + { url = "https://files.pythonhosted.org/packages/ad/ec/96941474a18a04b69b6f6562a5bd79bd68049fa3728d3b350976eccb8b93/scikit_image-0.26.0-cp313-cp313-win_arm64.whl", hash = "sha256:a2d211bc355f59725efdcae699b93b30348a19416cc9e017f7b2fb599faf7219", size = 11342506, upload-time = "2025-12-20T17:11:27.399Z" }, + { url = "https://files.pythonhosted.org/packages/03/e5/c1a9962b0cf1952f42d32b4a2e48eed520320dbc4d2ff0b981c6fa508b6b/scikit_image-0.26.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9eefb4adad066da408a7601c4c24b07af3b472d90e08c3e7483d4e9e829d8c49", size = 12663278, upload-time = "2025-12-20T17:11:29.358Z" }, + { url = "https://files.pythonhosted.org/packages/ae/97/c1a276a59ce8e4e24482d65c1a3940d69c6b3873279193b7ebd04e5ee56b/scikit_image-0.26.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:6caec76e16c970c528d15d1c757363334d5cb3069f9cea93d2bead31820511f3", size = 12405142, upload-time = "2025-12-20T17:11:31.282Z" }, + { url = "https://files.pythonhosted.org/packages/d4/4a/f1cbd1357caef6c7993f7efd514d6e53d8fd6f7fe01c4714d51614c53289/scikit_image-0.26.0-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a07200fe09b9d99fcdab959859fe0f7db8df6333d6204344425d476850ce3604", size = 12942086, upload-time = "2025-12-20T17:11:33.683Z" }, + { url = "https://files.pythonhosted.org/packages/5b/6f/74d9fb87c5655bd64cf00b0c44dc3d6206d9002e5f6ba1c9aeb13236f6bf/scikit_image-0.26.0-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:92242351bccf391fc5df2d1529d15470019496d2498d615beb68da85fe7fdf37", size = 13265667, upload-time = "2025-12-20T17:11:36.11Z" }, + { url = "https://files.pythonhosted.org/packages/a7/73/faddc2413ae98d863f6fa2e3e14da4467dd38e788e1c23346cf1a2b06b97/scikit_image-0.26.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:52c496f75a7e45844d951557f13c08c81487c6a1da2e3c9c8a39fcde958e02cc", size = 14001966, upload-time = "2025-12-20T17:11:38.55Z" }, + { url = "https://files.pythonhosted.org/packages/02/94/9f46966fa042b5d57c8cd641045372b4e0df0047dd400e77ea9952674110/scikit_image-0.26.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:20ef4a155e2e78b8ab973998e04d8a361d49d719e65412405f4dadd9155a61d9", size = 14359526, upload-time = "2025-12-20T17:11:41.087Z" }, + { url = "https://files.pythonhosted.org/packages/5d/b4/2840fe38f10057f40b1c9f8fb98a187a370936bf144a4ac23452c5ef1baf/scikit_image-0.26.0-cp313-cp313t-win_amd64.whl", hash = "sha256:c9087cf7d0e7f33ab5c46d2068d86d785e70b05400a891f73a13400f1e1faf6a", size = 12287629, upload-time = "2025-12-20T17:11:43.11Z" }, + { url = "https://files.pythonhosted.org/packages/22/ba/73b6ca70796e71f83ab222690e35a79612f0117e5aaf167151b7d46f5f2c/scikit_image-0.26.0-cp313-cp313t-win_arm64.whl", hash = "sha256:27d58bc8b2acd351f972c6508c1b557cfed80299826080a4d803dd29c51b707e", size = 11647755, upload-time = "2025-12-20T17:11:45.279Z" }, + { url = "https://files.pythonhosted.org/packages/51/44/6b744f92b37ae2833fd423cce8f806d2368859ec325a699dc30389e090b9/scikit_image-0.26.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:63af3d3a26125f796f01052052f86806da5b5e54c6abef152edb752683075a9c", size = 12365810, upload-time = "2025-12-20T17:11:47.357Z" }, + { url = "https://files.pythonhosted.org/packages/40/f5/83590d9355191f86ac663420fec741b82cc547a4afe7c4c1d986bf46e4db/scikit_image-0.26.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:ce00600cd70d4562ed59f80523e18cdcc1fae0e10676498a01f73c255774aefd", size = 12075717, upload-time = "2025-12-20T17:11:49.483Z" }, + { url = "https://files.pythonhosted.org/packages/72/48/253e7cf5aee6190459fe136c614e2cbccc562deceb4af96e0863f1b8ee29/scikit_image-0.26.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6381edf972b32e4f54085449afde64365a57316637496c1325a736987083e2ab", size = 13161520, upload-time = "2025-12-20T17:11:51.58Z" }, + { url = "https://files.pythonhosted.org/packages/73/c3/cec6a3cbaadfdcc02bd6ff02f3abfe09eaa7f4d4e0a525a1e3a3f4bce49c/scikit_image-0.26.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c6624a76c6085218248154cc7e1500e6b488edcd9499004dd0d35040607d7505", size = 13684340, upload-time = "2025-12-20T17:11:53.708Z" }, + { url = "https://files.pythonhosted.org/packages/d4/0d/39a776f675d24164b3a267aa0db9f677a4cb20127660d8bf4fd7fef66817/scikit_image-0.26.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f775f0e420faac9c2aa6757135f4eb468fb7b70e0b67fa77a5e79be3c30ee331", size = 14203839, upload-time = "2025-12-20T17:11:55.89Z" }, + { url = "https://files.pythonhosted.org/packages/ee/25/2514df226bbcedfe9b2caafa1ba7bc87231a0c339066981b182b08340e06/scikit_image-0.26.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede4d6d255cc5da9faeb2f9ba7fedbc990abbc652db429f40a16b22e770bb578", size = 14770021, upload-time = "2025-12-20T17:11:58.014Z" }, + { url = "https://files.pythonhosted.org/packages/8d/5b/0671dc91c0c79340c3fe202f0549c7d3681eb7640fe34ab68a5f090a7c7f/scikit_image-0.26.0-cp314-cp314-win_amd64.whl", hash = "sha256:0660b83968c15293fd9135e8d860053ee19500d52bf55ca4fb09de595a1af650", size = 12023490, upload-time = "2025-12-20T17:12:00.013Z" }, + { url = "https://files.pythonhosted.org/packages/65/08/7c4cb59f91721f3de07719085212a0b3962e3e3f2d1818cbac4eeb1ea53e/scikit_image-0.26.0-cp314-cp314-win_arm64.whl", hash = "sha256:b8d14d3181c21c11170477a42542c1addc7072a90b986675a71266ad17abc37f", size = 11473782, upload-time = "2025-12-20T17:12:01.983Z" }, + { url = "https://files.pythonhosted.org/packages/49/41/65c4258137acef3d73cb561ac55512eacd7b30bb4f4a11474cad526bc5db/scikit_image-0.26.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:cde0bbd57e6795eba83cb10f71a677f7239271121dc950bc060482834a668ad1", size = 12686060, upload-time = "2025-12-20T17:12:03.886Z" }, + { url = "https://files.pythonhosted.org/packages/e7/32/76971f8727b87f1420a962406388a50e26667c31756126444baf6668f559/scikit_image-0.26.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:163e9afb5b879562b9aeda0dd45208a35316f26cc7a3aed54fd601604e5cf46f", size = 12422628, upload-time = "2025-12-20T17:12:05.921Z" }, + { url = "https://files.pythonhosted.org/packages/37/0d/996febd39f757c40ee7b01cdb861867327e5c8e5f595a634e8201462d958/scikit_image-0.26.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:724f79fd9b6cb6f4a37864fe09f81f9f5d5b9646b6868109e1b100d1a7019e59", size = 12962369, upload-time = "2025-12-20T17:12:07.912Z" }, + { url = "https://files.pythonhosted.org/packages/48/b4/612d354f946c9600e7dea012723c11d47e8d455384e530f6daaaeb9bf62c/scikit_image-0.26.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3268f13310e6857508bd87202620df996199a016a1d281b309441d227c822394", size = 13272431, upload-time = "2025-12-20T17:12:10.255Z" }, + { url = "https://files.pythonhosted.org/packages/0a/6e/26c00b466e06055a086de2c6e2145fe189ccdc9a1d11ccc7de020f2591ad/scikit_image-0.26.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fac96a1f9b06cd771cbbb3cd96c5332f36d4efd839b1d8b053f79e5887acde62", size = 14016362, upload-time = "2025-12-20T17:12:12.793Z" }, + { url = "https://files.pythonhosted.org/packages/47/88/00a90402e1775634043c2a0af8a3c76ad450866d9fa444efcc43b553ba2d/scikit_image-0.26.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2c1e7bd342f43e7a97e571b3f03ba4c1293ea1a35c3f13f41efdc8a81c1dc8f2", size = 14364151, upload-time = "2025-12-20T17:12:14.909Z" }, + { url = "https://files.pythonhosted.org/packages/da/ca/918d8d306bd43beacff3b835c6d96fac0ae64c0857092f068b88db531a7c/scikit_image-0.26.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b702c3bb115e1dcf4abf5297429b5c90f2189655888cbed14921f3d26f81d3a4", size = 12413484, upload-time = "2025-12-20T17:12:17.046Z" }, + { url = "https://files.pythonhosted.org/packages/dc/cd/4da01329b5a8d47ff7ec3c99a2b02465a8017b186027590dc7425cee0b56/scikit_image-0.26.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0608aa4a9ec39e0843de10d60edb2785a30c1c47819b67866dd223ebd149acaf", size = 11769501, upload-time = "2025-12-20T17:12:19.339Z" }, +] + [[package]] name = "scipy" version = "1.17.1" @@ -3104,6 +3199,50 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, ] +[[package]] +name = "tifffile" +version = "2026.3.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "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 = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c5/cb/2f6d79c7576e22c116352a801f4c3c8ace5957e9aced862012430b62e14f/tifffile-2026.3.3.tar.gz", hash = "sha256:d9a1266bed6f2ee1dd0abde2018a38b4f8b2935cb843df381d70ac4eac5458b7", size = 388745, upload-time = "2026-03-03T19:14:38.134Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1a/e4/e804505f87627cd8cdae9c010c47c4485fd8c1ce31a7dd0ab7fcc4707377/tifffile-2026.3.3-py3-none-any.whl", hash = "sha256:e8be15c94273113d31ecb7aa3a39822189dd11c4967e3cc88c178f1ad2fd1170", size = 243960, upload-time = "2026-03-03T19:14:35.808Z" }, +] + +[[package]] +name = "tifffile" +version = "2026.11.16" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform == 'darwin'", + "python_full_version >= '3.14' 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 = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/e1/f09384869bcf78bae3a794a86d8a90753fb2a6f4646c07ec941ff629cd33/tifffile-2026.11.16.tar.gz", hash = "sha256:d9c246d464f1c3ca9ab62c5225b3ff45578f33629029dbbd9f62f4e901702726", size = 462802, upload-time = "2026-11-17T03:35:19.648Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cf/3a/483491be6f7eb070d1c22b1182bbbc0243e85bf5903fafe3f80b6aeb3dba/tifffile-2026.11.16-py3-none-any.whl", hash = "sha256:d2103c2537f185868f0a880eceba590b316aa1981bd76d91028e5f2eb0e1a6e6", size = 279737, upload-time = "2026-11-17T03:35:18.375Z" }, +] + [[package]] name = "torch" version = "2.12.1" diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index 9db288b..8b9794e 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -33,6 +33,26 @@ export type CircuitNodeType = */ export type YoloNodeType = CircuitNodeType | 'junction'; +/** One terminal of a detected component (export schema 2): its image point and the net it is wired to. */ +export interface CircuitPin { + x: number | null; + y: number | null; + /** Net id from CircuitExportJSON.nets, or null when the terminal is unwired. */ + net: string | null; +} + +/** Symbol orientation: mirror (x -> -x) first, then `rotation` degrees clockwise. */ +export interface CircuitOrientation { + rotation: 0 | 90 | 180 | 270; + mirror: boolean; +} + +/** Seeded standard cell a gate symbol maps to, with detector terminal -> cell pin id. */ +export interface CircuitLibraryCell { + id: string; + pins: Record; +} + /** One detected component placed on the canvas. */ export interface CircuitComponent { id: string; @@ -43,6 +63,36 @@ export interface CircuitComponent { y: number; /** Detector confidence in [0, 1]. */ confidence: number; + /** Schema 2: detector class name (ml/classes.yaml). */ + class?: string; + /** Schema 2: box size and corners in source-image pixels. */ + width?: number; + height?: number; + bbox?: [number, number, number, number]; + /** Schema 2: estimated symbol orientation. */ + orientation?: CircuitOrientation | null; + /** Schema 2: 'keypoints' (detector pin points) or 'geometry' (classical fallback). */ + pin_source?: 'keypoints' | 'geometry' | null; + /** Schema 2: terminal name (handle naming of ml/classes.yaml) -> pin. */ + pins?: Record; + /** Schema 2: seeded standard cell for gate symbols (null when none exists, e.g. XNOR). */ + library_cell?: CircuitLibraryCell | null; +} + +/** An undirected electrical net (export schema 2): the ":" pins it joins. */ +export interface CircuitNet { + id: string; + label: string | null; + pins: string[]; +} + +/** A net realised as a ReactFlow edge with the app's handle ids (export schema 2). */ +export interface CircuitEdge { + id: string; + source: string; + sourceHandle: string | null; + target: string; + targetHandle: string | null; } /** One directed wire between two components. */ @@ -71,12 +121,20 @@ export interface DetectGatesResponse { predictions?: GateDetection[]; } -/** Success payload of POST /detect_circuit. */ +/** + * Success payload of POST /detect_circuit. Schema 2 (backend/pipeline/circuit_exporter.py) adds nets, + * edges and per-component pins; `connections` stays the legacy gate-level list the importer reads today. + */ export interface CircuitExportJSON { status: 'ok'; components: CircuitComponent[]; connections: CircuitConnection[]; detections: GateDetection[]; + schema_version?: number; + image?: { width: number; height: number }; + nets?: CircuitNet[]; + edges?: CircuitEdge[]; + warnings?: string[]; } /** 503 payload of POST /detect_circuit while weights are missing. */ diff --git a/ml/class_schema.py b/ml/class_schema.py index f6f55b7..7ef41cd 100644 --- a/ml/class_schema.py +++ b/ml/class_schema.py @@ -170,6 +170,19 @@ def _validate(schema: ClassSchema) -> None: raise ValueError(f"legacy_order entry {name} is neither a class nor an alias") +def _py_tuple(items: tuple[str, ...]) -> str: + """ + Python source of a tuple of strings, formatted the way ruff format writes it. + + Args: + items: Strings. + Returns: + Source text such as ("a",) or ("a", "b"). + """ + quoted = ", ".join(f'"{t}"' for t in items) + return f"({quoted},)" if len(items) == 1 else f"({quoted})" + + def render_backend_map(schema: ClassSchema) -> str: """ Render backend/pipeline/class_map.py (ruff-format clean). @@ -184,7 +197,8 @@ def render_backend_map(schema: ClassSchema) -> str: "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.", + " that old weights still predict, the class-to-frontend-node-type map and the", + " terminal names of each class (the net tracer's pin vocabulary).", " Regenerate with `cd ml && uv run python class_schema.py generate`.", '"""', "", @@ -203,6 +217,11 @@ def render_backend_map(schema: ClassSchema) -> str: *[f' "{n}": "{t}",' for n, t in schema.node_type_map().items()], "}", "", + "# Canonical class name -> terminal names, in the frontend handle naming (t: / s:).", + "CLASS_TERMINALS: dict[str, tuple[str, ...]] = {", + *[f' "{c.name}": {_py_tuple(c.terminals)},' for c in schema.classes], + "}", + "", ] return "\n".join(lines) diff --git a/ml/eval_netlist.py b/ml/eval_netlist.py index 01a5787..b976084 100644 --- a/ml/eval_netlist.py +++ b/ml/eval_netlist.py @@ -6,11 +6,14 @@ 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): +Netlist JSON schema (ground truth and predictions use the same shape; the T8 exporter emits it): { "components": [{"id": "MP1", "type": "pmos", "bbox": [x1, y1, x2, y2]}, ...], "nets": [["MP1:d", "MN1:d", "Y:a"], ["IN:out", "MP1:g", "MN1:g"], ...] } + - A net may also be an object {"pins": [...], ...} (the exporter's schema 2 form, which adds id and label). + - The T2 generator's netlist.json (components with "node_type" and a "pins" terminal -> net-name map, + "nets" as a list of names) is accepted too and converted by from_pin_map(). - 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 @@ -78,6 +81,45 @@ def node_terminals() -> dict[str, tuple[str, ...]]: return {c.node_type: c.terminals for c in load_schema().classes if c.node_type != "junction"} +def from_pin_map(raw: Mapping[str, object]) -> dict[str, object]: + """ + Convert a pin-map netlist (the T2 generator's netlist.json) into the nets-of-pins schema. + + Args: + raw: Netlist whose components carry "pins": {terminal: net name} and a "node_type" (or "type"). + Pins of an unconnected terminal are not listed, so every listed pin joins its named net. + Returns: + {"components": [{"id", "type", "bbox"?}], "nets": [[pins], ...]} with one net per net name. + Raises: + NetlistError: If a component is malformed. + """ + components: list[dict[str, object]] = [] + by_net: dict[str, list[str]] = {} + for entry in raw.get("components") or []: + if not isinstance(entry, dict) or not isinstance(entry.get("pins"), dict): + raise NetlistError(f"malformed pin-map component {entry!r}") + comp: dict[str, object] = {"id": entry.get("id"), "type": entry.get("type", entry.get("node_type"))} + if entry.get("bbox") is not None: + comp["bbox"] = entry["bbox"] + components.append(comp) + for term, net in sorted(entry["pins"].items()): + by_net.setdefault(str(net), []).append(f"{entry.get('id')}:{term}") + return {"components": components, "nets": [sorted(pins) for _, pins in sorted(by_net.items())]} + + +def _is_pin_map(raw: Mapping[str, object]) -> bool: + """ + Whether a netlist dict uses the pin-map shape (components with a "pins" dict). + + Args: + raw: Parsed netlist JSON. + Returns: + True for the T2 generator's shape. + """ + comps = raw.get("components") + return isinstance(comps, list) and bool(comps) and all(isinstance(c, dict) and isinstance(c.get("pins"), dict) and all(isinstance(v, str) for v in c["pins"].values()) for c in comps) + + def parse_netlist(raw: Mapping[str, object], terminals: Mapping[str, Sequence[str]] | None = None) -> Netlist: """ Validate a netlist dict and normalise its nets. @@ -91,6 +133,8 @@ def parse_netlist(raw: Mapping[str, object], terminals: Mapping[str, Sequence[st NetlistError: On unknown types, duplicate ids, malformed pins, or pins on unknown components/terminals. """ terms = terminals if terminals is not None else node_terminals() + if _is_pin_map(raw): + raw = from_pin_map(raw) comps_raw = raw.get("components") nets_raw = raw.get("nets") if not isinstance(comps_raw, list) or not isinstance(nets_raw, list): @@ -122,6 +166,8 @@ def find(pin: str) -> str: return pin for net in nets_raw: + if isinstance(net, dict): + net = net.get("pins") 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: diff --git a/ml/tests/test_eval_netlist.py b/ml/tests/test_eval_netlist.py index 0c2db7f..e3ad81e 100644 --- a/ml/tests/test_eval_netlist.py +++ b/ml/tests/test_eval_netlist.py @@ -1,6 +1,7 @@ """ Module: test_eval_netlist.py -Purpose: Tests for ml/eval_netlist.py - netlist validation, component matching (by bbox and by id), +Purpose: Tests for ml/eval_netlist.py - netlist validation (nets-of-pins, net objects and the T2 + generator's pin-map shape), 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). @@ -17,6 +18,7 @@ BridgeError, NetlistError, evaluate_netlists, + from_pin_map, match_components, parse_netlist, pin_pairs, @@ -175,3 +177,27 @@ def test_truth_table_of_ground_truth_nand_is_correct() -> None: 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]] + + +def test_net_objects_are_accepted() -> None: + """Nets given as objects with a "pins" list (the exporter's schema 2 form) parse like plain pin lists.""" + raw = nand_netlist() + as_objects = {**raw, "nets": [{"id": f"n{i}", "label": None, "pins": pins} for i, pins in enumerate(raw["nets"])]} + assert parse_netlist(as_objects).nets == parse_netlist(raw).nets + + +def test_pin_map_netlist_from_the_generator() -> None: + """The T2 generator's netlist.json (components with a terminal -> net-name map) converts to nets of pins.""" + t2 = { + "components": [ + {"id": "IN_A", "class": "INPUT_PORT", "node_type": "input", "pins": {"out": "A"}}, + {"id": "M1", "class": "NMOS", "node_type": "nmos", "pins": {"d": "Y", "g": "A", "s": "GND"}}, + {"id": "GND1", "class": "GND", "node_type": "ground", "pins": {"gnd": "GND"}}, + {"id": "OUT_Y", "class": "OUTPUT_PORT", "node_type": "output", "pins": {"a": "Y"}}, + ], + "nets": ["A", "GND", "Y"], + } + assert from_pin_map(t2)["nets"] == [["IN_A:out", "M1:g"], ["GND1:gnd", "M1:s"], ["M1:d", "OUT_Y:a"]] + parsed = parse_netlist(t2) + assert {c.type for c in parsed.components.values()} == {"input", "nmos", "ground", "output"} + assert set(parsed.nets) == {frozenset({"IN_A:out", "M1:g"}), frozenset({"GND1:gnd", "M1:s"}), frozenset({"M1:d", "OUT_Y:a"})} From 26746160a66a05df833b65bf89550cf5f253c859 Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 02:51:32 +0530 Subject: [PATCH 2/4] no-mistakes(review): Document T2 net tracing bench results and T3 follow-up --- agent_docs/ml-pipeline.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index 0d76e37..8d514b0 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -27,8 +27,22 @@ Image → [Stage 1: YOLO Detection] → [Stage 2: OpenCV Net Tracing (wire extra - Bench: `cd backend && uv run python data_gen/generate_v2.py --count 300 --seed 1 --out DIR && uv run python bench_tracing.py --data DIR --truth-table` drives the tracer from perturbed ground-truth detections and scores it with `ml/eval_netlist.py` per render style (clean = cad/textbook, hand_drawn = hand/photo); it exits 1 unless net F1 >= 0.90 for both styles, exact match >= 70% clean / >= 50% hand-drawn, and p95 runtime < 2 s. -- Not yet: the T3 screenshot round-trip check, and the frontend importer (T9) still reads only the legacy `connections` (gate-level); wiring - transistor-level imports means consuming `nets`/`edges` (handles `t:`/`s:` + terminal) and `library_cell` in `App.tsx importCircuit`. +- Measured T2 results: 300 samples from `generate_v2.py --count 300 --seed 1` (held out from tuning, which used seed 7). Detections are + perturbed ground truth (box edges N(0, 3% of side), keypoints N(0, 3% of short side), 2% of junction dots dropped), scored with + `ml/eval_netlist.py`. These scores come from perturbed ground-truth detections because no trained detector for the new classes exists yet, + so they bound the tracer, not the end-to-end photo pipeline. + + | Mode | Style (circuits) | Net F1 | Exact match | Truth-table match | + |------|------------------|--------|-------------|-------------------| + | Keypoints | clean (151) | 0.9995 | 99.3% | 99.3% | + | Keypoints | hand-drawn (149) | 0.9989 | 98.7% | 98.7% | + | Geometry fallback (no keypoints) | clean | 0.9897 | 88.7% | 92.0% (overall) | + | Geometry fallback (no keypoints) | hand-drawn | 0.9799 | 86.6% | 92.0% (overall) | + + Keypoint mode overall truth-table match is 99.0%. Runtime per image: mean 0.12 s, p95 0.29 s, max 0.80 s (keypoints); p95 0.34 s (geometry fallback). +- Not yet: the T3 screenshot round-trip truth-table check is tracked as a T3/T8 follow-up (the T3 screenshot set does not exist yet). The + frontend importer (T9) still reads only the legacy `connections` (gate-level); wiring transistor-level imports means consuming + `nets`/`edges` (handles `t:`/`s:` + terminal) and `library_cell` in `App.tsx importCircuit`. ## Class Vocabulary Single source of truth: `ml/classes.yaml` (name, tier, YOLO id, frontend node type, terminals, default size, legacy aliases). From 16ce734495f7ec03278a12f1c6b532b76d031566 Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 02:55:30 +0530 Subject: [PATCH 3/4] no-mistakes(review): Downscale ink background estimate; guard pass-through repair on partial keypoints --- backend/pipeline/ink.py | 11 ++++++++--- backend/pipeline/net_tracer.py | 3 ++- backend/test_net_tracer.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/backend/pipeline/ink.py b/backend/pipeline/ink.py index 045746d..e6199c0 100644 --- a/backend/pipeline/ink.py +++ b/backend/pipeline/ink.py @@ -17,6 +17,8 @@ # Background kernel as a fraction of the longer image side (must exceed the largest junction dot). BACKGROUND_KERNEL_FRACTION = 0.03 MIN_BACKGROUND_KERNEL = 15 +# The paper background is smooth, so it is estimated on a copy whose longer side is at most this many pixels. +BACKGROUND_MAX_SIDE = 1000 def _odd(n: float) -> int: @@ -58,10 +60,13 @@ def ink_mask(image: np.ndarray) -> np.ndarray: """ gray = to_gray(image) h, w = gray.shape - k = _odd(max(MIN_BACKGROUND_KERNEL, BACKGROUND_KERNEL_FRACTION * max(h, w))) + shrink = min(1.0, BACKGROUND_MAX_SIDE / max(h, w)) + small = gray if shrink == 1.0 else cv2.resize(gray, (max(1, round(w * shrink)), max(1, round(h * shrink))), interpolation=cv2.INTER_AREA) + k = _odd(max(MIN_BACKGROUND_KERNEL, BACKGROUND_KERNEL_FRACTION * max(small.shape))) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k)) - background = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel) - background = cv2.blur(background, (k, k)) + background = cv2.blur(cv2.morphologyEx(small, cv2.MORPH_CLOSE, kernel), (k, k)) + if shrink != 1.0: + background = cv2.resize(background, (w, h), interpolation=cv2.INTER_LINEAR) ratio = gray / np.maximum(background, 1.0) return ratio < INK_RATIO diff --git a/backend/pipeline/net_tracer.py b/backend/pipeline/net_tracer.py index 3011741..672f3a2 100644 --- a/backend/pipeline/net_tracer.py +++ b/backend/pipeline/net_tracer.py @@ -249,7 +249,8 @@ def trace(self, image: np.ndarray, detections: list[Detection], texts: list[Text used = {id(c) for c in terms.values()} leftovers = [c for c in mine if id(c) not in used] diag.unassigned_contacts += len(leftovers) - diag.pass_through_repairs += self._repair_pass_through(leftovers, uf, cfg.pass_through_cos) + if not det.keypoints or all(t in det.keypoints for t in CLASS_TERMINALS[cls]): + diag.pass_through_repairs += self._repair_pass_through(leftovers, uf, cfg.pass_through_cos) net_of_root: dict[int, str] = {} counter = itertools.count() diff --git a/backend/test_net_tracer.py b/backend/test_net_tracer.py index 4258a64..88f52cc 100644 --- a/backend/test_net_tracer.py +++ b/backend/test_net_tracer.py @@ -9,6 +9,7 @@ from __future__ import annotations +import time from dataclasses import dataclass, field import cv2 @@ -334,6 +335,19 @@ def test_rotated_mirrored_transistor(orientation: Orientation, keypoints: bool) assert mos.orientation == orientation +def test_partial_keypoints_do_not_merge_drain_and_source_nets() -> None: + """A vertical NMOS whose drain and source keypoints were dropped keeps its two wires on separate nets.""" + sc = transistor_scene(0, False) + dets = sc.detections(keypoints=True) + mos = next(d for d, sym in zip(dets, sc.symbols) if sym.name == "M") + mos.keypoints = {"g": mos.keypoints["g"]} + result = NetTracer().trace(sc.image(), dets, texts=[]) + names = {c.id: s.name for c, s in zip(result.components, sc.symbols)} + nets = [{f"{names[p.partition(':')[0]]}:{p.partition(':')[2]}" for p in net.pins} for net in result.nets] + assert not any("OUT:a" in pins and "GND:gnd" in pins for pins in nets) + assert result.diagnostics.pass_through_repairs == 0 + + @pytest.mark.parametrize( ("cls", "variant", "four"), [ @@ -402,6 +416,22 @@ def test_ink_ignores_ruled_paper_lines() -> None: assert abs(stroke_width(mask) - int(mask[:, 150].sum())) <= 1.0 +def test_ink_mask_on_a_large_photo_is_fast_and_keeps_strokes() -> None: + """A 4000x3000 shaded photo binarises in well under a second and finds the same strokes as a downscaled copy.""" + h, w = 3000, 4000 + shade = np.linspace(190, 245, w, dtype=np.float32)[None, :].repeat(h, axis=0) + img = cv2.cvtColor(shade.astype(np.uint8), cv2.COLOR_GRAY2BGR) + cv2.line(img, (200, 1500), (3800, 1500), (25, 25, 25), 9) + cv2.line(img, (2000, 200), (2000, 2800), (25, 25, 25), 9) + start = time.perf_counter() + mask = ink_mask(img) + elapsed = time.perf_counter() - start + assert elapsed < 1.0 + assert mask.shape == (h, w) + assert mask[1500, 1000] and mask[1000, 2000] and not mask[700, 1000] and not mask[2500, 3000] + assert abs(stroke_width(mask) - int((img[:, 1000, 0] < 100).sum())) <= 1.0 + + def test_reads_port_labels_beside_symbols() -> None: """The label window beside each port is cropped and recognised; nets take their port's name.""" sc = crossing_scene(with_dot=False) From 328d2e4897a5d64b289c313651b0a18828285016 Mon Sep 17 00:00:00 2001 From: Mani212005 Date: Wed, 18 Nov 2026 03:02:15 +0530 Subject: [PATCH 4/4] no-mistakes(document): Fix stale DiGraph reference in testing.md --- testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing.md b/testing.md index 40950d5..7028329 100644 --- a/testing.md +++ b/testing.md @@ -65,7 +65,7 @@ Reviewer agent runs this checklist before approving anything. ### Phase 3 (Wire Extraction + Graph) - [ ] Wire extraction correctly traces connections on 5 test images -- [ ] Graph builder produces a valid `networkx.DiGraph` with correct node/edge count +- [ ] Graph builder produces a valid bipartite component/net `networkx.MultiGraph` with correct node/edge count - [ ] No isolated nodes in output graph (every component is connected) - [ ] Training run logged - [ ] `current_phase.txt` updated to `4`