NGSpice, the Open Source Spice Simulator

ngspice is a text-mode circuit simulator that numerically solves equations describing (electronic) circuits: These are made of passive and active devices. Time varying currents and voltages are simulated as well as noise and small signal behavior.

Ngspice is an open source update of Spice3f5, the last Berkeley's release of Spice3 simulator family. Ngspice is being developed to include new features to existing Spice3f5 and to fix its bugs. Improving a complex software like a circuit simulator is a very hard task and, while some improvements have been made, most of the work has been done on bug fixing and code refactoring.

On a linux (here Ubuntu) distribution several packages are available:

There is a detailed reference manual available for ngspice. This manual describes all commands and procedures available in ngspice and lists numerous examples. However, it is not an ngspice how-to or introductory text. This tutorial here gives you some information how to start. If you are interested in getting more in-depth information, you may refer to our book page or to a list of third party tutorials.

Installing

Linux Installing

If you are using LINUX, please check if your distribution already offers a ngspice package for installation. If not, you will need to download the latest ngspice-XX.tar.gz at https://sourceforge.net/projects/ngspice/files/ng-spice-rework/ and compile ngspice with

./configure --with-x --enable-xspice --enable-cider\
--with-readline=yes --enable-openmp --disable-debug\
CFLAGS="-m64 -O2" LDFLAGS="-m64 -s"
make -j8
sudo make install

or by running the script compile_linux.sh from folder ngspice/ by

./compile_linux.sh 64


          


          



        

An Example/Procedure

As shown in Fig. 1, You start with a circuit (here: an inverter). You have to create a netlist describing this circuit. The netlist is the input to ngspice, telling it about the circuit to be simulated. Together with some simulation commands this input cares for reading and parsing the netlist, starting the simulation and plotting the output. The output voltage (plotted in red) is the inverse of the (green) input. Both voltages are plotted versus time.

The input to ngspice is read from a file (either at the command line, as in ngspice vdiv.cir or at the ngspice prompt with command source, as in ngspice 1 -> source ./vdiv.cir), and it may be enhanced by commands given on the command line. The simulated output may be written to a file, or be plotted as a Y-X graph or a smith chart. There is no graphical user interface with schematic capture of circuit diagrams and automatic netlist generation.

Next we shall be looking at a simple example, a Circuit with Passive Elements, Operating Point.

Supported Analyses*

Excitation

Sinosoidal Excitation

An example:

Basic RC circuit

r 1 2 1.0
c 2 0 1.0
vin 1 0 dc 0 ac 1  ; the ac source

.options noacct

.control
  ac dec 10 .01 10
  plot vdb(2) xlog
.endc

.end

The syntax is:

.ac dec nd fstart fstop
.ac oct no fstart fstop
.ac lin np fstart fstop

Some example lines:

.ac dec 10 1 10K
.ac dec 10 1K 100MEG
.ac lin 100 1 100HZ

dec stands for decade variation, and nd is the number of points per decade. oct stands for octave variation, and no is the number of points per octave. lin stands for linear variation, and np is the number of points. fstart is the starting frequency, and fstop is the final frequency. If this line is included in the input file, Ngspice performs an AC analysis of the circuit over the specified frequency range. Note that in order for this analysis to be meaningful, at least one independent source must have been specified with an ac value. Typically it does not make much sense to specify more than one ac source. If you do, the result will be a superposition of all sources and difficult to interpret.


        

Pulses

For a pulse we have to add PULSE(VL VH TD TR TF PW PER PHASE) to the DC voltage of our voltage source, where VL is the starting voltage, VH the end voltage, TD a delay, TR and TF are rise and fall times, PW is the pulse width, PER the period of repetition, PHASE a phase shift.

An example in a netlist:

V1 in 0 dc 0 PULSE (0 5 1u 1u 1u 1 1)

In this example we have a pulse from 0 to 5 V, the delay before the pulse starts, its rise and fall times are all 1 us. Pulse width and pulse period are 1 s each, far beyond our intended simulation time. Phase does not matter here, we omit it. So here we apply just the rising edge of the pulse.

Circuit Description

General Structure and Conventions

The circuit to be analyzed is described to ngspice by a set of element lines, which define the circuit topology and element values, and a set of control lines, which define the model parameters and the run controls. All lines are assembled in an input file to be read by ngspice.

Two lines are essential:

  • The first line in the input file must be the title, which is the only comment line that does not need any special character in the first place.

  • The last line must be .end (mind the leading period).

The order of the remaining lines is arbitrary (except, of course, that continuation lines must immediately follow the line being continued).

