main
Colby Knox 0.2.117 source: altium_sim_copy (sources and loads on a simulation copy), generic R/C/L in add_sim_model 31ac6c7
//! altium_add_sim_model (#42): a SPICE model on a SchLib symbol, written the way Altium's Sim Model dialog writes it, so
//! the part simulates in Altium and the model goes into an IntLib. Measured 2026-12-01 on AD 26.11: a SIM implementation
//! linked with kind `mdl` (lower case), the model file's full path, no UseComponentLibrary and no locked data links,
//! with Kind, SubKind, Spice Prefix and Netlist on the implementation, compiles into an IntLib with `MDL/0.mdl` and a
//! SIM entry in LibCrossRef.Txt. The model file is read, cleaned (a vendor's uncommented title line goes) and written
//! beside the library; the symbol's pins are mapped onto the model's nodes.
use serde_json::{json, Value};
use std::collections::BTreeMap;

/// One model in a SPICE file.
#[derive(Clone, Debug, PartialEq)]
pub struct Model {
    pub name: String,
    /// `D`, `NPN`, `NMOS`, ... for a `.MODEL`; `SUBCKT` for a `.SUBCKT`
    pub kind: String,
    /// a subcircuit's nodes, in order
    pub nodes: Vec<String>,
    /// the cards, joined back into whole lines
    pub text: String,
}

/// The SPICE cards of a file: continuation lines (`+`) joined, comments and blank lines left out, and anything before
/// the first card that is not a comment (a vendor's title line) dropped.
fn cards(text: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for raw in text.lines() {
        let l = raw.split(';').next().unwrap_or("").trim_end();
        let t = l.trim_start();
        if t.is_empty() || t.starts_with('*') { continue; }
        if let Some(rest) = t.strip_prefix('+') {
            if let Some(last) = out.last_mut() { last.push(' '); last.push_str(rest.trim()); }
            continue;
        }
        out.push(t.to_string());
    }
    // a title line is not a card: SPICE reads the first line of a netlist as its title, which a vendor's model file
    // often carries uncommented
    while out.first().is_some_and(|c| !c.starts_with('.')) { out.remove(0); }
    out
}

/// A Cadence-encrypted model (PSpice packages carry `$CDNENCSTART`, even TI's "unencrypted" ones) or a protected block:
/// Altium cannot simulate it.
pub fn encrypted(text: &str) -> bool {
    let l = text.to_ascii_lowercase();
    l.contains("$cdnencstart") || l.contains("$cdnencfinish") || l.lines().any(|x| x.trim_start().starts_with(".prot"))
}

/// Every `.MODEL` and `.SUBCKT` in a file.
pub fn parse(text: &str) -> Vec<Model> {
    let cs = cards(text);
    let mut out = Vec::new();
    let mut i = 0;
    while i < cs.len() {
        let c = &cs[i];
        let low = c.to_ascii_lowercase();
        if low.starts_with(".model") {
            let mut w = c.split_whitespace().skip(1);
            let name = w.next().unwrap_or("").to_string();
            let kind = w.next().unwrap_or("").split('(').next().unwrap_or("").to_ascii_uppercase();
            if !name.is_empty() { out.push(Model { name, kind, nodes: vec![], text: c.clone() }); }
        } else if low.starts_with(".subckt") {
            let toks: Vec<&str> = c.split_whitespace().collect();
            let name = toks.get(1).unwrap_or(&"").to_string();
            let nodes: Vec<String> = toks.iter().skip(2).take_while(|t| !t.contains('=') && !t.eq_ignore_ascii_case("params:")).map(|t| t.to_string()).collect();
            let mut block = vec![c.clone()];
            let mut j = i + 1;
            while j < cs.len() {
                block.push(cs[j].clone());
                if cs[j].to_ascii_lowercase().starts_with(".ends") { break; }
                j += 1;
            }
            if !name.is_empty() { out.push(Model { name, kind: "SUBCKT".into(), nodes, text: block.join("\n") }); }
            i = j;
        }
        i += 1;
    }
    out
}

