:experimental:
[[simulator]]
== Simulator ==

KiCad provides an embedded electrical circuit simulator using
http://ngspice.sourceforge.net[ngspice] as the simulation engine. All but the
simplest simulations will require you to add simulation models to your symbols
before you can simulate your schematic.

When working with the simulator, the official `Simulation_SPICE` symbol library
may be useful. It contains common symbols used for simulation, like
voltage/current sources and transistors with pins numbered to match the ngspice
node order specification.

KiCad includes a few demo projects to illustrate the simulator's capabilities.
They can be found in the `demos/simulation` directory.

=== Value notation
The simulator supports several notations for writing numerical values:

* Plain notation : `10100`, `0.003`,
* Scientific notation: `1.01e4`, `3e-3`,
* Prefix notation: `10.1k`, `3m`.
* RKM notation: `4k7`, `10R`.

You can mix prefix and scientific notations. As such, `3e-4k` is a
valid input and is equivalent to `0.3`. The list of valid prefixes is shown
below. The prefixes are case sensitive.

[width="50%",cols="1,1,1",]
|====
| Prefix | Meaning | Value

| a | atto | 10^-18^ 
| f | femto | 10^-15^ 
| p | pico | 10^-12^ 
| n | nano | 10^-9^ 
| u | micro | 10^-6^ 
| m | milli | 10^-3^ 
| k | kilo | 10^3^ 
| M | mega | 10^6^ 
| G | giga | 10^9^ 
| T | tera | 10^12^ 
| P | peta | 10^15^ 
| E | exa | 10^15^ 
|====

[NOTE]
<<sim-builtin,Raw SPICE Element>> models and <<sim-directives,directives>> are
passed to ngspice directly, without KiCad reformatting the values for ngspice to
consume. Ngspice uses a different, case-insensitive notation: 1 mega (10^6^) is
denoted there as `1Meg`, while `1M` is 1 milli (10^-3^). Depending on the
compatibility mode selected, ngspice may not support the same value notations as
KiCad, so care should be taken when using raw SPICE elements and simulation
directives.

=== Assigning models

You need to assign simulation models to symbols before you can simulate your
circuit.

Each symbol can have only one model assigned, even if the symbol consists of
multiple units. For symbols with multiple units, you should assign the model to
the first unit.

SPICE model information is stored as text in symbol fields. Therefore you may
define it in either the symbol editor or the schematic editor. To assign a
simulation model to a symbol, open the Symbol Properties dialog and click the
**Simulation Model...** button, which opens the Simulation Model Editor dialog.

You can exclude a symbol from simulation entirely by checking the
**exclude from simulation** checkbox in the Symbol Properties dialog.

[[sim-inferred]]
==== Inferred models

Resistor, inductor, and capacitor models can be inferred, which means that KiCad
will detect that they are passives and automatically assign an appropriate
simulation model. Therefore they do not require any special settings; users only
need to set the `Value` field of the symbol.

KiCad infers simulation models for symbols based on the following criteria:

* The symbol has exactly two pins,
* The reference designator begins with `R`, `L` or `C`.

Inferred models are ideal models. If the simulation requires a non-ideal model,
you must explicitly assign a model.

[[sim-built-in]]
==== Built-in models
KiCad offers several standard simulation models. They do not require an external
model file. The following devices are available:

* Resistors (including potentiometers), capacitors, inductors
* Transmission lines
* Switches
* Voltage and current sources
* Diodes
* Transistors (BJT, MOSFET, MESFET, and JFET)
//* XSPICE code models
* Raw SPICE elements

// TODO: XSPICE code models may not exist in v7

To add a built-in model to a symbol, open the Simulation Model Editor dialog
(**Symbol Properties** -> **Simulation Model...**) and select
**Built-in SPICE model**.

Refer to the https://ngspice.sourceforge.io/docs.html[ngspice documentation] for
more details about these models.

image::images/sim_SME_builtin.png[alt="Interface to set-up built-in models"]

**Device** sets the type of device to simulate: a resistor, BJT, voltage source,
etc. This value is stored in the symbol's `Sim.Device` field.