Circuit Elements

Each element in the circuit is specified by an element line that contains:

  • the element name,
  • the circuit nodes to which the element is connected, and
  • the values of the parameters that determine the electrical characteristics of the element.

The first letter of the element name specifies the element type. For example, a resistor name must begin with the letter R and can contain one or more characters. Hence, R, R1, RSE, ROUT, and R3AC2ZY are valid resistor names. Details of each type of device are supplied below.

Fields on a line are separated by one or more blanks, a comma, an equal (=) sign, or a left or right parenthesis; extra spaces are ignored. A line may be continued by entering a + (plus) in column 1 of the following line; ngspice continues reading beginning with column 2. A name field must begin with a letter (A through Z) and cannot contain any delimiters. A number field may be an integer field (12, -44), a floating point field (3.14159), either an integer or floating point number followed by an integer exponent (1e-14, 2.65e3), or either an integer or a floating point number followed by one of the following scale factors:

Ngspice scale factors
Suffix Name Factor
T Tera 1012
G Giga 109
Meg Mega 106
K Kilo 103
mil Mil 25.4 × 10−6
m milli 10−3
u micro 10−6
n nano 10−9
p pico 10−12
f femto 10−15

Letters immediately following a number that are not scale factors are ignored, and letters immediately following a scale factor are ignored. Hence, 10, 10V, 10Volts, and 10Hz all represent the same number, and M, MA, MSec, and MMhos all represent the same scale factor. Note that 1000, 1000.0, 1000Hz, 1e3, 1.0e3, 1kHz, and 1k all represent the same number.

Node names may be arbitrary character strings and are case insensitive. The ground node must be named 0 (zero). For compatibility reason gnd is accepted as ground node, and will internally be treated as a global node and be converted to 0.

Each circuit has to have a ground node (gnd or 0)!

Note the difference in ngspice where the nodes are treated as character strings and not evaluated as numbers, thus 0 and 00 are distinct nodes in ngspice but not in SPICE2.


Ngspice requires that the following topological constraints are satisfied:

  • The circuit cannot contain a loop of voltage sources and/or inductors and cannot contain a cut-set of current sources and/or capacitors.
  • Each node in the circuit must have a dc path to ground.
  • Every node must have at least two connections except for transmission line nodes (to permit unterminated transmission lines) and MOSFET substrate nodes (which have two internal connections anyway).

Basic lines

Title

Example:

POWER AMPLIFIER CIRCUIT
* additional comment lines following
*...

You can also precede the title with period command .TITLE:

.TITLE line example:
* additional lines following
* ...

.END Line

The .End line must always be the last in the input file. Note that the period is an integral part of the name.

Example:

.end

Comments

The general form of a whole line comment is:

* <any comment>

Examples:

* RF=1K Gain should be 100
* Check open−loop gain and phase margin

The asterisk in the first column indicates that this line is a comment line. Comment lines may be placed anywhere in the circuit description.


The general form of end-of-line comments is:

<any command> ; <any comment>

Examples:

RF2=1K ; Gain should be 100
C1=10 p $ Check open−loop gain and phase margin

ngspice also supports comments that begin with single characters ’;’ or double characters ’$ ’ or ’//’ or ’- -’.

Device Models

General form:

.model mname type ( pname1=pval1 pname2=pval2 ... )

Example:

.model MOD1 npn ( bf=50 is=1e−13 vbf=50 )

Most simple circuit elements typically require only a few parameter values. However, some devices (semiconductor devices in particular) that are included in ngspice require many parameter values. Often, many devices in a circuit are defined by the same set of device model parameters. For these reasons, a set of device model parameters is defined on a separate .model line and assigned a unique model name. The device element lines in ngspice then refer to the model name.

For these more complex device types, each device element line contains the device name, the nodes to which the device is connected, and the device model name. In addition, other optional parameters may be specified for some devices: geometric factors and an initial condition. mname in the above is the model name, and type is one of the following fifteen types:

Ngspice model types
Code Model Type
R resistor model
C capacitor model
L Inductor model
SW Voltage controlled switch
CSW Current controlled switch
URC Uniform distributed RC model
LTRA Lossy transmission line model
D Diode model
NPN NPN BJT model
PNP PNP BJT model
NJF N-channel JFET model
PJF P-channel JFET model
NMOS N-channel MOSFET model
PMOS P-channel MOSFET model
NMF N-channel MESFET model
PMF P-channel MESFET model

