diff --git a/README.md b/README.md index df1ba6154..cc3c80d1e 100644 --- a/README.md +++ b/README.md @@ -207,3 +207,8 @@ Check out our papers (all open-access), which have more details: [Embedded Device Generation](https://dl.acm.org/doi/10.1145/3083157.3083159) (or more generally Electronic Device Generation) was a prior version of this project that focused on algorithms and models for embedded device synthesis, though it lacked a user-facing component. This project is a continuation of that work focusing on an end-to-end system, and for most of its development cycle has been called `edg`. But, for the purposes of writing research papers, naming collisions are confusing and bad, and we chose to keep the repo and paper name consistent. + +### Generated KiCad schematic views (opt-in) + +See [schematic export](docs/schematic-export.md) for generated review schematics, +symbol mappings, and validation requirements. PB Python remains the source of truth. diff --git a/docs/schematic-export.md b/docs/schematic-export.md new file mode 100644 index 000000000..7159dfa9f --- /dev/null +++ b/docs/schematic-export.md @@ -0,0 +1,771 @@ +# Generated KiCad schematics + +PB Python defines the parts, physical pad mappings and connectivity. Generated +schematics are a one-way view of that compiled design. Every sheet says to edit +Python and regenerate; KiCad edits are overwritten. The existing PB netlist +remains the supported PCB update workflow. + +## PB owns schematic generation + +The exporter is a native PB capability. Compilation, physical connectivity, +symbol resolution, functional placement, orientation search, routing, sheet +planning and KiCad serialization all run inside PB. Generation does not require +`agentic-pcb`, an MCP server, or an agent session. + +Use `compile_board(..., schematic=options)` or +`compile_board_inplace(..., schematic=options)` for integrated generation, or +`KiCadSchematicExporter().export(compiled, options)` for an in-memory bundle +after successful compilation and reference assignment. The PB CLI example below +uses this same native path. + +The companion agentic-pcb tools adapt these APIs for agents: they validate +requests, manage isolated candidates and provenance, and invoke native checks. +They do not supply a second schematic generator. Given identical compiled +input, options, libraries and sheet plan, the adapter and direct PB call produce +identical artifact contents. The standalone regression runs PB's CLI in a fresh +interpreter with all `agentic_pcb` imports blocked; companion parity tests compare +the actual native and adapter bundles. + +## Compile and open + +```python +from edg import compile_board_inplace, SchematicExportOptions + +compile_board_inplace( + MyBoard, + schematic=SchematicExportOptions( + design_name="MyBoard", + symbol_library_dirs=("/usr/share/kicad/symbols",), + ), +) +``` + +A runnable opt-in example is +[`examples/export_schematic.py`](../examples/export_schematic.py). Run +`python -m examples.export_schematic --output /tmp/pb-schematic-example --symbol-dir /usr/share/kicad/symbols` +from the PB checkout to generate the existing LED design in a dedicated +destination. The example uses Python presentation hints to keep the LED and +its current-limiting resistor in circuit order. The LED rotation stays locked; +the resistor explicitly allows fixed-center 180-degree trials. + +Open the root schematic in `MyBoard/MyBoard.schematic/`. Each independent +physical board scope has its own root. The manifest lists generated files, +source provenance, a compiled-design fingerprint and diagnostics. + +Library directories are searched in order, followed by `KICAD9_SYMBOL_DIR` +(or the major version selected in options). The output embeds the definitions, +so readers do not need the original symbol libraries installed. Generation does +not download files or require a running KiCad GUI. + +## Circuit meaning and engineering handoff + +`SchematicPresentation` schema 2 adds source-owned `circuits` to the existing +schema-1 descriptions, interfaces and group titles. Schema 1 remains accepted. +Use compiled physical component paths and pin numbers, for example: + +```python +from edg import SchematicPresentation + +presentation = SchematicPresentation.from_dict({ + "schema": 2, + "circuits": [{ + "id": "reset_interface", + "title": "Reset interface", + "summary": "Controller reset signal passes through the series resistor.", + "components": ["reset_resistor"], + "boundaries": [ + {"component": "reset_resistor", "pin": "1", "name": "Controller reset", "role": "input"}, + {"component": "reset_resistor", "pin": "2", "name": "Target reset", "role": "output"}, + ], + }], +}) +``` + +Pass this object as `SchematicExportOptions.presentation`. Replace the example +paths and physical pins with the actual compiled inventory. Circuit titles and +summaries appear on the detailed drawing; boundary notes identify the physical +terminal and generated net label. Their bounds are reserved before sheet packing. +The exported `circuit-model.json` records membership, pattern evidence, terminal +net witnesses and authored versus automatic provenance. + +Generic pin names initially describe PB ports. A strap pad connected to SDA or +SCL can therefore inherit that connected-port name rather than its physical +function. Use verified `components[path].pin_names` presentation entries to name +such pads A0/A1 while keeping their actual connections unchanged. Only annotate +modeled physical pins; do not invent omitted pads or NC declarations. + +Each circuit requires `id`, `title`, `summary` and `components`. Optional +`stages` contain ordered `{id, components}` objects. Optional `template` is +`auto` (default), `generic`, `buck`, `four_switch_bridge`, `gate_driver`, +`repeated_channel`, `connector_protection`, `mcu_support`, `series_path`, or +`controller_support`; non-generic templates require compiled topology evidence. +Boundary roles are `input`, `output`, `supply`, `return`, `control`, `feedback` +and `bidirectional`. Roles express authored intent, not electrical validation. +Unknown paths/pins, overlapping circuit membership, duplicate titles within a +board scope and circuits crossing independent scopes are errors. Ordered stages +must share a non-supply connection or an explicitly declared power-path boundary. + +The framework discovers patterns once per board scope, preserving ambiguous +support ownership instead of rediscovering a misleading association from a +smaller page. Placement evaluates at most eight deterministic whole-circuit +proposals, including the baseline, and routes at most three shortlisted proposals +plus that baseline. Candidates may not introduce failed endpoints, crossings, +collisions or page clipping. Selection prioritizes primary-path visibility, +crossings, unrelated-stage intrusion, bends, wire length and area. Fixed placement +hints remain authoritative. Complete circuits may use additional pages rather +than smaller text; oversized circuits continue at authored stages or child-circuit +boundaries. + +Local routing and label tails reserve 1.27 mm of visual clearance around +foreign parallel wires, endpoints and bends. Straight perpendicular interior +crossings remain permitted. This prevents electrically distinct half-grid buses +from looking joined in the drawing. When a board scope contains multiple ground +nets, every ground glyph displays its net identity so raw battery negative and +protected system return remain distinguishable. The configured ground graphic +style and physical connectivity are preserved. + +Validate automatic and curated outputs separately. Native KiCad equality proves +representation truth. For engineering handoff, fresh reviewers must explain +power paths, control, feedback, protection, decoupling and cross-sheet interfaces +from rendered drawings alone. Score those explanations against a separately +prepared source-backed checklist. Missing or guessed critical relationships block +handoff acceptance, even when native checks and geometry metrics pass. + +## Actual symbols and pin mappings + +Standard resistor, capacitor, inductor, LED, diode, switch and connector mappings +use verified KiCad pin numbers. An exact-model registry handles additional known +parts. It never guesses a symbol from the reference designator or substitutes an +unrelated IC with similar functions. A physical block can declare its own map: + +```python +self.schematic_symbol("Device:LED", {"1": "1", "2": "2"}) +``` + +Keys are library symbol pin numbers; values are physical footprint pad numbers. +The exporter first uses the part's explicit declaration, then the standard +footprint mapping, then the registry. Declaration order has no effect. +Export mappings do not change schematic-import `symbol_pinning()`. + +For ESP32-C6-WROOM-1, use the exact symbol in +[Espressif's official library](https://github.com/espressif/kicad-libraries/blob/main/symbols/Espressif.kicad_sym). +Download `Espressif.kicad_sym` into one of the configured directories, retaining +the vendor license. Definitions from newer libraries are normalized to the +supported embedded-symbol grammar. Explicit exact-part registry maps can omit +library pins absent from PB's modeled pad inventory; they do not invent NCs. + +Missing symbols produce diagnosed functional views with the actual modeled pin +names and numbers, supply pins above, and ground below. Such views are not +claimed to be vendor symbols. Unknown packages and ambiguous diode polarity +remain unmapped. Unsupported multi-unit symbols also fall back explicitly. + +## Wires, grouping and presentation + +The exporter places functional groups and routes orthogonal local connections. +Wire branches are explicitly split, with junction dots; crossings between +unrelated nets have no junction. Internal routed nets need no redundant labels. +Cross-sheet signals use labels, and ground uses the standard power symbol. +Native netlist comparison is required to establish connectivity equivalence. + +Readable electrical values are displayed near components; the original physical +Value and Footprint properties remain intact. Procurement descriptions do not +need to occupy the drawing. Failed local routes retain matching net labels and +produce diagnostics rather than changing connectivity. + +Repeated channels and power stages are grouped before packing. Complete circuits +that exceed A3 continue at compiled child-subcircuit boundaries, with the reason +and preserved sections recorded in placement evidence. Numeric channel and +continuation order is retained. Verified buck and four-switch bridge patterns +use switch-pin geometry and compiled gate/rail connections for placement; a +boost input coil or ambiguous topology declines the buck template. Gate-driver, +bootstrap and FET branches can stay together across sibling block boundaries. +Parallel pads establish a terminal role only when their compiled nets agree. +Multiple owned bypass capacitors wrap beside a large IC instead of extending +an unbounded vertical stack. Generic driver views put declared gate, switch +and bootstrap ports toward the power stage; physical pin identities stay intact. + +Annotation coordinates are resolved before routing and retained through page +translation; regeneration never reselects a different field location after the +router has reserved its space. Label repair prefers paths without crossings. +When a label is trapped, a straight perpendicular interior crossing can be +used without a junction; endpoints, bends, anchors and collinear overlaps remain +prohibited. Native tests verify that such label tails do not merge nets. + +Routing and label repair protect visible pin text and reference/value fields, +including KiCad's relative field rotation on rotated symbols. Dense connector +labels can use a measured outer lane reserved before sheet packing. The bounded +router searches toward the actual target tree rather than its bounding box. + +Automatic grouping and placement are a baseline, not a guarantee of readable +circuit topology. Complex circuits can use Python-owned presentation hints: + +```python +from edg import SchematicExportOptions, SchematicPlacement + +options = SchematicExportOptions( + "MyBoard", + symbol_library_dirs=("/usr/share/kicad/symbols",), + placements={ + "led.package": SchematicPlacement("Status LED", 70, 80, rotation=180), + "led.res": SchematicPlacement("Status LED", 100, 80, rotation=90, lock_rotation=False), + }, +) +``` + +A placement contains a functional region, millimetre coordinates, an orthogonal +rotation, optional horizontal reflection, and optional reference/value annotation +coordinates. `lock_rotation` is appended to the placement fields and defaults to +`True`, preserving authored rotations. Set it to `False` to permit a 180-degree +trial while retaining the same center and any explicit annotation. Hints define presentation only: the compiled physical graph still +defines every wire. Missing component paths and incomplete hinted groups fail +explicitly. Hints arrange a circuit within a region; the shared sheet planner +then translates whole regions onto A3 landscape pages, preserving their scale, +relative positions and wiring. A functional region is not a separate sheet. + +### Plan complete regions onto sheets + +Without assignments, the planner packs measured regions in stable order, +favoring related regions. Measurements include headings, symbol graphics, +fields, pin labels, power symbols and wires. Fixed margins and gutters prevent +region overlap; oversized automatic groups continue on numbered regions. +Explicitly hinted circuits must fit as a whole or report an error. Mechanical +parts may occupy the overview inset instead of a dedicated circuit page. +An automatically titled sheet for a group named `Overview` uses the title +`Overview (circuit)`. An explicit sheet assignment to `Overview` selects the +overview inset. + +Assign related regions to named pages when the automatic organization needs +refinement. Assignment keys are canonical region IDs or unambiguous titles: + +```python +options = SchematicExportOptions( + "MyBoard", + symbol_library_dirs=("/usr/share/kicad/symbols",), + sheet_assignments={ + "Charger": "1. Power input", + "USB interface": "1. Power input", + "MCU": "2. Controller", + }, +) +``` + +A requested page that cannot hold its complete regions gains a diagnosed +continuation rather than clipping content. Sheets containing multiple regions +retain local labels at region boundaries; short inter-region wires are added +only where an unobstructed aligned corridor exists. Power-rail affinity alone +does not justify merging every circuit into a single region. + +The same planner is available before serialization: + +```python +from dataclasses import replace +from edg import KiCadSchematicExporter, SchematicSheetPlanner, SchematicSheetPlan + +plan = SchematicSheetPlanner().plan(compiled, options) +plan_data = plan.to_dict() # JSON-compatible, stable region IDs and coordinates +# Refine region-to-sheet placement without changing the component inventory. +restored = SchematicSheetPlan.from_dict(plan_data) +options = replace(options, sheet_plan=restored) +bundle = KiCadSchematicExporter().export(compiled, options) +``` + +Plans bind to a deterministic fingerprint of the compiled design and resolved presentation. +Stale plans, missing/duplicate regions, cross-board moves, out-of-bounds positions +and overlapping regions are errors. The output includes `sheet-plan.json` and +planning diagnostics for sparse sheets, small regions and cross-sheet signal +counts. These measurements help review; they do not imply visual approval. + +The Ballu Gen3 companion `ballu_gen3_schematic.py` demonstrates functional hints +for parallel LED branches, a soft-power gate, charger, MCU support, servo +interfaces, display and an addressable RGB chain. Named sheet assignments +consolidate its circuits into seven circuit pages plus an overview. Circuit +connectivity remains defined by the board's Python source. + +### A useful first page + +Multi-sheet boards open on a system overview. Functional cards show a readable +name, circuit summary, actual component count and detail-sheet number. Each card +is a real KiCad hierarchical sheet link. The source notice, board identity and +mechanical reference area remain visible. The root has page number 1. + +By default, up to sixteen cards occupy a deterministic four-by-four grid. A +bounded selection of compiled cross-sheet relationships is drawn without arrows; +GND is excluded and no power or signal direction is guessed. The connection key +identifies each line. Large sheet inventories use a compact directory and the +existing contents hierarchy. Single-sheet designs retain their circuit root. + +Use Python-owned overview annotations for a stronger system narrative: + +```python +from edg import SchematicOverview, SchematicOverviewBlock, SchematicOverviewLink + +options = replace(options, overview=SchematicOverview( + blocks=( + SchematicOverviewBlock("Power", "Power management", "Protection / regulation", 0, 1), + SchematicOverviewBlock("Controller", "Controller", "MCU / programming support", 1, 1), + ), + links=( + SchematicOverviewLink("Power", "Controller", "3.3 V supply", ("v3v3",), directed=True), + ), +)) +``` + +Here `Power` and `Controller` must be actual unique sheet titles or canonical +sheet IDs, and `v3v3` must really connect components on both sheets. Grid columns +and rows are integers 0–3. Unspecified cards fill unused cells. Duplicate cells, +unknown/ambiguous sheets, cross-board links, self-links and unwitnessed nets are +errors. Titles/labels are limited to 48 characters, summaries to 96, and there +are at most eight authored relationships. The schema is available through +`SchematicOverview.to_dict()` / `from_dict()` for data-only tooling. + +An arrow states the author's intended functional flow. Its shared-net witnesses +establish physical association; they do not prove voltage direction, signal +causality or electrical safety. Diagram connectors are graphical polylines, +never schematic wires, pins or nets. They cannot alter electrical connectivity. + +`KiCadSchematicExporter().overview(compiled, options)` previews the same model +written to `overview.json`. Each board record contains card identities/bounds, +part counts, selected relationships with complete net witnesses, routing status, +and `shared_connections` for all non-GND sheet pairs. This lets agents refine +presentation using compiled evidence instead of guessing net names. The +`overview_present` flag distinguishes a circuit-only root from a system index. +Overview annotations are included in the plan fingerprint. + +The key and coverage counters disclose that the diagram is selective. A blocked +graphical route retains its relationship in the key with an explicit diagnostic; +it does not invent a wire or silently disappear. Direction/coverage, native +connectivity validation and visual approval are separate results. Inspect the +native page at readable scale, including arrowheads, line tags, descriptions, +mechanical notes, clipping and working sheet navigation. + +### Optional agent-assisted refinement + +The companion agentic-pcb integration provides `plan_pb_schematic`, +`generate_pb_schematic_candidate` and `review_pb_schematic_candidate`, backed by +the same framework planner and exporter. Candidates live in isolated directories; +source, plan, library and artifact hashes reject stale evidence. The tools accept +schema-validated presentation data rather than arbitrary Python callbacks. +Native review returns SVGs and connectivity results with visual approval pending. + +The `pb-schematic-generation` companion skill guides whole-board inspection and +presentation refinement. Keep durable choices beside the board source and +regenerate. Review every sheet for usable circuit communication, including local +support wiring and pin/field legibility; native netlist equality is a separate +acceptance gate. + +## Integrations and verification + +`KiCadSchematicExporter.export(compiled, options)` returns an in-memory +`SchematicExport` bundle and diagnostics. Compile successfully and assign +reference designators before calling it. `bundle.write()` stages files before +replacement and removes only stale manifest-owned files. It retains backups until +replacement and stale-file cleanup succeed, then publishes the manifest last. +Recoverable write failures restore the previous bundle, including removed stale +files, and remove newly introduced files. If rollback also fails, the exception +identifies a retained `.schematic-recovery-*` directory containing recovery copies. +This is exception rollback, not an atomic directory swap: concurrent readers can +observe intermediate files, and process termination or power loss requires manual +recovery. Avoid concurrent writers to the same destination. `generate=False` +writes nothing. + +For every root, use KiCad's schematic netlist export in `kicadxml` format, then +compare with `SchematicVerification.verify_schematic_netlist()` against that +`NetlistTransform` scope. This checks component identities, footprints, physical +pin inventories and connected pin sets, independently of net names. Inspect +native SVGs for circuit readability, annotations and visual crossing ambiguity; +netlist equality alone is not a readable-schematic acceptance test. + +The implementation is tested against native KiCad 9.0.9 and 10.0.8 using the +official containers under Apptainer. Focused regressions cover mappings, +inheritance, missing libraries, stable output, local wiring, preserved values, +Python placement/reflection, whole-region packing, stale/invalid plans, measured +bounds, exact component coverage, named continuations and index pagination. Interactive GUI navigation has +not been tested. Generic passive pin types do not reproduce PB electrical checks +or establish electrical design/manufacturing acceptance. + +## Functional presentation and readability evidence + +Exporter version 5 accepts optional `SchematicPresentation` data. It changes +visible descriptions, pin names and group titles without changing physical pins, +values, footprints or connectivity. Keep board-specific descriptions beside the +Python board source; reusable part semantics belong in the part model. + +```python +from edg import SchematicPresentation + +presentation = SchematicPresentation.from_dict({ + "schema": 1, + "components": {"target": {"description": "Programming target interface", + "pin_names": {"2": "EN / reset"}}}, + "interfaces": [{"component": "target", "pin": "2", "name": "Target reset"}], + "groups": {"programming": "Target programming"}, +}) +options = SchematicExportOptions("MyBoard", presentation=presentation) +``` + +Replace these illustrative component paths and physical pad numbers with verified +paths from the target design. Missing components, pins and groups are errors. +Annotations describe existing endpoints; they do not create wires or terminals. +`display_value` may supply a concise source-owned visible field; the original +compiled Value remains in its symbol property. Python `from_dict` accepts an +omitted schema as version 1; canonical JSON and MCP input use explicit schema 1. + +The exporter records actual recognized circuit patterns and conservative graphical +findings in `readability.json`, included in the generated manifest. The same +report is available through `KiCadSchematicExporter.readability(compiled, options)`. +It records text collisions, text outside page margins, wire/text intersections, +symbol fallbacks and local route fallbacks. Bounds use conservative font estimates +and may need visual disposition. Legal no-dot wire crossings are not shorts. +`visual_approval` remains `pending`: native fidelity and machine scene checks do +not establish that a person can explain the circuit from the sheets. + +Imports preserve verified symbol identity, physical pin mapping and pin names in +compiled metadata. Packed resistor arrays use a single physical instance with +separate visible branches, paired by the model's declared a/b indices. Missing +libraries retain explicit functional fallback diagnostics. Automatic circuit +patterns use verified terminal roles and actual nets; ambiguous patterns fall +back rather than inventing a topology. + +Labels use the shortest unambiguous suffix starting at three PB path segments; +`net-labels.json` retains every complete PB net name. Unsafe label characters are +encoded, and collisions are resolved deterministically. The compiled-design +fingerprint covers canonical solved physical components, modeled pinning, nets, +exporter version and resolved presentation; compiler source-location metadata is +excluded so checkout paths and source line numbers do not change it. + +Automatic field placement examines a fixed set of positions around each symbol, +avoiding its pin escape stubs, labels and ground graphics. Source-authored field +coordinates remain constraints. Recognized feedback/converter/amplifier patterns +improve grouping and preserve local support during pagination; complex analog +circuits still use the general routing algorithm and may need authored planning. +Machine findings remain visible even when an independent reader can trace a +candidate successfully. A review pass does not imply publication-quality spacing. + +`examples/schematic_presentations.py` contains source-verified descriptions for +seven examples whose interfaces or module power context benefit from explicit +notes. Pass `presentation_for(BoardClass.__name__)` as `options.presentation` to +use them. This is optional presentation data: the default automatic export is +measured separately from annotation-assisted output. No hand-authored coordinates +or electrical changes are needed for those descriptions. + +The planner reserves the native title-block area in addition to page margins. +Whole circuits that cannot fit the remaining space continue onto another sheet; +page counts may increase rather than draw through provenance or shrink text. +Display connector names follow verified device connection maps, including an +explicit FPC flip only when its exact adapter and compiled length are known. + +### Local bypass ownership + +The exporter preserves compiled block ancestry and recognizes typed +`DecouplingCapacitor` wrappers. A capacitor is associated with a unique device +inside the same functional owner only when both its actual supply and return +nets match the device's explicit terminal roles. Shared rails or array indices +alone never establish ownership. Ambiguous cases remain general circuits. + +Recognized device/bypass units stay together during automatic grouping and page +splitting. With either automatic or explicit placement, the router builds the +device supply backbone and attaches each bypass to its own device. It rejects +excessive local detours and paths through another bypass endpoint, retaining +net labels and reporting the existing local-wire fallback diagnostic. Source +placement hints may still require refinement. `readability.json` records +`local_decoupling` patterns and reports `decoupling_split` if explicit sheet +choices separate an associated unit; machine findings do not grant visual approval. + +### Ground symbol style + +`SchematicExportOptions(..., ground_style="bars")` uses the traditional +three-bar ground by default. Set `ground_style="triangle"` for the previous +KiCad triangle. MCP schematic options accept the same field and values. +Only embedded symbol graphics change; the PB ground net and power-pin semantics +remain unchanged. This is not a selection of earth, chassis or isolated ground. + +### Deterministic local routing optimizer + +`SchematicExportOptions.optimize_routes` defaults to `True`; set it to `False` +to compare against the baseline router. MCP uses the same default. The bounded +search evaluates eight candidates: baseline, X/Y/reversed endpoint orders, +short-net-first, two direction-aware tree searches, and a crossing-averse search. +Search budgets are fixed, not time-based; no global optimum is claimed. + +Component poses remain fixed during each routing search. Candidates cannot add +failed endpoints or crossings. A longer route is accepted only when it removes +crossings; otherwise union wire length must not increase. Selected routes are +measured before region packing, including any detours beyond the original route +envelope. Candidate order breaks ties deterministically. Visible symbol pin +names and numbers, properties, power graphics and labels are routing obstacles. +Final label repair keeps labels within their originating functional region. + +`routing.json` records before/after union wire length, bends, crossings, failed +endpoints and candidate selection per region. Metrics exclude fixed pin stubs, +ground symbols and inter-region wiring. Native electrical round trips and +independent visual review remain separate acceptance gates. + +### Fixed-center orientation optimization + +See the [native comparison and validation report](schematic-orientation-benchmark.md) +for matched USB-C renders, corpus results, runtime and visual limitations. + +`SchematicExportOptions.optimize_orientations` defaults to `True`. Each unlocked +component receives a 180-degree trial in stable PB-path order, for at most two +sweeps; a sweep without improvement terminates the search. Position constraints +and rotation constraints are independent. Graphics, physical pins and their +numbers rotate together; polarity and connectivity never change. Automatic +reference/value fields are recalculated for each trial, while explicit field +coordinates are preserved. + +The incumbent baseline route is cached. Each geometrically viable rotation uses +one baseline-router call, at most `2N` calls for `N` eligible components. The +route-order optimizer runs after orientation selection. Trials cannot add failed +endpoints, worsen collisions, overflow their page envelope or degrade visual +wire clearance. Valid trials rank primary-path fallbacks, crossings, unrelated +stage intrusion, bends, detour and total local wire length, with ties retaining +the incumbent. The detour estimate uses a Manhattan bounding lower bound, not an +optimal Steiner tree. Metrics include fixed pin stubs; final repaired label tails +and inter-region links remain outside the orientation score. + +For a source-declared `four_switch_bridge` circuit with uniquely verified +physical topology, the exporter then compares four +measured conventional arrangements (two bridge spacings by two controller +clearances) against the cached, orientation-optimized result. These add at most +four baseline-router calls. The controller's actual gate-pin geometry orders the +legs; rail identities and bidirectionality come from compiled connectivity. +Half-bridges are vertical, the inductor joins their switch nodes, and banks, +shunts and bootstrap branches stay with their verified rails. Driver-supply +bypass sits beside its actual controller supply pin. Bank rows grow from the +controller outward so the baseline router can extend each connected rail tree. No orientation +sweep is repeated for each bridge variant. Explicit component placement regions +skip this position-changing comparison. + +Primary-path scoring identifies physical endpoints on the verified controller, +FET, inductor, series shunt and bootstrap paths, even when authored external +boundaries are classified as supplies. Parallel bulk/bypass banks are reported +separately as `noncore_converter_fallbacks`; a bank label does not break the main +conversion path. Shared ground is excluded. Authored primary nets outside a +verified converter retain their original semantics. This prevents +an apparently lower-crossing candidate from winning by hiding the inductor path +behind labels. A better primary path may therefore win despite more crossings; +the comparison records that tradeoff rather than claiming every metric improved. + +`routing.json` records eligibility, every attempted angle, rejection reasons and +selected rotations. `bridge_comparison` records all four measured candidates, +including topology, symbol/field, escape and overflow rejection reasons, routed +metrics and the selected result. `orientation.after` and `selected_rotations` +describe the fixed-center stage; a later winning bridge can change those poses. +The region-level `after` metrics describe the final route-order result, and final +symbol poses are serialized in the schematic. Setting `optimize_orientations=False` +skips the fixed-center angle passes and this bridge comparison; automatic +functional placement, including the compact LED-buck pass below, remains active. +Search is finite but potentially +expensive for dense circuits: electrical equality and better metrics still need +native drawing review. + +### Verified capacitor coverage and compact LED bucks + +Ordinary `GenericMlcc` capacitors resolve to `Device:C` for the model's six +verified standard ceramic packages, with physical 1=pos and 2=neg. This applies +to Datalogger's direct generic capacitors as well as the existing verified +parallel-capacitor leaves. Model identity, package and pin roles must all match; +reference prefixes and names do not select symbols. Polarized capacitors retain +their separate mappings. Explicit declarations take precedence and invalid +explicit pin maps remain errors. + +`manifest.json` includes `symbol_coverage` per physical component: compiled +class, mapping source, selected symbol, status and a categorized fallback reason. +Missing mappings, unavailable libraries, missing library symbols and unsupported +symbols are distinct conditions. Symbols are still embedded in generated files. + +Verified TPS92200 buck LED-driver regions automatically compare the cached +incumbent with four compact arrangements after legacy orientation and routing, +before optional passive quarter turns. Compiled connections identify the exact +BOOT–SW capacitor, FB-to-ground current-sense resistor, output inductor and +separate input/output banks. BOOT is recognized from this verified model, not a +global alias applied to arbitrary ICs. Ambiguous circuits decline specialization. +Virtual off-board LED loads do not require inventing a connector or another pad. + +The bootstrap capacitor stays beside BOOT/SW; the sense resistor occupies a +separate feedback corridor. Authored placements skip this position-changing +pass, including placements with unlocked rotation. Automatic fields are +recomputed while authored field coordinates are retained. No public option is +added: this bounded functional placement is automatic, independently of the +orientation-pass switch. `optimize_orientations=False` still bypasses both +fixed-center orientation passes. + +Each region adds at most four routing trials using the incumbent's selected +strategy. Primary-path visibility, crossings and unrelated-circuit intrusion +precede wire length plus 2.54 mm per bend; ties keep the incumbent. New failed +endpoints, escape conflicts, collisions, overflow and degraded wire clearance +reject proposals. An additional bounded route-order search follows selection. +The fully serialized candidate must introduce no new or worse blocking scene +finding or increase the board scope's sheet count; failure restores the exact +cached region. A smaller circuit retains its incumbent packing-cell size as +explicit whitespace so unrelated regions keep their established sheet placement; +`content_bounds` and `reserved_bounds` disclose both measurements. Final geometry determines +bounds and plan fingerprints. + +`routing.json` stores `regions[].led_buck`: topology witnesses, all candidate +decisions, route-call counts, before/after metrics, serialized-scene evidence and +any rollback. Metrics and native netlist equality do not imply visual approval. +See the [symbol and converter gap report](schematic-symbol-converter-gaps.md) +for matched drawings, regression results and runtime measurements. + +### Opt-in passive quarter-turn refinement + +`SchematicExportOptions.orientation_mode` defaults to `"half_turn"`, retaining +that pipeline. Explicitly select `"passive_quarter_turn"` to test all four +orthogonal orientations for verified two-terminal passive symbols: + +```python +options = SchematicExportOptions( + "MyBoard", + symbol_library_dirs=("/usr/share/kicad/symbols",), + orientation_mode="passive_quarter_turn", +) +``` + +The additional pass runs after 180-degree optimization, converter-template +selection and their routing search. Templates cannot overwrite its selected +angles. Eligibility requires a resolved single-unit `Device:R`, `Device:R_US`, +`Device:C`, `Device:C_Polarized` or `Device:L` view with two distinct terminal +attachment positions. Stacked parallel physical pads remain distinct identities; +generic fallback boxes, other symbols and rotation-locked placements are not +quarter-turned. Reference prefixes and footprint names do not establish +eligibility. Explicit placements still require `lock_rotation=False` to participate. + +The cached incumbent keeps its centers and selected routing strategy. The pass +visits each eligible passive once in stable PB-path order, evaluates the three +other absolute angles from the same incumbent, then commits the best valid +candidate. At most `3P` additional router calls are made for `P` eligible passives; +geometric rejection needs no route call. Automatic fields are recomputed from +their original policy, while authored field coordinates are preserved. Rotation +never swaps physical pin numbers, changes polarity or rewires the compiled graph. + +Primary-path fallbacks, crossings and unrelated-circuit intrusion remain the +leading priorities. Otherwise the pass minimizes local wire length plus 2.54 mm +per bend, rounded to four decimal places. Equal weighted cost retains the +incumbent when those leading priorities also tie; there is no secondary bend, +detour or length tie-breaker. Equally good improving alternatives retain the first +one in stable angle order. Trials +cannot add failed endpoints, pin-neck reentry, collisions, clipping or degraded +wire clearance. Each region with proposed changes receives at most one additional +bounded route-order search when `optimize_routes=True`. Existing placement, +180-degree and bridge searches remain separate costs from the `3P` bound. + +The exporter reuses the prepared baseline and compares fully serialized scenes, +including labels, properties, pin text and GND graphics. A new or worsened +blocking scene contact rolls back all accepted passive changes in that independent +board scope to its cached baseline; other scopes can keep their improvements. +Rollback restores cached poses, routes and bounds without another optimization +loop. Final chosen geometry supplies bounds and fingerprints, and adopted sheet +plans are validated against that result. No generated schematic is manually repaired. + +`routing.json` records `passive_orientation` evidence per region: eligibility, +allowed and attempted angles, reasons, route-call counts, final angles and any +rollback. Retained baseline geometry is a valid result when no safe improvement +exists. `optimize_orientations=False` bypasses both orientation passes regardless +of mode. Source-of-truth notices and the existing compile return values are unchanged. + +The final functional run passed 228 schematic tests (including KiCad 9/10), +25 MCP tests, all 51 valid automatic corpus targets and six curated mode/board +cases. Two expected compile rejections and one empty design remain separate. +All 69 curated default-mode files were byte-identical to the legacy output. +The automatic corpus retained 28 rotations across ten valid targets (13 at 90°, +12 at 270° and three at 180°), using 5,765 routing calls for 1,941 eligible passives +against the 5,823-call bound. Curated PDU retained one 90° turn, saving 10.16 mm +of wire with one extra bend; curated Ballu and USB-C retained their baselines. +Serialized scene findings were unchanged. These checks establish selective safe +improvements, not drawing-only readability approval. + +Single cold first-export observations under eight concurrent workers were +135.4/239.6 seconds for Ballu, 333.2/638.5 for PDU and 578.4/1,047.1 for USB-C +(`half_turn` / `passive_quarter_turn`). These are loaded, single observations, +not controlled performance measurements. MCP's default 300-second timeout and +900-second maximum can both be exceeded. Use the native API or batch harness +for longer experiments and retain the default mode for interactive work when +its runtime fits better. + +A separate sequential USB-C benchmark reused one compiled design, warmed each +mode once, then measured three exports per mode in alternating AB/BA/AB order +on logical CPU 10. Default-mode median was 415.9436 seconds (range +372.6785–417.3414); quarter-turn median was 779.7176 seconds (range +700.8048–794.9586), or 1.8746 times the default median. All six exports passed +input/source/symbol/hash guards; curated USB-C retained the same 20 schematic +documents. Three observations per mode establish neither statistical significance +nor a general latency bound. CPU frequency, sibling activity and host load were +not reserved or controlled, and peak memory was not measured. + +Quarter turns remain opt-in. See the +[passive quarter-turn benchmark](schematic-passive-quarter-turn-benchmark.md) +for matched legacy/new views, verification scope and observed limitations. + +### Native functional layout and label geometry + +Automatic export now places recognized circuits as complete functional atoms: +feedback networks, converters, indicator branches, and owned local bypasses. +Overlapping support patterns share one atom. A bounded two-pass search evaluates +up to 32 position transforms per atom per pass, then compares up to three improving +finalists with the template using the actual router. New failed endpoints or increased crossings reject the +finalist. This default placement search is separate from `optimize_routes`. +Explicit source-owned component centers remain fixed. Rotation is locked unless +the placement explicitly sets `lock_rotation=False`. Disabling orientation +optimization also restores the earlier mixed position/angle proposal search. + +Complete repeated channels are established from compiled sibling class ownership +and private internal nets. Verified power-terminal roles and inductor mappings +identify power-circuit groups. Larger power circuits retain controller/stage +boundaries; smaller bypass patterns cannot join these boundaries back together. +Measured multirow templates place each whole channel before sheet packing. +FET source/drain geometry and inductor terminals establish stage orientation. +A route detour that would break A3 fit falls back to a fitting baseline route. +Pin escape conflicts include neighboring visible pin names and numbers, in +addition to cross-net contacts. Continuation titles for repeated groups name the +actual channel indices drawn on that sheet. + + +Continuation splitting preserves atoms and minimizes non-supply signal cuts. +The sheet planner considers signal neighbours and hierarchy before unrelated +free space. Large overviews use a grouped directory with page references and +component counts; names remain source-derived unless authored presentation +metadata supplies descriptions. Connectivity does not imply directed flow. + +The exporter chooses labels per connected graphical island. Distinct islands of +the same physical net retain labels; a routed bus does not need a label at every +pin. Final-sheet label placement tries horizontal text and short orthogonal +extensions without moving the original electrical anchor. Candidate paths must +avoid fields, pin names, symbols and other labels; unrelated nets may only be +crossed under the strict interior-crossing rules above. Missing or +ambiguous anchors retain their original representation and report diagnostics. +Text and global-label outlines use shared conservative geometry for routing, +region measurement and serialized-document inspection. Unresolved collisions +are reported rather than silently hidden. + +`layout.json` (schema 1), also available through +`KiCadSchematicExporter.layout(compiled, options)`, records recognized patterns, +component/atom membership, bounded search counts, routing finalist decisions, +label moves, unresolved anchors and label conflicts. Its `summary` provides +counts for MCP consumers. `readability.json` independently inspects the final +serialized documents. Neither artifact grants visual approval. Timing belongs +in external benchmark reports, not deterministic bundle contents. New measured +bounds may invalidate an old authored sheet plan; regenerate its plan rather +than discarding authored placements or shrinking its text. + +When a pin's label cannot be placed safely, the final-sheet search can try up to +eight vertices, sampling both near and far parts of that same existing wire island. A shared +net name does not establish a drawn connection: disconnected islands are never +interchanged. Original pins and wires stay fixed, and label tails pass through +the normal wire/junction serializer. Native regressions cover T-junction tails, +same-island reanchoring, and all four readable label orientations in KiCad 9/10. + +Bypass ownership first establishes the nearest physical-device boundary, including +a footprint block that directly owns its bypass. Devices with ambiguous supply +roles still establish that boundary; the exporter leaves the association +unclassified rather than handing an outer device's capacitors to nested memory +merely because its supply roles are easier to recognize. + + +### USB source/measure example + +The native KiCad 10 comparison used the same compiled USB source/measure design. The earlier layout separates the current-amplifier feedback diodes; +the new layout keeps U41, D8/D9 and its owned bypass together. Physical +connectivity is independently round-tripped in KiCad 9 and 10. The new automatic +layout remains a generated reference, with generic-symbol fallbacks and some +long routes; publication-quality spacing is not claimed. diff --git a/docs/schematic-orientation-benchmark.md b/docs/schematic-orientation-benchmark.md new file mode 100644 index 000000000..699308a48 --- /dev/null +++ b/docs/schematic-orientation-benchmark.md @@ -0,0 +1,109 @@ +# Orientation and converter layout evaluation + +PB Python remains authoritative for components, physical pins and connectivity. +These generated schematics are reference artifacts. Evaluation completed on +2026-11-08–09 using native KiCad 9.0.9 and 10.0.8. + +## USB-C converter comparison + +All three profiles use the same compiled 261-component design and source-owned +presentation intent. The controlled baseline preserves the new position-search +stage and suppresses orientation/bridge selection in the evaluation harness. +The rotation-only profile suppresses bridge proposals. Route-order optimization +stays enabled in all profiles. Native component identities, footprints, values, +modeled pin inventories and connected physical-pin sets match across profiles. These two harness profiles are diagnostic controls; +the public API exposes `optimize_orientations`, and explicit placements constrain +position-changing proposals. + +| Power-stage sheet | Local fallback endpoints | Crossings | Bends | Local wire (mm) | First export (s) | +| --- | ---: | ---: | ---: | ---: | ---: | +| Controlled baseline | 7 | 45 | 53 | 1939.3 | 182.8 | +| Fixed-center rotations | 6 | 34 | 59 | 1934.2 | 476.2 | +| Rotations + bridge | 0 | 26 | 60 | 1602.1 | 399.8 | + +The final bridge removes local route fallbacks, reduces crossings by 42%, and +reduces local wire length by 17% against the controlled baseline. Bends increase +from 53 to 60. Metrics cover local routed wires; fixed pin stubs, final label +repair tails and inter-region connections are excluded. Counts are physical +fallback endpoints, not disconnected electrical nets: labels preserve electrical +connectivity in every profile. + +The first-export timings are one observation per profile. Compilation, repeat +verification, native CLI and raster rendering are excluded. Parallel validation +load, OS cache and unrelated host activity were not controlled. No statistical +speedup claim is made, and peak memory was not measured. Orientation increases +export cost; large boards may require the MCP's explicit 900-second timeout +instead of its 300-second default. + +## Verification + +| Check | Result | +| --- | --- | +| Schematic unit/native suite | 203 tests pass, no skips | +| MCP suite, including complete direct Python/MCP bundle parity | 23 tests pass, no skips | +| Full automatic corpus | 54 targets: 51 valid pass, 2 expected compile rejections, 1 empty | +| Native fidelity | Every valid corpus scope passes KiCad 9 and 10 physical identity, footprint, modeled pin inventory and connected-pin-set comparisons | +| Determinism | Byte-identical repeated exports for every valid corpus design and final curated USB-C export | +| Fixed centers | All 261 physical component centers retain relative positions within their functional regions in the controlled rotation-only comparison; sheet packing may translate regions | +| Opt-out compatibility | Complete USB-C bundle: all 28 files byte-identical to the preceding exporter when `optimize_orientations=False` | +| MCP preparation cost | Exactly one native export per plan, generate or review action; stale plans still rejected before artifact writing | + +Across the 51 valid automatic exports, local routing counts compare with the +preceding native implementation as follows. These are machine measures, not +whole-corpus visual acceptance; grouping changes can affect their scope. + +| Metric | Decreased | Same | Increased | +| --- | ---: | ---: | ---: | +| Local fallback endpoints | 37 | 14 | 0 | +| Crossings | 34 | 2 | 15 | +| Bends | 33 | 3 | 15 | +| Local wire length | 26 | 2 | 23 | + +## Drawing-only findings + +Fresh reviewers inspected all eight Ballu sheets and all seventeen PDU sheets, +with dense-region crops. Both are qualified usable references. Ballu retains +convoluted white-LED branches and regulator wiring; PDU retains dense converter +feedback and long connector/MCU harnesses. + +The blind USB-C comparison selected the conventional bridge as clearest: two +vertical halfbridges, the inductor link, rail banks and series shunts are directly +recognizable. Review caught a real C66/driver-label overlap. The final bypass +placement uses the controller's measured external-label corridor, and the final +full-board power sheet was rechecked. That overlap is resolved. Gate/bootstrap +and I2C routing around L4 remains dense. Independent final USB-C review covers +the converter sheet, not all twenty pages; the complete page inventory was +contact-sheet scanned separately. Native equality does not approve aesthetics +or electrical design safety. + +## Search and evidence scope + +The fixed-center stage performs at most two stable PB-path sweeps, with one +baseline-router call per geometrically viable 180-degree trial and cached +incumbent routes. Four measured bridge alternatives add at most four calls. +Existing automatic placement and final route-order searches add separate costs. +This is a finite local search, not a global optimum. Explicit placements retain +rotation locks unless `lock_rotation=False`. + +Verified converter core endpoints (controller, FETs, inductor, series shunts and +bootstrap branches) determine primary-path fallbacks. Bulk/bypass-bank fallbacks +are recorded separately. Authored primary nets elsewhere keep their original +meaning. `orientation.after` and `selected_rotations` describe that stage; a +later bridge can change poses. Final symbol coordinates are in the schematic, +and region-level `routing.after` records the selected final local route. + +The broad corpus snapshot is `17e639c5da676449bdf5c4ba41cdd779c42285343875421a7442853835757447`. +The final snapshot is `be45bd1a3136463855b796e383bb3729af1f5dfb6b44c7d4ebdb2a0621790292`. +Only `KiCadSchematicPower.power_template_candidates` changed between them, to +move bypasses outside controller label corridors. Automatic corpus circuits use +`template="auto"`, and Ballu/PDU do not request a four-switch bridge, so that +changed function is outside those export paths. The final fix received the full +USB-C export/repeat/native 9+10 checks plus complete unit/MCP suites. The broad +corpus was not redundantly rerun after this isolated visual placement fix. + +Reproduction inputs, scripts, source ledgers, per-target results, native XML/SVG, +full PNGs, hash-bound reviews, change-impact analysis and aggregate `RESULTS.json` +are retained in the host PCB repository under +`.local-execution/orientation-readability-2026-11-08/`. Expected rejections and +superseded/rejected visual candidates are retained separately. No PCB edits, +normal board regeneration, commits or pushes were performed. diff --git a/docs/schematic-passive-quarter-corpus.md b/docs/schematic-passive-quarter-corpus.md new file mode 100644 index 000000000..efe824fbe --- /dev/null +++ b/docs/schematic-passive-quarter-corpus.md @@ -0,0 +1,68 @@ +# Passive quarter-turn corpus results + +Frozen implementation: `8f93b26079b6790fd2de88ab445148d4140cdb4a498a3ee7899f25a3df95af20`. + +All 54 targets completed: 51 valid designs passed, two intentionally invalid designs were rejected during compilation, and one design was empty. Each valid design and the empty design passed KiCad 9.0.9 and 10.0.8 physical-netlist comparisons and byte-identical repeat checks. Source and framework hashes remained stable. + +Deltas compare the cached incumbent after the legacy placement/half-turn/template/routing pipeline with the final selected passive result, including rollback. Wire, bend and cost deltas use local routed wires plus fixed pin stubs, excluding final label tails and inter-region links. Cost is wire millimeters + 2.54 per measured bend. The scene column counts all final readability findings, including fallback-symbol diagnostics. Export seconds are a single first successful export under eight-worker functional load; they are not controlled performance samples. + +Adopted turns are relative angle changes (90/180/270). The three 180-degree changes arise from the balanced objective; the 25 quarter turns exercise the new angular capability. The 28 changes occur across 10 targets. All 1,941 eligible passives receive three angle evaluations; 5,765 additional router calls stay within the 5,823-call limit. Geometry rejects the other trials before routing. + +| Target | Status | Eligible P | Calls / 3P | Adopted 90/180/270 | Δ fallback | Δ crossings | Δ bends | Δ wire mm | Δ cost mm | Scene | Export s | +| --- | --- | ---: | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `BalluGen3` | pass | 54 | 162 / 162 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 130 | 160.7 | +| `PduMain` | pass | 99 | 291 / 297 | 1/0/1 | +0 | +0 | -4 | -17.78 | -27.94 | 195 | 454.4 | +| `UsbcPdBidir` | pass | 183 | 540 / 549 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 414 | 959.3 | +| `BatteryProtectorCircuit` | pass | 3 | 9 / 9 | 1/0/1 | +0 | +0 | -1 | -33.02 | -35.56 | 5 | 24.6 | +| `BldcController` | pass | 38 | 114 / 114 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 97 | 114.8 | +| `BleJoystick` | pass | 36 | 108 / 108 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 146 | 92.4 | +| `TestBlinkyArray` | pass | 17 | 49 / 51 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 21 | 33.5 | +| `TestBlinkyBasic` | pass | 1 | 3 / 3 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 2 | 2.4 | +| `TestBlinkyEmpty` | empty (0 physical components) | — | — | — | — | — | — | — | — | — | — | +| `TestBlinkyImplicit` | pass | 21 | 61 / 63 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 61 | 92.3 | +| `TestBlinkyIncomplete` | expected compile rejection | — | — | — | — | — | — | — | — | — | — | +| `TestBlinkyInvalid` | expected compile rejection | — | — | — | — | — | — | — | — | — | — | +| `TestBlinkyPacked` | pass | 13 | 37 / 39 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 21 | 31.6 | +| `TestBlinkyPinned` | pass | 21 | 61 / 63 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 61 | 97.4 | +| `TestBlinkyRegulated` | pass | 14 | 40 / 42 | 1/1/1 | +0 | -2 | +2 | +15.88 | +20.95 | 47 | 64.3 | +| `TestBlinkyRgb` | pass | 21 | 61 / 63 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 62 | 100.0 | +| `TestBlinkySwitchMatrix` | pass | 1 | 3 / 3 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 22 | 27.1 | +| `TestBlinkySwitchMatrixRefined` | pass | 1 | 3 / 3 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 22 | 29.3 | +| `TestBlinkyWithLibrary` | pass | 18 | 52 / 54 | 3/0/1 | +0 | -2 | -6 | -52.70 | -67.95 | 27 | 38.4 | +| `TestBlinkyWithLibraryExport` | pass | 18 | 52 / 54 | 3/0/1 | +0 | -2 | -6 | -52.70 | -67.95 | 27 | 35.8 | +| `TestBlinkyWithModeledSchematicImport` | pass | 21 | 61 / 63 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 26 | 86.8 | +| `TestBlinkyWithSchematicImport` | pass | 21 | 61 / 63 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 26 | 86.9 | +| `TestLed` | pass | 1 | 3 / 3 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 1 | 1.2 | +| `CanAdapter` | pass | 18 | 54 / 54 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 29 | 29.4 | +| `Datalogger` | pass | 33 | 99 / 99 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 233 | 160.0 | +| `DeskController` | pass | 34 | 102 / 102 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 72 | 168.7 | +| `EspProgrammer` | pass | 11 | 33 / 33 | 1/1/1 | +0 | -3 | -5 | -54.61 | -67.31 | 28 | 20.4 | +| `Fcml` | pass | 107 | 317 / 321 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 288 | 364.1 | +| `HighSwitch` | pass | 25 | 75 / 75 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 147 | 128.1 | +| `IotCurtainCrawler` | pass | 26 | 78 / 78 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 41 | 64.0 | +| `IotRollerBlinds` | pass | 21 | 63 / 63 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 27 | 33.8 | +| `IotDisplay` | pass | 33 | 99 / 99 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 125 | 76.7 | +| `IotFan` | pass | 52 | 156 / 156 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 113 | 114.8 | +| `IotIron` | pass | 60 | 180 / 180 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 124 | 173.1 | +| `IotLedDriver` | pass | 58 | 166 / 174 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 65 | 155.6 | +| `IotThermalCamera` | pass | 82 | 242 / 246 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 185 | 207.1 | +| `JacdacKeyswitch` | pass | 11 | 33 / 33 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 35 | 53.6 | +| `Keyboard` | pass | 33 | 99 / 99 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 120 | 174.5 | +| `LedMatrix` | pass | 13 | 39 / 39 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 105 | 134.3 | +| `EspLora` | pass | 68 | 204 / 204 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 152 | 306.7 | +| `Multimeter` | pass | 61 | 182 / 183 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 178 | 168.4 | +| `PcbBot` | pass | 45 | 135 / 135 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 191 | 116.5 | +| `ProtectedCharger` | pass | 8 | 24 / 24 | 2/0/0 | +0 | -1 | -1 | +6.35 | +3.81 | 16 | 13.1 | +| `RobotCrawler` | pass | 64 | 190 / 192 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 208 | 276.5 | +| `RobotDriver` | pass | 40 | 120 / 120 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 123 | 98.6 | +| `SevenSegment` | pass | 87 | 261 / 261 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 179 | 427.1 | +| `Simon` | pass | 17 | 51 / 51 | 1/0/3 | +0 | +0 | -3 | -66.04 | -73.66 | 59 | 38.4 | +| `PicoProbe` | pass | 26 | 78 / 78 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 75 | 208.2 | +| `SwdDebugger` | pass | 25 | 73 / 75 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 69 | 72.6 | +| `TofArray` | pass | 34 | 102 / 102 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 119 | 103.7 | +| `UsbFpgaProgrammer` | pass | 21 | 63 / 63 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 56 | 109.8 | +| `UsbKey` | pass | 9 | 27 / 27 | 0/0/2 | +0 | +0 | +2 | -40.64 | -35.56 | 4 | 16.5 | +| `UsbSourceMeasure` | pass | 209 | 625 / 627 | 0/0/0 | +0 | +0 | +0 | 0.00 | 0.00 | 488 | 469.9 | +| `UsbUart` | pass | 8 | 24 / 24 | 0/1/1 | +0 | -1 | -3 | -36.83 | -44.45 | 17 | 17.0 | + +These are machine acceptance results. Drawing-only review covered the named curated sheets in the [main report](schematic-passive-quarter-turn-benchmark.md); this table does not assert whole-corpus visual approval. diff --git a/docs/schematic-passive-quarter-turn-benchmark.md b/docs/schematic-passive-quarter-turn-benchmark.md new file mode 100644 index 000000000..b54346d5f --- /dev/null +++ b/docs/schematic-passive-quarter-turn-benchmark.md @@ -0,0 +1,246 @@ +# Passive quarter-turn evaluation + +The opt-in `orientation_mode="passive_quarter_turn"` adds one fixed-center +passive sweep after the established placement, half-turn, converter-template and +routing pipeline. The default remains `half_turn`. PB Python remains authoritative +for component identities, values, footprints, physical pins and connectivity. +Generated schematics remain reference artifacts. + +Evaluation uses KiCad 9.0.9 and 10.0.8. The frozen implementation digest is +`8f93b26079b6790fd2de88ab445148d4140cdb4a498a3ee7899f25a3df95af20`. +The evaluation harness, source ledgers, native logs, full generated bundles and +controlled timing protocol are retained in the host's ignored +`.local-execution/passive-quarter-turn-2026-11-10/` directory. An earlier, +incomplete cohort was superseded before acceptance when independent review +identified a conflict-count safety gap. A second cohort was superseded to enforce +strict weighted-cost tie retention; secondary bend counts cannot replace an +equal-cost incumbent. + +## Selection and safety + +Only verified `Device:R`, `Device:R_US`, `Device:C`, `Device:C_Polarized` and +`Device:L` mappings with two distinct terminal attachment positions qualify. +Parallel physical pads remain separate identities. Explicit rotation locks and +authored field coordinates are preserved. Automatic fields are recomputed from +their original policy. No component movement, mirroring or pin swapping occurs +in the new pass; later sheet packing can translate a complete region. + +Every eligible passive receives all three alternative-angle evaluations against +the same incumbent, in stable PB-path order. Geometry can reject an angle before +routing. Thus `P` eligible passives add at most `3P` router calls, separately from +the earlier pipeline and one additional bounded route-order search per changed +region. The incumbent's selected routing strategy is reused. + +Primary-path fallbacks, crossings and unrelated-circuit intrusion precede +`wire length + 2.54 mm per bend`. New failed endpoints, escape-conflict identities, +wire-clearance contact identities, collisions and page overflow reject a trial. +The identity checks also guard the final route-order result; equal conflict +counts cannot conceal a replacement conflict. Collinear wire splitting does +not change contact identity. + +The fully serialized candidate is compared with the cached baseline, including +fields, labels, pin text and ground symbols. New or worsened blocking contacts +roll back all adopted passive changes in that independent board scope. Existing +bad labels cannot whitelist contact with a different obstacle or a larger +overlap. Rollback restores cached poses and routes without another optimization +loop. Final geometry determines bounds and fingerprints before an adopted sheet +plan is validated. Per-region `routing.json` records trials and rollback evidence. + +## Verified-library fixture + +This small compiled fixture uses KiCad's actual `Device:C_Polarized` definition +and a generic physical anchor. A 270-degree turn makes the positive-terminal +connection shorter while preserving polarity and the relative component centers. +Both modes pass native KiCad 9/10 physical-netlist comparisons. The only +readability diagnostics in either mode are the two intentionally generic anchors. + +| Optimizer metric, local wires plus fixed pin stubs | Half-turn | Quarter-turn | +| --- | ---: | ---: | +| Wire length (mm) | 66.50 | 48.87 | +| Bends | 4 | 4 | +| Weighted cost (mm) | 76.66 | 59.03 | +| Crossings / failed endpoints / visual-clearance conflicts | 0 / 0 / 0 | 0 / 0 / 0 | + +The optimizer's segment-based bend measure can differ from a viewer's count of +visible corners. The shorter retained path reduces this fixture's measured wire +length by 26.5% and weighted cost by 23.0%; it does not establish whole-board gains. + +## Focused verification + +| Check | Result | +| --- | --- | +| Complete schematic suite | 228 tests pass, no skips; native KiCad 9/10 enabled | +| MCP suite | 25 tests pass, no skips; complete Python/MCP bundle parity | +| Legacy golden bundle | All nine files byte-identical to the preceding exporter with default options | +| Curated default compatibility | All 69 bundle files byte-identical to the preceding exporter: Ballu 16, PDU 25, USB-C 28; source ledgers match | +| Real-routing coverage | 90/270-degree resistor, capacitor, polarized capacitor and inductor fixtures; parallel pads retained | +| Search safety | Complete three-angle coverage, stable ordering, 3P bound, locks, fixed fields, ties, collisions and clearance replacement regressions | +| Integration safety | Post-template ordering, cached-baseline rollback, final-route-order guard, final plan fingerprint, serialized label/body and wire-contact severity | + +The C66 driver-supply label-corridor regression remains in the complete suite. +`optimize_orientations=False` bypasses both orientation passes and preserves +legacy output. Tests and native equivalence do not imply whole-sheet visual +acceptance or electrical-design approval. + + +## Full corpus + +| Outcome | Targets | Native KiCad 9/10 and repeat checks | +| --- | ---: | --- | +| Valid compiled designs | 51 | All pass | +| Expected compile rejections | 2 | `TestBlinkyIncomplete`, `TestBlinkyInvalid`; no schematic generated | +| Empty design | 1 | Zero physical components; recorded separately and native-checked | +| Curated mode comparisons | 6 | Ballu, PDU and USB-C in both modes; all pass | + +All source ledgers and frozen implementation hashes remain unchanged during +these runs. Every eligible passive receives complete three-angle coverage. +Across the automatic corpus, 1,941 eligible instances produce 5,765 router calls +within the 5,823-call bound. Ten valid targets retain 28 changes: 13 turns of 90 +degrees, 12 of 270 degrees, and three of 180 degrees. The latter arise from the +balanced objective rather than an additional angular capability. + +The [complete per-target table](schematic-passive-quarter-corpus.md) includes +fallbacks, crossings, bends, wire length, weighted cost, scene findings and +first-export time. Its route-plus-stub metrics differ from serialized wire totals. +These are machine acceptance results; whole-corpus visual approval is not claimed. + +The opt-in example was executed successfully with +`python -m examples.export_schematic --output --symbol-dir --orientation-mode passive_quarter_turn`. + +## Curated boards + +Both modes pass byte-identical repeated exports and KiCad 9/10 physical identity, +footprint, modeled-pin inventory and connected-pin-set comparisons in every +scope. Ballu contains 105 components on eight sheets. PDU contains 166 components +across its main, driver-daughter and e-stop-panel scopes on 17 sheets. USB-C +contains 261 components across main and control scopes on 20 sheets. + +These totals cover local routed wires across each complete design. Fixed pin +stubs, final label-repair tails and inter-region links are excluded here. The +optimizer uses the wider wire-plus-stub measure shown in the fixture table. +Fallback endpoints remain electrically connected through labels. The scene +column counts all readability findings, including symbol-fallback diagnostics; +it is not a count of newly introduced blocking collisions. + +| Board / mode | Fallback endpoints | Crossings | Bends | Local wire (mm) | Weighted cost (mm) | Readability findings | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Ballu / half-turn | 11 | 57 | 173 | 7804.2 | 8243.6 | 117 | +| Ballu / quarter-turn | 11 | 57 | 173 | 7804.2 | 8243.6 | 117 | +| PDU / half-turn | 16 | 218 | 398 | 16873.2 | 17884.1 | 175 | +| PDU / quarter-turn | 16 | 218 | 399 | 16863.1 | 17876.5 | 175 | +| USB-C / half-turn | 33 | 245 | 508 | 19749.1 | 21039.5 | 361 | +| USB-C / quarter-turn | 33 | 245 | 508 | 19749.1 | 21039.5 | 361 | + +| Board | Eligible passives | Angle evaluations | Additional router calls / 3P limit | Locally proposed turns | Finally adopted turns | Regions rolled back | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Ballu | 54 | 162 | 156 / 162 | 15 | 0 | 9 | +| PDU | 99 | 297 | 287 / 297 | 30 | 1 | 9 | +| USB-C | 183 | 549 | 506 / 549 | 43 | 0 | 9 | + +All three boards receive complete trial coverage. Geometry rejects some angles +before routing. New blocking serialized-scene findings cause the reported +scope-wide rollbacks. All eight Ballu schematic documents and all twenty USB-C +documents are byte-identical between modes after rollback. Their routing +evidence still records the attempted opportunities. The retained PDU change is +`estop_panel.estop.indicator.res`, R40, from 0 to 90 degrees; it saves 10.16 mm of +wire with one additional measured bend, reducing weighted cost by 7.62 mm. + +| First export under parallel functional load (not controlled timing) | Half-turn (s) | Quarter-turn (s) | +| --- | ---: | ---: | +| Ballu | 135.4 | 239.6 | +| PDU | 333.2 | 638.5 | +| USB-C | 578.4 | 1047.1 | + +These are single first-export observations. Compilation, repeat verification, +native CLI and raster rendering are excluded. Parallel test load and host +conditions prevent treating these observations as controlled performance ratios. +The final functional cohort used eight isolated workers, with long historical +cases scheduled first. The controlled timing run is separate. + +## Drawing-only review + +A fresh reviewer inspected the PDU e-stop detail from drawings alone. The +horizontal R40 makes its D9 LED branch read more directly left to right, with no +visible regression or label/body/wire overlap. The sheet still has generic +connector pin names, long crossing wire runs, small whole-sheet text and a short +stepped LED-to-resistor connection. The reviewed PNGs match the final validated +native render hashes. The other 16 PDU documents differ only in the design +fingerprint in title-block comment 2; their parsed S-expressions otherwise match. + +A different fresh reviewer inspected the actual USB-C converter sheet 4/10. +Both modes produce identical pixels, SHA256 +`732941d7d122b18d837b5e8e6680176fd6b7aa78226ed47237d34c6524e3a685`. +No definite controller/C66 body-field collision or clipping was seen. The dense +central wire corridor, crowded controller-side ground markings, long C66 +driver-supply detour and remote C67/C68/L4 fields remain. The earlier C66 overlap +stays resolved, while fixed-center optimization provides no retained improvement +on this sheet. The initially supplied overview-only render was rejected by the +reviewer and replaced with the title-verified converter render before acceptance. + +Ballu has no changed schematic pages to review; its complete eight-document +identity was checked and the regenerated contact sheet inspected. These reviews +cover the named drawings only, with electrical fidelity checked separately. + +## Remaining readability flags + +The pass is a nonregression optimizer and preserves existing baseline findings. +The following unchanged flags require visual triage; the drawing-only reviews +above do not establish that all sheets are clear of existing contacts. + +| Final curated design, either mode | Text-collision flags | Wire-through-text flags | Label-placement conflicts | Unresolved anchors | +| --- | ---: | ---: | ---: | ---: | +| Ballu | 29 | 68 | 1 | 0 | +| PDU | 27 | 88 | 2 | 0 | +| USB-C | 68 | 232 | 13 | 0 | + +These detector findings are not electrical mismatches. They also are not all +symbol-fallback warnings: substantial baseline presentation work remains. The +new pass rejects new or worsened blocking contacts and does not repair the +baseline scene. A scope-level rollback can discard otherwise useful local +rotations elsewhere in that scope. Keep the feature opt-in. + +## Controlled USB-C timing + +Controlled USB-C timing used one compiled design instance, one warm-up per mode, then three sequential exports per mode in AB / BA / AB order. Both option files differ only in `orientation_mode`. The process was pinned to logical CPU 10 on the Intel Core i9-14900K; sibling CPU 11, CPU frequency, thermal state and other host activity were not reserved or fixed. Functional workers had finished before measurement. Each export had a 900-second limit. + +| Mode | Three measured exports (s) | Median (s) | Min–max (s) | +|---|---|---:|---| +| `half_turn` | 372.68, 417.34, 415.94 | 415.94 | 372.68–417.34 | +| `passive_quarter_turn` | 700.80, 779.72, 794.96 | 779.72 | 700.80–794.96 | + +The median quarter-turn export took 1.875× the half-turn median (87.5% longer). For this USB-C input, both modes produced byte-identical schematic files and equal final local-route metrics: 245 crossings, 508 bends, 19,749.135 mm wire length and 21,039.455 mm weighted cost. The serialized wire length was25,257.76 mm across 1,769 segments; 13 label-placement conflicts remained, with zero unresolved anchors. Those metric scopes differ: local-route totals omit fixed pin stubs, final label tails and inter-region links. No quarter-turn change survived the serialized-scene safety gate on this board. + +Timing includes only `KiCadSchematicExporter.export()`. Compilation, reference assignment, presentation-plan refresh, KiCad CLI/netlist verification, rendering, bundle hashing/metrics and garbage collection between exports are excluded. Warm-up files are audit artifacts, not additional measured observations. Three observations per mode support descriptive median/min/max reporting only; no statistical significance, controlled-frequency performance or peak-memory claim is made. + +Independent post-run audit passed all six sample statuses, planned order, summary statistics, warm-up/sample bundle hashes, saved warm bundles, same-input fingerprint, source hashes (69 files), symbol-library hashes (448 files), runner hash, frozen implementation hash and protocol hash. Framework: `8f93b26079b6790fd2de88ab445148d4140cdb4a498a3ee7899f25a3df95af20`. Compiled input: `baacea3f413ce899b340b821691118d9778a3dad4473ebd6a93c3b6f60face07`. Runtime assertions also checked the compiled payload and source hashes before each sample and after the last sample; the summary is written only after all final guards pass. + +Evidence: `benchmark/protocol.json`, `benchmark/samples.json`, `benchmark/summary.json`, `benchmark/compiled-input.json`, and `controlled-timing-audit.json`. + + +## Final geometry and rollout + +The post-timing artifact audit checks all 532 curated physical symbol instances: +Ballu 105, PDU 166 and USB-C 261. Reference/value/footprint/PB-path properties, +instance UUIDs and physical-pin UUID inventories remain unchanged between modes. +All region translations are zero in these exports, so absolute and relative +component centers remain fixed. Only the PDU indicator resistor changes angle, +from 0 to 90 degrees. Rotation locks remain respected. + +Keep `passive_quarter_turn` opt-in. It finds genuine quarter-turn improvements in +some automatic targets and the PDU branch, but the curated USB-C export takes +about 1.87 times the default median runtime while retaining identical drawings. +A reviewed explicit Python rotation hint can preserve a known presentation choice +without repeatedly searching unrelated passives. This change does not write hints +back into Python or edit generated schematics by hand. + +The MCP default timeout is 300 seconds and its maximum is 900 seconds. The +controlled quarter-turn observations fit inside 900 seconds, while the separate +1,047.1-second parallel cold observation exceeds that limit. These observations +provide no general deadline guarantee; use native Python for longer batch +experiments. Generation itself needs no KiCad process or GUI; native KiCad was +used for the acceptance checks and rendered views. + +Code, tests, example, API documentation, MCP guide, companion skill and rendered +comparisons are supplied in the existing development worktrees. Experimental ELK +work and project PCB/manufacturing outputs are preserved. No commits or pushes +are part of this delivery. diff --git a/docs/schematic-symbol-converter-corpus.md b/docs/schematic-symbol-converter-corpus.md new file mode 100644 index 000000000..9a23191db --- /dev/null +++ b/docs/schematic-symbol-converter-corpus.md @@ -0,0 +1,71 @@ +# Default schematic corpus + +Implementation: `8a3c23d8e0fdaeb8d62dc3793d157eda1ded1f37dd439f1f0a3e5a2e02d941bc`. Completed 54/54. + +| Target | Status | Parts / sheets | KiCad 9 / 10 | Repeat | Fallback endpoints | Symbol fallbacks | Crossings | Bends | Local wire mm | Weighted mm | Export s | +|---|---|---:|---|---|---:|---:|---:|---:|---:|---:|---:| +| `examples.test_battery_protector:BatteryProtectorCircuit` | pass | 9 / 3 | pass / pass | True | 1 | 3 | 5 | 20 | 1140.46 | 1191.26 | 9.89 | +| `examples.test_bldc_controller:BldcController` | pass | 74 / 5 | pass / pass | True | 5 | 7 | 20 | 108 | 4258.31 | 4532.63 | 49.75 | +| `examples.test_ble_joystick:BleJoystick` | pass | 97 / 10 | pass / pass | True | 2 | 24 | 26 | 88 | 5373.37 | 5596.89 | 39.98 | +| `examples.test_blinky:TestLed` | pass | 2 / 1 | pass / pass | True | 0 | 0 | 0 | 0 | 2.54 | 2.54 | 0.87 | +| `examples.test_blinky:TestBlinkyEmpty` | empty design | 0 / 1 | pass / pass | True | 0 | 0 | 0 | 0 | 0.00 | 0.00 | 0.05 | +| `examples.test_blinky:TestBlinkyBasic` | pass | 3 / 1 | pass / pass | True | 0 | 1 | 0 | 1 | 109.86 | 112.40 | 1.37 | +| `examples.test_blinky:TestBlinkySwitchMatrix` | pass | 15 / 3 | pass / pass | True | 2 | 1 | 8 | 24 | 1360.17 | 1421.13 | 21.87 | +| `examples.test_blinky:TestBlinkySwitchMatrixRefined` | pass | 15 / 3 | pass / pass | True | 2 | 1 | 8 | 24 | 1360.17 | 1421.13 | 22.42 | +| `examples.test_blinky:TestBlinkyRegulated` | pass | 33 / 4 | pass / pass | True | 2 | 5 | 28 | 65 | 3225.16 | 3390.26 | 41.81 | +| `examples.test_blinky:TestBlinkyRgb` | pass | 47 / 4 | pass / pass | True | 2 | 12 | 24 | 74 | 4032.25 | 4220.21 | 42.84 | +| `examples.test_blinky:TestBlinkyImplicit` | pass | 47 / 4 | pass / pass | True | 2 | 12 | 24 | 74 | 4032.25 | 4220.21 | 42.11 | +| `examples.test_blinky:TestBlinkyPinned` | pass | 47 / 4 | pass / pass | True | 2 | 12 | 24 | 74 | 4032.25 | 4220.21 | 43.20 | +| `examples.test_blinky:TestBlinkyWithLibrary` | pass | 29 / 3 | pass / pass | True | 0 | 3 | 10 | 43 | 1911.99 | 2021.21 | 16.83 | +| `examples.test_blinky:TestBlinkyWithLibraryExport` | pass | 29 / 3 | pass / pass | True | 0 | 3 | 10 | 43 | 1911.99 | 2021.21 | 16.43 | +| `examples.test_blinky:TestBlinkyArray` | pass | 27 / 3 | pass / pass | True | 0 | 2 | 7 | 44 | 1880.87 | 1992.63 | 16.80 | +| `examples.test_blinky:TestBlinkyPacked` | pass | 24 / 3 | pass / pass | True | 0 | 2 | 7 | 44 | 1870.71 | 1982.47 | 16.25 | +| `examples.test_blinky:TestBlinkyWithSchematicImport` | pass | 29 / 4 | pass / pass | True | 3 | 2 | 21 | 60 | 3176.27 | 3328.67 | 39.10 | +| `examples.test_blinky:TestBlinkyWithModeledSchematicImport` | pass | 29 / 4 | pass / pass | True | 3 | 2 | 21 | 60 | 3176.27 | 3328.67 | 41.36 | +| `examples.test_blinky:TestBlinkyIncomplete` | expected compile rejection | — | — | — | — | — | — | — | — | — | — | +| `examples.test_blinky:TestBlinkyInvalid` | expected compile rejection | — | — | — | — | — | — | — | — | — | — | +| `examples.test_can_adapter:CanAdapter` | pass | 31 / 3 | pass / pass | True | 0 | 4 | 3 | 28 | 1598.29 | 1669.41 | 11.80 | +| `examples.test_datalogger:Datalogger` | pass | 108 / 8 | pass / pass | True | 3 | 25 | 25 | 142 | 8195.94 | 8556.62 | 84.03 | +| `examples.test_deskcontroller:DeskController` | pass | 74 / 6 | pass / pass | True | 6 | 12 | 24 | 96 | 6003.29 | 6247.13 | 77.48 | +| `examples.test_esp_programmer:EspProgrammer` | pass | 24 / 3 | pass / pass | True | 0 | 5 | 5 | 35 | 1337.95 | 1426.85 | 10.60 | +| `examples.test_fcml:Fcml` | pass | 177 / 12 | pass / pass | True | 11 | 29 | 110 | 271 | 12218.03 | 12906.37 | 152.99 | +| `examples.test_high_switch:HighSwitch` | pass | 89 / 10 | pass / pass | True | 2 | 30 | 28 | 145 | 7497.44 | 7865.74 | 65.16 | +| `examples.test_iot_blinds:IotRollerBlinds` | pass | 39 / 3 | pass / pass | True | 0 | 4 | 20 | 54 | 2348.86 | 2486.02 | 16.15 | +| `examples.test_iot_blinds:IotCurtainCrawler` | pass | 50 / 3 | pass / pass | True | 0 | 7 | 20 | 69 | 3275.96 | 3451.22 | 24.88 | +| `examples.test_iot_display:IotDisplay` | pass | 75 / 5 | pass / pass | True | 2 | 8 | 12 | 60 | 3339.47 | 3491.87 | 36.60 | +| `examples.test_iot_fan:IotFan` | pass | 94 / 8 | pass / pass | True | 3 | 20 | 28 | 91 | 5035.55 | 5266.69 | 44.95 | +| `examples.test_iot_iron:IotIron` | pass | 94 / 6 | pass / pass | True | 9 | 14 | 23 | 128 | 6127.11 | 6452.23 | 74.68 | +| `examples.test_iot_led_driver:IotLedDriver` | pass | 78 / 5 | pass / pass | True | 1 | 9 | 39 | 88 | 4351.02 | 4574.54 | 75.58 | +| `examples.test_iot_thermal_camera:IotThermalCamera` | pass | 119 / 8 | pass / pass | True | 3 | 20 | 36 | 174 | 8555.35 | 8997.31 | 71.89 | +| `examples.test_jd_keyswitch:JacdacKeyswitch` | pass | 37 / 3 | pass / pass | True | 0 | 16 | 8 | 45 | 2266.31 | 2380.61 | 29.98 | +| `examples.test_keyboard:Keyboard` | pass | 80 / 7 | pass / pass | True | 10 | 19 | 24 | 95 | 6205.86 | 6447.16 | 88.04 | +| `examples.test_ledmatrix:LedMatrix` | pass | 56 / 5 | pass / pass | True | 0 | 5 | 14 | 54 | 3690.62 | 3827.78 | 102.09 | +| `examples.test_lora:EspLora` | pass | 105 / 7 | pass / pass | True | 14 | 13 | 13 | 128 | 6196.33 | 6521.45 | 132.68 | +| `examples.test_multimeter:Multimeter` | pass | 107 / 7 | pass / pass | True | 7 | 28 | 18 | 121 | 6920.86 | 7228.20 | 71.54 | +| `examples.test_pcbbot:PcbBot` | pass | 108 / 8 | pass / pass | True | 7 | 29 | 19 | 128 | 7134.86 | 7459.98 | 61.66 | +| `examples.test_protected_charger:ProtectedCharger` | pass | 21 / 2 | pass / pass | True | 0 | 1 | 2 | 18 | 532.13 | 577.85 | 6.40 | +| `examples.test_robotcrawler:RobotCrawler` | pass | 122 / 8 | pass / pass | True | 14 | 21 | 63 | 133 | 7814.94 | 8152.76 | 117.38 | +| `examples.test_robotdriver:RobotDriver` | pass | 83 / 7 | pass / pass | True | 1 | 20 | 31 | 126 | 6395.08 | 6715.12 | 44.28 | +| `examples.test_seven_segment:SevenSegment` | pass | 174 / 13 | pass / pass | True | 9 | 66 | 59 | 116 | 12713.33 | 13007.97 | 144.27 | +| `examples.test_simon:Simon` | pass | 41 / 5 | pass / pass | True | 0 | 12 | 8 | 73 | 3185.80 | 3371.22 | 19.74 | +| `examples.test_swd_debugger:SwdDebugger` | pass | 41 / 4 | pass / pass | True | 2 | 7 | 12 | 56 | 2453.01 | 2595.24 | 29.72 | +| `examples.test_swd_debugger:PicoProbe` | pass | 42 / 3 | pass / pass | True | 14 | 6 | 36 | 63 | 3226.43 | 3386.45 | 82.91 | +| `examples.test_tofarray:TofArray` | pass | 72 / 5 | pass / pass | True | 3 | 23 | 15 | 93 | 4364.99 | 4601.21 | 42.76 | +| `examples.test_usb_fpga_programmer:UsbFpgaProgrammer` | pass | 37 / 3 | pass / pass | True | 5 | 5 | 17 | 60 | 2328.54 | 2480.94 | 43.86 | +| `examples.test_usb_key:UsbKey` | pass | 17 / 2 | pass / pass | True | 0 | 4 | 3 | 14 | 720.72 | 756.28 | 6.74 | +| `examples.test_usb_source_measure:UsbSourceMeasure` | pass | 320 / 18 | pass / pass | True | 8 | 62 | 61 | 363 | 19078.58 | 20000.60 | 212.00 | +| `examples.test_usb_uart:UsbUart` | pass | 18 / 2 | pass / pass | True | 0 | 3 | 3 | 22 | 789.31 | 845.19 | 8.18 | +| `boards.ballu.ballu_gen3.ballu_gen3:BalluGen3` | pass | 105 / 8 | pass / pass | True | 6 | 9 | 25 | 124 | 6763.39 | 7078.35 | 75.92 | +| `boards.pdu.pdu_main:PduMain` | pass | 166 / 14 | pass / pass | True | 10 | 44 | 127 | 279 | 11986.89 | 12695.55 | 177.80 | +| `boards.usbc_pd_bidir.usbc_pd_bidir:UsbcPdBidir` | pass | 261 / 17 | pass / pass | True | 25 | 28 | 144 | 366 | 18053.69 | 18983.33 | 390.46 | + +Local selected-route metrics exclude fixed pin stubs, final tails and inter-region wiring. Weighted cost = wire length + 2.54 mm per bend. Export times came from parallel functional workers and are not controlled performance measurements. Native pass and deterministic output do not establish visual approval. + +Expected compile rejections remain separate from exporter failures: + +- `TestBlinkyIncomplete`: missing refinements/model parameters and resulting unevaluated assertions. +- `TestBlinkyInvalid`: failed voltage-limit assertions. + +The empty design is also separate from the 51 nonempty designs. All 52 successful exports, including the empty design, passed both native versions and deterministic repeats. No unexpected failures occurred. + +Export times above were collected under parallel functional load; use the [controlled comparison report](schematic-symbol-converter-gaps.md) for runtime conclusions. Native equality does not imply visual acceptance. diff --git a/docs/schematic-symbol-converter-gaps.md b/docs/schematic-symbol-converter-gaps.md new file mode 100644 index 000000000..481243f2c --- /dev/null +++ b/docs/schematic-symbol-converter-gaps.md @@ -0,0 +1,218 @@ +# Capacitor coverage and compact LED-driver layouts + +This change fixes ordinary capacitor symbol fallbacks and gives verified +TPS92200 buck LED drivers a bounded functional layout in the native exporter. +Python remains authoritative. No electrical redesign, PCB edits, manufacturing +output adoption, commits or pushes are part of this evaluation. + +## Implementation and limits + +Fresh Datalogger compilation identified its ordinary capacitor leaves as +`edg.vendor_parts.generic.GenericCapacitor.GenericMlcc`, with physical +1=pos and 2=neg. The registry now resolves the exact model's six supported +ceramic packages to `Device:C`. Model identity, footprint and pin roles must +all match. Polarized/custom capacitors do not acquire guessed mappings. +Explicit mappings retain precedence and invalid explicit mappings remain errors. + +The manifest's additive `symbol_coverage` inventory records every component's +compiled class, mapping origin, selected symbol or categorized fallback reason. +Library absence is distinct from missing mappings. Resolved symbols also enter +the existing ownership and passive-orientation logic. + +The verified TPS92200 model supplies the BOOT/SW and FB/sense roles. A unique +compiled bootstrap capacitor, current-sense resistor and output inductor are +required. Virtual loads remain virtual; no pads or connectors are invented. +Four measured placement proposals compare against the cached legacy result, +using its selected routing strategy. The bootstrap sits beside BOOT/SW; the +sense resistor has its own feedback corridor; rail banks pack by measured field +edges rather than capacitor centers. + +Primary-path visibility, crossings and unrelated-circuit intrusion precede +wire length plus 2.54 mm per bend. Ties preserve the incumbent. Failed endpoints, +new pin escape conflicts, collisions, page overflow and degraded wire clearance +reject proposals. A final serialized-scene check includes pin text, labels, +fields and ground glyphs. New or worse findings or more sheets restore the +cached region. Fitting proposals retain the incumbent packing-cell dimensions +as explicit whitespace to avoid disturbing unrelated circuits; both content +and reserved bounds are recorded. This reservation also avoids claiming that +shorter local wiring necessarily makes the whole board smaller. + +The pass is automatic, skips authored placements, and precedes optional passive +quarter turns. The quarter-turn default is unchanged. Authored field coordinates +are preserved. Search evidence is under `routing.json`'s `regions[].led_buck`; +top-level `after` metrics describe the actually selected route. + +MCP exposes this same native evidence and compares manifest/routing artifacts +with its one fresh export per action. It adds no layout algorithm or public +option. Whole-bundle bytes intentionally change because of the additive manifest +inventory; deterministic repeated exports remain required. + +## Reproducibility + +The final frozen non-test PB implementation digest is +`8a3c23d8e0fdaeb8d62dc3793d157eda1ded1f37dd439f1f0a3e5a2e02d941bc`. +The baseline is the prior frozen implementation +`8f93b26079b6790fd2de88ab445148d4140cdb4a498a3ee7899f25a3df95af20`. +Matched comparisons use the default `half_turn` mode; the previous quarter-turn +corpus is not substituted for a default-mode baseline. + +Host evidence is isolated under +`.local-execution/schematic-gaps-2026-11-11-final/`; exploratory runs and rejected +larger layouts remain under `.local-execution/schematic-gaps-2026-11-11/`. +Sources, implementation files, artifacts and native render inventories are +hash-bound. KiCad 9.0.9 and 10.0.8 use the installed container wrappers. + +The public examples can also be reproduced without MCP or the host harness. +With PB's normal compiler dependencies and `KICAD9_SYMBOL_DIR` configured: + +```python +from pathlib import Path +from edg import ScalaCompiler, KiCadSchematicExporter, SchematicExportOptions +from edg.electronics_model.RefdesRefinementPass import RefdesRefinementPass +from examples.test_iot_led_driver import IotLedDriver + +compiled = ScalaCompiler.compile(IotLedDriver) +compiled.append_values(RefdesRefinementPass().run(compiled)) +bundle = KiCadSchematicExporter().export(compiled, SchematicExportOptions( + "IotLedDriver", source="examples.test_iot_led_driver.IotLedDriver")) +bundle.write(Path("output/IotLedDriver.schematic")) +``` + +Use `Datalogger` from `examples.test_datalogger` for the capacitor case. The +focused regressions are `edg.electronics_model.test_kicad_symbol_registry` and +`edg.electronics_model.test_schematic_led_buck`. The manifest identifies each +root for native KiCad netlist/SVG export and physical-pin comparison as described +in [schematic export verification](schematic-export.md#integrations-and-verification). + +## Validation results + +- 261 schematic tests passed, with zero skips, including configured native + KiCad 9/10 fixtures, symbol mappings, ambiguous topologies, parallel pads, + authored annotations/placements, ties, failed endpoints, scene rollback, + sheet-count rollback and final metric/strategy evidence. +- 27 configured MCP tests passed with zero skips; a real candidate also passed + KiCad 9.0.9/10.0.8 connectivity comparisons and native SVG export. Twelve + package resource/dependency contracts passed. Review preserves one fresh + native export per action and rejects changed evidence artifacts. +- Both focused designs passed native component identity, footprint, modeled + pin-inventory and connected-pin-partition comparisons on KiCad 9 and 10. + Repeated exports were byte-identical and captured sources stayed unchanged. + +| Default automatic export | Symbols falling back | Sheets | Failed endpoints | Crossings | Bends | Local wire mm | Weighted mm | Scene findings | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| Datalogger before | 67 | 10 | 9 | 24 | 142 | 8036.560 | 8397.240 | 233 | +| Datalogger after | 25 | 8 | 3 | 25 | 142 | 8195.945 | 8556.625 | 195 | +| IotLedDriver before | 9 | 5 | 1 | 47 | 104 | 5341.620 | 5605.780 | 65 | +| IotLedDriver after | 9 | 5 | 1 | 39 | 88 | 4351.020 | 4574.540 | 61 | + +These whole-design measurements cover selected local router wires, excluding +fixed pin stubs, final label tails and inter-region links. Weighted cost is +wire length plus 2.54 mm per bend. Remaining scene findings are reported, not +waived. Failed local-wire endpoints retain labeled electrical connections; they +are not missing physical pins or native netlist mismatches. Datalogger resolves +42 ordinary capacitor boxes and recovers six local +endpoints, but has one more crossing and 159.385 mm more local wire. Symbol +correction is not a claim that every whole-design route metric improves. + +All four IotLedDriver channels adopt compact layouts. Each uses four proposal +route calls, reduces local crossings 2→0, bends 10→6, wire 397.51→149.86 mm and +weighted cost 422.91→165.10 mm, with zero failed endpoints. This is a 62.3% +wire-length and 61.0% weighted-cost reduction per channel. The entire design +retains five sheets and reduces weighted local cost by 18.4%. All four final +serialized-scene gates record no new or worse findings. + +The [complete 54-target default corpus](schematic-symbol-converter-corpus.md) +has 51 nonempty native/repeat passes, one separately reported empty-design pass +and two expected compile rejections. `TestBlinkyIncomplete` lacks required +refinements/model parameters; `TestBlinkyInvalid` violates voltage assertions. +Neither rejection reaches the exporter. No unexpected exporter, electrical, +determinism or provenance failure occurred. + +| Curated design / mode | Parts / sheets | KiCad 9 / 10 | Byte-identical repeat | Unchanged prior schematic files | +|---|---:|---|---|---:| +| Ballu / half turn | 105 / 8 | pass / pass | yes | 8 / 8 | +| Ballu / quarter turn | 105 / 8 | pass / pass | yes | 8 / 8 | +| PDU / half turn | 166 / 17 | pass / pass | yes | 17 / 17 | +| PDU / quarter turn | 166 / 17 | pass / pass | yes | 17 / 17 | +| USB-C / half turn | 261 / 20 | pass / pass | yes | 20 / 20 | +| USB-C / quarter turn | 261 / 20 | pass / pass | yes | 20 / 20 | + +All 90 curated schematic files match their prior matching-mode outputs. +Presentation options and every loaded design-source hash also match: 48 source +files for Ballu, 54 for PDU and 63 for USB-C. The additive manifest evidence is +intentionally excluded from that schematic-byte comparison. Existing drawing +review limitations are retained; these checks do not create new visual approval. + +The additional LED-driver quarter-turn compatibility case also passed both +native versions, deterministic repeat and all source guards: 78 components, +five sheets, 58 eligible passives, 174 angle evaluations and 174 routing calls +(`3P`, with complete coverage). Serialized-scene safety rolled seven regions +back to their cached incumbents. All four compact LED channels remain selected, +and all five final schematic documents are byte-identical to the new default +mode. No additional quarter-turn improvement is claimed for this circuit. + +## Controlled runtime + +Timing runs only after every functional coordinator has exited. Each +design/implementation pair uses one compiled object, one warm-up and three +sequential measured exports, with a 900-second ceiling per export. Compilation, +native CLI checks, rendering and input/library hashing are outside the measured +interval. All measured processes use logical CPU 10 on an Intel Core i9-14900K. +Its sibling CPU 11 is not reserved; host load and frequency are not controlled. + +Normalized physical-input hashes include component paths, references, +footprints, values, part identifiers, compiled pinning and connected physical-pin +partitions, including singletons. Before/after input and library hashes must +stay unchanged, and old/new physical-input hashes must match per design. +All measured output bundle hashes must repeat exactly within each implementation. +These guards are separate from the earlier native electrical comparisons. +Manifest fingerprints also bind symbol and placement geometry, so old/new +manifest fingerprints deliberately differ; the normalized physical-input hash +establishes equal electrical input for timing. + +| Design | Baseline median s (range) | New median s (range) | Observed change | Guards | +|---|---:|---:|---:|---| +| Datalogger | 77.32 (75.94–77.51) | 72.72 (72.05–73.02) | −5.9% | pass | +| IotLedDriver | 55.25 (55.05–56.03) | 63.81 (63.05–63.88) | +15.5% | pass | + +Measured sample order was baseline Datalogger, new Datalogger, baseline +IotLedDriver, new IotLedDriver, each with its own warm-up followed by three +samples. Baseline-first ordering, uncontrolled host activity/frequency and only +three observations limit inference: these results do not establish statistical +significance, a general latency bound or cold MCP action performance. Peak +memory is not measured. + +All input, library, source, implementation and output-repeat guards passed. +The compact LED-driver pass costs about 8.56 seconds in this measured case while +reducing each channel's weighted local route cost by 61.0%. Datalogger's median +falls by about 4.60 seconds. These are case-specific observed costs, not a claim +of universal exporter speedup. The automatic gated rollout is retained; passive +quarter turns remain opt-in. + +Raw samples, physical/library hashes and per-export bundle hashes are in the +host evidence's `timing/` records and `timing-summary.json`. `FINAL-VERIFICATION.json` +confirms that the production-source digest still matches the frozen snapshot, +all functional work is complete and no functional worker remains active. + +## Visual limitations + +Native component/net equality is independent of visual acceptance. The drawing +review of Datalogger's MCU closes the ordinary-capacitor-box finding for the +inspected components, but retains long supply/oscillator detours, a generic +crystal, split support and mixed functional page grouping as limitations. +Its custom supercapacitor remains a deliberate unresolved symbol mapping. + +A separate fresh drawing-only review inspected native full sheets and readable +details for all four LED-driver channels. It closes the bootstrap long-loop and +crossover finding throughout. The external LED load/terminal meaning is still +missing from the rendered channel, and inductor fields remain farther away than +ideal. Page-three whitespace and mixed automatic grouping also remain. These +are recorded limitations; whole-board visual approval is pending. No +corpus-wide aesthetic approval is inferred from the native checks. + +The final Datalogger PNGs match the precursor drawing review byte-for-byte; the +hash-bound reuse record retains that review's sampled scope and limitations. +Native SVG export timestamps differ, so only drawing bytes are reused as visual +evidence. Final native connectivity checks are fresh. + +Full-sheet inventories and hashes remain in the isolated host evidence. diff --git a/edg/BoardCompiler.py b/edg/BoardCompiler.py index 1f7ef6eaa..096cf4b68 100644 --- a/edg/BoardCompiler.py +++ b/edg/BoardCompiler.py @@ -9,9 +9,17 @@ from .electronics_model.SvgPcbBackend import SvgPcbBackend from .electronics_model.RefdesRefinementPass import RefdesRefinementPass from .electronics_model.BomBackend import GenerateBom +from .electronics_model.KiCadSchematicExporter import KiCadSchematicExporter, SchematicExportOptions +from pathlib import Path +from dataclasses import replace -def compile_board(design: Type[Block], target_dir_name: Optional[Tuple[str, str]]) -> CompiledDesign: +def compile_board( + design: Type[Block], + target_dir_name: Optional[Tuple[str, str]], + *, + schematic: Optional[SchematicExportOptions] = None, +) -> CompiledDesign: if target_dir_name is not None: target_dir, target_name = target_dir_name if not os.path.exists(target_dir): @@ -80,10 +88,21 @@ def compile_board(design: Type[Block], target_dir_name: Optional[Tuple[str, str] ) ) + if schematic is not None: + options = replace(schematic, source=schematic.source or f"{design.__module__}.{design.__qualname__}") + exported = KiCadSchematicExporter().export(compiled, options) + if target_dir_name is not None: + exported.write(Path(target_dir_name[0]) / (target_dir_name[1] + ".schematic")) + return compiled -def compile_board_inplace(design: Type[Block], generate: bool = True) -> CompiledDesign: +def compile_board_inplace( + design: Type[Block], + generate: bool = True, + *, + schematic: Optional[SchematicExportOptions] = None, +) -> CompiledDesign: """Compiles a board and writes the results in a sub-directory where the module containing the top-level is located""" designfile = inspect.getfile(design) @@ -91,6 +110,6 @@ def compile_board_inplace(design: Type[Block], generate: bool = True) -> Compile target_dir_name = (os.path.join(os.path.dirname(designfile), design.__name__), design.__name__) else: target_dir_name = None - compiled = compile_board(design, target_dir_name) + compiled = compile_board(design, target_dir_name, schematic=schematic) return compiled diff --git a/edg/abstract_parts/Diode.py b/edg/abstract_parts/Diode.py index 53aea04ab..04059782b 100644 --- a/edg/abstract_parts/Diode.py +++ b/edg/abstract_parts/Diode.py @@ -1,4 +1,4 @@ -from typing import Any, Dict +from typing import Any, Dict, Union from typing_extensions import override from ..electronics_interfaces import * @@ -23,6 +23,20 @@ def __init__(self) -> None: class DiodeStandardFootprint(StandardFootprint["BaseDiode"]): REFDES_PREFIX = "D" + @classmethod + @override + def _make_pinning(cls, block: "BaseDiode", footprint: str) -> Dict[str, Union[Passive, HasPassivePort]]: + pinning = super()._make_pinning(block, footprint) + from .ZenerDiode import ZenerDiode + from .TvsDiode import TvsDiode + + # Device:D and D_Zener have 1=K, 2=A. TVS polarity is not modeled well + # enough to choose a unidirectional/bidirectional symbol automatically. + if isinstance(block, FootprintBlock) and not isinstance(block, TvsDiode) and set(pinning) == {"1", "2"}: + symbol = "Device:D_Zener" if isinstance(block, ZenerDiode) else "Device:D" + block._default_schematic_symbol(symbol, {"1": "1", "2": "2"}) + return pinning + FOOTPRINT_PINNING_MAP = { ( "Diode_SMD:D_MiniMELF", diff --git a/edg/abstract_parts/Led.py b/edg/abstract_parts/Led.py index 32ae9f9c5..bb163599c 100644 --- a/edg/abstract_parts/Led.py +++ b/edg/abstract_parts/Led.py @@ -1,4 +1,4 @@ -from typing import Any +from typing import Any, Dict, Union from typing_extensions import override from ..electronics_interfaces import * @@ -38,6 +38,15 @@ def __init__(self, color: LedColorLike = Any): class LedStandardFootprint(StandardFootprint[Led]): REFDES_PREFIX = "D" + @classmethod + @override + def _make_pinning(cls, block: Led, footprint: str) -> Dict[str, Union[Passive, HasPassivePort]]: + pinning = super()._make_pinning(block, footprint) + # Device:LED has 1=K, 2=A, matching these verified standard packages. + if isinstance(block, FootprintBlock) and set(pinning) == {"1", "2"}: + block._default_schematic_symbol("Device:LED", {"1": "1", "2": "2"}) + return pinning + FOOTPRINT_PINNING_MAP = { ( "LED_SMD:LED_0402_1005Metric", diff --git a/edg/abstract_parts/PassiveConnector.py b/edg/abstract_parts/PassiveConnector.py index 95486d7cc..b57dc9c10 100644 --- a/edg/abstract_parts/PassiveConnector.py +++ b/edg/abstract_parts/PassiveConnector.py @@ -101,3 +101,11 @@ def generate(self) -> None: pnp_rot=self.part_footprint_pnp_rot(length), pnp_offset=self.part_footprint_pnp_offset(length), ) + # Generic connector symbols preserve the actual modeled physical pad numbers. + # Do not invent pins for unmodeled positions in a partially allocated connector. + modeled_pins = {pin for pin, _ in self.pins.items()} + if 1 <= length <= 40 and modeled_pins == {str(pin) for pin in range(1, length + 1)}: + self._default_schematic_symbol( + f"Connector_Generic:Conn_01x{length:02d}", + {pin: pin for pin in modeled_pins}, + ) diff --git a/edg/abstract_parts/StandardFootprint.py b/edg/abstract_parts/StandardFootprint.py index 5ce927489..8c6352b5e 100644 --- a/edg/abstract_parts/StandardFootprint.py +++ b/edg/abstract_parts/StandardFootprint.py @@ -40,7 +40,29 @@ def _footprint_pinning_map(cls) -> Dict[str, PinningFunction[StandardPinningType @classmethod def _make_pinning(cls, block: StandardPinningType, footprint: str) -> Dict[str, Union[Passive, HasPassivePort]]: """Returns the pinning for a footprint for a specific block's pins""" - return cls._footprint_pinning_map()[footprint](block) + pinning = cls._footprint_pinning_map()[footprint](block) + # These category helpers explicitly declare the physical pad mappings. + from .Resistor import ResistorStandardFootprint + from .Capacitor import CapacitorStandardFootprint + from .Inductor import InductorStandardFootprint + from .FerriteBead import FerriteBeadStandardFootprint + from .Fuse import FuseStandardFootprint + + symbols = { + ResistorStandardFootprint: "Device:R", + InductorStandardFootprint: "Device:L", + FerriteBeadStandardFootprint: "Device:Ferrite_Bead", + FuseStandardFootprint: "Device:Fuse", + } + lib_id = symbols.get(cls) + if cls is CapacitorStandardFootprint: + if footprint.startswith("Capacitor_SMD:C_"): + lib_id = "Device:C" + elif footprint.startswith("Capacitor_SMD:CP_"): + lib_id = "Device:C_Polarized" + if lib_id and set(pinning) == {"1", "2"} and isinstance(block, FootprintBlock): + block._default_schematic_symbol(lib_id, {"1": "1", "2": "2"}) + return pinning @non_library diff --git a/edg/abstract_parts/Switch.py b/edg/abstract_parts/Switch.py index 5f4a6e538..fbc4a01b4 100644 --- a/edg/abstract_parts/Switch.py +++ b/edg/abstract_parts/Switch.py @@ -1,4 +1,4 @@ -from typing import Any, Dict +from typing import Any, Dict, Mapping, Optional, Tuple from typing_extensions import override from ..electronics_interfaces import * @@ -13,6 +13,22 @@ def symbol_pinning(self, symbol_name: str) -> Dict[str, BasePort]: assert symbol_name == "Switch:SW_SPST" return {"1": self.sw, "2": self.com} + def _schematic_symbol_for_footprint( + self, pinning: Mapping[str, Passive] + ) -> Optional[Tuple[str, Mapping[str, str]]]: + """Map only footprints whose modeled pads are exactly the two switch contacts.""" + sw_pads = sorted(pin for pin, port in pinning.items() if port is self.sw) + com_pads = sorted(pin for pin, port in pinning.items() if port is self.com) + if len(sw_pads) + len(com_pads) != len(pinning): + return None + if len(sw_pads) == len(com_pads) == 1: + symbol = "Switch:SW_Push" if isinstance(self, (TactileSwitch, MechanicalKeyswitch)) else "Switch:SW_SPST" + return symbol, {"1": sw_pads[0], "2": com_pads[0]} + if len(sw_pads) == len(com_pads) == 2 and isinstance(self, TactileSwitch): + # SW_Push_Dual's two left contact pins are 1/3; right contact pins 2/4. + return "Switch:SW_Push_Dual", {"1": sw_pads[0], "3": sw_pads[1], "2": com_pads[0], "4": com_pads[1]} + return None + def __init__(self, voltage: RangeLike, current: RangeLike = 0 * Amp(tol=0)) -> None: super().__init__() diff --git a/edg/abstract_parts/test_schematic_symbol_annotations.py b/edg/abstract_parts/test_schematic_symbol_annotations.py new file mode 100644 index 000000000..2ce83448f --- /dev/null +++ b/edg/abstract_parts/test_schematic_symbol_annotations.py @@ -0,0 +1,184 @@ +"""Verify schematic metadata against the physical pad mappings, including sparse connectors.""" + +from typing_extensions import override +import json +from pathlib import Path +import tempfile +import unittest +from typing import Any, Dict, Optional, Tuple + +from ..electronics_model import Block, FootprintBlock, ScalaCompiler +from ..BoardCompiler import compile_board +from ..electronics_model.KiCadSchematicExporter import SchematicExportOptions +from .Diode import BaseDiode, DiodeStandardFootprint +from .Led import Led, LedStandardFootprint +from .PassiveConnector import FootprintPassiveConnector +from .Switch import TactileSwitch +from .ZenerDiode import ZenerDiode +from .TvsDiode import TvsDiode + + +class AnnotationLed(Led, FootprintBlock): + @override + def contents(self) -> None: + super().contents() + footprint = "LED_SMD:LED_0603_1608Metric" + self.footprint("D", footprint, LedStandardFootprint._make_pinning(self, footprint)) + + +class AnnotationDiode(BaseDiode, FootprintBlock): + @override + def contents(self) -> None: + super().contents() + footprint = "Diode_SMD:D_SOD-123" + self.footprint("D", footprint, DiodeStandardFootprint._make_pinning(self, footprint)) + + +class SchottkyBeforeFootprint(AnnotationDiode): + @override + def contents(self) -> None: + self.schematic_symbol("Device:D_Schottky", {"1": "1", "2": "2"}) + super().contents() + + +class SchottkyAfterFootprint(AnnotationDiode): + @override + def contents(self) -> None: + super().contents() + self.schematic_symbol("Device:D_Schottky", {"1": "1", "2": "2"}) + + +class SchottkyBoard(Block): + @override + def contents(self) -> None: + super().contents() + self.before = self.Block(SchottkyBeforeFootprint()) + self.after = self.Block(SchottkyAfterFootprint()) + self.connect(self.before.anode, self.after.anode) + self.connect(self.before.cathode, self.after.cathode) + + +class AnnotationZener(ZenerDiode, FootprintBlock): + @override + def contents(self) -> None: + super().contents() + footprint = "Diode_SMD:D_SOD-123" + self.footprint("D", footprint, DiodeStandardFootprint._make_pinning(self, footprint)) + + +class AnnotationTvs(TvsDiode, FootprintBlock): + @override + def contents(self) -> None: + super().contents() + footprint = "Diode_SMD:D_SOD-123" + self.footprint("D", footprint, DiodeStandardFootprint._make_pinning(self, footprint)) + + +class AnnotationSwitch(TactileSwitch, FootprintBlock): + @override + def contents(self) -> None: + super().contents() + self.footprint( + "SW", "Button_Switch_SMD:SW_SPST_TL3305A", {"1": self.sw, "2": self.sw, "3": self.com, "4": self.com} + ) + + +class AnnotationConnector(FootprintPassiveConnector): + allowed_pins = range(1, 5) + + @override + def part_footprint_mfr_name(self, length: int) -> Tuple[str, str, str]: + return f"Connector_PinHeader_2.54mm:PinHeader_1x{length:02d}_P2.54mm_Vertical", "", "" + + +class AnnotationBoard(Block): + @override + def contents(self) -> None: + super().contents() + self.led = self.Block(AnnotationLed()) + self.diode = self.Block(AnnotationDiode()) + self.zener = self.Block(AnnotationZener(zener_voltage=(4, 6))) + self.tvs = self.Block(AnnotationTvs(working_voltage=(0, 5))) + self.sw = self.Block(AnnotationSwitch(voltage=(0, 5))) + self.conn = self.Block(AnnotationConnector(length=3)) + self.sparse = self.Block(AnnotationConnector(length=3)) + self.connect( + self.led.a, + self.diode.anode, + self.zener.anode, + self.tvs.anode, + self.sw.sw, + self.conn.pins.request("1"), + self.sparse.pins.request("1"), + ) + self.connect( + self.led.k, + self.diode.cathode, + self.zener.cathode, + self.tvs.cathode, + self.sw.com, + self.conn.pins.request("2"), + self.conn.pins.request("3"), + self.sparse.pins.request("3"), + ) + + +class SchematicSymbolAnnotationTest(unittest.TestCase): + def test_explicit_diode_symbol_overrides_standard_footprint_in_either_order(self) -> None: + for export in (False, True): + with self.subTest(export=export), tempfile.TemporaryDirectory() as directory: + options = None + if export: + Path(directory, "Device.kicad_sym").write_text( + '(kicad_symbol_lib (symbol "D_Schottky" (symbol "D_Schottky_1_1" ' + '(pin passive line (at -5.08 0 0) (length 2.54) (name "K") (number "1")) ' + '(pin passive line (at 5.08 0 180) (length 2.54) (name "A") (number "2")))))', + encoding="utf-8", + ) + options = SchematicExportOptions("Schottky", symbol_library_dirs=(directory,)) + compiled = compile_board(SchottkyBoard, (directory, "Schottky"), schematic=options) + for path in ("before", "after"): + raw = compiled.get_value((path, "sch_symbol")) + assert isinstance(raw, str) + self.assertEqual(json.loads(raw), {"lib_id": "Device:D_Schottky", "pinning": {"1": "1", "2": "2"}}) + pins = compiled.get_value((path, "fp_pinning")) + assert isinstance(pins, list) + self.assertEqual(set(pins), {"1=cathode", "2=anode"}) + if export: + manifest = json.loads(Path(directory, "Schottky.schematic", "manifest.json").read_text("utf-8")) + self.assertEqual( + [ + (item["mapping_source"], item["lib_id"], item["status"]) + for item in manifest["symbol_coverage"] + ], + [("explicit", "Device:D_Schottky", "resolved")] * 2, + ) + + def test_verified_physical_pad_mappings(self) -> None: + compiled = ScalaCompiler.compile(AnnotationBoard) + + def mapping(path: str) -> Optional[Dict[str, Any]]: + raw = compiled.get_value((path, "sch_symbol_default")) + if not raw: + return None + assert isinstance(raw, str) + result: Dict[str, Any] = json.loads(raw) + return result + + self.assertEqual(mapping("led"), {"lib_id": "Device:LED", "pinning": {"1": "1", "2": "2"}}) + self.assertEqual(mapping("diode"), {"lib_id": "Device:D", "pinning": {"1": "1", "2": "2"}}) + self.assertEqual(mapping("zener"), {"lib_id": "Device:D_Zener", "pinning": {"1": "1", "2": "2"}}) + self.assertIsNone(mapping("tvs")) + self.assertEqual( + mapping("sw"), + {"lib_id": "Switch:SW_Push_Dual", "pinning": {"1": "1", "3": "2", "2": "3", "4": "4"}}, + ) + self.assertEqual( + mapping("conn"), + {"lib_id": "Connector_Generic:Conn_01x03", "pinning": {"1": "1", "2": "2", "3": "3"}}, + ) + self.assertIsNone(mapping("sparse")) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/CircuitBlock.py b/edg/electronics_model/CircuitBlock.py index fa40b7c21..be8b86ec9 100644 --- a/edg/electronics_model/CircuitBlock.py +++ b/edg/electronics_model/CircuitBlock.py @@ -25,6 +25,8 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.fp_footprint = self.Parameter(StringExpr()) self.fp_pinning = self.Parameter(ArrayStringExpr()) self.fp_datasheet = self.Parameter(StringExpr()) + self.sch_symbol = self.Parameter(StringExpr()) + self.sch_symbol_default = self.Parameter(StringExpr()) self.fp_mfr = self.Parameter(StringExpr()) self.fp_part = self.Parameter(StringExpr()) @@ -36,6 +38,49 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.fp_pnp_offset_x = self.Parameter(FloatExpr()) self.fp_pnp_offset_y = self.Parameter(FloatExpr()) + def schematic_symbol( + self, + lib_id: str, + pinning: Mapping[str, str], + *, + pin_names: Optional[Mapping[str, str]] = None, + ) -> None: + """Declare a generated schematic symbol: library pin number -> physical pad number. + + This is export-only metadata; Python remains the connectivity source of truth. + """ + self._assign_schematic_symbol(self.sch_symbol, lib_id, pinning, pin_names) + + def _default_schematic_symbol(self, lib_id: str, pinning: Mapping[str, str]) -> None: + """Supply category metadata when the concrete part has no explicit symbol.""" + self._assign_schematic_symbol(self.sch_symbol_default, lib_id, pinning, None) + + def _assign_schematic_symbol( + self, parameter: StringExpr, lib_id: str, pinning: Mapping[str, str], pin_names: Optional[Mapping[str, str]] + ) -> None: + import json + + if ( + not isinstance(lib_id, str) + or ":" not in lib_id + or not all(lib_id.split(":", 1)) + or not pinning + or any(not isinstance(k, str) or not k or not isinstance(v, str) or not v for k, v in pinning.items()) + ): + raise ValueError("schematic_symbol requires Library:Symbol and string pin numbers") + metadata: Dict[str, Any] = {"lib_id": lib_id, "pinning": dict(pinning)} + if pin_names is not None: + if not set(pin_names).issubset(set(pinning.values())) or any( + not isinstance(v, str) or not v for v in pin_names.values() + ): + raise ValueError("schematic pin names must name mapped physical pads") + metadata["pin_names"] = dict(pin_names) + self.assign(parameter, json.dumps(metadata, sort_keys=True)) + + def _schematic_symbol_for_footprint(self, pinning: Mapping[str, Any]) -> Optional[Tuple[str, Mapping[str, str]]]: + """Optional category hook; must map verified physical pads to symbol pins.""" + return None + @overload def footprint( self, @@ -106,6 +151,7 @@ def footprint( pinning_array = [] assigned_pins: Set[str] = set() + flat_pinning = {} for pin_name, pin_port in pinning.items(): if isinstance(pin_port, HasPassivePort): pin_port = pin_port.net @@ -120,7 +166,11 @@ def footprint( pinning_array.append(f"{pin}={self._path_name_of(pin_port)}") assert pin not in assigned_pins, f"duplicate pin name {pin} in footprint pinning" assigned_pins.add(pin) + flat_pinning[pin] = pin_port self.assign(self.fp_pinning, pinning_array) + schematic = self._schematic_symbol_for_footprint(flat_pinning) + if schematic is not None: + self._default_schematic_symbol(*schematic) self.assign(self.fp_footprint, footprint) self.assign(self.fp_refdes_prefix, refdes) diff --git a/edg/electronics_model/KiCadCompositeSymbols.py b/edg/electronics_model/KiCadCompositeSymbols.py new file mode 100644 index 000000000..1a50b96d0 --- /dev/null +++ b/edg/electronics_model/KiCadCompositeSymbols.py @@ -0,0 +1,91 @@ +"""Single-instance symbols for verified packed passive networks. + +The physical pin inventory remains authoritative. Branch pairing comes from the +ResistorArray model's a[index]/b[index] exports, never physical pad ordering. +""" + +from __future__ import annotations + +import re +from typing import Any, Optional, Sequence, Tuple, TYPE_CHECKING +from .KiCadSchematicTypes import SExpr + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent + +from sexpdata import Symbol as S + +RESISTOR_ARRAY_CLASSES = { + "edg.vendor_parts.jlc.JlcResistorArray.JlcResistorArray", +} + + +def resistor_array_symbol( + component: PhysicalComponent, class_names: Sequence[str] +) -> Optional[Tuple[SExpr, list[tuple[str, float, float, float]], str]]: + if not class_names or class_names[-1].removeprefix("PolymorphicBlocks.") not in RESISTOR_ARRAY_CLASSES: + return None + pairs: dict[str, dict[str, str]] = {} + for number, role in component.pins.items(): + match = re.fullmatch(r"([ab])\.(\d+)(?:\.net)?", role) + if match is None: + return None + side, index = match.groups() + if side in pairs.setdefault(index, {}): + return None + pairs[index][side] = number + if not pairs or any(set(pair) != {"a", "b"} for pair in pairs.values()): + return None + + # Use inventory and branch pairing in the identity, independent of position. + import hashlib + import json + + pin_names = (getattr(component, "mapping", None) or {}).get("pin_names", {}) + identity = {"pairs": pairs, "pin_names": pin_names} if pin_names else pairs + digest = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:16] + lib_id = "PB:ResistorArray_" + digest + body: SExpr = [S("symbol"), lib_id.split(":", 1)[1] + "_1_1"] + positions: list[tuple[str, float, float, float]] = [] + for row, index in enumerate(sorted(pairs, key=int)): + y = round((row - (len(pairs) - 1) / 2) * 7.62, 4) + body.append( + [ + S("rectangle"), + [S("start"), -2.54, -y + 1.016], + [S("end"), 2.54, -y - 1.016], + [S("stroke"), [S("width"), 0.254], [S("type"), S("default")]], + [S("fill"), [S("type"), S("none")]], + ] + ) + for side, x, angle in (("a", -7.62, 0), ("b", 7.62, 180)): + number = pairs[index][side] + body.append( + [ + S("pin"), + S("passive"), + S("line"), + [S("at"), x, -y, angle], + [S("length"), 5.08], + [ + S("name"), + "~", + [S("effects"), [S("font"), [S("size"), 1.0, 1.0]]], + ], + [ + S("number"), + number, + [S("effects"), [S("font"), [S("size"), 1.0, 1.0]]], + ], + ] + ) + positions.append((number, x, y, angle)) + definition: SExpr = [ + S("symbol"), + lib_id, + [S("pin_names"), [S("offset"), 0]], + [S("in_bom"), S("yes")], + [S("on_board"), S("yes")], + body, + ] + return definition, positions, lib_id diff --git a/edg/electronics_model/KiCadSchematicBlock.py b/edg/electronics_model/KiCadSchematicBlock.py index f3b4d0fb0..dd37e8d32 100644 --- a/edg/electronics_model/KiCadSchematicBlock.py +++ b/edg/electronics_model/KiCadSchematicBlock.py @@ -56,6 +56,7 @@ def block_from_symbol( kicad_part=symbol.lib, kicad_value=symbol.properties.get("Value", ""), kicad_datasheet=symbol.properties.get("Datasheet", ""), + kicad_pin_names=[f"{pin.number}={pin.name}" for pin in lib.pins if pin.name and pin.name != "~"], ) def block_pinning(block: KiCadBlackbox) -> Mapping[str, BasePort]: @@ -71,6 +72,8 @@ def __init__( kicad_part: StringLike, kicad_value: StringLike, kicad_datasheet: StringLike, + *, + kicad_pin_names: ArrayStringLike = [], ): super().__init__() self.ports = self.Port(Vector(Passive()), optional=True) @@ -81,7 +84,8 @@ def __init__( self.kicad_datasheet = self.ArgParameter(kicad_datasheet) self.kicad_pins = self.ArgParameter(kicad_pins) - self.generator_param(self.kicad_pins) + self.kicad_pin_names = self.ArgParameter(kicad_pin_names) + self.generator_param(self.kicad_pins, self.kicad_part, self.kicad_pin_names) @override def generate(self) -> None: @@ -95,6 +99,13 @@ def generate(self) -> None: value=self.kicad_value, datasheet=self.kicad_datasheet, ) + # Imported library pin numbers are the footprint pad numbers by the + # blackbox contract. Preserve verified identity through compilation. + numbers = self.get(self.kicad_pins) + lib_id = self.get(self.kicad_part) + if numbers and ":" in lib_id: + names = dict(value.split("=", 1) for value in self.get(self.kicad_pin_names)) + self.schematic_symbol(lib_id, {number: number for number in numbers}, pin_names=names) @non_library diff --git a/edg/electronics_model/KiCadSchematicCircuits.py b/edg/electronics_model/KiCadSchematicCircuits.py new file mode 100644 index 000000000..f9322861b --- /dev/null +++ b/edg/electronics_model/KiCadSchematicCircuits.py @@ -0,0 +1,385 @@ +"""Shared, deterministic circuit presentation backed by physical connectivity. + +This model describes existing compiled terminals only. Authored flow and function +are presentation intent; they never redefine electrical topology. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Collection, Mapping, Optional, Sequence +from .KiCadSchematicTypes import PinNets, Views + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent + from .KiCadSchematicPresentation import SchematicPresentation + + +from collections import defaultdict +from dataclasses import dataclass +import hashlib +from typing import Tuple + +from .KiCadSchematicPatterns import SchematicPattern, discover_patterns, terminal_roles + +BOUNDARY_ROLES = frozenset(("input", "output", "supply", "return", "control", "feedback", "bidirectional")) +TEMPLATES = frozenset( + ( + "auto", + "generic", + "buck", + "four_switch_bridge", + "gate_driver", + "repeated_channel", + "connector_protection", + "mcu_support", + "series_path", + "controller_support", + ) +) +SUPPLY_ROLES = frozenset(("gnd", "vss", "pgnd", "vdd", "vcc", "pwr", "vin", "vout", "pwr_in", "pwr_out", "vp", "vn")) + + +def _text(value: object, what: str) -> None: + if not isinstance(value, str) or not value.strip() or value != value.strip() or len(value) > 240: + raise ValueError(what + " must be trimmed nonempty text of at most 240 characters") + + +def _paths(value: object, what: str) -> None: + if not isinstance(value, (list, tuple)) or not value: + raise ValueError(what + " must be a nonempty array") + for item in value: + _text(item, what) + if len(set(value)) != len(value): + raise ValueError(what + " contains duplicate component paths") + + +def validate_circuit_entries( + entries: Sequence[Mapping[str, Any]], inventories: Optional[Mapping[str, Mapping[str, str]]] = None +) -> None: + """Validate input syntax and, when available, exact physical references.""" + ids, ownership = set(), {} + for entry in entries: + if ( + not isinstance(entry, Mapping) + or set(entry) - {"id", "title", "summary", "components", "template", "stages", "boundaries"} + or not {"id", "title", "summary", "components"} <= set(entry) + ): + raise ValueError("circuit has unknown or missing fields") + for key in ("id", "title", "summary"): + _text(entry[key], "circuit " + key) + identity = entry["id"] + if identity in ids: + raise ValueError("duplicate circuit id: " + identity) + ids.add(identity) + _paths(entry["components"], "circuit components") + members = set(entry["components"]) + for path in members: + if path in ownership: + raise ValueError("component belongs to conflicting circuits: " + path) + ownership[path] = identity + if inventories is not None and path not in inventories: + raise ValueError("circuit references missing component: " + path) + template = entry.get("template", "auto") + if not isinstance(template, str) or template not in TEMPLATES: + raise ValueError("unsupported circuit template: " + str(template)) + stages = entry.get("stages", []) + boundaries = entry.get("boundaries", []) + if not isinstance(stages, (list, tuple)) or not isinstance(boundaries, (list, tuple)): + raise ValueError("circuit stages and boundaries must be arrays") + stage_ids: set[str] = set() + stage_members: set[str] = set() + for stage in stages: + if not isinstance(stage, Mapping) or set(stage) != {"id", "components"}: + raise ValueError("circuit stage requires id and components") + _text(stage["id"], "stage id") + _paths(stage["components"], "stage components") + if stage["id"] in stage_ids: + raise ValueError("duplicate stage id: " + stage["id"]) + stage_ids.add(stage["id"]) + if not set(stage["components"]) <= members: + raise ValueError("stage components must belong to their circuit: " + identity) + if stage_members & set(stage["components"]): + raise ValueError("component belongs to conflicting stages: " + identity) + stage_members.update(stage["components"]) + boundary_keys = set() + for boundary in boundaries: + if not isinstance(boundary, Mapping) or set(boundary) != {"component", "pin", "name", "role"}: + raise ValueError("circuit boundary requires component, pin, name and role") + for key in ("component", "pin", "name", "role"): + _text(boundary[key], "boundary " + key) + if boundary["role"] not in BOUNDARY_ROLES: + raise ValueError("unsupported boundary role: " + boundary["role"]) + path, pin = boundary["component"], boundary["pin"] + if path not in members: + raise ValueError("boundary component must belong to its circuit: " + path) + if (path, pin) in boundary_keys: + raise ValueError("duplicate circuit boundary terminal: " + path + ":" + pin) + boundary_keys.add((path, pin)) + if inventories is not None and pin not in inventories[path]: + raise ValueError("circuit boundary references unknown physical pin: " + path + ":" + pin) + + +@dataclass(frozen=True) +class CircuitStage: + id: str + components: Tuple[str, ...] + + def to_dict(self) -> dict[str, Any]: + return dict(id=self.id, components=list(self.components)) + + +@dataclass(frozen=True) +class CircuitBoundary: + component: str + pin: str + name: str + role: str + net: str + + def to_dict(self) -> dict[str, Any]: + return dict(component=self.component, pin=self.pin, name=self.name, role=self.role, net=self.net) + + +@dataclass(frozen=True) +class SchematicCircuit: + id: str + title: str + summary: str + components: Tuple[str, ...] + template: str = "auto" + stages: Tuple[CircuitStage, ...] = () + boundaries: Tuple[CircuitBoundary, ...] = () + patterns: Tuple[SchematicPattern, ...] = () + provenance: str = "automatic" + + @property + def primary_nets(self) -> tuple[str, ...]: + return tuple( + sorted( + {b.net for b in self.boundaries if b.role in ("input", "output", "bidirectional")} + | {n for p in self.patterns if p.kind == "serial_data_chain" for n in p.nets} + ) + ) + + def to_dict(self) -> dict[str, Any]: + return dict( + id=self.id, + title=self.title, + summary=self.summary, + components=list(self.components), + template=self.template, + stages=[s.to_dict() for s in self.stages], + boundaries=[b.to_dict() for b in self.boundaries], + patterns=[p.to_dict() for p in self.patterns], + primary_nets=list(self.primary_nets), + provenance=self.provenance, + ) + + +@dataclass(frozen=True) +class SchematicCircuitModel: + circuits: Tuple[SchematicCircuit, ...] + patterns: Tuple[SchematicPattern, ...] + diagnostics: Tuple[str, ...] = () + + def to_dict(self) -> dict[str, Any]: + return dict( + schema=1, + circuits=[c.to_dict() for c in self.circuits], + patterns=[p.to_dict() for p in self.patterns], + diagnostics=list(self.diagnostics), + ) + + +def _rails(components: Sequence[PhysicalComponent], pin_nets: PinNets) -> set[str]: + return { + pin_nets[c.path, number] + for c in components + for role, number in terminal_roles(c, pin_nets).items() + if role in SUPPLY_ROLES and (c.path, number) in pin_nets + } + + +def _validate_template( + entry: Mapping[str, Any], + members: Collection[str], + by_path: Mapping[str, PhysicalComponent], + pin_nets: PinNets, + views: Views, + patterns: Sequence[SchematicPattern], +) -> None: + template = entry.get("template", "auto") + if template in ("auto", "generic"): + return + kinds = {p.kind for p in patterns if set(p.components) <= set(members)} + valid = False + if template in ("buck", "four_switch_bridge"): + from .KiCadSchematicPower import power_topology + + topology = power_topology(members, by_path, views, pin_nets) if views else None + valid = topology is not None and topology["kind"] == {"buck": "buck", "four_switch_bridge": "bridge"}[template] + elif template == "gate_driver": + valid = "gate_driver_stage" in kinds + elif template == "repeated_channel": + valid = bool(kinds & {"repeated_subcircuit", "serial_data_chain"}) + elif template == "series_path": + valid = bool(kinds & {"indicator_branch", "serial_data_chain"}) + elif template in ("controller_support", "mcu_support"): + valid = "local_decoupling" in kinds and any(len(by_path[p].pins) >= 8 for p in members) + elif template == "connector_protection": + # A protection template must establish its series stages explicitly. + # Merely sharing a rail or a connector-like name is insufficient. + symbol = {p: views[p].lib_id.split("_PB_", 1)[0] for p in members} if views else {} + connectors = {p for p, sid in symbol.items() if sid.startswith(("Connector_Generic:Conn_", "Connector:Conn_"))} + diodes = { + p for p, sid in symbol.items() if sid in ("Device:D", "Device:D_Zener", "Device:D_TVS", "Device:D_Schottky") + } + returns = { + pin_nets[p, number] + for p in members + for role, number in terminal_roles(by_path[p], pin_nets).items() + if role in ("gnd", "vss", "pgnd", "vn") and (p, number) in pin_nets + } + terminal_nets = {p: {pin_nets[p, pin] for pin in by_path[p].pins if (p, pin) in pin_nets} for p in members} + rails = _rails([by_path[p] for p in members], pin_nets) + valid = len(entry.get("stages", ())) >= 2 and any( + len(terminal_nets[d]) == 2 + and bool(terminal_nets[d] & returns) + and bool((terminal_nets[d] - rails - returns) & terminal_nets[c]) + for d in diodes + for c in connectors + ) + if not valid: + raise ValueError( + "circuit template lacks required compiled connectivity evidence: " + entry["id"] + " (" + template + ")" + ) + + +def build_circuits( + components: Sequence[PhysicalComponent], + pin_nets: PinNets, + views: Views, + presentation: SchematicPresentation, + *, + scope_by_path: Optional[Mapping[str, str]] = None, +) -> SchematicCircuitModel: + """Discover once, then overlay source-owned circuit boundaries and intent. + + Called per board scope: disjoint authored circuits are skipped and a partial + intersection is an error. Optional scope metadata also permits full-design + callers to reject a circuit spanning independent board scopes. + """ + by_path = {c.path: c for c in components} + patterns = tuple( + sorted(discover_patterns(components, pin_nets, views), key=lambda p: (p.kind, p.components, p.nets)) + ) + circuits, diagnostics, claimed = [], [], set() + rails = _rails(components, pin_nets) + endpoints = defaultdict(set) + for (path, pin), net in pin_nets.items(): + if path in by_path: + endpoints[net].add(path) + # Syntax/global physical references were checked by presentation.validate; + # repeat syntax here so direct model clients receive the same strictness. + validate_circuit_entries(presentation.circuits) + authored_titles = set() + for entry in sorted(presentation.circuits, key=lambda e: e["id"]): + members = set(entry["components"]) + if not members & set(by_path): + continue + if members - set(by_path): + raise ValueError("circuit crosses board scope or references missing components: " + entry["id"]) + if scope_by_path is not None and len({scope_by_path[p] for p in members}) != 1: + raise ValueError("circuit crosses independent board scopes: " + entry["id"]) + if entry["title"] in authored_titles: + raise ValueError("duplicate circuit title within board scope: " + entry["title"]) + authored_titles.add(entry["title"]) + validate_circuit_entries([entry], {p: c.pins for p, c in by_path.items()}) + boundary = [] + for item in entry.get("boundaries", ()): + key = item["component"], item["pin"] + if key not in pin_nets: + raise ValueError("circuit boundary has no compiled net: " + ":".join(key)) + boundary.append(CircuitBoundary(**item, net=pin_nets[key])) + stages = tuple(CircuitStage(s["id"], tuple(s["components"])) for s in entry.get("stages", ())) + for first, second in zip(stages, stages[1:]): + first_nets = {n for n, ends in endpoints.items() if ends & set(first.components)} + second_nets = {n for n, ends in endpoints.items() if ends & set(second.components)} + authored_flow = {b.net for b in boundary if b.role in ("input", "output", "bidirectional")} + if not ((first_nets & second_nets) - rails or first_nets & second_nets & authored_flow): + raise ValueError( + "ordered circuit stages lack a non-supply connection: " + + entry["id"] + + ":" + + first.id + + " -> " + + second.id + ) + local_patterns = tuple(p for p in patterns if set(p.components) <= members) + _validate_template(entry, tuple(sorted(members)), by_path, pin_nets, views, local_patterns) + circuits.append( + SchematicCircuit( + entry["id"], + entry["title"], + entry["summary"], + tuple(sorted(members)), + entry.get("template", "auto"), + stages, + tuple(boundary), + local_patterns, + "explicit", + ) + ) + claimed.update(members) + # Merge verified support ownership only. A serial chain records order but + # remains cuttable between complete locally supported channels. + remaining = set(by_path) - claimed + parent = {p: p for p in remaining} + + def root(p: str) -> str: + while parent[p] != p: + p = parent[p] + return p + + for pattern in patterns: + members = set(pattern.components) + if pattern.kind == "serial_data_chain" or not members <= remaining: + continue + for p in sorted(members)[1:]: + a, b = root(min(members)), root(p) + parent[max(a, b)] = min(a, b) + groups = defaultdict(set) + for path in sorted(remaining): + groups[root(path)].add(path) + for _, group in sorted(groups.items()): + automatic_members = tuple(sorted(group)) + local = tuple(p for p in patterns if set(p.components) <= group) + identity = "auto_" + hashlib.sha256("\0".join(automatic_members).encode()).hexdigest()[:16] + kinds = sorted({p.kind for p in local}) + title = " / ".join(k.replace("_", " ") for k in kinds) if kinds else automatic_members[0] + # No automatic summary makes a functional claim beyond its evidence. + boundary = [] + for path in automatic_members: + roles = terminal_roles(by_path[path], pin_nets) + by_number = {number: role for role, number in roles.items()} + for pin in sorted(by_path[path].pins): + boundary_net = pin_nets.get((path, pin)) + if boundary_net is None or not endpoints[boundary_net] - group: + continue + declared = by_number.get(pin) + role = ( + "return" + if declared in ("gnd", "vss", "pgnd", "vn") + else "supply" if declared in SUPPLY_ROLES else "bidirectional" + ) + boundary.append(CircuitBoundary(path, pin, by_path[path].pins[pin], role, boundary_net)) + circuits.append( + SchematicCircuit(identity, title, "", automatic_members, boundaries=tuple(boundary), patterns=local) + ) + associated = {p for pattern in patterns if pattern.kind == "local_decoupling" for p in pattern.components[1:]} + for c in sorted(components, key=lambda c: c.path): + if c.path not in associated and any( + cls.endswith(".DecouplingCapacitor") for _, cls in getattr(c, "hierarchy", ()) + ): + diagnostics.append("Unassigned bypass ownership: " + c.path + "; shared rails do not establish an owner") + return SchematicCircuitModel(tuple(sorted(circuits, key=lambda c: c.id)), patterns, tuple(diagnostics)) diff --git a/edg/electronics_model/KiCadSchematicExporter.py b/edg/electronics_model/KiCadSchematicExporter.py new file mode 100644 index 000000000..b8e03085c --- /dev/null +++ b/edg/electronics_model/KiCadSchematicExporter.py @@ -0,0 +1,2371 @@ +"""Deterministic, one-way schematic views of compiled PB physical connectivity.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import math +import os +import re +import shutil +import tempfile +import textwrap +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, TYPE_CHECKING, cast + +import sexpdata +from .KiCadSchematicWriter import ( + S as S, + children as children, + effects as effects, + node as node, + uid as uid, + write_wires, +) +from .KiCadSymbolRegistry import infer_symbol +from .KiCadSchematicRoles import infer_pin_names, infer_description +from .KiCadCompositeSymbols import resistor_array_symbol +from .KiCadSchematicTypes import SymbolView as SymbolView +from .KiCadSchematicTypes import SExpr, Bounds, Point, PinKey, Wire, Placement, Placements, Views, PinNets, RouteResult + +if TYPE_CHECKING: + from .KiCadSchematicCircuits import SchematicCircuit, SchematicCircuitModel + from _hashlib import HASH + from ..core.Range import Range + +from ..core import CompiledDesign +from .NetlistGenerator import NetlistTransform, NetBlock +from .KiCadSchematicPlanner import ( + SchematicRegion, + SchematicRegionPlacement, + SchematicSheet, + SchematicSheetPlan, + SchematicSheetPlanner, + region_fits_page, +) +from .KiCadSchematicPresentation import SchematicPresentation +from .KiCadSchematicOverview import SchematicOverview, build_overviews, render_overview +from .KiCadSchematicScene import pin_label_bounds, text_width +from .KiCadSchematicLayout import ( + annotation_position, + annotation_bounds, + freeze_annotations, + ground_bounds, + ground_label_position, + ground_rotation, + graphic_bounds, + pin_escape, + pins as positioned_pins, + place_group, + regroup, + route_local, + split_group, +) + +NOTICE = "GENERATED FROM POLYMORPHICBLOCKS PYTHON — SOURCE OF TRUTH" +INSTRUCTIONS = "Edit the PB Python source and regenerate. Schematic edits will be overwritten." +VERSION = "8" + + +@dataclass(frozen=True) +class SchematicPlacement: + """Optional Python-owned functional schematic placement, in millimetres.""" + + group: str + x: float + y: float + rotation: int = 0 + flip_horizontal: bool = False + annotation: Optional[Tuple[float, float]] = None + lock_rotation: bool = True + + def __post_init__(self) -> None: + if type(self.lock_rotation) is not bool: + raise ValueError("lock_rotation must be a boolean") + + +@dataclass(frozen=True) +class SchematicExportOptions: + design_name: str + source: str = "" + symbol_library_dirs: Tuple[str, ...] = () + kicad_major: int = 9 + placements: Mapping[str, SchematicPlacement] = field(default_factory=dict) + sheet_assignments: Mapping[str, str] = field(default_factory=dict) + sheet_plan: Optional[SchematicSheetPlan] = None + overview: Optional[SchematicOverview] = None + presentation: Optional[SchematicPresentation] = None + ground_style: str = "bars" + optimize_routes: bool = True + optimize_orientations: bool = True + orientation_mode: str = "half_turn" + + def __post_init__(self) -> None: + if self.orientation_mode not in ("half_turn", "passive_quarter_turn"): + raise ValueError("orientation_mode must be half_turn or passive_quarter_turn") + if type(self.optimize_orientations) is not bool: + raise ValueError("optimize_orientations must be a boolean") + if type(self.optimize_routes) is not bool: + raise ValueError("optimize_routes must be a boolean") + if self.ground_style not in ("bars", "triangle"): + raise ValueError("ground_style must be bars or triangle") + + +def ground_symbol(resolver: SymbolResolver, style: str) -> SExpr: + """Change only ground graphics, retaining the original power-net semantics. + + Do not substitute Earth/GNDREF: those are different electrical net names in + some supported KiCad versions. Both styles fit the router's ground bounds. + """ + definition = copy.deepcopy(resolver.load("power:GND")) + if style == "bars": + body = next(body for body in children(definition, "symbol") if body[1].endswith("_0_1")) + body[:] = body[:2] + for a, b in ( + ((0, 0), (0, -1.27)), + ((-1.27, -1.27), (1.27, -1.27)), + ((-0.635, -1.905), (0.635, -1.905)), + ((-0.127, -2.54), (0.127, -2.54)), + ): + body.append( + node( + "polyline", + node("pts", node("xy", *a), node("xy", *b)), + node("stroke", node("width", 0), node("type", S("default"))), + node("fill", node("type", S("none"))), + ) + ) + return definition + + +@dataclass(frozen=True) +class SchematicDiagnostic: + component: str + reason: str + + +@dataclass +class SchematicExport: + files: Dict[str, str] + diagnostics: List[SchematicDiagnostic] + + def write(self, directory: Path) -> None: + """Stage all files first; clean only stale files owned by our previous manifest.""" + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + old = directory / "manifest.json" + previous = json.loads(old.read_text(encoding="utf-8")).get("files", []) if old.exists() else [] + for name in list(self.files) + previous: + if Path(name).name != name or name in (".", ".."): + raise ValueError("unsafe generated filename") + # Roll back ordinary I/O failures, not process termination or power loss. + # Keep recovery files if rollback itself fails. + stage = Path(tempfile.mkdtemp(prefix=".schematic-recovery-", dir=directory)) + changed: List[str] = [] + retain_recovery = False + try: + incoming, backup = stage / "incoming", stage / "backup" + incoming.mkdir() + backup.mkdir() + for name, content in self.files.items(): + (incoming / name).write_text(content, encoding="utf-8") + for name in sorted(set(self.files) | set(previous)): + destination = directory / name + if destination.is_symlink() or destination.exists(): + if destination.is_dir() and not destination.is_symlink(): + raise ValueError("generated file destination is a directory: " + name) + shutil.copy2(destination, backup / name, follow_symlinks=False) + try: + for name in sorted(n for n in self.files if n != "manifest.json"): + os.replace(incoming / name, directory / name) + changed.append(name) + for name in sorted(set(previous) - set(self.files)): + destination = directory / name + if destination.exists() or destination.is_symlink(): + destination.unlink() + changed.append(name) + # Publish ownership only after replacements and cleanup succeed. + if "manifest.json" in self.files: + os.replace(incoming / "manifest.json", directory / "manifest.json") + changed.append("manifest.json") + except BaseException as error: + failures = [] + for name in reversed(changed): + try: + saved = backup / name + if saved.exists() or saved.is_symlink(): + os.replace(saved, directory / name) + else: + (directory / name).unlink(missing_ok=True) + except OSError as rollback_error: + failures.append(f"{name}: {rollback_error}") + if failures: + retain_recovery = True + raise RuntimeError( + f"schematic write failed and rollback was incomplete; recovery files retained at {stage}: " + + "; ".join(failures) + ) from error + raise + finally: + if not retain_recovery: + shutil.rmtree(stage, ignore_errors=True) + + +@dataclass +class PhysicalComponent: + path: str + refdes: str + footprint: str + value: str + pins: Dict[str, str] + mapping: Optional[dict[str, Any]] + group: str + display_value: str = "" + annotation: Optional[Tuple[float, float]] = None + descriptions: Tuple[str, ...] = () + net_labels: Mapping[str, str] = field(default_factory=dict) + hierarchy: Tuple[Tuple[str, str], ...] = () + ground_net_labels: Mapping[str, str] = field(default_factory=dict) + symbol_coverage: Dict[str, Any] = field(default_factory=dict) + # These are attached by later passes, not constructor/dataclass fields. + if TYPE_CHECKING: + presentation_pin_roles: dict[str, str] = field(init=False) + circuit_model: SchematicCircuitModel = field(init=False) + functional_circuit: Optional[SchematicCircuit] = field(init=False) + placement_evidence: dict[str, Any] = field(init=False) + functional_continuation: dict[str, Any] = field(init=False) + + +class SymbolResolver: + def __init__(self, directories: Sequence[str]) -> None: + self.directories = directories + self.libraries: Dict[str, dict[str, SExpr]] = {} + + def load(self, lib_id: str, stack: Tuple[str, ...] = ()) -> SExpr: + if lib_id in stack: + raise ValueError("cyclic symbol inheritance") + library, symbol = lib_id.split(":", 1) + if library not in self.libraries: + filename = next( + ( + Path(d, library + ".kicad_sym") + for d in self.directories + if Path(d, library + ".kicad_sym").is_file() + ), + None, + ) + if filename is None: + raise FileNotFoundError(lib_id) + tree = sexpdata.loads(filename.read_text(encoding="utf-8")) + self.libraries[library] = {v[1]: v for v in children(tree, "symbol")} + result = copy.deepcopy(self.libraries[library][symbol]) + parent = children(result, "extends") + if parent: + base = self.load(library + ":" + parent[0][1], stack + (lib_id,)) + overridden = {v[1] for v in children(result, "property")} + inherited = [ + v for v in base[2:] if not (isinstance(v, list) and v and v[0] == S("property") and v[1] in overridden) + ] + result = result[:2] + inherited + [v for v in result[2:] if v not in parent] + result[1] = lib_id + for sub in children(result, "symbol"): + suffix = re.search(r"_(\d+_\d+)$", sub[1]) + if suffix: + sub[1] = symbol + "_" + suffix[1] + return result + + def resolve(self, component: PhysicalComponent) -> SymbolView: + mapping = component.mapping + if mapping is None: + raise LookupError("no schematic symbol mapping") + definition = self.load(mapping["lib_id"]) + pins = [] + observed = set() + for sub in children(definition, "symbol"): + match = re.search(r"_(\d+)_(\d+)$", sub[1]) + if match and int(match[1]) > 1: + raise LookupError("multi-unit symbol unsupported") + if match and int(match[2]) > 1: + continue # alternate body style + for pin in children(sub, "pin"): + number = str(children(pin, "number")[0][1]) + if number not in mapping["pinning"]: + if mapping.get("_omit_unmodeled"): + sub.remove(pin) + continue + raise ValueError("unmapped library pin " + number) + observed.add(number) + physical = mapping["pinning"][number] + if physical not in component.pins: + raise ValueError("symbol maps to unknown physical pin " + physical) + children(pin, "number")[0][1] = physical + at = children(pin, "at")[0] + pins.append((physical, float(at[1]), -float(at[2]), float(at[3]))) + if observed != set(mapping["pinning"]) or set(component.pins) != set(mapping["pinning"].values()): + raise ValueError("symbol mapping must cover the modeled physical pins exactly") + if len({p[0] for p in pins}) != len(pins): + raise LookupError("stacked or repeated symbol pins unsupported") + export_id = mapping["lib_id"] + "_PB_" + uid(json.dumps(mapping, sort_keys=True))[:8] + definition[1] = export_id + # Vendor libraries may target KiCad10; these library flags are not part + # of the KiCad9 embedded-symbol grammar and do not affect our pin graph. + definition[:] = [ + v + for v in definition + if not ( + isinstance(v, list) + and v + and str(v[0]) + in ( + "in_pos_files", + "duplicate_pin_numbers_are_jumpers", + "embedded_fonts", + ) + ) + ] + for sub in children(definition, "symbol"): + match = re.search(r"_(\d+_\d+)$", sub[1]) + if match: + sub[1] = export_id.split(":", 1)[1] + "_" + match[1] + # Remove alternate bodies excluded from the selected pin geometry. + definition[:] = [ + v + for v in definition + if not (isinstance(v, list) and v and v[0] == S("symbol") and re.search(r"_\d+_[2-9]$", str(v[1]))) + ] + return SymbolView(definition, pins, export_id) + + +def generic(component: PhysicalComponent) -> SymbolView: + """Functional IC view when no exact library definition is available. + + Pin numbers and electrical inventory remain the PB physical mapping. Only + graphical grouping uses logical roles; no missing vendor pins are invented. + """ + lib_id = "PB:" + uid(component.path) + sides: dict[str, list[tuple[str, str]]] = {"left": [], "right": [], "top": [], "bottom": []} + declared_names = (component.mapping or {}).get("pin_names", {}) + declared_roles = getattr(component, "presentation_pin_roles", {}) + display_pins = {number: declared_names.get(number, name) for number, name in component.pins.items()} + for number, name in sorted(display_pins.items()): + role = name.removesuffix(".net").lower() + if number in declared_roles: + side = { + "input": "left", + "output": "right", + "supply": "top", + "return": "bottom", + "control": "left", + "feedback": "left", + "bidirectional": "right", + }[declared_roles[number]] + elif role in ("gnd", "vss", "com"): + side = "bottom" + elif role in ("pwr", "vdd", "vcc", "vs", "vddio"): + side = "top" + elif role.startswith(("out", "vout", "bat", "chrg", "alrt", "alert", "int", "dout")) or re.fullmatch( + r"(?:gate|sw|boot|cboot|bst|btst|hidrv|lodrv|tgup|tgdn|gh|gl)\d*", role + ): + # Declared gate-drive/switch ports face the adjacent power stage. + # This changes graphics only, never pin numbers or connectivity. + side = "right" + else: + side = "left" + sides[side].append((number, name.removesuffix(".net"))) + if len(display_pins) == 2: + entries = sorted(display_pins.items()) + sides = {"left": [entries[0]], "right": [entries[1]], "top": [], "bottom": []} + if len(sides["left"]) > 8 and not sides["right"]: + midpoint = (len(sides["left"]) + 1) // 2 + sides["right"] = sides["left"][midpoint:] + sides["left"] = sides["left"][:midpoint] + rows = max(len(sides["left"]), len(sides["right"]), 2) + # Dense fallback ICs must leave room for native global-label outlines and + # pin text. Physical pin inventory is unchanged; only the drawing grows. + side_pitch = 3.81 + rail_pitch = 5.08 + rail_name_depth = max([text_width(name, 1.27) for _, name in sides["top"] + sides["bottom"]] + [0]) + half_height = (rows + 1) * side_pitch / 2 + max(0, rail_name_depth + 2.54 - side_pitch) + half_width = max( + 10.16, + max([text_width(v.removesuffix(".net"), 1.27) for v in display_pins.values()] + [1]) + 5.08, + max(len(sides["top"]), len(sides["bottom"])) * rail_pitch / 2 + 2.54, + ) + body = node( + "symbol", + lib_id.split(":")[1] + "_0_1", + node( + "rectangle", + node("start", -half_width, half_height), + node("end", half_width, -half_height), + node("stroke", node("width", 0), node("type", S("default"))), + node("fill", node("type", S("background"))), + ), + ) + positions: list[tuple[str, float, float, float]] = [] + for side, entries in sides.items(): + for i, (number, name) in enumerate(entries): + offset = (i - (len(entries) - 1) / 2) * (side_pitch if side in ("left", "right") else rail_pitch) + if side == "left": + x, y, angle = -half_width - 2.54, offset, 0 + elif side == "right": + x, y, angle = half_width + 2.54, offset, 180 + elif side == "top": + x, y, angle = offset, -half_height - 2.54, 270 + else: + x, y, angle = offset, half_height + 2.54, 90 + body.append( + node( + "pin", + S("passive"), + S("line"), + node("at", x, -y, angle), + node("length", 2.54), + node("name", name, effects()), + node("number", number, effects()), + ) + ) + positions.append((number, x, y, angle)) + return SymbolView( + node("symbol", lib_id, node("in_bom", S("yes")), node("on_board", S("yes")), body), + positions, + lib_id, + ) + + +@dataclass +class _RegionDrawing: + spec: SchematicRegion + placed: list[Placement] + wires: list[Wire] + failed_routes: list[tuple[PinKey, str]] + routing: dict[str, Any] = field(default_factory=dict) + heading_positions: tuple[tuple[str, float, float, float], ...] = () + heading_boxes: tuple[Bounds, ...] = () + route_snapshot: Optional[RouteResult] = None + source_annotations: dict[str, Optional[Point]] = field(default_factory=dict) + + def sheet_offset(self, location: SchematicRegionPlacement) -> Point: + # Translate every route, symbol and pin on the same 0.0001 mm coordinate lattice. + return round(location.x - self.spec.bounds[0], 4), round(location.y - self.spec.bounds[1], 4) + + def sheet_escape(self, key: PinKey, dx: float, dy: float, px: float, py: float, direction: float) -> Point: + if self.route_snapshot is None: + return pin_escape(px, py, direction) + _, _, ex, ey, _ = self.route_snapshot[1][key] + return round(ex + dx, 4), round(ey + dy, 4) + + +@dataclass +class _PreparedBoard: + scope: str + prefix: str + root_id: str + views: dict[str, SymbolView] + pin_nets: dict[PinKey, str] + names: dict[str, str] + regions: dict[str, _RegionDrawing] + net_regions: dict[str, set[str]] = field(default_factory=dict) + circuit_model: Optional[SchematicCircuitModel] = None + + +class KiCadSchematicExporter: + _wires = staticmethod(write_wires) + + def prepare_regions( + self, compiled: CompiledDesign, options: SchematicExportOptions + ) -> tuple[tuple[SchematicRegion, ...], str]: + """Prepare the same measured regions consumed by planning and rendering.""" + boards, fingerprint, _, _ = self._prepare_boards(compiled, options) + return tuple(d.spec for b in boards for d in b.regions.values()), fingerprint + + def _prepare_boards( + self, compiled: CompiledDesign, options: SchematicExportOptions + ) -> tuple[list[_PreparedBoard], str, SymbolResolver, list[SchematicDiagnostic]]: + boards, fingerprint, resolver, diagnostics, prefix = self._prepare_legacy_boards(compiled, options) + boards, fingerprint = self._prepare_led_bucks(boards, fingerprint, prefix, resolver, diagnostics, options) + if not options.optimize_orientations or options.orientation_mode == "half_turn": + return boards, fingerprint, resolver, diagnostics + from .KiCadSchematicOrientation import ( + optimize_passive_orientations, + orientation_metrics, + passive_orientation_rank, + orientation_conflict_identities, + ) + from .KiCadSchematicRouting import optimize_fixed_routes, route_metrics + + # Provisional scene checks do not adopt a plan whose fingerprint belongs + # to the eventual quarter-turn geometry. The public serializer validates + # that requested plan only after the geometry has been selected. + provisional = replace(options, sheet_plan=None, overview=None) + baseline_bundle = self._serialize_prepared(boards, fingerprint, resolver, list(diagnostics), provisional) + candidate_boards, changed_scopes = [], set() + for board in boards: + candidate_board = copy.copy(board) + candidate_board.regions = dict(board.regions) + candidate_boards.append(candidate_board) + for identity, drawing in board.regions.items(): + if drawing.route_snapshot is None: + continue + strategy = drawing.routing.get("selected", "baseline") + router = lambda items, views, nets, strategy=strategy: route_local( + items, views, nets, strategy=strategy + ) + locked = { + c.path + for c, _, _, _ in drawing.placed + if (hint := options.placements.get(c.path)) is not None and hint.lock_rotation + } + placed, route, evidence = optimize_passive_orientations( + drawing.placed, + board.views, + board.pin_nets, + router, + locked=locked, + baseline=drawing.route_snapshot, + source_annotations=drawing.source_annotations, + region_bounds=lambda items, result: self._region_bounds( + items, board.views, board.pin_nets, board.names, result[0], drawing.spec.title + ), + ) + selected = copy.copy(drawing) + selected.routing = copy.deepcopy(drawing.routing) + selected.routing["passive_orientation"] = evidence + candidate_board.regions[identity] = selected + if not evidence["changed"]: + evidence["accepted"] = False + continue + final_route, order_evidence = ( + optimize_fixed_routes(placed, board.views, board.pin_nets, route, route_local) + if options.optimize_routes + else (route, None) + ) + final_metric = orientation_metrics(placed, board.views, board.pin_nets, final_route) + old_metric = orientation_metrics(drawing.placed, board.views, board.pin_nets, drawing.route_snapshot) + old_conflicts = orientation_conflict_identities( + drawing.placed, board.views, board.pin_nets, drawing.route_snapshot + ) + final_conflicts = orientation_conflict_identities(placed, board.views, board.pin_nets, final_route) + bounds, headings, heading_boxes = self._region_geometry( + placed, board.views, board.pin_nets, board.names, final_route[0], drawing.spec.title + ) + w, h = bounds[2] - bounds[0], bounds[3] - bounds[1] + valid = ( + set(final_route[2]) <= set(drawing.failed_routes) + and final_conflicts["escape"] <= old_conflicts["escape"] + and final_conflicts["visual_clearance"] <= old_conflicts["visual_clearance"] + and final_metric["visual_conflicts"] <= old_metric["visual_conflicts"] + and passive_orientation_rank(final_metric) < passive_orientation_rank(old_metric) + and region_fits_page(w, h) + ) + if not valid: + self._rollback_passive(selected, drawing, "final routing or page-fit guard") + continue + selected.placed, selected.wires, selected.failed_routes = placed, final_route[0], final_route[2] + selected.route_snapshot = final_route + selected.spec = replace(drawing.spec, bounds=bounds) + selected.heading_positions, selected.heading_boxes = headings, heading_boxes + evidence.update(accepted=True, after=final_metric) + selected.routing["after"] = route_metrics(final_route[0], final_route[2]) + if order_evidence is not None: + selected.routing["passive_route_order"] = order_evidence + if order_evidence["selected"] != "baseline": + selected.routing["selected"] = order_evidence["selected"] + changed_scopes.add(board.scope) + if changed_scopes: + candidate_fingerprint = self._prepared_fingerprint(prefix, candidate_boards, options) + try: + candidate_bundle = self._serialize_prepared( + candidate_boards, candidate_fingerprint, resolver, list(diagnostics), provisional + ) + old_issues = self._passive_scene_issues(baseline_bundle) + new_issues = self._passive_scene_issues(candidate_bundle) + rejected = { + scope + for scope in changed_scopes + if any( + severity > old_issues.get(scope, {}).get(key, 0) + 1e-7 + for key, severity in new_issues.get(scope, {}).items() + ) + } + except ValueError as error: + rejected = set(changed_scopes) + scene_reason = "serialized candidate could not be planned: " + str(error) + else: + scene_reason = "new blocking serialized scene finding" + for old_board, new_board in zip(boards, candidate_boards): + if old_board.scope in rejected: + for identity, new_drawing in new_board.regions.items(): + if new_drawing.routing.get("passive_orientation", {}).get("accepted"): + self._rollback_passive(new_drawing, old_board.regions[identity], scene_reason) + fingerprint = self._prepared_fingerprint(prefix, candidate_boards, options) + return candidate_boards, fingerprint, resolver, diagnostics + + def _prepare_led_bucks( + self, + boards: list[_PreparedBoard], + fingerprint: str, + prefix: HASH, + resolver: SymbolResolver, + diagnostics: Sequence[SchematicDiagnostic], + options: SchematicExportOptions, + ) -> tuple[list[_PreparedBoard], str]: + """Bounded converter proposals, followed by a cached serialized-scene gate.""" + from .KiCadSchematicPower import led_buck_topology, compare_led_buck_variants + from .KiCadSchematicRouting import optimize_fixed_routes, route_metrics + from .KiCadSchematicOrientation import orientation_metrics, passive_orientation_rank + + bundle = None + provisional = replace(options, sheet_plan=None, overview=None) + for board in boards: + for identity, drawing in list(board.regions.items()): + by_path = {c.path: c for c, _, _, _ in drawing.placed} + topology, reason = led_buck_topology(tuple(sorted(by_path)), by_path, board.views, board.pin_nets) + if topology is None and reason is None: + continue + if any(c.path in options.placements for c in by_path.values()): + drawing.routing["led_buck"] = dict( + accepted=False, reason="authored placements take precedence", route_trials=0, trials=[] + ) + continue + if topology is None: + drawing.routing["led_buck"] = dict(accepted=False, reason=reason, route_trials=0, trials=[]) + continue + if bundle is None: + bundle = self._serialize_prepared(boards, fingerprint, resolver, list(diagnostics), provisional) + strategy = drawing.routing.get("selected", "baseline") + router = lambda items, views, nets, strategy=strategy: route_local( + items, views, nets, strategy=strategy + ) + placed, route, evidence = compare_led_buck_variants( + drawing.placed, + board.views, + board.pin_nets, + cast(RouteResult, drawing.route_snapshot), + router, + source_annotations=drawing.source_annotations, + region_bounds=lambda items, result: self._region_bounds( + items, board.views, board.pin_nets, board.names, result[0], drawing.spec.title + ), + ) + assert evidence is not None # topology was verified above + drawing.routing["led_buck"] = evidence + if not evidence["accepted"]: + continue + final_route, order = ( + optimize_fixed_routes(placed, board.views, board.pin_nets, route, route_local) + if options.optimize_routes + else (route, None) + ) + metric = orientation_metrics(placed, board.views, board.pin_nets, final_route) + if ( + not set(final_route[2]) <= set(drawing.failed_routes) + or metric["visual_conflicts"] > evidence["before"]["visual_conflicts"] + or passive_orientation_rank(metric) >= passive_orientation_rank(evidence["before"]) + ): + final_route, order, metric = route, None, evidence["after"] + bounds, headings, heading_boxes = self._region_geometry( + placed, board.views, board.pin_nets, board.names, final_route[0], drawing.spec.title + ) + content_bounds = bounds + old_width = drawing.spec.bounds[2] - drawing.spec.bounds[0] + old_height = drawing.spec.bounds[3] - drawing.spec.bounds[1] + if bounds[2] - bounds[0] <= old_width and bounds[3] - bounds[1] <= old_height: + # A local improvement must not disturb unrelated circuits' + # established packing. Retain the incumbent's measured cell + # size as explicit whitespace when the new content fits. + # Its origin follows the newly measured content, so no pins, + # wires or authored field coordinates need translating. + bounds = (bounds[0], bounds[1], bounds[0] + old_width, bounds[1] + old_height) + selected = copy.copy(drawing) + selected.routing = copy.deepcopy(drawing.routing) + selected.routing["led_buck"].update( + after=metric, route_order=order, content_bounds=content_bounds, reserved_bounds=bounds + ) + selected.routing["after"] = route_metrics(final_route[0], final_route[2]) + # "baseline" in the additional search means its supplied + # incumbent, which may already use tree_search or another + # strategy. Preserve that strategy for subsequent quarter turns. + selected.routing["selected"] = ( + order["selected"] if order and order["selected"] != "baseline" else strategy + ) + selected.placed, selected.wires, selected.failed_routes = placed, final_route[0], final_route[2] + selected.route_snapshot = final_route + selected.spec = replace(drawing.spec, bounds=bounds) + selected.heading_positions, selected.heading_boxes = headings, heading_boxes + board.regions[identity] = selected + candidate_fingerprint = self._prepared_fingerprint(prefix, boards, options) + rejection = None + try: + candidate_bundle = self._serialize_prepared( + boards, candidate_fingerprint, resolver, list(diagnostics), provisional + ) + old = self._passive_scene_issues(bundle).get(board.scope, {}) + new = self._passive_scene_issues(candidate_bundle).get(board.scope, {}) + scene_changes = [ + dict(identity=list(key), before=old.get(key, 0), after=value) + for key, value in sorted(new.items()) + if value > old.get(key, 0) + 1e-6 + ] + before_pages = sum( + name.endswith(".kicad_sch") and name.startswith(board.prefix) for name in bundle.files + ) + after_pages = sum( + name.endswith(".kicad_sch") and name.startswith(board.prefix) for name in candidate_bundle.files + ) + selected.routing["led_buck"]["scene_gate"] = dict( + before_findings=len(old), + after_findings=len(new), + new_or_worsened=scene_changes, + before_sheets=before_pages, + after_sheets=after_pages, + ) + if after_pages > before_pages: + rejection = "increased schematic sheet fragmentation" + elif scene_changes: + rejection = "new or worsened blocking serialized scene finding" + except ValueError as error: + rejection = "serialized candidate could not be planned: " + str(error) + if rejection: + board.regions[identity] = drawing + evidence.update( + accepted=False, rollback_reason=rejection, attempted_after=metric, after=evidence["before"] + ) + evidence["scene_gate"] = selected.routing["led_buck"].get("scene_gate") + else: + bundle, fingerprint = candidate_bundle, candidate_fingerprint + return boards, fingerprint + + @staticmethod + def _rollback_passive(candidate: _RegionDrawing, baseline: _RegionDrawing, reason: str) -> None: + evidence = candidate.routing["passive_orientation"] + evidence.update( + accepted=False, + rollback_reason=reason, + final_rotations={c.path: angle for c, _, _, angle in baseline.placed}, + ) + evidence["attempted_after"] = evidence["after"] + evidence["after"] = evidence["before"] + candidate.placed, candidate.wires, candidate.failed_routes = ( + baseline.placed, + baseline.wires, + baseline.failed_routes, + ) + candidate.route_snapshot, candidate.spec = baseline.route_snapshot, baseline.spec + candidate.heading_positions, candidate.heading_boxes = baseline.heading_positions, baseline.heading_boxes + candidate.routing = copy.deepcopy(baseline.routing) + candidate.routing["passive_orientation"] = evidence + + @staticmethod + def _passive_scene_issues(bundle: SchematicExport) -> dict[str, dict[tuple[str, ...], float]]: + """Compare actual serialized contacts, including existing bad labels. + + A label UUID alone cannot distinguish its old overlap from a new body + contact. Stable collider identities and overlap area detect both new + contacts and worsening existing ones. Wire indices are not identities. + """ + from .KiCadSchematicReadability import text_item, SceneText + from .KiCadSchematicScene import pin_name_items, pin_number_items, instance_property_at + + manifest = json.loads(bundle.files["manifest.json"]) + scopes = {Path(b["root"]).stem: b["scope"] for b in manifest["boards"]} + result: dict[str, dict[tuple[str, ...], float]] = {} + sheet_scopes: dict[str, str] = {} + + def scope_for(filename: str) -> str: + return str(next(scope for prefix, scope in scopes.items() if filename.startswith(prefix))) + + def area(a: Bounds, b: Bounds) -> float: + return max(0, min(a[2], b[2]) - max(a[0], b[0]) + 0.25) * max(0, min(a[3], b[3]) - max(a[1], b[1]) + 0.25) + + for filename, content in bundle.files.items(): + if filename.endswith(".kicad_sch"): + doc = sexpdata.loads(content) + scope = scope_for(filename) + sheet_scopes[children(doc, "uuid")[0][1]] = scope + issues = result.setdefault(scope, {}) + definitions = {d[1]: d for lib in children(doc, "lib_symbols") for d in children(lib, "symbol")} + texts: list[SceneText] = [] + bodies: list[tuple[str, Bounds]] = [] + for symbol in children(doc, "symbol"): + at = children(symbol, "at")[0] + props = {p[1]: p for p in children(symbol, "property")} + owner = props["PBPath"][2] if "PBPath" in props else children(symbol, "uuid")[0][1] + lib_id = children(symbol, "lib_id")[0][1] + definition = definitions.get(lib_id) + if definition is not None: + x1, y1, x2, y2 = graphic_bounds(SymbolView(definition, [], lib_id), int(at[3]), False) + bodies.append((owner, (at[1] + x1, at[2] + y1, at[1] + x2, at[2] + y2))) + texts.extend( + SceneText(**item) + for item in ( + pin_name_items(definition, at[1], at[2], at[3], owner) + + pin_number_items(definition, at[1], at[2], at[3], owner) + ) + ) + for name, prop in props.items(): + positions, effects_nodes = children(prop, "at"), children(prop, "effects") + if positions and effects_nodes: + field_text = text_item( + owner + ":" + name, + prop[2], + instance_property_at(positions[0], at), + effects_nodes[0], + owner, + "field", + ) + if field_text is not None: + texts.append(field_text) + for kind in ("text", "label", "global_label"): + for item in children(doc, kind): + positions, effects_nodes = children(item, "at"), children(item, "effects") + if positions and effects_nodes: + text = text_item( + children(item, "uuid")[0][1], item[1], positions[0], effects_nodes[0], "", kind + ) + if text is not None: + texts.append(text) + for index, text in enumerate(texts): + for owner, box in bodies: + # Pin text is intentionally inside its own symbol. + if text.owner == owner and text.kind.startswith("pin_"): + continue + severity = area(text.bounds, box) + if severity: + key: tuple[str, ...] = ("text_body_contact", text.identity, owner) + issues[key] = max(issues.get(key, 0), severity) + for other in texts[index + 1 :]: + severity = area(text.bounds, other.bounds) + if severity: + key = ("text_contact", *sorted((text.identity, other.identity))) + issues[key] = max(issues.get(key, 0), severity) + # Quantify crossings too: an already affected text UUID + # must not whitelist another or longer wire through it. + spans: dict[tuple[int, float], list[tuple[float, float]]] = {} + for wire in children(doc, "wire"): + points = [tuple(p[1:3]) for pts in children(wire, "pts") for p in children(pts, "xy")] + if len(points) != 2: + continue + a, b = points + x1, y1, x2, y2 = text.bounds + axis = 1 if a[0] == b[0] else 0 + fixed = a[1 - axis] + low, high = (y1 + 0.3, y2 - 0.3) if axis else (x1 + 0.3, x2 - 0.3) + inside = x1 + 0.3 < fixed < x2 - 0.3 if axis else y1 + 0.3 < fixed < y2 - 0.3 + lo, hi = max(min(a[axis], b[axis]), low), min(max(a[axis], b[axis]), high) + if inside and hi > lo: + spans.setdefault((axis, fixed), []).append((lo, hi)) + length = 0.0 + for intervals in spans.values(): + merged: list[tuple[float, float]] = [] + for lo, hi in sorted(intervals): + if merged and lo <= merged[-1][1]: + merged[-1] = (merged[-1][0], max(hi, merged[-1][1])) + else: + merged.append((lo, hi)) + length += sum(hi - lo for lo, hi in merged) + if length: + issues["text_wire_contact", text.identity] = length + for entry in json.loads(bundle.files["layout.json"])["label_placement"]: + issues = result.setdefault(sheet_scopes[entry["sheet"]], {}) + issues.update({("label_collision", item["identity"]): 1 for item in entry["conflicts"]}) + issues.update({("unresolved_anchor", item["identity"]): 1 for item in entry["unresolved_anchors"]}) + for finding in json.loads(bundle.files["readability.json"])["findings"]: + if finding["code"] not in ("text_collision", "text_outside_page", "wire_through_text"): + continue + objects = tuple(o for o in finding["objects"] if not o.startswith("wire:")) + result.setdefault(scope_for(finding["sheet"]), {})[(finding["code"],) + objects] = 1 + return result + + def _prepare_legacy_boards( + self, compiled: CompiledDesign, options: SchematicExportOptions + ) -> tuple[list[_PreparedBoard], str, SymbolResolver, list[SchematicDiagnostic], HASH]: + presentation = options.presentation or SchematicPresentation() + if not isinstance(presentation, SchematicPresentation): + raise ValueError("presentation must be a SchematicPresentation") + presentation = SchematicPresentation.from_dict(presentation.to_dict()) + if options.overview is not None and not isinstance(options.overview, SchematicOverview): + raise ValueError("overview must be a SchematicOverview") + if compiled.errors: + raise ValueError("cannot export a design with compilation errors") + scopes = NetlistTransform(compiled).run() + # Hash canonical solved physical state, not compiler source-location metadata: + # the latter contains machine-specific Python paths and line numbers. + digest = hashlib.sha256(VERSION.encode()) + digest.update(options.source.encode("utf-8")) + for scope, netlist in sorted(scopes.items(), key=lambda entry: str(entry[0])): + resolved: dict[str, Any] = { + "scope": str(scope), + "blocks": [ + list(b[:4]) + + [ + str(b.full_path), + [cls.target.name for cls in b.path_classes], + compiled.get_value(b.full_path.to_tuple() + ("fp_pinning",)), + compiled.get_value(b.full_path.to_tuple() + ("sch_symbol",)) + or compiled.get_value(b.full_path.to_tuple() + ("sch_symbol_default",)), + ] + for b in sorted(netlist.blocks, key=lambda b: str(b.full_path)) + ], + "nets": [(n.name, sorted((str(p.block_path), p.pin_name) for p in n.pins)) for n in netlist.nets], + } + digest.update(json.dumps(resolved, sort_keys=True, ensure_ascii=False).encode("utf-8")) + fingerprint = digest.hexdigest() + directories = list(options.symbol_library_dirs) + env = os.environ.get(f"KICAD{options.kicad_major}_SYMBOL_DIR") + if env: + directories.append(env) + resolver = SymbolResolver(directories) + boards = [] + all_hints = set(options.placements) + known_paths = {str(b.full_path) for n in scopes.values() for b in n.blocks} + if all_hints - known_paths: + raise ValueError( + "schematic placement references missing components: " + str(sorted(all_hints - known_paths)) + ) + presentation.validate( + { + str(b.full_path): dict( + (number, port) + for number, port in ( + v.split("=", 1) + for v in cast(list[str], compiled.get_value(b.full_path.to_tuple() + ("fp_pinning",))) + ) + ) + for n in scopes.values() + for b in n.blocks + } + ) + used_groups = set() + diagnostics: List[SchematicDiagnostic] = [] + for scope, netlist in scopes.items(): + scope_name = str(scope) + prefix = "board_" + uid(options.design_name, scope_name) + root_id = uid(prefix, "root") + components = [] + blocks_by_path = {str(block.full_path): block for block in netlist.blocks} + classes_by_path = { + path: [c.target.name for c in block.path_classes] for path, block in blocks_by_path.items() + } + for block in netlist.blocks: + path = str(block.full_path) + raw = cast(list[str], compiled.get_value(block.full_path.to_tuple() + ("fp_pinning",))) + pins = {number: port for number, port in (v.split("=", 1) for v in raw)} + mapping_raw = cast(Optional[str], compiled.get_value(block.full_path.to_tuple() + ("sch_symbol",))) + mapping_source = "explicit" + if mapping_raw is None: + mapping_raw = cast( + Optional[str], compiled.get_value(block.full_path.to_tuple() + ("sch_symbol_default",)) + ) + mapping_source = "footprint_default" if mapping_raw else "registry" + relative = block.full_path.blocks[len(scope.blocks) :] + group = relative[0] if relative else "Board-level components" + if not pins and ("MountingHole" in block.footprint or "ToolingHole" in block.footprint): + group = "Mechanical notes" + components.append( + PhysicalComponent( + path, + block.refdes, + block.footprint, + block.value, + pins, + json.loads(mapping_raw) if mapping_raw else None, + group, + ) + ) + component = components[-1] + component.hierarchy = tuple( + (".".join(block.full_path.blocks[: i + 1]), cls.target.name) + for i, cls in enumerate(block.path_classes) + ) + component.display_value = self._display_value(compiled, block, component.mapping) + component.symbol_coverage = dict( + component=path, + refdes=component.refdes, + compiled_class=block.path_classes[-1].target.name if block.path_classes else "", + mapping_source=mapping_source, + ) + if component.mapping is None: + component.mapping = infer_symbol( + component, classes_by_path[path], block.part, resolver, component.symbol_coverage + ) + for component in components: + entry = presentation.components.get(component.path, {}) + component.presentation_pin_roles = { + boundary["pin"]: boundary["role"] + for circuit in presentation.circuits + for boundary in circuit.get("boundaries", ()) + if boundary["component"] == component.path + } + if entry.get("display_value"): + component.display_value = entry["display_value"] + classes = classes_by_path[component.path] + physical_block = blocks_by_path[component.path] + connector_length = compiled.get_value(physical_block.full_path.to_tuple() + ("length",)) + inferred_names = infer_pin_names(component, classes, connector_length) + if inferred_names: + component.mapping = dict(component.mapping or {}) + component.mapping["pin_names"] = dict(inferred_names, **component.mapping.get("pin_names", {})) + description = infer_description(component, classes, connector_length) + component.descriptions = presentation.descriptions(component.path) or ( + (description,) if description else () + ) + if entry.get("pin_names"): + component.mapping = dict(component.mapping or {}) + component.mapping["pin_names"] = dict( + (component.mapping or {}).get("pin_names", {}), + **entry["pin_names"], + ) + views = {} + for component in components: + composite = resistor_array_symbol(component, classes_by_path[component.path]) + if composite is not None: + views[component.path] = SymbolView(*composite) + component.symbol_coverage.update( + status="resolved", category="composite", lib_id=views[component.path].lib_id + ) + continue + try: + if not (component.mapping or {}).get("lib_id"): + raise LookupError("no schematic symbol mapping") + views[component.path] = resolver.resolve(component) + component.symbol_coverage.update( + status="resolved", category="library_symbol", lib_id=(component.mapping or {})["lib_id"] + ) + except (LookupError, FileNotFoundError) as error: + coverage = component.symbol_coverage + category = ( + "missing_library" + if isinstance(error, FileNotFoundError) + else ( + "unsupported_multi_unit" + if str(error) == "multi-unit symbol unsupported" + else ( + "unsupported_symbol" + if str(error) == "stacked or repeated symbol pins unsupported" + else "missing_symbol" if isinstance(error, KeyError) else "missing_mapping" + ) + ) + ) + # Registry lookup may already have identified an unavailable + # library before returning None. Preserve that exact reason. + coverage.update( + status="fallback", + category=coverage.get("category", category), + reason=coverage.get("reason", str(error)), + ) + if (component.mapping or {}).get("lib_id"): + coverage["lib_id"] = (component.mapping or {})["lib_id"] + diagnostics.append(SchematicDiagnostic(component.path, str(coverage["reason"]))) + views[component.path] = generic(component) + for component in components: + view = views[component.path] + for body in children(view.definition, "symbol"): + for pin in children(body, "pin"): + number = str(children(pin, "number")[0][1]) + name = (component.mapping or {}).get("pin_names", {}).get(number) + if name: + children(pin, "name")[0][1] = name + hint = options.placements.get(component.path) + if hint: + component.annotation = hint.annotation + if hint.flip_horizontal: + view = views[component.path] + definition = copy.deepcopy(view.definition) + + def reflect(tree: object) -> None: + if isinstance(tree, list) and tree: + if ( + str(tree[0]) in ("at", "start", "mid", "end", "xy", "center") + and len(tree) >= 3 + and isinstance(tree[1], (float, int)) + ): + tree[1] = -tree[1] + if str(tree[0]) == "at" and len(tree) >= 4: + tree[3] = (180 - tree[3]) % 360 + for child in tree: + reflect(child) + + reflect(definition) + reflected_id = view.lib_id + "_reflected" + definition[1] = reflected_id + for body in children(definition, "symbol"): + match = re.search(r"_(\d+_\d+)$", body[1]) + if match: + body[1] = reflected_id.split(":", 1)[1] + "_" + match[1] + views[component.path] = SymbolView( + definition, + [(n, -x, y, (180 - angle) % 360) for n, x, y, angle in view.pins], + reflected_id, + ) + pin_nets = {(str(p.block_path), p.pin_name): n.name for n in netlist.nets for p in n.pins} + from .KiCadSchematicCircuits import build_circuits + + circuit_model = build_circuits(components, pin_nets, views, presentation) + for diagnostic in circuit_model.diagnostics: + diagnostics.append(SchematicDiagnostic(scope_name, str(diagnostic))) + by_component = {path: circuit for circuit in circuit_model.circuits for path in circuit.components} + for component in components: + component.circuit_model = circuit_model + component.functional_circuit = by_component.get(component.path) + from .KiCadSchematicLabels import readable_labels + + names = readable_labels(n.name for n in netlist.nets) + ground_nets = {n.name for n in netlist.nets if n.name.lower().split(".")[-1] == "gnd"} + for component in components: + component.ground_net_labels = ( + { + number: names[net] + for number in component.pins + if (net := pin_nets.get((component.path, number))) in ground_nets + } + if len(ground_nets) > 1 + else {} + ) + component.net_labels = { + number: names[pin_nets[(component.path, number)]] + for number in component.pins + if (component.path, number) in pin_nets + } + regroup(components, pin_nets, views) + for component in components: + circuit = component.functional_circuit + if circuit is not None and circuit.provenance == "explicit": + component.group = circuit.title + hint = options.placements.get(component.path) + if hint: + if hint.rotation not in (0, 90, 180, 270): + raise ValueError("schematic rotation must be orthogonal") + if not all(math.isfinite(v) for v in (hint.x, hint.y)): + raise ValueError("schematic coordinates must be finite") + if hint.annotation and not all(math.isfinite(v) for v in hint.annotation): + raise ValueError("schematic annotations must be finite") + component.group = hint.group + + for component in components: + selector = component.group + if selector in presentation.groups: + component.group = presentation.groups[selector] + used_groups.add(selector) + board = _PreparedBoard(scope_name, prefix, root_id, views, pin_nets, names, {}) + board.circuit_model = circuit_model + for group in sorted({c.group for c in components}): + members = [c for c in components if c.group == group] + hints = [options.placements.get(c.path) for c in members] + hinted = any(hints) + if hinted: + if not all(hints): + raise ValueError("all members of hinted group require placements: " + group) + batches: list[list[Placement]] = [ + [(c, h.x, h.y, h.rotation) for c, h in zip(members, cast(list[SchematicPlacement], hints))] + ] + elif group == "Mechanical notes": + batches = [[(c, 40 + (i % 9) * 35, 220 + (i // 9) * 25, 0) for i, c in enumerate(members)]] + else: + batches = place_group(members, views, pin_nets, optimize_orientations=options.optimize_orientations) + pending = list(batches) + part = 0 + while pending: + # Quantize origins before combining them with pin offsets or page translations. + source_placed = [(c, round(x, 4), round(y, 4), angle) for c, x, y, angle in pending.pop(0)] + placed = freeze_annotations(source_placed, views) + baseline = route_local(placed, views, pin_nets) + orientation = None + bridge_comparison = None + if options.optimize_orientations: + from .KiCadSchematicOrientation import optimize_orientations + + rotation_locks = { + c.path + for c, _, _, _ in source_placed + if (hint := options.placements.get(c.path)) is not None and hint.lock_rotation + } + placed, baseline, orientation = optimize_orientations( + source_placed, + views, + pin_nets, + route_local, + locked=rotation_locks, + baseline=baseline, + region_bounds=lambda items, route: self._region_bounds( + items, views, pin_nets, names, route[0], group + ), + ) + if options.optimize_orientations and not hinted: + from .KiCadSchematicPower import compare_bridge_variants + + placed, baseline, bridge_comparison = compare_bridge_variants( + placed, + views, + pin_nets, + baseline, + route_local, + region_bounds=lambda items, route: self._region_bounds( + items, views, pin_nets, names, route[0], group + ), + source_annotations={c.path: getattr(c, "annotation", None) for c, _, _, _ in source_placed}, + ) + from .KiCadSchematicRouting import optimize_fixed_routes, route_metrics + + if options.optimize_routes: + routed, routing = optimize_fixed_routes(placed, views, pin_nets, baseline, route_local) + else: + routed = baseline + metric = route_metrics(baseline[0], baseline[2]) + routing = dict(before=metric, after=metric, selected="baseline", candidates=1) + if orientation is not None: + routing["orientation"] = orientation + if bridge_comparison is not None: + routing["bridge_comparison"] = bridge_comparison + wires, _, failed = routed + # Measure the selected route so detours reserve their actual packing area. + bounds = self._region_bounds(placed, views, pin_nets, names, wires, group) + width, height = bounds[2] - bounds[0], bounds[3] - bounds[1] + if routed is not baseline and not region_fits_page(width, height): + original = self._region_bounds(placed, views, pin_nets, names, baseline[0], group) + original_width, original_height = original[2] - original[0], original[3] - original[1] + if region_fits_page(original_width, original_height): + routing["rejected_for_page_fit"] = routing["selected"] + routing["selected"] = "baseline" + routing["after"] = routing["before"] + routed = baseline + wires, _, failed = baseline + bounds, width, height = original, original_width, original_height + if not region_fits_page(width, height) and len(placed) > 1 and not hinted: + subsets = split_group(placed, views, pin_nets) + if subsets is None: + raise ValueError( + f"indivisible functional region exceeds A3: {group} ({width:.1f} x {height:.1f} mm); components: " + + ", ".join(c.path for c, _, _, _ in placed) + ) + # Repacking must resolve automatic fields afresh at the + # new placement, not retain this rejected region's fields. + originals = {c.path: c for c, _, _, _ in source_placed} + for subset in subsets: + pending.extend( + place_group( + [originals[c.path] for c, _, _, _ in subset], + views, + pin_nets, + optimize_orientations=options.optimize_orientations, + ) + ) + diagnostics.append( + SchematicDiagnostic( + group, + "continuation: measured circuit region requires functional continuation", + ) + ) + continue + if not region_fits_page(width, height): + raise ValueError( + f"region {group!r} ({width:.1f} x {height:.1f} mm) exceeds A3; revise presentation without shrinking text" + ) + part += 1 + title = group if part == 1 else group + " /" + str(part) + # Identify the actual repeated-channel indices on this sheet. + match = re.fullmatch(r"(.+)\[0\]", group) + if match and not hinted: + prefix = (scope_name + "." if scope_name != "(root)" else "") + match.group(1) + indices = set() + for component, _, _, _ in placed: + item = re.match(re.escape(prefix) + r"\[(\d+)\](?:\.|$)", component.path) + if item: + indices.add(int(item.group(1))) + if indices: + title = match.group(1) + "[" + ",".join(str(i) for i in sorted(indices)) + "]" + + identity = json.dumps( + [scope_name, group, part], + ensure_ascii=False, + separators=(",", ":"), + ) + spec = SchematicRegion( + identity, + title, + scope_name, + tuple(c.path for c, _, _, _ in placed), + bounds, + kind=( + "mechanical" + if group == "Mechanical notes" and all(not c.pins for c in members) + else "circuit" + ), + ) + rendered_heading = self._region_heading_lines(title, placed) + if len(rendered_heading) == len(textwrap.wrap(title, 42) or [""]): + # Retain existing automatic geometry even when the final + # channel/continuation title differs from its group key. + headings = tuple( + (line, size, bounds[0] + 3, bounds[1] + 3 + i * 2.54) + for i, (line, size) in enumerate(rendered_heading) + ) + heading_boxes: tuple[Bounds, ...] = ( + (bounds[0], bounds[1], bounds[2], bounds[1] + 5 + 2.54 * len(rendered_heading)), + ) + else: + _, headings, heading_boxes = self._region_geometry( + placed, + views, + pin_nets, + names, + wires, + title, + ) + board.regions[identity] = _RegionDrawing( + spec, + placed, + wires, + failed, + routing, + headings, + heading_boxes, + routed, + {c.path: c.annotation for c, _, _, _ in source_placed}, + ) + if not board.regions: + spec = SchematicRegion( + scope_name + "::Empty design", + "Empty design", + scope_name, + (), + (0, 0, 50, 10), + kind="empty", + ) + board.regions[spec.id] = _RegionDrawing(spec, [], [], []) + rendered = [c.path for drawing in board.regions.values() for c, _, _, _ in drawing.placed] + if ( + len(rendered) != len(components) + or set(rendered) != {c.path for c in components} + or len(set(rendered)) != len(rendered) + ): + raise ValueError("prepared schematic regions must contain each physical component exactly once") + for identity, drawing in board.regions.items(): + for c, _, _, _ in drawing.placed: + for pin_number in c.pins: + net = pin_nets.get((c.path, pin_number)) + if net is not None: + board.net_regions.setdefault(net, set()).add(identity) + boards.append(board) + if set(presentation.groups) - used_groups: + raise ValueError( + "presentation references unknown groups: " + str(sorted(set(presentation.groups) - used_groups)) + ) + digest.update(json.dumps(presentation.to_dict(), sort_keys=True, ensure_ascii=False).encode("utf-8")) + return boards, self._prepared_fingerprint(digest, boards, options), resolver, diagnostics, digest + + @staticmethod + def _prepared_fingerprint(prefix: HASH, boards: Sequence[_PreparedBoard], options: SchematicExportOptions) -> str: + digest = prefix.copy() + # Bind plans to solved electrical state AND actual symbol/layout geometry. + # Library, hint or source changes cannot silently reuse an old packing plan. + geometry = [ + dict( + scope=b.scope, + regions=[d.spec.to_dict() for d in b.regions.values()], + placed=[ + (c.path, x, y, a, c.annotation, c.display_value) + for d in b.regions.values() + for c, x, y, a in d.placed + ], + symbols={k: sexpdata.dumps(v.definition) for k, v in sorted(b.views.items())}, + ) + for b in boards + ] + digest.update( + json.dumps( + options.overview.to_dict() if options.overview is not None else None, + sort_keys=True, + ensure_ascii=False, + ).encode("utf-8") + ) + digest.update(json.dumps(geometry, sort_keys=True, ensure_ascii=False, allow_nan=False).encode("utf-8")) + return digest.hexdigest() + + @staticmethod + def _region_heading_lines(title: str, placed: Placements) -> list[tuple[str, float]]: + lines = [(line, 1.5) for line in (textwrap.wrap(title, 42) or [""])] + members = {c.path: c for c, _, _, _ in placed} + circuits = { + circuit.id: circuit + for c in members.values() + if (circuit := cast("Optional[SchematicCircuit]", getattr(c, "functional_circuit", None))) is not None + and circuit.provenance == "explicit" + } + for circuit in sorted(circuits.values(), key=lambda c: c.id): + lines.extend((line, 1.1) for line in textwrap.wrap(circuit.summary, 52)) + for boundary in circuit.boundaries: + if boundary.component in members: + component = members[boundary.component] + label = component.net_labels.get(boundary.pin, "unconnected") + note = f"{boundary.name}: {component.refdes}.{boundary.pin} [{label}]" + lines.extend((line, 1.1) for line in textwrap.wrap(note, 52)) + return lines + + @staticmethod + def _region_bounds( + placed: Placements, + views: Views, + pin_nets: PinNets, + names: Mapping[str, str], + wires: Sequence[Wire], + title: str = "", + ) -> Bounds: + return KiCadSchematicExporter._region_geometry( + placed, + views, + pin_nets, + names, + wires, + title, + )[0] + + @staticmethod + def _region_geometry( + placed: Placements, + views: Views, + pin_nets: PinNets, + names: Mapping[str, str], + wires: Sequence[Wire], + title: str = "", + ) -> tuple[Bounds, tuple[tuple[str, float, float, float], ...], tuple[Bounds, ...]]: + """Measure circuit and explanatory notes with one shared layout. + + Ordinary headings retain their historical geometry. When authored notes + would overflow the usable A3 height, a measured right-hand column may + preserve the complete circuit without shrinking or dropping any text. + """ + points: list[Point] = [] + for c, x, y, angle in placed: + xmin, ymin, xmax, ymax = graphic_bounds(views[c.path], angle) + points.extend(((x + xmin, y + ymin), (x + xmax, y + ymax))) + tx, ty, align = annotation_position(c, views[c.path], x, y, angle) + ax1, ay1, ax2, ay2 = annotation_bounds(c, tx, ty, angle) + points.extend(((ax1, ay1), (ax2, ay2))) + connector_labels = [] + for number, px, py, direction in positioned_pins(views[c.path], x, y, angle): + net = pin_nets.get((c.path, number)) + if net is None: + continue + ex, ey = pin_escape(px, py, direction) + if net.lower().split(".")[-1] == "gnd": + gx1, gy1, gx2, gy2 = ground_bounds( + ex, + ey, + direction, + c.ground_net_labels.get(number, ""), + ) + points.extend(((gx1, gy1), (gx2, gy2))) + continue + bounds = pin_label_bounds(names[net], ex, ey, direction) + points.extend(((bounds[0], bounds[1]), (bounds[2], bounds[3]))) + if views[c.path].lib_id.startswith("Connector") and direction in (0, 180): + connector_labels.append((direction, bounds, names[net])) + # Dense connector pin rows can mix local text and outlined global + # labels. Reserve an outer lane only when their measured boxes + # conflict, so the final scene can stagger them without clipping. + from .KiCadSchematicScene import overlap + + for direction, bounds, name in connector_labels: + if any( + other_direction == direction and other_bounds != bounds and overlap(bounds, other_bounds) + for other_direction, other_bounds, _ in connector_labels + ): + extra = math.ceil((text_width(name, 1.27) + 5.08) / 2.54) * 2.54 + side = bounds[0] - extra if direction == 0 else bounds[2] + extra + points.append((side, bounds[1])) + for _, a, b in wires: + points.extend((a, b)) + if not points: + return (0, 0, 50, 10), (), () + measured = KiCadSchematicExporter._region_heading_lines(title + " /999", placed) + rendered = KiCadSchematicExporter._region_heading_lines(title, placed) + title_count = len(textwrap.wrap(title, 42) or [""]) + measured_title_count = len(textwrap.wrap(title + " /999", 42) or [""]) + notes = rendered[title_count:] + xmin = min(p[0] for p in points) - 3 + bottom = max(p[1] for p in points) + 3 + + def top_layout( + lines: Sequence[tuple[str, float]], reserved: Sequence[tuple[str, float]], header_gap: float = 6 + ) -> tuple[Bounds, tuple[tuple[str, float, float, float], ...], tuple[Bounds, ...]]: + ymin = min(p[1] for p in points) - (header_gap + len(reserved) * 2.54) + xmax = max(max(p[0] for p in points) + 3, xmin + max(text_width(line, size) for line, size in reserved) + 6) + bounds: Bounds = (round(xmin, 4), round(ymin, 4), round(xmax, 4), round(bottom, 4)) + headings = tuple((line, size, xmin + 3, ymin + 3 + i * 2.54) for i, (line, size) in enumerate(lines)) + boxes = ((xmin, ymin, xmax, ymin + 5 + 2.54 * len(lines)),) + return bounds, headings, boxes + + def fits(bounds: Bounds) -> bool: + width, height = bounds[2] - bounds[0], bounds[3] - bounds[1] + return region_fits_page(width, height) + + top = top_layout(rendered, measured) + if not notes or fits(top[0]): + return top + # Keep the original title above the circuit. The notes occupy their own + # obstacle column with measured padding and the same font/line spacing. + for header_gap in (6, 4.73, 3): + body = top_layout(rendered[:title_count], measured[:measured_title_count], header_gap) + body_bounds, body_headings, body_boxes = body + # Compact only whitespace; keep at least one grid of clearance + # below the title glyphs, above the measured circuit content. + if max(y + size / 2 for _, size, _, y in body_headings) > min(p[1] for p in points) - 1.27: + continue + column_x = body_bounds[2] + 5.08 + column_width = max(text_width(line, size) for line, size in notes) + 6 + column_bottom = body_bounds[1] + 6 + len(notes) * 2.54 + side_bounds = (body_bounds[0], body_bounds[1], column_x + column_width, max(body_bounds[3], column_bottom)) + if not fits(side_bounds): + continue + note_positions = tuple( + (line, size, column_x + 3, body_bounds[1] + 3 + i * 2.54) for i, (line, size) in enumerate(notes) + ) + note_box = (column_x, body_bounds[1], column_x + column_width, column_bottom) + return ( + cast(Bounds, tuple(round(v, 4) for v in side_bounds)), + body_headings + note_positions, + body_boxes + (note_box,), + ) + return top + + def _plan_compiled(self, compiled: CompiledDesign, options: SchematicExportOptions) -> SchematicSheetPlan: + boards, fingerprint, _, _ = self._prepare_boards(compiled, options) + return self._plan_prepared(boards, fingerprint, options) + + @staticmethod + def _plan_prepared( + boards: Sequence[_PreparedBoard], fingerprint: str, options: SchematicExportOptions + ) -> SchematicSheetPlan: + regions = tuple(d.spec for b in boards for d in b.regions.values()) + adjacency: dict[tuple[str, str], float] = {} + for b in boards: + for net, identities in b.net_regions.items(): + if KiCadSchematicExporter._is_backbone(net) or len(identities) > 8: + continue + for a in sorted(identities): + for other in sorted(identities): + if a < other: + adjacency[(a, other)] = adjacency.get((a, other), 0) + 1 + return SchematicSheetPlanner().plan_regions( + regions, + fingerprint, + assignments=options.sheet_assignments, + requested=options.sheet_plan, + adjacency=adjacency, + ) + + def overview(self, compiled: CompiledDesign, options: SchematicExportOptions) -> dict[str, Any]: + """Preview the same compiled, witnessed functional overview emitted by export.""" + boards, fingerprint, _, _ = self._prepare_boards(compiled, options) + plan = self._plan_prepared(boards, fingerprint, options) + return build_overviews(boards, plan, options.overview) + + def layout(self, compiled: CompiledDesign, options: SchematicExportOptions) -> dict[str, Any]: + """Return deterministic native layout evidence from the exported artifact.""" + return cast(dict[str, Any], json.loads(self.export(compiled, options).files["layout.json"])) + + def readability(self, compiled: CompiledDesign, options: SchematicExportOptions) -> dict[str, Any]: + return cast(dict[str, Any], json.loads(self.export(compiled, options).files["readability.json"])) + + def export(self, compiled: CompiledDesign, options: SchematicExportOptions) -> SchematicExport: + boards, fingerprint, resolver, diagnostics = self._prepare_boards(compiled, options) + return self._serialize_prepared(boards, fingerprint, resolver, list(diagnostics), options) + + def _serialize_prepared( + self, + boards: Sequence[_PreparedBoard], + fingerprint: str, + resolver: SymbolResolver, + diagnostics: list[SchematicDiagnostic], + options: SchematicExportOptions, + ) -> SchematicExport: + plan = self._plan_prepared(boards, fingerprint, options) + overview_data = build_overviews(boards, plan, options.overview) + files = {} + board_records = [] + label_evidence = [] + for board in boards: + sheets = [s for s in plan.sheets if s.scope == board.scope] + if not sheets: + raise ValueError("sheet plan omitted board scope: " + board.scope) + overview = next((s for s in sheets if s.id == "overview"), None) + content = [s for s in sheets if s.id != "overview"] + root_sheet = overview or (content[0] if len(content) == 1 else None) + if root_sheet is None: + raise ValueError("multiple sheets require an overview") + root_title = root_sheet.title if board.scope in ("", "(root)") else board.scope + " / " + root_sheet.title + root = self._document(board.root_id, options, fingerprint, root_title) + root.append(node("sheet_instances", node("path", "/", node("page", "1")))) + root_filename = board.prefix + ".kicad_sch" + board_records.append(dict(scope=board.scope, root=root_filename)) + index_docs = {} + net_pages: dict[str, set[str]] = {} + for sheet in sheets: + for location in sheet.regions: + drawing = board.regions[location.region_id] + for c, _, _, _ in drawing.placed: + for pin in c.pins: + net = board.pin_nets.get((c.path, pin)) + if net is not None: + net_pages.setdefault(net, set()).add(sheet.id) + for number, sheet in enumerate(sheets): + is_root = sheet.id == root_sheet.id + sheet_id = board.root_id if is_root else uid(board.prefix, sheet.id) + parent_path = "/" + board.root_id + child_index = content.index(sheet) if not is_root else -1 + if not is_root and len(content) > 40: + bucket = child_index // 40 + index_id = uid(board.prefix, "contents", str(bucket)) + parent_path += "/" + index_id + if bucket not in index_docs: + index_docs[bucket] = self._document(index_id, options, fingerprint, f"Contents {bucket + 1}") + index_docs[bucket].append(node("lib_symbols")) + instance_path = "/" + board.root_id if is_root else parent_path + "/" + sheet_id + doc = root if is_root else self._document(sheet_id, options, fingerprint, sheet.title) + definitions = {} + for location in sheet.regions: + for c, _, _, _ in board.regions[location.region_id].placed: + definitions[board.views[c.path].lib_id] = board.views[c.path].definition + try: + ground = ground_symbol(resolver, options.ground_style) + definitions["power:GND"] = ground + except (LookupError, FileNotFoundError): + ground = None + doc.append(node("lib_symbols", *[definitions[k] for k in sorted(definitions)])) + ground_positions: set[Point] = set() + sheet_segments = [] + pin_stubs: dict[Wire, str] = {} + for location in sheet.regions: + sheet_segments.extend( + self._render_region( + doc, + board, + board.regions[location.region_id], + location, + sheet_id, + instance_path, + net_pages, + ground, + ground_positions, + diagnostics, + pin_stubs, + ) + ) + self._inter_region_wires(doc, board, sheet, sheet_id, sheet_segments) + from .KiCadSchematicScene import place_document_labels + + evidence = place_document_labels(doc, sheet_segments, sheet_id, pin_stubs) + label_evidence.append(evidence) + for unknown in evidence["unresolved_anchors"]: + diagnostics.append( + SchematicDiagnostic( + unknown["identity"], "label anchor missing or ambiguous on sheet " + sheet.title + ) + ) + for conflict in evidence["conflicts"]: + diagnostics.append( + SchematicDiagnostic( + conflict["identity"], + "label collision on sheet " + sheet.title + ": " + json.dumps(conflict, sort_keys=True), + ) + ) + if is_root: + continue + filename = board.prefix + "_" + uid(sheet.id)[:12] + ".kicad_sch" + files[filename] = sexpdata.dumps(doc) + "\n" + parent_doc = index_docs[child_index // 40] if len(content) > 40 else root + slot = child_index % 40 + self._sheet_link( + parent_doc, + board.prefix, + sheet_id, + parent_path, + sheet.title, + filename, + 20 + (slot // 10) * 90, + 50 + (slot % 10) * 14, + child_index + 2, + ) + for bucket, index_doc in sorted(index_docs.items()): + index_id = uid(board.prefix, "contents", str(bucket)) + filename = board.prefix + "_contents_" + str(bucket + 1) + ".kicad_sch" + files[filename] = sexpdata.dumps(index_doc) + "\n" + self._sheet_link( + root, + board.prefix, + index_id, + "/" + board.root_id, + f"Contents {bucket + 1}", + filename, + 20 + (bucket // 10) * 90, + 50 + (bucket % 10) * 14, + len(sheets) + bucket + 1, + ) + if overview: + render_overview( + root, + board, + next(d for d in overview_data["boards"] if d["scope"] == board.scope), + options, + ) + files[root_filename] = sexpdata.dumps(root) + "\n" + files["net-labels.json"] = json.dumps({b.scope: b.names for b in boards}, indent=2, ensure_ascii=False) + "\n" + files["overview.json"] = json.dumps(overview_data, indent=2, ensure_ascii=False) + "\n" + files["sheet-plan.json"] = json.dumps(plan.to_dict(), indent=2, ensure_ascii=False) + "\n" + from .KiCadSchematicReadability import inspect_documents + + patterns: list[dict[str, Any]] = [] + for board in boards: + patterns.extend( + dict(scope=board.scope, **p.to_dict()) + for p in cast("SchematicCircuitModel", board.circuit_model).patterns + ) + files["circuit-model.json"] = ( + json.dumps( + dict( + schema=1, + boards=[ + dict(scope=b.scope, **cast("SchematicCircuitModel", b.circuit_model).to_dict()) for b in boards + ], + ), + indent=2, + ensure_ascii=False, + ) + + "\n" + ) + readability = inspect_documents(files, diagnostics, patterns) + files["readability.json"] = json.dumps(readability, indent=2, ensure_ascii=False) + "\n" + files["routing.json"] = ( + json.dumps( + dict( + schema=1, + optimize_routes=options.optimize_routes, + metric_scope="Local routed wires only; excludes fixed pin stubs and inter-region links", + regions=[ + dict(scope=b.scope, region=d.spec.title, **d.routing) + for b in boards + for d in b.regions.values() + if d.routing + ], + ), + indent=2, + ) + + "\n" + ) + placement_records = [ + dict( + scope=b.scope, + region=d.spec.title, + components=[dict(path=c.path, **getattr(c, "placement_evidence", {})) for c, _, _, _ in d.placed], + ) + for b in boards + for d in b.regions.values() + ] + atom_evidence = { + (b.scope, tuple(getattr(c, "placement_evidence", {}).get("atom", [c.path]))): getattr( + c, "placement_evidence", {} + ) + for b in boards + for d in b.regions.values() + for c, _, _, _ in d.placed + } + layout = dict( + schema=1, + exporter_version=VERSION, + patterns=patterns, + regions=placement_records, + label_placement=label_evidence, + summary=dict( + label_conflicts=sum(len(e["conflicts"]) for e in label_evidence), + label_moves=sum(len(e["moves"]) for e in label_evidence), + route_fallbacks=sum(len(d.failed_routes) for b in boards for d in b.regions.values()), + regions=len(plan.regions), + sheets=len(plan.sheets), + atomic_groups=len( + { + tuple(getattr(c, "placement_evidence", {}).get("atom", [c.path])) + for b in boards + for d in b.regions.values() + for c, _, _, _ in d.placed + } + ), + search_candidates=sum(e.get("candidates", 0) for e in atom_evidence.values()), + ), + ) + files["layout.json"] = json.dumps(layout, indent=2, ensure_ascii=False) + "\n" + manifest = dict( + exporter_version=VERSION, + source=options.source, + design=options.design_name, + fingerprint=fingerprint, + boards=board_records, + files=sorted(list(files) + ["manifest.json"]), + planning=dict( + regions=len(plan.regions), + sheets=len(plan.sheets), + total_documents=sum(n.endswith(".kicad_sch") for n in files), + diagnostics=list(plan.diagnostics), + ), + diagnostics=[vars(d) for d in diagnostics], + symbol_coverage=[ + dict(component.symbol_coverage, scope=board.scope) + for board in boards + for component in sorted( + {c.path: c for drawing in board.regions.values() for c, _, _, _ in drawing.placed}.values(), + key=lambda c: c.path, + ) + ], + ) + files["manifest.json"] = json.dumps(manifest, indent=2, ensure_ascii=False) + "\n" + return SchematicExport(files, diagnostics) + + @staticmethod + def _is_backbone(net: str) -> bool: + return any( + word.startswith("pwr") or word in ("gnd", "v3v3", "vbus", "vusb", "vbat", "vcell", "power") + for word in net.lower().split(".") + ) + + @staticmethod + def _sheet_link( + doc: SExpr, + prefix: str, + identity: str, + parent_path: str, + title: str, + filename: str, + x: float, + y: float, + page: int, + ) -> None: + doc.append( + node( + "sheet", + node("at", x, y), + node("size", 80, 8), + node("stroke", node("width", 0), node("type", S("default"))), + node("fill", node("color", 0, 0, 0, 0)), + node("uuid", identity), + node( + "property", + "Sheetname", + title, + node("at", x, y - 2, 0), + node( + "effects", + node("font", node("size", 1.27, 1.27)), + node("justify", S("left")), + ), + ), + node( + "property", + "Sheetfile", + filename, + node("at", x, y + 10, 0), + effects(hide=True), + ), + node( + "instances", + node( + "project", + prefix, + node("path", parent_path, node("page", str(page))), + ), + ), + ) + ) + + def _render_region( + self, + doc: SExpr, + board: _PreparedBoard, + drawing: _RegionDrawing, + location: SchematicRegionPlacement, + sheet_id: str, + instance_path: str, + net_pages: Mapping[str, set[str]], + ground_definition: SExpr | None, + ground_positions: set[Point], + diagnostics: list[SchematicDiagnostic], + pin_stubs: Optional[dict[Wire, str]] = None, + ) -> list[Wire]: + bounds = drawing.spec.bounds + dx, dy = drawing.sheet_offset(location) + + def move(p: Point) -> Point: + return (round(p[0] + dx, 4), round(p[1] + dy, 4)) + + headings = drawing.heading_positions or tuple( + (line, size, bounds[0] + 3, bounds[1] + 3 + i * 2.54) + for i, (line, size) in enumerate(self._region_heading_lines(drawing.spec.title, drawing.placed)) + ) + for line_number, (line, size, hx, hy) in enumerate(headings): + doc.append( + node( + "text", + line, + node("at", *move((hx, hy)), 0), + node( + "effects", + node("font", node("size", size, size)), + node("justify", S("left")), + ), + node( + "uuid", + uid(board.prefix, drawing.spec.id, "title", str(line_number)), + ), + ) + ) + doc.append( + node( + "rectangle", + node("start", location.x, location.y), + node( + "end", + round(location.x + bounds[2] - bounds[0], 4), + round(location.y + bounds[3] - bounds[1], 4), + ), + node("stroke", node("width", 0.15), node("type", S("default"))), + node("fill", node("type", S("none"))), + node("uuid", uid(board.prefix, drawing.spec.id, "border")), + ) + ) + if not drawing.placed: + doc.append( + node( + "text", + "No physical components in compiled design", + node("at", location.x + 3, location.y + 7, 0), + node("effects", node("font", node("size", 1.1, 1.1)), node("justify", S("left"))), + node("uuid", uid(board.prefix, "empty")), + ) + ) + views = board.views + pin_nets = board.pin_nets + names = board.names + local_wires = [(net, move(a), move(b)) for net, a, b in drawing.wires] + for failed_pin, failed_net in drawing.failed_routes: + diagnostics.append(SchematicDiagnostic(failed_pin[0], "local wire route retained net label: " + failed_net)) + all_segments = list(local_wires) + from .KiCadSchematicScene import label_islands + + selected_labels = label_islands( + drawing.placed, + views, + pin_nets, + drawing.wires, + {net for net, regions in board.net_regions.items() if len(regions) > 1}, + ) + for original, x, y, rotation in drawing.placed: + x, y = move((x, y)) + component = replace( + original, + annotation=move(original.annotation) if original.annotation else None, + ) + view = views[component.path] + instance_id = uid(board.prefix, component.path, "symbol") + instance = node( + "symbol", + node("lib_id", view.lib_id), + node("at", x, y, rotation), + node("unit", 1), + node("in_bom", S("yes")), + node("on_board", S("yes")), + node("dnp", S("no")), + node("uuid", instance_id), + ) + display_value = component.display_value or component.value + px, py, align = annotation_position(component, view, x, y, rotation) + for i, (key, value) in enumerate( + ( + ("Reference", component.refdes), + ("Value", component.value), + ("Footprint", component.footprint), + ("PBPath", component.path), + ) + ): + instance.append( + node( + "property", + key, + value, + node("at", px, py + i * 2.54, rotation % 180), + node( + "effects", + node("font", node("size", 1.27, 1.27)), + *([node("justify", S(align))] if align else []), + *([S("hide")] if i > 1 or (i == 1 and display_value != component.value) else []), + ), + ) + ) + if display_value != component.value: + instance.append( + node( + "property", + "PBDisplayValue", + "\n".join(textwrap.wrap(display_value, 30)), + node("at", px, py + 2.54, rotation % 180), + node( + "effects", + node("font", node("size", 1.27, 1.27)), + *([node("justify", S(align))] if align else []), + ), + ) + ) + description_line = 0 + for description in component.descriptions: + for line in textwrap.wrap(description, 42): + doc.append( + node( + "text", + line, + node("at", px, py + 10 + description_line * 2.54, 0), + effects(1.1), + node( + "uuid", + uid(instance_id, "description", str(description_line)), + ), + ) + ) + description_line += 1 + instance.append( + node( + "instances", + node( + "project", + board.prefix, + node( + "path", + instance_path, + node("reference", component.refdes), + node("unit", 1), + ), + ), + ) + ) + for number, px, py, angle in positioned_pins(view, x, y, rotation): + instance.append(node("pin", number, node("uuid", uid(instance_id, number)))) + net = pin_nets.get((component.path, number)) + if net is None: + continue + lx, ly = drawing.sheet_escape((component.path, number), dx, dy, px, py, angle) + stub = net, (px, py), (lx, ly) + all_segments.append(stub) + if pin_stubs is not None: + pin_stubs[stub] = f"{component.path}.{number}" + if (component.path, number) not in selected_labels and net.lower().split(".")[-1] != "gnd": + continue + if net.lower().split(".")[-1] == "gnd" and ground_definition is not None: + if (lx, ly) not in ground_positions: + ground_positions.add((lx, ly)) + gid = uid(sheet_id, str(lx), str(ly), "ground") + ref = "#PWR" + gid.replace("-", "")[:10] + doc.append( + node( + "symbol", + node("lib_id", "power:GND"), + node("at", lx, ly, ground_rotation(angle)), + node("unit", 1), + node("in_bom", S("no")), + node("on_board", S("yes")), + node("dnp", S("no")), + node("uuid", gid), + node( + "property", + "Reference", + ref, + node("at", lx, ly, 0), + effects(hide=True), + ), + node( + "property", + "Value", + names[net], + node("at", lx, ly + 5.08, 0), + effects(hide=True), + ), + node("pin", "1", node("uuid", uid(gid, "pin"))), + node( + "instances", + node( + "project", + board.prefix, + node( + "path", + instance_path, + node("reference", ref), + node("unit", 1), + ), + ), + ), + ) + ) + ground_label = component.ground_net_labels.get(number) + if ground_label: + gx, gy = ground_label_position(lx, ly, angle) + doc.append( + node( + "text", + ground_label, + node("at", gx, gy, 0), + effects(), + node("uuid", uid(gid, "return-identity")), + ) + ) + continue + kind = "global_label" if len(net_pages[net]) > 1 else "label" + a = (180 - int(angle)) % 360 + eff = effects() + eff.append( + node( + "justify", S("left" if a in (0, 270) else "right"), *([S("bottom")] if kind == "label" else []) + ) + ) + label = node( + kind, + names[net], + node("at", lx, ly, a), + eff, + node("uuid", uid(instance_id, number, "label")), + ) + if kind == "global_label": + label.append(node("shape", S("bidirectional"))) + label.append( + node( + "property", + "Intersheetrefs", + "${INTERSHEET_REFS}", + node("at", lx, ly, 0), + effects(hide=True), + ) + ) + doc.append(label) + doc.append(instance) + write_wires(doc, all_segments, sheet_id, drawing.spec.id) + return all_segments + + @staticmethod + def _inter_region_wires( + doc: SExpr, board: _PreparedBoard, sheet: SchematicSheet, sheet_id: str, segments: list[Wire] + ) -> None: + """Add only short, straight, unobstructed same-net sheet connections. + + Region interfaces keep their labels. No search through other circuits is + attempted; distant or obstructed interfaces remain labeled connections. + """ + terminals: dict[str, list[tuple[str, Point]]] = {} + boxes: list[tuple[str | None, Bounds]] = [] + for location in sheet.regions: + drawing = board.regions[location.region_id] + bounds = drawing.spec.bounds + dx, dy = drawing.sheet_offset(location) + heading_boxes = drawing.heading_boxes or ( + ( + bounds[0], + bounds[1], + bounds[2], + bounds[1] + + 5 + + 2.54 * len(KiCadSchematicExporter._region_heading_lines(drawing.spec.title, drawing.placed)), + ), + ) + boxes.extend((None, (x1 + dx, y1 + dy, x2 + dx, y2 + dy)) for x1, y1, x2, y2 in heading_boxes) + for original, x, y, angle in drawing.placed: + x, y = round(x + dx, 4), round(y + dy, 4) + c = replace( + original, + annotation=( + ( + original.annotation[0] + dx, + original.annotation[1] + dy, + ) + if original.annotation + else None + ), + ) + view = board.views[c.path] + min_x, min_y, max_x, max_y = graphic_bounds(view, angle) + boxes.append((None, (x + min_x, y + min_y, x + max_x, y + max_y))) + tx, ty, align = annotation_position(c, view, x, y, angle) + visible = c.display_value or c.value + lines = (textwrap.wrap(visible, 30) if visible != c.value else visible.splitlines()) or [""] + width = max([len(c.refdes)] + [len(line) for line in lines]) * 1.27 + 2 + boxes.append( + ( + None, + ( + tx if align else tx - width / 2, + ty - 1.5 - len(lines) * 1.27, + tx + width if align else tx + width / 2, + ty + 3.81 + len(lines) * 1.27, + ), + ) + ) + for number, px, py, direction in positioned_pins(view, x, y, angle): + net = board.pin_nets.get((c.path, number)) + if net is None: + continue + ex, ey = drawing.sheet_escape((c.path, number), dx, dy, px, py, direction) + if net.lower().split(".")[-1] == "gnd": + boxes.append((None, ground_bounds(ex, ey, direction, c.ground_net_labels.get(number, "")))) + continue + rect = pin_label_bounds(board.names[net], ex, ey, direction) + boxes.append((net, rect)) + terminals.setdefault(net, []).append((location.region_id, (ex, ey))) + + def crosses_box(a: Point, b: Point, rect: Bounds) -> bool: + return ( + a[0] == b[0] + and rect[0] <= a[0] <= rect[2] + and max(min(a[1], b[1]), rect[1]) <= min(max(a[1], b[1]), rect[3]) + ) or ( + a[1] == b[1] + and rect[1] <= a[1] <= rect[3] + and max(min(a[0], b[0]), rect[0]) <= min(max(a[0], b[0]), rect[2]) + ) + + def crosses_segment(a: Point, b: Point, c: Point, d: Point) -> bool: + return crosses_box( + a, + b, + (min(c[0], d[0]), min(c[1], d[1]), max(c[0], d[0]), max(c[1], d[1])), + ) + + candidates = [] + for net, entries in terminals.items(): + for index, (ra, a) in enumerate(entries): + for rb, b in entries[index + 1 :]: + length = abs(a[0] - b[0]) + abs(a[1] - b[1]) + if ra != rb and 0 < length <= 50 and (a[0] == b[0] or a[1] == b[1]): + candidates.append((length, net, ra, rb, a, b)) + joined: dict[str, dict[str, str]] = {} + for _, net, ra, rb, a, b in sorted(candidates): + parent = joined.setdefault(net, {}) + + def root(identity: str) -> str: + while identity in parent: + identity = parent[identity] + return identity + + if root(ra) == root(rb): + continue + if any(kind != net and crosses_box(a, b, rect) for kind, rect in boxes): + continue + if any(other != net and crosses_segment(a, b, c, d) for other, c, d in segments): + continue + parent[root(rb)] = root(ra) + doc.append( + node( + "wire", + node("pts", node("xy", *a), node("xy", *b)), + node("stroke", node("width", 0), node("type", S("default"))), + node( + "uuid", + uid(sheet_id, net, ra, rb, str(a), str(b), "region-wire"), + ), + ) + ) + for point in (a, b): + doc.append( + node( + "junction", + node("at", *point), + node("diameter", 0), + node("color", 0, 0, 0, 0), + node("uuid", uid(sheet_id, net, str(point), "region-junction")), + ) + ) + segments.append((net, a, b)) + + @staticmethod + def _display_value(compiled: CompiledDesign, block: NetBlock, mapping: Mapping[str, Any] | None = None) -> str: + classes = [c.target.name.rsplit(".", 1)[-1].lower() for c in block.path_classes] + leaf = classes[-1] if classes else "" + quantities = [] + declared = (mapping or {}).get("lib_id", "") + if declared in ("Device:C", "Device:C_Polarized"): + quantities = [("actual_capacitance", "F")] + elif declared == "Device:R": + quantities = [("actual_resistance", "Ω")] + elif declared == "Device:L": + quantities = [("actual_inductance", "H")] + elif "crystal" in leaf or "oscillator" in leaf: + quantities = [("actual_frequency", "Hz")] + elif "resistor" in leaf: + quantities = [("actual_resistance", "Ω")] + elif "capacitor" in leaf: + quantities = [("actual_capacitance", "F")] + elif "inductor" in leaf: + quantities = [("actual_inductance", "H")] + for parameter, unit in quantities: + value = compiled.get_value(block.full_path.to_tuple() + (parameter,)) + if value is None: + value = compiled.get_value(block.full_path.to_tuple() + (parameter.removeprefix("actual_"),)) + if hasattr(value, "lower") and hasattr(value, "upper"): + interval = cast("Range", value) + nominal = (interval.lower + interval.upper) / 2 + elif isinstance(value, (float, int)): + nominal = value + else: + continue + if math.isfinite(nominal): + for scale, prefix in ( + (1e9, "G"), + (1e6, "M"), + (1e3, "k"), + (1, ""), + (1e-3, "m"), + (1e-6, "µ"), + (1e-9, "n"), + (1e-12, "p"), + ): + if abs(nominal) >= scale * (1 - 1e-10): + return f"{nominal / scale:.3g}{prefix}{unit}" + return "0" + unit + color = compiled.get_value(block.full_path.to_tuple() + ("actual_color",)) + if isinstance(color, str) and color: + return color + " LED" + if block.part: + return block.part.split(" (")[0] + return block.value if len(block.value) <= 48 else "\n".join(textwrap.wrap(block.value, 30)) + + @staticmethod + def _document(identity: str, options: SchematicExportOptions, fingerprint: str, group: str) -> SExpr: + return node( + "kicad_sch", + node("version", 20250114), + node("generator", "polymorphicblocks"), + node("uuid", identity), + node("paper", "A3"), + node( + "title_block", + node("title", options.design_name + " / " + group), + node("comment", 1, options.source), + node("comment", 2, fingerprint), + ), + node( + "text", + NOTICE, + node("at", 20, 15, 0), + node( + "effects", + node("font", node("size", 2, 2)), + node("justify", S("left")), + ), + node("uuid", uid(identity, "notice")), + ), + node( + "text", + INSTRUCTIONS, + node("at", 20, 22, 0), + node( + "effects", + node("font", node("size", 1.27, 1.27)), + node("justify", S("left")), + ), + node("uuid", uid(identity, "instructions")), + ), + ) diff --git a/edg/electronics_model/KiCadSchematicLabels.py b/edg/electronics_model/KiCadSchematicLabels.py new file mode 100644 index 000000000..55afac7e4 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicLabels.py @@ -0,0 +1,42 @@ +"""Readable injective net labels, retaining the complete PB name in evidence.""" + +import re +import hashlib +from typing import Iterable + + +def readable_labels(net_names: Iterable[str]) -> dict[str, str]: + names = sorted(set(net_names)) + parts = {name: name.split(".") for name in names} + depth = {name: min(3, len(parts[name])) for name in names} + while True: + candidate = {name: ".".join(parts[name][-depth[name] :]) for name in names} + duplicates: dict[str, list[str]] = {} + for name, label in candidate.items(): + duplicates.setdefault(label, []).append(name) + expand = [ + name for group in duplicates.values() if len(group) > 1 for name in group if depth[name] < len(parts[name]) + ] + if not expand: + break + for name in expand: + depth[name] += 1 + result = {} + for name in names: + label = candidate[name] + if re.search(r"[\s~{}]", label): + label = "N_" + name.encode("utf-8").hex() + result[name] = label + # Encoded names can collide with a legal PB name. Escape both with a stable + # digest, never rely on iteration order or a UUID derived from coordinates. + groups: dict[str, list[str]] = {} + for name, label in result.items(): + groups.setdefault(label, []).append(name) + for group in groups.values(): + if len(group) > 1: + for name in group: + result[name] += "_" + hashlib.sha256(name.encode()).hexdigest() + if len(set(result.values())) != len(result): + # Cryptographic collision or deliberately crafted names: full hex is injective. + return {name: "N_" + name.encode("utf-8").hex() for name in names} + return result diff --git a/edg/electronics_model/KiCadSchematicLayout.py b/edg/electronics_model/KiCadSchematicLayout.py new file mode 100644 index 000000000..6b4233a58 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicLayout.py @@ -0,0 +1,913 @@ +"""Connectivity-driven placement and conservative orthogonal local wiring. + +Layout consumes the physical netlist; it never introduces electrical connections. +Failed local routes retain labels and are reported, rather than guessed wires. +""" + +from __future__ import annotations + +import bisect +import heapq +import math +import textwrap +from collections import defaultdict +from typing import Any, Optional, Sequence, Tuple, TYPE_CHECKING, Callable, Iterable, Mapping, cast, Union +from .KiCadSchematicTypes import ( + Bounds, + Point, + GridPoint, + PinKey, + PinNets, + Placement, + Placements, + Views, + Wire, + RouteResult, + Escape, + SExpr, +) + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +RouteState = Union[GridPoint, tuple[GridPoint, Optional[int]]] + +from .KiCadSchematicScene import pin_label_bounds, pin_name_items, pin_number_items +from .KiCadSchematicPatterns import decoupling_associations, discover_patterns, terminal_roles + +GRID = 1.27 + + +def tree_distance(targets: Iterable[GridPoint]) -> Callable[[GridPoint], float]: + """Cached exact Manhattan distance to a route tree, an admissible A* bound.""" + raw_columns: defaultdict[int, list[int]] = defaultdict(list) + for x, y in targets: + raw_columns[x].append(y) + columns = {x: sorted(set(ys)) for x, ys in raw_columns.items()} + xs = sorted(columns) + cache: dict[GridPoint, float] = {} + + def distance(point: GridPoint) -> float: + if point in cache: + return cache[point] + x, y = point + right = bisect.bisect_left(xs, x) + left = right - 1 + best = float("inf") + while left >= 0 or right < len(xs): + dl = abs(xs[left] - x) if left >= 0 else float("inf") + dr = abs(xs[right] - x) if right < len(xs) else float("inf") + if min(dl, dr) >= best: + break + if dl <= dr: + cx = xs[left] + left -= 1 + else: + cx = xs[right] + right += 1 + ys = columns[cx] + index = bisect.bisect_left(ys, y) + for i in (index - 1, index): + if 0 <= i < len(ys): + best = min(best, abs(cx - x) + abs(ys[i] - y)) + cache[point] = best + return best + + return distance + + +def snap(value: float) -> float: + return round(round(value / GRID) * GRID, 4) + + +def transform(x: float, y: float, angle: int) -> Tuple[float, float]: + r = math.radians(angle) + return round(x * math.cos(r) + y * math.sin(r), 4), round(-x * math.sin(r) + y * math.cos(r), 4) + + +def pins(view: SymbolView, x: float, y: float, angle: int) -> list[tuple[str, float, float, float]]: + result = [] + for number, dx, dy, direction in view.pins: + tx, ty = transform(dx, dy, angle) + result.append((number, round(x + tx, 4), round(y + ty, 4), (direction + angle) % 360)) + return result + + +def pin_escape(px: float, py: float, direction: float) -> Point: + """Outward endpoint of the fixed native pin stub, in sheet coordinates.""" + angle = math.radians(direction) + return round(px - 5.08 * math.cos(angle), 4), round(py + 5.08 * math.sin(angle), 4) + + +def _arc_extrema(start: Point, mid: Point, end: Point) -> Iterable[Point]: + """Yield circle extrema on the sweep from start to end through mid.""" + # Solve for the circle center relative to start using the two perpendicular bisectors. + mx, my = mid[0] - start[0], mid[1] - start[1] + ex, ey = end[0] - start[0], end[1] - start[1] + cross = mx * ey - my * ex + if cross == 0: # Repeated or collinear points have no unique circle. + return + m_squared, e_squared = mx * mx + my * my, ex * ex + ey * ey + cx = (m_squared * ey - e_squared * my) / (2 * cross) + cy = (mx * e_squared - ex * m_squared) / (2 * cross) + radius = math.hypot(cx, cy) + # The endpoint chord divides the circle into two arcs. Keep its midpoint's side. + for x, y in ((cx - radius, cy), (cx + radius, cy), (cx, cy - radius), (cx, cy + radius)): + if (x * ey - y * ex) * cross >= 0: + yield start[0] + x, start[1] + y + + +def graphic_bounds(view: SymbolView, angle: int = 0, include_pins: bool = True) -> Tuple[float, float, float, float]: + points: list[Point] = [] + + def collect(tree: object) -> None: + if not isinstance(tree, list) or not tree: + return + name = str(tree[0]) + if name in ("property", "pin"): + return + if name == "arc": + arc = { + str(v[0]): (v[1], v[2]) + for v in tree + if isinstance(v, list) and len(v) >= 3 and str(v[0]) in ("start", "mid", "end") + } + if {"start", "mid", "end"} <= arc.keys(): + for x, y in _arc_extrema(arc["start"], arc["mid"], arc["end"]): + points.append(transform(x, -y, angle)) + if name == "circle": + center = next((v for v in tree if isinstance(v, list) and str(v[0]) == "center"), None) + radius = next( + (v[1] for v in tree if isinstance(v, list) and str(v[0]) == "radius"), + None, + ) + if center is not None and radius is not None: + for dx, dy in ((radius, 0), (-radius, 0), (0, radius), (0, -radius)): + points.append(transform(center[1] + dx, -center[2] + dy, angle)) + if name in ("start", "mid", "end", "xy", "center") and len(tree) >= 3: + if isinstance(tree[1], (int, float)) and isinstance(tree[2], (int, float)): + points.append(transform(float(tree[1]), -float(tree[2]), angle)) + for child in tree: + collect(child) + + collect(view.definition) + if include_pins: + points.extend((transform(p[1], p[2], angle)) for p in view.pins) + if not points: + return -5, -5, 5, 5 + return ( + min(p[0] for p in points), + min(p[1] for p in points), + max(p[0] for p in points), + max(p[1] for p in points), + ) + + +def ground_rotation(direction: float) -> int: + """Point ground away from the pin instead of into adjacent pin labels.""" + return int(direction + 270) % 360 + + +def ground_bounds(x: float, y: float, direction: float, label: str = "") -> Bounds: + angle = ground_rotation(direction) + corners = [transform(dx, dy, angle) for dx in (-2.54, 2.54) for dy in (0, 4.445)] + bounds = ( + x + min(p[0] for p in corners), + y + min(p[1] for p in corners), + x + max(p[0] for p in corners), + y + max(p[1] for p in corners), + ) + if label: + from .KiCadSchematicScene import text_bounds + + lx, ly = ground_label_position(x, y, direction) + text = text_bounds(label, lx, ly, size=1.27) + bounds = (min(bounds[0], text[0]), min(bounds[1], text[1]), max(bounds[2], text[2]), max(bounds[3], text[3])) + return bounds + + +def ground_label_position(x: float, y: float, direction: float) -> Point: + """Keep distinct return identities horizontal below the ground glyph.""" + bounds = ground_bounds(x, y, direction) + return round((bounds[0] + bounds[2]) / 2, 4), round(bounds[3] + 2.54, 4) + + +def annotation_bounds(component: PhysicalComponent, x: float, y: float, rotation: int) -> Bounds: + """Visible field bounds matching serialized instance-relative text angles. + + Exported Reference/Value angles equal the symbol rotation modulo 180, so + native KiCad renders these fields horizontally for every symbol orientation. + """ + from .KiCadSchematicScene import text_bounds + + visible = getattr(component, "display_value", "") or component.value + value = "\n".join(textwrap.wrap(visible, 30)) if visible != component.value else visible + boxes = [text_bounds(component.refdes, x, y, size=1.27), text_bounds(value, x, y + 2.54, size=1.27)] + count = 0 + for description in getattr(component, "descriptions", ()): + for line in textwrap.wrap(description, 42): + boxes.append(text_bounds(line, x, y + 10 + count * 2.54, size=1.1)) + count += 1 + # Reserve stroke clearance beyond the font envelope. + return ( + min(b[0] for b in boxes) - 0.3, + min(b[1] for b in boxes) - 0.3, + max(b[2] for b in boxes) + 0.3, + max(b[3] for b in boxes) + 0.3, + ) + + +def annotation_obstacles( + component: PhysicalComponent, view: SymbolView, x: float, y: float, rotation: int +) -> list[Bounds]: + """Own symbol and pin outward corridors, including long external labels.""" + xmin, ymin, xmax, ymax = graphic_bounds(view, rotation) + result = [(x + xmin, y + ymin, x + xmax, y + ymax)] + labels = getattr(component, "net_labels", {}) + for number, px, py, direction in pins(view, x, y, rotation): + ex, ey = pin_escape(px, py, direction) + result.append((min(px, ex) - 0.8, min(py, ey) - 0.8, max(px, ex) + 0.8, max(py, ey) + 0.8)) + ground_label = getattr(component, "ground_net_labels", {}).get(number, "") + name = labels.get(number, "") or ground_label + if not name: + continue + if ground_label or name.lower().split(".")[-1] == "gnd": + result.append(ground_bounds(ex, ey, direction, ground_label)) + continue + result.append(pin_label_bounds(name, ex, ey, direction)) + + return result + + +def annotation_position( + component: PhysicalComponent, view: SymbolView, x: float, y: float, rotation: int +) -> tuple[float, float, str]: + if component.annotation is not None: + return component.annotation[0], component.annotation[1], "" + # Score locally so translation cannot change a floating-point tie. + origin_x, origin_y = x, y + x = y = 0.0 + xmin, ymin, xmax, ymax = graphic_bounds(view, rotation) + local = annotation_bounds(component, 0, 0, rotation) + half_width = (local[2] - local[0]) / 2 + half_height = (local[3] - local[1]) / 2 + # Existing preferred placement remains first; repair examines a finite list + # of side/corner positions, never a time-dependent unconstrained search. + preferred = (x, y + ymax + 12.7) + terminals = pins(view, x, y, rotation) + if ("FET" in view.lib_id or "Q_NMOS" in view.lib_id or "Q_PMOS" in view.lib_id) and rotation in (0, 180): + preferred = (x + xmax + 3.81 + half_width, y - 1.27) + elif len(terminals) == 2 and abs(terminals[0][1] - terminals[1][1]) < 0.01: + preferred = (x + xmax + 3.81 + half_width, y - 1.27) + candidates = [preferred] + for margin in (3.81, 8.89, 15.24): + left, right = x + xmin - margin - half_width, x + xmax + margin + half_width + top, bottom = y + ymin - margin - half_height, y + ymax + margin + half_height + candidates.extend( + ( + (right, y), + (left, y), + (x, top), + (x, bottom), + (right, top), + (left, top), + (right, bottom), + (left, bottom), + ) + ) + obstacles = annotation_obstacles(component, view, x, y, rotation) + + def score(candidate: Point) -> tuple[float, float]: + box = annotation_bounds(component, *candidate, rotation) + overlap = sum( + max(0, min(box[2], b[2]) - max(box[0], b[0])) * max(0, min(box[3], b[3]) - max(box[1], b[1])) + for b in obstacles + ) + return overlap, abs(candidate[0] - preferred[0]) + abs(candidate[1] - preferred[1]) + + chosen = min(enumerate(candidates), key=lambda pair: (*score(pair[1]), pair[0]))[1] + return chosen[0] + origin_x, chosen[1] + origin_y, "" + + +def freeze_annotations(placed: Placements, views: Views) -> list[Placement]: + """Resolve fields once for routing, measurement, and final serialization. + + Copies retain placement evidence without leaking generated coordinates into + source components, which may subsequently be split and placed again. + """ + from copy import copy + + result = [] + for component, x, y, rotation in placed: + resolved = copy(component) + ax, ay, _ = annotation_position(component, views[component.path], x, y, rotation) + resolved.annotation = (ax, ay) + result.append((resolved, x, y, rotation)) + return result + + +def regroup(components: Sequence[PhysicalComponent], pin_nets: PinNets, views: Optional[Views] = None) -> None: + """Co-locate small sibling circuits; IC/control groups stay boundaries.""" + original_groups = {c.path: c.group for c in components} + groups = defaultdict(list) + for c in components: + groups[c.group].append(c) + parent = {g: g for g in groups} + + def root(g: str) -> str: + while parent[g] != g: + g = parent[g] + return g + + by_net = defaultdict(set) + by_path = {c.path: c for c in components} + for (path, _), net in pin_nets.items(): + by_net[net].add(path) + for net, paths in sorted(by_net.items()): + if len(paths) > 8 or any( + word.startswith("pwr") or word in ("gnd", "v3v3", "vbus", "vusb", "vbat", "power") + for word in net.lower().split(".") + ): + continue + candidates = sorted( + { + root(by_path[p].group) + for p in paths + if p in by_path and max([len(c.pins) for c in groups[by_path[p].group]] + [0]) <= 6 + } + ) + if len(candidates) < 2: + continue + for g in candidates[1:]: + parent[root(g)] = root(candidates[0]) + for c in components: + c.group = root(c.group) + # Explicit feedback terminal + conventional resistor symbols justify a + # complete local divider region, even across nested PB implementation blocks. + model = getattr(components[0], "circuit_model", None) if components else None + patterns = model.patterns if model is not None else discover_patterns(components, pin_nets, views) + for pattern in patterns: + if pattern.kind in ( + "feedback_divider", + "indicator_branch", + "converter_output", + "gate_driver_stage", + "amplifier_feedback", + "local_decoupling", + ): + owner = original_groups[pattern.components[0]] + for path in pattern.components: + by_path[path].group = owner + + +def place_group( + components: Sequence[PhysicalComponent], views: Views, pin_nets: PinNets, *, optimize_orientations: bool = True +) -> list[list[Placement]]: + """Place whole functional atoms; retain established inline serial chains.""" + from .KiCadSchematicPlacement import functional_atoms, place_functional + + _, patterns = functional_atoms(components, pin_nets, views) + nonserial = [p for p in patterns if p.kind != "serial_data_chain"] + authored = any(p.kind == "authored_circuit" for p in patterns) + chains = [p for p in patterns if p.kind == "serial_data_chain"] + circuits = { + circuit.id: circuit + for c in components + if (circuit := getattr(c, "functional_circuit", None)) is not None and circuit.provenance == "explicit" + } + # A declared repeated channel without ordered stages selects the proven + # inline chain template, including its locally owned bypass capacitors. + # Ordered stages remain authoritative and use functional placement. + inline_authored = ( + authored + and bool(circuits) + and all( + circuit.template == "repeated_channel" + and not circuit.stages + and any(set(chain.components) <= set(circuit.components) for chain in chains) + for circuit in circuits.values() + ) + ) + if inline_authored or (not authored and (chains or (all(len(c.pins) == 2 for c in components) and not nonserial))): + return _place_group_legacy(components, views, pin_nets) + return place_functional(components, views, pin_nets, optimize_orientations=optimize_orientations) + + +def _place_group_legacy( + components: Sequence[PhysicalComponent], views: Views, pin_nets: PinNets +) -> list[list[Placement]]: + """Compact graph ordering; simple two-terminal chains get inline orientation.""" + components = sorted(components, key=lambda c: c.path) + adjacency: dict[str, set[str]] = {c.path: set() for c in components} + nets: defaultdict[str, list[PinKey]] = defaultdict(list) + for c in components: + for pin in c.pins: + net = pin_nets.get((c.path, pin)) + if net is not None: + nets[net].append((c.path, pin)) + edge_pins = {} + for net, endpoints in nets.items(): + paths = sorted({p for p, _ in endpoints}) + if len(paths) == 2: + a, b = paths + adjacency[a].add(b) + adjacency[b].add(a) + edge_pins[(a, b)] = next(pin for p, pin in endpoints if p == a) + edge_pins[(b, a)] = next(pin for p, pin in endpoints if p == b) + by_path = {c.path: c for c in components} + chain = ( + bool(components) and all(len(c.pins) == 2 for c in components) and all(len(v) <= 2 for v in adjacency.values()) + ) + order = [] + if chain: + todo = sorted( + (p for p in adjacency if len(adjacency[p]) == 1), + key=lambda p: ( + "Resistor" in views[p].lib_id or ":R_" in views[p].lib_id, + p, + ), + ) + if todo: + current = todo[0] + while current not in order: + order.append(current) + following = sorted(adjacency[current] - set(order)) + if not following: + break + current = following[0] + chain = len(order) == len(components) + if not chain: + order = [] + remaining = set(by_path) + while remaining: + start = max(remaining, key=lambda p: (len(by_path[p].pins), len(adjacency[p]), p)) + queue = [start] + while queue: + current = queue.pop(0) + if current not in remaining: + continue + remaining.remove(current) + order.append(current) + queue.extend(sorted(adjacency[current] & remaining)) + # Serial order follows verified DIN/DOUT connections, not lexical paths. + patterns = discover_patterns(components, pin_nets, views) + serial_order = [p for pattern in patterns if pattern.kind == "serial_data_chain" for p in pattern.components] + serial_members = set(serial_order) + supports: defaultdict[str, list[str]] = defaultdict(list) + for pattern in patterns: + if pattern.kind == "local_decoupling": + supports[pattern.components[0]].extend(pattern.components[1:]) + support_members = {p for values in supports.values() for p in values} + order = serial_order + [p for p in order if p not in serial_members | support_members] + x = 65.0 + y = 80.0 + row_height = 0.0 + page: list[Placement] = [] + pages: list[list[Placement]] = [] + for i, path in enumerate(order): + component = by_path[path] + view = views[path] + rotation = 0 + if chain and len(order) > 1: + target = order[i + 1] if i + 1 < len(order) else order[i - 1] + target_pin = edge_pins[(path, target)] + desired = 1 if i + 1 < len(order) else -1 + rotation = max( + (0, 90, 180, 270), + key=lambda a: ( + desired * next(transform(dx, dy, a)[0] for n, dx, dy, _ in view.pins if n == target_pin) + ), + ) + if path in serial_members: + # Use actual physical pin geometry to put DOUT to the right of DIN. + roles = terminal_roles(component) + rotation = max( + (0, 90, 180, 270), + key=lambda a: ( + next(transform(dx, dy, a)[0] for n, dx, dy, _ in view.pins if n == roles["dout"]) + - next(transform(dx, dy, a)[0] for n, dx, dy, _ in view.pins if n == roles["din"]), + -a, + ), + ) + xmin, ymin, xmax, ymax = graphic_bounds(view, rotation) + # Space includes outward labels, annotation block, and local routing lanes. + width = max(30, xmax - xmin + 20) if chain else max(60, xmax - xmin + 48) + height = max(52, ymax - ymin + 32) + tx, ty, _ = annotation_position(component, view, 0, 0, rotation) + fx1, fy1, fx2, fy2 = annotation_bounds(component, tx, ty, rotation) + width = max(width, max(xmax, fx2) - min(xmin, fx1) + 10) + height = max(height, max(ymax, fy2) - min(ymin, fy1) + 10) + if supports[path]: + height += 38 + 30 * (len(supports[path]) - 1) + width = max(width, 60) + if width > 340 or height > 205: + raise ValueError("symbol exceeds page bounds: " + path) + if x + width / 2 > 390: + x = 65 + y += row_height + row_height = 0 + if y + height / 2 > 265: + pages.append(page) + page = [] + x = 65 + y = 80 + row_height = 0 + page.append((component, snap(x), snap(y), rotation)) + for index, support in enumerate(sorted(supports[path])): + page.append((by_path[support], snap(x), snap(y + ymax + 30 + index * 30), 90)) + x += width + row_height = max(row_height, height) + if page: + pages.append(page) + return pages + + +class _NearForeignCache: + """Monotonic exact cache of the eight-neighbor visual-clearance rule. + + A source track forbids its own axes in neighboring cells; protected source + points forbid both axes. The source cell itself is intentionally excluded: + exact perpendicular interior crossings use the existing track rule. + """ + + def __init__(self, tracks: defaultdict[GridPoint, dict[str, set[int]]], protected: set[GridPoint]) -> None: + self.tracks = tracks + self.protected = protected + self.owners: tuple[defaultdict[GridPoint, set[str]], defaultdict[GridPoint, set[str]]] = ( + defaultdict(set), + defaultdict(set), + ) + for point, nets in tracks.items(): + for net, axes in nets.items(): + self._reserve(point, net, axes) + + def _reserve(self, point: GridPoint, net: str, axes: Iterable[int]) -> None: + axes = (0, 1) if point in self.protected else axes + x, y = point + for nx in (x - 1, x, x + 1): + for ny in (y - 1, y, y + 1): + if (nx, ny) != point: + for axis in axes: + self.owners[axis][nx, ny].add(net) + + def add_track(self, point: GridPoint, net: str, axes: Iterable[int]) -> None: + existing = self.tracks[point].setdefault(net, set()) + existing.update(axes) + self._reserve(point, net, existing) + + def protect(self, points: Iterable[GridPoint]) -> None: + for point in points: + if point in self.protected: + continue + self.protected.add(point) + for net, axes in self.tracks.get(point, {}).items(): + self._reserve(point, net, axes) + + def blocked(self, point: GridPoint, axis: int, net: str) -> bool: + owners = self.owners[axis].get(point) + return owners is not None and bool(owners) and (len(owners) > 1 or net not in owners) + + +def _pin_lengths(definition: SExpr) -> dict[str, float]: + """Read the resolved embedded symbol's actual library pin-leg lengths.""" + result: dict[str, float] = {} + + def visit(tree: object) -> None: + if not isinstance(tree, list) or not tree: + return + if str(tree[0]) == "pin": + number = next((v[1] for v in tree if isinstance(v, list) and v and str(v[0]) == "number"), None) + length = next((v[1] for v in tree if isinstance(v, list) and v and str(v[0]) == "length"), None) + if number is not None and length is not None: + result[str(number)] = float(length) + for child in tree: + visit(child) + + visit(definition) + return result + + +def route_local(placed: Placements, views: Views, pin_nets: PinNets, *, strategy: str = "baseline") -> RouteResult: + """Route a same-net tree between pin escapes on a grid, avoiding other copper. + + Crossings remain straight and junction-free; crossing-averse trials penalize + them explicitly. All failed endpoints retain a label. + Router output is independently checked through native KiCad netlist export. + """ + step = 0.635 + + def grid(x: float, y: float) -> GridPoint: + return round(x / step), round(y / step) + + def point(p: GridPoint) -> Point: + return round(p[0] * step, 4), round(p[1] * step, 4) + + obstacles: set[GridPoint] = set() + label_obstacles: defaultdict[GridPoint, set[str]] = defaultdict(set) + occupied = {} + tracks: defaultdict[GridPoint, dict[str, set[int]]] = defaultdict(dict) + protected: set[GridPoint] = set() + fixed_clearance: defaultdict[GridPoint, set[str]] = defaultdict(set) + pin_necks = set() + endpoints: defaultdict[str, list[tuple[PinKey, GridPoint]]] = defaultdict(list) + escapes = {} + wires = [] + failures = [] + for c, x, y, rotation in placed: + xmin, ymin, xmax, ymax = graphic_bounds(views[c.path], rotation, include_pins=False) + # Pin contacts remain outside the actual symbol graphics. + a, b = grid(x + xmin, y + ymin) + d, e = grid(x + xmax, y + ymax) + if a <= d and b <= e: + obstacles.update((ix, iy) for ix in range(a, d + 1) for iy in range(b, e + 1)) + tx, ty, align = annotation_position(c, views[c.path], x, y, rotation) + field_box = annotation_bounds(c, tx, ty, rotation) + ax, ay = grid(field_box[0], field_box[1]) + bx, by = grid(field_box[2], field_box[3]) + obstacles.update((ix, iy) for ix in range(ax, bx + 1) for iy in range(ay, by + 1)) + for item in pin_name_items(views[c.path].definition, x, y, rotation, c.path) + pin_number_items( + views[c.path].definition, x, y, rotation, c.path + ): + lo_x, lo_y, hi_x, hi_y = item["bounds"] + # Only grid points actually inside the text box are obstacles. + obstacles.update( + (ix, iy) + for ix in range(math.ceil(lo_x / step), math.floor(hi_x / step) + 1) + for iy in range(math.ceil(lo_y / step), math.floor(hi_y / step) + 1) + ) + pin_lengths = _pin_lengths(views[c.path].definition) + for number, px, py, direction in pins(views[c.path], x, y, rotation): + key = c.path, number + net = pin_nets.get(key) + if net is None: + continue + r = math.radians(direction) + ex, ey = pin_escape(px, py, direction) + escape = grid(ex, ey) + escapes[key] = (px, py, ex, ey, direction) + endpoints[net].append((key, escape)) + # Reserve true-coordinate stub geometry, including its off-grid + # transition, by a full 1.27 mm. Rounded grid occupancy alone lets + # distinct buses approach within 0.635 mm and look joined. + from .KiCadSchematicScene import WIRE_VISUAL_CLEARANCE + + gx, gy = point(escape) + # Routes join fixed stubs only at outward escape anchors. Reserve + # the entire inward neck, including the red library pin leg, even + # from the SAME net. Otherwise a path may backtrack through its pin + # and hide against the symbol body while the visible stub hangs bare. + inward = (round(math.cos(r)), -round(math.sin(r))) + length = pin_lengths.get(number, 0.0) + body = (px + length * inward[0], py + length * inward[1]) + lo_x, hi_x = sorted((gx, body[0])) + lo_y, hi_y = sorted((gy, body[1])) + for ix in range(math.floor((lo_x - 1.27) / step), math.ceil((hi_x + 1.27) / step) + 1): + for iy in range(math.floor((lo_y - 1.27) / step), math.ceil((hi_y + 1.27) / step) + 1): + qx, qy = point((ix, iy)) + along = (qx - gx) * inward[0] + (qy - gy) * inward[1] + across = abs((qx - gx) * inward[1] - (qy - gy) * inward[0]) + extent = (body[0] - gx) * inward[0] + (body[1] - gy) * inward[1] + if 0.0001 < along <= extent + 0.0001 and across < 1.27 - 0.0001: + pin_necks.add((ix, iy)) + for first, last in (((px, py), (ex, ey)), ((ex, ey), (gx, ey)), ((gx, ey), (gx, gy))): + lo_x, hi_x = sorted((first[0], last[0])) + lo_y, hi_y = sorted((first[1], last[1])) + margin = WIRE_VISUAL_CLEARANCE + for ix in range(math.floor((lo_x - margin) / step), math.ceil((hi_x + margin) / step) + 1): + for iy in range(math.floor((lo_y - margin) / step), math.ceil((hi_y + margin) / step) + 1): + qx, qy = point((ix, iy)) + distance = math.hypot(max(lo_x - qx, qx - hi_x, 0), max(lo_y - qy, qy - hi_y, 0)) + if distance < margin - 0.0001: + fixed_clearance[ix, iy].add(net) + # Reserve the entire escape stub from unrelated nets. + start = grid(px, py) + protected.update((start, escape)) + axis = 0 if start[1] == escape[1] else 1 + for ix in range(min(start[0], escape[0]), max(start[0], escape[0]) + 1): + for iy in range(min(start[1], escape[1]), max(start[1], escape[1]) + 1): + occupied[(ix, iy)] = net + tracks[(ix, iy)].setdefault(net, set()).add(axis) + # Ground glyphs and external net-label text are real graphical obstacles, + # even though they are not physical components in the compiled netlist. + for net, entries in endpoints.items(): + # Repeated physical pins on one IC still need one external island + # label. Reserve its canonical side-facing anchor before a foreign + # pin bus can trap it; final label_islands uses this same ordering. + single_component = len({key[0] for key, _ in entries}) == 1 + label_key = min(entries, key=lambda entry: (escapes[entry[0]][4] % 180 != 0, entry[0]))[0] + for key, _ in entries: + _, _, ex, ey, direction = escapes[key] + if net.lower().split(".")[-1] == "gnd": + component = next(c for c, _, _, _ in placed if c.path == key[0]) + label = getattr(component, "ground_net_labels", {}).get(key[1], "") + bounds = ground_bounds(ex, ey, direction, label) + elif len(entries) == 1 or (single_component and key == label_key): + component = next(c for c, _, _, _ in placed if c.path == key[0]) + name = getattr(component, "net_labels", {}).get(key[1], net) + bounds = pin_label_bounds(name, ex, ey, direction) + + else: + continue + ax, ay = grid(bounds[0], bounds[1]) + bx, by = grid(bounds[2], bounds[3]) + for ix in range(ax, bx + 1): + for iy in range(ay, by + 1): + if single_component and len(entries) > 1 and net.lower().split(".")[-1] != "gnd": + # Its own tree may reach the label terminal; unrelated + # nets must leave the full outline clear. + label_obstacles[(ix, iy)].add(net) + else: + obstacles.add((ix, iy)) + # Preserve verified functional ownership even for explicitly positioned + # circuits: bypass branches terminate at their own device's supply escape, + # never at a neighbouring capacitor simply because it is geometrically near. + local_targets: dict[PinKey, tuple[PinKey, GridPoint]] = {} + components = [c for c, _, _, _ in placed] + for association in decoupling_associations(components, pin_nets, views): + device, *capacitors = association.components + supply, _ = association.nets + device_entries = [(key, pos) for key, pos in endpoints[supply] if key[0] == device] + if len(device_entries) != 1: + continue + for key, pos in endpoints[supply]: + if key[0] in capacitors: + local_targets[key] = device_entries[0] + + def net_order(pair: tuple[str, list[tuple[PinKey, GridPoint]]]) -> tuple[float, int, str] | tuple[int, str]: + net, entries = pair + if strategy == "short_first": + xs, ys = zip(*(p for _, p in entries)) + return (max(xs) - min(xs) + max(ys) - min(ys), len(entries), net) + return (len(entries), net) + + near_cache = _NearForeignCache(tracks, protected) + escape_anchors = {anchor for entries in endpoints.values() for _, anchor in entries} + connected = set() + for net, entries in sorted(endpoints.items(), key=net_order): + if len(entries) < 2 or net.lower().split(".")[-1] == "gnd": + continue + # Build the device backbone first; attach each local bypass directly + # to its verified owner. Sorting also removes input traversal dependence. + entries = sorted(entries, key=lambda entry: (entry[0] in local_targets, entry[0])) + if strategy in ("x", "y", "reverse", "tree_reverse"): + anchors = [entry for entry in entries if entry[0] not in local_targets] + supports = [entry for entry in entries if entry[0] in local_targets] + if strategy in ("reverse", "tree_reverse"): + anchors.reverse() + else: + axis = 0 if strategy == "x" else 1 + anchors.sort(key=lambda entry: (entry[1][axis], entry[1][1 - axis], entry[0])) + entries = anchors + supports + tree = {entries[0][1]} + connected.add(entries[0][0]) + for key, start in entries[1:]: + targets = {local_targets[key][1]} if key in local_targets else tree + target = min(targets, key=lambda p: (abs(p[0] - start[0]) + abs(p[1] - start[1]), p)) + own_stub = set() + if key in local_targets: + px, py, _, _, _ = escapes[key] + pin = grid(px, py) + own_stub = { + (ix, iy) + for ix in range(min(pin[0], start[0]), max(pin[0], start[0]) + 1) + for iy in range(min(pin[1], start[1]), max(pin[1], start[1]) + 1) + } - {start} + direction_search = strategy in ("tree_search", "tree_reverse", "crossing_averse") + # Distance to the actual tree stays informative inside its bounding + # box, avoiding budget exhaustion on sparse U-shaped route trees. + distance_to_tree = tree_distance(targets) if direction_search else None + start_state: RouteState = (start, None) if direction_search else start + queue: list[tuple[float, int, GridPoint, Optional[int]]] = [(0, 0, start, None)] + cost: dict[RouteState, int] = {start_state: 0} + previous: dict[RouteState, RouteState] = {} + found: Optional[RouteState] = None + expanded = 0 + while queue and expanded < 20000: + _, distance, current, prior_direction = heapq.heappop(queue) + state: RouteState = (current, prior_direction) if direction_search else current + if distance != cost.get(state): + continue + if current in targets: + found = state + break + expanded += 1 + for direction, (dx, dy) in enumerate(((1, 0), (-1, 0), (0, 1), (0, -1))): + q = current[0] + dx, current[1] + dy + if not (25 <= q[0] <= 625 and 65 <= q[1] <= 425): + continue + if ( + q in obstacles or any(owner != net for owner in label_obstacles.get(q, ())) + ) and q not in targets: + continue + if q in own_stub or (q in pin_necks and q not in escape_anchors): + continue + if any(owner != net for owner in fixed_clearance.get(q, ())): + continue + axis = 0 if dx else 1 + # A one-cell gap is electrically separate but visually + # ambiguous beside a foreign bus, endpoint or bend. Keep + # parallel tracks at least two 0.635 mm cells apart. A + # strict perpendicular interior crossing remains legal. + if near_cache.blocked(q, axis, net): + continue + others = {n: axes for n, axes in tracks.get(q, {}).items() if n != net} + if others: + if q in protected or any(axis in axes for axes in others.values()): + continue + # Crossings must pass straight through, never terminate or + # turn on another net. No junction is emitted at crossings. + if any(n != net for n in tracks.get(current, {})): + if prior_direction != direction: + continue + new_cost = ( + distance + + 1 + + (24 if others and strategy == "crossing_averse" else 0) + + (3 if prior_direction is not None and prior_direction != direction else 0) + ) + next_state: RouteState = (q, direction) if direction_search else q + if new_cost >= cost.get(next_state, float("inf")): + continue + cost[next_state] = new_cost + previous[next_state] = state + if distance_to_tree is not None: + heuristic = distance_to_tree(q) + else: + heuristic = abs(q[0] - target[0]) + abs(q[1] - target[1]) + heapq.heappush(queue, (new_cost + heuristic, new_cost, q, direction)) + if found is None: + failures.append((key, net)) + continue + state_path = [found] + while state_path[-1] != start_state: + state_path.append(previous[state_path[-1]]) + state_path.reverse() + if direction_search: + path = [cast(tuple[GridPoint, Optional[int]], item)[0] for item in state_path] + else: + path = [cast(GridPoint, item) for item in state_path] + if key in local_targets: + direct = abs(start[0] - target[0]) + abs(start[1] - target[1]) + other_caps = {pos for other, pos in entries if other != key and other in local_targets} + # Conflicting hints must not turn a local bypass into a remote + # loop or a chain through another bypass endpoint. + if len(path) - 1 > 2 * direct + 16 or other_caps.intersection(path): + failures.append((key, net)) + continue + tree.update(path) + connected.add(key) + near_cache.protect((path[0], path[-1])) + for i, q in enumerate(path): + occupied[q] = net + axes = set() + for neighbor in path[max(0, i - 1) : i] + path[i + 1 : i + 2]: + axes.add(0 if neighbor[1] == q[1] else 1) + near_cache.add_track(q, net, axes) + if len(axes) > 1: + near_cache.protect((q,)) + compact = [path[0]] + for i in range(1, len(path) - 1): + before = path[i][0] - path[i - 1][0], path[i][1] - path[i - 1][1] + after = path[i + 1][0] - path[i][0], path[i + 1][1] - path[i][1] + if before != after: + compact.append(path[i]) + compact.append(path[-1]) + for first_point, last_point in zip(compact, compact[1:]): + if first_point != last_point: + wires.append((net, point(first_point), point(last_point))) + routed_nets = {net for net, _, _ in wires} + for key, (_, _, ex, ey, _) in sorted(escapes.items()): + net = pin_nets[key] + if net not in routed_nets: + continue + gx, gy = point(grid(ex, ey)) + # Real library pins need not lie on the routing grid. Preserve the exact + # electrical contact with short orthogonal transitions to the search grid. + if ex != gx: + wires.append((net, (ex, ey), (gx, ey))) + if ey != gy: + wires.append((net, (gx, ey), (gx, gy))) + return wires, escapes, failures + + +def split_group(placed: Placements, views: Views, pin_nets: PinNets) -> Optional[tuple[Placements, Placements]]: + """Cut complete functional atoms, minimizing signal-net page boundaries.""" + from .KiCadSchematicPlacement import functional_atoms, signal_nets, atom_bounds + + components = [entry[0] for entry in placed] + atoms, _ = functional_atoms(components, pin_nets, views) + paths = [c.path for c in components] + endpoints = signal_nets(components, pin_nets) + choices = [] + for cut in range(1, len(placed)): + left, right = set(paths[:cut]), set(paths[cut:]) + if any(set(atom) & left and set(atom) & right for atom in atoms): + continue + crossing = sum(bool(ends & left) and bool(ends & right) for ends in endpoints.values()) + a, b = atom_bounds(placed[:cut], views), atom_bounds(placed[cut:], views) + area_a, area_b = (a[2] - a[0]) * (a[3] - a[1]), (b[2] - b[0]) * (b[3] - b[1]) + choices.append(((crossing, abs(area_a - area_b), abs(2 * cut - len(placed)), tuple(sorted(left))), cut)) + if not choices: + return None + _, cut = min(choices) + return placed[:cut], placed[cut:] diff --git a/edg/electronics_model/KiCadSchematicOrientation.py b/edg/electronics_model/KiCadSchematicOrientation.py new file mode 100644 index 000000000..d3270ac12 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicOrientation.py @@ -0,0 +1,492 @@ +"""Bounded deterministic orientation trials with immutable physical pin identities.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable, Collection, Mapping, Optional, Sequence +from .KiCadSchematicPlanner import region_fits_page +from .KiCadSchematicTypes import Bounds, Point, PinKey, PinNets, Wire, Placement, Placements, Views, RouteResult + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent, SymbolView +from typing import TypedDict + + +class ConflictIdentities(TypedDict): + escape: frozenset[tuple[str, PinKey, str | PinKey]] + visual_clearance: frozenset[tuple[Wire, ...]] + + +from collections import defaultdict + +from .KiCadSchematicLayout import freeze_annotations, pins +from .KiCadSchematicPlacement import ( + packing_bounds, + component_boxes, + _overlap, + _score as geometry_score, + _stage_intrusions, +) +from .KiCadSchematicRouting import route_metrics +from .KiCadSchematicScene import wire_visual_conflict, pin_name_items, pin_number_items + + +def _segments(route: RouteResult, pin_nets: PinNets) -> list[Wire]: + result = list(route[0]) + for key, (px, py, ex, ey, _) in route[1].items(): + net = pin_nets.get(key) + if net is not None: + result.append((net, (px, py), (ex, ey))) + return result + + +def _visual_conflicts(segments: Sequence[Wire]) -> int: + # Spatial buckets avoid an all-wire quadratic scan on large IC regions. + buckets: dict[tuple[int, int], list[int]] = defaultdict(list) + pairs: set[tuple[int, int]] = set() + for i, (_, a, b) in enumerate(segments): + for x in range(int((min(a[0], b[0]) - 1.27) // 10.16), int((max(a[0], b[0]) + 1.27) // 10.16) + 1): + for y in range(int((min(a[1], b[1]) - 1.27) // 10.16), int((max(a[1], b[1]) + 1.27) // 10.16) + 1): + for j in buckets[x, y]: + pairs.add((j, i)) + buckets[x, y].append(i) + return sum( + segments[i][0] != segments[j][0] and wire_visual_conflict(*segments[i][1:], *segments[j][1:]) for i, j in pairs + ) + + +def orientation_metrics(placed: Placements, views: Views, pin_nets: PinNets, route: RouteResult) -> dict[str, Any]: + segments = _segments(route, pin_nets) + metric: dict[str, Any] = dict(route_metrics(segments, route[2])) + primary = { + net for c, _, _, _ in placed for net in getattr(getattr(c, "functional_circuit", None), "primary_nets", ()) + } + # Verified internal power paths matter even when authored boundary roles + # classify the external terminals as supplies rather than signal inputs. + from .KiCadSchematicPower import topology_primary_endpoints + + topology_endpoints = topology_primary_endpoints([c for c, _, _, _ in placed], pin_nets, views) + primary.update(topology_endpoints) + # A labeled bulk-bank branch does not sever the converter's main visible + # path. Count core physical endpoints on a verified converter net, while + # retaining authored net-level semantics outside that unique topology. + primary_failures = [ + (key, net) + for key, net in route[2] + if net in primary and (net not in topology_endpoints or key in topology_endpoints[net]) + ] + metric["primary_fallbacks"] = len(primary_failures) + metric["noncore_converter_fallbacks"] = sum( + net in topology_endpoints and key not in topology_endpoints[net] for key, net in route[2] + ) + metric["primary_fallback_scope"] = ( + "Core physical endpoints of uniquely verified converter nets; " + "authored net-level primary paths elsewhere. Bulk/bypass bank endpoints excluded." + ) + metric["unrelated_intrusions"] = _stage_intrusions(placed, route[0], views, pin_nets) + terminals = defaultdict(list) + for c, x, y, angle in placed: + for number, px, py, _ in pins(views[c.path], x, y, angle): + if (c.path, number) in pin_nets: + terminals[pin_nets[c.path, number]].append((px, py)) + lower = sum( + max(x for x, y in pts) - min(x for x, y in pts) + max(y for x, y in pts) - min(y for x, y in pts) + for pts in terminals.values() + if len(pts) > 1 + ) + metric["detour_mm"] = round(max(0, metric["length_mm"] - lower), 4) + metric["visual_conflicts"] = _visual_conflicts(segments) + return metric + + +def _rank(metric: Mapping[str, Any]) -> tuple[float, ...]: + return tuple( + metric[key] + for key in ("primary_fallbacks", "crossings", "unrelated_intrusions", "bends", "detour_mm", "length_mm") + ) + + +def _geometry(placed: Placements, views: Views, pin_nets: PinNets) -> dict[str, Any]: + score = geometry_score(placed, views, pin_nets) + a, b, c, d = packing_bounds(placed, views, pin_nets) + width, height = c - a, d - b + boxes: list[tuple[str, int, Bounds]] = [] + for entry in placed: + component, x, y, angle = entry + measured = component_boxes(entry, views) + measured += [ + item["bounds"] + for item in ( + pin_name_items(views[component.path].definition, x, y, angle) + + pin_number_items(views[component.path].definition, x, y, angle) + ) + ] + boxes.extend((component.path, index, box) for index, box in enumerate(measured)) + contacts = sorted( + (a, ai, b, bi) + for i, (a, ai, first) in enumerate(boxes) + for b, bi, second in boxes[i + 1 :] + if a != b and _overlap(first, second) + ) + return dict( + collision_pairs=contacts, + escape_conflicts=score[0], + collisions=score[1], + clipped=not region_fits_page(width, height), + ) + + +def optimize_orientations( + source_placed: Placements, + views: Views, + pin_nets: PinNets, + router: Callable[[Placements, Views, PinNets], RouteResult], + *, + locked: Collection[str] = (), + baseline: Optional[RouteResult] = None, + region_bounds: Optional[Callable[[Placements, RouteResult], Bounds]] = None, +) -> tuple[list[Placement], RouteResult, dict[str, Any]]: + """Try each unlocked PB path once per sweep, at most two complete sweeps. + + The incumbent route is cached. Each geometrically viable trial invokes only + the baseline router; its pin-neck and text/ground/label masks remain active. + Route-order optimization belongs to the caller and runs only after selection. + Automatic fields are recomputed from source objects for each orientation; + explicitly authored annotations retain their coordinates. + """ + current = list(source_placed) + placed = freeze_annotations(current, views) + route = baseline if baseline is not None else router(placed, views, pin_nets) + before = metric = orientation_metrics(placed, views, pin_nets, route) + original_failures = set(route[2]) + geometry = _geometry(placed, views, pin_nets) + locked = set(locked) + eligibility = [ + dict( + path=c.path, + eligible=c.path not in locked, + reason="explicit rotation lock" if c.path in locked else "180 degree trial", + ) + for c, _, _, _ in sorted(current, key=lambda e: e[0].path) + ] + trials: list[dict[str, Any]] = [] + route_calls, sweeps = 0, 0 + for sweep in range(2): + improved = False + sweeps += 1 + for index in sorted(range(len(current)), key=lambda i: current[i][0].path): + c, x, y, angle = current[index] + if c.path in locked: + continue + candidate = list(current) + candidate[index] = c, x, y, (angle + 180) % 360 + trial_placed = freeze_annotations(candidate, views) + trial_geometry = _geometry(trial_placed, views, pin_nets) + reason = next( + (key for key in ("escape_conflicts", "collisions") if trial_geometry[key] > geometry[key]), None + ) + if not set(trial_geometry.get("collision_pairs", ())) <= set(geometry.get("collision_pairs", ())): + reason = "new symbol, field or pin text collision" + if trial_geometry["clipped"]: + reason = "page overflow" + trial: dict[str, Any] = dict( + sweep=sweep + 1, + path=c.path, + from_rotation=angle, + to_rotation=(angle + 180) % 360, + selected=False, + geometry=trial_geometry, + ) + if reason is None: + trial_route = router(trial_placed, views, pin_nets) + route_calls += 1 + trial_metric = orientation_metrics(trial_placed, views, pin_nets, trial_route) + trial["metrics"] = trial_metric + if region_bounds is not None: + a, b, cx, d = region_bounds(trial_placed, trial_route) + width, height = cx - a, d - b + trial_geometry["clipped"] = not region_fits_page(width, height) + if trial_geometry["clipped"]: + reason = "routed region page overflow" + elif not set(trial_route[2]) <= original_failures: + reason = "new failed endpoints" + elif trial_metric["visual_conflicts"] > metric["visual_conflicts"]: + reason = "inadequate visual wire clearance" + elif _rank(trial_metric) >= _rank(metric): + reason = "incumbent scores better or ties" + else: + current, placed, route, metric, geometry = ( + candidate, + trial_placed, + trial_route, + trial_metric, + trial_geometry, + ) + trial["selected"] = True + improved = True + reason = "improved routed score" + trial["reason"] = reason + trials.append(trial) + if not improved: + break + return ( + placed, + route, + dict( + eligibility=eligibility, + trials=trials, + sweeps=sweeps, + route_trials=route_calls, + before=before, + after=metric, + selected_rotations={c.path: angle for c, _, _, angle in placed}, + metric_scope="Union of local routed wires and fixed pin stubs; detour uses Manhattan bounding lower bound. Primary fallbacks count core physical endpoints on uniquely verified converter paths, excluding bulk/bypass bank endpoints; authored primary nets elsewhere retain net-level semantics. Final repaired label tails are checked downstream by the shared scene.", + ), + ) + + +_PASSIVE_QUARTER_TURN_SYMBOLS = frozenset( + ( + "Device:R", + "Device:R_US", + "Device:C", + "Device:C_Polarized", + "Device:L", + ) +) + + +def passive_orientation_rank(metric: Mapping[str, Any]) -> tuple[float, ...]: + """Balanced wire cost after electrical visibility and crossing priorities.""" + return ( + metric["primary_fallbacks"], + metric["crossings"], + metric["unrelated_intrusions"], + round(metric["length_mm"] + 2.54 * metric["bends"], 4), + ) + + +def _passive_quarter_turn_eligibility( + component: PhysicalComponent, view: SymbolView, locked: Collection[str] +) -> tuple[bool, str]: + if component.path in locked: + return False, "explicit rotation lock" + # Resolver-derived IDs carry a pin-map suffix. Reference prefixes, + # footprint names and two-pin generic boxes do not establish a passive. + lib_id = view.lib_id.rsplit("_PB_", 1)[0] + if lib_id not in _PASSIVE_QUARTER_TURN_SYMBOLS: + return False, "not a verified resistor, capacitor or inductor symbol" + if len({(x, y) for _, x, y, _ in view.pins}) != 2: + return False, "symbol does not have two distinct terminal attachment positions" + return True, "verified two-terminal passive" + + +def _escape_conflict_identities( + placed: Placements, views: Views, pin_nets: PinNets +) -> frozenset[tuple[str, PinKey, str | PinKey]]: + """Physical endpoint identities distinguish replacement escape conflicts.""" + from .KiCadSchematicPlacement import pin_escapes + from .KiCadSchematicScene import segments_touch, segment_box + + escapes = pin_escapes(placed, views, pin_nets) + glyphs = [ + (c.path, item["identity"], item["bounds"]) + for c, x, y, angle in placed + for item in ( + pin_name_items(views[c.path].definition, x, y, angle, c.path) + + pin_number_items(views[c.path].definition, x, y, angle, c.path) + ) + ] + conflicts: set[tuple[str, PinKey, str | PinKey]] = set() + for index, (net, a, b, owner, number) in enumerate(escapes): + key = owner, number + for other_owner, identity, box in glyphs: + if owner != other_owner and segment_box(a, b, box): + conflicts.add(("pin_text", key, identity)) + for other_net, c, d, other_owner, other_number in escapes[index + 1 :]: + if net != other_net and segments_touch(a, b, c, d): + first_key, second_key = sorted((key, (other_owner, other_number))) + conflicts.add(("escape_pair", first_key, second_key)) + return frozenset(conflicts) + + +def _visual_clearance_conflict_identities(route: RouteResult, pin_nets: PinNets) -> frozenset[tuple[Wire, ...]]: + """Canonical wire-union contacts, independent of collinear segmentation. + + Coordinates distinguish a new bad location on an already affected net pair. + Existing count-based clearance checks remain active independently. + """ + lines = defaultdict(list) + for net, a, b in _segments(route, pin_nets): + if a == b: + continue + axis = 0 if a[1] == b[1] else 1 + fixed = a[1 - axis] + lines[net, axis, fixed].append(tuple(sorted((a[axis], b[axis])))) + segments = [] + for (net, axis, fixed), intervals in sorted(lines.items()): + merged: list[Point] = [] + for lo, hi in sorted(intervals): + if merged and lo <= merged[-1][1]: + merged[-1] = merged[-1][0], max(hi, merged[-1][1]) + else: + merged.append((lo, hi)) + for lo, hi in merged: + a, b = ((lo, fixed), (hi, fixed)) if axis == 0 else ((fixed, lo), (fixed, hi)) + segments.append((net, a, b)) + buckets: dict[tuple[int, int], list[int]] = defaultdict(list) + pairs: set[tuple[int, int]] = set() + for index, (_, a, b) in enumerate(segments): + for x in range(int((min(a[0], b[0]) - 1.27) // 10.16), int((max(a[0], b[0]) + 1.27) // 10.16) + 1): + for y in range(int((min(a[1], b[1]) - 1.27) // 10.16), int((max(a[1], b[1]) + 1.27) // 10.16) + 1): + pairs.update((other, index) for other in buckets[x, y]) + buckets[x, y].append(index) + return frozenset( + tuple(sorted((segments[i], segments[j]))) + for i, j in pairs + if segments[i][0] != segments[j][0] and wire_visual_conflict(*segments[i][1:], *segments[j][1:]) + ) + + +def orientation_conflict_identities( + placed: Placements, views: Views, pin_nets: PinNets, route: RouteResult +) -> ConflictIdentities: + """Additional monotonic safety guards for quarter turns and final rerouting.""" + return ConflictIdentities( + escape=_escape_conflict_identities(placed, views, pin_nets), + visual_clearance=_visual_clearance_conflict_identities(route, pin_nets), + ) + + +def optimize_passive_orientations( + source_placed: Placements, + views: Views, + pin_nets: PinNets, + router: Callable[[Placements, Views, PinNets], RouteResult], + *, + locked: Collection[str] = (), + baseline: Optional[RouteResult] = None, + region_bounds: Optional[Callable[[Placements, RouteResult], Bounds]] = None, + source_annotations: Optional[Mapping[str, Optional[Point]]] = None, +) -> tuple[list[Placement], RouteResult, dict[str, Any]]: + """One complete stable sweep, at most three routed trials per passive. + + All three alternatives for a component start from the same incumbent. Only + the best valid angle commits, and ties preserve the incumbent. The caller + binds ``router`` to the incumbent's selected routing strategy and performs + final route-order and serialized-scene validation after this local search. + + ``source_annotations`` distinguishes authored coordinates from frozen + automatic fields in a prepared baseline; it must contain None for automatic + fields. Omitting the map preserves annotations supplied by direct callers. + """ + from copy import copy + + current = [] + for component, x, y, angle in source_placed: + source = copy(component) + if source_annotations is not None and component.path in source_annotations: + source.annotation = source_annotations[component.path] + current.append((source, x, y, angle)) + placed = freeze_annotations(current, views) + route = baseline if baseline is not None else router(placed, views, pin_nets) + before = metric = orientation_metrics(placed, views, pin_nets, route) + geometry = _geometry(placed, views, pin_nets) + conflicts = orientation_conflict_identities(placed, views, pin_nets, route) + locked = set(locked) + eligibility = [] + eligible = set() + for component, _, _, _ in sorted(current, key=lambda entry: entry[0].path): + allowed, eligibility_reason = _passive_quarter_turn_eligibility(component, views[component.path], locked) + eligibility.append( + dict( + path=component.path, + eligible=allowed, + reason=eligibility_reason, + allowed_rotations=[0, 90, 180, 270] if allowed else [], + ) + ) + if allowed: + eligible.add(component.path) + trials: list[dict[str, Any]] = [] + route_calls, changed = 0, False + for index in sorted(range(len(current)), key=lambda i: current[i][0].path): + component, x, y, angle = current[index] + if component.path not in eligible: + continue + best = None + visit_failures = set(route[2]) + for alternative in (0, 90, 180, 270): + if alternative == angle: + continue + candidate = list(current) + candidate[index] = component, x, y, alternative + trial_placed = freeze_annotations(candidate, views) + trial_geometry = _geometry(trial_placed, views, pin_nets) + reason = next( + (key for key in ("escape_conflicts", "collisions") if trial_geometry[key] > geometry[key]), None + ) + if not set(trial_geometry.get("collision_pairs", ())) <= set(geometry.get("collision_pairs", ())): + reason = "new symbol, field or pin text collision" + trial_escape_conflicts = _escape_conflict_identities(trial_placed, views, pin_nets) + if not trial_escape_conflicts <= conflicts["escape"]: + reason = "new physical escape conflict" + if trial_geometry["clipped"]: + reason = "page overflow" + trial: dict[str, Any] = dict( + path=component.path, + from_rotation=angle, + to_rotation=alternative, + selected=False, + acceptable=False, + geometry=trial_geometry, + ) + if reason is None: + trial_route = router(trial_placed, views, pin_nets) + route_calls += 1 + trial_metric = orientation_metrics(trial_placed, views, pin_nets, trial_route) + trial["metrics"] = trial_metric + if region_bounds is not None: + a, b, c, d = region_bounds(trial_placed, trial_route) + width, height = c - a, d - b + trial_geometry["clipped"] = not region_fits_page(width, height) + if trial_geometry["clipped"]: + reason = "routed region page overflow" + elif not set(trial_route[2]) <= visit_failures: + reason = "new failed endpoints" + elif not _visual_clearance_conflict_identities(trial_route, pin_nets) <= conflicts["visual_clearance"]: + reason = "new visual wire clearance conflict" + elif trial_metric["visual_conflicts"] > metric["visual_conflicts"]: + reason = "inadequate visual wire clearance" + elif passive_orientation_rank(trial_metric) >= passive_orientation_rank(metric): + reason = "incumbent scores better or ties" + else: + trial["acceptable"] = True + reason = "another angle for this component scores better" + if best is None or passive_orientation_rank(trial_metric) < passive_orientation_rank(best[3]): + best = candidate, trial_placed, trial_route, trial_metric, trial_geometry, len(trials) + trial["reason"] = reason + trials.append(trial) + if best is not None: + current, placed, route, metric, geometry, chosen = best + trials[chosen]["selected"] = True + trials[chosen]["reason"] = "improved balanced routed score" + conflicts = orientation_conflict_identities(placed, views, pin_nets, route) + changed = True + return ( + placed, + route, + dict( + mode="passive_quarter_turn", + eligibility=eligibility, + trials=trials, + sweeps=1 if eligible else 0, + route_trials=route_calls, + eligible_passives=len(eligible), + route_trial_limit=3 * len(eligible), + changed=changed, + before=before, + after=metric, + final_rotations={component.path: angle for component, _, _, angle in placed}, + metric_scope="Union of local routed wires and fixed pin stubs; weighted cost is length_mm + 2.54*bends. Final serialized label, field and GND findings are checked by the caller.", + ), + ) diff --git a/edg/electronics_model/KiCadSchematicOverview.py b/edg/electronics_model/KiCadSchematicOverview.py new file mode 100644 index 000000000..bd59f6c0f --- /dev/null +++ b/edg/electronics_model/KiCadSchematicOverview.py @@ -0,0 +1,696 @@ +"""Presentation-only system overviews backed by compiled cross-sheet nets. + +Diagram connectors are graphics, never electrical wires. Direction is an explicit +source annotation; shared-net witnesses establish association, not signal flow. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import heapq +import math +import re +import textwrap +from typing import Any, Mapping, Tuple, Sequence, TYPE_CHECKING, cast +from .KiCadSchematicWriter import S, children, effects, node, uid +from .KiCadSchematicTypes import SExpr, Bounds, GridPoint + +if TYPE_CHECKING: + from .KiCadSchematicExporter import _PreparedBoard, SchematicExportOptions + from .KiCadSchematicPlanner import SchematicSheetPlan, SchematicSheet + +GRID = 1.27 +CARD_W, CARD_H = 83.82, 27.94 + + +def _text(value: object, name: str, limit: int | None = None) -> None: + if ( + not isinstance(value, str) + or not value.strip() + or value != value.strip() + or (limit is not None and len(value) > limit) + ): + raise ValueError(f"{name} must be nonempty text" + (f" of at most {limit} characters" if limit else "")) + + +def _object(value: object, fields: Sequence[str], required: Sequence[str]) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or set(value) - set(fields) or set(required) - set(value): + raise ValueError("overview object has unknown or missing fields") + return value + + +@dataclass(frozen=True) +class SchematicOverviewBlock: + sheet: str + title: str + summary: str + column: int + row: int + + def __post_init__(self) -> None: + _text(self.sheet, "overview sheet") + _text(self.title, "overview title", 48) + _text(self.summary, "overview summary", 96) + for value in (self.column, self.row): + if type(value) is not int or not 0 <= value <= 3: + raise ValueError("overview column and row must be integers from 0 to 3") + + def to_dict(self) -> dict[str, Any]: + return dict(sheet=self.sheet, title=self.title, summary=self.summary, column=self.column, row=self.row) + + @classmethod + def from_dict(cls, value: object) -> SchematicOverviewBlock: + return cls( + **_object( + value, ("sheet", "title", "summary", "column", "row"), ("sheet", "title", "summary", "column", "row") + ) + ) + + +@dataclass(frozen=True) +class SchematicOverviewLink: + source: str + target: str + label: str + nets: Tuple[str, ...] + directed: bool = False + + def __post_init__(self) -> None: + _text(self.source, "overview link source") + _text(self.target, "overview link target") + _text(self.label, "overview link label", 48) + if ( + not isinstance(self.nets, tuple) + or not self.nets + or not all(isinstance(n, str) for n in self.nets) + or len(set(self.nets)) != len(self.nets) + ): + raise ValueError("overview link nets must be a nonempty tuple without duplicates") + for net in self.nets: + _text(net, "overview link net") + if not isinstance(self.directed, bool): + raise ValueError("overview directed must be boolean") + + def to_dict(self) -> dict[str, Any]: + return dict( + source=self.source, target=self.target, label=self.label, nets=list(self.nets), directed=self.directed + ) + + @classmethod + def from_dict(cls, value: object) -> SchematicOverviewLink: + data = dict( + _object(value, ("source", "target", "label", "nets", "directed"), ("source", "target", "label", "nets")) + ) + if not isinstance(data["nets"], (list, tuple)): + raise ValueError("overview link nets must be an array") + data["nets"] = tuple(data["nets"]) + return cls(**data) + + +@dataclass(frozen=True) +class SchematicOverview: + blocks: Tuple[SchematicOverviewBlock, ...] = () + links: Tuple[SchematicOverviewLink, ...] = () + + def __post_init__(self) -> None: + if ( + not isinstance(self.blocks, tuple) + or len(self.blocks) > 16 + or not all(isinstance(v, SchematicOverviewBlock) for v in self.blocks) + ): + raise ValueError("overview blocks must be a tuple of at most 16 blocks") + if ( + not isinstance(self.links, tuple) + or len(self.links) > 8 + or not all(isinstance(v, SchematicOverviewLink) for v in self.links) + ): + raise ValueError("overview links must be a tuple of at most 8 links") + + def to_dict(self) -> dict[str, Any]: + return dict(blocks=[v.to_dict() for v in self.blocks], links=[v.to_dict() for v in self.links]) + + @classmethod + def from_dict(cls, value: object) -> SchematicOverview: + data = _object(value, ("blocks", "links"), ()) + if any(not isinstance(data.get(k, []), (list, tuple)) for k in ("blocks", "links")): + raise ValueError("overview blocks and links must be arrays") + return cls( + tuple(SchematicOverviewBlock.from_dict(v) for v in data.get("blocks", [])), + tuple(SchematicOverviewLink.from_dict(v) for v in data.get("links", [])), + ) + + +def _ground(net: str) -> bool: + return any(p in ("gnd", "ground") for p in re.split(r"[.\[\]]", net.lower())) + + +def _route( + start: Sequence[float], end: Sequence[float], rectangles: Sequence[Sequence[float]], occupied: set[GridPoint] +) -> tuple[list[list[float]], set[GridPoint]]: + def grid(p: Sequence[float]) -> GridPoint: + return round(p[0] / GRID), round(p[1] / GRID) + + grid_start, grid_end = grid(start), grid(end) + blocked = set(occupied) + for x1, y1, x2, y2 in rectangles: + for x in range(math.floor(x1 / GRID), math.ceil(x2 / GRID) + 1): + for y in range(math.floor(y1 / GRID), math.ceil(y2 / GRID) + 1): + blocked.add((x, y)) + blocked.discard(grid_start) + blocked.discard(grid_end) + queue: list[tuple[float, float, GridPoint, int]] = [(0, 0, grid_start, -1)] + best: dict[tuple[GridPoint, int], float] = {(grid_start, -1): 0} + previous: dict[tuple[GridPoint, int], tuple[GridPoint, int]] = {} + goal = None + while queue: + _, cost, point, direction = heapq.heappop(queue) + key = (point, direction) + if best.get(key) != cost: + continue + if point == grid_end: + goal = key + break + for d, (dx, dy) in enumerate(((1, 0), (0, 1), (-1, 0), (0, -1))): + nxt = point[0] + dx, point[1] + dy + if not (14 <= nxt[0] <= 314 and 36 <= nxt[1] <= 150) or nxt in blocked: + continue + nc = cost + 1 + (0.3 if direction not in (-1, d) else 0) + nk = (nxt, d) + if nc < best.get(nk, math.inf): + best[nk] = nc + previous[nk] = key + heapq.heappush(queue, (nc + abs(nxt[0] - grid_end[0]) + abs(nxt[1] - grid_end[1]), nc, nxt, d)) + if goal is None: + return [], set() + points = [] + while True: + points.append(goal[0]) + if goal not in previous: + break + goal = previous[goal] + points.reverse() + compact = [points[0]] + for i in range(1, len(points) - 1): + if (points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]) != ( + points[i + 1][0] - points[i][0], + points[i + 1][1] - points[i][1], + ): + compact.append(points[i]) + if len(points) > 1: + compact.append(points[-1]) + return [[round(x * GRID, 4), round(y * GRID, 4)] for x, y in compact], set(points) + + +def _segment_cells(a: Sequence[float], b: Sequence[float]) -> set[GridPoint]: + ga, gb = [(round(p[0] / GRID), round(p[1] / GRID)) for p in (a, b)] + return { + (x, y) + for x in range(min(ga[0], gb[0]), max(ga[0], gb[0]) + 1) + for y in range(min(ga[1], gb[1]), max(ga[1], gb[1]) + 1) + } + + +def _intersects(a: Sequence[float], b: Sequence[float]) -> bool: + return not (a[2] < b[0] or b[2] < a[0] or a[3] < b[1] or b[3] < a[1]) + + +def _tag_box(p: Sequence[float]) -> Bounds: + return (p[0] - 0.5, p[1] - 1.4, p[0] + 3.8, p[1] + 1.4) + + +def _position_tags(nodes: Sequence[dict[str, Any]], links: Sequence[dict[str, Any]], diagnostics: list[str]) -> None: + # Reserve all strokes and arrowheads before placing any text. Label IDs are + # graphical annotations, so they must never sit on another relationship. + obstacles = [(x1 - 0.8, y1 - 0.8, x2 + 0.8, y2 + 0.8) for x1, y1, x2, y2 in (n["bounds"] for n in nodes)] + for link in links: + for a, b in zip(link["path"], link["path"][1:]): + obstacles.append( + (min(a[0], b[0]) - 0.65, min(a[1], b[1]) - 0.65, max(a[0], b[0]) + 0.65, max(a[1], b[1]) + 0.65) + ) + if link["directed"] and link["path"]: + a, b = link["path"][-2:] + obstacles.append( + (min(a[0], b[0]) - 1.1, min(a[1], b[1]) - 1.1, max(a[0], b[0]) + 1.1, max(a[1], b[1]) + 1.1) + ) + for link in links: + candidates = [] + for a, b in zip(link["path"], link["path"][1:]): + length = math.dist(a, b) + if length < GRID: + continue + steps = max(1, round(length / GRID)) + for step in sorted(range(steps + 1), key=lambda i: (abs(i - steps / 2), i)): + x = a[0] + (b[0] - a[0]) * step / steps + y = a[1] + (b[1] - a[1]) * step / steps + for side in (-1, 1): + candidates.append( + (x - 1.65, y + side * 3.81) if a[1] == b[1] else (x + side * 3.81 - (3.8 if side < 0 else 0), y) + ) + tag = None + for candidate in candidates: + box = _tag_box(candidate) + if ( + 18 <= box[0] + and box[2] <= 396 + and 47 <= box[1] + and box[3] <= 190 + and not any(_intersects(box, o) for o in obstacles) + ): + tag = [round(v, 4) for v in candidate] + obstacles.append(box) + break + link["tag"] = tag + if tag is None and link["path"]: + link["path"] = [] + link["status"] = "legend_only" + diagnostics.append(link["id"] + ": no clear diagram tag position; relationship retained in connection key") + + +def build_overviews( + boards: Sequence[_PreparedBoard], plan: SchematicSheetPlan, custom: SchematicOverview | None = None +) -> dict[str, Any]: + custom = custom or SchematicOverview() + if not isinstance(custom, SchematicOverview): + raise ValueError("overview must be a SchematicOverview") + all_sheets = [s for s in plan.sheets if s.id != "overview"] + + def resolve(selector: str) -> SchematicSheet: + found = [s for s in all_sheets if s.id == selector] + if not found: + found = [s for s in all_sheets if s.title == selector] + if len(found) != 1: + raise ValueError("unknown or ambiguous overview sheet: " + selector) + return found[0] + + blocks = {} + for authored_block in custom.blocks: + sheet = resolve(authored_block.sheet) + if sheet.id in blocks: + raise ValueError("duplicate overview block: " + authored_block.sheet) + blocks[sheet.id] = authored_block + links = [] + pairs = set() + for authored_link in custom.links: + source, target = resolve(authored_link.source), resolve(authored_link.target) + if source.scope != target.scope or source.id == target.id: + raise ValueError("overview links must join different sheets in one board scope") + pair = tuple(sorted((source.id, target.id))) + if pair in pairs: + raise ValueError("duplicate overview relationship") + pairs.add(pair) + links.append((source, target, authored_link)) + result: dict[str, Any] = dict(schema=1, fingerprint=plan.fingerprint, boards=[]) + for board in boards: + sheets = [s for s in all_sheets if s.scope == board.scope] + sheet_of = {p.region_id: s.id for s in sheets for p in s.regions} + available: dict[tuple[str, str], list[str]] = {} + for net, regions in sorted(board.net_regions.items()): + if _ground(net): + continue + pages = sorted({sheet_of[r] for r in regions if r in sheet_of}) + for i, a in enumerate(pages): + for b in pages[i + 1 :]: + available.setdefault((a, b), []).append(net) + used = set() + nodes: list[dict[str, Any]] = [] + overview_present = any(s.id == "overview" and s.scope == board.scope for s in plan.sheets) + mode = "diagram" if len(sheets) <= 16 else "directory" + for sheet in sheets: + if sheet.id in blocks: + occupied_block = blocks[sheet.id] + if (occupied_block.column, occupied_block.row) in used: + raise ValueError("overview blocks occupy the same grid cell") + used.add((occupied_block.column, occupied_block.row)) + for index, sheet in enumerate(sheets): + block = blocks.get(sheet.id) + if block and mode != "diagram": + raise ValueError("custom overview diagrams support at most 16 sheets per scope") + if block: + column, row = block.column, block.row + else: + free = next( + ((c, r) for r in range(4) for c in range(4) if (c, r) not in used), (index // 10, index % 10) + ) + column, row = free + used.add(free) + groups = [board.regions[p.region_id].spec.title for p in sheet.regions] + # Region continuation indices describe packing fragments, not circuit + # sheet numbers. Only the actual sheet title names a continuation. + summary_groups = list(dict.fromkeys(re.sub(r" /\d+$", "", group) for group in groups)) + summary = "; ".join(summary_groups) + if len(summary) > 96: + summary = summary[:76].rsplit(";", 1)[0] + f"; {len(groups)} circuit regions" + x, y = round(20.32 + column * 96.52, 4), round(49.53 + row * 36.83, 4) + nodes.append( + dict( + sheet_id=sheet.id, + sheet_title=sheet.title, + title=( + block.title + if block + else ( + re.sub(r"^\d+[. ]+", "", sheet.title)[:45] + "..." + if len(re.sub(r"^\d+[. ]+", "", sheet.title)) > 48 + else re.sub(r"^\d+[. ]+", "", sheet.title) + ) + ), + summary=block.summary if block else summary[:96], + column=column, + row=row, + page=sheets.index(sheet) + (2 if overview_present else 1), + components=sum(len(board.regions[p.region_id].spec.components) for p in sheet.regions), + regions=groups, + section=groups[0].split(" /")[0] if groups else sheet.title, + bounds=[x, y, round(x + CARD_W, 4), round(y + CARD_H, 4)], + ) + ) + directory_pages = [] + if mode == "directory": + if len(nodes) > 40: + # The serializer inserts Contents pages above forty children. + # Record the real document owning each circuit link, and its + # legacy measured bounds there, rather than claiming those links + # exist on the overview root. Keep that pagination unbounded. + for index, item in enumerate(nodes): + bucket, slot = divmod(index, 40) + x, y = 20 + (slot // 10) * 90, 50 + (slot % 10) * 14 + item["column"], item["row"] = divmod(slot, 10) + item["bounds"] = [x, y, x + 80, y + 8] + item["directory_document"] = board.prefix + f"_contents_{bucket + 1}.kicad_sch" + for bucket in range((len(nodes) + 39) // 40): + members = nodes[bucket * 40 : (bucket + 1) * 40] + x, y = 20 + (bucket // 10) * 90, 50 + (bucket % 10) * 14 + directory_pages.append( + dict( + index=bucket, + title=f"Contents {bucket + 1}", + filename=board.prefix + f"_contents_{bucket + 1}.kicad_sch", + page=len(sheets) + bucket + 2, + sheets=len(members), + components=sum(n["components"] for n in members), + bounds=[x, y, x + 80, y + 8], + ) + ) + else: + # Group navigation by actual source-owned functional titles. + directory_nodes = sorted(nodes, key=lambda n: (n["section"], n["sheet_title"], n["sheet_id"])) + for index, item in enumerate(directory_nodes): + column, row = divmod(index, 10) + x, y = round(20.32 + column * 96.52, 4), round(52.07 + row * 12.7, 4) + item["column"], item["row"] = column, row + item["bounds"] = [x, y, round(x + CARD_W, 4), round(y + 12, 4)] + item["directory_document"] = board.prefix + ".kicad_sch" + selected: list[dict[str, Any]] = [] + explicit = [(a, b, l) for a, b, l in links if a.scope == board.scope] + if explicit and mode != "diagram": + raise ValueError("overview connections require at most 16 sheets") + if explicit: + for source_sheet, target_sheet, authored_link in explicit: + witness = available.get(cast(tuple[str, str], tuple(sorted((source_sheet.id, target_sheet.id)))), []) + if not set(authored_link.nets).issubset(witness): + raise ValueError("overview net does not connect both sheets: " + authored_link.label) + selected.append( + dict( + source=source_sheet.id, + target=target_sheet.id, + label=authored_link.label, + nets=list(authored_link.nets), + directed=authored_link.directed, + origin="authored", + ) + ) + elif mode == "diagram": + parent = {s.id: s.id for s in sheets} + + def root(a: str) -> str: + while parent[a] != a: + a = parent[a] + return a + + for (a, b), nets in sorted(available.items(), key=lambda item: (-len(item[1]), item[0])): + if len(selected) == 8: + break + if root(a) == root(b): + continue + parent[root(a)] = root(b) + selected.append( + dict( + source=a, + target=b, + label=( + (nets[0][:45] + "..." if len(nets[0]) > 48 else nets[0]) + if len(nets) == 1 + else f"{len(nets)} shared nets" + ), + nets=nets, + directed=False, + origin="compiled", + ) + ) + by_id = {n["sheet_id"]: n for n in nodes} + ports: dict[tuple[str, str], list[int]] = {} + for index, link in enumerate(selected): + left_node, right_node = by_id[link["source"]], by_id[link["target"]] + side_a, side_b = ("right", "left") if left_node["column"] < right_node["column"] else ("left", "right") + if left_node["column"] == right_node["column"]: + side_a, side_b = ("bottom", "top") if left_node["row"] < right_node["row"] else ("top", "bottom") + link["_sides"] = (side_a, side_b) + for n, side in ((left_node, side_a), (right_node, side_b)): + ports.setdefault((n["sheet_id"], side), []).append(index) + reserved: set[GridPoint] = set() + diagnostics = [] + for index, link in enumerate(selected): + ends = [] + stubs = [] + for identity, side in zip((link["source"], link["target"]), link.pop("_sides")): + n = by_id[identity] + x1, y1, x2, y2 = n["bounds"] + order = ports[(identity, side)] + offset = (order.index(index) - (len(order) - 1) / 2) * 3.81 + if side in ("left", "right"): + p = (x1 if side == "left" else x2, round((y1 + y2) / 2 + offset, 4)) + d = (-1, 0) if side == "left" else (1, 0) + else: + p = (round((x1 + x2) / 2 + offset, 4), y1 if side == "top" else y2) + d = (0, -1) if side == "top" else (0, 1) + p = (round(round(p[0] / GRID) * GRID, 4), round(round(p[1] / GRID) * GRID, 4)) + ends.append(list(p)) + stubs.append([round(p[0] + d[0] * 3.81, 4), round(p[1] + d[1] * 3.81, 4)]) + link["_ends"] = ends + link["_stubs"] = stubs + for end_point, stub_point in zip(ends, stubs): + reserved.update(_segment_cells(end_point, stub_point)) + occupied: set[GridPoint] = set() + for index, link in enumerate(selected): + ends = link.pop("_ends") + stubs = link.pop("_stubs") + path, cells = _route(stubs[0], stubs[1], [n["bounds"] for n in nodes], occupied | reserved) + link["id"] = "L" + str(index + 1) + link["endpoints"] = [ + dict(sheet_id=identity, sheet_title=by_id[identity]["sheet_title"], page=by_id[identity]["page"]) + for identity in (link["source"], link["target"]) + ] + link["path"] = [ends[0], *path, ends[1]] if path else [] + link["status"] = "drawn" if path else "legend_only" + if path: + occupied.update(cells) + else: + diagnostics.append(link["id"] + ": diagram route unavailable; relationship retained in connection key") + _position_tags(nodes, selected, diagnostics) + mechanical = sum(len(d.spec.components) for d in board.regions.values() if d.spec.kind == "mechanical") + overview_sheet = next((s for s in plan.sheets if s.scope == board.scope and s.id == "overview"), None) + overview_bounds = [] + if overview_sheet: + for location in overview_sheet.regions: + r = board.regions[location.region_id].spec + overview_bounds.append( + [ + location.x, + location.y, + location.x + r.bounds[2] - r.bounds[0], + location.y + r.bounds[3] - r.bounds[1], + ] + ) + result["boards"].append( + dict( + scope=board.scope, + root=board.prefix + ".kicad_sch", + mode=mode, + overview_present=overview_present, + mechanical_area_bounds=overview_bounds, + components=sum(len(d.spec.components) for d in board.regions.values()), + mechanical_components=mechanical, + circuit_sheets=len(sheets), + nodes=nodes, + directory_layout="paginated" if directory_pages else "grouped" if mode == "directory" else None, + directory_pages=directory_pages, + connections=selected, + diagnostics=diagnostics, + omitted_connection_pairs=max(0, len(available) - len(selected)), + total_shared_pairs=len(available), + shared_connections=[dict(source=a, target=b, nets=nets) for (a, b), nets in sorted(available.items())], + ) + ) + return result + + +def render_overview( + doc: SExpr, board: _PreparedBoard, data: Mapping[str, Any], options: SchematicExportOptions +) -> None: + # Import only when rendering, so the option models stay independent of the writer. + + def text(role: str, value: str, x: float, y: float, size: float = 1.27) -> None: + doc.append( + node( + "text", + value, + node("at", round(x, 4), round(y, 4), 0), + node("effects", node("font", node("size", size, size)), node("justify", S("left"))), + node("uuid", uid(board.prefix, "overview", role)), + ) + ) + + text("title", options.design_name + " / SYSTEM OVERVIEW", 20, 33, 2.54) + text( + "subtitle", + f"{data['components']} physical components / {data['circuit_sheets']} circuit sheets / Open a functional card for circuit detail", + 20, + 40, + 1.27, + ) + if data["mode"] == "directory": + text( + "directory", "SHEET DIRECTORY — complete connectivity is shown on the detailed circuit sheets", 20, 46, 1.1 + ) + actual = {children(sheet, "uuid")[0][1]: sheet for sheet in children(doc, "sheet")} + if data.get("directory_layout") == "paginated": + for item in data["directory_pages"]: + identity = uid(board.prefix, "contents", str(item["index"])) + sheet = actual.get(identity) + if sheet is None: + continue + x, y, right, bottom = item["bounds"] + for prop in children(sheet, "property"): + prop[-1] = effects(hide=True) + text("directory-" + identity + "-title", item["title"], x + 2, y + 2, 1.1) + text( + "directory-" + identity + "-count", + f"Page {item['page']} / {item['sheets']} sheets / {item['components']} components", + x + 2, + y + 5.5, + 1.1, + ) + return + for item in data["nodes"]: + identity = uid(board.prefix, item["sheet_id"]) + sheet = actual.get(identity) + if sheet is None: + continue + x, y, right, bottom = item["bounds"] + children(sheet, "at")[0][1:] = [x, y] + children(sheet, "size")[0][1:] = [right - x, bottom - y] + for prop in children(sheet, "property"): + prop[-1] = effects(hide=True) + section = item["section"] + section = section if len(section) <= 48 else section[:45] + "..." + display = item["title"] + display = display if len(display) <= 48 else display[:45] + "..." + text("directory-" + identity + "-section", section, x + 2, y + 2.5, 1.1) + text("directory-" + identity + "-title", display, x + 2, y + 6, 1.1) + text( + "directory-" + identity + "-count", + f"Sheet {item['page']} / {item['components']} components", + x + 2, + y + 9.5, + 1.1, + ) + return + key_only = sum(link["status"] != "drawn" for link in data["connections"]) + text( + "coverage", + f"{len(data['connections'])} selected relationships / {data['total_shared_pairs']} shared sheet pairs / {key_only} key-only routes. Detail sheets define complete wiring.", + 20, + 46, + 1.27, + ) + actual = {children(s, "uuid")[0][1]: s for s in children(doc, "sheet")} + for n in data["nodes"]: + identity = uid(board.prefix, n["sheet_id"]) + sheet = actual.get(identity) + if sheet is None: + continue + x, y, x2, y2 = n["bounds"] + children(sheet, "at")[0][1:] = [x, y] + children(sheet, "size")[0][1:] = [CARD_W, CARD_H] + children(children(sheet, "stroke")[0], "width")[0][1] = 0.35 + for prop in children(sheet, "property"): + if prop[1] == "Sheetname": + prop[-1] = effects(hide=True) + children(prop, "at")[0][1:] = [x + 3.81, y + 4.445, 0] + for i, line in enumerate(textwrap.wrap(n["title"], 38)): + text(n["sheet_id"] + "-title-" + str(i), line, x + 3.81, y + 4.445 + i * 4.0, 2.0) + for i, line in enumerate(textwrap.wrap(n["summary"], 56)): + text(n["sheet_id"] + "-summary-" + str(i), line, x + 3.81, y + 13.0 + i * 3.1, 1.4) + text(n["sheet_id"] + "-count", f"Sheet {n['page']} / {n['components']} components", x + 3.81, y + 23.5, 1.4) + for index, link in enumerate(data["connections"]): + path = link["path"] + + def draw_line(role: str, pts: Sequence[Sequence[float]]) -> None: + doc.append( + node( + "polyline", + node("pts", *[node("xy", *p) for p in pts]), + node("stroke", node("width", 0.25), node("type", S("default"))), + node("fill", node("type", S("none"))), + node("uuid", uid(board.prefix, "overview", link["id"], role)), + ) + ) + + if path: + draw_line("relationship", path) + p = link["tag"] + text(link["id"] + "-tag", link["id"], p[0], p[1], 1.27) + if link["directed"]: + a, b = path[-2:] + dx = b[0] - a[0] + dy = b[1] - a[1] + length = math.hypot(dx, dy) + dx /= length + dy /= length + draw_line( + "arrow", + [[b[0] - dx * 1.8 - dy, b[1] - dy * 1.8 + dx], b, [b[0] - dx * 1.8 + dy, b[1] - dy * 1.8 - dx]], + ) + # Two bounded lines fit between the last card row and the mechanical + # inset at y=205. Page identities remain useful even with no drawn route + # or with long, repeated, or source-authored card titles. + source, target = link["endpoints"] + relation = "→" if link["directed"] else "↔" + label = f"{link['id']} Sheet {source['page']} {relation} Sheet {target['page']}" + if not path: + label += " (key only)" + x, y = 20.32 + (index % 4) * 96.52, 191.0 + (index // 4) * 6.35 + text(link["id"] + "-key", label, x, y, 1.27) + text(link["id"] + "-key-label", link["label"], x, y + 2.54, 1.27) + text( + "legend", + "Functional relationships only; arrow direction is source-authored. See detail sheets for complete electrical connectivity.", + 20, + 204, + 1.0, + ) + # Keep explanatory notes outside every physical region in the overview inset. + occupied_right = max((b[2] for b in data["mechanical_area_bounds"]), default=20) + note_x = max(20, occupied_right + 10) + if note_x + 105 <= 395: + text("mechanical-title", "MECHANICAL REFERENCES", note_x, 212, 1.65) + text( + "mechanical-count", + f"{data['mechanical_components']} reference footprints in compiled scope", + note_x, + 218, + 1.4, + ) + text("mechanical-help", "Reference symbols identify mechanical parts.", note_x, 224, 1.27) + text("mechanical-pins", "They have no modeled electrical pins.", note_x, 230, 1.27) + text("workflow", "PB Python > compile > regenerate", note_x, 239, 1.4) diff --git a/edg/electronics_model/KiCadSchematicParser.py b/edg/electronics_model/KiCadSchematicParser.py index 4ff904829..03779e19a 100644 --- a/edg/electronics_model/KiCadSchematicParser.py +++ b/edg/electronics_model/KiCadSchematicParser.py @@ -3,7 +3,7 @@ from typing import List, Any, Dict, Tuple, TypeVar, Type, Set, NamedTuple, Union, Iterable, cast import math -import sexpdata # type: ignore +import sexpdata from typing_extensions import override # This defines the minimum resolvable grid, so all coordinates are rounded to integer @@ -60,7 +60,7 @@ def parse_at(sexp: List[Any], expected_car: str = "at") -> Tuple[float, float, f def parse_symbol(sexp: Any) -> str: """Asserts sexp is a Symbol and returns its value.""" assert isinstance(sexp, sexpdata.Symbol) - return cast(str, sexp.value()) + return sexp.value() class KiCadLibPin: diff --git a/edg/electronics_model/KiCadSchematicPatterns.py b/edg/electronics_model/KiCadSchematicPatterns.py new file mode 100644 index 000000000..26f34e1d1 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicPatterns.py @@ -0,0 +1,440 @@ +"""Pure circuit patterns established from declared terminal roles and real nets. + +Patterns suggest presentation only. They neither rename nets nor add electrical +connections; ambiguous fan-outs and rings are deliberately left unclassified. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Sequence, cast +from .KiCadSchematicTypes import PinKey, PinNets, Views + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent + + +from dataclasses import dataclass +import re +from typing import Tuple + + +@dataclass(frozen=True) +class SchematicPattern: + kind: str + components: Tuple[str, ...] + nets: Tuple[str, ...] + + def to_dict(self) -> dict[str, Any]: + return dict(kind=self.kind, components=list(self.components), nets=list(self.nets)) + + +def terminal_roles(component: PhysicalComponent, pin_nets: Optional[PinNets] = None) -> dict[str, str]: + """Use declared PB terminal names; accept parallel pads only with net proof.""" + roles: dict[str, str] = {} + for number, name in component.pins.items(): + role = name.removesuffix(".net").split(".")[-1].lower() + if role in roles: + if ( + pin_nets is not None + and pin_nets.get((component.path, number)) is not None + and pin_nets.get((component.path, number)) == pin_nets.get((component.path, roles[role])) + ): + continue + return {} # Ambiguous parallel/packed terminals remain unsupported. + roles[role] = number + return roles + + +def amplifier_channels(component: PhysicalComponent) -> dict[str, dict[str, str]]: + """Read explicit amplifier terminal roles, including packed/vector channels. + + Physical packed blocks use inpa/inna/outa; other compiled models retain + inp.0/inn.0/out.0. These are declared terminal names, not net-name guesses. + Ambiguous duplicate roles invalidate only that channel. + """ + channels: dict[str, dict[str, str]] = {} + ambiguous = set() + for number, name in sorted(component.pins.items()): + parts = name.removesuffix(".net").lower().split(".") + leaf = parts[-1] + if leaf in ("inp", "inn", "out"): + role, channel = leaf, "" + elif len(parts) >= 2 and parts[-2] in ("inp", "inn", "out") and leaf.isdecimal(): + role, channel = parts[-2], leaf + else: + match = re.fullmatch(r"(inp|inn|out)([a-z])", leaf) + if match is None: + continue + role, channel = match.groups() + roles = channels.setdefault(channel, {}) + if role in roles: + ambiguous.add(channel) + roles[role] = number + return { + channel: roles + for channel, roles in sorted(channels.items()) + if channel not in ambiguous and {"inp", "inn", "out"} <= set(roles) + } + + +def decoupling_associations( + components: Sequence[PhysicalComponent], pin_nets: PinNets, views: Optional[Views] = None +) -> Tuple[SchematicPattern, ...]: + """Associate typed local bypass wrappers with their unique powered device. + + A common supply does not establish ownership. The compiled DecouplingCapacitor + ancestor establishes the functional owner's subtree; actual supply and return + pins then verify the association. Ambiguous owners remain unclassified. + """ + by_path = {c.path: c for c in components} + roles = {c.path: terminal_roles(c, pin_nets) for c in components} + associations: dict[tuple[str, tuple[str, str]], list[str]] = {} + for cap in sorted(components, key=lambda c: c.path): + if len(cap.pins) != 2: + continue + symbol = ( + views[cap.path].lib_id + if views is not None and cap.path in views + else (getattr(cap, "mapping", None) or {}).get("lib_id", "") + ).split("_PB_", 1)[0] + if symbol not in ("Device:C", "Device:C_Polarized"): + continue + wrappers = [ + path + for path, cls in getattr(cap, "hierarchy", ()) + if cls.removeprefix("PolymorphicBlocks.") == "edg.abstract_parts.Capacitor.DecouplingCapacitor" + ] + if not wrappers: + continue + wrapper = max(wrappers, key=lambda path: len(path.split("."))) + owner = wrapper.rpartition(".")[0] + if not owner: + continue + cap_nets = {pin_nets.get((cap.path, n)) for n in cap.pins} + if len(cap_nets) != 2 or None in cap_nets: + continue + # Establish the nearest physical-device boundary BEFORE checking role + # eligibility. An FPGA with repeated/ambiguous supply roles still owns + # this boundary; a nested memory must not capture the FPGA's outer + # bypasses merely because it is the only device with simple role names. + physical = [ + path + for path, device in by_path.items() + if (path == owner or path.startswith(owner + ".")) + and not path.startswith(wrapper + ".") + and len(device.pins) >= 3 + ] + if not physical: + continue + nearest = min(len(path.split(".")) for path in physical) + boundary = sorted(path for path in physical if len(path.split(".")) == nearest) + candidates = [] + for path in boundary: + role = roles[path] + supplies = {pin_nets.get((path, n)) for r, n in role.items() if r in ("vdd", "vcc", "pwr", "vin", "vp")} + grounds = {pin_nets.get((path, n)) for r, n in role.items() if r in ("gnd", "vss", "vn")} + matches = { + (supply, ground) + for supply in supplies + for ground in grounds + if supply is not None and ground is not None and supply != ground and {supply, ground} == cap_nets + } + if len(matches) == 1: + candidates.append((path, next(iter(matches)))) + if len(candidates) != 1: + continue + path, nets = candidates[0] + associations.setdefault((path, nets), []).append(cap.path) + return tuple( + SchematicPattern("local_decoupling", (path, *caps), nets) for (path, nets), caps in sorted(associations.items()) + ) + + +def discover_patterns( + components: Sequence[PhysicalComponent], pin_nets: PinNets, views: Optional[Views] = None +) -> Tuple[SchematicPattern, ...]: + """Find unambiguous data chains using explicit DIN/DOUT terminal roles. + + Endpoint degree is measured against *all* provided physical pins. A shared + power net or a branched data output cannot accidentally become a serial link. + """ + by_path = {c.path: c for c in components} + roles = {c.path: terminal_roles(c, pin_nets) for c in components} + serial = {p for p, r in roles.items() if "din" in r and "dout" in r} + endpoints: dict[str, set[PinKey]] = {} + for key, endpoint_net in pin_nets.items(): + if key[0] in by_path: + endpoints.setdefault(endpoint_net, set()).add(key) + following = {} + preceding = {} + edge_net = {} + for source in sorted(serial): + out_key = (source, roles[source]["dout"]) + net = pin_nets.get(out_key) + peers = endpoints.get(net, set()) - {out_key} if net is not None else set() + if len(peers) != 1: + continue + target, number = next(iter(peers)) + if target not in serial or target == source or roles[target]["din"] != number: + continue + following[source] = target + preceding[target] = source + assert net is not None + edge_net[source] = net + patterns = [] + visited = set() + for start in sorted(serial - set(preceding)): + chain = [start] + while chain[-1] in following: + target = following[chain[-1]] + if target in chain: + break + chain.append(target) + if len(chain) > 1: + visited.update(chain) + patterns.append( + SchematicPattern( + "serial_data_chain", + tuple(chain), + tuple(edge_net[p] for p in chain[:-1]), + ) + ) + + # Conventional two-terminal symbols establish passive roles. Names such as + # R1, part strings, and footprint identifiers are never used as evidence. + def symbol(path: str) -> str: + if views is not None and path in views: + return views[path].lib_id.split("_PB_", 1)[0] + return cast(str, (getattr(by_path[path], "mapping", None) or {}).get("lib_id", "")) + + resistors = {p for p, c in by_path.items() if len(c.pins) == 2 and symbol(p) in ("Device:R", "Device:R_US")} + indicators = {p for p, c in by_path.items() if len(c.pins) == 2 and symbol(p) == "Device:LED"} + claimed = set(visited) + for anchor in sorted(by_path): + role = roles[anchor] + if "fb" not in role or "gnd" not in role: + continue + feedback = pin_nets.get((anchor, role["fb"])) + ground = pin_nets.get((anchor, role["gnd"])) + if feedback is None or ground is None or feedback == ground: + continue + entries = endpoints.get(feedback, set()) + branches = sorted({p for p, _ in entries if p in resistors}) + if len(entries) != 3 or len(branches) != 2 or claimed.intersection(branches): + continue + other = {} + for p in branches: + connections = {pin_nets.get((p, number)) for number in by_path[p].pins} + other[p] = connections - {feedback} + lower = [p for p in branches if other[p] == {ground}] + upper = [p for p in branches if len(other[p]) == 1 and None not in other[p] and ground not in other[p]] + if len(lower) == len(upper) == 1: + members: tuple[str, ...] = (anchor, upper[0], lower[0]) + patterns.append( + SchematicPattern( + "feedback_divider", + members, + (cast(str, next(iter(other[upper[0]]))), feedback, ground), + ) + ) + claimed.update(members) + for net in sorted(endpoints): + entries = endpoints[net] + if len(entries) != 2: + continue + paths = {p for p, _ in entries} + led = paths & indicators + resistor = paths & resistors + if len(led) == len(resistor) == 1 and not claimed.intersection(paths): + members = (next(iter(led)), next(iter(resistor))) + patterns.append(SchematicPattern("indicator_branch", members, (net,))) + claimed.update(members) + inductors = {p for p, c in by_path.items() if len(c.pins) == 2 and symbol(p) == "Device:L"} + capacitors = {p for p, c in by_path.items() if len(c.pins) == 2 and symbol(p) in ("Device:C", "Device:C_Polarized")} + for anchor in sorted(by_path): + role = roles[anchor] + if "sw" not in role or "gnd" not in role: + continue + switch_net = pin_nets.get((anchor, role["sw"])) + ground = pin_nets.get((anchor, role["gnd"])) + entries = endpoints.get(switch_net, set()) if switch_net is not None else set() + coils = sorted({p for p, _ in entries if p in inductors}) + if len(entries) != 2 or len(coils) != 1 or ground is None: + continue + coil = coils[0] + output = {pin_nets.get((coil, n)) for n in by_path[coil].pins} - {switch_net} + if len(output) != 1 or None in output or ground in output: + continue + output_net = next(iter(output)) + caps = sorted(p for p in capacitors if {pin_nets.get((p, n)) for n in by_path[p].pins} == {output_net, ground}) + # Shared rails alone do not justify merging all output capacitors: source + # siblings identify local support of this converter implementation. + parent = anchor.rpartition(".")[0] + caps = [p for p in caps if parent and p.startswith(parent + ".")] + patterns.append( + SchematicPattern( + "converter_output", + (anchor, coil, *caps), + (cast(str, switch_net), cast(str, output_net), ground), + ) + ) + # Diode feedback is common in clamp/error amplifiers. The verified symbol + # identity establishes a two-terminal branch; its polarity remains untouched. + diodes = { + p + for p, c in by_path.items() + if len(c.pins) == 2 + and symbol(p) + in ( + "Device:D", + "Device:D_Schottky", + "Device:D_Zener", + "Device:D_Small", + "Device:D_Schottky_Small", + "Device:D_Zener_Small", + ) + } + for anchor in sorted(by_path): + for channel, role in amplifier_channels(by_path[anchor]).items(): + negative = pin_nets.get((anchor, role["inn"])) + amplifier_output = pin_nets.get((anchor, role["out"])) + if negative is None or amplifier_output is None or negative == amplifier_output: + continue + feedback_branches = sorted( + p + for p in resistors | capacitors | diodes + if {pin_nets.get((p, n)) for n in by_path[p].pins} == {negative, amplifier_output} + ) + # Require a direct branch for this exact channel. A common negative + # input or supply does not associate arbitrary incident components. + if feedback_branches: + patterns.append( + SchematicPattern("amplifier_feedback", (anchor, *feedback_branches), (negative, amplifier_output)) + ) + # Differential sense networks belong together even when their controller + # is in an independently bounded power-stage region. + for anchor, role in sorted(roles.items()): + for positive, negative in (("acp", "acn"), ("srp", "srn")): + if positive not in role or negative not in role: + continue + sense_nets = {pin_nets.get((anchor, role[positive])), pin_nets.get((anchor, role[negative]))} + if len(sense_nets) != 2 or None in sense_nets: + continue + caps = [p for p in capacitors if {pin_nets.get((p, n)) for n in by_path[p].pins} == sense_nets] + branches = [] + for net in sorted(cast(set[str], sense_nets)): + candidates = [p for p in resistors if net in {pin_nets.get((p, n)) for n in by_path[p].pins}] + if len(candidates) == 1: + branches.append(candidates[0]) + if len(caps) == 1 and len(set(branches)) == 2: + patterns.append( + SchematicPattern( + "differential_sense_filter", + tuple(sorted([*branches, caps[0]])), + tuple(sorted(cast(set[str], sense_nets))), + ) + ) + from .KiCadSchematicPower import gate_driver_circuits + + patterns.extend( + SchematicPattern("gate_driver_stage", (anchor, *members), nets) + for anchor, members, nets in gate_driver_circuits(components, pin_nets, views) + ) + return ( + tuple(patterns) + + decoupling_associations(components, pin_nets, views) + + hierarchy_circuits(components, pin_nets, views) + ) + + +def hierarchy_circuits( + components: Sequence[PhysicalComponent], pin_nets: PinNets, views: Optional[Views] = None +) -> tuple[SchematicPattern, ...]: + """Keep compiled repeated subcircuits and verified power stages together. + + Hierarchy establishes ownership; actual terminal incidence establishes the + circuit. No supply-name, reference-prefix or part-number inference is used. + Repeated siblings require the same compiled class, not just similar names. + """ + from collections import defaultdict + + by_path = {c.path: c for c in components} + owners, classes = defaultdict(set), {} + endpoints = defaultdict(set) + for c in components: + for number in c.pins: + if (net := pin_nets.get((c.path, number))) is not None: + endpoints[net].add(c.path) + for path, cls in getattr(c, "hierarchy", ()): + if path != c.path: + owners[path].add(c.path) + classes[path] = cls + siblings = defaultdict(list) + for path in owners: + match = re.fullmatch(r"(.*)\[([^]]+)\]", path) + if match: + siblings[match[1], classes[path]].append(path) + patterns: list[SchematicPattern] = [] + claimed: set[str] = set() + for _, paths in sorted(siblings.items()): + if len(paths) < 2: + continue + for owner in sorted(paths): + members = owners[owner] + internal = tuple(sorted(n for n, ends in endpoints.items() if len(ends) > 1 and ends <= members)) + if 3 <= len(members) <= 24 and internal and not claimed.intersection(members): + patterns.append(SchematicPattern("repeated_subcircuit", tuple(sorted(members)), internal)) + claimed.update(members) + # A power stage needs declared FET terminals plus a verified inductor, or + # multiple FETs sharing a declared multi-input controller subtree. + for owner in sorted(owners, key=lambda p: (-len(p.split(".")), p)): + members = owners[owner] + if not 4 <= len(members) <= 64 or claimed.intersection(members): + continue + role_sets = { + p: {name.removesuffix(".net").split(".")[-1].lower() for name in by_path[p].pins.values()} for p in members + } + fets = {p for p in members if {"gate", "source", "drain"} <= role_sets[p]} + coils = {p for p in members if views and views[p].lib_id.split("_PB_", 1)[0] == "Device:L"} + controllers = { + p + for p in members + if len(by_path[p].pins) >= 6 and (role_sets[p] & {"sw", "sw1", "sw2", "gate1", "gate2", "drvhi", "ho"}) + } + if not controllers or not (coils or len(fets) >= 2): + continue + if len(members) <= 32: + selected = members + kind = "power_subcircuit" + else: + from .KiCadSchematicPower import power_topology, bridge_kernel + + topology = power_topology(members, by_path, views, pin_nets) if views else None + selected = fets | coils + power_nets = { + pin_nets.get((p, n)) + for p in selected + for n, role in by_path[p].pins.items() + if role.removesuffix(".net").split(".")[-1].lower() != "gate" + } + grounds = { + pin_nets.get((p, n)) + for p in controllers + for n, role in by_path[p].pins.items() + if role.removesuffix(".net").split(".")[-1].lower() in ("gnd", "vss") + } + power_nets -= grounds | {None} + selected |= { + p + for p in members + if len(by_path[p].pins) == 2 and any(pin_nets.get((p, n)) in power_nets for n in by_path[p].pins) + } + if topology is not None and topology["kind"] == "bridge": + selected = bridge_kernel(topology, members, by_path, cast(Views, views), pin_nets) + kind = "power_stage" + if not 3 <= len(selected) <= 32: + continue + nets = tuple(sorted(n for n, ends in endpoints.items() if len(ends & selected) > 1)) + patterns.append(SchematicPattern(kind, tuple(sorted(selected)), nets)) + claimed.update(selected) + return tuple(patterns) diff --git a/edg/electronics_model/KiCadSchematicPlacement.py b/edg/electronics_model/KiCadSchematicPlacement.py new file mode 100644 index 000000000..46ce405a6 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicPlacement.py @@ -0,0 +1,936 @@ +"""Deterministic placement of verified functional atoms, without electrical edits. + +Electrical roles come from discovered patterns. Bounded candidate search uses +pin geometry and occupied bounds; the normal router subsequently proves whether +those geometric estimates admit actual routes. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Collection, Mapping, Optional, Sequence +from .KiCadSchematicTypes import Bounds, Point, PinNets, Wire, Placement, Placements, Views, RouteResult + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent, SymbolView + from .KiCadSchematicCircuits import SchematicCircuit +from .KiCadSchematicPatterns import SchematicPattern + + +from collections import defaultdict +import hashlib +import json +import os +import re + +from .KiCadSchematicPatterns import discover_patterns, terminal_roles + + +def functional_atoms( + components: Sequence[PhysicalComponent], pin_nets: PinNets, views: Views +) -> tuple[tuple[tuple[str, ...], ...], tuple[SchematicPattern, ...]]: + """Merge overlapping support patterns; serial links remain cuttable edges.""" + paths = {c.path for c in components} + parent = {p: p for p in paths} + + def root(p: str) -> str: + while parent[p] != p: + parent[p] = parent[parent[p]] + p = parent[p] + return p + + # The exporter builds the shared model once from the complete board scope. + # Filtering here retains its ownership decisions instead of rediscovering + # patterns from a smaller group, where ambiguous owners can look unique. + model = next( + (getattr(c, "circuit_model", None) for c in components if getattr(c, "circuit_model", None) is not None), None + ) + patterns: Sequence[SchematicPattern] = ( + list(p for p in model.patterns if set(p.components) <= paths) + if model + else list(discover_patterns(components, pin_nets, views)) + ) + if model: + # Explicit ownership is a boundary, even when an automatic power or + # repeated-subtree pattern was discovered across it on the full board. + protected = [set(c.components) for c in model.circuits if c.provenance == "explicit"] + patterns = [ + p + for p in patterns + if p.kind == "serial_data_chain" + or not any(set(p.components) & owned and not set(p.components) <= owned for owned in protected) + ] + from .KiCadSchematicPatterns import SchematicPattern + + for circuit in model.circuits: + if circuit.provenance == "explicit" and set(circuit.components) <= paths: + patterns.append(SchematicPattern("authored_circuit", circuit.components, circuit.primary_nets)) + by_path = {c.path: c for c in components} + bounded: list[SchematicPattern] = [] + continuation_sections: list[set[str]] = [] + for pattern in patterns: + if pattern.kind in ("repeated_subcircuit", "power_subcircuit", "power_stage", "authored_circuit"): + entries = _circuit_template(pattern.components, by_path, views, pin_nets) + bounds = packing_bounds(entries, views, pin_nets) + if bounds[2] - bounds[0] + 17.78 > 340 or bounds[3] - bounds[1] + 17.78 > 205: + # A complex repeated channel may contain several independent + # compiled support subcircuits. Preserve those authored child + # boundaries instead of either clipping or splitting by role. + owner = os.path.commonprefix([p.split(".") for p in pattern.components]) + children = defaultdict(list) + for path in pattern.components: + suffix = path.split(".")[len(owner) :] + children[suffix[0] if suffix else path].append(path) + sections = [paths for paths in children.values() if len(paths) > 1] + direct = [paths[0] for paths in children.values() if len(paths) == 1] + if direct: + sections.append(direct) + circuit = _authored_circuit(pattern.components, by_path) + if circuit is not None and circuit.stages: + sections = [list(stage.components) for stage in circuit.stages] + rest = sorted(set(pattern.components) - {p for section in sections for p in section}) + if rest: + sections.append(rest) + if len(sections) > 1: + continuation_sections.extend(set(section) for section in sections) + for section_paths in sections: + bounded.append(type(pattern)("functional_section", tuple(sorted(section_paths)), pattern.nets)) + for path in pattern.components: + by_path[path].functional_continuation = dict( + owner=".".join(owner), + reason="measured whole circuit exceeds A3", + sections=[sorted(paths) for paths in sections], + ) + continue + bounded.append(pattern) + # A smaller discovered support pattern cannot rejoin a deliberate measured + # continuation, including a whole repeated-subtree or power-stage pattern. + patterns = tuple( + p + for p in bounded + if p.kind == "functional_section" + or not any( + set(p.components) & section and not set(p.components) <= section for section in continuation_sections + ) + ) + boundaries = [ + set(p.components) + for p in patterns + if p.kind + in ("repeated_subcircuit", "power_subcircuit", "power_stage", "functional_section", "authored_circuit") + ] + for pattern in patterns: + if pattern.kind not in ( + "repeated_subcircuit", + "power_subcircuit", + "power_stage", + "functional_section", + "authored_circuit", + ) and any( + set(pattern.components) & boundary and not set(pattern.components) <= boundary for boundary in boundaries + ): + # Keep the support branch intact without rejoining a controller + # already owned by an explicit power-stage continuation. + if pattern.kind == "feedback_divider": + support = set(pattern.components[1:]) + if not any(support & boundary for boundary in boundaries): + members = sorted(support & paths) + for path in members[1:]: + a, b = root(members[0]), root(path) + parent[max(a, b)] = min(a, b) + continue # A support pattern cannot reunite an explicit continuation. + if pattern.kind == "serial_data_chain": + continue + members = sorted(set(pattern.components) & paths) + for path in members[1:]: + a, b = root(members[0]), root(path) + parent[max(a, b)] = min(a, b) + groups = defaultdict(set) + for path in sorted(paths): + groups[root(path)].add(path) + return tuple(tuple(sorted(group)) for _, group in sorted(groups.items())), patterns + + +def signal_nets(components: Sequence[PhysicalComponent], pin_nets: PinNets) -> dict[str, set[str]]: + """Exclude actual declared supply terminals, rather than guessing net names.""" + rails = set() + for c in components: + for role, number in terminal_roles(c).items(): + if role in ("gnd", "vss", "vdd", "vcc", "pwr", "vin", "vout", "pwr_in", "pwr_out", "vp", "vn"): + net = pin_nets.get((c.path, number)) + if net is not None: + rails.add(net) + endpoints = defaultdict(set) + for c in components: + for number in c.pins: + net = pin_nets.get((c.path, number)) + if net is not None and net not in rails: + endpoints[net].add(c.path) + return endpoints + + +def channel_signature( + atom: tuple[str, ...], + by_path: Mapping[str, PhysicalComponent], + pin_nets: PinNets, + views: Views, + patterns: Sequence[SchematicPattern], +) -> Optional[str]: + """Recognize repeated compiled circuits conservatively, without net names. + + Matching requires compiled class evidence, identical relative implementation + paths, physical pin inventories and net-incidence structure. A visual + resemblance or an array-like path alone never establishes equivalence. + """ + if not atom or not all(getattr(by_path[path], "hierarchy", ()) for path in atom): + return None + prefix = os.path.commonprefix([path.split(".")[:-1] for path in atom]) + members = sorted(atom, key=lambda path: path.split(".")[len(prefix) :]) + indices = {path: i for i, path in enumerate(members)} + components = [] + nets = defaultdict(list) + for path in members: + c = by_path[path] + components.append( + ( + path.split(".")[len(prefix) :], + [cls for _, cls in c.hierarchy], + sorted(c.pins.items()), + views[path].lib_id.split("_PB_", 1)[0] if not views[path].lib_id.startswith("PB:") else "generic", + ) + ) + for number in sorted(c.pins): + net = pin_nets.get((path, number)) + if net is not None: + nets[net].append((indices[path], number)) + kinds = sorted(p.kind for p in patterns if set(p.components) <= set(atom)) + signature = (components, sorted(tuple(value) for value in nets.values()), kinds) + return hashlib.sha256(json.dumps(signature, sort_keys=True).encode()).hexdigest()[:16] + + +def _union(boxes: Sequence[Bounds]) -> Bounds: + return (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)) + + +def _overlap(a: Bounds, b: Bounds, margin: float = 1.27) -> bool: + return min(a[2], b[2]) + margin > max(a[0], b[0]) and min(a[3], b[3]) + margin > max(a[1], b[1]) + + +def component_boxes(entry: Placement, views: Views) -> list[Bounds]: + from .KiCadSchematicLayout import graphic_bounds, annotation_bounds, annotation_position + + c, x, y, angle = entry + a, b, d, e = graphic_bounds(views[c.path], angle) + tx, ty, _ = annotation_position(c, views[c.path], x, y, angle) + return [(x + a, y + b, x + d, y + e), annotation_bounds(c, tx, ty, angle)] + + +def pin_escapes(entries: Placements, views: Views, pin_nets: PinNets) -> list[tuple[str, Point, Point, str, str]]: + """Use the exact immutable 5.08 mm pin escapes emitted by the exporter.""" + from .KiCadSchematicLayout import pin_escape, pins + + result = [] + for c, x, y, angle in entries: + for number, px, py, direction in pins(views[c.path], x, y, angle): + net = pin_nets.get((c.path, number)) + if net is None: + continue + ex, ey = pin_escape(px, py, direction) + result.append((net, (px, py), (ex, ey), c.path, number)) + return result + + +def escape_conflicts(entries: Placements, views: Views, pin_nets: PinNets) -> int: + """Reject cross-net escape touching, including identical escape endpoints. + + The downstream router reserves escapes but cannot repair a short introduced + before routing. Same-net contacts, including parallel physical pins, remain + legal. Nonconnected crossings are also conservatively kept apart here. + """ + from .KiCadSchematicScene import segments_touch, segment_box, pin_name_items, pin_number_items + + escapes = pin_escapes(entries, views, pin_nets) + glyphs = [ + (c.path, item["bounds"]) + for c, x, y, angle in entries + for item in ( + pin_name_items(views[c.path].definition, x, y, angle) + + pin_number_items(views[c.path].definition, x, y, angle) + ) + ] + text_conflicts = sum( + owner != other and segment_box(a, b, box) for _, a, b, owner, _ in escapes for other, box in glyphs + ) + return text_conflicts + sum( + net != other and segments_touch(a, b, c, d) + for i, (net, a, b, _, _) in enumerate(escapes) + for other, c, d, _, _ in escapes[i + 1 :] + ) + + +def atom_bounds(entries: Placements, views: Views) -> Bounds: + return _union([box for entry in entries for box in component_boxes(entry, views)]) + + +def packing_bounds(entries: Placements, views: Views, pin_nets: PinNets) -> Bounds: + """Measure bodies, fields, escapes and labels that leave this atom. + + Only external-net and singleton labels reserve packing corridors. Internal + loop nets are handled by local routing; reserving their hypothetical label + walls inside a template would artificially explode complete circuits. + """ + import copy + from .KiCadSchematicLayout import annotation_obstacles + + members = {c.path for c, _, _, _ in entries} + endpoints = defaultdict(list) + for (path, number), net in pin_nets.items(): + endpoints[net].append((path, number)) + outside = {net for net, pins in endpoints.items() if len(pins) == 1 or any(path not in members for path, _ in pins)} + boxes = [box for entry in entries for box in component_boxes(entry, views)] + for c, x, y, angle in entries: + measured = copy.copy(c) + labels = getattr(c, "net_labels", {}) + measured.net_labels = { + number: labels.get(number, label_net) + for number in c.pins + if (label_net := pin_nets.get((c.path, number))) is not None and label_net in outside + } + # annotation_obstacles shares the exporter's pin-label/ground bounds, + # while keeping actual pin escapes even when their net is internal. + boxes.extend(annotation_obstacles(measured, views[c.path], x, y, angle)) + return _union(boxes) + + +def _rotation_for_pin(view: SymbolView, number: str, desired: Point) -> int: + from .KiCadSchematicLayout import transform + + pin = next((p for p in view.pins if p[0] == number), None) + if pin is None: + return 0 + return max((0, 90, 180, 270), key=lambda a: (sum(u * v for u, v in zip(transform(pin[1], pin[2], a), desired)), -a)) + + +def _horizontal(view: SymbolView) -> int: + from .KiCadSchematicLayout import transform + + if len(view.pins) != 2: + return 0 + return max( + (0, 90, 180, 270), + key=lambda a: (abs(transform(view.pins[0][1] - view.pins[1][1], view.pins[0][2] - view.pins[1][2], a)[0]), -a), + ) + + +def _authored_circuit(members: Collection[str], by_path: Mapping[str, PhysicalComponent]) -> Optional[SchematicCircuit]: + circuits: list[Optional[SchematicCircuit]] = [getattr(by_path[p], "functional_circuit", None) for p in members] + return next( + (c for c in circuits if c is not None and c.provenance == "explicit" and set(c.components) == set(members)), + None, + ) + + +def _staged_template( + members: Collection[str], by_path: Mapping[str, PhysicalComponent], views: Views, pin_nets: PinNets +) -> Optional[list[Placement]]: + """Measured left-to-right authored stages, never inferred signal arrows. + + Boundary roles guide rotation only; net and physical pad identities remain + unchanged. Components omitted from ordered stages form a support column. + """ + from .KiCadSchematicLayout import snap, transform + + circuit = _authored_circuit(members, by_path) + if circuit is None or not circuit.stages: + return None + stages = [tuple(stage.components) for stage in circuit.stages] + unassigned = tuple(sorted(set(members) - {p for stage in stages for p in stage})) + if unassigned: + stages.append(unassigned) + entries, x = [], 0.0 + desired = {"input": (-1, 0), "output": (1, 0), "supply": (0, -1), "return": (0, 1)} + for stage in stages: + column, y = [], 0.0 + for path in stage: + roles = [b for b in circuit.boundaries if b.component == path and b.role in desired] + + def orientation_score(angle: int) -> tuple[float, int]: + result = 0.0 + for boundary in roles: + pin = next(p for p in views[path].pins if p[0] == boundary.pin) + position = transform(pin[1], pin[2], angle) + result += sum(a * b for a, b in zip(position, desired[boundary.role])) + return result, -angle + + angle = max((0, 90, 180, 270), key=orientation_score) if roles else 0 + box = packing_bounds([(by_path[path], 0, 0, angle)], views, pin_nets) + column.append((by_path[path], snap(x - box[0]), snap(y - box[1]), angle)) + y += box[3] - box[1] + 15.24 + if column: + entries.extend(column) + x = packing_bounds(column, views, pin_nets)[2] + 20.32 + # Preserve measured stage order even when it exceeds A3: functional_atoms + # must see the oversized bounds and create explicit stage continuations. + # A shelf fallback here would silently erase the authored flow just to fit. + if entries and _score(entries, views, pin_nets)[:2] == (0, 0): + return entries + return None + + +def _circuit_template( + members: Collection[str], by_path: Mapping[str, PhysicalComponent], views: Views, pin_nets: PinNets +) -> list[Placement]: + """Measured shelf placement around an owner, preserving complete channels. + + Try three fixed widths. Unlike the old unclaimed-member horizontal strip, + support parts wrap within their circuit, before sheet packing is considered. + """ + from .KiCadSchematicLayout import snap + from .KiCadSchematicPower import power_template + + circuit = _authored_circuit(members, by_path) + requested = circuit.template if circuit is not None else "auto" + # Ordered stages explicitly describe flow and take geometric precedence. + # A typed template still requires its compiled topology during validation. + authored = _staged_template(members, by_path, views, pin_nets) + if authored is not None: + return authored + # Generic and signal/support families must not silently become converters + # just because a recognized power topology happens to lie in their members. + if requested in ("auto", "buck", "four_switch_bridge"): + power = power_template(members, by_path, views, pin_nets) + if power is not None: + return power + if requested == "series_path": + from .KiCadSchematicLayout import _place_group_legacy + + pages = _place_group_legacy([by_path[p] for p in members], views, pin_nets) + if len(pages) == 1 and _candidate_valid(pages[0], views, pin_nets): + return pages[0] + anchor = min(members, key=lambda p: (-len(by_path[p].pins), p)) + signals = signal_nets([by_path[p] for p in members], pin_nets) + + def stage_part(path: str) -> bool: + roles = {v.removesuffix(".net").split(".")[-1].lower() for v in by_path[path].pins.values()} + return {"gate", "source", "drain"} <= roles or views[path].lib_id.split("_PB_", 1)[0] == "Device:L" + + def angle_for(path: str) -> int: + if views[path].lib_id.split("_PB_", 1)[0] == "Device:L": + return _horizontal(views[path]) + if stage_part(path): + source = [p for p in views[path].pins if by_path[path].pins.get(p[0], "").removesuffix(".net") == "source"] + drain = [p for p in views[path].pins if by_path[path].pins.get(p[0], "").removesuffix(".net") == "drain"] + if source and drain: + return 90 if abs(source[0][2] - drain[0][2]) > abs(source[0][1] - drain[0][1]) else 0 + return 0 + + remaining = set(members) - {anchor} + ordered, prior = [], {anchor} + while remaining: + path = min( + remaining, + key=lambda p: (not stage_part(p), -sum(p in ends and bool(prior & ends) for ends in signals.values()), p), + ) + ordered.append(path) + remaining.remove(path) + prior = {path} + trials = [] + for shelf_width in (160.02, 220.98, 281.94): + owner = (by_path[anchor], 0.0, 0.0, angle_for(anchor)) + owner_box = atom_bounds([owner], views) + start_x = owner_box[2] + 15.24 if len(by_path[anchor].pins) >= 6 else owner_box[0] + start_y = owner_box[1] if len(by_path[anchor].pins) >= 6 else owner_box[3] + 15.24 + entries = [owner] + x, y, row_height = start_x, start_y, 0.0 + for path in ordered: + c = by_path[path] + angle = angle_for(path) + box = atom_bounds([(c, 0, 0, angle)], views) + width, height = box[2] - box[0], box[3] - box[1] + if x > start_x and x + width > start_x + shelf_width: + x, y, row_height = start_x, y + row_height + 15.24, 0.0 + entry = (c, snap(x - box[0]), snap(y - box[1]), angle) + entries.append(entry) + x += width + 15.24 + row_height = max(row_height, height) + bounds = packing_bounds(entries, views, pin_nets) + width, height = bounds[2] - bounds[0] + 17.78, bounds[3] - bounds[1] + 17.78 + if width <= 340 and height <= 205 and _score(entries, views, pin_nets)[:2] == (0, 0): + trials.append((round(width * height, 4), entries)) + if trials: + return min(trials, key=lambda t: t[0])[1] + # Let the normal measured-bounds gate report an oversized complete atom; + # never silently split a verified channel or shrink its typography. + return entries + + +def _template( + members: Sequence[str], + patterns: Sequence[SchematicPattern], + by_path: Mapping[str, PhysicalComponent], + views: Views, + pin_nets: PinNets, +) -> list[Placement]: + """Finite layout templates for already validated electrical patterns.""" + from .KiCadSchematicLayout import graphic_bounds, snap + + local = [p for p in patterns if p.kind != "serial_data_chain" and set(p.components) <= set(members)] + if any( + p.kind + in ( + "repeated_subcircuit", + "power_subcircuit", + "power_stage", + "functional_section", + "gate_driver_stage", + "authored_circuit", + ) + for p in local + ): + return _circuit_template(members, by_path, views, pin_nets) + bypasses = [p for p in local if p.kind == "local_decoupling"] + if ( + sum(len(p.components) - 1 for p in bypasses) >= 2 + and len({p.components[0] for p in bypasses}) == 1 + and set(members) == {path for p in bypasses for path in p.components} + ): + # Parallel supply pads can legitimately own many capacitors. Use the + # measured, wrapped bank beside the IC instead of a vertical stack + # that grows below an already tall MCU. + return _circuit_template(members, by_path, views, pin_nets) + priority = { + "converter_output": 0, + "amplifier_feedback": 1, + "feedback_divider": 2, + "indicator_branch": 3, + "local_decoupling": 4, + } + local.sort(key=lambda p: (priority.get(p.kind, 9), p.components)) + anchor = local[0].components[0] if local else members[0] + entries = {anchor: (by_path[anchor], 0.0, 0.0, 0)} + feedback_count = 0 + for pattern in local: + owner = pattern.components[0] + if owner not in entries: + entries[owner] = (by_path[owner], 0.0, 0.0, 0) + _, ox, oy, oa = entries[owner] + owner_box = atom_bounds([entries[owner]], views) + right = owner_box[2] + if pattern.kind == "feedback_divider": + # The feedback junction is between a vertical upper/lower pair. + _, hi, lo = pattern.components + x = right + 20.32 + for path, y, toward in ((hi, oy - 12.7, (0, 1)), (lo, oy + 17.78, (0, -1))): + number = next(n for n in by_path[path].pins if pin_nets.get((path, n)) == pattern.nets[1]) + angle = _rotation_for_pin(views[path], number, toward) + entries.setdefault(path, (by_path[path], snap(x), snap(y), angle)) + elif pattern.kind == "amplifier_feedback": + for path in pattern.components[1:]: + # Distinct packed channels keep separate branches; parallel + # feedback components are never placed over the same location. + if path not in entries: + entries[path] = ( + by_path[path], + snap(ox + feedback_count * 25.4), + snap(oy - 30.48), + _horizontal(views[path]), + ) + feedback_count += 1 + elif pattern.kind == "converter_output": + for i, path in enumerate(pattern.components[1:]): + x = right + 25.4 + i * 30.48 + angle = _horizontal(views[path]) if i == 0 else (_horizontal(views[path]) + 90) % 360 + entries.setdefault(path, (by_path[path], snap(x), snap(oy + (0 if i == 0 else 15.24)), angle)) + elif pattern.kind == "indicator_branch": + shared = pattern.nets[0] + owner_pin = next(number for number in by_path[owner].pins if pin_nets.get((owner, number)) == shared) + owner_angle = _rotation_for_pin(views[owner], owner_pin, (1, 0)) + entries[owner] = (by_path[owner], ox, oy, owner_angle) + right = atom_bounds([entries[owner]], views)[2] + for path in pattern.components[1:]: + target_pin = next(number for number in by_path[path].pins if pin_nets.get((path, number)) == shared) + angle = _rotation_for_pin(views[path], target_pin, (-1, 0)) + entries.setdefault(path, (by_path[path], snap(right + 25.4), oy, angle)) + elif pattern.kind == "local_decoupling": + ymax = graphic_bounds(views[owner], oa)[3] + for i, path in enumerate(pattern.components[1:]): + # Bypass ownership remains visible and consistent across arrays. + entries.setdefault(path, (by_path[path], ox, snap(oy + ymax + 30.48 + i * 30.48), 90)) + for i, path in enumerate(sorted(set(members) - set(entries))): + entries[path] = (by_path[path], 60.96 + i * 40.64, 0.0, 0) + # If long values or unusual symbols collide, spread the new member locally. + accepted: list[Placement] = [] + for path in [anchor] + sorted(set(entries) - {anchor}): + entry = entries[path] + # Keep a support on its template's intended side of the owner. Moving + # every collision downward can push a feedback branch through the IC + # and below its own bypass when a larger rail-pin envelope is measured. + _, ax, ay, _ = entries[anchor] + _, ex, ey, _ = entry + if ey < ay: + spread = (0.0, -5.08) + elif ey > ay: + spread = (0.0, 5.08) + else: + spread = (-5.08 if ex < ax else 5.08, 0.0) + for attempt in range(32): + boxes = component_boxes(entry, views) + if not any( + _overlap(a, b) for prior in accepted for a in boxes for b in component_boxes(prior, views) + ) and not escape_conflicts(accepted + [entry], views, pin_nets): + break + c, x, y, angle = entry + entry = (c, snap(x + spread[0]), snap(y + spread[1]), angle) + else: + raise ValueError( + "cannot separate symbol fields or cross-net pin escapes in functional atom: " + ", ".join(members) + ) + accepted.append(entry) + return accepted + + +def _score(entries: Placements, views: Views, pin_nets: PinNets) -> tuple[int, int, float, float]: + from .KiCadSchematicLayout import pins + + boxes = [component_boxes(e, views) for e in entries] + collisions = sum( + _overlap(a, b) for i, first in enumerate(boxes) for second in boxes[i + 1 :] for a in first for b in second + ) + terminals = defaultdict(list) + for c, x, y, angle in entries: + for number, px, py, _ in pins(views[c.path], x, y, angle): + net = pin_nets.get((c.path, number)) + if net is not None: + terminals[net].append((px, py)) + # A Manhattan bounding tree is only an estimate, never a routing guarantee. + length = sum( + max(x for x, y in pts) - min(x for x, y in pts) + max(y for x, y in pts) - min(y for x, y in pts) + for pts in terminals.values() + if len(pts) > 1 + ) + a, b, d, e = atom_bounds(entries, views) + return escape_conflicts(entries, views, pin_nets), collisions, round(length, 4), round((d - a) * (e - b), 4) + + +def _optimize( + entries: Placements, views: Views, pin_nets: PinNets, locked: Collection[str], *, rotations: bool = True +) -> tuple[list[Placement], int, list[list[Placement]]]: + """At most two passes of 32 orthogonal candidate transforms per atom.""" + from .KiCadSchematicLayout import snap + + best = list(entries) + score = _score(best, views, pin_nets) + count = 0 + finalists: list[list[Placement]] = [] + if len(best) == 1: + return best, count, finalists + for _ in range(2): + trials = 0 + # Stable path order removes traversal dependence. Owners and dedicated + # bypass positions are retained; only unclaimed support transforms move. + for index in sorted(range(len(best)), key=lambda i: best[i][0].path): + c, x, y, angle = best[index] + if c.path in locked: + continue + candidates = [(x, y, a) for a in (0, 90, 180, 270) if a != angle] if rotations else [] + candidates += [ + (snap(x + dx), snap(y + dy), angle) + for dx, dy in ( + (-2.54, 0), + (2.54, 0), + (0, -2.54), + (0, 2.54), + (-5.08, 0), + (5.08, 0), + (0, -5.08), + (0, 5.08), + ) + ] + for tx, ty, ta in candidates: + if trials >= 32: + break + trials += 1 + count += 1 + candidate = list(best) + candidate[index] = (c, tx, ty, ta) + candidate_score = _score(candidate, views, pin_nets) + if candidate_score < score: + best, score = candidate, candidate_score + finalists.append(candidate) + if trials >= 32: + break + return best, count, finalists[-3:] + + +def _candidate_valid(entries: Placements, views: Views, pin_nets: PinNets) -> bool: + if not entries or _score(entries, views, pin_nets)[:2] != (0, 0): + return False + a, b, c, d = packing_bounds(entries, views, pin_nets) + return c - a + 17.78 <= 340 and d - b + 17.78 <= 205 + + +def _whole_candidates( + baseline: list[Placement], + finalists: Sequence[list[Placement]], + views: Views, + pin_nets: PinNets, + locked: Collection[str], +) -> list[tuple[str, list[Placement]]]: + """At most eight stable proposals, baseline included, before routing. + + Spacing changes apply to the whole unlocked support arrangement. They expose + alternatives that a distance-only sequence of single-part moves cannot find. + The conventional circuit orientation itself is never mirrored or reversed. + """ + from .KiCadSchematicLayout import snap + + proposals = [("template", baseline)] + proposals.extend(("local_" + str(i + 1), candidate) for i, candidate in enumerate(finalists)) + cx = sum(x for _, x, _, _ in baseline) / len(baseline) + cy = sum(y for _, _, y, _ in baseline) / len(baseline) + for name, sx, sy in (("wide", 1.15, 1.0), ("tall", 1.0, 1.15), ("compact_x", 0.9, 1.0), ("compact_y", 1.0, 0.9)): + candidate = [ + ( + c, + x if c.path in locked else snap(cx + (x - cx) * sx), + y if c.path in locked else snap(cy + (y - cy) * sy), + angle, + ) + for c, x, y, angle in baseline + ] + proposals.append((name, candidate)) + seen, result = set(), [] + for name, candidate in proposals: + key = tuple((c.path, x, y, angle) for c, x, y, angle in candidate) + if key in seen: + continue + seen.add(key) + if name == "template" or _candidate_valid(candidate, views, pin_nets): + result.append((name, candidate)) + if len(result) == 8: + break + return result + + +def _stage_intrusions(entries: Placements, wires: Sequence[Wire], views: Views, pin_nets: PinNets) -> int: + """Count routes crossing authored stages unrelated to their endpoints. + + A region includes its support wiring space, beyond individual symbol bodies + already protected by the router. This keeps another stage's signal from + visually threading through the middle of a coherent local circuit. + """ + from .KiCadSchematicScene import segment_box + + by_path = {entry[0].path: entry for entry in entries} + stages, seen = [], set() + for component, _, _, _ in entries: + circuit = getattr(component, "functional_circuit", None) + if circuit is None or circuit.id in seen: + continue + seen.add(circuit.id) + for stage in circuit.stages: + members = set(stage.components) & set(by_path) + if len(members) >= 2: + bounds = atom_bounds([by_path[p] for p in sorted(members)], views) + related = {net for (path, _), net in pin_nets.items() if path in members} + stages.append((bounds, related)) + return sum(net not in related and segment_box(a, b, bounds) for net, a, b in wires for bounds, related in stages) + + +def _choose_routes( + baseline: list[Placement], + candidates: Sequence[tuple[str, list[Placement]]], + views: Views, + pin_nets: PinNets, + *, + max_candidates: int = 3, +) -> tuple[list[Placement], dict[str, Any]]: + """Route a baseline and at most three shortlisted complete arrangements. + + Each candidate uses its own deterministic page translation. Failed endpoint + identities are checked against the original baseline, never a moving target. + """ + from .KiCadSchematicLayout import route_local, snap + from .KiCadSchematicRouting import route_metrics + + primary = set() + for c, _, _, _ in baseline: + circuit = getattr(c, "functional_circuit", None) + if circuit is not None: + primary.update(circuit.primary_nets) + + def evaluate(entries: Placements) -> tuple[RouteResult, dict[str, Any]]: + a, b, c, d = packing_bounds(entries, views, pin_nets) + dx, dy = snap(25.4 - a + 8.89), snap(60.96 - b + 8.89) + placed = [(component, round(x + dx, 4), round(y + dy, 4), angle) for component, x, y, angle in entries] + route = route_local(placed, views, pin_nets) + metric: dict[str, Any] = dict(route_metrics(route[0], route[2])) + metric["primary_fallbacks"] = sum(net in primary for _, net in route[2]) + metric["unrelated_intrusions"] = _stage_intrusions(placed, route[0], views, pin_nets) + metric["area_mm2"] = round((c - a) * (d - b), 4) + metric["outside_page"] = any( + not (15 <= p[0] <= 400 and 35 <= p[1] <= 275) for _, a, b in route[0] for p in (a, b) + ) + return route, metric + + def score(metric: Mapping[str, Any]) -> tuple[float, ...]: + return ( + metric["primary_fallbacks"], + metric["crossings"], + metric["unrelated_intrusions"], + metric["bends"], + metric["length_mm"], + metric["area_mm2"], + ) + + shortlisted = sorted(candidates[1:], key=lambda item: _score(item[1], views, pin_nets))[:max_candidates] + if not shortlisted: + return baseline, dict(selected="template", route_trials=0, candidates=len(candidates), trials=[]) + original, before = evaluate(baseline) + selected, best, best_name = baseline, before, "template" + trials = [] + for name, candidate in shortlisted: + route, metric = evaluate(candidate) + acceptable = ( + set(route[2]) <= set(original[2]) + and not metric["outside_page"] + and metric["crossings"] <= before["crossings"] + and _candidate_valid(candidate, views, pin_nets) + ) + chosen = acceptable and score(metric) < score(best) + trials.append( + dict( + candidate=name, + metrics=metric, + acceptable=acceptable, + selected=chosen, + reason=( + "improved routed score" + if chosen + else ( + "invalid or new fallback/crossing/page violation" + if not acceptable + else "baseline or earlier candidate scores better" + ) + ), + ) + ) + if chosen: + selected, best, best_name = candidate, metric, name + return selected, dict( + selected=best_name, + route_trials=1 + len(shortlisted), + candidates=len(candidates), + before=before, + after=best, + trials=trials, + ) + + +def _route_guard( + baseline: list[Placement], candidate: list[Placement], views: Views, pin_nets: PinNets +) -> tuple[list[Placement], dict[str, Any]]: + """Compatibility helper for callers evaluating a single finalist.""" + if baseline == candidate: + return baseline, {"selected": "template", "route_trials": 0} + selected, evidence = _choose_routes(baseline, [("template", baseline), ("optimized", candidate)], views, pin_nets) + evidence["accepted"] = selected != baseline + evidence["trial"] = evidence["trials"][0]["metrics"] if evidence["trials"] else evidence.get("before") + return selected, evidence + + +def place_functional( + components: Sequence[PhysicalComponent], views: Views, pin_nets: PinNets, *, optimize_orientations: bool = True +) -> list[list[Placement]]: + """Pack complete measured functional atoms before splitting across pages.""" + from .KiCadSchematicLayout import snap + + components = sorted(components, key=lambda c: c.path) + by_path = {c.path: c for c in components} + atoms, patterns = functional_atoms(components, pin_nets, views) + net_paths = signal_nets(components, pin_nets) + families = {atom: channel_signature(atom, by_path, pin_nets, views, patterns) for atom in atoms} + family_counts: dict[Optional[str], int] = defaultdict(int) + for family in families.values(): + if family is not None: + family_counts[family] += 1 + # Strong connectivity orders complete atoms. Stable pattern kind provides + # repeated channels with the same template, without inferred signal arrows. + # Repeated compiled channels have a semantic ordinal. Connectivity degree + # must not move a terminal channel ahead of channel zero. + from .KiCadSchematicPlanner import natural_order + + repeated = {} + for pattern in patterns: + if pattern.kind == "repeated_subcircuit": + owner = ".".join(os.path.commonprefix([p.split(".") for p in pattern.components])) + for atom in atoms: + if set(pattern.components) <= set(atom): + repeated[atom] = (re.sub(r"\[[^]]+\]", "[]", owner), natural_order(owner)) + remaining = set(atoms) + order: list[tuple[str, ...]] = [] + while remaining: + prior = set(order[-1]) if order else set() + + def affinity(atom: tuple[str, ...]) -> tuple[int, int, tuple[str, ...]]: + shared = sum(bool(set(atom) & ends) and bool(prior & ends) for ends in net_paths.values()) + degree = sum(bool(set(atom) & ends) and bool(ends - set(atom)) for ends in net_paths.values()) + return (-shared, -degree, atom) + + eligible = [ + atom + for atom in remaining + if atom not in repeated + or not any( + other in repeated and repeated[other][0] == repeated[atom][0] and repeated[other][1] < repeated[atom][1] + for other in remaining + ) + ] + selected = min(eligible, key=affinity) + remaining.remove(selected) + order.append(selected) + pages: list[list[Placement]] = [] + page: list[Placement] = [] + x, y, row_height = 25.4, 60.96, 0.0 + for atom in order: + entries = _template(atom, patterns, by_path, views, pin_nets) + locked = {p.components[0] for p in patterns if p.kind != "serial_data_chain" and set(p.components) <= set(atom)} + locked.update(path for p in patterns if p.kind == "local_decoupling" for path in p.components) + baseline = entries + entries, candidates, finalists = _optimize( + entries, views, pin_nets, locked, rotations=not optimize_orientations + ) + # Route a fixed shortlist, not only the single best distance estimate. + # A slightly worse geometric estimate may have much clearer real wires. + proposals = _whole_candidates(baseline, finalists, views, pin_nets, locked) + entries, routing = _choose_routes(baseline, proposals, views, pin_nets) + local_transforms = candidates + candidates = len(proposals) + bounds = packing_bounds(entries, views, pin_nets) + width, height = bounds[2] - bounds[0] + 17.78, bounds[3] - bounds[1] + 17.78 + if width > 340 or height > 205: + raise ValueError("indivisible functional atom exceeds page bounds: " + ", ".join(atom)) + if page and x + width > 390: + x, y, row_height = 25.4, y + row_height, 0.0 + if page and y + height > 265: + pages.append(page) + page = [] + x, y, row_height = 25.4, 60.96, 0.0 + dx, dy = x - bounds[0] + 8.89, y - bounds[1] + 8.89 + for c, px, py, angle in entries: + c.placement_evidence = { + "atom": list(atom), + "candidates": candidates, + "local_transforms": local_transforms, + "requested_template": getattr(getattr(c, "functional_circuit", None), "template", "auto"), + "patterns": sorted({p.kind for p in patterns if set(p.components) <= set(atom)}), + "routing": routing, + "functional_continuation": getattr(c, "functional_continuation", None), + "repeated_family": families[atom], + "matching_channels": family_counts.get(families[atom], 0), + } + page.append((c, snap(px + dx), snap(py + dy), angle)) + x += width + row_height = max(row_height, height) + if page: + pages.append(page) + return pages diff --git a/edg/electronics_model/KiCadSchematicPlanner.py b/edg/electronics_model/KiCadSchematicPlanner.py new file mode 100644 index 000000000..177f95bc3 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicPlanner.py @@ -0,0 +1,700 @@ +"""Pure planning of complete functional regions onto KiCad schematic sheets. + +Bounds include the region heading, symbols, text and wires. Planning translates +those rectangles without changing components, connectivity, scale or typography. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +from collections import Counter +from dataclasses import dataclass +from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, TYPE_CHECKING, Union, cast + +if TYPE_CHECKING: + from ..core import CompiledDesign + from .KiCadSchematicExporter import SchematicExportOptions + +Bounds = Tuple[float, float, float, float] +USABLE_BOUNDS: Bounds = (20, 40, 395, 265) +OVERVIEW_BOUNDS: Bounds = (20, 205, 395, 265) +GUTTER = 8.0 +TITLE_BLOCK_BOUNDS: Bounds = (230, 245, 410, 287) + + +def region_fits_page(width: float, height: float) -> bool: + """Whether an A3 content page has room beside or above the title block.""" + left, top, right, bottom = USABLE_BOUNDS + return ( + width <= right - left + and height <= bottom - top + and (width <= TITLE_BLOCK_BOUNDS[0] - left or height <= TITLE_BLOCK_BOUNDS[1] - top) + ) + + +def natural_order(value: str) -> tuple[tuple[int, Union[int, str]], ...]: + """Stable human ordering for continuation and array indices.""" + return tuple((1, int(part)) if part.isdecimal() else (0, part) for part in re.split(r"(\d+)", value)) + + +def _continuation_order( + sheets: Sequence[SchematicSheet], regions: Mapping[str, SchematicRegion], diagnostics: list[str] +) -> list[SchematicSheet]: + """Keep source-region continuations ordered even on mixed-title pages.""" + + def key(sheet: SchematicSheet) -> tuple[str, bool, tuple[tuple[int, Union[int, str]], ...], int, str]: + title = sheet.title.rsplit(" /", 1) + continuation = int(title[1]) if len(title) == 2 and title[1].isdigit() else 0 + return sheet.scope, sheet.id != "overview", natural_order(title[0]), continuation, sheet.id + + families: dict[tuple[str, ...], list[tuple[int, int]]] = {} + for index, sheet in enumerate(sheets): + for placement in sheet.regions: + region = regions[placement.region_id] + suffix = region.title.rsplit(" /", 1) + number = int(suffix[1]) if len(suffix) == 2 and suffix[1].isdigit() else 1 + family = suffix[0] if len(suffix) == 2 and suffix[1].isdigit() else region.title + families.setdefault((sheet.scope, family), []).append((number, index)) + array = re.fullmatch(r"(.*)\[([0-9, ]+)\](.*)", family) + if array: + indices = [int(item.strip()) for item in array[2].split(",")] + array_family = (sheet.scope, "array", array[1], array[3]) + families.setdefault(array_family, []).append((min(indices), index)) + before: dict[int, set[int]] = {i: set() for i in range(len(sheets))} + for entries in families.values(): + for first_number, first in entries: + for second_number, second in entries: + if first_number < second_number and first != second: + before[second].add(first) + remaining, ordered = set(before), [] + while remaining: + eligible = [i for i in remaining if not before[i] & remaining] + if not eligible: + diagnostics.append( + "continuation_order_conflict: mixed sheet assignments impose a cycle; retaining stable title order" + ) + eligible = list(remaining) + chosen = min(eligible, key=lambda i: key(sheets[i])) + ordered.append(sheets[chosen]) + remaining.remove(chosen) + return ordered + + +def _string(value: Any, name: str, allow_empty: bool = False) -> None: + if not isinstance(value, str) or (not allow_empty and not value): + raise ValueError(f"{name} must be {'a' if allow_empty else 'a nonempty'} string") + + +def _number(value: Any, name: str) -> None: + try: + valid = not isinstance(value, bool) and isinstance(value, (float, int)) and math.isfinite(value) + except OverflowError: + valid = False + if not valid: + raise ValueError(f"{name} must be a finite number") + + +def _bounds(value: Any, name: str) -> None: + if not isinstance(value, tuple) or len(value) != 4: + raise ValueError(f"{name} must contain four coordinates") + for coordinate in value: + _number(coordinate, name) + if value[2] <= value[0] or value[3] <= value[1]: + raise ValueError(f"{name} must have positive width and height") + + +def _object(value: Any, fields: set[str], required: set[str], name: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise ValueError(f"{name} must be an object") + if set(value) - fields or required - set(value): + raise ValueError(f"{name} has unknown or missing fields") + return value + + +def _array(value: Any, name: str) -> Sequence[Any]: + if not isinstance(value, (list, tuple)): + raise ValueError(f"{name} must be an array") + return value + + +@dataclass(frozen=True) +class SchematicRegion: + id: str + title: str + scope: str + components: Tuple[str, ...] + bounds: Bounds + kind: str = "circuit" + + def __post_init__(self) -> None: + _string(self.id, "region id") + _string(self.title, "region title") + _string(self.scope, "region scope", allow_empty=True) + if not isinstance(self.components, tuple): + raise ValueError("region components must be a tuple") + for component in self.components: + _string(component, "component path") + if len(set(self.components)) != len(self.components): + raise ValueError("region has duplicate component paths") + _bounds(self.bounds, "region bounds") + if self.kind not in ("circuit", "mechanical", "empty"): + raise ValueError("region kind must be circuit, mechanical or empty") + if self.kind == "empty" and self.components: + raise ValueError("empty region cannot contain physical components") + + def to_dict(self) -> Dict[str, Any]: + result: Dict[str, Any] = dict( + id=self.id, title=self.title, scope=self.scope, components=list(self.components), bounds=list(self.bounds) + ) + if self.kind != "circuit": + result["kind"] = self.kind + return result + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> SchematicRegion: + data = _object( + value, + {"id", "title", "scope", "components", "bounds", "kind"}, + {"id", "title", "scope", "components", "bounds"}, + "region", + ) + return cls( + data["id"], + data["title"], + data["scope"], + tuple(_array(data["components"], "components")), + cast(Bounds, tuple(_array(data["bounds"], "bounds"))), + data.get("kind", "circuit"), + ) + + +@dataclass(frozen=True) +class SchematicRegionPlacement: + region_id: str + x: float + y: float + + def __post_init__(self) -> None: + _string(self.region_id, "placement region_id") + _number(self.x, "placement x") + _number(self.y, "placement y") + + def to_dict(self) -> Dict[str, Any]: + return dict(region_id=self.region_id, x=self.x, y=self.y) + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> SchematicRegionPlacement: + data = _object(value, {"region_id", "x", "y"}, {"region_id", "x", "y"}, "placement") + return cls(data["region_id"], data["x"], data["y"]) + + +# Compatibility with the short name used in the initial architecture discussion. +RegionPlacement = SchematicRegionPlacement + + +@dataclass(frozen=True) +class SchematicSheet: + id: str + title: str + scope: str + regions: Tuple[SchematicRegionPlacement, ...] + + def __post_init__(self) -> None: + _string(self.id, "sheet id") + _string(self.title, "sheet title") + _string(self.scope, "sheet scope", allow_empty=True) + if not isinstance(self.regions, tuple) or not all( + isinstance(v, SchematicRegionPlacement) for v in self.regions + ): + raise ValueError("sheet regions must be a tuple of region placements") + if not self.regions and self.id != "overview": + raise ValueError("only an overview sheet may be empty") + if (self.id == "overview") != (self.title == "Overview"): + raise ValueError("overview sheet id and title must be overview and Overview together") + + def to_dict(self) -> Dict[str, Any]: + return dict( + id=self.id, title=self.title, scope=self.scope, regions=[placement.to_dict() for placement in self.regions] + ) + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> SchematicSheet: + data = _object(value, {"id", "title", "scope", "regions"}, {"id", "title", "scope", "regions"}, "sheet") + return cls( + data["id"], + data["title"], + data["scope"], + tuple(SchematicRegionPlacement.from_dict(v) for v in _array(data["regions"], "sheet regions")), + ) + + +def _rect(region: SchematicRegion, placement: SchematicRegionPlacement) -> Bounds: + return ( + placement.x, + placement.y, + placement.x + region.bounds[2] - region.bounds[0], + placement.y + region.bounds[3] - region.bounds[1], + ) + + +def _separated(first: Bounds, second: Bounds) -> bool: + tolerance = 1e-7 + return ( + first[2] + GUTTER <= second[0] + tolerance + or second[2] + GUTTER <= first[0] + tolerance + or first[3] + GUTTER <= second[1] + tolerance + or second[3] + GUTTER <= first[1] + tolerance + ) + + +def _outside_title_block(rect: Bounds) -> bool: + return rect[2] <= TITLE_BLOCK_BOUNDS[0] or rect[3] <= TITLE_BLOCK_BOUNDS[1] + + +def _inside(rect: Bounds, usable: Bounds) -> bool: + tolerance = 1e-7 + return ( + rect[0] >= usable[0] - tolerance + and rect[1] >= usable[1] - tolerance + and rect[2] <= usable[2] + tolerance + and rect[3] <= usable[3] + tolerance + ) + + +def _region_map(regions: Tuple[SchematicRegion, ...]) -> Dict[str, SchematicRegion]: + result: Dict[str, SchematicRegion] = {} + components = set() + for region in regions: + if not isinstance(region, SchematicRegion): + raise ValueError("regions must contain SchematicRegion objects") + if region.id in result: + raise ValueError(f"duplicate region id: {region.id}") + for path in region.components: + identity = (region.scope, path) + if identity in components: + raise ValueError(f"component belongs to more than one region: {path}") + components.add(identity) + result[region.id] = region + return result + + +@dataclass(frozen=True) +class SchematicSheetPlan: + fingerprint: str + regions: Tuple[SchematicRegion, ...] + sheets: Tuple[SchematicSheet, ...] + diagnostics: Tuple[str, ...] = () + overview: bool = True + + def __post_init__(self) -> None: + _string(self.fingerprint, "plan fingerprint") + if not isinstance(self.regions, tuple) or not isinstance(self.sheets, tuple): + raise ValueError("plan regions and sheets must be tuples") + if not isinstance(self.overview, bool): + raise ValueError("overview must be a boolean") + if not isinstance(self.diagnostics, tuple) or not all(isinstance(v, str) for v in self.diagnostics): + raise ValueError("diagnostics must be a tuple of strings") + regions = _region_map(self.regions) + sheet_ids = set() + covered = set() + scope_sheets: Dict[str, list[SchematicSheet]] = {} + for sheet in self.sheets: + if not isinstance(sheet, SchematicSheet): + raise ValueError("sheets must contain SchematicSheet objects") + identity = (sheet.scope, sheet.id) + if identity in sheet_ids: + raise ValueError(f"duplicate sheet id in scope {sheet.scope}: {sheet.id}") + sheet_ids.add(identity) + scope_sheets.setdefault(sheet.scope, []).append(sheet) + if sheet.id == "overview" and not self.overview: + raise ValueError("overview sheet conflicts with overview=False") + occupied: list[Bounds] = [] + for placement in sheet.regions: + if placement.region_id not in regions: + raise ValueError(f"unknown placement region: {placement.region_id}") + region = regions[placement.region_id] + if region.scope != sheet.scope: + raise ValueError(f"region cannot move between board scopes: {region.id}") + if region.id in covered: + raise ValueError(f"region placed more than once: {region.id}") + covered.add(region.id) + rectangle = _rect(region, placement) + usable = OVERVIEW_BOUNDS if sheet.id == "overview" else USABLE_BOUNDS + if not _inside(rectangle, usable) or not _outside_title_block(rectangle): + raise ValueError(f"region outside usable sheet bounds: {region.id}") + if any(not _separated(rectangle, previous) for previous in occupied): + raise ValueError(f"region overlap or insufficient {GUTTER:g} mm gutter: {region.id}") + occupied.append(rectangle) + if covered != set(regions): + raise ValueError( + "plan must place every region exactly once; missing: " + ", ".join(sorted(set(regions) - covered)) + ) + if self.overview: + for scope, sheets in scope_sheets.items(): + if ( + len([sheet for sheet in sheets if sheet.id != "overview"]) > 1 + and (scope, "overview") not in sheet_ids + ): + raise ValueError(f"multiple content sheets require an overview in scope {scope}") + + def to_dict(self) -> Dict[str, Any]: + return dict( + fingerprint=self.fingerprint, + regions=[region.to_dict() for region in self.regions], + sheets=[sheet.to_dict() for sheet in self.sheets], + diagnostics=list(self.diagnostics), + overview=self.overview, + ) + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> SchematicSheetPlan: + data = _object( + value, + {"fingerprint", "regions", "sheets", "diagnostics", "overview"}, + {"fingerprint", "regions", "sheets"}, + "plan", + ) + return cls( + data["fingerprint"], + tuple(SchematicRegion.from_dict(v) for v in _array(data["regions"], "regions")), + tuple(SchematicSheet.from_dict(v) for v in _array(data["sheets"], "sheets")), + tuple(_array(data.get("diagnostics", []), "diagnostics")), + data.get("overview", True), + ) + + +class SchematicSheetPlanner: + def plan(self, compiled: CompiledDesign, options: SchematicExportOptions) -> SchematicSheetPlan: + from .KiCadSchematicExporter import KiCadSchematicExporter + + # Share the exporter's prepared regions and non-rail adjacency weights. + # A planning preview must be identical to the plan used for export. + return KiCadSchematicExporter()._plan_compiled(compiled, options) + + @staticmethod + def _assignments( + regions: Mapping[str, SchematicRegion], assignments: Optional[Mapping[str, str]] + ) -> Dict[str, str]: + if assignments is not None and not isinstance(assignments, Mapping): + raise ValueError("sheet assignments must be an object") + titles: Dict[str, list[str]] = {} + for region in regions.values(): + titles.setdefault(region.title, []).append(region.id) + result: Dict[str, str] = {} + for reference, title in (assignments or {}).items(): + _string(reference, "assignment region reference") + _string(title, "assignment sheet title") + if reference in regions: + identity = reference + elif reference not in titles: + raise ValueError(f"unknown assignment region: {reference}") + elif len(titles[reference]) != 1: + raise ValueError(f"ambiguous assignment region title: {reference}; use a canonical region id") + else: + identity = titles[reference][0] + if identity in result and result[identity] != title: + raise ValueError(f"conflicting assignments for region {identity}") + result[identity] = title + for region in regions.values(): + if region.kind == "mechanical" and region.id not in result: + result[region.id] = "Overview" + return result + + @staticmethod + def _adjacency( + regions: Mapping[str, SchematicRegion], adjacency: Optional[Mapping[Tuple[str, str], float]] + ) -> Dict[Tuple[str, str], float]: + if adjacency is not None and not isinstance(adjacency, Mapping): + raise ValueError("adjacency must map region-id pairs to weights") + result: Dict[Tuple[str, str], float] = {} + for pair, weight in (adjacency or {}).items(): + if not isinstance(pair, tuple) or len(pair) != 2 or not all(v in regions for v in pair): + raise ValueError(f"unknown or invalid adjacency pair: {pair}") + _number(weight, "adjacency weight") + if weight < 0: + raise ValueError("adjacency weight cannot be negative") + if pair[0] == pair[1] or weight == 0: + continue + key = cast(Tuple[str, str], tuple(sorted(pair))) + if key in result and result[key] != weight: + raise ValueError(f"conflicting adjacency weights: {pair}") + result[key] = float(weight) + return result + + @staticmethod + def _position( + region: SchematicRegion, occupied: Sequence[Bounds], usable: Bounds + ) -> Optional[SchematicRegionPlacement]: + xs = sorted({usable[0]} | {rect[2] + GUTTER for rect in occupied}) + ys = sorted({usable[1]} | {rect[3] + GUTTER for rect in occupied}) + for y in ys: + for x in xs: + candidate = SchematicRegionPlacement(region.id, x, y) + rectangle = _rect(region, candidate) + if ( + _inside(rectangle, usable) + and _outside_title_block(rectangle) + and all(_separated(rectangle, other) for other in occupied) + ): + return candidate + return None + + def plan_regions( + self, + regions: Sequence[SchematicRegion], + fingerprint: str, + *, + assignments: Optional[Mapping[str, str]] = None, + requested: Optional[Union[SchematicSheetPlan, Mapping[str, Any]]] = None, + overview: bool = True, + adjacency: Optional[Mapping[Tuple[str, str], float]] = None, + ) -> SchematicSheetPlan: + _string(fingerprint, "fingerprint") + if not isinstance(overview, bool): + raise ValueError("overview must be boolean") + if not isinstance(regions, Sequence) or not all(isinstance(region, SchematicRegion) for region in regions): + raise ValueError("regions must be a sequence of SchematicRegion objects") + prepared = tuple(sorted(regions, key=lambda region: region.id)) + by_id = _region_map(prepared) + assigned = self._assignments(by_id, assignments) + edges = self._adjacency(by_id, adjacency) + if requested is not None: + adopted = ( + requested if isinstance(requested, SchematicSheetPlan) else SchematicSheetPlan.from_dict(requested) + ) + if adopted.fingerprint != fingerprint: + raise ValueError( + "stale sheet plan fingerprint; regenerate the plan for this compiled design and geometry" + ) + supplied = {region.id: region for region in adopted.regions} + if set(supplied) != set(by_id): + raise ValueError("requested plan regions differ from prepared regions") + for identity, region in by_id.items(): + other = supplied[identity] + if (region.title, region.scope, region.kind, region.bounds, set(region.components)) != ( + other.title, + other.scope, + other.kind, + other.bounds, + set(other.components), + ): + raise ValueError(f"requested region bounds or membership changed: {identity}") + for sheet in adopted.sheets: + for placement in sheet.regions: + title = assigned.get(placement.region_id) + if title is not None and not self._title_matches(sheet.title, title): + raise ValueError(f"requested plan conflicts with sheet assignment: {placement.region_id}") + if title == "Overview" and sheet.id != "overview": + raise ValueError("Overview assignment must use sheet id overview") + return SchematicSheetPlan( + fingerprint, + prepared, + adopted.sheets, + self._diagnostics(prepared, adopted.sheets, edges, adopted.diagnostics, measured=adjacency is not None), + adopted.overview, + ) + + groups: Dict[Tuple[str, Optional[str]], list[SchematicRegion]] = {} + for region in prepared: + groups.setdefault((region.scope, assigned.get(region.id)), []).append(region) + sheets = [] + diagnostics = [] + # Allocate explicit sheet titles before naming automatic pages in the same scope. + used_titles: dict[str, set[str]] = {} + for scope, title in sorted(groups, key=lambda group: (group[0], group[1] is None, group[1] or "")): + members = groups[(scope, title)] + scope_titles = used_titles.setdefault(scope, set()) + if title == "Overview" and not overview: + raise ValueError("Overview assignment requires overview=True") + usable = OVERVIEW_BOUNDS if title == "Overview" else USABLE_BOUNDS + pages: list[list[SchematicRegionPlacement]] = [] + ordered = sorted( + members, + key=lambda r: ( + -(r.bounds[2] - r.bounds[0]) * (r.bounds[3] - r.bounds[1]), + -max(r.bounds[2] - r.bounds[0], r.bounds[3] - r.bounds[1]), + r.id, + ), + ) + # Keep signal neighbours contiguous in the packing order, rather than + # letting unrelated large rectangles consume their available space. + # Adjacency is measured upstream with common rails excluded. + remaining = list(ordered) + ordered = [] + while remaining: + if not ordered: + chosen = remaining[0] + else: + previous = ordered[-1] + chosen = min( + remaining, + key=lambda r: ( + -edges.get(cast(Tuple[str, str], tuple(sorted((previous.id, r.id)))), 0), + -(previous.title.split(" /")[0] == r.title.split(" /")[0]), + remaining.index(r), + ), + ) + remaining.remove(chosen) + ordered.append(chosen) + for region in ordered: + if self._position(region, (), usable) is None: + width = region.bounds[2] - region.bounds[0] + height = region.bounds[3] - region.bounds[1] + raise ValueError( + f"region {region.id} ({width:g} x {height:g} mm) exceeds usable " + f"{'overview inset' if title == 'Overview' else 'A3 sheet'}; " + "partition it into whole functional continuation regions before planning; no content was cropped" + ) + candidates = [] + for index, placements in enumerate(pages): + occupied = [_rect(by_id[p.region_id], p) for p in placements] + candidate_placement = self._position(region, occupied, usable) + if candidate_placement is not None: + colocated = {p.region_id for p in placements} + inside = sum( + weight + for pair, weight in edges.items() + if region.id in pair and (set(pair) - {region.id}).issubset(colocated) + ) + placed_elsewhere = {p.region_id for page in pages for p in page} - colocated + crossing = sum( + weight + for pair, weight in edges.items() + if region.id in pair and bool((set(pair) - {region.id}) & placed_elsewhere) + ) + family = region.title.split(" /")[0] + siblings = sum(by_id[p.region_id].title.split(" /")[0] == family for p in placements) + candidates.append( + ( + (-inside, -siblings, crossing, candidate_placement.y, candidate_placement.x, index), + index, + candidate_placement, + ) + ) + if candidates: + _, index, placement = min(candidates, key=lambda candidate: candidate[0]) + pages[index].append(placement) + else: + if title == "Overview" and pages: + raise ValueError( + "explicit Overview regions do not fit the reserved lower inset; revise their grouping or geometry" + ) + first_placement = self._position(region, (), usable) + assert first_placement is not None # checked above for this region + pages.append([first_placement]) + # Continuation numbers are local to a functional title. A single + # Control page must not become /17 because sixteen other pages exist. + pages.sort( + key=lambda placements: min( + (natural_order(by_id[p.region_id].title), by_id[p.region_id].id) for p in placements + ) + ) + bases = [] + for placements in pages: + if title is not None: + bases.append(title) + else: + labels = sorted(set(by_id[p.region_id].title.split(" /")[0] for p in placements)) + base = " + ".join(labels[:2]) + (" + others" if len(labels) > 2 else "") + bases.append("Overview (circuit)" if base == "Overview" else base[:60]) + totals = Counter(bases) + counts: Counter[str] = Counter() + for index, placements in enumerate(pages): + if title == "Overview": + sheet_id, sheet_title = "overview", "Overview" + else: + base = bases[index] + counts[base] += 1 + sheet_title = base if totals[base] == 1 else f"{base} /{counts[base]}" + if title is None and sheet_title in scope_titles: + while f"{base} /{counts[base]}" in scope_titles: + counts[base] += 1 + sheet_title = f"{base} /{counts[base]}" + token = json.dumps( + [scope, title, sorted(p.region_id for p in placements)], ensure_ascii=False + ).encode("utf-8") + sheet_id = "sheet_" + hashlib.sha256(token).hexdigest()[:16] + if title is not None and counts[base] > 1: + diagnostics.append( + f"continuation: explicit sheet {title!r} in scope {scope!r} continues as {sheet_title!r}" + ) + scope_titles.add(sheet_title) + sheets.append(SchematicSheet(sheet_id, sheet_title, scope, tuple(placements))) + scopes = sorted({region.scope for region in prepared}) + if not scopes and overview: + sheets.append(SchematicSheet("overview", "Overview", "", ())) + for scope in scopes: + content = [sheet for sheet in sheets if sheet.scope == scope and sheet.id != "overview"] + if overview and len(content) > 1 and not any(s.scope == scope and s.id == "overview" for s in sheets): + sheets.append(SchematicSheet("overview", "Overview", scope, ())) + sheets = _continuation_order(sheets, by_id, diagnostics) + return SchematicSheetPlan( + fingerprint, + prepared, + tuple(sheets), + self._diagnostics(prepared, tuple(sheets), edges, tuple(diagnostics), measured=adjacency is not None), + overview, + ) + + @staticmethod + def _title_matches(actual: str, assigned: str) -> bool: + if actual == assigned: + return True + prefix = assigned + " /" + return actual.startswith(prefix) and actual[len(prefix) :].isdigit() and int(actual[len(prefix) :]) >= 1 + + @staticmethod + def _diagnostics( + regions: Tuple[SchematicRegion, ...], + sheets: Tuple[SchematicSheet, ...], + adjacency: Mapping[Tuple[str, str], float], + initial: Tuple[str, ...], + *, + measured: bool, + ) -> Tuple[str, ...]: + generated = ("sparse_sheet:", "tiny_sheet:", "cross_sheet_connections:", "region_continuation:") + result = [note for note in initial if not note.startswith(generated)] + by_id = {region.id: region for region in regions} + location = {p.region_id: (sheet.scope, sheet.id) for sheet in sheets for p in sheet.regions} + for region in regions: + suffix = region.title.rsplit(" /", 1) + if len(suffix) == 2 and suffix[1].isdigit() and int(suffix[1]) >= 2: + result.append( + f"region_continuation: prepared region {region.id!r} retains whole functional continuation {region.title!r}" + ) + for sheet in sheets: + if sheet.id == "overview": + continue + area = sum( + (by_id[p.region_id].bounds[2] - by_id[p.region_id].bounds[0]) + * (by_id[p.region_id].bounds[3] - by_id[p.region_id].bounds[1]) + for p in sheet.regions + ) + fraction = area / ((USABLE_BOUNDS[2] - USABLE_BOUNDS[0]) * (USABLE_BOUNDS[3] - USABLE_BOUNDS[1])) + if fraction < 0.25: + result.append( + f"sparse_sheet: {sheet.title!r} in scope {sheet.scope!r} uses {fraction:.1%} of its usable region area" + ) + component_count = sum(len(by_id[p.region_id].components) for p in sheet.regions) + if component_count <= 2: + result.append( + f"tiny_sheet: {sheet.title!r} in scope {sheet.scope!r} contains {component_count} physical components" + ) + crossing = sum( + weight + for pair, weight in adjacency.items() + if by_id[pair[0]].scope == by_id[pair[1]].scope and location[pair[0]] != location[pair[1]] + ) + if measured: + result.append( + f"cross_sheet_connections: {crossing:g} weighted region connections (not an electrical or visual acceptance result)" + ) + else: + result.append("cross_sheet_connections: not measured (no adjacency supplied)") + return tuple(dict.fromkeys(result)) + + +KiCadSchematicPlanner = SchematicSheetPlanner diff --git a/edg/electronics_model/KiCadSchematicPower.py b/edg/electronics_model/KiCadSchematicPower.py new file mode 100644 index 000000000..6be8e5160 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicPower.py @@ -0,0 +1,932 @@ +"""Power-circuit presentation from verified symbols and compiled terminal nets.""" + +from __future__ import annotations + +from collections import defaultdict +from typing import TYPE_CHECKING, Any, Callable, Collection, Mapping, Optional, Sequence, TypedDict, cast +from .KiCadSchematicTypes import Bounds, Point, PinKey, PinNets, Placement, Placements, Views, RouteResult + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent, SymbolView + from .KiCadSchematicCircuits import SchematicCircuit + + +class PowerTopology(TypedDict, total=False): + kind: str + ic: str + coil: str + ground: str + input: str + output: str + switch: str + roles: dict[str, dict[str, str]] + bridges: list[tuple[str, str, str]] + + +class LedBuckTopology(TypedDict): + kind: str + ic: str + coil: str + bootstrap: str + sense: str + input: str + switch: str + boot: str + feedback: str + ground: str + output: str + roles: dict[str, str] + input_caps: list[str] + output_caps: list[str] + load_return_witnesses: list[PinKey] + + +def role_nets(component: PhysicalComponent, pin_nets: PinNets) -> dict[str, str]: + """Parallel physical pads may share a role only when their nets agree.""" + roles = defaultdict(set) + for number, port in component.pins.items(): + role = port.removesuffix(".net").split(".")[-1].lower() + roles[role].add(pin_nets.get((component.path, number))) + return {role: cast(str, next(iter(nets))) for role, nets in roles.items() if len(nets) == 1 and None not in nets} + + +def symbol_id(view: SymbolView) -> str: + return view.lib_id.rsplit("_PB_", 1)[0] + + +def led_buck_topology( + members: Collection[str], by_path: Mapping[str, PhysicalComponent], views: Views, pin_nets: PinNets +) -> tuple[Optional[LedBuckTopology], Optional[str]]: + """Verified TPS92200 model plus unique compiled bootstrap/sense witnesses. + + A BOOT-like spelling on another model is not permission to specialize its + layout. Parallel modeled pads are allowed only when their role nets agree. + """ + controllers = [ + p + for p in members + if getattr(by_path[p], "hierarchy", ()) + and by_path[p].hierarchy[-1][1].removeprefix("PolymorphicBlocks.") + == "edg.parts.power.LedDriver_Tps92200.Tps92200_Device" + ] + if not controllers: + return None, None + if len(controllers) != 1: + return None, "ambiguous LED buck controllers in region" + ic = controllers[0] + roles = role_nets(by_path[ic], pin_nets) + declared = {n: r.removesuffix(".net") for n, r in by_path[ic].pins.items()} + required = {"1": "fb", "2": "dim", "3": "gnd", "4": "vin", "5": "sw", "6": "boot"} + if any(declared.get(n) != role for n, role in required.items()) or not set(required.values()) <= roles.keys(): + return None, "verified LED buck terminal roles do not match compiled pins" + if len({roles[r] for r in required.values()}) != 6: + return None, "LED buck terminal nets are not distinct" + circuit = getattr(by_path[ic], "functional_circuit", None) + if circuit is not None and (circuit.template not in ("auto", "buck") or circuit.stages): + return None, "authored circuit template or stages take precedence" + nets = {p: {pin_nets.get((p, n)) for n in by_path[p].pins} for p in members} + caps = [p for p in members if symbol_id(views[p]) in ("Device:C", "Device:C_Polarized")] + boots = [p for p in caps if nets[p] == {roles["boot"], roles["sw"]}] + senses = [ + p + for p in members + if symbol_id(views[p]) in ("Device:R", "Device:R_US") and nets[p] == {roles["fb"], roles["gnd"]} + ] + coils = [ + p + for p in members + if symbol_id(views[p]) == "Device:L" + and len(nets[p]) == 2 + and None not in nets[p] + and roles["sw"] in nets[p] + and not (nets[p] & {roles["vin"], roles["gnd"], roles["boot"], roles["fb"]}) + ] + if len(boots) != 1 or len(senses) != 1 or len(coils) != 1: + return None, "bootstrap capacitor, sense resistor or output inductor is missing or ambiguous" + output = next(iter(nets[coils[0]] - {roles["sw"]})) + # This verified model exports the FB/sense node as LED cathode. Some boards + # solder the load directly to existing pads and use virtual DummyPassive + # endpoints, so there need not be another modeled physical pad on this net. + outside = [(p, n) for (p, n), net in pin_nets.items() if p not in members and net == roles["fb"]] + return ( + LedBuckTopology( + kind="led_buck", + ic=ic, + coil=coils[0], + bootstrap=boots[0], + sense=senses[0], + input=roles["vin"], + switch=roles["sw"], + boot=roles["boot"], + feedback=roles["fb"], + ground=roles["gnd"], + output=cast(str, output), + roles=roles, + input_caps=sorted(p for p in caps if nets[p] == {roles["vin"], roles["gnd"]}), + output_caps=sorted(p for p in caps if nets[p] == {output, roles["gnd"]}), + load_return_witnesses=sorted(outside), + ), + None, + ) + + +def led_buck_candidates( + topology: LedBuckTopology, by_path: Mapping[str, PhysicalComponent], views: Views, pin_nets: PinNets +) -> list[tuple[str, list[Placement]]]: + """Four finite measured arrangements; no movement of an authored plan.""" + from .KiCadSchematicLayout import pins, snap + from .KiCadSchematicPlacement import atom_bounds, _rotation_for_pin + + t = topology + candidates = [] + for gap in (5.08, 10.16): + for sense_side in ("above", "below"): + entries: dict[str, Placement] = {} + + def put(path: str, x: float, y: float, angle: int = 0) -> None: + entries[path] = (by_path[path], snap(x), snap(y), angle) + + def local(path: str, net: Optional[str], angle: int = 0) -> Point: + ps = [(x, y) for n, x, y, _ in pins(views[path], 0, 0, angle) if pin_nets.get((path, n)) == net] + return sum(x for x, y in ps) / len(ps), sum(y for x, y in ps) / len(ps) + + def angle(path: str, net: Optional[str], direction: Point) -> int: + n = next(n for n in by_path[path].pins if pin_nets.get((path, n)) == net) + return _rotation_for_pin(views[path], n, direction) + + ic, coil, boot, sense = t["ic"], t["coil"], t["bootstrap"], t["sense"] + put(ic, 0, 0) + box = atom_bounds([entries[ic]], views) + sx, sy = local(ic, t["switch"]) + bx, by = local(ic, t["boot"]) + # SW branches at the capacitor's upper terminal; BOOT occupies the + # lower corridor. Neither wire needs to circle the whole channel. + ba = angle(boot, t["switch"], (0, -1)) + bpx, bpy = local(boot, t["switch"], ba) + put(boot, max(box[2], sx, bx) + gap - bpx, sy - bpy, ba) + boot_box = atom_bounds([entries[boot]], views) + ca = angle(coil, t["switch"], (-1, 0)) + cx, cy = local(coil, t["switch"], ca) + put(coil, max(boot_box[2], box[2]) + gap - cx, sy - cy, ca) + coil_box = atom_bounds([entries[coil]], views) + fx, fy = local(ic, t["feedback"]) + ra = angle(sense, t["ground"], (0, 1)) + rx, ry = local(sense, t["feedback"], ra) + # FB is on the left. Keep its sense shunt outside VIN/DIM pin + # escapes, with a short GND glyph instead of a ground return loop. + sense_y = min(fy, box[1] - gap) if sense_side == "above" else max(fy, box[3] + gap) + sense_box = atom_bounds([(by_path[sense], 0, 0, ra)], views) + put(sense, min(box[0], fx) - gap - sense_box[2], sense_y - ry, ra) + for bank_paths, rail, x0, y0, direction in ( + (t["input_caps"], t["input"], box[0] - gap, local(ic, t["input"])[1] + gap, -1), + (t["output_caps"], t["output"], coil_box[2] + gap, sy + gap, 1), + ): + x = x0 + for path in bank_paths: + a = angle(path, rail, (0, -1)) + px, py = local(path, rail, a) + local_box = atom_bounds([(by_path[path], 0, 0, a)], views) + # Pack measured field edges, not terminal centers: left- + # facing bank growth otherwise puts the next capacitor's + # right-hand value text through its neighbour's body. + put(path, x - local_box[2 if direction < 0 else 0], y0 - py, a) + bounds = atom_bounds([entries[path]], views) + x = bounds[2] + gap if direction > 0 else bounds[0] - gap + remaining = sorted(set(by_path) - set(entries)) + if remaining: + bounds = atom_bounds(list(entries.values()), views) + x, y = bounds[0], bounds[3] + gap + for path in remaining: + bounds = atom_bounds([(by_path[path], 0, 0, 0)], views) + put(path, x - bounds[0], y - bounds[1]) + x += bounds[2] - bounds[0] + gap + candidates.append((f"led_buck_{gap:g}_{sense_side}", list(entries.values()))) + return candidates + + +def compare_led_buck_variants( + placed: list[Placement], + views: Views, + pin_nets: PinNets, + baseline: RouteResult, + router: Callable[[Placements, Views, PinNets], RouteResult], + *, + source_annotations: Optional[Mapping[str, Optional[Point]]] = None, + region_bounds: Optional[Callable[[Placements, RouteResult], Bounds]] = None, +) -> tuple[list[Placement], RouteResult, Optional[dict[str, Any]]]: + """Try at most four routes against one cached incumbent, then select once.""" + import copy + from .KiCadSchematicLayout import freeze_annotations, snap + from .KiCadSchematicPlacement import packing_bounds + from .KiCadSchematicOrientation import ( + orientation_metrics, + passive_orientation_rank, + _geometry, + _escape_conflict_identities, + ) + + by_path = {c.path: c for c, _, _, _ in placed} + t, reason = led_buck_topology(tuple(sorted(by_path)), by_path, views, pin_nets) + if t is None: + return placed, baseline, (dict(accepted=False, reason=reason, route_trials=0, trials=[]) if reason else None) + source: dict[str, PhysicalComponent] = {} + for path, c in by_path.items(): + source[path] = copy.copy(c) + source[path].annotation = (source_annotations or {}).get(path) + before = best = orientation_metrics(placed, views, pin_nets, baseline) + original_geometry = _geometry(placed, views, pin_nets) + original_escapes = _escape_conflict_identities(placed, views, pin_nets) + original_failures = set(baseline[2]) + a, b, _, _ = packing_bounds(placed, views, pin_nets) + selected, selected_route, selected_name = placed, baseline, "incumbent" + trials: list[dict[str, Any]] = [] + calls = 0 + for name, entries in led_buck_candidates(t, source, views, pin_nets): + x, y, _, _ = packing_bounds(entries, views, pin_nets) + candidate = freeze_annotations([(c, snap(px + a - x), snap(py + b - y), r) for c, px, py, r in entries], views) + geometry = _geometry(candidate, views, pin_nets) + trial: dict[str, Any] = dict(candidate=name, geometry=geometry, selected=False) + reason = None + if geometry["collision_pairs"] or geometry["collisions"]: + reason = "symbol, field or pin text collision" + elif ( + geometry["escape_conflicts"] > original_geometry["escape_conflicts"] + or not _escape_conflict_identities(candidate, views, pin_nets) <= original_escapes + ): + reason = "new pin escape conflict" + elif geometry["clipped"]: + reason = "page overflow" + if reason is None: + route = router(candidate, views, pin_nets) + calls += 1 + metric = orientation_metrics(candidate, views, pin_nets, route) + trial["metrics"] = metric + bounds = region_bounds(candidate, route) if region_bounds else packing_bounds(candidate, views, pin_nets) + w, h = bounds[2] - bounds[0], bounds[3] - bounds[1] + if not set(route[2]) <= original_failures: + reason = "new failed endpoints" + elif w > 375 or h > 225 or (w > 210 and h > 205): + reason = "routed region page overflow" + elif metric["visual_conflicts"] > before["visual_conflicts"]: + reason = "degraded wire clearance" + elif passive_orientation_rank(metric) >= passive_orientation_rank(best): + reason = "incumbent scores better or ties" + else: + selected, selected_route, best, selected_name = candidate, route, metric, name + reason = "improved routed score" + trial["selected"] = True + trial["reason"] = reason + trials.append(trial) + for trial in trials: + trial["selected"] = trial["candidate"] == selected_name + return ( + selected, + selected_route, + dict( + accepted=selected_name != "incumbent", + selected=selected_name, + topology={k: v for k, v in t.items() if k != "roles"}, + route_trials=calls, + candidate_limit=4, + before=before, + after=best, + trials=trials, + ), + ) + + +def power_topology( + members: Collection[str], by_path: Mapping[str, PhysicalComponent], views: Views, pin_nets: PinNets +) -> Optional[PowerTopology]: + """Recognize a single buck or four-switch bridge; ambiguous cases decline.""" + roles = {p: role_nets(by_path[p], pin_nets) for p in members} + coils = [p for p in members if symbol_id(views[p]) == "Device:L"] + matches: list[PowerTopology] = [] + for ic in members: + r = roles[ic] + ground = r.get("gnd", r.get("pgnd")) + if ground is None: + continue + for coil in coils: + nets = {pin_nets.get((coil, n)) for n in by_path[coil].pins} + if len(nets) != 2 or None in nets: + continue + if ( + "sw" in r + and r["sw"] in nets + and ("vin" in r or "pwr_in" in r) + and r.get("vin", r.get("pwr_in")) not in nets + ): + matches.append( + PowerTopology( + kind="buck", + ic=ic, + coil=coil, + ground=ground, + input=cast(str, r.get("vin", r.get("pwr_in"))), + output=cast(str, next(iter(nets - {r["sw"]}))), + switch=r["sw"], + roles=roles, + ) + ) + elif {"sw1", "sw2", "hidrv1", "hidrv2", "lodrv1", "lodrv2"} <= r.keys() and nets == {r["sw1"], r["sw2"]}: + bridges = [] + for index in (1, 2): + sw = r[f"sw{index}"] + hi = [ + p + for p, fr in roles.items() + if fr.get("source") == sw and fr.get("gate") == r[f"hidrv{index}"] and "drain" in fr + ] + lo = [ + p + for p, fr in roles.items() + if fr.get("drain") == sw and fr.get("source") == ground and fr.get("gate") == r[f"lodrv{index}"] + ] + if len(hi) != 1 or len(lo) != 1: + break + bridges.append((hi[0], lo[0], roles[hi[0]]["drain"])) + if len(bridges) == 2: + matches.append( + PowerTopology( + kind="bridge", + ic=ic, + coil=coil, + ground=ground, + bridges=bridges, + input=bridges[0][2], + output=bridges[1][2], + roles=roles, + ) + ) + return matches[0] if len(matches) == 1 else None + + +def bridge_kernel( + topology: PowerTopology, + members: Collection[str], + by_path: Mapping[str, PhysicalComponent], + views: Views, + pin_nets: PinNets, +) -> set[str]: + """Controller, bridge, rail banks, shunts and actual bootstrap branches. + + Sense-filter and configuration networks remain separate functional detail. + The power kernel is bounded independently of their number. + """ + t = topology + selected = {t["ic"], t["coil"]} | {p for hi, lo, _ in t["bridges"] for p in (hi, lo)} + r, rails = t["roles"][t["ic"]], {t["input"], t["output"]} + caps = {p for p in members if symbol_id(views[p]) in ("Device:C", "Device:C_Polarized")} + resistors = {p for p in members if symbol_id(views[p]) in ("Device:R", "Device:R_US")} + nets = {p: {pin_nets.get((p, n)) for n in by_path[p].pins} for p in members} + # Series shunts link a bridge rail to another rail with its own ground bank. + bank_rails = {next(iter(nets[p] - {t["ground"]})) for p in caps if len(nets[p]) == 2 and t["ground"] in nets[p]} + for p in sorted(resistors): + if len(nets[p]) == 2 and nets[p] & rails and nets[p] <= bank_rails: + selected.add(p) + rails |= cast(set[str], nets[p]) + selected |= {p for p in caps if len(nets[p]) == 2 and t["ground"] in nets[p] and nets[p] & rails} + boot_pairs = [{r.get(f"btst{i}"), r[f"sw{i}"]} for i in (1, 2)] + selected |= {p for p in caps if nets[p] in boot_pairs} + return selected + + +def topology_primary_nets(components: Sequence[PhysicalComponent], views: Views, pin_nets: PinNets) -> frozenset[str]: + """Primary paths from a unique verified converter, never net-name guesses. + + Include both rail directions for bidirectional bridges. Gate/bootstrap paths + are part of recognizing the drawn converter, while a shared return does not + make every ground connection a primary routed power path. + """ + by_path = {component.path: component for component in components} + t = power_topology(tuple(sorted(by_path)), by_path, views, pin_nets) + if t is None: + return frozenset() + primary = {t["input"], t["output"]} + if t["kind"] == "buck": + primary.add(t["switch"]) + led, _ = led_buck_topology(tuple(sorted(by_path)), by_path, views, pin_nets) + if led is not None: + primary.update((led["boot"], led["feedback"])) + else: + roles = t["roles"][t["ic"]] + primary.update( + roles[role] + for role in ("sw1", "sw2", "hidrv1", "hidrv2", "lodrv1", "lodrv2", "btst1", "btst2") + if role in roles + ) + kernel = bridge_kernel(t, tuple(sorted(by_path)), by_path, views, pin_nets) + for path in kernel: + if symbol_id(views[path]) in ("Device:R", "Device:R_US"): + primary.update(pin_nets[path, number] for number in by_path[path].pins if (path, number) in pin_nets) + primary.discard(t["ground"]) + return frozenset(primary) + + +def topology_primary_endpoints( + components: Sequence[PhysicalComponent], pin_nets: PinNets, views: Views +) -> dict[str, frozenset[PinKey]]: + """Core terminals whose missing drawn wire hides converter operation. + + Rail-bank and bypass labels do not interrupt the main controller/bridge/ + inductor path. Classifying the endpoint as well as the net distinguishes + those presentation fallbacks without changing electrical net identity. + """ + components = tuple(components) + by_path = {component.path: component for component in components} + t = power_topology(tuple(sorted(by_path)), by_path, views, pin_nets) + if t is None: + return {} + nets = topology_primary_nets(components, views, pin_nets) + core = {t["ic"], t["coil"]} + roles = t["roles"][t["ic"]] + if t["kind"] == "bridge": + core.update(path for hi, lo, _ in t["bridges"] for path in (hi, lo)) + kernel = bridge_kernel(t, tuple(sorted(by_path)), by_path, views, pin_nets) + core.update(path for path in kernel if symbol_id(views[path]) in ("Device:R", "Device:R_US")) + bootstrap_pairs = [{roles.get("btst%d" % i), roles.get("sw%d" % i)} for i in (1, 2)] + else: + bootstrap_pairs = [{roles.get(role), t["switch"]} for role in ("btst", "bst") if role in roles] + led, _ = led_buck_topology(tuple(sorted(by_path)), by_path, views, pin_nets) + if led is not None: + core.add(led["sense"]) + bootstrap_pairs.append({led["boot"], led["switch"]}) + core.update( + path + for path, component in by_path.items() + if symbol_id(views[path]) in ("Device:C", "Device:C_Polarized") + and {pin_nets.get((path, n)) for n in component.pins} in bootstrap_pairs + ) + return { + net: frozenset( + (path, number) for path in core for number in by_path[path].pins if pin_nets.get((path, number)) == net + ) + for net in nets + } + + +def power_template( + members: Collection[str], by_path: Mapping[str, PhysicalComponent], views: Views, pin_nets: PinNets +) -> Optional[list[Placement]]: + """Place signal-bearing power geometry before measured support packing.""" + from .KiCadSchematicLayout import pins, snap + from .KiCadSchematicPlacement import atom_bounds, packing_bounds, _horizontal, _rotation_for_pin, _score + + t = power_topology(members, by_path, views, pin_nets) + if t is None: + return None + entries: dict[str, Placement] = {} + + def put(path: str, x: float, y: float, angle: int = 0) -> None: + entries[path] = (by_path[path], snap(x), snap(y), angle) + + def terminal(path: str, net: Optional[str], angle: int = 0) -> Point: + found = [v for v in pins(views[path], 0, 0, angle) if pin_nets.get((path, v[0])) == net] + return (sum(v[1] for v in found) / len(found), sum(v[2] for v in found) / len(found)) + + def orient_net(path: str, net: Optional[str], desired: Point) -> int: + number = next(n for n in by_path[path].pins if pin_nets.get((path, n)) == net) + return _rotation_for_pin(views[path], number, desired) + + ic, coil = t["ic"], t["coil"] + put(ic, 0, 0) + ic_box = atom_bounds([entries[ic]], views) + if t["kind"] == "buck": + sx, sy = terminal(ic, t["switch"]) + angle = orient_net(coil, t["switch"], (-1, 0)) + cx, cy = terminal(coil, t["switch"], angle) + put(coil, max(ic_box[2], sx) + 25.4 - cx, sy - cy, angle) + coil_box = atom_bounds([entries[coil]], views) + bank_origins = { + t["input"]: (ic_box[0] - 30.48, ic_box[1] + 15.24, -1), + t["output"]: (coil_box[2] + 20.32, sy + 20.32, 1), + } + else: + # Two vertical half bridges joined at their switch midpoints. Source/ + # drain orientation comes from physical pins, never guessed pin numbers. + for x, (hi, lo, rail) in zip((-50.8, 50.8), t["bridges"]): + ah = orient_net(hi, t["roles"][hi]["source"], (0, 1)) + al = orient_net(lo, t["roles"][lo]["drain"], (0, -1)) + put(hi, x, -17.78, ah) + put(lo, x, 17.78, al) + put(coil, 0, 0, _horizontal(views[coil])) + # Controller sits below both bridges, preserving short local gate paths. + rotated_box = atom_bounds([(by_path[ic], 0, 0, 90)], views) + put(ic, 0, 40.64 - rotated_box[1], 90) + bank_origins = {t["input"]: (-91.44, -15.24, -1), t["output"]: (91.44, -15.24, 1)} + # Separate input and output banks. Every capacitor keeps its actual rail + # identity; a shared ground alone cannot choose a bank. + for rail, (x0, y0, direction) in bank_origins.items(): + bank = sorted( + p + for p in members + if p not in entries + and symbol_id(views[p]) in ("Device:C", "Device:C_Polarized") + and {pin_nets.get((p, n)) for n in by_path[p].pins} == {rail, t["ground"]} + ) + columns = 2 if t["kind"] == "bridge" else 3 + for i, path in enumerate(bank): + angle = orient_net(path, rail, (0, -1)) + put(path, x0 + direction * (i % columns) * 25.4, y0 + (i // columns) * 30.48, angle) + # Remaining sense/bootstrap/configuration parts are packed below the + # principal circuit in real measured cells, outside its power paths. + occupied = atom_bounds(list(entries.values()), views) + x0, y0 = occupied[0], occupied[3] + 15.24 + x, y, row = x0, y0, 0.0 + supports = sorted(set(members) - set(entries)) + if t["kind"] == "bridge": + # Measured horizontal support rows sit below the controller, leaving + # gate escapes and the bridge switch midpoint clear. + support_columns = [(-139.7, 88.9), (-40.64, 88.9), (60.96, 88.9)] + for index, path in enumerate(supports): + column = index % 3 + x, y = support_columns[column] + angle = _horizontal(views[path]) + box = atom_bounds([(by_path[path], 0, 0, angle)], views) + put(path, x - box[0], y - box[1], angle) + support_columns[column] = (x, y + box[3] - box[1] + 10.16) + supports = [] + for path in supports: + box = atom_bounds([(by_path[path], 0, 0, 0)], views) + width, height = box[2] - box[0], box[3] - box[1] + if x > x0 and x + width > x0 + 300: + x, y, row = x0, y + row + 12.7, 0.0 + put(path, x - box[0], y - box[1]) + x += width + 12.7 + row = max(row, height) + result = list(entries.values()) + bounds = packing_bounds(result, views, pin_nets) + if ( + bounds[2] - bounds[0] + 17.78 <= 340 + and bounds[3] - bounds[1] + 17.78 <= 205 + and _score(result, views, pin_nets)[:2] == (0, 0) + ): + return result + return None + + +def power_template_candidates( + members: Collection[str], by_path: Mapping[str, PhysicalComponent], views: Views, pin_nets: PinNets +) -> tuple[list[tuple[str, list[Placement]]], list[dict[str, Any]]]: + """Four measured bridge proposals and explicit geometry rejection evidence. + + This is a presentation search over a uniquely verified physical topology. + Rail names and component reference prefixes never choose a terminal role. + """ + from .KiCadSchematicLayout import pins, snap + from .KiCadSchematicPlacement import atom_bounds, packing_bounds, _horizontal, _rotation_for_pin, _score + + topology = power_topology(members, by_path, views, pin_nets) + if topology is None or topology["kind"] != "bridge": + return [], [ + dict( + candidate="four_switch_bridge", + acceptable=False, + reason="topology ambiguity or no unique four-switch bridge", + ) + ] + t = topology + + def orientation(path: str, net: Optional[str], direction: Point) -> int: + number = next(n for n in by_path[path].pins if pin_nets.get((path, n)) == net) + return _rotation_for_pin(views[path], number, direction) + + def box(path: str, angle: int) -> Bounds: + return atom_bounds([(by_path[path], 0, 0, angle)], views) + + def netset(path: str) -> set[Optional[str]]: + return {pin_nets.get((path, n)) for n in by_path[path].pins} + + ic, coil = t["ic"], t["coil"] + # Follow the controller's measured gate-pin order. A bidirectional + # converter has no implied left-to-right power direction. + controller_pins = pins(views[ic], 0, 0, 90) + + def gate_position(bridge: tuple[str, str, str]) -> float: + gate_net = t["roles"][bridge[0]]["gate"] + positions = [x for number, x, _, _ in controller_pins if pin_nets.get((ic, number)) == gate_net] + return sum(positions) / len(positions) + + bridges = sorted(enumerate(t["bridges"], 1), key=lambda item: gate_position(item[1])) + candidates: list[tuple[str, list[Placement]]] = [] + diagnostics: list[dict[str, Any]] = [] + for gap in (15.24, 25.4): + for offset in (0.0, 12.7): + name = "bridge_spacing_%g_controller_%g" % (gap, offset) + entries: dict[str, Placement] = {} + + def put(path: str, x: float, y: float, angle: int = 0) -> None: + entries[path] = (by_path[path], snap(x), snap(y), angle) + + coil_angle = _horizontal(views[coil]) + cb = box(coil, coil_angle) + put(coil, 0, 0, coil_angle) + # Measured occupied rectangles determine separation, including + # fields and pin text. Switch nodes face the inductor midline. + bridge_x = [] + for direction, (_, (hi, lo, rail)) in zip((-1, 1), bridges): + ah = orientation(hi, t["roles"][hi]["source"], (0, 1)) + al = orientation(lo, t["roles"][lo]["drain"], (0, -1)) + hb, lb = box(hi, ah), box(lo, al) + x = cb[0] - gap - max(hb[2], lb[2]) if direction < 0 else cb[2] + gap - min(hb[0], lb[0]) + bridge_x.append(x) + put(hi, x, -gap / 2 - hb[3], ah) + put(lo, x, gap / 2 - lb[1], al) + # The wide rotated controller lives beneath both bridge legs. + core = atom_bounds(list(entries.values()), views) + ib = box(ic, 90) + put(ic, offset, core[3] + 10.16 - ib[1], 90) + controller_bounds = atom_bounds([entries[ic]], views) + # Each true rail owns its capacitor bank, outward from its leg. + # Shunts retain the same side as the rail they physically join. + for index, (_, (hi, lo, rail)) in enumerate(bridges): + direction = -1 if index == 0 else 1 + leg = atom_bounds([entries[hi], entries[lo]], views) + bank = sorted( + p + for p in members + if p not in entries + and symbol_id(views[p]) in ("Device:C", "Device:C_Polarized") + and netset(p) == {rail, t["ground"]} + ) + y = leg[1] + for ordinal, path in enumerate(bank): + angle = orientation(path, rail, (0, -1)) + b = box(path, angle) + x = leg[0] - gap - b[2] if direction < 0 else leg[2] + gap - b[0] + # Reserve physical pin escapes beyond the visible body. + # Start stable path order beside the controller, then grow + # toward the far row. This avoids attempting isolated far + # branches before the nearer rail tree exists. + x += direction * (ordinal % 2) * 30.48 + put(path, x, y + ((len(bank) - 1) // 2 - ordinal // 2) * 30.48 - b[1], angle) + # A uniquely connected series resistor is a rail shunt, placed + # above its actual high-side drain, with its outer bank nearby. + for index, (_, (hi, lo, rail)) in enumerate(bridges): + shunts = sorted( + p + for p in members + if p not in entries + and symbol_id(views[p]) in ("Device:R", "Device:R_US") + and len(netset(p)) == 2 + and rail in netset(p) + ) + if len(shunts) != 1: + continue + path = shunts[0] + angle = orientation(path, rail, (0, 1)) + hb = atom_bounds([entries[hi]], views) + b = box(path, angle) + put(path, bridge_x[index], hb[1] - 12.7 - b[3], angle) + outer = next(iter(netset(path) - {rail})) + raw = sorted( + p + for p in members + if p not in entries + and symbol_id(views[p]) in ("Device:C", "Device:C_Polarized") + and netset(p) == {outer, t["ground"]} + ) + direction = -1 if index == 0 else 1 + for ordinal, cap in enumerate(raw): + ca = orientation(cap, outer, (0, -1)) + bb = box(cap, ca) + capx = hb[0] - gap - bb[2] if direction < 0 else hb[2] + gap - bb[0] + put(cap, capx + direction * ordinal * 30.48, hb[1] - 20.32 - bb[3], ca) + # Bootstrap branches beside their actual switch; remaining parts + # are measured shelves below, retaining exact component identity. + r = t["roles"][ic] + for side, (index, (hi, lo, rail)) in enumerate(bridges): + pair = {r.get("btst%d" % index), r["sw%d" % index]} + branch = sorted(p for p in members if p not in entries and netset(p) == pair) + direction = -1 if side == 0 else 1 + leg = atom_bounds([entries[hi]], views) + for path in branch: + angle = _horizontal(views[path]) + b = box(path, angle) + x = bridge_x[side] - direction * 15.24 + put(path, x, -0.5 * (b[1] + b[3]), angle) + # A controller driver-supply bypass belongs beside its actual + # supply pin, rather than extending the unrelated support shelf. + # Only an exact capacitor between the compiled supply and return + # qualifies; no component or reference names participate. + supplies = {r[role] for role in ("regn", "drv_sup") if role in r} + for supply in sorted(supplies): + bypasses = sorted( + p + for p in members + if p not in entries + and symbol_id(views[p]) in ("Device:C", "Device:C_Polarized") + and netset(p) == {supply, t["ground"]} + ) + terminals = [ + (x, y) + for number, x, y, _ in pins(views[ic], *entries[ic][1:]) + if pin_nets.get((ic, number)) == supply + ] + if not terminals: + continue + px = sum(x for x, y in terminals) / len(terminals) + py = max(y for x, y in terminals) + supply_bounds = packing_bounds([entries[ic]], views, pin_nets) + for ordinal, path in enumerate(bypasses): + angle = orientation(path, supply, (0, -1)) + b = box(path, angle) + # Dense controller pins reserve vertical external-label + # corridors below the body. Keep the bypass outside the + # entire measured corridor, not merely outside the body. + left = supply_bounds[0] - 12.7 - b[2] + right = supply_bounds[2] + 12.7 - b[0] + proposals = [ + (x, py + ordinal * 25.4 + dy) + for dy in (0, -15.24, 15.24) + for x in sorted((left, right), key=lambda x: (abs(x - px), x)) + ] + for x, y in proposals: + candidate = (by_path[path], snap(x), snap(y), angle) + if _score(list(entries.values()) + [candidate], views, pin_nets)[:2] == (0, 0): + entries[path] = candidate + break + else: + # The final measured gate reports a specific failure; + # it must never move the part into the label corridor. + put(path, left, py + ordinal * 25.4, angle) + remaining = sorted(set(members) - set(entries)) + occupied = atom_bounds(list(entries.values()), views) + x0, y = occupied[0], occupied[3] + 10.16 + x, row = x0, 0.0 + for path in remaining: + angle = _horizontal(views[path]) + b = box(path, angle) + width, height = b[2] - b[0], b[3] - b[1] + if x > x0 and x + width > x0 + 300: + x, y, row = x0, y + row + 10.16, 0.0 + put(path, x - b[0], y - b[1], angle) + x += width + 10.16 + row = max(row, height) + result = list(entries.values()) + bounds = packing_bounds(result, views, pin_nets) + geometry = _score(result, views, pin_nets) + reasons = [] + if geometry[0]: + reasons.append("escape conflict") + if geometry[1]: + reasons.append("symbol or field collision") + width, height = bounds[2] - bounds[0] + 17.78, bounds[3] - bounds[1] + 17.78 + if width > 340 or height > 205: + reasons.append("overflow") + diagnostics.append( + dict( + candidate=name, + acceptable=not reasons, + reason="; ".join(reasons) if reasons else "valid measured bridge", + escape_conflicts=geometry[0], + collisions=geometry[1], + width_mm=round(width, 4), + height_mm=round(height, 4), + ) + ) + if not reasons: + candidates.append((name, result)) + return candidates, diagnostics + + +def compare_bridge_variants( + placed: list[Placement], + views: Views, + pin_nets: PinNets, + baseline: RouteResult, + router: Callable[[Placements, Views, PinNets], RouteResult], + *, + region_bounds: Optional[Callable[[Placements, RouteResult], Bounds]] = None, + source_annotations: Optional[Mapping[str, Optional[Point]]] = None, +) -> tuple[list[Placement], RouteResult, Optional[dict[str, Any]]]: + """Compare measured bridges against an already oriented, cached incumbent. + + At most four baseline-router calls, with exactly the orientation pass's + objective. No second orientation sweep or route-order optimizer is hidden + inside this bounded comparison. + """ + import copy + from .KiCadSchematicLayout import freeze_annotations, snap + from .KiCadSchematicPlacement import packing_bounds + from .KiCadSchematicOrientation import orientation_metrics, _rank, _geometry + + by_path = {c.path: c for c, _, _, _ in placed} + circuits = { + circuit.id: circuit + for c in by_path.values() + if (circuit := cast("Optional[SchematicCircuit]", getattr(c, "functional_circuit", None))) is not None + and circuit.template == "four_switch_bridge" + } + if len(circuits) != 1: + return placed, baseline, None + circuit = next(iter(circuits.values())) + if not set(by_path) <= set(circuit.components) or any( + getattr(getattr(c, "functional_circuit", None), "id", None) != circuit.id for c in by_path.values() + ): + return ( + placed, + baseline, + dict( + selected="orientation_only", + route_trials=0, + reason="region includes components outside the bridge circuit", + trials=[], + ), + ) + source_by_path = {} + for path, component in by_path.items(): + source = copy.copy(component) + source.annotation = (source_annotations or {}).get(path) + source_by_path[path] = source + candidates, diagnostics = power_template_candidates(tuple(sorted(source_by_path)), source_by_path, views, pin_nets) + before = best = orientation_metrics(placed, views, pin_nets, baseline) + original_failures = set(baseline[2]) + selected, selected_route, name = placed, baseline, "orientation_only" + old_bounds = packing_bounds(placed, views, pin_nets) + geometry = _geometry(placed, views, pin_nets) + trials: list[dict[str, Any]] = [] + calls = 0 + for candidate_name, entries in candidates: + bounds = packing_bounds(entries, views, pin_nets) + dx, dy = snap(old_bounds[0] - bounds[0]), snap(old_bounds[1] - bounds[1]) + candidate_source: list[Placement] = [] + for c, x, y, angle in entries: + component = copy.copy(c) + annotation = (source_annotations or {}).get(c.path) + component.annotation = annotation + candidate_source.append((component, snap(x + dx), snap(y + dy), angle)) + candidate = freeze_annotations(candidate_source, views) + trial_geometry = _geometry(candidate, views, pin_nets) + reason = None + if trial_geometry["escape_conflicts"] > geometry["escape_conflicts"]: + reason = "escape conflict" + elif trial_geometry["collisions"] or trial_geometry["collision_pairs"]: + reason = "symbol, field or pin text collision" + elif trial_geometry["clipped"]: + reason = "page overflow" + trial: dict[str, Any] = dict(candidate=candidate_name, selected=False, geometry=trial_geometry) + if reason is None: + route = router(candidate, views, pin_nets) + calls += 1 + metric = orientation_metrics(candidate, views, pin_nets, route) + trial["metrics"] = metric + clipped = False + if region_bounds is not None: + a, b, right, d = region_bounds(candidate, route) + w, h = right - a, d - b + clipped = w > 375 or h > 225 or (w > 210 and h > 205) + if clipped: + reason = "routed region page overflow" + elif not set(route[2]) <= original_failures: + reason = "new failed endpoints" + elif metric["visual_conflicts"] > best["visual_conflicts"]: + reason = "inadequate visual wire clearance" + elif _rank(metric) >= _rank(best): + reason = "incumbent scores better or ties" + else: + selected, selected_route, best, name = candidate, route, metric, candidate_name + trial["selected"] = True + reason = "improved routed score" + trial["reason"] = reason + trials.append(trial) + return ( + selected, + selected_route, + dict(selected=name, route_trials=calls, before=before, after=best, candidates=diagnostics, trials=trials), + ) + + +def gate_driver_circuits( + components: Sequence[PhysicalComponent], pin_nets: PinNets, views: Optional[Views] +) -> list[tuple[str, tuple[str, ...], tuple[str, ...]]]: + """Verify a split pull-up/down driver, source return and local bootstrap.""" + if views is None: + return [] + by_path = {c.path: c for c in components} + roles = {p: role_nets(c, pin_nets) for p, c in by_path.items()} + nets = {p: {pin_nets.get((p, n)) for n in c.pins} for p, c in by_path.items()} + resistors = {p for p in by_path if symbol_id(views[p]) in ("Device:R", "Device:R_US")} + capacitors = {p for p in by_path if symbol_id(views[p]) in ("Device:C", "Device:C_Polarized")} + diodes = {p for p in by_path if symbol_id(views[p]) in ("Device:D", "Device:D_Schottky", "Device:D_Zener")} + result = [] + for anchor, r in sorted(roles.items()): + if not {"tgup", "tgdn", "ts", "bst", "vcc", "gnd"} <= r.keys(): + continue + fets = [ + p + for p, terminals in roles.items() + if terminals.get("gate") == r["tgdn"] and terminals.get("source") == r["ts"] and "drain" in terminals + ] + gate_resistors = [p for p in resistors if nets[p] == {r["tgup"], r["tgdn"]}] + bootstrap = [p for p in capacitors if nets[p] == {r["bst"], r["ts"]}] + if len(fets) != 1 or len(gate_resistors) != 1 or len(bootstrap) != 1: + continue + members = {anchor, fets[0], gate_resistors[0], bootstrap[0]} + members |= {p for p in resistors if nets[p] == {r["tgdn"], r["ts"]}} + members |= {p for p in diodes if nets[p] in ({r["vcc"], r["bst"]}, {r["gnd"], r["ts"]})} + result.append( + (anchor, tuple(sorted(members - {anchor})), tuple(sorted({r["tgup"], r["tgdn"], r["ts"], r["bst"]}))) + ) + return result diff --git a/edg/electronics_model/KiCadSchematicPresentation.py b/edg/electronics_model/KiCadSchematicPresentation.py new file mode 100644 index 000000000..168f82694 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicPresentation.py @@ -0,0 +1,128 @@ +"""Source-owned presentation descriptions, independent of electrical identity.""" + +from __future__ import annotations +from dataclasses import dataclass, field +from typing import Mapping, Any +import copy + + +def _text(value: object, name: str) -> str: + if not isinstance(value, str) or not value.strip() or len(value) > 240: + raise ValueError(name + " must be nonempty text of at most 240 characters") + return value.strip() + + +@dataclass(frozen=True) +class SchematicPresentation: + components: Mapping[str, Mapping[str, Any]] = field(default_factory=dict) + interfaces: tuple[Mapping[str, str], ...] = () + groups: Mapping[str, str] = field(default_factory=dict) + circuits: tuple[dict[str, Any], ...] = () + schema: int = 1 + + @classmethod + def from_dict(cls, value: object) -> SchematicPresentation: + if not isinstance(value, dict) or set(value) - { + "schema", + "components", + "interfaces", + "groups", + "circuits", + }: + raise ValueError("unknown presentation fields") + if type(value.get("schema", 1)) is not int or value.get("schema", 1) not in (1, 2): + raise ValueError("unsupported presentation schema") + circuits = value.get("circuits", []) + if not isinstance(circuits, (list, tuple)): + raise ValueError("presentation circuits must be an array") + if circuits and value.get("schema", 1) != 2: + raise ValueError("circuits require presentation schema 2") + from .KiCadSchematicCircuits import validate_circuit_entries + + validate_circuit_entries(circuits) + components = value.get("components", {}) + groups = value.get("groups", {}) + interfaces = value.get("interfaces", []) + if ( + not isinstance(components, dict) + or not isinstance(groups, dict) + or not isinstance(interfaces, (list, tuple)) + ): + raise ValueError("invalid presentation collections") + for path, entry in components.items(): + _text(path, "component path") + if not isinstance(entry, dict) or set(entry) - { + "description", + "pin_names", + "display_value", + }: + raise ValueError("unknown component presentation fields") + for key in ("description", "display_value"): + if key in entry: + _text(entry[key], key) + pins = entry.get("pin_names", {}) + if not isinstance(pins, dict): + raise ValueError("pin_names must be an object") + for number, name in pins.items(): + _text(number, "physical pin") + _text(name, "pin name") + for entry in interfaces: + if ( + not isinstance(entry, dict) + or set(entry) - {"component", "pin", "name", "description"} + or not {"component", "name"} <= set(entry) + ): + raise ValueError("unknown or missing interface presentation fields") + for key, item in entry.items(): + _text(item, key) + for selector, title in groups.items(): + _text(selector, "group selector") + _text(title, "group title") + return cls( + copy.deepcopy(components), + tuple(copy.deepcopy(interfaces)), + copy.deepcopy(groups), + tuple(copy.deepcopy(circuits)), + value.get("schema", 1), + ) + + def to_dict(self) -> dict[str, Any]: + result: dict[str, Any] = dict( + schema=2 if self.circuits else self.schema, + components=copy.deepcopy(dict(self.components)), + interfaces=copy.deepcopy(list(self.interfaces)), + groups=dict(self.groups), + ) + if self.circuits or self.schema == 2: + result["circuits"] = copy.deepcopy(list(self.circuits)) + return result + + def validate(self, inventories: Mapping[str, Mapping[str, str]]) -> None: + from .KiCadSchematicCircuits import validate_circuit_entries + + validate_circuit_entries(self.circuits, inventories) + known = set(inventories) + requested = set(self.components) | {i["component"] for i in self.interfaces} + if requested - known: + raise ValueError("presentation references missing components: " + str(sorted(requested - known))) + for path, entry in self.components.items(): + if set(entry.get("pin_names", {})) - set(inventories[path]): + raise ValueError("presentation references unknown physical pins: " + path) + for entry in self.interfaces: + if "pin" in entry and entry["pin"] not in inventories[entry["component"]]: + raise ValueError("interface references unknown physical pin: " + entry["component"]) + + def descriptions(self, path: str) -> tuple[str, ...]: + result: list[str] = [] + entry = self.components.get(path, {}) + if entry.get("description"): + result.append(entry["description"]) + for interface in self.interfaces: + if interface["component"] == path: + prefix = "Pin " + interface["pin"] + ": " if "pin" in interface else "" + result.append( + prefix + + interface["name"] + + (": " + interface["description"] if interface.get("description") else "") + ) + return tuple(result) diff --git a/edg/electronics_model/KiCadSchematicReadability.py b/edg/electronics_model/KiCadSchematicReadability.py new file mode 100644 index 000000000..b088bc77a --- /dev/null +++ b/edg/electronics_model/KiCadSchematicReadability.py @@ -0,0 +1,197 @@ +"""Conservative scene inspection. Machine evidence never grants visual approval.""" + +from __future__ import annotations +from dataclasses import dataclass, asdict +import hashlib +from typing import Any, Mapping, Sequence, TYPE_CHECKING +from .KiCadSchematicTypes import SExpr, Bounds + +if TYPE_CHECKING: + from .KiCadSchematicExporter import SchematicDiagnostic +from .KiCadSchematicScene import ( + text_width as text_width, + text_bounds, + label_bounds, + pin_name_items, + pin_number_items, + instance_property_at, +) +import sexpdata + + +def children(tree: SExpr, name: str) -> list[SExpr]: + return [v for v in tree if isinstance(v, list) and v and str(v[0]) == name] + + +@dataclass(frozen=True) +class SceneText: + identity: str + text: str + bounds: Bounds + owner: str + kind: str + + +def text_item(identity: str, text: object, at: SExpr, effect: SExpr, owner: str, kind: str) -> SceneText | None: + if any(str(v) == "hide" for v in effect[1:]): + return None + font = children(effect, "font") + size = children(font[0], "size")[0][1] if font and children(font[0], "size") else 1.27 + justify = children(effect, "justify") + terms = {str(v) for v in justify[0][1:]} if justify else set() + angle = float(at[3]) if len(at) > 3 else 0 + arguments: tuple[object, float, float, float, float, str, bool] = ( + text, + float(at[1]), + float(at[2]), + angle, + size, + "left" if "left" in terms else "right" if "right" in terms else "center", + kind == "global_label", + ) + bounds = ( + label_bounds(*arguments, bottom="bottom" in terms) + if kind in ("label", "global_label") + else text_bounds(*arguments) + ) + return SceneText(identity, str(text), bounds, owner, kind) + + +def inspect_documents( + files: Mapping[str, str], diagnostics: Sequence[SchematicDiagnostic], patterns: Sequence[Mapping[str, Any]] = () +) -> dict[str, Any]: + findings: list[dict[str, Any]] = [] + scenes = [] + component_sheets: dict[str, str] = {} + + def finding(code: str, sheet: str, objects: Sequence[str], detail: str) -> None: + identity = hashlib.sha256((code + "|" + sheet + "|" + "|".join(sorted(objects))).encode()).hexdigest()[:20] + findings.append( + dict( + id=identity, + code=code, + sheet=sheet, + objects=sorted(objects), + detail=detail, + ) + ) + + for filename, content in sorted(files.items()): + if not filename.endswith(".kicad_sch"): + continue + doc = sexpdata.loads(content) + texts = [] + for i, item in enumerate(children(doc, "text") + children(doc, "label") + children(doc, "global_label")): + at = children(item, "at") + ef = children(item, "effects") + if at and ef: + ids = children(item, "uuid") + t = text_item( + str(ids[0][1]) if ids else str(i), + item[1], + at[0], + ef[0], + "", + str(item[0]), + ) + if t: + texts.append(t) + definitions = {d[1]: d for container in children(doc, "lib_symbols") for d in children(container, "symbol")} + wires = [ + tuple((p[1], p[2]) for p in children(pts, "xy")) + for wire in children(doc, "wire") + for pts in children(wire, "pts") + ] + for symbol in children(doc, "symbol"): + props = children(symbol, "property") + owner = next((p[2] for p in props if p[1] == "PBPath"), "") + if owner: + component_sheets[owner] = filename + for p in props: + at = children(p, "at") + ef = children(p, "effects") + if at and ef: + symbol_at = children(symbol, "at") + visible_at = instance_property_at(at[0], symbol_at[0]) if symbol_at else at[0] + t = text_item(owner + ":" + str(p[1]), p[2], visible_at, ef[0], owner, "field") + if t: + texts.append(t) + lib = children(symbol, "lib_id") + ats = children(symbol, "at") + if lib and ats and lib[0][1] in definitions: + definition = definitions[lib[0][1]] + texts.extend( + SceneText(**item) + for item in pin_name_items(definition, ats[0][1], ats[0][2], ats[0][3], owner) + + pin_number_items(definition, ats[0][1], ats[0][2], ats[0][3], owner) + ) + for i, a in enumerate(texts): + x1, y1, x2, y2 = a.bounds + if x1 < 10 or y1 < 8 or x2 > 410 or y2 > 287: + finding( + "text_outside_page", + filename, + [a.identity], + "Text bounds extend outside page margins", + ) + for b in texts[i + 1 :]: + if a.owner and a.owner == b.owner and a.kind != "pin_name" and b.kind != "pin_name": + continue + u1, v1, u2, v2 = b.bounds + if min(x2, u2) - max(x1, u1) > 0.3 and min(y2, v2) - max(y1, v1) > 0.3: + finding( + "text_collision", + filename, + [a.identity, b.identity], + "Visible text bounds overlap", + ) + for text in texts: + x1, y1, x2, y2 = text.bounds + for index, wire in enumerate(wires): + if len(wire) != 2: + continue + (ax, ay), (bx, by) = wire + # Only orthogonal wire interiors qualify; legal wire crossings are unrelated. + crosses = ( + ax == bx and x1 + 0.3 < ax < x2 - 0.3 and min(ay, by) < y2 - 0.3 and max(ay, by) > y1 + 0.3 + ) or (ay == by and y1 + 0.3 < ay < y2 - 0.3 and min(ax, bx) < x2 - 0.3 and max(ax, bx) > x1 + 0.3) + if crosses: + finding( + "wire_through_text", + filename, + [text.identity, "wire:" + str(index)], + "Wire intersects visible text bounds", + ) + scenes.append(dict(sheet=filename, texts=[asdict(t) for t in texts])) + for pattern in patterns: + if pattern["kind"] == "local_decoupling": + members = pattern["components"] + sheets = {component_sheets.get(path) for path in members} + if None in sheets or len(sheets) != 1: + finding( + "decoupling_split", + "", + members, + "A verified device and its local bypass capacitors are not on one sheet", + ) + for d in diagnostics: + reason = d.reason + if reason == "no schematic symbol mapping" or reason.startswith("local wire"): + finding( + "symbol_fallback" if reason == "no schematic symbol mapping" else "local_wire_fallback", + "", + [d.component], + reason, + ) + return dict( + schema=1, + visual_approval="pending", + status="findings" if findings else "no_machine_findings", + findings=findings, + patterns=list(patterns), + scenes=scenes, + limitations=[ + "Text bounds are conservative stroke-font estimates.", + "Machine evidence cannot establish circuit meaning or visual acceptance.", + ], + ) diff --git a/edg/electronics_model/KiCadSchematicRoles.py b/edg/electronics_model/KiCadSchematicRoles.py new file mode 100644 index 000000000..c6020776a --- /dev/null +++ b/edg/electronics_model/KiCadSchematicRoles.py @@ -0,0 +1,238 @@ +"""Verified display pin presentation, transcribed from PB model connection maps. + +Only annotates modeled pads. Does not add pins, NCs or electrical connections. +Integration: copy to electronics_model/KiCadSchematicRoles.py after source thaw. +Call infer_pin_names(component, [p.target.name for p in block.path_classes]). +Merge returned names BELOW explicit compiled/board presentation pin names. +""" + +from __future__ import annotations +from typing import Any, Mapping, Sequence, TYPE_CHECKING, Optional, cast + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent + +RoleEntry = tuple[set[str], dict[str, str], str] + +# Each table follows device.__init__'s .connected(...) maps in these modules. +# Exact direct-child connector classes ensure no intervening pin-flip adapter. +FPC050 = {"edg.parts.connector.Fpc.Afc01", "edg.parts.connector.Fpc.HiroseFh12sh"} +FPC030 = {"edg.parts.connector.Fpc.HiroseFh35cshw"} +OLED = "edg.parts.display.oled." +MAPS: dict[str, RoleEntry] = { + OLED + + "Er_Oled_096_1_1.Er_Oled_096_1_1_Device": ( + FPC050, + { + "1": "VSS", + "2": "C2P", + "3": "C2N", + "4": "C1P", + "5": "C1N", + "6": "VBAT", + "8": "VSS", + "9": "VDD", + "10": "BS0", + "11": "BS1", + "12": "BS2 (GND)", + "13": "CS", + "14": "RES", + "15": "DC", + "16": "PARALLEL (GND)", + "17": "PARALLEL (GND)", + "18": "D0/CLK", + "19": "D1/DATA", + "20": "D2", + "21": "D3 (GND)", + "22": "D4 (GND)", + "23": "D5 (GND)", + "24": "D6 (GND)", + "25": "D7 (GND)", + "26": "IREF", + "27": "VCOMH", + "28": "VCC", + "29": "NC/GND", + "30": "VSS", + }, + "ER-OLED-0.96-1.1 display interface: logic supply, charge pump, IREF and serial control", + ), + OLED + + "Er_Oled_022.Er_Oled022_1_Device": ( + FPC050, + { + "1": "VSS", + "2": "NC/GND", + "3": "VSS", + "5": "VDD", + "6": "BS1", + "7": "BS2", + "8": "CS", + "9": "RES", + "10": "DC", + "11": "PARALLEL (GND)", + "12": "PARALLEL (GND)", + "13": "D0/CLK", + "14": "D1/DATA", + "15": "D2", + "16": "D3 (GND)", + "17": "D4 (GND)", + "18": "D5 (GND)", + "19": "D6 (GND)", + "20": "D7 (GND)", + "21": "IREF", + "22": "VCOMH", + "23": "VCC", + "24": "VSS", + }, + "ER-OLED022-1 display interface: logic VDD, external VCC, IREF and serial control", + ), + OLED + + "Er_Oled_096_1c.Er_Oled_096_1c_Device": ( + FPC030, + { + "1": "VSS", + "2": "VSL", + "3": "VCOMH", + "4": "VP", + "5": "VCC", + "6": "IREF", + "7": "VSS", + "8": "VDD", + "9": "RES", + "10": "DC", + "11": "CS", + "12": "BS2 (GND)", + "13": "BS1", + "14": "BS0", + "15": "PARALLEL (GND)", + "16": "PARALLEL (GND)", + "17": "VDD", + "18": "D0/CLK", + "19": "D1/DATA", + "20": "D2", + "21": "D3 (GND)", + "22": "D4 (GND)", + "23": "D5 (GND)", + "24": "D6 (GND)", + "25": "D7 (GND)", + "26": "VLSS", + "27": "VCC", + "28": "VP", + "29": "VCOMH", + "30": "VSL", + "31": "VSS", + }, + "ER-OLED0.96-1C RGB display interface: logic VDD, external VCC, VSL/VP bias and serial control", + ), + "edg.parts.display.Waveshare_Epd.Waveshare_Epd_Device": ( + FPC050, + { + "2": "GDR", + "3": "RESE", + "4": "VGL", + "5": "VGH", + "8": "BS", + "9": "BUSY", + "10": "RST", + "11": "DC", + "12": "CS", + "13": "SCLK", + "14": "SDIN", + "15": "VDDIO", + "16": "VDD", + "17": "VSS", + "18": "VDD1V8", + "20": "VSH", + "21": "PREVGH", + "22": "VSL", + "23": "PREVGL", + "24": "VCOM", + }, + "Waveshare-compatible EPD interface: SPI control, boost gate/current sense and display bias rails", + ), + "edg.parts.display.EInk_Er_Epd027_2.Er_Epd027_2_Device": ( + FPC050, + { + "2": "GDR", + "3": "RESE", + "5": "VSHR", + "8": "BS", + "9": "BUSY", + "10": "RST", + "11": "DC", + "12": "CS", + "13": "SCLK", + "14": "SDIN", + "15": "VDDIO", + "16": "VDD", + "17": "VSS", + "18": "VDD1V8", + "20": "VSH", + "21": "VGH", + "22": "VSL", + "23": "VGL", + "24": "VCOM", + }, + "ER-EPD027-2 EPD interface: SPI control, boost gate/current sense and display bias rails", + ), +} + + +def _entry( + component: PhysicalComponent, class_names: Sequence[str], connector_length: object = None +) -> Optional[RoleEntry]: + classes = [c.removeprefix("PolymorphicBlocks.") for c in class_names] + if len(classes) < 2: + return None + entry = MAPS.get(classes[-2]) + if entry is None or classes[-1] not in entry[0]: + # Fpc050BottomFlip.generate explicitly exports logical n as physical + # length + 1 - n. Require that exact adapter, leaf model and compiled + # length; neither footprint text nor omitted-pad count establishes it. + if ( + len(classes) < 3 + or classes[-2] != "edg.parts.connector.Fpc.Fpc050BottomFlip" + or classes[-1] != "edg.parts.connector.Fpc.Afc07Top" + ): + return None + entry = MAPS.get(classes[-3]) + if entry is None or connector_length != max(map(int, entry[1])): + return None + length = connector_length + entry = ( + entry[0], + {str(length + 1 - int(pin)): name for pin, name in entry[1].items()}, + entry[2] + "; pin numbers are physical connector pads", + ) + # Physical connector mapping is identity pins.N, checked before assigning + # semantic names. A refined connector with any renumbering stays unknown. + if any(role.removesuffix(".net") != "pins." + number for number, role in component.pins.items()): + return None + if not set(component.pins).issubset(entry[1]): + return None + return entry + + +def infer_pin_names( + component: PhysicalComponent, class_names: Sequence[str], connector_length: object = None +) -> Mapping[str, str]: + entry = _entry(component, class_names, connector_length) + return {number: entry[1][number] for number in component.pins} if entry else {} + + +def infer_description(component: PhysicalComponent, class_names: Sequence[str], connector_length: object = None) -> str: + entry = _entry(component, class_names, connector_length) + if entry: + return entry[2] + classes = [c.removeprefix("PolymorphicBlocks.") for c in class_names] + if not component.pins and classes and classes[-1].endswith("_Outline"): + verified = { + OLED + + "Er_Oled_096_1_1.Er_Oled_096_1_1_Outline": "ER-OLED-0.96-1.1 mechanical panel outline; electrical interface is the FPC connector", + OLED + + "Er_Oled_022.Er_Oled022_1_Outline": "ER-OLED022-1 mechanical panel outline; electrical interface is the FPC connector", + OLED + + "Er_Oled_096_1c.Er_Oled_096_1c_Outline": "ER-OLED0.96-1C mechanical panel outline; electrical interface is the FPC connector", + } + return verified.get(classes[-1], "") + return "" diff --git a/edg/electronics_model/KiCadSchematicRouting.py b/edg/electronics_model/KiCadSchematicRouting.py new file mode 100644 index 000000000..547486774 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicRouting.py @@ -0,0 +1,111 @@ +"""Bounded fixed-placement routing search; electrical identities are immutable.""" + +from __future__ import annotations + +from collections import defaultdict +from typing import Any, Protocol, Sequence, TypedDict, Sized +from .KiCadSchematicTypes import Placements, Views, PinNets, RouteResult, Wire, PinKey, Point + + +class RouteMetrics(TypedDict): + length_mm: float + bends: int + crossings: int + failures: int + + +class Router(Protocol): + def __call__( + self, placed: Placements, views: Views, pin_nets: PinNets, *, strategy: str = "default" + ) -> RouteResult: ... + + +def route_metrics(wires: Sequence[Wire], failures: Sized) -> RouteMetrics: + """Measure union length, geometric corners and distinct cross-net crossings. + + Measurements cover local routed wires, excluding pin stubs and inter-region + links, which are fixed by the caller. Collinear overlaps count only once. + """ + lines: dict[tuple[str, int, float], list[tuple[float, float]]] = defaultdict(list) + ends: dict[tuple[str, Point], set[int]] = defaultdict(set) + for net, a, b in wires: + axis = 0 if a[1] == b[1] else 1 + fixed = a[1 - axis] + lo, hi = sorted((a[axis], b[axis])) + if lo == hi: + continue + lines[net, axis, fixed].append((lo, hi)) + ends[net, a].add(axis) + ends[net, b].add(axis) + segments: list[tuple[str, int, float, float, float]] = [] + for (net, axis, fixed), spans in sorted(lines.items()): + merged: list[tuple[float, float]] = [] + for lo, hi in sorted(spans): + if merged and lo <= merged[-1][1]: + merged[-1] = (merged[-1][0], max(hi, merged[-1][1])) + else: + merged.append((lo, hi)) + segments.extend((net, axis, fixed, lo, hi) for lo, hi in merged) + crossings = set() + corners = set() + for i, (net, axis, fixed, lo, hi) in enumerate(segments): + for other, other_axis, other_fixed, other_lo, other_hi in segments[i + 1 :]: + if axis == other_axis: + continue + if lo <= other_fixed <= hi and other_lo <= fixed <= other_hi: + xy = (other_fixed, fixed) if axis == 0 else (fixed, other_fixed) + if net != other: + crossings.add((tuple(sorted((net, other))), xy)) + elif other_fixed in (lo, hi) and fixed in (other_lo, other_hi): + corners.add((net, xy)) + return dict( + length_mm=round(sum(hi - lo for _, _, _, lo, hi in segments), 4), + bends=len(corners), + crossings=len(crossings), + failures=len(failures), + ) + + +def optimize_fixed_routes( + placed: Placements, views: Views, pin_nets: PinNets, baseline: RouteResult, router: Router +) -> tuple[RouteResult, dict[str, Any]]: + """Evaluate a fixed set of orders; ties retain the earlier candidate. + + Never accept new fallback endpoints or more crossings. A longer route may + remove crossings; the caller measures the selected route before packing. + """ + before = route_metrics(baseline[0], baseline[2]) + best, score, selected = baseline, _score(before), "baseline" + points = [p for _, a, b in baseline[0] for p in (a, b)] + if not points: + return best, dict(before=before, after=before, selected=selected, candidates=1) + evaluated = [] + for strategy in ("x", "y", "reverse", "short_first", "tree_search", "tree_reverse", "crossing_averse"): + candidate = router(placed, views, pin_nets, strategy=strategy) + metric = route_metrics(candidate[0], candidate[2]) + acceptable = ( + set(candidate[2]) <= set(baseline[2]) + and metric["crossings"] <= before["crossings"] + and (metric["crossings"] < before["crossings"] or metric["length_mm"] <= before["length_mm"]) + and all(15 <= p[0] <= 400 and 35 <= p[1] <= 275 for _, a, b in candidate[0] for p in (a, b)) + ) + evaluated.append(dict(strategy=strategy, metrics=metric, acceptable=acceptable)) + if acceptable and _score(metric) < score: + best, score, selected = candidate, _score(metric), strategy + return best, dict( + before=before, + after=route_metrics(best[0], best[2]), + selected=selected, + candidates=1 + len(evaluated), + trials=evaluated, + ) + + +def _score(metrics: RouteMetrics) -> tuple[int, int, float, int, float]: + return ( + metrics["failures"], + metrics["crossings"], + round(metrics["length_mm"] + 2.54 * metrics["bends"], 4), + metrics["bends"], + metrics["length_mm"], + ) diff --git a/edg/electronics_model/KiCadSchematicScene.py b/edg/electronics_model/KiCadSchematicScene.py new file mode 100644 index 000000000..c663b77f1 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicScene.py @@ -0,0 +1,696 @@ +"""Shared conservative scene geometry and bounded electrical-label placement. + +Moving a label adds a wire from its existing electrical anchor. No pin, existing +wire or net name is changed. Only strict interior perpendicular crossings +without electrical junctions are allowed across unrelated wires. +""" + +from __future__ import annotations + +import math +import unicodedata +from dataclasses import dataclass +from typing import Any, Iterable, Mapping, Sequence +from .KiCadSchematicWriter import S, children, node, validate_wire_contacts, write_wires +from .KiCadSchematicTypes import SymbolView, Bounds, Point, SExpr, PinTextItem, Placements, Views, PinNets, Wire, PinKey + + +def text_width(text: object, size: float) -> float: + return sum(2 if unicodedata.east_asian_width(c) in ("W", "F") else 1 for c in str(text)) * size + + +def text_bounds( + text: object, + x: float, + y: float, + angle: float = 0, + size: float = 1.27, + justify: str = "center", + outline: bool = False, +) -> Bounds: + lines = str(text).splitlines() or [""] + w = max(text_width(line, size) for line in lines) + h = size * 1.4 * len(lines) + lo = 0 if justify == "left" else -w if justify == "right" else -w / 2 + if outline: + lo -= 1.27 + w += 2.54 + h += 1.27 + r = math.radians(angle) + pts = [ + (x + a * math.cos(r) + b * math.sin(r), y - a * math.sin(r) + b * math.cos(r)) + for a, b in ((lo, -h / 2), (lo + w, -h / 2), (lo + w, h / 2), (lo, h / 2)) + ] + return min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts) + + +def label_bounds( + text: object, + x: float, + y: float, + angle: float = 0, + size: float = 1.27, + justify: str = "center", + outline: bool = False, + bottom: bool = False, +) -> Bounds: + """KiCad keeps labels readable at 0/180 and 90/270 degrees. + + Justification remains left/right in the readable text frame. Rotating a + right-justified 180-degree label as ordinary text mirrors its measured box + to the wrong side of the anchor, accepting body collisions and clipping. + """ + readable = angle % 180 + if bottom: + shift = size * 1.4 * len(str(text).splitlines() or [""]) / 2 + x -= shift * math.sin(math.radians(readable)) + y -= shift * math.cos(math.radians(readable)) + bounds = text_bounds(text, x, y, readable, size, justify, outline) + if bottom: + # Native stroke glyphs extend slightly beyond the nominal font ascent. + # Keep the electrical baseline fixed and reserve an extra stroke width. + return ( + bounds[0] - (0.1524 if readable == 90 else 0), + bounds[1] - (0.1524 if readable == 0 else 0), + bounds[2], + bounds[3], + ) + return bounds + + +def pin_label_bounds(name: str, x: float, y: float, direction: float, outline: bool = True) -> Bounds: + angle = (180 - int(direction)) % 360 + return label_bounds(name, x, y, angle, 1.27, "left" if angle in (0, 270) else "right", outline) + + +def overlap(a: Bounds, b: Bounds, margin: float = 0.25) -> bool: + return min(a[2], b[2]) - max(a[0], b[0]) > -margin and min(a[3], b[3]) - max(a[1], b[1]) > -margin + + +def segment_box(a: Point, b: Point, box: Bounds, margin: float = 0.15) -> bool: + return ( + a[0] == b[0] + and box[0] - margin <= a[0] <= box[2] + margin + and max(min(a[1], b[1]), box[1] - margin) <= min(max(a[1], b[1]), box[3] + margin) + ) or ( + a[1] == b[1] + and box[1] - margin <= a[1] <= box[3] + margin + and max(min(a[0], b[0]), box[0] - margin) <= min(max(a[0], b[0]), box[2] + margin) + ) + + +def safe_wire_crossing(a: Point, b: Point, c: Point, d: Point, protected: Iterable[Point] = ()) -> Point | None: + """Return the strict orthogonal interior crossing, or None for a touch. + + Endpoints, bends, pins, anchors, and junctions are never valid crossings. + Keeping both segments unsplit at the returned point preserves KiCad nets. + """ + if a[0] == b[0] and c[1] == d[1]: + point = (a[0], c[1]) + inside = ( + min(a[1], b[1]) + 0.15 < point[1] < max(a[1], b[1]) - 0.15 + and min(c[0], d[0]) + 0.15 < point[0] < max(c[0], d[0]) - 0.15 + ) + elif a[1] == b[1] and c[0] == d[0]: + return safe_wire_crossing(c, d, a, b, protected) + else: + return None + if not inside or any(abs(point[0] - p[0]) < 0.15 and abs(point[1] - p[1]) < 0.15 for p in protected): + return None + return point + + +# One conventional schematic grid step leaves distinct nets distinguishable at +# normal sheet scale. Exact native connectivity alone cannot detect near joins. +WIRE_VISUAL_CLEARANCE = 1.27 + + +def wire_visual_conflict( + a: Point, b: Point, c: Point, d: Point, protected: Iterable[Point] = (), clearance: float = WIRE_VISUAL_CLEARANCE +) -> bool: + """Reject near joins/parallel buses; permit clear interior crossings.""" + crossing = safe_wire_crossing(a, b, c, d, protected) + if crossing is not None: + return any( + math.hypot(crossing[0] - p[0], crossing[1] - p[1]) < clearance - 0.0001 for p in (a, b, c, d, *protected) + ) + dx = max(min(a[0], b[0]) - max(c[0], d[0]), min(c[0], d[0]) - max(a[0], b[0]), 0) + dy = max(min(a[1], b[1]) - max(c[1], d[1]), min(c[1], d[1]) - max(a[1], b[1]), 0) + return math.hypot(dx, dy) < clearance - 0.0001 + + +def wire_through_text(a: Point, b: Point, rect: Bounds) -> bool: + x1, y1, x2, y2 = rect + return ( + abs(a[0] - b[0]) < 0.001 + and x1 + 0.3 < a[0] < x2 - 0.3 + and max(min(a[1], b[1]), y1 + 0.3) < min(max(a[1], b[1]), y2 - 0.3) + ) or ( + abs(a[1] - b[1]) < 0.001 + and y1 + 0.3 < a[1] < y2 - 0.3 + and max(min(a[0], b[0]), x1 + 0.3) < min(max(a[0], b[0]), x2 - 0.3) + ) + + +def segments_touch(a: Point, b: Point, c: Point, d: Point) -> bool: + return segment_box(a, b, (min(c[0], d[0]), min(c[1], d[1]), max(c[0], d[0]), max(c[1], d[1])), 0.01) + + +@dataclass(frozen=True) +class SceneObject: + identity: str + kind: str + bounds: Bounds + owner: str = "" + + +def pin_name_items(definition: SExpr, sx: float, sy: float, rotation: float, owner: str = "") -> list[PinTextItem]: + """Visible library pin names in sheet coordinates, including actual fonts.""" + options = children(definition, "pin_names") + if options and any(str(v) == "hide" for v in options[0][1:]): + return [] + offsets = children(options[0], "offset") if options else [] + offset = offsets[0][1] if offsets else 0.508 + result: list[PinTextItem] = [] + r = math.radians(rotation) + for body in children(definition, "symbol"): + for pin in children(body, "pin"): + if any(str(v) == "hide" for v in pin[1:] if not isinstance(v, list)): + continue + names, ats, lengths = children(pin, "name"), children(pin, "at"), children(pin, "length") + if not names or names[0][1] in ("~", "") or not ats or not lengths: + continue + px, py, angle = ats[0][1:4] + a = math.radians(angle) + px += (lengths[0][1] + offset) * math.cos(a) + py += (lengths[0][1] + offset) * math.sin(a) + x = sx + px * math.cos(r) - py * math.sin(r) + y = sy - px * math.sin(r) - py * math.cos(r) + effective = (angle + rotation) % 360 + textangle = 0 if effective in (0, 180) else 90 + justify = "left" if effective in (0, 90) else "right" + eff = children(names[0], "effects") + font = children(eff[0], "font") if eff else [] + sizes = children(font[0], "size") if font else [] + size = sizes[0][1] if sizes else 1.27 + number = children(pin, "number")[0][1] + result.append( + dict( + identity=owner + ":pin:" + str(number), + text=str(names[0][1]), + owner=owner, + kind="pin_name", + bounds=text_bounds(names[0][1], x, y, textangle, size, justify), + ) + ) + return result + + +def instance_property_at(property_at: SExpr, symbol_at: SExpr) -> SExpr: + """Convert KiCad's instance-relative field angle into its visible text frame. + + Instance property positions are absolute, but the stored field angle includes + symbol rotation. KiCad renders equal field/symbol angles horizontally. + """ + return [property_at[0], property_at[1], property_at[2], (property_at[3] - symbol_at[3]) % 180] + + +def pin_number_items(definition: SExpr, sx: float, sy: float, rotation: float, owner: str = "") -> list[PinTextItem]: + """Reserve visible pin-number glyphs above the native readable pin line.""" + options = children(definition, "pin_numbers") + if options and any(str(v) == "hide" for v in options[0][1:]): + return [] + result: list[PinTextItem] = [] + r = math.radians(rotation) + for body in children(definition, "symbol"): + for pin in children(body, "pin"): + if any(str(v) == "hide" for v in pin[1:] if not isinstance(v, list)): + continue + numbers, ats, lengths = children(pin, "number"), children(pin, "at"), children(pin, "length") + if not numbers or not ats or not lengths: + continue + number = numbers[0] + px, py, angle = ats[0][1:4] + a = math.radians(angle) + px += lengths[0][1] * math.cos(a) / 2 + py += lengths[0][1] * math.sin(a) / 2 + x = sx + px * math.cos(r) - py * math.sin(r) + y = sy - px * math.sin(r) - py * math.cos(r) + horizontal = (angle + rotation) % 180 == 0 + effects = children(number, "effects") + fonts = children(effects[0], "font") if effects else [] + sizes = children(fonts[0], "size") if fonts else [] + size = sizes[0][1] if sizes else 1.27 + # Text baseline is displaced from the pin line; use a conservative + # readable-frame envelope at all four symbol orientations. + if horizontal: + y -= 0.508 + size * 0.7 + else: + x -= 0.508 + size * 0.7 + result.append( + dict( + identity=owner + ":number:" + str(number[1]), + owner=owner, + kind="pin_number", + text=str(number[1]), + bounds=text_bounds(number[1], x, y, 0 if horizontal else 90, size), + ) + ) + return result + + +def label_islands( + placed: Placements, views: Views, pin_nets: PinNets, wires: Sequence[Wire], external_nets: Iterable[str] +) -> set[PinKey]: + """Choose one label for each connected graphical island needing a name. + + This operates only on generated same-net segments, never re-extracts PB + connectivity. Junctions are recognized at segment endpoints (KiCad T joins), + not at unmarked crossings between wire interiors. + """ + from .KiCadSchematicLayout import pin_escape, pins + + by_net: dict[str, list[tuple[PinKey, Point, Point, float]]] = {} + for component, x, y, angle in placed: + for number, px, py, direction in pins(views[component.path], x, y, angle): + net = pin_nets.get((component.path, number)) + if net is None: + continue + escape = pin_escape(px, py, direction) + by_net.setdefault(net, []).append(((component.path, number), (px, py), escape, direction)) + selected = set() + for net, entries in by_net.items(): + segments = [(a, b) for n, a, b in wires if n == net] + [(a, b) for _, a, b, _ in entries] + parent = list(range(len(segments))) + + def root(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + for i, (a, b) in enumerate(segments): + for j in range(i): + c, d = segments[j] + if any(segments_touch(point, point, c, d) for point in (a, b)) or any( + segments_touch(point, point, a, b) for point in (c, d) + ): + left, right = root(i), root(j) + parent[max(left, right)] = min(left, right) + islands: dict[int, list[tuple[PinKey, Point, Point, float]]] = {} + offset = len(segments) - len(entries) + for i, entry in enumerate(entries): + islands.setdefault(root(offset + i), []).append(entry) + if net not in external_nets and len(islands) == 1 and len(entries) > 1: + continue + for members in islands.values(): + # Side-facing labels need less displacement than vertical ones. + selected.add(min(members, key=lambda e: (e[3] % 180 != 0, e[0]))[0]) + return selected + + +def wire_island_anchors(anchor: Point, net: str, segments: Sequence[Wire], limit: int = 8) -> list[Point]: + """Nearby vertices of the same *drawn* island, never another net island.""" + same = [(a, b) for name, a, b in segments if name == net] + connected = {i for i, (a, b) in enumerate(same) if segments_touch(anchor, anchor, a, b)} + pending = list(sorted(connected)) + while pending: + i = pending.pop() + a, b = same[i] + for j, (c, d) in enumerate(same): + if j in connected: + continue + if any(segments_touch(p, p, c, d) for p in (a, b)) or any(segments_touch(p, p, a, b) for p in (c, d)): + connected.add(j) + pending.append(j) + points = {p for i in connected for p in same[i] if p != anchor} + + def distance(p: Point) -> float: + return abs(p[0] - anchor[0]) + abs(p[1] - anchor[1]) + + ordered = sorted(points, key=lambda p: (distance(p), p)) + # A local pin cluster can occupy all nearby vertices. Include distant + # vertices of the same existing tree as well; this moves only a label, + # never draws a new long wire or jumps to a disconnected same-name island. + near_count = (limit - 1) // 2 + chosen = ordered[:near_count] + sorted(points, key=lambda p: (-distance(p), p)) + result = [anchor] + for point in chosen: + if point not in result: + result.append(point) + if len(result) >= limit: + break + return result + + +def place_document_labels( + doc: SExpr, electrical_segments: Sequence[Wire], identity: str, pin_stubs: Mapping[Wire, str] | None = None +) -> dict[str, Any]: + """Repair serialized labels against the actual sheet scene, in UUID order. + + The finite search retains the original label on failure, with an explicit + diagnostic. At most six settling passes let constrained labels benefit from + later repairs; stable or repeated states stop the search early. + """ + from .KiCadSchematicLayout import graphic_bounds + from .KiCadSchematicReadability import text_item + + definitions = {d[1]: d for lib in children(doc, "lib_symbols") for d in children(lib, "symbol")} + from .KiCadSchematicPlanner import TITLE_BLOCK_BOUNDS + + obstacles = [TITLE_BLOCK_BOUNDS] + for symbol in children(doc, "symbol"): + at = children(symbol, "at")[0] + lib = children(symbol, "lib_id")[0][1] + if lib in definitions: + x1, y1, x2, y2 = graphic_bounds(SymbolView(definitions[lib], [], lib), int(at[3]), False) + obstacles.append((at[1] + x1, at[2] + y1, at[1] + x2, at[2] + y2)) + obstacles.extend( + item["bounds"] + for item in pin_name_items(definitions[lib], at[1], at[2], at[3]) + + pin_number_items(definitions[lib], at[1], at[2], at[3]) + ) + for prop in children(symbol, "property"): + positions, effects = children(prop, "at"), children(prop, "effects") + if positions and effects: + field_text = text_item("", prop[2], instance_property_at(positions[0], at), effects[0], "", "field") + if field_text: + obstacles.append(field_text.bounds) + for item in children(doc, "text"): + positions, effects = children(item, "at"), children(item, "effects") + if positions and effects: + text = text_item("", item[1], positions[0], effects[0], "", "text") + if text: + obstacles.append(text.bounds) + labels = children(doc, "label") + children(doc, "global_label") + labels.sort(key=lambda label: children(label, "uuid")[0][1]) + unique: dict[tuple[str, str, Point], SExpr] = {} + duplicates = [] + for label in labels: + label_at = children(label, "at")[0] + label_key = (str(label[0]), label[1], (label_at[1], label_at[2])) + if label_key in unique: + duplicates.append(label) + else: + unique[label_key] = label + for label in duplicates: + doc.remove(label) + labels = list(unique.values()) + + def box(label: SExpr) -> Bounds: + at = children(label, "at")[0] + effect = children(label, "effects")[0] + font = children(effect, "font") + size = children(font[0], "size")[0][1] if font else 1.27 + just = children(effect, "justify") + terms = {str(x) for x in just[0][1:]} if just else set() + return label_bounds( + label[1], + at[1], + at[2], + at[3], + size, + "left" if "left" in terms else "right" if "right" in terms else "center", + str(label[0]) == "global_label", + bottom="bottom" in terms, + ) + + boxes = {id(label): box(label) for label in labels} + anchors: dict[int, Point] = { + id(label): (children(label, "at")[0][1], children(label, "at")[0][2]) for label in labels + } + # The electrical net is recovered from the unchanged anchor, never guessed + # from the shortened display name. + nets = {} + for label in labels: + matches = {n for n, a, b in electrical_segments if segments_touch(anchors[id(label)], anchors[id(label)], a, b)} + nets[id(label)] = next(iter(matches)) if len(matches) == 1 else None + regions = [] + for rectangle in children(doc, "rectangle"): + start, end = children(rectangle, "start"), children(rectangle, "end") + if start and end: + x1, y1 = start[0][1:3] + x2, y2 = end[0][1:3] + regions.append((min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))) + owners = {} + for key, (x, y) in anchors.items(): + containing = [b for b in regions if b[0] <= x <= b[2] and b[1] <= y <= b[3]] + if containing: + owners[key] = min(containing, key=lambda b: (b[2] - b[0]) * (b[3] - b[1])) + + def inside_region(key: int, rect: Bounds) -> bool: + region = owners.get(key) + return region is None or ( + region[0] + 0.5 <= rect[0] + and region[1] + 0.5 <= rect[1] + and rect[2] <= region[2] - 0.5 + and rect[3] <= region[3] - 0.5 + ) + + added: dict[int, list[Wire]] = {} + records: dict[int, dict[str, Any]] = {} + + def placement_state() -> tuple[tuple[str, tuple[float, ...], tuple[str, ...], tuple[Wire, ...]], ...]: + return tuple( + ( + children(label, "uuid")[0][1], + tuple(children(label, "at")[0][1:]), + tuple(str(v) for j in children(children(label, "effects")[0], "justify") for v in j[1:]), + tuple(added.get(id(label), ())), + ) + for label in labels + ) + + previous_state = placement_state() + seen_states = {previous_state} + termination = "pass_limit" + passes_completed = 0 + for repair_pass in range(6): + for label in labels: + key = id(label) + anchor = anchors[key] + net = nets[key] + at = children(label, "at")[0] + if net is None: + continue + bounds = boxes[key] + others = [b for k, b in boxes.items() if k != key] + conflict_count = sum(overlap(bounds, b) for b in obstacles + others) + int(not inside_region(key, bounds)) + # Keep clear horizontal labels; repair vertical labels first where + # possible, so dense bottom-edge pins do not form vertical walls. + text_rect = label_bounds( + label[1], + at[1], + at[2], + at[3], + 1.27, + ( + "left" + if any(str(v) == "left" for j in children(children(label, "effects")[0], "justify") for v in j[1:]) + else "right" + ), + bottom=str(label[0]) == "label", + ) + current_segments = list(electrical_segments) + [ + segment for entries in added.values() for segment in entries + ] + wire_conflict = any(wire_through_text(a, b, text_rect) for _, a, b in current_segments) + outline_conflict = str(label[0]) == "global_label" and any( + n != net and segment_box(a, b, bounds) for n, a, b in current_segments + ) + if conflict_count == 0 and not wire_conflict and not outline_conflict and int(at[3]) % 180 == 0: + continue + candidates = [] + for route_anchor in wire_island_anchors(anchor, net, electrical_segments): + for angle, justify in ( + (0, "left"), + (0, "right"), + (int(at[3]), "left" if int(at[3]) in (0, 270) else "right"), + ): + # Outer lanes clear long pin-label banks and enclosing + # supply rails; all normal scene and electrical gates apply. + for offset in ( + 0, + 1.27, + -1.27, + 2.54, + -2.54, + 3.81, + -3.81, + 5.08, + -5.08, + 7.62, + -7.62, + 10.16, + -10.16, + 15.24, + -15.24, + 20.32, + -20.32, + 30.48, + -30.48, + 40.64, + -40.64, + 50.8, + -50.8, + ): + # One measured outer lane resolves dense connector + # label stacks without unbounded or time-based search. + outer_lane = math.ceil((text_width(label[1], 1.27) + 5.08) / 2.54) * 2.54 + for extension in (0, 2.54, 5.08, outer_lane): + sign = 1 if justify == "left" else -1 + target = (round(route_anchor[0] + sign * extension, 4), round(route_anchor[1] + offset, 4)) + rect = label_bounds( + label[1], + *target, + angle, + 1.27, + justify, + str(label[0]) == "global_label", + bottom=str(label[0]) == "label", + ) + if ( + not inside_region(key, rect) + or rect[0] < 12 + or rect[1] < 30 + or rect[2] > 408 + or rect[3] > 278 + ): + continue + if any(overlap(rect, b) for b in obstacles + others): + continue + existing = list(electrical_segments) + [ + seg for k, entries in added.items() if k != key for seg in entries + ] + text_rect = label_bounds( + label[1], *target, angle, 1.27, justify, bottom=str(label[0]) == "label" + ) + if any(wire_through_text(c, d, text_rect) for n, c, d in existing): + continue + if any(n != net and segment_box(c, d, rect) for n, c, d in existing): + continue + for bend in ((route_anchor[0], target[1]), (target[0], route_anchor[1])): + path = [(a, b) for a, b in ((route_anchor, bend), (bend, target)) if a != b] + if net is None and path: + continue + if any(segment_box(a, b, ob) for a, b in path for ob in obstacles): + continue + if any( + segment_box(a, b, ob) + and not (ob[0] <= route_anchor[0] <= ob[2] and ob[1] <= route_anchor[1] <= ob[3]) + for a, b in path + for ob in others + ): + continue + protected = set(anchors.values()) | {p for _, c, d in existing for p in (c, d)} + protected.update(p for a, b in path for p in (a, b)) + crossings = set() + unsafe = False + for a, b in path: + for n, c, d in existing: + if n == net: + continue + if wire_visual_conflict(a, b, c, d, protected): + unsafe = True + break + crossing = safe_wire_crossing(a, b, c, d, protected) + if crossing is not None: + crossings.add(crossing) + if unsafe: + break + if unsafe: + continue + cost = ( + len(crossings), + angle % 180 != 0, + abs(route_anchor[0] - anchor[0]) + abs(route_anchor[1] - anchor[1]), + abs(offset) + extension, + len(path), + angle, + justify, + offset, + extension, + bend, + ) + candidates.append((cost, target, angle, justify, path, rect, route_anchor)) + if any(candidate[0][0] == 0 for candidate in candidates): + break + if candidates: + _, target, angle, justify, path, rect, route_anchor = min(candidates, key=lambda c: c[0]) + at[1:] = [*target, angle] + effect = children(label, "effects")[0] + effect[:] = [v for v in effect if not (isinstance(v, list) and v and str(v[0]) == "justify")] + effect.append(node("justify", S(justify), *([S("bottom")] if str(label[0]) == "label" else []))) + added[key] = [(net, a, b) for a, b in path] + boxes[key] = rect + records[key] = dict( + identity=children(label, "uuid")[0][1], + name=label[1], + anchor=anchor, + wire_anchor=route_anchor, + at=target, + angle=angle, + candidates=len(candidates), + pass_index=repair_pass, + ) + passes_completed = repair_pass + 1 + current_state = placement_state() + if current_state == previous_state: + termination = "stable" + break + if current_state in seen_states: + termination = "cycle" + break + seen_states.add(current_state) + previous_state = current_state + conflicts = [] + for label in labels: + key = id(label) + bounds = boxes[key] + at = children(label, "at")[0] + terms = {str(v) for j in children(children(label, "effects")[0], "justify") for v in j[1:]} + text_rect = label_bounds( + label[1], + at[1], + at[2], + at[3], + 1.27, + "left" if "left" in terms else "right" if "right" in terms else "center", + bottom="bottom" in terms, + ) + all_wires = list(electrical_segments) + [seg for entries in added.values() for seg in entries] + if ( + any(overlap(bounds, b) for b in obstacles + [b for k, b in boxes.items() if k != key]) + or any(wire_through_text(a, b, text_rect) for _, a, b in all_wires) + or ( + str(label[0]) == "global_label" + and any(n != nets[key] and segment_box(a, b, bounds) for n, a, b in all_wires) + ) + ): + conflicts.append(dict(identity=children(label, "uuid")[0][1], name=label[1], bounds=bounds)) + # Label extensions can introduce T junctions or overlap a portion of an + # existing route. Rebuild the wire graph with the same writer that splits + # segments and emits explicit junctions; raw appended tails can appear + # connected while KiCad exports them as separate nets. + final_segments = list(electrical_segments) + [segment for entries in added.values() for segment in entries] + if pin_stubs is not None: + validate_wire_contacts(final_segments, pin_stubs) + if any(added.values()): + doc[:] = [ + item for item in doc if not (isinstance(item, list) and item and str(item[0]) in ("wire", "junction")) + ] + write_wires(doc, final_segments, identity, "final-label-scene") + unresolved_anchors = [ + dict(identity=children(label, "uuid")[0][1], name=label[1], anchor=anchors[id(label)]) + for label in labels + if nets[id(label)] is None + ] + return dict( + sheet=identity, + unresolved_anchors=unresolved_anchors, + moves=list(records.values()), + conflicts=conflicts, + passes=passes_completed, + termination=termination, + deduplicated=len(duplicates), + ) diff --git a/edg/electronics_model/KiCadSchematicTypes.py b/edg/electronics_model/KiCadSchematicTypes.py new file mode 100644 index 000000000..0577d30a0 --- /dev/null +++ b/edg/electronics_model/KiCadSchematicTypes.py @@ -0,0 +1,41 @@ +"""Internal geometry types shared by native schematic passes. + +S-expressions remain heterogeneous at the sexpdata parsing boundary. Physical +identity and routing geometry have concrete types independent of serialization. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Sequence, TYPE_CHECKING, TypedDict + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent + +SExpr = list[Any] +Point = tuple[float, float] +GridPoint = tuple[int, int] +Bounds = tuple[float, float, float, float] +PinKey = tuple[str, str] +PinNets = Mapping[PinKey, str] +Wire = tuple[str, Point, Point] +Placement = tuple["PhysicalComponent", float, float, int] +Placements = Sequence[Placement] +Views = Mapping[str, "SymbolView"] +Escape = tuple[float, float, float, float, float] +RouteResult = tuple[list[Wire], dict[PinKey, Escape], list[tuple[PinKey, str]]] + + +@dataclass +class SymbolView: + definition: SExpr + pins: list[tuple[str, float, float, float]] + lib_id: str + + +class PinTextItem(TypedDict): + identity: str + text: str + owner: str + kind: str + bounds: Bounds diff --git a/edg/electronics_model/KiCadSchematicWriter.py b/edg/electronics_model/KiCadSchematicWriter.py new file mode 100644 index 000000000..0aafd9a6d --- /dev/null +++ b/edg/electronics_model/KiCadSchematicWriter.py @@ -0,0 +1,113 @@ +"""KiCad schematic S-expression construction and electrical wire serialization.""" + +import json +import uuid +from collections import defaultdict +from typing import Any, Mapping, Sequence + +import sexpdata + +from .KiCadSchematicTypes import Point, SExpr, Wire + +S = sexpdata.Symbol + + +def node(name: str, *args: Any) -> SExpr: + return [S(name), *args] + + +def children(tree: SExpr, name: str) -> list[SExpr]: + return [v for v in tree if isinstance(v, list) and v and v[0] == S(name)] + + +def uid(*parts: str) -> str: + return str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(parts, ensure_ascii=False))) + + +def effects(size: float = 1.27, hide: bool = False) -> SExpr: + return node( + "effects", + node("font", node("size", size, size)), + *([S("hide")] if hide else []), + ) + + +def validate_wire_contacts(segments: Sequence[Wire], pin_stubs: Mapping[Wire, str]) -> None: + """Reject foreign-net endpoint contacts and overlaps in final sheet coordinates. + + An orthogonal interior crossing has no electrical junction unless another + endpoint lands there. Collinear overlaps always contain at least one end. + """ + rows: dict[float, list[Wire]] = defaultdict(list) + columns: dict[float, list[Wire]] = defaultdict(list) + for wire in segments: + _, a, b = wire + if a[1] == b[1]: + rows[a[1]].append(wire) + else: + columns[a[0]].append(wire) + + def contains(wire: Wire, p: Point) -> bool: + _, a, b = wire + return min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]) + + def affected_pins(net: str, p: Point) -> str: + pins = [(wire, name) for wire, name in pin_stubs.items() if wire[0] == net] + touching = [name for wire, name in pins if contains(wire, p)] + return ", ".join(sorted(touching or [name for _, name in pins])) + + for net, a, b in segments: + for point in (a, b): + for line in (rows.get(point[1], []), columns.get(point[0], [])): + for other in line: + if net != other[0] and contains(other, point): + raise ValueError( + f"schematic short at {point}: {net} ({affected_pins(net, point)}) " + f"contacts {other[0]} ({affected_pins(other[0], point)})" + ) + + +def write_wires(doc: SExpr, all_segments: Sequence[Wire], sheet_id: str, region_id: str) -> None: + """Split orthogonal wires at endpoints and emit junctions with stable identities.""" + for net in sorted({n for n, _, _ in all_segments}): + segments = [(a, b) for n, a, b in all_segments if n == net and a != b] + candidates = {p for pair in segments for p in pair} + edges: set[tuple[Point, Point]] = set() + for a, b in segments: + cuts = [ + p + for p in candidates + if (a[0] == b[0] == p[0] and min(a[1], b[1]) <= p[1] <= max(a[1], b[1])) + or (a[1] == b[1] == p[1] and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])) + ] + cuts.sort() + edges.update((u, v) for u, v in zip(cuts, cuts[1:]) if u != v) + degrees: dict[Point, int] = {} + for a, b in sorted(edges): + for p in (a, b): + degrees[p] = degrees.get(p, 0) + 1 + doc.append( + node( + "wire", + node("pts", node("xy", *a), node("xy", *b)), + node("stroke", node("width", 0), node("type", S("default"))), + node( + "uuid", + uid(sheet_id, region_id, net, str(a), str(b), "wire"), + ), + ) + ) + for p, degree in sorted(degrees.items()): + if degree >= 3: + doc.append( + node( + "junction", + node("at", *p), + node("diameter", 0), + node("color", 0, 0, 0, 0), + node( + "uuid", + uid(sheet_id, region_id, net, str(p), "junction"), + ), + ) + ) diff --git a/edg/electronics_model/KiCadSymbolRegistry.py b/edg/electronics_model/KiCadSymbolRegistry.py new file mode 100644 index 000000000..c001a40cb --- /dev/null +++ b/edg/electronics_model/KiCadSymbolRegistry.py @@ -0,0 +1,333 @@ +"""Conservative library-symbol defaults for compiled physical component models. + +This registry never selects symbols by reference designator. Each entry identifies +an exact leaf PB model and, where a model selects several parts, an actual part +or verified terminal roles. Missing libraries and unknown variants return None. +The exporter must retain the actual component Value and Footprint properties. + +ESP32-C6-WROOM-1 is provided by Espressif's official KiCad library: +https://github.com/espressif/kicad-libraries/blob/main/symbols/Espressif.kicad_sym +Other symbols below are from the official KiCad libraries. No library files are +bundled here. Unmodeled pins are omitted deliberately; never emit invented NCs. +""" + +from __future__ import annotations + +from typing import Any, Dict, Mapping, Optional, Sequence, Protocol, TYPE_CHECKING +from .KiCadSchematicTypes import SExpr + +if TYPE_CHECKING: + from .KiCadSchematicExporter import PhysicalComponent + + +class LibraryResolver(Protocol): + def load(self, lib_id: str) -> SExpr: ... + + +def _leaf_class(class_names: Sequence[str]) -> str: + if not class_names: + return "" + # A path's last entry describes the physical block, not a functional ancestor. + return class_names[-1].removeprefix("PolymorphicBlocks.") + + +def _children(tree: SExpr, name: str) -> list[SExpr]: + return [item for item in tree if isinstance(item, list) and item and str(item[0]) == name] + + +def _checked_mapping( + component: PhysicalComponent, resolver: LibraryResolver, lib_id: str, pinning: Optional[Mapping[str, str]] = None +) -> Optional[Dict[str, Any]]: + """Require an installed definition and a complete one-to-one physical pin map.""" + try: + definition = resolver.load(lib_id) + except (LookupError, FileNotFoundError): + return None + available = { + str(_children(pin, "number")[0][1]) + for body in _children(definition, "symbol") + for pin in _children(body, "pin") + } + if pinning is None: + pinning = {number: number for number in component.pins} + mapping = dict(pinning) + if ( + not set(mapping).issubset(available) + or set(mapping.values()) != set(component.pins) + or len(mapping.values()) != len(set(mapping.values())) + ): + return None + return {"lib_id": lib_id, "pinning": mapping, "_omit_unmodeled": True} + + +def _role_pins(component: PhysicalComponent) -> Dict[str, str]: + """Use declared PB terminal semantics, never a guess from copper or pad order.""" + aliases = {"a": "anode", "k": "cathode"} + roles: Dict[str, str] = {} + for number, path in component.pins.items(): + terms = path.split(".") + role = terms[-2] if terms[-1] == "net" and len(terms) > 1 else terms[-1] + role = aliases.get(role, role) + if role in roles: + return {} # ambiguous parallel pads require a part-specific entry + roles[role] = number + return roles + + +def infer_symbol( + component: PhysicalComponent, + class_names: Sequence[str], + part: str, + resolver: LibraryResolver, + evidence: Optional[Dict[str, Any]] = None, +) -> Optional[Dict[str, Any]]: + """Resolve verified defaults, optionally retaining failed library lookup evidence.""" + attempts = [] + + class RecordingResolver: + def load(self, lib_id: str) -> SExpr: + attempt = {"lib_id": lib_id} + attempts.append(attempt) + try: + result = resolver.load(lib_id) + except (LookupError, FileNotFoundError) as error: + attempt.update( + reason=str(error), + category=("missing_library" if isinstance(error, FileNotFoundError) else "missing_symbol"), + ) + raise + attempt["category"] = "loaded" + return result + + result = _infer_symbol(component, class_names, part, RecordingResolver()) + if evidence is not None: + evidence.update(attempts=attempts) + if result is None: + failure = next((a for a in reversed(attempts) if a["category"] != "loaded"), None) + evidence.update( + category=( + failure["category"] if failure else ("invalid_registry_mapping" if attempts else "missing_mapping") + ), + reason=( + failure["reason"] + if failure + else ( + "verified symbol does not match modeled pin inventory" + if attempts + else "no schematic symbol mapping" + ) + ), + ) + return result + + +def _infer_symbol( + component: PhysicalComponent, class_names: Sequence[str], part: str, resolver: LibraryResolver +) -> Optional[Dict[str, Any]]: + """Return explicit library-pin -> physical-pad mapping, or None if unverified. + + ``class_names`` is the compiled hierarchy's library class names in path order, + with the physical block's class last. Both ``edg`` import namespaces work. + ``part`` is NetBlock.part (part identifier followed by optional manufacturer). + ``component`` supplies physical ``pins`` and ``footprint``; resolver.load() + returns a fully resolved KiCad symbol definition. + """ + cls = _leaf_class(class_names) + identifier = part.split(" (", 1)[0].strip() + pins = set(component.pins) + + if ( + cls == "edg.parts.analog.Comparator_Lmv331.Lmv331_Device" + and identifier == "LMV331IDCKR" + and component.footprint == "Package_TO_SOT_SMD:SOT-353_SC-70-5" + and _role_pins(component) == {"inp": "1", "gnd": "2", "inn": "3", "out": "4", "vcc": "5"} + ): + # TI LMV331 datasheet, Pin Configuration and Functions (DBV/DCK): + # https://www.ti.com/lit/ds/symlink/lmv331.pdf + # 1=IN+, 2=GND, 3=IN-, 4=OUT, 5=VCC. The official single-unit + # Comparator:LMV331 symbol uses these same numbers in KiCad 9 and 10. + return _checked_mapping(component, resolver, "Comparator:LMV331") + + if ( + cls == "edg.vendor_parts.generic.CustomFet.CustomFet" + and identifier == "IRF540N" + and component.footprint + in { + "Package_TO_SOT_THT:TO-220-3_Horizontal_TabUp", + "Package_TO_SOT_THT:TO-220-3_Horizontal_TabDown", + "Package_TO_SOT_THT:TO-220-3_Vertical", + } + and _role_pins(component) == {"gate": "1", "drain": "2", "source": "3"} + ): + # Infineon IRF540N datasheet TO-220 front view: 1=G, 2=D, 3=S. + # https://www.infineon.com/assets/row/public/documents/24/49/ + # infineon-irf540n-datasheet-en.pdf + # Official KiCad single-unit IRF540N has the same physical inventory. + return _checked_mapping(component, resolver, "Transistor_FET:IRF540N") + + if ( + cls == "edg.vendor_parts.generic.GenericCapacitor.GenericMlcc" + and component.footprint + in { + "Capacitor_SMD:C_0402_1005Metric", + "Capacitor_SMD:C_0603_1608Metric", + "Capacitor_SMD:C_0805_2012Metric", + "Capacitor_SMD:C_1206_3216Metric", + "Capacitor_SMD:C_1210_3225Metric", + "Capacitor_SMD:C_1812_4532Metric", + } + and pins == {"1", "2"} + and _role_pins(component) == {"pos": "1", "neg": "2"} + ): + # GenericMlcc.PACKAGE_SPECS enumerates these nonpolar ceramic packages; + # generate() explicitly declares physical 1=pos,2=neg. This also covers + # Datalogger's direct generic capacitors, not only parallel dummy leaves. + return _checked_mapping(component, resolver, "Device:C") + + if ( + cls + in { + "edg.vendor_parts.jlc.JlcCapacitor.JlcDummyCapacitor", + "edg.abstract_parts.Capacitor.DummyCapacitorFootprint", + } + and component.footprint.startswith("Capacitor_SMD:C_") + and pins == {"1", "2"} + and _role_pins(component) == {"pos": "1", "neg": "2"} + ): + # DummyCapacitorFootprint.__init__ explicitly declares 1=pos, 2=neg. + # C_ packages are the verified nonpolar standard SMD family; CP_ is not. + return _checked_mapping(component, resolver, "Device:C") + + if ( + cls == "lib.power.converter.Tps631000.Tps631000_Inductor" + and identifier == "DFE252012F-1R0M=P2" + and component.footprint == "fp:DFE252012P-1R0M=P2" + and dict(component.pins) == {"1": "a", "2": "b"} + ): + # The local model declares the two nonpolar coil terminals as 1=a,2=b. + return _checked_mapping(component, resolver, "Device:L") + + if ( + cls == "lib.esp32.Esp32c6.Esp32c6_Wroom_1_Device" + and identifier == "ESP32-C6-WROOM-1-N4" + and component.footprint == "Espressif:ESP32-C6-WROOM-1" + ): + # Vendor symbol and PB model use the module's exact physical pad numbers. + return _checked_mapping(component, resolver, "Espressif:ESP32-C6-WROOM-1") + + if cls == "edg.parts.connector.UsbPorts.UsbCReceptacle_Device": + if component.footprint == "Connector_USB:USB_C_Receptacle_XKB_U262-16XN-4BVC11": + # KiCad names the physical shield SH; this footprint/model calls it S1. + # KiCad 9 calls the shield S1; KiCad 10 calls it SH. + identity = _checked_mapping(component, resolver, "Connector:USB_C_Receptacle_USB2.0_16P") + if identity is not None: + return identity + mapping = {("SH" if number == "S1" else number): number for number in pins} + return _checked_mapping(component, resolver, "Connector:USB_C_Receptacle_USB2.0_16P", mapping) + + if cls in { + "edg.vendor_parts.jlc.JlcFet.JlcFet", + "edg.vendor_parts.jlc.JlcFet.JlcSwitchFet", + "lib.power.Ao3400a.Ao3400a", + }: + roles = _role_pins(component) + if set(roles) == {"gate", "source", "drain"}: + mapping = {"1": roles["gate"], "2": roles["source"], "3": roles["drain"]} + exact = {"AO3400A": "AO3400A", "AO3401A": "AO3401A", "2N7002": "2N7002"} + if identifier in exact: + return _checked_mapping(component, resolver, "Transistor_FET:" + exact[identifier], mapping) + if identifier == "SI2301CDS-T1-GE3": + # Verified PB model records gate/source/drain; this PMOS pin order + # is explicitly 1=G, 2=S, 3=D in the generic standard symbol. + return _checked_mapping(component, resolver, "Transistor_FET:Q_PMOS_GSD", mapping) + + if cls == "edg.vendor_parts.jlc.JlcBjt.JlcBjt" and identifier in { + "MMBT3904", + "MMBT3906", + }: + # Exact KiCad definitions use 1=B, 2=E, 3=C. PB physical pad roles, + # rather than SOT-23 ordering, determine the remapping. + roles = _role_pins(component) + if set(roles) == {"base", "emitter", "collector"}: + return _checked_mapping( + component, + resolver, + "Transistor_BJT:" + identifier, + {"1": roles["base"], "2": roles["emitter"], "3": roles["collector"]}, + ) + + diode_classes = { + "edg.vendor_parts.jlc.JlcDiode.JlcDiode": "Device:D", + "edg.vendor_parts.jlc.JlcDiode.JlcZenerDiode": "Device:D_Zener", + } + led_classes = { + "edg.vendor_parts.jlc.JlcLed.JlcLed", + "lib.human_interface.Kt0603y.Kt0603y", + "lib.power.converter.XinglightXl4008uwc.XinglightXl4008uwc", + } + if cls in diode_classes or cls in led_classes: + roles = _role_pins(component) + if set(roles) == {"anode", "cathode"}: + lib_id = "Device:LED" if cls in led_classes else diode_classes[cls] + if cls in diode_classes and identifier in ("1N5819WS", "BAT60B"): + lib_id = "Device:D_Schottky" + return _checked_mapping(component, resolver, lib_id, {"1": roles["cathode"], "2": roles["anode"]}) + + connector_classes = { + "lib.connector.Jst.JlcJstPhKVerticalTwoPin": ("Connector_Generic:Conn_01x02", {"1", "2"}), + "lib.components_lib.JlcPwmPinHeader254Vertical": ("Connector_Generic:Conn_01x03", {"1", "2", "3"}), + "edg.parts.connector.TagConnect.TagConnectNonLegged": ( + "Connector_Generic:Conn_02x03_Odd_Even", + {str(i) for i in range(1, 7)}, + ), + "edg.parts.connector.Fpc.Afc01": ("Connector_Generic:Conn_01x30", {str(i) for i in range(1, 31)}), + } + if cls in connector_classes: + lib_id, expected = connector_classes[cls] + if pins == expected: + return _checked_mapping(component, resolver, lib_id) + if ( + cls == "edg.parts.connector.Fpc.Afc01" + and identifier == "AFC01-S30FC*-00" + and pins + and pins.issubset(expected) + ): + # The OLED connector intentionally does not model unused pad 7. + return _checked_mapping(component, resolver, lib_id) + + if ( + cls == "edg.vendor_parts.jlc.JlcSwitches.JlcSwitch" + and identifier == "5.1mm switch" + and component.footprint == "Button_Switch_SMD:SW_SPST_SKQG_WithoutStem" + and pins == {"1", "2"} + ): + return _checked_mapping(component, resolver, "Switch:SW_Push") + + if ( + cls == "lib.human_interface.Sk6812sideas.Sk6812SideAS_Device" + and identifier == "SK6812SIDE-A-S" + and component.footprint == "fp:LED_SK6812SIDE_A_S" + ): + roles = _role_pins(component) + if set(roles) == {"din", "vdd", "dout", "gnd"}: + # Explicit family-graphic alias, NOT an identical physical package. + # Both are single-wire addressable RGB LEDs (PB Neopixel model). + # KiCad LED:SK6812 has 1=VSS, 2=DIN, 3=VDD, 4=DOUT. + # SIDE-A-S datasheet/model instead has 1=DIN, 2=VDD, 3=DOUT, 4=GND: + # https://atta.szlcsc.com/upload/public/pdf/source/20230330/ + # F1A167741926C16B6569128F16D7FD80.pdf + # The exporter retains the SIDE-A-S Value and custom Footprint. + return _checked_mapping( + component, + resolver, + "LED:SK6812", + {"1": roles["gnd"], "2": roles["din"], "3": roles["vdd"], "4": roles["dout"]}, + ) + + if cls == "edg.parts.debug.TestPoint_Keystone.CompactKeystone5015" and pins == {"1"}: + return _checked_mapping(component, resolver, "Connector:TestPoint") + + if cls in {"edg.BoardTop.JlcToolingHole", "edg.parts.Mechanicals.MountingHole_NoPad_M2_5"} and not pins: + return _checked_mapping(component, resolver, "Mechanical:MountingHole") + + return None diff --git a/edg/electronics_model/SchematicVerification.py b/edg/electronics_model/SchematicVerification.py new file mode 100644 index 000000000..91b4015bc --- /dev/null +++ b/edg/electronics_model/SchematicVerification.py @@ -0,0 +1,53 @@ +"""Independent KiCad XML-netlist acceptance checks for generated schematic views.""" + +from pathlib import Path +import xml.etree.ElementTree as ET + +from .NetlistGenerator import Netlist + + +def verify_schematic_netlist(expected: Netlist, exported_xml: Path) -> None: + """Compare KiCad's `sch export netlist --format kicadxml` output to PB. + + Ignore net names and singleton-net omission, but verify the library pin inventory, + component/footprint identity, and exact partition of connected physical pins. + Raises ValueError on mismatch. Run once for each independent board scope. + """ + root = ET.parse(exported_xml).getroot() + components = {c.attrib["ref"]: c for c in root.findall("./components/comp")} + blocks = {b.refdes: b for b in expected.blocks} + if set(components) != set(blocks): + raise ValueError("schematic component identities differ from PB") + library_parts = {(p.attrib["lib"], p.attrib["part"]): p for p in root.findall("./libparts/libpart")} + path_refs = {str(b.full_path): ref for ref, b in blocks.items()} + expected_pins: dict[str, set[str]] = {ref: set() for ref in blocks} + expected_nets = set() + for net in expected.nets: + pins = frozenset((path_refs[str(p.block_path)], p.pin_name) for p in net.pins) + for ref, pin in pins: + expected_pins[ref].add(pin) + if len(pins) > 1: + expected_nets.add(pins) + # Include modeled pins that the netlister might omit from singleton nets by reading + # the generated symbol inventory separately in extraction tests. + for ref, comp in components.items(): + if (comp.findtext("footprint") or "") != blocks[ref].footprint: + raise ValueError("footprint mismatch: " + ref) + source = comp.find("libsource") + if source is None: + raise ValueError("missing library pin inventory: " + ref) + part = library_parts[(source.attrib["lib"], source.attrib["part"])] + actual = {pin.attrib["num"] for pin in part.findall("./pins/pin")} + if actual != expected_pins[ref]: + raise ValueError("physical pin inventory mismatch: " + ref) + actual_nets = set() + seen: set[tuple[str, str]] = set() + for xml_net in root.findall("./nets/net"): + pins = frozenset((p.attrib["ref"], p.attrib["pin"]) for p in xml_net.findall("node")) + if seen.intersection(pins): + raise ValueError("physical pin occurs on multiple nets") + seen.update(pins) + if len(pins) > 1: + actual_nets.add(pins) + if actual_nets != expected_nets: + raise ValueError("schematic connectivity differs from PB (merged, split, missing, or extra net)") diff --git a/edg/electronics_model/__init__.py b/edg/electronics_model/__init__.py index 4f3adc1eb..3c276136c 100644 --- a/edg/electronics_model/__init__.py +++ b/edg/electronics_model/__init__.py @@ -69,3 +69,16 @@ from .PinAssignmentUtil import PinAssignmentUtil, AnyPinAssign, PeripheralPinAssign, NotConnectedPin, AnyPin from .SvgPcbTemplateBlock import SvgPcbTemplateBlock + +from .KiCadSchematicExporter import KiCadSchematicExporter, SchematicExportOptions, SchematicExport, SchematicPlacement +from .KiCadSchematicPlanner import ( + SchematicSheetPlanner, + SchematicSheetPlan, + SchematicSheet, + SchematicRegion, + SchematicRegionPlacement, +) + +from .KiCadSchematicOverview import SchematicOverview, SchematicOverviewBlock, SchematicOverviewLink + +from .KiCadSchematicPresentation import SchematicPresentation diff --git a/edg/electronics_model/resources/build_kicad_footprint_table.py b/edg/electronics_model/resources/build_kicad_footprint_table.py index 66c6ae17d..61b16e484 100644 --- a/edg/electronics_model/resources/build_kicad_footprint_table.py +++ b/edg/electronics_model/resources/build_kicad_footprint_table.py @@ -5,7 +5,7 @@ import os from typing import Dict, List, Tuple, Any, Optional -import sexpdata # type: ignore +import sexpdata from pydantic import RootModel, BaseModel KICAD_FP_DIRECTORIES = [ diff --git a/edg/electronics_model/test_composite_schematic_symbols.py b/edg/electronics_model/test_composite_schematic_symbols.py new file mode 100644 index 000000000..73eb270c2 --- /dev/null +++ b/edg/electronics_model/test_composite_schematic_symbols.py @@ -0,0 +1,43 @@ +import unittest +from types import SimpleNamespace + +from .KiCadCompositeSymbols import resistor_array_symbol +from .KiCadSchematicExporter import PhysicalComponent +from typing import Any + + +def component_fixture(*, pins: dict[str, str], mapping: dict[str, Any] | None = None) -> PhysicalComponent: + return PhysicalComponent("fixture", "RN1", "FP", "fixture", pins, mapping, "fixture") + + +class CompositeSchematicSymbolTest(unittest.TestCase): + classes = ["edg.vendor_parts.jlc.JlcResistorArray.JlcResistorArray"] + + def test_pairing_follows_roles_not_pad_order(self) -> None: + c = component_fixture(pins={"1": "a.0", "8": "b.0", "2": "a.1", "7": "b.1"}) + result = resistor_array_symbol(c, self.classes) + assert result is not None + definition, pins, lib_id = result + locations = {number: (x, y) for number, x, y, angle in pins} + self.assertEqual(locations["1"][1], locations["8"][1]) + self.assertEqual(locations["2"][1], locations["7"][1]) + self.assertNotEqual(locations["1"][1], locations["2"][1]) + self.assertEqual(set(locations), set(c.pins)) + self.assertEqual((definition, pins, lib_id), resistor_array_symbol(c, self.classes)) + + def test_incomplete_unknown_and_ambiguous_roles_are_not_guessed(self) -> None: + for inventory in ( + {"1": "a.0"}, + {"1": "ports.1", "2": "ports.2"}, + {"1": "a.0", "2": "a.0", "3": "b.0"}, + ): + self.assertIsNone(resistor_array_symbol(component_fixture(pins=inventory), self.classes)) + self.assertIsNone(resistor_array_symbol(component_fixture(pins={"1": "a.0", "2": "b.0"}), ["Other"])) + + def test_custom_pin_names_have_distinct_embedded_identities(self) -> None: + a = component_fixture(pins={"1": "a.0", "8": "b.0"}, mapping={"pin_names": {"1": "CHANNEL_A"}}) + b = component_fixture(pins=dict(a.pins), mapping={"pin_names": {"1": "CHANNEL_B"}}) + a_symbol, b_symbol = resistor_array_symbol(a, self.classes), resistor_array_symbol(b, self.classes) + assert a_symbol is not None and b_symbol is not None + self.assertNotEqual(a_symbol[2], b_symbol[2]) + self.assertEqual(a_symbol[1], b_symbol[1]) diff --git a/edg/electronics_model/test_imported_schematic_metadata.py b/edg/electronics_model/test_imported_schematic_metadata.py new file mode 100644 index 000000000..11f3ec545 --- /dev/null +++ b/edg/electronics_model/test_imported_schematic_metadata.py @@ -0,0 +1,74 @@ +"""Imported symbol meaning survives compilation without changing physical connectivity.""" + +from typing_extensions import override +import json +from typing import cast +import unittest + +from ..core import Block, ScalaCompiler +from .CircuitBlock import FootprintBlock +from .KiCadSchematicBlock import KiCadBlackbox +from .PassivePort import Passive + + +class ImportedMetadataBoard(Block): + @override + def contents(self) -> None: + super().contents() + self.imported = self.Block( + KiCadBlackbox( + ["1", "2", "3"], + "U", + "Test:Package", + "Test:Amplifier", + "Part", + "", + kicad_pin_names=["1=IN+", "2=OUT", "3=GND"], + ) + ) + self.graphic = self.Block(KiCadBlackbox([], "SYM", "Test:Graphic", "Graphic:Logo", "Logo", "")) + + +class ImportedSchematicMetadataTest(unittest.TestCase): + def test_blackbox_metadata_and_physical_inventory(self) -> None: + compiled = ScalaCompiler.compile(ImportedMetadataBoard) + raw = compiled.get_value(("imported", "sch_symbol")) + assert isinstance(raw, str) + metadata = json.loads(raw) + self.assertEqual( + metadata, + { + "lib_id": "Test:Amplifier", + "pinning": {"1": "1", "2": "2", "3": "3"}, + "pin_names": {"1": "IN+", "2": "OUT", "3": "GND"}, + }, + ) + self.assertEqual( + compiled.get_value(("imported", "fp_pinning")), + ["1=ports.1", "2=ports.2", "3=ports.3"], + ) + self.assertFalse(compiled.get_value(("graphic", "sch_symbol"))) + + def test_real_import_keeps_hx711_pin_meaning(self) -> None: + from examples.test_blinky import TestBlinkyWithModeledSchematicImport + + compiled = ScalaCompiler.compile(TestBlinkyWithModeledSchematicImport) + raw = compiled.get_value(("sense", "U1", "sch_symbol")) + assert isinstance(raw, str) + metadata = json.loads(raw) + self.assertEqual(metadata["lib_id"], "Analog_ADC:HX711") + self.assertEqual(set(metadata["pinning"]), {str(i) for i in range(1, 17)}) + self.assertIn("DOUT", metadata["pin_names"].values()) + self.assertIn("INA+", metadata["pin_names"].values()) + self.assertIn("INA-", metadata["pin_names"].values()) + + def test_invalid_physical_pin_names_rejected(self) -> None: + block = FootprintBlock() + with self.assertRaisesRegex(ValueError, "mapped physical pads"): + block.schematic_symbol("Device:R", {"1": "3", "2": "4"}, pin_names={"1": "a"}) + with self.assertRaisesRegex(ValueError, "string pin numbers"): + block.schematic_symbol("Device:R", cast(dict[str, str], {1: "3"})) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_kicad_symbol_registry.py b/edg/electronics_model/test_kicad_symbol_registry.py new file mode 100644 index 000000000..7daa2d060 --- /dev/null +++ b/edg/electronics_model/test_kicad_symbol_registry.py @@ -0,0 +1,245 @@ +"""Default symbol selection must preserve physical identity and terminal roles.""" + +from typing import Any, Mapping, Sequence + +import unittest +from types import SimpleNamespace + +import sexpdata + +from .KiCadSymbolRegistry import infer_symbol +from .KiCadSchematicExporter import PhysicalComponent + + +def component_fixture(*, footprint: str, pins: dict[str, str]) -> PhysicalComponent: + return PhysicalComponent("fixture", "U1", footprint, "fixture", pins, None, "fixture") + + +class FixtureResolver: + """Pin inventories transcribed from official KiCad/Espressif library symbols.""" + + def __init__(self, inventories: Mapping[str, Sequence[str]]) -> None: + self.inventories = inventories + + def load(self, lib_id: str) -> list[Any]: + pins = self.inventories[lib_id] + sym = sexpdata.Symbol + return [ + sym("symbol"), + lib_id, + [ + sym("symbol"), + "Body_1_1", + *[[sym("pin"), sym("passive"), sym("line"), [sym("number"), number]] for number in pins], + ], + ] + + +class KiCadSymbolRegistryTest(unittest.TestCase): + def test_datalogger_generic_mlcc_requires_exact_model_package_and_roles(self) -> None: + classes = ["edg.vendor_parts.generic.GenericCapacitor.GenericMlcc"] + component = component_fixture(footprint="Capacitor_SMD:C_0603_1608Metric", pins={"1": "pos", "2": "neg"}) + resolver = FixtureResolver({"Device:C": ["1", "2"]}) + result = infer_symbol(component, classes, "", resolver) + assert result is not None + self.assertEqual(result["lib_id"], "Device:C") + assert result is not None + self.assertEqual(result["pinning"], {"1": "1", "2": "2"}) + self.assertIsNone(infer_symbol(component, ["custom.Capacitor"], "", resolver)) + component.pins = {"1": "neg", "2": "pos"} + self.assertIsNone(infer_symbol(component, classes, "", resolver)) + component.pins = {"1": "pos", "2": "neg", "3": "shield"} + self.assertIsNone(infer_symbol(component, classes, "", resolver)) + component.pins = {"1": "pos", "2": "neg"} + for footprint in ("Capacitor_SMD:CP_Elec_5x5.8", "Capacitor_SMD:C_Custom"): + component.footprint = footprint + self.assertIsNone(infer_symbol(component, classes, "", resolver)) + + def test_symbol_lookup_evidence_distinguishes_mapping_symbol_and_library(self) -> None: + classes = ["edg.vendor_parts.generic.GenericCapacitor.GenericMlcc"] + component = component_fixture(footprint="Capacitor_SMD:C_0603_1608Metric", pins={"1": "pos", "2": "neg"}) + evidence: dict[str, Any] = {} + self.assertIsNone(infer_symbol(component, ["custom.Capacitor"], "", FixtureResolver({}), evidence)) + self.assertEqual(evidence["category"], "missing_mapping") + evidence = {} + self.assertIsNone(infer_symbol(component, classes, "", FixtureResolver({}), evidence)) + self.assertEqual(evidence["category"], "missing_symbol") + self.assertEqual(evidence["attempts"][0]["lib_id"], "Device:C") + + class MissingLibrary: + def load(self, lib_id: str) -> list[Any]: + raise FileNotFoundError(lib_id) + + evidence = {} + self.assertIsNone(infer_symbol(component, classes, "", MissingLibrary(), evidence)) + self.assertEqual(evidence["category"], "missing_library") + evidence = {} + self.assertIsNone(infer_symbol(component, classes, "", FixtureResolver({"Device:C": ["1"]}), evidence)) + self.assertEqual(evidence["category"], "invalid_registry_mapping") + + def test_custom_irf540n_requires_exact_part_package_and_terminal_order(self) -> None: + component = component_fixture( + footprint="Package_TO_SOT_THT:TO-220-3_Horizontal_TabUp", + pins={"1": "gate", "2": "drain", "3": "source"}, + ) + classes = ["edg.vendor_parts.generic.CustomFet.CustomFet"] + resolver = FixtureResolver({"Transistor_FET:IRF540N": ["1", "2", "3"]}) + result = infer_symbol(component, classes, "IRF540N", resolver) + assert result is not None + self.assertEqual(result["lib_id"], "Transistor_FET:IRF540N") + assert result is not None + self.assertEqual(result["pinning"], {"1": "1", "2": "2", "3": "3"}) + self.assertIsNone(infer_symbol(component, classes, "IRF9540", resolver)) + component.pins["2"], component.pins["3"] = component.pins["3"], component.pins["2"] + self.assertIsNone(infer_symbol(component, classes, "IRF540N", resolver)) + + def test_lmv331_exact_package_and_declared_polarity(self) -> None: + component = component_fixture( + footprint="Package_TO_SOT_SMD:SOT-353_SC-70-5", + pins={"1": "inp", "2": "gnd", "3": "inn", "4": "out", "5": "vcc"}, + ) + classes = ["edg.parts.analog.Comparator_Lmv331.Lmv331_Device"] + resolver = FixtureResolver({"Comparator:LMV331": ["1", "2", "3", "4", "5"]}) + result = infer_symbol(component, classes, "LMV331IDCKR (Texas Instruments)", resolver) + assert result is not None + self.assertEqual(result["lib_id"], "Comparator:LMV331") + assert result is not None + self.assertEqual(result["pinning"], {str(n): str(n) for n in range(1, 6)}) + component.pins["1"], component.pins["3"] = component.pins["3"], component.pins["1"] + self.assertIsNone(infer_symbol(component, classes, "LMV331IDCKR", resolver)) + + def test_parallel_dummy_capacitor_uses_nonpolar_symbol_only(self) -> None: + component = component_fixture(footprint="Capacitor_SMD:C_1206_3216Metric", pins={"1": "pos", "2": "neg"}) + cls = ["PolymorphicBlocks.edg.vendor_parts.jlc.JlcCapacitor.JlcDummyCapacitor"] + resolver = FixtureResolver({"Device:C": ["1", "2"]}) + result = infer_symbol(component, cls, "CL31A226KPHNNNE", resolver) + assert result is not None + self.assertEqual(result["pinning"], {"1": "1", "2": "2"}) + component.footprint = "Capacitor_SMD:CP_Elec_5x5.8" + self.assertIsNone(infer_symbol(component, cls, "CL31A226KPHNNNE", resolver)) + + def test_local_buck_boost_inductor_requires_verified_model_and_terminals(self) -> None: + component = component_fixture(footprint="fp:DFE252012P-1R0M=P2", pins={"1": "a", "2": "b"}) + cls = ["lib.power.converter.Tps631000.Tps631000_Inductor"] + resolver = FixtureResolver({"Device:L": ["1", "2"]}) + result = infer_symbol(component, cls, "DFE252012F-1R0M=P2 (Murata)", resolver) + assert result is not None + self.assertEqual(result["pinning"], {"1": "1", "2": "2"}) + component.pins["3"] = "tap" + self.assertIsNone(infer_symbol(component, cls, "DFE252012F-1R0M=P2 (Murata)", resolver)) + + def test_exact_module_identity_and_omitted_unmodeled_pins(self) -> None: + component = component_fixture( + footprint="Espressif:ESP32-C6-WROOM-1", + pins={"1": "gnd.net", "2": "pwr.net", "29": "gnd.net"}, + ) + classes = ["lib.esp32.Esp32c6.Esp32c6_Wroom_1_Device"] + resolver = FixtureResolver({"Espressif:ESP32-C6-WROOM-1": [str(i) for i in range(1, 30)]}) + result = infer_symbol(component, classes, "ESP32-C6-WROOM-1-N4 (Espressif Systems)", resolver) + assert result is not None + self.assertEqual(result["pinning"], {"1": "1", "2": "2", "29": "29"}) + self.assertTrue(result["_omit_unmodeled"]) + self.assertIsNone(infer_symbol(component, classes, "ESP32-C6-MINI-1", resolver)) + component.pins["99"] = "unknown" + self.assertIsNone(infer_symbol(component, classes, "ESP32-C6-WROOM-1-N4", resolver)) + + def test_functional_ancestor_cannot_select_child_symbol(self) -> None: + component = component_fixture(footprint="Espressif:ESP32-C6-WROOM-1", pins={"1": "a", "2": "b"}) + classes = [ + "lib.esp32.Esp32c6.Esp32c6_Wroom_1_Device", + "PolymorphicBlocks.edg.vendor_parts.jlc.JlcCapacitor.JlcCapacitor", + ] + self.assertIsNone(infer_symbol(component, classes, "ESP32-C6-WROOM-1-N4", FixtureResolver({}))) + + def test_diode_mapping_uses_terminal_roles(self) -> None: + component = component_fixture(footprint="Test:Diode", pins={"4": "anode", "7": "cathode"}) + result = infer_symbol( + component, + ["edg.vendor_parts.jlc.JlcDiode.JlcDiode"], + "1N5819WS", + FixtureResolver({"Device:D_Schottky": ["1", "2"]}), + ) + assert result is not None + self.assertEqual(result["pinning"], {"1": "7", "2": "4"}) + + def test_exact_bjt_uses_verified_role_mapping(self) -> None: + component = component_fixture( + footprint="Test:Package", + pins={"7": "base", "8": "collector", "9": "emitter"}, + ) + classes = ["edg.vendor_parts.jlc.JlcBjt.JlcBjt"] + result = infer_symbol( + component, + classes, + "MMBT3904", + FixtureResolver({"Transistor_BJT:MMBT3904": ["1", "2", "3"]}), + ) + assert result is not None + self.assertEqual(result["pinning"], {"1": "7", "2": "9", "3": "8"}) + self.assertIsNone(infer_symbol(component, classes, "UNKNOWN", FixtureResolver({}))) + + def test_fet_unknown_part_cannot_guess_polarity(self) -> None: + component = component_fixture( + footprint="Package_TO_SOT_SMD:SOT-23", + pins={"1": "gate", "2": "source", "3": "drain"}, + ) + self.assertIsNone( + infer_symbol( + component, + ["edg.vendor_parts.jlc.JlcFet.JlcFet"], + "UNKNOWN_FET", + FixtureResolver({}), + ) + ) + + def test_usb_shield_pin_rename_between_kicad_versions(self) -> None: + component = component_fixture( + footprint="Connector_USB:USB_C_Receptacle_XKB_U262-16XN-4BVC11", + pins={"A1": "gnd.net", "A6": "usb.dp", "S1": "shield.net"}, + ) + cls = ["edg.parts.connector.UsbPorts.UsbCReceptacle_Device"] + lib_id = "Connector:USB_C_Receptacle_USB2.0_16P" + old = infer_symbol( + component, + cls, + "USB-C Receptacle", + FixtureResolver({lib_id: ["A1", "A6", "S1"]}), + ) + new = infer_symbol( + component, + cls, + "USB-C Receptacle", + FixtureResolver({lib_id: ["A1", "A6", "SH"]}), + ) + assert old is not None and new is not None + self.assertEqual(old["pinning"]["S1"], "S1") + self.assertEqual(new["pinning"]["SH"], "S1") + + def test_rgb_family_graphic_alias_explicitly_remaps_pads(self) -> None: + component = component_fixture( + footprint="fp:LED_SK6812SIDE_A_S", + pins={"1": "din.net", "2": "vdd.net", "3": "dout.net", "4": "gnd.net"}, + ) + result = infer_symbol( + component, + ["lib.human_interface.Sk6812sideas.Sk6812SideAS_Device"], + "SK6812SIDE-A-S (OPSCO Optoelectronics)", + FixtureResolver({"LED:SK6812": ["1", "2", "3", "4"]}), + ) + assert result is not None + self.assertEqual(result["pinning"], {"1": "4", "2": "1", "3": "2", "4": "3"}) + + def test_missing_library_is_not_an_unsafe_substitution(self) -> None: + component = component_fixture(footprint="Test:LED", pins={"1": "k", "2": "a"}) + self.assertIsNone( + infer_symbol( + component, + ["edg.vendor_parts.jlc.JlcLed.JlcLed"], + "LED", + FixtureResolver({}), + ) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_annotations.py b/edg/electronics_model/test_schematic_annotations.py new file mode 100644 index 000000000..b5fbbf0ab --- /dev/null +++ b/edg/electronics_model/test_schematic_annotations.py @@ -0,0 +1,102 @@ +"""Fields remain fixed from local routing through sheet translation.""" + +from __future__ import annotations +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import unittest +from dataclasses import replace +from .KiCadSchematicExporter import node, S +from .KiCadSchematicLayout import annotation_position, annotation_bounds, freeze_annotations, graphic_bounds +from .KiCadSchematicScene import segment_box + + +class SchematicAnnotationsTest(unittest.TestCase): + def test_arc_body_bounds_follow_the_selected_sweep(self) -> None: + for midpoint, angle, expected in ( + ((3, 4), 0, (-4, -5, 4, -3)), # Minor arc reaches beyond all three defining points. + ((3, -4), 0, (-5, -3, 5, 5)), # Same endpoints, major arc around the other side. + ((3, -4), 90, (-3, -5, 5, 5)), + ((0, 3), 0, (-4, -3, 4, -3)), # Collinear input retains its endpoints. + ): + with self.subTest(midpoint=midpoint, angle=angle): + arc = node("arc", node("start", -4, 3), node("mid", *midpoint), node("end", 4, 3)) + view = SymbolView(node("symbol", "Test:Arc", node("symbol", "Arc_0_1", arc)), [], "Test:Arc") + self.assertEqual(graphic_bounds(view, angle, include_pins=False), expected) + + def fixture(self) -> tuple[PhysicalComponent, SymbolView]: + # Geometry and labels of PDU hv_or.q1: rotated PowerPAK FET, with + # three coincident source pins and a long manufacturer value. + pins: list[tuple[str, float, float, float]] = [ + ("4", -5.08, 0, 0), + ("5", 2.54, 5.08, 270), + ("1", 2.54, -5.08, 90), + ("2", 2.54, -5.08, 90), + ("3", 2.54, -5.08, 90), + ] + body = node("symbol", "FET_0_1", node("circle", node("center", 1.651, 0), node("radius", 2.794))) + terminals = node( + "symbol", + "FET_1_1", + *[ + node( + "pin", + S("passive"), + S("line"), + node("at", x, y, a), + node("length", 2.54), + node("name", number), + node("number", number), + ) + for number, x, y, a in pins + ], + ) + view = SymbolView(node("symbol", "Transistor_FET:test", body, terminals), pins, "Transistor_FET:test") + component = PhysicalComponent( + "hv_or.q1", "Q2", "Package_SO:PowerPAK_SO-8_Single", "SIR882BDP-T1-RE3-HXY", {}, None, "hv_or" + ) + component.net_labels = { + "4": "hv_or + tp_gnd + others/hv_or.ic.gate1", + "5": "hv_or.pwr_out", + **{n: "xt60_in.pwr" for n in ("1", "2", "3")}, + } + component.placement_evidence = {"pattern": "power-path"} + return component, view + + def test_annotation_selection_is_translation_invariant(self) -> None: + component, view = self.fixture() + local = annotation_position(component, view, 130.81, 114.30, 90) + for dx, dy in ((-11.29, -21.31), (200.123, 30.777), (-110.81, 0)): + translated = annotation_position(component, view, 130.81 + dx, 114.30 + dy, 90) + self.assertAlmostEqual(translated[0], local[0] + dx) + self.assertAlmostEqual(translated[1], local[1] + dy) + + def test_frozen_fields_are_shared_by_routing_and_serialization(self) -> None: + component, view = self.fixture() + frozen, x, y, angle = freeze_annotations([(component, 130.81, 114.30, 90)], {component.path: view})[0] + self.assertIsNone(component.annotation) + self.assertEqual(frozen.placement_evidence, component.placement_evidence) + assert frozen.annotation is not None + before = annotation_bounds(frozen, *frozen.annotation, angle) + dx, dy = -11.29, -21.31 + rendered = replace(frozen, annotation=(frozen.annotation[0] + dx, frozen.annotation[1] + dy)) + at = annotation_position(rendered, view, x + dx, y + dy, angle) + after = annotation_bounds(rendered, at[0], at[1], angle) + for old, new, shift in zip(before, after, (dx, dy, dx, dy)): + self.assertAlmostEqual(new, old + shift) + # The native Q2 failure wire must have the same field collision verdict + # before and after sheet translation; rerendering cannot move the field. + wire = ((148.73, 87.91), (148.73, 123.47)) + self.assertEqual( + segment_box(*wire, after), + segment_box((wire[0][0] - dx, wire[0][1] - dy), (wire[1][0] - dx, wire[1][1] - dy), before), + ) + repacked = freeze_annotations([(component, 220, 180, 90)], {component.path: view})[0][0] + self.assertNotEqual(repacked.annotation, frozen.annotation) + self.assertIsNone(component.annotation) + + def test_explicit_annotations_remain_authoritative(self) -> None: + component, view = self.fixture() + component.annotation = (60, 80) + frozen = freeze_annotations([(component, 130, 114, 90)], {component.path: view})[0][0] + self.assertEqual(frozen.annotation, (60, 80)) + self.assertEqual(component.annotation, (60, 80)) diff --git a/edg/electronics_model/test_schematic_bridge_variants.py b/edg/electronics_model/test_schematic_bridge_variants.py new file mode 100644 index 000000000..b4b721949 --- /dev/null +++ b/edg/electronics_model/test_schematic_bridge_variants.py @@ -0,0 +1,208 @@ +"""Measured bridge proposals preserve terminal identity and disclose failures.""" + +from typing import Any, Mapping +from .KiCadSchematicTypes import PinKey, Placements, Placement, Views, PinNets, Bounds, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SymbolView +from .KiCadSchematicCircuits import SchematicCircuit +import unittest +from unittest.mock import patch + +from .test_schematic_functional_placement import part, passive_view +from .KiCadSchematicExporter import generic +from .KiCadSchematicPower import power_template_candidates + + +def bridge() -> tuple[tuple[str, ...], dict[str, PhysicalComponent], dict[str, SymbolView], dict[PinKey, str]]: + ic = part( + "controller", + {str(i): role for i, role in enumerate(("gnd", "sw1", "sw2", "hidrv1", "hidrv2", "lodrv1", "lodrv2"))}, + ) + coil = part("coil", {"1": "sw1", "2": "sw2"}, "Device:L") + parts = [ic, coil] + nets = {(ic.path, n): role for n, role in ic.pins.items()} + nets.update({("coil", "1"): "sw1", ("coil", "2"): "sw2"}) + for i in (1, 2): + hi = part("hi%d" % i, {"1": "gate", "2": "source", "3": "drain"}) + lo = part("lo%d" % i, {"1": "gate", "2": "source", "3": "drain"}) + parts.extend((hi, lo)) + nets.update( + { + (hi.path, "1"): "hidrv%d" % i, + (hi.path, "2"): "sw%d" % i, + (hi.path, "3"): "rail%d" % i, + (lo.path, "1"): "lodrv%d" % i, + (lo.path, "2"): "gnd", + (lo.path, "3"): "sw%d" % i, + } + ) + by_path = {c.path: c for c in parts} + views = {c.path: generic(c) for c in parts} + views["coil"] = passive_view("Device:L") + return tuple(sorted(by_path)), by_path, views, nets + + +class BridgeVariantTest(unittest.TestCase): + def test_verified_topology_marks_switch_gate_and_both_rail_paths_primary(self) -> None: + from .KiCadSchematicPower import topology_primary_nets + + members, by_path, views, nets = bridge() + primary = topology_primary_nets(list(by_path.values()), views, nets) + self.assertEqual(primary, {"sw1", "sw2", "rail1", "rail2", "hidrv1", "hidrv2", "lodrv1", "lodrv2"}) + self.assertNotIn("gnd", primary) + # A gate-like spelling without the required physical connection is + # insufficient to classify any of the topology as a converter. + nets["hi1", "1"] = "hidrv1_looks_similar" + self.assertFalse(topology_primary_nets(list(by_path.values()), views, nets)) + + def test_primary_shunt_outer_rail_requires_its_real_ground_bank(self) -> None: + from .KiCadSchematicPower import topology_primary_nets + + members, by_path, views, nets = bridge() + for path, netlist in ( + ("shunt", ("rail1", "external")), + ("local_bank", ("rail1", "gnd")), + ("outer_bank", ("external", "gnd")), + ): + lib = "Device:R" if path == "shunt" else "Device:C" + component = part(path, {"1": "a", "2": "b"}, lib) + by_path[path] = component + views[path] = passive_view(lib) + nets.update({(path, "1"): netlist[0], (path, "2"): netlist[1]}) + self.assertIn("external", topology_primary_nets(list(by_path.values()), views, nets)) + nets["outer_bank", "2"] = "unrelated" + self.assertNotIn("external", topology_primary_nets(list(by_path.values()), views, nets)) + + def test_primary_endpoints_exclude_rail_banks_and_include_inductor(self) -> None: + from .KiCadSchematicPower import topology_primary_endpoints + + members, by_path, views, nets = bridge() + cap = part("rail_bank", {"1": "a", "2": "b"}, "Device:C") + by_path[cap.path] = cap + views[cap.path] = passive_view("Device:C") + nets.update({("rail_bank", "1"): "rail1", ("rail_bank", "2"): "gnd"}) + endpoints = topology_primary_endpoints(list(by_path.values()), nets, views) + self.assertIn(("coil", "2"), endpoints["sw2"]) + self.assertIn(("hi1", "3"), endpoints["rail1"]) + self.assertNotIn(("rail_bank", "1"), endpoints["rail1"]) + self.assertNotIn("gnd", endpoints) + + def test_driver_supply_bypass_avoids_controller_label_corridors(self) -> None: + from .KiCadSchematicLayout import pins + + members, by_path, views, nets = bridge() + controller = by_path["controller"] + controller.pins["8"] = "regn" + views["controller"] = generic(controller) + nets["controller", "8"] = "driver_supply" + cap = part("anonymous_bypass", {"1": "a", "2": "b"}, "Device:C") + by_path[cap.path] = cap + views[cap.path] = passive_view("Device:C") + nets.update({("anonymous_bypass", "1"): "driver_supply", ("anonymous_bypass", "2"): "gnd"}) + from .KiCadSchematicPlacement import packing_bounds, atom_bounds + + def measured(entries: Placements, views: Views, nets: PinNets) -> Bounds: + return packing_bounds(entries, views, nets) if len(entries) == 1 else (0, 0, 100, 100) + + with ( + patch("edg.electronics_model.KiCadSchematicPlacement._score", return_value=(0, 0, 0, 0)), + patch("edg.electronics_model.KiCadSchematicPlacement.packing_bounds", side_effect=measured), + ): + candidates, _ = power_template_candidates(tuple(sorted(by_path)), by_path, views, nets) + self.assertTrue(candidates) + for _, entries in candidates: + placed = {c.path: (x, y, a) for c, x, y, a in entries} + supply = [(x, y) for number, x, y, _ in pins(views["controller"], *placed["controller"]) if number == "8"][ + 0 + ] + controller_bounds = packing_bounds([next(e for e in entries if e[0].path == "controller")], views, nets) + cap_bounds = atom_bounds([next(e for e in entries if e[0].path == "anonymous_bypass")], views) + self.assertTrue( + cap_bounds[2] <= controller_bounds[0] - 12.065 or cap_bounds[0] >= controller_bounds[2] + 12.065 + ) + self.assertAlmostEqual(placed["anonymous_bypass"][1], supply[1], delta=0.635) + self.assertEqual(placed["anonymous_bypass"][2], 0) + + def test_four_finite_deterministic_variants(self) -> None: + args = bridge() + # Geometry is tested independently by the scene tests; this fixture + # isolates topology, deterministic enumeration and identity retention. + with ( + patch("edg.electronics_model.KiCadSchematicPlacement._score", return_value=(0, 0, 0, 0)), + patch("edg.electronics_model.KiCadSchematicPlacement.packing_bounds", return_value=(0, 0, 100, 100)), + ): + candidates, diagnostics = power_template_candidates(*args) + repeat, repeated_diagnostics = power_template_candidates(*args) + self.assertEqual(len(candidates), 4) + self.assertEqual(diagnostics, repeated_diagnostics) + self.assertEqual(candidates, repeat) + for _, entries in candidates: + self.assertEqual({c.path for c, _, _, _ in entries}, set(args[0])) + by_path = {c.path: (x, y, a) for c, x, y, a in entries} + for index in (1, 2): + self.assertLess(by_path["hi%d" % index][1], by_path["lo%d" % index][1]) + self.assertLess(by_path["hi1"][0], by_path["coil"][0]) + self.assertLess(by_path["coil"][0], by_path["hi2"][0]) + self.assertEqual(args[1]["hi1"].pins, {"1": "gate", "2": "source", "3": "drain"}) + + def test_rejection_reasons_are_specific(self) -> None: + with ( + patch("edg.electronics_model.KiCadSchematicPlacement._score", return_value=(2, 3, 0, 0)), + patch("edg.electronics_model.KiCadSchematicPlacement.packing_bounds", return_value=(0, 0, 500, 500)), + ): + candidates, diagnostics = power_template_candidates(*bridge()) + self.assertFalse(candidates) + self.assertEqual(len(diagnostics), 4) + for diagnostic in diagnostics: + self.assertIn("escape conflict", diagnostic["reason"]) + self.assertIn("symbol or field collision", diagnostic["reason"]) + self.assertIn("overflow", diagnostic["reason"]) + + def test_candidate_measurement_recomputes_automatic_fields(self) -> None: + from .KiCadSchematicPower import compare_bridge_variants + from unittest.mock import Mock + + members, by_path, views, nets = bridge() + circuit = SchematicCircuit( + id="bridge", + title="Bridge", + summary="Bridge test", + template="four_switch_bridge", + components=members + ("separate_support_continuation",), + stages=(), + ) + for component in by_path.values(): + component.functional_circuit = circuit + component.annotation = (900, 900) + placed: list[Placement] = [(by_path[path], index * 40, 0, 0) for index, path in enumerate(members)] + + def candidates( + paths: tuple[str, ...], source: Mapping[str, PhysicalComponent], *_: Any + ) -> tuple[list[tuple[str, list[Placement]]], list[dict[str, Any]]]: + self.assertTrue(all(c.annotation is None for c in source.values())) + self.assertTrue(all(c is not by_path[path] for path, c in source.items())) + return [], [] + + with patch("edg.electronics_model.KiCadSchematicPower.power_template_candidates", side_effect=candidates): + compare_bridge_variants(placed, views, nets, ([], {}, []), Mock()) + self.assertTrue(all(c.annotation == (900, 900) for c in by_path.values())) + + def test_uncategorized_region_reuses_incumbent_route(self) -> None: + from .KiCadSchematicPower import compare_bridge_variants + from unittest.mock import Mock + + members, by_path, views, nets = bridge() + placed: list[Placement] = [(by_path[path], index * 40, 0, 0) for index, path in enumerate(members)] + route: RouteResult = ([], {}, []) + router = Mock(side_effect=AssertionError("incumbent must be reused")) + actual, cached, evidence = compare_bridge_variants(placed, views, nets, route, router) + self.assertIs(actual, placed) + self.assertIs(cached, route) + self.assertIsNone(evidence) + router.assert_not_called() + + def test_ambiguous_or_missing_topology_is_not_guessed(self) -> None: + members, by_path, views, nets = bridge() + nets["hi1", "1"] = "unrelated" + candidates, diagnostics = power_template_candidates(members, by_path, views, nets) + self.assertFalse(candidates) + self.assertIn("topology ambiguity", diagnostics[0]["reason"]) diff --git a/edg/electronics_model/test_schematic_circuit_placement.py b/edg/electronics_model/test_schematic_circuit_placement.py new file mode 100644 index 000000000..b44979aa7 --- /dev/null +++ b/edg/electronics_model/test_schematic_circuit_placement.py @@ -0,0 +1,268 @@ +"""Circuit-level placement honors authored intent without losing net truth.""" + +from __future__ import annotations +from typing import Sequence +from .KiCadSchematicTypes import PinKey, Wire, Placement, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import unittest +from dataclasses import replace +from .KiCadSchematicCircuits import SchematicCircuit, SchematicCircuitModel, CircuitStage, CircuitBoundary +from unittest.mock import patch + +from .test_schematic_functional_placement import part, passive_view +from .KiCadSchematicExporter import generic +from .KiCadSchematicPatterns import SchematicPattern +from .KiCadSchematicPlacement import ( + functional_atoms, + _whole_candidates, + _choose_routes, + _staged_template, + _candidate_valid, +) + + +class CircuitPlacementTest(unittest.TestCase): + def parts(self) -> tuple[list[PhysicalComponent], dict[str, SymbolView], dict[PinKey, str]]: + parts = [part(p, {"1": "input", "2": "output", "3": "gnd"}) for p in ("a", "b", "c")] + views = {c.path: generic(c) for c in parts} + nets = {(c.path, n): c.path + n for c in parts for n in c.pins} + nets["a", "2"] = nets["b", "1"] = "ab" + nets["b", "2"] = nets["c", "1"] = "bc" + return parts, views, nets + + def circuit( + self, components: Sequence[str], stages: Sequence[CircuitStage] = (), boundaries: Sequence[CircuitBoundary] = () + ) -> SchematicCircuit: + return SchematicCircuit( + id="test", + title="Test", + summary="Test circuit", + provenance="explicit", + template="auto", + components=tuple(components), + stages=tuple(stages), + boundaries=tuple(boundaries), + patterns=(SchematicPattern("serial_data_chain", tuple(components), ("ab", "bc")),), + ) + + def test_shared_model_preserves_authored_boundary_against_automatic_union(self) -> None: + parts, views, nets = self.parts() + first = self.circuit(("a", "b")) + model = SchematicCircuitModel( + circuits=(first,), patterns=(SchematicPattern("power_subcircuit", ("a", "b", "c"), ("ab", "bc")),) + ) + for c in parts: + c.circuit_model = model + c.functional_circuit = first if c.path in first.components else None + with patch( + "edg.electronics_model.KiCadSchematicPlacement.discover_patterns", + side_effect=AssertionError("shared model must be reused"), + ): + atoms, _ = functional_atoms(parts, nets, views) + self.assertEqual(atoms, (("a", "b"), ("c",))) + + def test_explicit_stages_place_input_to_output_and_rotate_boundary(self) -> None: + from .KiCadSchematicLayout import pins + + parts, views, nets = self.parts() + boundary = CircuitBoundary("a", "1", "Input", "input", "a1") + stages = [CircuitStage(p, (p,)) for p in ("a", "b", "c")] + circuit = self.circuit(("a", "b", "c"), stages, [boundary]) + for c in parts: + c.functional_circuit = circuit + placed = _staged_template(circuit.components, {c.path: c for c in parts}, views, nets) + assert placed is not None + self.assertTrue(_candidate_valid(placed, views, nets)) + self.assertEqual([c.path for c, _, _, _ in placed], ["a", "b", "c"]) + self.assertLess(placed[0][1], placed[1][1]) + self.assertLess(placed[1][1], placed[2][1]) + c, x, y, angle = placed[0] + terminal = next(p for p in pins(views[c.path], x, y, angle) if p[0] == "1") + self.assertLess(terminal[1], x) + + def test_measured_overflow_splits_authored_stages_without_rejoining(self) -> None: + from .KiCadSchematicExporter import SymbolView, node + + parts, _, nets = self.parts() + views = { + c.path: SymbolView( + node( + "symbol", + "Large", + node("symbol", "Large_0_1", node("rectangle", node("start", -65, -35), node("end", 65, 35))), + ), + [("1", -70, 0, 0), ("2", 70, 0, 180), ("3", 0, 40, 90)], + "Fixture:Large", + ) + for c in parts + } + stages = [CircuitStage(p, (p,)) for p in ("a", "b", "c")] + circuit = self.circuit(("a", "b", "c"), stages) + model = SchematicCircuitModel( + circuits=(circuit,), patterns=(SchematicPattern("power_subcircuit", ("a", "b", "c"), ("ab", "bc")),) + ) + for c in parts: + c.functional_circuit = circuit + c.circuit_model = model + atoms, _ = functional_atoms(parts, nets, views) + self.assertEqual(atoms, (("a",), ("b",), ("c",))) + self.assertTrue(all(c.functional_continuation for c in parts)) + + def test_unrelated_stage_space_is_protected_from_through_routes(self) -> None: + from .KiCadSchematicPlacement import _stage_intrusions + + parts, views, nets = self.parts() + circuit = self.circuit(("a", "b", "c"), [CircuitStage("ab", ("a", "b"))]) + for c in parts: + c.functional_circuit = circuit + placed = [(parts[0], 40, 80, 0), (parts[1], 100, 80, 0), (parts[2], 150, 80, 0)] + unrelated: list[Wire] = [("external", (70, 60), (70, 100))] + self.assertEqual(_stage_intrusions(placed, unrelated, views, nets), 1) + self.assertEqual(_stage_intrusions(placed, [("ab", (70, 60), (70, 100))], views, nets), 0) + + def test_route_selection_prefers_visible_primary_path_to_shorter_wire(self) -> None: + parts, views, nets = self.parts() + circuit = self.circuit(("a", "b", "c")) + for c in parts: + c.functional_circuit = circuit + baseline: list[Placement] = [(c, i * 45.72, 0, 0) for i, c in enumerate(parts)] + candidate: list[Placement] = [(c, x + 5.08, y, a) for c, x, y, a in baseline] + original: RouteResult = ([("ab", (40, 80), (50, 80))], {}, [(("a", "2"), "ab")]) + clearer: RouteResult = ([("ab", (40, 80), (100, 80))], {}, []) + with patch("edg.electronics_model.KiCadSchematicLayout.route_local", side_effect=[original, clearer]): + selected, evidence = _choose_routes(baseline, [("template", baseline), ("clear", candidate)], views, nets) + self.assertEqual(selected, candidate) + self.assertEqual(evidence["after"]["primary_fallbacks"], 0) + self.assertGreater(evidence["after"]["length_mm"], evidence["before"]["length_mm"]) + + def test_explicit_generic_does_not_invoke_power_template(self) -> None: + from .KiCadSchematicPlacement import _circuit_template + + parts, views, nets = self.parts() + circuit = self.circuit(("a", "b", "c")) + circuit = replace(circuit, template="generic") + for c in parts: + c.functional_circuit = circuit + with patch( + "edg.electronics_model.KiCadSchematicPower.power_template", + side_effect=AssertionError("generic must not select a power layout"), + ): + entries = _circuit_template(circuit.components, {c.path: c for c in parts}, views, nets) + self.assertEqual({c.path for c, _, _, _ in entries}, {"a", "b", "c"}) + + def test_explicit_power_template_dispatch_and_authored_stage_precedence(self) -> None: + from .KiCadSchematicPlacement import _circuit_template + + parts, views, nets = self.parts() + circuit = self.circuit(("a", "b", "c")) + circuit = replace(circuit, template="buck") + for c in parts: + c.functional_circuit = circuit + marker: list[Placement] = [(c, 40 * i, 0, 0) for i, c in enumerate(parts)] + with patch("edg.electronics_model.KiCadSchematicPower.power_template", return_value=marker) as power: + self.assertEqual(_circuit_template(circuit.components, {c.path: c for c in parts}, views, nets), marker) + power.assert_called_once() + circuit = replace(circuit, stages=tuple(CircuitStage(c.path, (c.path,)) for c in parts)) + for c in parts: + c.functional_circuit = circuit + with patch( + "edg.electronics_model.KiCadSchematicPower.power_template", + side_effect=AssertionError("authored stages take precedence"), + ): + entries = _circuit_template(circuit.components, {c.path: c for c in parts}, views, nets) + self.assertEqual([c.path for c, _, _, _ in entries], ["a", "b", "c"]) + + def test_authored_serial_chain_uses_functional_stage_placement(self) -> None: + from .KiCadSchematicLayout import place_group + + parts, views, nets = self.parts() + circuit = self.circuit(("a", "b", "c"), [CircuitStage(c.path, (c.path,)) for c in parts]) + circuit = replace(circuit, template="repeated_channel") + model = SchematicCircuitModel( + circuits=(circuit,), patterns=(SchematicPattern("serial_data_chain", ("a", "b", "c"), ("ab", "bc")),) + ) + for c in parts: + c.functional_circuit = circuit + c.circuit_model = model + with patch( + "edg.electronics_model.KiCadSchematicLayout._place_group_legacy", + side_effect=AssertionError("authored stages must not use legacy bypass"), + ): + pages = place_group(parts, views, nets) + self.assertTrue(pages) + self.assertTrue(all(hasattr(c, "placement_evidence") for page in pages for c, _, _, _ in page)) + + def test_authored_repeated_chain_without_stages_retains_inline_template(self) -> None: + from .KiCadSchematicLayout import place_group + + parts, views, nets = self.parts() + circuit = self.circuit(("a", "b", "c")) + circuit = replace(circuit, template="repeated_channel") + model = SchematicCircuitModel( + circuits=(circuit,), patterns=(SchematicPattern("serial_data_chain", ("a", "b", "c"), ("ab", "bc")),) + ) + for c in parts: + c.functional_circuit = circuit + c.circuit_model = model + marker = [[(c, 40 * i, 80, 0) for i, c in enumerate(parts)]] + with patch("edg.electronics_model.KiCadSchematicLayout._place_group_legacy", return_value=marker) as inline: + with patch( + "edg.electronics_model.KiCadSchematicPlacement.place_functional", + side_effect=AssertionError("unstaged repeated chain must retain inline template"), + ): + self.assertEqual(place_group(parts, views, nets), marker) + inline.assert_called_once() + # The template name alone cannot establish a serial relationship. + model = replace(model, patterns=()) + for c in parts: + c.circuit_model = model + with patch( + "edg.electronics_model.KiCadSchematicLayout._place_group_legacy", + side_effect=AssertionError("serial topology must be verified"), + ): + with patch("edg.electronics_model.KiCadSchematicPlacement.place_functional", return_value=marker): + self.assertEqual(place_group(parts, views, nets), marker) + + def test_whole_candidate_budget_deduplication_and_locked_owner(self) -> None: + parts, views, nets = self.parts() + baseline: list[Placement] = [(c, i * 45.72, 0, 0) for i, c in enumerate(parts)] + candidates = _whole_candidates(baseline, [baseline] * 10, views, nets, {"a"}) + self.assertLessEqual(len(candidates), 8) + self.assertEqual(candidates[0], ("template", baseline)) + for _, candidate in candidates: + self.assertEqual(candidate[0], baseline[0]) + keys = [tuple((c.path, x, y, a) for c, x, y, a in entries) for _, entries in candidates] + self.assertEqual(len(keys), len(set(keys))) + + def test_route_shortlist_is_bounded_and_new_failed_endpoint_rejected(self) -> None: + parts, views, nets = self.parts() + baseline: list[Placement] = [(c, i * 45.72, 0, 0) for i, c in enumerate(parts)] + candidates = [("template", baseline)] + [ + (str(i), [(c, x, y + i * 2.54, a) for c, x, y, a in baseline]) for i in range(1, 8) + ] + original: RouteResult = ([], {}, [((("a", "1")), "a1")]) + invalid: RouteResult = ([], {}, [((("b", "1")), "ab")]) + with patch( + "edg.electronics_model.KiCadSchematicLayout.route_local", side_effect=[original, invalid, invalid, invalid] + ) as router: + selected, evidence = _choose_routes(baseline, candidates, views, nets) + self.assertEqual(router.call_count, 4) + self.assertEqual(selected, baseline) + self.assertEqual(evidence["route_trials"], 4) + self.assertFalse(any(t["acceptable"] for t in evidence["trials"])) + + def test_safe_baseline_retained_when_candidate_routes_outside_page(self) -> None: + parts, views, nets = self.parts() + baseline: list[Placement] = [(c, i * 45.72, 0, 0) for i, c in enumerate(parts)] + candidate: list[Placement] = [(c, x + 5.08, y, a) for c, x, y, a in baseline] + original: RouteResult = ([("ab", (40, 80), (80, 80))], {}, []) + outside: RouteResult = ([("ab", (5, 80), (20, 80))], {}, []) + with patch("edg.electronics_model.KiCadSchematicLayout.route_local", side_effect=[original, outside]): + selected, evidence = _choose_routes(baseline, [("template", baseline), ("bad", candidate)], views, nets) + self.assertEqual(selected, baseline) + self.assertFalse(evidence["trials"][0]["acceptable"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_circuits.py b/edg/electronics_model/test_schematic_circuits.py new file mode 100644 index 000000000..30693603d --- /dev/null +++ b/edg/electronics_model/test_schematic_circuits.py @@ -0,0 +1,225 @@ +"""Source-owned circuit intent is checked against compiled physical witnesses.""" + +from __future__ import annotations +from typing import Any +from .KiCadSchematicTypes import PinKey +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import copy +import unittest + +from .KiCadSchematicCircuits import build_circuits +from .KiCadSchematicPresentation import SchematicPresentation +from .KiCadSchematicExporter import generic + + +def resistor(path: str) -> PhysicalComponent: + return PhysicalComponent(path, "R1", "FP", "1k", {"1": "a", "2": "b"}, {"lib_id": "Device:R"}, "group") + + +def circuit(*members: str, **options: Any) -> dict[str, Any]: + return dict(id="chain", title="Input protection", summary="Series input path", components=list(members), **options) + + +class CircuitPresentationTest(unittest.TestCase): + def fixture(self) -> tuple[list[PhysicalComponent], dict[PinKey, str], dict[str, SymbolView]]: + components = [resistor("first"), resistor("second"), resistor("other")] + wiring = { + ("first", "1"): "in", + ("first", "2"): "middle", + ("second", "1"): "middle", + ("second", "2"): "out", + ("other", "1"): "unrelated", + ("other", "2"): "return", + } + views = {c.path: generic(c) for c in components} + return components, wiring, views + + def test_schema1_unchanged_schema2_roundtrip_and_input_copy(self) -> None: + self.assertEqual(SchematicPresentation().to_dict(), dict(schema=1, components={}, interfaces=[], groups={})) + value: dict[str, Any] = dict(schema=2, circuits=[circuit("first", "second")]) + presentation = SchematicPresentation.from_dict(value) + saved = presentation.to_dict() + value["circuits"][0]["components"].append("other") + self.assertEqual(saved, presentation.to_dict()) + self.assertEqual(saved, SchematicPresentation.from_dict(saved).to_dict()) + self.assertEqual(SchematicPresentation.from_dict(dict(schema=2)).to_dict()["schema"], 2) + with self.assertRaisesRegex(ValueError, "schema 2"): + SchematicPresentation.from_dict(dict(circuits=[circuit("first")])) + + def test_invalid_structure_and_membership(self) -> None: + invalid = [ + [circuit("first", "first")], + [circuit("first", template="mystery")], + [circuit("first", unknown=True)], + [circuit("first"), dict(circuit("second"), id="chain")], + [circuit("first"), dict(circuit("first"), id="another")], + [circuit("first", boundaries=[dict(component="second", pin="1", name="Input", role="input")])], + [circuit("first", boundaries=[dict(component="first", pin="1", name="Input", role="guess")])], + [circuit("first", stages=[dict(id="stage", components=["second"])])], + ] + for entries in invalid: + with self.subTest(entries=entries), self.assertRaises(ValueError): + SchematicPresentation.from_dict(dict(schema=2, circuits=entries)) + + def test_physical_references_and_boundaries(self) -> None: + for entries in [ + [circuit("missing")], + [circuit("first", boundaries=[dict(component="first", pin="99", name="Input", role="input")])], + ]: + p = SchematicPresentation.from_dict(dict(schema=2, circuits=entries)) + with self.subTest(entries=entries), self.assertRaises(ValueError): + p.validate({"first": {"1": "a", "2": "b"}}) + + def test_compiled_witnesses_and_determinism(self) -> None: + components, wiring, views = self.fixture() + original = copy.deepcopy(wiring) + p = SchematicPresentation.from_dict( + dict( + schema=2, + circuits=[ + circuit( + "first", + "second", + stages=[dict(id="input", components=["first"]), dict(id="output", components=["second"])], + boundaries=[ + dict(component="first", pin="1", name="External input", role="input"), + dict(component="second", pin="2", name="Protected output", role="output"), + ], + ) + ], + ) + ) + model = build_circuits(components, wiring, views, p) + entry = next(c for c in model.circuits if c.provenance == "explicit") + self.assertEqual(entry.primary_nets, ("in", "out")) + self.assertEqual(entry.boundaries[0].net, "in") + self.assertEqual([s.id for s in entry.stages], ["input", "output"]) + self.assertEqual( + model.to_dict(), + build_circuits(list(reversed(components)), dict(reversed(list(wiring.items()))), views, p).to_dict(), + ) + self.assertEqual(wiring, original) + + def test_board_scope_missing_net_and_duplicate_titles_rejected(self) -> None: + components, wiring, views = self.fixture() + p = SchematicPresentation(circuits=(circuit("first", "second"),)) + with self.assertRaisesRegex(ValueError, "scope"): + build_circuits( + components, wiring, views, p, scope_by_path={"first": "board1", "second": "board2", "other": "board1"} + ) + with self.assertRaisesRegex(ValueError, "scope"): + build_circuits(components[:1], wiring, views, p) + p = SchematicPresentation( + circuits=(circuit("first", boundaries=[dict(component="first", pin="1", name="Input", role="input")]),) + ) + del wiring["first", "1"] + with self.assertRaisesRegex(ValueError, "no compiled net"): + build_circuits(components, wiring, views, p) + p = SchematicPresentation(circuits=(circuit("first"), dict(circuit("second"), id="different"))) + with self.assertRaisesRegex(ValueError, "duplicate circuit title"): + build_circuits(components, wiring, views, p) + + def test_ordered_stages_require_real_connection(self) -> None: + components, wiring, views = self.fixture() + p = SchematicPresentation( + circuits=( + circuit( + "first", "other", stages=[dict(id="a", components=["first"]), dict(id="b", components=["other"])] + ), + ) + ) + with self.assertRaisesRegex(ValueError, "lack a non-supply connection"): + build_circuits(components, wiring, views, p) + p = SchematicPresentation(circuits=(circuit("first", "second", template="buck"),)) + with self.assertRaisesRegex(ValueError, "lacks required compiled"): + build_circuits(components, wiring, views, p) + + def test_shared_rails_do_not_create_automatic_circuit(self) -> None: + components, wiring, views = self.fixture() + for c in components: + c.pins = {"1": "vdd", "2": "gnd"} + wiring[c.path, "1"], wiring[c.path, "2"] = "common_supply", "common_return" + model = build_circuits(components, wiring, views, SchematicPresentation()) + self.assertEqual({c.components for c in model.circuits}, {("first",), ("second",), ("other",)}) + self.assertTrue(all({b.role for b in c.boundaries} == {"supply", "return"} for c in model.circuits)) + self.assertFalse(any(c.primary_nets for c in model.circuits)) + + def test_schema2_rail_stage_flow_requires_explicit_flow_witness(self) -> None: + components, wiring, views = self.fixture() + components[0].pins = {"1": "vin", "2": "vout"} + components[1].pins = {"1": "vin", "2": "vout"} + stages = [dict(id="a", components=["first"]), dict(id="b", components=["second"])] + p = SchematicPresentation(circuits=(circuit("first", "second", stages=stages),)) + with self.assertRaisesRegex(ValueError, "lack a non-supply connection"): + build_circuits(components, wiring, views, p) + p = SchematicPresentation( + circuits=( + circuit( + "first", + "second", + stages=stages, + boundaries=[dict(component="first", pin="2", name="Power output", role="output")], + ), + ) + ) + self.assertTrue(build_circuits(components, wiring, views, p).circuits) + + def test_automatic_boundaries_are_undirected_without_authored_intent(self) -> None: + components, wiring, views = self.fixture() + model = build_circuits(components, wiring, views, SchematicPresentation()) + first = next(c for c in model.circuits if c.components == ("first",)) + self.assertEqual([(b.pin, b.net, b.role) for b in first.boundaries], [("2", "middle", "bidirectional")]) + self.assertEqual(first.primary_nets, ("middle",)) + + def test_ambiguous_bypass_ownership_remains_diagnostic(self) -> None: + components, wiring, views = self.fixture() + components[0].hierarchy = (("first.wrapper", "edg.abstract_parts.Capacitor.DecouplingCapacitor"),) + model = build_circuits(components, wiring, views, SchematicPresentation()) + self.assertEqual(len(model.diagnostics), 1) + self.assertIn("Unassigned bypass ownership: first", model.diagnostics[0]) + + +class ConnectorProtectionEvidenceTest(unittest.TestCase): + def test_protection_requires_connector_signal_attachment_not_common_rails(self) -> None: + connector = PhysicalComponent( + "connector", "J1", "FP", "Connector", {"1": "pins.0", "2": "pins.1", "3": "pins.2"}, None, "group" + ) + clamp = PhysicalComponent("clamp", "D1", "FP", "TVS", {"1": "a", "2": "k"}, None, "group") + device = PhysicalComponent( + "device", "U1", "FP", "Receiver", {"1": "input", "2": "gnd", "3": "vcc"}, None, "group" + ) + components = [connector, clamp, device] + views = {c.path: generic(c) for c in components} + views["connector"].lib_id = "Connector_Generic:Conn_01x03" + views["clamp"].lib_id = "Device:D_TVS" + nets = { + ("connector", "1"): "signal", + ("connector", "2"): "gnd", + ("connector", "3"): "vcc", + ("device", "1"): "signal", + ("device", "2"): "gnd", + ("device", "3"): "vcc", + ("clamp", "1"): "signal", + ("clamp", "2"): "gnd", + } + presentation = SchematicPresentation( + circuits=( + circuit( + "connector", + "clamp", + "device", + template="connector_protection", + stages=[ + dict(id="entry", components=["connector"]), + dict(id="protected", components=["clamp", "device"]), + ], + ), + ) + ) + self.assertTrue(build_circuits(components, nets, views, presentation).circuits) + for invalid_net in ("unrelated", "vcc"): + with self.subTest(net=invalid_net): + nets["clamp", "1"] = invalid_net + with self.assertRaisesRegex(ValueError, "lacks required compiled connectivity"): + build_circuits(components, nets, views, presentation) diff --git a/edg/electronics_model/test_schematic_decoupling_routing.py b/edg/electronics_model/test_schematic_decoupling_routing.py new file mode 100644 index 000000000..f4d50a04d --- /dev/null +++ b/edg/electronics_model/test_schematic_decoupling_routing.py @@ -0,0 +1,160 @@ +"""Ownership-aware routing must survive explicit presentation coordinates.""" + +from __future__ import annotations +from .KiCadSchematicTypes import PinKey, Placement +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import copy +import unittest +from collections import defaultdict + +from .KiCadSchematicExporter import node +from .KiCadSchematicLayout import route_local + + +class DecouplingRoutingTest(unittest.TestCase): + def fixture( + self, count: int + ) -> tuple[list[Placement], dict[str, SymbolView], dict[PinKey, str], list[tuple[str, str, float]]]: + placed: list[Placement] = [] + views: dict[str, SymbolView] = {} + wiring: dict[PinKey, str] = {} + pairs: list[tuple[str, str, float]] = [] + for i in range(count): + owner = f"rgb.pixel[{i}]" + device = PhysicalComponent( + owner + ".device", + f"U{i}", + "FP", + "pixel", + {"1": "vdd", "2": "gnd", "3": "din", "4": "dout"}, + None, + "rgb", + ) + cap = PhysicalComponent( + owner + ".bypass.cap", + f"C{i}", + "FP", + "100nF", + {"1": "pos", "2": "neg"}, + {"lib_id": "Device:C"}, + "rgb", + hierarchy=((owner + ".bypass", "edg.abstract_parts.Capacitor.DecouplingCapacitor"),), + ) + x = 35.3 + i * 40.64 # Intentionally not on the routing grid. + device.annotation = (x, 133.35) + cap.annotation = (x + 12.7, 59.69) + placed.extend(((device, x, 110.49, 0), (cap, x + 12.7, 76.2, 0))) + views[device.path] = SymbolView( + node("symbol", node("rectangle", node("start", -2.54, 2.54), node("end", 2.54, -2.54))), + [("1", 0, -5.08, 270), ("2", 0, 5.08, 90), ("3", -5.08, 0, 0), ("4", 5.08, 0, 180)], + "Test:Pixel", + ) + views[cap.path] = SymbolView( + node("symbol", node("rectangle", node("start", -1.27, 1.27), node("end", 1.27, -1.27))), + [("1", -3.81, 0, 0), ("2", 3.81, 0, 180)], + "Device:C", + ) + wiring.update( + { + (device.path, "1"): "supply", + (device.path, "2"): "gnd", + (device.path, "3"): f"data{i}", + (device.path, "4"): f"data{i + 1}", + (cap.path, "1"): "supply", + (cap.path, "2"): "gnd", + } + ) + pairs.append((device.path, cap.path, x)) + return placed, views, wiring, pairs + + def test_explicit_hints_keep_each_cap_branch_local_without_second_bus(self) -> None: + for count in (1, 8): + placed, views, wiring, pairs = self.fixture(count) + before = copy.deepcopy((placed, views, wiring)) + wires, escapes, failures = route_local(placed, views, wiring) + self.assertEqual(failures, []) + self.assertEqual((placed, views, wiring), before) + self.assertEqual(set(escapes), set(wiring)) + self.assertTrue(all(net in wiring.values() for net, _, _ in wires)) + for device, cap, x in pairs: + # Inspect only the owner's narrow channel. A remote capacitor + # bus cannot satisfy this connectivity check via another pixel. + graph = defaultdict(set) + for net, a, b in wires: + if net != "supply" or min(a[0], b[0]) < x - 6 or max(a[0], b[0]) > x + 18: + continue + dx, dy = b[0] - a[0], b[1] - a[1] + self.assertTrue(dx == 0 or dy == 0) + steps = max(1, round(max(abs(dx), abs(dy)) / 0.635)) + points = [ + (round(a[0] + dx * n / steps, 4), round(a[1] + dy * n / steps, 4)) for n in range(steps + 1) + ] + for p, q in zip(points, points[1:]): + graph[p].add(q) + graph[q].add(p) + start = (escapes[cap, "1"][2], escapes[cap, "1"][3]) + target = (escapes[device, "1"][2], escapes[device, "1"][3]) + todo, reached = [start], set() + while todo: + point = todo.pop() + if point not in reached: + reached.add(point) + todo.extend(graph[point] - reached) + self.assertIn(target, reached) + # Upper support area must contain short branches, not a parallel + # horizontal rail spanning neighboring bypass capacitors. + for net, a, b in wires: + if net == "supply" and a[1] == b[1] and a[1] < 95: + self.assertLess(abs(a[0] - b[0]), 20) + + def test_conflicting_cap_hints_report_fallback_instead_of_shared_branch(self) -> None: + placed, views, wiring, pairs = self.fixture(2) + # An authored plan overlays two bypasses. Their identical supply escapes + # must not become a misleading local branch that appears to serve both. + cap0 = placed[1] + cap1 = placed[3] + placed[3] = (cap1[0], cap0[1], cap0[2], cap0[3]) + cap1[0].annotation = cap0[0].annotation + _, escapes, failures = route_local(placed, views, wiring) + self.assertEqual(escapes[cap0[0].path, "1"], escapes[cap1[0].path, "1"]) + self.assertTrue({((cap, "1"), "supply") for _, cap, _ in pairs}.issubset(set(failures))) + + def test_readability_flags_split_or_missing_support_and_never_auto_approves(self) -> None: + import sexpdata + from .KiCadSchematicReadability import inspect_documents + from .KiCadSchematicPatterns import decoupling_associations + + placed, views, wiring, _ = self.fixture(1) + device, cap = [entry[0] for entry in placed] + patterns = [p.to_dict() for p in decoupling_associations([device, cap], wiring, views)] + + def document(*components: PhysicalComponent) -> str: + return sexpdata.dumps( + node("kicad_sch", *[node("symbol", node("property", "PBPath", c.path)) for c in components]) + ) + + cases = ( + ({"together.kicad_sch": document(device, cap)}, False), + ({"device.kicad_sch": document(device), "cap.kicad_sch": document(cap)}, True), + ({"device.kicad_sch": document(device)}, True), + ) + for files, expected in cases: + evidence = inspect_documents(files, [], patterns) + split = [f for f in evidence["findings"] if f["code"] == "decoupling_split"] + self.assertEqual(bool(split), expected) + if expected: + self.assertEqual(split[0]["objects"], sorted((device.path, cap.path))) + self.assertEqual(evidence["visual_approval"], "pending") + + def test_input_order_does_not_change_routing_or_pin_escapes(self) -> None: + placed, views, wiring, _ = self.fixture(3) + actual = route_local(placed, views, wiring) + reversed_result = route_local( + list(reversed(placed)), dict(reversed(list(views.items()))), dict(reversed(list(wiring.items()))) + ) + self.assertEqual(actual, reversed_result) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_export.py b/edg/electronics_model/test_schematic_export.py new file mode 100644 index 000000000..a0065528c --- /dev/null +++ b/edg/electronics_model/test_schematic_export.py @@ -0,0 +1,598 @@ +"""Exporter tests use real compiled connectivity, independent of KiCad installation.""" + +from __future__ import annotations +from typing import Any +from pathlib import Path +from ..core import CompiledDesign +from .KiCadSchematicTypes import PinNets, Placements, Views, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SchematicExport + +from typing_extensions import override +import json +import tempfile +import unittest +import shutil +import subprocess +import xml.etree.ElementTree as ET + +import sexpdata + +from ..core import ScalaCompiler, GeneratorBlock, Block +from .CircuitBlock import FootprintBlock +from .PassivePort import Passive +from ..electronics_interfaces.test_netlist import TestBasicCircuit +from .NetlistGenerator import NetlistTransform +from .SchematicVerification import verify_schematic_netlist +from .RefdesRefinementPass import RefdesRefinementPass +from .KiCadSchematicExporter import ( + KiCadSchematicExporter, + SchematicExportOptions, + SchematicPlacement, + SymbolResolver, + children, + NOTICE, + generic, +) + + +class GeneratedMappedPart(GeneratorBlock, FootprintBlock): + def __init__(self) -> None: + super().__init__() + self.a = self.Port(Passive(), optional=True) + self.b = self.Port(Passive(), optional=True) + + @override + def generate(self) -> None: + super().generate() + self.footprint( + "R", "Resistor_SMD:R_0603_1608Metric", {"1": self.a, "2": self.b}, value="Long supplier description " * 8 + ) + self.schematic_symbol("Device:R", {"1": "1", "2": "2"}) + + +class GeneratedMappedBoard(Block): + @override + def contents(self) -> None: + super().contents() + self.part = self.Block(GeneratedMappedPart()) + + +class ManyGroupsBoard(Block): + @override + def contents(self) -> None: + super().contents() + for index in range(41): + setattr(self, "group" + str(index), self.Block(GeneratedMappedBoard())) + + +class SchematicExportTest(unittest.TestCase): + compiled: CompiledDesign + + @classmethod + @override + def setUpClass(cls) -> None: + cls.compiled = ScalaCompiler.compile(TestBasicCircuit) + cls.compiled.append_values(RefdesRefinementPass().run(cls.compiled)) + + def pin_numbers(self, path: tuple[str, ...]) -> set[str]: + inventory = self.compiled.get_value(path + ("fp_pinning",)) + assert isinstance(inventory, list) + result = set() + for pin in inventory: + assert isinstance(pin, str) + result.add(pin.split("=", 1)[0]) + return result + + def test_manifest_symbol_coverage_has_compiled_identity_and_fallback_reason(self) -> None: + result = KiCadSchematicExporter().export(self.compiled, SchematicExportOptions("Coverage")) + coverage = json.loads(result.files["manifest.json"])["symbol_coverage"] + expected = {str(b.full_path) for n in NetlistTransform(self.compiled).run().values() for b in n.blocks} + self.assertEqual({entry["component"] for entry in coverage}, expected) + for entry in coverage: + self.assertTrue(entry["compiled_class"]) + self.assertEqual(entry["status"], "fallback") + self.assertEqual(entry["category"], "missing_mapping") + self.assertEqual(entry["reason"], "no schematic symbol mapping") + + def test_explicit_mapping_precedence_and_failure_evidence(self) -> None: + from unittest.mock import patch + + compiled = ScalaCompiler.compile(GeneratedMappedBoard) + compiled.append_values(RefdesRefinementPass().run(compiled)) + for error, category in ( + (FileNotFoundError("Device:R"), "missing_library"), + (KeyError("R"), "missing_symbol"), + (LookupError("multi-unit symbol unsupported"), "unsupported_multi_unit"), + (LookupError("stacked or repeated symbol pins unsupported"), "unsupported_symbol"), + ): + with ( + self.subTest(category=category), + patch( + "edg.electronics_model.KiCadSymbolRegistry.infer_symbol", + side_effect=AssertionError("explicit mapping replaced"), + ), + patch.object(SymbolResolver, "resolve", side_effect=error), + ): + result = KiCadSchematicExporter().export(compiled, SchematicExportOptions("Coverage")) + (entry,) = json.loads(result.files["manifest.json"])["symbol_coverage"] + self.assertEqual(entry["mapping_source"], "explicit") + self.assertEqual(entry["lib_id"], "Device:R") + self.assertEqual(entry["category"], category) + self.assertEqual(entry["status"], "fallback") + with patch.object(SymbolResolver, "resolve", side_effect=ValueError("unmapped library pin 3")): + with self.assertRaisesRegex(ValueError, "unmapped library pin"): + KiCadSchematicExporter().export(compiled, SchematicExportOptions("Invalid")) + + def test_generated_symbol_metadata_and_long_description(self) -> None: + compiled = ScalaCompiler.compile(GeneratedMappedBoard) + compiled.append_values(RefdesRefinementPass().run(compiled)) + result = KiCadSchematicExporter().export(compiled, SchematicExportOptions("GeneratedMappedPart")) + symbols = [ + symbol + for name, content in result.files.items() + if name.endswith(".kicad_sch") + for symbol in children(sexpdata.loads(content), "symbol") + ] + self.assertEqual(len(symbols), 1) + properties = {prop[1]: prop[2] for prop in children(symbols[0], "property")} + self.assertEqual(properties["Value"], "Long supplier description " * 8) + self.assertIn("\n", properties["PBDisplayValue"]) + + def test_flipped_symbol_reflects_all_three_arc_points(self) -> None: + compiled = ScalaCompiler.compile(GeneratedMappedBoard) + compiled.append_values(RefdesRefinementPass().run(compiled)) + with tempfile.TemporaryDirectory() as directory: + Path(directory, "Device.kicad_sym").write_text( + """(kicad_symbol_lib (symbol "R" (symbol "R_1_1" + (arc (start 4 3) (mid 3 4) (end -4 3)) + (pin passive line (at -7.62 0 0) (length 2.54) (name "A") (number "1")) + (pin passive line (at 7.62 0 180) (length 2.54) (name "B") (number "2")))))""", + encoding="utf-8", + ) + result = KiCadSchematicExporter().export( + compiled, + SchematicExportOptions( + "Reflected", + symbol_library_dirs=(directory,), + placements={"part": SchematicPlacement("Test", 50, 50, flip_horizontal=True)}, + ), + ) + (arc,) = [ + arc + for name, content in result.files.items() + if name.endswith(".kicad_sch") + for library in children(sexpdata.loads(content), "lib_symbols") + for definition in children(library, "symbol") + if definition[1].endswith("_reflected") + for body in children(definition, "symbol") + for arc in children(body, "arc") + ] + self.assertEqual([children(arc, key)[0][1:] for key in ("start", "mid", "end")], [[-4, 3], [-3, 4], [4, 3]]) + + def test_oversized_optimized_route_retains_fitting_baseline(self) -> None: + from unittest import mock + from .KiCadSchematicRouting import route_metrics + + def oversized( + placed: Placements, views: Views, nets: PinNets, baseline: RouteResult, router: object + ) -> tuple[RouteResult, dict[str, Any]]: + metric = route_metrics(baseline[0], baseline[2]) + candidate = (baseline[0] + [("oversized-trial", (15, 40), (400, 40))], baseline[1], baseline[2]) + return candidate, dict(before=metric, after=metric, selected="trial", candidates=2) + + with mock.patch("edg.electronics_model.KiCadSchematicRouting.optimize_fixed_routes", oversized): + result = KiCadSchematicExporter().export(self.compiled, SchematicExportOptions("PageFit")) + self.assertIn("rejected_for_page_fit", result.files["routing.json"]) + self.assertNotIn("oversized-trial", "".join(v for k, v in result.files.items() if k.endswith(".kicad_sch"))) + + def test_paginated_index_hierarchy(self) -> None: + compiled = ScalaCompiler.compile(ManyGroupsBoard) + compiled.append_values(RefdesRefinementPass().run(compiled)) + consolidated = KiCadSchematicExporter().export(compiled, SchematicExportOptions("ManyGroupsBoard")) + self.assertLess(sum(name.endswith(".kicad_sch") for name in consolidated.files), 41) + result = KiCadSchematicExporter().export( + compiled, + SchematicExportOptions( + "ManyGroupsBoard", sheet_assignments={"group" + str(i): "Explicit sheet " + str(i) for i in range(41)} + ), + ) + self.assertEqual(len([name for name in result.files if "_contents_" in name]), 2) + self.assertEqual( + sum( + len(children(sexpdata.loads(content), "symbol")) + for name, content in result.files.items() + if name.endswith(".kicad_sch") + ), + 41, + ) + if shutil.which("kicad-cli"): + with tempfile.TemporaryDirectory() as directory: + result.write(Path(directory)) + root = next( + name + for name in result.files + if name.endswith(".kicad_sch") and len(Path(name).stem.split("_")) == 2 + ) + output = Path(directory, "roundtrip.xml") + subprocess.run( + [ + "kicad-cli", + "sch", + "export", + "netlist", + "--format", + "kicadxml", + "-o", + str(output), + str(Path(directory, root)), + ], + check=True, + capture_output=True, + timeout=45, + ) + verify_schematic_netlist(next(iter(NetlistTransform(compiled).run().values())), output) + + def test_large_generic_symbol_has_centered_two_sided_pins(self) -> None: + component = PhysicalComponent( + "mcu", "U1", "Package:QFP", "mcu", {str(i): "gpio" + str(i) for i in range(1, 97)}, None, "mcu" + ) + view = generic(component) + self.assertEqual(len(view.pins), 96) + self.assertTrue(any(p[1] < 0 for p in view.pins)) + self.assertTrue(any(p[1] > 0 for p in view.pins)) + self.assertLess(max(p[2] for p in view.pins) - min(p[2] for p in view.pins), 180) + + def test_compiled_export_deterministic(self) -> None: + exporter = KiCadSchematicExporter() + options = SchematicExportOptions("TestBasicCircuit", source="test.TestBasicCircuit") + first = exporter.export(self.compiled, options) + self.assertEqual(first.files, exporter.export(self.compiled, options).files) + self.assertTrue(first.diagnostics) + symbols = [] + for name, content in first.files.items(): + if name.endswith(".kicad_sch"): + self.assertIn(NOTICE, content) + tree = sexpdata.loads(content) + symbols.extend(children(tree, "symbol")) + self.assertGreater(len(symbols), 0) + self.assertEqual(len(symbols), len({children(s, "uuid")[0][1] for s in symbols})) + + def test_scope_and_wrapper_preservation(self) -> None: + from ..electronics_interfaces.test_netlist_subboard import TestSubboardCircuit + from ..electronics_interfaces.test_netlist_subboard_wrapper import TestWrapperCircuit + from ..electronics_interfaces.test_netlist_subboard_array import TestArrayWrapperCircuit + + for design in (TestSubboardCircuit, TestWrapperCircuit, TestArrayWrapperCircuit): + with self.subTest(design=design.__name__): + compiled = ScalaCompiler.compile(design) + compiled.append_values(RefdesRefinementPass().run(compiled)) + expected = NetlistTransform(compiled).run() + bundle = KiCadSchematicExporter().export(compiled, SchematicExportOptions(design.__name__)) + roots = [n for n in bundle.files if n.endswith(".kicad_sch") and len(Path(n).stem.split("_")) == 2] + self.assertEqual(len(roots), len(expected)) + actual_count = sum( + len(children(sexpdata.loads(content), "symbol")) + for name, content in bundle.files.items() + if name.endswith(".kicad_sch") + ) + self.assertEqual(actual_count, sum(len(n.blocks) for n in expected.values())) + + def test_missing_python_placement_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "missing components"): + KiCadSchematicExporter().export( + self.compiled, + SchematicExportOptions("Test", placements={"nonexistent": SchematicPlacement("Circuit", 60, 80)}), + ) + + def test_foreign_pin_escapes_cannot_short_a_hinted_sheet(self) -> None: + for separation in (35.56, 34.29, 33.02): + with ( + self.subTest(separation=separation), + self.assertRaisesRegex(ValueError, r"(?=.*gnd)(?=.*vpos)(?=.*source\.2)(?=.*sink\.1)(?=.* at \()"), + ): + KiCadSchematicExporter().export( + self.compiled, + SchematicExportOptions( + "Short", + placements={ + "source": SchematicPlacement("Power", 50, 50), + "sink": SchematicPlacement("Power", 50 + separation, 50), + }, + ), + ) + + def test_separated_pin_escapes_preserve_both_nets(self) -> None: + for y in (50.0, 50.00015): + with self.subTest(y=y): + result = KiCadSchematicExporter().export( + self.compiled, + SchematicExportOptions( + "Control", + placements={ + "source": SchematicPlacement("Power", 50, y), + "sink": SchematicPlacement("Power", 100.8, y), + }, + ), + ) + if shutil.which("kicad-cli"): + with tempfile.TemporaryDirectory() as directory: + result.write(Path(directory)) + root = json.loads(result.files["manifest.json"])["boards"][0]["root"] + xml = Path(directory, "control.xml") + subprocess.run( + [ + "kicad-cli", + "sch", + "export", + "netlist", + "--format", + "kicadxml", + "-o", + str(xml), + str(xml.parent / root), + ], + check=True, + capture_output=True, + timeout=45, + ) + verify_schematic_netlist(next(iter(NetlistTransform(self.compiled).run().values())), xml) + + def test_foreign_route_endpoint_on_wire_is_a_short(self) -> None: + from .KiCadSchematicWriter import validate_wire_contacts + + horizontal = ("input", (10.0, 20.0), (30.0, 20.0)) + vertical = ("output", (20.0, 20.0), (20.0, 30.0)) + with self.assertRaisesRegex(ValueError, r"short at \(20.0, 20.0\).*output.*input"): + validate_wire_contacts([horizontal, vertical], {}) + validate_wire_contacts([horizontal, ("input", vertical[1], vertical[2])], {}) + + def test_python_placement_rotation_and_reflection(self) -> None: + options = SchematicExportOptions( + "Hinted", + placements={ + "source": SchematicPlacement("Circuit", 70, 90, 90, True), + "sink": SchematicPlacement("Circuit", 140, 90, 270), + }, + ) + result = KiCadSchematicExporter().export(self.compiled, options) + physical = [ + symbol + for name, content in result.files.items() + if name.endswith(".kicad_sch") + for symbol in children(sexpdata.loads(content), "symbol") + ] + self.assertEqual(len(physical), 2) + if shutil.which("kicad-cli"): + with tempfile.TemporaryDirectory() as directory: + result.write(Path(directory)) + root = next( + name + for name in result.files + if name.endswith(".kicad_sch") and len(Path(name).stem.split("_")) == 2 + ) + output = Path(directory, "roundtrip.xml") + subprocess.run( + [ + "kicad-cli", + "sch", + "export", + "netlist", + "--format", + "kicadxml", + "-o", + str(output), + str(Path(directory, root)), + ], + check=True, + capture_output=True, + timeout=45, + ) + verify_schematic_netlist(next(iter(NetlistTransform(self.compiled).run().values())), output) + + def test_physical_inventory_and_wires(self) -> None: + bundle = KiCadSchematicExporter().export(self.compiled, SchematicExportOptions("Test")) + expected = next(iter(NetlistTransform(self.compiled).run().values())) + expected_pins = {b.refdes: self.pin_numbers(b.full_path.to_tuple()) for b in expected.blocks} + actual = {} + wire_count = 0 + for name, content in bundle.files.items(): + if not name.endswith(".kicad_sch"): + continue + tree = sexpdata.loads(content) + wire_count += len(children(tree, "wire")) + for symbol in children(tree, "symbol"): + props = {p[1]: p[2] for p in children(symbol, "property")} + actual[props["Reference"]] = {p[1] for p in children(symbol, "pin")} + self.assertEqual(actual, expected_pins) + self.assertGreaterEqual(wire_count, sum(len(n.pins) for n in expected.nets)) + + @unittest.skipUnless(shutil.which("kicad-cli"), "KiCad CLI not installed") + def test_native_round_trip(self) -> None: + bundle = KiCadSchematicExporter().export(self.compiled, SchematicExportOptions("Test")) + with tempfile.TemporaryDirectory() as directory: + bundle.write(Path(directory)) + root = next( + name for name in bundle.files if name.endswith(".kicad_sch") and len(Path(name).stem.split("_")) == 2 + ) + output = Path(directory, "roundtrip.xml") + subprocess.run( + [ + "kicad-cli", + "sch", + "export", + "netlist", + "--format", + "kicadxml", + "-o", + str(output), + str(Path(directory, root)), + ], + check=True, + capture_output=True, + ) + verify_schematic_netlist(next(iter(NetlistTransform(self.compiled).run().values())), output) + + def test_checker_rejects_merged_nets(self) -> None: + expected = next(iter(NetlistTransform(self.compiled).run().values())) + root = ET.Element("export") + comps = ET.SubElement(root, "components") + parts = ET.SubElement(root, "libparts") + for block in expected.blocks: + c = ET.SubElement(comps, "comp", ref=block.refdes) + ET.SubElement(c, "footprint").text = block.footprint + ET.SubElement(c, "libsource", lib="Test", part=block.refdes) + part = ET.SubElement(parts, "libpart", lib="Test", part=block.refdes) + pins = ET.SubElement(part, "pins") + for pin_number in self.pin_numbers(block.full_path.to_tuple()): + ET.SubElement(pins, "pin", num=pin_number) + nets = ET.SubElement(root, "nets") + refs = {str(b.full_path): b.refdes for b in expected.blocks} + for net in expected.nets: + n = ET.SubElement(nets, "net") + for pin in net.pins: + ET.SubElement(n, "node", ref=refs[str(pin.block_path)], pin=pin.pin_name) + with tempfile.TemporaryDirectory() as directory: + output = Path(directory, "net.xml") + ET.ElementTree(root).write(output) + verify_schematic_netlist(expected, output) + entries = list(nets) + self.assertGreaterEqual(len(entries), 2) + entries[0].extend(list(entries[1])) + nets.remove(entries[1]) + ET.ElementTree(root).write(output) + with self.assertRaises(ValueError): + verify_schematic_netlist(expected, output) + + def test_compile_opt_in_and_generate_false(self) -> None: + from ..BoardCompiler import compile_board + + with tempfile.TemporaryDirectory() as directory: + target = (directory, "Test") + compile_board(TestBasicCircuit, target) + netlist = Path(directory, "Test.net").read_bytes() + self.assertFalse(Path(directory, "Test.schematic").exists()) + compile_board(TestBasicCircuit, target, schematic=SchematicExportOptions("Test")) + self.assertEqual(Path(directory, "Test.net").read_bytes(), netlist) + self.assertTrue(Path(directory, "Test.schematic", "manifest.json").exists()) + result = compile_board(TestBasicCircuit, None, schematic=SchematicExportOptions("Test")) + self.assertFalse(result.errors) + + def test_write_preserves_unowned_files(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "keep.txt").write_text("user") + (root / "old.kicad_sch").write_text("old") + (root / "manifest.json").write_text(json.dumps({"files": ["old.kicad_sch"]})) + SchematicExport({"new.kicad_sch": "new", "manifest.json": '{"files": ["new.kicad_sch"]}'}, []).write(root) + self.assertTrue((root / "keep.txt").exists()) + self.assertFalse((root / "old.kicad_sch").exists()) + + def test_write_rolls_back_replacement_and_cleanup_failures(self) -> None: + import os + from unittest.mock import patch + + for failure in ("a.kicad_sch", "b.kicad_sch", "old.kicad_sch", "manifest.json"): + with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + original = { + "b.kicad_sch": b"old B", + "old.kicad_sch": b"obsolete sheet", + "keep.txt": b"user content", + "manifest.json": json.dumps({"files": ["b.kicad_sch", "old.kicad_sch"]}).encode(), + } + for name, content in original.items(): + (root / name).write_bytes(content) + bundle = SchematicExport( + { + "a.kicad_sch": "new A", + "b.kicad_sch": "new B", + "manifest.json": json.dumps({"files": ["a.kicad_sch", "b.kicad_sch"]}), + }, + [], + ) + real_replace, real_unlink = os.replace, Path.unlink + + def replace(source: Path, destination: Path) -> None: + if Path(source).parent.name == "incoming" and Path(destination).name == failure: + raise OSError("injected replacement failure") + return real_replace(source, destination) + + def unlink(path: Path, *args: Any, **kwargs: Any) -> None: + if path == root / failure and failure == "old.kicad_sch": + raise OSError("injected cleanup failure") + return real_unlink(path, *args, **kwargs) + + with patch("os.replace", replace), patch.object(Path, "unlink", unlink): + with self.assertRaisesRegex(OSError, "injected"): + bundle.write(root) + self.assertEqual({p.name: p.read_bytes() for p in root.iterdir()}, original) + # A retry must complete normally and retire only owned stale files. + bundle.write(root) + self.assertEqual((root / "keep.txt").read_bytes(), original["keep.txt"]) + self.assertFalse((root / "old.kicad_sch").exists()) + for name, new_content in bundle.files.items(): + self.assertEqual((root / name).read_text(), new_content) + + def test_write_staging_failure_does_not_touch_existing_bundle(self) -> None: + from unittest.mock import patch + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + original = {"a.kicad_sch": b"old A", "manifest.json": b'{"files": ["a.kicad_sch"]}'} + for name, content in original.items(): + (root / name).write_bytes(content) + real_write = Path.write_text + + def write(path: Path, *args: Any, **kwargs: Any) -> int: + if path.parent.name == "incoming" and path.name == "b.kicad_sch": + raise OSError("injected staging failure") + return real_write(path, *args, **kwargs) + + with patch.object(Path, "write_text", write): + with self.assertRaisesRegex(OSError, "injected staging failure"): + SchematicExport({"a.kicad_sch": "new A", "b.kicad_sch": "new B"}, []).write(root) + self.assertEqual({p.name: p.read_bytes() for p in root.iterdir()}, original) + + def test_write_retains_backups_if_rollback_fails(self) -> None: + import os + from unittest.mock import patch + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "a.kicad_sch").write_text("old A") + (root / "manifest.json").write_text('{"files": ["a.kicad_sch"]}') + real_replace = os.replace + + def replace(source: Path, destination: Path) -> None: + if Path(destination).name == "manifest.json" or Path(source).parent.name == "backup": + raise OSError("injected persistent failure") + return real_replace(source, destination) + + with patch("os.replace", replace): + with self.assertRaisesRegex(RuntimeError, "recovery files retained"): + SchematicExport({"a.kicad_sch": "new A", "manifest.json": "{}"}, []).write(root) + (recovery,) = root.glob(".schematic-recovery-*") + self.assertEqual((recovery / "backup" / "a.kicad_sch").read_text(), "old A") + self.assertEqual((root / "manifest.json").read_text(), '{"files": ["a.kicad_sch"]}') + + def test_library_inheritance_and_mapping_validation(self) -> None: + library = """(kicad_symbol_lib (version 20241209) (generator test) + (symbol "Base" (symbol "Base_1_1" + (pin passive line (at 0 0 0) (length 2.54) (name "A") (number "1")))) + (symbol "Child" (extends "Base")))""" + with tempfile.TemporaryDirectory() as directory: + Path(directory, "Test.kicad_sym").write_text(library) + component = PhysicalComponent( + "test", "U1", "Test:FP", "test", {"7": "a"}, {"lib_id": "Test:Child", "pinning": {"1": "7"}}, "test" + ) + resolver = SymbolResolver([directory]) + view = resolver.resolve(component) + self.assertEqual(view.pins[0][0], "7") + assert component.mapping is not None + component.mapping["pinning"]["1"] = "8" + with self.assertRaises(ValueError): + resolver.resolve(component) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_functional_placement.py b/edg/electronics_model/test_schematic_functional_placement.py new file mode 100644 index 000000000..48e11aced --- /dev/null +++ b/edg/electronics_model/test_schematic_functional_placement.py @@ -0,0 +1,626 @@ +"""Functional circuits remain complete, compact and deterministic during layout.""" + +from __future__ import annotations +from .KiCadSchematicTypes import PinKey, Placement, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import unittest + +from .KiCadSchematicExporter import generic, node +from .KiCadSchematicLayout import place_group, split_group +from .KiCadSchematicPlacement import functional_atoms, component_boxes, _overlap, signal_nets + + +def part(path: str, pins: dict[str, str], lib_id: str | None = None) -> PhysicalComponent: + return PhysicalComponent( + path, path.rsplit(".", 1)[-1], "Test:FP", "part", pins, {"lib_id": lib_id} if lib_id else None, "circuit" + ) + + +def passive_view(lib_id: str) -> SymbolView: + return SymbolView( + node("symbol", lib_id, node("symbol", "part_0_1", node("rectangle", node("start", -1, 3), node("end", 1, -3)))), + [("1", 0, -5.08, 270), ("2", 0, 5.08, 90)], + lib_id, + ) + + +class FunctionalPlacementTest(unittest.TestCase): + def test_power_roles_allow_parallel_pads_only_on_same_net(self) -> None: + from .KiCadSchematicPower import role_nets + + ic = part("ic", {"1": "sw", "2": "sw", "3": "gnd"}) + nets = {("ic", "1"): "switch", ("ic", "2"): "switch", ("ic", "3"): "return"} + self.assertEqual(role_nets(ic, nets)["sw"], "switch") + nets["ic", "2"] = "different" + self.assertNotIn("sw", role_nets(ic, nets)) + + def test_buck_coil_aligns_with_switch_terminal(self) -> None: + from .KiCadSchematicPower import power_template + from .KiCadSchematicLayout import pins + + ic = part("ic", {"1": "vin", "2": "sw", "3": "gnd"}) + coil = part("coil", {"1": "a", "2": "b"}, "Device:L") + views = {"ic": generic(ic), "coil": passive_view("Device:L")} + nets = { + ("ic", "1"): "in", + ("ic", "2"): "switch", + ("ic", "3"): "gnd", + ("coil", "1"): "switch", + ("coil", "2"): "out", + } + entries = power_template(["ic", "coil"], {"ic": ic, "coil": coil}, views, nets) + assert entries is not None + terminals = {} + for component, x, y, angle in entries: + for number, px, py, _ in pins(views[component.path], x, y, angle): + if nets[component.path, number] == "switch": + terminals[component.path] = (px, py) + self.assertEqual(terminals["ic"][1], terminals["coil"][1]) + self.assertGreater(terminals["coil"][0], terminals["ic"][0]) + + def test_input_inductor_does_not_claim_buck_topology(self) -> None: + from .KiCadSchematicPower import power_topology + + ic = part("ic", {"1": "vin", "2": "sw", "3": "gnd"}) + coil = part("coil", {"1": "a", "2": "b"}, "Device:L") + parts = {"ic": ic, "coil": coil} + views = {"ic": generic(ic), "coil": passive_view("Device:L")} + nets = {("ic", "1"): "in", ("ic", "2"): "sw", ("ic", "3"): "gnd", ("coil", "1"): "in", ("coil", "2"): "sw"} + self.assertIsNone(power_topology(parts, parts, views, nets)) + + def test_bridge_kernel_excludes_unrelated_control_fet(self) -> None: + from .KiCadSchematicPower import power_topology, bridge_kernel + + ic = part( + "ic", {str(i): role for i, role in enumerate(["gnd", "sw1", "sw2", "hidrv1", "hidrv2", "lodrv1", "lodrv2"])} + ) + coil = part("coil", {"1": "sw1", "2": "sw2"}, "Device:L") + parts = [ic, coil] + for i in (1, 2): + parts += [ + part(f"hi{i}", {"1": "gate", "2": "source", "3": "drain"}), + part(f"lo{i}", {"1": "gate", "2": "source", "3": "drain"}), + ] + parts.append(part("ce", {"1": "gate", "2": "source", "3": "drain"})) + nets = {(ic.path, n): role for n, role in ic.pins.items()} + nets.update({("coil", "1"): "sw1", ("coil", "2"): "sw2"}) + for i in (1, 2): + nets.update( + { + (f"hi{i}", "1"): f"hidrv{i}", + (f"hi{i}", "2"): f"sw{i}", + (f"hi{i}", "3"): f"rail{i}", + (f"lo{i}", "1"): f"lodrv{i}", + (f"lo{i}", "2"): "gnd", + (f"lo{i}", "3"): f"sw{i}", + } + ) + nets.update({("ce", "1"): "enable", ("ce", "2"): "gnd", ("ce", "3"): "ce"}) + by_path = {c.path: c for c in parts} + views = {c.path: generic(c) for c in parts} + views["coil"] = passive_view("Device:L") + topology = power_topology(list(by_path), by_path, views, nets) + assert topology is not None + self.assertEqual(topology["kind"], "bridge") + kernel = bridge_kernel(topology, by_path, by_path, views, nets) + self.assertEqual(kernel, set(by_path) - {"ce"}) + + def test_gate_driver_cross_sibling_graph_requires_gate_and_return(self) -> None: + from .KiCadSchematicPower import gate_driver_circuits + + roles = ["vcc", "gnd", "gnd", "tgup", "tgdn", "ts", "bst"] + ic = part("driver", {str(i): r for i, r in enumerate(roles)}) + fet = part("switch", {"1": "gate", "2": "source", "3": "drain"}) + res = part("gate_r", {"1": "a", "2": "b"}, "Device:R") + cap = part("bootstrap", {"1": "pos", "2": "neg"}, "Device:C") + unrelated = part("unrelated", {"1": "pos", "2": "neg"}, "Device:C") + parts = [ic, fet, res, cap, unrelated] + views = {c.path: generic(c) for c in parts} + for c, lib in [(res, "Device:R"), (cap, "Device:C"), (unrelated, "Device:C")]: + views[c.path] = passive_view(lib) + nets = {(ic.path, n): role for n, role in ic.pins.items()} + nets.update( + { + ("switch", "1"): "tgdn", + ("switch", "2"): "ts", + ("switch", "3"): "power", + ("gate_r", "1"): "tgup", + ("gate_r", "2"): "tgdn", + ("bootstrap", "1"): "bst", + ("bootstrap", "2"): "ts", + ("unrelated", "1"): "vcc", + ("unrelated", "2"): "gnd", + } + ) + circuits = gate_driver_circuits(parts, nets, views) + self.assertEqual(len(circuits), 1) + self.assertEqual(set(circuits[0][1]), {"switch", "gate_r", "bootstrap"}) + nets["switch", "2"] = "another_return" + self.assertFalse(gate_driver_circuits(parts, nets, views)) + + def test_differential_sense_filters_form_support_atoms(self) -> None: + from .KiCadSchematicPatterns import discover_patterns + + ic = part("charger.ic", {"1": "acp", "2": "acn", "3": "gnd", "4": "gnd"}) + rp = part("charger.rp", {"1": "a", "2": "b"}, "Device:R") + rn = part("charger.rn", {"1": "a", "2": "b"}, "Device:R") + cap = part("charger.c", {"1": "pos", "2": "neg"}, "Device:C") + parts = [ic, rp, rn, cap] + nets = { + ("charger.ic", "1"): "p", + ("charger.ic", "2"): "n", + ("charger.ic", "3"): "gnd", + ("charger.ic", "4"): "gnd", + (rp.path, "1"): "p", + (rp.path, "2"): "input", + (rn.path, "1"): "n", + (rn.path, "2"): "output", + (cap.path, "1"): "p", + (cap.path, "2"): "n", + } + patterns = discover_patterns(parts, nets) + sense = next(p for p in patterns if p.kind == "differential_sense_filter") + self.assertEqual(set(sense.components), {rp.path, rn.path, cap.path}) + views = { + ic.path: generic(ic), + rp.path: passive_view("Device:R"), + rn.path: passive_view("Device:R"), + cap.path: passive_view("Device:C"), + } + atoms, _ = functional_atoms(parts, nets, views) + self.assertIn(tuple(sorted(sense.components)), atoms) + + def test_large_mcu_with_five_bypasses_uses_measured_bank(self) -> None: + from .KiCadSchematicPlacement import _template, packing_bounds, _score + + ic = part("control.mcu.ic", {str(i): f"gpio{i}" for i in range(64)}) + ic.pins.update({"64": "gnd", "65": "gnd", "66": "vdd", "67": "vdd"}) + caps = [part(f"control.mcu.pwr_cap[{i}].cap", {"1": "pos", "2": "neg"}, "Device:C") for i in range(5)] + for c in caps: + c.hierarchy = ((c.path.rpartition(".")[0], "edg.abstract_parts.Capacitor.DecouplingCapacitor"),) + parts = [ic, *caps] + views = {ic.path: generic(ic), **{c.path: passive_view("Device:C") for c in caps}} + nets = {(ic.path, n): role if role in ("gnd", "vdd") else "signal" + n for n, role in ic.pins.items()} + for c in caps: + nets[c.path, "1"] = "vdd" + nets[c.path, "2"] = "gnd" + atoms, patterns = functional_atoms(parts, nets, views) + self.assertEqual(len(atoms), 1) + entries = _template(atoms[0], patterns, {c.path: c for c in parts}, views, nets) + bounds = packing_bounds(entries, views, nets) + self.assertLessEqual(bounds[2] - bounds[0] + 17.78, 340) + self.assertLessEqual(bounds[3] - bounds[1] + 17.78, 205) + self.assertEqual(_score(entries, views, nets)[:2], (0, 0)) + self.assertEqual(len(place_group(parts, views, nets)), 1) + + def amplifier( + self, prefix: str = "amp" + ) -> tuple[list[PhysicalComponent], dict[str, SymbolView], dict[PinKey, str]]: + amp = part(prefix + ".ic", {"1": "out", "2": "inp", "3": "inn", "4": "vcc", "5": "gnd"}) + fb = part(prefix + ".feedback", {"1": "a", "2": "b"}, "Device:R") + cap = part(prefix + ".bypass.cap", {"1": "pos", "2": "neg"}, "Device:C") + cap.hierarchy = ((prefix + ".bypass", "edg.abstract_parts.Capacitor.DecouplingCapacitor"),) + parts = [amp, fb, cap] + views = {amp.path: generic(amp), fb.path: passive_view("Device:R"), cap.path: passive_view("Device:C")} + wiring = { + (amp.path, "1"): prefix + "_output", + (amp.path, "2"): prefix + "_input", + (amp.path, "3"): prefix + "_negative", + (amp.path, "4"): "common_positive", + (amp.path, "5"): "common_return", + (fb.path, "1"): prefix + "_output", + (fb.path, "2"): prefix + "_negative", + (cap.path, "1"): "common_positive", + (cap.path, "2"): "common_return", + } + return parts, views, wiring + + def test_same_net_escape_cannot_cross_neighbor_pin_number(self) -> None: + from .KiCadSchematicPlacement import escape_conflicts + from .KiCadSchematicExporter import S + + a = part("a", {"1": "p"}) + b = part("b", {"1": "p"}) + definition = node( + "symbol", + "Fixture", + node( + "symbol", + "Fixture_1_1", + node("pin", S("passive"), S("line"), node("at", 0, 0, 0), node("length", 2.54), node("number", "3")), + ), + ) + views = { + "a": SymbolView(node("symbol"), [("1", 0, 0, 0)], "Fixture:A"), + "b": SymbolView(definition, [("1", 0, 0, 0)], "Fixture:B"), + } + entries = [(a, 50, 50, 0), (b, 46, 51.397, 0)] + nets = {("a", "1"): "same", ("b", "1"): "same"} + self.assertGreater(escape_conflicts(entries, views, nets), 0) + definition.append(node("pin_numbers", S("hide"))) + self.assertEqual(escape_conflicts(entries, views, nets), 0) + + def test_compiled_repeated_channels_keep_all_support_parts_together(self) -> None: + first, va, wa = self.amplifier("balance[0]") + second, vb, wb = self.amplifier("balance[1]") + for group in (first, second): + for c in group: + owner = c.path.split(".")[0] + c.hierarchy = ((owner, "Test.BalanceChannel"),) + c.hierarchy + parts, views, wiring = first + second, {**va, **vb}, {**wa, **wb} + atoms, patterns = functional_atoms(parts, wiring, views) + self.assertEqual(sum(p.kind == "repeated_subcircuit" for p in patterns), 2) + self.assertEqual({frozenset(a) for a in atoms}, {frozenset(c.path for c in group) for group in (first, second)}) + for page in place_group(parts, views, wiring): + members = {entry[0].path for entry in page} + for atom in atoms: + self.assertTrue(not set(atom) & members or set(atom) <= members) + + def test_verified_power_subtree_keeps_controller_and_stage_together(self) -> None: + ic = part("supply.ic", {"1": "sw", "2": "gnd", "3": "vin", "4": "fb", "5": "en", "6": "pg"}) + coil = part("supply.coil", {"1": "a", "2": "b"}, "Device:L") + cap = part("supply.cap", {"1": "pos", "2": "neg"}, "Device:C") + res = part("supply.res", {"1": "a", "2": "b"}, "Device:R") + parts = [ic, coil, cap, res] + for c in parts: + c.hierarchy = (("supply", "Test.PowerCircuit"),) + views = {ic.path: generic(ic), **{c.path: passive_view((c.mapping or {})["lib_id"]) for c in parts[1:]}} + wiring = { + (ic.path, "1"): "switch", + (ic.path, "2"): "return", + (coil.path, "1"): "switch", + (coil.path, "2"): "output", + (cap.path, "1"): "output", + (cap.path, "2"): "return", + (res.path, "1"): "output", + (res.path, "2"): "feedback", + (ic.path, "4"): "feedback", + } + atoms, patterns = functional_atoms(parts, wiring, views) + self.assertEqual(len(atoms), 1) + self.assertTrue(any(p.kind == "power_subcircuit" for p in patterns)) + pages = place_group(parts, views, wiring) + self.assertEqual(len(pages), 1) + self.assertIsNone(split_group(pages[0], views, wiring)) + + def test_repeated_channel_order_is_numeric(self) -> None: + parts: list[PhysicalComponent] = [] + views: dict[str, SymbolView] = {} + wiring: dict[PinKey, str] = {} + for index in (10, 2, 0): + group, gv, gw = self.amplifier(f"channel[{index}]") + for c in group: + c.hierarchy = ((f"channel[{index}]", "Test.Channel"),) + c.hierarchy + parts += group + views.update(gv) + wiring.update(gw) + pages = place_group(parts, views, wiring) + self.assertEqual( + [c.path for page in pages for c, _, _, _ in page if c.path.endswith(".ic")], + ["channel[0].ic", "channel[2].ic", "channel[10].ic"], + ) + + def test_oversized_repeated_channel_splits_at_compiled_child_boundaries(self) -> None: + parts: list[PhysicalComponent] = [] + views: dict[str, SymbolView] = {} + wiring: dict[PinKey, str] = {} + for channel in range(2): + owner = f"channel[{channel}]" + for child in ("driver", "isolator", "regulator"): + parent = owner + "." + child + device = part(parent + ".ic", {"1": "input", "2": "output", "3": "gnd"}) + cap = part(parent + ".cap", {"1": "pos", "2": "neg"}, "Device:C") + for c in (device, cap): + c.hierarchy = ((owner, "Test.ComplexChannel"), (parent, "Test.SupportCircuit")) + parts.extend((device, cap)) + views[device.path] = SymbolView( + node( + "symbol", + "Test:Large", + node("symbol", "part_0_1", node("rectangle", node("start", -60, -50), node("end", 60, 50))), + ), + [("1", -65, 0, 0), ("2", 65, 0, 180), ("3", 0, 55, 90)], + "Test:Large", + ) + views[cap.path] = passive_view("Device:C") + wiring.update( + { + (device.path, "2"): parent + ".local", + (cap.path, "1"): parent + ".local", + (device.path, "3"): "return", + (cap.path, "2"): "return", + } + ) + atoms, patterns = functional_atoms(parts, wiring, views) + self.assertEqual(len(atoms), 6) + self.assertTrue(all(len(atom) == 2 for atom in atoms)) + self.assertTrue(all("measured whole circuit exceeds A3" == c.functional_continuation["reason"] for c in parts)) + self.assertTrue(any(p.kind == "functional_section" for p in patterns)) + + def test_shared_rails_do_not_establish_repeated_channel_ownership(self) -> None: + from .KiCadSchematicPatterns import hierarchy_circuits + + parts = [ + part(f"array[{channel}].cap{index}", {"1": "pos", "2": "neg"}, "Device:C") + for channel in range(2) + for index in range(3) + ] + for c in parts: + c.hierarchy = ((c.path.split(".")[0], "Test.Channel"),) + views = {c.path: passive_view("Device:C") for c in parts} + wiring = {(c.path, n): net for c in parts for n, net in [("1", "supply"), ("2", "return")]} + self.assertEqual(hierarchy_circuits(parts, wiring, views), ()) + + def test_overlapping_feedback_and_bypass_patterns_form_one_atom(self) -> None: + parts, views, wiring = self.amplifier() + atoms, patterns = functional_atoms(parts, wiring, views) + self.assertEqual(atoms, (tuple(sorted(p.path for p in parts)),)) + self.assertEqual({p.kind for p in patterns}, {"amplifier_feedback", "local_decoupling"}) + pages = place_group(parts, views, wiring) + self.assertEqual(len(pages), 1) + positions = {e[0].path: e for e in pages[0]} + amp, fb, cap = [positions[p.path] for p in parts] + self.assertLess(fb[2], amp[2]) + self.assertGreater(cap[2], amp[2]) + self.assertEqual(cap[1], amp[1]) + self.assertLess(abs(fb[1] - amp[1]) + abs(fb[2] - amp[2]), 50) + self.assertIsNone(split_group(pages[0], views, wiring)) + + def test_compact_template_has_no_body_or_field_overlap(self) -> None: + parts, views, wiring = self.amplifier() + page = place_group(parts, views, wiring)[0] + for i, entry in enumerate(page): + for other in page[i + 1 :]: + for a in component_boxes(entry, views): + for b in component_boxes(other, views): + self.assertFalse(_overlap(a, b)) + + def test_packed_amplifier_vp_vn_bypass_stays_in_its_owner_atom(self) -> None: + parts, views, wiring = self.amplifier() + owner, _, cap = parts + owner.pins["4"], owner.pins["5"] = "vp", "vn" + atoms, patterns = functional_atoms(parts, wiring, views) + self.assertEqual(atoms, (tuple(sorted(p.path for p in parts)),)) + self.assertIn("local_decoupling", {p.kind for p in patterns}) + wiring[cap.path, "2"] = "other_return" + atoms, patterns = functional_atoms(parts, wiring, views) + self.assertNotIn("local_decoupling", {p.kind for p in patterns}) + + def test_repeated_channels_keep_distinct_bypass_ownership(self) -> None: + first, va, wa = self.amplifier("channel[0]") + second, vb, wb = self.amplifier("channel[1]") + parts, views, wiring = first + second, {**va, **vb}, {**wa, **wb} + atoms, _ = functional_atoms(parts, wiring, views) + self.assertEqual( + {frozenset(a) for a in atoms}, {frozenset(p.path for p in first), frozenset(p.path for p in second)} + ) + pages = place_group(parts, views, wiring) + self.assertEqual(pages, place_group(list(reversed(parts)), views, dict(reversed(list(wiring.items()))))) + flattened = [e for page in pages for e in page] + self.assertEqual(sorted(e[0].path for e in flattened), sorted(p.path for p in parts)) + for p in parts: + self.assertLessEqual(p.placement_evidence["candidates"], 64) + for page in pages: + membership = {e[0].path for e in page} + for atom in atoms: + self.assertTrue(not set(atom) & membership or set(atom) <= membership) + + def test_repeated_signature_requires_compiled_classes_and_same_connectivity(self) -> None: + from .KiCadSchematicPlacement import channel_signature + + first, va, wa = self.amplifier("channel[0]") + second, vb, wb = self.amplifier("channel[1]") + parts, views, wiring = first + second, {**va, **vb}, {**wa, **wb} + for group in (first, second): + for i, c in enumerate(group): + c.hierarchy = ((c.path.rpartition(".")[0], "Test.CompiledClass" + str(i)),) + c.hierarchy + by_path = {c.path: c for c in parts} + atoms, patterns = functional_atoms(parts, wiring, views) + self.assertEqual(len(atoms), 2) + signatures = [channel_signature(atom, by_path, wiring, views, patterns) for atom in atoms] + self.assertIsNotNone(signatures[0]) + self.assertEqual(signatures[0], signatures[1]) + changed = dict(wiring) + changed[second[1].path, "1"] = "distinct_output" + self.assertNotEqual(signatures[1], channel_signature(atoms[1], by_path, changed, views, patterns)) + second[0].hierarchy = () + self.assertIsNone(channel_signature(atoms[1], by_path, wiring, views, patterns)) + + def test_declared_supply_roles_exclude_anonymously_named_rails(self) -> None: + parts, views, wiring = self.amplifier() + signals = signal_nets(parts, wiring) + self.assertNotIn("common_positive", signals) + self.assertNotIn("common_return", signals) + self.assertIn("amp_output", signals) + + def test_split_prefers_fewer_signal_boundaries_over_component_midpoint(self) -> None: + # A-B-C is a complete signal island; D is isolated. Splitting in the + # middle would cut the actual path even though it balances pin count. + parts = [part(p, {"1": "sig", "2": "other", "3": "gnd"}) for p in ("a", "b", "c", "d")] + views = {p.path: generic(p) for p in parts} + wiring = {("a", "1"): "ab", ("b", "1"): "ab", ("b", "2"): "bc", ("c", "1"): "bc"} + for p in parts: + wiring[p.path, "3"] = "shared_return" + placed = [(p, 30 + i * 50, 70, 0) for i, p in enumerate(parts)] + split = split_group(placed, views, wiring) + assert split is not None + left, right = split + self.assertEqual([e[0].path for e in left], ["a", "b", "c"]) + self.assertEqual([e[0].path for e in right], ["d"]) + + def test_feedback_diodes_cannot_share_cross_net_escape_endpoint(self) -> None: + from .KiCadSchematicPlacement import escape_conflicts, _score + + amp = part("packed.ic", {"1": "outa", "2": "inna", "3": "inpa", "5": "inpb", "6": "innb", "7": "outb"}) + d9 = part("control.err_sink.diode", {"1": "cathode", "2": "anode"}, "Device:D") + d8 = part("control.err_source.diode", {"1": "cathode", "2": "anode"}, "Device:D") + # Real D9/D8 geometry from the native SMU failure: a 10.16 mm + # pin-tip gap lets opposite 5.08 mm escapes touch exactly. + definition = node( + "symbol", "Device:D", node("symbol", "D_0_1", node("rectangle", node("start", -1, 1), node("end", 1, -1))) + ) + views = { + amp.path: generic(amp), + d9.path: SymbolView(definition, [("1", 3.81, 0, 180), ("2", -3.81, 0, 0)], "Device:D"), + d8.path: SymbolView(definition, [("1", -3.81, 0, 0), ("2", 3.81, 0, 180)], "Device:D"), + } + wiring = { + (amp.path, "1"): "out0", + (amp.path, "2"): "negative", + (amp.path, "3"): "signal0", + (amp.path, "7"): "out1", + (amp.path, "6"): "negative", + (amp.path, "5"): "signal1", + (d9.path, "1"): "out0", + (d9.path, "2"): "negative", + (d8.path, "1"): "negative", + (d8.path, "2"): "out1", + } + touching = [(d9, 48.4, 56.16, 0), (d8, 66.18, 56.16, 0)] + safe = [(d9, 48.4, 56.16, 0), (d8, 66.18, 61.24, 0)] + self.assertGreater(escape_conflicts(touching, views, wiring), 0) + self.assertEqual(escape_conflicts(safe, views, wiring), 0) + self.assertLess(_score(safe, views, wiring), _score(touching, views, wiring)) + pages = place_group([amp, d9, d8], views, wiring) + for page in pages: + self.assertEqual(escape_conflicts(page, views, wiring), 0) + shared = dict(wiring) + shared[d9.path, "1"] = shared[d8.path, "1"] + self.assertEqual(escape_conflicts(touching, views, shared), 0) + + def test_packing_reserves_mcu_header_external_label_corridors(self) -> None: + from .KiCadSchematicPlacement import packing_bounds + + mcu = part("mcu.ic", {"1": "uart_tx", "2": "uart_rx", "3": "gnd"}) + header = part("header.conn", {"1": "a", "2": "b"}) + wiring = { + (mcu.path, "1"): "uart.tx", + (header.path, "1"): "uart.tx", + (mcu.path, "2"): "uart.rx", + (header.path, "2"): "uart.rx", + (mcu.path, "3"): "gnd", + } + mcu.net_labels = {"1": "serial.interface.transmit", "2": "serial.interface.receive", "3": "gnd"} + header.net_labels = {"1": mcu.net_labels["1"], "2": mcu.net_labels["2"]} + views = {c.path: generic(c) for c in (mcu, header)} + pages = place_group([mcu, header], views, wiring) + for page in pages: + for i, entry in enumerate(page): + for other in page[i + 1 :]: + self.assertFalse( + _overlap(packing_bounds([entry], views, wiring), packing_bounds([other], views, wiring)) + ) + self.assertEqual(pages, place_group([header, mcu], views, wiring)) + + def test_packing_does_not_reserve_unrendered_internal_label_wall(self) -> None: + from .KiCadSchematicPlacement import packing_bounds, atom_bounds + + a = part("a", {"1": "a", "2": "b"}) + b = part("b", {"1": "a", "2": "b"}) + views = {c.path: passive_view("Device:R") for c in (a, b)} + wiring = {(a.path, "1"): "inner", (b.path, "1"): "inner"} + a.net_labels = b.net_labels = {"1": "long_internal_connection" * 8} + entries = [(a, 40, 100, 90), (b, 80, 100, 270)] + bound = packing_bounds(entries, views, wiring) + # The internal label would be over 200 mm wide; packing only needs + # bodies/fields and exact pin escapes because this net is inside atom. + self.assertLess(bound[2] - bound[0], 100) + wiring["outside", "1"] = "inner" + outside = packing_bounds(entries, views, wiring) + self.assertGreater(outside[2] - outside[0], bound[2] - bound[0] + 100) + + def test_indicator_pairs_are_inline_atomic_even_when_entire_group_is_two_terminal(self) -> None: + from .KiCadSchematicLayout import pins + + for count in (1, 4): + parts: list[PhysicalComponent] = [] + views: dict[str, SymbolView] = {} + wiring: dict[PinKey, str] = {} + pairs: list[tuple[PhysicalComponent, PhysicalComponent]] = [] + for i in range(count): + led = part(f"branch[{i}].led", {"1": "a", "2": "k"}, "Device:LED") + resistor = part(f"branch[{i}].resistor", {"1": "a", "2": "b"}, "Device:R") + parts.extend((led, resistor)) + pairs.append((led, resistor)) + views[led.path] = passive_view("Device:LED") + views[resistor.path] = passive_view("Device:R") + wiring[led.path, "1"] = wiring[resistor.path, "1"] = f"inner{i}" + wiring[led.path, "2"] = "return" + wiring[resistor.path, "2"] = f"input{i}" + pages = place_group(parts, views, wiring) + self.assertEqual(sorted(e[0].path for page in pages for e in page), sorted(p.path for p in parts)) + for led, resistor in pairs: + owning = [page for page in pages if any(e[0] is led for e in page)] + self.assertEqual(len(owning), 1) + entries = {e[0].path: e for e in owning[0]} + self.assertIn(resistor.path, entries) + a, b = entries[led.path], entries[resistor.path] + self.assertEqual(a[2], b[2]) + self.assertLess(a[1], b[1]) + # Both actual shared terminals face each other horizontally. + p1 = next(pin for pin in pins(views[led.path], *a[1:]) if pin[0] == "1") + p2 = next(pin for pin in pins(views[resistor.path], *b[1:]) if pin[0] == "1") + self.assertEqual(p1[3], 180) + self.assertEqual(p2[3], 0) + + def test_route_guard_rejects_new_fallback_endpoint(self) -> None: + from unittest.mock import patch + from .KiCadSchematicPlacement import _route_guard + + parts, views, wiring = self.amplifier() + baseline: list[Placement] = [(parts[0], 0, 0, 0), (parts[1], 40, 0, 90)] + candidate: list[Placement] = [(parts[0], 0, 0, 0), (parts[1], 30, 0, 90)] + # Even an equal failure count is insufficient if a formerly visible + # endpoint becomes a different label fallback. + old: RouteResult = ([], {}, [((parts[0].path, "1"), "amp_output")]) + new: RouteResult = ([], {}, [((parts[1].path, "1"), "amp_output")]) + with patch("edg.electronics_model.KiCadSchematicLayout.route_local", side_effect=[old, new]): + selected, evidence = _route_guard(baseline, candidate, views, wiring) + self.assertEqual(selected, baseline) + self.assertFalse(evidence["accepted"]) + self.assertEqual(evidence["route_trials"], 2) + + def test_route_guard_translates_both_local_templates_into_router_window(self) -> None: + from unittest.mock import patch + from .KiCadSchematicPlacement import _route_guard, atom_bounds + + parts, views, wiring = self.amplifier() + baseline: list[Placement] = [(parts[0], 0, 0, 0), (parts[1], 0, -30.48, 90)] + candidate: list[Placement] = [(parts[0], 0, 0, 0), (parts[1], 2.54, -30.48, 90)] + with patch("edg.electronics_model.KiCadSchematicLayout.route_local", return_value=([], {}, [])) as route: + _route_guard(baseline, candidate, views, wiring) + trials = [call.args[0] for call in route.call_args_list] + self.assertEqual(len(trials), 2) + shifts = [] + for original, trial in zip((baseline, candidate), trials): + box = atom_bounds(trial, views) + self.assertGreater(box[0], 20) + self.assertGreater(box[1], 55) + shifts.append((trial[0][1] - original[0][1], trial[0][2] - original[0][2])) + self.assertEqual(shifts[0], shifts[1]) + + def test_divider_uses_vertical_resistor_pair_beside_owner(self) -> None: + owner = part("reg.ic", {"1": "fb", "2": "gnd", "3": "vin"}) + hi = part("reg.top", {"1": "a", "2": "b"}, "Device:R") + lo = part("reg.bottom", {"1": "a", "2": "b"}, "Device:R") + parts = [owner, hi, lo] + views = {owner.path: generic(owner), hi.path: passive_view("Device:R"), lo.path: passive_view("Device:R")} + wiring = { + (owner.path, "1"): "fb", + (owner.path, "2"): "gnd", + (owner.path, "3"): "input", + (hi.path, "1"): "output", + (hi.path, "2"): "fb", + (lo.path, "1"): "fb", + (lo.path, "2"): "gnd", + } + page = place_group(parts, views, wiring)[0] + placements = {e[0].path: e for e in page} + self.assertGreater(placements[hi.path][1], placements[owner.path][1]) + self.assertGreater(placements[lo.path][1], placements[owner.path][1]) + self.assertLess(placements[hi.path][2], placements[lo.path][2]) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_led_buck.py b/edg/electronics_model/test_schematic_led_buck.py new file mode 100644 index 000000000..7eaf811fa --- /dev/null +++ b/edg/electronics_model/test_schematic_led_buck.py @@ -0,0 +1,416 @@ +"""Verified LED-buck topology, bounded real routing, and cached scene rollback.""" + +from __future__ import annotations +from typing import Any, Mapping, Optional +from .KiCadSchematicTypes import Point, PinKey, PinNets, Placement, Placements, Views, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SymbolView, SchematicExport + +import copy +import hashlib +from .KiCadSchematicCircuits import SchematicCircuit, CircuitStage +from .KiCadSchematicExporter import SymbolResolver +from .KiCadSchematicRouting import Router +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from .test_schematic_functional_placement import part, passive_view +from .KiCadSchematicExporter import ( + KiCadSchematicExporter, + SchematicExportOptions, + SchematicPlacement, + generic, + _PreparedBoard, + _RegionDrawing, +) +from .KiCadSchematicLayout import freeze_annotations, route_local +from .KiCadSchematicPlanner import SchematicRegion +from .KiCadSchematicPower import ( + led_buck_topology, + led_buck_candidates, + compare_led_buck_variants, + power_template, +) +from .KiCadSchematicOrientation import passive_orientation_rank + +MODEL = "edg.parts.power.LedDriver_Tps92200.Tps92200_Device" + + +def led_buck_fixture() -> ( + tuple[tuple[str, ...], dict[str, PhysicalComponent], dict[str, SymbolView], dict[PinKey, str]] +): + roles = {"1": "fb", "2": "dim", "3": "gnd", "4": "vin", "5": "sw", "6": "boot"} + ic = part("driver.ic", roles) + ic.hierarchy = ((ic.path, MODEL),) + parts = {ic.path: ic} + views = {ic.path: generic(ic)} + nets = {(ic.path, n): role for n, role in roles.items()} + for path, lib_id, terminals in ( + ("bootstrap", "Device:C", ("boot", "sw")), + ("sense", "Device:R", ("gnd", "fb")), + ("coil", "Device:L", ("sw", "out")), + ("input_cap", "Device:C", ("vin", "gnd")), + ("output_cap", "Device:C", ("out", "gnd")), + ): + parts[path] = part(path, {"1": "a", "2": "b"}, lib_id) + views[path] = passive_view(lib_id) + nets[path, "1"], nets[path, "2"] = terminals + # Physical cathode terminal outside this region witnesses the LED load. + nets["led_connector", "2"] = "fb" + return tuple(sorted(parts)), parts, views, nets + + +def incumbent(parts: Mapping[str, PhysicalComponent], views: Views, nets: PinNets) -> list[Placement]: + entries = power_template(tuple(sorted(parts)), parts, views, nets) + assert entries is not None + return freeze_annotations([(c, x + 180, y + 100, a) for c, x, y, a in entries], views) + + +class LedBuckTopologyTest(unittest.TestCase): + def test_verified_bootstrap_sense_banks_and_return_witness(self) -> None: + members, parts, views, nets = led_buck_fixture() + t, reason = led_buck_topology(members, parts, views, nets) + self.assertIsNone(reason) + assert t is not None + self.assertEqual((t["bootstrap"], t["sense"], t["coil"]), ("bootstrap", "sense", "coil")) + self.assertEqual(t["input_caps"], ["input_cap"]) + self.assertEqual(t["output_caps"], ["output_cap"]) + self.assertEqual(t["load_return_witnesses"], [("led_connector", "2")]) + self.assertEqual(t["boot"], "boot") + + def test_similar_roles_on_unverified_model_do_not_select_template(self) -> None: + members, parts, views, nets = led_buck_fixture() + parts["driver.ic"].hierarchy = (("driver.ic", "custom.Tps92200_Lookalike"),) + self.assertEqual(led_buck_topology(members, parts, views, nets), (None, None)) + + def test_unique_bootstrap_and_sense_are_required(self) -> None: + for original in ("bootstrap", "sense"): + with self.subTest(original=original): + members, parts, views, nets = led_buck_fixture() + duplicate = copy.deepcopy(parts[original]) + duplicate.path = original + "_duplicate" + parts[duplicate.path] = duplicate + views[duplicate.path] = views[original] + for n in duplicate.pins: + nets[duplicate.path, n] = nets[original, n] + t, reason = led_buck_topology(tuple(sorted(parts)), parts, views, nets) + self.assertIsNone(t) + assert reason is not None + self.assertIn("ambiguous", reason) + + def test_virtual_load_is_allowed_but_terminal_nets_must_be_distinct(self) -> None: + members, parts, views, nets = led_buck_fixture() + del nets["led_connector", "2"] + topology, reason = led_buck_topology(members, parts, views, nets) + self.assertIsNone(reason) + assert topology is not None + self.assertEqual(topology["load_return_witnesses"], []) + nets["driver.ic", "6"] = "sw" + reason = led_buck_topology(members, parts, views, nets)[1] + assert reason is not None + self.assertIn("not distinct", reason) + + def test_parallel_modeled_pads_preserve_identity_and_must_agree(self) -> None: + members, parts, views, nets = led_buck_fixture() + parts["driver.ic"].pins["7"] = "sw" + nets["driver.ic", "7"] = "sw" + t, reason = led_buck_topology(members, parts, views, nets) + assert t is not None + self.assertIsNone(reason) + before = copy.deepcopy(parts["driver.ic"].pins) + for _, entries in led_buck_candidates(t, parts, views, nets): + self.assertEqual(next(c.pins for c, _, _, _ in entries if c.path == "driver.ic"), before) + nets["driver.ic", "7"] = "different" + reason = led_buck_topology(members, parts, views, nets)[1] + assert reason is not None + self.assertIn("roles do not match", reason) + + def test_authored_stages_and_nonconverter_templates_take_precedence(self) -> None: + for template, stages in (("generic", ()), ("auto", ("stage",))): + members, parts, views, nets = led_buck_fixture() + parts["driver.ic"].functional_circuit = SchematicCircuit( + "test", + "Test", + "Test", + members, + template=template, + stages=tuple(CircuitStage(stage, members) for stage in stages), + ) + reason = led_buck_topology(members, parts, views, nets)[1] + assert reason is not None + self.assertIn("take precedence", reason) + + def test_candidates_are_finite_deterministic_complete_and_preserve_inputs(self) -> None: + args = led_buck_fixture() + t, _ = led_buck_topology(*args) + assert t is not None + before = copy.deepcopy(args) + candidates = led_buck_candidates(t, *args[1:]) + self.assertEqual(candidates, led_buck_candidates(t, *args[1:])) + self.assertEqual(len(candidates), 4) + for _, entries in candidates: + self.assertEqual({c.path for c, _, _, _ in entries}, set(args[0])) + positions = {c.path: (x, y, a) for c, x, y, a in entries} + self.assertLess(positions["driver.ic"][0], positions["bootstrap"][0]) + self.assertLess(positions["bootstrap"][0], positions["coil"][0]) + self.assertLess(positions["sense"][0], positions["driver.ic"][0]) + self.assertEqual(args[3], before[3]) + self.assertEqual({p: c.pins for p, c in args[1].items()}, {p: c.pins for p, c in before[1].items()}) + + +class LedBuckRoutingTest(unittest.TestCase): + def compare( + self, router: Router = route_local, *, source_annotations: Optional[Mapping[str, Optional[Point]]] = None + ) -> tuple[list[Placement], RouteResult, tuple[list[Placement], RouteResult, dict[str, Any]]]: + members, parts, views, nets = led_buck_fixture() + placed = incumbent(parts, views, nets) + baseline = route_local(placed, views, nets) + selected, route, evidence = compare_led_buck_variants( + placed, views, nets, baseline, router, source_annotations=source_annotations + ) + assert evidence is not None + return placed, baseline, (selected, route, evidence) + + def test_real_routes_reduce_crossings_and_weighted_cost_without_fallbacks(self) -> None: + seen = [] + + def router(placed: Placements, views: Views, pin_nets: PinNets, *, strategy: str = "baseline") -> RouteResult: + seen.append(placed) + return route_local(placed, views, pin_nets, strategy=strategy) + + placed, baseline, (selected, route, evidence) = self.compare(router) + self.assertTrue(evidence["accepted"]) + self.assertEqual(len(evidence["trials"]), 4) + self.assertLessEqual(evidence["route_trials"], 4) + self.assertGreater(evidence["route_trials"], 0) + self.assertEqual(len(seen), evidence["route_trials"]) + self.assertLess(evidence["after"]["crossings"], evidence["before"]["crossings"]) + self.assertLess( + evidence["after"]["length_mm"] + 2.54 * evidence["after"]["bends"], + evidence["before"]["length_mm"] + 2.54 * evidence["before"]["bends"], + ) + self.assertEqual(route[2], []) + self.assertEqual({c.path: c.pins for c, _, _, _ in placed}, {c.path: c.pins for c, _, _, _ in selected}) + _, _, repeated = self.compare() + self.assertEqual(evidence, repeated[2]) + + def test_every_candidate_keeps_authored_field_coordinates(self) -> None: + seen = [] + + def router(placed: Placements, views: Views, pin_nets: PinNets, *, strategy: str = "baseline") -> RouteResult: + seen.append(placed) + return route_local(placed, views, pin_nets, strategy=strategy) + + authored = {"sense": (25.4, 50.8)} + self.compare(router, source_annotations=authored) + self.assertTrue(seen) + for entries in seen: + self.assertEqual(next(c.annotation for c, _, _, _ in entries if c.path == "sense"), authored["sense"]) + + def test_new_failed_endpoints_retain_cached_incumbent(self) -> None: + def router(placed: Placements, views: Views, pin_nets: PinNets, *, strategy: str = "baseline") -> RouteResult: + wires, endpoints, failed = route_local(placed, views, pin_nets, strategy=strategy) + return wires, endpoints, failed + [(("driver.ic", "6"), "boot")] + + placed, baseline, (selected, route, evidence) = self.compare(router) + self.assertIs(selected, placed) + self.assertIs(route, baseline) + self.assertFalse(evidence["accepted"]) + self.assertEqual(len(evidence["trials"]), 4) + self.assertLessEqual(evidence["route_trials"], 4) + routed = [t for t in evidence["trials"] if "metrics" in t] + self.assertEqual(len(routed), evidence["route_trials"]) + self.assertTrue(routed) + self.assertTrue(all(t["reason"] == "new failed endpoints" for t in routed)) + + def test_collision_rejection_does_not_call_router(self) -> None: + clean = dict(escape_conflicts=0, collisions=0, collision_pairs=[], clipped=False) + collision = dict(clean, collisions=1, collision_pairs=[("sense", "driver.ic")]) + router = Mock(side_effect=AssertionError("colliding candidate must not route")) + with patch("edg.electronics_model.KiCadSchematicOrientation._geometry", side_effect=[clean] + [collision] * 4): + placed, baseline, (selected, route, evidence) = self.compare(router) + self.assertIs(selected, placed) + self.assertIs(route, baseline) + self.assertEqual(evidence["route_trials"], 0) + self.assertTrue(all("collision" in t["reason"] for t in evidence["trials"])) + + def test_ties_retain_incumbent_after_complete_bounded_coverage(self) -> None: + metric = dict( + primary_fallbacks=0, crossings=0, unrelated_intrusions=0, length_mm=100, bends=1, visual_conflicts=0 + ) + with patch("edg.electronics_model.KiCadSchematicOrientation.orientation_metrics", return_value=metric): + placed, baseline, (selected, route, evidence) = self.compare() + self.assertIs(selected, placed) + self.assertIs(route, baseline) + self.assertEqual(len(evidence["trials"]), 4) + self.assertLessEqual(evidence["route_trials"], 4) + self.assertGreater(evidence["route_trials"], 0) + self.assertFalse(evidence["accepted"]) + + +class LedBuckSceneGateTest(unittest.TestCase): + def prepared(self) -> tuple[_PreparedBoard, _RegionDrawing]: + _, parts, views, nets = led_buck_fixture() + placed = incumbent(parts, views, nets) + route = route_local(placed, views, nets) + spec = SchematicRegion("region", "LED driver", "(root)", tuple(parts), (0, 0, 180, 100)) + drawing = _RegionDrawing( + spec, placed, route[0], route[2], {"selected": "baseline"}, (), (), route, {p: None for p in parts} + ) + board = _PreparedBoard( + "(root)", + "board_fixture", + "root_fixture", + views, + nets, + {net: net for net in nets.values()}, + {"region": drawing}, + ) + return board, drawing + + def test_authored_placements_are_not_moved_even_when_rotation_is_unlocked(self) -> None: + board, drawing = self.prepared() + options = SchematicExportOptions( + "fixture", placements={"driver.ic": SchematicPlacement("LED driver", 150, 100, lock_rotation=False)} + ) + exporter = KiCadSchematicExporter() + with patch.object( + exporter, "_serialize_prepared", side_effect=AssertionError("locked region must not serialize") + ): + boards, fingerprint = exporter._prepare_led_bucks( + [board], "fingerprint", hashlib.sha256(b"prefix"), SymbolResolver(()), [], options + ) + self.assertIs(boards[0].regions["region"], drawing) + self.assertEqual(fingerprint, "fingerprint") + self.assertEqual(drawing.routing["led_buck"]["route_trials"], 0) + self.assertIn("authored placements", drawing.routing["led_buck"]["reason"]) + + def test_new_serialized_finding_rolls_back_exact_cached_region(self) -> None: + board, drawing = self.prepared() + exporter = KiCadSchematicExporter() + options = SchematicExportOptions("fixture", optimize_routes=False) + baseline_bundle = SchematicExport({"board_fixture.kicad_sch": ""}, []) + candidate_bundle = SchematicExport({"board_fixture.kicad_sch": ""}, []) + + def findings(bundle: SchematicExport) -> dict[str, dict[tuple[str, ...], float]]: + return { + "(root)": {} if bundle is baseline_bundle else {("text_body_contact", "sense:Value", "driver.ic"): 1.0} + } + + with ( + patch.object(exporter, "_serialize_prepared", side_effect=[baseline_bundle, candidate_bundle]) as serialize, + patch.object(exporter, "_passive_scene_issues", side_effect=findings), + patch.object(exporter, "_prepared_fingerprint", return_value="candidate_fingerprint"), + patch.object(exporter, "_region_geometry", return_value=((0, 0, 180, 100), (), ())), + ): + boards, fingerprint = exporter._prepare_led_bucks( + [board], "fingerprint", hashlib.sha256(b"prefix"), SymbolResolver(()), [], options + ) + self.assertEqual(serialize.call_count, 2) + self.assertIs(boards[0].regions["region"], drawing) + self.assertEqual(fingerprint, "fingerprint") + evidence = drawing.routing["led_buck"] + self.assertFalse(evidence["accepted"]) + self.assertEqual(evidence["after"], evidence["before"]) + self.assertIn("serialized scene", evidence["rollback_reason"]) + self.assertIn("attempted_after", evidence) + + def test_successful_serialized_gate_keeps_selected_region(self) -> None: + board, drawing = self.prepared() + exporter = KiCadSchematicExporter() + options = SchematicExportOptions("fixture", optimize_routes=False) + with ( + patch.object( + exporter, "_serialize_prepared", return_value=SchematicExport({"board_fixture.kicad_sch": ""}, []) + ), + patch.object(exporter, "_passive_scene_issues", return_value={"(root)": {}}), + patch.object(exporter, "_prepared_fingerprint", return_value="candidate_fingerprint"), + patch.object(exporter, "_region_geometry", return_value=((0, 0, 160, 90), (), ())), + ): + boards, fingerprint = exporter._prepare_led_bucks( + [board], "fingerprint", hashlib.sha256(b"prefix"), SymbolResolver(()), [], options + ) + selected = boards[0].regions["region"] + self.assertIsNot(selected, drawing) + self.assertTrue(selected.routing["led_buck"]["accepted"]) + self.assertEqual(selected.routing["led_buck"]["content_bounds"], (0, 0, 160, 90)) + self.assertEqual(selected.spec.bounds, drawing.spec.bounds) + from .KiCadSchematicRouting import route_metrics + + self.assertEqual(selected.routing["after"], route_metrics(selected.wires, selected.failed_routes)) + self.assertEqual(fingerprint, "candidate_fingerprint") + self.assertEqual(selected.spec.components, drawing.spec.components) + self.assertLess( + passive_orientation_rank(selected.routing["led_buck"]["after"]), + passive_orientation_rank(selected.routing["led_buck"]["before"]), + ) + + def test_more_sheets_roll_back_even_when_serialized_scene_is_clean(self) -> None: + board, drawing = self.prepared() + exporter = KiCadSchematicExporter() + baseline_bundle = SchematicExport({"board_fixture.kicad_sch": ""}, []) + candidate_bundle = SchematicExport( + {"board_fixture.kicad_sch": "", "board_fixture_continuation.kicad_sch": ""}, [] + ) + with ( + patch.object(exporter, "_serialize_prepared", side_effect=[baseline_bundle, candidate_bundle]), + patch.object(exporter, "_passive_scene_issues", return_value={"(root)": {}}), + patch.object(exporter, "_prepared_fingerprint", return_value="candidate_fingerprint"), + patch.object(exporter, "_region_geometry", return_value=((0, 0, 180, 100), (), ())), + ): + boards, fingerprint = exporter._prepare_led_bucks( + [board], + "fingerprint", + hashlib.sha256(b"prefix"), + SymbolResolver(()), + [], + SchematicExportOptions("fixture", optimize_routes=False), + ) + self.assertIs(boards[0].regions["region"], drawing) + self.assertEqual(fingerprint, "fingerprint") + evidence = drawing.routing["led_buck"] + self.assertFalse(evidence["accepted"]) + self.assertIn("fragmentation", evidence["rollback_reason"]) + self.assertEqual(evidence["scene_gate"]["before_sheets"], 1) + self.assertEqual(evidence["scene_gate"]["after_sheets"], 2) + + def test_route_order_baseline_retains_incumbent_strategy_and_final_metrics(self) -> None: + from .KiCadSchematicRouting import route_metrics + + board, drawing = self.prepared() + drawing.routing["selected"] = "tree_search" + exporter = KiCadSchematicExporter() + + def keep_supplied_route( + entries: Placements, views: Views, nets: PinNets, route: RouteResult, router: Router + ) -> tuple[RouteResult, dict[str, str]]: + return route, {"selected": "baseline"} + + with ( + patch.object( + exporter, "_serialize_prepared", return_value=SchematicExport({"board_fixture.kicad_sch": ""}, []) + ), + patch.object(exporter, "_passive_scene_issues", return_value={"(root)": {}}), + patch.object(exporter, "_prepared_fingerprint", return_value="candidate_fingerprint"), + patch.object(exporter, "_region_geometry", return_value=((0, 0, 180, 100), (), ())), + patch( + "edg.electronics_model.KiCadSchematicRouting.optimize_fixed_routes", side_effect=keep_supplied_route + ) as order, + ): + boards, _ = exporter._prepare_led_bucks( + [board], + "fingerprint", + hashlib.sha256(b"prefix"), + SymbolResolver(()), + [], + SchematicExportOptions("fixture"), + ) + selected = boards[0].regions["region"] + self.assertTrue(selected.routing["led_buck"]["accepted"]) + self.assertEqual(order.call_count, 1) + self.assertEqual(selected.routing["selected"], "tree_search") + self.assertEqual(selected.routing["after"], route_metrics(selected.wires, selected.failed_routes)) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_orientation.py b/edg/electronics_model/test_schematic_orientation.py new file mode 100644 index 000000000..3edcf47f6 --- /dev/null +++ b/edg/electronics_model/test_schematic_orientation.py @@ -0,0 +1,259 @@ +"""Fairness, immutable identities, source-owned locks and cached routing.""" + +from __future__ import annotations +from typing import Any, cast +from ..core import CompiledDesign +from .KiCadSchematicTypes import PinKey, PinNets, Placement, Placements, Views, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +from typing_extensions import override +import copy +import unittest +from unittest.mock import patch + +from .KiCadSchematicExporter import node, SchematicPlacement, SchematicExportOptions +from .KiCadSchematicOrientation import optimize_orientations +from .KiCadSchematicLayout import route_local + + +class OrientationTest(unittest.TestCase): + def fixture(self, count: int = 1) -> tuple[list[Placement], dict[str, SymbolView], dict[PinKey, str]]: + entries, views, nets = [], {}, {} + for i in range(count): + c = PhysicalComponent( + f"part{i:03}", f"D{i}", "Fixture:Pad", "polar", {"1": "anode", "2": "cathode"}, None, "g" + ) + entries.append((c, 50.0 + i * 10, 70.0, 0)) + views[c.path] = SymbolView(node("symbol"), [("1", -1.0, 0.0, 0), ("2", 1.0, 0.0, 180)], "Fixture:Polar") + nets[c.path, "1"] = "positive" + nets[c.path, "2"] = "negative" + return entries, views, nets + + def metric(self, placed: Placements, *args: object) -> dict[str, float]: + # Rotating the final device is beneficial even after >32 early paths. + return dict( + primary_fallbacks=0, + crossings=0, + unrelated_intrusions=0, + bends=0, + detour_mm=0, + length_mm=100 - sum(a == 180 for _, _, _, a in placed), + visual_conflicts=0, + ) + + def geometry(self, *args: object) -> dict[str, int | bool]: + return dict(escape_conflicts=0, collisions=0, clipped=False) + + def test_every_path_gets_trial_without_starvation_and_two_sweep_limit(self) -> None: + entries, views, nets = self.fixture(40) + original = copy.deepcopy((entries, views, nets)) + calls = [] + baseline: RouteResult = ([], {}, []) + + def router(*args: object) -> RouteResult: + calls.append(args) + return baseline + + with ( + patch("edg.electronics_model.KiCadSchematicOrientation._geometry", self.geometry), + patch("edg.electronics_model.KiCadSchematicOrientation.orientation_metrics", self.metric), + ): + placed, route, evidence = optimize_orientations(entries, views, nets, router, baseline=baseline) + self.assertEqual(len(calls), 80) + self.assertEqual([trial["path"] for trial in evidence["trials"][:40]], sorted(c.path for c, _, _, _ in entries)) + self.assertTrue(all(a == 180 for _, _, _, a in placed)) + self.assertEqual((entries, views, nets), original) + self.assertEqual([(x, y) for _, x, y, _ in placed], [(x, y) for _, x, y, _ in entries]) + self.assertEqual(route, baseline) + + def test_lock_and_explicit_annotation_and_ties_preserve_incumbent(self) -> None: + entries, views, nets = self.fixture(2) + entries[1][0].annotation = (66.0, 88.0) + with ( + patch("edg.electronics_model.KiCadSchematicOrientation._geometry", self.geometry), + patch("edg.electronics_model.KiCadSchematicOrientation.orientation_metrics", self.metric), + ): + placed, _, evidence = optimize_orientations( + entries, views, nets, lambda *args: ([], {}, []), locked={"part000"} + ) + self.assertEqual([a for _, _, _, a in placed], [0, 180]) + self.assertEqual(placed[1][0].annotation, (66.0, 88.0)) + self.assertFalse(evidence["eligibility"][0]["eligible"]) + self.assertEqual(len(evidence["trials"]), 2) + self.assertFalse(evidence["trials"][-1]["selected"]) + + def test_new_failed_endpoint_and_geometry_overflow_rejected(self) -> None: + entries, views, nets = self.fixture() + baseline: RouteResult = ([], {}, []) + with ( + patch("edg.electronics_model.KiCadSchematicOrientation._geometry", self.geometry), + patch("edg.electronics_model.KiCadSchematicOrientation.orientation_metrics", self.metric), + ): + placed, _, evidence = optimize_orientations( + entries, views, nets, lambda *args: ([], {}, [(("part000", "1"), "positive")]), baseline=baseline + ) + self.assertEqual(placed[0][3], 0) + self.assertEqual(evidence["trials"][0]["reason"], "new failed endpoints") + with ( + patch("edg.electronics_model.KiCadSchematicOrientation._geometry", self.geometry), + patch("edg.electronics_model.KiCadSchematicOrientation.orientation_metrics", self.metric), + ): + _, _, evidence = optimize_orientations( + entries, + views, + nets, + lambda *args: baseline, + baseline=baseline, + region_bounds=lambda *args: (0, 0, 400, 240), + ) + self.assertEqual(evidence["trials"][0]["reason"], "routed region page overflow") + + def test_real_router_shortens_polar_parts_without_swapping_pins(self) -> None: + entries, views, nets = self.fixture(2) + entries = [(entries[0][0], 50.0, 70.0, 0), (entries[1][0], 90.0, 70.0, 0)] + # Parallel physical pads remain distinct identities on the same net. + entries[1][0].pins["3"] = "anode_parallel" + views["part001"].pins.append(("3", -1.0, 2.54, 0)) + nets["part001", "3"] = "positive" + original = copy.deepcopy((entries, views, nets)) + actual, route, report = optimize_orientations(entries, views, nets, route_local) + self.assertEqual((entries, views, nets), original) + self.assertLess(report["after"]["length_mm"], report["before"]["length_mm"]) + self.assertEqual(route[2], []) + self.assertEqual(set(route[1]), set(nets)) + self.assertEqual([(x, y) for _, x, y, _ in actual], [(x, y) for _, x, y, _ in entries]) + repeated = optimize_orientations(entries, views, nets, route_local) + self.assertEqual(repeated, (actual, route, report)) + + def test_converter_primary_fallbacks_use_verified_core_endpoints(self) -> None: + from .KiCadSchematicCircuits import SchematicCircuit, CircuitBoundary + from .test_schematic_bridge_variants import bridge + from .test_schematic_functional_placement import part, passive_view + from .KiCadSchematicOrientation import orientation_metrics + from .KiCadSchematicPower import topology_primary_endpoints + + _, by_path, views, nets = bridge() + bank = part("bank", {"1": "supply", "2": "return"}, "Device:C") + by_path["bank"] = bank + views["bank"] = passive_view("Device:C") + nets["bank", "1"] = "rail1" + nets["bank", "2"] = "gnd" + endpoints = topology_primary_endpoints(list(by_path.values()), nets, views) + self.assertNotIn(("bank", "1"), endpoints["rail1"]) + self.assertIn(("coil", "1"), endpoints["sw1"]) + self.assertIn(("hi1", "1"), endpoints["hidrv1"]) + placed = [(c, 50 + i * 40, 70, 0) for i, c in enumerate(by_path.values())] + for c in by_path.values(): + c.functional_circuit = SchematicCircuit( + id="fixture", + title="Fixture", + summary="", + components=tuple(by_path), + boundaries=( + CircuitBoundary("bank", "1", "Rail", "input", "rail1"), + CircuitBoundary("bank", "2", "Signal", "output", "authored_signal"), + ), + ) + for failures, expected, noncore in ( + ([(("bank", "1"), "rail1")], 0, 1), + ([(("coil", "1"), "sw1")], 1, 0), + ([(("hi1", "1"), "hidrv1")], 1, 0), + ([(("bank", "1"), "authored_signal")], 1, 0), + ): + metric = orientation_metrics(placed, views, nets, ([], {}, failures)) + self.assertEqual(metric["primary_fallbacks"], expected) + self.assertEqual(metric["noncore_converter_fallbacks"], noncore) + # Removing the actual gate connectivity makes topology classification + # ambiguous/invalid; authored primary nets keep their original meaning. + nets["hi1", "1"] = "broken_gate" + metric = orientation_metrics(placed, views, nets, ([], {}, [(("bank", "1"), "rail1")])) + self.assertEqual(metric["primary_fallbacks"], 1) + + def test_public_boolean_validation_and_placement_compatibility(self) -> None: + self.assertTrue(SchematicPlacement("g", 1, 2).lock_rotation) + self.assertFalse(SchematicPlacement("g", 1, 2, 180, False, None, False).lock_rotation) + self.assertTrue(SchematicExportOptions("design").optimize_orientations) + with self.assertRaises(ValueError): + SchematicPlacement("g", 1, 2, lock_rotation=cast(bool, 1)) + with self.assertRaises(ValueError): + SchematicExportOptions("design", optimize_orientations=cast(bool, "yes")) + + +if __name__ == "__main__": + unittest.main() + + +class OrientationPipelineTest(unittest.TestCase): + compiled: CompiledDesign + + @classmethod + @override + def setUpClass(cls) -> None: + from ..core import ScalaCompiler + from ..electronics_interfaces.test_netlist import TestBasicCircuit + from .RefdesRefinementPass import RefdesRefinementPass + + cls.compiled = ScalaCompiler.compile(TestBasicCircuit) + cls.compiled.append_values(RefdesRefinementPass().run(cls.compiled)) + + def test_orientation_then_bridge_then_one_route_order_pass(self) -> None: + from .KiCadSchematicExporter import KiCadSchematicExporter + from .KiCadSchematicLayout import freeze_annotations + from .KiCadSchematicRouting import route_metrics + + calls = [] + cached = {} + + def orientations( + items: Placements, views: Views, nets: PinNets, router: object, **kwargs: Any + ) -> tuple[Placements, RouteResult, dict[str, Any]]: + calls.append("orientations") + route = kwargs["baseline"] + cached["oriented"] = route + return freeze_annotations(items, views), route, {"selected": "fixture"} + + def bridges( + items: Placements, views: Views, nets: PinNets, baseline: RouteResult, router: object, **kwargs: Any + ) -> tuple[Placements, RouteResult, dict[str, Any]]: + calls.append("bridge") + self.assertIs(baseline, cached["oriented"]) + self.assertEqual(set(kwargs["source_annotations"]), {c.path for c, _, _, _ in items}) + # A distinct cached result proves that downstream does not reroute + # the baseline or discard the selected variant's route object. + route = (list(baseline[0]), dict(baseline[1]), list(baseline[2])) + cached["bridge"] = route + return items, route, {"selected": "fixture"} + + def route_order( + items: Placements, views: Views, nets: PinNets, baseline: RouteResult, router: object + ) -> tuple[RouteResult, dict[str, Any]]: + calls.append("route_order") + self.assertIs(baseline, cached["bridge"]) + metrics = route_metrics(baseline[0], baseline[2]) + return baseline, dict(before=metrics, after=metrics, selected="fixture", candidates=1) + + with ( + patch("edg.electronics_model.KiCadSchematicOrientation.optimize_orientations", orientations), + patch("edg.electronics_model.KiCadSchematicPower.compare_bridge_variants", bridges, create=True), + patch("edg.electronics_model.KiCadSchematicRouting.optimize_fixed_routes", route_order), + ): + result = KiCadSchematicExporter().export(self.compiled, SchematicExportOptions("Pipeline")) + self.assertEqual(calls, ["orientations", "bridge", "route_order"] * (len(calls) // 3)) + self.assertGreater(len(calls), 0) + self.assertIn("bridge_comparison", result.files["routing.json"]) + with ( + patch( + "edg.electronics_model.KiCadSchematicOrientation.optimize_orientations", + side_effect=AssertionError("off"), + ), + patch( + "edg.electronics_model.KiCadSchematicPower.compare_bridge_variants", + side_effect=AssertionError("off"), + create=True, + ), + ): + disabled = KiCadSchematicExporter().export( + self.compiled, SchematicExportOptions("Pipeline", optimize_orientations=False) + ) + self.assertNotIn("bridge_comparison", disabled.files["routing.json"]) + self.assertNotIn('"orientation"', disabled.files["routing.json"]) diff --git a/edg/electronics_model/test_schematic_overview.py b/edg/electronics_model/test_schematic_overview.py new file mode 100644 index 000000000..60c8486b1 --- /dev/null +++ b/edg/electronics_model/test_schematic_overview.py @@ -0,0 +1,387 @@ +"""Overview relationships are witnessed presentation, never electrical wiring.""" + +from __future__ import annotations +from typing import Any +from pathlib import Path +from .KiCadSchematicTypes import SExpr +from .KiCadSchematicPlanner import SchematicSheetPlan + +import json +import unittest +from dataclasses import replace +import tempfile +import shutil +import subprocess +import sexpdata +from .KiCadSchematicExporter import _PreparedBoard, _RegionDrawing + +from .KiCadSchematicOverview import ( + SchematicOverview, + SchematicOverviewBlock, + SchematicOverviewLink, + build_overviews, + render_overview, +) +from .KiCadSchematicPlanner import SchematicRegion, SchematicSheetPlanner +from .KiCadSchematicExporter import KiCadSchematicExporter, SchematicExportOptions, children, uid + + +def fixture(count: int = 3, scope: str = "board") -> tuple[_PreparedBoard, SchematicSheetPlan]: + regions = tuple( + SchematicRegion(scope + str(i), "Function " + str(i), scope, (scope + str(i) + ".part",), (0, 0, 50, 20)) + for i in range(count) + ) + plan = SchematicSheetPlanner().plan_regions(regions, "fingerprint", assignments={r.id: r.title for r in regions}) + board = _PreparedBoard( + scope=scope, + prefix=scope, + root_id=scope, + views={}, + pin_nets={}, + names={}, + regions={r.id: _RegionDrawing(r, [], [], []) for r in regions}, + net_regions={ + "gnd": set(r.id for r in regions), + "supply": set(r.id for r in regions), + "data": set(r.id for r in regions[:2]), + }, + ) + return board, plan + + +class SchematicOverviewTest(unittest.TestCase): + def test_data_contract_and_malformed_inputs(self) -> None: + data = { + "blocks": [dict(sheet="Function 0", title="Source", summary="Power entry", column=0, row=1)], + "links": [dict(source="Function 0", target="Function 1", label="Supply", nets=["supply"], directed=True)], + } + self.assertEqual(SchematicOverview.from_dict(data).to_dict(), data) + invalid: dict[str, Any] + for invalid in ( + {"callback": "execute"}, + {"blocks": {}}, + {"links": {}}, + {"blocks": [dict(data["blocks"][0], column=True)]}, + {"blocks": [dict(data["blocks"][0], row=4)]}, + {"blocks": [dict(data["blocks"][0], title="x" * 49)]}, + {"links": [dict(data["links"][0], directed="yes")]}, + {"links": [dict(data["links"][0], nets=[{}])]}, + {"links": [dict(data["links"][0], nets=[])]}, + ): + with self.subTest(invalid=invalid), self.assertRaises(ValueError): + SchematicOverview.from_dict(invalid) + + def test_authored_flow_requires_actual_shared_nets(self) -> None: + board, plan = fixture() + custom = SchematicOverview( + links=(SchematicOverviewLink("Function 0", "Function 1", "Supply", ("supply",), True),) + ) + data = build_overviews([board], plan, custom)["boards"][0] + link = data["connections"][0] + self.assertTrue(link["directed"]) + self.assertEqual(link["origin"], "authored") + self.assertEqual(link["nets"], ["supply"]) + for net in ("invented", "gnd"): + with self.assertRaisesRegex(ValueError, "does not connect"): + build_overviews( + [board], + plan, + SchematicOverview(links=(SchematicOverviewLink("Function 0", "Function 1", "Invalid", (net,)),)), + ) + with self.assertRaisesRegex(ValueError, "different sheets"): + build_overviews( + [board], + plan, + SchematicOverview(links=(SchematicOverviewLink("Function 0", "Function 0", "Self", ("supply",)),)), + ) + with self.assertRaisesRegex(ValueError, "unknown or ambiguous"): + build_overviews( + [board], + plan, + SchematicOverview(links=(SchematicOverviewLink("Unknown", "Function 0", "Missing", ("supply",)),)), + ) + + def test_automatic_relationships_are_undirected_and_repeatable(self) -> None: + board, plan = fixture() + a = build_overviews([board], plan) + b = build_overviews([board], plan) + self.assertEqual(json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)) + data = a["boards"][0] + self.assertEqual(data["components"], 3) + self.assertEqual(len(data["nodes"]), 3) + self.assertTrue(data["connections"]) + self.assertTrue(all(not l["directed"] and "gnd" not in l["nets"] for l in data["connections"])) + self.assertEqual(data["omitted_connection_pairs"], 1) + + def test_key_only_relationship_names_actual_endpoint_pages(self) -> None: + board, plan = fixture(10) + data = build_overviews([board], plan)["boards"][0] + by_id = {n["sheet_id"]: n for n in data["nodes"]} + self.assertEqual(len(data["connections"]), 8) + for link in data["connections"]: + # Exercise the fallback independently of routing-order heuristics. + link["path"] = [] + link["status"] = "legend_only" + self.assertEqual( + link["endpoints"], + [ + dict(sheet_id=identity, sheet_title=by_id[identity]["sheet_title"], page=by_id[identity]["page"]) + for identity in (link["source"], link["target"]) + ], + ) + doc: SExpr = [] + render_overview(doc, board, data, SchematicExportOptions("Overview")) + texts = {children(t, "uuid")[0][1]: t for t in children(doc, "text")} + for link in data["connections"]: + item = texts[uid(board.prefix, "overview", link["id"] + "-key")] + for endpoint in link["endpoints"]: + self.assertIn(f"Sheet {endpoint['page']}", item[1]) + self.assertIn("key only", item[1]) + for role in ("-key", "-key-label"): + item = texts[uid(board.prefix, "overview", link["id"] + role)] + x, y, angle = children(item, "at")[0][1:] + self.assertGreaterEqual(y, 190) + self.assertLess(y + 1.27, 203) + self.assertLess(x + len(item[1]) * 1.27, 410) + + def test_summary_does_not_contradict_sheet_continuation_title(self) -> None: + board, plan = fixture(2) + original = next(iter(board.regions)) + board.regions[original].spec = replace(board.regions[original].spec, title="Balance /5") + data = build_overviews([board], plan)["boards"][0] + item = next(n for n in data["nodes"] if "Balance /5" in n["regions"]) + self.assertEqual(item["summary"], "Balance") + self.assertEqual(item["sheet_title"], next(s.title for s in plan.sheets if s.id == item["sheet_id"])) + + def test_custom_cards_reserve_cells_and_detect_duplicates(self) -> None: + board, plan = fixture() + a = SchematicOverviewBlock("Function 1", "Controller", "Unicode μC", 0, 0) + data = build_overviews([board], plan, SchematicOverview(blocks=(a,)))["boards"][0] + self.assertEqual(len({(n["column"], n["row"]) for n in data["nodes"]}), 3) + b = SchematicOverviewBlock("Function 0", "Input", "Power", 0, 0) + with self.assertRaisesRegex(ValueError, "same grid cell"): + build_overviews([board], plan, SchematicOverview(blocks=(a, b))) + with self.assertRaisesRegex(ValueError, "duplicate overview block"): + build_overviews([board], plan, SchematicOverview(blocks=(a, a))) + + def test_lines_are_graphics_and_sheet_navigation_is_preserved(self) -> None: + board, plan = fixture() + data = build_overviews([board], plan)["boards"][0] + doc: SExpr = [] + for n in data["nodes"]: + KiCadSchematicExporter._sheet_link( + doc, + board.prefix, + uid(board.prefix, n["sheet_id"]), + "/root", + n["sheet_title"], + n["sheet_id"] + ".kicad_sch", + 20, + 50, + n["page"], + ) + before = [children(s, "instances") for s in children(doc, "sheet")] + render_overview(doc, board, data, SchematicExportOptions("Overview")) + self.assertEqual(before, [children(s, "instances") for s in children(doc, "sheet")]) + self.assertEqual(len(children(doc, "sheet")), 3) + self.assertTrue(children(doc, "polyline")) + self.assertFalse(children(doc, "wire")) + self.assertFalse(children(doc, "symbol")) + self.assertFalse(any(children(s, "pin") for s in children(doc, "sheet"))) + for s in children(doc, "sheet"): + self.assertEqual(children(s, "size")[0][1:], [83.82, 27.94]) + for link in data["connections"]: + for p, q in zip(link["path"], link["path"][1:]): + self.assertTrue(p[0] == q[0] or p[1] == q[1]) + + def test_dense_branch_routes_reserve_stubs_and_clear_identifier_text(self) -> None: + from .KiCadSchematicOverview import _segment_cells, _tag_box, _intersects + + board, plan = fixture(7) + cells = ((0, 1), (1, 1), (2, 1), (3, 0), (3, 1), (3, 2), (3, 3)) + pairs = ((0, 1), (1, 2), (2, 3), (2, 4), (2, 5), (2, 6), (0, 2)) + custom = SchematicOverview( + blocks=tuple( + SchematicOverviewBlock(f"Function {i}", f"Function {i}", "Support circuit", *cell) + for i, cell in enumerate(cells) + ), + links=tuple( + SchematicOverviewLink(f"Function {a}", f"Function {b}", f"Relationship {i}", ("supply",), True) + for i, (a, b) in enumerate(pairs) + ), + ) + data = build_overviews([board], plan, custom)["boards"][0] + self.assertFalse(data["diagnostics"]) + occupied: set[tuple[int, int]] = set() + strokes = [] + for link in data["connections"]: + self.assertEqual(link["status"], "drawn") + self.assertIsNotNone(link["tag"]) + path = link["path"] + route = set() + for a, b in zip(path, path[1:]): + route.update(_segment_cells(a, b)) + strokes.append( + (min(a[0], b[0]) - 0.125, min(a[1], b[1]) - 0.125, max(a[0], b[0]) + 0.125, max(a[1], b[1]) + 0.125) + ) + self.assertFalse(route & occupied, link["id"]) + occupied.update(route) + for a, b, c in zip(path, path[1:], path[2:]): + self.assertGreaterEqual((b[0] - a[0]) * (c[0] - b[0]) + (b[1] - a[1]) * (c[1] - b[1]), 0) + boxes = [_tag_box(link["tag"]) for link in data["connections"]] + for i, box in enumerate(boxes): + self.assertFalse(any(_intersects(box, line) for line in strokes)) + self.assertFalse(any(_intersects(box, other) for other in boxes[i + 1 :])) + self.assertFalse(any(_intersects(box, n["bounds"]) for n in data["nodes"])) + + def test_multi_board_selectors_and_cross_scope_links(self) -> None: + from .KiCadSchematicPlanner import SchematicSheetPlan + + a, pa = fixture(2, "a") + b, pb = fixture(2, "b") + plan = SchematicSheetPlan("fingerprint", pa.regions + pb.regions, pa.sheets + pb.sheets) + with self.assertRaisesRegex(ValueError, "ambiguous"): + build_overviews( + [a, b], + plan, + SchematicOverview(blocks=(SchematicOverviewBlock("Function 0", "Title", "Summary", 0, 0),)), + ) + sa = next(s for s in pa.sheets if s.id != "overview") + sb = next(s for s in pb.sheets if s.id != "overview") + with self.assertRaisesRegex(ValueError, "one board scope"): + build_overviews( + [a, b], plan, SchematicOverview(links=(SchematicOverviewLink(sa.id, sb.id, "Cross", ("supply",)),)) + ) + data = build_overviews([a, b], plan) + self.assertEqual(len(data["boards"]), 2) + self.assertTrue(all(d["components"] == 2 for d in data["boards"])) + self.assertTrue(all([n["page"] for n in d["nodes"]] == [2, 3] for d in data["boards"])) + + def test_large_inventory_falls_back_without_dropping_sheets(self) -> None: + board, plan = fixture(41) + data = build_overviews([board], plan)["boards"][0] + self.assertEqual(data["mode"], "directory") + self.assertEqual(len(data["nodes"]), 41) + self.assertFalse(data["connections"]) + self.assertEqual(data["components"], 41) + self.assertTrue(all(node["section"] for node in data["nodes"])) + self.assertEqual({node["page"] for node in data["nodes"]}, set(range(2, 43))) + self.assertTrue(all(node["bounds"][2] < 410 and node["bounds"][3] < 205 for node in data["nodes"])) + with self.assertRaisesRegex(ValueError, "at most 16 sheets"): + build_overviews( + [board], + plan, + SchematicOverview(blocks=(SchematicOverviewBlock("Function 0", "Title", "Summary", 0, 0),)), + ) + + def test_paginated_directory_machine_geometry_matches_actual_links(self) -> None: + # Contents nesting begins at 41; 49 must remain supported rather than + # overflowing the old grouped-directory capacity or dropping navigation. + for count in (41, 49): + with self.subTest(count=count): + board, plan = fixture(count) + data = build_overviews([board], plan)["boards"][0] + self.assertEqual(data["directory_layout"], "paginated") + self.assertEqual(sum(p["sheets"] for p in data["directory_pages"]), count) + options = SchematicExportOptions("Directory") + root = KiCadSchematicExporter._document(uid("root"), options, "f", "Overview") + documents = {} + for page in data["directory_pages"]: + identity = uid(board.prefix, "contents", str(page["index"])) + documents[page["filename"]] = KiCadSchematicExporter._document( + identity, options, "f", page["title"] + ) + x, y = page["bounds"][:2] + KiCadSchematicExporter._sheet_link( + root, board.prefix, identity, "/root", page["title"], page["filename"], x, y, page["page"] + ) + for index, item in enumerate(data["nodes"]): + slot = index % 40 + document = documents[item["directory_document"]] + # Actual serializer placement, independently of evidence. + x, y = 20 + (slot // 10) * 90, 50 + (slot % 10) * 14 + KiCadSchematicExporter._sheet_link( + document, + board.prefix, + uid(board.prefix, item["sheet_id"]), + "/contents", + item["sheet_title"], + "circuit.kicad_sch", + x, + y, + item["page"], + ) + link = children(document, "sheet")[-1] + at, size = children(link, "at")[0][1:], children(link, "size")[0][1:] + self.assertEqual(item["bounds"], [at[0], at[1], at[0] + size[0], at[1] + size[1]]) + render_overview(root, board, data, options) + links = children(root, "sheet") + self.assertEqual(len(links), len(data["directory_pages"])) + for link, page in zip(links, data["directory_pages"]): + at, size = children(link, "at")[0][1:], children(link, "size")[0][1:] + self.assertEqual(page["bounds"], [at[0], at[1], at[0] + size[0], at[1] + size[1]]) + titles = [item[1] for item in children(root, "text")] + self.assertTrue(any("40 sheets / 40 components" in text for text in titles)) + + def test_compiled_preview_bundle_staleness_and_native_truth(self) -> None: + from ..core import ScalaCompiler + from ..electronics_interfaces.test_netlist import TestBasicCircuit + from .RefdesRefinementPass import RefdesRefinementPass + from .NetlistGenerator import NetlistTransform + from .SchematicVerification import verify_schematic_netlist + from .KiCadSchematicExporter import SchematicPlacement + + compiled = ScalaCompiler.compile(TestBasicCircuit) + compiled.append_values(RefdesRefinementPass().run(compiled)) + options = SchematicExportOptions( + "OverviewFixture", + placements={"source": SchematicPlacement("Power", 70, 80), "sink": SchematicPlacement("Load", 100, 80)}, + sheet_assignments={"Power": "Power", "Load": "Load"}, + ) + old_plan = SchematicSheetPlanner().plan(compiled, options) + nets = next(iter(NetlistTransform(compiled).run().values())) + shared = next(n.name for n in nets.nets if len(n.pins) > 1 and "gnd" not in n.name.lower()) + custom = SchematicOverview( + blocks=( + SchematicOverviewBlock("Power", "Input", "Source support", 0, 1), + SchematicOverviewBlock("Load", "Output", "Load support", 1, 1), + ), + links=(SchematicOverviewLink("Power", "Load", "Physical association", (shared,), True),), + ) + options = replace(options, overview=custom) + exporter = KiCadSchematicExporter() + with self.assertRaisesRegex(ValueError, "stale sheet plan"): + exporter.export(compiled, replace(options, sheet_plan=old_plan)) + bundle = exporter.export(compiled, options) + self.assertEqual(json.loads(bundle.files["overview.json"]), exporter.overview(compiled, options)) + self.assertEqual(bundle.files, exporter.export(compiled, options).files) + manifest = json.loads(bundle.files["manifest.json"]) + root = manifest["boards"][0]["root"] + tree = sexpdata.loads(bundle.files[root]) + page = children(children(children(tree, "sheet_instances")[0], "path")[0], "page")[0][1] + self.assertEqual(page, "1") + self.assertEqual(sum(n.endswith(".kicad_sch") for n in bundle.files), 3) + if shutil.which("kicad-cli"): + with tempfile.TemporaryDirectory() as directory: + bundle.write(Path(directory)) + xml = Path(directory) / "truth.xml" + subprocess.run( + [ + "kicad-cli", + "sch", + "export", + "netlist", + "--format", + "kicadxml", + "-o", + str(xml), + str(Path(directory) / root), + ], + check=True, + capture_output=True, + ) + verify_schematic_netlist(nets, xml) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_passive_integration.py b/edg/electronics_model/test_schematic_passive_integration.py new file mode 100644 index 000000000..4aeb98215 --- /dev/null +++ b/edg/electronics_model/test_schematic_passive_integration.py @@ -0,0 +1,398 @@ +"""Prepared baseline reuse, final geometry plans and serialized rollback.""" + +from __future__ import annotations +from typing import Any, Sequence +from pathlib import Path +from ..core import CompiledDesign +from .KiCadSchematicTypes import Point, PinNets, Wire, Placements, Views, RouteResult +from .KiCadSchematicExporter import SchematicExport +from .KiCadSchematicPlanner import SchematicSheetPlan + +from typing_extensions import override +import copy +import json +import os +import subprocess +import tempfile +import unittest +from dataclasses import replace +from unittest.mock import patch + +import sexpdata + +from ..core import Block, GeneratorBlock, ScalaCompiler +from .CircuitBlock import FootprintBlock +from .PassivePort import Passive +from .KiCadSchematicExporter import KiCadSchematicExporter, SchematicExportOptions, SchematicPlacement, children +from .KiCadSchematicLayout import freeze_annotations +from .RefdesRefinementPass import RefdesRefinementPass + + +class QuarterPassive(GeneratorBlock, FootprintBlock): + def __init__(self) -> None: + super().__init__() + self.a = self.Port(Passive(), optional=True) + self.gnd = self.Port(Passive(), optional=True) + + @override + def generate(self) -> None: + super().generate() + self.footprint("C", "Test:Cap", {"1": self.a, "2": self.gnd}, value="4.7uF") + self.schematic_symbol("Device:C_Polarized", {"1": "1", "2": "2"}) + + +class QuarterAnchor(GeneratorBlock, FootprintBlock): + def __init__(self) -> None: + super().__init__() + self.a = self.Port(Passive(), optional=True) + + @override + def generate(self) -> None: + super().generate() + self.footprint("J", "Test:Pad", {"1": self.a}, value="PAD") + + +class QuarterSpare(GeneratorBlock, FootprintBlock): + def __init__(self) -> None: + super().__init__() + self.a = self.Port(Passive(), optional=True) + self.b = self.Port(Passive(), optional=True) + + @override + def generate(self) -> None: + super().generate() + self.footprint("U", "Test:Unmapped", {"1": self.a, "2": self.b}, value="unmapped") + + +class QuarterCircuit(Block): + @override + def contents(self) -> None: + super().contents() + self.passive = self.Block(QuarterPassive()) + self.anchor = self.Block(QuarterAnchor()) + self.spare = self.Block(QuarterSpare()) + self.connect(self.passive.a, self.anchor.a) + + +LIBRARY = """(kicad_symbol_lib (version 20211014) (generator test) + (symbol "C_Polarized" (pin_names (offset 0)) + (property "Reference" "C" (at 2 1 0) (effects (font (size 1.27 1.27)))) + (property "Value" "C_Polarized" (at 2 -1 0) (effects (font (size 1.27 1.27)))) + (symbol "C_Polarized_0_1" + (rectangle (start -1 3) (end 1 -3) (stroke (width 0) (type default)) (fill (type none)))) + (symbol "C_Polarized_1_1" + (pin passive line (at 0 5.08 270) (length 2.08) (name "positive") (number "1")) + (pin passive line (at 0 -5.08 90) (length 2.08) (name "negative") (number "2")))))""" + + +class PassiveIntegrationTest(unittest.TestCase): + temp: tempfile.TemporaryDirectory[str] + compiled: CompiledDesign + + @classmethod + @override + def setUpClass(cls) -> None: + cls.temp = tempfile.TemporaryDirectory() + Path(cls.temp.name, "Device.kicad_sym").write_text(LIBRARY) + cls.compiled = ScalaCompiler.compile(QuarterCircuit) + cls.compiled.append_values(RefdesRefinementPass().run(cls.compiled)) + + @classmethod + @override + def tearDownClass(cls) -> None: + cls.temp.cleanup() + + def options(self, **kwargs: Any) -> SchematicExportOptions: + return SchematicExportOptions( + "QuarterCircuit", + symbol_library_dirs=(self.temp.name,), + placements={ + "passive": SchematicPlacement("Demo", 50, 70, lock_rotation=False), + "anchor": SchematicPlacement("Demo", 110, 70), + }, + **kwargs, + ) + + def evidence(self, bundle: SchematicExport) -> dict[str, Any]: + return {r["region"]: r for r in json.loads(bundle.files["routing.json"])["regions"]} + + def poses(self, bundle: SchematicExport) -> dict[str, Any]: + result = {} + for name, text in bundle.files.items(): + if not name.endswith(".kicad_sch"): + continue + for symbol in children(sexpdata.loads(text), "symbol"): + props = {p[1]: p[2] for p in children(symbol, "property")} + if "PBPath" in props: + result[props["PBPath"]] = children(symbol, "at")[0][1:] + return result + + def test_default_and_disabled_modes_preserve_legacy_files(self) -> None: + exporter = KiCadSchematicExporter() + default = exporter.export(self.compiled, self.options()) + explicit = exporter.export(self.compiled, self.options(orientation_mode="half_turn")) + self.assertEqual(default.files, explicit.files) + old_off = exporter.export(self.compiled, self.options(optimize_orientations=False)) + quarter_off = exporter.export( + self.compiled, self.options(optimize_orientations=False, orientation_mode="passive_quarter_turn") + ) + self.assertEqual(old_off.files, quarter_off.files) + self.assertNotIn("passive_orientation", quarter_off.files["routing.json"]) + for value in ("unknown", None, False): + with self.assertRaises(ValueError): + self.options(orientation_mode=value) + + def test_real_quarter_turn_after_legacy_routing_is_deterministic_and_immutable(self) -> None: + exporter = KiCadSchematicExporter() + original = self.compiled.design.SerializeToString(), copy.deepcopy(self.compiled._values) + options = self.options(orientation_mode="passive_quarter_turn") + first = exporter.export(self.compiled, options) + evidence = self.evidence(first)["Demo"]["passive_orientation"] + self.assertTrue(evidence["accepted"], evidence) + self.assertEqual(evidence["final_rotations"]["passive"], 270) + self.assertEqual(evidence["route_trials"], 3) + self.assertLess(evidence["after"]["length_mm"], evidence["before"]["length_mm"]) + self.assertEqual(first.files, exporter.export(self.compiled, options).files) + self.assertEqual((self.compiled.design.SerializeToString(), self.compiled._values), original) + base = self.poses(exporter.export(self.compiled, self.options())) + actual = self.poses(first) + for axis in (0, 1): + self.assertEqual( + round(base["passive"][axis] - base["anchor"][axis], 4), + round(actual["passive"][axis] - actual["anchor"][axis], 4), + ) + self.assertEqual(base["anchor"][2], actual["anchor"][2]) + + def test_adopted_plan_validates_final_quarter_turn_geometry(self) -> None: + exporter = KiCadSchematicExporter() + options = self.options(orientation_mode="passive_quarter_turn") + first = exporter.export(self.compiled, options) + plan = SchematicSheetPlan.from_dict(json.loads(first.files["sheet-plan.json"])) + adopted = exporter.export(self.compiled, replace(options, sheet_plan=plan)) + self.assertEqual(first.files, adopted.files) + stale = replace(plan, fingerprint="stale") + with self.assertRaisesRegex(ValueError, "stale"): + exporter.export(self.compiled, replace(options, sheet_plan=stale)) + + def test_serialized_scene_rollback_uses_cached_baseline_without_repreparing(self) -> None: + exporter = KiCadSchematicExporter() + options = self.options(orientation_mode="passive_quarter_turn") + baseline = exporter.export(self.compiled, self.options()) + prepare = exporter._prepare_legacy_boards + with ( + patch.object(exporter, "_prepare_legacy_boards", wraps=prepare) as preparations, + patch.object( + exporter, "_passive_scene_issues", side_effect=[{}, {"(root)": {("label_collision", "new"): 1.0}}] + ), + ): + result = exporter.export(self.compiled, options) + self.assertEqual(preparations.call_count, 1) + evidence = self.evidence(result)["Demo"]["passive_orientation"] + self.assertFalse(evidence["accepted"]) + self.assertEqual(evidence["rollback_reason"], "new blocking serialized scene finding") + self.assertEqual(self.poses(result), self.poses(baseline)) + self.assertEqual( + json.loads(result.files["sheet-plan.json"])["fingerprint"], + json.loads(baseline.files["sheet-plan.json"])["fingerprint"], + ) + + def _serialized_label_contacts( + self, existing_x: float, other_x: float, wires: Sequence[tuple[Point, Point]] = () + ) -> dict[tuple[str, ...], float]: + # A deliberately preexisting bad label keeps the same UUID and fallback + # flag. Only its actual serialized obstacle contacts change. + document = f"""(kicad_sch (uuid "sheet") + (lib_symbols (symbol "Test:Box" + (symbol "Box_0_1" (rectangle (start -1 -1) (end 1 1))))) + (symbol (lib_id "Test:Box") (at {existing_x} 50 0) (uuid "old") + (property "PBPath" "existing-body" (at 0 0 0) + (effects (font (size 1.27 1.27)) hide))) + (symbol (lib_id "Test:Box") (at {other_x} 50 0) (uuid "other") + (property "PBPath" "other-body" (at 0 0 0) + (effects (font (size 1.27 1.27)) hide))) + (label "BUS" (at 50 50 0) (uuid "same-label") + (effects (font (size 1.27 1.27)))))""" + wire_nodes = "".join(f"(wire (pts (xy {a[0]} {a[1]}) (xy {b[0]} {b[1]})))" for a, b in wires) + document = document[:-1] + wire_nodes + ")" + bundle = SchematicExport( + { + "Board.kicad_sch": document, + "manifest.json": json.dumps({"boards": [{"root": "Board.kicad_sch", "scope": "(root)"}]}), + "layout.json": json.dumps( + { + "label_placement": [ + {"sheet": "sheet", "conflicts": [{"identity": "same-label"}], "unresolved_anchors": []} + ] + } + ), + "readability.json": json.dumps({"findings": []}), + }, + [], + ) + return KiCadSchematicExporter._passive_scene_issues(bundle)["(root)"] + + def test_existing_bad_label_new_obstacle_rolls_back(self) -> None: + old = self._serialized_label_contacts(50, 100) + new = self._serialized_label_contacts(50, 50) + self.assertEqual(old[("label_collision", "same-label")], new[("label_collision", "same-label")]) + key = ("text_body_contact", "same-label", "other-body") + self.assertNotIn(key, old) + self.assertGreater(new[key], 0) + self._assert_serialized_contact_rollback(old, new) + + def test_existing_contact_worsened_overlap_rolls_back(self) -> None: + old = self._serialized_label_contacts(53, 100) + new = self._serialized_label_contacts(52, 100) + self.assertEqual(set(old), set(new)) + key = ("text_body_contact", "same-label", "existing-body") + self.assertGreater(new[key], old[key]) + self._assert_serialized_contact_rollback(old, new) + + def test_existing_text_wire_contact_worsened_length_rolls_back(self) -> None: + old = self._serialized_label_contacts(100, 120, [((49, 50), (50, 50))]) + split = self._serialized_label_contacts(100, 120, [((49, 50), (49.5, 50)), ((49.5, 50), (50, 50))]) + new = self._serialized_label_contacts(100, 120, [((49, 50), (51, 50))]) + key = ("text_wire_contact", "same-label") + self.assertEqual(old, split, "Wire segmentation is not a scene identity") + self.assertEqual(set(old), set(new)) + self.assertGreater(new[key], old[key]) + self._assert_serialized_contact_rollback(old, new) + + def _assert_serialized_contact_rollback( + self, old: dict[tuple[str, ...], float], new: dict[tuple[str, ...], float] + ) -> None: + exporter = KiCadSchematicExporter() + baseline = exporter.export(self.compiled, self.options()) + with patch.object(exporter, "_passive_scene_issues", side_effect=[{"(root)": old}, {"(root)": new}]): + result = exporter.export(self.compiled, self.options(orientation_mode="passive_quarter_turn")) + evidence = self.evidence(result)["Demo"]["passive_orientation"] + self.assertFalse(evidence["accepted"]) + self.assertEqual(evidence["rollback_reason"], "new blocking serialized scene finding") + self.assertEqual(self.poses(result), self.poses(baseline)) + + def test_final_route_order_cannot_replace_existing_clearance_pair(self) -> None: + from .KiCadSchematicOrientation import orientation_metrics, passive_orientation_rank + + exporter = KiCadSchematicExporter() + options = self.options(orientation_mode="passive_quarter_turn") + prepared = exporter._prepare_legacy_boards(self.compiled, options) + board = prepared[0][0] + drawing = next(region for region in board.regions.values() if region.spec.title == "Demo") + old_pair: list[Wire] = [("old-a", (20, 20), (30, 20)), ("old-b", (20, 20.635), (30, 20.635))] + old_route = drawing.route_snapshot + assert old_route is not None + drawing.route_snapshot = (old_route[0] + old_pair, old_route[1], old_route[2]) + drawing.wires = drawing.route_snapshot[0] + before = orientation_metrics(drawing.placed, board.views, board.pin_nets, drawing.route_snapshot) + observed = [] + + def replace_pair( + placed: Placements, views: Views, nets: PinNets, route: RouteResult, router: object + ) -> tuple[RouteResult, dict[str, Any]]: + new_pair: list[Wire] = [("new-a", (20, 20), (30, 20)), ("new-b", (20, 20.635), (30, 20.635))] + final = (route[0] + new_pair, route[1], route[2]) + after = orientation_metrics(placed, views, nets, final) + observed.append(after) + return final, {"selected": "baseline"} + + with ( + patch.object(exporter, "_prepare_legacy_boards", return_value=prepared), + patch("edg.electronics_model.KiCadSchematicRouting.optimize_fixed_routes", replace_pair), + ): + result = exporter.export(self.compiled, options) + self.assertEqual(len(observed), 1) + self.assertEqual(observed[0]["visual_conflicts"], before["visual_conflicts"]) + self.assertLess(passive_orientation_rank(observed[0]), passive_orientation_rank(before)) + evidence = self.evidence(result)["Demo"]["passive_orientation"] + self.assertFalse(evidence["accepted"]) + self.assertEqual(evidence["rollback_reason"], "final routing or page-fit guard") + self.assertEqual(evidence["final_rotations"], {c.path: angle for c, _, _, angle in drawing.placed}) + + def test_only_changed_regions_receive_additional_route_order_search(self) -> None: + from .KiCadSchematicRouting import optimize_fixed_routes + + calls = [] + + def record(placed: Placements, *args: Any, **kwargs: Any) -> tuple[RouteResult, dict[str, Any]]: + calls.append(tuple(sorted(c.path for c, _, _, _ in placed))) + return optimize_fixed_routes(placed, *args, **kwargs) + + with patch("edg.electronics_model.KiCadSchematicRouting.optimize_fixed_routes", record): + result = KiCadSchematicExporter().export( + self.compiled, self.options(orientation_mode="passive_quarter_turn") + ) + self.assertTrue(self.evidence(result)["Demo"]["passive_orientation"]["accepted"]) + self.assertEqual(calls.count(("anchor", "passive")), 2) + self.assertEqual(calls.count(("spare",)), 1) + + def test_passive_phase_follows_bridge_and_restores_source_annotation_policy(self) -> None: + from .KiCadSchematicOrientation import optimize_passive_orientations + from .KiCadSchematicPower import compare_bridge_variants + + calls = [] + + def bridge(*args: Any, **kwargs: Any) -> tuple[Placements, RouteResult, dict[str, Any] | None]: + calls.append("bridge") + return compare_bridge_variants(*args, **kwargs) + + def passive(items: Placements, *args: Any, **kwargs: Any) -> tuple[Placements, RouteResult, dict[str, Any]]: + calls.append("passive") + self.assertEqual(set(kwargs["source_annotations"]), {c.path for c, _, _, _ in items}) + self.assertTrue(all(value is None for value in kwargs["source_annotations"].values())) + self.assertTrue(all(c.annotation is not None for c, _, _, _ in items)) + return optimize_passive_orientations(items, *args, **kwargs) + + with ( + patch("edg.electronics_model.KiCadSchematicPower.compare_bridge_variants", bridge), + patch("edg.electronics_model.KiCadSchematicOrientation.optimize_passive_orientations", passive), + ): + KiCadSchematicExporter().export(self.compiled, self.options(orientation_mode="passive_quarter_turn")) + # The automatic spare invokes the bridge phase, while the hinted + # circuit keeps its centers. All template decisions precede this pass. + self.assertGreater(calls.count("passive"), 0) + self.assertGreater(calls.count("bridge"), 0) + self.assertLess( + max(i for i, v in enumerate(calls) if v == "bridge"), min(i for i, v in enumerate(calls) if v == "passive") + ) + + def test_native_quarter_turn_preserves_physical_inventory_and_connected_pin_sets(self) -> None: + from .NetlistGenerator import NetlistTransform + from .SchematicVerification import verify_schematic_netlist + + clis = tuple(filter(None, os.environ.get("PB_SCHEMATIC_TEST_KICAD_CLIS", "").split(os.pathsep))) + if not clis: + clis = tuple(filter(None, (os.environ.get("KICAD_CLI9"), os.environ.get("KICAD_CLI10")))) + if not clis: + self.skipTest("Set PB_SCHEMATIC_TEST_KICAD_CLIS or KICAD_CLI9/10 for native acceptance") + scopes = {str(scope): netlist for scope, netlist in NetlistTransform(self.compiled).run().items()} + for mode in ("half_turn", "passive_quarter_turn"): + bundle = KiCadSchematicExporter().export(self.compiled, self.options(orientation_mode=mode)) + with tempfile.TemporaryDirectory() as directory: + destination = Path(directory) + bundle.write(destination) + for board in json.loads(bundle.files["manifest.json"])["boards"]: + for index, cli in enumerate(clis): + with self.subTest(mode=mode, scope=board["scope"], cli=cli): + output = destination / f"native-{index}.xml" + result = subprocess.run( + [ + cli, + "sch", + "export", + "netlist", + "--format", + "kicadxml", + "-o", + str(output), + str(destination / board["root"]), + ], + capture_output=True, + text=True, + timeout=60, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + verify_schematic_netlist(scopes[board["scope"]], output) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_passive_orientation.py b/edg/electronics_model/test_schematic_passive_orientation.py new file mode 100644 index 000000000..020eca16f --- /dev/null +++ b/edg/electronics_model/test_schematic_passive_orientation.py @@ -0,0 +1,387 @@ +"""Quarter turns preserve electrical identities while improving real wire paths.""" + +from __future__ import annotations +from typing import Any +from .KiCadSchematicTypes import Point, PinKey, Wire, Placement, Placements, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import copy +import unittest +from unittest.mock import patch + +from .KiCadSchematicExporter import node +from .KiCadSchematicLayout import route_local +from .KiCadSchematicOrientation import ( + optimize_passive_orientations, + passive_orientation_rank, + orientation_conflict_identities, + _visual_clearance_conflict_identities, + _visual_conflicts, +) +from .test_schematic_functional_placement import passive_view + +MODULE = "edg.electronics_model.KiCadSchematicOrientation." + + +class PassiveOrientationTest(unittest.TestCase): + def fixture(self, count: int = 1) -> tuple[list[Placement], dict[str, SymbolView], dict[PinKey, str]]: + entries, views, nets = [], {}, {} + for index in range(count): + component = PhysicalComponent( + f"part{index:03}", f"R{index}", "Fixture:Pad", "part", {"1": "a", "2": "b"}, None, "circuit" + ) + entries.append((component, 50.0 + index * 20, 70.0, 0)) + views[component.path] = passive_view("Device:R") + nets[component.path, "1"] = "positive" + nets[component.path, "2"] = "negative" + return entries, views, nets + + def geometry(self, *args: object) -> dict[str, Any]: + return dict(escape_conflicts=0, collisions=0, collision_pairs=[], clipped=False) + + def metric(self, placed: Placements, *args: object) -> dict[str, float]: + return dict( + primary_fallbacks=0, + crossings=0, + unrelated_intrusions=0, + length_mm=1000 - sum(angle == (90 if int(c.path[-3:]) % 2 == 0 else 270) for c, _, _, angle in placed), + bends=0, + detour_mm=0, + visual_conflicts=0, + ) + + def test_all_three_angles_share_incumbent_and_every_path_gets_one_visit(self) -> None: + entries, views, nets = self.fixture(40) + original = copy.deepcopy((entries, views, nets)) + calls = [] + baseline: RouteResult = ([], {}, []) + + def router(*args: object) -> RouteResult: + calls.append(args) + return baseline + + with ( + patch(MODULE + "_geometry", self.geometry), + patch(MODULE + "orientation_metrics", self.metric), + patch(MODULE + "_escape_conflict_identities", return_value=frozenset()), + ): + placed, _, evidence = optimize_passive_orientations(entries, views, nets, router, baseline=baseline) + self.assertEqual(len(calls), 120) + self.assertEqual(evidence["route_trial_limit"], 120) + self.assertEqual(evidence["sweeps"], 1) + self.assertEqual( + [trial["path"] for trial in evidence["trials"]], [c.path for c, _, _, _ in entries for _ in range(3)] + ) + for offset in range(0, 120, 3): + trials = evidence["trials"][offset : offset + 3] + self.assertEqual([trial["to_rotation"] for trial in trials], [90, 180, 270]) + self.assertEqual([trial["from_rotation"] for trial in trials], [0, 0, 0]) + self.assertEqual(sum(trial["selected"] for trial in trials), 1) + self.assertEqual([angle for _, _, _, angle in placed], [90, 270] * 20) + self.assertEqual((entries, views, nets), original) + self.assertEqual([(x, y) for _, x, y, _ in entries], [(x, y) for _, x, y, _ in placed]) + + def test_replacement_escape_conflict_same_count_is_rejected(self) -> None: + entries, views, nets = self.fixture() + old: list[tuple[str, Point, Point, str, str]] = [ + ("a", (0, 0), (10, 0), "moving", "1"), + ("b", (0, 0), (0, 10), "old-neighbor", "1"), + ("c", (20, 0), (20, 10), "new-neighbor", "1"), + ] + new = [("a", (10, 0), (20, 0), "moving", "1"), *old[1:]] + + def escapes(placed: Placements, *args: object) -> list[tuple[str, Point, Point, str, str]]: + return old if placed[0][3] == 0 else new + + baseline: RouteResult = ([], {}, []) + with ( + patch("edg.electronics_model.KiCadSchematicPlacement.pin_escapes", escapes), + patch(MODULE + "_geometry", self.geometry), + patch(MODULE + "orientation_metrics", self.metric), + ): + initial = orientation_conflict_identities(entries, views, nets, baseline)["escape"] + changed = orientation_conflict_identities([(entries[0][0], 50, 70, 90)], views, nets, baseline)["escape"] + self.assertEqual(len(initial), len(changed)) + self.assertNotEqual(initial, changed) + calls = [] + + def recorder(*args: object) -> RouteResult: + calls.append(args) + return baseline + + _, _, evidence = optimize_passive_orientations(entries, views, nets, recorder, baseline=baseline) + self.assertFalse(evidence["changed"]) + self.assertEqual(calls, []) + self.assertTrue(all(t["reason"] == "new physical escape conflict" for t in evidence["trials"])) + + def test_replacement_wire_clearance_same_count_is_rejected(self) -> None: + entries, views, nets = self.fixture() + old_wires: list[Wire] = [("a", (0, 0), (10, 0)), ("b", (0, 0.635), (10, 0.635))] + new_wires: list[Wire] = [("a", (0, 0), (10, 0)), ("c", (0, 0.635), (10, 0.635))] + self.assertEqual(_visual_conflicts(old_wires), _visual_conflicts(new_wires)) + self.assertNotEqual( + _visual_clearance_conflict_identities((old_wires, {}, []), nets), + _visual_clearance_conflict_identities((new_wires, {}, []), nets), + ) + with ( + patch(MODULE + "_geometry", self.geometry), + patch(MODULE + "orientation_metrics", self.metric), + patch(MODULE + "_escape_conflict_identities", return_value=frozenset()), + ): + _, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: (new_wires, {}, []), baseline=(old_wires, {}, []) + ) + self.assertFalse(evidence["changed"]) + self.assertEqual(evidence["route_trials"], 3) + self.assertTrue(all(t["reason"] == "new visual wire clearance conflict" for t in evidence["trials"])) + + def test_visual_clearance_identities_ignore_straight_wire_segmentation(self) -> None: + whole: list[Wire] = [("a", (0, 0), (10, 0)), ("b", (0, 0.635), (10, 0.635))] + split: list[Wire] = [ + ("a", (0, 0), (5, 0)), + ("a", (5, 0), (10, 0)), + ("b", (10, 0.635), (3, 0.635)), + ("b", (3, 0.635), (0, 0.635)), + ] + self.assertEqual( + _visual_clearance_conflict_identities((whole, {}, []), {}), + _visual_clearance_conflict_identities((split, {}, []), {}), + ) + + def test_verified_symbol_policy_ignores_reference_and_footprint_guesses(self) -> None: + entries, views, nets = self.fixture(8) + ids = [ + "Device:R", + "Device:R_US_PB_mapping", + "Device:C", + "Device:C_Polarized", + "Device:L", + "Fixture:Capacitor", + "PB:generic", + "Device:R", + ] + for (component, _, _, _), lib in zip(entries, ids): + views[component.path].lib_id = lib + views["part007"].pins.append(("3", 5.08, 0.0, 180)) + with ( + patch(MODULE + "_geometry", self.geometry), + patch(MODULE + "orientation_metrics", self.metric), + patch(MODULE + "_escape_conflict_identities", return_value=frozenset()), + ): + _, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: ([], {}, []), baseline=([], {}, []), locked={"part004"} + ) + self.assertEqual( + [item["eligible"] for item in evidence["eligibility"]], [True, True, True, True, False, False, False, False] + ) + self.assertEqual(evidence["route_trials"], 12) + self.assertEqual(evidence["eligibility"][4]["reason"], "explicit rotation lock") + self.assertIn("two distinct", evidence["eligibility"][7]["reason"]) + + def test_custom_symbol_name_cannot_masquerade_as_verified_id(self) -> None: + from .KiCadSchematicOrientation import _passive_quarter_turn_eligibility + + entries, views, _ = self.fixture() + component = entries[0][0] + view = views[component.path] + view.lib_id = "Device:R_PB_custom_PB_resolvermap" + self.assertFalse(_passive_quarter_turn_eligibility(component, view, set())[0]) + view.lib_id = "Device:R_PB_resolvermap" + self.assertTrue(_passive_quarter_turn_eligibility(component, view, set())[0]) + + def test_auto_fields_recomputed_authored_annotations_preserved_and_inputs_unchanged(self) -> None: + entries, views, nets = self.fixture(2) + entries[0][0].annotation = (900.0, 900.0) # a frozen automatic baseline + entries[1][0].annotation = (100.0, 120.0) # authored; partial map preserves it + original = copy.deepcopy((entries, views, nets)) + observations = [] + + def router(placed: Placements, *args: object) -> RouteResult: + observations.append({c.path: c.annotation for c, _, _, _ in placed}) + return [], {}, [] + + with patch(MODULE + "_geometry", self.geometry), patch(MODULE + "orientation_metrics", self.metric): + placed, _, evidence = optimize_passive_orientations( + entries, + views, + nets, + router, + baseline=([], {}, []), + locked={"part001"}, + source_annotations={"part000": None}, + ) + self.assertTrue(all(item["part000"] != (900.0, 900.0) for item in observations)) + self.assertTrue(all(item["part001"] == (100.0, 120.0) for item in observations)) + self.assertEqual(placed[1][0].annotation, (100.0, 120.0)) + self.assertEqual((entries, views, nets), original) + self.assertEqual(evidence["final_rotations"], {"part000": 90, "part001": 0}) + + def test_ties_preserve_angle_and_locked_components_consume_no_trials(self) -> None: + entries, views, nets = self.fixture(2) + entries[0] = (*entries[0][:3], 90) + metric = dict( + primary_fallbacks=0, + crossings=0, + unrelated_intrusions=0, + length_mm=20, + bends=0, + detour_mm=0, + visual_conflicts=0, + ) + with patch(MODULE + "_geometry", self.geometry), patch(MODULE + "orientation_metrics", return_value=metric): + placed, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: ([], {}, []), baseline=([], {}, []), locked={"part001"} + ) + self.assertEqual([angle for _, _, _, angle in placed], [90, 0]) + self.assertEqual([trial["to_rotation"] for trial in evidence["trials"]], [0, 180, 270]) + self.assertFalse(evidence["changed"]) + self.assertEqual(evidence["route_trials"], 3) + + def test_weighted_cost_tie_keeps_incumbent_despite_fewer_bends(self) -> None: + entries, views, nets = self.fixture() + + def metric(items: Placements, *args: object) -> dict[str, float]: + result = self.metric(items, *args) + angle = items[0][3] + result.update(length_mm=100.0 if angle == 0 else 102.54, bends=1 if angle == 0 else 0, detour_mm=0) + return result + + with patch(MODULE + "_geometry", self.geometry), patch(MODULE + "orientation_metrics", metric): + placed, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: ([], {}, []), baseline=([], {}, []) + ) + self.assertEqual(placed[0][3], 0) + self.assertFalse(evidence["changed"]) + self.assertEqual(evidence["route_trials"], 3) + self.assertTrue(all(t["reason"] == "incumbent scores better or ties" for t in evidence["trials"])) + + def test_equal_cost_improving_alternatives_keep_first_stable_angle(self) -> None: + entries, views, nets = self.fixture() + + def metric(items: Placements, *args: object) -> dict[str, float]: + result = self.metric(items, *args) + angle = items[0][3] + length, bends = {0: (200.0, 0), 90: (100.0, 1), 180: (102.54, 0), 270: (110.0, 0)}[angle] + result.update(length_mm=length, bends=bends, detour_mm=length) + return result + + with patch(MODULE + "_geometry", self.geometry), patch(MODULE + "orientation_metrics", metric): + placed, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: ([], {}, []), baseline=([], {}, []) + ) + self.assertEqual(placed[0][3], 90) + self.assertTrue(evidence["changed"]) + self.assertEqual(evidence["route_trials"], 3) + self.assertEqual([t["to_rotation"] for t in evidence["trials"] if t["selected"]], [90]) + + def test_new_failed_endpoint_rejected(self) -> None: + entries, views, nets = self.fixture() + with patch(MODULE + "_geometry", self.geometry), patch(MODULE + "orientation_metrics", self.metric): + placed, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: ([], {}, [(("part000", "1"), "positive")]), baseline=([], {}, []) + ) + self.assertEqual(placed[0][3], 0) + self.assertTrue(all(trial["reason"] == "new failed endpoints" for trial in evidence["trials"])) + + def test_collisions_and_overflow_are_recorded_without_routing_invalid_angles(self) -> None: + entries, views, nets = self.fixture() + + def geometry(placed: Placements, *args: object) -> dict[str, Any]: + angle = placed[0][3] + return dict( + escape_conflicts=0, + collisions=0, + collision_pairs=[("part000", 0, "foreign", 0)] if angle == 90 else [], + clipped=angle == 270, + ) + + with patch(MODULE + "_geometry", geometry), patch(MODULE + "orientation_metrics", self.metric): + _, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: ([], {}, []), baseline=([], {}, []) + ) + self.assertEqual(evidence["route_trials"], 1) + self.assertEqual(evidence["trials"][0]["reason"], "new symbol, field or pin text collision") + self.assertEqual(evidence["trials"][2]["reason"], "page overflow") + with patch(MODULE + "_geometry", self.geometry), patch(MODULE + "orientation_metrics", self.metric): + _, _, evidence = optimize_passive_orientations( + entries, + views, + nets, + lambda *args: ([], {}, []), + baseline=([], {}, []), + region_bounds=lambda *args: (0, 0, 500, 500), + ) + self.assertTrue(all(t["reason"] == "routed region page overflow" for t in evidence["trials"])) + + def test_balanced_wire_cost_allows_a_shorter_path_with_an_extra_bend(self) -> None: + entries, views, nets = self.fixture() + + def metric(placed: Placements, *args: object) -> dict[str, float]: + angle = placed[0][3] + length, bends = {0: (100.0, 0), 90: (90.0, 1), 180: (99.0, 0), 270: (89.0, 5)}[angle] + return dict( + primary_fallbacks=0, + crossings=0, + unrelated_intrusions=0, + length_mm=length, + bends=bends, + detour_mm=0, + visual_conflicts=0, + ) + + with patch(MODULE + "_geometry", self.geometry), patch(MODULE + "orientation_metrics", metric): + placed, _, evidence = optimize_passive_orientations( + entries, views, nets, lambda *args: ([], {}, []), baseline=([], {}, []) + ) + self.assertEqual(placed[0][3], 90) + self.assertLess(passive_orientation_rank(evidence["after"]), passive_orientation_rank(evidence["before"])) + + def real_fixture( + self, lib_id: str, target_angle: int, parallel: bool = False + ) -> tuple[list[Placement], dict[str, SymbolView], dict[PinKey, str]]: + component = PhysicalComponent( + "passive", "C1", "Fixture:Passive", "4.7uF", {"1": "pos", "2": "neg"}, None, "circuit" + ) + anchor = PhysicalComponent("anchor", "J1", "Fixture:Pad", "PAD", {"1": "power"}, None, "circuit") + view = passive_view(lib_id) + nets = {("passive", "1"): "power", ("passive", "2"): "gnd", ("anchor", "1"): "power"} + if parallel: + component.pins["3"] = "pos" + view.pins.append(("3", *view.pins[0][1:])) + nets["passive", "3"] = "power" + views = { + "passive": view, + "anchor": SymbolView( + node( + "symbol", node("symbol", "anchor_0_1", node("rectangle", node("start", -1, -1), node("end", 1, 1))) + ), + [("1", 0.0, 0.0, 0 if target_angle == 270 else 180)], + "Fixture:Anchor", + ), + } + px, ax = (50.0, 90.0) if target_angle == 270 else (90.0, 50.0) + return [(component, px, 70.0, 0), (anchor, ax, 70.0, 0)], views, nets + + def test_real_router_quarter_turns_shorten_rcl_preserving_parallel_pads_and_polarity(self) -> None: + for lib_id in ("Device:R", "Device:R_US", "Device:C", "Device:C_Polarized", "Device:L"): + for angle in (90, 270): + with self.subTest(lib_id=lib_id, angle=angle): + entries, views, nets = self.real_fixture(lib_id, angle, parallel=True) + original = copy.deepcopy((entries, views, nets)) + placed, route, evidence = optimize_passive_orientations(entries, views, nets, route_local) + self.assertEqual(placed[0][3], angle) + self.assertLess(evidence["after"]["length_mm"], evidence["before"]["length_mm"]) + self.assertLess( + passive_orientation_rank(evidence["after"]), passive_orientation_rank(evidence["before"]) + ) + self.assertEqual(route[2], []) + self.assertEqual(set(route[1]), set(nets)) + self.assertEqual((entries, views, nets), original) + self.assertEqual([(x, y) for _, x, y, _ in entries], [(x, y) for _, x, y, _ in placed]) + self.assertEqual( + optimize_passive_orientations(entries, views, nets, route_local), (placed, route, evidence) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_patterns.py b/edg/electronics_model/test_schematic_patterns.py new file mode 100644 index 000000000..98f07b523 --- /dev/null +++ b/edg/electronics_model/test_schematic_patterns.py @@ -0,0 +1,483 @@ +"""Electrical role patterns and deterministic ordering, independent of net names.""" + +from __future__ import annotations +from typing import Sequence +from .KiCadSchematicTypes import PinKey +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import unittest + +from .KiCadSchematicPatterns import discover_patterns, terminal_roles, decoupling_associations +from .KiCadSchematicLayout import place_group +from .KiCadSchematicExporter import generic + + +def led(path: str) -> PhysicalComponent: + return PhysicalComponent( + path, + "D1", + "Test:LED", + "LED", + {"4": "dout", "2": "din", "1": "gnd", "3": "vdd"}, + None, + "chain", + ) + + +def nets(parts: Sequence[PhysicalComponent]) -> dict[PinKey, str]: + result = {} + for i, c in enumerate(parts): + result[c.path, "1"] = "arbitrary_common_return" + result[c.path, "3"] = "arbitrary_common_supply" + result[c.path, "2"] = "input" if i == 0 else "n" + str(i - 1) + result[c.path, "4"] = "output" if i == len(parts) - 1 else "n" + str(i) + return result + + +class SchematicPatternsTest(unittest.TestCase): + def decoupling_fixture( + self, count: int = 8, prefix: str = "array" + ) -> tuple[list[PhysicalComponent], list[PhysicalComponent], dict[PinKey, str]]: + devices = [led(f"{prefix}.pixel[{i}].implementation.device") for i in range(count)] + wiring = nets(devices) + caps: list[PhysicalComponent] = [] + for i, device in enumerate(devices): + owner = f"{prefix}.pixel[{i}]" + cap = PhysicalComponent( + owner + ".bypass.wrapper.cap", + f"C{i}", + "FP", + "100nF", + {"1": "pos", "2": "neg"}, + {"lib_id": "Device:C"}, + "caps", + ) + cap.hierarchy = ( + (owner, "edg.parts.human_interface.Neopixel.Sk6812Mini_E"), + (owner + ".bypass", "edg.abstract_parts.Capacitor.DecouplingCapacitor"), + ) + wiring[cap.path, "1"] = "arbitrary_common_supply" + wiring[cap.path, "2"] = "arbitrary_common_return" + caps.append(cap) + return devices, caps, wiring + + def test_nested_decoupling_owner_single_and_repeated(self) -> None: + from .KiCadSchematicLayout import regroup, split_group + + for count in (1, 8): + devices, caps, wiring = self.decoupling_fixture(count) + parts = devices + caps + patterns = decoupling_associations(parts, wiring) + self.assertEqual(len(patterns), count) + self.assertEqual([p.components for p in patterns], [(d.path, c.path) for d, c in zip(devices, caps)]) + self.assertEqual(patterns, decoupling_associations(list(reversed(parts)), wiring)) + regroup(parts, wiring) + self.assertTrue(all(c.group == d.group for c, d in zip(caps, devices))) + views = {c.path: generic(c) for c in parts} + for cap in caps: + views[cap.path] = SymbolView( + generic(cap).definition, [("1", 0, -2.54, 270), ("2", 0, 2.54, 90)], "Device:C" + ) + pages = place_group(parts, views, wiring) + for device, cap in zip(devices, caps): + containing = [page for page in pages if any(e[0] is device for e in page)] + self.assertEqual(len(containing), 1) + self.assertTrue(any(e[0] is cap for e in containing[0])) + pair = [(devices[0], 0, 0, 0), (caps[0], 0, 30, 0)] + self.assertIsNone(split_group(pair, views, wiring)) + + def test_two_arrays_sharing_rails_do_not_share_cap_ownership(self) -> None: + a, ca, wa = self.decoupling_fixture(2, "first") + b, cb, wb = self.decoupling_fixture(2, "second") + patterns = decoupling_associations(a + b + ca + cb, {**wa, **wb}) + self.assertEqual({p.components for p in patterns}, {(d.path, c.path) for d, c in zip(a + b, ca + cb)}) + + def test_decoupling_requires_typed_owner_and_both_matching_rails(self) -> None: + devices, caps, wiring = self.decoupling_fixture(1) + parts = devices + caps + cap = caps[0] + original = cap.hierarchy + cap.hierarchy = () + self.assertEqual(decoupling_associations(parts, wiring), ()) + cap.hierarchy = original + wiring[cap.path, "2"] = "different_return" + self.assertEqual(decoupling_associations(parts, wiring), ()) + wiring[cap.path, "2"] = "arbitrary_common_return" + duplicate = led("array.pixel[0].other.device") + wiring.update(nets([duplicate])) + self.assertEqual(decoupling_associations(parts + [duplicate], wiring), ()) + + def test_outer_bypass_cannot_fall_through_ambiguous_fpga_to_nested_memory(self) -> None: + fpga = PhysicalComponent( + "fpga.ic", "U1", "FP", "FPGA", {"1": "vdd.0", "2": "vdd.1", "3": "gnd.0", "4": "gnd.1"}, None, "fpga" + ) + memory = PhysicalComponent( + "fpga.mem.ic", "U2", "FP", "memory", {"1": "vcc", "2": "gnd", "3": "clk"}, None, "memory" + ) + self.assertEqual(terminal_roles(fpga), {}) + caps: list[PhysicalComponent] = [] + wiring = { + (fpga.path, "1"): "rail", + (fpga.path, "2"): "rail", + (fpga.path, "3"): "return", + (fpga.path, "4"): "return", + (memory.path, "1"): "rail", + (memory.path, "2"): "return", + (memory.path, "3"): "clock", + } + for wrapper in ("fpga.vio_cap0", "fpga.vio_cap1", "fpga.vpp_cap", "fpga.mem.vcc_cap"): + cap = PhysicalComponent( + wrapper + ".cap", + "C" + str(len(caps)), + "FP", + "100n", + {"1": "pos", "2": "neg"}, + {"lib_id": "Device:C"}, + "capacitors", + ) + cap.hierarchy = ((wrapper, "edg.abstract_parts.Capacitor.DecouplingCapacitor"),) + wiring[cap.path, "1"], wiring[cap.path, "2"] = "rail", "return" + caps.append(cap) + parts = [fpga, memory, *caps] + expected = [(memory.path, caps[-1].path)] + patterns = decoupling_associations(parts, wiring) + self.assertEqual([p.components for p in patterns], expected) + self.assertEqual(patterns, decoupling_associations(list(reversed(parts)), wiring)) + # If the direct owner's supplies become independently verifiable, the + # outer bypasses belong to that owner, while memory retains its own cap. + fpga.pins = {"1": "vdd", "3": "gnd", "4": "clk"} + wiring[fpga.path, "4"] = "fpga_clock" + patterns = decoupling_associations(parts, wiring) + self.assertEqual( + {p.components for p in patterns}, {(fpga.path, *(c.path for c in caps[:-1])), (memory.path, caps[-1].path)} + ) + + def test_footprint_owner_at_exact_wrapper_parent_blocks_nested_memory(self) -> None: + owner = PhysicalComponent( + "fpga", "U1", "FP", "FPGA", {"1": "vdd.0", "2": "vdd.1", "3": "gnd.0", "4": "gnd.1"}, None, "fpga" + ) + owner.hierarchy = (("fpga", "Test.FootprintWrapper"),) + memory = PhysicalComponent( + "fpga.mem.ic", "U2", "FP", "memory", {"1": "vcc", "2": "gnd", "3": "clk"}, None, "memory" + ) + outer = PhysicalComponent( + "fpga.bypass.cap", "C1", "FP", "100n", {"1": "pos", "2": "neg"}, {"lib_id": "Device:C"}, "outer" + ) + outer.hierarchy = ( + ("fpga", "Test.FootprintWrapper"), + ("fpga.bypass", "edg.abstract_parts.Capacitor.DecouplingCapacitor"), + ) + local = PhysicalComponent( + "fpga.mem.bypass.cap", "C2", "FP", "100n", {"1": "pos", "2": "neg"}, {"lib_id": "Device:C"}, "local" + ) + local.hierarchy = (("fpga.mem.bypass", "edg.abstract_parts.Capacitor.DecouplingCapacitor"),) + wiring = { + (owner.path, "1"): "rail", + (owner.path, "2"): "rail", + (owner.path, "3"): "return", + (owner.path, "4"): "return", + (memory.path, "1"): "rail", + (memory.path, "2"): "return", + (memory.path, "3"): "clock", + } + for cap in (outer, local): + wiring[cap.path, "1"], wiring[cap.path, "2"] = "rail", "return" + parts = [owner, memory, outer, local] + patterns = decoupling_associations(parts, wiring) + self.assertEqual([p.components for p in patterns], [(memory.path, local.path)]) + owner.pins = {"1": "vdd", "3": "gnd", "4": "clk"} + wiring[owner.path, "4"] = "fpga_clock" + patterns = decoupling_associations(parts, wiring) + self.assertEqual({p.components for p in patterns}, {(owner.path, outer.path), (memory.path, local.path)}) + + def test_chain_follows_physical_pins_and_is_permutation_invariant(self) -> None: + parts = [led("led[2].ic"), led("led[0].ic"), led("led[10].ic")] + actual = discover_patterns(parts, nets(parts)) + self.assertEqual( + actual, + discover_patterns(list(reversed(parts)), dict(reversed(list(nets(parts).items())))), + ) + self.assertEqual(actual[0].components, tuple(c.path for c in parts)) + self.assertEqual(actual[0].nets, ("n0", "n1")) + + def test_branch_and_ring_do_not_invent_a_serial_order(self) -> None: + parts = [led("a"), led("b"), led("c")] + wiring = nets(parts) + wiring["c", "2"] = "n0" # DIN fanout is not a serial connection. + self.assertEqual(discover_patterns(parts, wiring), ()) + wiring = nets(parts) + wiring["a", "2"] = wiring["c", "4"] + self.assertEqual(discover_patterns(parts, wiring), ()) + + def test_anonymous_or_ambiguous_roles_are_not_guessed(self) -> None: + c = led("a") + c.pins = {"1": "ports.1", "2": "ports.2", "3": "ports.3", "4": "ports.4"} + self.assertEqual(discover_patterns([c], {}), ()) + c.pins = {"1": "a.din", "2": "b.din"} + self.assertEqual(terminal_roles(c), {}) + + def test_feedback_divider_uses_symbol_and_terminal_roles(self) -> None: + ic = PhysicalComponent( + "reg.ic", + "U1", + "Test:IC", + "reg", + {"1": "fb", "2": "gnd", "3": "vin"}, + None, + "reg", + ) + hi = PhysicalComponent( + "reg.fb.top", + "R1", + "Test:R", + "10k", + {"1": "a", "2": "b"}, + {"lib_id": "Device:R"}, + "top", + ) + lo = PhysicalComponent( + "reg.fb.bottom", + "R2", + "Test:R", + "1k", + {"1": "a", "2": "b"}, + {"lib_id": "Device:R"}, + "bottom", + ) + wiring = { + (ic.path, "1"): "feedback", + (ic.path, "2"): "return", + (ic.path, "3"): "input", + (hi.path, "1"): "output", + (hi.path, "2"): "feedback", + (lo.path, "1"): "feedback", + (lo.path, "2"): "return", + } + # Parallel exposed/ground pads must not hide an otherwise exact FB role. + ic.pins["4"] = "gnd" + wiring[ic.path, "4"] = "return" + p = discover_patterns([lo, ic, hi], wiring)[0] + self.assertEqual(p.kind, "feedback_divider") + self.assertEqual(p.components, (ic.path, hi.path, lo.path)) + from .KiCadSchematicLayout import regroup + + regroup([lo, ic, hi], wiring) + self.assertEqual({c.group for c in (lo, ic, hi)}, {"reg"}) + hi.mapping = None + self.assertEqual(discover_patterns([lo, ic, hi], wiring), ()) + + def test_converter_support_requires_switch_role_and_local_output_cap(self) -> None: + ic = PhysicalComponent("buck.ic", "U1", "FP", "IC", {"1": "sw", "2": "gnd"}, None, "buck") + coil = PhysicalComponent( + "buck.coil", + "L1", + "FP", + "L", + {"1": "a", "2": "b"}, + {"lib_id": "Device:L"}, + "coil", + ) + cap = PhysicalComponent( + "buck.cap", + "C1", + "FP", + "C", + {"1": "pos", "2": "neg"}, + {"lib_id": "Device:C"}, + "cap", + ) + remote = PhysicalComponent("other.cap", "C2", "FP", "C", dict(cap.pins), dict(cap.mapping or {}), "other") + wiring = { + (ic.path, "1"): "switch", + (ic.path, "2"): "return", + (coil.path, "1"): "switch", + (coil.path, "2"): "rail", + } + for c in (cap, remote): + wiring[c.path, "1"] = "rail" + wiring[c.path, "2"] = "return" + pattern = discover_patterns([remote, cap, coil, ic], wiring)[0] + self.assertEqual(pattern.kind, "converter_output") + self.assertEqual(pattern.components, (ic.path, coil.path, cap.path)) + ic.pins["1"] = "ports.1" + self.assertEqual(discover_patterns([remote, cap, coil, ic], wiring), ()) + + def test_fields_avoid_long_vertical_label_without_moving_source_override(self) -> None: + from .KiCadSchematicLayout import ( + annotation_position, + annotation_bounds, + annotation_obstacles, + ) + + c = led("testpoint") + c.net_labels = { + "1": "regulator.feedback.really_long_voltage_testpoint", + "2": "GND", + } + view = SymbolView(generic(c).definition, [("1", 0, 10, 90), ("2", 10, 0, 180)], "Test:TP") + x, y, _ = annotation_position(c, view, 100, 100, 0) + box = annotation_bounds(c, x, y, 0) + for other in annotation_obstacles(c, view, 100, 100, 0): + self.assertFalse( + min(box[2], other[2]) > max(box[0], other[0]) and min(box[3], other[3]) > max(box[1], other[1]) + ) + self.assertEqual(annotation_position(c, view, 100, 100, 0), (x, y, "")) + c.annotation = (100, 120) + self.assertEqual(annotation_position(c, view, 100, 100, 0), (100, 120, "")) + + def test_rotated_instance_multiline_fields_remain_native_horizontal(self) -> None: + from .KiCadSchematicLayout import annotation_bounds + + c = led("a") + c.display_value = "a long manufacturer identifier with several words" + c.descriptions = ("external load terminal",) + a = annotation_bounds(c, 0, 0, 0) + b = annotation_bounds(c, 0, 0, 90) + self.assertLess(b[0], b[2]) + self.assertEqual(b, a) + self.assertGreater(b[2] - b[0], b[3] - b[1]) + + def test_amplifier_feedback_uses_explicit_negative_input(self) -> None: + ic = PhysicalComponent( + "amp.ic", + "U1", + "FP", + "amp", + {"1": "out", "2": "inp", "3": "inn"}, + None, + "amp", + ) + resistor = PhysicalComponent( + "amp.feedback", + "R1", + "FP", + "R", + {"1": "a", "2": "b"}, + {"lib_id": "Device:R"}, + "feedback", + ) + wiring = { + (ic.path, "1"): "output", + (ic.path, "2"): "signal", + (ic.path, "3"): "negative", + (resistor.path, "1"): "output", + (resistor.path, "2"): "negative", + } + self.assertEqual(discover_patterns([resistor, ic], wiring)[0].kind, "amplifier_feedback") + wiring[resistor.path, "2"] = "signal" + self.assertEqual(discover_patterns([resistor, ic], wiring), ()) + + def test_packed_amplifier_channels_require_matching_explicit_roles(self) -> None: + from .KiCadSchematicPatterns import amplifier_channels + + for names in ( + {"1": "outa", "2": "inna", "3": "inpa", "5": "inpb", "6": "innb", "7": "outb"}, + {"1": "out.0", "2": "inn.0", "3": "inp.0", "5": "inp.1", "6": "inn.1", "7": "out.1"}, + ): + amp = PhysicalComponent("packed.ic", "U1", "FP", "dual", names, None, "packed") + feedback = [ + PhysicalComponent( + "support." + name, ref, "FP", "part", {"1": "a", "2": "b"}, {"lib_id": symbol}, "support" + ) + for name, ref, symbol in ( + ("diode", "D1", "Device:D"), + ("resistor", "R1", "Device:R"), + ("wrong_channel", "R2", "Device:R"), + ) + ] + diode, resistor, wrong = feedback + wiring = { + (amp.path, "1"): "out0", + (amp.path, "2"): "neg0", + (amp.path, "3"): "signal0", + (amp.path, "7"): "out1", + (amp.path, "6"): "neg1", + (amp.path, "5"): "signal1", + (diode.path, "1"): "out0", + (diode.path, "2"): "neg0", + (resistor.path, "1"): "out1", + (resistor.path, "2"): "neg1", + (wrong.path, "1"): "out0", + (wrong.path, "2"): "neg1", + } + self.assertEqual(len(amplifier_channels(amp)), 2) + patterns = [p for p in discover_patterns([amp, *feedback], wiring) if p.kind == "amplifier_feedback"] + self.assertEqual({p.components for p in patterns}, {(amp.path, diode.path), (amp.path, resistor.path)}) + self.assertEqual( + patterns, + [p for p in discover_patterns([*reversed(feedback), amp], wiring) if p.kind == "amplifier_feedback"], + ) + # A duplicate explicit negative role invalidates its own channel. + amp.pins["9"] = amp.pins["2"] + self.assertEqual(len(amplifier_channels(amp)), 1) + remaining = [p for p in discover_patterns([amp, *feedback], wiring) if p.kind == "amplifier_feedback"] + self.assertEqual([p.components for p in remaining], [(amp.path, resistor.path)]) + + def test_unknown_diode_symbol_does_not_establish_feedback(self) -> None: + amp = PhysicalComponent("amp.ic", "U1", "FP", "amp", {"1": "outa", "2": "inna", "3": "inpa"}, None, "amp") + branch = PhysicalComponent("amp.diode", "D1", "FP", "diode", {"1": "a", "2": "b"}, None, "amp") + wiring = { + (amp.path, "1"): "output", + (amp.path, "2"): "negative", + (amp.path, "3"): "signal", + (branch.path, "1"): "output", + (branch.path, "2"): "negative", + } + self.assertEqual(discover_patterns([amp, branch], wiring), ()) + + def test_atomic_split_keeps_channel_bypass_together(self) -> None: + from .KiCadSchematicLayout import split_group + + parts = [led("ch[0].ic"), led("ch[1].ic")] + caps = [ + PhysicalComponent( + "ch[0].cap", + "C1", + "Test:C", + "1u", + {"1": "pos", "2": "neg"}, + None, + "chain", + ) + ] + caps[0].hierarchy = (("ch[0].cap", "edg.abstract_parts.Capacitor.DecouplingCapacitor"),) + views = {c.path: generic(c) for c in parts + caps} + views[caps[0].path].lib_id = "Device:C" + placed = [(parts[0], 10, 10, 0), (caps[0], 10, 40, 0), (parts[1], 80, 10, 0)] + wiring = nets(parts) + wiring[caps[0].path, "1"] = "arbitrary_common_supply" + wiring[caps[0].path, "2"] = "arbitrary_common_return" + split = split_group(placed, views, wiring) + assert split is not None + left, right = split + self.assertEqual([e[0].path for e in left], ["ch[0].ic", "ch[0].cap"]) + self.assertEqual([e[0].path for e in right], ["ch[1].ic"]) + + def test_serial_layout_follows_chain_and_retains_every_component(self) -> None: + parts = [led("ch[2].ic"), led("ch[0].ic"), led("ch[1].ic")] + views = {c.path: generic(c) for c in parts} + # Capacitor uses a verified symbol identity, never the C reference prefix. + cap = PhysicalComponent("ch[0].cap", "C1", "Test:C", "1u", {"1": "pos", "2": "neg"}, None, "chain") + cap.hierarchy = (("ch[0].cap", "edg.abstract_parts.Capacitor.DecouplingCapacitor"),) + parts.append(cap) + views[cap.path] = SymbolView( + views[parts[0].path].definition, + [("1", 0, -2.54, 270), ("2", 0, 2.54, 90)], + "Device:C", + ) + wiring = nets(parts[:3]) + wiring[cap.path, "1"] = "arbitrary_common_supply" + wiring[cap.path, "2"] = "arbitrary_common_return" + pages = place_group(parts, views, wiring) + flat = [entry for page in pages for entry in page] + self.assertEqual([c.path for c, _, _, _ in flat if c is not cap], [c.path for c in parts[:3]]) + self.assertEqual(sorted(c.path for c, _, _, _ in flat), sorted(c.path for c in parts)) + ch = next(e for e in flat if e[0].path == "ch[0].ic") + cp = next(e for e in flat if e[0] is cap) + self.assertEqual(ch[1], cp[1]) + self.assertGreater(cp[2], ch[2]) + self.assertEqual(pages, place_group(list(reversed(parts)), views, wiring)) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_pin_neck.py b/edg/electronics_model/test_schematic_pin_neck.py new file mode 100644 index 000000000..238e17a89 --- /dev/null +++ b/edg/electronics_model/test_schematic_pin_neck.py @@ -0,0 +1,193 @@ +"""Pin escapes remain visible and cache optimization preserves route decisions.""" + +from .KiCadSchematicTypes import GridPoint, Placement, PinKey +import os +import random +import unittest +from collections import defaultdict +from unittest.mock import patch +import xml.etree.ElementTree as ET + +from .KiCadSchematicExporter import ( + PhysicalComponent, + SymbolView, + generic, + node, + uid, + effects, + S, + KiCadSchematicExporter, +) +from .KiCadSchematicLayout import route_local, _NearForeignCache + + +def legacy_blocked(cache: _NearForeignCache, point: GridPoint, axis: int, net: str) -> bool: + for nx in (point[0] - 1, point[0], point[0] + 1): + for ny in (point[1] - 1, point[1], point[1] + 1): + if (nx, ny) == point: + continue + foreign = [axes for owner, axes in cache.tracks.get((nx, ny), {}).items() if owner != net] + if foreign and ((nx, ny) in cache.protected or any(axis in axes for axes in foreign)): + return True + return False + + +def neck_fixture() -> tuple[list[Placement], dict[str, SymbolView], dict[PinKey, str]]: + # Exact U12 left border53.48 and pin5/6 tips50.94,y117.12/120.93. + ic = PhysicalComponent("bms.ic", "U12", "Test:IC", "BMS", {"5": "scl", "6": "sda"}, None, "control") + definition = node( + "symbol", + "Fixture:U12", + node("symbol", "U12_0_1", node("rectangle", node("start", -16.52, 10.16), node("end", 16.52, -10.16))), + ) + body = definition[2] + pin_list: list[tuple[str, float, float, float]] = [] + for number, dy in (("5", -1.905), ("6", 1.905)): + body.append( + node( + "pin", + S("passive"), + S("line"), + node("at", -19.06, -dy, 0), + node("length", 2.54), + node("name", ic.pins[number], effects()), + node("number", number, effects()), + ) + ) + pin_list.append((number, -19.06, dy, 0)) + views = {ic.path: SymbolView(definition, pin_list, "Fixture:U12")} + placed: list[Placement] = [(ic, 70, 119.025, 0)] + nets = {("bms.ic", "5"): "scl", ("bms.ic", "6"): "sda"} + # Targets to the right encourage the old illegal shortcut through a pin + # neck toward the body instead of a visible outside route. + for index, (net, y) in enumerate((("scl", 100), ("sda", 145)), 1): + target = PhysicalComponent( + "target" + str(index), "TP" + str(index), "Test:One", "Target", {"1": "io"}, None, "control" + ) + views[target.path] = generic(target) + placed.append((target, 125, y, 0)) + nets[target.path, "1"] = net + return placed, views, nets + + +class PinNeckTest(unittest.TestCase): + def test_cache_matches_old_rule_across_incremental_tracks_and_protection(self) -> None: + rng = random.Random(137) + tracks: defaultdict[GridPoint, dict[str, set[int]]] = defaultdict(dict) + protected = set() + for _ in range(25): + p = (rng.randrange(-3, 4), rng.randrange(-3, 4)) + net = rng.choice(("a", "b", "c")) + tracks[p].setdefault(net, set()).add(rng.randrange(2)) + if rng.randrange(4) == 0: + protected.add(p) + cache = _NearForeignCache(tracks, protected) + + def verify() -> None: + for x in range(-4, 5): + for y in range(-4, 5): + for axis in (0, 1): + for net in ("a", "b", "c", "absent"): + self.assertEqual( + cache.blocked((x, y), axis, net), + legacy_blocked(cache, (x, y), axis, net), + ((x, y), axis, net), + ) + + verify() + for iteration in range(100): + p = (rng.randrange(-3, 4), rng.randrange(-3, 4)) + net = rng.choice(("a", "b", "c")) + if rng.randrange(3) == 0: + cache.protect((p,)) + cache.add_track(p, net, {rng.randrange(2)}) + if iteration % 10 == 0: + verify() + verify() + + def test_cache_keeps_legible_exact_perpendicular_interior_crossing(self) -> None: + tracks = defaultdict(dict, {(x, 0): {"a": {0}} for x in range(-4, 5)}) + cache = _NearForeignCache(tracks, {(-4, 0), (4, 0)}) + self.assertFalse(cache.blocked((0, 0), 1, "b")) + self.assertTrue(cache.blocked((0, 1), 0, "b")) + self.assertTrue(cache.blocked((-4, 1), 1, "b")) + + def test_cache_and_reference_produce_identical_q4_routes(self) -> None: + from .test_schematic_visual_clearance import fixture + + placed, views, nets = fixture() + cached = route_local(placed, views, nets) + with patch.object(_NearForeignCache, "blocked", legacy_blocked): + reference = route_local(placed, views, nets) + self.assertEqual(cached, reference) + + def test_u12_routes_never_backtrack_inside_pin_stub_or_library_leg(self) -> None: + placed, views, nets = neck_fixture() + wires, escapes, failures = route_local(placed, views, nets) + self.assertEqual(failures, []) + for number in ("5", "6"): + px, py, ex, ey, _ = escapes["bms.ic", number] + self.assertAlmostEqual(px, 50.94) + self.assertAlmostEqual(py, 117.12 if number == "5" else 120.93) + # Fixed stub remains outward. Every generated route segment stays + # outside the open escape-to-body corridor regardless of net. + for net, a, b in wires: + lo_x, hi_x = sorted((a[0], b[0])) + lo_y, hi_y = sorted((a[1], b[1])) + crosses_neck = max(lo_x, ex + 0.4) < min(hi_x, 53.48) and lo_y <= py <= hi_y + inside_neck_vertical = ex + 0.4 < a[0] < 53.48 and a[0] == b[0] and lo_y <= py <= hi_y + self.assertFalse(crosses_neck or inside_neck_vertical, (number, net, a, b)) + + def test_u12_native_nets_preserve_both_bare_pin_identities(self) -> None: + from .test_schematic_scene_native import export_native + + clis = tuple(filter(None, os.environ.get("PB_SCHEMATIC_TEST_KICAD_CLIS", "").split(os.pathsep))) + if not clis: + self.skipTest("Set PB_SCHEMATIC_TEST_KICAD_CLIS for native acceptance") + placed, views, nets = neck_fixture() + wires, escapes, failures = route_local(placed, views, nets) + self.assertEqual(failures, []) + wires += [(nets[key], (px, py), (ex, ey)) for key, (px, py, ex, ey, _) in escapes.items()] + root_id = uid("pin-neck-native", "root") + doc = node( + "kicad_sch", + node("version", 20250114), + node("generator", S("eeschema")), + node("uuid", root_id), + node("paper", "A3"), + node("lib_symbols", *[v.definition for v in views.values()]), + ) + for c, x, y, angle in placed: + sid = uid(root_id, c.path) + symbol = node( + "symbol", + node("lib_id", views[c.path].lib_id), + node("at", x, y, angle), + node("unit", 1), + node("in_bom", S("yes")), + node("on_board", S("yes")), + node("dnp", S("no")), + node("uuid", sid), + ) + for name, value in (("Reference", c.refdes), ("Value", c.value), ("Footprint", c.footprint)): + symbol.append(node("property", name, value, node("at", x, y, 0), effects(hide=True))) + symbol.extend(node("pin", n, node("uuid", uid(sid, n))) for n in c.pins) + symbol.append( + node( + "instances", + node( + "project", "Fixture", node("path", "/" + root_id, node("reference", c.refdes), node("unit", 1)) + ), + ) + ) + doc.append(symbol) + KiCadSchematicExporter._wires(doc, wires, "fixture", "pin-neck") + for cli in clis: + with self.subTest(cli=cli): + xml = ET.parse(export_native(self, cli, doc, "netlist")).getroot() + native = [ + {(n.attrib["ref"], n.attrib["pin"]) for n in net.findall("node")} + for net in xml.findall("./nets/net") + ] + self.assertIn({("U12", "5"), ("TP1", "1")}, native) + self.assertIn({("U12", "6"), ("TP2", "1")}, native) diff --git a/edg/electronics_model/test_schematic_planner.py b/edg/electronics_model/test_schematic_planner.py new file mode 100644 index 000000000..fd8892032 --- /dev/null +++ b/edg/electronics_model/test_schematic_planner.py @@ -0,0 +1,361 @@ +"""Whole-region planning is deterministic and rejects unsafe edited plans.""" + +from __future__ import annotations +from ..core import CompiledDesign +from .KiCadSchematicPlanner import SchematicSheetPlan + +from typing_extensions import override +import copy +import json +import math +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +from .KiCadSchematicPlanner import ( + SchematicRegion, + SchematicRegionPlacement, + SchematicSheet, + SchematicSheetPlanner, + OVERVIEW_BOUNDS, +) + + +def region( + identity: str, + width: float = 80, + height: float = 50, + scope: str = "(root)", + title: str | None = None, + components: tuple[str, ...] | None = None, + kind: str = "circuit", +) -> SchematicRegion: + return SchematicRegion( + identity, + title or identity, + scope, + (identity + ".part",) if components is None else components, + (-5, -10, width - 5, height - 10), + kind, + ) + + +class SchematicPlannerTest(unittest.TestCase): + @override + def setUp(self) -> None: + self.planner = SchematicSheetPlanner() + + def test_packs_whole_regions_together_and_is_order_independent(self) -> None: + regions = [region("controller"), region("power", 120, 70), region("usb", 70, 40)] + first = self.planner.plan_regions(regions, "fingerprint") + second = self.planner.plan_regions(list(reversed(regions)), "fingerprint") + self.assertEqual(first, second) + self.assertEqual(len(first.sheets), 1) + self.assertEqual({p.region_id for p in first.sheets[0].regions}, {r.id for r in regions}) + self.assertEqual(first.sheets[0].regions[0].region_id, "power") + self.assertEqual(first.regions[0].components, ("controller.part",)) + + def test_reserves_native_title_block(self) -> None: + plan = self.planner.plan_regions([region("a", 200, 200), region("b", 140, 80), region("c", 140, 80)], "f") + regions = {r.id: r for r in plan.regions} + for sheet in plan.sheets: + for p in sheet.regions: + r = regions[p.region_id] + self.assertTrue(p.x + r.bounds[2] - r.bounds[0] <= 230 or p.y + r.bounds[3] - r.bounds[1] <= 245) + + def test_json_round_trip_is_strict_and_does_not_alias_input(self) -> None: + plan = self.planner.plan_regions([region("power")], "fingerprint") + data = json.loads(json.dumps(plan.to_dict())) + self.assertEqual(SchematicSheetPlan.from_dict(data), plan) + adopted = self.planner.plan_regions(plan.regions, "fingerprint", requested=data) + self.assertEqual(adopted.sheets, plan.sheets) + data["regions"][0]["components"][0] = "mutated" + self.assertEqual(plan.regions[0].components, ("power.part",)) + bad = plan.to_dict() + bad["approved"] = True + with self.assertRaisesRegex(ValueError, "unknown or missing"): + SchematicSheetPlan.from_dict(bad) + bad = plan.to_dict() + bad["sheets"][0]["regions"][0]["x"] = True + with self.assertRaisesRegex(ValueError, "finite number"): + SchematicSheetPlan.from_dict(bad) + bad = plan.to_dict() + bad["overview"] = "yes" + with self.assertRaisesRegex(ValueError, "boolean"): + SchematicSheetPlan.from_dict(bad) + + def test_assignment_aliases_unknown_ambiguous_and_conflicting(self) -> None: + regions = [region("root::Power", title="Power"), region("root::USB", title="USB")] + plan = self.planner.plan_regions(regions, "f", assignments={"Power": "Supply", "root::Power": "Supply"}) + self.assertEqual( + next(s.title for s in plan.sheets if any(p.region_id == "root::Power" for p in s.regions)), "Supply" + ) + with self.assertRaisesRegex(ValueError, "unknown assignment"): + self.planner.plan_regions(regions, "f", assignments={"typo": "Supply"}) + with self.assertRaisesRegex(ValueError, "conflicting assignments"): + self.planner.plan_regions(regions, "f", assignments={"Power": "Supply", "root::Power": "Other"}) + with self.assertRaisesRegex(ValueError, "ambiguous"): + self.planner.plan_regions( + [region("a", title="Power"), region("b", title="Power", scope="other")], + "f", + assignments={"Power": "Supply"}, + ) + + def test_requested_plan_rejects_stale_fingerprint_geometry_and_membership(self) -> None: + regions = [region("a"), region("b")] + plan = self.planner.plan_regions(regions, "f") + with self.assertRaisesRegex(ValueError, "stale"): + self.planner.plan_regions(regions, "new", requested=plan) + bad = plan.to_dict() + bad["regions"][0]["components"] = ["different.part"] + with self.assertRaisesRegex(ValueError, "membership"): + self.planner.plan_regions(regions, "f", requested=bad) + bad = plan.to_dict() + bad["regions"][0]["bounds"][2] -= 1 + with self.assertRaisesRegex(ValueError, "bounds or membership"): + self.planner.plan_regions(regions, "f", requested=bad) + bad = plan.to_dict() + bad["sheets"][0]["regions"].pop() + with self.assertRaisesRegex(ValueError, "exactly once"): + self.planner.plan_regions(regions, "f", requested=bad) + bad = plan.to_dict() + bad["sheets"][0]["regions"].append(copy.deepcopy(bad["sheets"][0]["regions"][0])) + with self.assertRaisesRegex(ValueError, "more than once"): + SchematicSheetPlan.from_dict(bad) + + def test_requested_plan_rejects_overlap_small_gutter_outside_and_nonfinite(self) -> None: + regions = [region("a", 50, 30), region("b", 50, 30)] + plan = self.planner.plan_regions(regions, "f") + for x, y, message in [(20, 40, "overlap"), (77, 40, "gutter"), (394, 40, "outside")]: + bad = plan.to_dict() + bad["sheets"][0]["regions"][1].update(x=x, y=y) + with self.assertRaisesRegex(ValueError, message): + SchematicSheetPlan.from_dict(bad) + for value in (math.inf, math.nan, True): + with self.assertRaisesRegex(ValueError, "finite number"): + SchematicRegionPlacement("a", value, 40) + + def test_board_scopes_do_not_merge_even_with_heavy_adjacency(self) -> None: + regions = [region("left", scope="one"), region("right", scope="two")] + plan = self.planner.plan_regions(regions, "f", adjacency={("left", "right"): 1000}) + self.assertEqual(len(plan.sheets), 2) + self.assertEqual({s.scope for s in plan.sheets}, {"one", "two"}) + bad = plan.to_dict() + bad["sheets"][0]["scope"] = "two" + with self.assertRaisesRegex(ValueError, "between board scopes"): + SchematicSheetPlan.from_dict(bad) + + def test_explicit_fixed_set_can_continue_without_cropping(self) -> None: + regions = [region("a", 300, 150), region("b", 300, 150)] + plan = self.planner.plan_regions(regions, "f", assignments={"a": "Power", "b": "Power"}) + self.assertEqual({s.title for s in plan.sheets}, {"Overview", "Power /1", "Power /2"}) + self.assertTrue(any(d.startswith("continuation:") for d in plan.diagnostics)) + with self.assertRaisesRegex(ValueError, "exceeds usable A3.*no content was cropped"): + self.planner.plan_regions([region("oversize", 400, 250)], "f") + with self.assertRaisesRegex(ValueError, "overview inset"): + self.planner.plan_regions([region("mechanical", 200, 70)], "f", assignments={"mechanical": "Overview"}) + + def test_root_overview_contains_only_explicit_inset_regions(self) -> None: + regions = [region("mechanical", 230, 20), region("power", 100, 100), region("mcu", 100, 100)] + plan = self.planner.plan_regions( + regions, "f", assignments={"mechanical": "Overview", "power": "Power", "mcu": "MCU"} + ) + overview = next(s for s in plan.sheets if s.id == "overview") + self.assertEqual(overview.title, "Overview") + self.assertEqual(overview.regions[0].region_id, "mechanical") + self.assertEqual((overview.regions[0].x, overview.regions[0].y), OVERVIEW_BOUNDS[:2]) + bad = plan.to_dict() + bad["sheets"][0]["regions"][0]["y"] = 100 + with self.assertRaisesRegex(ValueError, "outside usable"): + SchematicSheetPlan.from_dict(bad) + + def test_overview_rules_and_empty_design(self) -> None: + one = self.planner.plan_regions([region("a")], "f") + self.assertEqual(len(one.sheets), 1) + multiple = self.planner.plan_regions([region("a", 300, 150), region("b", 300, 150)], "f") + self.assertEqual(len(multiple.sheets), 3) + self.assertEqual(multiple.sheets[0].id, "overview") + no_overview = self.planner.plan_regions(multiple.regions, "f", overview=False) + self.assertEqual(len(no_overview.sheets), 2) + empty = self.planner.plan_regions([region("empty", components=())], "f") + self.assertEqual(len(empty.sheets), 1) + self.assertEqual(SchematicSheetPlan.from_dict(empty.to_dict()), empty) + standalone_empty = self.planner.plan_regions([], "f") + self.assertEqual(standalone_empty.sheets[0].id, "overview") + with self.assertRaisesRegex(ValueError, "only an overview"): + SchematicSheet("empty", "Empty", "scope", ()) + + def test_automatic_overview_content_title_respects_reserved_overview(self) -> None: + circuit = region("a", title="Overview") + single = self.planner.plan_regions([circuit], "f") + self.assertEqual(single.regions[0].title, "Overview") + self.assertEqual(single.sheets[0].title, "Overview (circuit)") + self.assertNotEqual(single.sheets[0].id, "overview") + combined = self.planner.plan_regions( + [ + region("one", 300, 150, title="Overview"), + region("two", 300, 150, title="Overview"), + region("mount", 60, 20), + ], + "f", + assignments={"mount": "Overview"}, + ) + self.assertEqual( + [s.title for s in combined.sheets], ["Overview", "Overview (circuit) /1", "Overview (circuit) /2"] + ) + self.assertEqual(combined.sheets[0].id, "overview") + self.assertEqual([p.region_id for p in combined.sheets[0].regions], ["mount"]) + + def test_explicit_sheet_titles_take_precedence_over_automatic_overview_title(self) -> None: + plan = self.planner.plan_regions( + [region("auto", 300, 150, title="Overview"), region("base"), region("first")], + "f", + assignments={"base": "Overview (circuit)", "first": "Overview (circuit) /1"}, + ) + names = {p.region_id: s.title for s in plan.sheets for p in s.regions} + self.assertEqual( + names, {"auto": "Overview (circuit) /2", "base": "Overview (circuit)", "first": "Overview (circuit) /1"} + ) + + def test_adjacency_prefers_a_connected_sheet_when_both_fit(self) -> None: + # First two regions cannot share a sheet; the small third can fit either. + regions = [region("a", 250, 150), region("b", 250, 150), region("c", 40, 40)] + plan = self.planner.plan_regions(regions, "f", adjacency={("b", "c"): 5}) + locations = {p.region_id: s.id for s in plan.sheets for p in s.regions} + self.assertEqual(locations["b"], locations["c"]) + self.assertNotEqual(locations["a"], locations["c"]) + self.assertTrue(any(d.startswith("cross_sheet_connections:") for d in plan.diagnostics)) + + def test_continuations_are_numbered_within_functional_title(self) -> None: + regions = [ + region("a", 300, 150, title="Control"), + region("b", 300, 150, title="Control /2"), + region("c", 300, 150, title="USB"), + ] + plan = self.planner.plan_regions(regions, "f") + self.assertEqual({s.title for s in plan.sheets}, {"Overview", "Control /1", "Control /2", "USB"}) + + def test_continuation_page_order_is_numeric(self) -> None: + regions = [region(f"r{i:02}", 300, 150, title="Control") for i in range(12)] + plan = self.planner.plan_regions(regions, "f") + self.assertEqual([s.title for s in plan.sheets if s.id != "overview"], [f"Control /{i}" for i in range(1, 13)]) + + def test_mixed_titles_follow_underlying_region_continuations(self) -> None: + from .KiCadSchematicPlanner import _continuation_order + + regions = { + r.id: r + for r in [ + region("a", title="bms"), + region("b", title="bms /2"), + region("c", title="bms /3"), + region("d", title="epd"), + region("e", title="epd /2"), + ] + } + sheets = [ + SchematicSheet("a", "bms + alert", "(root)", (SchematicRegionPlacement("a", 20, 40),)), + SchematicSheet("b", "bms + vbus", "(root)", (SchematicRegionPlacement("b", 20, 40),)), + SchematicSheet("c", "bms + logic", "(root)", (SchematicRegionPlacement("c", 20, 40),)), + SchematicSheet("d", "epd", "(root)", (SchematicRegionPlacement("d", 20, 40),)), + SchematicSheet("e", "balance + epd", "(root)", (SchematicRegionPlacement("e", 20, 40),)), + ] + ordered = _continuation_order(list(reversed(sheets)), regions, []) + indices = {s.id: i for i, s in enumerate(ordered)} + self.assertLess(indices["a"], indices["b"]) + self.assertLess(indices["b"], indices["c"]) + self.assertLess(indices["d"], indices["e"]) + self.assertEqual(ordered, _continuation_order(sheets, regions, [])) + + def test_array_ranges_remain_ordered_when_first_page_waits_for_epd(self) -> None: + from .KiCadSchematicPlanner import _continuation_order + + regions = { + r.id: r + for r in [ + region("a", title="balance[0,1]"), + region("b", title="balance[2,3]"), + region("c", title="balance[4,5]"), + region("d", title="epd"), + region("e", title="epd /2"), + ] + } + sheets = [ + SchematicSheet( + "a", + "balance + epd", + "(root)", + (SchematicRegionPlacement("a", 20, 40), SchematicRegionPlacement("e", 20, 100)), + ), + SchematicSheet("b", "balance", "(root)", (SchematicRegionPlacement("b", 20, 40),)), + SchematicSheet("c", "balance", "(root)", (SchematicRegionPlacement("c", 20, 40),)), + SchematicSheet("d", "epd", "(root)", (SchematicRegionPlacement("d", 20, 40),)), + ] + diagnostics: list[str] = [] + ordered = _continuation_order(sheets, regions, diagnostics) + self.assertEqual([sheet.id for sheet in ordered], ["d", "a", "b", "c"]) + self.assertFalse(diagnostics) + + def test_signal_neighbour_is_packed_before_unrelated_larger_region(self) -> None: + regions = [region("a", 250, 150), region("b", 200, 60), region("c", 100, 60)] + plan = self.planner.plan_regions(regions, "f", adjacency={("a", "c"): 5}) + sheet = next(s for s in plan.sheets if any(p.region_id == "a" for p in s.regions)) + self.assertEqual([p.region_id for p in sheet.regions][:2], ["a", "c"]) + + def test_duplicate_component_ownership_and_unsafe_requested_assignment(self) -> None: + with self.assertRaisesRegex(ValueError, "more than one region"): + self.planner.plan_regions([region("a", components=("same",)), region("b", components=("same",))], "f") + regions = [region("a")] + plan = self.planner.plan_regions(regions, "f", assignments={"a": "Supply"}) + with self.assertRaisesRegex(ValueError, "conflicts with sheet assignment"): + self.planner.plan_regions(regions, "f", requested=plan, assignments={"a": "Other"}) + + def test_mechanical_kind_defaults_to_overview_and_explicit_override_wins(self) -> None: + regions = [region("root::holes", 230, 20, title="Any title", kind="mechanical"), region("power")] + plan = self.planner.plan_regions(regions, "f") + overview = next(sheet for sheet in plan.sheets if sheet.id == "overview") + self.assertEqual([p.region_id for p in overview.regions], ["root::holes"]) + for assignments in ({"root::holes": "Assembly notes"}, {"Any title": "Assembly notes"}): + plan = self.planner.plan_regions(regions, "f", assignments=assignments) + sheet = next(sheet for sheet in plan.sheets if sheet.title == "Assembly notes") + self.assertEqual([p.region_id for p in sheet.regions], ["root::holes"]) + self.assertFalse(next(sheet for sheet in plan.sheets if sheet.id == "overview").regions) + # A title alone does not classify a circuit as mechanical. + ordinary = self.planner.plan_regions([region("ordinary", title="Mechanical notes")], "f") + self.assertNotEqual(ordinary.sheets[0].id, "overview") + + def test_kind_json_compatibility_and_validation(self) -> None: + ordinary = region("circuit") + self.assertNotIn("kind", ordinary.to_dict()) + self.assertEqual(SchematicRegion.from_dict(ordinary.to_dict()).kind, "circuit") + mechanical = region("holes", 230, 20, kind="mechanical") + self.assertEqual(SchematicRegion.from_dict(mechanical.to_dict()), mechanical) + plan = self.planner.plan_regions([mechanical], "f") + self.assertEqual(SchematicSheetPlan.from_dict(plan.to_dict()), plan) + with self.assertRaisesRegex(ValueError, "region kind"): + region("bad", kind="guess") + with self.assertRaisesRegex(ValueError, "empty region"): + region("bad", kind="empty") + empty = region("empty", components=(), kind="empty") + self.assertEqual(SchematicRegion.from_dict(empty.to_dict()), empty) + + def test_plan_convenience_delegates_to_prepared_regions(self) -> None: + regions = (region("a"),) + from .KiCadSchematicExporter import SchematicExportOptions + from unittest.mock import Mock + + options = SchematicExportOptions("fixture") + from .KiCadSchematicExporter import KiCadSchematicExporter + + expected = self.planner.plan_regions(regions, "f") + compiled = Mock(spec=CompiledDesign) + with patch.object(KiCadSchematicExporter, "_plan_compiled", return_value=expected, create=True) as prepare: + plan = self.planner.plan(compiled, options) + prepare.assert_called_once_with(compiled, options) + self.assertIs(plan, expected) + self.assertEqual(plan.fingerprint, "f") + self.assertEqual(plan.regions, regions) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_presentation.py b/edg/electronics_model/test_schematic_presentation.py new file mode 100644 index 000000000..95aea46f2 --- /dev/null +++ b/edg/electronics_model/test_schematic_presentation.py @@ -0,0 +1,420 @@ +"""Presentation descriptions cannot alter physical inventory or net identity.""" + +from __future__ import annotations +from pathlib import Path +from ..core import CompiledDesign +from .KiCadSchematicTypes import SExpr, Placement +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +from typing_extensions import override +import json +import unittest +from dataclasses import replace +from .KiCadSchematicCircuits import SchematicCircuit, CircuitBoundary +from .KiCadSchematicExporter import _PreparedBoard +from .KiCadSchematicPlanner import SchematicRegionPlacement +from unittest import mock +from .KiCadSchematicPresentation import SchematicPresentation +from .KiCadSchematicReadability import inspect_documents, text_width +from .KiCadSchematicExporter import ( + KiCadSchematicExporter, + SchematicExportOptions, + children, +) +from .test_schematic_export import GeneratedMappedBoard, GeneratedMappedPart +from ..core import Block +from .PassivePort import Passive +from .RefdesRefinementPass import RefdesRefinementPass +from ..core import ScalaCompiler +import sexpdata + + +class GroundTerminal(Block): + def __init__(self) -> None: + super().__init__() + self.gnd = self.Port(Passive(), optional=True) + + +class SplitGroundBoard(Block): + @override + def contents(self) -> None: + super().contents() + self.raw = self.Block(GroundTerminal()) + self.system = self.Block(GroundTerminal()) + self.shunt = self.Block(GeneratedMappedPart()) + self.connect(self.raw.gnd, self.shunt.a) + self.connect(self.system.gnd, self.shunt.b) + + +class PresentationTest(unittest.TestCase): + compiled: CompiledDesign + + @classmethod + @override + def setUpClass(cls) -> None: + cls.compiled = ScalaCompiler.compile(GeneratedMappedBoard) + cls.compiled.append_values(RefdesRefinementPass().run(cls.compiled)) + + def test_annotations_and_pin_names_are_durable(self) -> None: + presentation = SchematicPresentation.from_dict( + dict( + components={ + "part": dict( + description="Target reset interface", + pin_names={"1": "RESET"}, + display_value="Reset resistor", + ) + }, + interfaces=[dict(component="part", pin="2", name="Target EN")], + ) + ) + options = SchematicExportOptions("Presentation", presentation=presentation) + exporter = KiCadSchematicExporter() + a = exporter.export(self.compiled, options) + b = exporter.export(self.compiled, options) + self.assertEqual(a.files, b.files) + self.assertIn("Target reset interface", "".join(a.files.values())) + self.assertIn("Target EN", "".join(a.files.values())) + self.assertEqual(json.loads(a.files["readability.json"])["visual_approval"], "pending") + self.assertEqual( + exporter.readability(self.compiled, options), + json.loads(a.files["readability.json"]), + ) + doc = next(sexpdata.loads(v) for k, v in a.files.items() if k.endswith(".kicad_sch")) + physical = [s for s in children(doc, "symbol") if any(p[1] == "PBPath" for p in children(s, "property"))] + self.assertEqual(len(physical), 1) + self.assertEqual({p[1] for p in children(physical[0], "pin")}, {"1", "2"}) + baseline = exporter.export(self.compiled, SchematicExportOptions("Presentation")) + self.assertNotEqual( + json.loads(a.files["manifest.json"])["fingerprint"], + json.loads(baseline.files["manifest.json"])["fingerprint"], + ) + + def test_fingerprint_excludes_source_location_metadata(self) -> None: + import copy + + compiled = copy.deepcopy(self.compiled) + exporter = KiCadSchematicExporter() + options = SchematicExportOptions("PortableFingerprint") + before = exporter.export(compiled, options) + entry = compiled.design.contents.meta.members.node["source_checkout_location"] + entry.text_leaf = "/different/machine/checkout/board.py:123" + after = exporter.export(compiled, options) + self.assertEqual(before.files, after.files) + + def test_circuit_summary_and_boundary_are_measured_and_exported(self) -> None: + presentation = SchematicPresentation.from_dict( + dict( + schema=2, + circuits=[ + dict( + id="interface", + title="Reset interface", + summary="Series interface between controller and target.", + components=["part"], + boundaries=[dict(component="part", pin="1", name="Controller reset", role="input")], + ) + ], + ) + ) + exporter = KiCadSchematicExporter() + options = SchematicExportOptions("CircuitMeaning", presentation=presentation) + bundle = exporter.export(self.compiled, options) + self.assertEqual(bundle.files, exporter.export(self.compiled, options).files) + model = json.loads(bundle.files["circuit-model.json"])["boards"][0] + circuit = next(c for c in model["circuits"] if c["id"] == "interface") + self.assertEqual(circuit["boundaries"][0]["component"], "part") + documents = "".join(value for name, value in bundle.files.items() if name.endswith(".kicad_sch")) + self.assertIn("Series interface between controller and target.", documents) + self.assertIn("Controller reset:", documents) + regions, _ = exporter.prepare_regions(self.compiled, options) + plain, _ = exporter.prepare_regions(self.compiled, SchematicExportOptions("CircuitMeaning")) + self.assertGreater(regions[0].bounds[3] - regions[0].bounds[1], plain[0].bounds[3] - plain[0].bounds[1]) + + def test_tall_authored_circuit_notes_use_measured_side_column(self) -> None: + from .KiCadSchematicExporter import PhysicalComponent, SymbolView, node + + component = PhysicalComponent("power", "U1", "Test:Power", "Power", {}, None, "Power") + component.functional_circuit = SchematicCircuit( + id="power", + title="Power", + components=("power",), + provenance="explicit", + summary="Protected input and regulated output stage.", + boundaries=( + CircuitBoundary( + component="power", pin="1", name="Protected supply input", role="supply", net="protected_supply" + ), + ), + ) + component.net_labels = {"1": "protected_supply"} + view = SymbolView(node("symbol", "Test:Power"), [], "Test:Power") + placed: list[Placement] = [(component, 0, 0, 0)] + # A 275 mm wide, 203.94 mm tall circuit (including title) already fills + # the wide A3 height. Adding notes above it would exceed that space. + import importlib + + exporter_module = importlib.import_module(__package__ + ".KiCadSchematicExporter") + with ( + mock.patch.object(exporter_module, "graphic_bounds", return_value=(0, 0, 269, 192.4)), + mock.patch.object(exporter_module, "annotation_bounds", return_value=(0, 0, 1, 1)), + ): + geometry = KiCadSchematicExporter._region_geometry(placed, {"power": view}, {}, {}, [], "Power") + self.assertEqual( + geometry, KiCadSchematicExporter._region_geometry(placed, {"power": view}, {}, {}, [], "Power") + ) + ordinary = replace(component) + plain = KiCadSchematicExporter._region_geometry([(ordinary, 0, 0, 0)], {"power": view}, {}, {}, [], "Power") + with ( + mock.patch.object(exporter_module, "graphic_bounds", return_value=(0, 0, 365, 192.4)), + mock.patch.object(exporter_module, "annotation_bounds", return_value=(0, 0, 1, 1)), + ): + overflow = KiCadSchematicExporter._region_geometry(placed, {"power": view}, {}, {}, [], "Power") + self.assertGreater(overflow[0][3] - overflow[0][1], 205) + self.assertEqual(len(overflow[2]), 1) # Neither alternative fits: normal caller rejects it. + # Real PDU converter title/body occupied 205.85 mm before notes. + # Side mode may reduce only surplus title whitespace to fit this case. + for content_bottom, expected_height in ((194.31, 204.58), (196.0, 204.54)): + with ( + mock.patch.object(exporter_module, "graphic_bounds", return_value=(0, 0, 269, content_bottom)), + mock.patch.object(exporter_module, "annotation_bounds", return_value=(0, 0, 1, 1)), + ): + compact = KiCadSchematicExporter._region_geometry(placed, {"power": view}, {}, {}, [], "Power") + self.assertEqual(len(compact[2]), 2) + self.assertAlmostEqual(compact[0][3] - compact[0][1], expected_height) + title = compact[1][0] + self.assertLessEqual(title[3] + title[1] / 2, -1.27) + bounds, headings, boxes = geometry + self.assertLessEqual(bounds[2] - bounds[0], 375) + self.assertLessEqual(bounds[3] - bounds[1], 205) + self.assertAlmostEqual(bounds[3] - bounds[1], plain[0][3] - plain[0][1]) + self.assertEqual(len(boxes), 2) + self.assertGreater(boxes[1][0], plain[0][2]) + self.assertTrue(any("Protected supply input" in line for line, *_ in headings)) + for line, size, x, y in headings: + self.assertGreaterEqual(x, bounds[0]) + self.assertLessEqual(x + text_width(line, size), bounds[2]) + self.assertGreaterEqual(y - size, bounds[1]) + self.assertLessEqual(y + size, bounds[3]) + from .KiCadSchematicExporter import _RegionDrawing + from .KiCadSchematicPlanner import SchematicRegion + + drawing = _RegionDrawing( + SchematicRegion("power", "Power", "root", ("power",), bounds), placed, [], [], {}, headings, boxes + ) + board = _PreparedBoard( + scope="root", + prefix="board", + root_id="root", + views={"power": view}, + pin_nets={}, + names={}, + regions={"power": drawing}, + net_regions={}, + ) + doc: SExpr = [] + KiCadSchematicExporter()._render_region( + doc, board, drawing, SchematicRegionPlacement("power", x=20, y=40), "sheet", "root", {}, None, set(), [] + ) + text_nodes = children(doc, "text") + self.assertEqual([node[1] for node in text_nodes], [line for line, *_ in headings]) + for text_node, (_, _, x, y) in zip(text_nodes, headings): + at = children(text_node, "at")[0] + self.assertAlmostEqual(at[1], round(x + 20 - bounds[0], 4)) + self.assertAlmostEqual(at[2], round(y + 40 - bounds[1], 4)) + + def test_distinct_returns_are_named_without_merging_the_shunt(self) -> None: + from .NetlistGenerator import NetlistTransform + from .KiCadSchematicExporter import node + + compiled = ScalaCompiler.compile(SplitGroundBoard) + compiled.append_values(RefdesRefinementPass().run(compiled)) + physical = next(iter(NetlistTransform(compiled).run().values())) + net_pins = {net.name: {(str(pin.block_path), pin.pin_name) for pin in net.pins} for net in physical.nets} + self.assertEqual(set(net_pins), {"system.gnd", "raw.gnd"}) + self.assertNotEqual( + next(net for net, pins in net_pins.items() if ("shunt", "1") in pins), + next(net for net, pins in net_pins.items() if ("shunt", "2") in pins), + ) + # Isolate the presentation behavior from an external symbol-library install. + # Native multi-ground equality is separately exercised on real boards. + import importlib + + module = importlib.import_module(__package__ + ".KiCadSchematicExporter") + ground = node("symbol", "power:GND", node("symbol", "GND_0_1")) + exporter = KiCadSchematicExporter() + with mock.patch.object(module, "ground_symbol", return_value=ground): + bundle = exporter.export(compiled, SchematicExportOptions("SplitGround")) + documents = [sexpdata.loads(value) for name, value in bundle.files.items() if name.endswith(".kicad_sch")] + grounds = [ + symbol + for doc in documents + for symbol in children(doc, "symbol") + if children(symbol, "lib_id")[0][1] == "power:GND" + ] + self.assertEqual( + {prop[2] for symbol in grounds for prop in children(symbol, "property") if prop[1] == "Value"}, + {"system.gnd", "raw.gnd"}, + ) + visible = [text[1] for doc in documents for text in children(doc, "text")] + self.assertIn("system.gnd", visible) + self.assertIn("raw.gnd", visible) + self.assertEqual(len(grounds), 2) + prepared, _, _, _ = exporter._prepare_boards(compiled, SchematicExportOptions("SplitGround")) + labels = { + label + for board in prepared + for region in board.regions.values() + for component, *_ in region.placed + for label in component.ground_net_labels.values() + } + self.assertEqual(labels, {"system.gnd", "raw.gnd"}) + from .KiCadSchematicLayout import ground_bounds, ground_label_position + from .KiCadSchematicScene import text_bounds + + for angle in (0, 90, 180, 270): + x, y = ground_label_position(50, 50, angle) + bounds = ground_bounds(50, 50, angle, "raw.gnd") + text = text_bounds("raw.gnd", x, y) + self.assertTrue(bounds[0] <= text[0] <= text[2] <= bounds[2]) + self.assertTrue(bounds[1] <= text[1] <= text[3] <= bounds[3]) + + def test_distinct_return_model_native_roundtrip(self) -> None: + import os + import subprocess + import tempfile + from pathlib import Path + from .KiCadSchematicExporter import node, effects, S + from .NetlistGenerator import NetlistTransform + from .SchematicVerification import verify_schematic_netlist + + clis = tuple(filter(None, os.environ.get("PB_SCHEMATIC_TEST_KICAD_CLIS", "").split(os.pathsep))) + if not clis: + clis = tuple(filter(None, (os.environ.get("KICAD_CLI9"), os.environ.get("KICAD_CLI10")))) + if not clis: + self.skipTest("Set PB_SCHEMATIC_TEST_KICAD_CLIS for native split-return acceptance") + compiled = ScalaCompiler.compile(SplitGroundBoard) + compiled.append_values(RefdesRefinementPass().run(compiled)) + physical = {str(scope): netlist for scope, netlist in NetlistTransform(compiled).run().items()} + with tempfile.TemporaryDirectory() as temporary: + folder = Path(temporary) + # Minimal zero-length standard ground power pin: instance Value + # carries its compiled net name, exactly as the installed libraries. + definition = node( + "symbol", + "GND", + node("power"), + node("pin_names", node("offset", 0)), + node("in_bom", S("yes")), + node("on_board", S("yes")), + node("property", "Reference", "#PWR", node("at", 0, 0, 0), effects(hide=True)), + node("property", "Value", "GND", node("at", 0, -3.81, 0), effects()), + node("symbol", "GND_0_1"), + node( + "symbol", + "GND_1_1", + node( + "pin", + S("power_in"), + S("line"), + node("at", 0, 0, 90), + node("length", 0), + node("name", "GND", effects()), + node("number", "1", effects()), + ), + ), + ) + library = node( + "kicad_symbol_lib", node("version", 20241209), node("generator", S("kicad_symbol_editor")), definition + ) + (folder / "power.kicad_sym").write_text(sexpdata.dumps(library), encoding="utf-8") + bundle = KiCadSchematicExporter().export( + compiled, SchematicExportOptions("SplitGround", symbol_library_dirs=(str(folder),)) + ) + bundle.write(folder / "artifacts") + for index, cli in enumerate(clis): + for board in json.loads(bundle.files["manifest.json"])["boards"]: + with self.subTest(cli=cli): + schematic = folder / "artifacts" / board["root"] + xml = folder / ("native" + str(index) + ".xml") + result = subprocess.run( + [cli, "sch", "export", "netlist", "--format", "kicadxml", "-o", str(xml), str(schematic)], + capture_output=True, + text=True, + timeout=60, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + verify_schematic_netlist(physical[board["scope"]], xml) + import xml.etree.ElementTree as ET + + nets = ET.parse(xml).getroot().findall("./nets/net") + self.assertEqual({net.attrib["name"] for net in nets}, {"raw.gnd", "system.gnd"}) + self.assertEqual(sorted(len(net.findall("node")) for net in nets), [1, 1]) + svg = folder / ("svg" + str(index)) + result = subprocess.run( + [cli, "sch", "export", "svg", "-o", str(svg), str(schematic)], + capture_output=True, + text=True, + timeout=60, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertTrue(list(svg.glob("*.svg"))) + + def test_invalid_paths_and_pins_fail(self) -> None: + for data in [ + dict(components={"missing": {}}), + dict(components={"part": dict(pin_names={"77": "GATE"})}), + dict(interfaces=[dict(component="part", pin="77", name="Load")]), + dict(groups={"missing": "Power"}), + ]: + with self.subTest(data=data), self.assertRaises(ValueError): + KiCadSchematicExporter().export( + self.compiled, + SchematicExportOptions("Invalid", presentation=SchematicPresentation.from_dict(data)), + ) + + def test_strict_schema(self) -> None: + for value in [ + dict(schema=True), + dict(unknown=1), + dict(components={"part": dict(footprint="wrong")}), + dict(interfaces=[dict(component="part")]), + ]: + with self.subTest(value=value), self.assertRaises(ValueError): + SchematicPresentation.from_dict(value) + + def test_scene_text_checks(self) -> None: + def text(value: str, x: float) -> str: + return f'(text "{value}" (at {x} 50 0) (effects (font (size 1.27 1.27))) (uuid "{value}"))' + + report = inspect_documents( + {"a.kicad_sch": "(kicad_sch " + text("alpha", 50) + text("beta", 50) + ")"}, + [], + ) + self.assertTrue(any(f["code"] == "text_collision" for f in report["findings"])) + self.assertEqual(report["visual_approval"], "pending") + self.assertGreater(text_width("界", 1), text_width("a", 1)) + self.assertEqual( + report, + inspect_documents( + {"a.kicad_sch": "(kicad_sch " + text("alpha", 50) + text("beta", 50) + ")"}, + [], + ), + ) + + def test_pin_name_scene_uses_library_y_up_coordinates(self) -> None: + for rotation in (0, 90): + doc = ( + '(kicad_sch (lib_symbols (symbol "Test:Part" (symbol "Part_1_1" (pin passive line (at 0 5 0) (length 1) (name "PIN") (number "1"))))) (symbol (lib_id "Test:Part") (at 40 50 ' + + str(rotation) + + ') (property "PBPath" "part")))' + ) + report = inspect_documents({"a.kicad_sch": doc}, []) + text = next(t for t in report["scenes"][0]["texts"] if t["kind"] == "pin_name") + x1, y1, x2, y2 = text["bounds"] + if rotation == 0: + self.assertAlmostEqual((y1 + y2) / 2, 45) + self.assertAlmostEqual(x1, 41.508) + else: + self.assertAlmostEqual((x1 + x2) / 2, 35) + self.assertAlmostEqual(y2, 48.492) diff --git a/edg/electronics_model/test_schematic_regions.py b/edg/electronics_model/test_schematic_regions.py new file mode 100644 index 000000000..0b3b3b9bc --- /dev/null +++ b/edg/electronics_model/test_schematic_regions.py @@ -0,0 +1,153 @@ +"""Measured-region regressions independent of human visual acceptance.""" + +from __future__ import annotations +from typing import Any, Sequence +from .KiCadSchematicTypes import SExpr, PinNets, Placement, Views +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +from typing_extensions import override +import unittest +import importlib +from types import SimpleNamespace +from unittest.mock import patch + +from ..core import Block, ScalaCompiler +from .KiCadSchematicExporter import ( + KiCadSchematicExporter, + SchematicExportOptions, + children, + generic, + node, + _RegionDrawing, +) +from .KiCadSchematicLayout import ground_bounds, ground_rotation, annotation_position, graphic_bounds +from .KiCadSchematicPlanner import SchematicRegion, SchematicRegionPlacement, SchematicSheet +from .RefdesRefinementPass import RefdesRefinementPass +from .test_schematic_export import GeneratedMappedBoard + + +class TwoCircuitParts(Block): + @override + def contents(self) -> None: + super().contents() + self.a = self.Block(GeneratedMappedBoard()) + self.b = self.Block(GeneratedMappedBoard()) + + +class ContinuationCollisionBoard(Block): + @override + def contents(self) -> None: + super().contents() + self.foo = self.Block(TwoCircuitParts()) + setattr(self, "foo /2", self.Block(GeneratedMappedBoard())) + + +class SchematicRegionTest(unittest.TestCase): + def test_ground_graphic_points_away_from_adjacent_pin_rows(self) -> None: + # The contact remains at the stub endpoint; the complete graphic must + # extend outwards, never down into the next connector/IC pin row. + for direction, rotation in ((0, 270), (90, 0), (180, 90), (270, 180)): + self.assertEqual(ground_rotation(direction), rotation) + xmin, ymin, xmax, ymax = ground_bounds(100, 100, direction) + if direction == 0: + self.assertLess(xmin, 100) + self.assertEqual(xmax, 100) + elif direction == 180: + self.assertEqual(xmin, 100) + self.assertGreater(xmax, 100) + elif direction == 90: + self.assertEqual(ymin, 100) + self.assertGreater(ymax, 100) + else: + self.assertLess(ymin, 100) + self.assertEqual(ymax, 100) + + def test_default_ic_fields_clear_ground_stub_and_graphic(self) -> None: + component = PhysicalComponent("ic", "U1", "Test:FP", "device", {"1": "gnd"}, None, "IC") + view = generic(component) + _, _, _, bottom = graphic_bounds(view) + _, field_y, _ = annotation_position(component, view, 100, 100, 0) + self.assertGreater(field_y - 1.27, 100 + bottom + 3.81 + 4.445) + + def test_short_inter_region_wire_requires_a_clear_corridor(self) -> None: + definition = node( + "symbol", + "Test:C", + node("symbol", "C_0_1", node("rectangle", node("start", -1.27, 1.27), node("end", 1.27, -1.27))), + ) + view = SymbolView(definition, [("1", 0, -3.81, 270), ("2", 0, 3.81, 90)], "Device:C") + regions = {} + components = [] + for index in range(2): + name = "cap" + str(index) + component = PhysicalComponent( + name, "C" + str(index + 1), "Test:FP", "100nF", {"1": "pwr", "2": "gnd"}, None, name + ) + components.append(component) + spec = SchematicRegion(name, name, "root", (name,), (50, 50, 80, 100)) + regions[name] = _RegionDrawing(spec, [(component, 65, 75, 0)], [], []) + from .KiCadSchematicExporter import _PreparedBoard + + board = _PreparedBoard( + scope="root", + prefix="root", + root_id="root", + regions=regions, + views={c.path: view for c in components}, + pin_nets={(c.path, pin): net for c in components for pin, net in (("1", "v3v3"), ("2", "gnd"))}, + names={"v3v3": "v3v3", "gnd": "gnd"}, + ) + sheet = SchematicSheet( + "sheet", + "Caps", + "root", + (SchematicRegionPlacement("cap0", 20, 40), SchematicRegionPlacement("cap1", 58, 40)), + ) + clear: SExpr = [] + KiCadSchematicExporter._inter_region_wires(clear, board, sheet, "id", []) + self.assertEqual(len(children(clear, "wire")), 1) + blocked: SExpr = [] + KiCadSchematicExporter._inter_region_wires(blocked, board, sheet, "id", [("other_net", (54, 50), (54, 60))]) + self.assertFalse(children(blocked, "wire")) + + def test_unwrapped_value_reserves_full_rendered_width(self) -> None: + component = PhysicalComponent("x", "U1", "Test:FP", "W" * 40, {}, None, "Tiny") + view = generic(component) + bounds = KiCadSchematicExporter._region_bounds([(component, 70, 80, 0)], {"x": view}, {}, {}, [], "Tiny") + # Full 40-character native line plus 0.3 mm stroke clearance on + # each side and the region's 3 mm left/right packing margin. + self.assertGreaterEqual(bounds[2] - bounds[0], 40 * 1.27 + 6.6 - 1e-6) + + def test_heading_wrap_and_measured_width(self) -> None: + component = PhysicalComponent("x", "U1", "Test:FP", "part", {}, None, "Tiny") + view = generic(component) + short = KiCadSchematicExporter._region_bounds([(component, 70, 80, 0)], {"x": view}, {}, {}, [], "X") + long = KiCadSchematicExporter._region_bounds( + [(component, 70, 80, 0)], {"x": view}, {}, {}, [], "functional " * 20 + ) + self.assertLess(long[1], short[1]) + self.assertGreaterEqual(long[2] - long[0], 42) + + def test_literal_name_cannot_overwrite_another_groups_continuation(self) -> None: + compiled = ScalaCompiler.compile(ContinuationCollisionBoard) + compiled.append_values(RefdesRefinementPass().run(compiled)) + + def split_every_member( + members: Sequence[PhysicalComponent], views: Views, pin_nets: PinNets, **options: Any + ) -> list[list[Placement]]: + return [[(c, 70, 80, 0)] for c in members] + + with patch.object( + importlib.import_module(__package__ + ".KiCadSchematicExporter"), + "place_group", + side_effect=split_every_member, + ): + regions, _ = KiCadSchematicExporter().prepare_regions(compiled, SchematicExportOptions("Collision")) + paths = [path for region in regions for path in region.components] + self.assertEqual(len(paths), 3) + self.assertEqual(len(set(paths)), 3) + self.assertEqual(len({r.id for r in regions}), 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_routing_optimizer.py b/edg/electronics_model/test_schematic_routing_optimizer.py new file mode 100644 index 000000000..ecb09e756 --- /dev/null +++ b/edg/electronics_model/test_schematic_routing_optimizer.py @@ -0,0 +1,148 @@ +"""Fixed-placement search keeps the baseline unless a bounded trial improves it.""" + +from __future__ import annotations +from .KiCadSchematicTypes import PinNets, Placements, Views, RouteResult +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import copy +import unittest +from collections import defaultdict + +from .KiCadSchematicExporter import node +from .KiCadSchematicLayout import route_local, tree_distance +from .KiCadSchematicRouting import optimize_fixed_routes, route_metrics + + +class RoutingOptimizerTest(unittest.TestCase): + def test_tree_heuristic_matches_nearest_actual_tree_point(self) -> None: + # Inside a sparse U-shaped tree, bounding-box distance is zero but + # the actual remaining route still has a substantial lower bound. + targets = {(x, 0) for x in range(41)} | {(0, y) for y in range(41)} | {(40, y) for y in range(41)} + distance = tree_distance(targets) + self.assertEqual(distance((20, 30)), 20) + for x in range(-5, 46, 3): + for y in range(-5, 46, 3): + expected = min(abs(x - tx) + abs(y - ty) for tx, ty in targets) + self.assertEqual(distance((x, y)), expected) + self.assertEqual(distance((x, y)), expected) # Cached query. + + def test_union_metrics_are_independent_of_duplicate_and_split_segments(self) -> None: + wires = [("a", (0, 0), (10, 0)), ("a", (10, 0), (10, 10)), ("b", (5, -2), (5, 2))] + expected = dict(length_mm=24, bends=1, crossings=1, failures=0) + self.assertEqual(route_metrics(wires, []), expected) + overlapping = [("a", (0, 0), (5, 0)), ("a", (3, 0), (10, 0)), wires[1], wires[2], wires[2]] + self.assertEqual(route_metrics(overlapping, []), expected) + self.assertEqual(route_metrics(list(reversed(overlapping)), []), expected) + + def test_real_routes_shorten_without_changing_fixed_placements_or_net_identity(self) -> None: + placed, views, wiring = [], {}, {} + for i, (x, y) in enumerate(((127, 63.5), (76.2, 88.9), (76.2, 114.3), (101.6, 114.3))): + component = PhysicalComponent( + str(i), "X" + str(i), "Fixture:Pad", "Pad", {"1": "p"}, None, "group", annotation=(x + 5, y + 10) + ) + placed.append((component, x, y, 0)) + views[component.path] = SymbolView(node("symbol"), [("1", 0, 0, 0)], "Fixture:Pad") + wiring[component.path, "1"] = "signal" + original = copy.deepcopy((placed, views, wiring)) + baseline = route_local(placed, views, wiring) + actual, report = optimize_fixed_routes(placed, views, wiring, baseline, route_local) + self.assertEqual((placed, views, wiring), original) + self.assertLess(report["after"]["length_mm"], report["before"]["length_mm"]) + self.assertEqual(actual[1], baseline[1]) # Every physical pin escape remains fixed. + self.assertEqual(actual[2], []) + self.assertEqual({net for net, _, _ in actual[0]}, {"signal"}) + reverse = (list(reversed(placed)), dict(reversed(list(views.items()))), dict(reversed(list(wiring.items())))) + reversed_baseline = route_local(*reverse) + reversed_actual = optimize_fixed_routes(*reverse, reversed_baseline, route_local) + self.assertEqual(reversed_actual, (actual, report)) + # Exercise both heading-aware searches directly, even when another + # candidate wins. Reconstruct their grid graph to catch lost/truncated + # predecessor states or a route that misses an existing tree attachment. + tight = [(c, 63.5 + i * 6.35, 76.2 + (i % 2) * 6.35, a) for i, (c, _, _, a) in enumerate(placed)] + tight_baseline = route_local(tight, views, wiring) + for strategy in ("tree_search", "tree_reverse"): + wires, escapes, failures = route_local(tight, views, wiring, strategy=strategy) + self.assertEqual(failures, []) + self.assertEqual(escapes, tight_baseline[1]) + self.assertEqual( + (wires, escapes, failures), route_local(list(reversed(tight)), views, wiring, strategy=strategy) + ) + graph = defaultdict(set) + for _, a, b in wires: + start = (round(a[0] / 0.635), round(a[1] / 0.635)) + end = (round(b[0] / 0.635), round(b[1] / 0.635)) + self.assertTrue(start[0] == end[0] or start[1] == end[1]) + dx = (end[0] > start[0]) - (end[0] < start[0]) + dy = (end[1] > start[1]) - (end[1] < start[1]) + while start != end: + next_point = start[0] + dx, start[1] + dy + graph[start].add(next_point) + graph[next_point].add(start) + start = next_point + endpoints = {(round(escape[2] / 0.635), round(escape[3] / 0.635)) for escape in escapes.values()} + pending, reached = [min(endpoints)], set() + while pending: + point = pending.pop() + if point not in reached: + reached.add(point) + pending.extend(graph[point] - reached) + self.assertTrue(endpoints.issubset(reached)) + + def test_candidate_gates_reject_new_failures_crossings_length_and_envelope_growth(self) -> None: + baseline: RouteResult = ([("a", (0, 0), (10, 0)), ("a", (10, 0), (10, 10))], {}, []) + candidates: dict[str, RouteResult] = { + "new_failure": ([("a", (0, 0), (5, 0))], {}, [(("device", "1"), "a")]), + "crossing": ([("a", (0, 5), (10, 5)), ("b", (5, 0), (5, 10))], {}, []), + "longer": ([("a", (0, 0), (10, 0)), ("a", (10, 0), (10, 10)), ("a", (10, 10), (0, 10))], {}, []), + "outside": ([("a", (-1, 0), (2, 0))], {}, []), + } + for reason, candidate in candidates.items(): + with self.subTest(reason=reason): + calls = [] + + def router( + placed: Placements, views: Views, pin_nets: PinNets, *, strategy: str = "shortest" + ) -> RouteResult: + calls.append(strategy) + return candidate + + result, report = optimize_fixed_routes([], {}, {}, baseline, router) + self.assertEqual(result, baseline) + self.assertEqual(report["selected"], "baseline") + self.assertEqual(len(calls), report["candidates"] - 1) + self.assertLessEqual(len(calls), 8) + self.assertEqual(len(calls), len(set(calls))) + self.assertTrue(all(not trial["acceptable"] for trial in report["trials"])) + + def test_longer_detour_can_remove_crossing_outside_original_envelope(self) -> None: + baseline: RouteResult = ([("a", (50, 60), (70, 60)), ("b", (60, 50), (60, 70))], {}, []) + candidate: RouteResult = ( + [ + ("a", (50, 60), (50, 45)), + ("a", (50, 45), (70, 45)), + ("a", (70, 45), (70, 60)), + ("b", (60, 50), (60, 70)), + ], + {}, + [], + ) + actual, report = optimize_fixed_routes([], {}, {}, baseline, lambda *args, **kwargs: candidate) + self.assertEqual(actual, candidate) + self.assertEqual(report["after"]["crossings"], 0) + self.assertGreater(report["after"]["length_mm"], report["before"]["length_mm"]) + + def test_equal_score_keeps_baseline_and_empty_baseline_does_not_search(self) -> None: + baseline: RouteResult = ([("a", (0, 0), (10, 0))], {}, []) + result, report = optimize_fixed_routes([], {}, {}, baseline, lambda *args, **kwargs: baseline) + self.assertIs(result, baseline) + self.assertEqual(report["selected"], "baseline") + + def forbidden(*args: object, **kwargs: object) -> RouteResult: + self.fail("Empty baseline must not invoke candidate router") + + empty: RouteResult = ([], {}, []) + self.assertEqual(optimize_fixed_routes([], {}, {}, empty, forbidden)[0], empty) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_scene.py b/edg/electronics_model/test_schematic_scene.py new file mode 100644 index 000000000..4c32b2130 --- /dev/null +++ b/edg/electronics_model/test_schematic_scene.py @@ -0,0 +1,389 @@ +"""Regression checks for final-sheet label geometry and electrical anchors.""" + +from __future__ import annotations +from pathlib import Path +from .KiCadSchematicTypes import SExpr, Wire +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import copy +import unittest +from .KiCadSchematicExporter import node, children, S +from .KiCadSchematicScene import text_bounds, place_document_labels + + +def label(name: str, x: float, y: float, angle: float, identity: str) -> SExpr: + return node( + "global_label", + name, + node("at", x, y, angle), + node("effects", node("font", node("size", 1.27, 1.27)), node("justify", S("left"))), + node("uuid", identity), + node("shape", S("bidirectional")), + ) + + +class SceneTest(unittest.TestCase): + def test_late_label_moves_free_an_earlier_label_after_second_pass(self) -> None: + import json + from pathlib import Path + import sexpdata + + fixture = json.loads(Path(__file__).with_name("test_schematic_scene_settling.json").read_text()) + doc = sexpdata.loads(fixture["document"]) + original = copy.deepcopy(doc) + segments = [(net, tuple(a), tuple(b)) for net, a, b in fixture["segments"]] + result = place_document_labels(doc, segments, "settling-regression") + self.assertEqual(result["conflicts"], []) + early = next(item for item in result["moves"] if item["name"] == "charger.ic.fbg") + self.assertGreaterEqual(early["pass_index"], 2) + self.assertLessEqual(result["passes"], 6) + self.assertEqual(result["termination"], "stable") + self.assertEqual(place_document_labels(original, segments, "settling-regression"), result) + self.assertEqual(doc, original) + + def test_clear_scene_stops_after_one_stable_pass(self) -> None: + doc = node("kicad_sch", node("lib_symbols"), label("clear", 80, 80, 0, "clear")) + result = place_document_labels(doc, [("clear", (70, 80), (80, 80))], "clear") + self.assertEqual(result["conflicts"], []) + self.assertEqual(result["passes"], 1) + self.assertEqual(result["termination"], "stable") + + def test_label_can_escape_beyond_ten_mm(self) -> None: + definitions = node("lib_symbols") + doc = node("kicad_sch", definitions, label("long_signal_label", 98, 80, 0, "wide-detour")) + for name, box in (("left", (60, 65, 95, 95)), ("right", (101, 60, 140, 100))): + x1, y1, x2, y2 = box + definitions.append( + node( + "symbol", + name, + node("symbol", name + "_0_1", node("rectangle", node("start", x1, -y1), node("end", x2, -y2))), + ) + ) + doc.append(node("symbol", node("lib_id", name), node("at", 0, 0, 0))) + result = place_document_labels(doc, [("signal", (98, 78), (98, 80))], "wide-detour") + self.assertEqual(result["conflicts"], []) + self.assertTrue(result["moves"]) + self.assertGreater(abs(result["moves"][0]["at"][1] - 80), 10.16) + + def test_label_escapes_bank_taller_than_thirty_mm(self) -> None: + definitions = node("lib_symbols") + doc = node("kicad_sch", definitions, label("long_signal_label", 98, 80, 0, "outer-detour")) + for name, box in (("left", (60, 45, 95, 115)), ("right", (101, 40, 140, 120))): + x1, y1, x2, y2 = box + definitions.append( + node( + "symbol", + name, + node("symbol", name + "_0_1", node("rectangle", node("start", x1, -y1), node("end", x2, -y2))), + ) + ) + doc.append(node("symbol", node("lib_id", name), node("at", 0, 0, 0))) + result = place_document_labels(doc, [("signal", (98, 78), (98, 80))], "outer-detour") + self.assertEqual(result["conflicts"], []) + self.assertTrue(result["moves"]) + self.assertGreater(abs(result["moves"][0]["at"][1] - 80), 30.48) + + def test_crossings_reject_endpoints_bends_anchors_and_overlap(self) -> None: + from .KiCadSchematicScene import safe_wire_crossing + + a, b, c, d = (40, 50), (60, 50), (50, 40), (50, 60) + self.assertEqual(safe_wire_crossing(a, b, c, d), (50, 50)) + self.assertIsNone(safe_wire_crossing(a, b, c, d, [(50, 50)])) + self.assertIsNone(safe_wire_crossing(a, (50, 50), c, d)) + self.assertIsNone(safe_wire_crossing(a, b, (45, 50), (55, 50))) + + def test_foreign_wire_through_global_label_tip_triggers_repair(self) -> None: + from .KiCadSchematicScene import label_bounds, segment_box + + doc = node("kicad_sch", node("lib_symbols"), label("power", 80, 80, 0, "tip")) + foreign = ((79.4, 78.7), (79.4, 79.2)) + segments = [("power", (75, 80), (80, 80)), ("sense", *foreign)] + result = place_document_labels(doc, segments, "tip-regression") + self.assertTrue(result["moves"]) + self.assertEqual(result["conflicts"], []) + item = children(doc, "global_label")[0] + at = children(item, "at")[0] + justify = str(children(children(item, "effects")[0], "justify")[0][1]) + self.assertFalse( + segment_box(*foreign, label_bounds(item[1], at[1], at[2], at[3], justify=justify, outline=True)) + ) + + def test_repeated_ic_pin_bus_preserves_external_label_outline(self) -> None: + from .KiCadSchematicExporter import PhysicalComponent, SymbolView + from .KiCadSchematicLayout import route_local + from .KiCadSchematicScene import pin_label_bounds, segment_box + + # INA780's repeated shunt-sense pins (1/2) and power pins (14/8) + # previously routed a sense bus through the power label's pointed end. + c = PhysicalComponent("ina", "U1", "Test:INA", "INA780", {}, None, "ina") + c.net_labels = { + "1": "shunt_pos", + "2": "shunt_pos", + "14": "driver_daughter.pwr_pre_gate", + "8": "driver_daughter.pwr_pre_gate", + } + view = SymbolView( + node( + "symbol", + "Test", + node("symbol", "Test_0_1", node("rectangle", node("start", 0, 15), node("end", 30, -20))), + ), + [("1", -2.54, 10.16, 0), ("14", -2.54, 5.08, 0), ("2", -2.54, 0, 0), ("8", -2.54, -10.16, 0)], + "Test", + ) + wiring = {(c.path, number): net for number, net in c.net_labels.items()} + wires, escapes, failures = route_local([(c, 100, 100, 0)], {c.path: view}, wiring) + self.assertEqual(failures, []) + bounds = pin_label_bounds(c.net_labels["14"], *escapes[c.path, "14"][2:]) + self.assertTrue(any(net == "shunt_pos" for net, _, _ in wires)) + self.assertFalse(any(segment_box(a, b, bounds) for net, a, b in wires if net == "shunt_pos")) + + def test_rotated_instance_fields_reserve_native_horizontal_glyphs(self) -> None: + from types import SimpleNamespace + from .KiCadSchematicLayout import annotation_bounds + from .KiCadSchematicScene import instance_property_at, segment_box + + component = PhysicalComponent("fet", "Q2", "FP", "SIR882BDP-T1-RE3-HXY", {}, None, "fixture") + for rotation in (0, 90, 180, 270): + with self.subTest(rotation=rotation): + at = instance_property_at(node("at", 130, 120, rotation % 180), node("at", 110, 90, rotation)) + self.assertEqual(at[3], 0) + bounds = annotation_bounds(component, 130, 117.46, rotation) + # The observed PDU failure: a vertical wire 8 mm right of the + # field center crossed its native horizontal part-number glyphs. + self.assertTrue(segment_box((138, 118), (138, 122), bounds)) + self.assertLess(bounds[0], 119) + self.assertGreater(bounds[2], 141) + + def test_dense_mixed_connector_labels_can_use_reserved_outer_lane(self) -> None: + def entry(kind: str, name: str, y: float, identity: str) -> SExpr: + effect = node( + "effects", + node("font", node("size", 1.27, 1.27)), + node("justify", S("right"), *([S("bottom")] if kind == "label" else [])), + ) + return node( + kind, + name, + node("at", 100, y, 180), + effect, + node("uuid", identity), + *([node("shape", S("bidirectional"))] if kind == "global_label" else []), + ) + + doc = node( + "kicad_sch", + node("lib_symbols"), + node("rectangle", node("start", 20, 57.5), node("end", 150, 67.5)), + node("text", "XXXXX", node("at", 120, 62.54, 0), node("effects", node("font", node("size", 5, 5)))), + entry("global_label", "control.i2c.sda", 60, "a"), + entry("label", "control.bms_alert", 62.54, "b"), + entry("global_label", "control.taps[0]", 65.08, "c"), + ) + segments = [(net, (100, y), (105.08, y)) for net, y in (("sda", 60), ("alert", 62.54), ("tap", 65.08))] + report = place_document_labels(doc, segments, "dense") + self.assertFalse(report["conflicts"]) + self.assertTrue( + any( + abs(children(item, "at")[0][1] - 100) > 5.08 + for kind in ("label", "global_label") + for item in children(doc, kind) + ) + ) + + def test_unicode_rotated_text_and_outline_use_same_bounds(self) -> None: + horizontal = text_bounds("输出.foo", 80, 80, 0, outline=True) + vertical = text_bounds("输出.foo", 80, 80, 90, outline=True) + self.assertAlmostEqual(horizontal[2] - horizontal[0], vertical[3] - vertical[1]) + self.assertGreater(horizontal[2] - horizontal[0], text_bounds("aa.foo", 80, 80, 0)[2] - 80) + + def fixture(self) -> tuple[SExpr, list[Wire]]: + doc = node( + "kicad_sch", + node("lib_symbols"), + label("control.isense_out", 100, 80, 90, "a"), + label("cintref_amps.out.1", 101.27, 80, 90, "b"), + ) + segments: list[Wire] = [("net_a", (100, 74.92), (100, 80)), ("net_b", (101.27, 74.92), (101.27, 80))] + return doc, segments + + def test_vertical_collision_repaired_without_moving_original_wire_or_net(self) -> None: + doc, segments = self.fixture() + before = copy.deepcopy(segments) + report = place_document_labels(doc, segments, "sheet") + self.assertEqual(report["conflicts"], []) + self.assertEqual(segments, before) + self.assertEqual([x[1] for x in children(doc, "global_label")], ["control.isense_out", "cintref_amps.out.1"]) + self.assertTrue(all(children(x, "at")[0][3] == 0 for x in children(doc, "global_label"))) + for wire in children(doc, "wire"): + a, b = children(wire, "pts")[0][1:] + self.assertTrue(a[1] == b[1] or a[2] == b[2]) + + def test_label_stays_inside_its_functional_region(self) -> None: + from .KiCadSchematicReadability import text_item + + doc = node( + "kicad_sch", + node("lib_symbols"), + node("rectangle", node("start", 40, 60), node("end", 110, 100)), + label("long_control_signal", 100, 80, 0, "border-label"), + ) + segments = [("signal", (60, 80), (100, 80))] + result = place_document_labels(doc, segments, "border") + self.assertEqual(result["conflicts"], []) + item = children(doc, "global_label")[0] + text = text_item("test", item[1], children(item, "at")[0], children(item, "effects")[0], "", "global_label") + assert text is not None + bounds = text.bounds + self.assertGreaterEqual(bounds[0], 40) + self.assertLessEqual(bounds[2], 110) + self.assertEqual(segments, [("signal", (60, 80), (100, 80))]) + + def test_pin_numbers_remain_obstacles_when_names_hidden(self) -> None: + from .KiCadSchematicScene import pin_number_items, pin_name_items + + definition = node( + "symbol", + "Fixture", + node("pin_names", S("hide")), + node( + "symbol", + "Fixture_1_1", + node( + "pin", + S("passive"), + S("line"), + node("at", -5.08, 0, 0), + node("length", 2.54), + node("name", "input"), + node("number", "3"), + ), + ), + ) + self.assertEqual(pin_name_items(definition, 50, 50, 0), []) + for rotation in (0, 90, 180, 270): + items = pin_number_items(definition, 50, 50, rotation) + self.assertEqual(len(items), 1) + self.assertEqual(items[0]["text"], "3") + definition.append(node("pin_numbers", S("hide"))) + self.assertEqual(pin_number_items(definition, 50, 50, 0), []) + + def test_deterministic_and_unknown_anchors_not_extended(self) -> None: + doc, segments = self.fixture() + other = copy.deepcopy(doc) + self.assertEqual(place_document_labels(doc, segments, "sheet"), place_document_labels(other, segments, "sheet")) + self.assertEqual(doc, other) + isolated = node("kicad_sch", node("lib_symbols"), label("single", 60, 60, 90, "x")) + place_document_labels(isolated, [], "single") + self.assertEqual(children(isolated, "wire"), []) + + def test_unknown_or_ambiguous_anchor_preserves_original_label(self) -> None: + for segments in ([], [("a", (60, 55), (60, 60)), ("b", (55, 60), (65, 60))]): + original = label("unknown", 60, 60, 90, "x") + doc = node("kicad_sch", node("lib_symbols"), copy.deepcopy(original)) + result = place_document_labels(doc, segments, "unknown") + self.assertEqual(children(doc, "global_label")[0], original) + self.assertEqual(len(result["unresolved_anchors"]), 1) + self.assertEqual(children(doc, "wire"), []) + + def test_one_label_per_graphical_island_including_disconnected_same_net(self) -> None: + from types import SimpleNamespace + from .KiCadSchematicScene import label_islands + + view = SymbolView([], [("1", 0, 0, 180)], "Test:Pin") + placed = [ + (PhysicalComponent(p, "U1", "FP", "fixture", {"1": "pin"}, None, "fixture"), x, 60, 0) + for p, x in [("a", 40), ("b", 60), ("c", 100)] + ] + views = {p.path: view for p, _, _, _ in placed} + nets = {(p.path, "1"): "supply" for p, _, _, _ in placed} + wire = [("supply", (45.08, 60), (65.08, 60))] + chosen = label_islands(placed, views, nets, wire, {"supply"}) + self.assertEqual(chosen, {("a", "1"), ("c", "1")}) + + def test_same_net_wire_does_not_strike_through_moved_text(self) -> None: + from .KiCadSchematicScene import wire_through_text + + doc = node("kicad_sch", node("lib_symbols"), label("supply", 80, 80, 0, "supply")) + segments = [("supply", (80, 80), (110, 80))] + result = place_document_labels(doc, segments, "same-net") + self.assertEqual(result["conflicts"], []) + item = children(doc, "global_label")[0] + at = children(item, "at")[0] + terms = children(children(item, "effects")[0], "justify")[0] + rect = text_bounds(item[1], at[1], at[2], at[3], justify=str(terms[1])) + self.assertFalse(wire_through_text((80, 80), (110, 80), rect)) + + def test_label_tail_reserializes_t_junction_on_existing_wire(self) -> None: + original = label("branch", 80, 80, 90, "branch") + doc = node("kicad_sch", node("lib_symbols"), original) + segments = [("branch", (70, 80), (80, 80)), ("branch", (80, 80), (90, 80))] + result = place_document_labels(doc, segments, "junction-regression") + self.assertEqual(result["conflicts"], []) + self.assertTrue(result["moves"]) + junctions = {tuple(children(item, "at")[0][1:3]) for item in children(doc, "junction")} + self.assertIn((80, 80), junctions) + self.assertEqual(children(original, "uuid")[0][1], "branch") + + def test_dense_generic_keeps_labels_readable_without_changing_pin_inventory(self) -> None: + from .KiCadSchematicExporter import PhysicalComponent, generic + + component = PhysicalComponent( + "mcu.ic", "U1", "Test:QFN", "MCU", {str(i): f"io{i}" for i in range(1, 25)}, None, "mcu" + ) + view = generic(component) + self.assertEqual({p[0] for p in view.pins}, set(component.pins)) + for side in (0, 180): + rows = sorted(p[2] for p in view.pins if p[3] == side) + self.assertTrue(all(b - a >= 3.81 - 0.0001 for a, b in zip(rows, rows[1:]))) + + def test_readable_180_label_bounds_remain_on_justified_side_of_anchor(self) -> None: + from .KiCadSchematicScene import label_bounds, pin_label_bounds + + # Native KiCad SVG renders this at text-anchor=end, extending left of + # x=25.16. Applying an ordinary 180-degree text transform flips the box + # incorrectly to the right and hides page-edge clipping from the planner. + bounds = label_bounds("mcu.gpio.led_0", 25.16, 169.656, 180, justify="right") + self.assertAlmostEqual(bounds[2], 25.16) + self.assertLess(bounds[0], 12) + self.assertEqual(bounds, label_bounds("mcu.gpio.led_0", 25.16, 169.656, 0, justify="right")) + pin_box = pin_label_bounds("long.external.interface", 30, 80, 0) + self.assertLess(pin_box[0], 12) + + def test_alternate_anchor_never_jumps_to_another_island_with_same_net_name(self) -> None: + from .KiCadSchematicScene import wire_island_anchors + + segments = [ + ("supply", (40, 80), (50, 80)), + ("supply", (50, 80), (50, 90)), + ("supply", (45, 70), (55, 70)), + ("other", (40, 80), (40, 90)), + ] + anchors = wire_island_anchors((40, 80), "supply", segments) + self.assertIn((50, 90), anchors) + self.assertNotIn((45, 70), anchors) + self.assertNotIn((55, 70), anchors) + self.assertNotIn((40, 90), anchors) + + def test_generic_bottom_pin_names_have_clearance_from_last_side_row(self) -> None: + from .KiCadSchematicExporter import PhysicalComponent, generic + from .KiCadSchematicScene import pin_name_items, overlap + + c = PhysicalComponent( + "mcu.ic", "U1", "Test", "MCU", {"1": "gpio.led_2", "2": "gpio.led_1", "3": "gnd", "4": "vdd"}, None, "mcu" + ) + names = pin_name_items(generic(c).definition, 80, 80, 0) + side = next(t for t in names if t["text"] == "gpio.led_2") + ground = next(t for t in names if t["text"] == "gnd") + self.assertFalse(overlap(side["bounds"], ground["bounds"])) + + def test_anchor_budget_samples_distant_connected_wire_without_new_connections(self) -> None: + from .KiCadSchematicScene import wire_island_anchors + + segments = [("output", (40 + i * 5.08, 80), (40 + (i + 1) * 5.08, 80)) for i in range(20)] + candidates = wire_island_anchors((40, 80), "output", segments) + self.assertLessEqual(len(candidates), 8) + self.assertEqual(candidates[0], (40, 80)) + self.assertIn(segments[-1][2], candidates) + self.assertTrue(all(point in {p for _, a, b in segments for p in (a, b)} for point in candidates)) diff --git a/edg/electronics_model/test_schematic_scene_native.py b/edg/electronics_model/test_schematic_scene_native.py new file mode 100644 index 000000000..876d41218 --- /dev/null +++ b/edg/electronics_model/test_schematic_scene_native.py @@ -0,0 +1,291 @@ +"""Optional native acceptance of label-tail junctions and readable text frames. + +Set PB_SCHEMATIC_TEST_KICAD_CLIS to an os.pathsep-separated CLI list, or +KICAD_CLI9 / KICAD_CLI10 to individual executables. These +fixtures exercise native connectivity and SVG geometry, not circuit semantics. +""" + +from __future__ import annotations +from pathlib import Path +from .KiCadSchematicTypes import SExpr, Point +from .KiCadSchematicExporter import PhysicalComponent + +from typing_extensions import override +import os +import re +import subprocess +import tempfile +import unittest +import xml.etree.ElementTree as ET + +import sexpdata + +from .KiCadSchematicExporter import KiCadSchematicExporter, children, effects, generic, node, uid, S +from .KiCadSchematicLayout import transform +from .KiCadSchematicScene import label_bounds, place_document_labels + + +def global_label(name: str, x: float, y: float, angle: float, justify: str) -> SExpr: + eff = effects() + eff.append(node("justify", S(justify))) + return node( + "global_label", + name, + node("at", x, y, angle), + eff, + node("uuid", uid("native-label-fixture", name)), + node("shape", S("bidirectional")), + ) + + +def export_native(test: unittest.TestCase, cli: str, doc: SExpr, action: str) -> Path: + temporary = tempfile.TemporaryDirectory() + test.addCleanup(temporary.cleanup) + folder = Path(temporary.name) + schematic = folder / "Fixture.kicad_sch" + schematic.write_text(sexpdata.dumps(doc), encoding="utf-8") + output = folder / ("netlist.xml" if action == "netlist" else "svg") + args = [cli, "sch", "export", action] + if action == "netlist": + args += ["--format", "kicadxml"] + proc = subprocess.run(args + ["-o", str(output), str(schematic)], capture_output=True, text=True, timeout=60) + test.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + return output + + +class NativeSceneTest(unittest.TestCase): + clis: tuple[str, ...] + + @classmethod + @override + def setUpClass(cls) -> None: + cls.clis = tuple(filter(None, os.environ.get("PB_SCHEMATIC_TEST_KICAD_CLIS", "").split(os.pathsep))) + if not cls.clis: + cls.clis = tuple(filter(None, (os.environ.get("KICAD_CLI9"), os.environ.get("KICAD_CLI10")))) + if not cls.clis: + raise unittest.SkipTest("Set PB_SCHEMATIC_TEST_KICAD_CLIS or KICAD_CLI9/10 for native KiCad acceptance") + + def fixture(self) -> SExpr: + root_id = uid("native-label-fixture", "root") + doc = node( + "kicad_sch", + node("version", 20250114), + node("generator", S("eeschema")), + node("uuid", root_id), + node("paper", "A3"), + node("lib_symbols"), + ) + libraries = children(doc, "lib_symbols")[0] + for index, endpoint, rotation in ((1, 70, 180), (2, 90, 0)): + component = PhysicalComponent( + "part" + str(index), "U" + str(index), "Test:OnePin", "OnePin", {"1": "port"}, None, "Fixture" + ) + view = generic(component) + libraries.append(view.definition) + _, dx, dy, _ = view.pins[0] + dx, dy = transform(dx, dy, rotation) + cx, cy = endpoint - dx, 80 - dy + symbol_id = uid(root_id, component.path) + symbol = node( + "symbol", + node("lib_id", view.lib_id), + node("at", cx, cy, rotation), + node("unit", 1), + node("in_bom", S("yes")), + node("on_board", S("yes")), + node("dnp", S("no")), + node("uuid", symbol_id), + ) + for name, value in (("Reference", component.refdes), ("Value", "OnePin"), ("Footprint", "Test:OnePin")): + symbol.append(node("property", name, value, node("at", cx, cy, 0), effects(hide=True))) + symbol.extend( + ( + node("pin", "1", node("uuid", uid(symbol_id, "pin"))), + node( + "instances", + node( + "project", + "Fixture", + node("path", "/" + root_id, node("reference", component.refdes), node("unit", 1)), + ), + ), + ) + ) + doc.append(symbol) + return doc + + def test_label_tail_crosses_foreign_wire_without_joining_nets(self) -> None: + from copy import deepcopy + from .KiCadSchematicScene import safe_wire_crossing + from .KiCadSchematicWriter import validate_wire_contacts + + doc = self.fixture() + for index, original in enumerate(list(children(doc, "symbol")), 3): + symbol = deepcopy(original) + children(symbol, "at")[0][2] -= 10 + children(symbol, "uuid")[0][1] = uid("crossing", str(index)) + for pin in children(symbol, "pin"): + children(pin, "uuid")[0][1] = uid("crossing", str(index), pin[1]) + for prop in children(symbol, "property"): + if prop[1] == "Reference": + prop[2] = "U" + str(index) + path = children(children(children(symbol, "instances")[0], "project")[0], "path")[0] + children(path, "reference")[0][1] = "U" + str(index) + doc.append(symbol) + # The label moves from (80,80) to (80,60). Its new tail crosses + # the foreign wire at (80,70), strictly inside both unsplit segments. + tail = ((80, 80), (80, 60)) + foreign = ((70, 70), (90, 70)) + self.assertEqual(safe_wire_crossing(*tail, *foreign), (80, 70)) + segments = [("branch", (70, 80), (90, 80)), ("branch", *tail), ("foreign", *foreign)] + validate_wire_contacts(segments, {}) + KiCadSchematicExporter._wires(doc, segments, "fixture", "crossing") + doc.append(global_label("branch", 80, 60, 0, "left")) + doc.append(global_label("foreign", 90, 70, 0, "left")) + self.assertNotIn((80, 70), [tuple(children(j, "at")[0][1:]) for j in children(doc, "junction")]) + for cli in self.clis: + with self.subTest(cli=cli): + xml = ET.parse(export_native(self, cli, doc, "netlist")).getroot() + nets = { + net.attrib["name"]: {(n.attrib["ref"], n.attrib["pin"]) for n in net.findall("node")} + for net in xml.findall("./nets/net") + } + self.assertEqual(nets["branch"], {("U1", "1"), ("U2", "1")}) + self.assertEqual(nets["foreign"], {("U3", "1"), ("U4", "1")}) + + def test_label_tail_keeps_connected_physical_pins(self) -> None: + doc = self.fixture() + segments = [("branch", (70, 80), (80, 80)), ("branch", (80, 80), (90, 80))] + KiCadSchematicExporter._wires(doc, segments, "fixture", "branch") + doc.append(global_label("branch", 80, 80, 90, "left")) + evidence = place_document_labels(doc, segments, "fixture") + self.assertTrue(evidence["moves"]) + self.assertEqual(evidence["conflicts"], []) + for cli in self.clis: + with self.subTest(cli=cli): + xml = ET.parse(export_native(self, cli, doc, "netlist")).getroot() + components = {c.attrib["ref"] for c in xml.findall("./components/comp")} + self.assertEqual(components, {"U1", "U2"}) + nets = [ + {(n.attrib["ref"], n.attrib["pin"]) for n in net.findall("node")} + for net in xml.findall("./nets/net") + ] + self.assertIn({("U1", "1"), ("U2", "1")}, nets) + connected = next( + net + for net in xml.findall("./nets/net") + if {(n.attrib["ref"], n.attrib["pin"]) for n in net.findall("node")} == {("U1", "1"), ("U2", "1")} + ) + self.assertEqual(connected.attrib["name"], "branch") + + def test_all_label_angles_and_justifications_cover_native_glyphs(self) -> None: + doc = self.fixture() + cases = [] + for kind in ("global_label", "label"): + for row, angle in enumerate((0, 90, 180, 270)): + for column, justify in enumerate(("left", "right")): + name = f"{kind[0].upper()}FRAME{angle}{justify[0].upper()}" + x, y = 150 + column * 70, 100 + row * 35 + item = global_label(name, x, y, angle, justify) + if kind == "label": + item[0] = S("label") + item[:] = [v for v in item if not (isinstance(v, list) and v and str(v[0]) == "shape")] + children(children(item, "effects")[0], "justify")[0].append(S("bottom")) + doc.append(item) + cases.append( + ( + name, + label_bounds( + name, + x, + y, + angle, + justify=justify, + outline=kind == "global_label", + bottom=kind == "label", + ), + ) + ) + for cli in self.clis: + folder = export_native(self, cli, doc, "svg") + svg = ET.parse(next(folder.glob("*.svg"))).getroot() + parents = {child: parent for parent in svg.iter() for child in parent} + for name, bounds in cases: + with self.subTest(cli=cli, label=name): + group = next( + item + for item in svg.iter() + if item.tag.endswith("}g") + and any(child.tag.endswith("}desc") and child.text == name for child in item) + ) + points: list[Point] = [] + for path in group.iter(): + if not path.tag.endswith("}path"): + continue + current = path + while current in parents: + self.assertNotIn( + "transform", + current.attrib, + "Native SVG changed to transformed glyph paths; update fixture measurement", + ) + current = parents[current] + commands = path.attrib["d"] + self.assertFalse(set(re.findall(r"[A-Za-z]", commands)) - set("MLZmlz")) + values = [float(v) for v in re.findall(r"[-+]?(?:\d*\.\d+|\d+)", commands)] + self.assertEqual(len(values) % 2, 0) + points.extend(zip(values[::2], values[1::2])) + self.assertTrue(points) + actual = ( + min(x for x, _ in points), + min(y for _, y in points), + max(x for x, _ in points), + max(y for _, y in points), + ) + self.assertLessEqual(bounds[0], actual[0]) + self.assertLessEqual(bounds[1], actual[1]) + self.assertGreaterEqual(bounds[2], actual[2]) + self.assertGreaterEqual(bounds[3], actual[3]) + + def test_180_degree_label_bounds_cover_native_readable_text(self) -> None: + doc = self.fixture() + doc.append(global_label("LEFT_FRAME", 120, 180, 180, "right")) + bounds = label_bounds("LEFT_FRAME", 120, 180, 180, justify="right", outline=True) + self.assertLess(bounds[0], 120) + self.assertLess(bounds[2], 122) + for cli in self.clis: + with self.subTest(cli=cli): + folder = export_native(self, cli, doc, "svg") + root = ET.parse(next(folder.glob("*.svg"))).getroot() + text = next(item for item in root.iter() if item.tag.endswith("}text") and item.text == "LEFT_FRAME") + self.assertEqual(text.attrib["text-anchor"], "end") + hi = float(text.attrib["x"]) + lo = hi - float(text.attrib["textLength"]) + self.assertLessEqual(bounds[0], lo) + self.assertGreaterEqual(bounds[2], hi) + + def test_label_can_reanchor_only_within_its_existing_native_wire_island(self) -> None: + doc = self.fixture() + segments = [("branch", (70, 80), (80, 80)), ("branch", (80, 80), (90, 80))] + KiCadSchematicExporter._wires(doc, segments, "fixture", "branch") + # A field at the old label anchor prevents all new tails from starting + # there. A different vertex of the existing same-net wire remains safe. + doc.append(node("text", "BLOCK", node("at", 80, 80, 0), effects(), node("uuid", uid("block-field")))) + doc.append(global_label("branch", 80, 80, 90, "left")) + evidence = place_document_labels(doc, segments, "fixture") + self.assertTrue(evidence["moves"]) + self.assertNotEqual(tuple(evidence["moves"][0]["wire_anchor"]), (80, 80)) + for cli in self.clis: + with self.subTest(cli=cli): + xml = ET.parse(export_native(self, cli, doc, "netlist")).getroot() + connected = [ + net + for net in xml.findall("./nets/net") + if {(n.attrib["ref"], n.attrib["pin"]) for n in net.findall("node")} == {("U1", "1"), ("U2", "1")} + ] + self.assertEqual(len(connected), 1) + self.assertEqual(connected[0].attrib["name"], "branch") + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_scene_settling.json b/edg/electronics_model/test_schematic_scene_settling.json new file mode 100644 index 000000000..ee2c186df --- /dev/null +++ b/edg/electronics_model/test_schematic_scene_settling.json @@ -0,0 +1,490 @@ +{ + "document": "(kicad_sch (version 20250114) (generator \"polymorphicblocks\") (uuid \"faf7f4ae-5f59-5732-90f7-f6b0a6ea1555\") (paper \"A3\") (title_block (title \"UsbcPdBidir / adcin_high + charger + others\") (comment 1 \"boards.usbc_pd_bidir.usbc_pd_bidir.UsbcPdBidir\") (comment 2 \"fbe7cf57c5f2dfd776c39ea9137f38643706ef47ac5e2beb5cc6d0063af3686f\")) (lib_symbols (symbol \"Device:C_PB_d51e40ba\" (pin_numbers (hide yes)) (pin_names (offset 0.254)) (exclude_from_sim no) (in_bom yes) (on_board yes) (property \"Reference\" \"C\" (at 0.635 2.54 0) (effects (font (size 1.27 1.27)) (justify left))) (property \"Value\" \"C\" (at 0.635 -2.54 0) (effects (font (size 1.27 1.27)) (justify left))) (property \"Footprint\" \"\" (at 0.9652 -3.81 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"Datasheet\" \"~\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"Description\" \"Unpolarized capacitor\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"ki_keywords\" \"cap capacitor\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"ki_fp_filters\" \"C_*\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (symbol \"C_PB_d51e40ba_0_1\" (polyline (pts (xy -2.032 0.762) (xy 2.032 0.762)) (stroke (width 0.508) (type default)) (fill (type none))) (polyline (pts (xy -2.032 -0.762) (xy 2.032 -0.762)) (stroke (width 0.508) (type default)) (fill (type none)))) (symbol \"C_PB_d51e40ba_1_1\" (pin passive line (at 0 3.81 270) (length 2.794) (name \"~\" (effects (font (size 1.27 1.27)))) (number \"1\" (effects (font (size 1.27 1.27))))) (pin passive line (at 0 -3.81 90) (length 2.794) (name \"~\" (effects (font (size 1.27 1.27)))) (number \"2\" (effects (font (size 1.27 1.27))))))) (symbol \"Device:C_Polarized_PB_0b26ae06\" (pin_numbers (hide yes)) (pin_names (offset 0.254)) (exclude_from_sim no) (in_bom yes) (on_board yes) (property \"Reference\" \"C\" (at 0.635 2.54 0) (effects (font (size 1.27 1.27)) (justify left))) (property \"Value\" \"C_Polarized\" (at 0.635 -2.54 0) (effects (font (size 1.27 1.27)) (justify left))) (property \"Footprint\" \"\" (at 0.9652 -3.81 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"Datasheet\" \"~\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"Description\" \"Polarized capacitor\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"ki_keywords\" \"cap capacitor\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (property \"ki_fp_filters\" \"CP_*\" (at 0 0 0) (effects (font (size 1.27 1.27)) (hide yes))) (symbol \"C_Polarized_PB_0b26ae06_0_1\" (rectangle (start -2.286 0.508) (end 2.286 1.016) (stroke (width 0) (type default)) (fill (type none))) (polyline (pts (xy -1.778 2.286) (xy -0.762 2.286)) (stroke (width 0) (type default)) (fill (type none))) (polyline (pts (xy -1.27 2.794) (xy -1.27 1.778)) (stroke (width 0) (type default)) (fill (type none))) (rectangle (start 2.286 -0.508) (end -2.286 -1.016) (stroke (width 0) (type default)) (fill (type outline)))) (symbol \"C_Polarized_PB_0b26ae06_1_1\" (pin passive line (at 0 3.81 270) (length 2.794) (name \"~\" (effects (font (size 1.27 1.27)))) (number \"1\" (effects (font (size 1.27 1.27))))) (pin passive line (at 0 -3.81 90) (length 2.794) (name \"~\" (effects (font (size 1.27 1.27)))) (number \"2\" (effects (font (size 1.27 1.27))))))) (symbol \"PB:c53207b6-1507-51de-842a-1fa97d051a52\" (in_bom yes) (on_board yes) (symbol \"c53207b6-1507-51de-842a-1fa97d051a52_0_1\" (rectangle (start -15.24 48.26) (end 15.24 -48.26) (stroke (width 0) (type default)) (fill (type background))) (pin passive line (at -17.78 41.910000000000004 0) (length 2.54) (name \"i2c.scl\" (effects (font (size 1.27 1.27)))) (number \"1\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 38.1 0) (length 2.54) (name \"ilim_hiz\" (effects (font (size 1.27 1.27)))) (number \"10\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 34.29 0) (length 2.54) (name \"fbg\" (effects (font (size 1.27 1.27)))) (number \"11\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 30.48 0) (length 2.54) (name \"fb\" (effects (font (size 1.27 1.27)))) (number \"12\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 26.67 0) (length 2.54) (name \"srn\" (effects (font (size 1.27 1.27)))) (number \"13\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 22.86 0) (length 2.54) (name \"srp\" (effects (font (size 1.27 1.27)))) (number \"14\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 19.05 0) (length 2.54) (name \"i2c.sda\" (effects (font (size 1.27 1.27)))) (number \"2\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 15.24 0) (length 2.54) (name \"drv_sup\" (effects (font (size 1.27 1.27)))) (number \"23\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 11.43 0) (length 2.54) (name \"regn\" (effects (font (size 1.27 1.27)))) (number \"24\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 7.62 0) (length 2.54) (name \"acn\" (effects (font (size 1.27 1.27)))) (number \"29\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 3.81 0) (length 2.54) (name \"irq\" (effects (font (size 1.27 1.27)))) (number \"3\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -0.0 0) (length 2.54) (name \"acp\" (effects (font (size 1.27 1.27)))) (number \"30\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -3.81 0) (length 2.54) (name \"vac\" (effects (font (size 1.27 1.27)))) (number \"32\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -7.62 0) (length 2.54) (name \"vac\" (effects (font (size 1.27 1.27)))) (number \"33\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -11.43 0) (length 2.54) (name \"acuv\" (effects (font (size 1.27 1.27)))) (number \"34\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -15.24 0) (length 2.54) (name \"acov\" (effects (font (size 1.27 1.27)))) (number \"35\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -19.05 0) (length 2.54) (name \"fsw_sync\" (effects (font (size 1.27 1.27)))) (number \"36\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -22.86 0) (length 2.54) (name \"stat1\" (effects (font (size 1.27 1.27)))) (number \"4\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -26.67 0) (length 2.54) (name \"stat2\" (effects (font (size 1.27 1.27)))) (number \"5\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -30.48 0) (length 2.54) (name \"pg\" (effects (font (size 1.27 1.27)))) (number \"6\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -34.29 0) (length 2.54) (name \"ce\" (effects (font (size 1.27 1.27)))) (number \"7\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -38.1 0) (length 2.54) (name \"ts\" (effects (font (size 1.27 1.27)))) (number \"8\" (effects (font (size 1.27 1.27))))) (pin passive line (at -17.78 -41.910000000000004 0) (length 2.54) (name \"ichg\" (effects (font (size 1.27 1.27)))) (number \"9\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 13.335 180) (length 2.54) (name \"sw2\" (effects (font (size 1.27 1.27)))) (number \"18\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 9.525 180) (length 2.54) (name \"hidrv2\" (effects (font (size 1.27 1.27)))) (number \"19\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 5.715 180) (length 2.54) (name \"btst2\" (effects (font (size 1.27 1.27)))) (number \"20\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 1.905 180) (length 2.54) (name \"lodrv2\" (effects (font (size 1.27 1.27)))) (number \"21\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 -1.905 180) (length 2.54) (name \"lodrv1\" (effects (font (size 1.27 1.27)))) (number \"25\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 -5.715 180) (length 2.54) (name \"btst1\" (effects (font (size 1.27 1.27)))) (number \"26\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 -9.525 180) (length 2.54) (name \"hidrv1\" (effects (font (size 1.27 1.27)))) (number \"27\" (effects (font (size 1.27 1.27))))) (pin passive line (at 17.78 -13.335 180) (length 2.54) (name \"sw1\" (effects (font (size 1.27 1.27)))) (number \"28\" (effects (font (size 1.27 1.27))))) (pin passive line (at -5.08 -50.8 90) (length 2.54) (name \"gnd\" (effects (font (size 1.27 1.27)))) (number \"17\" (effects (font (size 1.27 1.27))))) (pin passive line (at 0.0 -50.8 90) (length 2.54) (name \"gnd\" (effects (font (size 1.27 1.27)))) (number \"22\" (effects (font (size 1.27 1.27))))) (pin passive line (at 5.08 -50.8 90) (length 2.54) (name \"gnd\" (effects (font (size 1.27 1.27)))) (number \"37\" (effects (font (size 1.27 1.27)))))))) (rectangle (start 20 40) (end 324.542 236.625) (stroke (width 0.15) (type default)) (fill (type none)) (uuid \"b401f03c-744d-566c-b7da-bc8323a4ce4c\")) (global_label \"pd.i2c_controller.scl\" (at 147.46 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"63d25c02-8e6a-57f3-8c5c-5b3efaab38f3\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 147.46 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.ilim_hiz\" (at 151.27 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"57e093a9-6bee-59b5-a880-25c0c7814ebf\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 151.27 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.fbg\" (at 155.08 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"0d8e4425-2a61-544c-867d-1dd500338be6\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 155.08 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.fb\" (at 158.89 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"44a2d118-2a1c-5a81-b823-6df0a89926cb\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 158.89 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.srn\" (at 162.7 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"56d46222-3f4e-58a0-8254-a98562e3f7d8\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 162.7 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.srp\" (at 166.51 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"8c2ccc3c-5509-518f-9bd7-2c52acde6789\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 166.51 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"pd.i2c_controller.sda\" (at 170.32 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"b432c085-2b98-544a-8155-c2f2962ab950\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 170.32 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.drv_sup\" (at 174.13 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"bf29137d-82f6-5fd2-a562-18e13eb1cb00\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 174.13 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.acn\" (at 181.75 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"9c98ca6b-7592-5b74-835b-2c865e6d7af2\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 181.75 174.27 0) (effects (font (size 1.27 1.27)) hide))) (label \"charger.ic.irq\" (at 185.56 174.27 90) (effects (font (size 1.27 1.27)) (justify right bottom)) (uuid \"330a8973-4a58-59a3-b4e1-165afbfbffdf\")) (global_label \"charger.ic.acp\" (at 189.37 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"7c073c3f-9cdf-5016-9255-05ff3d5df603\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 189.37 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.acuv\" (at 200.8 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"2c73bff3-47f1-592d-b8c5-1bef14e1a752\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 200.8 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.acov\" (at 204.61 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"995475ad-518f-5055-b2c1-6f4701010d27\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 204.61 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.fsw_sync\" (at 208.42 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"9c195b02-43b4-58b5-a3a5-67be069d2540\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 208.42 174.27 0) (effects (font (size 1.27 1.27)) hide))) (label \"charger.ic.stat1\" (at 212.23 174.27 90) (effects (font (size 1.27 1.27)) (justify right bottom)) (uuid \"ace9621d-df82-5ac4-870d-b233e497ac3d\")) (label \"charger.ic.stat2\" (at 216.04 174.27 90) (effects (font (size 1.27 1.27)) (justify right bottom)) (uuid \"a516c8c2-8cd8-5e59-a93b-5b8bb932a5cd\")) (label \"charger.ic.pg\" (at 219.85 174.27 90) (effects (font (size 1.27 1.27)) (justify right bottom)) (uuid \"9ac47ad9-c7de-57e8-a8d3-98c9bfb4aece\")) (global_label \"charger.ic.ce\" (at 223.66 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"b37c0b7a-5e33-5adb-b0fa-f5530a40d466\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 223.66 174.27 0) (effects (font (size 1.27 1.27)) hide))) (global_label \"charger.ic.ts\" (at 227.47 174.27 90) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"11a302f7-717a-5616-919e-b9f675e12eeb\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 227.47 174.27 0) (effects (font (size 1.27 1.27)) hide))) (symbol (lib_id \"PB:c53207b6-1507-51de-842a-1fa97d051a52\") (at 189.37 151.41 90) (unit 1) (in_bom yes) (on_board yes) (dnp no) (uuid \"2ae400f1-df12-5e42-8044-c1dc21ffda35\") (property \"Reference\" \"U12\" (at 130.015 175.459 90) (effects (font (size 1.27 1.27)))) (property \"Value\" \"BQ25756RRVR\" (at 130.015 177.999 90) (effects (font (size 1.27 1.27)))) (property \"Footprint\" \"Package_DFN_QFN:QFN-36-1EP_5x6mm_P0.5mm_EP3.6x4.6mm\" (at 130.015 180.53900000000002 90) (effects (font (size 1.27 1.27)) hide)) (property \"PBPath\" \"charger.ic\" (at 130.015 183.079 90) (effects (font (size 1.27 1.27)) hide)) (instances (project \"board_b9163855-f12c-54dc-bbd8-73a80467fca7\" (path \"/e2dd551f-1abf-5489-9c78-e2a764158af1/faf7f4ae-5f59-5732-90f7-f6b0a6ea1555\" (reference \"U12\") (unit 1)))) (pin \"1\" (uuid \"e8a7955f-a0a3-5c85-9d7c-088ffab1ebdd\")) (pin \"10\" (uuid \"ccdf626f-7211-5805-910b-c18cb8904fbf\")) (pin \"11\" (uuid \"79cff87a-88d2-53e2-a21d-3582d0f925d6\")) (pin \"12\" (uuid \"51c5f65b-397d-558d-a80f-2439587aa13e\")) (pin \"13\" (uuid \"40f30016-1f7a-5a43-ae48-42db310eb620\")) (pin \"14\" (uuid \"fc69d7d1-f339-5e20-bfd3-9e97e813254e\")) (pin \"2\" (uuid \"cfc96108-effa-52c7-afbc-d252e6daae1f\")) (pin \"23\" (uuid \"38e1bca9-d2bb-58ad-b781-e654cb06561f\")) (pin \"24\" (uuid \"3e1a4c1c-3d5c-52c7-8bab-a5e0a5b046ff\")) (pin \"29\" (uuid \"fe6a2996-eecd-5913-b610-b9fc5005f697\")) (pin \"3\" (uuid \"5f5343f7-e4cd-5441-afcd-49464995ea35\")) (pin \"30\" (uuid \"43108a93-99bf-5375-aabd-f67e04c68be9\")) (pin \"32\" (uuid \"af39ade4-6074-5f59-8b53-0ec39cfd41e1\")) (pin \"33\" (uuid \"b40306b2-3850-5a30-a797-69c47fcdb62e\")) (pin \"34\" (uuid \"bf237e88-2088-55d9-a519-d5aeb2ac5b7b\")) (pin \"35\" (uuid \"dbae9420-cc0c-5f97-bb25-3409a04b9d5d\")) (pin \"36\" (uuid \"b741459d-e6cd-5829-8368-07cf3a69c8e3\")) (pin \"4\" (uuid \"5f3727ac-0762-538f-9405-fa2d18c644ad\")) (pin \"5\" (uuid \"bb408ac6-3013-568f-9d7a-aafef9b77083\")) (pin \"6\" (uuid \"1dcd6f42-37d8-506a-8515-e82bfc8d4de0\")) (pin \"7\" (uuid \"98b6bdbb-b333-5d06-a756-b69e1c3ee51a\")) (pin \"8\" (uuid \"609850c0-52b9-53d7-b825-75ae81d25154\")) (pin \"9\" (uuid \"297bc937-533b-5ac1-8da6-125386ee9038\")) (pin \"18\" (uuid \"41d5d71b-ff41-55d2-9cd3-7467b51ff829\")) (pin \"19\" (uuid \"c4acca05-a2d9-58cc-9fb4-b4391ab3f957\")) (pin \"20\" (uuid \"f1ce8538-8b68-5419-9c55-aedeb485248d\")) (pin \"21\" (uuid \"73e7d18f-4ad1-53a7-b941-570994d6ed19\")) (pin \"25\" (uuid \"e5878010-5529-5a2f-aeaa-aafaa13a9ff8\")) (pin \"26\" (uuid \"8c67b479-31e6-598f-9950-f1fde36588b1\")) (pin \"27\" (uuid \"545ba6e7-fab3-5ef8-bb37-fed5600e5bac\")) (pin \"28\" (uuid \"d4aab2a8-9395-5695-9d6f-2928b102f3ab\")) (pin \"17\" (uuid \"2474db2a-6e2e-5ff5-9eb6-d958ac5ceae3\")) (pin \"22\" (uuid \"d84ee035-d615-5585-9607-e9cbf3cec64f\")) (pin \"37\" (uuid \"9476286d-d474-5af2-a04e-c18625f19b96\"))) (symbol (lib_id \"Device:C_PB_d51e40ba\") (at 152.54 184.43 90) (unit 1) (in_bom yes) (on_board yes) (dnp no) (uuid \"5fe97e52-b8cf-5d91-b70b-50944dd1a11e\") (property \"Reference\" \"C68\" (at 152.54 199.162 90) (effects (font (size 1.27 1.27)))) (property \"Value\" \"470nF 50V X7R \u00b110% 0805 Multilayer Ceramic Capacitors MLCC - SMD/SMT ROHS\" (at 152.54 201.702 90) (effects (font (size 1.27 1.27)) hide)) (property \"Footprint\" \"Capacitor_SMD:C_0805_2012Metric\" (at 152.54 204.24200000000002 90) (effects (font (size 1.27 1.27)) hide)) (property \"PBPath\" \"charger.boot2\" (at 152.54 206.782 90) (effects (font (size 1.27 1.27)) hide)) (property \"PBDisplayValue\" \"470nF\" (at 152.54 201.702 90) (effects (font (size 1.27 1.27)))) (instances (project \"board_b9163855-f12c-54dc-bbd8-73a80467fca7\" (path \"/e2dd551f-1abf-5489-9c78-e2a764158af1/faf7f4ae-5f59-5732-90f7-f6b0a6ea1555\" (reference \"C68\") (unit 1)))) (pin \"1\" (uuid \"5c8e20c0-803c-5466-a8bc-5d94dce6b2b0\")) (pin \"2\" (uuid \"79b010bb-4aa7-5802-b472-b60e796a1858\"))) (global_label \"protected_batt\" (at 143.65 214.91 180) (effects (font (size 1.27 1.27)) (justify right)) (uuid \"6cf78129-4f15-5554-ab41-080cc659f777\") (shape bidirectional) (property \"Intersheetrefs\" \"${INTERSHEET_REFS}\" (at 143.65 214.91 0) (effects (font (size 1.27 1.27)) hide))) (symbol (lib_id \"Device:C_Polarized_PB_0b26ae06\") (at 152.54 214.91 90) (unit 1) (in_bom yes) (on_board yes) (dnp no) (uuid \"809ff94d-32e3-5083-97ec-67a7e14807af\") (property \"Reference\" \"C74\" (at 152.54 229.896 90) (effects (font (size 1.27 1.27)))) (property \"Value\" \"PCR1J101MCL1GS\" (at 152.54 232.43599999999998 90) (effects (font (size 1.27 1.27)) hide)) (property \"Footprint\" \"Capacitor_SMD:CP_Elec_10x12.5\" (at 152.54 234.976 90) (effects (font (size 1.27 1.27)) hide)) (property \"PBPath\" \"charger.output_bulk_raw.cap\" (at 152.54 237.516 90) (effects (font (size 1.27 1.27)) hide)) (property \"PBDisplayValue\" \"100\u00b5F\" (at 152.54 232.43599999999998 90) (effects (font (size 1.27 1.27)))) (instances (project \"board_b9163855-f12c-54dc-bbd8-73a80467fca7\" (path \"/e2dd551f-1abf-5489-9c78-e2a764158af1/faf7f4ae-5f59-5732-90f7-f6b0a6ea1555\" (reference \"C74\") (unit 1)))) (pin \"1\" (uuid \"deaf0ba9-5b3e-54a1-ad2d-4d2fd75454f9\")) (pin \"2\" (uuid \"3eaec59a-9a16-5258-8124-e948061068c4\"))) (rectangle (start 332.542 40) (end 356.542 95.99) (stroke (width 0.15) (type default)) (fill (type none)) (uuid \"04ead29d-ee26-5e1f-942a-5427a4af7659\")) (rectangle (start 364.542 40) (end 388.542 83.925) (stroke (width 0.15) (type default)) (fill (type none)) (uuid \"79a21b7e-2eab-5f0f-bc1c-5c00fd86c105\")))", + "segments": [ + [ + "charger.ic.btst2", + [ + 143.65, + 184.43 + ], + [ + 143.65, + 167.285 + ] + ], + [ + "charger.ic.btst2", + [ + 143.65, + 167.285 + ], + [ + 140.475, + 167.285 + ] + ], + [ + "charger.ic.btst2", + [ + 140.475, + 167.285 + ], + [ + 140.475, + 129.82 + ] + ], + [ + "charger.ic.drv_sup", + [ + 177.94, + 174.27 + ], + [ + 174.13, + 174.27 + ] + ], + [ + "charger.vsys_raw", + [ + 44.59, + 203.48 + ], + [ + 245.25, + 203.48 + ] + ], + [ + "protected_batt", + [ + 143.65, + 214.91 + ], + [ + 143.65, + 211.1 + ] + ], + [ + "protected_batt", + [ + 143.65, + 211.1 + ], + [ + 263.03, + 211.1 + ] + ], + [ + "charger.sw2", + [ + 161.43, + 184.43 + ], + [ + 160.795, + 184.43 + ] + ], + [ + "charger.sw2", + [ + 160.795, + 184.43 + ], + [ + 160.795, + 169.825 + ] + ], + [ + "charger.sw2", + [ + 160.795, + 169.825 + ], + [ + 139.84, + 169.825 + ] + ], + [ + "charger.sw2", + [ + 139.84, + 169.825 + ], + [ + 139.84, + 128.55 + ] + ], + [ + "charger.vsys", + [ + 193.18, + 174.27 + ], + [ + 191.275, + 174.27 + ] + ], + [ + "charger.vsys", + [ + 191.275, + 174.27 + ], + [ + 191.275, + 170.46 + ] + ], + [ + "charger.vsys", + [ + 191.275, + 170.46 + ], + [ + 101.105, + 170.46 + ] + ], + [ + "charger.vsys", + [ + 196.99, + 174.27 + ], + [ + 193.18, + 174.27 + ] + ], + [ + "pd.i2c_controller.scl", + [ + 147.46, + 169.19 + ], + [ + 147.46, + 174.27 + ] + ], + [ + "charger.ic.ilim_hiz", + [ + 151.27, + 169.19 + ], + [ + 151.27, + 174.27 + ] + ], + [ + "charger.ic.fbg", + [ + 155.08, + 169.19 + ], + [ + 155.08, + 174.27 + ] + ], + [ + "charger.ic.fb", + [ + 158.89, + 169.19 + ], + [ + 158.89, + 174.27 + ] + ], + [ + "charger.ic.srn", + [ + 162.7, + 169.19 + ], + [ + 162.7, + 174.27 + ] + ], + [ + "charger.ic.srp", + [ + 166.51, + 169.19 + ], + [ + 166.51, + 174.27 + ] + ], + [ + "pd.i2c_controller.sda", + [ + 170.32, + 169.19 + ], + [ + 170.32, + 174.27 + ] + ], + [ + "charger.ic.drv_sup", + [ + 174.13, + 169.19 + ], + [ + 174.13, + 174.27 + ] + ], + [ + "charger.ic.drv_sup", + [ + 177.94, + 169.19 + ], + [ + 177.94, + 174.27 + ] + ], + [ + "charger.ic.acn", + [ + 181.75, + 169.19 + ], + [ + 181.75, + 174.27 + ] + ], + [ + "charger.ic.irq", + [ + 185.56, + 169.19 + ], + [ + 185.56, + 174.27 + ] + ], + [ + "charger.ic.acp", + [ + 189.37, + 169.19 + ], + [ + 189.37, + 174.27 + ] + ], + [ + "charger.vsys", + [ + 193.18, + 169.19 + ], + [ + 193.18, + 174.27 + ] + ], + [ + "charger.vsys", + [ + 196.99, + 169.19 + ], + [ + 196.99, + 174.27 + ] + ], + [ + "charger.ic.acuv", + [ + 200.8, + 169.19 + ], + [ + 200.8, + 174.27 + ] + ], + [ + "charger.ic.acov", + [ + 204.61, + 169.19 + ], + [ + 204.61, + 174.27 + ] + ], + [ + "charger.ic.fsw_sync", + [ + 208.42, + 169.19 + ], + [ + 208.42, + 174.27 + ] + ], + [ + "charger.ic.stat1", + [ + 212.23, + 169.19 + ], + [ + 212.23, + 174.27 + ] + ], + [ + "charger.ic.stat2", + [ + 216.04, + 169.19 + ], + [ + 216.04, + 174.27 + ] + ], + [ + "charger.ic.pg", + [ + 219.85, + 169.19 + ], + [ + 219.85, + 174.27 + ] + ], + [ + "charger.ic.ce", + [ + 223.66, + 169.19 + ], + [ + 223.66, + 174.27 + ] + ], + [ + "charger.ic.ts", + [ + 227.47, + 169.19 + ], + [ + 227.47, + 174.27 + ] + ], + [ + "charger.ic.ichg", + [ + 231.28, + 169.19 + ], + [ + 231.28, + 174.27 + ] + ], + [ + "gnd", + [ + 240.17, + 156.49 + ], + [ + 245.25, + 156.49 + ] + ], + [ + "gnd", + [ + 240.17, + 151.41 + ], + [ + 245.25, + 151.41 + ] + ], + [ + "charger.ic.btst2", + [ + 148.73, + 184.43 + ], + [ + 143.65, + 184.43 + ] + ], + [ + "charger.sw2", + [ + 156.35, + 184.43 + ], + [ + 161.43, + 184.43 + ] + ], + [ + "protected_batt", + [ + 148.73, + 214.91 + ], + [ + 143.65, + 214.91 + ] + ], + [ + "gnd", + [ + 156.35, + 214.91 + ], + [ + 161.43, + 214.91 + ] + ] + ], + "description": "Reduced raw pre-repair USB charger scene: three symbols and a dense bottom-pin label bank. Later labels free the first label only on the third pass. Captured from an isolated fresh export; no repaired positions are used." +} diff --git a/edg/electronics_model/test_schematic_semantics.py b/edg/electronics_model/test_schematic_semantics.py new file mode 100644 index 000000000..c2b83b8e7 --- /dev/null +++ b/edg/electronics_model/test_schematic_semantics.py @@ -0,0 +1,125 @@ +"""Regression cases for missing meaning and overprinted two-terminal fallbacks.""" + +from __future__ import annotations +from ..core import CompiledDesign +from .KiCadSchematicExporter import PhysicalComponent + +import unittest +from types import SimpleNamespace +from .KiCadSchematicExporter import generic, KiCadSchematicExporter +from .KiCadSchematicLabels import readable_labels +from .KiCadSchematicRoles import infer_pin_names, infer_description + + +class SchematicSemanticsTest(unittest.TestCase): + def test_authored_boundary_roles_only_rearrange_generic_pin_graphics(self) -> None: + component = PhysicalComponent( + "interface", + "U1", + "Test:IC", + "Interface", + {"1": "port_a", "2": "port_b", "3": "port_c", "4": "port_d"}, + None, + "Interface", + ) + component.presentation_pin_roles = {"1": "input", "2": "output", "3": "supply", "4": "return"} + view = generic(component) + pins = {n: (x, y) for n, x, y, _ in view.pins} + self.assertEqual(set(pins), set(component.pins)) + self.assertLess(pins["1"][0], 0) + self.assertGreater(pins["2"][0], 0) + self.assertLess(pins["3"][1], 0) + self.assertGreater(pins["4"][1], 0) + + def test_declared_power_driver_ports_face_power_stage(self) -> None: + outputs = ("gate1", "sw", "cboot", "btst1", "btst2", "hidrv1", "lodrv2", "tgup", "tgdn") + names = {"1": "in1", **{str(i + 2): name for i, name in enumerate(outputs)}, "20": "gnd"} + component = PhysicalComponent("driver", "U1", "Test:Package", "Driver", names, None, "Power") + view = generic(component) + pins = {n: (x, y, a) for n, x, y, a in view.pins} + self.assertEqual(set(pins), set(component.pins)) + self.assertLess(pins["1"][0], 0) + for number, name in names.items(): + if name in outputs: + self.assertGreater(pins[number][0], 0) + self.assertEqual(pins[number][2], 180) + + def test_two_pin_fallback_escapes_opposite_sides(self) -> None: + component = PhysicalComponent("filter", "FB1", "Test:Package", "Filter", {"1": "a", "2": "b"}, None, "Power") + view = generic(component) + pins = {n: (x, y, a) for n, x, y, a in view.pins} + self.assertLess(pins["1"][0], 0) + self.assertGreater(pins["2"][0], 0) + self.assertEqual(pins["1"][2], 0) + self.assertEqual(pins["2"][2], 180) + + def test_display_connector_pin_meaning_requires_verified_model(self) -> None: + component = PhysicalComponent( + "oled.device.conn", + "J1", + "Test:Connector", + "FPC", + {"9": "pins.9", "28": "pins.28", "14": "pins.14"}, + None, + "Display", + ) + classes = ["edg.parts.display.oled.Er_Oled_096_1_1.Er_Oled_096_1_1_Device", "edg.parts.connector.Fpc.Afc01"] + self.assertEqual(infer_pin_names(component, classes), {"9": "VDD", "28": "VCC", "14": "RES"}) + self.assertIn("charge pump", infer_description(component, classes)) + self.assertEqual(infer_pin_names(component, classes[:-1] + ["UnknownConnector"]), {}) + component.pins["9"] = "pins.28" + self.assertEqual(infer_pin_names(component, classes), {}) + + def test_verified_fpc_flip_requires_compiled_length(self) -> None: + component = PhysicalComponent( + "oled.conn.conn", + "J1", + "Test:FPC", + "FPC", + {"2": "pins.2", "16": "pins.16", "24": "pins.24"}, + None, + "Display", + ) + classes = [ + "edg.parts.display.oled.Er_Oled_022.Er_Oled022_1_Device", + "edg.parts.connector.Fpc.Fpc050BottomFlip", + "edg.parts.connector.Fpc.Afc07Top", + ] + self.assertEqual(infer_pin_names(component, classes), {}) + self.assertEqual(infer_pin_names(component, classes, 30), {}) + self.assertEqual(infer_pin_names(component, classes, 24), {"2": "VCC", "16": "RES", "24": "VSS"}) + + def test_clock_and_protection_values_ignore_parasitic_capacitance(self) -> None: + from unittest.mock import Mock + from .NetlistGenerator import NetBlock + + def block(cls: str) -> NetBlock: + return Mock( + spec=NetBlock, + path_classes=[SimpleNamespace(target=SimpleNamespace(name=cls))], + full_path=SimpleNamespace(to_tuple=lambda: ("device",)), + part="VerifiedPart (Vendor)", + value="fallback", + ) + + values = {("device", "actual_capacitance"): 0.0, ("device", "actual_frequency"): 16e6} + compiled = Mock(spec=CompiledDesign) + compiled.get_value.side_effect = lambda key: values.get(key) + self.assertEqual(KiCadSchematicExporter._display_value(compiled, block("edg.Crystal")), "16MHz") + self.assertEqual(KiCadSchematicExporter._display_value(compiled, block("edg.ZenerDiode")), "VerifiedPart") + values[("device", "actual_capacitance")] = 0.9999999999999999e-6 + self.assertEqual(KiCadSchematicExporter._display_value(compiled, block("edg.Capacitor")), "1µF") + self.assertEqual( + KiCadSchematicExporter._display_value( + compiled, block("project.Bulk100Cap"), {"lib_id": "Device:C_Polarized"} + ), + "1µF", + ) + + def test_short_labels_are_injective_and_order_independent(self) -> None: + names = ["a.b.c.d", "x.b.c.d", "v3v3", "unicode.接口", "a name", "N_61206e616d65"] + labels = readable_labels(names) + self.assertEqual(labels, readable_labels(reversed(names))) + self.assertEqual(len(set(labels.values())), len(names)) + self.assertEqual(labels["v3v3"], "v3v3") + self.assertNotEqual(labels["a.b.c.d"], labels["x.b.c.d"]) diff --git a/edg/electronics_model/test_schematic_standalone.py b/edg/electronics_model/test_schematic_standalone.py new file mode 100644 index 000000000..86ed79a70 --- /dev/null +++ b/edg/electronics_model/test_schematic_standalone.py @@ -0,0 +1,62 @@ +"""The PB compile/export entry point must work without agentic-pcb installed.""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +class StandaloneSchematicTest(unittest.TestCase): + def test_pb_cli_exports_without_agentic_pcb(self) -> None: + # Use a fresh interpreter so an adapter already imported by another test + # cannot conceal a reverse dependency. Block even optional imports. + script = """ +import importlib.abc +import runpy +import sys + +attempts = [] + +class NoAgenticPcb(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == "agentic_pcb" or fullname.startswith("agentic_pcb."): + attempts.append(fullname) + raise AssertionError("PB export attempted to import its agent adapter: " + fullname) + +assert not any(n == "agentic_pcb" or n.startswith("agentic_pcb.") for n in sys.modules) +sys.meta_path.insert(0, NoAgenticPcb()) +sys.argv = ["examples.export_schematic", "--output", sys.argv[1]] +runpy.run_module("examples.export_schematic", run_name="__main__") +assert not attempts, "PB must not delegate export to its agent adapter: " + repr(attempts) +assert not any(n == "agentic_pcb" or n.startswith("agentic_pcb.") for n in sys.modules) +""" + with tempfile.TemporaryDirectory() as directory: + output = Path(directory, "export") + result = subprocess.run( + [sys.executable, "-c", script, str(output)], + cwd=Path(__file__).resolve().parents[2], + text=True, + capture_output=True, + timeout=120, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertTrue((output / "TestLed.net").is_file()) + bundle = output / "TestLed.schematic" + manifest = json.loads((bundle / "manifest.json").read_text(encoding="utf-8")) + self.assertEqual(manifest["source"], "examples.test_blinky.TestLed") + self.assertTrue(manifest["boards"]) + documents = [name for name in manifest["files"] if name.endswith(".kicad_sch")] + self.assertTrue(documents) + for name in documents: + self.assertIn("SOURCE OF TRUTH", (bundle / name).read_text(encoding="utf-8")) + for board in manifest["boards"]: + self.assertIn(board["root"], documents) + self.assertIn("symbol_coverage", manifest) + for name in ("routing.json", "layout.json", "sheet-plan.json"): + self.assertTrue((bundle / name).is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/edg/electronics_model/test_schematic_visual_clearance.py b/edg/electronics_model/test_schematic_visual_clearance.py new file mode 100644 index 000000000..b87aad63d --- /dev/null +++ b/edg/electronics_model/test_schematic_visual_clearance.py @@ -0,0 +1,142 @@ +"""Distinct electrical nets must also remain visually distinguishable. + +The source/drain fixture uses the exact Q4 position and generic physical pin +geometry from the PDU handoff finding: old buses approached within 0.635 mm. +""" + +from __future__ import annotations +from .KiCadSchematicTypes import PinKey, PinNets, Wire, Placement, Placements, Views +from .KiCadSchematicExporter import PhysicalComponent, SymbolView + +import os +import unittest +import xml.etree.ElementTree as ET + +from .KiCadSchematicExporter import generic, node, uid, S, effects, KiCadSchematicExporter +from .KiCadSchematicLayout import route_local +from .KiCadSchematicScene import wire_visual_conflict + + +def fixture() -> tuple[list[Placement], dict[str, SymbolView], dict[PinKey, str]]: + transistor = PhysicalComponent( + "system_power_or.fet", + "Q4", + "Test:SOIC8", + "AO4407A", + { + "1": "source", + "2": "source", + "3": "source", + "4": "gate", + "5": "drain", + "6": "drain", + "7": "drain", + "8": "drain", + }, + None, + "power", + ) + parts = [transistor] + [ + PhysicalComponent("tap" + str(i), "TP" + str(i), "Test:One", "Tap", {"1": "io"}, None, "power") for i in (1, 2) + ] + views = {c.path: generic(c) for c in parts} + # Preserve exact PDU fractional placement and 90-degree SOIC view. + placed: list[Placement] = [(transistor, 79.18, 109.5, 90), (parts[1], 140, 150, 0), (parts[2], 180, 150, 0)] + nets = { + (transistor.path, n): ("source" if n in ("1", "2", "3") else "gate" if n == "4" else "drain") + for n in transistor.pins + } + nets.update({(c.path, "1"): "source" for c in parts[1:]}) + return placed, views, nets + + +def segments( + placed: Placements, views: Views, nets: PinNets +) -> tuple[list[Wire], dict[PinKey, tuple[float, float, float, float, float]], list[tuple[PinKey, str]], list[Wire]]: + wires, escapes, failures = route_local(placed, views, nets) + all_segments = list(wires) + all_segments.extend((nets[key], (px, py), (ex, ey)) for key, (px, py, ex, ey, _) in escapes.items()) + return wires, escapes, failures, all_segments + + +class VisualClearanceTest(unittest.TestCase): + def test_actual_source_drain_near_join_and_parallel_bus_are_rejected(self) -> None: + self.assertTrue(wire_visual_conflict((67.75, 129.82), (75.37, 129.82), (76.005, 129.82), (90.61, 129.82))) + self.assertTrue(wire_visual_conflict((75.37, 129.185), (95.69, 129.185), (79.18, 129.82), (90.61, 129.82))) + + def test_near_t_join_and_off_grid_stub_gap_are_rejected(self) -> None: + # A configuration resistor must not look like an I2C pullup when its + # separately connected branch stops half a routing cell from the bus. + self.assertTrue(wire_visual_conflict((80, 80), (80, 89.365), (70, 90), (100, 90))) + self.assertTrue(wire_visual_conflict((80, 80), (80, 89.9), (70, 90), (100, 90))) + self.assertFalse(wire_visual_conflict((80, 80), (80, 88.73), (70, 90), (100, 90))) + + def test_legible_interior_perpendicular_crossing_is_preserved(self) -> None: + self.assertFalse(wire_visual_conflict((40, 80), (100, 80), (70, 60), (70, 100))) + self.assertTrue(wire_visual_conflict((40, 80), (100, 80), (70, 79.365), (70, 100))) + self.assertTrue(wire_visual_conflict((40, 80), (100, 80), (70, 60), (70, 100), protected=((70.635, 80),))) + + def test_q4_route_has_no_source_drain_visual_near_join(self) -> None: + placed, views, nets = fixture() + _, _, failures, all_segments = segments(placed, views, nets) + self.assertEqual(failures, []) + conflicts = [ + (n, a, b, m, c, d) + for i, (n, a, b) in enumerate(all_segments) + for m, c, d in all_segments[i + 1 :] + if n != m and wire_visual_conflict(a, b, c, d) + ] + self.assertEqual(conflicts, []) + + def test_q4_native_nets_keep_all_parallel_physical_pins(self) -> None: + from .test_schematic_scene_native import export_native + + clis = tuple(filter(None, os.environ.get("PB_SCHEMATIC_TEST_KICAD_CLIS", "").split(os.pathsep))) + if not clis: + self.skipTest("Set PB_SCHEMATIC_TEST_KICAD_CLIS for KiCad 9/10 native acceptance") + placed, views, nets = fixture() + _, _, failures, all_segments = segments(placed, views, nets) + self.assertEqual(failures, []) + root_id = uid("native-visual-clearance", "root") + doc = node( + "kicad_sch", + node("version", 20250114), + node("generator", S("eeschema")), + node("uuid", root_id), + node("paper", "A3"), + node("lib_symbols", *[v.definition for v in views.values()]), + ) + for c, x, y, angle in placed: + symbol_id = uid(root_id, c.path) + symbol = node( + "symbol", + node("lib_id", views[c.path].lib_id), + node("at", x, y, angle), + node("unit", 1), + node("in_bom", S("yes")), + node("on_board", S("yes")), + node("dnp", S("no")), + node("uuid", symbol_id), + ) + for name, value in (("Reference", c.refdes), ("Value", c.value), ("Footprint", c.footprint)): + symbol.append(node("property", name, value, node("at", x, y, 0), effects(hide=True))) + symbol.extend(node("pin", n, node("uuid", uid(symbol_id, n))) for n in c.pins) + symbol.append( + node( + "instances", + node( + "project", "Fixture", node("path", "/" + root_id, node("reference", c.refdes), node("unit", 1)) + ), + ) + ) + doc.append(symbol) + KiCadSchematicExporter._wires(doc, all_segments, "fixture", "visual-clearance") + for cli in clis: + with self.subTest(cli=cli): + xml = ET.parse(export_native(self, cli, doc, "netlist")).getroot() + native = [ + {(n.attrib["ref"], n.attrib["pin"]) for n in net.findall("node")} + for net in xml.findall("./nets/net") + ] + self.assertIn({("Q4", n) for n in ("1", "2", "3")} | {("TP1", "1"), ("TP2", "1")}, native) + self.assertIn({("Q4", n) for n in ("5", "6", "7", "8")}, native) diff --git a/edg/vendor_parts/jlc/JlcBlackbox.py b/edg/vendor_parts/jlc/JlcBlackbox.py index cc029fa97..2911becf5 100644 --- a/edg/vendor_parts/jlc/JlcBlackbox.py +++ b/edg/vendor_parts/jlc/JlcBlackbox.py @@ -26,6 +26,7 @@ def block_from_symbol( kicad_value=symbol.properties.get("Value", ""), kicad_datasheet=symbol.properties.get("Datasheet", ""), kicad_jlcpcb_part=symbol.properties["JLCPCB Part #"], + kicad_pin_names=[f"{pin.number}={pin.name}" for pin in lib.pins if pin.name and pin.name != "~"], ) # required, no .get(...) def block_pinning(block: KiCadJlcBlackbox) -> Mapping[str, BasePort]: @@ -42,6 +43,8 @@ def __init__( kicad_value: StringLike, kicad_datasheet: StringLike, kicad_jlcpcb_part: StringLike, + *, + kicad_pin_names: ArrayStringLike = [], ): super().__init__() self.ports = self.Port(Vector(Passive()), optional=True) @@ -54,7 +57,8 @@ def __init__( self.assign(self.actual_basic_part, False) # assumed self.kicad_pins = self.ArgParameter(kicad_pins) - self.generator_param(self.kicad_pins) + self.kicad_pin_names = self.ArgParameter(kicad_pin_names) + self.generator_param(self.kicad_pins, self.kicad_part, self.kicad_pin_names) @override def generate(self) -> None: @@ -69,3 +73,8 @@ def generate(self) -> None: value=self.kicad_value, datasheet=self.kicad_datasheet, ) + numbers = self.get(self.kicad_pins) + lib_id = self.get(self.kicad_part) + if numbers and ":" in lib_id: + names = dict(value.split("=", 1) for value in self.get(self.kicad_pin_names)) + self.schematic_symbol(lib_id, {number: number for number in numbers}, pin_names=names) diff --git a/examples/export_schematic.py b/examples/export_schematic.py new file mode 100644 index 000000000..861bda9af --- /dev/null +++ b/examples/export_schematic.py @@ -0,0 +1,61 @@ +"""Opt-in schematic export example; run from the PB checkout. + +python -m examples.export_schematic --output /tmp/pb-schematic-example \\ + --symbol-dir /usr/share/kicad/symbols + +This writes generated review artifacts to the requested destination. PB Python +remains authoritative; no KiCad installation is needed for generation. +""" + +import argparse +from pathlib import Path + +from edg import SchematicExportOptions, SchematicPlacement, SchematicPresentation, compile_board +from .test_blinky import TestLed + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument( + "--symbol-dir", action="append", default=[], help="Ordered symbol library directory (repeatable)" + ) + parser.add_argument( + "--orientation-mode", + choices=("half_turn", "passive_quarter_turn"), + default="half_turn", + help="Opt in to four-orientation passive refinement", + ) + args = parser.parse_args() + compile_board( + TestLed, + (str(args.output), "TestLed"), + schematic=SchematicExportOptions( + "TestLed", + symbol_library_dirs=tuple(args.symbol_dir), + optimize_orientations=True, # deterministic fixed-center trials + orientation_mode=args.orientation_mode, + presentation=SchematicPresentation.from_dict( + { + "schema": 2, + "circuits": [ + { + "id": "status_indicator", + "title": "Status LED", + "summary": "Current-limited LED indicator; the series resistor sets LED current.", + "components": ["led.res", "led.package"], + } + ], + } + ), + placements={ + "led.res": SchematicPlacement("Status LED", 80, 100, lock_rotation=False), + "led.package": SchematicPlacement("Status LED", 80, 70, rotation=90), + }, + ), + ) + print(args.output / "TestLed.schematic") + + +if __name__ == "__main__": + main() diff --git a/examples/schematic_presentations.py b/examples/schematic_presentations.py new file mode 100644 index 000000000..3a23585b3 --- /dev/null +++ b/examples/schematic_presentations.py @@ -0,0 +1,131 @@ +"""Optional source-owned explanatory annotations for generated example schematics. + +These describe intent already present in the example/model sources. They do not +supply layout coordinates, change parts, or add electrical connections. The +ordinary automatic export remains available without this companion data. +""" + +from edg.electronics_model.KiCadSchematicPresentation import SchematicPresentation + +# Evidence: test_battery_protector.py contents connects the holder to protector +# input and the LED/resistor to protector output; there is no external load jack. +PRESENTATIONS = { + "BatteryProtectorCircuit": { + "schema": 1, + "components": { + "li_ion_bat": {"description": "18650 battery source, 2.5-4.2 V", "pin_names": {"1": "BAT+", "2": "BAT-"}}, + "led.package": {"description": "Protected-output indicator; this LED branch is the modeled load"}, + "battery_protector.do_fet": {"description": "Discharge protection in battery return"}, + "battery_protector.co_fet": {"description": "Charge protection in battery return"}, + }, + }, + # test_bldc_controller.py explicitly uses IoControllerPowerOut/UsbOut; + # Feather_Nrf52840.generate exports device pins 2 (3V3) and 26 (USB). + "BldcController": { + "schema": 1, + "components": { + "mcu.device": { + "description": "Feather module supplies USB-derived vusb and regulated 3.3 V", + "pin_names": {"2": "3V3 OUT", "26": "USB OUT", "4": "GND"}, + }, + }, + }, + # EspProgrammerTc2030Inline.contents explicitly assigns all six contacts; + # UART TX/RX names are from the TARGET perspective, as its comment states. + "EspProgrammer": { + "schema": 1, + "components": { + "out.conn": { + "description": "ESP target programming; UART names are target-side", + "pin_names": { + "1": "3V3", + "2": "BOOT", + "3": "TARGET TX", + "4": "TARGET RX", + "5": "GND", + "6": "EN / RESET", + }, + }, + }, + }, + # test_protected_charger.py connects battery -> pmos -> pmos_load -> pin2. + "ProtectedCharger": { + "schema": 1, + "components": { + "pmos.mp1": {"description": "Battery reverse protection with bidirectional charge path"}, + "pmos_load.fet": {"description": "Protected battery/charger node feeds load reverse protection"}, + "pwr_pins": {"description": "Protected load output", "pin_names": {"1": "GND", "2": "LOAD+", "3": "GND"}}, + }, + }, + # StTscSenseChannel.contents terminates res.b in DummyPassive. It models the + # touch input but creates no physical electrode/connector footprint. + "UsbKey": { + "schema": 1, + "components": { + "ts1.res": {"description": "Touch channel 1; electrode geometry is not modeled in PB"}, + "ts2.res": {"description": "Touch channel 2; electrode geometry is not modeled in PB"}, + }, + "interfaces": [ + {"component": "ts1.res", "pin": "2", "name": "Touch electrode 1 endpoint"}, + {"component": "ts2.res", "pin": "2", "name": "Touch electrode 2 endpoint"}, + ], + }, + # FpgaProgrammingHeader.pwr is optional and receives no board connection. + # Ft232hl.contents connects internal VCCD regulator output to VCCIO. + "UsbFpgaProgrammer": { + "schema": 1, + "components": { + "out.conn": { + "description": "FPGA MPSSE target; pin 1 is unconnected in this PB design", + "pin_names": { + "1": "PWR (unconnected)", + "2": "CS", + "3": "GND", + "4": "SCK", + "5": "GND", + "6": "MOSI", + "8": "MISO", + "9": "GND", + "10": "RESET", + }, + }, + "ft232.ic": {"description": "USB MPSSE bridge; VCCIO supplied by internal VCCD regulator"}, + }, + }, + # test_iot_led_driver.py explicitly omits connectors and uses DummyPassive + # loads. Tps92200 connects leda to output capacitor +, ledk to sense resistor b. + "IotLedDriver": { + "schema": 1, + "components": { + **{ + f"led_drv[{i}].power_path.out_cap.cap": { + "description": f"LED channel {i + 1} output; solder external LED anode to this positive node" + } + for i in range(4) + }, + **{ + f"led_drv[{i}].rsense.res.res": { + "description": f"LED channel {i + 1} return; external LED cathode connects at pin 2" + } + for i in range(4) + }, + }, + "interfaces": [ + { + "component": f"led_drv[{i}].power_path.out_cap.cap", + "pin": "1", + "name": f"LED{i + 1}+ (solder connection)", + } + for i in range(4) + ] + + [ + {"component": f"led_drv[{i}].rsense.res.res", "pin": "2", "name": f"LED{i + 1}- (solder connection)"} + for i in range(4) + ], + }, +} + + +def presentation_for(design_name: str) -> SchematicPresentation: + """Return an independent typed presentation, empty for unannotated examples.""" + return SchematicPresentation.from_dict(PRESENTATIONS.get(design_name, {"schema": 1})) diff --git a/pyproject.toml b/pyproject.toml index d4693f5a5..fdb68259b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,7 @@ include = ["edg*"] "edg" = ["core/resources/edg-compiler-precompiled.jar", "**/*.kicad_sch", "**/*.json", "**/*.csv", "**/py.typed"] [tool.mypy] +mypy_path = "$MYPY_CONFIG_FILE_DIR/stubs" enable_error_code = ["explicit-override"] strict = true diff --git a/stubs/sexpdata/__init__.pyi b/stubs/sexpdata/__init__.pyi new file mode 100644 index 000000000..06c0d9277 --- /dev/null +++ b/stubs/sexpdata/__init__.pyi @@ -0,0 +1,15 @@ +"""Typed surface used by PB for sexpdata 1.x; parsed trees are heterogeneous.""" + +from typing import Any + +class String(str): + def value(self) -> str: ... + @classmethod + def quote(cls, string: str) -> str: ... + @classmethod + def unquote(cls, string: str) -> str: ... + +class Symbol(String): ... + +def loads(string: str, **kwds: Any) -> Any: ... +def dumps(obj: Any, **kwds: Any) -> str: ...