main
John Lauer
Add JST GH libraries, native schematic parity and revised sensor harness study with reviewed clips
1ac01c3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
"""Plan only the added sensor branch against conservative two-layer copper obstacles.
Native DRC is mandatory; no acceptance is inferred from this search.
"""
from pathlib import Path
import json,copy,shutil,math,heapq,uuid,hashlib
import numpy as np
from shapely.geometry import Point,LineString,box
from shapely.affinity import rotate,translate
from shapely.ops import unary_union
from shapely import contains_xy
import sexp
R=Path(__file__).resolve().parents[1];src=R/'checkpoints/sensor-gh-review-v6';O=R/'checkpoints/sensor-gh-review-v8';O.mkdir(exist_ok=True);S=sexp.Sym
for name in ['3d','lib']:shutil.copytree(src/name,O/name,dirs_exist_ok=True)
for name in ['fp-lib-table','sensor-gh-candidate.kicad_pro','sensor-gh-candidate.kicad_dru','netlist.json']:shutil.copy2(src/name,O/name)
b=sexp.parse((src/'sensor-gh-candidate.kicad_pcb').read_text());base=sexp.parse((R/'checkpoints/scaffold-fit-review/native-saved/scaffold-fit-candidate.kicad_pcb').read_text());ids={sexp.first(v,'uuid')[1]for tag in ['segment','via']for v in sexp.find(base,tag)}
b[:]=[v for v in b if not(isinstance(v,list)and v and v[0]in ['segment','via']and sexp.first(v,'uuid')[1]not in ids)]
obs=[[],[]];goals=[[],[]];holes=[];allpads=[];window=box(98.5,35,118,62)
def net(v):n=sexp.first(v,'net');return n[-1]if n else None
def put(shape,layers,n,isgoal=True):
if not shape.intersects(window.buffer(1)):return
for l in layers:
if n=='TEMP_SENSE':
if isgoal:goals[l].append(shape)
else:obs[l].append(shape)
for f in sexp.find(b,'footprint'):
props={p[1]:p[2]for p in sexp.find(f,'property')};at=sexp.first(f,'at');fx,fy=map(float,at[1:3]);angle=math.radians(float(at[3])if len(at)>3 else 0)
for p in sexp.find(f,'pad'):
a=sexp.first(p,'at');px,py=map(float,a[1:3]);x=fx+px*math.cos(angle)+py*math.sin(angle);y=fy-px*math.sin(angle)+py*math.cos(angle);w,h=map(float,sexp.first(p,'size')[1:3]);pa=float(a[3])if len(a)>3 else math.degrees(angle)
shape=Point(0,0).buffer(w/2)if p[3]=='circle' else box(-w/2,-h/2,w/2,h/2)
shape=translate(rotate(shape,-pa,origin=(0,0)),x,y);layers=sexp.first(p,'layers')[1:];ls=[l for l,name in enumerate(['F.Cu','B.Cu'])if name in layers or '*.Cu'in layers]
put(shape,ls,net(p),props['Reference']!='J10');allpads.append(shape)
dr=sexp.first(p,'drill')
if dr:
nums=[float(v)for v in dr[1:]if isinstance(v,str)and v.replace('.','',1).isdigit()]
if nums:holes.append(Point(x,y).buffer(max(nums)/2))
for s in sexp.find(b,'segment'):
a=list(map(float,sexp.first(s,'start')[1:3]));c=list(map(float,sexp.first(s,'end')[1:3]));g=LineString([a,c]).buffer(float(sexp.first(s,'width')[1])/2);put(g,[0 if sexp.first(s,'layer')[1]=='F.Cu'else 1],net(s))
for v in sexp.find(b,'via'):
x,y=map(float,sexp.first(v,'at')[1:3]);put(Point(x,y).buffer(float(sexp.first(v,'size')[1])/2),[0,1],net(v));holes.append(Point(x,y).buffer(float(sexp.first(v,'drill')[1])/2))
step=.1;xs=np.arange(98.5,118.001,step);ys=np.arange(35,62.001,step);X,Y=np.meshgrid(xs,ys);shape=X.shape
# Extra10um raster margin; rectangular approximations are conservative for rounded pads.
blocked=np.array([contains_xy(unary_union(v).buffer(.2+.125+.01),X,Y)for v in obs]);goal=np.array([contains_xy(unary_union(v),X,Y)for v in goals])
via_obstacle=unary_union([unary_union(v).buffer(.2+.3+.01)for v in obs]+[unary_union(holes).buffer(.25+.15+.01),unary_union(allpads).buffer(.3+.1)])
via_blocked=contains_xy(via_obstacle,X,Y);goal_y,goal_x=np.where(np.any(goal,axis=0));assert len(goal_x)>0
heuristic=np.hypot(np.maximum(np.maximum(xs[goal_x.min()]-X,X-xs[goal_x.max()]),0),np.maximum(np.maximum(ys[goal_y.min()]-Y,Y-ys[goal_y.max()]),0))
start=(0,int(round((39-35)/step)),int(round((108-98.5)/step)));assert not blocked[start]
q=[(float(heuristic[start[1:]]),0.,start)];dist={start:0};parent={};end=None;expanded=0
while q:
_,cost,u=heapq.heappop(q)
if cost>dist[u]+1e-9:continue
expanded+=1;l,y,x=u
if goal[u]:end=u;break
candidates=[]
for dy,dx in [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]:
yy,xx=y+dy,x+dx
if 0<=yy<shape[0]and 0<=xx<shape[1]and not blocked[l,yy,xx]:
if dx and dy and(blocked[l,y,xx]or blocked[l,yy,x]):continue
candidates.append(((l,yy,xx),step*math.hypot(dx,dy)))
if not via_blocked[y,x]and not blocked[1-l,y,x]:candidates.append(((1-l,y,x),5.0))
for v,inc in candidates:
nc=cost+inc
if nc+1e-9<dist.get(v,float('inf')):dist[v]=nc;parent[v]=u;heapq.heappush(q,(nc+float(heuristic[v[1:]]),nc,v))
assert end is not None,'No route in bounded search window; expand or review layout'
path=[end]
while path[-1]!=start:path.append(parent[path[-1]])
path.reverse()
def xy(u):return [round(float(xs[u[2]]),6),round(float(ys[u[1]]),6)]
# Preserve every layer transition; collapse only exactly collinear grid legs.
points=[path[0]]
for i in range(1,len(path)-1):
a,c,d=path[i-1:i+2]
if (c[0]-a[0],c[1]-a[1],c[2]-a[2])!=(d[0]-c[0],d[1]-c[1],d[2]-c[2]):points.append(c)
points.append(path[-1])
# Simplify search-grid turns using only horizontal/vertical/45-degree links,
# checking each whole segment against the original conservative obstacles.
clearance_shapes=[unary_union(v).buffer(.335)for v in obs]
simplified=[points[0]];i=0
while i<len(points)-1:
if points[i+1][0]!=points[i][0]:simplified.append(points[i+1]);i+=1;continue
end_index=i+1
while end_index+1<len(points)and points[end_index+1][0]==points[i][0]:end_index+=1
selected=None
for j in range(end_index,i,-1):
aa,cc=xy(points[i]),xy(points[j]);dx,dy=cc[0]-aa[0],cc[1]-aa[1];sx=1 if dx>=0 else -1;sy=1 if dy>=0 else -1
options=[]
if abs(dx)<1e-8 or abs(dy)<1e-8 or abs(abs(dx)-abs(dy))<1e-8:options.append([aa,cc])
elif abs(dx)>abs(dy):options.extend([[aa,[aa[0]+sx*abs(dy),cc[1]],cc],[aa,[cc[0]-sx*abs(dy),aa[1]],cc]])
else:options.extend([[aa,[cc[0],aa[1]+sy*abs(dx)],cc],[aa,[aa[0],cc[1]-sy*abs(dx)],cc]])
for option in options:
if not LineString(option).intersects(clearance_shapes[points[i][0]]):selected=(j,option);break
if selected:break
if selected:
j,option=selected
for x,y in option[1:]:simplified.append((points[i][0],int(round((y-35)/step)),int(round((x-98.5)/step))))
i=j
else:simplified.append(points[i+1]);i+=1
points=simplified
segments=[];vias=[]
for a,c in zip(points,points[1:]):
if a[0]!=c[0]:
pos=xy(a);assert pos==xy(c);vias.append(pos);b.append([S('via'),[S('at'),*[S(str(v))for v in pos]],[S('size'),S('.6')],[S('drill'),S('.3')],[S('layers'),'F.Cu','B.Cu'],[S('net'),'TEMP_SENSE'],[S('uuid'),str(uuid.uuid4())]])
else:
aa,cc=xy(a),xy(c);layer=['F.Cu','B.Cu'][a[0]];segments.append({'start':aa,'end':cc,'layer':layer});b.append([S('segment'),[S('start'),*[S(str(v))for v in aa]],[S('end'),*[S(str(v))for v in cc]],[S('width'),S('.25')],[S('layer'),layer],[S('net'),'TEMP_SENSE'],[S('uuid'),str(uuid.uuid4())]])
board=O/'sensor-gh-candidate.kicad_pcb';board.write_text(sexp.dump(b)+'\n');r={'adopted':False,'method':'Bounded two-layer A*; conservative pad boxes;0.1mm search grid;0.25mm track;0.2mm clearance plus0.01 raster margin;0.6/0.3mm vias;5mm via cost','expandedStates':expanded,'routeCost':dist[end],'segments':segments,'vias':vias,'terminalXY':xy(end),'candidateSha256':hashlib.sha256(board.read_bytes()).hexdigest(),'nativeDRCRequired':True,'limits':['Ground pours refill around new branch; return continuity remains a separate check','Solder mask, thermal effects, clamp tolerances and assembly are not inferred from this planner']};(O/'route-plan.json').write_text(json.dumps(r,indent=2)+'\n');print(json.dumps(r,indent=2))