**Type** selects the type of model to use for the device. Most devices have
several types of models to choose from, which may vary in their degree of
accuracy, which characteristics they are optimized for, and what parameters they
have available. Refer to the ngspice documentation for details. This value is
stored in the symbol's `Sim.Type` field.

The **parameters** tab displays the parameters of the model and lets you edit
them. For example, a resistor's resistance, a voltage source's waveform, a
MOSFET's width and length, etc. Any parameters that differ from the model's
defaults are stored in the symbol's `Sim.Params` field.

The **code** tab displays the generated SPICE model as it will be written to the
SPICE netlist for simulation.

The **Save parameter '<parameter name>' in Value field** checkbox uses the
symbol's `Value` field for storing parameters instead of the `Sim.Params` field.
This may make it easier to edit simple models from the schematic, without
opening the Simulation Model Editor. This option is only available for ideal
passive models (R, L, C) and DC sources. If the field `Sim.Params` exists in the
symbol, it will take priority over the `Value` field.

[[sim-library]]
==== Library models

KiCad can load SPICE models from external files. The models must be in a
standard SPICE format and not encrypted.

To load a model from an external file, open the Simulation Model Editor dialog
(**Symbol Properties** -> **Simulation Model...**) and select
**SPICE model from file**.

image::images/sim_SME_from_file.png[alt="Interface to set-up library models from file"]

**File** is the path to the model file to use. The path can be absolute or
relative to the project folder. The path can also be relative to the value of 
`SPICE_LIB_DIR` if you have
xref:../kicad/kicad.adoc#kicad-environment-variables[defined that path variable].
The library filename is saved in the symbol's `Sim.Library` field.

**Model** is the name of the desired model in the model file. If the file
contains multiple models, they will all be listed in the dropdown. The selected
model is listed in the symbol's `Sim.Name` field.

Parameters can be overridden (or additional parameters specified) using
the **parameters** tab. All parameters specified in the selected model or the
**parameters** tab are stored in the symbol's `Sim.Params` field.

The **code** tab displays the generated SPICE model as it will be written to the
SPICE netlist for simulation.

[NOTE]
KiCad does not ship with SPICE models for symbols. SPICE models are usually
available from device manufacturers.

[[ibis-library]]
==== Library models (IBIS)

IBIS (I/O Buffer Information Specification) files are an alternative to SPICE
models for modeling the behavior of input/output buffers on digital parts. In
order to load an IBIS file, users should follow the procedure for SPICE library
models, but provide a `.ibs` file.

image::images/sim_SME_ibis.png[alt="Interface to set-up ibis models"]

**File** is the path to the model file to use. The path can be absolute or
relative to the project folder. The path can also be relative to the value of
`SPICE_LIB_DIR` if you have
xref:../kicad/kicad.adoc#kicad-environment-variables[defined that path variable].
The library filename is saved in the symbol's `Sim.Library` field. If an IBIS
model file is loaded, the remaining fields in the dialog will relate to the IBIS
model.

**Component** selects which component from the IBIS file to use, as IBIS files
can contain multiple components. The component name is saved in the symbol's
`Sim.Name` field.

// TODO, mention "differential" checkbox
**Pin** selects which pin in the IBIS model to simulate. The selected pin must
be mapped to a symbol pin in the **Pin Assignments** tab. The chosen pin's
number is saved in the symbol's `Sim.Ibis.Pin` field.

**Model** is the list of models available for the selected pin, for example an
input or an output. The chosen model name is saved in the symbol's
`Sim.Ibis.Model` field.

**Type** selects what the pin should do in the simulation. A pin can be a passive
**device** that doesn't drive any value; it can be a **DC driver** that drives
high, low, or high-impedance; or it can be a **rectangular wave** or
**PRBS driver**.  This value is stored in the symbol's `Sim.Type` field.

The **Parameters** tab lets you see and edit the parameters of the model. For
each parameter, you can switch between a minimum, typical, or maximum value, as
defined in the IBIS file. You can also choose the parameters of the driven
waveform, depending on the pin's chosen **type**. Any parameters that differ
from the defaults are stored in the symbol's `Sim.Params` field.

