main
John Lauer Preserve branch-current and auxiliary envelope results without closing live gates c9b1be2
#!/usr/bin/env python3
"""Project-only resistive centerline diagnostic; not a replacement for filled-copper Fields."""
import hashlib,json,math
from pathlib import Path
import numpy as np
from sexp import parse,find,first
ROOT=Path(__file__).resolve().parents[1]
BOARD=ROOT/'aiflow/run/board-19.kicad_pcb'
SIGMA=58000.0 # S/mm at nominal reference temperature

def solve(edges,injections):
    nodes=sorted({n for a,b,r,meta in edges for n in [a,b]}); ids={n:i for i,n in enumerate(nodes)}
    matrix=np.zeros((len(nodes),len(nodes))); rhs=np.zeros(len(nodes))
    for a,b,r,meta in edges:
        if a==b:continue
        assert r>0
        i,j=ids[a],ids[b];g=1/r
        matrix[i,i]+=g;matrix[j,j]+=g;matrix[i,j]-=g;matrix[j,i]-=g
    for n,a in injections.items():rhs[ids[n]]+=a
    assert abs(sum(injections.values()))<1e-10
    v=np.zeros(len(nodes));v[1:]=np.linalg.solve(matrix[1:,1:],rhs[1:])
    residual=matrix@v-rhs
    assert np.max(np.abs(residual))<1e-8
    return [(v[ids[a]]-v[ids[b]])/r if a!=b else 0 for a,b,r,meta in edges],float(np.max(np.abs(residual)))

# Analytic series and parallel checks prevent current-sharing/unit regressions.
assert np.allclose(np.abs(solve([('a','b',1,{}),('b','c',2,{})],{'a':3,'c':-3})[0]),[3,3])
assert np.allclose(np.abs(solve([('a','b',1,{}),('a','b',2,{})],{'a':3,'b':-3})[0]),[2,1])
b=parse(BOARD.read_text());netnames={str(n[1]):str(n[2]) for n in find(b,'net')}
def net(n):
    v=first(n,'net')[1];return netnames.get(str(v),str(v))
def xy(n,k):return tuple(float(x) for x in first(n,k)[1:3])
def node(layer,p):return (layer,round(p[0],6),round(p[1],6))
allresults=[]
for name in ['DUT_POS','DUT_FUSED']:
    edges=[]; unions={}
    def root(n):
        while n in unions:n=unions[n]
        return n
    def union(a,c):
        a,c=root(a),root(c)
        if a!=c:unions[max(a,c)]=min(a,c)
    for s in find(b,'segment'):
        if net(s)!=name:continue
        a,c=xy(s,'start'),xy(s,'end');width=float(first(s,'width')[1]);layer=str(first(s,'layer')[1]);length=math.dist(a,c)
        edges.append((node(layer,a),node(layer,c),length/(SIGMA*width*.035),{'kind':'track','id':str(first(s,'uuid')[1]),'widthMm':width,'lengthMm':length,'layer':layer}))
    for v in find(b,'via'):
        if net(v)!=name:continue
        at=xy(v,'at');d=float(first(v,'drill')[1]);plating=.025
        area=math.pi*((d/2+plating)**2-(d/2)**2)
        edges.append((node('F.Cu',at),node('B.Cu',at),1.6/(SIGMA*area),{'kind':'via','id':str(first(v,'uuid')[1]),'barrelAreaMm2':area}))
    # This board's flagged nets have axis-aligned pads. Reject other orientations.
    pads={}
    for f in find(b,'footprint'):
        ref=next((str(p[2]) for p in find(f,'property') if p[1]=='Reference'),'')
        at=first(f,'at');fx,fy=map(float,at[1:3]);angle=float(at[3]) if len(at)>3 else 0
        for p in find(f,'pad'):
            if not first(p,'net') or net(p)!=name:continue
            assert angle % 180 == 0,(ref,'only 0/180 degree footprints supported in this diagnostic')
            px,py=xy(p,'at');sign=1 if angle % 360 == 0 else -1;cx,cy=fx+sign*px,fy+sign*py;size=xy(p,'size');padnum=str(p[1]);pads[(ref,padnum)]=(cx,cy)
            layers=['F.Cu','B.Cu'] if p[2]=='thru_hole' else [str(first(p,'layers')[1])]
            for layer in layers:
                center=node(layer,(cx,cy))
                # Only endpoints in a conservative central disk are equipotential here.
                for edge in edges:
                    for n in edge[:2]:
                        if n[0]==layer and math.dist(n[1:],(cx,cy))<=min(size)/2:union(center,n)
            if p[2]=='thru_hole':
                drill=float(first(p,'drill')[1]);area=math.pi*((drill/2+.025)**2-(drill/2)**2)
                edges.append((node('F.Cu',(cx,cy)),node('B.Cu',(cx,cy)),1.6/(SIGMA*area),{'kind':'plated-pad','pin':ref+'.'+padnum,'barrelAreaMm2':area}))
    edges=[(root(a),root(c),r,m) for a,c,r,m in edges]
    for source_layer in (['F.Cu','B.Cu'] if name=='DUT_POS' else ['F.Cu']):
        if name=='DUT_POS':
            sense=24/(110000*.99)
            points=[(source_layer,pads[('J1','1')],3+sense),('F.Cu',pads[('F1','1')],-3),('F.Cu',pads[('R24','1')],-sense)]
        else:points=[('F.Cu',pads[('F1','2')],3),('F.Cu',pads[('D1','2')],-3)]
        injection={}
        for layer,p,amps in points:injection[root(node(layer,p))]=injection.get(root(node(layer,p)),0)+amps
        currents,residual=solve(edges,injection);rows=[]
        for e,current in zip(edges,currents):
            m=dict(e[3]);m['amps']=abs(float(current));m['resistanceOhm']=e[2]
            if m['kind']=='track':
                area=m['widthMm']*.035*1550.0031
                m['ipc2221RiseC']=(m['amps']/(.048*area**.725))**(1/.44)
            rows.append(m)
        allresults.append({'net':name,'sourceLayer':source_layer,'kclMaxResidualA':residual,'conductors':rows,'peakTrackRiseC':max(r.get('ipc2221RiseC',0) for r in rows)})
report={'formalAcceptance':False,'kind':'resistive-centerline-branch-diagnostic','boardSha256':hashlib.sha256(BOARD.read_bytes()).hexdigest(),'cases':allresults,'limits':['Tracks modeled as uniform straight resistors; no filled polygon current distribution','Pad central regions treated equipotential; pad necks/contact spreading not qualified','35 um copper, 25 um barrel plating, 1.6 mm barrels assumed, not measured','Both J1 source-layer extremes checked; actual contact distribution unknown','No thermal coupling, conductivity-temperature feedback or pulse heating','This diagnostic does not override AIFlow or Fields gates']}
(ROOT/'design/step12-resistive-branch-summary.json').write_text(json.dumps(report,indent=2)+'\n')
for r in allresults:print(r['net'],r['sourceLayer'],'peak track rise',round(r['peakTrackRiseC'],3),'C')