Skip to main content

general_mna/
system.rs

1use std::collections::BTreeMap;
2
3use crate::{Expression, Matrix, TransientFunction};
4
5/// One `ic=` (or `.IC`) initial condition, already resolved against this system's own unknown
6/// ordering.
7///
8/// **Sign conventions, stated once, explicitly** — these are the half that gets misremembered:
9///
10/// - A capacitor's `ic` is the voltage of its **first** node minus its **second**:
11///   `C1 b 0 1e-6 ic=5` means `V(b) - V(0) = 5 V` at `t = 0`.
12/// - An inductor's `ic` is the current flowing **from its first node to its second node,
13///   through the inductor**: `L1 a b 5e-6 ic=12` means 12 A enter the inductor at `a` and
14///   leave it at `b` at `t = 0`. This is exactly the sign of the system's own `I(L1)` unknown,
15///   because `stamp_branch_incidence` puts `+1` in the first node's KCL row — so a positive
16///   branch current leaves that node and enters the element. Writing `L1 b a 5e-6 ic=12`
17///   instead declares the opposite physical current.
18#[derive(Debug, Clone, PartialEq)]
19pub enum InitialCondition {
20    /// `ic=` on a `C` card: the voltage across the capacitor at `t = 0`.
21    CapacitorVoltage {
22        /// The capacitor's element name, for diagnostics.
23        element: String,
24        /// Index into `unknowns` of the first node's voltage, `None` when it is ground.
25        positive: Option<usize>,
26        /// Index into `unknowns` of the second node's voltage, `None` when it is ground.
27        negative: Option<usize>,
28        /// The declared value, in volts.
29        value: Expression,
30    },
31    /// `ic=` on an `L` card: the current through the inductor at `t = 0`.
32    InductorCurrent {
33        /// The inductor's element name, for diagnostics.
34        element: String,
35        /// Index into `unknowns` of this inductor's own branch-current unknown.
36        branch: usize,
37        /// The declared value, in amperes, first node -> second node.
38        value: Expression,
39    },
40}
41
42impl InitialCondition {
43    /// The element the condition was declared on.
44    pub fn element(&self) -> &str {
45        match self {
46            Self::CapacitorVoltage { element, .. } | Self::InductorCurrent { element, .. } => {
47                element
48            }
49        }
50    }
51
52    /// The declared value, still symbolic.
53    pub fn value(&self) -> &Expression {
54        match self {
55            Self::CapacitorVoltage { value, .. } | Self::InductorCurrent { value, .. } => value,
56        }
57    }
58}
59
60/// A symbolic MNA descriptor system.
61#[derive(Debug, Clone, PartialEq)]
62pub struct MnaSystem {
63    /// Memoryless matrix in `A*x + K*dot(x) = B*u`.
64    pub a: Matrix<Expression>,
65    /// Storage matrix in `A*x + K*dot(x) = B*u`.
66    pub k: Matrix<Expression>,
67    /// Independent-source incidence matrix.
68    pub b: Matrix<Expression>,
69    /// Expanded right-hand-side vector using the source values from the netlist.
70    pub u: Vec<Expression>,
71    /// MNA unknown names in matrix order.
72    pub unknowns: Vec<String>,
73    /// Independent source names in `B` column order.
74    pub inputs: Vec<String>,
75    /// Source values in `inputs` order.
76    pub input_values: Vec<Expression>,
77    /// Every `V`/`I` source declared with a `SIN`/`PULSE`/`EXP`/`PWL`/`SFFM` transient
78    /// function, keyed by source name — such a source's own `input_values` entry is
79    /// `Expression::symbol(name)` (not a baked literal), so the caller must supply
80    /// `values.insert(name, transient_sources[name].value_at(t))` before every
81    /// [`MnaSystem::evaluate`] call, exactly the way a PWL diode's `{name}_Ioff` symbol
82    /// already has to be supplied per step — see `transient_source`'s own module doc comment.
83    /// Empty for a netlist with no such sources (every existing caller is unaffected).
84    pub transient_sources: BTreeMap<String, TransientFunction>,
85    /// Every `ic=` initial condition declared on a storage element, in netlist order, followed
86    /// by every `.IC V(node)=` / `.IC V(n1,n2)=` / `.IC I(inductor)=` assignment, in netlist
87    /// order (a `.IC` node voltage is a [`InitialCondition::CapacitorVoltage`] whose second
88    /// terminal is ground, labelled `.IC V(node)`). Empty for a netlist that declares none,
89    /// which is every netlist that predates the feature.
90    ///
91    /// These are *not* folded into `a`/`k`/`b`/`u` — the descriptor system is the circuit's
92    /// equations, and an initial condition is a statement about `x` at one instant, not about
93    /// the equations. Turn them into a consistent starting `x` with
94    /// [`MnaSystem::initial_state`], which is what a transient run actually needs.
95    pub initial_conditions: Vec<InitialCondition>,
96    /// Defaults collected from `.param` statements.
97    pub parameter_defaults: BTreeMap<String, Expression>,
98    /// Non-fatal build messages, primarily for deliberately ignored elements.
99    pub warnings: Vec<String>,
100    /// Every `key=value` field on a device card whose name the caller registered through
101    /// [`BuildOptions::annotate`](crate::BuildOptions::annotate), in netlist order.
102    ///
103    /// Like [`Self::initial_conditions`] these are *not* folded into `a`/`k`/`b`/`u`, and for
104    /// a stronger reason: an initial condition at least constrains `x`, whereas an annotation
105    /// says nothing about the circuit at all. It is a statement about the component — a
106    /// current rating, a part number, what to do when a limit is exceeded — carried from the
107    /// netlist to whoever asked for it.
108    ///
109    /// This crate does not interpret a single one of them. Values stay as written, because a
110    /// rating may be a number, an enum or a name, and parsing it belongs to the caller that
111    /// registered the field. Empty for a netlist that declares none, which is every netlist
112    /// built by a caller that registered nothing.
113    pub annotations: Vec<DeviceAnnotation>,
114}
115
116/// One registered `key=value` field read off a device card and carried through unexamined.
117///
118/// See [`MnaSystem::annotations`].
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct DeviceAnnotation {
121    /// The annotated element's name, as the netlist spells it (dotted-path-resolved when the
122    /// card came from inside a `.subckt`, like every other name this crate reports).
123    pub element: String,
124    /// Its SPICE device letter, so a consumer can tell an inductor's rating from a switch's
125    /// without re-parsing the deck.
126    pub device_letter: char,
127    /// The field name, lowercased — fields are case-insensitive in every SPICE dialect.
128    pub key: String,
129    /// The value exactly as written, including its suffix: `60`, `36u`, `console`.
130    pub value: String,
131    /// Line the card starts on, for a diagnostic that points at the netlist.
132    pub line: usize,
133}
134
135impl MnaSystem {
136    /// Number of MNA unknowns.
137    pub fn order(&self) -> usize {
138        self.unknowns.len()
139    }
140
141    /// Converts the system into strings suitable for a thin Python or WASM DTO.
142    pub fn to_string_system(&self) -> StringMnaSystem {
143        StringMnaSystem {
144            rows: self.order(),
145            inputs_count: self.inputs.len(),
146            a: self.a.iter().map(ToString::to_string).collect(),
147            k: self.k.iter().map(ToString::to_string).collect(),
148            b: self.b.iter().map(ToString::to_string).collect(),
149            u: self.u.iter().map(ToString::to_string).collect(),
150            unknowns: self.unknowns.clone(),
151            inputs: self.inputs.clone(),
152            input_values: self.input_values.iter().map(ToString::to_string).collect(),
153            parameter_defaults: self
154                .parameter_defaults
155                .iter()
156                .map(|(name, value)| (name.clone(), value.to_string()))
157                .collect(),
158            warnings: self.warnings.clone(),
159        }
160    }
161}
162
163/// Serialization-neutral string representation for language bindings.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct StringMnaSystem {
166    /// Number of rows and columns in `a` and `k`.
167    pub rows: usize,
168    /// Number of columns in `b`.
169    pub inputs_count: usize,
170    /// Row-major memoryless matrix.
171    pub a: Vec<String>,
172    /// Row-major storage matrix.
173    pub k: Vec<String>,
174    /// Row-major input-incidence matrix.
175    pub b: Vec<String>,
176    /// Expanded source vector.
177    pub u: Vec<String>,
178    /// Unknown names.
179    pub unknowns: Vec<String>,
180    /// Input names.
181    pub inputs: Vec<String>,
182    /// Netlist source values.
183    pub input_values: Vec<String>,
184    /// Netlist parameter defaults.
185    pub parameter_defaults: BTreeMap<String, String>,
186    /// Build warnings.
187    pub warnings: Vec<String>,
188}