Skip to main content

MnaSystem

Struct MnaSystem 

Source
pub struct MnaSystem {
    pub a: Matrix<Expression>,
    pub k: Matrix<Expression>,
    pub b: Matrix<Expression>,
    pub u: Vec<Expression>,
    pub unknowns: Vec<String>,
    pub inputs: Vec<String>,
    pub input_values: Vec<Expression>,
    pub transient_sources: BTreeMap<String, TransientFunction>,
    pub initial_conditions: Vec<InitialCondition>,
    pub parameter_defaults: BTreeMap<String, Expression>,
    pub warnings: Vec<String>,
    pub annotations: Vec<DeviceAnnotation>,
}
Expand description

A symbolic MNA descriptor system.

Fields§

§a: Matrix<Expression>

Memoryless matrix in A*x + K*dot(x) = B*u.

§k: Matrix<Expression>

Storage matrix in A*x + K*dot(x) = B*u.

§b: Matrix<Expression>

Independent-source incidence matrix.

§u: Vec<Expression>

Expanded right-hand-side vector using the source values from the netlist.

§unknowns: Vec<String>

MNA unknown names in matrix order.

§inputs: Vec<String>

Independent source names in B column order.

§input_values: Vec<Expression>

Source values in inputs order.

§transient_sources: BTreeMap<String, TransientFunction>

Every V/I source declared with a SIN/PULSE/EXP/PWL/SFFM transient function, keyed by source name — such a source’s own input_values entry is Expression::symbol(name) (not a baked literal), so the caller must supply values.insert(name, transient_sources[name].value_at(t)) before every MnaSystem::evaluate call, exactly the way a PWL diode’s {name}_Ioff symbol already has to be supplied per step — see transient_source’s own module doc comment. Empty for a netlist with no such sources (every existing caller is unaffected).

§initial_conditions: Vec<InitialCondition>

Every ic= initial condition declared on a storage element, in netlist order, followed by every .IC V(node)= / .IC V(n1,n2)= / .IC I(inductor)= assignment, in netlist order (a .IC node voltage is a InitialCondition::CapacitorVoltage whose second terminal is ground, labelled .IC V(node)). Empty for a netlist that declares none, which is every netlist that predates the feature.

These are not folded into a/k/b/u — the descriptor system is the circuit’s equations, and an initial condition is a statement about x at one instant, not about the equations. Turn them into a consistent starting x with MnaSystem::initial_state, which is what a transient run actually needs.

§parameter_defaults: BTreeMap<String, Expression>

Defaults collected from .param statements.

§warnings: Vec<String>

Non-fatal build messages, primarily for deliberately ignored elements.

§annotations: Vec<DeviceAnnotation>

Every key=value field on a device card whose name the caller registered through BuildOptions::annotate, in netlist order.

Like Self::initial_conditions these are not folded into a/k/b/u, and for a stronger reason: an initial condition at least constrains x, whereas an annotation says nothing about the circuit at all. It is a statement about the component — a current rating, a part number, what to do when a limit is exceeded — carried from the netlist to whoever asked for it.

This crate does not interpret a single one of them. Values stay as written, because a rating may be a number, an enum or a name, and parsing it belongs to the caller that registered the field. Empty for a netlist that declares none, which is every netlist built by a caller that registered nothing.

Implementations§

Source§

impl MnaSystem

Source

pub fn evaluate( &self, values: &BTreeMap<String, f64>, ) -> Result<NumericMnaSystem, EvaluationError>

Evaluates component expressions using explicit values plus numeric .param defaults from the netlist.

Examples found in repository?
examples/rc_state_space.rs (line 15)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let netlist = "V1 in 0 1\nR1 in out R\nC1 out 0 C";
8    let symbolic = MnaBuilder::new(Dialect::Ngspice).build_fragment(netlist)?;
9
10    println!("unknowns: {:?}", symbolic.unknowns);
11    println!("A: {:?}", symbolic.to_string_system().a);
12    println!("K: {:?}", symbolic.to_string_system().k);
13
14    let values = BTreeMap::from([("R".into(), 1_000.0), ("C".into(), 1e-6)]);
15    let state_space = symbolic.evaluate(&values)?.to_state_space(1e-12)?;
16    println!("states: {:?}", state_space.states);
17    println!("state A: {:?}", state_space.a.as_slice());
18    println!("state B: {:?}", state_space.b.as_slice());
19    Ok(())
20}
Source§

impl MnaSystem

Source

pub fn initial_state( &self, values: &BTreeMap<String, f64>, tolerance: f64, ) -> Result<Option<Vec<f64>>, InitialStateError>

Turns this netlist’s declared ic= values into the starting state vector of a transient run, in unknowns order — the x at t = 0.