[NOTE]
KiCad does not ship with IBIS models for symbols. IBIS models are usually
available from device manufacturers.

[NOTE]
KiCad's `Simulation_SPICE` symbol library provides several symbols that may be
useful for IBIS simulations. `IBIS_DEVICE` can be used for device (input) pins,
while `IBIS_DRIVER` can be used for simulating driver pins. There are also
variants of each for differential pins.

==== Pin Assignment

Simulation models may have their pins numbered differently than the
corresponding symbol. For example, SPICE models for diodes usually consider
pin 1 to be the anode, while schematic symbols are usually drawn with pin 1 as
the cathode.

You can use the Simulation Model Editor's **Pin Assignments** tab to map the
symbol's pins to the simulation model pins.

NOTE: Always make sure symbol pins are correctly mapped to simulation model
      pins.

image::images/sim_SME_pin.png[alt="Interface for pin assignment"]

The left column displays the name and number of each symbol pin. For each symbol
pin, you can select the corresponding pin from the simulation model in the
dropdown in the right column.

When you use a subcircuit model, the dialog displays the model's code under the
pin assignments for use as a reference while assigning pins.

[[sim-directives]]
=== SPICE directives

It is possible to add SPICE directives by placing them in text fields on a
schematic sheet. This approach is convenient for defining the default
simulation type. The list of supported directives in text fields is:

* Directives starting with a dot (e.g. `.tran 10n 1m`)
* Coupling coefficients for inductors (e.g. `K1 L1 L2 0.89`)

It is not possible to place additional components using text fields.

If a simulation command is included in schematic text, the simulator will use
it as the simulation command when you open the simulator. However, you can
override it in the Simulation Command dialog.

Refer to the https://ngspice.sourceforge.io/docs.html[ngspice documentation] for
more details about SPICE directives.

=== Running simulations

==== User Interface

To run a simulation, open the SPICE simulator dialog by clicking 
**Inspect** -> **Simulator** in the schematics editor window or using the
image:images/icons/simulator_24.png[simulator icon] button in the top toolbar.

image::images/sim_main_dialog.png[alt="Main simulation dialog"]

The dialog is divided into several sections:

* The top of the window has a toolbar with buttons for commonly used actions.

* The main part of the window graphically shows the simulation results. Signals
  need to be probed before they are displayed in the plot.

* Below the plot panel, the output console shows logs from the ngspice simulation
engine.

* The right side of the window displays a list of plotted signals, a list of
  active cursors, and a tuning tool for adjusting component values based on
  simulation results.

==== Workbooks

Workbooks are files that store information about the simulation environment,
including simulation setup parameters and the list of displayed signals.
They can be used to store the setup for a set of analyses, which can then be
reloaded and rerun at a later time.

You can save and load a workbook using **File** -> **Save Workbook** and
**File** -> **Open Workbook**.

NOTE: Workbooks store simulation setup information, but they do not store
      simulation results. You can export simulation results to PNG (graphics) or
      CSV (data points) with **File** -> **Export Current Plot as PNG...** and
      **File** -> **Export Current Plot as CSV...**.

==== Running a Simulation

Before running a simulation, you need to select a simulation type and choose the
simulation parameters. This can be done using **Simulation** -> **Settings...**
or the **Sim Command** button (image:images/icons/config_24.png[]) and then
selecting one of the available analysis types:

* AC
* DC Transfer
* Operating Point
* Transient
* Custom

Analysis types are further explained in the https://ngspice.sourceforge.io/docs.html[ngspice documentation].

An alternative way to configure a simulation is to type
<<sim-directives,SPICE directives>> into text fields on schematics. Any text
field directives related to a simulation command are overridden by the settings
selected in the dialog. This means that once a simulation has run, the dialog
overrides the schematic directives until the simulator is reopened.

Once the simulation command is set, users can start a simulation with
**Simulation** -> **Start Simulation** (kbd:[Ctrl+R]) or the
**Run/Stop Simulation** button
(image:images/icons/sim_run_24.png[run simulation icon]).

