From 951608c1bad89bbad1157f5364d861a44994e612 Mon Sep 17 00:00:00 2001 From: Alex Van Damme Date: Fri, 13 Nov 2026 18:17:54 -0800 Subject: [PATCH] Clip router SVG geometry to viewport bounds Clip belt, pipe, and tunnel segments in showcase_svg.py to the 48x36 viewport box. Wrap routed panels and placement panels in SVG clipPath elements. Extend 1-tile belts along their travel vector and query machine footprints dynamically. Remove duplicate reduction text that overlaps the placement badge. Add coordinate bounds tests for all four pipeline SVGs. --- site/assets/pipeline_lp_dag.svg | 1 + site/assets/pipeline_placement.svg | 631 +++++++++++----------- site/assets/pipeline_router_3d.svg | 235 ++++++-- site/assets/pipeline_verilog_campaign.svg | 1 + test/test_showcase_site.py | 249 ++++++++- tools/build_showcase_site.py | 122 +++-- tools/showcase_data.py | 14 +- tools/showcase_svg.py | 381 ++++++++++--- 8 files changed, 1150 insertions(+), 484 deletions(-) diff --git a/site/assets/pipeline_lp_dag.svg b/site/assets/pipeline_lp_dag.svg index 6c8d3e7..3f89980 100644 --- a/site/assets/pipeline_lp_dag.svg +++ b/site/assets/pipeline_lp_dag.svg @@ -2,6 +2,7 @@ + diff --git a/site/assets/pipeline_placement.svg b/site/assets/pipeline_placement.svg index 4e6f660..1c3f9dd 100644 --- a/site/assets/pipeline_placement.svg +++ b/site/assets/pipeline_placement.svg @@ -2,8 +2,11 @@ + + + @@ -15,6 +18,7 @@ HPWL 107,969 + @@ -276,64 +280,64 @@ - - - - - - - - + + + + + + + + - - - - + + + + - - - + + + - - + + - + - - - + + + - - + + - + - - - + + + - - - - - - - - - - - - - + + + + + + + + + + + + + @@ -355,23 +359,23 @@ - - - - - - - - - - + + + + + + + + + + - - + + @@ -415,13 +419,13 @@ - - - - - - - + + + + + + + @@ -537,15 +541,15 @@ - - - - - - + + + + + + - - + + @@ -776,65 +780,65 @@ - - - + + + - - + + - + - - - + + + - - - - + + + + - - - + + + - - - - + + + + - - - + + + - - - - + + + + - - - + + + - - + + - + - - - - - + + + + + @@ -853,9 +857,10 @@ - - - + + + + @@ -870,10 +875,11 @@ Rank gradient: West inputs (cyan) -> East science outputs (rose) | Street width: 6 tiles -Quadratic + SCC + 94x94 Legalized (HPWL: 22,482 tiles, -79.2%) +Quadratic + SCC + 94x94 Legalized (HPWL: 22,482 tiles) -79.2% HPWL + @@ -1145,152 +1151,152 @@ - - - - - - - - + + + + + + + + - - - - + + + + - - - - - - - - + + + + + + + + - - - + + + - - - + + + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1406,15 +1412,15 @@ - - - - - - - - - + + + + + + + + + @@ -1641,52 +1647,52 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - - - - - - + + + + + + + @@ -1696,35 +1702,36 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/site/assets/pipeline_router_3d.svg b/site/assets/pipeline_router_3d.svg index 909ef70..94e294c 100644 --- a/site/assets/pipeline_router_3d.svg +++ b/site/assets/pipeline_router_3d.svg @@ -2,20 +2,22 @@ + + Stage 3: Two-Stage 3D Multi-Layer Dual-Lane Maze Router and Underground Transitions -Left: real routed chassis slice [188,182]..[236,218] tiles | Right: z-layer PDK stack & negotiated congestion +Left: real routed chassis slice [176,242]..[224,278] tiles | Right: z-layer PDK stack & negotiated congestion Routed Block-to-Street Detail (48x36 tiles) 0 DRC - + @@ -39,8 +41,6 @@ - - @@ -58,52 +58,185 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Amber: M1 surface belts | Cyan dashed: M2 tunnels | Violet: M3 fluid pipes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Teal: Macros | Amber: M1 belts | Cyan dashed: M2 tunnels | Violet: M3 pipes 3D Layer Stack & Negotiated Congestion @@ -114,7 +247,7 @@ Assembling machines, inserters, splitters, dual-lane belts z = 1..N (M2 Tunnels) -Prototype spans: express-underground-belt=9t, fast-undergrou.. +Spans: express-ug=9t, fast-ug=7t, pipe-to-ground=10t, ug=5t Fluid Grid (M3 Pipes) Pressure-aware surface pipes, pumps, underground jumps diff --git a/site/assets/pipeline_verilog_campaign.svg b/site/assets/pipeline_verilog_campaign.svg index 62aa679..f22211b 100644 --- a/site/assets/pipeline_verilog_campaign.svg +++ b/site/assets/pipeline_verilog_campaign.svg @@ -2,6 +2,7 @@ + diff --git a/test/test_showcase_site.py b/test/test_showcase_site.py index cc0d761..d73f981 100644 --- a/test/test_showcase_site.py +++ b/test/test_showcase_site.py @@ -7,6 +7,7 @@ from __future__ import annotations import json +import math import re import tarfile import unittest @@ -16,7 +17,20 @@ from PIL import Image from foundry.circuit_synth import synthesize_power_sequencer -from tools.showcase_svg import build_verilog_campaign_svg +from foundry.entity_helpers import ( + DIRECTION_EAST, + DIRECTION_NORTH, + DIRECTION_SOUTH, +) +from tools.showcase_svg import ( + PALETTE, + ROUTER_VP_H, + ROUTER_VP_W, + ROUTER_VP_X, + ROUTER_VP_Y, + build_router_3d_svg, + build_verilog_campaign_svg, +) from tools.showcase_template import render_showcase_html RUNFILES_ROOT = Path(__file__).parent.parent @@ -54,6 +68,11 @@ README_ASSET_REF_RE = re.compile(r"\((site/assets/[^)\s]+)\)") SHORT_HEX_RE = re.compile(r"^[0-9a-f]{7,12}$") FULL_HEX_RE = re.compile(r"^[0-9a-f]{40}$") +COORD_PAIR_RE = re.compile(r"(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)") +VP_MIN_LEN = 1.0 +BOUND_EPS = 0.5 +VP_EPS = 0.2 +RIGHT_STACK_X = 644.0 class ShowcaseSiteTest(unittest.TestCase): @@ -168,6 +187,234 @@ def test_generated_site_bundle(self) -> None: for rel_path in README_ASSET_REF_RE.findall(readme_text): self.assertTrue((RUNFILES_ROOT / rel_path).is_file(), f"Broken README link: {rel_path}") + def test_svg_coordinate_bounds(self) -> None: + """Verify all SVG elements stay inside viewBox and router viewport bounds.""" + for svg_name in EXPECTED_SVGS: + root = ET.fromstring((ASSETS_DIR / svg_name).read_text(encoding="utf-8")) + vb_parts = [float(val) for val in root.attrib["viewBox"].split()] + vb_w, vb_h = vb_parts[2], vb_parts[3] + self._assert_tree_within_bounds(root, vb_w, vb_h, svg_name) + + router_root = ET.fromstring( + (ASSETS_DIR / "pipeline_router_3d.svg").read_text(encoding="utf-8") + ) + vp_group = next( + (elem for elem in router_root.iter() if elem.attrib.get("id") == "router-viewport"), + None, + ) + self.assertIsNotNone(vp_group) + assert vp_group is not None + self.assertEqual(vp_group.attrib.get("clip-path"), "url(#router-vp-clip)") + self._assert_router_viewport_contents(vp_group, require_all_layers=True) + + for elem in router_root.iter(): + if not elem.tag.endswith("text"): + continue + if float(elem.attrib.get("x", "0")) >= RIGHT_STACK_X: + text_val = elem.text or "" + self.assertFalse(text_val.endswith(".."), f"Truncated text in SVG: {text_val}") + + def test_router_svg_clips_escaping_segments(self) -> None: + """Verify router SVG clips overflowing runs and extends 1-tile belts cleanly.""" + cat_map = { + "assembling-machine-2": "assembling-machine", + "transport-belt": "transport-belt", + "underground-belt": "underground-belt", + "express-underground-belt": "underground-belt", + "pipe": "pipe", + } + entities: list[dict[str, object]] = [ + {"name": "assembling-machine-2", "position": {"x": 90.0, "y": 20.0}, "direction": 0}, + {"name": "transport-belt", "position": {"x": 94.5, "y": 16.5}, "direction": 0}, + { + "name": "underground-belt", + "type": "input", + "position": {"x": 121.5, "y": 14.5}, + "direction": DIRECTION_EAST, + }, + { + "name": "underground-belt", + "type": "output", + "position": {"x": 126.5, "y": 14.5}, + "direction": DIRECTION_EAST, + }, + { + "name": "express-underground-belt", + "type": "input", + "position": {"x": 88.5, "y": 11.5}, + "direction": DIRECTION_NORTH, + }, + { + "name": "express-underground-belt", + "type": "output", + "position": {"x": 88.5, "y": 4.5}, + "direction": DIRECTION_NORTH, + }, + ] + for tx in range(0, 180): + entities.append( + { + "name": "transport-belt", + "position": {"x": tx + 0.5, "y": 26.5}, + "direction": DIRECTION_EAST, + } + ) + entities.append( + { + "name": "pipe", + "position": {"x": tx + 0.5, "y": 32.5}, + "direction": DIRECTION_NORTH, + } + ) + for ty in range(-20, 120): + entities.append( + { + "name": "transport-belt", + "position": {"x": 102.5, "y": ty + 0.5}, + "direction": DIRECTION_SOUTH, + } + ) + + def_data = { + "units": 1000, + "blockages": [{"x1": 97000, "y1": 0, "x2": 103000, "y2": 120000}], + } + bp_payload = {"entities": entities} + svg_text = build_router_3d_svg( + def_data, + bp_payload, + cat_map, + {"underground-belt": 5, "express-underground-belt": 9, "pipe-to-ground": 10}, + ) + root = ET.fromstring(svg_text) + vp_group = next( + (elem for elem in root.iter() if elem.attrib.get("id") == "router-viewport"), + None, + ) + self.assertIsNotNone(vp_group) + assert vp_group is not None + self._assert_router_viewport_contents(vp_group, require_all_layers=True) + + north_1tile = [ + elem + for elem in vp_group.iter() + if elem.tag.endswith("line") + and elem.attrib.get("stroke") == PALETTE["amber"] + and elem.attrib.get("x1") == elem.attrib.get("x2") + and elem.attrib.get("marker-end") == "url(#arr-belt)" + ] + self.assertTrue(any(float(e.attrib["y2"]) < float(e.attrib["y1"]) for e in north_1tile)) + + def _assert_tree_within_bounds( + self, + elem: ET.Element, + vb_w: float, + vb_h: float, + label: str, + ) -> None: + """Check recursively that SVG elements outside `` stay in `viewBox`.""" + tag = elem.tag.split("}")[-1].lower() + if tag == "marker": + return + for attr in ("x", "x1", "x2", "cx"): + val = elem.attrib.get(attr) + if val is not None: + fval = float(val) + self.assertGreaterEqual(fval, 0.0, f"{label} {tag} {attr}={fval}") + self.assertLessEqual(fval, vb_w, f"{label} {tag} {attr}={fval}") + for attr in ("y", "y1", "y2", "cy"): + val = elem.attrib.get(attr) + if val is not None: + fval = float(val) + self.assertGreaterEqual(fval, 0.0, f"{label} {tag} {attr}={fval}") + self.assertLessEqual(fval, vb_h, f"{label} {tag} {attr}={fval}") + if tag == "rect" and "width" in elem.attrib and "height" in elem.attrib: + w_str, h_str = elem.attrib["width"], elem.attrib["height"] + if not w_str.endswith("%") and not h_str.endswith("%"): + x0 = float(elem.attrib.get("x", "0")) + y0 = float(elem.attrib.get("y", "0")) + self.assertLessEqual(x0 + float(w_str), vb_w + BOUND_EPS, label) + self.assertLessEqual(y0 + float(h_str), vb_h + BOUND_EPS, label) + if tag == "circle": + cx = float(elem.attrib["cx"]) + cy = float(elem.attrib["cy"]) + rad = float(elem.attrib["r"]) + self.assertGreaterEqual(cx - rad, -BOUND_EPS, label) + self.assertLessEqual(cx + rad, vb_w + BOUND_EPS, label) + self.assertGreaterEqual(cy - rad, -BOUND_EPS, label) + self.assertLessEqual(cy + rad, vb_h + BOUND_EPS, label) + for attr in ("points", "d"): + raw = elem.attrib.get(attr) + if raw: + for sx, sy in COORD_PAIR_RE.findall(raw): + self.assertGreaterEqual(float(sx), 0.0, label) + self.assertLessEqual(float(sx), vb_w, label) + self.assertGreaterEqual(float(sy), 0.0, label) + self.assertLessEqual(float(sy), vb_h, label) + for child in elem: + self._assert_tree_within_bounds(child, vb_w, vb_h, label) + + def _assert_router_viewport_contents( + self, + vp_group: ET.Element, + *, + require_all_layers: bool, + ) -> None: + """Check that all geometry inside `router-viewport` stays strictly inside box.""" + vx0 = ROUTER_VP_X - VP_EPS + vy0 = ROUTER_VP_Y - VP_EPS + vx1 = ROUTER_VP_X + ROUTER_VP_W + VP_EPS + vy1 = ROUTER_VP_Y + ROUTER_VP_H + VP_EPS + machines = 0 + belts = 0 + underground = 0 + pipes = 0 + for elem in vp_group.iter(): + tag = elem.tag.split("}")[-1].lower() + if tag == "line": + x1, y1 = float(elem.attrib["x1"]), float(elem.attrib["y1"]) + x2, y2 = float(elem.attrib["x2"]), float(elem.attrib["y2"]) + self.assertGreaterEqual(x1, vx0) + self.assertLessEqual(x1, vx1) + self.assertGreaterEqual(x2, vx0) + self.assertLessEqual(x2, vx1) + self.assertGreaterEqual(y1, vy0) + self.assertLessEqual(y1, vy1) + self.assertGreaterEqual(y2, vy0) + self.assertLessEqual(y2, vy1) + self.assertGreaterEqual(math.hypot(x2 - x1, y2 - y1), VP_MIN_LEN) + stroke = elem.attrib.get("stroke") + if stroke == PALETTE["amber"]: + belts += 1 + elif stroke == PALETTE["cyan"]: + underground += 1 + elif stroke == PALETTE["violet"]: + pipes += 1 + elif tag == "rect": + x = float(elem.attrib["x"]) + y = float(elem.attrib["y"]) + w = float(elem.attrib["width"]) + h = float(elem.attrib["height"]) + self.assertGreaterEqual(x, vx0) + self.assertGreaterEqual(y, vy0) + self.assertLessEqual(x + w, vx1) + self.assertLessEqual(y + h, vy1) + if elem.attrib.get("stroke") == PALETTE["teal"]: + machines += 1 + elif tag == "circle": + cx = float(elem.attrib["cx"]) + cy = float(elem.attrib["cy"]) + rad = float(elem.attrib["r"]) + self.assertGreaterEqual(cx - rad, vx0) + self.assertLessEqual(cx + rad, vx1) + self.assertGreaterEqual(cy - rad, vy0) + self.assertLessEqual(cy + rad, vy1) + if require_all_layers: + self.assertGreaterEqual(machines, 1) + self.assertGreaterEqual(belts, 1) + self.assertGreaterEqual(underground, 1) + self.assertGreaterEqual(pipes, 1) + if __name__ == "__main__": unittest.main() diff --git a/tools/build_showcase_site.py b/tools/build_showcase_site.py index da13bbb..198bbe8 100644 --- a/tools/build_showcase_site.py +++ b/tools/build_showcase_site.py @@ -253,6 +253,67 @@ def build_showcase_site(workspace: Path) -> None: ) # 3. Generate deterministic pipeline vector SVGs from compiled flow artifacts + refresh_pipeline_svgs( + workspace, + cat_map=cat_map, + ug_spans=ug_spans, + science_netlist=science_netlist, + ) + + # 4. Copy downloadable blueprint exchange strings + for bp_target in BLUEPRINT_EXPORTS: + shutil.copyfile(flow_bin / f"{bp_target}.blueprint", bp_dir / f"{bp_target}.blueprint") + shutil.copyfile(starter_dir / "starter_base.blueprint", bp_dir / "starter_base.blueprint") + + # 5. Export benchmarks JSON with git + host CPU/thread provenance and render site/index.html + provenance = {**collect_git_provenance(workspace), **collect_cpu_provenance()} + targets = collect_target_benchmarks(flow_bin, decode) + benchmarks_doc = { + "provenance": provenance, + "targets": targets, + } + (data_dir / "benchmarks.json").write_text( + json.dumps(benchmarks_doc, indent=2) + "\n", + encoding="utf-8", + ) + (site_dir / "index.html").write_text( + render_showcase_html(benchmarks_doc), + encoding="utf-8", + ) + + +def _add_bytes_to_tar(tf: tarfile.TarFile, arcname: str, payload: bytes) -> None: + """Write an in-memory payload into a deterministic tar archive entry.""" + info = tarfile.TarInfo(name=arcname) + info.size = len(payload) + info.mtime = 0 + info.mode = TAR_FILE_MODE + tf.addfile(info, io.BytesIO(payload)) + + +def refresh_pipeline_svgs( + workspace: Path, + *, + cat_map: Mapping[str, str] | None = None, + ug_spans: Mapping[str, int] | None = None, + science_netlist: Mapping[str, Any] | None = None, +) -> None: + """Regenerate all four pipeline SVGs without changing WebPs or benchmark provenance.""" + flow_bin = workspace / "bazel-bin" / "flow" + dump_path = workspace / "test" / "data" / "dump-fixture.json" + assets_dir = workspace / "site" / "assets" + assets_dir.mkdir(parents=True, exist_ok=True) + + if cat_map is None or ug_spans is None: + _prototypes, loaded_cats, loaded_spans = load_prototype_catalog(dump_path) + cat_map = cat_map or loaded_cats + ug_spans = ug_spans or loaded_spans + + if science_netlist is None: + science_netlist = json.loads( + (flow_bin / "science_chassis_netlist.json").read_text(encoding="utf-8") + ) + logistic_netlist = json.loads( (flow_bin / "logistic_science_netlist.json").read_text(encoding="utf-8") ) @@ -274,65 +335,33 @@ def build_showcase_site(workspace: Path) -> None: encoding="utf-8", ) - auto_log_def = parse_def( - (flow_bin / "automation_logistic_chassis.def").read_text(encoding="utf-8") - ) - auto_log_bp_doc = decode( - (flow_bin / "automation_logistic_chassis.blueprint").read_text(encoding="utf-8").strip() + router_target = "automation_logistic_military_chemical_chassis" + if not (flow_bin / f"{router_target}.blueprint").is_file(): + router_target = "automation_logistic_chassis" + router_def = parse_def((flow_bin / f"{router_target}.def").read_text(encoding="utf-8")) + router_bp_doc = decode( + (flow_bin / f"{router_target}.blueprint").read_text(encoding="utf-8").strip() ) netlist_spans = { str(k): int(v) for k, v in science_netlist.get("underground_spans", ug_spans).items() } (assets_dir / "pipeline_router_3d.svg").write_text( build_router_3d_svg( - auto_log_def, - auto_log_bp_doc.get("blueprint", auto_log_bp_doc), + router_def, + router_bp_doc.get("blueprint", router_bp_doc), cat_map, netlist_spans, ), encoding="utf-8", ) - verilog_src = (workspace / "flow" / "controllers" / "power_sequencer.v").read_text( - encoding="utf-8" - ) - synth_res = synthesize_power_sequencer() + verilog_path = workspace / "flow" / "controllers" / "power_sequencer.v" (assets_dir / "pipeline_verilog_campaign.svg").write_text( - build_verilog_campaign_svg(synth_res, verilog_src), - encoding="utf-8", - ) - - # 4. Copy downloadable blueprint exchange strings - for bp_target in BLUEPRINT_EXPORTS: - shutil.copyfile(flow_bin / f"{bp_target}.blueprint", bp_dir / f"{bp_target}.blueprint") - shutil.copyfile(starter_dir / "starter_base.blueprint", bp_dir / "starter_base.blueprint") - - # 5. Export benchmarks JSON with git + host CPU/thread provenance and render site/index.html - provenance = {**collect_git_provenance(workspace), **collect_cpu_provenance()} - targets = collect_target_benchmarks(flow_bin, decode) - benchmarks_doc = { - "provenance": provenance, - "targets": targets, - } - (data_dir / "benchmarks.json").write_text( - json.dumps(benchmarks_doc, indent=2) + "\n", - encoding="utf-8", - ) - (site_dir / "index.html").write_text( - render_showcase_html(benchmarks_doc), + _synthesize_fresh_verilog_svg(verilog_path), encoding="utf-8", ) -def _add_bytes_to_tar(tf: tarfile.TarFile, arcname: str, payload: bytes) -> None: - """Write an in-memory payload into a deterministic tar archive entry.""" - info = tarfile.TarInfo(name=arcname) - info.size = len(payload) - info.mtime = 0 - info.mode = TAR_FILE_MODE - tf.addfile(info, io.BytesIO(payload)) - - def _synthesize_fresh_verilog_svg(verilog_path: Path) -> str: """Synthesize the power sequencer controller SVG from Verilog source.""" verilog_src = verilog_path.read_text(encoding="utf-8") @@ -431,6 +460,11 @@ def main(argv: list[str] | None = None) -> int: action="store_true", help="Regenerate index.html and the Verilog SVG without full builds.", ) + parser.add_argument( + "--refresh-svgs", + action="store_true", + help="Regenerate pipeline SVGs without changing WebPs or benchmarks.json.", + ) parser.add_argument( "--stamp-git", action="store_true", @@ -451,6 +485,10 @@ def main(argv: list[str] | None = None) -> int: return 0 workspace = _resolve_workspace(args.workspace) + if args.refresh_svgs: + refresh_pipeline_svgs(workspace) + print(f"factorilog: pipeline SVGs refreshed in {workspace / 'site' / 'assets'}") + return 0 if args.refresh_hermetic: refresh_hermetic_site(workspace, stamp_git=args.stamp_git) print(f"factorilog: hermetic site refreshed in {workspace / 'site'}") diff --git a/tools/showcase_data.py b/tools/showcase_data.py index eec5267..e713fea 100644 --- a/tools/showcase_data.py +++ b/tools/showcase_data.py @@ -78,6 +78,9 @@ WIRE_TUPLE_LEN = 4 WINDOW_MIN_ENTITIES = 25 SHA_SHORT_LEN = 7 +MACHINE_CATEGORY_KEYS: frozenset[str] = frozenset( + ("assembling-machine", "furnace", "boiler", "generator", "lab", "rocket-silo") +) def load_prototype_catalog( @@ -488,7 +491,7 @@ def select_street_straddle_window( if not candidates: candidates.append((0, 0)) - best_score = -1.0 + best_score = -math.inf best_win = (0, 0, win_w, win_h) for wx0, wy0 in candidates: wx1 = wx0 + win_w @@ -498,6 +501,7 @@ def select_street_straddle_window( ug_count = 0 pipe_count = 0 split_count = 0 + machine_count = 0 ent_count = 0 for ent in entities: pos = ent.get("position") @@ -519,16 +523,24 @@ def select_street_straddle_window( pipe_count += 1 elif cat == "splitter": split_count += 1 + elif cat in MACHINE_CATEGORY_KEYS: + machine_count += 1 if ent_count < WINDOW_MIN_ENTITIES: continue pipe_bonus = min(pipe_count, 35) * (3.0 if prefer_pipes else 1.0) + machine_bonus = ( + ((60.0 if machine_count > 0 else 0.0) + min(machine_count, 8) * 40.0) + if prefer_pipes + else 0.0 + ) score = ( len(recipes) * 18.0 + len(cats) * 14.0 + min(ug_count, 30) * 3.0 + min(split_count, 20) * 2.5 + pipe_bonus + + machine_bonus + min(ent_count, 500) * 0.25 ) if score > best_score: diff --git a/tools/showcase_svg.py b/tools/showcase_svg.py index 34c8209..44cb340 100644 --- a/tools/showcase_svg.py +++ b/tools/showcase_svg.py @@ -7,6 +7,7 @@ from __future__ import annotations import collections +import math import re from collections.abc import Mapping, Sequence from typing import Any @@ -14,8 +15,12 @@ from foundry.entity_helpers import ( DEFAULT_DEF_UNITS, + DIR_STEPS, + DIRECTION_NORTH, + entity_size, ) from tools.showcase_data import ( + MACHINE_CATEGORY_KEYS, extract_geometry_layers, naive_rank_hpwl, select_street_straddle_window, @@ -26,6 +31,22 @@ SVG_H_STD = 540 ROUTER_WIN_W = 48 ROUTER_WIN_H = 36 +ROUTER_VP_X = 30 +ROUTER_VP_Y = 100 +ROUTER_VP_W = 586 +ROUTER_VP_H = 390 +PLACEMENT_PANEL_W = 572 +PLACEMENT_MAP_SIZE = 412.0 +PLACEMENT_MAP_Y_OFFSET = 38.0 +BELT_EXTEND_TILES = 0.38 +PIPE_ISOLATED_HALF_TILES = 0.3 +UG_ENDPOINT_MARGIN_TILES = 0.4 +CLIP_T_EPS = 1e-6 +CLIP_MIN_WORLD_LEN = 1e-3 +MIN_BELT_PX_LEN = 2.0 +MIN_ARROW_PX_LEN = 5.0 +MIN_PIPE_PX_LEN = 1.0 +STACK_DESC_MAX_CHARS = 68 MIN_TREEMAP_LABEL_W = 68.0 MIN_TREEMAP_LABEL_H = 32.0 MAX_FLYLINES = 260 @@ -61,15 +82,23 @@ ) -def _svg_open(width: int, height: int, title: str, subtitle: str) -> list[str]: +def _svg_open( + width: int, + height: int, + title: str, + subtitle: str, + extra_defs: Sequence[str] = (), +) -> list[str]: """Return opening SVG tags, dark theme styles, and top header banner.""" return [ f'', "", '', '', + '', '', '', + *extra_defs, "", f'', '', @@ -402,11 +431,19 @@ def build_placement_comparison_svg( naive_xy, hpwl_naive, hpwl_legal = naive_rank_hpwl(def_data, netlist_data) reduction_pct = ((hpwl_naive - hpwl_legal) / hpwl_naive * 100.0) if hpwl_naive > 0 else 0.0 + ox_left = 16 + (PLACEMENT_PANEL_W - PLACEMENT_MAP_SIZE) * 0.5 + ox_right = 612 + (PLACEMENT_PANEL_W - PLACEMENT_MAP_SIZE) * 0.5 + oy_map = 64 + PLACEMENT_MAP_Y_OFFSET + clip_defs = ( + f'', + f'', + ) lines = _svg_open( SVG_W, SVG_H_TALL, "Stage 2: Analytical Quadratic Placement, SCC Condensation, and City-Block Legalization", f"4-Science Chassis ({die_w:.0f}x{die_h:.0f} die, {len(def_data['components'])} instances, {len(def_data['nets'])} nets) | HPWL drops {reduction_pct:.1f}%", + extra_defs=clip_defs, ) inst_meta = { @@ -430,7 +467,7 @@ def build_placement_comparison_svg( title=f"Uncondensed Rank Columns (HPWL: {hpwl_naive:,.0f} tiles)", panel_x=16, panel_y=64, - panel_w=572, + panel_w=PLACEMENT_PANEL_W, panel_h=480, die_w=die_w, die_h=die_h, @@ -443,14 +480,15 @@ def build_placement_comparison_svg( draw_streets=False, badge_text=f"HPWL {hpwl_naive:,.0f}", badge_color=PALETTE["amber"], + clip_id="place-left-clip", ) _append_placement_panel( lines, - title=f"Quadratic + SCC + 94x94 Legalized (HPWL: {hpwl_legal:,.0f} tiles, -{reduction_pct:.1f}%)", + title=f"Quadratic + SCC + 94x94 Legalized (HPWL: {hpwl_legal:,.0f} tiles)", panel_x=612, panel_y=64, - panel_w=572, + panel_w=PLACEMENT_PANEL_W, panel_h=480, die_w=die_w, die_h=die_h, @@ -463,6 +501,7 @@ def build_placement_comparison_svg( draw_streets=True, badge_text=f"-{reduction_pct:.1f}% HPWL", badge_color=PALETTE["emerald"], + clip_id="place-right-clip", ) lines.append("") @@ -488,6 +527,7 @@ def _append_placement_panel( draw_streets: bool, badge_text: str, badge_color: str, + clip_id: str, ) -> None: """Render one die placement scatter panel with net flylines and macro blocks.""" lines.append( @@ -501,15 +541,16 @@ def _append_placement_panel( f'{escape(badge_text)}' ) - map_size = 412.0 + map_size = PLACEMENT_MAP_SIZE ox = panel_x + (panel_w - map_size) * 0.5 - oy = panel_y + 38.0 + oy = panel_y + PLACEMENT_MAP_Y_OFFSET sx = map_size / max(die_w, 1.0) sy = map_size / max(die_h, 1.0) lines.append( f'' ) + lines.append(f'') units = float(def_data.get("units", DEFAULT_DEF_UNITS)) if draw_streets: @@ -518,9 +559,14 @@ def _append_placement_panel( by1 = oy + (float(blk["y1"]) / units) * sy bw = ((float(blk["x2"]) - float(blk["x1"])) / units) * sx bh = ((float(blk["y2"]) - float(blk["y1"])) / units) * sy - lines.append( - f'' - ) + rx0 = max(ox, bx1) + ry0 = max(oy, by1) + rx1 = min(ox + map_size, bx1 + max(bw, 1.0)) + ry1 = min(oy + map_size, by1 + max(bh, 1.0)) + if rx1 > rx0 and ry1 > ry0: + lines.append( + f'' + ) # Draw a deterministic sample of net flylines drawn_lines = 0 @@ -536,8 +582,12 @@ def _append_placement_panel( continue x0, y0 = pts[0] for tx, ty in pts[1:]: + clipped = _clip_segment_to_box(x0, y0, tx, ty, ox, oy, ox + map_size, oy + map_size) + if clipped is None: + continue + cx1, cy1, cx2, cy2, _s_in, _e_in = clipped lines.append( - f'' + f'' ) drawn_lines += 1 @@ -551,12 +601,20 @@ def _append_placement_panel( cell = cells.get(str(inst.get("cell", comp.get("macro", ""))), {}) mw = max(float(cell.get("width", 2)) * sx, 2.2) mh = max(float(cell.get("height", 2)) * sy, 2.2) + rx0 = max(ox, ox + pt[0] * sx) + ry0 = max(oy, oy + pt[1] * sy) + rx1 = min(ox + map_size, ox + pt[0] * sx + mw) + ry1 = min(oy + map_size, oy + pt[1] * sy + mh) + if rx1 <= rx0 or ry1 <= ry0: + continue rank = int(inst.get("rank", 0)) color = _lerp_rank_color(rank / max_rank) lines.append( - f'' + f'' ) + lines.append("") + # Draw I/O pins along perimeter for px, py in pin_xy.values(): lines.append( @@ -568,6 +626,174 @@ def _append_placement_panel( ) +def _router_to_svg_coords( + wx: float, + wy: float, + wx0: int, + wy0: int, + scale_x: float, + scale_y: float, +) -> tuple[float, float]: + """Map world tile coordinates into router viewport pixel coordinates.""" + return ROUTER_VP_X + (wx - wx0) * scale_x, ROUTER_VP_Y + (wy - wy0) * scale_y + + +def _append_routed_entities( + lines: list[str], + entities: Sequence[Mapping[str, Any]], + cat_map: Mapping[str, str], + wx0: int, + wy0: int, + wx1: int, + wy1: int, + scale_x: float, + scale_y: float, +) -> None: + """Append clipped production machine and splitter footprints in the router window.""" + for ent in entities: + pos = ent.get("position", {}) + if not isinstance(pos, Mapping): + continue + name = str(ent.get("name", "")) + cat = cat_map.get(name, "") + if cat not in MACHINE_CATEGORY_KEYS and cat != "splitter": + continue + ex, ey = float(pos.get("x", 0.0)), float(pos.get("y", 0.0)) + direction = int(ent.get("direction", DIRECTION_NORTH)) + ew, eh = entity_size(name, direction) + ix1 = max(ex - ew * 0.5, float(wx0)) + iy1 = max(ey - eh * 0.5, float(wy0)) + ix2 = min(ex + ew * 0.5, float(wx1)) + iy2 = min(ey + eh * 0.5, float(wy1)) + if ix2 <= ix1 or iy2 <= iy1: + continue + rx, ry = _router_to_svg_coords(ix1, iy1, wx0, wy0, scale_x, scale_y) + rw_px = (ix2 - ix1) * scale_x + rh_px = (iy2 - iy1) * scale_y + if rw_px < MIN_PIPE_PX_LEN or rh_px < MIN_PIPE_PX_LEN: + continue + if cat in MACHINE_CATEGORY_KEYS: + lines.append( + f'' + ) + else: + lines.append( + f'' + ) + + +def _append_routed_pipes( + lines: list[str], + pipes: Sequence[Sequence[float]], + wx0: int, + wy0: int, + wx1: int, + wy1: int, + scale_x: float, + scale_y: float, +) -> None: + """Append clipped M3 fluid pipe segments in the router window.""" + for x1, y1, x2, y2, is_ug in pipes: + sx1, sx2 = x1, x2 + if math.hypot(x2 - x1, y2 - y1) < CLIP_MIN_WORLD_LEN: + sx1 = x1 - PIPE_ISOLATED_HALF_TILES + sx2 = x1 + PIPE_ISOLATED_HALF_TILES + clipped = _clip_segment_to_box( + sx1, y1, sx2, y2, float(wx0), float(wy0), float(wx1), float(wy1) + ) + if clipped is None: + continue + cx1, cy1, cx2, cy2, _s_in, _e_in = clipped + px1, py1 = _router_to_svg_coords(cx1, cy1, wx0, wy0, scale_x, scale_y) + px2, py2 = _router_to_svg_coords(cx2, cy2, wx0, wy0, scale_x, scale_y) + if math.hypot(px2 - px1, py2 - py1) < MIN_PIPE_PX_LEN: + continue + dash = ' stroke-dasharray="4 3"' if is_ug else "" + lines.append( + f'' + ) + + +def _append_routed_belts( + lines: list[str], + belts: Sequence[Sequence[float]], + wx0: int, + wy0: int, + wx1: int, + wy1: int, + scale_x: float, + scale_y: float, +) -> None: + """Extend, clip, and append M1 surface belt segments in the router window.""" + for x1, y1, x2, y2, raw_dir in belts: + dx, dy = DIR_STEPS.get(int(raw_dir), (0, -1)) + seg_dx, seg_dy = x2 - x1, y2 - y1 + has_span = abs(seg_dx) > CLIP_MIN_WORLD_LEN or abs(seg_dy) > CLIP_MIN_WORLD_LEN + if has_span and abs(seg_dx * dx + seg_dy * dy) < CLIP_MIN_WORLD_LEN: + # Skip perpendicular splitter bars because splitters render as boxes + continue + bx1, by1 = x1 - BELT_EXTEND_TILES * dx, y1 - BELT_EXTEND_TILES * dy + bx2, by2 = x2 + BELT_EXTEND_TILES * dx, y2 + BELT_EXTEND_TILES * dy + clipped = _clip_segment_to_box( + bx1, by1, bx2, by2, float(wx0), float(wy0), float(wx1), float(wy1) + ) + if clipped is None: + continue + cx1, cy1, cx2, cy2, _s_in, end_in = clipped + px1, py1 = _router_to_svg_coords(cx1, cy1, wx0, wy0, scale_x, scale_y) + px2, py2 = _router_to_svg_coords(cx2, cy2, wx0, wy0, scale_x, scale_y) + px_len = math.hypot(px2 - px1, py2 - py1) + if px_len < MIN_BELT_PX_LEN: + continue + marker = ' marker-end="url(#arr-belt)"' if (end_in and px_len >= MIN_ARROW_PX_LEN) else "" + lines.append( + f'' + ) + + +def _append_routed_underground( + lines: list[str], + underground: Sequence[Sequence[float]], + wx0: int, + wy0: int, + wx1: int, + wy1: int, + scale_x: float, + scale_y: float, +) -> None: + """Clip and append M2 underground tunnel spans and interior endpoint markers.""" + for x1, y1, x2, y2 in underground: + clipped = _clip_segment_to_box( + x1, y1, x2, y2, float(wx0), float(wy0), float(wx1), float(wy1) + ) + if clipped is None: + continue + cx1, cy1, cx2, cy2, start_in, end_in = clipped + px1, py1 = _router_to_svg_coords(cx1, cy1, wx0, wy0, scale_x, scale_y) + px2, py2 = _router_to_svg_coords(cx2, cy2, wx0, wy0, scale_x, scale_y) + if math.hypot(px2 - px1, py2 - py1) < MIN_PIPE_PX_LEN: + continue + lines.append( + f'' + ) + if ( + start_in + and (wx0 + UG_ENDPOINT_MARGIN_TILES <= cx1 <= wx1 - UG_ENDPOINT_MARGIN_TILES) + and (wy0 + UG_ENDPOINT_MARGIN_TILES <= cy1 <= wy1 - UG_ENDPOINT_MARGIN_TILES) + ): + lines.append( + f'' + ) + if ( + end_in + and (wx0 + UG_ENDPOINT_MARGIN_TILES <= cx2 <= wx1 - UG_ENDPOINT_MARGIN_TILES) + and (wy0 + UG_ENDPOINT_MARGIN_TILES <= cy2 <= wy1 - UG_ENDPOINT_MARGIN_TILES) + ): + lines.append( + f'' + ) + + def build_router_3d_svg( def_data: Mapping[str, Any], bp_payload: Mapping[str, Any], @@ -583,11 +809,15 @@ def build_router_3d_svg( prefer_pipes=True, ) layers = extract_geometry_layers(bp_payload, cat_map) + clip_defs = ( + f'', + ) lines = _svg_open( SVG_W, SVG_H_STD, "Stage 3: Two-Stage 3D Multi-Layer Dual-Lane Maze Router and Underground Transitions", f"Left: real routed chassis slice [{wx0},{wy0}]..[{wx1},{wy1}] tiles | Right: z-layer PDK stack & negotiated congestion", + extra_defs=clip_defs, ) # Left routed tile window @@ -605,20 +835,21 @@ def build_router_3d_svg( f'0 DRC' ) - vx, vy, vw, vh = lx + 14, ly + 36, 586, 390 + vx, vy, vw, vh = ROUTER_VP_X, ROUTER_VP_Y, ROUTER_VP_W, ROUTER_VP_H scale_x = vw / ROUTER_WIN_W scale_y = vh / ROUTER_WIN_H lines.append( f'' ) + lines.append('') # Tile gridlines - for gx in range(0, ROUTER_WIN_W + 1, 2): + for gx in range(2, ROUTER_WIN_W, 2): px = vx + gx * scale_x lines.append( f'' ) - for gy in range(0, ROUTER_WIN_H + 1, 2): + for gy in range(2, ROUTER_WIN_H, 2): py = vy + gy * scale_y lines.append( f'' @@ -632,63 +863,22 @@ def build_router_3d_svg( bx2 = min(float(blk["x2"]) / units, float(wx1)) by2 = min(float(blk["y2"]) / units, float(wy1)) if bx2 > bx1 and by2 > by1: - rx = vx + (bx1 - wx0) * scale_x - ry = vy + (by1 - wy0) * scale_y - rw = (bx2 - bx1) * scale_x - rh = (by2 - by1) * scale_y - lines.append( - f'' - ) - - # Machines / macros in window - for ent in bp_payload.get("entities", ()): - pos = ent.get("position", {}) - if not isinstance(pos, Mapping): - continue - ex, ey = float(pos.get("x", 0.0)), float(pos.get("y", 0.0)) - if not (wx0 <= ex <= wx1 and wy0 <= ey <= wy1): - continue - cat = cat_map.get(str(ent.get("name", "")), "") - if cat in ("assembling-machine", "furnace", "boiler", "generator", "lab", "rocket-silo"): - half_dim = 2.4 if cat == "assembling-machine" or cat == "furnace" else 1.4 - rx = vx + (ex - half_dim - wx0) * scale_x - ry = vy + (ey - half_dim - wy0) * scale_y - lines.append( - f'' - ) - - # Pipes and pipe-to-ground - for x1, y1, x2, y2, is_ug in layers["pipes"]: - if _segment_in_window(x1, y1, x2, y2, wx0, wy0, wx1, wy1): - dash = ' stroke-dasharray="4 3"' if is_ug else "" + rx, ry = _router_to_svg_coords(bx1, by1, wx0, wy0, scale_x, scale_y) + rw_px = (bx2 - bx1) * scale_x + rh_px = (by2 - by1) * scale_y lines.append( - f'' + f'' ) - # M1 Surface belts - for x1, y1, x2, y2, _dir in layers["belts"]: - if _segment_in_window(x1, y1, x2, y2, wx0, wy0, wx1, wy1): - lines.append( - f'' - ) - - # M2 Underground belt tunnels - for x1, y1, x2, y2 in layers["underground"]: - if _segment_in_window(x1, y1, x2, y2, wx0, wy0, wx1, wy1): - px1, py1 = vx + (x1 - wx0) * scale_x, vy + (y1 - wy0) * scale_y - px2, py2 = vx + (x2 - wx0) * scale_x, vy + (y2 - wy0) * scale_y - lines.append( - f'' - ) - lines.append( - f'' - ) - lines.append( - f'' - ) + entities = [ent for ent in bp_payload.get("entities", ()) if isinstance(ent, Mapping)] + _append_routed_entities(lines, entities, cat_map, wx0, wy0, wx1, wy1, scale_x, scale_y) + _append_routed_pipes(lines, layers["pipes"], wx0, wy0, wx1, wy1, scale_x, scale_y) + _append_routed_belts(lines, layers["belts"], wx0, wy0, wx1, wy1, scale_x, scale_y) + _append_routed_underground(lines, layers["underground"], wx0, wy0, wx1, wy1, scale_x, scale_y) + lines.append("") lines.append( - f'Amber: M1 surface belts | Cyan dashed: M2 tunnels | Violet: M3 fluid pipes' + f'Teal: Macros | Amber: M1 belts | Cyan dashed: M2 tunnels | Violet: M3 pipes' ) # Right 3D stack & PathFinder panel @@ -700,7 +890,10 @@ def build_router_3d_svg( f'3D Layer Stack & Negotiated Congestion' ) - ug_summary = ", ".join(f"{k}={v}t" for k, v in sorted(max_ug_spans.items())) + ug_summary = ", ".join( + f"{k.replace('-underground-belt', '-ug').replace('underground-belt', 'ug')}={v}t" + for k, v in sorted(max_ug_spans.items()) + ) layer_cards = [ ( "Overhead (PDN + Circuit)", @@ -714,7 +907,7 @@ def build_router_3d_svg( ), ( "z = 1..N (M2 Tunnels)", - f"Prototype spans: {ug_summary}" if ug_summary else "Dynamic prototype spans", + f"Spans: {ug_summary}" if ug_summary else "Dynamic prototype spans", PALETTE["cyan"], ), ( @@ -732,7 +925,7 @@ def build_router_3d_svg( f'{escape(head)}' ) lines.append( - f'{escape(_short_label(desc, 62))}' + f'{escape(_short_label(desc, STACK_DESC_MAX_CHARS))}' ) eq_y = ry0 + 314 @@ -759,18 +952,52 @@ def build_router_3d_svg( return "\n".join(lines) -def _segment_in_window( +def _clip_segment_to_box( x1: float, y1: float, x2: float, y2: float, - wx0: int, - wy0: int, - wx1: int, - wy1: int, -) -> bool: - """Return True if either endpoint or span lies inside `[wx0, wx1] x [wy0, wy1]`.""" - return max(x1, x2) >= wx0 and min(x1, x2) <= wx1 and max(y1, y2) >= wy0 and min(y1, y2) <= wy1 + bx0: float, + by0: float, + bx1: float, + by1: float, +) -> tuple[float, float, float, float, bool, bool] | None: + """Clip segment `(x1, y1)->(x2, y2)` to `[bx0, bx1] x [by0, by1]` via Liang-Barsky.""" + dx = x2 - x1 + dy = y2 - y1 + t0 = 0.0 + t1 = 1.0 + for p, q in ( + (-dx, x1 - bx0), + (dx, bx1 - x1), + (-dy, y1 - by0), + (dy, by1 - y1), + ): + if abs(p) <= 1e-12: + if q < 0.0: + return None + continue + r = q / p + if p < 0.0: + if r > t1: + return None + if r > t0: + t0 = r + else: + if r < t0: + return None + if r < t1: + t1 = r + + cx1 = x1 + t0 * dx + cy1 = y1 + t0 * dy + cx2 = x1 + t1 * dx + cy2 = y1 + t1 * dy + if math.hypot(cx2 - cx1, cy2 - cy1) < CLIP_MIN_WORLD_LEN: + return None + start_inside = t0 <= CLIP_T_EPS + end_inside = t1 >= 1.0 - CLIP_T_EPS + return (cx1, cy1, cx2, cy2, start_inside, end_inside) def build_verilog_campaign_svg(