← Commit history

0.2.82 (unreleased): simulate answers no_model and notSimulated; every sheet runs the analysis asked for (its own settings, keyed by its project id); a new .simcfg joins the project

Colby Knox ·c9c064be29 · ·parent deeabd5
3 files changed +125−11
CHANGELOG.md+9
@@ -11,6 +11,15 @@   which the dialog reaper declines, refused agent_start while the reaper was still photographing it (the first AD 26   battery of 0.2.80 lost 60 verbs to the cascade). A dialog with a safe answer now gets up to 12 s to go; save prompts   and anything without one still refuse at once.+- **`altium_simulate` answers `no_model`**, as the standard defines it. Altium's netlister drops a part with no simulation+  model without a word, so a sheet of such parts ran nothing and the call waited out the relay's 120 s. Now the+  netlist's elements are compared with the sheet's parts: none simulated refuses `no_model` with the parts named (6 s on+  the battery's lane sheet), and a partly modelled sheet runs and lists the rest in `notSimulated`. A run that has not+  answered in 95 s says so instead of timing out.+- **`altium_simulate` runs the analysis asked for on every sheet.** A sheet with no simulation settings of its own ran+  on what Altium stored for it (sheet 1 of Altium's example ran its old AC sweep for an `op`): it now gets its own+  settings, keyed by its id in the project (given one when it has none, as a bridge-made project's sheets do), and a new+  `.simcfg` is listed in the project, the only way Altium reads it.  ## 0.2.81 
bridge-rs/src/sim.rs+115−10
@@ -162,7 +162,7 @@ fn xml_esc(s: &str) -> String { s.replace('&', "&amp;").replace('<', "&lt;").rep  /// 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 {+pub fn write_simcfg(xml: &str, sheet_name: &str, sheet_id: Option<&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 };@@ -173,10 +173,37 @@ pub fn write_simcfg(xml: &str, sheet_name: &str, kv: &[(String, String)], drop:     };     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); }+    if let Some(p) = out.find(&tag) { edit(&mut out, p); return out; }+    // a sheet with no settings of its own runs on what Altium stored for it, not on the project's (sheet 1 of the+    // example ran its old AC sweep, 2026-10-29): give it its own, keyed by the project's id for the sheet+    if let Some(id) = sheet_id {+        let doc = format!("    <DocumentConfig>\r\n      <Name>{}</Name>\r\n      <Id>{id}</Id>\r\n      <Config>{}</Config>\r\n      <Results />\r\n    </DocumentConfig>\r\n",+            xml_esc(sheet_name), set_config("", kv, drop));+        if let Some(p) = out.find("</Documents>") { out.insert_str(p, &doc); }+        else if let Some(p) = out.find("</ProjectConfig>") { out.insert_str(p, &format!("  <Documents>\r\n{doc}  </Documents>\r\n")); }+    }     out } +/// The project's id for a sheet (its DocumentUniqueId), given one when it has none: the simulation settings of a+/// sheet are keyed by it. Returns the project text and the id. Pure apart from the new id's letters.+pub fn sheet_unique_id(prj: &str, sheet_name: &str, fresh: &str) -> (String, String) {+    let nl = if prj.contains("\r\n") { "\r\n" } else { "\n" };+    let lines: Vec<&str> = prj.split(nl).collect();+    let Some(at) = lines.iter().position(|l| l.trim().eq_ignore_ascii_case(&format!("DocumentPath={sheet_name}"))) else { return (prj.to_string(), fresh.to_string()) };+    let end = lines[at + 1..].iter().position(|l| l.trim_start().starts_with('[')).map(|e| at + 1 + e).unwrap_or(lines.len());+    if let Some(i) = (at + 1..end).find(|i| lines[*i].trim().starts_with("DocumentUniqueId=")) {+        let v = lines[i].trim()["DocumentUniqueId=".len()..].to_string();+        if !v.is_empty() { return (prj.to_string(), v); }+        let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();+        out[i] = format!("DocumentUniqueId={fresh}");+        return (out.join(nl), fresh.to_string());+    }+    let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();+    out.insert(at + 1, format!("DocumentUniqueId={fresh}"));+    (out.join(nl), fresh.to_string())+}+ /// 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",@@ -311,11 +338,26 @@ fn configure(sheet: &Path, prj: &Path, analysis: &Value, probes: &[String]) -> R         .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 fresh = !cfg.exists();+    // the sheet's id in the project, given one when it has none+    let prj_text = std::fs::read_to_string(prj).unwrap_or_default();+    let letters: String = { let mut x = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(7) as u64;+        (0..8).map(|_| { x ^= x << 13; x ^= x >> 7; x ^= x << 17; (b'A' + (x % 26) as u8) as char }).collect() };+    let (prj_text, id) = sheet_unique_id(&prj_text, &name, &letters);+    let _ = std::fs::write(prj, &prj_text);     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),+        Ok(b) => write_simcfg(String::from_utf8_lossy(&b).trim_start_matches('\u{feff}'), &name, Some(&id), &kv, &drop),+        Err(_) => write_simcfg(&new_simcfg(&kv), &name, Some(&id), &kv, &drop),     };     std::fs::write(&cfg, text).map_err(|e| json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", cfg.display())}))?;+    // Altium reads a .simcfg only when the project lists it as a document (a new one beside lane.PrjPcb was ignored and+    // the run kept Altium's default transient, 2026-10-29)+    if let Ok(prj_text) = std::fs::read_to_string(prj) {+        let cfg_name = cfg.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+        if fresh || !prj_text.to_lowercase().contains(&format!("documentpath={}", cfg_name.to_lowercase())) {+            let _ = std::fs::write(prj, add_project_document(&prj_text, &cfg_name));+        }+    }     Ok(kind) } @@ -331,9 +373,16 @@ fn run(sheet: &Path, prj: &Path) -> Result<(Option<PathBuf>, Option<PathBuf>, Va     }     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));+    let dir = prj.parent().unwrap_or(Path::new("."));+    // under the relay's 120 s for one call: a run that has not answered by then is reported, not waited out+    while start.elapsed() < Duration::from_secs(95) {+        let c = crate::agent::call("sim_collect", &[], None, Duration::from_secs(60));         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; }+        // the netlist comes first: one with no elements has nothing to run, and no results ever come+        if let Some(n) = newest(dir, "nsx", t0) {+            let (el, _, _) = netlist_parts(&std::fs::read_to_string(&n).unwrap_or_default());+            if el.is_empty() && start.elapsed() > Duration::from_secs(3) { return Ok((None, Some(n), d)); }+        }         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,@@ -341,10 +390,36 @@ fn run(sheet: &Path, prj: &Path) -> Result<(Option<PathBuf>, Option<PathBuf>, Va         }         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)) } +/// The project file with one more [DocumentN] listing `name`. Pure.+pub fn add_project_document(prj: &str, name: &str) -> String {+    let n = prj.lines().filter_map(|l| l.trim().strip_prefix("[Document").and_then(|r| r.strip_suffix(']')).and_then(|x| x.parse::<u32>().ok())).max().unwrap_or(0) + 1;+    let nl = if prj.contains("\r\n") { "\r\n" } else { "\n" };+    let mut out = prj.trim_end().to_string();+    out.push_str(&format!("{nl}{nl}[Document{n}]{nl}DocumentPath={name}{nl}"));+    out+}++/// The designators a netlist simulates: each element is a SPICE letter plus the part's designator (RR3 is R3). Pure.+pub fn netlist_designators(elements: &[String]) -> Vec<String> {+    elements.iter().filter_map(|e| e.split_whitespace().next()).filter(|n| n.len() > 1).map(|n| n[1..].to_ascii_uppercase()).collect()+}++/// The sheet's parts the netlist left out: a part with no simulation model is dropped silently.+fn not_simulated(sheet: &Path, nsx: &Path) -> Vec<String> {+    let text = std::fs::read_to_string(nsx).unwrap_or_default();+    let (elements, _, _) = netlist_parts(&text);+    let have = netlist_designators(&elements);+    let parts = crate::schdoc::read_sheet_file(&json!({"path": sheet.to_string_lossy(), "pins": false}));+    let mut out: Vec<String> = parts["components"].as_array().cloned().unwrap_or_default().iter()+        .filter_map(|c| c["designator"].as_str().map(String::from)).filter(|d| !d.is_empty() && !have.contains(&d.to_ascii_uppercase())).collect();+    out.sort();+    out.dedup();+    out+}+ /// 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![]);@@ -366,10 +441,17 @@ pub fn simulate(args: &Value) -> Value {     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 missing_models = nsx.as_ref().map(|n| not_simulated(&sheet, n)).unwrap_or_default();     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",+        let empty = nsx.as_ref().map(|n| netlist_parts(&std::fs::read_to_string(n).unwrap_or_default()).0.is_empty()).unwrap_or(false);+        if empty || !missing_models.is_empty() {+            return json!({"success": false, "errorCode": "no_model", "error": if empty { "no part of the sheet has a simulation model: the netlist holds no elements".to_string() } else { format!("{} has no simulation model", missing_models.join(", ")) },+                "parts": missing_models, "netlist": nsx.map(|p| p.to_string_lossy().to_string()),+                "_hint": "Altium's netlister drops a part with no simulation model without a word. Give each one a model (a SIM model in its library: Altium's simulation-ready parts, or a SPICE model added to the symbol), or simulate a sheet built from Altium's simulation parts."});+        }+        return json!({"success": false, "errorCode": "simulation_failed", "error": "the run left no results (.sdf) within 95 s",             "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)."});+            "_hint": "Altium may still be simulating (a long transient): call again, or open the project's Simulation folder. Read Altium's Messages (altium_compile) for the simulator's errors."});     };     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())}) };@@ -379,6 +461,7 @@ pub fn simulate(args: &Value) -> Value {         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()),+        "notSimulated": missing_models,         "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."}) }@@ -470,7 +553,7 @@ mod tests {         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);+        let out = write_simcfg(xml, "b.SchDoc", None, &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}");@@ -493,4 +576,26 @@ mod tests {         assert_eq!(a, vec![".AC DEC 20 10 1meg", ".TRAN 1u 1m"]);         assert_eq!(i, vec![".INCLUDE \"x.lib\""]);     }+    #[test]+    fn a_new_config_joins_the_project_and_dropped_parts_are_found() {+        let prj = "[Design]\r\nVersion=1.0\r\n\r\n[Document1]\r\nDocumentPath=lane.SchDoc\r\n\r\n[Document2]\r\nDocumentPath=lane.PcbDoc\r\n";+        let out = add_project_document(prj, "project_sim_config.simcfg");+        assert!(out.ends_with("[Document3]\r\nDocumentPath=project_sim_config.simcfg\r\n"), "{out:?}");+        let (el, _, _) = netlist_parts("t\nRR3 in Vcc 1k\nQQ3 out in e QN\nXU1 a b c OPAMP\n.END\n");+        assert_eq!(netlist_designators(&el), vec!["R3", "Q3", "U1"]);+    }+    #[test]+    fn a_sheet_without_settings_gets_its_own() {+        let (kv, drop) = (vec![("OP_Analysis".to_string(), "True".to_string())], vec![]);+        let xml = "<P>\r\n  <Settings></Settings>\r\n  <Config>OP_Analysis=False</Config>\r\n  <Documents>\r\n  </Documents>\r\n</P>";+        let out = write_simcfg(xml, "1_a.SchDoc", Some("JJTZIGMC"), &kv, &drop);+        assert!(out.contains("<Name>1_a.SchDoc</Name>\r\n      <Id>JJTZIGMC</Id>\r\n      <Config>OP_Analysis=True</Config>"), "{out}");+        let bare = "<ProjectConfig>\r\n  <Settings></Settings>\r\n  <Config></Config>\r\n</ProjectConfig>";+        assert!(write_simcfg(bare, "x.SchDoc", Some("ABCDEFGH"), &kv, &drop).contains("<Documents>"));+        let prj = "[Document1]\r\nDocumentPath=lane.SchDoc\r\n\r\n[Document2]\r\nDocumentPath=lane.PcbDoc\r\nDocumentUniqueId=QQQQQQQQ\r\n";+        let (t, id) = sheet_unique_id(prj, "lane.SchDoc", "NEWIDXYZ");+        assert_eq!(id, "NEWIDXYZ");+        assert!(t.contains("DocumentPath=lane.SchDoc\r\nDocumentUniqueId=NEWIDXYZ\r\n"), "{t:?}");+        assert_eq!(sheet_unique_id(prj, "lane.PcbDoc", "X").1, "QQQQQQQQ");+    } }
bridge-rs/src/verbs.rs+1−1
@@ -440,7 +440,7 @@ fn describe() -> Value {         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.",+            "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. elements are exact; analyses are the lines Altium wrote, which can lag a sheet's newest settings by a run (measured: a transient ran while the file still read its earlier .AC): altium_simulate reports the analysis that ran.",             &["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)"}),