main
John Lauer Board34 R10 nominal cooling and probe-clearance verification; refreshed prototype assets and native export checks 5460526
#!/usr/bin/env python3
"""Check native review exports against the unchanged PCB, not release approval."""
from collections import Counter
import argparse
import csv
import hashlib
import json
import math
from pathlib import Path
import re
import shutil
import sexp

ROOT=Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser()
parser.add_argument('--board',type=Path,default=ROOT/'kicad/adom-custom-electronic-load.kicad_pcb')
parser.add_argument('--out',type=Path,default=ROOT/'manufacturing-review/v85')
args=parser.parse_args()
OUT=args.out
board=args.board
prefix=board.stem
b=sexp.parse(board.read_text())
fps=sexp.find(b,'footprint')
key=lambda x,y,d:(round(x,3),round(y,3),round(d,3))
expected={'PTH':Counter(),'NPTH':Counter()}
for v in sexp.find(b,'via'):
    x,y=map(float,sexp.first(v,'at')[1:3]);d=float(sexp.first(v,'drill')[1])
    expected['PTH'][key(x,-y,d)]+=1
positions={}
for f in fps:
    props={p[1]:p[2] for p in sexp.find(f,'property')}
    at=sexp.first(f,'at');x,y=map(float,at[1:3]);angle=float(at[3])if len(at)>3 else 0
    attr=sexp.first(f,'attr')or[]
    if 'exclude_from_pos_files' not in attr and 'dnp' not in attr:
        positions[props['Reference']]=(x,-y,angle%360)
    a=math.radians(angle)
    for p in sexp.find(f,'pad'):
        if p[2] not in ['thru_hole','np_thru_hole']:continue
        at=sexp.first(p,'at');u,v=map(float,at[1:3]);dr=sexp.first(p,'drill')
        dimensions=[float(z)for z in dr[1:]if isinstance(z,str)and re.fullmatch(r'[\d.]+',z)]
        d=min(dimensions)
        expected['NPTH'if p[2]=='np_thru_hole'else'PTH'][key(x+u*math.cos(a)+v*math.sin(a),-y+u*math.sin(a)-v*math.cos(a),d)]+=1

drill_results={}
for kind in ['PTH','NPTH']:
    tools={};actual=Counter();tool=None;slots=0
    for line in (OUT/'drill'/f'{prefix}-{kind}.drl').read_text().splitlines():
        m=re.fullmatch(r'T(\d+)C([\d.]+)',line)
        if m:tools[m[1]]=float(m[2]);continue
        m=re.fullmatch(r'T(\d+)',line)
        if m:tool=m[1];continue
        if line.startswith('X'):
            coords=re.findall(r'X(-?[\d.]+)Y(-?[\d.]+)',line)
            assert len(coords)in[1,2],line
            if len(coords)==2:slots+=1
            x=sum(float(c[0])for c in coords)/len(coords);y=sum(float(c[1])for c in coords)/len(coords)
            actual[key(x,y,tools[tool])]+=1
    assert actual==expected[kind],(kind,list((actual-expected[kind]).items()),list((expected[kind]-actual).items()))
    drill_results[kind]=dict(count=actual.total(),slots=slots,centersAndToolDiametersMatch=True)

rows=list(csv.DictReader((OUT/'positions.csv').open()))
assert {r['Ref']for r in rows}==set(positions)
for r in rows:
    x,y,a=positions[r['Ref']]
    assert abs(float(r['PosX'])-x)<1e-5 and abs(float(r['PosY'])-y)<1e-5
    assert abs((float(r['Rot'])-a+180)%360-180)<1e-5
job=json.loads((OUT/'gerbers'/f'{prefix}-job.gbrjob').read_text())
assert job['GeneralSpecs']['LayerNumber']==2
for item in job['FilesAttributes']:
    p=OUT/'gerbers'/item['Path'];assert p.exists()and p.stat().st_size>0
bom_rows=list(csv.DictReader((ROOT/'design/bom.csv').open()))
board_refs={next(p[2] for p in sexp.find(f,'property') if p[1]=='Reference') for f in fps}
bom_refs=[r['ref'] for r in bom_rows]
assert len(bom_refs)==len(set(bom_refs)), 'Duplicate BOM reference'
assert set(bom_refs)==board_refs, ('BOM reference mismatch',sorted(board_refs-set(bom_refs)),sorted(set(bom_refs)-board_refs))
shutil.copy2(ROOT/'design/bom.csv',OUT/'bom-review.csv')
manifest=dict(status='REVIEW_ONLY_NOT_FOR_FABRICATION',boardSha256=hashlib.sha256(board.read_bytes()).hexdigest(),
    bom=dict(referenceCount=len(bom_refs),exactReferenceCoverage=True),
    nativeVersion=job['Header']['GenerationSoftware']['Version'],copperLayers=2,drills=drill_results,
    placements=dict(count=len(rows),positionsAndRotationsMatch=True,frame='KiCad absolute XY, Y negated; mm'),
    limitations=['Export verification is separate from fabrication release, external mechanical assembly and later hardware qualification.',
      'Finished copper:1oz standard;2oz on request. This board and solve use nominal35um copper, not2oz.',
      'Native stack and thermal-model dielectric conventions require documented reconciliation before fabrication release.',
      'BOM includes test points and stock interfaces; procurement and placement-machine filtering require assembly review.',
      'Checks verify drill centers/tool diameters and placement coordinates, not complete CAM/DFM, slot length, solder paste or manufacturing acceptance.'],
    files=[dict(path=str(p.relative_to(OUT)),bytes=p.stat().st_size,sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sorted(OUT.rglob('*'))if p.is_file()and p.name!='review.json'])
(OUT/'review.json').write_text(json.dumps(manifest,indent=2)+'\n')
print(json.dumps({k:v for k,v in manifest.items()if k!='files'},indent=2))