# How Spice works

## Modified Nodal Analysis and Newton-Raphson

Spice uses Modified Nodal Analysis (MNA) to solve circuits. How it works is explored here: https://en.wikipedia.org/wiki/Modified_nodal_analysis. Basically, we can solve a whole circuit by solving the following linear system of equations (in matrix form):

$Y\cdot X=V$

Because we usually using a simulator for circuits with nonlinear components, MNA is modified to be an iterative solving method using Newton-Raphson (https://en.wikipedia.org/wiki/Newton's_method).

$X_{N+1}=X_N - Y^{-1}(X_N)\cdot V$

This system of equations still work for linear components, in which case the method converges in a single step. The Y-matrix is the Jacobian matrix.

This is modified somewhat for convenience in

$X_{N+1}=Y^{-1}(X_N)\cdot\left(Y(X_N)\cdot X_N-V_N \right)$

In Spice.NET, these variables are called:
$Matrix=Y(X_N)$
$Rhs=Y(X_N)\cdot X_N-V$

During each iteration, every instance will get a chance to add its contributions to the Matrix and Rhs. When all instances have finished loading the Matrix and Rhs properties, a solution is calculated.
Convergence is then tested by comparing the last solution to the current one. If the differences between the two are small enough, we stop iterating and accept the solution as the final one.

This is used when calculating the operating point for example.

## Integration

When integrating a variable from one time point to the next, we have to use some numerical methods. The first one being used is the Backward-Euler method:
$\dot{x}_{t_n}\approx\frac{x_{t_n}-x_{t_{n-1}}}{h_n}$
This method can be combined with MNA by adding extra contributions in the Matrix and Rhs properties.

For example, a capacitor will lead to the equations:
$i_C=C\cdot \frac{d(v_A-v_B)}{dt} \approx C\cdot \left(\frac{v_{A,t_n}-v_{A,t_{n-1}}}{h_n} - \frac{v_{B,t_n}-v_{B,t_{n-1}}}{h_n} \right )$

The solution at the last time point is known, and we are going to solve for vA and vB at the current timepoint. This equation can be filled in the Matrix and Rhs properties to compute the next time point.

There are some other fancy things going on during transient simulations. For example, the time step is controlled by looking at the Local Truncation Error (LTE) (You can find some nice slides about this here: http://www2.engr.arizona.edu/~ece570/session8.pdf).

Last edited Feb 10 at 2:53 PM by SBoulang, version 8