Parameter values are defined by appending the parameter name followed by an equal sign and the parameter value. Model parameters that are not given a value are assigned the default values given below for each model type. Models are listed in the section on each device along with the description of device element lines

Subcircuits

A subcircuit that consists of ngspice elements can be defined and referenced in a fashion similar to device models. Subcircuits are the way ngspice implements hierarchical modeling, but this is not entirely true because each subcircuit instance is flattened during parsing, and thus ngspice is not a hierarchical simulator.

The subcircuit is defined in the input deck by a grouping of element cards delimited by the .subckt and the .ends cards; the program then automatically inserts the defined group of elements wherever the subcircuit is referenced. Instances of subcircuits within a larger circuit are defined through the use of an instance card which begins with the letter X. A complete example of all three of these cards follows:

* The following is the instance card :
*
xdiv1 10 7 0 vdivide

* The following are the subcircuit definition cards :
*
.subckt vdivide 1 2 3
  r1 1 2 10 K
  r2 2 3 5 K
.ends

The above specifies a subcircuit with ports numbered 1, 2 and 3:

  • Resistor R1 is connected from port “1” to port “2”, and has value 10 kOhms.
  • Resistor R2 is connected from port “2” to port “3”, and has value 5 kOhms.

The instance card, when placed in an ngspice deck, will cause subcircuit port “1” to be equated to circuit node “10”, while port “2” will be equated to node “7” and port “3” will equated to node “0”.

There is no limit on the size or complexity of subcircuits, and subcircuits may contain other subcircuits.


The general form of the .SUBCKT line is:

.SUBCKT subnam N1 <N2 N3 . . . >

Example:

. SUBCKT OPAMP 1 2 3 4

A circuit definition is begun with a .SUBCKT line. SUBNAM is the subcircuit name, and N1, N2, ... are the external nodes, which cannot be zero. The group of element lines which immediately follow the .SUBCKT line define the subcircuit. The last line in a subcircuit definition is the .ENDS line (see below). Control lines may not appear within a subcircuit definition; however, subcircuit definitions may contain anything else, including other subcircuit definitions, device models, and subcircuit calls (see below). Note that any device models or subcircuit definitions included as part of a subcircuit definition are strictly local (i.e., such models and definitions are not known outside the subcircuit definition). Also, any element nodes not included on the .SUBCKT line are strictly local, with the exception of 0 (ground) which is always global. If you use parameters, the .SUBCKT line will be extended.

The .ENDS [subcircuit_name] line must be the last one for any subcircuit definition. The subcircuit name, if included, indicates which subcircuit definition is being terminated; if omitted, all subcircuits being defined are terminated. Therefore, the name is needed only when nested subcircuit definitions are being made.

Last, a subcircuit is called with syntax:

X<any_name> N1 [N2 N3 ...] subnam

For example:

X1 2 4 17 3 1 MULTI

Subcircuits are used in ngspice by specifying pseudo-elements beginning with the letter X, followed by the circuit nodes to be used in expanding the subcircuit. If you use parameters, the subcircuit call will be modified

Other Dot Directives

.GLOBAL

General form:

.GLOBAL nodename1 [ nodename2 ... ]

Examples:

. GLOBAL gnd vcc

Nodes defined in the .GLOBAL statement are available to all circuit and subcircuit blocks independently from any circuit hierarchy. After parsing the circuit, these nodes are accessible from top level.

.INCLUDE

General form:

.INCLUDE filename

Examples:

. INCLUDE /users/spice/common/bsim3-param.mod

Frequently, portions of circuit descriptions will be reused in several input files, particularly with common models and subcircuits. In any ngspice input file, the .INCLUDE line may be used to copy some other file as if that second file appeared in place of the .INCLUDE line in the original file.

If the filename is a relative path and the file is not found, it is searched for in the locations given by variable sourcepath. There is no restriction on the file name imposed by ngspice beyond those imposed by the local operating system.

.LIB

General form:

.LIB filename libname

Examples:

.LIB /users/spice/common/mosfets.lib mos1

The .LIB statement allows including library descriptions into the input file. Inside the *.lib file a library libname will be selected. The statements of each library inside the *.lib file are enclosed in .LIB libname <...> .ENDL statements. The file is searched for in the same way as for .include.

If the compatibility mode is set to ps by set ngbehavior=ps in spinit or .spiceinit, then a simplified syntax .LIB filename is available: a warning is issued and filename is simply included.

.PARAM for Parametric netlists

Ngspice allows for the definition of parametric attributes in the netlists. This is an enhancement of the ngspice front-end that adds arithmetic functionality to the circuit description language.

