← Commit history

0.2.81: altium_simulate and altium_export_spice on Altium's mixed-signal simulator (EDA Bridge Standard #23); batteries on the final build: Develop 256/0/1, AD26 256/0/1

Colby Knox ·232980e14a · ·parent affacf6
13 files changed +654−15
CHANGELOG.md+11
@@ -1,5 +1,16 @@ # Changelog +## 0.2.81++- **`altium_simulate` and `altium_export_spice`: Altium's mixed-signal simulator, no clicks** (EDA Bridge Standard #23,+  the two verbs proposed there). The analysis (`op`, `dc`, `ac`, `tran`) is written into the project's `.simcfg` for the+  sheet, with the probes as the signals the run keeps; the sheet runs as Altium's "Mixed Sim" output, and the results+  file (`.sdf`: text headers, then each signal's points as doubles) is read into the standard's `signals`, AC as dB with+  unwrapped phase. On Altium's "Simulation Quick Start" amplifier the operating point and all 71 AC points agree with+  ngspice to 0.0001 dB and 0.000 degrees. `export_spice` returns the `.nsx` SPICE netlist Altium writes for the run.+  Runs about 4 s. Unsaved documents of the project refuse it (it is closed and reopened to write the analysis); an+  earlier run's unsaved results document is closed without saving, since every run makes its own. 257 verbs.+ ## 0.2.80  Every verb of the EDA Bridge Standard: 236 of 236, 255 verbs in all. The standard's shared engine is adom-eda-checks
README.md+6−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 -255 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+257 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. 255 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 257 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 255 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 257 `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 255 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 257 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -249,6 +249,8 @@ All 255 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_place_decoupling`: Put an IC's decoupling caps beside the power pins they serve: each cap just outside the IC, power pad facing its pin, lined up with it, sliding along the side when the spot is taken (the standard's shared planner). - `altium_plan_fanout`: Plan a BGA's or a QFN/QFP's escape (the standard's shared planner): the outer ring on the surface and a dogbone via (or via in pad) for each inner ball, an outward stub per perimeter pad (with a via for ground or viaPerimeter), a via grid in an exposed pad. - `altium_estimate_cost`: The numbers a fab quote needs (size, copper layers, thickness, smallest track, gap and drill, holes, parts and joints) from the board, and a rough price table at the quantities asked when you pass a price record read from the fab's own page (the standard's shared estimator; it has no rates of its own).+- `altium_simulate`: Run a circuit simulation of a schematic sheet in Altium's mixed-signal simulator (Advanced Sim) and return the signals as data: an operating point, a DC sweep, an AC sweep or a transient, as the standard's simulate gives them.+- `altium_export_spice`: The schematic's SPICE netlist from Altium's mixed-signal simulator (the .nsx its Mixed Sim output writes): elements, analyses, models. - `altium_export_library_part`: Export one library part into its own small library files: a symbol library with only its symbol, a footprint library with only its footprint, and its 3D model file. - `altium_create_part_project`: Generate a small real project (schematic and board) around one library part, so the part can be shown and tested in every view: schematic, 2D board and 3D board. - `altium_library_views`: Pictures of library parts for review, each as an image file: the schematic symbol, the footprint (pads and layers), the 3D body seated on the footprint, and the device view that maps symbol pins to pads.
SKILL.md+1
@@ -25,6 +25,7 @@ Say **altium** to reach this bridge. Every verb returns `success`, a stable `err | Add a part / wire pins / change values / delete | `altium_sch_place_part`, `altium_sch_connect`, `altium_sch_edit`, `altium_sheet_params` (**altium-schematic-edit**) | | Replace a part with another library part, keeping its wiring | `altium_sch_swap_part` (**altium-schematic-edit**) | | Hierarchical sheets: a sheet symbol, its entries, the child's ports | `altium_sch_sheet_symbol`, `altium_sch_connect {kind:"port"}` (**altium-schematic-edit**) |+| Simulate a sheet (op, DC, AC, transient) / its SPICE netlist | `altium_simulate`, `altium_export_spice` (**altium-schematic-edit**) | | The compiled netlist, or check it against the nets you meant | `altium_netlist {projectPath, net?, expect?}` (**altium-schematic-edit**) | | Number `?` designators, set the title block | `altium_annotate`, `altium_doc_params` (**altium-schematic-edit**) | | Push schematic changes to the board | `altium_update_pcb` (previews; `execute:true` runs the change order) (**altium-schematic-edit**) |
bridge-rs/src/main.rs+2−1
@@ -53,6 +53,7 @@ mod route; mod routing; mod shot; mod silkplace;+mod sim; mod support; mod surfaces; mod taskbar;@@ -67,7 +68,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.80";+pub const BRIDGE_VERSION: &str = "0.2.81";  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/sim.rsadded+496
@@ -0,0 +1,496 @@+//! simulate and export_spice (EDA Bridge Standard #23) on Altium's mixed-signal simulator. The analyses live in the+//! project's .simcfg (one `Name=Value|...` string per sheet, `Affect=Document`); the run is Altium's "Mixed Sim" output+//! (WorkspaceManager:GenerateReport ObjectKind=Simulator|Index=1|Action=Run), which writes <project>.nsx (a SPICE+//! netlist) and then simulates; the results are the .sdf it saves: text headers per wave, then the points as doubles.+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use std::time::Duration;++/// One signal of a results file: its chart (the analysis), name, unit, sweep step, and points. A complex wave (AC)+/// keeps its imaginary parts in `yi`.+#[derive(Debug, Clone)]+pub struct Wave { pub chart: String, pub name: String, pub suffix: String, pub unit: String, pub hint: String, pub independent: bool,+                  pub x: Vec<f64>, pub y: Vec<f64>, pub yi: Option<Vec<f64>> }++fn le_f64(b: &[u8], at: usize) -> f64 { f64::from_le_bytes(b[at..at + 8].try_into().unwrap()) }++/// Altium's .sdf ("SDF: 1.0"): chart setups as text, then, after `#ChartSetupsEnd`, `Chart: <name>` lines, each+/// followed by its waves. A wave is text header lines (`Wave:`, `WaveYUnitStr:`, `WaveHint:`, `WavePoints:`,+/// `WaveIsXComplex:`, `WaveIsYComplex:`, ...) up to `WaveExtendedDataStart`, then n points as little-endian doubles+/// (x then y, each two doubles, real and imaginary, when complex) and a newline, then `WaveDataStart` and the same+/// points as 4-byte floats. Read in order, so the binary data is never searched for text. Pure.+pub fn parse_sdf(b: &[u8]) -> Result<Vec<Wave>, String> {+    if !b.starts_with(b"SDF:") { return Err("not an Altium simulation data file (no SDF header)".into()); }+    let end = b.windows(16).position(|w| w == b"#ChartSetupsEnd\n").ok_or("no #ChartSetupsEnd")? + 16;+    let mut at = end;+    let line = |at: usize| -> (String, usize) {+        let e = b[at..].iter().position(|c| *c == b'\n').map(|p| at + p).unwrap_or(b.len());+        (String::from_utf8_lossy(&b[at..e]).trim_end_matches('\r').to_string(), (e + 1).min(b.len()))+    };+    let mut chart = String::new();+    let mut out = Vec::new();+    while at < b.len() {+        let (l, next) = line(at);+        if let Some(c) = l.strip_prefix("Chart: ") { chart = c.trim().to_string(); at = next; continue; }+        let Some(name) = l.strip_prefix("Wave: ") else { at = next; continue };+        let mut w = Wave { chart: chart.clone(), name: name.trim().to_string(), suffix: String::new(), unit: String::new(), hint: String::new(),+                           independent: false, x: vec![], y: vec![], yi: None };+        let (mut n, mut xc, mut yc) = (0usize, false, false);+        at = next;+        loop {+            if at >= b.len() { return Err(format!("{}: the header runs off the end of the file", w.name)); }+            let (h, nx) = line(at);+            at = nx;+            if h == "WaveExtendedDataStart" { break; }+            let (k, v) = h.split_once(':').map(|(k, v)| (k.trim(), v.trim())).unwrap_or((h.as_str(), ""));+            match k {+                "WavePoints" => n = v.parse().map_err(|_| format!("{}: WavePoints {v:?}", w.name))?,+                "WaveIsXComplex" => xc = v.eq_ignore_ascii_case("TRUE"),+                "WaveIsYComplex" => yc = v.eq_ignore_ascii_case("TRUE"),+                "WaveYUnitStr" => w.unit = v.to_string(),+                "WaveHint" => w.hint = v.to_string(),+                "WaveSuffix" => w.suffix = v.to_string(),+                "WaveIndependent" => w.independent = v.eq_ignore_ascii_case("TRUE"),+                _ => {}+            }+        }+        let (sx, sy) = (if xc { 16 } else { 8 }, if yc { 16 } else { 8 });+        let need = n * (sx + sy);+        if at + need > b.len() { return Err(format!("{}: {n} points run off the end of the file", w.name)); }+        let mut yi = Vec::new();+        for i in 0..n {+            let p = at + i * (sx + sy);+            w.x.push(le_f64(b, p));+            w.y.push(le_f64(b, p + sx));+            if yc { yi.push(le_f64(b, p + sx + 8)); }+        }+        if yc { w.yi = Some(yi); }+        // the doubles, a newline, `WaveDataStart`, the same points as floats, a newline+        at += need;+        if b.get(at) == Some(&b'\n') { at += 1; }+        let (ds, nx) = line(at);+        if ds != "WaveDataStart" { return Err(format!("{}: expected WaveDataStart after its {n} points, found {:?}", w.name, &ds[..ds.len().min(40)])); }+        at = (nx + n * (sx + sy) / 2).min(b.len());+        if b.get(at) == Some(&b'\n') { at += 1; }+        out.push(w);+    }+    Ok(out)+}++/// The chart an analysis lands in.+fn chart_of(kind: &str) -> &'static str {+    match kind { "op" => "Operating Point", "dc" => "DC Sweep", "tran" => "Transient Analysis", "ac" => "AC Analysis", _ => "" }+}++/// A number as plain decimal text: Altium's config and SPICE both read it, where a suffix like M is milli to one and+/// mega to the other. Pure.+fn num_text(v: f64) -> String {+    let s = format!("{v}");+    if s.contains('e') { format!("{v:.15}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s }+}++/// The config keys for an analysis (the standard's `analysis`), or the refusal. Every other analysis is switched off,+/// sweeps and Monte Carlo too, so the run is exactly the one asked for. Pure.+pub fn analysis_keys(a: &Value, probes: &[String]) -> Result<(String, Vec<(String, String)>, Vec<String>), Value> {+    let bad = |m: &str| json!({"success": false, "errorCode": "bad_args", "error": m});+    let t = a["type"].as_str().unwrap_or("").to_ascii_lowercase();+    let n = |k: &str| a.get(k).and_then(|v| v.as_f64());+    let mut kv: Vec<(String, String)> = ["OP_Analysis", "DC_Analysis", "AC_Analysis", "TRAN_Analysis", "ParamSweep_Analysis", "MonteCarlo_Analysis",+        "TempSweep_Analysis", "Noise_Analysis", "PZ_Analysis", "TF_Analysis", "TRAN_FourierAnalysis"].iter().map(|k| (k.to_string(), "False".into())).collect();+    let mut set = |k: &str, v: String| {+        kv.retain(|(a, _)| a != k);+        kv.push((k.into(), v.clone()));+        if !k.ends_with("_Analysis") && !k.contains("Sweep") && !k.ends_with("Source") { kv.push((format!("{k}_UserValue"), v)); }+    };+    match t.as_str() {+        "op" => set("OP_Analysis", "True".into()),+        "dc" => {+            let (Some(src), Some(s), Some(e), Some(st)) = (a["source"].as_str(), n("start"), n("stop"), n("step")) else { return Err(bad("a dc analysis is {type: \"dc\", source: \"V1\", start, stop, step}")) };+            set("DC_Analysis", "True".into());+            set("DC_PrimarySource", src.into());+            set("DC_PrimaryStart", num_text(s)); set("DC_PrimaryStop", num_text(e)); set("DC_PrimaryStep", num_text(st));+            set("DC_EnableSecondary", "False".into());+        }+        "ac" => {+            let (Some(s), Some(e)) = (n("start"), n("stop")) else { return Err(bad("an ac analysis is {type: \"ac\", sweep: \"dec\"|\"oct\"|\"lin\", points, start, stop} (Hz)")) };+            let sweep = a["sweep"].as_str().unwrap_or("dec").to_ascii_uppercase();+            if !["DEC", "OCT", "LIN"].contains(&sweep.as_str()) { return Err(bad("sweep is dec, oct or lin")); }+            set("AC_Analysis", "True".into());+            set("AC_StartFrequency", num_text(s)); set("AC_StopFrequency", num_text(e));+            set("AC_TestPoints", num_text(n("points").unwrap_or(20.0).round().max(1.0)));+            set("AC_SweepType", sweep);+        }+        "tran" => {+            let (Some(st), Some(e)) = (n("step"), n("stop")) else { return Err(bad("a tran analysis is {type: \"tran\", step, stop, start?} (s)")) };+            set("TRAN_Analysis", "True".into());+            set("TRAN_StartTime", num_text(n("start").unwrap_or(0.0))); set("TRAN_StopTime", num_text(e));+            set("TRAN_StepTime", num_text(st)); set("TRAN_MaxStepTime", num_text(st));+            set("TRAN_AlwaysSetDefaults", "False".into());+        }+        "raw" => return Err(json!({"success": false, "errorCode": "not_supported",+            "error": "Altium simulates the schematic through its own netlister: raw SPICE text is not taken",+            "_hint": "Give the analysis in the structured form (op, dc, ac, tran)."})),+        _ => return Err(bad("analysis.type is op, dc, ac, tran or raw")),+    }+    // a run keeps only the signals its analysis lists (AC_Variable0=dB(v(out)) kept v(out) alone): the probes become+    // that list, in place of the sheet's own. An operating point keeps every node and current anyway+    let mut drop = Vec::new();+    let pre = match t.as_str() { "ac" => "AC", "tran" => "TRAN", "dc" => "DC", _ => "" };+    if !pre.is_empty() && !probes.is_empty() {+        drop = vec![format!("{pre}_Variable"), format!("{pre}_XVariable")];+        for (i, p) in probes.iter().enumerate() {+            for (k, v) in [("VariableEnabled", "True".to_string()), ("XVariable", String::new()), ("Variable", p.clone()), ("VariableName", String::new()),+                           ("VariableUnits", String::new()), ("VariablePlot", "0".into()), ("VariableAxis", "0".into()), ("VariableColor", "8421504".into())] {+                kv.push((format!("{pre}_{k}{i}"), v));+            }+        }+    }+    Ok((t, kv, drop))+}++/// `A=1|B=2` with the keys given set (added when missing). Pure.+pub fn set_config(cfg: &str, kv: &[(String, String)], drop: &[String]) -> String {+    let mut parts: Vec<String> = cfg.split('|').filter(|p| !p.is_empty()).filter(|p| !drop.iter().any(|d| p.starts_with(d.as_str()))).map(String::from).collect();+    for (k, v) in kv {+        let pre = format!("{k}=");+        match parts.iter_mut().find(|p| p.starts_with(&pre)) { Some(p) => *p = format!("{k}={v}"), None => parts.push(format!("{k}={v}")) }+    }+    parts.join("|")+}++fn xml_esc(s: &str) -> String { s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;") }++/// The .simcfg with the analysis written into the project's config and the sheet's own (`<DocumentConfig>` named after+/// the sheet's file, which is the one a run uses). Pure.+pub fn write_simcfg(xml: &str, sheet_name: &str, kv: &[(String, String)], drop: &[String]) -> String {+    let mut out = xml.to_string();+    let edit = |s: &mut String, from: usize| -> bool {+        let Some(a) = s[from..].find("<Config>").map(|p| from + p + 8) else { return false };+        let Some(b) = s[a..].find("</Config>").map(|p| a + p) else { return false };+        let new = set_config(&s[a..b], kv, drop);+        s.replace_range(a..b, &new);+        true+    };+    if let Some(p) = out.find("</Settings>") { edit(&mut out, p); }+    let tag = format!("<Name>{}</Name>", xml_esc(sheet_name));+    if let Some(p) = out.find(&tag) { edit(&mut out, p); }+    out+}++/// A new .simcfg holding only these settings, for a project that has none.+fn new_simcfg(kv: &[(String, String)]) -> String {+    format!("<?xml version=\"1.0\"?>\r\n<ProjectConfig xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n  <Settings>\r\n    <Version>1.1</Version>\r\n    <Affect>Document</Affect>\r\n  </Settings>\r\n  <Config>{}</Config>\r\n</ProjectConfig>\r\n",+        set_config("", kv, &[]))+}++/// Keep at most `max` points, always the first, the last and the extremes of y, the rest evenly spread. Pure.+pub fn decimate(n: usize, y: &[f64], max: usize) -> Vec<usize> {+    if n <= max || max < 3 { return (0..n).collect(); }+    let (mut lo, mut hi) = (0, 0);+    for i in 0..n { if y[i] < y[lo] { lo = i; } if y[i] > y[hi] { hi = i; } }+    let mut keep: Vec<usize> = (0..max - 2).map(|k| k * (n - 1) / (max - 3).max(1)).collect();+    keep.extend([0, n - 1, lo, hi]);+    keep.sort();+    keep.dedup();+    keep+}++/// The degrees of each complex point, unwrapped (no jump of more than 180 between neighbours). Pure.+pub fn phase_unwrapped(re: &[f64], im: &[f64]) -> Vec<f64> {+    let mut out: Vec<f64> = Vec::with_capacity(re.len());+    let mut off = 0.0;+    for i in 0..re.len() {+        let p = im[i].atan2(re[i]).to_degrees();+        if let Some(prev) = out.last() { let d = p + off - prev; if d > 180.0 { off -= 360.0; } else if d < -180.0 { off += 360.0; } }+        out.push(p + off);+    }+    out+}++fn r6(v: f64) -> f64 { if v == 0.0 || !v.is_finite() { return v; } let m = 10f64.powi(5 - v.abs().log10().floor() as i32); (v * m).round() / m }++/// The standard's signals from the waves of one run: AC magnitude in dB with phase beside it, `points` a ceiling.+pub fn signals(waves: &[Wave], kind: Option<&str>, probes: &[String], points: usize) -> (Vec<Value>, Vec<String>, Vec<String>) {+    let want_chart = kind.map(chart_of).unwrap_or("");+    let swept = waves.iter().any(|w| !w.suffix.is_empty() && w.suffix != "_p1");+    let base = |w: &Wave| -> String { if !swept && !w.suffix.is_empty() { w.name.trim_end_matches(&w.suffix).to_string() } else { w.name.clone() } };+    let ws: Vec<&Wave> = waves.iter().filter(|w| !w.independent && (want_chart.is_empty() || w.chart == want_chart)).collect();+    let available: Vec<String> = ws.iter().map(|w| base(w)).collect();+    // a probe names the signal without the run's suffix (v(out), not v(out)_p3): every step of a sweep answers it+    let is = |p: &String, w: &Wave| p.eq_ignore_ascii_case(&base(w)) || p.eq_ignore_ascii_case(w.name.trim_end_matches(&w.suffix));+    let picked: Vec<&Wave> = if probes.is_empty() { ws.iter().take(100).cloned().collect() } else { ws.iter().filter(|w| probes.iter().any(|p| is(p, w))).cloned().collect() };+    let missing: Vec<String> = probes.iter().filter(|p| !ws.iter().any(|w| is(p, w))).cloned().collect();+    let out = picked.iter().map(|w| {+        let x_unit = match w.chart.as_str() { "AC Analysis" => "Hz", "Transient Analysis" => "s", "DC Sweep" => "V", _ => "" };+        let mut s = json!({"signal": base(w), "analysis": w.chart, "xUnit": x_unit});+        if !w.hint.is_empty() && swept { s["step"] = json!(w.hint); }+        match &w.yi {+            Some(im) => {+                let mag: Vec<f64> = w.y.iter().zip(im).map(|(r, i)| 20.0 * r.hypot(*i).max(1e-300).log10()).collect();+                let ph = phase_unwrapped(&w.y, im);+                let k = decimate(w.x.len(), &mag, points);+                s["x"] = json!(k.iter().map(|i| r6(w.x[*i])).collect::<Vec<_>>());+                s["y"] = json!(k.iter().map(|i| r6(mag[*i])).collect::<Vec<_>>());+                s["phase"] = json!(k.iter().map(|i| r6(ph[*i])).collect::<Vec<_>>());+                s["yUnit"] = json!("dB");+            }+            None => {+                let k = decimate(w.x.len(), &w.y, points);+                s["x"] = json!(k.iter().map(|i| r6(w.x[*i])).collect::<Vec<_>>());+                s["y"] = json!(k.iter().map(|i| r6(w.y[*i])).collect::<Vec<_>>());+                s["yUnit"] = json!(w.unit);+            }+        }+        s+    }).collect();+    (out, missing, available)+}++/// A probe as Altium names its wave: {net: OUT} is v(out), {current: V1} is i(v1), {signal} as given.+fn probe_name(p: &Value) -> Option<String> {+    if let Some(n) = p["net"].as_str() { return Some(format!("v({})", n.to_ascii_lowercase())); }+    if let Some(c) = p["current"].as_str() { return Some(format!("i({})", c.to_ascii_lowercase())); }+    p["signal"].as_str().or(p.as_str()).map(String::from)+}++/// The sheet and the project it belongs to (a .PrjPcb beside it that lists it, else the only one there).+fn sheet_and_project(args: &Value) -> Result<(PathBuf, PathBuf), Value> {+    let bad = |c: &str, m: String| json!({"success": false, "errorCode": c, "error": m});+    let Some(p) = crate::support::s(args, "schematic").or_else(|| crate::support::s(args, "filePath")) else {+        return Err(bad("bad_args", "schematic is the .SchDoc to simulate (filePath works too)".into()));+    };+    let sheet = PathBuf::from(p.replace('/', "\\"));+    if !sheet.extension().map(|e| e.eq_ignore_ascii_case("SchDoc")).unwrap_or(false) { return Err(bad("bad_args", format!("{}: give the .SchDoc sheet to simulate", sheet.display()))); }+    if !sheet.exists() { return Err(bad("file_not_found", format!("{} does not exist", sheet.display()))); }+    let dir = sheet.parent().unwrap_or(Path::new(".")).to_path_buf();+    let name = sheet.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+    let prjs: Vec<PathBuf> = std::fs::read_dir(&dir).map(|r| r.filter_map(|e| e.ok()).map(|e| e.path())+        .filter(|p| p.extension().map(|e| e.eq_ignore_ascii_case("PrjPcb")).unwrap_or(false)).collect()).unwrap_or_default();+    let lists = |p: &PathBuf| std::fs::read_to_string(p).map(|t| t.to_lowercase().contains(&name.to_lowercase())).unwrap_or(false);+    match prjs.iter().find(|p| lists(p)).or(if prjs.len() == 1 { prjs.first() } else { None }) {+        Some(p) => Ok((sheet, p.clone())),+        None => Err(json!({"success": false, "errorCode": "no_project", "error": format!("no .PrjPcb beside {} lists it", sheet.display()),+            "_hint": "Altium simulates a sheet of a project: put the sheet in a project (altium_project_create) and pass the sheet."})),+    }+}++fn newest(dir: &Path, ext: &str, since: std::time::SystemTime) -> Option<PathBuf> {+    let mut best: Option<(std::time::SystemTime, PathBuf)> = None;+    let mut stack = vec![dir.to_path_buf()];+    while let Some(d) = stack.pop() {+        for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {+            let p = e.path();+            if p.is_dir() { stack.push(p); continue; }+            if !p.extension().map(|x| x.eq_ignore_ascii_case(ext)).unwrap_or(false) { continue; }+            let Ok(m) = e.metadata().and_then(|m| m.modified()) else { continue };+            if m >= since && best.as_ref().map(|b| m > b.0).unwrap_or(true) { best = Some((m, p)); }+        }+    }+    best.map(|b| b.1)+}++/// Write the analysis into the project's .simcfg with the project closed (an edit made while it is open is not read:+/// Altium keeps its own copy), then reopen it. Refuses over unsaved documents of that project.+fn configure(sheet: &Path, prj: &Path, analysis: &Value, probes: &[String]) -> Result<String, Value> {+    let (kind, kv, drop) = analysis_keys(analysis, probes)?;+    let dir = prj.parent().unwrap_or(Path::new("."));+    let c = crate::project::close_all_documents(&json!({"under": dir.to_string_lossy()}));+    let mut kept = c["keptOpen"].as_array().cloned().unwrap_or_default();+    // an earlier run's results (an unsaved .sdf) are made again by the next run: close them unsaved. Anything else+    // unsaved is somebody's work+    let is_results = |k: &Value| k["name"].as_str().or(k.as_str()).map(|n| n.to_ascii_lowercase().ends_with(".sdf")).unwrap_or(false);+    if !kept.is_empty() && kept.iter().all(is_results) {+        let c2 = crate::project::close_all_documents(&json!({"under": dir.to_string_lossy(), "includeScratch": true, "discardUnsaved": true}));+        kept = c2["keptOpen"].as_array().cloned().unwrap_or_default();+    }+    if !kept.is_empty() {+        return Err(json!({"success": false, "errorCode": "unsaved_changes", "error": "documents of this project have unsaved changes, so it was not closed to write the analysis",+            "documents": kept, "_hint": "Save them (altium_save) and call again, or run without analysis to use the one the design carries."}));+    }+    let cfg = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path())+        .find(|p| p.extension().map(|e| e.eq_ignore_ascii_case("simcfg")).unwrap_or(false))+        .unwrap_or_else(|| dir.join("project_sim_config.simcfg"));+    let name = sheet.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+    let text = match std::fs::read(&cfg) {+        Ok(b) => write_simcfg(String::from_utf8_lossy(&b).trim_start_matches('\u{feff}'), &name, &kv, &drop),+        Err(_) => new_simcfg(&kv),+    };+    std::fs::write(&cfg, text).map_err(|e| json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", cfg.display())}))?;+    Ok(kind)+}++/// Open the project, run the sheet, and the .sdf and .nsx it left. The results document comes up after the run command+/// returns, so it is collected between agent calls (Altium works between them), up to `wait`; an error box stops it.+fn run(sheet: &Path, prj: &Path) -> Result<(Option<PathBuf>, Option<PathBuf>, Value), Value> {+    if let Some(e) = crate::support::must_open(&prj.to_string_lossy(), 120) { return Err(e); }+    let t0 = std::time::SystemTime::now() - Duration::from_secs(2);+    let r = crate::agent::call("sim_run", &[("path", sheet.to_string_lossy().to_string())], None, Duration::from_secs(900));+    let d = r.get("data").cloned().unwrap_or(Value::Null);+    if d.get("ok").and_then(|v| v.as_bool()) != Some(true) {+        return Err(json!({"success": false, "errorCode": d.get("errorCode").cloned().unwrap_or(json!("simulation_failed")), "error": d.get("error").cloned().unwrap_or(r.get("error").cloned().unwrap_or(Value::Null)), "agent": r}));+    }+    let start = std::time::Instant::now();+    let mut sdf = None;+    while start.elapsed() < Duration::from_secs(600) {+        let c = crate::agent::call("sim_collect", &[], None, Duration::from_secs(120));+        if let Some(p) = c.get("data").and_then(|v| v["sdf"].as_str()).filter(|s| !s.is_empty()) { sdf = Some(PathBuf::from(p)); break; }+        let boxes = crate::dialogs::scan();+        if !boxes.is_empty() {+            return Err(json!({"success": false, "errorCode": "simulation_failed", "error": "Altium raised a dialog during the run", "dialogs": boxes,+                "_hint": "Read the dialog (altium_check_dialogs): a netlister or simulator error names the part or node it could not handle."}));+        }+        std::thread::sleep(Duration::from_millis(800));+    }+    let dir = prj.parent().unwrap_or(Path::new("."));+    Ok((sdf.filter(|p| p.exists()), newest(dir, "nsx", t0), d))+}++/// What a SPICE netlist holds: element lines, analysis lines, includes. Pure.+pub fn netlist_parts(text: &str) -> (Vec<String>, Vec<String>, Vec<String>) {+    let (mut el, mut an, mut inc) = (vec![], vec![], vec![]);+    for (i, l) in text.lines().enumerate() {+        let t = l.trim();+        if i == 0 || t.is_empty() || t.starts_with('*') || t.starts_with('+') { continue; }+        let up = t.to_ascii_uppercase();+        if [".AC", ".TRAN", ".DC", ".OP", ".NOISE", ".TF", ".PZ", ".FOUR"].iter().any(|k| up == *k || up.starts_with(&format!("{k} "))) { an.push(t.to_string()); }+        else if up.starts_with(".INC") || up.starts_with(".LIB") { inc.push(t.to_string()); }+        else if !t.starts_with('.') && !up.starts_with("SWEEP") { el.push(t.to_string()); }+    }+    (el, an, inc)+}++/// altium_simulate {schematic | filePath, analysis?, probes?, points?}+pub fn simulate(args: &Value) -> Value {+    if let Some(g) = crate::support::need_licensed() { return g; }+    let (sheet, prj) = match sheet_and_project(args) { Ok(x) => x, Err(e) => return e };+    let probes: Vec<String> = args.get("probes").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(probe_name).collect()).unwrap_or_default();+    let kind = match args.get("analysis").filter(|a| !a.is_null()) { Some(a) => match configure(&sheet, &prj, a, &probes) { Ok(k) => Some(k), Err(e) => return e }, None => None };+    let (sdf, nsx, _) = match run(&sheet, &prj) { Ok(x) => x, Err(e) => return e };+    let Some(sdf) = sdf else {+        return json!({"success": false, "errorCode": "simulation_failed", "error": "the run left no results (.sdf): the netlist or the simulation failed",+            "netlist": nsx.map(|p| p.to_string_lossy().to_string()),+            "_hint": "Read Altium's Messages (altium_compile) for the netlister's errors: a part without a simulation model is the usual cause (no_model)."});+    };+    let bytes = match std::fs::read(&sdf) { Ok(b) => b, Err(e) => return json!({"success": false, "errorCode": "simulation_failed", "error": format!("{}: {e}", sdf.display())}) };+    let waves = match parse_sdf(&bytes) { Ok(w) => w, Err(e) => return json!({"success": false, "errorCode": "simulation_failed", "error": format!("{}: {e}", sdf.display())}) };+    let points = args.get("points").and_then(|v| v.as_u64()).unwrap_or(200).max(3) as usize;+    let (sig, missing, available) = signals(&waves, kind.as_deref(), &probes, points);+    if !probes.is_empty() && sig.is_empty() {+        return json!({"success": false, "errorCode": "no_such_probe", "error": format!("none of {probes:?} is in the run"), "available": available});+    }+    json!({"success": true, "signals": sig, "missing": missing, "available": available, "analysis": kind.unwrap_or("as the design carries it".into()),+        "engine": "Altium mixed-signal simulator (Advanced Sim)", "results": sdf.to_string_lossy(), "netlist": nsx.map(|p| p.to_string_lossy().to_string()),+        "_hint": "AC signals are magnitude in dB with phase (degrees, unwrapped) beside them; points is a ceiling (the first, last and extreme points are kept). The full run is in results (Altium's .sdf): open it in Altium to see every wave."})+}++/// altium_export_spice {schematic | filePath, outputPath?}+pub fn export_spice(args: &Value) -> Value {+    if let Some(g) = crate::support::need_licensed() { return g; }+    let (sheet, prj) = match sheet_and_project(args) { Ok(x) => x, Err(e) => return e };+    let (_, nsx, _) = match run(&sheet, &prj) { Ok(x) => x, Err(e) => return e };+    let Some(nsx) = nsx else { return json!({"success": false, "errorCode": "export_failed", "error": "Altium wrote no SPICE netlist (.nsx)", "_hint": "Read Altium's Messages (altium_compile): a part without a simulation model stops the netlister."}) };+    let text = std::fs::read_to_string(&nsx).unwrap_or_default();+    let mut path = nsx.clone();+    if let Some(o) = crate::support::s(args, "outputPath") {+        let o = PathBuf::from(o.replace('/', "\\"));+        if let Some(p) = o.parent() { let _ = std::fs::create_dir_all(p); }+        if let Err(e) = std::fs::copy(&nsx, &o) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", o.display())}); }+        path = o;+    }+    let (elements, analyses, includes) = netlist_parts(&text);+    json!({"success": true, "path": path.to_string_lossy(), "elements": elements, "analyses": analyses, "includes": includes, "format": "SPICE (Altium Advanced Sim, .nsx)",+        "_hint": "Altium's Mixed Sim netlister writes this as part of a run, so the sheet was also simulated (its results are in the project's Simulation folder). Models are inline (.model / .subckt) or in includes."})+}++#[cfg(test)]+mod tests {+    use super::*;++    fn wave_bytes(name: &str, chart: &str, pts: &[(f64, f64, Option<f64>)], unit: &str, suffix: &str) -> Vec<u8> {+        let yc = pts.iter().any(|p| p.2.is_some());+        let mut b = format!("Chart: {chart}\nChartId: X\nWave: {name}\nWaveYUnitStr: {unit}\nWaveHint: C6 = 1e-10\nWavePoints: {}\nWaveIsXComplex: {}\nWaveIsYComplex: {}\nWaveSuffix: {suffix}\nWaveExtendedDataStart\n",+            pts.len(), if yc { "TRUE" } else { "FALSE" }, if yc { "TRUE" } else { "FALSE" }).into_bytes();+        for (x, y, yi) in pts {+            b.extend(x.to_le_bytes());+            if yc { b.extend(0f64.to_le_bytes()); }+            b.extend(y.to_le_bytes());+            if yc { b.extend(yi.unwrap_or(0.0).to_le_bytes()); }+        }+        b.extend(b"\nWaveDataStart\n");+        for (x, y, yi) in pts {+            b.extend((*x as f32).to_le_bytes());+            if yc { b.extend(0f32.to_le_bytes()); }+            b.extend((*y as f32).to_le_bytes());+            if yc { b.extend((yi.unwrap_or(0.0) as f32).to_le_bytes()); }+        }+        b.push(b'\n');+        b+    }++    #[test]+    fn a_results_file_reads_back_as_signals() {+        let mut b = b"SDF: 1.0\nTotalPoints: 3\n#ChartSetupsBegin\nChart: AC Analysis\nWaveName: v(out)\n#ChartSetupsEnd\n".to_vec();+        b.extend(wave_bytes("v(out)_p1", "AC Analysis", &[(10.0, 0.5, Some(-0.5)), (100.0, 0.0, Some(-0.1)), (1000.0, -0.01, Some(-0.01))], "V", "_p1"));+        b.extend(wave_bytes("v(in)_p1", "Transient Analysis", &[(0.0, 0.0, None), (1e-3, 1.0, None)], "V", "_p1"));+        let w = parse_sdf(&b).unwrap();+        assert_eq!(w.len(), 2);+        assert_eq!((w[0].chart.as_str(), w[0].x.len(), w[0].yi.is_some()), ("AC Analysis", 3, true));+        assert_eq!(w[1].y, vec![0.0, 1.0]);+        let (s, missing, avail) = signals(&w, Some("ac"), &["v(out)".into(), "v(nope)".into()], 200);+        assert_eq!(s.len(), 1);+        assert_eq!(s[0]["signal"], "v(out)", "a single run drops the _p1 suffix");+        assert_eq!(missing, vec!["v(nope)".to_string()]);+        assert_eq!(avail, vec!["v(out)".to_string()]);+        // |0.5 - 0.5j| is -3.01 dB at -45 degrees+        assert!((s[0]["y"][0].as_f64().unwrap() + 3.0103).abs() < 1e-3 && (s[0]["phase"][0].as_f64().unwrap() + 45.0).abs() < 1e-6, "{}", s[0]);+        assert_eq!(s[0]["xUnit"], "Hz");+        assert!(parse_sdf(b"not an sdf").is_err());+    }++    /// SDF_FILE=<an Altium .sdf>: read a real results file and print what it holds+    #[test]+    fn a_real_results_file() {+        let Ok(p) = std::env::var("SDF_FILE") else { return };+        let w = parse_sdf(&std::fs::read(p).unwrap()).unwrap();+        let mut charts: Vec<String> = w.iter().map(|x| x.chart.clone()).collect();+        charts.dedup();+        println!("{} waves in {charts:?}", w.len());+        let (s, _, _) = signals(&w, Some("ac"), &["v(out)".into()], 5);+        println!("{}", serde_json::to_string(&s).unwrap());+    }++    #[test]+    fn analyses_become_altiums_settings() {+        let (k, kv, drop) = analysis_keys(&json!({"type": "ac", "sweep": "dec", "points": 20, "start": 10, "stop": 1e6}), &["v(out)".into(), "i(r4)".into()]).unwrap();+        assert_eq!(k, "ac");+        let cfg = set_config("OP_Analysis=True|AC_TestPoints=1000|AC_Variable0=dB(v(in))|AC_VariableEnabled0=True|AC_XVariable0=|Other=x", &kv, &drop);+        assert!(cfg.contains("AC_Variable0=v(out)") && cfg.contains("AC_Variable1=i(r4)") && !cfg.contains("v(in)"), "the probes replace the sheet's own signals: {cfg}");+        assert!(cfg.contains("OP_Analysis=False") && cfg.contains("AC_Analysis=True") && cfg.contains("AC_TestPoints=20") && cfg.contains("AC_StopFrequency=1000000") && cfg.contains("Other=x"), "{cfg}");+        assert!(cfg.contains("ParamSweep_Analysis=False"), "sweeps are switched off");+        assert_eq!(analysis_keys(&json!({"type": "raw", "text": ".op"}), &[]).unwrap_err()["errorCode"], "not_supported");+        assert_eq!(analysis_keys(&json!({"type": "tran", "stop": 1}), &[]).unwrap_err()["errorCode"], "bad_args");+        let xml = "<P><Settings></Settings>\n  <Config>OP_Analysis=True</Config>\n  <Documents><DocumentConfig><Name>a.SchDoc</Name><Config>AC_TestPoints=5</Config></DocumentConfig>\n<DocumentConfig><Name>b.SchDoc</Name><Config>AC_TestPoints=7</Config></DocumentConfig></Documents></P>";+        let out = write_simcfg(xml, "b.SchDoc", &kv, &drop);+        assert!(out.contains("<Name>a.SchDoc</Name><Config>AC_TestPoints=5</Config>"), "another sheet's settings stay: {out}");+        assert!(out.contains("<Name>b.SchDoc</Name><Config>AC_TestPoints=20"), "{out}");+        assert!(out.contains("<Config>OP_Analysis=False"), "the project's own too: {out}");+        assert_eq!(num_text(1e-9), "0.000000001");+    }++    #[test]+    fn decimation_keeps_the_ends_and_extremes() {+        let y: Vec<f64> = (0..1000).map(|i| if i == 537 { 50.0 } else if i == 211 { -50.0 } else { (i as f64).sin() }).collect();+        let k = decimate(1000, &y, 20);+        assert!(k.contains(&0) && k.contains(&999) && k.contains(&537) && k.contains(&211) && k.len() <= 24, "{k:?}");+        assert_eq!(phase_unwrapped(&[1.0, -1.0, -1.0], &[0.0, 0.01, -0.01]).last().map(|p| p.round()), Some(181.0));+    }++    #[test]+    fn a_netlist_splits_into_elements_analyses_and_includes() {+        let t = "Title\n*comment\nRR1 a b 1k\nCC1 b 0 100n\n.AC DEC 20 10 1meg\n.TRAN 1u 1m\n.INCLUDE \"x.lib\"\n.model Q npn\n.CONTROL\nSWEEP DEC C6 1 2 3\n.ENDC\n.END\n";+        let (e, a, i) = netlist_parts(t);+        assert_eq!(e, vec!["RR1 a b 1k", "CC1 b 0 100n"]);+        assert_eq!(a, vec![".AC DEC 20 10 1meg", ".TRAN 1u 1m"]);+        assert_eq!(i, vec![".INCLUDE \"x.lib\""]);+    }+}
bridge-rs/src/verbs.rs+13−1
@@ -22,7 +22,7 @@ pub const KNOWN: &[&str] = &[     "list_nets", "net_connections", "layers", "copper_layers", "read_rules",     "set_layer_visibility", "footprint_primitives", "schematic_data", "layer_stack", "net_classes", "diff_pairs", "board_outline", "set_track_width", "find_space", "selection", "check_orientation", "replicate_layout", "outjob_info", "find_symbol", "part_parameters",     // the live-board lane AI Flow drives-    "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",+    "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "simulate", "export_spice", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",     // surfaces     "show_project", "show_schematic", "show_2d_board", "show_3d_board", "show_library",     "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo",@@ -432,6 +432,16 @@ fn describe() -> Value {             json!({"board": "{widthMm, heightMm, areaMm2, layers, thicknessMm, minTrackMm, minGapMm, minDrillMm, holes, vias, smdParts, thtParts, smdJoints, thtJoints, uniqueParts, assemblySides}", "prices": "[{quantity, ...}] - only with a price record", "source": "{name, url, read} of the record", "notes": "[string]", "rough": "bool", "engine": "string"}), 120,             "No rates are built in, so none can go stale: read the fab's current prices from its page, pass them as prices with the date read, and the reply prices the quantities from them. altium_fab_check compares the same numbers with a fab's limits. altium_jlcpcb_order makes the order files.",             &["fab_check", "jlcpcb_order", "layer_stack", "board_report"], &["A rough estimate only: get a real quote before ordering."], json!({"quantities": [5, 30]})),+        verb_doc("simulate", "Run a circuit simulation of a schematic sheet in Altium's mixed-signal simulator (Advanced Sim) and return the signals as data: an operating point, a DC sweep, an AC sweep or a transient, as the standard's simulate gives them.",+            json!({"schematic": "the .SchDoc to simulate (filePath works too); it must belong to a .PrjPcb beside it", "analysis": "{type: op} | {type: dc, source: V1, start, stop, step} | {type: ac, sweep: dec|oct|lin, points, start, stop} (Hz) | {type: tran, step, stop, start?} (s); omitted: the analyses the design carries. {type: raw} is refused (not_supported): Altium netlists the schematic itself", "probes": "[{net: OUT} | {current: R3} | {signal: \"v(out)\"}]; with an analysis they become the signals the run keeps; omitted: the signals the design's own simulation setup keeps (an operating point keeps every node and current)", "points": "int, default 200: a ceiling per signal (the first, last and extreme points are kept)"}),+            json!({"signals": "[{signal, analysis, x, y, xUnit, yUnit, phase? (AC, degrees unwrapped), step? (a sweep's step)}]", "missing": "[probes the run did not have]", "available": "[every signal of the run]", "engine": "string", "results": "path of Altium's .sdf", "netlist": "path of the .nsx it ran"}), 900,+            "With analysis, the project's documents are closed, the analysis is written into its .simcfg (for this sheet and the project) and the project is reopened: Altium reads the file only on opening. Unsaved documents of that project refuse it (unsaved_changes). AC y is in dB with phase beside it. Every part needs a simulation model (Altium's generic R, C, L, sources and the models of its simulation libraries).",+            &["export_spice", "compile", "open_project"], &["A part with no simulation model stops the netlister: simulation_failed, and Altium's Messages name it.", "The run also opens Altium's results document; it is saved beside the project (Simulation folder) and closed."], json!({"schematic": "C:/proj/Filter.SchDoc", "analysis": {"type": "ac", "sweep": "dec", "points": 20, "start": 10, "stop": 1e6}, "probes": [{"net": "OUT"}]})),+        verb_doc("export_spice", "The schematic's SPICE netlist from Altium's mixed-signal simulator (the .nsx its Mixed Sim output writes): elements, analyses, models.",+            json!({"schematic": "the .SchDoc (filePath works too); it must belong to a .PrjPcb beside it", "outputPath": "optional: copy the netlist here"}),+            json!({"path": "the netlist", "elements": "[element lines]", "analyses": "[.AC / .TRAN / .DC / .OP lines]", "includes": "[.INCLUDE / .LIB lines]", "format": "string"}), 900,+            "Altium writes this netlist only as part of a run, so the sheet is simulated too (its results land in the project's Simulation folder). Models come inline (.model, .subckt) or as includes.",+            &["simulate"], &["A part with no simulation model stops the netlister: export_failed."], json!({"schematic": "C:/proj/Filter.SchDoc", "outputPath": "C:/proj/Filter.cir"})),         verb_doc("move_parts", "Move, rotate and flip placed components (side top or bottom; flip:true turns a part over); each part is read back to 0.001 mm, the exact rotation and its side. One undo step.",             json!({"parts": "[{ref, x, y, rotation, side?: top|bottom, flip?: bool}] - mm and degrees, Altium's frame; or {ref, dx, dy} to move by an offset; rotation and side kept when left out", "expectedRevision": "string (optional) - the revision you last read; refused with stale_board if the board changed", "boardId": "string (optional) - refused with board_mismatch unless this is the current board", "expectPath": "string (optional)"}),             json!({"revision": "string", "results": "[ok|err:...]", "mismatches": "[{ref, asked, got}] when a part did not land where asked (errorCode readback_mismatch)"}), 300,@@ -2094,6 +2104,8 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "plan_route" => crate::checks::plan_route(args),         "place_decoupling" => crate::checks::place_decoupling(args),         "plan_fanout" => crate::checks::plan_fanout(args),+        "simulate" => crate::sim::simulate(args),+        "export_spice" => crate::sim::export_spice(args),         "estimate_cost" => crate::checks::estimate_cost(args),         "height_check" => crate::bodies::height_check(args),         "bodies" => crate::bodies::bodies(args),
dev-skills/altium-bridge-test/run_verb_tests.py+8
@@ -437,6 +437,11 @@ def matrix(w):                            check=lambda d: len(d.get("files") or []) == 2 and not d.get("unknownLayers"))     M["export_gencad"] = dict(phase=4, timeout=300, **ok(filePath=LB, outputDir=D + "/gencad", uniquePins=True),                               check=lambda d: str(d.get("file", "")).endswith(".cad") and (d.get("counts") or {}).get("components", 0) > 0)+    SIM = D + "/sim/3_Reinforcing properties  Frequency characteristics.SchDoc"+    # 0.2.80 (EDA Bridge Standard #23): the amplifier's AC gain levels off at 9.27 dB (ngspice agrees to 0.0001 dB)+    M["simulate"] = dict(phase=4, timeout=900, **ok(schematic=SIM, analysis={"type": "ac", "sweep": "dec", "points": 10, "start": 10, "stop": 1e8}, probes=[{"net": "OUT"}], points=50),+                         check=lambda d: bool(d.get("signals")) and abs(d["signals"][0]["y"][-1] - 9.266) < 0.05 and d["signals"][0]["xUnit"] == "Hz")+    M["export_spice"] = dict(phase=4, timeout=900, **ok(schematic=SIM), check=lambda d: len(d.get("elements") or []) >= 8 and bool(d.get("analyses")))     M["generate_body"] = dict(phase=4, **ok(family="qfn", outputPath=D + "/bodies/QFN16.step", marking="STM32\nG031"),                               check=lambda d: abs(((d.get("bboxMm") or {}).get("x") or 0) - 4.0) < 0.01 and d.get("marking") and not d.get("notApplied"))     M["export_step"] = dict(phase=4, timeout=300, **anyo("STEP of the battery board", filePath=PD, output=D + "/battery.step"))@@ -544,6 +549,9 @@ def main():     ab(T, TH, "send_files", {"filePaths": fx}, timeout=300)     dw = D.replace("/", "\\"); hw = home.replace("/", "\\")     ab(T, TH, "shell_execute", {"command": f'cmd /c rmdir /S /Q "{dw}" 2>nul & mkdir "{dw}" & move /Y "{hw}\\Downloads\\Adom_Test.SchLib" "{dw}\\Battery.SchLib" & move /Y "{hw}\\Downloads\\Adom_Test.PcbLib" "{dw}\\Battery.PcbLib"'})+    # 0.2.80: Altium's own simulation example (its sheet 3, a one-transistor amplifier) for simulate and export_spice+    ex = "C:\\Users\\Public\\Documents\\Altium\\{}\\Examples\\Simulation Quick Start"+    ab(T, TH, "shell_execute", {"command": f'cmd /c (if exist "{ex.format("ADDevelop")}" (xcopy /E /I /Y /Q "{ex.format("ADDevelop")}" "{dw}\\sim") else (xcopy /E /I /Y /Q "{ex.format("AD26")}" "{dw}\\sim")) >nul'})      live = ab(T, TH, "altium_describe", {})     verbs = sorted(v[len("altium_"):] for v in (live.get("allVerbs") or []))
package.json+7−2
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.80",+  "version": "0.2.81",   "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": [@@ -254,7 +254,12 @@     "fan out a bga in altium",     "escape routing for a qfn in altium",     "estimate pcb cost from altium",-    "how much will this altium board cost"+    "how much will this altium board cost",+    "simulate this circuit in altium",+    "run an ac analysis in altium",+    "transient simulation in altium",+    "spice netlist from altium",+    "altium mixed signal simulation"   ],   "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.",   "sample_prompts": [
page.json+7−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.80",+  "version": "0.2.81",   "hero": {     "type": "image",     "path": "screenshots/hero.png"@@ -246,7 +246,12 @@     "fan out a bga in altium",     "escape routing for a qfn in altium",     "estimate pcb cost from altium",-    "how much will this altium board cost"+    "how much will this altium board cost",+    "simulate this circuit in altium",+    "run an ac analysis in altium",+    "transient simulation in altium",+    "spice netlist from altium",+    "altium mixed signal simulation"   ],   "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.",   "metadata": {},
skills/altium-schematic-edit/SKILL.md+26−2
@@ -3,8 +3,9 @@ name: altium-schematic-edit description: >-   Edit an Altium schematic and push it to the board: place library or Altium 365 parts, swap, wire pin to pin,   buses and bus entries, junctions, labels, text, move a region, trace a net, annotate, hierarchical sheets, the-  compiled netlist, a previewed ECO, PDF. Use when asked to add a part in altium, wire these pins, add a bus, check-  the netlist, or update pcb.+  compiled netlist, a previewed ECO, PDF, and circuit simulation (op, DC, AC, transient) with its SPICE netlist. Use+  when asked to add a part in altium, wire these pins, add a bus, check the netlist, update pcb, simulate this+  circuit, run an AC or transient analysis, or get the SPICE netlist. ---  Parent skill: **altium-bridge**@@ -203,6 +204,29 @@ Altium's Design > Update PCB Document (from the board: Import Changes), the engi - Edits made with these verbs (designators, comments, parameters) reach the change order. A part changed   some other way without Altium being told (an outside script) can be missed: reopen the sheet first. +## Simulate a sheet: `altium_simulate`, `altium_export_spice` (0.2.81)++```bash+altium_simulate '{"schematic":"C:/proj/Amp.SchDoc","analysis":{"type":"ac","sweep":"dec","points":10,"start":10,"stop":1e8},"probes":[{"net":"OUT"}]}'+altium_simulate '{"schematic":"C:/proj/Amp.SchDoc","analysis":{"type":"tran","step":1e-6,"stop":5e-3},"probes":[{"net":"OUT"},{"current":"R4"}]}'+altium_export_spice '{"schematic":"C:/proj/Amp.SchDoc","outputPath":"C:/proj/Amp.cir"}'+```++- Altium's own mixed-signal simulator (Advanced Sim), no clicks: the analysis (`op`, `dc`, `ac`, `tran`) is written into the+  project's `.simcfg` for that sheet (the project is closed for it and reopened: Altium reads the file on opening), the+  sheet is run as Altium's "Mixed Sim" output, and the results document (`.sdf`, in the project's Simulation folder) is+  saved, read and closed. About 4 s for a small circuit.+- `signals` are data: `{signal, analysis, x, y, xUnit, yUnit}`; AC `y` is dB with `phase` (degrees, unwrapped) beside it;+  `points` is a ceiling (first, last and extreme points kept). Probes become the signals the run keeps; without probes+  you get what the design's own setup keeps.+- Checked against ngspice on Altium's "Simulation Quick Start" amplifier: the operating point and all 71 AC points agree+  to 0.0001 dB.+- `export_spice` returns the `.nsx` netlist (elements, analyses, includes). Altium writes it only as part of a run, so the+  sheet is simulated too.+- Refusals: `unsaved_changes` (save the project's documents first: it is closed to write the analysis),+  `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.+ ## Title block and PDF  ```bash
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.80+0.2.81
src/agent/AdomAgent.pas.tmpl+72
@@ -9844,6 +9844,76 @@ End; { save_doc: save the document at path= itself. The save process saves the FOCUSED document, and open shows a document   without focusing it, so a save by path through it saved whichever document had focus (a source library, measured   2026-10-27). }+{ The open SimData (results) documents, every server's. }+Function SimDataDocs : TInterfaceList;+Var+    SM : IServerModule;+    D  : IServerDocument;+    I, J : Integer;+Begin+    Result := TInterfaceList.Create;+    For I := 0 To Client.Count - 1 Do+    Begin+        SM := Client.ServerModule[I];+        If SM = Nil Then Continue;+        For J := 0 To SM.DocumentCount - 1 Do+        Begin+            D := SM.Documents[J];+            If (D <> Nil) And (UpperCase(D.Kind) = 'SIMDATA') Then Result.Add(D);+        End;+    End;+    { the one in front, when the server walk misses it }+    D := Nil;+    Try D := Client.CurrentView.OwnerDocument; Except D := Nil; End;+    If (D <> Nil) And (UpperCase(D.Kind) = 'SIMDATA') And (Result.IndexOf(D) < 0) Then Result.Add(D);+End;++{ sim_run: start Altium's mixed-signal simulator on one schematic sheet (path=<SchDoc>). Earlier results documents are+  closed first (each run makes its own) and the sheet is made the CURRENT document: the run netlists whatever is in+  front, and with the last run's results in front it netlisted nothing (2026-10-29). Then WorkspaceManager:+  GenerateReport ObjectKind=Simulator|Index=1|Action=Run (the "Mixed Sim" output: <project>.nsx, then the run). The+  results document comes up after this returns: sim_collect saves and closes it. }+Function CmdSimRun(Lines : TStringList) : String;+Var+    Doc : IServerDocument;+    L   : TInterfaceList;+    Path : String;+    I : Integer;+Begin+    Path := Param(Lines, 'path');+    L := SimDataDocs;+    For I := 0 To L.Count - 1 Do Try Client.CloseDocument(L[I]); Except End;+    Doc := Nil;+    Try Doc := Client.OpenDocument('SCH', Path); Except Doc := Nil; End;+    If Doc = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','not_open') + ',' + JStr('error', Path + ' could not be opened') + '}'; Exit; End;+    Client.ShowDocument(Doc);+    ResetParameters;+    AddStringParameter('ObjectKind', 'Simulator');+    AddStringParameter('Index', '1');+    AddStringParameter('Action', 'Run');+    RunProcess('WorkspaceManager:GenerateReport');+    Result := '{' + JRaw('ok','true') + ',' + JStr('sheet', Path) + ',' + JStr('current', Client.CurrentView.OwnerDocument.FileName) + '}';+End;++{ sim_collect: the run's results document, saved (so its .sdf is on disk) and closed; sdf is empty while none is up. }+Function CmdSimCollect(Lines : TStringList) : String;+Var+    L : TInterfaceList;+    D : IServerDocument;+    Sdf : String;+Begin+    L := SimDataDocs;+    Sdf := '';+    If L.Count > 0 Then+    Begin+        D := L[L.Count - 1];+        D.DoFileSave('');+        Sdf := D.FileName;+        Try Client.CloseDocument(D); Except End;+    End;+    Result := '{' + JRaw('ok','true') + ',' + JStr('sdf', Sdf) + ',' + JRaw('open', IntToStr(L.Count)) + '}';+End;+ Function CmdSaveDoc(Lines : TStringList) : String; Var     Doc : IServerDocument;@@ -9954,6 +10024,8 @@ Begin     Else If Cmd = 'run_process' Then Result := CmdRunProcess(Lines)     Else If Cmd = 'open' Then Result := CmdOpen(Lines)     Else If Cmd = 'save_doc' Then Result := CmdSaveDoc(Lines)+    Else If Cmd = 'sim_run' Then Result := CmdSimRun(Lines)+    Else If Cmd = 'sim_collect' Then Result := CmdSimCollect(Lines)     Else If Cmd = 'edit_fp' Then Result := CmdEditFp(Lines, Payload)     Else If Cmd = 'close_document' Then Result := CmdCloseDocument(Lines)     Else If Cmd = 'eval' Then Result := CmdEval(Lines, Payload)
src/bridge.json+4−2
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.80",+  "version": "0.2.81",   "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",@@ -194,6 +194,8 @@     "altium_place_decoupling",     "altium_plan_fanout",     "altium_estimate_cost",+    "altium_simulate",+    "altium_export_spice",     "altium_route_pair",     "altium_routing_drc",     "altium_routing_state",@@ -287,7 +289,7 @@       "launch": 240,       "panelize": 240,       "impedance": 120,-      "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120,+      "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900,       "height_check": 150,       "copper_balance": 240,       "return_path": 240,