"""Convert pinned PIC Routing Benchmark and LiDAR inputs into inire fixtures.""" from __future__ import annotations from argparse import ArgumentParser from collections import defaultdict from csv import DictReader from dataclasses import dataclass from hashlib import file_digest from json import dumps, loads from math import ceil, floor from pathlib import Path from tarfile import TarFile from typing import TYPE_CHECKING from zipfile import ZipFile from shapely import get_parts from shapely.affinity import scale, translate from shapely.geometry import Polygon, box if TYPE_CHECKING: from collections.abc import Callable, Iterable from shapely.geometry.base import BaseGeometry PIC_REVISION = "0c1f445792926d97fae01893c89e96b8a9393800" LIDAR_REVISION = "4e7004d32b0b80d959553797fb30f0737513de0c" PIC_DIGEST = "e4a9479a7fcabe64a0083bdab42a615e2200e7245ab5863a7bf109229d7ec588" LIDAR_DIGEST = "cfd7a43762a9e71435d6d91a488f31ae1527c8752179805bdb4c345cb3089ba3" UNITS_PER_MICRON = 10 HEADINGS = {"E": 0, "N": 90, "W": 180, "S": 270} ROTATIONS = ((1, 0), (0, 1), (-1, 0), (0, -1)) OUTPUT = Path(__file__).resolve().parents[1] / "inire/tests/data/external_routing_benchmarks.json" PIC_DESIGNS = ( "splitter_tree_1x8_ew", "splitter_ring_mod_ap_combiner_2_ew", "splitter_mzm_combiner_4_ew", ) LIDAR_DESIGNS = { "toy_example/toy_example.gp.yml": (), "clements_8x8/clements_8x8.yml": tuple(f"n_{n}" for n in range(30, 36)), "mrr_weight_bank_4x4/mrr_weight_bank_4x4.yml": tuple(f"n_{n}" for n in range(18, 26)), } @dataclass(frozen=True, slots=True) class Pin: x: float y: float heading: int width: float @dataclass(frozen=True, slots=True) class Device: footprints: tuple[Polygon, ...] pins: dict[str, Pin] Connection = tuple[str, tuple[str, str], tuple[str, str]] def _rotate(x: float, y: float, angle: int) -> tuple[float, float]: if angle % 90: raise ValueError(f"Cannot import noncardinal rotation {angle}") ux, uy = ROTATIONS[int(angle // 90) % 4] return ux * x - uy * y, uy * x + ux * y def _footprint(bounds: tuple[float, float, float, float], transform: Callable[[float, float], tuple[float, float]]) -> Polygon: left, bottom, right, top = bounds return Polygon([transform(left, bottom), transform(right, bottom), transform(right, top), transform(left, top)]) def _port_cutout(pin: Pin, width: float, clearance: float, extent: Polygon) -> Polygon: # Carve access only from this port's own device. Allow one lattice unit # for the snap from fractional source coordinates to inire's Port. margin = width / 2 + clearance + 1 / UNITS_PER_MICRON reach = max(extent.bounds[2] - extent.bounds[0], extent.bounds[3] - extent.bounds[1]) + 2 * margin return _footprint((-margin, -margin, reach, margin), lambda x, y: _pin_frame(pin, x, y)) def _pin_frame(pin: Pin, x: float, y: float) -> tuple[float, float]: dx, dy = _rotate(x, y, pin.heading) return pin.x + dx, pin.y + dy def _polygons(shape: BaseGeometry) -> Iterable[Polygon]: for part in get_parts(shape): if isinstance(part, Polygon) and not part.is_empty and part.area > 0: yield part def _fixture( name: str, source: str, member: str, devices: dict[str, Device], connections: list[Connection], radius: float, clearance: float, *, die: tuple[float, float, float, float] | None = None, min_straight: float = 0.5, expected_routed: int | None = None, ) -> dict: if not connections: raise ValueError(f"No compatible connections in {name}") active = {device for _, start, finish in connections for device, _ in (start, finish)} if die is None: bounds = [footprint.bounds for key in active for footprint in devices[key].footprints] pad = 4 * radius die = ( floor(min(b[0] for b in bounds) - pad), floor(min(b[1] for b in bounds) - pad), ceil(max(b[2] for b in bounds) + pad), ceil(max(b[3] for b in bounds) + pad), ) x0, y0, x1, y1 = die board = box(*die) cutouts: dict[str, list[Polygon]] = defaultdict(list) nets = [] for net_id, (a, ap), (b, bp) in connections: start, finish = devices[a].pins[ap], devices[b].pins[bp] width = max(start.width, finish.width) for key, pin in ((a, start), (b, finish)): for footprint in devices[key].footprints: cutouts[key].append(_port_cutout(pin, width, clearance, footprint)) nets.append( { "id": net_id, "start": [round((start.x - x0) * UNITS_PER_MICRON), round((start.y - y0) * UNITS_PER_MICRON), start.heading], "target": [round((finish.x - x0) * UNITS_PER_MICRON), round((finish.y - y0) * UNITS_PER_MICRON), (finish.heading + 180) % 360], "width": round(width * UNITS_PER_MICRON, 6), } ) obstacles = [] for key, device in devices.items(): for footprint in device.footprints: clipped = footprint.intersection(board) for access in cutouts.get(key, ()): clipped = clipped.difference(access) for part in _polygons(clipped): local = scale(translate(part, -x0, -y0), xfact=UNITS_PER_MICRON, yfact=UNITS_PER_MICRON, origin=(0, 0)) encoded = [[(round(x, 6), round(y, 6)) for x, y in ring.coords] for ring in (local.exterior, *local.interiors)] polygon = Polygon(encoded[0], encoded[1:]) if polygon.area > 0: if not polygon.is_valid: raise ValueError(f"Invalid device geometry in {name}: {key}") obstacles.append(encoded) return { "name": name, **({"expected_routed": expected_routed} if expected_routed is not None else {}), "source": source, "member": member, "crop_um": list(die), "bounds": [0, 0, round((x1 - x0) * UNITS_PER_MICRON), round((y1 - y0) * UNITS_PER_MICRON)], "bend_radius": radius * UNITS_PER_MICRON, "clearance": clearance * UNITS_PER_MICRON, "min_straight": min_straight * UNITS_PER_MICRON, "obstacles": obstacles, "nets": nets, } def _pic_transform(place: dict, x: float, y: float, *, position: bool = True) -> tuple[float, float]: dx, dy = _rotate(-x if place["mirror_x"] else x, -y if place["mirror_y"] else y, place["orientation_deg"]) return (dx + place["x_um"], dy + place["y_um"]) if position else (dx, dy) def _pic_device(cell: dict, place: dict, width: float) -> Device: w, h = cell["bbox"]["width_um"], cell["bbox"]["height_um"] outline = _footprint((-w / 2, -h / 2, w / 2, h / 2), lambda x, y: _pic_transform(place, x, y)) pins = {} for name, port in cell["port_geometry"].items(): x, y = _pic_transform(place, port["x_um"], port["y_um"]) dx, dy = _pic_transform(place, *ROTATIONS[HEADINGS[port["orientation"]] // 90], position=False) pins[name] = Pin(x, y, ROTATIONS.index((dx, dy)) * 90, width) return Device((outline,), pins) def _pic_macro(module: dict, pdk: dict, place: dict) -> Device: # The selected designs use vertical edge-coupler arrays at the boundary. # Their constituent boxes remain obstacles, while optical I/O is outside # the primitive-to-primitive routing subproblem. children = module["instances"] attributes = module["attributes"] if not (attributes["hard_macro"] and attributes["array_axis"] == "V" and all(child["module"] == "EDGE_COUPLER" for child in children)): raise ValueError("Unsupported PIC macro in the selected design") box_size = pdk["EDGE_COUPLER"]["bbox"] w, h = box_size["width_um"], box_size["height_um"] outlines = [] for i in range(len(children)): row = (i - (len(children) - 1) / 2) * attributes["pitch"] outlines.append(_footprint((-w / 2, row - h / 2, w / 2, row + h / 2), lambda x, y: _pic_transform(place, x, y))) return Device(tuple(outlines), {}) def _pic_cases(archive: ZipFile) -> list[dict]: root = "pic-benchmark" pdk = loads(archive.read(f"{root}/pdk/pdk_v2_mzi80.json"))["device_defs"] rules = loads(archive.read(f"{root}/pdk/design_rules_v2_mzi80.json"))["routing_rules"] summary = list(DictReader(archive.read(f"{root}/data/_batch_summary.csv").decode().splitlines())) cases = [] for design in PIC_DESIGNS: result = next(row for row in summary if row["design"] == design and row["variant"] == "rectilinear") if result["lvs_ok"] != "True" or result["drc_ok"] != "True" or int(result["n_crossings"]): raise ValueError(f"Source variant failed the crossing-free LVS and DRC screen: {design}") folder = f"{root}/data/{design}" source = loads(archive.read(f"{folder}/{design}_netlist.json")) member = f"{folder}/rectilinear/{design}_placement.json" placements = {row["instance"]: row for row in loads(archive.read(member))["placements"]} modules = source["modules"] devices = {} net_ports: dict[str, list[tuple[str, str, str]]] = defaultdict(list) for inst in modules[source["top_module"]]["instances"]: key, cell = inst["name"], inst["module"] module = modules[cell] if cell not in pdk: devices[key] = _pic_macro(module, pdk, placements[key]) continue devices[key] = _pic_device(pdk[cell], placements[key], rules["waveguide_width_um"]) directions = {port["name"]: port["direction"] for port in module["ports"]} for port, wire in inst["connections"].items(): net_ports[wire].append((directions[port], key, port)) connections = [] for net_id, pins in sorted(net_ports.items()): if len(pins) != 2: continue source_pin, sink_pin = sorted(pins, reverse=True) if (source_pin[0], sink_pin[0]) != ("output", "input"): raise ValueError(f"Expected a directed 2-pin net in {design}: {net_id}") connections.append((net_id, (source_pin[1], source_pin[2]), (sink_pin[1], sink_pin[2]))) cases.append( _fixture( f"pic-{design.lower().replace('_', '-')}", "pic-benchmark", member, devices, connections, rules["fixed_bend_radius_um"], rules["min_spacing_um"], min_straight=rules["min_straight_section_um"], ) ) return cases def _lidar_device(inst: dict, macro: dict) -> Device: _, (x0, y0), orientation, _ = inst["settings"]["placement"] w, h = macro["size"] rotations = {"N": 0, "S": 180, "W": 90, "E": 270, "FN": 0, "FS": 0} angle = rotations[orientation] sx, sy = (-1 if orientation == "FN" else 1), (-1 if orientation == "FS" else 1) rotated = [_rotate(sx * x, sy * y, angle) for x, y in ((0, 0), (w, 0), (w, h), (0, h))] tx, ty = x0 - min(x for x, _ in rotated), y0 - min(y for _, y in rotated) def transform(x: float, y: float) -> tuple[float, float]: dx, dy = _rotate(sx * x, sy * y, angle) return dx + tx, dy + ty pins = {} for name, port in (macro.get("pins") or {}).items(): px, py = transform(port["pin_offset_x"], port["pin_offset_y"]) hx, hy = _rotate(1, 0, port["pin_orient"]) heading = ROTATIONS.index(_rotate(sx * hx, sy * hy, angle)) * 90 pins[name] = Pin(px, py, heading, port["pin_width"]) return Device((_footprint((0, 0, w, h), transform),), pins) def _lidar_cases(archive: TarFile) -> list[dict]: import yaml # noqa: PLC0415 class BenchmarkLoader(yaml.SafeLoader): """Accept LiDAR's tuple-valued parameters as inert YAML sequences.""" BenchmarkLoader.add_constructor("tag:yaml.org,2002:python/tuple", yaml.SafeLoader.construct_sequence) cases = [] for member, selected in LIDAR_DESIGNS.items(): path = f"LiDAR-{LIDAR_REVISION}/src/picroute/benchmarks/{member}" source = archive.extractfile(path) if source is None: raise ValueError(f"Missing LiDAR input {member}") with source: netlist = yaml.load(source, Loader=BenchmarkLoader) devices = {name: _lidar_device(inst, netlist["library"][inst["settings"]["macro_type"]]) for name, inst in netlist["instances"].items()} connections = [] for net_id in selected or netlist["nets"]: start, finish = netlist["nets"][net_id] a, ap = start.split(",") b, bp = finish.split(",") connections.append((net_id, (a, ap), (b, bp))) settings = netlist["settings"] die = tuple(value for corner in settings["die_area"] for value in corner) if not selected else None name = f"lidar-{settings['design'].replace('_', '-')}" expected_routed = 3 if name == "lidar-clements-8x8" else None cases.append(_fixture(name, "lidar", member, devices, connections, settings["wg_radius"], 1.0, die=die, expected_routed=expected_routed)) return cases def _verify_archive(path: Path, expected: str) -> None: with path.open("rb") as stream: if file_digest(stream, "sha256").hexdigest() != expected: raise ValueError(f"Archive does not match the pinned SHA-256: {path}") def main() -> None: parser = ArgumentParser(description=__doc__) parser.add_argument("--pic-archive", type=Path, required=True) parser.add_argument("--lidar-archive", type=Path, required=True) parser.add_argument("--output", type=Path, default=OUTPUT) args = parser.parse_args() _verify_archive(args.pic_archive, PIC_DIGEST) _verify_archive(args.lidar_archive, LIDAR_DIGEST) with ZipFile(args.pic_archive) as pic, TarFile.open(args.lidar_archive) as lidar: data = { "units_per_micron": UNITS_PER_MICRON, "revisions": {"pic-benchmark": PIC_REVISION, "lidar": LIDAR_REVISION}, "cases": [*_pic_cases(pic), *_lidar_cases(lidar)], } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(dumps(data, indent=2) + "\n", encoding="utf-8") if __name__ == "__main__": main()