main
Drew Owens Scrub internal hostnames, quota ledger, local paths, and private links for public release 09af481
#!/usr/bin/env python3
"""Compute and validate Microgoose Spine initial staging placement and final functional placement."""

from __future__ import annotations

import json
import math
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
KICAD_DIR = ROOT / "kicad"
NETLIST_PATH = ROOT / "design" / "netlist.json"

# Origin MP1 in KiCad Y-down coordinates (mm)
X0 = 100.0
Y0 = 150.0


def parse_courtyard(mod_path: Path) -> tuple[float, float, float, float]:
    s = mod_path.read_text()
    xs: list[float] = []
    ys: list[float] = []
    depth = 0
    start = None
    for idx, ch in enumerate(s):
        if ch == "(":
            if depth == 1:
                start = idx
            depth += 1
        elif ch == ")":
            depth -= 1
            if depth == 1 and start is not None:
                blk = s[start : idx + 1]
                if '"F.CrtYd"' in blk:
                    for m in re.finditer(r"\((?:start|end|center|xy)\s+([-\d.]+)\s+([-\d.]+)\)", blk):
                        xs.append(float(m.group(1)))
                        ys.append(float(m.group(2)))
                    cm = re.search(
                        r"\(center\s+([-\d.]+)\s+([-\d.]+)\).*?\(end\s+([-\d.]+)\s+([-\d.]+)\)",
                        blk,
                        re.S,
                    )
                    if cm and blk.startswith("(fp_circle"):
                        cx, cy, ex, ey = map(float, cm.groups())
                        r = math.hypot(ex - cx, ey - cy)
                        xs += [cx - r, cx + r]
                        ys += [cy - r, cy + r]
                start = None
    assert xs and ys, f"No F.CrtYd in {mod_path}"
    return (min(xs), min(ys), max(xs), max(ys))


def rot_bbox(
    bb: tuple[float, float, float, float], cx: float, cy: float, rot_deg: float
) -> tuple[float, float, float, float]:
    """Rotate footprint local KiCad (Y-down) bbox by KiCad CCW angle rot_deg around (cx, cy)."""
    x0, y0, x1, y1 = bb
    rad = math.radians(rot_deg)
    c = math.cos(rad)
    s = math.sin(rad)
    pts = []
    for px, py in ((x0, y0), (x0, y1), (x1, y0), (x1, y1)):
        # In KiCad pcbnew, footprint orientation is CCW in screen (meaning x' = x cos - y sin? Wait:
        # for 0/90/180/270, axis-aligned bounding box of {+,-} is symmetric under sign of sin if we check exact!)
        # Exact KiCad Y-down CCW rotation: (rx, ry) = (px*c - py*s, -px*s - py*c)? No:
        # At 90 deg CCW in KiCad (Y-down): +x goes to -y, +y goes to +x: rx = py*s + px*c, ry = py*c - px*s.
        rx = px * c + py * s
        ry = -px * s + py * c
        pts.append((cx + rx, cy + ry))
    return (
        min(p[0] for p in pts),
        min(p[1] for p in pts),
        max(p[0] for p in pts),
        max(p[1] for p in pts),
    )


def mol_to_kicad(mx: float, my: float) -> tuple[float, float]:
    return (round(X0 + mx, 3), round(Y0 - my, 3))


