198 lines
10 KiB
Python
198 lines
10 KiB
Python
"""Repeatable placement with quarter-turn search and bounded provisional sizing.
|
|
|
|
Geometry is mm in the editor's XY coordinate system. User mechanical limits
|
|
are immutable; only an explicitly provisional rectangle may grow.
|
|
"""
|
|
import math
|
|
import re
|
|
from collections import Counter
|
|
from .board_policy import can_grow
|
|
from .mounting import hole_geometry
|
|
|
|
EDGE, GAP = .6, .4
|
|
|
|
|
|
def power_net(net):
|
|
return bool(re.search(r'(^|[_+/-])(GND|VCC|VDD|VSS|VBAT|VBUS|VIN|VOUT|VPLUS|VMINUS|\d+V\d*)(_|$)',net,re.I))
|
|
|
|
|
|
def is_connector(part):
|
|
name=part['designator']
|
|
if re.match(r'^(J|CN|P)\d',name,re.I) or (re.match(r'^H\d',name,re.I) and part.get('pins',0)>=2):return True
|
|
identity=' '.join(str(part.get(k) or '') for k in ('device_name','manufacturer_part'))
|
|
return bool(re.search(r'\b(?:HDR|HEADER|USB|TYPE.?C)[_ -]|\b(?:TLW|TSW|SSW)-|\bXT(?:30|60)\b',identity,re.I))
|
|
|
|
|
|
def rotate(x,y,degrees):
|
|
a=math.radians(degrees);c,s=math.cos(a),math.sin(a)
|
|
return (c*x-s*y,s*x+c*y)
|
|
|
|
|
|
def variants(part):
|
|
original=float(part.get('rotation') or 0)
|
|
angles=part.get('allowed_rotations')
|
|
if angles is None:angles=[(original+d)%360 for d in (0,90,180,270)]
|
|
for angle in dict.fromkeys(angles):
|
|
delta=(float(angle)-original)%360
|
|
c,s=abs(math.cos(math.radians(delta))),abs(math.sin(math.radians(delta)))
|
|
yield {**part,'w':c*part['w']+s*part['h'],'h':s*part['w']+c*part['h'],
|
|
'rotation':float(angle)%360,'delta':delta,
|
|
'pad_offsets':[{**p,'x':rotate(p['x'],p['y'],delta)[0],'y':rotate(p['x'],p['y'],delta)[1]}
|
|
for p in part.get('pad_offsets',[])]}
|
|
|
|
|
|
def rectangle(p,x,y):
|
|
return (x-p['w']/2,y-p['h']/2,x+p['w']/2,y+p['h']/2)
|
|
|
|
|
|
def separated(r,q):
|
|
return r[2]+GAP<=q[0]+1e-8 or q[2]+GAP<=r[0]+1e-8 or r[3]+GAP<=q[1]+1e-8 or q[3]+GAP<=r[1]+1e-8
|
|
|
|
|
|
def _place_once(parts,board,holes,anchor):
|
|
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)
|
|
width,height=float(board['width_mm']),float(board['height_mm'])
|
|
if not all(math.isfinite(v) and v>0 for v in (width,height)):raise ValueError('Invalid board dimensions')
|
|
occupied=[];placed={};placed_shapes={};conflicts=[]
|
|
for hole in holes:
|
|
r,x,y=hole_geometry(hole)
|
|
occupied.append((x-r,y-r,x+r,y+r))
|
|
frequency=Counter(n for p in parts for n in set(p['nets']) if n)
|
|
options={p['id']:list(variants(p)) for p in parts}
|
|
|
|
def fits(p,x,y):
|
|
r=rectangle(p,x,y)
|
|
return (r[0]>=EDGE-1e-8 and r[1]>=EDGE-1e-8 and r[2]<=width-EDGE+1e-8 and r[3]<=height-EDGE+1e-8
|
|
and all(separated(r,q) for q in occupied))
|
|
|
|
def scorer(p):
|
|
links=[]
|
|
own={n:[(q['x'],q['y']) for q in p.get('pad_offsets',[]) if q['net']==n] or [(0,0)] for n in set(p['nets']) if n}
|
|
for ident,pos in placed.items():
|
|
other=placed_shapes[ident]
|
|
for net in sorted(set(own).intersection(other['nets'])):
|
|
weight=.1 if power_net(net) else 6/max(1,frequency[net]-1)
|
|
if (p['designator'].startswith('C') and other['designator'].startswith('U') and not is_connector(other)
|
|
and power_net(net) and not re.search(r'GND|VSS|VMINUS',net,re.I)):weight+=2
|
|
remote=[(q['x'],q['y']) for q in other.get('pad_offsets',[]) if q['net']==net] or [(0,0)]
|
|
links.append((pos['cx'],pos['cy'],weight,[(a[0]-b[0],a[1]-b[1]) for a in own[net] for b in remote]))
|
|
def score(x,y):
|
|
total=sum(weight*min(math.hypot(x-px+ox,y-py+oy) for ox,oy in offsets) for px,py,weight,offsets in links)
|
|
return total+.06*math.hypot(x-width/2,y-height/2) if links else math.hypot(x-width/2,y-height/2)
|
|
return score
|
|
|
|
def commit(p,x,y,edge=None):
|
|
placed[p['id']]={'id':p['id'],'cx':x,'cy':y,'rotation':p['rotation'],'w':p['w'],'h':p['h'],
|
|
**({'edge':edge} if edge else {})}
|
|
placed_shapes[p['id']]=p;occupied.append(rectangle(p,x,y))
|
|
|
|
connectors=sorted([p for p in parts if is_connector(p)],key=lambda p:(-p['w']*p['h'],key(p)))
|
|
core=sorted((p for p in parts if not is_connector(p)),key=lambda p:(not p['designator'].upper().startswith('U'),-p.get('pins',0),-p['w']*p['h'],key(p)))
|
|
# Reserve long edge headers before the MCU/regulator so they cannot be
|
|
# squeezed out by early greedy placements. Core still follows connectivity.
|
|
for index,part in enumerate(connectors):
|
|
best=None
|
|
for vi,p in enumerate(options[part['id']]):
|
|
score=scorer(p)
|
|
for j in range(1,40):
|
|
f=j/40
|
|
candidates=[]
|
|
if p['w']>=p['h']/2:candidates.extend(((width*f,EDGE+p['h']/2,'bottom'),(width*f,height-EDGE-p['h']/2,'top')))
|
|
if p['h']>=p['w']/2:candidates.extend(((EDGE+p['w']/2,height*f,'left'),(width-EDGE-p['w']/2,height*f,'right')))
|
|
for x,y,side in candidates:
|
|
vector=p.get('mating_vector')
|
|
if vector:
|
|
vx,vy=rotate(*vector,p['delta']);nx,ny={'left':(-1,0),'right':(1,0),'bottom':(0,-1),'top':(0,1)}[side]
|
|
if vx*nx+vy*ny<.99:continue
|
|
if not fits(p,x,y):continue
|
|
value=score(x,y)+vi*.001
|
|
if len(connectors)==len(parts):
|
|
# Distribute pure connector boards between opposite edges.
|
|
tx=EDGE+p['w']/2 if index==0 else width-EDGE-p['w']/2
|
|
ty=height/2 if index==0 else height*index/max(1,len(connectors))
|
|
value+=20*math.hypot(x-tx,y-ty)
|
|
candidate=(value,vi,j,x,y,side,p)
|
|
if best is None or candidate[:5]<best[:5]:best=candidate
|
|
if best is None:conflicts.append(part['designator']+' does not fit at a board edge');continue
|
|
_,_,_,x,y,side,p=best;commit(p,x,y,side)
|
|
|
|
for ci,part in enumerate(core):
|
|
best=None
|
|
for vi,p in enumerate(options[part['id']]):
|
|
score=scorer(p)
|
|
for ix in range(math.ceil((EDGE+p['w']/2)*2),math.floor((width-EDGE-p['w']/2)*2)+1):
|
|
for iy in range(math.ceil((EDGE+p['h']/2)*2),math.floor((height-EDGE-p['h']/2)*2)+1):
|
|
x,y=ix/2,iy/2
|
|
if not fits(p,x,y):continue
|
|
value=score(x,y)+vi*.001
|
|
if ci==0 and part['designator'].upper().startswith('U'):
|
|
value+=20*math.hypot(x-width*anchor[0],y-height*anchor[1])
|
|
candidate=(value,vi,x,y,p)
|
|
if best is None or candidate[:4]<best[:4]:best=candidate
|
|
if best is None:conflicts.append(part['designator']+' cannot fit within the specified outline');continue
|
|
_,_,x,y,p=best;commit(p,x,y)
|
|
return {'width_mm':width,'height_mm':height,'placements':list(placed.values()),'conflicts':conflicts,
|
|
'distance_basis':'actual_rotated_pad_positions' if all(p.get('pad_offsets') for p in parts) else 'component_centres',
|
|
'connector_orientation_review':[p['designator'] for p in connectors if not p.get('mating_vector')],
|
|
'connector_openings':[{'id':p['id'],'rotation':placed[p['id']]['rotation'],'edge':placed[p['id']]['edge'],
|
|
'evidence':p.get('mating_evidence')} for p in connectors if p['id'] in placed and p.get('mating_vector')],
|
|
'passed':len(placed)==len(parts) and not conflicts}
|
|
|
|
|
|
def _fixed_place(parts,board,holes):
|
|
best=None
|
|
for anchor in ((.5,.5),(.75,.5),(.25,.5),(.5,.7),(.5,.3)):
|
|
result=_place_once(parts,board,holes,anchor)
|
|
if best is None or len(result['conflicts'])<len(best['conflicts']):best=result
|
|
if result['passed']:return result
|
|
return best
|
|
|
|
|
|
def place(parts,board,holes=()):
|
|
original=(float(board['width_mm']),float(board['height_mm']));attempts=[]
|
|
dimensions=original;growth=can_grow(board,holes)
|
|
for index in range(9 if growth else 1):
|
|
trial={**board,'width_mm':dimensions[0],'height_mm':dimensions[1]}
|
|
result=_fixed_place(parts,trial,holes)
|
|
attempts.append({'width_mm':dimensions[0],'height_mm':dimensions[1],'conflicts':result['conflicts']})
|
|
if result['passed']:break
|
|
# Bounded geometric growth preserves the proposal's aspect ratio and
|
|
# records actual dimensions without altering the frozen request/contract.
|
|
dimensions=tuple(round(v*1.2,2) for v in dimensions)
|
|
result.update(size_attempts=attempts,size_origin=board.get('size_origin','unknown'),
|
|
provisional_resized=(result['width_mm'],result['height_mm'])!=original,
|
|
requested_board_mm=list(original))
|
|
return result
|
|
|
|
|
|
def placement_moves(parts,layout):
|
|
measured={p['id']:p for p in parts};moves=[]
|
|
for p in layout['placements']:
|
|
old=measured[p['id']];dx,dy=rotate(old['dx'],old['dy'],p['rotation']-old.get('rotation',0))
|
|
moves.append({'id':p['id'],'x':(p['cx']-dx)/.0254,'y':(p['cy']-dy)/.0254,'rotation':p['rotation']})
|
|
return moves
|
|
|
|
|
|
def audit_placement(parts,layout,holes=(),tolerance_mm=.06):
|
|
"""Check the written geometry, not just the algorithm's predicted boxes."""
|
|
expected={p['id']:p for p in layout['placements']};errors=[];boxes=[]
|
|
for p in parts:
|
|
q=expected.get(p['id']);b=p.get('bbox')
|
|
if q is None or not b:errors.append('Unexpected/missing component extent '+p['designator']);continue
|
|
r=tuple(b[k]*.0254 for k in ('minX','minY','maxX','maxY'))
|
|
cx,cy=(r[0]+r[2])/2,(r[1]+r[3])/2
|
|
if (max(abs(cx-q['cx']),abs(cy-q['cy']),abs(r[2]-r[0]-q['w']),abs(r[3]-r[1]-q['h']))>tolerance_mm
|
|
or abs((p['rotation']-q['rotation']+180)%360-180)>.01):errors.append('Placement readback mismatch '+p['designator'])
|
|
if min(r[0],r[1],layout['width_mm']-r[2],layout['height_mm']-r[3])<EDGE-tolerance_mm:errors.append('Outside board clearance '+p['designator'])
|
|
for name,other in boxes:
|
|
if not separated(r,other):errors.append('Component clearance conflict '+p['designator']+'/'+name)
|
|
for hole in holes:
|
|
radius,x,y=hole_geometry(hole)
|
|
if not separated(r,(x-radius,y-radius,x+radius,y+radius)):errors.append('Mounting clearance conflict '+p['designator'])
|
|
boxes.append((p['designator'],r))
|
|
if {p['id'] for p in parts}!=set(expected):errors.append('Placement component identities changed')
|
|
return {'passed':not errors,'errors':errors,'components':len(parts),'scope':'rotation, rotated extents, centre, board bounds and body gaps'}
|