110 lines
6.3 KiB
Python
110 lines
6.3 KiB
Python
"""Pack actual schematic symbols inside the native sheet, reserving label space."""
|
|
import math
|
|
import re
|
|
|
|
|
|
def _dense_pack(parts,sizes,width,height,title):
|
|
"""Maximal free rectangles avoid the fragmented pockets of target placement."""
|
|
gap=8
|
|
def subtract(free,used):
|
|
result=[]
|
|
for r in free:
|
|
if r[2]<=used[0] or used[2]<=r[0] or r[3]<=used[1] or used[3]<=r[1]:result.append(r);continue
|
|
if used[0]>r[0]:result.append((r[0],r[1],used[0],r[3]))
|
|
if used[2]<r[2]:result.append((used[2],r[1],r[2],r[3]))
|
|
if used[1]>r[1]:result.append((r[0],r[1],r[2],used[1]))
|
|
if used[3]<r[3]:result.append((r[0],used[3],r[2],r[3]))
|
|
result=sorted(set(r for r in result if r[2]>r[0] and r[3]>r[1]))
|
|
return [r for r in result if not any(q!=r and q[0]<=r[0] and q[1]<=r[1] and q[2]>=r[2] and q[3]>=r[3] for q in result)]
|
|
for strategy in ('area','height','edge'):
|
|
free=subtract([(40,40,width-40+gap,height-40+gap)],(title[0]-gap,title[1]-gap,title[2]+gap,title[3]+gap))
|
|
def order(p):
|
|
z=sizes[p['id']];w,h=z['w'],z['h']
|
|
return (-{'area':w*h,'height':h,'edge':max(w,h)}[strategy],-w*h,p['designator'])
|
|
moves=[]
|
|
for p in sorted(parts,key=order):
|
|
z=sizes[p['id']];w,h=z['w'],z['h'];choices=[]
|
|
for r in free:
|
|
x=math.ceil((r[0]+w/2)/10)*10-w/2
|
|
y=math.ceil((r[1]+h/2)/10)*10-h/2
|
|
if x+w+gap<=r[2]+1e-7 and y+h+gap<=r[3]+1e-7:
|
|
dw,dh=r[2]-x-w-gap,r[3]-y-h-gap
|
|
choices.append((min(dw,dh),max(dw,dh),y,x))
|
|
if not choices:break
|
|
_,_,y,x=min(choices);box=(x,y,x+w,y+h)
|
|
moves.append({'id':p['id'],'designator':p['designator'],'x':x+w/2-z['dx'],'y':y+h/2-z['dy'],'box':list(box)})
|
|
free=subtract(free,(x,y,x+w+gap,y+h+gap))
|
|
if len(moves)==len(parts):return moves
|
|
return None
|
|
|
|
|
|
def place(parts,width,height,nets):
|
|
width,height=float(width),float(height)
|
|
if not all(math.isfinite(v) and v>0 for v in (width,height)):raise ValueError('Invalid schematic sheet dimensions')
|
|
def key(p):
|
|
name=p['designator'].upper();m=re.fullmatch(r'([A-Z]+)(\d+)(.*)',name)
|
|
return (m[1],int(m[2]),m[3]) if m else (name,0,'')
|
|
parts=sorted(parts,key=key);sizes={}
|
|
for p in parts:
|
|
xs=[p['x']]+[v['x'] for v in p['pins']];ys=[p['y']]+[v['y'] for v in p['pins']]
|
|
props=p.get('properties',{});label=props.get('Name',props.get('Manufacturer Part') or props.get('DeviceName') or '')
|
|
if isinstance(label,str) and label.startswith('='):
|
|
label=re.sub(r'\{([^}]+)\}',lambda m:str(props.get(m[1]) or ''),label[1:])
|
|
text_width=min(130,max(0,len(str(label))*4))
|
|
left=min(xs)-40;right=max(max(xs)+40,p['x']+text_width+30)
|
|
bottom=min(ys)-35;top=max(ys)+35
|
|
sizes[p['id']]={'w':max(110,right-left),'h':max(75,top-bottom),
|
|
'dx':(left+right)/2-p['x'],'dy':(bottom+top)/2-p['y']}
|
|
core=max(parts,key=lambda p:(p['designator'].upper().startswith('U'),len(p['pins'])),default=None)
|
|
def priority(p):
|
|
s=sizes[p['id']]
|
|
return (0 if p is core else 1 if p['designator'].upper().startswith('U') else 2 if len(p['pins'])>=4 else 3,
|
|
-s['w']*s['h'],key(p))
|
|
title_block=(width*.37,0,width,min(220,height*.27))
|
|
occupied=[title_block];positions={};moves=[];conflicts=[];connector_index=0
|
|
# Newly provisioned native sheets use a lower-left origin; their title block
|
|
# occupies the lower-right. Preserve the rest of the lower-left for parts.
|
|
xlow,xhigh,ylow,yhigh=40,width-40,40,height-40
|
|
for p in sorted(parts,key=priority):
|
|
d=p['designator'].upper();s=sizes[p['id']]
|
|
if p is core:target=(width*.59,height*.60)
|
|
elif d.startswith('U'):target=(width*.28,height*.76)
|
|
elif re.search(r'USB|TYPE.?C',str(p.get('properties',{}).get('Manufacturer Part','')),re.I):
|
|
target=(width*.13,height*.75)
|
|
elif len(p['pins'])>=4:
|
|
target=(width*.86,height*.82-connector_index*175);connector_index+=1
|
|
elif d.startswith(('Y','X')):target=(width*.42,height*.55)
|
|
else:
|
|
own={net for (designator,_),net in nets.items() if designator==p['designator'] and net}
|
|
weighted=[]
|
|
for other in parts:
|
|
if other['id'] not in positions:continue
|
|
shared=own.intersection(net for (designator,_),net in nets.items() if designator==other['designator'])
|
|
weight=sum(.15 if re.search(r'GND|VSS|VDD|VCC|\dV',n,re.I) else 3 for n in shared)
|
|
if weight:weighted.append((positions[other['id']],weight))
|
|
total=sum(v for _,v in weighted)
|
|
target=(sum(pos[0]*v for pos,v in weighted)/total,sum(pos[1]*v for pos,v in weighted)/total) if total else (width*.45,height*.65)
|
|
candidates=[]
|
|
for ix in range(math.ceil((xlow+s['w']/2)/10),math.floor((xhigh-s['w']/2)/10)+1):
|
|
for iy in range(math.ceil((ylow+s['h']/2)/10),math.floor((yhigh-s['h']/2)/10)+1):
|
|
x,y=ix*10,iy*10;box=(x-s['w']/2,y-s['h']/2,x+s['w']/2,y+s['h']/2)
|
|
if all(box[2]+8<=r[0] or r[2]+8<=box[0] or box[3]+8<=r[1] or r[3]+8<=box[1] for r in occupied):
|
|
candidates.append((math.hypot(x-target[0],y-target[1]),x,-y,box))
|
|
if not candidates:
|
|
conflicts.append(p['designator']+' cannot fit with symbol/pin/label margins');continue
|
|
_,x,negative_y,box=min(candidates);y=-negative_y
|
|
positions[p['id']]=(x,y);occupied.append(box)
|
|
moves.append({'id':p['id'],'designator':p['designator'],'x':x-s['dx'],'y':y-s['dy'],'box':list(box)})
|
|
if conflicts and nets:
|
|
fallback=place(parts,width,height,{})
|
|
if fallback['passed']:
|
|
fallback['connection_targets_relaxed']=True
|
|
return fallback
|
|
if conflicts:
|
|
dense=_dense_pack(parts,sizes,width,height,title_block)
|
|
if dense is not None:moves=dense;conflicts=[]
|
|
return {'passed':not conflicts and len(moves)==len(parts),'sheet_width':width,'sheet_height':height,
|
|
'usable_area':[xlow,ylow,xhigh,yhigh],'moves':moves,'conflicts':conflicts,
|
|
'title_block_reserved':list(title_block),
|
|
'scope':'actual pin extents plus reserved symbol/name/net-label margins; not an electrical check'}
|