/// How Altium describes a model of this kind: (Description, Kind, SubKind, Spice Prefix, model nodes). The names are
/// Altium's own (its examples: General/Diode/D, Transistor/BJT/Q). None for a kind this verb does not attach.
pub fn altium_kind(m: &Model) -> Option<(&'static str, &'static str, &'static str, &'static str, usize)> {
    Some(match m.kind.as_str() {
        "D" => ("Diode", "General", "Diode", "D", 2),
        "NPN" => ("NPN", "Transistor", "BJT", "Q", 3),
        "PNP" => ("PNP", "Transistor", "BJT", "Q", 3),
        "NMOS" => ("NMOS", "Transistor", "MOSFET", "M", 4),
        "PMOS" => ("PMOS", "Transistor", "MOSFET", "M", 4),
        "NJF" => ("NJFET", "Transistor", "JFET", "J", 3),
        "PJF" => ("PJFET", "Transistor", "JFET", "J", 3),
        "SUBCKT" => ("Subcircuit", "General", "Spice Subcircuit", "X", m.nodes.len()),
        _ => return None,
    })
}

/// The netlist template: `@DESIGNATOR %1 %2 ... @MODEL`. A MOSFET drawn with three pins ties its body to its source
/// (`%1 %2 %3 %3`).
pub fn netlist(nodes: usize, mosfet_three_pins: bool) -> String {
    let mut ns: Vec<String> = (1..=nodes).map(|i| format!("%{i}")).collect();
    if mosfet_three_pins { ns.push("%3".into()); }
    format!("@DESIGNATOR {} @MODEL", ns.join(" "))
}

/// The symbol-pin to model-node map. Given: `{"1": 2, "2": 1}` (symbol pin number to model node, from 1). Without one,
/// a diode's pins named for anode and cathode go to nodes 1 and 2, and otherwise the pins in number order go to the
/// nodes in order. Err says why the symbol and the model do not fit.
pub fn pin_map(given: Option<&Value>, pins: &[(String, String)], nodes: usize, kind: &str) -> Result<BTreeMap<String, usize>, String> {
    let mut map = BTreeMap::new();
    if let Some(g) = given.and_then(|v| v.as_object()) {
        for (k, v) in g {
            let n = v.as_u64().map(|n| n as usize).or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())).ok_or_else(|| format!("pinMap {k}: a model node number"))?;
            if n < 1 || n > nodes { return Err(format!("pinMap {k}: node {n}, the model has {nodes}")); }
            if !pins.iter().any(|(d, _)| d == k) { return Err(format!("pinMap {k}: the symbol has no pin {k}")); }
            map.insert(k.clone(), n);
        }
        return Ok(map);
    }
    // pins named for their role go to that node, whatever their numbers: SPICE's order is anode-cathode for a diode,
    // collector-base-emitter for a BJT, drain-gate-source(-body) for a FET
    let roles: &[&[&str]] = match kind {
        "D" => &[&["A", "ANODE", "+"], &["K", "C", "CATHODE", "KATHODE", "-"]],
        "NPN" | "PNP" => &[&["C", "COLLECTOR"], &["B", "BASE"], &["E", "EMITTER"]],
        "NMOS" | "PMOS" => &[&["D", "DRAIN"], &["G", "GATE"], &["S", "SOURCE"], &["B", "BULK", "BODY", "SUB"]],
        "NJF" | "PJF" => &[&["D", "DRAIN"], &["G", "GATE"], &["S", "SOURCE"]],
        _ => &[],
    };
    if !roles.is_empty() {
        let mut by_role = BTreeMap::new();
        for (i, words) in roles.iter().take(nodes).enumerate() {
            if let Some(p) = pins.iter().find(|(_, n)| words.iter().any(|w| n.eq_ignore_ascii_case(w))) { by_role.insert(p.0.clone(), i + 1); }
        }
        if by_role.len() == nodes && by_role.len() == pins.len().min(nodes) { return Ok(by_role); }
    }
    if pins.len() < nodes { return Err(format!("the symbol has {} pins and the model {nodes} nodes: give pinMap", pins.len())); }
    let mut ps: Vec<&(String, String)> = pins.iter().collect();
    ps.sort_by(|a, b| match (a.0.parse::<f64>(), b.0.parse::<f64>()) { (Ok(x), Ok(y)) => x.partial_cmp(&y).unwrap(), _ => a.0.cmp(&b.0) });
    for (i, p) in ps.iter().take(nodes).enumerate() { map.insert(p.0.clone(), i + 1); }
    Ok(map)
}

