main
John Lauer Verified thermal vias with ground continuity; device protocol and host interoperability tests; no thermal or fabricatio… 8082416
"""Propose ground stitching from native filled copper. Native DRC remains mandatory."""
import sys,json,math
from pathlib import Path
from shapely.geometry import Polygon,Point
from shapely.ops import polylabel
sys.path.insert(0,str(Path(__file__).parent));from sexp import parse,find,first
b=parse(Path(sys.argv[1]).read_text())
polys=[];layers=[]
for z in find(b,'zone'):
 if first(z,'net') is None or first(z,'net')[-1]!='GND':continue
 for f in find(z,'filled_polygon'):
  poly=Polygon([(float(p[1]),float(p[2])) for p in first(f,'pts')[1:]]).buffer(0)
  polys.append(poly);layers.append(first(f,'layer')[1])
parent=list(range(len(polys)))
def root(i):
 while parent[i]!=i:i=parent[i]
 return i
def join(ids):
 if ids:
  for i in ids[1:]:parent[root(i)]=root(ids[0])
obstacles=[]
for v in find(b,'via'):
 x,y=map(float,first(v,'at')[1:3]);size=float(first(v,'size')[1]);drill=float(first(v,'drill')[1]);p=Point(x,y);obstacles.append(p.buffer(drill/2+.4))
 if first(v,'net')[1]=='GND':join([i for i,g in enumerate(polys) if g.distance(p)<size/2+.001])
for f in find(b,'footprint'):
 at=first(f,'at');x,y=map(float,at[1:3]);a=math.radians(float(at[3]) if len(at)>3 else 0)
 for pad in find(f,'pad'):
  if pad[2] not in ['thru_hole','np_thru_hole']:continue
  atp=first(pad,'at');u,v=map(float,atp[1:3]);p=Point(x+u*math.cos(a)+v*math.sin(a),y-u*math.sin(a)+v*math.cos(a));sz=first(pad,'size');dr=first(pad,'drill');rad=max(float(q) for q in dr[1:] if str(q).replace('.','',1).isdigit())/2
  obstacles.append(p.buffer(rad+.4))
  net=first(pad,'net')
  if net and net[1]=='GND':join([i for i,g in enumerate(polys) if g.distance(p)<min(float(sz[1]),float(sz[2]))/2+.001])
edges=[]
for i,g in enumerate(polys):
 for j,h in enumerate(polys[:i]):
  if layers[i]==layers[j]:continue
  overlap=g.buffer(-.36).intersection(h.buffer(-.36))
  for obs in obstacles:
   if not overlap.is_empty and overlap.intersects(obs):overlap=overlap.difference(obs)
  if overlap.is_empty:continue
  shapes=list(overlap.geoms) if hasattr(overlap,'geoms') else [overlap]
  for s in shapes:
   if s.geom_type!='Polygon' or s.area<.005:continue
   p=polylabel(s,tolerance=.03);score=p.distance(s.boundary)
   edges.append((score,i,j,p.x,p.y))
initial=len({root(i) for i in parent});selected=[]
for score,i,j,x,y in sorted(edges,reverse=True):
 if root(i)==root(j):continue
 join([i,j]);selected.append({'x':round(x,3),'y':round(y,3),'from':i,'to':j,'marginMm':round(score,3)})
report={'initialComponents':initial,'remainingComponents':len({root(i) for i in parent}),'stitches':selected,'polygons':[{'id':i,'layer':layers[i],'area':round(g.area,3),'group':root(i)} for i,g in enumerate(polys)]}
Path(sys.argv[2]).write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))