diff --git a/README.md b/README.md index 8e23bce..dc99970 100644 --- a/README.md +++ b/README.md @@ -146,8 +146,9 @@ What is true today: It does not recognise NMOS/PMOS transistors or supply symbols, and it detects nothing useful on transistor-level schematics. - **Retraining on transistor-level classes is in progress.** The class schema - (`ml/classes.yaml`) is in place; it still needs a synthetic transistor-level - generator, real hand-drawn data (see [Data and licences](#-data-and-licences)), + (`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, treat detection results on transistor schematics as unsupported. - **Training is transfer learning only** (pretrained COCO weights, never random diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index b2ca01c..c58543f 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -67,7 +67,8 @@ Current phase: `ml/experiments/current_phase.txt` ## Dataset - **Source:** Synthetic screenshots from DigiSim (primary) + hand-drawn images (supplement) -- **Generation:** `backend/data_gen/screenshot_pipeline.py` +- **Generation:** `backend/data_gen/generate_v2.py` (tier A, transistor + gate domains, pins/orientation/netlists, + topology-hash splits, held-out test styles; see `docs/synth_v2/README.md`); legacy gate-era `backend/data_gen/screenshot_pipeline.py` - **Augmentation:** `backend/data_gen/augmentation.py` - **Minimum size:** Phase 1 → 500 images. Phase 2+ → 2000 images - **Format:** YOLO `.txt` per image — ` ` (normalized) diff --git a/backend/data_gen/generate_v2.py b/backend/data_gen/generate_v2.py new file mode 100644 index 0000000..f860292 --- /dev/null +++ b/backend/data_gen/generate_v2.py @@ -0,0 +1,358 @@ +""" +Module: generate_v2.py +Purpose: Synthetic circuit dataset generator v2. Samples netlist-driven circuits (transistor-level + CMOS and gate-level), lays them out and routes them like textbook schematics, renders + them in clean, textbook, hand-drawn and phone-photo styles, and writes per sample: + a JPEG, YOLO box labels (ml/classes.yaml ids), an annotation JSON (pins, orientation, + junctions, wires, crossings, texts) and a netlist JSON (components, nets, reference + truth table). Splits are by topology hash; some test samples use held-out styles. + Output is fully deterministic per (--seed, sample index), so the manifest is + byte-identical across runs and worker counts. + +Usage: + cd backend && uv run python data_gen/generate_v2.py --count 8000 --seed 1 + cd backend && uv run python data_gen/generate_v2.py --count 200 --seed 1 --out /tmp/synth --workers 4 +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import sys +from collections import Counter +from dataclasses import dataclass +from multiprocessing import Pool +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from data_gen.synth_v2.layout import LayoutError, build_layout, sample_draw_style # noqa: E402 +from data_gen.synth_v2.logic import Circuit, sample_circuit, topology_hash # noqa: E402 +from data_gen.synth_v2.render import DOT_MAX_PER_1000, DOT_MIN_PER_1000, render, sample_render_style # noqa: E402 +from data_gen.synth_v2.schema import CLASS_ID, NODE_TYPE, REPO_ROOT, SCHEMA, SCHEMA_VERSION, TIER_A, render_data_yaml # noqa: E402 + +GENERATOR_VERSION = 1 +DEFAULT_OUT = REPO_ROOT / "ml" / "dataset" / "synth_v2" +SPLITS: tuple[str, ...] = ("train", "valid", "test") +DOMAIN_WEIGHTS: tuple[tuple[str, float], ...] = (("transistor", 0.7), ("gate", 0.3)) +HELD_OUT_FRACTION = 0.5 +DOMAIN_CLASSES: dict[str, tuple[str, ...]] = { + "transistor": ("NMOS", "PMOS", "VDD", "GND", "INPUT_PORT", "OUTPUT_PORT", "JUNCTION"), + "gate": ("AND", "OR", "NOT", "NAND", "NOR", "XOR", "XNOR", "INPUT_PORT", "OUTPUT_PORT", "JUNCTION"), +} +BALANCE_MIN_RATIO = 0.10 + + +@dataclass +class Sample: + """Everything generated for one sample index, ready to write.""" + + index: int + sample_id: str + split: str + domain: str + recipe: str + topology: str + held_out: bool + image: bytes + label: str + annotation: dict + netlist: dict + + +def split_for(topology: str) -> str: + """ + Deterministic split from a topology hash (about 80/10/10). + + Args: + topology: Hex topology hash. + Returns: + "train", "valid" or "test". + """ + bucket = int(topology[:8], 16) % 100 + return "train" if bucket < 80 else ("valid" if bucket < 90 else "test") + + +def build_netlist(circuit: Circuit, annotation: dict, topology: str) -> dict: + """ + Netlist JSON for a sample: drawn components (devices, ports, supplies), nets and truth table. + + Args: + circuit: Sampled circuit. + annotation: Render annotation (its symbols carry the drawn components and nets). + topology: Topology hash. + Returns: + JSON-serialisable netlist. + """ + components = [] + nets: set[str] = set() + for sym in sorted(annotation["symbols"], key=lambda s: s["id"]): + pins = dict(sorted(sym["nets"].items())) + nets.update(pins.values()) + comp = {"id": sym["id"], "class": sym["class"], "node_type": NODE_TYPE[sym["class"]], "pins": pins} + if sym["class"] in ("INPUT_PORT", "OUTPUT_PORT"): + comp["label"] = next(iter(pins.values())) + components.append(comp) + return { + "version": GENERATOR_VERSION, + "domain": circuit.domain, + "recipe": circuit.recipe, + "topology_hash": topology, + "inputs": list(circuit.inputs), + "outputs": list(circuit.outputs), + "nets": sorted(nets), + "components": components, + "truth_table": circuit.truth_table(), + } + + +def yolo_label(annotation: dict) -> str: + """ + YOLO label text: one line per symbol and junction dot, normalised center/size. + + Args: + annotation: Render annotation. + Returns: + Label file content. + """ + w, h = annotation["image"]["width"], annotation["image"]["height"] + rows = [(s["class_id"], s["bbox"]) for s in annotation["symbols"]] + rows += [(CLASS_ID["JUNCTION"], j["bbox"]) for j in annotation["junctions"]] + lines = [] + for cid, (x1, y1, x2, y2) in rows: + lines.append(f"{cid} {(x1 + x2) / 2 / w:.6f} {(y1 + y2) / 2 / h:.6f} {(x2 - x1) / w:.6f} {(y2 - y1) / h:.6f}") + return "\n".join(lines) + "\n" + + +def generate_sample(seed: int, index: int) -> Sample: + """ + Generate one sample; depends only on (seed, index). + + Args: + seed: Global seed. + index: Sample index. + Returns: + The generated Sample. + """ + rng = np.random.default_rng([seed, index]) + names = [d for d, _ in DOMAIN_WEIGHTS] + weights = np.array([w for _, w in DOMAIN_WEIGHTS]) + domain = names[int(rng.choice(len(names), p=weights / weights.sum()))] + while True: + circuit = sample_circuit(rng, domain) + topology = topology_hash(circuit) + split = split_for(topology) + held_out = split == "test" and bool(rng.random() < HELD_OUT_FRACTION) + draw_style = sample_draw_style(rng, domain, held_out) + try: + layout = build_layout(circuit, draw_style, rng) + except LayoutError: + continue + break + style = sample_render_style(rng, layout, held_out) + image, annotation = render(layout, style, rng) + sample_id = f"{index:06d}" + annotation = {"id": sample_id, "split": split, "domain": domain, "held_out_style": held_out, **annotation} + netlist = build_netlist(circuit, annotation, topology) + return Sample(index, sample_id, split, domain, circuit.recipe, topology, held_out, image, yolo_label(annotation), annotation, netlist) + + +def _dumps(obj: object) -> bytes: + """ + Canonical JSON encoding (sorted keys, fixed separators) for reproducible bytes. + + Args: + obj: JSON-serialisable object. + Returns: + UTF-8 bytes with a trailing newline. + """ + return (json.dumps(obj, sort_keys=True, separators=(",", ":")) + "\n").encode() + + +def _write(path: Path, data: bytes) -> str: + """ + Write bytes and return their SHA-256. + + Args: + path: Destination file. + data: Content. + Returns: + Hex digest. + """ + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return hashlib.sha256(data).hexdigest() + + +def write_sample(out: Path, sample: Sample) -> dict: + """ + Write a sample's four files and return its manifest entry. + + Args: + out: Dataset root. + sample: Generated sample. + Returns: + Manifest entry with relative paths and SHA-256 per file. + """ + rel = { + "image": f"images/{sample.split}/{sample.sample_id}.jpg", + "label": f"labels/{sample.split}/{sample.sample_id}.txt", + "annotation": f"annotations/{sample.split}/{sample.sample_id}.json", + "netlist": f"netlists/{sample.split}/{sample.sample_id}.json", + } + payloads = { + "image": sample.image, + "label": sample.label.encode(), + "annotation": _dumps(sample.annotation), + "netlist": _dumps(sample.netlist), + } + files = {k: {"path": rel[k], "sha256": _write(out / rel[k], payloads[k])} for k in rel} + return { + "id": sample.sample_id, + "split": sample.split, + "domain": sample.domain, + "recipe": sample.recipe, + "topology_hash": sample.topology, + "held_out_style": sample.held_out, + "files": files, + } + + +def balance_report(annotations: list[dict]) -> dict: + """ + Per-domain (and per-split) class instance counts with the 10%-of-max balance rule. + + Args: + annotations: Annotation dicts (need "domain", "split", "symbols", "junctions"). + Returns: + Report dict with counts, ratios, pass flags and junction dot size statistics. + """ + report: dict = {"rule": f"no class under {BALANCE_MIN_RATIO:.0%} of the most frequent class, per domain", "domains": {}} + for domain, classes in DOMAIN_CLASSES.items(): + subset = [a for a in annotations if a["domain"] == domain] + counts = Counter() + per_split: dict[str, Counter] = {s: Counter() for s in SPLITS} + for a in subset: + c = Counter(s["class"] for s in a["symbols"]) + c["JUNCTION"] += len(a["junctions"]) + counts.update(c) + per_split[a["split"]].update(c) + biggest = max([counts[c] for c in classes] + [1]) + ratios = {c: round(counts[c] / biggest, 4) for c in classes} + report["domains"][domain] = { + "images": len(subset), + "counts": {c: counts[c] for c in classes}, + "ratio_to_max": ratios, + "passes": all(r >= BALANCE_MIN_RATIO for r in ratios.values()) and bool(subset), + "per_split": {s: {c: per_split[s][c] for c in classes} for s in SPLITS}, + "images_per_split": {s: sum(1 for a in subset if a["split"] == s) for s in SPLITS}, + } + dots = [j["diameter"] * 1000.0 / a["image"]["width"] for a in annotations for j in a["junctions"]] + report["junction_dot_diameter_per_1000px"] = { + "target": [DOT_MIN_PER_1000, DOT_MAX_PER_1000], + "count": len(dots), + "min": round(min(dots), 3) if dots else None, + "max": round(max(dots), 3) if dots else None, + "mean": round(float(np.mean(dots)), 3) if dots else None, + } + return report + + +def _worker(args: tuple[int, int]) -> Sample: + """ + Pool entry point. + + Args: + args: (seed, index). + Returns: + Generated sample. + """ + return generate_sample(*args) + + +def _init_worker() -> None: + """Keep each worker single-threaded (OpenCV and BLAS).""" + import cv2 + + cv2.setNumThreads(1) + + +def generate_dataset(out: Path, count: int, seed: int, workers: int = 1) -> dict: + """ + Generate a whole dataset and write manifest.json, balance_report.json and data.yaml. + + Args: + out: Output root (created). + count: Number of samples. + seed: Global seed. + workers: Worker processes (output does not depend on it). + Returns: + The manifest dict. + """ + out.mkdir(parents=True, exist_ok=True) + entries: list[dict] = [] + annotations: list[dict] = [] + jobs = [(seed, i) for i in range(count)] + + def consume(sample: Sample) -> None: + """Write one sample and collect its manifest entry and annotation.""" + entries.append(write_sample(out, sample)) + annotations.append(sample.annotation) + + if workers > 1: + with Pool(workers, initializer=_init_worker) as pool: + for sample in pool.imap(_worker, jobs, chunksize=8): + consume(sample) + else: + _init_worker() + for job in jobs: + consume(_worker(job)) + manifest = { + "generator": "backend/data_gen/generate_v2.py", + "version": GENERATOR_VERSION, + "seed": seed, + "count": count, + "classes": list(TIER_A), + "schema_version": SCHEMA_VERSION, + "splits": {s: sum(1 for e in entries if e["split"] == s) for s in SPLITS}, + "held_out_style_samples": sum(1 for e in entries if e["held_out_style"]), + "samples": entries, + } + (out / "manifest.json").write_bytes(_dumps(manifest)) + (out / "balance_report.json").write_bytes(_dumps(balance_report(annotations))) + (out / "data.yaml").write_text(render_data_yaml(SCHEMA, out)) + return manifest + + +def main(argv: list[str] | None = None) -> int: + """ + CLI entry point. + + Args: + argv: Arguments (defaults to sys.argv). + Returns: + Process exit code. + """ + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--count", type=int, default=8000) + parser.add_argument("--seed", type=int, default=1) + parser.add_argument("--out", type=Path, default=DEFAULT_OUT) + parser.add_argument("--workers", type=int, default=min(4, os.cpu_count() or 1), help="worker processes (default min(4, cpus))") + args = parser.parse_args(argv) + manifest = generate_dataset(args.out, args.count, args.seed, args.workers) + report = json.loads((args.out / "balance_report.json").read_text()) + print(f"wrote {manifest['count']} samples to {args.out} splits={manifest['splits']} held_out_style={manifest['held_out_style_samples']}") + for domain, info in report["domains"].items(): + worst = min(info["ratio_to_max"], key=info["ratio_to_max"].get) + print(f" {domain:10s} images={info['images']:5d} passes={info['passes']} min_ratio={info['ratio_to_max'][worst]:.3f} ({worst}) counts={info['counts']}") + print(f" junction dot diameter per 1000 px: {report['junction_dot_diameter_per_1000px']}") + print(f" manifest sha256: {hashlib.sha256((args.out / 'manifest.json').read_bytes()).hexdigest()}") + return 0 if all(info["passes"] for info in report["domains"].values()) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/data_gen/synth_v2/__init__.py b/backend/data_gen/synth_v2/__init__.py new file mode 100644 index 0000000..938efb6 --- /dev/null +++ b/backend/data_gen/synth_v2/__init__.py @@ -0,0 +1,6 @@ +""" +Module: __init__.py +Purpose: Synthetic circuit dataset generator v2 (netlist-driven topologies, textbook and + hand-drawn rendering, exact boxes, pins, orientation and netlists). Entry point is + backend/data_gen/generate_v2.py. +""" diff --git a/backend/data_gen/synth_v2/contact_sheet.py b/backend/data_gen/synth_v2/contact_sheet.py new file mode 100644 index 0000000..3823fc5 --- /dev/null +++ b/backend/data_gen/synth_v2/contact_sheet.py @@ -0,0 +1,141 @@ +""" +Module: contact_sheet.py +Purpose: Visual QA for the v2 synthetic dataset. Draws every label of a sample on its image + (class boxes, pin points with terminal names, junction boxes, crossings) and tiles + randomly chosen overlays into one contact sheet JPEG, so a reviewer can check that + boxes, pins and dots match the drawing. + +Usage: + cd backend && uv run python data_gen/synth_v2/contact_sheet.py --data DIR --out sheet.jpg --samples 50 --seed 1 +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import cv2 +import numpy as np + +# One distinct BGR colour per tier-A class (index = YOLO id). +PALETTE: tuple[tuple[int, int, int], ...] = ( + (40, 40, 230), + (230, 60, 40), + (0, 140, 255), + (120, 80, 0), + (0, 170, 0), + (170, 0, 170), + (0, 0, 0), + (200, 120, 0), + (0, 120, 200), + (120, 0, 200), + (60, 160, 160), + (160, 60, 120), + (90, 90, 200), + (40, 120, 90), +) + + +def overlay(image: np.ndarray, annotation: dict) -> np.ndarray: + """ + Draw labels of one sample onto a copy of its image. + + Args: + image: BGR image. + annotation: Annotation JSON of the sample. + Returns: + Annotated BGR image. + """ + out = image.copy() + scale = max(1, round(image.shape[1] / 900)) + for sym in annotation["symbols"]: + color = PALETTE[sym["class_id"] % len(PALETTE)] + x1, y1, x2, y2 = (int(round(v)) for v in sym["bbox"]) + cv2.rectangle(out, (x1, y1), (x2, y2), color, scale) + cv2.putText(out, sym["class"], (x1, max(10, y1 - 3)), cv2.FONT_HERSHEY_SIMPLEX, 0.4 * scale, color, scale, cv2.LINE_AA) + for term, (px, py) in sym["pins"].items(): + cv2.circle(out, (int(round(px)), int(round(py))), 3 * scale, (0, 200, 255), -1, cv2.LINE_AA) + cv2.putText(out, term, (int(px) + 4, int(py) - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.35 * scale, (0, 120, 255), scale, cv2.LINE_AA) + for j in annotation["junctions"]: + x1, y1, x2, y2 = (int(round(v)) for v in j["bbox"]) + cv2.rectangle(out, (x1 - 1, y1 - 1), (x2 + 1, y2 + 1), (0, 0, 255), scale) + for c in annotation["crossings"]: + x, y = (int(round(v)) for v in c["point"]) + cv2.drawMarker(out, (x, y), (255, 0, 255), cv2.MARKER_TILTED_CROSS, 8 * scale, scale) + return out + + +def contact_sheet(data: Path, out: Path, samples: int, seed: int, cols: int = 5, tile_w: int = 420) -> list[str]: + """ + Tile overlays of randomly chosen samples into one JPEG. + + Args: + data: Dataset root (with manifest.json). + out: Output JPEG path. + samples: Number of samples to show. + seed: Selection seed. + cols: Tiles per row. + tile_w: Tile width in pixels. + Returns: + IDs of the samples shown. + """ + manifest = json.loads((data / "manifest.json").read_text()) + entries = manifest["samples"] + rng = np.random.default_rng(seed) + chosen = sorted(rng.choice(len(entries), size=min(samples, len(entries)), replace=False).tolist()) + tiles: list[np.ndarray] = [] + for i in chosen: + e = entries[i] + img = cv2.imread(str(data / e["files"]["image"]["path"])) + ann = json.loads((data / e["files"]["annotation"]["path"]).read_text()) + ov = overlay(img, ann) + # Fit into a square tile so tall (rotated) drawings do not stretch the sheet. + scale = min(tile_w / ov.shape[1], tile_w / ov.shape[0]) + fw, fh = max(1, int(round(ov.shape[1] * scale))), max(1, int(round(ov.shape[0] * scale))) + fitted = cv2.resize(ov, (fw, fh), interpolation=cv2.INTER_AREA) + tile = np.full((tile_w, tile_w, 3), 235, dtype=np.uint8) + y0, x0 = (tile_w - fh) // 2, (tile_w - fw) // 2 + tile[y0 : y0 + fh, x0 : x0 + fw] = fitted + caption = f"{e['id']} {e['split']} {e['domain']} {e['recipe']} {ann['render_style']['mode']}{' HELD-OUT' if e['held_out_style'] else ''}" + bar = np.full((18, tile_w, 3), 255, dtype=np.uint8) + cv2.putText(bar, caption, (4, 13), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (0, 0, 0), 1, cv2.LINE_AA) + tiles.append(np.vstack([bar, tile])) + rows = [] + for r in range(0, len(tiles), cols): + row_tiles = tiles[r : r + cols] + row_h = max(t.shape[0] for t in row_tiles) + padded = [np.vstack([t, np.full((row_h - t.shape[0], tile_w, 3), 235, dtype=np.uint8)]) for t in row_tiles] + padded += [np.full((row_h, tile_w, 3), 235, dtype=np.uint8)] * (cols - len(row_tiles)) + rows.append(np.hstack([np.pad(t, ((2, 2), (2, 2), (0, 0)), constant_values=200) for t in padded])) + sheet = np.vstack(rows) + out.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(out), sheet, [cv2.IMWRITE_JPEG_QUALITY, 82]) + return [entries[i]["id"] for i in chosen] + + +def main(argv: list[str] | None = None) -> int: + """ + CLI entry point. + + Args: + argv: Arguments (defaults to sys.argv). + Returns: + Process exit code. + """ + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--data", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--samples", type=int, default=50) + parser.add_argument("--seed", type=int, default=1) + parser.add_argument("--cols", type=int, default=5) + parser.add_argument("--tile-width", type=int, default=420) + args = parser.parse_args(argv) + ids = contact_sheet(args.data, args.out, args.samples, args.seed, args.cols, args.tile_width) + print(f"wrote {args.out} with {len(ids)} samples") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/data_gen/synth_v2/layout.py b/backend/data_gen/synth_v2/layout.py new file mode 100644 index 0000000..a6142ab --- /dev/null +++ b/backend/data_gen/synth_v2/layout.py @@ -0,0 +1,549 @@ +""" +Module: layout.py +Purpose: Places the symbols of a sampled circuit on an integer grid the way a textbook would + draw it, then routes every net with the grid router. Transistor circuits use the + classic CMOS picture (pull-up network on top, pull-down below, series stacks vertical, + parallel branches side by side, transmission gates horizontal); gate circuits use a + left-to-right layered layout. Supply symbols (shared rail, per stage or per device) + and I/O port symbols are added here, and an optional global rotation/mirror varies + symbol orientation. The result is an exact geometric netlist ready for rendering. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field, replace + +import numpy as np + +from .logic import GND_NET, VDD_NET, Circuit, SPNode, Stage +from .router import GridRouter, RoutedNet, RoutingError +from .symbols import GridPoint, compose_orientation, orient_grid, orient_points, orientation_for, symbol_geometry + +BORDER = 5 +MAX_GRID = 84 +# Symbol variant reserved for held-out-style test samples (never drawn in train/valid). +HELD_OUT_VDD_VARIANT = "circle" + + +class LayoutError(Exception): + """Raised when a circuit cannot be laid out or routed within the size limits.""" + + +@dataclass +class PlacedSymbol: + """One symbol instance on the grid with its orientation and terminal-to-net map.""" + + comp_id: str + cls: str + variant: str + rotation: int + mirror: bool + anchor: GridPoint + nets: dict[str, str] + label: str = "" + + def pins(self) -> dict[str, GridPoint]: + """ + World grid position of every pin. + + Returns: + Terminal name to grid point. + """ + geom = symbol_geometry(self.cls, self.variant) + out = {} + for name, p in geom.pins.items(): + dx, dy = orient_grid(p, self.rotation, self.mirror) + out[name] = (self.anchor[0] + dx, self.anchor[1] + dy) + return out + + def pin_dirs(self) -> dict[str, GridPoint]: + """ + World outward direction of every pin. + + Returns: + Terminal name to unit direction. + """ + geom = symbol_geometry(self.cls, self.variant) + return {name: orient_grid(d, self.rotation, self.mirror) for name, d in geom.pin_dirs.items()} + + def world_points(self) -> np.ndarray: + """ + All stroke and fill vertices in world grid units (float). + + Returns: + Nx2 array. + """ + geom = symbol_geometry(self.cls, self.variant) + pts = np.concatenate(list(geom.strokes) + list(geom.fills), axis=0) + return orient_points(pts, self.rotation, self.mirror) + np.array(self.anchor, dtype=np.float64) + + def footprint(self) -> tuple[int, int, int, int]: + """ + Inclusive integer bounds of the drawing (pins lie on the boundary). + + Returns: + (x0, y0, x1, y1). + """ + pts = self.world_points() + lo = np.floor(pts.min(axis=0) + 1e-9).astype(int) + hi = np.ceil(pts.max(axis=0) - 1e-9).astype(int) + return int(lo[0]), int(lo[1]), int(hi[0]), int(hi[1]) + + def transformed(self, rotation: int, mirror: bool) -> PlacedSymbol: + """ + Copy of the symbol after a global orientation about the grid origin. + + Args: + rotation: Global rotation in degrees clockwise. + mirror: Global mirror applied before the rotation. + Returns: + New PlacedSymbol. + """ + rot, mir = compose_orientation((self.rotation, self.mirror), (rotation, mirror)) + return replace(self, rotation=rot, mirror=mir, anchor=orient_grid(self.anchor, rotation, mirror)) + + +@dataclass +class Layout: + """Placed and routed drawing in grid units.""" + + domain: str + symbols: list[PlacedSymbol] + width: int + height: int + nets: list[RoutedNet] = field(default_factory=list) + key_net: dict[int, str] = field(default_factory=dict) + crossings: list[tuple[GridPoint, str, str]] = field(default_factory=list) + global_orientation: tuple[int, bool] = (0, False) + + +@dataclass +class DrawStyle: + """Layout-level style choices (symbol variants, supply style, spacing).""" + + nmos: str = "plain3" + pmos: str = "bubble3" + vdd: str = "bar" + gnd: str = "bars" + in_port: str = "tag" + out_port: str = "tag" + gate: str = "ansi" + supply: str = "shared" # shared | per_stage | per_device + mirror_transistors: bool = False + global_rotation: int = 0 + global_mirror: bool = False + + +def sample_draw_style(rng: np.random.Generator, domain: str, held_out: bool) -> DrawStyle: + """ + Sample consistent per-image symbol variants and layout options. + + Args: + rng: Random generator. + domain: "transistor" or "gate". + held_out: Use the held-out VDD symbol variant (test split only); otherwise never use it. + Returns: + DrawStyle. + """ + pairs = (("plain3", "bubble3"), ("arrow3", "arrow3"), ("dashed3", "bubble3"), ("plain3", "arrow3"), ("body4", "body4"), ("body4", "bubble4")) + weights = np.array([0.3, 0.15, 0.1, 0.1, 0.2, 0.15]) + nmos, pmos = pairs[int(rng.choice(len(pairs), p=weights / weights.sum()))] + style = DrawStyle( + nmos=nmos, + pmos=pmos, + vdd=HELD_OUT_VDD_VARIANT if held_out else ("bar", "arrow")[int(rng.integers(0, 2))], + gnd=("bars", "triangle", "filled")[int(rng.integers(0, 3))], + in_port=("tag", "arrow")[int(rng.integers(0, 2))], + out_port=("tag", "arrow")[int(rng.integers(0, 2))], + gate="iec" if rng.random() < 0.15 else "ansi", + supply=("shared", "per_stage", "per_device")[int(rng.choice(3, p=[0.3, 0.2, 0.5]))], + mirror_transistors=bool(rng.random() < 0.3), + ) + p_rot = 0.2 if domain == "transistor" else 0.1 + if rng.random() < p_rot: + style.global_rotation = int(rng.choice([90, 180, 270])) + style.global_mirror = bool(rng.random() < 0.5) + return style + + +# --------------------------------------------------------------------------------------------- +# Transistor-level placement +# --------------------------------------------------------------------------------------------- + + +def _place_sp(node: SPNode, mirror: bool) -> tuple[list[tuple[str, int, int]], int, int, bool, bool]: + """ + Recursive textbook placement of a series-parallel network. + + Leaves are 4 columns by 4 rows (top pin row 0, bottom pin row 4). Series children stack + vertically, parallel children sit side by side with routing channels between them. + + Args: + node: Series-parallel tree. + mirror: Whether transistors are mirrored (gate on the right). + Returns: + (items as (device_id, anchor_x, anchor_y), width, bottom_row, top_is_multi, bottom_is_multi). + """ + if node.kind == "leaf": + return [(node.device_id, 1 if mirror else 2, 2)], 4, 4, False, False + placed = [_place_sp(child, mirror) for child in node.children] + items: list[tuple[str, int, int]] = [] + if node.kind == "series": + width = max(p[1] for p in placed) + y = 0 + for i, (sub, w, h, _, bm) in enumerate(placed): + dx = (width - w) // 2 + items += [(d, x + dx, yy + y) for d, x, yy in sub] + if i + 1 < len(placed): + y += h + (4 if bm or placed[i + 1][3] else 2) + else: + y += h + return items, width, y, placed[0][3], placed[-1][4] + x = 0 + for sub, w, _, _, _ in placed: + items += [(d, xx + x, yy) for d, xx, yy in sub] + x += w + 4 + return items, x - 4, max(p[2] for p in placed), True, True + + +def _layout_transistor(circuit: Circuit, style: DrawStyle, rng: np.random.Generator) -> list[PlacedSymbol]: + """ + Place transistors, ports and supplies for a CMOS circuit (canonical frame, before global transform). + + Args: + circuit: Transistor-domain circuit with devices. + style: Drawing style. + rng: Random generator. + Returns: + Placed symbols. + """ + devs = {d.id: d for d in circuit.devices} + symbols: list[PlacedSymbol] = [] + mirror = style.mirror_transistors + stage_x = 0 + mid_rows: dict[str, int] = {} + stage_bounds: list[tuple[int, int, int]] = [] + body = style.nmos == "body4" + + def add_mos(dev_id: str, ax: int, ay: int, rotation: int, mir: bool) -> None: + """Add one transistor symbol, wiring its bulk to the matching supply when drawn.""" + dev = devs[dev_id] + variant = style.nmos if dev.cls == "NMOS" else style.pmos + nets = dict(dev.pins) + if variant in ("body4", "bubble4"): + nets["b"] = GND_NET if dev.cls == "NMOS" else VDD_NET + symbols.append(PlacedSymbol(dev_id, dev.cls, variant, rotation, mir, (ax, ay), nets)) + + for stage in circuit.stages: + if stage.kind == "cmos": + pun = _place_sp(stage.pun, mirror) + pdn = _place_sp(stage.pdn, mirror) + width = max(pun[1], pdn[1]) + y_pdn = pun[2] + 6 + for items, y0, w in ((pun[0], 0, pun[1]), (pdn[0], y_pdn, pdn[1])): + dx = stage_x + (width - w) // 2 + for dev_id, x, y in items: + add_mos(dev_id, x + dx, y + y0, 0, mirror) + mid_rows[stage.out] = pun[2] + 3 + height = y_pdn + pdn[2] + else: + _place_tg_mux(stage, stage_x, body, add_mos) + width = 5 + s = 6 if body else 4 + mid_rows[stage.out] = 2 + s + 4 + height = 2 + 2 * s + 8 + 2 + stage_bounds.append((stage_x, width, height)) + stage_x += width + 7 + + total_h = max(b[2] for b in stage_bounds) + in_variant, out_variant = style.in_port, style.out_port + n_in = len(circuit.inputs) + rows = _spread_rows(n_in, 2, total_h - 2, 3) + order = list(range(n_in)) + for name, row in zip([circuit.inputs[i] for i in order], rows): + symbols.append(PlacedSymbol(f"IN_{name}", "INPUT_PORT", in_variant, 0, False, (-6, row), {"out": name}, label=name)) + right = stage_x - 7 + 6 + used_rows: list[int] = [] + for name in circuit.outputs: + row = mid_rows.get(name, total_h // 2) + while any(abs(row - r) < 3 for r in used_rows): + row += 3 + used_rows.append(row) + symbols.append(PlacedSymbol(f"OUT_{name}", "OUTPUT_PORT", out_variant, 0, False, (right, row), {"a": name}, label=name)) + _add_supplies(symbols, style, stage_bounds, rng) + return symbols + + +def _place_tg_mux(stage: Stage, x0: int, body: bool, add_mos: Callable[[str, int, int, int, bool], None]) -> None: + """ + Place the four transistors of a transmission-gate 2:1 mux as two horizontal TGs. + + Each TG is an NMOS (gate up) above a PMOS (gate down); sources face left (data), drains + face right (output). + + Args: + stage: The tg_mux stage (tg_devices = [N_A, P_A, N_B, P_B]). + x0: Left column of the stage. + body: Whether 4-terminal symbols are drawn (needs more vertical room). + add_mos: Callback (device_id, x, y, rotation, mirror) that adds a transistor. + """ + s = 6 if body else 4 + cx = x0 + 2 + n_rot = orientation_for("NMOS", "plain3", "g", (0, -1)) + p_rot = orientation_for("PMOS", "bubble3", "g", (0, 1)) + y_a = 2 + y_b = y_a + s + 8 + n_a, p_a, n_b, p_b = stage.tg_devices + add_mos(n_a, cx, y_a, n_rot, False) + add_mos(p_a, cx, y_a + s, p_rot, False) + add_mos(n_b, cx, y_b, n_rot, False) + add_mos(p_b, cx, y_b + s, p_rot, False) + + +def _spread_rows(n: int, lo: int, hi: int, min_gap: int) -> list[int]: + """ + Evenly spread n rows over [lo, hi] keeping a minimum gap. + + Args: + n: Number of rows. + lo: Lowest row. + hi: Highest row. + min_gap: Minimum distance between consecutive rows. + Returns: + Sorted list of rows. + """ + span = max(hi - lo, (n - 1) * min_gap) + if n == 1: + return [lo + span // 2] + return [lo + round(i * span / (n - 1)) for i in range(n)] + + +def _cells(footprint: tuple[int, int, int, int], ring: int = 1) -> set[GridPoint]: + """ + Grid cells covered by a footprint plus a ring. + + Args: + footprint: (x0, y0, x1, y1). + ring: Ring width. + Returns: + Set of cells. + """ + x0, y0, x1, y1 = footprint + return {(x, y) for x in range(x0 - ring, x1 + ring + 1) for y in range(y0 - ring, y1 + ring + 1)} + + +def _add_supplies(symbols: list[PlacedSymbol], style: DrawStyle, stage_bounds: list[tuple[int, int, int]], rng: np.random.Generator) -> None: + """ + Add VDD and GND symbols in the chosen supply style. + + Args: + symbols: Placed symbols (extended in place). + style: Drawing style (supply style and variants). + stage_bounds: (x, width, height) per stage. + rng: Random generator. + """ + occupied: set[GridPoint] = set() + for sym in symbols: + occupied |= _cells(sym.footprint()) + top = min(sym.footprint()[1] for sym in symbols) + bottom = max(sym.footprint()[3] for sym in symbols) + for net, cls, variant, out_dir in ((VDD_NET, "VDD", style.vdd, (0, -1)), (GND_NET, "GND", style.gnd, (0, 1))): + pin_name = "pos" if cls == "VDD" else "gnd" + supply_pins: list[GridPoint] = [] + facing: list[GridPoint] = [] + for sym in symbols: + dirs = sym.pin_dirs() + for term, p in sym.pins().items(): + if sym.nets.get(term) == net: + supply_pins.append(p) + if dirs[term] == out_dir: + facing.append(p) + if not supply_pins: + continue + anchors: list[GridPoint] = [] + if style.supply == "per_device": + for px, py in sorted(facing): + cand = (px, py + 3 * out_dir[1]) + sym = PlacedSymbol("", cls, variant, 0, False, cand, {pin_name: net}) + cells = _cells(sym.footprint()) + if not cells & occupied: + anchors.append(cand) + occupied |= cells + elif style.supply == "per_stage": + for x, w, _ in stage_bounds: + in_stage = [p for p in (facing or supply_pins) if x <= p[0] < x + w] + if in_stage: + px = sorted(in_stage)[0][0] + anchors.append((px, top - 4 if cls == "VDD" else bottom + 4)) + if not anchors: + px = sorted(facing or supply_pins)[0][0] + anchors.append((px, top - 4 if cls == "VDD" else bottom + 4)) + for i, a in enumerate(anchors): + symbols.append(PlacedSymbol(f"{cls}{i + 1}", cls, variant, 0, False, a, {pin_name: net}, label=cls)) + + +# --------------------------------------------------------------------------------------------- +# Gate-level placement +# --------------------------------------------------------------------------------------------- + + +def _layout_gate(circuit: Circuit, style: DrawStyle, rng: np.random.Generator) -> list[PlacedSymbol]: + """ + Layered left-to-right placement of a gate-level DAG with ports. + + Args: + circuit: Gate-domain circuit. + style: Drawing style. + rng: Random generator. + Returns: + Placed symbols. + """ + depth: dict[str, int] = {s: 0 for s in circuit.inputs} + for dev in circuit.devices: + depth[dev.pins["out"]] = 1 + max(depth[dev.pins[t]] for t in ("a", "b") if t in dev.pins) + max_d = max(depth.values()) + colw = int(rng.integers(10, 13)) + si = int(rng.integers(4, 7)) + sg = int(rng.integers(7, 10)) + row: dict[str, float] = {} + symbols: list[PlacedSymbol] = [] + for i, name in enumerate(circuit.inputs): + row[name] = i * si + symbols.append(PlacedSymbol(f"IN_{name}", "INPUT_PORT", style.in_port, 0, False, (0, i * si), {"out": name}, label=name)) + for d in range(1, max_d + 1): + col = [dev for dev in circuit.devices if depth[dev.pins["out"]] == d] + bary = {dev.id: float(np.mean([row[dev.pins[t]] for t in ("a", "b") if t in dev.pins])) + rng.uniform(-1, 1) for dev in col} + col.sort(key=lambda dev: (bary[dev.id], dev.id)) + start = round(float(np.mean(list(bary.values()))) - (len(col) - 1) * sg / 2) + for i, dev in enumerate(col): + r = start + i * sg + row[dev.pins["out"]] = r + symbols.append(PlacedSymbol(dev.id, dev.cls, style.gate, 0, False, (d * colw, r), dict(dev.pins))) + out_x = max_d * colw + 9 + for name in circuit.outputs: + symbols.append(PlacedSymbol(f"OUT_{name}", "OUTPUT_PORT", style.out_port, 0, False, (out_x, int(row[name])), {"a": name}, label=name)) + return symbols + + +# --------------------------------------------------------------------------------------------- +# Routing +# --------------------------------------------------------------------------------------------- + + +def build_layout(circuit: Circuit, style: DrawStyle, rng: np.random.Generator) -> Layout: + """ + Place, orient, normalise and route a circuit. + + Args: + circuit: Sampled circuit with devices. + style: Drawing style. + rng: Random generator. + Returns: + Fully routed Layout. + Raises: + LayoutError: If the drawing exceeds MAX_GRID or cannot be routed. + """ + if circuit.domain == "transistor": + symbols = _layout_transistor(circuit, style, rng) + else: + symbols = _layout_gate(circuit, style, rng) + rot, mir = style.global_rotation, style.global_mirror + if rot or mir: + symbols = [s.transformed(rot, mir) for s in symbols] + fps = [s.footprint() for s in symbols] + min_x = min(f[0] for f in fps) + min_y = min(f[1] for f in fps) + shift = (BORDER - min_x, BORDER - min_y) + symbols = [replace(s, anchor=(s.anchor[0] + shift[0], s.anchor[1] + shift[1])) for s in symbols] + fps = [s.footprint() for s in symbols] + width = max(f[2] for f in fps) + BORDER + 1 + height = max(f[3] for f in fps) + BORDER + 1 + if width > MAX_GRID or height > MAX_GRID: + raise LayoutError(f"layout {width}x{height} exceeds {MAX_GRID}") + layout = Layout(circuit.domain, symbols, width, height, global_orientation=(rot, mir)) + _route(layout, rng) + return layout + + +def _drawn_nets(symbols: list[PlacedSymbol]) -> tuple[dict[tuple[str, str], int], dict[int, str], dict[int, list[GridPoint]]]: + """ + Split logical nets into drawn nets (one per supply symbol for supply nets). + + Args: + symbols: Placed symbols. + Returns: + (pin (comp_id, terminal) -> key, key -> logical net, key -> pin points with the root first). + """ + supply_syms = [s for s in symbols if s.cls in ("VDD", "GND")] + key_of_net: dict[str, int] = {} + key_net: dict[int, str] = {} + pin_key: dict[tuple[str, str], int] = {} + key_pins: dict[int, list[GridPoint]] = {} + sym_key: dict[str, int] = {} + for s in supply_syms: + k = len(key_net) + key_net[k] = next(iter(s.nets.values())) + sym_key[s.comp_id] = k + for sym in symbols: + pins = sym.pins() + for term, net in sorted(sym.nets.items()): + p = pins[term] + if sym.comp_id in sym_key: + k = sym_key[sym.comp_id] + elif net in (VDD_NET, GND_NET): + cands = [s for s in supply_syms if next(iter(s.nets.values())) == net] + best = min(cands, key=lambda s: (abs(s.pins()[next(iter(s.nets))][0] - p[0]) + abs(s.pins()[next(iter(s.nets))][1] - p[1]), s.comp_id)) + k = sym_key[best.comp_id] + else: + if net not in key_of_net: + key_of_net[net] = len(key_net) + key_net[key_of_net[net]] = net + k = key_of_net[net] + pin_key[(sym.comp_id, term)] = k + key_pins.setdefault(k, []) + if sym.comp_id in sym_key or sym.cls in ("INPUT_PORT",): + key_pins[k].insert(0, p) + else: + key_pins[k].append(p) + return pin_key, key_net, key_pins + + +def _route(layout: Layout, rng: np.random.Generator) -> None: + """ + Route every drawn net; retries with shuffled net orders before giving up. + + Args: + layout: Layout to fill with nets and crossings. + rng: Random generator. + Raises: + LayoutError: When routing fails for every attempted order. + """ + pin_key, key_net, key_pins = _drawn_nets(layout.symbols) + single = [k for k, pins in key_pins.items() if len(pins) < 2] + if single: + raise LayoutError("net with a single pin") + + def span(k: int) -> int: + """Half-perimeter of a drawn net's pin bounding box.""" + xs = [p[0] for p in key_pins[k]] + ys = [p[1] for p in key_pins[k]] + return (max(xs) - min(xs)) + (max(ys) - min(ys)) + + base_order = sorted(key_pins, key=lambda k: (span(k), k)) + for attempt in range(4): + order = base_order if attempt == 0 else [base_order[i] for i in rng.permutation(len(base_order))] + router = GridRouter(layout.width, layout.height) + try: + for sym in layout.symbols: + pins, dirs = sym.pins(), sym.pin_dirs() + router.add_symbol(sym.footprint(), [(pins[t], dirs[t], pin_key[(sym.comp_id, t)]) for t in sorted(sym.nets)]) + for k in order: + router.route_net(k, [router.idx(x, y) for x, y in key_pins[k]]) + except RoutingError: + continue + layout.nets = [router.extract(k) for k in sorted(key_pins)] + layout.key_net = key_net + layout.crossings = [(p, key_net[a], key_net[b]) for p, a, b in router.crossings()] + return + raise LayoutError("routing failed") diff --git a/backend/data_gen/synth_v2/logic.py b/backend/data_gen/synth_v2/logic.py new file mode 100644 index 0000000..c688252 --- /dev/null +++ b/backend/data_gen/synth_v2/logic.py @@ -0,0 +1,687 @@ +""" +Module: logic.py +Purpose: Netlist-driven topology sampler for the synthetic dataset. Samples valid circuits + (static CMOS cells built from series-parallel pull-down/pull-up networks, transmission + gate muxes, multi-stage compositions, and gate-level DAGs), expands them into logical + devices with exact pin-to-net assignments, computes the reference truth table from the + abstract boolean function, and hashes the topology so dataset splits never share a + circuit. The renderer consumes the series-parallel trees to lay out textbook CMOS. +""" + +from __future__ import annotations + +import hashlib +import itertools +from dataclasses import dataclass, field + +import networkx as nx +import numpy as np + +# A boolean expression over named signals: ("var", name) | ("and", [e, ...]) | ("or", [e, ...]). +Expr = tuple + +GATE_KINDS: tuple[str, ...] = ("AND", "OR", "NOT", "NAND", "NOR", "XOR", "XNOR") +VDD_NET = "VDD" +GND_NET = "GND" +MAX_TRANSISTORS = 14 +MAX_INPUTS = 4 + + +def var(name: str) -> Expr: + """ + Build a literal expression. + + Args: + name: Signal (net) name. + Returns: + The ("var", name) expression. + """ + return ("var", name) + + +def eval_expr(expr: Expr, env: dict[str, int]) -> int: + """ + Evaluate a positive AND/OR expression. + + Args: + expr: Expression tree. + env: Signal values (0/1) by name. + Returns: + 0 or 1. + Raises: + ValueError: If the expression kind is unknown. + """ + kind = expr[0] + if kind == "var": + return env[expr[1]] + if kind == "and": + return int(all(eval_expr(e, env) for e in expr[1])) + if kind == "or": + return int(any(eval_expr(e, env) for e in expr[1])) + raise ValueError(f"unknown expression kind {kind!r}") + + +def expr_literals(expr: Expr) -> list[str]: + """ + Signals used by an expression, in first-use order. + + Args: + expr: Expression tree. + Returns: + Distinct literal names. + """ + if expr[0] == "var": + return [expr[1]] + out: list[str] = [] + for child in expr[1]: + for name in expr_literals(child): + if name not in out: + out.append(name) + return out + + +def _flatten(expr: Expr) -> Expr: + """ + Merge nested operators of the same kind (and(and(a,b),c) -> and(a,b,c)). + + Args: + expr: Expression tree. + Returns: + Equivalent flattened expression. + """ + if expr[0] == "var": + return expr + kids: list[Expr] = [] + for child in expr[1]: + flat = _flatten(child) + if flat[0] == expr[0]: + kids.extend(flat[1]) + else: + kids.append(flat) + return (expr[0], kids) + + +def random_expr(rng: np.random.Generator, literals: list[str]) -> Expr: + """ + Random series-parallel expression using every literal exactly once. + + Args: + rng: Random generator. + literals: Distinct signal names (at least one). + Returns: + Flattened AND/OR expression. + """ + nodes: list[Expr] = [var(name) for name in literals] + order = list(rng.permutation(len(nodes))) + nodes = [nodes[i] for i in order] + while len(nodes) > 1: + i = int(rng.integers(0, len(nodes) - 1)) + op = "and" if rng.random() < 0.5 else "or" + nodes[i : i + 2] = [(op, [nodes[i], nodes[i + 1]])] + return _flatten(nodes[0]) + + +@dataclass +class SPNode: + """Series-parallel switch network node; leaves are single transistors.""" + + kind: str # "leaf" | "series" | "parallel" + children: list[SPNode] = field(default_factory=list) + signal: str = "" + device_id: str = "" + + +def sp_from_expr(expr: Expr, dual: bool) -> SPNode: + """ + Build the switch network for a static CMOS pull-down (dual=False) or pull-up (dual=True). + + Args: + expr: Positive expression E; the cell output is NOT E. + dual: True for the PMOS pull-up network (AND -> parallel, OR -> series). + Returns: + Series-parallel tree. + """ + if expr[0] == "var": + return SPNode("leaf", signal=expr[1]) + series_op = "or" if dual else "and" + kind = "series" if expr[0] == series_op else "parallel" + return SPNode(kind, [sp_from_expr(child, dual) for child in expr[1]]) + + +def sp_leaves(node: SPNode) -> list[SPNode]: + """ + Leaves of a series-parallel tree in drawing order. + + Args: + node: Tree root. + Returns: + Leaf nodes. + """ + if node.kind == "leaf": + return [node] + out: list[SPNode] = [] + for child in node.children: + out.extend(sp_leaves(child)) + return out + + +@dataclass +class Stage: + """One transistor-level stage: a static CMOS cell (out = NOT expr) or a transmission-gate mux.""" + + kind: str # "cmos" | "tg_mux" + out: str + expr: Expr | None = None + sel: str = "" + sel_n: str = "" + d0: str = "" + d1: str = "" + pun: SPNode | None = None + pdn: SPNode | None = None + tg_devices: list[str] = field(default_factory=list) + + def inputs(self) -> list[str]: + """ + Signals this stage reads. + + Returns: + Distinct input signal names. + """ + if self.kind == "cmos": + return expr_literals(self.expr) + return [self.d0, self.d1, self.sel, self.sel_n] + + def evaluate(self, env: dict[str, int]) -> int: + """ + Reference boolean value of the stage output. + + Args: + env: Signal values by name. + Returns: + 0 or 1. + """ + if self.kind == "cmos": + return 1 - eval_expr(self.expr, env) + return env[self.d1] if env[self.sel] else env[self.d0] + + +@dataclass +class Device: + """A logical device: transistor or logic gate, with terminal-to-net pins.""" + + id: str + cls: str + pins: dict[str, str] + stage: int = -1 + + +@dataclass +class Circuit: + """A sampled circuit in either domain, with its devices and reference behaviour.""" + + domain: str # "transistor" | "gate" + recipe: str + inputs: list[str] + outputs: list[str] + stages: list[Stage] = field(default_factory=list) + devices: list[Device] = field(default_factory=list) + + def evaluate(self, env: dict[str, int]) -> dict[str, int]: + """ + Evaluate every signal for one input assignment. + + Args: + env: Primary input values. + Returns: + Values of all signals (inputs, internal nets and outputs). + """ + values = dict(env) + if self.domain == "transistor": + for stage in self.stages: + values[stage.out] = stage.evaluate(values) + else: + for dev in self.devices: + ins = [values[dev.pins[t]] for t in ("a", "b") if t in dev.pins] + values[dev.pins["out"]] = gate_function(dev.cls, ins) + return values + + def truth_table(self) -> list[dict[str, dict[str, int]]]: + """ + Reference truth table from the abstract function (not from the transistors). + + Returns: + Rows of {"in": {name: v}, "out": {name: v}} in binary counting order. + """ + rows = [] + for bits in itertools.product((0, 1), repeat=len(self.inputs)): + env = dict(zip(self.inputs, bits)) + values = self.evaluate(env) + rows.append({"in": env, "out": {o: values[o] for o in self.outputs}}) + return rows + + def transistor_count(self) -> int: + """ + Number of MOSFETs in the circuit. + + Returns: + Count of NMOS plus PMOS devices. + """ + return sum(1 for d in self.devices if d.cls in ("NMOS", "PMOS")) + + +def gate_function(kind: str, ins: list[int]) -> int: + """ + Boolean function of a 1- or 2-input logic gate. + + Args: + kind: Gate class name (AND ... XNOR). + ins: Input values. + Returns: + Output value. + Raises: + ValueError: If kind is not a gate class. + """ + if kind == "NOT": + return 1 - ins[0] + a, b = ins + table = { + "AND": a & b, + "OR": a | b, + "NAND": 1 - (a & b), + "NOR": 1 - (a | b), + "XOR": a ^ b, + "XNOR": 1 - (a ^ b), + } + if kind not in table: + raise ValueError(f"not a gate class: {kind}") + return table[kind] + + +# --------------------------------------------------------------------------------------------- +# Transistor-level recipes +# --------------------------------------------------------------------------------------------- + +_NAMED_CELLS: dict[str, Expr] = { + "inv": var("A"), + "nand2": ("and", [var("A"), var("B")]), + "nand3": ("and", [var("A"), var("B"), var("C")]), + "nor2": ("or", [var("A"), var("B")]), + "nor3": ("or", [var("A"), var("B"), var("C")]), + "aoi21": ("or", [("and", [var("A"), var("B")]), var("C")]), + "aoi22": ("or", [("and", [var("A"), var("B")]), ("and", [var("C"), var("D")])]), + "oai21": ("and", [("or", [var("A"), var("B")]), var("C")]), + "oai22": ("and", [("or", [var("A"), var("B")]), ("or", [var("C"), var("D")])]), + "aoi211": ("or", [("and", [var("A"), var("B")]), var("C"), var("D")]), + "oai211": ("and", [("or", [var("A"), var("B")]), var("C"), var("D")]), +} + +TRANSISTOR_RECIPES: tuple[tuple[str, float], ...] = ( + ("named_cell", 0.22), + ("random_cell", 0.18), + ("and_or", 0.12), + ("buf", 0.03), + ("xor_xnor", 0.10), + ("mux2_tg", 0.08), + ("chain", 0.27), +) + + +def _cmos(expr: Expr, out: str) -> Stage: + """ + Static CMOS stage computing out = NOT expr. + + Args: + expr: Pull-down expression. + out: Output net name. + Returns: + Stage with its pull-up and pull-down networks built. + """ + return Stage("cmos", out, expr=expr, pun=sp_from_expr(expr, dual=True), pdn=sp_from_expr(expr, dual=False)) + + +def _pick(rng: np.random.Generator, options: tuple[tuple[str, float], ...]) -> str: + """ + Weighted choice over (name, weight) pairs. + + Args: + rng: Random generator. + options: Names with relative weights. + Returns: + The chosen name. + """ + weights = np.array([w for _, w in options], dtype=np.float64) + idx = int(rng.choice(len(options), p=weights / weights.sum())) + return options[idx][0] + + +def _out_name(rng: np.random.Generator, used: set[str]) -> str: + """ + Pick a primary output name not already used. + + Args: + rng: Random generator. + used: Names already taken. + Returns: + A fresh output name. + """ + for name in [str(n) for n in rng.permutation(["Y", "Z", "F", "OUT", "W"])]: + if name not in used: + return name + raise ValueError("ran out of output names") + + +def sample_transistor_circuit(rng: np.random.Generator) -> Circuit: + """ + Sample a transistor-level (CMOS) circuit with a known boolean function. + + Args: + rng: Random generator. + Returns: + Circuit with stages and devices; at most MAX_INPUTS inputs and MAX_TRANSISTORS devices. + """ + while True: + circuit = _sample_transistor_once(rng) + _expose_internal_output(circuit, rng) + _expand_transistors(circuit) + if circuit.transistor_count() <= MAX_TRANSISTORS and len(circuit.inputs) <= MAX_INPUTS: + return circuit + + +def _rename_expr(expr: Expr, old: str, new: str) -> Expr: + """ + Rename one signal inside an expression. + + Args: + expr: Expression tree. + old: Signal to rename. + new: New name. + Returns: + Renamed expression. + """ + if expr[0] == "var": + return var(new) if expr[1] == old else expr + return (expr[0], [_rename_expr(e, old, new) for e in expr[1]]) + + +def _expose_internal_output(circuit: Circuit, rng: np.random.Generator) -> None: + """ + Sometimes make an internal stage output an extra primary output (e.g. both Y and its complement). + + Inverted copies of primary inputs (A_n, S_n) are never exposed. + + Args: + circuit: Circuit without devices yet; modified in place. + rng: Random generator. + """ + internal = [st.out for st in circuit.stages if st.kind == "cmos" and st.out not in circuit.outputs and not st.out.endswith("_n")] + if not internal or rng.random() >= 0.6: + return + old = internal[int(rng.integers(0, len(internal)))] + new = _out_name(rng, set(circuit.outputs) | set(circuit.inputs)) + for st in circuit.stages: + if st.out == old: + st.out = new + if st.kind == "cmos": + st.expr = _rename_expr(st.expr, old, new) + st.pun = sp_from_expr(st.expr, dual=True) + st.pdn = sp_from_expr(st.expr, dual=False) + circuit.outputs.append(new) + + +def _sample_transistor_once(rng: np.random.Generator) -> Circuit: + """ + One draw of a transistor recipe (may exceed size limits; caller retries). + + Args: + rng: Random generator. + Returns: + Circuit with stages but no devices yet. + """ + recipe = _pick(rng, TRANSISTOR_RECIPES) + if recipe == "named_cell": + name = str(rng.choice(sorted(_NAMED_CELLS))) + expr = _NAMED_CELLS[name] + out = _out_name(rng, set()) + return Circuit("transistor", name, expr_literals(expr), [out], [_cmos(expr, out)]) + if recipe == "random_cell": + n = int(rng.integers(2, 5)) + ins = ["A", "B", "C", "D"][:n] + expr = random_expr(rng, ins) + out = _out_name(rng, set()) + return Circuit("transistor", f"random_cell{n}", ins, [out], [_cmos(expr, out)]) + if recipe == "and_or": + n = int(rng.integers(2, 4)) + ins = ["A", "B", "C"][:n] + op = "and" if rng.random() < 0.5 else "or" + out = _out_name(rng, set()) + stages = [_cmos((op, [var(i) for i in ins]), "n1"), _cmos(var("n1"), out)] + return Circuit("transistor", f"{op}{n}", ins, [out], stages) + if recipe == "buf": + out = _out_name(rng, set()) + return Circuit("transistor", "buf", ["A"], [out], [_cmos(var("A"), "n1"), _cmos(var("n1"), out)]) + if recipe == "xor_xnor": + is_xor = rng.random() < 0.5 + out = _out_name(rng, set()) + a, b, an, bn = var("A"), var("B"), var("A_n"), var("B_n") + expr = ("or", [("and", [a, b]), ("and", [an, bn])]) if is_xor else ("or", [("and", [a, bn]), ("and", [an, b])]) + stages = [_cmos(a, "A_n"), _cmos(b, "B_n"), _cmos(expr, out)] + return Circuit("transistor", "xor2" if is_xor else "xnor2", ["A", "B"], [out], stages) + if recipe == "mux2_tg": + out = _out_name(rng, set()) + mux = Stage("tg_mux", out, sel="S", sel_n="S_n", d0="D0", d1="D1") + return Circuit("transistor", "mux2_tg", ["D0", "D1", "S"], [out], [_cmos(var("S"), "S_n"), mux]) + return _sample_chain(rng) + + +def _sample_chain(rng: np.random.Generator) -> Circuit: + """ + Random composition of 2-3 CMOS stages where later stages consume earlier outputs. + + Args: + rng: Random generator. + Returns: + Circuit whose outputs are the stage outputs nobody consumes. + """ + n_stages = int(rng.integers(2, 4)) + pool = ["A", "B", "C", "D"] + n_in = int(rng.integers(2, 5)) + inputs = pool[:n_in] + stages: list[Stage] = [] + produced: list[str] = [] + consumed: set[str] = set() + for k in range(n_stages): + lits: list[str] = [] + if produced: + lits.append(produced[-1]) + if len(produced) > 1 and rng.random() < 0.3: + lits.append(produced[-2]) + extra = int(rng.integers(1, 3)) if produced else int(rng.integers(2, 4)) + fresh = [s for s in inputs if s not in consumed] + stale = [s for s in inputs if s in consumed] + candidates = fresh + [stale[i] for i in rng.permutation(len(stale))] + for s in candidates[:extra]: + lits.append(s) + lits = lits[:4] + expr = random_expr(rng, lits) + out = f"n{k + 1}" + stages.append(_cmos(expr, out)) + consumed.update(lits) + produced.append(out) + used_inputs = [s for s in inputs if s in consumed] + sinks = [s.out for s in stages if s.out not in consumed] + rename: dict[str, str] = {} + taken: set[str] = set() + for s in sinks: + rename[s] = _out_name(rng, taken) + taken.add(rename[s]) + for st in stages: + st.out = rename.get(st.out, st.out) + outputs = [rename[s] for s in sinks] + return Circuit("transistor", f"chain{n_stages}", used_inputs, outputs, stages) + + +def _expand_transistors(circuit: Circuit) -> None: + """ + Turn stages into NMOS/PMOS devices with drawing-consistent terminal names. + + The canonical symbols are vertical: NMOS drain on top, PMOS source on top. A leaf's top + and bottom nets therefore map to (d, s) for NMOS and (s, d) for PMOS. Transmission gates + are drawn horizontally with the source on the left (data side) and drain on the right. + + Args: + circuit: Circuit whose stages are filled in; devices are appended in place. + """ + counter = itertools.count(1) + net_counter = itertools.count(1) + circuit.devices = [] + + def build(node: SPNode, top: str, bottom: str, cls: str, stage_idx: int) -> None: + """Assign devices and intermediate nets for one series-parallel subtree.""" + if node.kind == "leaf": + node.device_id = f"M{next(counter)}" + t_name, b_name = ("d", "s") if cls == "NMOS" else ("s", "d") + circuit.devices.append(Device(node.device_id, cls, {t_name: top, "g": node.signal, b_name: bottom}, stage_idx)) + elif node.kind == "parallel": + for child in node.children: + build(child, top, bottom, cls, stage_idx) + else: + nets = [top] + [f"x{next(net_counter)}" for _ in node.children[:-1]] + [bottom] + for i, child in enumerate(node.children): + build(child, nets[i], nets[i + 1], cls, stage_idx) + + for idx, stage in enumerate(circuit.stages): + if stage.kind == "cmos": + build(stage.pun, VDD_NET, stage.out, "PMOS", idx) + build(stage.pdn, stage.out, GND_NET, "NMOS", idx) + else: + stage.tg_devices = [] + for data, n_gate, p_gate in ((stage.d0, stage.sel_n, stage.sel), (stage.d1, stage.sel, stage.sel_n)): + for cls, g in (("NMOS", n_gate), ("PMOS", p_gate)): + dev_id = f"M{next(counter)}" + circuit.devices.append(Device(dev_id, cls, {"s": data, "g": g, "d": stage.out}, idx)) + stage.tg_devices.append(dev_id) + + +# --------------------------------------------------------------------------------------------- +# Gate-level recipes +# --------------------------------------------------------------------------------------------- + + +def sample_gate_circuit(rng: np.random.Generator) -> Circuit: + """ + Sample a gate-level DAG (2-4 inputs, 2-8 gates, depth <= 4, 1-3 outputs). + + Args: + rng: Random generator. + Returns: + Circuit with gate devices in topological order. + """ + while True: + circuit = _sample_gate_once(rng) + if circuit is not None: + return circuit + + +def _sample_gate_once(rng: np.random.Generator) -> Circuit | None: + """ + One draw of a random gate DAG; None when the draw violates the shape limits. + + Args: + rng: Random generator. + Returns: + Circuit or None. + """ + n_in = int(rng.integers(2, 5)) + inputs = ["A", "B", "C", "D"][:n_in] + n_gates = int(rng.integers(2, 9)) + depth: dict[str, int] = {s: 0 for s in inputs} + use: dict[str, int] = {s: 0 for s in inputs} + devices: list[Device] = [] + for k in range(n_gates): + kind = GATE_KINDS[int(rng.integers(0, len(GATE_KINDS)))] + arity = 1 if kind == "NOT" else 2 + signals = list(depth) + unused = [s for s in signals if use[s] == 0] + chosen: list[str] = [] + for _ in range(arity): + pool = [s for s in (unused if unused and rng.random() < 0.8 else signals) if s not in chosen] + if not pool: + pool = [s for s in signals if s not in chosen] + pick = pool[int(rng.integers(0, len(pool)))] + chosen.append(pick) + if pick in unused: + unused.remove(pick) + out = f"g{k + 1}" + pins = {t: s for t, s in zip(("a", "b") if arity == 2 else ("a",), chosen)} + pins["out"] = out + devices.append(Device(f"U{k + 1}", kind, pins)) + for s in chosen: + use[s] += 1 + depth[out] = 1 + max(depth[s] for s in chosen) + use[out] = 0 + if max(depth.values()) > 4: + return None + sinks = [d.pins["out"] for d in devices if use[d.pins["out"]] == 0] + if not 1 <= len(sinks) <= 3: + return None + used_inputs = [s for s in inputs if use[s] > 0] + if len(used_inputs) < 2: + return None + rename: dict[str, str] = {} + taken: set[str] = set() + for s in sinks: + rename[s] = _out_name(rng, taken) + taken.add(rename[s]) + for dev in devices: + dev.pins = {t: rename.get(n, n) for t, n in dev.pins.items()} + return Circuit("gate", f"gates{n_gates}", used_inputs, [rename[s] for s in sinks], devices=devices) + + +def sample_circuit(rng: np.random.Generator, domain: str) -> Circuit: + """ + Sample a circuit for the requested domain. + + Args: + rng: Random generator. + domain: "transistor" or "gate". + Returns: + A circuit with devices and a computable truth table. + Raises: + ValueError: If the domain is unknown. + """ + if domain == "transistor": + return sample_transistor_circuit(rng) + if domain == "gate": + return sample_gate_circuit(rng) + raise ValueError(f"unknown domain {domain!r}") + + +def topology_hash(circuit: Circuit) -> str: + """ + Isomorphism-invariant hash of the logical circuit (devices, nets, port roles). + + Drawing-only choices (supply symbol count, bulk terminals, net and device names, layout) + do not change the hash, so every rendering of the same circuit lands in the same split. + + Args: + circuit: Circuit with devices. + Returns: + Hex digest string. + """ + g = nx.Graph() + role: dict[str, str] = {} + for name in circuit.inputs: + role[name] = "pi" + for name in circuit.outputs: + role[name] = "po" + role[VDD_NET] = "vdd" + role[GND_NET] = "gnd" + for dev in circuit.devices: + g.add_node(f"dev:{dev.id}", label=dev.cls) + for term, net in dev.pins.items(): + if term == "b": + continue + g.add_node(f"net:{net}", label=role.get(net, "net")) + g.add_edge(f"dev:{dev.id}", f"net:{net}", label=term) + wl = nx.weisfeiler_lehman_graph_hash(g, node_attr="label", edge_attr="label", iterations=4) + return hashlib.sha256(f"{circuit.domain}|{wl}".encode()).hexdigest()[:16] diff --git a/backend/data_gen/synth_v2/render.py b/backend/data_gen/synth_v2/render.py new file mode 100644 index 0000000..e2edb83 --- /dev/null +++ b/backend/data_gen/synth_v2/render.py @@ -0,0 +1,565 @@ +""" +Module: render.py +Purpose: Rasterises a routed Layout into a training image in one of four rendering modes + (cad, textbook, hand-drawn, phone photo) with paper textures, pen styles, fonts and + photo effects, and returns exact annotations: YOLO boxes, per-symbol pin points and + orientation, junction dots, wire polylines, crossings and text boxes. Junction dot + diameters follow the real-image finding (10-17 px at 1000 px image width). +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass + +import cv2 +import numpy as np + +from .layout import Layout +from .schema import CLASS_ID +from .symbols import orient_points, symbol_geometry + +MODES: tuple[str, ...] = ("cad", "textbook", "hand", "photo") +TRAIN_FONTS: dict[str, int] = { + "simplex": cv2.FONT_HERSHEY_SIMPLEX, + "duplex": cv2.FONT_HERSHEY_DUPLEX, + "complex": cv2.FONT_HERSHEY_COMPLEX, + "triplex": cv2.FONT_HERSHEY_TRIPLEX, + "plain": cv2.FONT_HERSHEY_PLAIN, + "script_simplex": cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, +} +# Rendering style values reserved for held-out-style test samples (never used in train/valid). +HELD_OUT_FONT = "script_complex" +HELD_OUT_PAPER = "grid" +HELD_OUT_LINE = "sketch" +FONTS: dict[str, int] = {**TRAIN_FONTS, HELD_OUT_FONT: cv2.FONT_HERSHEY_SCRIPT_COMPLEX} +TRAIN_PAPERS: tuple[str, ...] = ("white", "cream", "lined", "noisy") +INKS: dict[str, tuple[int, int, int]] = { + "black": (20, 20, 20), + "gray": (70, 70, 70), + "blue": (150, 60, 25), + "pencil": (95, 95, 100), +} +DOT_MIN_PER_1000 = 10.0 +DOT_MAX_PER_1000 = 17.0 +TITLES: tuple[str, ...] = ("Fig. 1", "Fig. 3", "CMOS", "Circuit", "Ex. 2", "Lab 4", "static CMOS", "Logic", "Q3", "Schematic") + + +@dataclass +class RenderStyle: + """Pixel-level rendering choices for one image.""" + + mode: str + pitch: float + thickness: int + font: str + paper: str + ink: str + line: str # "clean" | "wobble" | "sketch" + wobble: float + dot_per_1000: float + jpeg_quality: int + label_ports: bool + label_supplies: bool + label_devices: bool + title: bool + + +def sample_render_style(rng: np.random.Generator, layout: Layout, held_out: bool) -> RenderStyle: + """ + Sample the rendering style; held-out samples use the reserved font, paper and line style. + + Args: + rng: Random generator. + layout: Routed layout (its grid size bounds the pitch). + held_out: Whether this is a held-out-style test sample. + Returns: + RenderStyle. + """ + mode = ("textbook", "hand", "photo")[int(rng.integers(0, 3))] if held_out else MODES[int(rng.integers(0, 4))] + pitch = float(rng.uniform(15.0, 24.0)) + width_px = layout.width * pitch + if width_px < 700: + pitch = 700.0 / layout.width + elif width_px > 1800: + pitch = 1800.0 / layout.width + rel = {"cad": (0.07, 0.1), "textbook": (0.09, 0.14), "hand": (0.1, 0.17), "photo": (0.1, 0.17)}[mode] + thickness = max(1, round(pitch * float(rng.uniform(*rel)))) + hi = min(DOT_MAX_PER_1000, 0.8 * 1000.0 / layout.width) + dot = float(rng.uniform(DOT_MIN_PER_1000, max(DOT_MIN_PER_1000, hi))) + if held_out: + font, paper, line = HELD_OUT_FONT, HELD_OUT_PAPER, (HELD_OUT_LINE if mode != "textbook" else "clean") + else: + font = sorted(TRAIN_FONTS)[int(rng.integers(0, len(TRAIN_FONTS)))] + if mode == "cad": + paper = "white" + elif mode == "textbook": + paper = ("white", "cream")[int(rng.integers(0, 2))] + else: + paper = TRAIN_PAPERS[int(rng.integers(0, len(TRAIN_PAPERS)))] + line = "clean" if mode in ("cad", "textbook") else "wobble" + if mode in ("cad", "textbook"): + ink = ("black", "gray")[int(rng.integers(0, 2))] + else: + ink = ("black", "blue", "pencil", "gray")[int(rng.integers(0, 4))] + quality = {"cad": (92, 97), "textbook": (85, 95), "hand": (80, 92), "photo": (55, 85)}[mode] + return RenderStyle( + mode=mode, + pitch=round(pitch, 4), + thickness=thickness, + font=font, + paper=paper, + ink=ink, + line=line, + wobble=round(float(rng.uniform(0.6, 1.6)) * pitch / 18.0, 4) if line != "clean" else 0.0, + dot_per_1000=round(dot, 4), + jpeg_quality=int(rng.integers(quality[0], quality[1] + 1)), + label_ports=bool(rng.random() < 0.9), + label_supplies=bool(rng.random() < 0.6), + label_devices=bool(rng.random() < 0.3), + title=bool(rng.random() < 0.3), + ) + + +def _densify(pts: np.ndarray, step: float) -> np.ndarray: + """ + Resample a polyline so consecutive points are at most `step` pixels apart. + + Args: + pts: Nx2 vertices. + step: Maximum spacing. + Returns: + Mx2 resampled points (original vertices kept). + """ + out: list[np.ndarray] = [] + for a, b in zip(pts[:-1], pts[1:]): + n = max(1, int(np.ceil(float(np.linalg.norm(b - a)) / step))) + ts = np.arange(n, dtype=np.float64) / n + out.append(a[None, :] + ts[:, None] * (b - a)[None, :]) + out.append(pts[-1:]) + return np.concatenate(out, axis=0) + + +def _wobble(pts: np.ndarray, rng: np.random.Generator, amp: float) -> np.ndarray: + """ + Hand-drawn wobble: smooth low-frequency drift plus jitter, pinned to zero at both ends. + + Args: + pts: Nx2 polyline in pixels. + rng: Random generator. + amp: Wobble amplitude in pixels. + Returns: + Wobbled dense polyline with the exact original endpoints. + """ + dense = _densify(pts, 4.0) + n = len(dense) + if n < 3 or amp <= 0: + return dense + noise = rng.normal(0.0, 1.0, (n + 24, 2)) + kernel = np.hanning(25) + kernel /= kernel.sum() + smooth = np.stack([np.convolve(noise[:, i], kernel, mode="valid")[:n] for i in range(2)], axis=1) * 3.5 + t = np.linspace(0.0, 1.0, n) + taper = np.sqrt(np.sin(np.pi * t))[:, None] + jitter = rng.normal(0.0, 0.06, (n, 2)) + return dense + (smooth + jitter) * amp * taper + + +class _Canvas: + """Ink mask plus bookkeeping of the exact drawn points per item.""" + + def __init__(self, w: int, h: int, style: RenderStyle, rng: np.random.Generator) -> None: + """ + Create an empty ink mask. + + Args: + w: Width in pixels. + h: Height in pixels. + style: Render style. + rng: Random generator. + """ + self.mask = np.zeros((h, w), dtype=np.uint8) + self.style = style + self.rng = rng + + def stroke(self, pts: np.ndarray, thickness: int | None = None) -> np.ndarray: + """ + Draw one polyline in the current line style. + + Args: + pts: Nx2 polyline in pixels. + thickness: Override thickness. + Returns: + All points actually drawn (for tight boxes). + """ + t = thickness or self.style.thickness + drawn: list[np.ndarray] = [] + if self.style.line == "clean": + passes = [pts] + elif self.style.line == "wobble": + passes = [_wobble(pts, self.rng, self.style.wobble)] + else: + passes = [_wobble(pts, self.rng, self.style.wobble * 1.3) for _ in range(2)] + t = max(1, t - 1) + for p in passes: + cv2.polylines(self.mask, [np.round(p * 16).astype(np.int32)], False, 255, t, cv2.LINE_AA, shift=4) + drawn.append(p) + return np.concatenate(drawn, axis=0) + + def fill(self, pts: np.ndarray) -> np.ndarray: + """ + Fill a closed polygon. + + Args: + pts: Nx2 polygon in pixels. + Returns: + The polygon points. + """ + cv2.fillPoly(self.mask, [np.round(pts * 16).astype(np.int32)], 255, cv2.LINE_AA, shift=4) + return pts + + def dot(self, center: tuple[float, float], diameter: float) -> None: + """ + Filled junction dot. + + Args: + center: Centre in pixels. + diameter: Dot diameter in pixels. + """ + c = (int(round(center[0] * 16)), int(round(center[1] * 16))) + cv2.circle(self.mask, c, int(round(diameter / 2 * 16)), 255, -1, cv2.LINE_AA, shift=4) + + def text_size(self, text: str, height: float) -> tuple[float, int, int, int]: + """ + Font scale and pixel size of a text for a target cap height. + + Args: + text: String. + height: Target text height in pixels. + Returns: + (scale, thickness, width, height). + """ + font = FONTS[self.style.font] + (_, h1), _ = cv2.getTextSize("A", font, 1.0, 1) + scale = height / max(h1, 1) + thick = max(1, round(self.style.thickness * 0.8)) + (w, h), _ = cv2.getTextSize(text, font, scale, thick) + return scale, thick, w, h + + def text(self, text: str, org: tuple[float, float], scale: float, thick: int) -> None: + """ + Draw text with its baseline-left corner at org. + + Args: + text: String. + org: Bottom-left corner in pixels. + scale: Font scale. + thick: Stroke thickness. + """ + cv2.putText(self.mask, text, (int(round(org[0])), int(round(org[1]))), FONTS[self.style.font], scale, 255, thick, cv2.LINE_AA) + + +def _paper(w: int, h: int, paper: str, rng: np.random.Generator) -> np.ndarray: + """ + Paper background. + + Args: + w: Width. + h: Height. + paper: white | cream | lined | grid | noisy. + rng: Random generator. + Returns: + HxWx3 float32 BGR image in [0, 255]. + """ + if paper == "white": + return np.full((h, w, 3), 255.0, dtype=np.float32) + base = float(rng.uniform(222, 248)) + tint = np.array([base - rng.uniform(4, 16), base - rng.uniform(0, 6), base], dtype=np.float32) + img = np.empty((h, w, 3), dtype=np.float32) + img[:] = tint + if paper in ("lined", "grid"): + spacing = float(rng.uniform(22, 34)) + color = np.array([205, 175, 150] if rng.random() < 0.6 else [170, 200, 170], dtype=np.float32) + lines = np.zeros((h, w), dtype=np.float32) + y = float(rng.uniform(0, spacing)) + while y < h: + cv2.line(lines, (0, int(y)), (w, int(y)), 1.0, 1, cv2.LINE_AA) + y += spacing + if paper == "grid": + x = float(rng.uniform(0, spacing)) + while x < w: + cv2.line(lines, (int(x), 0), (int(x), h), 1.0, 1, cv2.LINE_AA) + x += spacing + a = (lines * 0.55)[:, :, None] + img = img * (1 - a) + color * a + noise = 6.0 if paper == "noisy" else 2.0 + img += rng.normal(0.0, noise, (h, w, 1)).astype(np.float32) + return img + + +def _apply_photo(img: np.ndarray, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]: + """ + Phone-photo effects: perspective, uneven lighting, shadow, blur and sensor noise. + + Args: + img: HxWx3 float32 image. + rng: Random generator. + Returns: + (processed image, 3x3 homography applied to coordinates). + """ + h, w = img.shape[:2] + m = 0.035 + src = np.float32([[0, 0], [w, 0], [w, h], [0, h]]) + jitter = rng.uniform(-m, m, (4, 2)) * np.array([w, h]) + dst = (src + jitter).astype(np.float32) + homography = cv2.getPerspectiveTransform(src, dst) + border = tuple(float(v) for v in np.median(img.reshape(-1, 3), axis=0)) + out = cv2.warpPerspective(img, homography, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=border) + yy, xx = np.mgrid[0:h, 0:w].astype(np.float32) + gx, gy = rng.uniform(-0.25, 0.25, 2) + light = 1.0 + gx * (xx / w - 0.5) + gy * (yy / h - 0.5) + vignette = 1.0 - 0.18 * (((xx / w - 0.5) ** 2 + (yy / h - 0.5) ** 2) * 2.0) + out *= (light * vignette)[:, :, None] + if rng.random() < 0.5: + shadow = np.zeros((h, w), dtype=np.float32) + cx, cy = rng.uniform(0, w), rng.uniform(0, h) + cv2.ellipse(shadow, (int(cx), int(cy)), (int(w * rng.uniform(0.2, 0.5)), int(h * rng.uniform(0.2, 0.5))), float(rng.uniform(0, 180)), 0, 360, 1.0, -1) + shadow = cv2.GaussianBlur(shadow, (0, 0), sigmaX=w * 0.05) + out *= (1.0 - 0.18 * shadow)[:, :, None] + out = cv2.GaussianBlur(out, (0, 0), sigmaX=float(rng.uniform(0.5, 1.2))) + out += rng.normal(0.0, float(rng.uniform(3, 7)), out.shape).astype(np.float32) + return out, homography + + +def _transform(pts: np.ndarray, homography: np.ndarray | None) -> np.ndarray: + """ + Apply a homography to Nx2 points (identity when None). + + Args: + pts: Nx2 points. + homography: 3x3 matrix or None. + Returns: + Transformed Nx2 points. + """ + if homography is None or len(pts) == 0: + return pts + return cv2.perspectiveTransform(pts.reshape(-1, 1, 2).astype(np.float64), homography).reshape(-1, 2) + + +def _bbox(pts: np.ndarray, pad: float, w: int, h: int) -> list[float]: + """ + Padded bounding box clipped to the image. + + Args: + pts: Nx2 points. + pad: Padding in pixels. + w: Image width. + h: Image height. + Returns: + [x1, y1, x2, y2] rounded to 0.01 px. + """ + x1 = max(0.0, float(pts[:, 0].min()) - pad) + y1 = max(0.0, float(pts[:, 1].min()) - pad) + x2 = min(float(w), float(pts[:, 0].max()) + pad) + y2 = min(float(h), float(pts[:, 1].max()) + pad) + return [round(x1, 2), round(y1, 2), round(x2, 2), round(y2, 2)] + + +def _boxes_overlap(a: list[float], b: list[float]) -> bool: + """ + Whether two [x1, y1, x2, y2] boxes intersect. + + Args: + a: First box. + b: Second box. + Returns: + True on overlap. + """ + return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3] + + +def render(layout: Layout, style: RenderStyle, rng: np.random.Generator) -> tuple[bytes, dict]: + """ + Render a routed layout to an encoded JPEG plus exact annotations. + + Args: + layout: Routed layout. + style: Render style. + rng: Random generator. + Returns: + (JPEG bytes, annotation dict with image size, symbols, junctions, wires, crossings, texts). + """ + p = style.pitch + w = int(round(layout.width * p)) + h = int(round(layout.height * p)) + + def to_px(pts: np.ndarray) -> np.ndarray: + """Grid units to pixel coordinates.""" + return (np.asarray(pts, dtype=np.float64) + 0.5) * p + + canvas = _Canvas(w, h, style, rng) + pad = style.thickness / 2.0 + 1.0 + sym_records: list[dict] = [] + sym_points: list[np.ndarray] = [] + for sym in layout.symbols: + geom = symbol_geometry(sym.cls, sym.variant) + + def world(pts: np.ndarray, sym: object = sym) -> np.ndarray: + """Local symbol units to pixels for this symbol.""" + return to_px(orient_points(pts, sym.rotation, sym.mirror) + np.array(sym.anchor, dtype=np.float64)) + + drawn = [canvas.stroke(world(s)) for s in geom.strokes] + drawn += [canvas.fill(world(f)) for f in geom.fills] + for text, center, size in geom.texts: + c = world(np.array([center]))[0] + scale, thick, tw, th = canvas.text_size(text, size * p * 0.55) + canvas.text(text, (c[0] - tw / 2, c[1] + th / 2), scale, thick) + sym_points.append(np.concatenate(drawn, axis=0)) + pins = sym.pins() + sym_records.append( + { + "id": sym.comp_id, + "class": sym.cls, + "class_id": CLASS_ID[sym.cls], + "variant": sym.variant, + "orientation": {"rotation": sym.rotation, "mirror": sym.mirror}, + "pins": {t: to_px(np.array([pins[t]]))[0] for t in sorted(pins)}, + "nets": dict(sorted(sym.nets.items())), + } + ) + wires: list[dict] = [] + for net in layout.nets: + name = layout.key_net[net.key] + for poly in net.polylines: + canvas.stroke(to_px(np.array(poly))) + wires.append({"net": name, "points": to_px(np.array(poly))}) + diameter = style.dot_per_1000 * w / 1000.0 + junctions: list[dict] = [] + for net in layout.nets: + for pt in net.junctions: + c = to_px(np.array([pt]))[0] + canvas.dot((c[0], c[1]), diameter) + junctions.append({"net": layout.key_net[net.key], "center": c}) + + sym_boxes = [_bbox(pts, pad, w, h) for pts in sym_points] + dot_r = diameter / 2 + 1.0 + taken = sym_boxes + [[j["center"][0] - dot_r, j["center"][1] - dot_r, j["center"][0] + dot_r, j["center"][1] + dot_r] for j in junctions] + texts = _place_texts(canvas, layout, style, sym_boxes, taken, to_px, rng) + + paper = _paper(w, h, style.paper, rng) + ink = np.array(INKS[style.ink], dtype=np.float32) + alpha = (canvas.mask.astype(np.float32) / 255.0) * (0.75 if style.ink == "pencil" else 1.0) + img = paper * (1.0 - alpha[:, :, None]) + ink * alpha[:, :, None] + homography: np.ndarray | None = None + if style.mode == "photo": + img, homography = _apply_photo(img, rng) + elif style.mode == "hand": + img = cv2.GaussianBlur(img, (0, 0), sigmaX=float(rng.uniform(0.3, 0.7))) + img += rng.normal(0.0, float(rng.uniform(1.5, 4.0)), img.shape).astype(np.float32) + elif style.mode == "textbook" and rng.random() < 0.5: + img = cv2.GaussianBlur(img, (0, 0), sigmaX=float(rng.uniform(0.3, 0.6))) + img_u8 = np.clip(np.round(img), 0, 255).astype(np.uint8) + ok, enc = cv2.imencode(".jpg", img_u8, [cv2.IMWRITE_JPEG_QUALITY, style.jpeg_quality]) + if not ok: + raise RuntimeError("JPEG encoding failed") + + for rec, pts in zip(sym_records, sym_points): + rec["bbox"] = _bbox(_transform(pts, homography), pad, w, h) + rec["pins"] = {t: [round(float(v), 2) for v in _transform(np.array([xy]), homography)[0]] for t, xy in rec["pins"].items()} + for j in junctions: + c = j["center"] + ring = np.array([[c[0] + diameter / 2 * np.cos(a), c[1] + diameter / 2 * np.sin(a)] for a in np.linspace(0, 2 * np.pi, 12, endpoint=False)]) + tc = _transform(np.array([c]), homography)[0] + j["center"] = [round(float(tc[0]), 2), round(float(tc[1]), 2)] + j["diameter"] = round(diameter, 2) + j["bbox"] = _bbox(_transform(ring, homography), 1.0, w, h) + for wire in wires: + wire["points"] = [[round(float(x), 2), round(float(y), 2)] for x, y in _transform(wire["points"], homography)] + for t in texts: + corners = np.array([[t["bbox"][0], t["bbox"][1]], [t["bbox"][2], t["bbox"][1]], [t["bbox"][2], t["bbox"][3]], [t["bbox"][0], t["bbox"][3]]]) + t["bbox"] = _bbox(_transform(corners, homography), 0.0, w, h) + crossings = [] + for pt, a, b in layout.crossings: + c = _transform(to_px(np.array([pt])), homography)[0] + crossings.append({"nets": sorted([a, b]), "point": [round(float(c[0]), 2), round(float(c[1]), 2)]}) + annotation = { + "image": {"width": w, "height": h}, + "render_style": asdict(style), + "global_orientation": {"rotation": layout.global_orientation[0], "mirror": layout.global_orientation[1]}, + "symbols": sym_records, + "junctions": junctions, + "wires": wires, + "crossings": crossings, + "texts": texts, + } + return enc.tobytes(), annotation + + +def _place_texts(canvas: _Canvas, layout: Layout, style: RenderStyle, sym_boxes: list[list[float]], taken: list[list[float]], to_px: object, rng: np.random.Generator) -> list[dict]: + """ + Draw port names, supply names, device names and a title where they collide with nothing. + + Args: + canvas: Canvas whose mask already holds symbols, wires and dots. + layout: Layout. + style: Render style. + sym_boxes: Pixel boxes of the symbols (same order as layout.symbols). + taken: Boxes texts must avoid (symbols and junctions); extended in place. + to_px: Grid-to-pixel function. + rng: Random generator. + Returns: + Text records {"text", "bbox"} in pre-photo pixel coordinates. + """ + h, w = canvas.mask.shape + p = style.pitch + gap = 0.35 * p + texts: list[dict] = [] + + def try_at(text: str, x0: float, y0: float, scale: float, thick: int, tw: int, th: int) -> bool: + """Draw text with its top-left at (x0, y0) if the spot is inside the image and free.""" + tb = [x0 - 2, y0 - 3, x0 + tw + 2, y0 + th + 4] + if tb[0] < 1 or tb[1] < 1 or tb[2] > w - 1 or tb[3] > h - 1: + return False + if any(_boxes_overlap(tb, b) for b in taken): + return False + region = canvas.mask[max(0, int(tb[1]) - 2) : int(tb[3]) + 3, max(0, int(tb[0]) - 2) : int(tb[2]) + 3] + if region.size and int(region.max()) > 0: + return False + canvas.text(text, (x0, y0 + th), scale, thick) + texts.append({"text": text, "bbox": [round(tb[0], 2), round(tb[1], 2), round(tb[2], 2), round(tb[3], 2)]}) + taken.append(tb) + return True + + def try_place(text: str, box: list[float], side: tuple[int, int], size: float) -> None: + """Place text next to box on the given side if the spot is free.""" + scale, thick, tw, th = canvas.text_size(text, size) + cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 + if side == (-1, 0): + x0, y0 = box[0] - gap - tw, cy - th / 2 + elif side == (1, 0): + x0, y0 = box[2] + gap, cy - th / 2 + elif side == (0, -1): + x0, y0 = cx - tw / 2, box[1] - gap - th + else: + x0, y0 = cx - tw / 2, box[3] + gap + try_at(text, x0, y0, scale, thick, tw, th) + + size = p * float(rng.uniform(0.75, 1.1)) + for sym, box in zip(layout.symbols, sym_boxes): + dirs = sym.pin_dirs() + if sym.cls in ("INPUT_PORT", "OUTPUT_PORT") and style.label_ports: + d = next(iter(dirs.values())) + try_place(sym.label, box, (-d[0], -d[1]), size) + elif sym.cls in ("VDD", "GND") and style.label_supplies: + d = next(iter(dirs.values())) + name = sym.cls if rng.random() < 0.7 else ("Vdd" if sym.cls == "VDD" else "Vss") + try_place(name, box, (-d[0], -d[1]), size * 0.8) + elif sym.cls in ("NMOS", "PMOS") and style.label_devices: + g = dirs["g"] + try_place(sym.comp_id, box, (-g[0], -g[1]), size * 0.75) + if style.title: + title = TITLES[int(rng.integers(0, len(TITLES)))] + scale, thick, tw, th = canvas.text_size(title, size * 1.2) + for x0, y0 in ((p, p * 0.6), (w - tw - p, p * 0.6), (p, h - th - p), (w - tw - p, h - th - p)): + if try_at(title, x0, y0, scale, thick, tw, th): + break + return texts diff --git a/backend/data_gen/synth_v2/router.py b/backend/data_gen/synth_v2/router.py new file mode 100644 index 0000000..3b069c6 --- /dev/null +++ b/backend/data_gen/synth_v2/router.py @@ -0,0 +1,348 @@ +""" +Module: router.py +Purpose: Orthogonal grid maze router that draws every net of a placed schematic as a tree + of wires. Different nets may only cross at right angles (a crossover without a dot); + they never share a segment, a bend or a branch point. Same-net branch points become + junction dots. This keeps the rendered drawing an exact picture of the netlist, so + net ground truth (and junction vs crossover labels) is correct by construction. +""" + +from __future__ import annotations + +import heapq +from dataclasses import dataclass, field + +# Direction index -> (dx, dy). Bit for direction i is 1 << i. +DIRS: tuple[tuple[int, int], ...] = ((1, 0), (0, 1), (-1, 0), (0, -1)) +DIR_INDEX: dict[tuple[int, int], int] = {d: i for i, d in enumerate(DIRS)} +VERTICAL_BITS = (1 << 1) | (1 << 3) +HORIZONTAL_BITS = (1 << 0) | (1 << 2) + +STEP_COST = 10 +BEND_COST = 25 +CROSS_COST = 40 +NEAR_COST = 6 + + +@dataclass +class RoutedNet: + """Wiring of one drawn net: polylines, junction points and crossing points.""" + + key: int + polylines: list[list[tuple[int, int]]] = field(default_factory=list) + junctions: list[tuple[int, int]] = field(default_factory=list) + + +class RoutingError(Exception): + """Raised when a net cannot be routed on the grid.""" + + +class GridRouter: + """Maze router over a w x h integer grid with symbol obstacles and reserved pin exits.""" + + def __init__(self, w: int, h: int) -> None: + """ + Create an empty grid. + + Args: + w: Grid width in cells. + h: Grid height in cells. + """ + self.w = w + self.h = h + n = w * h + self.blocked = bytearray(n) + self.reserve = [-1] * n + self.owner = [-1] * n + self.mask = [0] * n + self.cross_net: dict[int, int] = {} + self.cross_mask: dict[int, int] = {} + self.pin_net: dict[int, int] = {} + self.pin_dir: dict[int, int] = {} + + def idx(self, x: int, y: int) -> int: + """ + Flat index of a grid point. + + Args: + x: Column. + y: Row. + Returns: + y * w + x. + """ + return y * self.w + x + + def add_symbol(self, footprint: tuple[int, int, int, int], pins: list[tuple[tuple[int, int], tuple[int, int], int]]) -> None: + """ + Block a symbol body (plus a one-cell ring) and register its pins. + + Args: + footprint: (x0, y0, x1, y1) inclusive integer bounds of the symbol drawing. + pins: (point, outward direction, net key) per pin. + Raises: + RoutingError: If the symbol is off-grid. + """ + x0, y0, x1, y1 = footprint + if x0 - 1 < 0 or y0 - 1 < 0 or x1 + 1 >= self.w or y1 + 1 >= self.h: + raise RoutingError("symbol outside grid") + for y in range(y0 - 1, y1 + 2): + for x in range(x0 - 1, x1 + 2): + self.blocked[self.idx(x, y)] = 1 + for (px, py), (dx, dy), key in pins: + p = self.idx(px, py) + if p in self.pin_net: + raise RoutingError("two pins on one grid point") + self.pin_net[p] = key + self.pin_dir[p] = DIR_INDEX[(dx, dy)] + ox, oy = px + dx, py + dy + if not (0 <= ox < self.w and 0 <= oy < self.h): + raise RoutingError("pin exit outside grid") + o = self.idx(ox, oy) + self.reserve[o] = key if self.reserve[o] in (-1, key) else -2 + + def _enter(self, q: int, d: int, key: int, target_pin: int) -> int: + """ + Classify moving into cell q along direction d for net `key`. + + Args: + q: Destination cell. + d: Move direction index. + key: Net being routed. + target_pin: Pin cell that ends the search, or -1 to target the net's existing tree. + Returns: + 0 blocked, 1 free, 2 perpendicular crossing of another net, 3 target reached. + """ + if q in self.pin_net: + if q == target_pin and (d + 2) % 4 == self.pin_dir[q]: + return 3 + return 0 + r = self.reserve[q] + if r == -2 or (r >= 0 and r != key): + return 0 + if self.blocked[q] and r != key: + return 0 + o = self.owner[q] + if o == -1: + return 1 + if o == key: + if target_pin >= 0 or q in self.cross_net: + return 0 + m = self.mask[q] + if m & (1 << ((d + 2) % 4)) or bin(m).count("1") >= 4: + return 0 + return 3 + if q in self.cross_net: + return 0 + need = VERTICAL_BITS if d in (0, 2) else HORIZONTAL_BITS + return 2 if self.mask[q] == need else 0 + + def _near_other(self, q: int, key: int) -> bool: + """ + Whether a cell touches (4-neighbourhood) a wire of another net. + + Args: + q: Cell index. + key: Net being routed. + Returns: + True if a neighbour is owned by a different net. + """ + x, y = q % self.w, q // self.w + for dx, dy in DIRS: + nx_, ny_ = x + dx, y + dy + if 0 <= nx_ < self.w and 0 <= ny_ < self.h: + o = self.owner[self.idx(nx_, ny_)] + if o != -1 and o != key: + return True + return False + + def _search(self, key: int, src: int, target_pin: int, tree_box: tuple[int, int, int, int]) -> list[int]: + """ + A* from a pin (leaving along its exit direction) to the target. + + Args: + key: Net key. + src: Source pin cell. + target_pin: Target pin cell, or -1 to stop at any legal point of the net's tree. + tree_box: (x0, y0, x1, y1) bounds of the targets for the heuristic. + Returns: + Cell path from src to the reached target. + Raises: + RoutingError: If unreachable. + """ + w = self.w + tx0, ty0, tx1, ty1 = tree_box + + def heur(q: int) -> int: + """Manhattan distance from q to the target bounding box, in step-cost units.""" + x, y = q % w, q // w + dx = tx0 - x if x < tx0 else (x - tx1 if x > tx1 else 0) + dy = ty0 - y if y < ty0 else (y - ty1 if y > ty1 else 0) + return (dx + dy) * STEP_COST + + d0 = self.pin_dir[src] + sx, sy = src % w, src // w + ex, ey = sx + DIRS[d0][0], sy + DIRS[d0][1] + if not (0 <= ex < w and 0 <= ey < self.h): + raise RoutingError("pin exit off grid") + first = self.idx(ex, ey) + status = self._enter(first, d0, key, target_pin) + if status == 0: + raise RoutingError("pin exit blocked") + if status == 3: + return [src, first] + start = (first, d0) + g_cost: dict[tuple[int, int], int] = {start: STEP_COST} + parent: dict[tuple[int, int], tuple[int, int] | None] = {start: None} + heap: list[tuple[int, int, int, int]] = [(STEP_COST + heur(first), STEP_COST, first, d0)] + crossing_state: set[tuple[int, int]] = set() + if status == 2: + crossing_state.add(start) + while heap: + _, g, p, d = heapq.heappop(heap) + if g != g_cost.get((p, d)): + continue + px, py = p % w, p // w + options = (d,) if (p, d) in crossing_state else (d, (d + 1) % 4, (d + 3) % 4) + for nd in options: + qx, qy = px + DIRS[nd][0], py + DIRS[nd][1] + if not (0 <= qx < w and 0 <= qy < self.h): + continue + q = qy * w + qx + st = self._enter(q, nd, key, target_pin) + if st == 0: + continue + cost = g + STEP_COST + (BEND_COST if nd != d else 0) + if st == 2: + cost += CROSS_COST + elif st == 1 and self._near_other(q, key): + cost += NEAR_COST + state = (q, nd) + if st == 3: + path = [q] + cur: tuple[int, int] | None = (p, d) + while cur is not None: + path.append(cur[0]) + cur = parent[cur] + path.append(src) + path.reverse() + if len(set(path)) != len(path): + raise RoutingError("self-intersecting path") + return path + if cost < g_cost.get(state, 1 << 60): + g_cost[state] = cost + parent[state] = (p, d) + if st == 2: + crossing_state.add(state) + heapq.heappush(heap, (cost + heur(q), cost, q, nd)) + raise RoutingError("no route") + + def _commit(self, key: int, path: list[int]) -> None: + """ + Record a found path as wire edges of net `key`. + + Args: + key: Net key. + path: Cells from source pin to target. + """ + w = self.w + for a, b in zip(path[:-1], path[1:]): + d = DIR_INDEX[(b % w - a % w, b // w - a // w)] + for cell, bit in ((a, 1 << d), (b, 1 << ((d + 2) % 4))): + o = self.owner[cell] + if o in (-1, key): + self.owner[cell] = key + self.mask[cell] |= bit + else: + self.cross_net[cell] = key + self.cross_mask[cell] = self.cross_mask.get(cell, 0) | bit + + def route_net(self, key: int, pins: list[int]) -> None: + """ + Route one net as a tree: connect pins one by one to the growing tree. + + Args: + key: Net key (all pins must be registered with it). + pins: Pin cells, first one is the tree root. + Raises: + RoutingError: If any pin cannot be connected. + """ + w = self.w + root = pins[0] + remaining = list(pins[1:]) + tree_pts = [root] + connected_once = False + while remaining: + xs = [p % w for p in tree_pts] + ys = [p // w for p in tree_pts] + box = (min(xs), min(ys), max(xs), max(ys)) + remaining.sort(key=lambda p: (abs(p % w - (box[0] + box[2]) / 2) + abs(p // w - (box[1] + box[3]) / 2), p)) + nxt = remaining.pop(0) + target = -1 if connected_once else root + path = self._search(key, nxt, target, box) + self._commit(key, path) + tree_pts.extend(path) + connected_once = True + + def extract(self, key: int) -> RoutedNet: + """ + Turn the committed edges of a net into polylines and junction points. + + Args: + key: Net key. + Returns: + RoutedNet with maximal polylines (vertices at bends, junctions and ends only). + """ + w = self.w + adj: dict[int, list[int]] = {} + cells = [c for c in range(w * self.h) if self.owner[c] == key] + [c for c, k in self.cross_net.items() if k == key] + for c in cells: + bits = self.mask[c] if self.owner[c] == key else self.cross_mask[c] + x, y = c % w, c // w + adj[c] = [self.idx(x + DIRS[i][0], y + DIRS[i][1]) for i in range(4) if bits & (1 << i)] + net = RoutedNet(key) + node_cells = sorted(c for c, nb in adj.items() if len(nb) != 2 or c in self.pin_net) + node_set = set(node_cells) + net.junctions = [(c % w, c // w) for c in node_cells if len(adj[c]) >= 3] + seen_edges: set[tuple[int, int]] = set() + for start in node_cells: + for nb in sorted(adj[start]): + if (start, nb) in seen_edges: + continue + chain = [start, nb] + seen_edges.add((start, nb)) + seen_edges.add((nb, start)) + while chain[-1] not in node_set: + cur = chain[-1] + nxt = [c for c in adj[cur] if c != chain[-2]][0] + seen_edges.add((cur, nxt)) + seen_edges.add((nxt, cur)) + chain.append(nxt) + net.polylines.append(_simplify([(c % w, c // w) for c in chain])) + return net + + def crossings(self) -> list[tuple[tuple[int, int], int, int]]: + """ + All perpendicular crossings of two nets. + + Returns: + (point, first net key, second net key) per crossing, sorted by cell. + """ + return [((c % self.w, c // self.w), self.owner[c], k) for c, k in sorted(self.cross_net.items())] + + +def _simplify(points: list[tuple[int, int]]) -> list[tuple[int, int]]: + """ + Drop collinear interior vertices of an orthogonal polyline. + + Args: + points: Grid points along the polyline. + Returns: + Polyline with only end and bend vertices. + """ + out = [points[0]] + for i in range(1, len(points) - 1): + a, b, c = out[-1], points[i], points[i + 1] + if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) != 0: + out.append(b) + out.append(points[-1]) + return out diff --git a/backend/data_gen/synth_v2/schema.py b/backend/data_gen/synth_v2/schema.py new file mode 100644 index 0000000..bded5c0 --- /dev/null +++ b/backend/data_gen/synth_v2/schema.py @@ -0,0 +1,21 @@ +""" +Module: schema.py +Purpose: Loads the detector class vocabulary from ml/classes.yaml (the single source of + truth) for the v2 generator, so class names and YOLO ids are never redefined here. +""" + +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[3] +_ML_DIR = REPO_ROOT / "ml" +if str(_ML_DIR) not in sys.path: + sys.path.insert(0, str(_ML_DIR)) + +from class_schema import SCHEMA_VERSION, load_schema, render_data_yaml # noqa: E402,F401 (re-exported) + +SCHEMA = load_schema() +TIER_A: tuple[str, ...] = tuple(c.name for c in SCHEMA.classes_up_to("A")) +CLASS_ID: dict[str, int] = {c.name: c.id for c in SCHEMA.classes} +NODE_TYPE: dict[str, str] = {c.name: c.node_type for c in SCHEMA.classes} +TERMINALS: dict[str, tuple[str, ...]] = {c.name: c.terminals for c in SCHEMA.classes} diff --git a/backend/data_gen/synth_v2/symbols.py b/backend/data_gen/synth_v2/symbols.py new file mode 100644 index 0000000..5fb2760 --- /dev/null +++ b/backend/data_gen/synth_v2/symbols.py @@ -0,0 +1,383 @@ +""" +Module: symbols.py +Purpose: Vector geometry of every tier-A schematic symbol drawn by the v2 generator, in + grid units with pins on integer grid points. Each class has several textbook style + variants (3- vs 4-terminal MOSFETs, bubble vs arrow PMOS, ANSI vs IEC gates, supply + and port shapes). Also implements the 8 orientations (4 rotations x mirror) so pins, + pin directions and strokes transform exactly; the renderer turns this into pixels. + +Coordinates are y-down. Orientation = mirror (x -> -x) applied first, then `rotation` +degrees clockwise on screen. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from functools import lru_cache + +import numpy as np + +GridPoint = tuple[int, int] + + +@dataclass(frozen=True) +class SymbolGeometry: + """Strokes, fills, in-symbol text and pins of one symbol in local grid units.""" + + strokes: tuple[np.ndarray, ...] + fills: tuple[np.ndarray, ...] = () + pins: dict[str, GridPoint] = field(default_factory=dict) + pin_dirs: dict[str, GridPoint] = field(default_factory=dict) + texts: tuple[tuple[str, tuple[float, float], float], ...] = () + + +# Variants per class: the renderer picks one per image (consistent style within a drawing). +VARIANTS: dict[str, tuple[str, ...]] = { + "NMOS": ("plain3", "arrow3", "dashed3", "body4"), + "PMOS": ("bubble3", "arrow3", "bubble4", "body4"), + "VDD": ("bar", "arrow", "circle"), + "GND": ("bars", "triangle", "filled"), + "INPUT_PORT": ("tag", "arrow"), + "OUTPUT_PORT": ("tag", "arrow"), + "GATE": ("ansi", "iec"), +} + + +def _line(*pts: tuple[float, float]) -> np.ndarray: + """ + Polyline from points. + + Args: + pts: Vertices in local units. + Returns: + Nx2 float array. + """ + return np.array(pts, dtype=np.float64) + + +def _closed(*pts: tuple[float, float]) -> np.ndarray: + """ + Closed polyline (first vertex repeated at the end). + + Args: + pts: Vertices in local units. + Returns: + (N+1)x2 float array. + """ + return np.array(list(pts) + [pts[0]], dtype=np.float64) + + +def _arc(cx: float, cy: float, rx: float, ry: float, a0: float, a1: float, n: int = 24) -> np.ndarray: + """ + Elliptical arc, angles in degrees (y-down, so +90 is straight down). + + Args: + cx: Centre x. + cy: Centre y. + rx: Horizontal radius. + ry: Vertical radius. + a0: Start angle. + a1: End angle. + n: Number of samples. + Returns: + Nx2 float array. + """ + ang = np.deg2rad(np.linspace(a0, a1, n)) + return np.stack([cx + rx * np.cos(ang), cy + ry * np.sin(ang)], axis=1) + + +def _circle(cx: float, cy: float, r: float, n: int = 20) -> np.ndarray: + """ + Closed circle polyline. + + Args: + cx: Centre x. + cy: Centre y. + r: Radius. + n: Number of segments. + Returns: + (N+1)x2 float array. + """ + return _arc(cx, cy, r, r, 0, 360, n + 1) + + +def _bezier(p0: tuple[float, float], p1: tuple[float, float], p2: tuple[float, float], n: int = 16) -> np.ndarray: + """ + Quadratic Bezier curve. + + Args: + p0: Start point. + p1: Control point. + p2: End point. + n: Number of samples. + Returns: + Nx2 float array. + """ + t = np.linspace(0.0, 1.0, n)[:, None] + a, b, c = (np.array(p, dtype=np.float64) for p in (p0, p1, p2)) + return (1 - t) ** 2 * a + 2 * (1 - t) * t * b + t**2 * c + + +def _mosfet(cls: str, variant: str) -> SymbolGeometry: + """ + MOSFET symbol, canonical orientation: gate pin left, channel vertical. + + NMOS: drain top (0,-2), source bottom (0,2). PMOS: source top, drain bottom. The gate pin + is (-2,0) and the optional body pin (1,0). + + Args: + cls: "NMOS" or "PMOS". + variant: One of VARIANTS[cls]. + Returns: + Symbol geometry. + """ + is_p = cls == "PMOS" + bubble = is_p and variant in ("bubble3", "bubble4") + strokes: list[np.ndarray] = [] + fills: list[np.ndarray] = [] + gate_end = -1.11 if bubble else -0.65 + strokes.append(_line((-2, 0), (gate_end, 0))) + if bubble: + strokes.append(_circle(-0.88, 0, 0.23)) + strokes.append(_line((-0.65, -0.75), (-0.65, 0.75))) + if variant == "dashed3": + for y0, y1 in ((-1.0, -0.45), (-0.25, 0.25), (0.45, 1.0)): + strokes.append(_line((-0.35, y0), (-0.35, y1))) + else: + strokes.append(_line((-0.35, -1.0), (-0.35, 1.0))) + top, bottom = ("s", "d") if is_p else ("d", "s") + strokes.append(_line((-0.35, -0.7), (0, -0.7), (0, -2))) + strokes.append(_line((-0.35, 0.7), (0, 0.7), (0, 2))) + pins = {"g": (-2, 0), top: (0, -2), bottom: (0, 2)} + dirs = {"g": (-1, 0), top: (0, -1), bottom: (0, 1)} + if variant == "arrow3": + # Arrow on the source lead: out of the channel for NMOS, into it for PMOS. + y = -0.7 if is_p else 0.7 + if is_p: + fills.append(_closed((-0.33, y), (-0.05, y - 0.16), (-0.05, y + 0.16))) + else: + fills.append(_closed((-0.02, y), (-0.3, y - 0.16), (-0.3, y + 0.16))) + if variant in ("body4", "bubble4"): + strokes.append(_line((-0.35, 0), (1, 0))) + if variant == "body4": + if is_p: + fills.append(_closed((0.35, 0), (0.07, -0.16), (0.07, 0.16))) + else: + fills.append(_closed((-0.3, 0), (-0.02, -0.16), (-0.02, 0.16))) + pins["b"] = (1, 0) + dirs["b"] = (1, 0) + return SymbolGeometry(tuple(strokes), tuple(fills), pins, dirs) + + +def _supply(cls: str, variant: str) -> SymbolGeometry: + """ + VDD (pin at bottom, symbol above) or GND (pin at top, symbol below). + + Args: + cls: "VDD" or "GND". + variant: One of VARIANTS[cls]. + Returns: + Symbol geometry. + """ + strokes: list[np.ndarray] = [] + fills: list[np.ndarray] = [] + if cls == "VDD": + if variant == "bar": + strokes += [_line((0, 0), (0, -1)), _line((-0.7, -1), (0.7, -1))] + elif variant == "arrow": + strokes += [_line((0, 0), (0, -1.25)), _line((-0.45, -0.8), (0, -1.25), (0.45, -0.8))] + else: + strokes += [_line((0, 0), (0, -0.85)), _circle(0, -1.12, 0.27)] + return SymbolGeometry(tuple(strokes), (), {"pos": (0, 0)}, {"pos": (0, 1)}) + strokes.append(_line((0, 0), (0, 1))) + if variant == "bars": + strokes += [_line((-0.7, 1), (0.7, 1)), _line((-0.45, 1.25), (0.45, 1.25)), _line((-0.2, 1.5), (0.2, 1.5))] + elif variant == "triangle": + strokes.append(_closed((-0.6, 1), (0.6, 1), (0, 1.6))) + else: + fills.append(_closed((-0.6, 1), (0.6, 1), (0, 1.6))) + strokes.append(_closed((-0.6, 1), (0.6, 1), (0, 1.6))) + return SymbolGeometry(tuple(strokes), tuple(fills), {"gnd": (0, 0)}, {"gnd": (0, -1)}) + + +def _port(cls: str, variant: str) -> SymbolGeometry: + """ + Input port (drives a net to its right) or output port (net arrives from its left). + + Args: + cls: "INPUT_PORT" or "OUTPUT_PORT". + variant: One of VARIANTS[cls]. + Returns: + Symbol geometry. + """ + if cls == "INPUT_PORT": + if variant == "tag": + strokes = (_closed((-2.4, -0.5), (-1.0, -0.5), (-0.5, 0), (-1.0, 0.5), (-2.4, 0.5)), _line((-0.5, 0), (0, 0))) + return SymbolGeometry(strokes, (), {"out": (0, 0)}, {"out": (1, 0)}) + strokes = (_line((-2.2, 0), (0, 0)),) + fills = (_closed((-1.25, -0.38), (-0.35, 0), (-1.25, 0.38)),) + return SymbolGeometry(strokes, fills, {"out": (0, 0)}, {"out": (1, 0)}) + if variant == "tag": + strokes = (_line((0, 0), (0.5, 0)), _closed((0.5, -0.5), (1.9, -0.5), (2.4, 0), (1.9, 0.5), (0.5, 0.5))) + return SymbolGeometry(strokes, (), {"a": (0, 0)}, {"a": (-1, 0)}) + strokes = (_line((0, 0), (2.2, 0)),) + fills = (_closed((1.4, -0.38), (2.3, 0), (1.4, 0.38)),) + return SymbolGeometry(strokes, fills, {"a": (0, 0)}, {"a": (-1, 0)}) + + +_IEC_TEXT = {"AND": "&", "NAND": "&", "OR": ">=1", "NOR": ">=1", "XOR": "=1", "XNOR": "=1", "NOT": "1"} + + +def _gate(cls: str, variant: str) -> SymbolGeometry: + """ + Logic gate facing right: inputs a (-1,-1) and b (-1,1) (NOT: a at (-1,0)), output at the right. + + Args: + cls: Gate class (AND ... XNOR). + variant: "ansi" (distinctive shapes) or "iec" (rectangle with qualifier text). + Returns: + Symbol geometry. + """ + inverted = cls in ("NAND", "NOR", "XNOR", "NOT") + strokes: list[np.ndarray] = [] + texts: list[tuple[str, tuple[float, float], float]] = [] + if cls == "NOT": + pins = {"a": (-1, 0), "out": (3, 0)} + dirs = {"a": (-1, 0), "out": (1, 0)} + if variant == "iec": + strokes += [_closed((0, -1), (2, -1), (2, 1), (0, 1)), _line((-1, 0), (0, 0))] + texts.append(("1", (1.0, 0.0), 0.8)) + else: + strokes += [_closed((0, -1), (0, 1), (2, 0)), _line((-1, 0), (0, 0))] + strokes += [_circle(2.22, 0, 0.22), _line((2.44, 0), (3, 0))] + return SymbolGeometry(tuple(strokes), (), pins, dirs, tuple(texts)) + pins = {"a": (-1, -1), "b": (-1, 1), "out": (4, 0)} + dirs = {"a": (-1, 0), "b": (-1, 0), "out": (1, 0)} + if variant == "iec": + strokes.append(_closed((0, -1.5), (2.6, -1.5), (2.6, 1.5), (0, 1.5))) + strokes += [_line((-1, -1), (0, -1)), _line((-1, 1), (0, 1))] + texts.append((_IEC_TEXT[cls], (1.3, 0.0), 0.8)) + front = 2.6 + else: + shift = 0.4 if cls in ("XOR", "XNOR") else 0.0 + length = 2.6 if inverted else 3.0 + if cls in ("AND", "NAND"): + straight = length - 1.5 + strokes.append(_line((straight, -1.5), (0, -1.5), (0, 1.5), (straight, 1.5))) + strokes.append(_arc(straight, 0, 1.5, 1.5, -90, 90)) + back_x = 0.0 + else: + strokes.append(_bezier((shift, -1.5), (shift + 0.6, 0), (shift, 1.5))) + strokes.append(_bezier((shift, -1.5), (shift + 0.63 * length, -1.5), (shift + length, 0))) + strokes.append(_bezier((shift, 1.5), (shift + 0.63 * length, 1.5), (shift + length, 0))) + if shift: + strokes.append(_bezier((0, -1.5), (0.6, 0), (0, 1.5))) + back_x = 0.1667 + strokes += [_line((-1, -1), (back_x, -1)), _line((-1, 1), (back_x, 1))] + front = shift + length + if inverted: + strokes.append(_circle(front + 0.22, 0, 0.22)) + front += 0.44 + strokes.append(_line((front, 0), (4, 0))) + return SymbolGeometry(tuple(strokes), (), pins, dirs, tuple(texts)) + + +@lru_cache(maxsize=None) +def symbol_geometry(cls: str, variant: str) -> SymbolGeometry: + """ + Local geometry for a class and style variant. + + Args: + cls: Tier-A class name except JUNCTION (drawn by the renderer as a dot). + variant: Variant name (gates use VARIANTS["GATE"]). + Returns: + Symbol geometry in canonical orientation. + Raises: + ValueError: For unknown classes. + """ + if cls in ("NMOS", "PMOS"): + return _mosfet(cls, variant) + if cls in ("VDD", "GND"): + return _supply(cls, variant) + if cls in ("INPUT_PORT", "OUTPUT_PORT"): + return _port(cls, variant) + if cls in ("AND", "OR", "NOT", "NAND", "NOR", "XOR", "XNOR"): + return _gate(cls, variant) + raise ValueError(f"no symbol geometry for class {cls!r}") + + +def orient_points(pts: np.ndarray, rotation: int, mirror: bool) -> np.ndarray: + """ + Apply an orientation to local points (mirror x first, then rotate clockwise). + + Args: + pts: Nx2 array. + rotation: 0, 90, 180 or 270 degrees clockwise (y-down screen). + mirror: Mirror horizontally before rotating. + Returns: + Nx2 transformed array. + """ + out = np.array(pts, dtype=np.float64).reshape(-1, 2).copy() + if mirror: + out[:, 0] = -out[:, 0] + for _ in range((rotation // 90) % 4): + out = np.stack([-out[:, 1], out[:, 0]], axis=1) + return out + + +def orient_grid(p: GridPoint, rotation: int, mirror: bool) -> GridPoint: + """ + Orient one integer grid point or direction. + + Args: + p: (x, y) integers. + rotation: Degrees clockwise. + mirror: Mirror before rotating. + Returns: + Transformed integer point. + """ + x, y = p + if mirror: + x = -x + for _ in range((rotation // 90) % 4): + x, y = -y, x + return (x, y) + + +def compose_orientation(inner: tuple[int, bool], outer: tuple[int, bool]) -> tuple[int, bool]: + """ + Orientation equal to applying `inner` then `outer`. + + Args: + inner: (rotation, mirror) applied first. + outer: (rotation, mirror) applied second. + Returns: + Combined (rotation, mirror). + """ + r1, m1 = inner + r2, m2 = outer + if m2: + return ((r2 - r1) % 360, not m1) + return ((r1 + r2) % 360, m1) + + +def orientation_for(cls: str, variant: str, pin: str, direction: GridPoint, mirror: bool = False) -> int: + """ + Rotation that makes a given pin face a given direction. + + Args: + cls: Class name. + variant: Variant name. + pin: Pin name. + direction: Desired outward unit direction. + mirror: Whether the symbol is mirrored. + Returns: + Rotation in degrees. + Raises: + ValueError: If no rotation achieves it. + """ + geom = symbol_geometry(cls, variant) + for rot in (0, 90, 180, 270): + if orient_grid(geom.pin_dirs[pin], rot, mirror) == direction: + return rot + raise ValueError(f"cannot face {cls}.{pin} towards {direction}") diff --git a/backend/test_generate_v2.py b/backend/test_generate_v2.py new file mode 100644 index 0000000..0b4a71d --- /dev/null +++ b/backend/test_generate_v2.py @@ -0,0 +1,243 @@ +""" +Module: test_generate_v2.py +Purpose: Acceptance tests for the v2 synthetic generator (backend/data_gen/generate_v2.py): + byte-identical manifests for a fixed seed regardless of worker count, YOLO label + bounds, no empty images, per-domain class balance, junction dot sizes, drawn wires + that connect exactly the netlist pins, topology-hash splits with held-out styles only + in test, and a 100% truth-table check of every netlist against DigiSim's switch-level + solver (frontend/scripts/verifySynthNetlists.js, run with node). +""" + +import json +import shutil +import subprocess +from pathlib import Path + +import cv2 +import numpy as np +import pytest + +from data_gen.generate_v2 import DOMAIN_CLASSES, balance_report, generate_dataset +from data_gen.synth_v2.render import DOT_MAX_PER_1000, DOT_MIN_PER_1000, HELD_OUT_FONT, HELD_OUT_LINE, HELD_OUT_PAPER +from data_gen.synth_v2.schema import TIER_A +from data_gen.synth_v2.symbols import compose_orientation, orient_grid + +REPO_ROOT = Path(__file__).resolve().parent.parent +VERIFY_SCRIPT = REPO_ROOT / "frontend" / "scripts" / "verifySynthNetlists.js" +DATASET_COUNT = 240 + + +@pytest.fixture(scope="module") +def dataset(tmp_path_factory: pytest.TempPathFactory) -> Path: + """ + Generate one small dataset shared by the tests in this module. + + Args: + tmp_path_factory: Pytest temp dir factory. + Returns: + Dataset root. + """ + root = tmp_path_factory.mktemp("synth_v2") + generate_dataset(root, DATASET_COUNT, seed=3, workers=4) + return root + + +def _entries(root: Path) -> list[dict]: + """ + Manifest sample entries. + + Args: + root: Dataset root. + Returns: + List of manifest entries. + """ + return json.loads((root / "manifest.json").read_text())["samples"] + + +def _annotation(root: Path, entry: dict) -> dict: + """ + Load a sample's annotation JSON. + + Args: + root: Dataset root. + entry: Manifest entry. + Returns: + Annotation dict. + """ + return json.loads((root / entry["files"]["annotation"]["path"]).read_text()) + + +def test_manifest_byte_identical_across_runs_and_workers(tmp_path: Path) -> None: + """Same seed gives the same manifest bytes, independent of the worker count.""" + generate_dataset(tmp_path / "a", 24, seed=11, workers=1) + generate_dataset(tmp_path / "b", 24, seed=11, workers=3) + assert (tmp_path / "a" / "manifest.json").read_bytes() == (tmp_path / "b" / "manifest.json").read_bytes() + generate_dataset(tmp_path / "c", 24, seed=12, workers=1) + assert (tmp_path / "a" / "manifest.json").read_bytes() != (tmp_path / "c" / "manifest.json").read_bytes() + + +def test_manifest_hashes_match_files(dataset: Path) -> None: + """Every file listed in the manifest exists and matches its SHA-256.""" + import hashlib + + entries = _entries(dataset) + assert len(entries) == DATASET_COUNT + for e in entries: + for f in e["files"].values(): + assert hashlib.sha256((dataset / f["path"]).read_bytes()).hexdigest() == f["sha256"] + + +def test_label_bounds_and_counts(dataset: Path) -> None: + """YOLO labels use tier-A ids, are normalised inside the image, and match the annotation.""" + for e in _entries(dataset): + ann = _annotation(dataset, e) + w, h = ann["image"]["width"], ann["image"]["height"] + lines = (dataset / e["files"]["label"]["path"]).read_text().splitlines() + assert len(lines) == len(ann["symbols"]) + len(ann["junctions"]) > 0 + for line in lines: + cid, cx, cy, bw, bh = line.split() + assert 0 <= int(cid) < len(TIER_A) + cx, cy, bw, bh = float(cx), float(cy), float(bw), float(bh) + assert 0 < bw <= 1 and 0 < bh <= 1 + assert 0 <= cx - bw / 2 + 1e-6 and cx + bw / 2 <= 1 + 1e-6 + assert 0 <= cy - bh / 2 + 1e-6 and cy + bh / 2 <= 1 + 1e-6 + for sym in ann["symbols"]: + x1, y1, x2, y2 = sym["bbox"] + assert x2 - x1 > 3 and y2 - y1 > 3 + for px, py in sym["pins"].values(): + assert 0 <= px <= w and 0 <= py <= h + # Pins sit on the lead ends, i.e. on (or within a few px of) the box boundary. + assert x1 - 1 <= px <= x2 + 1 and y1 - 1 <= py <= y2 + 1 + + +def test_no_empty_images(dataset: Path) -> None: + """Every image decodes, matches the annotated size and contains ink.""" + for e in _entries(dataset): + ann = _annotation(dataset, e) + img = cv2.imread(str(dataset / e["files"]["image"]["path"]), cv2.IMREAD_GRAYSCALE) + assert img is not None + assert img.shape == (ann["image"]["height"], ann["image"]["width"]) + background = float(np.median(img)) + assert float((img < background - 60).mean()) > 0.003, e["id"] + + +def test_class_balance_per_domain(dataset: Path) -> None: + """Within each domain no class falls under 10% of the most frequent class.""" + report = json.loads((dataset / "balance_report.json").read_text()) + for domain in DOMAIN_CLASSES: + info = report["domains"][domain] + assert info["images"] > 0 + assert info["passes"], (domain, info["ratio_to_max"]) + + +def test_balance_report_flags_imbalance() -> None: + """The balance check fails when a class is rare.""" + rare = [{"class": c} for c in DOMAIN_CLASSES["gate"] if c not in ("AND", "JUNCTION")] + ann = {"domain": "gate", "split": "train", "image": {"width": 1000}, "junctions": [], "symbols": [{"class": "AND"}] * 20 + rare} + assert not balance_report([ann])["domains"]["gate"]["passes"] + + +def test_junction_dot_size_matches_real(dataset: Path) -> None: + """Junction dot diameter is 10-17 px at 1000 px image width.""" + dots = [j["diameter"] * 1000 / _annotation(dataset, e)["image"]["width"] for e in _entries(dataset) for j in _annotation(dataset, e)["junctions"]] + assert dots + assert DOT_MIN_PER_1000 - 0.05 <= min(dots) and max(dots) <= DOT_MAX_PER_1000 + 0.05 + + +def test_wires_connect_exactly_the_netlist_pins(dataset: Path) -> None: + """Each pin is a wire end of its own net, and each drawn net is one connected tree.""" + for e in _entries(dataset): + ann = _annotation(dataset, e) + parent: dict[tuple, tuple] = {} + + def find(k: tuple) -> tuple: + """Union-find root.""" + while parent.setdefault(k, k) != k: + k = parent[k] + return k + + ends: dict[tuple, str] = {} + for wire in ann["wires"]: + pts = [(wire["net"], round(x, 1), round(y, 1)) for x, y in wire["points"]] + for a, b in zip(pts[:-1], pts[1:]): + parent[find(a)] = find(b) + for p in (pts[0], pts[-1]): + ends[p[1:]] = wire["net"] + net_roots: dict[str, set] = {} + for sym in ann["symbols"]: + for term, (px, py) in sym["pins"].items(): + key = (round(px, 1), round(py, 1)) + net = sym["nets"][term] + assert ends.get(key) == net, (e["id"], sym["id"], term) + if net not in ("VDD", "GND"): + net_roots.setdefault(net, set()).add(find((net, *key))) + for j in ann["junctions"]: + assert (round(j["center"][0], 1), round(j["center"][1], 1)) in ends, (e["id"], j) + for net, roots in net_roots.items(): + assert len(roots) == 1, (e["id"], net) + + +def test_topology_splits_and_held_out_styles(dataset: Path) -> None: + """A topology lives in one split only; held-out style values appear only in held-out test samples.""" + split_of: dict[str, str] = {} + for e in _entries(dataset): + assert split_of.setdefault(e["topology_hash"], e["split"]) == e["split"] + style = _annotation(dataset, e)["render_style"] + uses_held_out = style["font"] == HELD_OUT_FONT or style["paper"] == HELD_OUT_PAPER or style["line"] == HELD_OUT_LINE + if e["held_out_style"]: + assert e["split"] == "test" and style["font"] == HELD_OUT_FONT and style["paper"] == HELD_OUT_PAPER + else: + assert not uses_held_out, e["id"] + if any(s["class"] == "VDD" and s["variant"] == "circle" for s in _annotation(dataset, e)["symbols"]): + assert e["held_out_style"] + assert {e["split"] for e in _entries(dataset)} == {"train", "valid", "test"} + + +def test_orientation_composition() -> None: + """compose_orientation equals applying the two orientations in sequence.""" + for r1 in (0, 90, 180, 270): + for m1 in (False, True): + for r2 in (0, 90, 180, 270): + for m2 in (False, True): + r, m = compose_orientation((r1, m1), (r2, m2)) + for p in ((2, 1), (-1, 3)): + assert orient_grid(orient_grid(p, r1, m1), r2, m2) == orient_grid(p, r, m) + + +def _run_verifier(root: Path) -> subprocess.CompletedProcess: + """ + Run the node switch-level verifier on a dataset. + + Args: + root: Dataset root. + Returns: + Completed process. + """ + return subprocess.run(["node", str(VERIFY_SCRIPT), str(root)], capture_output=True, text=True, timeout=600, check=False) + + +needs_node = pytest.mark.skipif( + shutil.which("node") is None or not (REPO_ROOT / "frontend" / "node_modules" / "typescript").exists(), + reason="needs node and frontend/node_modules (cd frontend && npm install)", +) + + +@needs_node +def test_all_netlists_pass_switch_level_truth_table(dataset: Path) -> None: + """100% of generated netlists reproduce their truth table in DigiSim's switch-level solver.""" + result = _run_verifier(dataset) + assert result.returncode == 0, result.stdout + result.stderr + assert f"{DATASET_COUNT}/{DATASET_COUNT} netlists pass" in result.stdout + + +@needs_node +def test_verifier_catches_a_broken_netlist(dataset: Path, tmp_path: Path) -> None: + """Swapping a transistor gate to the wrong net makes the verifier fail.""" + entry = next(e for e in _entries(dataset) if e["domain"] == "transistor") + netlist = json.loads((dataset / entry["files"]["netlist"]["path"]).read_text()) + mos = next(c for c in netlist["components"] if c["class"] == "NMOS") + mos["pins"]["g"] = "VDD" + (tmp_path / "x.json").write_text(json.dumps(netlist)) + result = _run_verifier(tmp_path) + assert result.returncode == 1 + assert "0/1 netlists pass" in result.stdout diff --git a/docs/synth_v2/README.md b/docs/synth_v2/README.md new file mode 100644 index 0000000..3b5d678 --- /dev/null +++ b/docs/synth_v2/README.md @@ -0,0 +1,68 @@ +# Synthetic circuit dataset v2 + +Generator: `backend/data_gen/generate_v2.py` (package `backend/data_gen/synth_v2/`). Class vocabulary: tier A of `ml/classes.yaml`. + +```bash +cd backend +uv run python data_gen/generate_v2.py --count 8000 --seed 1 # -> ml/dataset/synth_v2 (gitignored) +uv run python data_gen/generate_v2.py --count 8000 --seed 1 --out DIR --workers 4 +node ../frontend/scripts/verifySynthNetlists.js DIR # switch-level truth-table check +uv run python data_gen/synth_v2/contact_sheet.py --data DIR --out sheet.jpg --samples 50 +uv run pytest test_generate_v2.py +``` + +## What it generates + +1. **Netlist-driven topologies** (`logic.py`). + - **Transistor domain (70%):** static CMOS cells built from series-parallel pull-down/pull-up networks (INV, NAND2/3, NOR2/3, AOI/OAI 21/22/211, random complex gates), AND/OR/BUF, XOR/XNOR, transmission-gate 2:1 mux, and random 2-3 stage chains. Some samples also expose an internal stage output as an extra output. + - **Gate domain (30%):** random gate DAGs with 2-4 inputs, 2-8 gates and depth up to 4. + - The reference truth table comes from the abstract boolean function, not from the transistors. +2. **Textbook placement and routing** (`layout.py`, `router.py`). + - Transistor circuits use the CMOS layout: pull-up network on top, pull-down network below, series stacks drawn vertically and parallel branches side by side. Transmission gates are drawn horizontally. + - Gate circuits are laid out left to right in layers. + - Supplies are drawn in one of three styles: a shared rail, one symbol per stage, or one symbol per device. + - Some drawings get a global rotation or mirror. + - An orthogonal maze router draws each net as a tree. Different nets only cross at right angles (no dot, recorded as a crossing), and every same-net branch point gets a junction dot. This makes the drawing an exact picture of the netlist. +3. **Rendering** (`render.py`, `symbols.py`). + - Four modes: cad, textbook, hand-drawn (wobble), and phone photo (perspective, lighting, shadow, blur, noise, JPEG). + - Symbol variants: 3- vs 4-terminal MOSFETs, bubble vs arrow PMOS, dashed channel, ANSI vs IEC gates, and several VDD, GND and port shapes. + - Papers, inks and Hershey fonts are varied. Port, supply and device labels and titles are placed only where they do not touch ink. + - Junction dot diameter is 10-17 px at 1000 px image width, matching the earlier real-data finding. + +## Output layout (per sample `NNNNNN`, split in `train|valid|test`) + +| File | Content | +|---|---| +| `images//NNNNNN.jpg` | image | +| `labels//NNNNNN.txt` | YOLO boxes, ids from `ml/classes.yaml` (symbols and JUNCTION dots) | +| `annotations//NNNNNN.json` | per symbol: id, class, bbox, variant, **pin points** per terminal, **orientation** (`rotation` clockwise after optional `mirror`), terminal nets; junctions (center, diameter, bbox, net); wire polylines per net; crossings; text boxes; render style | +| `netlists//NNNNNN.json` | components (devices, ports, supply symbols, with `node_type` and terminal-to-net pins), nets, inputs, outputs, reference truth table, topology hash | +| `manifest.json` | seed, count, per-sample split/domain/recipe/topology hash/held-out flag and SHA-256 of every file (canonical JSON, byte-identical for a given seed and count) | +| `balance_report.json` | per-domain and per-split class counts, the 10%-of-max rule, junction dot size stats | +| `data.yaml` | YOLO dataset config (tier A) | + +## Splits and held-out styles + +- **Split:** decided by an isomorphism-invariant topology hash of the logical circuit (Weisfeiler-Lehman over devices, nets and port roles). The result is about 80/10/10, and a circuit never appears in two splits. +- **Held-out styles:** half of the test samples use a style that train and valid never see: the `script_complex` font, `grid` paper, the `sketch` double-stroke line style and the `circle` VDD symbol. + +## Acceptance run (seed 1, 8000 samples, 4 workers) + +- **Reproducibility:** two runs gave byte-identical `manifest.json` (sha256 `36bc64bff0c19ddd1c332a45715a04c21c133e87b365de2006cc3022459a2aad`). About 9 min each under `nice` with 4 workers, 723 MB output. +- **Splits:** train 6354, valid 834, test 812. 391 test samples use held-out styles. +- **Truth tables:** `verifySynthNetlists.js` passes 8000/8000 netlists (5616 transistor, 2384 gate) with DigiSim's `switchLevel.ts` solver. Gate netlists are lowered to static CMOS first. +- **Class balance** (no class under 10% of the domain max): + + | Domain | Images | Counts | Min ratio | + |---|---|---|---| + | Transistor | 5616 | NMOS 20642, PMOS 20642, VDD 10117, GND 10043, INPUT_PORT 15019, OUTPUT_PORT 6681, JUNCTION 57391 | 0.116 (OUTPUT_PORT) | + | Gate | 2384 | AND 1144, OR 1169, NOT 1330, NAND 1119, NOR 1109, XOR 1170, XNOR 1122, INPUT_PORT 6917, OUTPUT_PORT 2982, JUNCTION 2862 | 0.160 (NOR) | + +- **Junction dots:** 60253 dots, diameter 10.0-17.0 px per 1000 px width (mean 12.3). +- `contact_sheet.jpg`: overlays of 50 random samples from this run. It shows class boxes, pin points with terminal names, junction boxes (red) and crossings (magenta x). + +## Limits and follow-ups + +- **Combinational circuits only.** The switch-level solver resolves one combinational state, so circuits with feedback (latches, 6T SRAM, ring oscillators) are not generated. Adding them needs a sequential check. +- **Tier B (analog) classes are not drawn yet.** +- **Committed manifest:** the per-file `ml/data_manifest.json` that merges synthetic and real data belongs to the real-data ingestion task. This generator writes its own `manifest.json` next to the data. diff --git a/docs/synth_v2/contact_sheet.jpg b/docs/synth_v2/contact_sheet.jpg new file mode 100644 index 0000000..9bb956c Binary files /dev/null and b/docs/synth_v2/contact_sheet.jpg differ diff --git a/frontend/scripts/verifySynthNetlists.js b/frontend/scripts/verifySynthNetlists.js new file mode 100644 index 0000000..6c0f862 --- /dev/null +++ b/frontend/scripts/verifySynthNetlists.js @@ -0,0 +1,237 @@ +/** + * @file verifySynthNetlists.js + * @description Checks every netlist written by backend/data_gen/generate_v2.py against + * DigiSim's own switch-level CMOS solver (src/logic/simulation/switchLevel.ts). Transistor + * netlists are simulated as drawn; gate-level netlists are first lowered to static CMOS + * (NAND/NOR/INV templates, XOR from four NANDs). Every row of the reference truth table must + * match with clean 0/1 outputs. switchLevel.ts is transpiled in memory with the frontend's + * TypeScript compiler, so the check always runs the shipped solver code. + * + * Usage: node frontend/scripts/verifySynthNetlists.js [--json report.json] + * Exit code 0 when 100% of netlists pass, 1 otherwise. + */ + +const fs = require('fs'); +const path = require('path'); +const Module = require('module'); +const ts = require('typescript'); + +/** + * Load switchLevel.ts as a CommonJS module. + * @returns The module exports ({ solveSwitchNets, ... }) + */ +function loadSolver() { + const file = path.join(__dirname, '..', 'src', 'logic', 'simulation', 'switchLevel.ts'); + const source = fs.readFileSync(file, 'utf8'); + const { outputText } = ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2019 }, + fileName: file, + }); + const mod = new Module(file, module); + mod.filename = file; + mod.paths = Module._nodeModulePaths(path.dirname(file)); + mod._compile(outputText, file); + return mod.exports; +} + +/** + * Recursively list netlist JSON files under a directory. + * @param dir - Directory to scan + * @returns Sorted absolute paths of *.json files + */ +function listNetlists(dir) { + const out = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) out.push(...listNetlists(full)); + else if (entry.name.endsWith('.json')) out.push(full); + } + return out.sort(); +} + +/** Handle prefix and terminal names per node type, as the canvas uses them. */ +const HANDLE = { + nmos: (t) => `t:${t}`, + pmos: (t) => `t:${t}`, + vsource: (t) => `s:${t}`, + ground: () => 't:gnd', + input: () => null, + output: () => null, +}; + +/** + * Lower one gate instance to static CMOS transistors. + * @param gate - Netlist component of a gate class + * @param fresh - Generator of unique internal net names + * @returns List of { type, pins } transistor records + */ +function lowerGate(gate, fresh) { + const { a, b, out } = gate.pins; + const inv = (x, y) => [ + { type: 'pmos', pins: { s: 'VDD', g: x, d: y } }, + { type: 'nmos', pins: { d: y, g: x, s: 'GND' } }, + ]; + const nand = (x, y, z) => { + const m = fresh(); + return [ + { type: 'pmos', pins: { s: 'VDD', g: x, d: z } }, + { type: 'pmos', pins: { s: 'VDD', g: y, d: z } }, + { type: 'nmos', pins: { d: z, g: x, s: m } }, + { type: 'nmos', pins: { d: m, g: y, s: 'GND' } }, + ]; + }; + const nor = (x, y, z) => { + const m = fresh(); + return [ + { type: 'pmos', pins: { s: 'VDD', g: x, d: m } }, + { type: 'pmos', pins: { s: m, g: y, d: z } }, + { type: 'nmos', pins: { d: z, g: x, s: 'GND' } }, + { type: 'nmos', pins: { d: z, g: y, s: 'GND' } }, + ]; + }; + const xor = (x, y, z) => { + const n1 = fresh(); + const n2 = fresh(); + const n3 = fresh(); + return [...nand(x, y, n1), ...nand(x, n1, n2), ...nand(y, n1, n3), ...nand(n2, n3, z)]; + }; + const t = fresh(); + switch (gate.class) { + case 'NOT': return inv(a, out); + case 'NAND': return nand(a, b, out); + case 'NOR': return nor(a, b, out); + case 'AND': return [...nand(a, b, t), ...inv(t, out)]; + case 'OR': return [...nor(a, b, t), ...inv(t, out)]; + case 'XOR': return xor(a, b, out); + case 'XNOR': return [...xor(a, b, t), ...inv(t, out)]; + default: throw new Error(`cannot lower class ${gate.class}`); + } +} + +/** + * Build canvas nodes/edges for one input assignment. + * @param netlist - Parsed netlist JSON + * @param assignment - Input values by port name + * @returns { nodes, edges, outputIds } where outputIds maps output name to node id + */ +function buildCircuit(netlist, assignment) { + const nodes = []; + const terminals = new Map(); // net -> [{ id, handle }] + const attach = (net, id, handle) => { + if (!terminals.has(net)) terminals.set(net, []); + terminals.get(net).push({ id, handle }); + }; + const addNode = (id, type, pins, value) => { + nodes.push({ id, type, position: { x: 0, y: 0 }, data: { label: id, value } }); + for (const [term, net] of Object.entries(pins)) { + // Bulk terminals are ignored by the solver (autoBulk); an edge from one would be dropped. + if ((type === 'nmos' || type === 'pmos') && term === 'b') continue; + attach(net, id, HANDLE[type](term)); + } + }; + const outputIds = {}; + let counter = 0; + const fresh = () => `__lowered_${counter++}`; + let needsSupplies = false; + for (const comp of netlist.components) { + switch (comp.class) { + case 'NMOS': + case 'PMOS': + addNode(comp.id, comp.node_type, comp.pins); + break; + case 'VDD': + addNode(comp.id, 'vsource', comp.pins); + break; + case 'GND': + addNode(comp.id, 'ground', comp.pins); + break; + case 'INPUT_PORT': + addNode(comp.id, 'input', comp.pins, assignment[comp.label]); + break; + case 'OUTPUT_PORT': + addNode(comp.id, 'output', comp.pins, 0); + outputIds[comp.label] = comp.id; + break; + default: { + needsSupplies = true; + lowerGate(comp, fresh).forEach((tr, i) => addNode(`${comp.id}__${i}`, tr.type, tr.pins)); + } + } + } + if (needsSupplies) { + addNode('__vdd', 'vsource', { pos: 'VDD' }); + addNode('__gnd', 'ground', { gnd: 'GND' }); + } + const edges = []; + for (const [net, list] of terminals) { + for (let i = 1; i < list.length; i++) { + edges.push({ + id: `${net}#${i}`, + source: list[0].id, + sourceHandle: list[0].handle, + target: list[i].id, + targetHandle: list[i].handle, + }); + } + } + return { nodes, edges, outputIds }; +} + +/** + * Check one netlist against its truth table. + * @param netlist - Parsed netlist JSON + * @param solver - switchLevel module exports + * @returns null when every row matches, else a failure description + */ +function checkNetlist(netlist, solver) { + for (const row of netlist.truth_table) { + const { nodes, edges, outputIds } = buildCircuit(netlist, row.in); + const byId = new Map(nodes.map((n) => [n.id, n])); + const solved = solver.solveSwitchNets(nodes, edges, byId); + for (const [name, expected] of Object.entries(row.out)) { + const got = solver.switchRootValue(solved, outputIds[name]); + if (got !== expected) return `in=${JSON.stringify(row.in)} ${name}: expected ${expected}, got ${got}`; + } + } + return null; +} + +/** + * CLI entry point. + * @returns Process exit code + */ +function main() { + const args = process.argv.slice(2); + const dir = args[0]; + if (!dir) { + console.error('usage: node verifySynthNetlists.js [--json report.json]'); + return 2; + } + const jsonIdx = args.indexOf('--json'); + const solver = loadSolver(); + // A dataset root also holds annotation JSON, so scan only its netlists/ subtree when present. + const netlistDir = path.join(dir, 'netlists'); + const files = listNetlists(fs.existsSync(netlistDir) ? netlistDir : dir); + const failures = []; + const byDomain = {}; + for (const file of files) { + const netlist = JSON.parse(fs.readFileSync(file, 'utf8')); + const d = (byDomain[netlist.domain] = byDomain[netlist.domain] || { total: 0, passed: 0 }); + d.total += 1; + let problem; + try { + problem = checkNetlist(netlist, solver); + } catch (err) { + problem = `error: ${err.message}`; + } + if (problem) failures.push({ file: path.relative(dir, file), problem }); + else d.passed += 1; + } + const report = { total: files.length, passed: files.length - failures.length, by_domain: byDomain, failures }; + if (jsonIdx >= 0) fs.writeFileSync(args[jsonIdx + 1], `${JSON.stringify(report, null, 2)}\n`); + console.log(`switch-level truth-table check: ${report.passed}/${report.total} netlists pass ${JSON.stringify(byDomain)}`); + failures.slice(0, 20).forEach((f) => console.log(` FAIL ${f.file}: ${f.problem}`)); + return files.length > 0 && failures.length === 0 ? 0 : 1; +} + +process.exitCode = main();