/// The map as Altium stores it: `(symbolPin:modelNode),...`.
pub fn map_string(m: &BTreeMap<String, usize>) -> String {
    m.iter().map(|(p, n)| format!("({p}:{n})")).collect::<Vec<_>>().join(",")
}

/// The clean model file: a header naming where it came from, the model (a subcircuit with every .MODEL of its file,
/// which it may use).
pub fn clean_file(m: &Model, all: &[Model], source: &str) -> String {
    let mut t = format!("* {} ({}), cleaned by altium-bridge from {}\n{}\n", m.name, m.kind, source, m.text);
    if m.kind == "SUBCKT" {
        for o in all.iter().filter(|o| o.kind != "SUBCKT") { t.push_str(&o.text); t.push('\n'); }
    }
    t
}

/// Altium's generic passive for a `generic` argument: (SubKind, Spice Prefix), as its Simulation Generic Components
/// library has them (Kind General). None for anything else.
pub fn generic_kind(g: &str) -> Option<(&'static str, &'static str)> {
    match g.trim().to_ascii_lowercase().as_str() {
        "resistor" | "r" | "res" => Some(("Resistor", "R")),
        "capacitor" | "c" | "cap" => Some(("Capacitor", "C")),
        "inductor" | "l" | "ind" => Some(("Inductor", "L")),
        _ => None,
    }
}

/// The netlist line of a generic passive: the part's own Value parameter, as Altium's generic library writes it.
pub const GENERIC_NETLIST: &str = "@DESIGNATOR %1 %2 @VALUE";

/// altium_add_sim_model {libraryPath, symbolName, generic: resistor|capacitor|inductor, pinMap?, replace?, dryRun?}
fn add_generic(args: &Value, lib: &str, sym: &str, g: &str) -> Value {
    let Some((sub, prefix)) = generic_kind(g) else {
        return json!({"success": false, "errorCode": "bad_args", "error": format!("generic {g}: resistor, capacitor or inductor")});
    };
    if let Some(e) = crate::support::must_open(lib, 60) { return e; }
    let read = crate::agent::call("lib_symbol_pins", &[("libref", sym.to_string())], None, std::time::Duration::from_secs(60));
    if read.pointer("/data/ok") != Some(&json!(true)) {
        return json!({"success": false, "errorCode": "symbol_not_found", "error": format!("no symbol {sym} in {lib}"), "reply": read.get("data")});
    }
    let pins: Vec<(String, String)> = read.pointer("/data/pins").and_then(|p| p.as_array()).map(|a| a.iter().filter_map(|p| Some((p.get(0)?.as_str()?.to_string(), p.get(1).and_then(|x| x.as_str()).unwrap_or("").to_string()))).collect()).unwrap_or_default();
    let map = match pin_map(args.get("pinMap"), &pins, 2, "") { Ok(x) => x, Err(e) => return json!({"success": false, "errorCode": "pin_map", "error": e, "pins": pins}) };
    if args.get("pinMap").is_none() && pins.len() != 2 {
        return json!({"success": false, "errorCode": "pin_map", "error": format!("{sym} has {} pins: a generic {} has two; give pinMap", pins.len(), sub.to_lowercase()), "pins": pins});
    }
    let name = sub.to_ascii_uppercase();
    let plan = json!({"model": {"name": name, "kind": "generic", "nodes": 2}, "file": Value::Null,
        "altium": {"description": sub, "kind": "General", "subKind": sub, "spicePrefix": prefix, "netlist": GENERIC_NETLIST},
        "pinMap": map, "symbolPins": pins.iter().map(|(d, n)| json!([d, n])).collect::<Vec<_>>()});
    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {
        let mut r = plan; r["success"] = json!(true); r["dryRun"] = json!(true);
        r["_hint"] = json!("Nothing changed. The model reads each placed part's Value parameter; call again without dryRun.");
        return r;
    }
    let replace = args.get("replace").and_then(|b| b.as_bool()).unwrap_or(true);
    let r = crate::agent::call("add_sim", &[("libref", sym.to_string()), ("name", name.clone()), ("file", String::new()), ("fkind", String::new()),
        ("desc", sub.into()), ("kind", "General".into()), ("subkind", sub.into()), ("prefix", prefix.into()), ("netlist", GENERIC_NETLIST.into()),
        ("map", map_string(&map)), ("replace", if replace { "1".into() } else { "0".into() })], None, std::time::Duration::from_secs(60));
    let d = r.get("data").cloned().unwrap_or(json!({}));
    if d["ok"] != true { let mut e = r.clone(); e["success"] = json!(false); return e; }
    let value = d["value"].as_str().unwrap_or("").to_string();
    let mut out = plan;
    out["success"] = json!(true);
    out["replaced"] = d["replaced"].clone();
    out["models"] = d["models"].clone();
    out["value"] = json!(value);
    out["saved"] = json!(false);
    out["_hint"] = json!(if value.trim().is_empty() {
        "Altium's generic model is on the symbol, but the symbol has no Value parameter: the model netlists each placed part's Value (10k, 100n, 4.7u), so give the placed parts one (or the symbol, with altium_set_params). altium_save {filePath: libraryPath} keeps the model."
    } else {
        "Altium's generic model is on the symbol: each placed part simulates at its own Value parameter. altium_save {filePath: libraryPath} keeps it."
    });
    out
}

