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.
main
Colby Knox
0.2.118 source: simulating leaves the design clean (copy sheets renamed _sim, bridge-written projects and simcfg saved)
8eb52bd
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
//! 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 charts an analysis lands in (a noise run fills two: the spectral densities and their integrals).
fn charts_of(kind: &str) -> &'static [&'static str] {
match kind { "op" => &["Operating Point"], "dc" => &["DC Sweep"], "tran" => &["Transient Analysis"], "ac" => &["AC Analysis"],
"noise" => &["Noise Spectral Density", "Integrated Noise"], _ => &[] }
}
/// 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], sweep: Option<&Value>, temps: Option<&Value>, mc: Option<&Value>) -> 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()));
// a number has a _UserValue twin, which Altium reads first when it is set (a TempSweep_Step without it was ignored:
// the old 10 degree step ran, 2026-10-29); words (sources, parameters, sweep types, flags) have none
if v.parse::<f64>().is_ok() { kv.retain(|(a, _)| a != &format!("{k}_UserValue")); 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());
}
"noise" => {
let (Some(src), Some(out), Some(s), Some(e)) = (a["source"].as_str(), a["output"].as_str(), n("start"), n("stop")) else {
return Err(bad("a noise analysis is {type: \"noise\", source: \"V1\" (the input source), output: \"OUT\" (a net), reference?: \"0\", 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("Noise_Analysis", "True".into());
set("Noise_Enabled", "True".into());
set("Noise_Source", src.into());
set("Noise_Output", out.into());
set("Noise_Reference", a["reference"].as_str().unwrap_or("0").into());
set("Noise_Start", num_text(s)); set("Noise_Stop", num_text(e));
set("Noise_TestPoints", num_text(n("points").unwrap_or(20.0).round().max(1.0)));
set("Noise_SweepType", sweep.clone());
// Altium's netlister takes the .NOISE sweep from the AC settings (it wrote the last AC run's DEC 5 1000
// 10000000 for a 10 Hz start, 2026-10-29): the same sweep goes there, with the AC analysis itself off
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);
}
"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, noise or raw")),
}
let mut sweep_drop: Vec<String> = Vec::new();
// a parameter sweep: the analysis again for each value of a part's value (C6) or a sheet parameter, every step its
// own signal (v(out)_p1 ...). Step is the increment for lin, the points per decade or octave for dec and oct, as
// Altium's own ParamSweep keys take it
if let Some(sw) = sweep.filter(|v| !v.is_null()) {
let f = |k: &str| sw.get(k).and_then(|v| v.as_f64());
let (Some(par), Some(st), Some(en), Some(step)) = (sw["parameter"].as_str(), f("start"), f("stop"), f("step")) else {
return Err(bad("sweep is {parameter: \"C6\" (a part) or a sheet parameter, start, stop, step, scale?: lin|dec|oct}"));
};
let scale = sw["scale"].as_str().unwrap_or("lin").to_ascii_uppercase();
if !["LIN", "DEC", "OCT"].contains(&scale.as_str()) { return Err(bad("sweep.scale is lin, dec or oct")); }
if step <= 0.0 { return Err(bad("sweep.step is above 0")); }
let n = if scale == "LIN" { ((en - st) / step).abs().floor() + 1.0 } else {
if st <= 0.0 || en <= 0.0 { return Err(bad("a dec or oct sweep runs over positive values")); }
let per = (en / st).abs().ln() / if scale == "DEC" { 10f64.ln() } else { 2f64.ln() };
(per * step).round() + 1.0
};
if n > 50.0 { return Err(bad(&format!("the sweep makes {n} runs: 50 at most"))); }
set("ParamSweep_Analysis", "True".into());
set("ParamSweep_Parameter1", par.into());
set("ParamSweep_Type1", scale.clone());
set("ParamSweep_Start1", num_text(st)); set("ParamSweep_Stop1", num_text(en)); set("ParamSweep_Step1", num_text(step));
set("ParamSweep_SecondaryEnabled", "False".into());
// the run reads Altium's sweep list (ParamSweep_Custom...0), not the ...1 keys its dialog shows: R4 asked for there
// ran the stored C6 sweep (2026-10-29). Ours is the list's only entry
set("ParamSweep_CustomEnabled0", "True".into());
set("ParamSweep_CustomParameter0", par.into());
set("ParamSweep_CustomType0", if scale == "LIN" { "LIN".into() } else { scale.clone() });
set("ParamSweep_CustomStart0", num_text(st)); set("ParamSweep_CustomStop0", num_text(en)); set("ParamSweep_CustomStep0", num_text(step));
sweep_drop.push("ParamSweep_Custom".into());
}
if let Some(tp) = temps.filter(|v| !v.is_null()) {
let f = |k: &str| tp.get(k).and_then(|v| v.as_f64());
let (Some(st), Some(en), Some(step)) = (f("start"), f("stop"), f("step")) else { return Err(bad("temperatures is {start, stop, step} in degrees C")) };
if step <= 0.0 || ((en - st) / step).abs() > 49.0 { return Err(bad("temperatures: a step above 0, and 50 runs at most")); }
set("TempSweep_Analysis", "True".into());
set("TempSweep_Start", num_text(st)); set("TempSweep_Stop", num_text(en)); set("TempSweep_Step", num_text(step));
}
// Monte Carlo: the analysis again with every part's value drawn within its tolerance, each run its own signal
if let Some(m) = mc.filter(|v| !v.is_null()) {
let runs = m.get("runs").and_then(|v| v.as_f64()).unwrap_or(10.0).round();
if !(1.0..=100.0).contains(&runs) { return Err(bad("monteCarlo.runs is 1 to 100")); }
let dist = match m["distribution"].as_str().unwrap_or("gauss").to_ascii_lowercase().as_str() { "gauss" | "gaussian" | "normal" => "GAUSS", "uniform" => "UNIFORM", _ => return Err(bad("monteCarlo.distribution is gauss or uniform")) };
set("MonteCarlo_Analysis", "True".into());
set("MonteCarlo_NumberOfRuns", num_text(runs));
set("MonteCarlo_DistributionType", dist.into());
set("MonteCarlo_Seed", num_text(m.get("seed").and_then(|v| v.as_f64()).unwrap_or(-1.0).round()));
// tolerances in percent; Altium keeps them as "10%" with a _UserValue twin
for (k, key) in [("resistor", "Resistor"), ("capacitor", "Capacitor"), ("inductor", "Inductor"), ("transistor", "Transistor"), ("dcSource", "DCSource"), ("digital", "DigitalTp")] {
if let Some(t) = m["tolerances"].get(k).and_then(|v| v.as_f64()) {
if !(0.0..=100.0).contains(&t) { return Err(bad("a tolerance is a percent, 0 to 100")); }
let v = format!("{}%", num_text(t));
set(&format!("MonteCarlo_{key}Tolerance"), v.clone());
set(&format!("MonteCarlo_{key}Tolerance_UserValue"), v);
}
}
}
// 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 = sweep_drop;
let pre = match t.as_str() { "ac" => "AC", "tran" => "TRAN", "dc" => "DC", _ => "" };
if !pre.is_empty() && !probes.is_empty() {
drop.extend([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('&', "&").replace('<', "<").replace('>', ">") }
/// 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, 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 };
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); 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",
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: &[&str] = kind.map(charts_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.is_empty() || want.contains(&w.chart.as_str()))).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" | "Noise Spectral Density" => "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);
// an integrated noise total is one number: its x is meaningless
s["x"] = if w.chart == "Integrated Noise" { json!([]) } else { json!(k.iter().map(|i| r6(w.x[*i])).collect::<Vec<_>>()) };
s["y"] = json!(k.iter().map(|i| r6(w.y[*i])).collect::<Vec<_>>());
// Altium leaves the noise units blank: a spectral density is V per root hertz, a total is V
let unit = if !w.unit.is_empty() { w.unit.clone() } else if w.chart == "Noise Spectral Density" { "V/rtHz".into() } else if w.chart == "Integrated Noise" { "V".into() } else { String::new() };
s["yUnit"] = json!(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).
pub(crate) 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], sweep: Option<&Value>, temps: Option<&Value>, mc: Option<&Value>) -> Result<String, Value> {
let (kind, kv, drop) = analysis_keys(analysis, probes, sweep, temps, mc)?;
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 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, 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)
}
/// 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;
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,
"_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));
}
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![]);
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();
if args.get("analysis").map(|a| a.is_null()).unwrap_or(true) && (args.get("sweep").is_some() || args.get("temperatures").is_some() || args.get("monteCarlo").is_some()) {
return json!({"success": false, "errorCode": "bad_args", "error": "a sweep runs an analysis again for each value: give the analysis too"});
}
let kind = match args.get("analysis").filter(|a| !a.is_null()) { Some(a) => match configure(&sheet, &prj, a, &probes, args.get("sweep"), args.get("temperatures"), args.get("monteCarlo")) { Ok(k) => Some(k), Err(e) => return e }, None => None };
let (sdf, nsx, _) = match run(&sheet, &prj) { Ok(x) => x, Err(e) => return e };
if kind.is_some() { save_configured(&prj); }
let missing_models = nsx.as_ref().map(|n| not_simulated(&sheet, n)).unwrap_or_default();
let Some(sdf) = sdf else {
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": "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())}) };
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()),
"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."})
}
/// The project file and its .simcfg, which configure wrote with the project closed: Altium reopens them and holds them as
/// changed, so closing Altium asked to save them (AI Flow, 2026-12-01). configure refused unsaved changes before it wrote,
/// so saving now stores only what it wrote.
fn save_configured(prj: &Path) {
let _ = crate::surfaces::save(&json!({"filePath": prj.to_string_lossy()}));
let dir = prj.parent().unwrap_or(Path::new("."));
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
if e.path().extension().map(|x| x.eq_ignore_ascii_case("simcfg")).unwrap_or(false) {
// the agent's own save: altium_save opens only the document kinds it knows, and a .simcfg is not one
let _ = crate::agent::call("save_doc", &[("path", e.path().to_string_lossy().replace('/', "\\"))], None, std::time::Duration::from_secs(60));
}
}
}
/// 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()], None, None, None).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"}), &[], None, None, None).unwrap_err()["errorCode"], "not_supported");
assert_eq!(analysis_keys(&json!({"type": "tran", "stop": 1}), &[], None, None, None).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", 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}");
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\""]);
}
#[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");
}
#[test]
fn sweeps_become_altiums_param_and_temperature_keys() {
let ac = json!({"type": "ac", "sweep": "dec", "points": 10, "start": 10, "stop": 1e8});
let (_, kv, drop) = analysis_keys(&ac, &[], Some(&json!({"parameter": "C6", "start": 1e-10, "stop": 1e-4, "step": 1, "scale": "dec"})), Some(&json!({"start": -10, "stop": 60, "step": 35})), None).unwrap();
let cfg = set_config("ParamSweep_Analysis=False|ParamSweep_CustomParameter1=R9|ParamSweep_CustomEnabled1=True", &kv, &drop);
assert!(cfg.contains("ParamSweep_CustomParameter0=C6") && cfg.contains("ParamSweep_CustomStart0_UserValue=0.0000000001") && !cfg.contains("R9"), "the sweep list holds ours alone: {cfg}");
assert!(cfg.contains("ParamSweep_Analysis=True") && cfg.contains("ParamSweep_Parameter1=C6") && cfg.contains("ParamSweep_Type1=DEC") && cfg.contains("ParamSweep_Start1=0.0000000001"), "{cfg}");
assert!(cfg.contains("TempSweep_Analysis=True") && cfg.contains("TempSweep_Stop=60") && cfg.contains("TempSweep_Step_UserValue=35"), "{cfg}");
assert!(cfg.contains("ParamSweep_Step1_UserValue=1") && !cfg.contains("ParamSweep_Parameter1_UserValue"), "numbers get their twin, words do not: {cfg}");
assert_eq!(analysis_keys(&ac, &[], Some(&json!({"parameter": "R1", "start": 1, "stop": 1000, "step": 1})), None, None).unwrap_err()["errorCode"], "bad_args", "1000 runs is too many");
let (_, plain, _) = analysis_keys(&ac, &[], None, None, None).unwrap();
assert!(set_config("ParamSweep_Analysis=True", &plain, &[]).contains("ParamSweep_Analysis=False"), "no sweep switches an old one off");
}
}