The general form of a .param line is:

.param <ident>= <expr> <ident>=<expr>...

Examples:

.param pippo = 5
.param po = 6 pp = 7.8 pap = { AGAUSS (pippo, 1, 1.67)}
.param pippp = { pippo + pp }
.param p = { pp }
.param pop = 'pp + p'

This line assigns numerical values to identifiers. More than one assignment per line is possible using a separating space. Parameter identifier names must begin with an alphabetic character. The other characters must be either alphabetic, a number, or ! # $ % [ ] _ as special char acters. The variables time, temper, and hertz (see 5.1.1) are not valid identifier names. Other restrictions on naming conventions apply as well.

The .param lines inside subcircuits are copied per call, like any other line. All assignments are executed sequentially through the expanded circuit. Before its first use, a parameter name must have been assigned a value. Expressions defining a parameter should be put within braces {p+p2}, or alternatively within single quotes 'AGAUSS(pippo, 1, 1.67)'. An assignment cannot be self-referential, something like .param pip = 'pip+3' will not work.

The current ngspice version does not always need quotes or braces in expressions, especially when spaces are used sparingly. However, it is recommended to do so, as the following examples demonstrate.

.param a = 123*3 b=sqrt(9) $ doesn't work, a <= 123
.param a = '123 * 3' b = sqrt (9) $ ok .
.param c = a + 123 $ won't work
.param c = 'a + 123 ' $ ok
.param c = a +123 $ ok

Parameters may also have string values, but support is limited. String-valued parameters can be defined by .param and used in the same ways as numeric parameters. The only operation on string values is concatenation and that is possible only in top-level .param assignments.

.param str1 = "first" str2 = "second"
.param both ={str1}" and "str2

Brace expressions in circuit elements

General form:

{<expression>}

These are allowed in .model lines and in device lines. A SPICE number is a floating point number with an optional scaling suffix, immediately glued to the numeric tokens. Brace expressions ({..}) cannot be used to parameterize node names or parts of names. All identifiers used within an expr must have known values at the time when the line is evaluated, else an error is flagged.

Subcircuit parameters

General form:

.subckt <identn> node node ... <ident>= <value> <ident>= <value> ...

Example:

.subckt myfilter in out rval =100 k cval =100 nF

<identn> is the name of the subcircuit given by the user. node is an integer number or an identifier, for one of the external nodes. The first <ident>=<value> introduces an optional section of the line. Each <ident> is a formal parameter, and each <value> is either a SPICE number or a brace expression. Inside the .subckt ... .ends context, each formal parameter may be used like any identifier that was defined on a .param control line. The <value> parts are default values of the parameters.

The syntax of a subcircuit call (invocation) is:

X <name> node node ... <identn> <ident>=<value> <ident>= <value> ...

Example:

X1 input output myfilter rval=1k

Here <name> is the symbolic name given to that instance of the subcircuit, <identn> is the name of a subcircuit defined beforehand. node node ... is the list of actual nodes where the subcircuit is connected. <value> is either a SPICE number or a brace expression {<expr>}.

Subcircuit example with parameters:

* Param - example
.param amplitude = 1 V
*
.subckt myfilter in out rval=100 k cval=100 nF
Ra in p1 {2* rval }
Rb p1 out {2* rval }
C1 p1 0 {2* cval }
Ca in p2 { cval }
Cb p2 out { cval }
R1 p2 0 { rval }
.ends myfilter
*
X1 input output myfilter rval=1k cval=1n
V1 input 0 AC {amplitude}
.end

Symbol scope

All subcircuit and model names are considered global and must be unique. The .param symbols that are defined outside of any .subckt ... .ends section are global. Inside such a section, the pertaining params: symbols and any .param assignments are considered local: they mask any global identical names, until the .ends line is encountered. You cannot reassign to a global number inside a .subckt, a local copy is created instead. Scope nesting works up to a level of 10. For example, if the main circuit calls A that has a formal parameter xx, A calls B that has a param. xx, and B calls C that also has a formal param. xx, there will be three versions of xx in the symbol table but only the most local one --belonging to C-- is visible.

.FUNC*


            

.CSPARAM*


            

.TEMP*


              


              


              


              


              


              


        

Circuit Elements*

Models for NGSpice

(Largely from Ngspice Tutorials)