/// altium_add_sim_model {libraryPath, symbolName, modelPath | generic, modelName?, pinMap?, replace?, dryRun?}
pub fn add_sim_model(args: &Value) -> Value {
    let s = |k: &str| crate::support::s(args, k);
    let bad = |m: String| json!({"success": false, "errorCode": "bad_args", "error": m});
    if let (Some(lib), Some(sym), Some(g)) = (s("libraryPath"), s("symbolName"), s("generic")) {
        if s("modelPath").is_some() { return bad("give modelPath (a SPICE file) or generic (Altium's own R, C, L), not both".into()); }
        if !lib.to_lowercase().ends_with(".schlib") { return bad(format!("{lib} is not a .SchLib")); }
        return add_generic(args, &lib, &sym, &g);
    }
    let (Some(lib), Some(sym), Some(mpath)) = (s("libraryPath"), s("symbolName"), s("modelPath")) else {
        return bad("libraryPath (.SchLib), symbolName and modelPath (the .mdl/.lib/.ckt SPICE file on this machine) or generic (resistor, capacitor, inductor) are required".into());
    };
    if !lib.to_lowercase().ends_with(".schlib") { return bad(format!("{lib} is not a .SchLib")); }
    let text = match std::fs::read(&mpath) {
        Ok(b) => String::from_utf8_lossy(&b).to_string(),
        Err(e) => return json!({"success": false, "errorCode": "file_not_found", "error": format!("{mpath}: {e}")}),
    };
    if encrypted(&text) {
        return json!({"success": false, "errorCode": "encrypted_model", "error": format!("{mpath} is encrypted ($CDNENCSTART or .PROT): Altium cannot simulate it"),
            "_hint": "Encrypted PSpice models (TI's \"unencrypted\" packages often are) run only in PSpice. Use an unencrypted model, or a behavioural one of your own."});
    }
    let models = parse(&text);
    if models.is_empty() { return json!({"success": false, "errorCode": "no_model", "error": format!("{mpath} holds no .MODEL or .SUBCKT")}); }
    let m = match s("modelName") {
        Some(n) => match models.iter().find(|m| m.name.eq_ignore_ascii_case(&n)) { Some(m) => m.clone(), None => return json!({"success": false, "errorCode": "model_not_found", "error": format!("{mpath} has no model {n}"), "models": models.iter().map(|m| json!({"name": m.name, "kind": m.kind})).collect::<Vec<_>>()}) },
        None if models.iter().filter(|m| m.kind == "SUBCKT").count() == 1 => models.iter().find(|m| m.kind == "SUBCKT").unwrap().clone(),
        None if models.len() == 1 => models[0].clone(),
        None => return json!({"success": false, "errorCode": "which_model", "error": format!("{mpath} holds {} models: name one with modelName", models.len()), "models": models.iter().map(|m| json!({"name": m.name, "kind": m.kind})).collect::<Vec<_>>()}),
    };
    let Some((desc, kind, subkind, prefix, nodes)) = altium_kind(&m) else {
        return json!({"success": false, "errorCode": "unsupported_model", "error": format!("{} is a {} model: this verb attaches diodes, BJTs, MOSFETs, JFETs and subcircuits", m.name, m.kind)});
    };
    if let Some(e) = crate::support::must_open(&lib, 60) { return e; }
    let read = crate::agent::call("lib_symbol_pins", &[("libref", sym.clone())], None, std::time::Duration::from_secs(60));
    let pins: Vec<(String, String)> = read.pointer("/data/pins").and_then(|p| p.as_array()).map(|a| a.iter().filter_map(|p| Some((p.get(0)?.as_str()?.to_string(), p.get(1).and_then(|x| x.as_str()).unwrap_or("").to_string()))).collect()).unwrap_or_default();
    if read.pointer("/data/ok") != Some(&json!(true)) {
        return json!({"success": false, "errorCode": "symbol_not_found", "error": format!("no symbol {sym} in {lib}"), "reply": read.get("data")});
    }
    let mos3 = subkind == "MOSFET" && pins.len() == 3 && args.get("pinMap").is_none();
    let node_count = if mos3 { 3 } else { nodes };
    let map = match pin_map(args.get("pinMap"), &pins, node_count, &m.kind) { Ok(x) => x, Err(e) => return json!({"success": false, "errorCode": "pin_map", "error": e, "pins": pins}) };
    let ext = if m.kind == "SUBCKT" { "ckt" } else { "mdl" };
    let dir = std::path::Path::new(&lib.replace('\\', "/")).parent().map(|p| p.to_path_buf()).unwrap_or_default();
    let file = dir.join(format!("{}.{ext}", m.name)).to_string_lossy().replace('/', "\\");
    let template = netlist(node_count, mos3);
    let plan = json!({"model": {"name": m.name, "kind": m.kind, "nodes": nodes}, "file": file, "altium": {"description": desc, "kind": kind, "subKind": subkind, "spicePrefix": prefix, "netlist": template},
        "pinMap": map, "symbolPins": pins.iter().map(|(d, n)| json!([d, n])).collect::<Vec<_>>()});
    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {
        let mut r = plan; r["success"] = json!(true); r["dryRun"] = json!(true);
        r["_hint"] = json!("Nothing changed. Check pinMap against the datasheet (a SPICE diode's node 1 is the anode), then call again without dryRun.");
        return r;
    }
    if let Err(e) = std::fs::write(&file, clean_file(&m, &models, &mpath)) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{file}: {e}")}); }
    let replace = args.get("replace").and_then(|b| b.as_bool()).unwrap_or(true);
    let r = crate::agent::call("add_sim", &[("libref", sym.clone()), ("name", m.name.clone()), ("file", file.clone()), ("fkind", ext.into()),
        ("desc", desc.into()), ("kind", kind.into()), ("subkind", subkind.into()), ("prefix", prefix.into()), ("netlist", template.clone()),
        ("map", map_string(&map)), ("replace", if replace { "1".into() } else { "0".into() })], None, std::time::Duration::from_secs(60));
    let d = r.get("data").cloned().unwrap_or(json!({}));
    if d["ok"] != true { let mut e = r.clone(); e["success"] = json!(false); return e; }
    let mut out = plan;
    out["success"] = json!(true);
    out["replaced"] = d["replaced"].clone();
    out["models"] = d["models"].clone();
    out["saved"] = json!(false);
    out["_hint"] = json!("The SIM model is on the symbol, in the form Altium's Sim Model dialog writes: it simulates once placed (altium_sch_place_part keeps it) and compiles into an IntLib with its model file. altium_save {filePath: libraryPath} keeps it. Check pinMap: a SPICE diode's node 1 is the anode, a BJT's 1-2-3 are collector, base, emitter.");
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    const VENDOR: &str = "1N4148 diode model from the vendor\r\n* comment\r\n.MODEL 1N4148 D(IS=2.52n RS=0.568 N=1.752 CJO=4p M=0.4\r\n+ TT=20n BV=100 IBV=100u) ; trailing\r\n";

    #[test]
    fn a_vendor_title_line_and_continuations_are_read_as_spice_does() {
        let m = parse(VENDOR);
        assert_eq!(m.len(), 1);
        assert_eq!(m[0].name, "1N4148");
        assert_eq!(m[0].kind, "D");
        assert!(m[0].text.contains("TT=20n BV=100 IBV=100u)") && !m[0].text.contains("vendor"), "{}", m[0].text);
        let f = clean_file(&m[0], &m, "C:/v/1N4148.lib");
        assert!(f.starts_with("* 1N4148 (D)") && f.lines().nth(1).unwrap().starts_with(".MODEL 1N4148 D("));
    }

    #[test]
    fn a_subcircuit_keeps_its_nodes_and_its_models() {
        let t = ".SUBCKT OPA1 IN+ IN- V+ V- OUT PARAMS: GAIN=10\nX1 IN+ IN- V+ V- OUT CORE\n.ENDS\n.MODEL DX D(IS=1e-14)\n";
        let m = parse(t);
        let s = m.iter().find(|m| m.kind == "SUBCKT").unwrap();
        assert_eq!(s.nodes, vec!["IN+", "IN-", "V+", "V-", "OUT"]);
        assert_eq!(altium_kind(s).unwrap().4, 5);
        assert!(clean_file(s, &m, "x").contains(".MODEL DX D"));
        assert_eq!(netlist(5, false), "@DESIGNATOR %1 %2 %3 %4 %5 @MODEL");
    }

    #[test]
    fn an_encrypted_model_is_refused() {
        assert!(encrypted("$CDNENCSTART\nabc\n$CDNENCFINISH"));
        assert!(encrypted(".PROT\n.MODEL X D\n.UNPROT"));
        assert!(!encrypted(VENDOR));
    }

    #[test]
    fn a_diode_maps_its_anode_to_node_one_whatever_its_pin_number() {
        let pins = vec![("1".to_string(), "K".to_string()), ("2".to_string(), "A".to_string())];
        let m = pin_map(None, &pins, 2, "D").unwrap();
        assert_eq!(map_string(&m), "(1:2),(2:1)");
        let given = pin_map(Some(&json!({"1": 1, "2": 2})), &pins, 2, "D").unwrap();
        assert_eq!(map_string(&given), "(1:1),(2:2)");
        assert!(pin_map(Some(&json!({"3": 1})), &pins, 2, "D").is_err());
        let q = vec![("2".to_string(), "B".to_string()), ("1".to_string(), "C".to_string()), ("3".to_string(), "E".to_string())];
        assert_eq!(map_string(&pin_map(None, &q, 3, "NPN").unwrap()), "(1:1),(2:2),(3:3)", "C B E by name");
        let q2 = vec![("1".to_string(), "B".to_string()), ("2".to_string(), "E".to_string()), ("3".to_string(), "C".to_string())];
        assert_eq!(map_string(&pin_map(None, &q2, 3, "NPN").unwrap()), "(1:2),(2:3),(3:1)", "SOT-23 B E C goes by name");
        let unnamed = vec![("2".to_string(), "x".to_string()), ("1".to_string(), "y".to_string())];
        assert_eq!(map_string(&pin_map(None, &unnamed, 2, "D").unwrap()), "(1:1),(2:2)", "number order without names");
        assert!(pin_map(None, &q[..2], 3, "NPN").is_err());
    }

    #[test]
    fn generic_passives_are_altiums_own() {
        assert_eq!(generic_kind("Resistor"), Some(("Resistor", "R")));
        assert_eq!(generic_kind("c"), Some(("Capacitor", "C")));
        assert_eq!(generic_kind("inductor"), Some(("Inductor", "L")));
        assert_eq!(generic_kind("diode"), None);
        let two = vec![("2".to_string(), "".to_string()), ("1".to_string(), "".to_string())];
        assert_eq!(map_string(&pin_map(None, &two, 2, "").unwrap()), "(1:1),(2:2)");
    }

    #[test]
    fn a_three_pin_mosfet_ties_its_body_to_its_source() {
        assert_eq!(netlist(3, true), "@DESIGNATOR %1 %2 %3 %3 @MODEL");
    }
}