Files
vibemake-pcb-studio/backend/easyeda_backend/design_runtime/schematic.py
T
2026-11-10 19:04:27 +08:00

188 lines
11 KiB
Python

"""Compile a model's explicit pin/net table into isolated, named schematic stubs."""
import json
import math
import re
from .copper_audit import point_distance,segment_distance
from .part_metadata import selection_properties
from .state import canonical, write, DesignError,sha
def designator_changes(parts):
used=set();pending=[]
for p in sorted(parts,key=lambda p:p['id']):
name=(p.get('designator') or '').strip()
if name and '?' not in name and name.upper() not in used:used.add(name.upper())
else:pending.append(p)
changes=[]
for p in pending:
name=(p.get('designator') or '').strip();match=re.match(r'[A-Za-z]+',name)
prefix=match.group().upper() if match else 'X';index=1
while prefix+str(index) in used:index+=1
assigned=prefix+str(index);used.add(assigned)
changes.append({'id':p['id'],'before':p.get('designator'),'designator':assigned})
return changes
def expand_net_groups(parts,plan):
actual={}
for p in parts:
for pin in p['pins']:
token=p['designator']+'.'+pin['number'];identity=(p['designator'],pin['number'])
if token in actual and actual[token]!=identity:raise DesignError('Ambiguous actual pin references')
actual[token]=identity
assigned={}
for group in plan['nets']:
if not group['name']:raise DesignError('Use unconnected for explicit no-connect pins')
for token in group['pins']:
if token not in actual:raise DesignError('Unknown actual pin reference: '+token)
if token in assigned:raise DesignError('Pin assigned more than once: '+token)
assigned[token]=group['name']
for token in plan['unconnected']:
if token not in actual or token in assigned:raise DesignError('Unknown or duplicate no-connect reference: '+token)
assigned[token]=''
missing=sorted(set(actual)-set(assigned))
if missing:raise DesignError('Circuit plan omitted actual pins: '+str(missing)[:800])
return {'connections':[{'designator':actual[token][0],'pin':actual[token][1],'net':net} for token,net in assigned.items()],
'findings':plan['findings']}
def annotate(controller,t):
"""Resolve placeholders/duplicates through fixed calls before model planning."""
a=controller.adapter(t)
parts=a.execute('return (await eda.sch_PrimitiveComponent.getAll("part")).map(c=>({id:c.getState_PrimitiveId(),designator:c.getState_Designator()}));')
changes=designator_changes(parts)
if not changes:return []
work=controller.state.path(t['task_id'])/'project/work'
backup=work/'schematic-before-annotation.json'
if not backup.exists():write(backup,{'source':a.execute('return await eda.sys_FileManager.getDocumentSource();')})
for offset in range(0,len(changes),6):
batch=changes[offset:offset+6]
code='const changes='+canonical(batch)+';const out=[];'
code+=('for(const p of changes){const c=await eda.sch_PrimitiveComponent.get(p.id);const s=c.toAsync();'
's.setState_Designator(p.designator);await s.done();const v=await eda.sch_PrimitiveComponent.get(p.id);'
'out.push({id:v.getState_PrimitiveId(),designator:v.getState_Designator()});}return {ok:true,items:out};')
result=controller.perform(t,t['round'],{'action':'execute','document':'schematic','code':code,
'summary':'Assign unique schematic references from actual primitive IDs'},
{'approved':True,'reason':'Fixed annotation recipe','findings':[]},'annotation-'+str(offset)+'-'+sha(batch)[:8])
if result.get('items')!=[{'id':p['id'],'designator':p['designator']} for p in batch]:
raise DesignError('Schematic annotation readback mismatch')
write(work/'schematic-annotation.json',{'changes':changes})
controller.state.event(t['task_id'],'schematic.annotated',{'renamed':len(changes)})
return changes
def inspect(controller,t):
controller.focus(t,'schematic');a=controller.adapter(t)
annotate(controller,t)
parts=a.execute('const out=[];for(const c of await eda.sch_PrimitiveComponent.getAll("part")){'
'const pins=await eda.sch_PrimitiveComponent.getAllPinsByPrimitiveId(c.getState_PrimitiveId());'
'out.push({id:c.getState_PrimitiveId(),designator:c.getState_Designator(),x:c.getState_X(),y:c.getState_Y(),'
'pins:pins.map(p=>({number:String(p.pinNumber),name:p.pinName||"",x:p.x,y:p.y,rotation:p.rotation}))});}return out;')
if not parts:raise DesignError('No real schematic components to connect')
raw=a.execute('const f=await eda.sch_ManufactureData.getNetlistFile("intent");return await f.text();')
nl=json.loads(raw)
metadata={c.get('props',{}).get('Designator'):selection_properties(c.get('props',{}))
for c in nl.get('components',{}).values()}
for part in parts:part['properties']=metadata.get(part['designator'],{})
return parts
def compile_stubs(parts,expected):
"""Use each actual pin's axis, never its offset from the symbol centre.
Long two-column headers have pins closer to the top/bottom than their centre
line. Radial guessing consequently joins neighbouring rows into false nets.
Check all endpoints/crossings before touching the existing document.
"""
pins=[(part['designator'],pin) for part in parts for pin in part['pins']]
stubs=[]
for designator,pin in pins:
net=expected[(designator,pin['number'])]
if not net:continue
x,y,rotation=pin['x'],pin['y'],pin.get('rotation')
if rotation is None or not all(isinstance(v,(int,float)) and math.isfinite(v) for v in (x,y,rotation)):
raise DesignError('Actual pin direction unavailable: '+designator+'.'+pin['number'])
angle=math.radians(rotation)
ex,ey=x+12*math.cos(angle),y+12*math.sin(angle)
stubs.append({'x':x,'y':y,'ex':round(ex,6),'ey':round(ey,6),'net':net,
'pin':designator+'.'+pin['number']})
for i,stub in enumerate(stubs):
a,b=(stub['x'],stub['y']),(stub['ex'],stub['ey'])
for d,pin in pins:
key=(d,pin['number'])
if expected[key]!=stub['net'] and point_distance((pin['x'],pin['y']),a,b)<1e-6:
raise DesignError('Named stub touches a different-net or NC pin: '+stub['pin']+' / '+d+'.'+pin['number'])
for other in stubs[:i]:
if other['net']!=stub['net'] and segment_distance(a,b,(other['x'],other['y']),(other['ex'],other['ey']))<1e-6:
raise DesignError('Named stubs intersect across nets: '+stub['pin']+' / '+other['pin'])
return stubs
def arrange(controller,t,parts,nets):
from .schematic_page import fit_sheet
layout=fit_sheet(controller,t,parts,nets)
a=controller.adapter(t)
work=controller.state.path(t['task_id'])/'project/work'
prior={p['id']:p for p in parts}
moves=[m for m in layout['moves'] if abs(prior[m['id']]['x']-m['x'])>.001 or abs(prior[m['id']]['y']-m['y'])>.001]
if moves:
backup=work/'schematic-before-layout.json'
if not backup.exists():write(backup,{'source':a.execute('return await eda.sys_FileManager.getDocumentSource();')})
for offset in range(0,len(moves),6):
batch=[{k:p[k] for k in ('id','x','y')} for p in moves[offset:offset+6]]
code='const items='+canonical(batch)+';const out=[];'
code+=('for(const p of items){const c=await eda.sch_PrimitiveComponent.get(p.id);const s=c.toAsync();'
's.setState_X(p.x);s.setState_Y(p.y);await s.done();const v=await eda.sch_PrimitiveComponent.get(p.id);'
'out.push({id:v.getState_PrimitiveId(),x:v.getState_X(),y:v.getState_Y()});}return {ok:true,items:out};')
result=controller.perform(t,t['round'],{'action':'execute','document':'schematic','code':code,
'summary':'Arrange actual symbols inside native sheet with title-block and label margins'},
{'approved':True,'reason':'Fixed schematic placement','findings':[]},'sheet-layout-'+str(offset)+'-'+sha(batch)[:8])
actual=result.get('items') or []
if len(actual)!=len(batch) or any(v.get('id')!=p['id'] or
any(abs(v[k]-p[k])>.001 for k in ('x','y')) for p,v in zip(batch,actual)):
raise DesignError('Schematic placement readback mismatch')
parts=inspect(controller,t)
return parts,layout
def apply(controller,t,parts,plan):
work=controller.state.path(t['task_id'])/'project/work'
expected={}
for conn in plan['connections']:
key=(conn['designator'],conn['pin'])
if key in expected:raise DesignError('Duplicate pin in circuit plan: '+str(key))
expected[key]=conn['net']
actual={(p['designator'],pin['number']) for p in parts for pin in p['pins']}
if set(expected)!=actual:raise DesignError('Circuit plan must assign every actual pin exactly once; missing '+str(sorted(actual-set(expected)))[:500])
parts,layout=arrange(controller,t,parts,expected)
if {(p['designator'],pin['number']) for p in parts for pin in p['pins']}!=actual:
raise DesignError('Schematic pin identities changed during placement')
stubs=compile_stubs(parts,expected)
write(work/'schematic-pin-plan.json',plan)
a=controller.adapter(t)
# Keep the source and intended mapping before replacing faulty model wires.
backup=work/'schematic-before-wiring.json'
if not backup.exists():write(backup,{'source':a.execute('return await eda.sys_FileManager.getDocumentSource();')})
a.execute('const ws=await eda.sch_PrimitiveWire.getAll();if(ws.length)await eda.sch_PrimitiveWire.delete(ws.map(w=>w.getState_PrimitiveId()));return true;')
for i in range(0,len(stubs),12):
result=a.execute('const stubs='+canonical(stubs[i:i+12])+';let n=0;for(const s of stubs){'
'const w=await eda.sch_PrimitiveWire.create([s.x,s.y,s.ex,s.ey],s.net);'
'if(!w)throw Error("Named wire creation failed");n++;}return n;')
if result!=len(stubs[i:i+12]):raise DesignError('Schematic wire batch incomplete')
a.execute('return await eda.sch_Document.save();')
raw=a.execute('const f=await eda.sch_ManufactureData.getNetlistFile("wired");return await f.text();')
nl=json.loads(raw);errors=[];seen=set()
for c in nl.get('components',{}).values():
d=(c.get('props') or {}).get('Designator')
for n,pin in (c.get('pinInfoMap') or {}).items():
key=(d,str(n));net=(pin or {}).get('net') or ''
if key in expected:seen.add(key)
if key in expected and net!=expected[key]:errors.append(f'{d}.{n}: expected {expected[key]!r}, read {net!r}')
errors.extend(d+'.'+n+': missing from exported netlist' for d,n in sorted(set(expected)-seen))
result={'passed':not errors,'errors':errors,'pins':len(expected),'stubs':len(stubs),'findings':plan['findings'],
'sheet_layout_passed':layout['passed']}
write(work/'schematic-wiring-check.json',result)
if errors:raise DesignError('Compiled schematic net verification failed: '+'; '.join(errors[:5]))
controller.state.event(t['task_id'],'schematic.wiring_verified',{'pins':len(expected),'stubs':len(stubs)})
return result