===== AC analysis

image::images/sim_analysis_ac.png[alt="AC analysis window", scaledwidth="80%"]

Calculates the small signal AC behavior of the circuit in response to a
stimulus. Performs a decade sweep of stimulus frequency.

To run an AC analysis, you must choose a number of points to measure per decade
and the start and end frequencies for the decade sweep.

The output is displayed as a Bode plot (output magnitude and phase vs. a decade
sweep of stimulus frequency).

===== DC transfer analysis

image::images/sim_analysis_dc.png[alt="DC analysis window", scaledwidth="80%"]

Calculates the DC behavior of the circuit while sweeping one or two sources
(voltage or current), resistors, or the simulation temperature.

To run a DC analysis, you must choose what type of sweep(s) to perform, which
source, resistor, or temperature value(s) to sweep, and what the sweep range(s)
and step(s) should be.

The output is displayed as a plot.

===== Operating point analysis

Calculates the DC operating point of the circuit. This analysis has no options,
and results are printed to the SPICE log.

===== Transient analysis

image::images/sim_analysis_tran.png[alt="Transient analysis window", scaledwidth="80%"]

Calculates the time-varying behavior of the circuit.

To run a transient analysis, you need to specify a suggested time step and a
final simulation time. You can optionally specify a starting time to override
the default of 0.

The output is displayed as a plot.

===== Custom analysis

image::images/sim_analysis_custom.png[alt="Custom analysis window", scaledwidth="80%"]

A custom analysis lets you write SPICE commands to set up the analysis. Press
the **Load directives from schematic** button to copy any SPICE directives in
schematic text into the custom analysis textbox.

Refer to the https://ngspice.sourceforge.io/docs.html[ngspice documentation] for
more information about analysis commands.

===== Additional simulation settings

There are several simulation options that apply to all types of simulations.

**Add full path for .include library directives** controls whether to convert
relative paths to absolute in `.include` directives in schematic text.

**Save all voltages** and **Save all currents** controls whether the simulator
saves voltages and currents, respectively, for internal nodes of devices. When
unchecked, the simulator only saves voltages and currents for external nodes.

The **Compatibility mode** dropdown selects the compatibility mode that the
simulator uses to load models. The **User configuration** option refers to the
user's `.spiceinit` ngspice configuration file. Compatibility modes are
described in the https://ngspice.sourceforge.io/docs.html[ngspice documentation].

==== Probing signals

===== Using the signal list

You can display a list of available signals with **Simulation** ->
**Add signals** (kbd:[Ctrl+A] hotkey or 
image:images/icons/sim_add_signal_24.png[add signal icon] button). Double
clicking an element in the list will add it to list of probed signals. Several
signals can be selected at once using the kbd:[Ctrl] / kbd:[Shift] keys.

===== Using the probe tool 

A probe tool is available in the toolbar of the simulator window
(image:images/icons/sim_probe_24.png[]), which provides a user-friendly way of
selecting signals for plotting. When activated, users can click elements in the
schematic editor. To probe a voltage, click a wire with the probe tool. When
hovering over wires with the tool, the corresponding net is highlighted. To
probe a current, click on a symbol pin. When hovering over a pin, the cursor
will change from a voltage probe symbol to a current clamp symbol. It is not
possible to probe power signals with this tool.

===== Using a SPICE directive

While ngspice supports the `.plot` directive, it cannot be used in current
versions of KiCad.

===== Differential voltage

Probing differential voltages usually requires a simulation symbol. One is
available in `Simulation_SPICE:VOLTMETER_DIFF` in the official libraries. This
symbol has two terminals for differential voltage sensing, and one the user can
probe.

[NOTE]
A SPICE model called `kicad_builtin_vdiff` is preassigned to the built-in
`VOLTMETER_DIFF` symbol. Users should not define a SPICE model with the same
name.

It is also possible to probe across two-terminal devices such as a resistor by
placing the `.probe vd(X)` directive, where `X` is the name of the device (such
as `R1`). Then in order to probe it, enter `vd_X` when adding a signal using the
list of signals. Note that the signal will not appear in the list of signals, it
should be typed in by the user. This method has the advantage of not adding
extra symbols to the schematic sheet.