# Target functional placement in molecule frame (mx in 0..64 right, my in 0..64 up) and KiCad rotation (deg CCW)
FINAL_MOL: dict[str, tuple[float, float, float]] = {
    # Connectors near edges (all mouths facing outward, signal pads facing inward)
    "J1": (16.0, 6.0, 180.0),
    "C27": (16.0, 11.5, 0.0),
    "J2": (48.0, 6.0, 180.0),
    "C28": (48.0, 11.5, 0.0),
    "J4": (16.0, 58.0, 0.0),
    "J3": (32.0, 58.0, 0.0),
    "C29": (32.0, 52.5, 0.0),
    "J5": (48.0, 58.0, 0.0),
    # 5V 4A Synchronous Buck near MC1(0,16), MC2(0,20), MC3(0,24)
    "U1": (12.5, 21.0, 0.0),
    "C4": (6.8, 22.5, 270.0),   # HF 100nF right across U1.2 VIN & U1.1 PGND
    "C1": (4.5, 22.5, 270.0),
    "C2": (4.5, 18.5, 270.0),
    "C3": (6.8, 18.5, 270.0),
    "R5": (6.8, 15.0, 0.0),     # UVLO top
    "R6": (10.5, 15.0, 0.0),    # UVLO bot
    "C5": (18.2, 22.2, 90.0),   # BOOT cap beside U1.7/U1.8
    "C6": (18.2, 18.8, 0.0),    # VCC cap beside U1.6
    "L1": (15.5, 29.0, 90.0),   # pad 1 SW at (15.5, 27.0), pad 2 5V_RAW at (15.5, 31.0)
    "C7": (9.5, 30.5, 180.0),   # 22uF 0805 on 5V_RAW
    "C8": (9.5, 33.0, 180.0),   # 22uF 0805 on 5V_RAW
    # Feedback divider quiet below U1
    "R1": (14.5, 15.5, 180.0),
    "R2": (14.5, 13.5, 0.0),
    "R3": (18.2, 15.5, 180.0),
    "R4": (18.2, 13.5, 0.0),
    # Shunt R20 & 5V_BUS output bank near MC4(0,44), MC5(0,48)
    "R20": (15.5, 37.0, 90.0),  # pad 1 5V_RAW at (15.5, 34.04), pad 2 5V_BUS at (15.5, 39.96)
    "C9": (9.5, 39.5, 180.0),
    "C10": (9.5, 42.0, 180.0),
    "C11": (9.5, 44.5, 180.0),
    # INA226 Kelvin shunt monitor
    "U3": (22.5, 37.0, 180.0),  # pins 10/9/8 face R20 on left; pin 6 VS is at (-2.1, -1.0) in rot=180 -> (20.4, 38.0)!
    "C20": (22.5, 40.2, 0.0),   # right next to U3.6 VS (20.4, 38.0)
    "R15": (27.8, 37.0, 90.0),  # right next to U3.3 Alert (24.6, 37.0)
    # VBAT_ADC divider
    "R11": (24.5, 24.5, 0.0),
    "R12": (24.5, 22.5, 0.0),
    "C25": (28.2, 23.5, 90.0),
    # 3.3V LDO AP2114H
    "U2": (21.5, 46.5, 0.0),
    "C12": (15.0, 46.5, 90.0),
    "C26": (21.5, 51.8, 0.0),
    # BMI270 Torso IMU at exact board center (32, 32)
    "U5": (32.0, 32.0, 0.0),
    "C18": (30.5, 28.8, 0.0),
    "C19": (34.0, 28.8, 0.0),
    "R16": (32.0, 35.5, 0.0),
    "R17": (32.0, 37.5, 0.0),
    # STM32G431CBT6 Spine MCU central-right near SWD MC6..MC9
    "U4": (46.0, 32.0, 0.0),
    "C13": (39.0, 34.5, 90.0),  # near U4.1 VBAT/VDD
    "C14": (43.5, 25.0, 0.0),   # near U4.24 VDD
    "C15": (47.5, 25.0, 0.0),   # near U4.20/21 VDDA/VREF+
    "C16": (53.0, 29.5, 90.0),  # near U4.36 VDD
    "C17": (48.5, 39.0, 0.0),   # near U4.48 VDD
    "R8": (39.0, 31.0, 0.0),    # NRST pullup
    "C24": (39.0, 29.0, 0.0),   # NRST cap
    "R9": (44.0, 39.0, 0.0),    # BOOT0 pulldown
    "R7": (40.5, 25.0, 90.0),   # BUCK_PG pullup
    # 1 Mbps Dynamixel half-duplex buffer near U4 bottom pins 22/25/26
    "U6": (46.0, 19.5, 0.0),
    "C21": (50.0, 21.0, 90.0),
    "R10": (42.0, 21.0, 0.0),
    "R14": (50.0, 18.0, 0.0),
    "R18": (46.0, 16.0, 0.0),
    # 5V Power-Good LED & WS2812B RGB Status Pixel + 5V Level Shifter
    "R13": (54.5, 49.5, 0.0),
    "D1": (58.5, 49.5, 0.0),
    "U7": (54.5, 44.5, 0.0),
    "C22": (58.5, 46.0, 0.0),
    "R19": (54.5, 41.0, 0.0),
    "D2": (58.5, 41.0, 0.0),
    "C23": (58.5, 38.0, 0.0),
    # Bare-copper 0.5 mm Workcell Test Points (>= 3.0 mm apart, clear of bodies, < 35 mm from GND MC3/5/9)
    "TP1": (6.5, 26.5, 0.0),    # VBAT
    "TP2": (6.5, 12.0, 0.0),    # BUCK_EN
    "TP3": (20.8, 29.0, 0.0),   # SW (right beside L1.1, zero antenna!)
    "TP4": (6.5, 47.0, 0.0),    # 5V_BUS (near MC4/MC5)
    "TP5": (22.0, 15.5, 0.0),   # FB
    "TP6": (30.0, 44.5, 0.0),   # 3V3
    "TP7": (39.5, 16.0, 0.0),   # DXL_DATA
    "TP8": (34.5, 44.5, 0.0),   # I2C_SCL
    "TP9": (39.0, 44.5, 0.0),   # I2C_SDA
}