Returns Ok(None) when the netlist declares no ic= at all, so a caller can keep its existing “start from rest” default untouched rather than having to special-case an all-zero vector.

§It is an assignment, not a solve

This is what “use initial conditions” means: the operating point is skipped. The declared states are written into x, every other unknown starts at rest, and the system that actually gets solved — A, K, B, u — is not touched at all. No element is swapped for a source, nothing is opened or shorted, and no auxiliary unknown is introduced, so the unknowns ordering (a public contract of this crate) cannot move.

Concretely, the assigned unknowns are:

  • for an ic-bearing inductor, its own branch-current unknown I(<name>), set to ic;
  • for an ic-bearing capacitor, the difference between its two node voltages, which is not one unknown but two. Those capacitors are treated as a graph over nodes, one edge per declared ic, and each connected component’s potentials are propagated from a root at 0: ground when the component touches ground, otherwise the component’s lowest-indexed node. A series chain and a floating island therefore both come out right, and the result does not depend on the order the cards appear in.

Everything else — the other node voltages, every source’s branch current, every ic-free capacitor’s voltage — stays at 0. That is the visible difference from a constrained operating-point solve, which would let the rest of the circuit move to accommodate the declared value and would hand back an ic-free capacitor pre-charged by a circuit that has not run yet.

The vector this returns therefore need not satisfy the circuit’s algebraic constraints, exactly like any hand-built x_initial. That is a consumer’s problem to know about, not a defect: a first backward-Euler step re-imposes them.

§What is reported rather than silently overridden
  • ic= values that contradict each other — a loop of ic-bearing capacitors whose declared voltages do not sum to zero — are InitialStateError::ConflictingConditions.
  • An assignment that violates one of the circuit’s own algebraic equations, in which every unknown is fixed by an ic=, is InitialStateError::InconsistentWithCircuit. That covers an ic on a capacitor directly across an ideal voltage source, and series ic-bearing inductors declaring different currents. Only equations with no K row are checked, and only those all of whose unknowns are assigned: any equation with a free unknown in it, or with storage in it, is one the circuit can still satisfy and is not this method’s business.
§Sign conventions

Stated in full on InitialCondition, and worth repeating for the one that is routinely misremembered: an inductor’s ic is the current flowing from its first node to its second node, through the inductor. L1 a b 5e-6 ic=12 puts 12 A into a and out of b; L1 b a 5e-6 ic=12 is the opposite physical current.

values supplies any symbol the netlist left open, exactly as MnaSystem::evaluate takes it. tolerance is the relative residual threshold of the consistency check; see DEFAULT_INITIAL_STATE_TOLERANCE.

Source§

impl MnaSystem

Source

pub fn to_symbolic_state_space( &self, ) -> Result<SymbolicStateSpace, StateSpaceError>

Eliminates algebraic variables with a Schur complement, entirely symbolically: component values are never evaluated to numbers.

Dynamic variables are the MNA indices whose row in K is nonzero, exactly as in the numeric reduction. Pivoting is structural: at each elimination step we pick the first candidate row whose entry is not the literal expression 0 (there is no notion of “numerically small” for a symbolic tree). This reliably catches rows that were never stamped at all (e.g. a disconnected node), but it cannot catch a combination that is only zero because of how specific component symbols happen to cancel (e.g. a capacitor-only loop) — Expression does not combine like symbolic terms. That case instead surfaces as crate::EvaluationError::DivisionByZero when a coefficient is later evaluated at concrete parameter values, which is an acceptable and correctly-reported place to find it.

Source§

impl MnaSystem

Source

pub fn order(&self) -> usize

Number of MNA unknowns.

Source

pub fn to_string_system(&self) -> StringMnaSystem

Converts the system into strings suitable for a thin Python or WASM DTO.

Examples found in repository?
examples/rc_state_space.rs (line 11)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let netlist = "V1 in 0 1\nR1 in out R\nC1 out 0 C";
8    let symbolic = MnaBuilder::new(Dialect::Ngspice).build_fragment(netlist)?;
9
10    println!("unknowns: {:?}", symbolic.unknowns);
11    println!("A: {:?}", symbolic.to_string_system().a);
12    println!("K: {:?}", symbolic.to_string_system().k);
13
14    let values = BTreeMap::from([("R".into(), 1_000.0), ("C".into(), 1e-6)]);
15    let state_space = symbolic.evaluate(&values)?.to_state_space(1e-12)?;
16    println!("states: {:?}", state_space.states);
17    println!("state A: {:?}", state_space.a.as_slice());
18    println!("state B: {:?}", state_space.b.as_slice());
19    Ok(())
20}

Trait Implementations§

Source§

impl Clone for MnaSystem

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MnaSystem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for MnaSystem

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for MnaSystem

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.