← Commit history

Merge PR #630: 0.2.126: SPICE models on the Altium library's symbols (release-0.2.126 -> main) merge

Colby Knox ·15ead16ea0 · ·parents 5e79b94, 4733550

Showing changes introduced by the merge (against its first parent).

12 files changed +156−17
Cargo.lock+10−10
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -27,7 +27,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-board",  "serde",@@ -37,7 +37,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.125"+version = "0.2.126" dependencies = [  "roxmltree",  "serde",@@ -46,7 +46,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-board",  "serde",@@ -55,7 +55,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -65,7 +65,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-board",  "serde",@@ -74,7 +74,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-board",  "serde",@@ -83,7 +83,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -93,7 +93,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.125"+version = "0.2.126" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -104,7 +104,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.125"+version = "0.2.126" dependencies = [  "serde",  "serde_json",
Cargo.toml+1−1
@@ -14,7 +14,7 @@ members = [ ]  [workspace.package]-version = "0.2.125"+version = "0.2.126" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow
⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/main.rs+1−1
@@ -5919,7 +5919,7 @@ fn main() {             // the lane's pure helpers (tools/altium-lane.py: the symbol check, project-library parts), then the Altium half             let run = Run::open(&dir);             let target = target.clone().or_else(|| run.as_ref().and_then(|r| r.data["target"].as_str().map(str::to_string))).or_else(|| std::env::var("AIFLOW_TARGET").ok()).unwrap_or_default();-            let script = format!("{}\n{}\n{}\n{}", include_str!("../../../tools/project-common.py"), include_str!("../../../tools/silkscreen-plan.py"), include_str!("../../../tools/altium-lane.py"), include_str!("../../../tools/altium-project.py"));+            let script = format!("{}\n{}\n{}\n{}\n{}", include_str!("../../../tools/project-common.py"), include_str!("../../../tools/silkscreen-plan.py"), include_str!("../../../tools/altium-lane.py"), include_str!("../../../tools/altium-spice.py"), include_str!("../../../tools/altium-project.py"));             let status = std::process::Command::new("python3").arg(lane_script("altium", &script)).args(args)                 .env("AIFLOW_RUN", &dir).env("AIFLOW_TARGET", &target).env("AIFLOW_THREAD", thread(&cli)).env("AIFLOW_EXE", std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default())                 .status().unwrap_or_else(|e| err(&format!("altium steps need python3: {e}"), &[]));
docs/altium-lane.md+10
@@ -148,3 +148,13 @@ A failing field screen names the neck and its fix. The solve runs on the snapsho   to 0.95 x the height and the stroke (a seventh of the height) pads every side.  On an Altium run every step's clip films Altium's main window, the board fitted to the view first.++## SPICE models on the library's symbols (altium-bridge 0.2.115+)++`altium library` attaches a SPICE model to each symbol that has one named, so the delivered Altium project simulates in Altium (and an IntLib built from it carries the model). Name it per MPN in the spec, or in the part's project-library entry:++```json+"spiceModels": {"1N4148W": {"file": "sim/models/1N4148.lib", "model": "1N4148", "pinMap": {"1": 2, "2": 1}}}+```++`file` is relative to the spec's folder (provenance.json: `"spice"`, `"spiceModel"`, `"spicePinMap"`, relative to the project library). `model` names one .MODEL/.SUBCKT when the file holds several. `pinMap` maps symbol pin to model node (from 1). Pins named for their SPICE role (A/K, C/B/E, D/G/S) map by name, others by number: give `pinMap` whenever the datasheet gives a subcircuit's node order. The model goes on after every import (an import replaces the symbol), and the library is saved. An encrypted vendor model (TI's PSpice packages) is refused and named; a part's import never fails for its model. Simulating the whole drawn schematic in Altium waits on altium-bridge: generic R/C/L models and a source on a simulation copy of the sheet are not there yet.
docs/release-0.2.126.mdadded+18
@@ -0,0 +1,18 @@+# adom-aiflow 0.2.126++## Altium: SPICE models on the project library's symbols (altium-bridge 0.2.115)++`altium library` now attaches a SPICE model to each symbol that has one named, through altium-bridge's new `altium_add_sim_model`, so the delivered Altium project simulates in Altium and an IntLib built from it carries the model.++- Name the model per MPN in the spec: `"spiceModels": {"<MPN>": {"file": "sim/models/x.lib", "model": "<name>", "pinMap": {"1": 2}}}`. A project-library part can carry it instead in provenance.json (`spice`, `spiceModel`, `spicePinMap`).+- The model goes on after every import (`altium_import_part` replaces the symbol), and the library is saved.+- Pins named for their SPICE role map by name. Give `pinMap` when the datasheet gives a subcircuit's node order.+- An encrypted vendor model is refused and named, as are a file with no model, a pin mismatch, several models with none named, or an unsupported model type. A part's import never fails for its model.+- The library step reports which symbols carry a model and which do not, and why.+- The aiflow-simulate skill says to name the unencrypted models it downloads on the Altium lane.++Tested live on the test desktop (Altium Designer 26, altium-bridge 0.2.116): a 1N4148W imported from its wiki page with a 1N4148 diode model attached, its pins mapped K to the cathode node and A to the anode.++Simulating the whole drawn schematic in Altium waits on the bridge: every part needs a model (resistors, capacitors and inductors have none yet), and nothing adds a source to drive the sheet. altium-lane is building both.++Also: the library step no longer crashes on a parts list entry with no reference.
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.125",+  "version": "0.2.126",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.125",+  "version": "0.2.126",   "title": "AI Flow",   "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.",   "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/aiflow-simulate/SKILL.md+1
@@ -74,6 +74,7 @@ Then write the design conclusion in engineering terms: what matched, what the ve  - `adom-aiflow evidence add --kind simulation --file sim/<results>.json`. Write the verdict into the JSON so the gate can read it: a top-level `"pass": true|false`, or `"checks": [{"name": "phase_margin_deg", "value": 76, "limit": {"min": 45}, "pass": true}]` (a numeric `limit` is a maximum). A failing result is refused: change the design and simulate again. - `adom-aiflow evidence add --kind vendor-model --file sim/<vendor>-validation.md` for the vendor PSpice/LTspice run, which belongs to the adom/adom-spice-skillpack.+- On the Altium lane, name each unencrypted model you downloaded in the spec (`spiceModels`: {MPN: {file, model, pinMap}}) so `altium library` puts it on the part's symbol and the Altium project simulates (docs/altium-lane.md).  `finish` wants simulation evidence when the spec says `"requireEvidence": ["calcs", "simulation"]`. Next: aiflow-schematic-to-board. 
tests/altium-spice.pyadded+28
@@ -0,0 +1,28 @@+"""tools/altium-spice.py without Altium: the encrypted-model check and the library step's summary lines.+  python3 tests/altium-spice.py"""+import re, unittest+from pathlib import Path++SRC = Path(__file__).resolve().parent.parent / 'tools' / 'altium-spice.py'+ns = {'re': re, 'Path': Path}+exec(SRC.read_text(), ns)+++class AltiumSpice(unittest.TestCase):+    def test_an_encrypted_vendor_model_is_told_apart(self):+        self.assertTrue(ns['encrypted']('* TI\n$CDNENCSTART\nabc\n$CDNENCFINISH\n'))+        self.assertTrue(ns['encrypted']('.SUBCKT X 1 2\n.PROT\n...'))+        self.assertFalse(ns['encrypted']('.MODEL 1N4148 D (IS=2.52n)\n'))++    def test_the_summary_names_attached_and_refused_models(self):+        parts = {'1N4148W': {'sim': {'attached': True, 'kind': 'D', 'model': '1N4148'}},+                 'TPS54202': {'sim': {'attached': False, 'why': 'the model is encrypted'}},+                 'R0603': {}}+        lines = ns['spice_summary'](parts)+        self.assertEqual(lines[0], 'SPICE models on 1 symbol(s), so they simulate in Altium: 1N4148W (D 1N4148).')+        self.assertEqual(lines[1], 'SPICE models not attached: TPS54202: the model is encrypted.')+        self.assertEqual(ns['spice_summary']({'R0603': {}}), [])+++if __name__ == '__main__':+    unittest.main()
tools/altium-project.py+6−3
@@ -177,16 +177,19 @@ def cmd_library(a):         # the symbol spec as imported, kept for the schematic's symbol check (every display mode's pins on its body)         if spec_sym: shutil.copy(spec_sym, kept_specs / spec_sym.name)         st['parts'][key] = {'imported': True, 'mpn': w.get('mpn'), 'refs': w['refs'], 'symbol': bool(spec_sym), 'step': bool(step), 'params': params, 'source': w['origin']}+        # a SPICE model, when the spec or the project library names one: attached after every import (import_part replaces the symbol)+        se = spice_entry(w) if spec_sym and w['origin'] != 'board-only' else None+        if se: st['parts'][key]['sim'] = attach_spice(key, se, sch_lib, bdir)         if w['origin'] == 'project-lib': st['parts'][key]['projectLib'] = {'dir': w['projectLib'].get('dir'), 'source': w['projectLib'].get('source')}         added.append(key)-        say('part %s: footprint%s%s, refs %s%s' % (key, ', symbol' if spec_sym else '', ', 3D' if step else '', ' '.join(w['refs']), ' (from the project library)' if w['origin'] == 'project-lib' else ''))+        say('part %s: footprint%s%s%s, refs %s%s' % (key, ', symbol' if spec_sym else '', ', 3D' if step else '', (', SPICE model' if st['parts'][key].get('sim', {}).get('attached') else ', no SPICE model (%s)' % st['parts'][key]['sim'].get('why')) if st['parts'][key].get('sim') else '', ' '.join(r for r in w['refs'] if r) or '-', ' (from the project library)' if w['origin'] == 'project-lib' else ''))         save_state(st)     st['schLib'], st['pcbLib'] = sch_lib, pcb_lib     save_state(st)-    prove('library', {'name': name, 'parts': len(st['parts']), 'tool': 'altium', 'projectLibParts': from_lib})+    prove('library', {'name': name, 'parts': len(st['parts']), 'tool': 'altium', 'projectLibParts': from_lib, 'spiceModels': sum(1 for p in st['parts'].values() if (p.get('sim') or {}).get('attached'))})     ok('library %s: %d part(s) (%d added, %d kept%s): %s and %s' % (name, len(st['parts']), len(added), len(kept),                                                                     '; %d from the board\'s project library: %s' % (len(from_lib), ', '.join(from_lib)) if from_lib else '', pcb_lib, sch_lib),-       ['No distributor number yet: ' + '; '.join('%s %s' % (m, ' '.join(v)) for m, v in unverified.items()) + '. Run `altium library` again when the services are back, or add the numbers to the part\'s wiki page (a project-library part: "mouser"/"digikey"/"lcsc" in its provenance.json entry).' if unverified else '',+       spice_summary(st['parts']) + ['No distributor number yet: ' + '; '.join('%s %s' % (m, ' '.join(v)) for m, v in unverified.items()) + '. Run `altium library` again when the services are back, or add the numbers to the part\'s wiki page (a project-library part: "mouser"/"digikey"/"lcsc" in its provenance.json entry).' if unverified else '',         'Next: adom-aiflow altium reference --kicad <reference .kicad_pcb> --spec <spec.json> (if there is a reference board), then adom-aiflow altium schematic --netlist <netlist.json> --name <Design> (the schematic, then the board in the same project).'])  
tools/altium-spice.pyadded+79
@@ -0,0 +1,79 @@+"""altium-spice: a SPICE model on each project-library symbol that has one, so the delivered Altium project simulates.++A part's model is named per MPN, in the run's spec or in its project-library entry:+  spec.json:        "spiceModels": {"1N4148W": {"file": "sim/models/1N4148.lib", "model": "1N4148", "pinMap": {"1": 2, "2": 1}}}+  provenance.json:  {"mpn": "...", "spice": "models/x.lib", "spiceModel": "X", "spicePinMap": {"1": 2}}+`file` is relative to the spec's folder (or the project library's), or absolute in this container. `model` names one+.MODEL/.SUBCKT when the file holds several; `pinMap` maps symbol pin -> model node (from 1) when the pins are not named+for their SPICE role (A/K, C/B/E, D/G/S): give it whenever the datasheet gives the subcircuit's node order.++After `altium_import_part` (which replaces the symbol on every import), `altium_add_sim_model` (altium-bridge 0.2.115+)+attaches the model the way Altium's Sim Model dialog does, and the SchLib is saved. An encrypted vendor model+($CDNENCSTART, TI's PSpice packages) is refused there and here, and named; no part's import fails for its model.+"""++SPICE_REFUSALS = {+    'encrypted_model': 'the model is encrypted (it runs only in the vendor\'s own simulator)',+    'no_model': 'the file holds no .MODEL or .SUBCKT',+    'pin_map': 'its pins do not map onto the model\'s nodes',+    'which_model': 'the file holds several models: name one (model)',+    'model_not_found': 'the named model is not in the file',+    'unsupported_model': 'Altium takes only D, BJT, MOSFET, JFET and subcircuit models here',+    'file_not_found': 'the model file is not on the desktop',+}+++def spice_entry(w):+    """The part's SPICE model declaration: the spec's spiceModels[MPN], else its project-library provenance. None: none."""+    mpn = w.get('mpn') or ''+    spec = run_spec()+    base = Path(run_data().get('spec') or '.').parent+    models = spec.get('spiceModels') or {}+    e = models.get(mpn) or next((v for k, v in models.items() if k.strip().upper() == mpn.strip().upper()), None)+    if e:+        return {'file': e.get('file'), 'model': e.get('model'), 'pinMap': e.get('pinMap'), 'base': base, 'from': 'spec spiceModels'}+    pl = w.get('projectLib') or {}+    prov = pl.get('provenance') or {}+    if prov.get('spice'):+        return {'file': prov['spice'], 'model': prov.get('spiceModel'), 'pinMap': prov.get('spicePinMap'), 'base': Path(pl.get('dir') or '.'), 'from': 'project library'}+    return None+++def encrypted(text):+    return '$CDNENCSTART' in text or '$CDNENCFINISH' in text or re.search(r'(?mi)^\s*\.prot\b', text) is not None+++def attach_spice(key, e, sch_lib, bdir):+    """Attach one part's model to its symbol. Returns {attached, model?, kind?, why?} for the library's state."""+    f = Path(e['file'] or '')+    if not f.is_absolute(): f = e['base'] / f+    if not f.is_file():+        return {'attached': False, 'why': 'model file %s not found (%s)' % (f, e['from'])}+    text = f.read_text(errors='replace')+    if encrypted(text):+        return {'attached': False, 'why': SPICE_REFUSALS['encrypted_model'], 'file': str(f)}+    send([f], bdir + '/stage/spice')+    args = {'libraryPath': win(sch_lib), 'symbolName': key, 'modelPath': win(bdir + '/stage/spice/' + f.name)}+    if e.get('model'): args['modelName'] = e['model']+    if e.get('pinMap'): args['pinMap'] = e['pinMap']+    r = ab('altium_add_sim_model', args, timeout=600)+    if not r.get('success'):+        code = r.get('errorCode') or ''+        why = SPICE_REFUSALS.get(code) or str(r.get('error') or code or 'refused')[:200]+        if code == 'pin_map' and r.get('symbolPins'): why += '; symbol pins %s' % r.get('symbolPins')+        if code in ('which_model', 'model_not_found') and r.get('models'): why += '; models in the file: %s' % ', '.join(map(str, r.get('models')))+        if code in ('unknown_verb', 'not_found') or 'unknown' in code: why = 'altium-bridge has no altium_add_sim_model (update it to 0.2.115 or later)'+        return {'attached': False, 'why': why, 'file': str(f)}+    ab('altium_save', {'filePath': win(sch_lib)})+    m = r.get('model') or {}+    return {'attached': True, 'model': m.get('name'), 'kind': m.get('kind'), 'nodes': m.get('nodes'), 'pinMap': r.get('pinMap'), 'file': str(f)}+++def spice_summary(parts):+    """Hint lines for the library step: models attached and models refused, per part."""+    on = ['%s (%s %s)' % (k, p['sim'].get('kind') or '', p['sim'].get('model') or '') for k, p in parts.items() if (p.get('sim') or {}).get('attached')]+    off = ['%s: %s' % (k, p['sim'].get('why')) for k, p in parts.items() if p.get('sim') and not p['sim'].get('attached')]+    out = []+    if on: out.append('SPICE models on %d symbol(s), so they simulate in Altium: %s.' % (len(on), ', '.join(on)))+    if off: out.append('SPICE models not attached: %s.' % '; '.join(off))+    return out