def main() -> None:
    netlist = json.loads(NETLIST_PATH.read_text())
    comp_map = {c["ref"]: c for c in netlist["components"]}

    assert set(FINAL_MOL.keys()) | {r for r, c in comp_map.items() if "fixed" in c} == set(comp_map.keys()), (
        f"Missing refs in FINAL_MOL: {set(comp_map.keys()) - set(FINAL_MOL.keys()) - {r for r, c in comp_map.items() if 'fixed' in c}}"
    )

    crtyds: dict[str, tuple[float, float, float, float]] = {}
    for ref, comp in comp_map.items():
        if ref.startswith("TP"):
            mod_path = KICAD_DIR / "lib" / "adom.pretty" / "Adom_TestPoint_D0.5mm.kicad_mod"
        else:
            fp_name = comp["fp"].split(":", 1)[1]
            mod_path = KICAD_DIR / "lib" / "PCM_microgoose.pretty" / f"{fp_name}.kicad_mod"
        crtyds[ref] = parse_courtyard(mod_path)

    # Build full KiCad coordinates for final layout
    final_kicad: dict[str, dict[str, float]] = {}
    for ref, comp in comp_map.items():
        if "fixed" in comp:
            kx, ky = mol_to_kicad(comp["fixed"]["x"], comp["fixed"]["y"])
            final_kicad[ref] = {"x": kx, "y": ky, "rot": 0.0, "fixed": True}
        else:
            mx, my, rot = FINAL_MOL[ref]
            kx, ky = mol_to_kicad(mx, my)
            final_kicad[ref] = {"x": kx, "y": ky, "rot": rot, "fixed": False}

    # Check board boundary [97.2, 83.2] .. [166.8, 152.8] and corner arcs!
    boxes: dict[str, tuple[float, float, float, float]] = {}
    for ref, pos in final_kicad.items():
        bb = rot_bbox(crtyds[ref], pos["x"], pos["y"], pos["rot"])
        boxes[ref] = bb
        if not pos["fixed"]:
            assert bb[0] >= 97.5 and bb[2] <= 166.5 and bb[1] >= 83.5 and bb[3] <= 152.5, (
                f"{ref} courtyard {bb} too close to board edge"
            )

    # Check pairwise courtyard overlaps across ALL 87 parts!
    refs = sorted(boxes.keys())
    overlaps = []
    for i, r1 in enumerate(refs):
        a0, a1, a2, a3 = boxes[r1]
        for r2 in refs[i + 1 :]:
            b0, b1, b2, b3 = boxes[r2]
            ox = min(a2, b2) - max(a0, b0)
            oy = min(a3, b3) - max(a1, b1)
            if ox > -0.05 and oy > -0.05:
                overlaps.append((r1, r2, round(ox, 3), round(oy, 3)))
    assert not overlaps, f"Courtyard overlaps/touches: {overlaps}"

    # Check TP spacing >= 2.5 mm and distance to nearest GND contact (MC3, MC5, MC9) <= 50 mm
    tps = [r for r in refs if r.startswith("TP")]
    gnd_mcs = ["MC3", "MC5", "MC9"]
    for i, t1 in enumerate(tps):
        for t2 in tps[i + 1 :]:
            d = math.hypot(final_kicad[t1]["x"] - final_kicad[t2]["x"], final_kicad[t1]["y"] - final_kicad[t2]["y"])
            assert d >= 2.5, f"TPs too close: {t1} and {t2} ({d:.2f} mm)"
        dg = min(
            math.hypot(final_kicad[t1]["x"] - final_kicad[m]["x"], final_kicad[t1]["y"] - final_kicad[m]["y"])
            for m in gnd_mcs
        )
        assert dg <= 48.0, f"{t1} too far from GND contact: {dg:.2f} mm"
        # Also check clearance from every other part's courtyard >= 1.2 mm
        for r2, bb in boxes.items():
            if r2 == t1:
                continue
            dx = max(bb[0] - final_kicad[t1]["x"], 0.0, final_kicad[t1]["x"] - bb[2])
            dy = max(bb[1] - final_kicad[t1]["y"], 0.0, final_kicad[t1]["y"] - bb[3])
            assert math.hypot(dx, dy) >= 1.2, f"{t1} too close to {r2} courtyard ({math.hypot(dx, dy):.2f} mm)"

    # Also build a tidy initial staging grid inside [106..158, 92..144] for movable parts so `place land`
    # records real visible placement motion in KiCad PCB Editor.
    staging_kicad: dict[str, dict[str, float]] = {}
    movables = [r for r in comp_map if "fixed" not in comp_map[r]]
    # Place movables slightly displaced into a clean 9x9 staging grid inside the board
    cols = [108.0, 114.5, 121.0, 127.5, 134.0, 140.5, 147.0, 153.5, 158.5]
    rows = [91.0, 97.5, 104.0, 110.5, 117.0, 123.5, 130.0, 136.5, 143.0]
    for idx, ref in enumerate(movables):
        c = idx % 9
        r = idx // 9
        staging_kicad[ref] = {"x": cols[c], "y": rows[r], "rot": 0.0}

    plan_out = ROOT / "aiflow" / "placement_coords.json"
    plan_out.parent.mkdir(parents=True, exist_ok=True)
    plan_out.write_text(
        json.dumps(
            {
                "origin_mp1_kicad_mm": [X0, Y0],
                "outline_bbox_kicad_mm": [97.0, 83.0, 167.0, 153.0],
                "final_kicad": final_kicad,
                "staging_kicad": staging_kicad,
            },
            indent=2,
        )
    )
    print(f"OK: validated {len(final_kicad)} placements (0 courtyard overlaps, all TPs clear & within 48 mm of GND MC)")


if __name__ == "__main__":
    main()