////
// TODO: AMMETER_DIFF is not in the official libs
===== Differential currents

Probing differential currents can be performed using the
`Simulation_SPICE:AMMETER_DIFF` symbol in the official libraries. It has four
input terminals, and two that should be shunted together. The latter two are
used for probing.

[NOTE]
A SPICE model called `kicad_builtin_adiff` is automatically called when using
the builtin `AMMETER_DIFF` symbol. Users should not define a SPICE model with
the same name.
////

===== Remove a signal probe

In order to remove a signal probe, double click on it in the signal list, or
right-click it and select **Remove Signal**.

==== Tuning components

It is possible to change passive (R, L, C) values using sliders to graphically
adjust them. Whenever the slider is set to a new position, the simulation is run
with the new parameters and plots are updated. In order to add a slider for a
component, use **Simulation** -> **Tune Component Value** or the
image:images/icons/sim_tune_24.png[tune icon] button in the toolbar, and then
click on the component to tune.

* The top text field sets the maximum component value.
* The middle text field sets the actual component value.
* The bottom text field sets the minimum component value.
* The slider allows the user to modify the component value.
* The **Save** button modifies component value on the schematic to the value
  selected with the slider.
* The image:images/icons/small_trash_16.png[trash icon] button removes the
  component from the Tune panel and restores its original value.

==== Visualizing results

===== Plotted quantities

This section applies to simulation commands that output vectors such as `.ac` and `.tran`.

Simulation results are visualized as plots. There can be multiple plots opened
in separate tabs, but only the active one is updated when a simulation is
executed. This way it is possible to compare simulation results for different
runs.

Plots can be customized by toggling grid and legend visibility using
the **View** menu. When a legend is visible, it can be dragged to
change its position. You can toggle the plot background from dark to light with
**View** -> **White Background** and switch current and phase plots to use
dotted lines instead of solid with **View** -> **Dotted Current/Phase**.

For precise measurement, it is possible to add a cursor to a a signal. To do so,
right click on a signal name in the **Signals** pane and select **Show Cursor**.
It is then possible to move the cursor to the point of interest. The values are
then shown in the *Cursor* section of the window. To hide a cursor, right click
on a signal and select **Hide Cursor**.  Each signal may have one cursor
displayed.

The following interactions are possible with the plot panel:

* scroll mouse wheel to zoom in/out
* right click to open a context menu to adjust the view
* draw a selection rectangle to zoom in the selected area
* drag a cursor to change its coordinates

===== Numerical values

Some analysis types, such as the DC operating point analysis (`.op`), do not
have any graphical output to plot. Instead, their output is printed in the SPICE
console.

==== Exporting results

KiCad's simulator offers two ways to export results:

* As an image using **File** -> **Export Current Plot as PNG...**
* As a `.csv` file containing the datapoints using **File** ->
  **Export Current Plot as CSV...**.

==== Troubleshooting

===== Incorrect netlist

It is possible to inspect the SPICE netlist with **Simulation** ->
**Show SPICE netlist...**. This method of troubleshooting requires some SPICE
knowledge, but spotting errors in the netlist can help determine the cause of
simulation problems.

===== Simulation error

The output console displays messages from the simulator. It is advised to check
the console output to verify there are no errors or warnings.

===== Convergence problems

In case the simulation does not converge in a reasonable amount of time (or not
at all), it is possible to add the following SPICE directives. 

[WARNING]
Changing convergence options can lead to erroneous results. These options should
be used with caution. 

....
.options gmin=1e-10 
.options abstol=1e-10 
.options reltol=0.003 
.options cshunt=1e-15 
....

* `gmin` is the minimum conductance allowed by the program.
The default value is `1e-12`.
* `abstol` is the absolute current error tolerance of the program. The default
value is 1 pA.
* `reltol` is the relative error tolerance of the program. The default value is
`0.001` (0.1%).
* `cshunt` adds a capacitor from each voltage node in the circuit to ground.
