by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
← Commit history
0.2.115: altium_add_sim_model, a SPICE model on a library symbol in the Sim Model dialog's form (#42)
12 files changed
+438−22
CHANGELOG.md+7README.md+5−4bridge-rs/src/main.rs+2−1bridge-rs/src/simmodel.rs+276bridge-rs/src/verbs.rs+9−1dev-skills/altium-bridge-test/run_verb_tests.py+3package.json+1−1page.json+2−2skills/altium-schematic-edit/SKILL.md+17−11src/BRIDGE_VERSION+1−1src/agent/AdomAgent.pas.tmpl+113src/bridge.json+2−1CHANGELOG.md+7@@ -1,5 +1,12 @@ # Changelog +## 0.2.115++- **New verb `altium_add_sim_model`: a SPICE model on a library symbol** (#42). Give it a `.SchLib` symbol and a SPICE file (`.MODEL` or `.SUBCKT`: diodes, BJTs, MOSFETs, JFETs, subcircuits). It writes a clean copy of the model beside the library (a vendor's uncommented title line dropped) and puts it on the symbol the way Altium's Sim Model dialog does: the model file linked by its full path with kind `mdl`, Kind, SubKind, Spice Prefix and Netlist on the model, and the symbol's pins mapped onto the model's nodes. The placed part simulates in Altium, and the IntLib compiler packs the model.+- Pins named for their role (anode/cathode, collector/base/emitter, drain/gate/source/body) go to their SPICE node whatever their numbers; `pinMap` sets any other mapping. `dryRun` answers the plan.+- An encrypted model (`$CDNENCSTART` or `.PROT`, as many PSpice packages are) is refused by name: only PSpice runs it.+- Tested with a 1N4148 from a vendor-style file (title line, continuation lines) on a two-pin symbol with its cathode on pin 1. On Altium Designer 26.11.1 and on Develop the IntLib held `MDL/0.mdl` and a SIM row for the symbol. On Altium Designer 26.11.1, placed in Altium's Simulation Quick Start amplifier, the netlist read `DD9 out 0 1N4148` (anode on OUT) and the operating point clamped OUT to 0.719 V.+ ## 0.2.114 - **Placed parts keep their models** (#42). `altium_sch_place_part`, `altium_create_part_project`, `altium_place_on_sch` and `altium_build_schematic` rebuilt each part from its drawing, which dropped every model but the footprint (a SIM model, its STRESS model, ...) and copied each model's parameters (a SIM model's `Netlist` template, its `.MODEL` values) onto the part, some as visible text. They now place the part through Altium's own library placement, as the Components panel does: every model, only the part's own parameters, its part count and its library identity. A part placed this way simulates with its library model. Replies list the part's `models` and say how it was placed (`placement: library`); a library Altium cannot load still falls back to the rebuild (`placement: rebuilt`), now with only the part's own parameters.
README.md+5−4@@ -15,7 +15,7 @@ normal session. Ask in plain words and it: - makes the outputs: Gerbers, NC drill, pick and place, BOMs grouped by MPN (JLCPCB, Mouser, DigiKey files), schematic PDF and STEP, checking that the outline and every copper layer reached the Gerbers -283 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+284 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free desktop app, through Adom Bridge. You bring your own AI subscription and your own Altium licence. ::youtube{id="dFecpcIzdSE" title="An AI designs a 12 V to 5 V buck converter in Altium Designer"}@@ -29,7 +29,7 @@ and the verb prefix `altium_`. ## What it can do -Tested on Altium Designer 26.11.1 and Altium Designer Develop. 283 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 284 verbs; each row names the ones behind it (prefix `altium_`). | Area | What the AI can do | Verbs |@@ -70,7 +70,7 @@ This bridge is the reference for the [EDA Bridge Standard](https://wiki.adom.inc Altium Designer is the user's own **host app**. The bridge finds an installed Altium (`%ProgramFiles%\Altium\AD*\X2.EXE`, Designer or Develop), starts it in the background, runs a small-**DelphiScript agent** inside it, and gives the AI 283 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 284 `altium_*` verbs. - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -170,7 +170,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`. <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 283 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 284 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -455,6 +455,7 @@ All 283 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_add_symbol_art`: Draw the chip-outline artwork (the chip-thumbnailer polylines adom-symbol baked into the KiCad symbol) into a SchLib component, fitted to its body rectangle, so the Altium symbol shows the same chip as KiCad and Fusion. - `altium_symbol_prims`: Read a SchLib component's drawing: primitive counts by kind, body rectangle, polyline bounding box, display mode and the footprint models. - `altium_set_models`: Replace every footprint model on a SchLib component with ONE PCBLIB model (set_params footprint and add_models APPEND, which is how a symbol ends up with two).+- `altium_add_sim_model`: Put a SPICE model (.MODEL or .SUBCKT from a .mdl/.lib/.ckt file) on a SchLib symbol, as Altium's Sim Model dialog does, so the placed part simulates in Altium and the model goes into an IntLib. - `altium_selftest_script_error`: Regression test for the script-error safety net (from 0.2.23): makes the agent raise a REAL DelphiScript runtime error on purpose and checks that the bridge photographs Altium's Error box, stops the halted script itself and leaves no dialog behind. - `altium_install`: Install Altium Designer on this machine, STAGED, with the rules in the verb (from 0.2.29).
bridge-rs/src/main.rs+2−1@@ -12,6 +12,7 @@ mod gloss; mod fplayers; mod layermap; mod layermap_verb;+mod simmodel; mod autoclass; mod board; mod bodies;@@ -87,7 +88,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.114";+pub const BRIDGE_VERSION: &str = "0.2.115"; fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> { let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/simmodel.rsadded+276@@ -0,0 +1,276 @@+//! altium_add_sim_model (#42): a SPICE model on a SchLib symbol, written the way Altium's Sim Model dialog writes it, so+//! the part simulates in Altium and the model goes into an IntLib. Measured 2026-12-01 on AD 26.11: a SIM implementation+//! linked with kind `mdl` (lower case), the model file's full path, no UseComponentLibrary and no locked data links,+//! with Kind, SubKind, Spice Prefix and Netlist on the implementation, compiles into an IntLib with `MDL/0.mdl` and a+//! SIM entry in LibCrossRef.Txt. The model file is read, cleaned (a vendor's uncommented title line goes) and written+//! beside the library; the symbol's pins are mapped onto the model's nodes.+use serde_json::{json, Value};+use std::collections::BTreeMap;++/// One model in a SPICE file.+#[derive(Clone, Debug, PartialEq)]+pub struct Model {+ pub name: String,+ /// `D`, `NPN`, `NMOS`, ... for a `.MODEL`; `SUBCKT` for a `.SUBCKT`+ pub kind: String,+ /// a subcircuit's nodes, in order+ pub nodes: Vec<String>,+ /// the cards, joined back into whole lines+ pub text: String,+}++/// The SPICE cards of a file: continuation lines (`+`) joined, comments and blank lines left out, and anything before+/// the first card that is not a comment (a vendor's title line) dropped.+fn cards(text: &str) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ for raw in text.lines() {+ let l = raw.split(';').next().unwrap_or("").trim_end();+ let t = l.trim_start();+ if t.is_empty() || t.starts_with('*') { continue; }+ if let Some(rest) = t.strip_prefix('+') {+ if let Some(last) = out.last_mut() { last.push(' '); last.push_str(rest.trim()); }+ continue;+ }+ out.push(t.to_string());+ }+ // a title line is not a card: SPICE reads the first line of a netlist as its title, which a vendor's model file+ // often carries uncommented+ while out.first().is_some_and(|c| !c.starts_with('.')) { out.remove(0); }+ out+}++/// A Cadence-encrypted model (PSpice packages carry `$CDNENCSTART`, even TI's "unencrypted" ones) or a protected block:+/// Altium cannot simulate it.+pub fn encrypted(text: &str) -> bool {+ let l = text.to_ascii_lowercase();+ l.contains("$cdnencstart") || l.contains("$cdnencfinish") || l.lines().any(|x| x.trim_start().starts_with(".prot"))+}++/// Every `.MODEL` and `.SUBCKT` in a file.+pub fn parse(text: &str) -> Vec<Model> {+ let cs = cards(text);+ let mut out = Vec::new();+ let mut i = 0;+ while i < cs.len() {+ let c = &cs[i];+ let low = c.to_ascii_lowercase();+ if low.starts_with(".model") {+ let mut w = c.split_whitespace().skip(1);+ let name = w.next().unwrap_or("").to_string();+ let kind = w.next().unwrap_or("").split('(').next().unwrap_or("").to_ascii_uppercase();+ if !name.is_empty() { out.push(Model { name, kind, nodes: vec![], text: c.clone() }); }+ } else if low.starts_with(".subckt") {+ let toks: Vec<&str> = c.split_whitespace().collect();+ let name = toks.get(1).unwrap_or(&"").to_string();+ let nodes: Vec<String> = toks.iter().skip(2).take_while(|t| !t.contains('=') && !t.eq_ignore_ascii_case("params:")).map(|t| t.to_string()).collect();+ let mut block = vec![c.clone()];+ let mut j = i + 1;+ while j < cs.len() {+ block.push(cs[j].clone());+ if cs[j].to_ascii_lowercase().starts_with(".ends") { break; }+ j += 1;+ }+ if !name.is_empty() { out.push(Model { name, kind: "SUBCKT".into(), nodes, text: block.join("\n") }); }+ i = j;+ }+ i += 1;+ }+ out+}++/// How Altium describes a model of this kind: (Description, Kind, SubKind, Spice Prefix, model nodes). The names are+/// Altium's own (its examples: General/Diode/D, Transistor/BJT/Q). None for a kind this verb does not attach.+pub fn altium_kind(m: &Model) -> Option<(&'static str, &'static str, &'static str, &'static str, usize)> {+ Some(match m.kind.as_str() {+ "D" => ("Diode", "General", "Diode", "D", 2),+ "NPN" => ("NPN", "Transistor", "BJT", "Q", 3),+ "PNP" => ("PNP", "Transistor", "BJT", "Q", 3),+ "NMOS" => ("NMOS", "Transistor", "MOSFET", "M", 4),+ "PMOS" => ("PMOS", "Transistor", "MOSFET", "M", 4),+ "NJF" => ("NJFET", "Transistor", "JFET", "J", 3),+ "PJF" => ("PJFET", "Transistor", "JFET", "J", 3),+ "SUBCKT" => ("Subcircuit", "General", "Spice Subcircuit", "X", m.nodes.len()),+ _ => return None,+ })+}++/// The netlist template: `@DESIGNATOR %1 %2 ... @MODEL`. A MOSFET drawn with three pins ties its body to its source+/// (`%1 %2 %3 %3`).+pub fn netlist(nodes: usize, mosfet_three_pins: bool) -> String {+ let mut ns: Vec<String> = (1..=nodes).map(|i| format!("%{i}")).collect();+ if mosfet_three_pins { ns.push("%3".into()); }+ format!("@DESIGNATOR {} @MODEL", ns.join(" "))+}++/// The symbol-pin to model-node map. Given: `{"1": 2, "2": 1}` (symbol pin number to model node, from 1). Without one,+/// a diode's pins named for anode and cathode go to nodes 1 and 2, and otherwise the pins in number order go to the+/// nodes in order. Err says why the symbol and the model do not fit.+pub fn pin_map(given: Option<&Value>, pins: &[(String, String)], nodes: usize, kind: &str) -> Result<BTreeMap<String, usize>, String> {+ let mut map = BTreeMap::new();+ if let Some(g) = given.and_then(|v| v.as_object()) {+ for (k, v) in g {+ let n = v.as_u64().map(|n| n as usize).or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())).ok_or_else(|| format!("pinMap {k}: a model node number"))?;+ if n < 1 || n > nodes { return Err(format!("pinMap {k}: node {n}, the model has {nodes}")); }+ if !pins.iter().any(|(d, _)| d == k) { return Err(format!("pinMap {k}: the symbol has no pin {k}")); }+ map.insert(k.clone(), n);+ }+ return Ok(map);+ }+ // pins named for their role go to that node, whatever their numbers: SPICE's order is anode-cathode for a diode,+ // collector-base-emitter for a BJT, drain-gate-source(-body) for a FET+ let roles: &[&[&str]] = match kind {+ "D" => &[&["A", "ANODE", "+"], &["K", "C", "CATHODE", "KATHODE", "-"]],+ "NPN" | "PNP" => &[&["C", "COLLECTOR"], &["B", "BASE"], &["E", "EMITTER"]],+ "NMOS" | "PMOS" => &[&["D", "DRAIN"], &["G", "GATE"], &["S", "SOURCE"], &["B", "BULK", "BODY", "SUB"]],+ "NJF" | "PJF" => &[&["D", "DRAIN"], &["G", "GATE"], &["S", "SOURCE"]],+ _ => &[],+ };+ if !roles.is_empty() {+ let mut by_role = BTreeMap::new();+ for (i, words) in roles.iter().take(nodes).enumerate() {+ if let Some(p) = pins.iter().find(|(_, n)| words.iter().any(|w| n.eq_ignore_ascii_case(w))) { by_role.insert(p.0.clone(), i + 1); }+ }+ if by_role.len() == nodes && by_role.len() == pins.len().min(nodes) { return Ok(by_role); }+ }+ if pins.len() < nodes { return Err(format!("the symbol has {} pins and the model {nodes} nodes: give pinMap", pins.len())); }+ let mut ps: Vec<&(String, String)> = pins.iter().collect();+ ps.sort_by(|a, b| match (a.0.parse::<f64>(), b.0.parse::<f64>()) { (Ok(x), Ok(y)) => x.partial_cmp(&y).unwrap(), _ => a.0.cmp(&b.0) });+ for (i, p) in ps.iter().take(nodes).enumerate() { map.insert(p.0.clone(), i + 1); }+ Ok(map)+}++/// The map as Altium stores it: `(symbolPin:modelNode),...`.+pub fn map_string(m: &BTreeMap<String, usize>) -> String {+ m.iter().map(|(p, n)| format!("({p}:{n})")).collect::<Vec<_>>().join(",")+}++/// The clean model file: a header naming where it came from, the model (a subcircuit with every .MODEL of its file,+/// which it may use).+pub fn clean_file(m: &Model, all: &[Model], source: &str) -> String {+ let mut t = format!("* {} ({}), cleaned by altium-bridge from {}\n{}\n", m.name, m.kind, source, m.text);+ if m.kind == "SUBCKT" {+ for o in all.iter().filter(|o| o.kind != "SUBCKT") { t.push_str(&o.text); t.push('\n'); }+ }+ t+}++/// altium_add_sim_model {libraryPath, symbolName, modelPath, modelName?, pinMap?, replace?, dryRun?}+pub fn add_sim_model(args: &Value) -> Value {+ let s = |k: &str| crate::support::s(args, k);+ let bad = |m: String| json!({"success": false, "errorCode": "bad_args", "error": m});+ let (Some(lib), Some(sym), Some(mpath)) = (s("libraryPath"), s("symbolName"), s("modelPath")) else {+ return bad("libraryPath (.SchLib), symbolName and modelPath (the .mdl/.lib/.ckt SPICE file on this machine) are required".into());+ };+ if !lib.to_lowercase().ends_with(".schlib") { return bad(format!("{lib} is not a .SchLib")); }+ let text = match std::fs::read(&mpath) {+ Ok(b) => String::from_utf8_lossy(&b).to_string(),+ Err(e) => return json!({"success": false, "errorCode": "file_not_found", "error": format!("{mpath}: {e}")}),+ };+ if encrypted(&text) {+ return json!({"success": false, "errorCode": "encrypted_model", "error": format!("{mpath} is encrypted ($CDNENCSTART or .PROT): Altium cannot simulate it"),+ "_hint": "Encrypted PSpice models (TI's \"unencrypted\" packages often are) run only in PSpice. Use an unencrypted model, or a behavioural one of your own."});+ }+ let models = parse(&text);+ if models.is_empty() { return json!({"success": false, "errorCode": "no_model", "error": format!("{mpath} holds no .MODEL or .SUBCKT")}); }+ let m = match s("modelName") {+ Some(n) => match models.iter().find(|m| m.name.eq_ignore_ascii_case(&n)) { Some(m) => m.clone(), None => return json!({"success": false, "errorCode": "model_not_found", "error": format!("{mpath} has no model {n}"), "models": models.iter().map(|m| json!({"name": m.name, "kind": m.kind})).collect::<Vec<_>>()}) },+ None if models.iter().filter(|m| m.kind == "SUBCKT").count() == 1 => models.iter().find(|m| m.kind == "SUBCKT").unwrap().clone(),+ None if models.len() == 1 => models[0].clone(),+ None => return json!({"success": false, "errorCode": "which_model", "error": format!("{mpath} holds {} models: name one with modelName", models.len()), "models": models.iter().map(|m| json!({"name": m.name, "kind": m.kind})).collect::<Vec<_>>()}),+ };+ let Some((desc, kind, subkind, prefix, nodes)) = altium_kind(&m) else {+ return json!({"success": false, "errorCode": "unsupported_model", "error": format!("{} is a {} model: this verb attaches diodes, BJTs, MOSFETs, JFETs and subcircuits", m.name, m.kind)});+ };+ if let Some(e) = crate::support::must_open(&lib, 60) { return e; }+ let read = crate::agent::call("lib_symbol_pins", &[("libref", sym.clone())], None, std::time::Duration::from_secs(60));+ let pins: Vec<(String, String)> = read.pointer("/data/pins").and_then(|p| p.as_array()).map(|a| a.iter().filter_map(|p| Some((p.get(0)?.as_str()?.to_string(), p.get(1).and_then(|x| x.as_str()).unwrap_or("").to_string()))).collect()).unwrap_or_default();+ if read.pointer("/data/ok") != Some(&json!(true)) {+ return json!({"success": false, "errorCode": "symbol_not_found", "error": format!("no symbol {sym} in {lib}"), "reply": read.get("data")});+ }+ let mos3 = subkind == "MOSFET" && pins.len() == 3 && args.get("pinMap").is_none();+ let node_count = if mos3 { 3 } else { nodes };+ let map = match pin_map(args.get("pinMap"), &pins, node_count, &m.kind) { Ok(x) => x, Err(e) => return json!({"success": false, "errorCode": "pin_map", "error": e, "pins": pins}) };+ let ext = if m.kind == "SUBCKT" { "ckt" } else { "mdl" };+ let dir = std::path::Path::new(&lib.replace('\\', "/")).parent().map(|p| p.to_path_buf()).unwrap_or_default();+ let file = dir.join(format!("{}.{ext}", m.name)).to_string_lossy().replace('/', "\\");+ let template = netlist(node_count, mos3);+ let plan = json!({"model": {"name": m.name, "kind": m.kind, "nodes": nodes}, "file": file, "altium": {"description": desc, "kind": kind, "subKind": subkind, "spicePrefix": prefix, "netlist": template},+ "pinMap": map, "symbolPins": pins.iter().map(|(d, n)| json!([d, n])).collect::<Vec<_>>()});+ if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {+ let mut r = plan; r["success"] = json!(true); r["dryRun"] = json!(true);+ r["_hint"] = json!("Nothing changed. Check pinMap against the datasheet (a SPICE diode's node 1 is the anode), then call again without dryRun.");+ return r;+ }+ if let Err(e) = std::fs::write(&file, clean_file(&m, &models, &mpath)) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{file}: {e}")}); }+ let replace = args.get("replace").and_then(|b| b.as_bool()).unwrap_or(true);+ let r = crate::agent::call("add_sim", &[("libref", sym.clone()), ("name", m.name.clone()), ("file", file.clone()), ("fkind", ext.into()),+ ("desc", desc.into()), ("kind", kind.into()), ("subkind", subkind.into()), ("prefix", prefix.into()), ("netlist", template.clone()),+ ("map", map_string(&map)), ("replace", if replace { "1".into() } else { "0".into() })], None, std::time::Duration::from_secs(60));+ let d = r.get("data").cloned().unwrap_or(json!({}));+ if d["ok"] != true { let mut e = r.clone(); e["success"] = json!(false); return e; }+ let mut out = plan;+ out["success"] = json!(true);+ out["replaced"] = d["replaced"].clone();+ out["models"] = d["models"].clone();+ out["saved"] = json!(false);+ out["_hint"] = json!("The SIM model is on the symbol, in the form Altium's Sim Model dialog writes: it simulates once placed (altium_sch_place_part keeps it) and compiles into an IntLib with its model file. altium_save {filePath: libraryPath} keeps it. Check pinMap: a SPICE diode's node 1 is the anode, a BJT's 1-2-3 are collector, base, emitter.");+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ const VENDOR: &str = "1N4148 diode model from the vendor\r\n* comment\r\n.MODEL 1N4148 D(IS=2.52n RS=0.568 N=1.752 CJO=4p M=0.4\r\n+ TT=20n BV=100 IBV=100u) ; trailing\r\n";++ #[test]+ fn a_vendor_title_line_and_continuations_are_read_as_spice_does() {+ let m = parse(VENDOR);+ assert_eq!(m.len(), 1);+ assert_eq!(m[0].name, "1N4148");+ assert_eq!(m[0].kind, "D");+ assert!(m[0].text.contains("TT=20n BV=100 IBV=100u)") && !m[0].text.contains("vendor"), "{}", m[0].text);+ let f = clean_file(&m[0], &m, "C:/v/1N4148.lib");+ assert!(f.starts_with("* 1N4148 (D)") && f.lines().nth(1).unwrap().starts_with(".MODEL 1N4148 D("));+ }++ #[test]+ fn a_subcircuit_keeps_its_nodes_and_its_models() {+ let t = ".SUBCKT OPA1 IN+ IN- V+ V- OUT PARAMS: GAIN=10\nX1 IN+ IN- V+ V- OUT CORE\n.ENDS\n.MODEL DX D(IS=1e-14)\n";+ let m = parse(t);+ let s = m.iter().find(|m| m.kind == "SUBCKT").unwrap();+ assert_eq!(s.nodes, vec!["IN+", "IN-", "V+", "V-", "OUT"]);+ assert_eq!(altium_kind(s).unwrap().4, 5);+ assert!(clean_file(s, &m, "x").contains(".MODEL DX D"));+ assert_eq!(netlist(5, false), "@DESIGNATOR %1 %2 %3 %4 %5 @MODEL");+ }++ #[test]+ fn an_encrypted_model_is_refused() {+ assert!(encrypted("$CDNENCSTART\nabc\n$CDNENCFINISH"));+ assert!(encrypted(".PROT\n.MODEL X D\n.UNPROT"));+ assert!(!encrypted(VENDOR));+ }++ #[test]+ fn a_diode_maps_its_anode_to_node_one_whatever_its_pin_number() {+ let pins = vec![("1".to_string(), "K".to_string()), ("2".to_string(), "A".to_string())];+ let m = pin_map(None, &pins, 2, "D").unwrap();+ assert_eq!(map_string(&m), "(1:2),(2:1)");+ let given = pin_map(Some(&json!({"1": 1, "2": 2})), &pins, 2, "D").unwrap();+ assert_eq!(map_string(&given), "(1:1),(2:2)");+ assert!(pin_map(Some(&json!({"3": 1})), &pins, 2, "D").is_err());+ let q = vec![("2".to_string(), "B".to_string()), ("1".to_string(), "C".to_string()), ("3".to_string(), "E".to_string())];+ assert_eq!(map_string(&pin_map(None, &q, 3, "NPN").unwrap()), "(1:1),(2:2),(3:3)", "C B E by name");+ let q2 = vec![("1".to_string(), "B".to_string()), ("2".to_string(), "E".to_string()), ("3".to_string(), "C".to_string())];+ assert_eq!(map_string(&pin_map(None, &q2, 3, "NPN").unwrap()), "(1:2),(2:3),(3:1)", "SOT-23 B E C goes by name");+ let unnamed = vec![("2".to_string(), "x".to_string()), ("1".to_string(), "y".to_string())];+ assert_eq!(map_string(&pin_map(None, &unnamed, 2, "D").unwrap()), "(1:1),(2:2)", "number order without names");+ assert!(pin_map(None, &q[..2], 3, "NPN").is_err());+ }++ #[test]+ fn a_three_pin_mosfet_ties_its_body_to_its_source() {+ assert_eq!(netlist(3, true), "@DESIGNATOR %1 %2 %3 %3 @MODEL");+ }+}
bridge-rs/src/verbs.rs+9−1@@ -37,7 +37,7 @@ pub const KNOWN: &[&str] = &[ "clone_symbol", "rename_symbol", "rename_footprint", "remove_symbol", "remove_footprint", "copy_footprint", "xcopy_footprint", "swap_footprint", "symbol_mode", "cleanup_libs", "install_library", "install_library_bundle", "install_receipt", "compile_intlib", "extract_intlib",- "place_on_sch", "place_on_pcb", "import_part", "add_symbol_art", "symbol_prims", "set_models", "selftest_script_error", "install",+ "place_on_sch", "place_on_pcb", "import_part", "add_symbol_art", "symbol_prims", "set_models", "add_sim_model", "selftest_script_error", "install", // licence / account "license", "license_status", "ensure_licensed", "setup_trial", "signin", "signin_status", "connect_workspace",@@ -148,6 +148,13 @@ fn describe() -> Value { verb_doc("set_models", "Replace every footprint model on a SchLib component with ONE PCBLIB model (set_params footprint and add_models APPEND, which is how a symbol ends up with two).", json!({"libraryPath": "path (.SchLib)", "symbolName": "string", "footprint": "string (PcbLib footprint name)"}), json!({"removed": "int: the footprint (PCBLIB) models replaced", "kept": "[model type]: the other models left as they were (SIM, STRESS, PCB3D, ...)", "footprint": "string"}), 60, "altium_save the SchLib afterwards. Only footprint models are replaced: a simulation or signal-integrity model stays.", &["symbol_prims", "set_params", "add_models"], &["Before 0.2.114 it removed every model, simulation models included (#42)."], json!({})),+ verb_doc("add_sim_model", "Put a SPICE model (.MODEL or .SUBCKT from a .mdl/.lib/.ckt file) on a SchLib symbol, as Altium's Sim Model dialog does, so the placed part simulates in Altium and the model goes into an IntLib. Diodes, BJTs, MOSFETs, JFETs and subcircuits.",+ json!({"libraryPath": "path to the .SchLib (required)", "symbolName": "the symbol (required)", "modelPath": "the SPICE file on this machine (required): a vendor .lib/.mdl is read and a clean copy written beside the library", "modelName": "which model, when the file holds several", "pinMap": "{symbolPin: modelNode} optional, nodes from 1: SPICE's order is anode-cathode (diode), collector-base-emitter (BJT), drain-gate-source-body (FET). Without it, pins named for their role (A/K, C/B/E, D/G/S/B) go to that node, else the pins in number order", "replace": "bool, default true: remove the symbol's other SIM models first", "dryRun": "bool: answer the plan (model, file, pin map, netlist) and change nothing"}),+ json!({"model": "{name, kind, nodes}", "file": "the clean model file written beside the library", "altium": "{description, kind, subKind, spicePrefix, netlist}", "pinMap": "{symbolPin: modelNode}", "replaced": "int: SIM models removed", "models": "[model type] on the symbol now", "saved": "false"}), 60,+ "Then altium_save the library. A placed part keeps the model (altium_sch_place_part places through Altium's own library placement), altium_simulate runs it, and altium_compile_intlib packs the model file into the IntLib.",+ &["set_models", "sch_place_part", "simulate", "export_spice", "compile_intlib", "read_symbol"],+ &["An encrypted model ($CDNENCSTART, as many PSpice packages are) is refused: only PSpice runs it.", "A vendor file's uncommented title line is dropped from the clean copy (SPICE reads a first line as a title).", "Passive models (R, C, L, switches) are not attached by this verb.", "A MOSFET symbol with three pins ties the body to the source."],+ json!({"libraryPath": "C:/lib/Diodes.SchLib", "symbolName": "1N4148WS", "modelPath": "C:/vendor/1N4148WS.lib"})), verb_doc("add_symbol_art", "Draw the chip-outline artwork (the chip-thumbnailer polylines adom-symbol baked into the KiCad symbol) into a SchLib component, fitted to its body rectangle, so the Altium symbol shows the same chip as KiCad and Fusion.", json!({"libraryPath": "path (.SchLib)", "symbolName": "string (LibReference)", "kicadSym": "Windows path to the .kicad_sym that carries the baked outline (stage it with send_files)", "clear": "bool, default true: remove the component's existing polylines/lines first", "mode": "lines (default) | polyline"}), json!({"polylines": "int", "points": "int", "bodyRectMil": "[x0,y0,x1,y1]"}), 180,@@ -2385,6 +2392,7 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "install" => crate::install::install(args), "symbol_prims" => library::symbol_prims(args), "set_models" => library::set_models(args),+ "add_sim_model" => crate::simmodel::add_sim_model(args), "place_on_pcb" => library::place_on_pcb(args), "import_part" => library::import_part(args), // ---- licence / account ----
dev-skills/altium-bridge-test/run_verb_tests.py+3@@ -142,6 +142,9 @@ def matrix(w): M["set_params"] = dict(phase=2, **ok(libraryPath=SL, symbolName="TST_SOIC8", params={"BatteryParam": "1"})) M["set_visibility"] = dict(phase=2, **anyo("param visibility", libraryPath=SL, symbolName="TST_SOIC8", param="BatteryParam", visible=False)) M["set_models"] = dict(phase=2, **ok(libraryPath=SL, symbolName="TST_QFN24", footprint="TST_QFN24"))+ # 0.2.115 (#42): a SPICE model from Altium's own simulation example (copied to D/sim by the setup) on a symbol+ M["add_sim_model"] = dict(phase=2, **ok(libraryPath=SL, symbolName="TST_QFN24", modelPath=D + "/sim/LIB PSPICE/BC846AL NPN.MDL"),+ check=lambda d: "SIM" in (d.get("models") or []) and (d.get("model") or {}).get("kind") == "NPN") M["add_models"] = dict(phase=2, **anyo("adds a footprint model row", libraryPath=SL, symbolName="TST_SOIC8", models=[{"type": "PCBLIB", "name": "TST_SOIC8"}])) # 0.2.66: pins as objects (they used to arrive as one garbage pin and still pass), a dual op-amp with the shared # power pins hidden on their nets; every pin and both parts must arrive
package.json+1−1@@ -1,6 +1,6 @@ { "slug": "altium-bridge",- "version": "0.2.114",+ "version": "0.2.115", "type": "app", "description": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.", "tags": [
page.json+2−2@@ -4,7 +4,7 @@ "type": "app", "title": "Altium Bridge: AI for Altium Designer", "brief": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",- "version": "0.2.114",+ "version": "0.2.115", "hero": { "type": "image", "path": "screenshots/hero.png"@@ -159,4 +159,4 @@ "tools/symbol_modes.py", "uninstall.sh" ]-}+}
skills/altium-schematic-edit/SKILL.md+17−11@@ -243,18 +243,24 @@ altium_export_spice '{"schematic":"C:/proj/Amp.SchDoc","outputPath":"C:/proj/Amp `simulation_failed` (usually a part without a simulation model; Altium's Messages name it), `no_project` (the sheet must belong to a `.PrjPcb` beside it), `not_supported` for raw SPICE analyses. -### A SPICE model on a library symbol (no verb yet; measured by a user on AD 26, #42)+### A SPICE model on a library symbol: `altium_add_sim_model` (0.2.115, #42) -- **A scripted SIM implementation is not enough for an IntLib.** `AddSchImplementation` with ModelType `SIM`, a model- name and `AddDataFileLink(name, file.mdl, 'MDL')` saves, and a placed part simulates, but the IntLib compiler does- not pack it (no `MDL/` stream, no SIM entry in `LibCrossRef.Txt`).-- **Altium's Sim Model dialog writes the form that packs**: `ModelDatafile0=<full path>.mdl`, `ModelDatafileKind0=mdl`- (lower case), parameters on the implementation (`Kind`, `SubKind`, `Spice Prefix`, `Netlist` template, `Syntax`,- `Source=Local`, and every `.MODEL` parameter as its own parameter), plus a separate `STRESS` implementation. Add the- model through the dialog when it must reach an IntLib.-- Vendor SPICE files often have an uncommented title line before `.MODEL`: strip it to a clean `.mdl`, and add the- `.mdl` to the LibPkg as a document.-- SPICE diode nodes are anode, cathode: with the cathode on pin 1, map symbol pin 1 to model node 2 and pin 2 to node 1.+```+altium_add_sim_model '{"libraryPath":"C:/lib/Diodes.SchLib","symbolName":"1N4148WS","modelPath":"C:/vendor/1N4148WS.lib"}'+```++- Reads the `.MODEL` or `.SUBCKT` (diodes, BJTs, MOSFETs, JFETs, subcircuits), writes a clean copy beside the library+ (a vendor's uncommented title line dropped: SPICE reads a first line as a title) and puts it on the symbol in the+ form Altium's Sim Model dialog writes. The placed part simulates (`altium_simulate`, `altium_export_spice`) and+ `altium_compile_intlib` packs the model (`MDL/0.mdl`, a SIM row in `LibCrossRef.Txt`). `dryRun` shows the plan.+- **Pins**: SPICE node order is anode-cathode (diode), collector-base-emitter (BJT), drain-gate-source-body (FET). Pins+ named for their role (A/K, C/B/E, D/G/S/B) go to that node whatever their numbers; otherwise give `pinMap`+ (`{"1": 2, "2": 1}`: symbol pin to model node). A diode with its cathode on pin 1 maps 1 to node 2.+- An encrypted model (`$CDNENCSTART`, as many PSpice packages carry, TI's "unencrypted" ones too) is refused: only+ PSpice runs it.+- What made the difference (measured on AD 26.11): the model file linked by its full path with kind `mdl` in lower+ case, no component-library use and no locked data links, and Kind, SubKind, Spice Prefix and Netlist on the model. A+ link written with kind `MDL` saved and simulated but did not reach the IntLib. The `.mdl` need not be in the LibPkg. - `altium_set_models` replaces only footprint models (0.2.114): a SIM or STRESS model stays. - A simulation run opens its own window with a second Altium taskbar icon; it is not a second Altium.
src/BRIDGE_VERSION+1−1@@ -1 +1 @@-0.2.114+0.2.115
src/agent/AdomAgent.pas.tmpl+113@@ -11651,6 +11651,117 @@ Begin End; +{ lib_symbol_pins: libref= -> a SchLib symbol's pins as [designator, name] (altium_add_sim_model maps them onto a+ SPICE model's nodes). }+Function CmdLibSymbolPins(Lines : TStringList) : String;+Var+ SLib : ISch_Lib;+ C : ISch_Component;+ It : ISch_Iterator;+ Pin : ISch_Pin;+ S : String;+Begin+ SLib := SchServer.GetCurrentSchDocument;+ If (SLib = Nil) Or (SLib.ObjectID <> eSchLib) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','the current document is not a schematic library') + '}'; Exit; End;+ C := LibCmpOf(SLib, Param(Lines, 'libref'));+ If C = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no symbol ' + Param(Lines, 'libref')) + '}'; Exit; End;+ S := '';+ It := C.SchIterator_Create;+ It.AddFilter_ObjectSet(MkSet(ePin));+ Pin := It.FirstSchObject;+ While Pin <> Nil Do+ Begin+ { one row per pin number: a multi-part symbol draws a shared pin once per part }+ If Pos('["' + JsonEsc(Pin.Designator) + '",', S) = 0 Then+ Begin+ If S <> '' Then S := S + ',';+ S := S + '["' + JsonEsc(Pin.Designator) + '","' + JsonEsc(Pin.Name) + '"]';+ End;+ Pin := It.NextSchObject;+ End;+ C.SchIterator_Destroy(It);+ Result := '{' + JRaw('ok','true') + ',' + JStr('libref', C.LibReference) + ',' + JRaw('pins', '[' + S + ']') + '}';+End;++{ A hidden parameter on a model (Kind, SubKind, Spice Prefix, Netlist), as Altium's Sim Model dialog keeps them. }+Procedure AddImplParam(Impl : ISch_Implementation; N, V : String);+Var+ P : ISch_Parameter;+Begin+ P := SchServer.SchObjectFactory(eParameter, eCreate_Default);+ P.Name := N;+ P.Text := V;+ P.IsHidden := True;+ Impl.AddSchObject(P);+End;++{ add_sim (#42): a SPICE model on a SchLib symbol in the form the Sim Model dialog writes, which a placed part simulates+ with and the IntLib compiler packs (MDL/0.mdl and a SIM row in LibCrossRef.Txt, measured on AD 26.11, 2026-12-01):+ the model file linked by its full path with kind mdl (lower case: a user's MDL did not pack), no component-library use+ and no locked data links, the Kind/SubKind/Spice Prefix/Netlist parameters on the model, the pin map as+ (symbolPin:modelNode). replace=1 removes the symbol's SIM models first. }+Function CmdAddSim(Lines : TStringList) : String;+Var+ SLib : ISch_Lib;+ C : ISch_Component;+ It : ISch_Iterator;+ Impl : ISch_Implementation;+ Found : Boolean;+ Replaced : Integer;+Begin+ SLib := SchServer.GetCurrentSchDocument;+ If (SLib = Nil) Or (SLib.ObjectID <> eSchLib) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','the current document is not a schematic library') + '}'; Exit; End;+ C := LibCmpOf(SLib, Param(Lines, 'libref'));+ If C = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','symbol_not_found') + ',' + JStr('error','no symbol ' + Param(Lines, 'libref')) + '}'; Exit; End;+ Replaced := 0;+ If Param(Lines, 'replace') = '1' Then+ Begin+ While Replaced < 32 Do+ Begin+ Found := False;+ It := C.SchIterator_Create;+ It.AddFilter_ObjectSet(MkSet(eImplementation));+ Impl := It.FirstSchObject;+ While Impl <> Nil Do+ Begin+ If UpperCase(Impl.ModelType) = 'SIM' Then Begin Found := True; Break; End;+ Impl := It.NextSchObject;+ End;+ C.SchIterator_Destroy(It);+ If Not Found Then Break;+ C.RemoveSchImplementation(Impl);+ Replaced := Replaced + 1;+ End;+ End;+ { the new model is the current SIM model: any other one the symbol keeps stops being current }+ It := C.SchIterator_Create;+ It.AddFilter_ObjectSet(MkSet(eImplementation));+ Impl := It.FirstSchObject;+ While Impl <> Nil Do+ Begin+ If UpperCase(Impl.ModelType) = 'SIM' Then Impl.IsCurrent := False;+ Impl := It.NextSchObject;+ End;+ C.SchIterator_Destroy(It);+ Impl := C.AddSchImplementation;+ Impl.ModelType := 'SIM';+ Impl.ModelName := Param(Lines, 'name');+ Impl.Description := Param(Lines, 'desc');+ Impl.ClearAllDatafileLinks;+ Impl.AddDataFileLink(Param(Lines, 'name'), Param(Lines, 'file'), LowerCase(Param(Lines, 'fkind')));+ Try Impl.UseComponentLibrary := False; Except End;+ Try Impl.DatalinksLocked := False; Except End;+ Impl.MapAsString := Param(Lines, 'map');+ AddImplParam(Impl, 'Kind', Param(Lines, 'kind'));+ AddImplParam(Impl, 'SubKind', Param(Lines, 'subkind'));+ AddImplParam(Impl, 'Spice Prefix', Param(Lines, 'prefix'));+ AddImplParam(Impl, 'Netlist', Param(Lines, 'netlist'));+ Impl.IsCurrent := True;+ SLib.GraphicallyInvalidate;+ Result := '{' + JRaw('ok','true') + ',' + JStr('libref', C.LibReference) + ',' + JRaw('replaced', IntToStr(Replaced)) + ',' ++ JStr('map', Impl.MapAsString) + ',' + JRaw('models', ImplTypesJson(C)) + '}';+End;+ Function Dispatch(Cmd : String; Lines : TStringList; Payload : String) : String; Begin If Cmd = 'ping' Then Result := CmdPing(Lines)@@ -11689,6 +11800,8 @@ Begin Else If Cmd = 'selftest_halt' Then Result := CmdSelfTestHalt(Lines) Else If Cmd = 'symbol_prims' Then Result := CmdSymbolPrims(Lines) Else If Cmd = 'set_models' Then Result := CmdSetModels(Lines)+ Else If Cmd = 'lib_symbol_pins' Then Result := CmdLibSymbolPins(Lines)+ Else If Cmd = 'add_sim' Then Result := CmdAddSim(Lines) Else If Cmd = 'place_on_pcb' Then Result := CmdPlaceOnPcb(Lines) Else If Cmd = 'pcb_report' Then Result := CmdPcbReport(Lines) Else If Cmd = 'list_designators' Then Result := CmdListDesignators(Lines)
src/bridge.json+2−1@@ -2,7 +2,7 @@ "manifest_version": 1, "name": "altium", "displayName": "Altium Designer",- "version": "0.2.114",+ "version": "0.2.115", "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.", "homepage": "https://wiki.adom.inc/adom/altium-bridge", "docs": "https://wiki.adom.inc/adom/altium-bridge",@@ -267,6 +267,7 @@ "altium_set_layer_count", "altium_set_layer_visibility", "altium_set_models",+ "altium_add_sim_model", "altium_set_outline", "altium_set_params", "altium_set_track_width",