master
Ray Publish 0.5.0 9332b6e
"""Acceptance 3: courtyard overlaps across the claude-pcb-f411 boards, checked against shapely.

For each board's committed circuit.json (and design.json) at a given claude-pcb-f411 commit, runs
`adom-2dboard render --circuit ... --json` and compares its overlapping pairs with shapely's positive-area
intersections of the same top-side courtyards. Usage: python3 courtyards.py <binary> <claude-pcb-f411 repo> <commit>"""
import json, subprocess, sys, tempfile
from pathlib import Path
sys.path.insert(0, '/home/adom/project/claude-pcb-f411/.validation-packages')
from shapely.geometry import Point, Polygon
from shapely import affinity

BIN, REPO, COMMIT = sys.argv[1], sys.argv[2], sys.argv[3]
git = lambda *a: subprocess.run(['git', '-C', REPO, *a], capture_output=True, text=True, check=True).stdout
paths = [p for p in git('ls-tree', '-r', '--name-only', COMMIT, '--', 'mcu-self-contained/boards').split('\n')
         if p.endswith('/dist/lib/index/circuit.json') and p.count('/') == 6]
def shapely_pairs(cj):
    name = {c['source_component_id']: c['name'] for c in cj if c['type'] == 'source_component'}
    comp = {c['pcb_component_id']: name.get(c['source_component_id']) for c in cj if c['type'] == 'pcb_component'}
    shapes = []
    for e in cj:
        if e.get('layer') == 'bottom' or e['type'] not in ('pcb_courtyard_outline', 'pcb_courtyard_circle', 'pcb_courtyard_rect'): continue
        o = comp.get(e.get('pcb_component_id'))
        if e['type'] == 'pcb_courtyard_circle': g = Point(e['center']['x'], e['center']['y']).buffer(e['radius'], 256)
        elif e['type'] == 'pcb_courtyard_rect':
            c, w, h = e['center'], e['width'], e['height']
            g = affinity.rotate(Polygon([(c['x'] - w / 2, c['y'] - h / 2), (c['x'] + w / 2, c['y'] - h / 2), (c['x'] + w / 2, c['y'] + h / 2), (c['x'] - w / 2, c['y'] + h / 2)]), e.get('ccw_rotation', 0) or 0, origin=(c['x'], c['y']))
        else: g = Polygon([(p['x'], p['y']) for p in e['outline']])
        shapes.append((o, g))
    out = set()
    for i, (a, ga) in enumerate(shapes):
        for b, gb in shapes[i + 1:]:
            if a != b and ga.intersection(gb).area > 1e-6: out.add(tuple(sorted((a, b))))
    return out
total, agree, excepted = 0, True, []
with tempfile.TemporaryDirectory() as t:
    for p in sorted(paths):
        board = p.split('/')[2]; bd = Path(t) / board; bd.mkdir()
        (bd / 'circuit.json').write_text(git('show', f'{COMMIT}:{p}'))
        args = [BIN, 'render', '--circuit', str(bd / 'circuit.json'), '--out', '/dev/null', '--json', '--title', board]
        try:
            (bd / 'design.json').write_text(git('show', f'{COMMIT}:mcu-self-contained/boards/{board}/design.json')); args += ['--design', str(bd / 'design.json')]
        except subprocess.CalledProcessError: pass
        out = subprocess.run(args, capture_output=True, text=True, check=True).stdout
        ov = json.loads(out[:out.rindex(']') + 1])[0]['courtyardOverlaps']
        mine = {tuple(sorted((o['a'], o['b']))) for o in ov}
        ref = shapely_pairs(json.loads((bd / 'circuit.json').read_text()))
        total += len(mine); agree &= mine == ref
        excepted += [(board, o['a'], o['b']) for o in ov if o['excepted']]
        if mine: print(f'{board}: ' + ', '.join(f"{o['a']}-{o['b']}{' (exception)' if o['excepted'] else ''}" for o in ov) + ('' if mine == ref else f'  SHAPELY: {sorted(ref)}'))
print(f'{len(paths)} boards, {total} overlapping pairs, shapely agrees on every board: {agree}; named exceptions: {excepted}')