general_mna/numeric.rs
1use std::collections::BTreeMap;
2use std::fmt;
3
4use crate::{EvaluationError, InitialCondition, Matrix, MnaSystem};
5
6/// Numerically evaluated descriptor system.
7#[derive(Debug, Clone, PartialEq)]
8pub struct NumericMnaSystem {
9 /// Memoryless matrix.
10 pub a: Matrix<f64>,
11 /// Storage matrix.
12 pub k: Matrix<f64>,
13 /// Independent-source incidence matrix.
14 pub b: Matrix<f64>,
15 /// Unknown names.
16 pub unknowns: Vec<String>,
17 /// Input names.
18 pub inputs: Vec<String>,
19 /// Source values in `inputs` order, evaluated the same way `a`/`k`/`b` are. Unlike
20 /// [`crate::MnaSystem::u`] (baked once, symbolically, at build time from each netlist
21 /// source's literal value), this is recomputed by every [`MnaSystem::evaluate`] call —
22 /// which matters for a source whose value genuinely changes between evaluations, such as
23 /// a piecewise-linear device's Norton-equivalent current (`{name}_Ioff`), rather than a
24 /// netlist-declared `V`/`I` source whose value never changes after parsing.
25 ///
26 /// Evaluating an input's value is best-effort, not required: a source whose symbol has no
27 /// entry in `values` (e.g. a duty ratio or `Vin` a caller only cares about symbolically,
28 /// while evaluating unrelated structural matrices) gets `f64::NAN` here rather than
29 /// failing the whole [`MnaSystem::evaluate`] call, matching this method's existing
30 /// behavior for `a`/`k`/`b` requiring only the symbols the caller actually supplied. `u`
31 /// below treats a `NAN` input as contributing `0.0`, not `NAN`, to every row.
32 pub input_values: Vec<f64>,
33 /// The expanded right-hand side `B * input_values`, in unknown order — the numeric twin
34 /// of [`crate::MnaSystem::u`], computed fresh from `input_values` above rather than from
35 /// the netlist's original (possibly stale) literal values. Rows depending only on inputs
36 /// that evaluated successfully are exact; see `input_values` above for the unresolved case.
37 pub u: Vec<f64>,
38}
39
40/// Explicit state-space system `dot(x) = A*x + B*u`.
41#[derive(Debug, Clone, PartialEq)]
42pub struct NumericStateSpace {
43 /// Dynamics matrix.
44 pub a: Matrix<f64>,
45 /// Input matrix.
46 pub b: Matrix<f64>,
47 /// Dynamic variable names.
48 pub states: Vec<String>,
49 /// Independent input names.
50 pub inputs: Vec<String>,
51 /// Indices of the dynamic variables in the original MNA vector.
52 pub mna_state_indices: Vec<usize>,
53}
54
55impl MnaSystem {
56 /// Evaluates component expressions using explicit values plus numeric
57 /// `.param` defaults from the netlist.
58 pub fn evaluate(
59 &self,
60 values: &BTreeMap<String, f64>,
61 ) -> Result<NumericMnaSystem, EvaluationError> {
62 let mut environment = BTreeMap::new();
63 for (name, expression) in &self.parameter_defaults {
64 if let Ok(value) = expression.evaluate(values) {
65 environment.insert(name.clone(), value);
66 }
67 }
68 environment.extend(values.iter().map(|(name, value)| (name.clone(), *value)));
69
70 let b = evaluate_matrix(&self.b, &environment)?;
71 let input_values: Vec<f64> = self
72 .input_values
73 .iter()
74 .map(|expression| expression.evaluate(&environment).unwrap_or(f64::NAN))
75 .collect();
76 let order = self.unknowns.len();
77 let mut u = vec![0.0; order];
78 for row in 0..order {
79 for (column, input_value) in input_values.iter().enumerate() {
80 if !input_value.is_nan() {
81 u[row] += b[(row, column)] * input_value;
82 }
83 }
84 }
85
86 Ok(NumericMnaSystem {
87 a: evaluate_matrix(&self.a, &environment)?,
88 k: evaluate_matrix(&self.k, &environment)?,
89 b,
90 unknowns: self.unknowns.clone(),
91 inputs: self.inputs.clone(),
92 input_values,
93 u,
94 })
95 }
96}
97
98/// Default residual tolerance for [`MnaSystem::initial_state`]'s consistency check, relative to
99/// the magnitude of the constraint row being checked. Matches the magnitude the state-space
100/// reduction in this module is normally called with; pass an explicit value for a circuit whose
101/// element values span a very different range.
102pub const DEFAULT_INITIAL_STATE_TOLERANCE: f64 = 1e-12;
103
104/// Why a netlist's declared `ic=` values could not be turned into a starting state vector.
105#[derive(Debug, Clone, PartialEq)]
106pub enum InitialStateError {
107 /// A component value, or an `ic=` value itself, could not be evaluated numerically.
108 Evaluation(EvaluationError),
109 /// Two or more `ic=` values on capacitors contradict each other, independently of the rest
110 /// of the circuit: they form a loop whose declared voltages do not sum to zero, so no
111 /// assignment of node voltages satisfies all of them at once.
112 ConflictingConditions {
113 /// The element whose condition closed the contradictory loop.
114 element: String,
115 /// The voltage the other conditions in the loop already imply across it, in the
116 /// orientation the loop was walked in — which may be the reverse of the card's own
117 /// node order, so compare it with `declared` rather than reading a polarity out of it.
118 implied: f64,
119 /// The voltage this element declares, in that same orientation.
120 declared: f64,
121 },
122 /// An assignment violates one of the circuit's own algebraic constraints — every unknown in
123 /// that constraint is fixed by an `ic=`, and the values they are fixed to do not satisfy it.
124 ///
125 /// The two textbook cases: an `ic` on a capacitor wired directly across an ideal voltage
126 /// source (the source's branch equation already fixes that voltage), and two series
127 /// inductors whose `ic` values declare different currents (the shared node's KCL row
128 /// already fixes them equal).
129 InconsistentWithCircuit {
130 /// The unknown whose equation is violated. A node voltage `V(n)` names that node's KCL
131 /// equation; a branch current `I(name)` names that device's own branch equation.
132 constraint: String,
133 /// The constraint's residual at the assigned state — how far from satisfied it is, in
134 /// the equation's own units.
135 residual: f64,
136 },
137}
138
139impl fmt::Display for InitialStateError {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 match self {
142 Self::Evaluation(error) => {
143 write!(f, "cannot evaluate the ic= initial state: {error}")
144 }
145 Self::ConflictingConditions {
146 element,
147 implied,
148 declared,
149 } => write!(
150 f,
151 "contradictory ic= values: '{element}' declares {declared} V across itself, but \
152 the other ic= conditions it forms a loop with already imply {implied} V in the \
153 same orientation"
154 ),
155 Self::InconsistentWithCircuit {
156 constraint,
157 residual,
158 } => write!(
159 f,
160 "the declared ic= values do not satisfy the circuit's own equation for \
161 {constraint} (residual {residual}); every unknown in that equation is fixed by \
162 an ic=, so nothing is left free to absorb the difference — check for an ic on a \
163 capacitor across an ideal voltage source, or series inductors declaring \
164 different currents"
165 ),
166 }
167 }
168}
169
170impl std::error::Error for InitialStateError {}
171
172impl From<EvaluationError> for InitialStateError {
173 fn from(error: EvaluationError) -> Self {
174 Self::Evaluation(error)
175 }
176}
177
178impl MnaSystem {
179 /// Turns this netlist's declared `ic=` values into the starting state vector of a transient
180 /// run, in `unknowns` order — the `x` at `t = 0`.
181 ///
182 /// Returns `Ok(None)` when the netlist declares no `ic=` at all, so a caller can keep its
183 /// existing "start from rest" default untouched rather than having to special-case an
184 /// all-zero vector.
185 ///
186 /// # It is an assignment, not a solve
187 ///
188 /// This is what "use initial conditions" means: the operating point is *skipped*. The
189 /// declared states are written into `x`, every other unknown starts at rest, and the system
190 /// that actually gets solved — `A`, `K`, `B`, `u` — is not touched at all. No element is
191 /// swapped for a source, nothing is opened or shorted, and no auxiliary unknown is
192 /// introduced, so the `unknowns` ordering (a public contract of this crate) cannot move.
193 ///
194 /// Concretely, the assigned unknowns are:
195 ///
196 /// - for an `ic`-bearing inductor, its own branch-current unknown `I(<name>)`, set to `ic`;
197 /// - for an `ic`-bearing capacitor, the *difference* between its two node voltages, which
198 /// is not one unknown but two. Those capacitors are treated as a graph over nodes, one
199 /// edge per declared `ic`, and each connected component's potentials are propagated from
200 /// a root at `0`: ground when the component touches ground, otherwise the component's
201 /// lowest-indexed node. A series chain and a floating island therefore both come out
202 /// right, and the result does not depend on the order the cards appear in.
203 ///
204 /// Everything else — the other node voltages, every source's branch current, every
205 /// `ic`-free capacitor's voltage — stays at `0`. That is the visible difference from a
206 /// constrained operating-point solve, which would let the rest of the circuit move to
207 /// accommodate the declared value and would hand back an `ic`-free capacitor pre-charged by
208 /// a circuit that has not run yet.
209 ///
210 /// The vector this returns therefore need not satisfy the circuit's algebraic constraints,
211 /// exactly like any hand-built `x_initial`. That is a consumer's problem to know about, not
212 /// a defect: a first backward-Euler step re-imposes them.
213 ///
214 /// # What is reported rather than silently overridden
215 ///
216 /// - `ic=` values that contradict *each other* — a loop of `ic`-bearing capacitors whose
217 /// declared voltages do not sum to zero — are [`InitialStateError::ConflictingConditions`].
218 /// - An assignment that violates one of the circuit's own algebraic equations, in which
219 /// every unknown is fixed by an `ic=`, is
220 /// [`InitialStateError::InconsistentWithCircuit`]. That covers an `ic` on a capacitor
221 /// directly across an ideal voltage source, and series `ic`-bearing inductors declaring
222 /// different currents. Only equations with no `K` row are checked, and only those all of
223 /// whose unknowns are assigned: any equation with a free unknown in it, or with storage
224 /// in it, is one the circuit can still satisfy and is not this method's business.
225 ///
226 /// # Sign conventions
227 ///
228 /// Stated in full on [`InitialCondition`], and worth repeating for the one that is
229 /// routinely misremembered: an inductor's `ic` is the current flowing **from its first
230 /// node to its second node, through the inductor**. `L1 a b 5e-6 ic=12` puts 12 A into `a`
231 /// and out of `b`; `L1 b a 5e-6 ic=12` is the opposite physical current.
232 ///
233 /// `values` supplies any symbol the netlist left open, exactly as
234 /// [`MnaSystem::evaluate`] takes it. `tolerance` is the relative residual threshold of the
235 /// consistency check; see [`DEFAULT_INITIAL_STATE_TOLERANCE`].
236 pub fn initial_state(
237 &self,
238 values: &BTreeMap<String, f64>,
239 tolerance: f64,
240 ) -> Result<Option<Vec<f64>>, InitialStateError> {
241 if self.initial_conditions.is_empty() {
242 return Ok(None);
243 }
244
245 let order = self.unknowns.len();
246 let mut environment = BTreeMap::new();
247 for (name, expression) in &self.parameter_defaults {
248 if let Ok(value) = expression.evaluate(values) {
249 environment.insert(name.clone(), value);
250 }
251 }
252 environment.extend(values.iter().map(|(name, value)| (name.clone(), *value)));
253
254 let mut x = vec![0.0; order];
255 let mut assigned = vec![false; order];
256
257 for condition in &self.initial_conditions {
258 let InitialCondition::InductorCurrent { branch, value, .. } = condition else {
259 continue;
260 };
261 x[*branch] = value.evaluate(&environment)?;
262 assigned[*branch] = true;
263 }
264
265 assign_capacitor_potentials(
266 &self.initial_conditions,
267 &environment,
268 tolerance,
269 &mut x,
270 &mut assigned,
271 )?;
272
273 let numeric = self.evaluate(values)?;
274 check_assignment_against_circuit(&numeric, &x, &assigned, tolerance)?;
275
276 Ok(Some(x))
277 }
278}
279
280/// Propagates the node potentials implied by every `ic`-bearing capacitor.
281///
282/// Each condition is an edge `v(positive) - v(negative) = ic` over the node unknowns, with
283/// ground as an extra vertex pinned at `0`. Every connected component is walked breadth-first
284/// from a root held at `0` — ground when the component contains it, otherwise the component's
285/// lowest-indexed node, since a floating island's absolute potential is not something the
286/// netlist declared and any choice is as good as another. An edge that closes a loop with a
287/// mismatching sum is a contradiction between the conditions themselves and is reported.
288/// A vertex of the `ic`-bearing-capacitor graph: an index into `unknowns` for a node voltage, or
289/// `None` for ground, which is not an unknown and is always at zero.
290type PotentialNode = Option<usize>;
291
292/// One edge of that graph, as stored on the vertex it leaves: the vertex it reaches, the voltage
293/// `v(this) - v(that)` the condition declares *in that direction*, and the element that declared
294/// it, for diagnostics. Each condition contributes two, one per direction.
295type PotentialEdge<'a> = (PotentialNode, f64, &'a str);
296
297fn assign_capacitor_potentials(
298 conditions: &[InitialCondition],
299 environment: &BTreeMap<String, f64>,
300 tolerance: f64,
301 x: &mut [f64],
302 assigned: &mut [bool],
303) -> Result<(), InitialStateError> {
304 let mut edges: BTreeMap<PotentialNode, Vec<PotentialEdge<'_>>> = BTreeMap::new();
305 for condition in conditions {
306 let InitialCondition::CapacitorVoltage {
307 element,
308 positive,
309 negative,
310 value,
311 } = condition
312 else {
313 continue;
314 };
315 let volts = value.evaluate(environment)?;
316 edges
317 .entry(*positive)
318 .or_default()
319 .push((*negative, volts, element.as_str()));
320 edges
321 .entry(*negative)
322 .or_default()
323 .push((*positive, -volts, element.as_str()));
324 }
325
326 let mut potential: BTreeMap<PotentialNode, f64> = BTreeMap::new();
327 // `BTreeMap` iteration puts `None` (ground) first and then ascending node indices, which is
328 // exactly the root order this method documents.
329 let roots: Vec<PotentialNode> = edges.keys().copied().collect();
330 for root in roots {
331 if potential.contains_key(&root) {
332 continue;
333 }
334 potential.insert(root, 0.0);
335 let mut queue = std::collections::VecDeque::from([root]);
336 while let Some(node) = queue.pop_front() {
337 let here = potential[&node];
338 for (neighbor, delta, element) in edges.get(&node).into_iter().flatten() {
339 // `delta` is `v(node) - v(neighbor)` as stored above.
340 let implied = here - delta;
341 match potential.get(neighbor) {
342 Some(known) => {
343 let scale = known.abs().max(implied.abs()).max(1.0);
344 if (known - implied).abs() > tolerance * scale {
345 return Err(InitialStateError::ConflictingConditions {
346 element: (*element).to_string(),
347 implied: here - known,
348 declared: *delta,
349 });
350 }
351 }
352 None => {
353 potential.insert(*neighbor, implied);
354 queue.push_back(*neighbor);
355 }
356 }
357 }
358 }
359 }
360
361 for (node, volts) in potential {
362 if let Some(index) = node {
363 x[index] = volts;
364 assigned[index] = true;
365 }
366 }
367 Ok(())
368}
369
370/// Reports an assignment that violates one of the circuit's own algebraic equations.
371///
372/// Only rows with an all-zero `K` row are checked: a row with storage in it describes a
373/// derivative this method says nothing about, so its residual at `t = 0` is not a contradiction
374/// — it is the current that starts flowing. And within those rows, only the ones every one of
375/// whose unknowns is assigned: a row with a free unknown left in it is a row the circuit can
376/// still satisfy on its own, and the first solved step is where that happens.
377fn check_assignment_against_circuit(
378 numeric: &crate::NumericMnaSystem,
379 x: &[f64],
380 assigned: &[bool],
381 tolerance: f64,
382) -> Result<(), InitialStateError> {
383 let order = x.len();
384 for row in 0..order {
385 if (0..order).any(|col| numeric.k[(row, col)] != 0.0) {
386 continue;
387 }
388 let contributing: Vec<usize> = (0..order)
389 .filter(|col| numeric.a[(row, *col)] != 0.0)
390 .collect();
391 // A *state* is determined whether or not it carries an `ic`: `initial_state` starts
392 // every unknown at zero and only overwrites the ones an `ic` names, so an `ic`-free
393 // inductor current is pinned at zero, not free. Nothing re-solves it -- the integrator
394 // takes that zero as the initial current -- so a row containing it is fully determined
395 // and its residual is a real contradiction. Treating it as free is what let an
396 // inductor cut-set with an `ic` on some of its branches and not others be accepted
397 // silently, starting 134% away from the requested current.
398 //
399 // Dynamic variables are the indices whose row in `K` is nonzero, the same test
400 // `schur_complement` uses.
401 // Restricted to inductor *branch currents*, which are the states nothing re-solves. A
402 // capacitor's node voltage is also a state started at zero, but it is shared with the
403 // resistive network and the first step genuinely does re-impose it -- treating it as
404 // determined rejects `V1 a 0 400` + an `ic`-free capacitor on `a` with residual -400,
405 // which is the documented and correct behaviour, not a contradiction. Measured: that
406 // over-reach rejected 12 of 40 of this project's own committed decks.
407 //
408 // An inductor branch current is `I(...)` with storage: a voltage source's branch
409 // current is also `I(...)` but has an all-zero `K` row, and a capacitor node voltage
410 // has storage but is `V(...)`.
411 let determined = |col: usize| {
412 assigned[col]
413 || (numeric.unknowns[col].starts_with("I(")
414 && (0..order).any(|j| numeric.k[(col, j)] != 0.0))
415 };
416 if contributing.is_empty() || !contributing.iter().all(|col| determined(*col)) {
417 continue;
418 }
419 let mut residual = -numeric.u[row];
420 let mut scale = numeric.u[row].abs();
421 for col in contributing {
422 let term = numeric.a[(row, col)] * x[col];
423 residual += term;
424 scale = scale.max(term.abs());
425 }
426 if residual.abs() > tolerance * scale.max(1.0) {
427 return Err(InitialStateError::InconsistentWithCircuit {
428 constraint: numeric.unknowns[row].clone(),
429 residual,
430 });
431 }
432 }
433 Ok(())
434}
435
436impl NumericMnaSystem {
437 /// Eliminates algebraic variables with a Schur complement.
438 ///
439 /// Dynamic variables are the MNA indices whose row in `K` is nonzero.
440 /// This matches capacitor-node voltages and inductor branch currents for
441 /// the linear stamps produced by this crate.
442 pub fn to_state_space(&self, tolerance: f64) -> Result<NumericStateSpace, StateSpaceError> {
443 let order = self.unknowns.len();
444 if self.a.rows() != order
445 || self.a.cols() != order
446 || self.k.rows() != order
447 || self.k.cols() != order
448 || self.b.rows() != order
449 {
450 return Err(StateSpaceError::InconsistentDimensions);
451 }
452
453 let state_indices: Vec<usize> = (0..order)
454 .filter(|row| (0..order).any(|col| self.k[(*row, col)].abs() > tolerance))
455 .collect();
456 if state_indices.is_empty() {
457 return Err(StateSpaceError::NoDynamicVariables);
458 }
459 let algebraic_indices: Vec<usize> = (0..order)
460 .filter(|index| !state_indices.contains(index))
461 .collect();
462
463 let a_ss = extract(&self.a, &state_indices, &state_indices);
464 let k_ss = extract(&self.k, &state_indices, &state_indices);
465 let b_s = extract_rows(&self.b, &state_indices);
466
467 let (a_reduced, b_reduced) = if algebraic_indices.is_empty() {
468 (a_ss, b_s)
469 } else {
470 let a_sa = extract(&self.a, &state_indices, &algebraic_indices);
471 let a_as = extract(&self.a, &algebraic_indices, &state_indices);
472 let a_aa = extract(&self.a, &algebraic_indices, &algebraic_indices);
473 let b_a = extract_rows(&self.b, &algebraic_indices);
474 let solved_as = solve(&a_aa, &a_as, tolerance).map_err(|pivot| {
475 StateSpaceError::singular_algebraic(&self.unknowns, &algebraic_indices, pivot)
476 })?;
477 let solved_b = solve(&a_aa, &b_a, tolerance).map_err(|pivot| {
478 StateSpaceError::singular_algebraic(&self.unknowns, &algebraic_indices, pivot)
479 })?;
480 (
481 subtract(&a_ss, &multiply(&a_sa, &solved_as)),
482 subtract(&b_s, &multiply(&a_sa, &solved_b)),
483 )
484 };
485
486 let negative_a = a_reduced.map(|value| -*value);
487 let state_a = solve(&k_ss, &negative_a, tolerance).map_err(|pivot| {
488 StateSpaceError::singular_storage(&self.unknowns, &state_indices, pivot)
489 })?;
490 let state_b = solve(&k_ss, &b_reduced, tolerance).map_err(|pivot| {
491 StateSpaceError::singular_storage(&self.unknowns, &state_indices, pivot)
492 })?;
493
494 Ok(NumericStateSpace {
495 a: state_a,
496 b: state_b,
497 states: state_indices
498 .iter()
499 .map(|index| self.unknowns[*index].clone())
500 .collect(),
501 inputs: self.inputs.clone(),
502 mna_state_indices: state_indices,
503 })
504 }
505}
506
507fn evaluate_matrix(
508 matrix: &Matrix<crate::Expression>,
509 values: &BTreeMap<String, f64>,
510) -> Result<Matrix<f64>, EvaluationError> {
511 let data = matrix
512 .iter()
513 .map(|expression| expression.evaluate(values))
514 .collect::<Result<Vec<_>, _>>()?;
515 Ok(Matrix::from_vec(matrix.rows(), matrix.cols(), data)
516 .expect("mapping a matrix preserves its shape"))
517}
518
519fn extract(matrix: &Matrix<f64>, rows: &[usize], cols: &[usize]) -> Matrix<f64> {
520 let mut result = Matrix::filled(rows.len(), cols.len(), 0.0);
521 for (target_row, source_row) in rows.iter().enumerate() {
522 for (target_col, source_col) in cols.iter().enumerate() {
523 result[(target_row, target_col)] = matrix[(*source_row, *source_col)];
524 }
525 }
526 result
527}
528
529fn extract_rows(matrix: &Matrix<f64>, rows: &[usize]) -> Matrix<f64> {
530 let columns: Vec<usize> = (0..matrix.cols()).collect();
531 extract(matrix, rows, &columns)
532}
533
534fn multiply(lhs: &Matrix<f64>, rhs: &Matrix<f64>) -> Matrix<f64> {
535 assert_eq!(lhs.cols(), rhs.rows());
536 let mut result = Matrix::filled(lhs.rows(), rhs.cols(), 0.0);
537 for row in 0..lhs.rows() {
538 for col in 0..rhs.cols() {
539 result[(row, col)] = (0..lhs.cols())
540 .map(|inner| lhs[(row, inner)] * rhs[(inner, col)])
541 .sum();
542 }
543 }
544 result
545}
546
547fn subtract(lhs: &Matrix<f64>, rhs: &Matrix<f64>) -> Matrix<f64> {
548 assert_eq!((lhs.rows(), lhs.cols()), (rhs.rows(), rhs.cols()));
549 Matrix::from_vec(
550 lhs.rows(),
551 lhs.cols(),
552 lhs.iter()
553 .zip(rhs.iter())
554 .map(|(left, right)| left - right)
555 .collect(),
556 )
557 .expect("zipped equal matrices preserve shape")
558}
559
560/// Solves `coefficients * x = rhs` by Gauss-Jordan elimination with partial
561/// pivoting. On failure, returns the index (within `coefficients`) of the
562/// column that had no usable pivot, so callers can report which unknown the
563/// singularity localizes to.
564fn solve(
565 coefficients: &Matrix<f64>,
566 rhs: &Matrix<f64>,
567 tolerance: f64,
568) -> Result<Matrix<f64>, usize> {
569 let n = coefficients.rows();
570 if coefficients.cols() != n || rhs.rows() != n {
571 return Err(0);
572 }
573 let rhs_cols = rhs.cols();
574 let mut augmented = Matrix::filled(n, n + rhs_cols, 0.0);
575 for row in 0..n {
576 for col in 0..n {
577 augmented[(row, col)] = coefficients[(row, col)];
578 }
579 for col in 0..rhs_cols {
580 augmented[(row, n + col)] = rhs[(row, col)];
581 }
582 }
583
584 for pivot_col in 0..n {
585 let pivot_row = (pivot_col..n)
586 .max_by(|left, right| {
587 augmented[(*left, pivot_col)]
588 .abs()
589 .total_cmp(&augmented[(*right, pivot_col)].abs())
590 })
591 .ok_or(pivot_col)?;
592 if augmented[(pivot_row, pivot_col)].abs() <= tolerance {
593 return Err(pivot_col);
594 }
595 if pivot_row != pivot_col {
596 for col in 0..n + rhs_cols {
597 let temporary = augmented[(pivot_col, col)];
598 augmented[(pivot_col, col)] = augmented[(pivot_row, col)];
599 augmented[(pivot_row, col)] = temporary;
600 }
601 }
602
603 let pivot = augmented[(pivot_col, pivot_col)];
604 for col in pivot_col..n + rhs_cols {
605 augmented[(pivot_col, col)] /= pivot;
606 }
607 for row in 0..n {
608 if row == pivot_col {
609 continue;
610 }
611 let factor = augmented[(row, pivot_col)];
612 for col in pivot_col..n + rhs_cols {
613 augmented[(row, col)] -= factor * augmented[(pivot_col, col)];
614 }
615 }
616 }
617
618 let mut result = Matrix::filled(n, rhs_cols, 0.0);
619 for row in 0..n {
620 for col in 0..rhs_cols {
621 result[(row, col)] = augmented[(row, n + col)];
622 }
623 }
624 Ok(result)
625}
626
627/// Error returned during descriptor-to-state-space reduction.
628#[derive(Debug, Clone, PartialEq, Eq)]
629pub enum StateSpaceError {
630 /// Matrix and name dimensions do not agree.
631 InconsistentDimensions,
632 /// No row of the storage matrix is dynamic.
633 NoDynamicVariables,
634 /// Algebraic constraints cannot be uniquely eliminated.
635 SingularAlgebraicBlock {
636 /// The algebraic unknown whose equation had no usable pivot.
637 unknown: String,
638 /// All algebraic unknowns considered in the same elimination.
639 block: Vec<String>,
640 },
641 /// The reduced storage (capacitor/inductor) block is singular: the
642 /// circuit has fewer independent dynamic states than reactive elements.
643 SingularStorageBlock {
644 /// The state variable that turned out not to be independent.
645 unknown: String,
646 /// All capacitor-voltage/inductor-current states in the same block.
647 block: Vec<String>,
648 },
649}
650
651impl StateSpaceError {
652 pub(crate) fn singular_algebraic(unknowns: &[String], indices: &[usize], pivot: usize) -> Self {
653 Self::SingularAlgebraicBlock {
654 unknown: unknowns[indices[pivot]].clone(),
655 block: indices
656 .iter()
657 .map(|index| unknowns[*index].clone())
658 .collect(),
659 }
660 }
661
662 pub(crate) fn singular_storage(unknowns: &[String], indices: &[usize], pivot: usize) -> Self {
663 Self::SingularStorageBlock {
664 unknown: unknowns[indices[pivot]].clone(),
665 block: indices
666 .iter()
667 .map(|index| unknowns[*index].clone())
668 .collect(),
669 }
670 }
671}
672
673impl fmt::Display for StateSpaceError {
674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675 match self {
676 Self::InconsistentDimensions => f.write_str("inconsistent MNA matrix dimensions"),
677 Self::NoDynamicVariables => {
678 f.write_str("the circuit has no capacitor or inductor state")
679 }
680 Self::SingularAlgebraicBlock { unknown, block } => write!(
681 f,
682 "no unique solution for {unknown}: the algebraic (non-storage) equations for {{{}}} are linearly dependent — check for a loop of ideal voltage sources/VCVS elements or a cut-set of ideal current sources/VCCS elements among them",
683 block.join(", "),
684 ),
685 Self::SingularStorageBlock { unknown, block } => {
686 let hint = if unknown.starts_with("V(") {
687 "a capacitor-only loop with no resistive path, so its voltage is not independent of the others — add a series resistor to break the loop"
688 } else {
689 "an inductor-only cut-set with no resistive path, so its current is not independent of the others (or a redundant coupled-inductor `K` specification) — add a parallel resistor or check the coupling coefficients"
690 };
691 write!(
692 f,
693 "{unknown} is not an independent state variable among {{{}}}: likely {hint}",
694 block.join(", "),
695 )
696 }
697 }
698 }
699}
700
701impl std::error::Error for StateSpaceError {}