For simulation you need as input to ngspice your circuit (aka the netlist), device models (or model parameters), simulation commands, and output commands. The ngspice distribution does offer some default model parameters only for the basic, intrinsic devices. Device makers, vendors and modeling specialists however provide models, and you may find many of them in the two collections offered below, or in the web (see links below, or search for a specific device or use a general search term like get SPICE models). Generally PSPICE, HSPICE, and (many) LTSPICE models are compatible with ngspice. Sometimes models by commercial vendors are encrypted. These cannot be used by open source ngspice. Some hints on how to make models and model parameters available to ngspice are given below.

Model and model parameter collections*

PDKs (Process Design Kits) for IC design*

How to add models and model parameters to the ngspice netlist

Basically ngspice may use three types of model data: the PDKs (we will not talk about them here, see our Application page), sets of model parameters for the intrinsic ngspice device models, and complete subcircuit models for OpAmps and other devices and circuits.

A set of model parameters is used by ngspice device models like bipolar or MOS transistors, JFETs or transmission lines. Such a model parameter set is arranged in a single line and looks like

.model mname type ( pname1=pval1 pname2=pval2 ... )

where mname is the model name, type is the ngspice model type, and pnamxx are the model parameters with their values pvalxx. The parameters are prescribed by the model type, the values are used to achieve best correlation between model and measured device reality. Please note that sometimes the .model is split into several lines, where consecutive lines start with a + in the first column. This is regarded as a single line. A typical example is:

*SRC=BC546;BC546;BJTs NPN;Gen. Purpose;65V 100mA
.MODEL BC546 NPN (IS=50.7F NF=1 BF=318 VAF=145 IKF=.3
+ ISE=15.9P NE=2 BR=4 NR=1 VAR=24 IKR=.45 RE=1.54 RB=6.17
+ RC=.617 XTB=1.5 CJE=20.8P CJC=8.33P TF=611P TR=138N)
*   National 65 Volt  .5 Amp  260 MHz  SiNPN  Transistor  01-26-1991
*PINOUT TO-92 3 2 1

The other model type is a subcircuit model, putting several interconnected intrinsic devices into a subcircuit, which is enclosed in .subckt ... .ends and looks like

.subckt sname node1 node2 node3
    ...
.ends

Including a Model

.include model-directory/mymodels.lib

or just:

.include mymodels.lib

Now, in a lib file, if you are looking for a model from TI, e.g. the OpAmp OPA1641, you will find a PSPICE compatible, zipped model file assembly sbom627b.zip on the TI web pages. If you unzip it, the ngspice compatible device model is contained in the file OPA1641.lib. To check its eligibility, open the file in a text editor. After the introduction (comment lines), you will find the characteristic line

.subckt OPA1641 IN+ IN- VCC VEE OUT

as the begin of the main subcircuit. So copy this file OPA1641.lib to your model folder and invoke it by:

.include model/OPA1641.lib
Xopamp inp inm vc ve opout OPA1641

And because this OpAmp model is a PSPICE model, don't forget to set

set ngbehavior=ltpsa

in file .spiceinit.

*


          


          


          


          


        

*


          


          


          


          


          


        

*


          


          


          


          


          


        

Control Language (Formerly Nutmeg)

(From https://ngspice.sourceforge.io/ngspice-control-language-tutorial.html)

See NGSpice Control Language (Formerly Nutmeg) for an in-depth discussion.

ngspice circuit simulator offers a built-in control language (formerly know as nutmeg language). It allows to create scripts which automate the simulation flow and provide support for simulation data analysis.

There are three basic methods to start a simulation with ngspice. The traditional method is the batch mode. With an input netlist given (see below), the command ngspice -b -r inv-example.raw inv-example.cir will start the simulation, executing the dot commands from the netlist, saving the simulation data in the raw file, without any further user interaction. Besides, we have the interactive mode. You start ngspice by ngspice inv-example.cir. ngspice sources the netlist and then waits for user input. You may type any of the commands found in chapter 17.5 of the ngspice manual or the ngspice xhtml manual to initiate some action (e.g. running the simulation, plotting or saving the data etc.). The real power of using these commands however is unfolded in the third mode of running ngspice, the control mode. You assemble a sequence of commands into a script, add this script to the netlist, and then start ngspice as usual by ngspice inv-example.cir. ngspice will execute the commands from the script, enabling multiple simulations, loops, data processing, plotting and saving data. About 100 commands are available, scripts may range from simple ones with few lines up to complex ones with several hundred commands.

More info on starting ngspice is available in chapter 16.4 of the ngspice manual. Commands used in the scripts below are not all explained in detail, please use the ngspice manual chapter 17.5 as your reference.

.tran and tran*

...

tran 100p 500n


          


          


        

dc and tran*

dc vin 0 2 0.01