Ngspice User's ManualVersion 41 Plus (Ngspice Deve
Ngspice User's ManualVersion 41 Plus (Ngspice Deve
Version 41 plus
(ngspice development version)
Holger Vogt, Giles Atkinson, Paolo Nenzi, Dietmar Warning
Locations
The project and download pages of ngspice may be found at
Status
This manual is a work in progress. Some to-dos are listed in Chapt. 24.3. More is surely needed. You are invited to report bugs, missing items,
wrongly described items, bad English style, etc.
License
This document is covered by the Creative Commons Attribution Share-Alike (CC-BY-SA) v4.0..
Table of Contents
Locations
Status
How to use this Manual
License
Acknowledgments
ngspice contributors
Chapter 1 Introduction
1.1 Simulation Algorithms
1.2 Supported Analyses
1.3 Analysis at Different Temperatures
1.4 Convergence
Chapter 7 Diodes
7.1 Junction Diodes
7.2 Diode Model (D)
7.3 Diode Equations
Chapter 8 BJT
8.1 Bipolar Junction Transistors (BJTs)
8.2 BJT Models (NPN/PNP)
Chapter 9 JFETs
9.1 Junction Field-Effect Transistors (JFETs)
9.2 JFET Models (NJF/PJF)
Chapter 10 MESFETs
10.1 MESFETs
10.2 MESFET Models (NMF/PMF)
Chapter 11 MOSFETs
11.1 MOSFET devices
11.2 MOSFET models (NMOS/PMOS)
11.3 Power MOSFET model (VDMOS)
Chapter 20 TCLspice
20.1 tclspice framework
20.2 tclspice documentation
20.3 spicetoblt
20.4 Running TCLspice
20.5 examples
20.6 Compiling
20.7 MS Windows 32 Bit binaries
Chapter 24 Notes
24.1 Glossary
24.2 Acronyms and Abbreviations
24.3 To Do
Bibliography A. Vladimirescu and S. Liu, `The Simulation of MOS Integrated Circuits Using
SPICE2' ERL Memo No. ERL M80/7, Electronics Research Laboratory University of
California, Berkeley, October 1980
Part IV Miscellaneous
Chapter 31 Model and Device Parameters
31.1 Accessing internal device parameters
31.2 Elementary Devices
31.3 Voltage and current sources
31.4 Transmission Lines
31.5 BJTs
31.6 MOSFETs
Prefaces
Preface to the first edition
This manual has been assembled from different sources:
In writing this text I followed the spice3f5 manual, both in the chapter sequence and presentation of material, mostly because that was already the user
manual of SPICE.
Ngspice is an open source software, users can download the source code, compile, and run it. This manual has an entire chapter describing program
compilation and available options to help users in building ngspice (see Chapt. 32). The source package already comes with all `safe' options enabled
by default, and activating the others can produce unpredictable results and thus is recommended to expert users only. This is the first ngspice manual
and I have removed all the historical material that described the differences between ngspice and spice3, since it was of no use for the user and not so
useful for the developer who can look for it in the Changelogs of in the revision control system.
I want to acknowledge the work done by Emmanuel Rouat and Arno W. Peters for converting the original spice3f documentation to TeXinfo. Their
effort gave ngspice users the only available documentation that described the changes for many years. A good source of ideas for this manual came
from the on-line spice3f manual written by Charles D.H. Williams (Spice3f5 User Guide), constantly updated and useful for its many insights.
Paolo Nenzi
Indeed. At the end of the day, this is engineering, and one learns to live
within the limitations of the tools.
Kevin Aylward, Warden of the King's Ale
Holger Vogt
Mülheim, 2023
Acknowledgments
ngspice contributors
Spice3 and CIDER were originally written at The University of California at Berkeley (USA).
Since then, there have been many people working on the software, most of them releasing patches to the original code through the Internet.
Vera Albrecht,
Cecil Aswell,
Giles Atkinson,
Giles C. Billingsley,
Phil Barker,
Steven Borley,
Stuart Brorson,
Alessio Cacciatori,
Mansun Chan,
Wayne A. Christopher,
Al Davis,
Glao S. Dezai,
Jon Engelbert,
Daniele Foci,
Noah Friedman,
David A. Gates,
Alan Gillespie,
John Heidemann,
Marcel Hendrix,
Jeffrey M. Hsu,
JianHui Huang,
S. Hwang,
Chris Inbody,
Gordon M. Jacobs,
Min-Chie Jeng,
Beorn Johnson,
Stefan Jones,
Kenneth H. Keller,
Francesco Lannutti,
Robert Larice,
Mathew Lew,
Robert Lindsell,
Weidong Liu,
Kartikeya Mayaram,
Richard D. McRoberts,
Manfred Metzger,
Jim Monte,
Wolfgang Muees,
Paolo Nenzi,
Gary W. Ng,
Hong June Park,
Stefano Perticaroli,
Arno Peters,
Serban-Mihai Popescu,
Georg Post,
Thomas L. Quarles,
Emmanuel Rouat,
Jean-Marc Routure,
Jaijeet S. Roychowdhury,
Lionel Sainte Cluque,
Takayasu Sakurai,
Amakawa Shuhei,
Kanwar Jit Singh,
Bill Swartz,
Hitoshi Tanaka,
Brian Taylor,
Steve Tell,
Andrew Tuckey,
Andreas Unger,
Holger Vogt,
Dietmar Warning,
Michael Widlok,
Charles D.H. Williams,
Antony Wilson,
and many others...
If someone helped in the development and has not been inserted in this list then this omission was unintentional. If you feel you should be on this list
then please write to <ngspice-devel@lists.sourceforge.net>. Do not be shy, we would like to make a list as complete as possible.
Chapter 1 Introduction
Ngspice is a general-purpose circuit simulation program for nonlinear and linear analyses. Circuits may contain resistors, capacitors, inductors,
mutual inductors, independent or dependent voltage and current sources, loss-less and lossy transmission lines, switches, uniform distributed RC
lines, and the five most common semiconductor devices: diodes, BJTs, JFETs, MESFETs, and MOSFETs.
The most common way to use Ngspice is to start it from the OS command prompt, passing the name of a netlist file: one containing the definition of a
circuit. The largest part of this manual is the description of such files. For a full description of starting options see Chapter 16. Input files may also
contain scripts written in Ngspice's command language (17). Interactive user interfaces are described in Chapter 18.
Some introductory remarks on how to use ngspice may be found in Chapter 21.
Ngspice is an 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.
Ngspice has built-in models for the semiconductor devices, and the user need specify only the pertinent model parameter values.
Ngspice supports mixed-level simulation and provides a direct link between technology parameters and circuit performance. A mixed-level circuit and
device simulator can provide greater simulation accuracy than a stand-alone circuit or device simulator by numerically modeling the critical devices
in a circuit. Compact models can be used for all other devices. The mixed-level extensions to ngspice is CIDER, a mixed-level circuit and device
simulator integrated into ngspice code.
Ngspice supports mixed-signal simulation through the integration of XSPICE code. XSPICE software, developed as an extension to Spice3C1 by
GeorgiaTech, has been enhanced and ported to ngspice to provide `board' level and mixed-signal simulation.
New devices can be added to ngspice by several means: behavioral B-, E- or G-sources, the XSPICE code-model interface for C-like device coding,
and the ADMS interface based on Verilog-A and XML.
Finally, numerous small bugs have been discovered and fixed, and the program has been ported to a wider variety of computing platforms.
However, to be practical, a simulator must execute in a reasonable amount of time. The key to efficient execution is choosing the proper level of
modeling abstraction for a given problem. To support a given modeling abstraction, the simulator must provide appropriate algorithms.
Historically, circuit simulators have supported either an analog simulation algorithm or a digital simulation algorithm. Ngspice inherits the XSPICE
framework and supports both analog and digital algorithms and is a `mixed-mode' simulator.
The response of a circuit is a function of the applied sources. Ngspice offers a variety of source types including DC, sine-wave, and pulse. In addition
to specifying sources, the user must define the type of simulation to be run. This is termed the `mode of analysis'. Analysis modes include DC
analysis, AC analysis, and transient analysis. For DC analysis, the time-varying behavior of reactive elements is neglected and the simulator
calculates the DC solution of the circuit. Swept DC analysis may also be accomplished with ngspice. This is simply the repeated application of DC
analysis over a range of DC levels for the input sources. For AC analysis, the simulator determines the response of the circuit, including reactive
elements to small-signal sinusoidal inputs over a range of frequencies. The simulator output in this case includes amplitudes and phases as a function
of frequency. For transient analysis, the circuit response, including reactive elements, is analyzed to calculate the behavior of the circuit as a function
of time.
The semiconductor diode model can be used for either junction diodes or Schottky barrier diodes. There are two models for JFET: the first (JFET) is
based on the model of Shichman and Hodges, the second (JFET2) is based on the Parker-Skellern model. All the original six MOSFET models are
implemented: MOS1 is described by a square-law I-V characteristic, MOS2 [28] is an analytical model, while MOS3 [28] is a semi-empirical model;
MOS6 [2] is a simple analytic model accurate in the short channel region; MOS9, is a slightly modified Level 3 MOSFET model - not to confuse with
Philips level 9; BSIM 1 [3, 4]; BSIM2 [5] are the old BSIM (Berkeley Short-channel IGFET Model) models. MOS2, MOS3, and BSIM include
second-order effects such as channel-length modulation, subthreshold conduction, scattering-limited velocity saturation, small-size effects, and charge
controlled capacitances. The recent MOS models for submicron devices are the BSIM3 (Berkeley BSIM3 web page) and BSIM4 (Berkeley BSIM4
web page) models. Silicon-on-insulator MOS transistors are described by the SOI models from the BSIMSOI family (Berkeley BSIMSOI web page)
and the STAG [18] model. There is some support for a couple of HFET models and one model for MESA devices. Verilog-A models are made
available via the OpenVAF/OSDI interface (see chapter 13).
When an event occurs, the simulator examines only those circuit elements that are affected by the event. As a result, matrix analysis is not required in
digital simulators. By comparison, analog simulators must iteratively solve for the behavior of the entire circuit because of the forward and reverse
transmission properties of analog components. This difference results in a considerable computational advantage for digital circuit simulators, which
is reflected in the significantly greater speed of digital simulations.
Two basic methods of implementing mixed-mode simulation used in practice are the `native mode' and `glued mode' approaches. Native mode
simulators implement both an analog algorithm and a digital algorithm in the same executable. Glued mode simulators actually use two simulators,
one of which is analog and the other digital. This type of simulator must define an input/output protocol so that the two executables can communicate
with each other effectively. The communication constraints tend to reduce the speed, and sometimes the accuracy, of the complete simulator. On the
other hand, the use of a glued mode simulator allows the component models developed for the separate executables to be used without modification.
Ngspice is a native mode simulator providing both analog and event-based simulation in the same executable. The underlying algorithms of ngspice
(coming from XSPICE and its Code Model Subsystem) allow use of all the standard SPICE models, provide a pre-defined collection of the most
common analog and digital functions, and provide an extensible base on which to build additional models.
Ngspice digital simulation is actually implemented as a special case of this User-Defined Node capability where the digital state is defined by a data
structure that holds a Boolean logic state and a strength value.
CIDER is a mixed-level circuit and device simulator that provides a direct link between technology parameters and circuit performance. A mixed-
level circuit and device simulator can provide greater simulation accuracy than a stand-alone circuit or device simulator by numerically modeling the
critical devices in a circuit. Compact models can be used for noncritical devices.
CIDER couples ngspice to a internal C-based device simulator, thus providing circuit analyses, compact models for semiconductor devices, and an
interactive user interface. CIDER provides accurate, one- and two-dimensional numerical device models based on the solution of Poisson's equation,
and the electron and hole current-continuity equations. CIDER incorporates many of the same basic physical models found in the the Stanford two-
dimensional device simulator PISCES [PINT85]. Input to CIDER consists of a SPICE-like description of the circuit and its compact models, and
PISCES-like descriptions of the structures of numerically modeled devices. As a result, CIDER should seem familiar to designers already accustomed
to these two tools.
The CIDER input format has great flexibility and allows increased access to physical model parameters. New physical models have been added to
allow simulation of state-of-the-art devices. These include transverse field mobility degradation [GATE90] that is important in scaled-down
MOSFETs and a polysilicon model for poly-emitter bipolar transistors. Temperature dependence has been included for most physical models over the
range from -50°C to 150°C. The numerical models can be used to simulate all the basic types of semiconductor devices: resistors, MOS capacitors,
diodes, BJTs, JFETs and MOSFETs. BJTs and JFETs can be modeled with or without a substrate contact. Support has been added for the management
of device internal states. Post-processing of device states can be performed using the control language user interface of ngspice. Previously computed
states can be loaded into the program to provide accurate initial guesses for subsequent analyses.
Details of the basic semiconductor equations and the physical models used by CIDER are not provided in this manual. Unfortunately, no other single
source exists that describes all of the relevant background material. Comprehensive reviews of device simulation can be found in [PINT90] and the
book [SELB84]. CODECS (predecessor to CIDER) and its inversion-layer mobility model are described in [MAYA88] and [LGATE90], respectively.
PISCES and its models are described in [PINT85]. Temperature dependencies for the PISCES models used by CIDER are available in [SOLL90].
For Linux users the cooperation of the TCAD software GSS with ngspice might be of interest, see https://ngspice.sourceforge.io/gss.html. This project
is no longer maintained however, but has moved into the Genius simulator, still available as open source cogenda genius.
In order to understand the relationship between the different analyses and the two underlying simulation algorithms of ngspice, it is important to
understand what is meant by each analysis type. This is detailed below.
1.2.1 DC Analysis
The DC analysis portion of ngspice determines the dc operating point of the circuit with inductors shorted and capacitors opened. DC analysis options
are specified on the .DC, .TF, and .OP control lines.
DC analysis does not consider any time dependence on any of the sources within the system description. The simulator algorithm subdivides the
circuit into those portions that require the analog simulator algorithm and those that require the event-driven algorithm. Each subsystem block is then
iterated to solution, with the interfaces between analog nodes and event-driven nodes iterated for consistency across the entire system.
Once stable values are obtained for all nodes in the system, the analysis halts and the results may be displayed or printed out as you request them.
A dc analysis is automatically performed prior to a transient analysis to determine the transient initial conditions, and prior to an ac small-signal
analysis to determine the linearized, small-signal models for nonlinear devices. If requested, the DC small-signal value of a transfer function (ratio of
output variable to input source), input resistance, and output resistance is also computed as a part of the DC solution. DC analysis can also be used to
generate DC transfer curves: a specified independent voltage, current source, resistor or temperature is stepped over a user-specified range and the DC
output variables are stored for each sequential source value.
The program first computes the dc operating point of the circuit and determines linearized, small-signal models for all of the nonlinear devices in the
circuit. The resultant linear circuit is then analyzed over a user-specified range of frequencies. The desired output of an ac small-signal analysis is
usually a transfer function (voltage gain, transimpedance, etc). If the circuit has only one ac input, it is convenient to set that input to unity and zero
phase, so that output variables have the same value as the transfer function of the output variable with respect to the input.
All sources that are not time dependent (for example, power supplies) are set to their dc value. The transient time interval is specified on a .TRAN
control line.
Diodes (DIO),
BJT,
JFET (level 1),
MOSFETs (levels 1, 2, 3, 9, and BSIM1),
MESFET (level 1).
All linear devices are automatically supported by distortion analysis. If there are switches present in the circuit, the analysis continues to be accurate
provided the switches do not change state under the small excitations used for distortion calculations.
If a device model does not support direct small signal distortion analysis, please use the Fourier of FFT statements and evaluate the output per
scripting.
Since each variable is perturbed by a small fraction of its value, zero-valued parameters are not analyzed, reducing what is usually a very large
amount of data.
PSS is a radio frequency periodical large-signal dedicated analysis. The implementation is based on a time domain shooting method that make use of
transient analysis. As it is in early development stage, PSS performs analysis only on autonomous circuits, meaning that it is able to predict
fundamental frequency and (harmonic) amplitude(s) for oscillators, VCOs, etc.. The algorithm is based on a search of the minimum error vector
defined as the difference of RHS vectors between two occurrences of an estimated period. Convergence is reached when the mean of this error vector
decreases below a given threshold parameter. Results of PSS are the basis of periodical large-signal analyses like PAC or PNoise.
All input data for ngspice is assumed to have been measured at the circuit nominal temperature. This value can further be overridden for any device
that models temperature effects by specifying the TNOM parameter on the .model itself. Individual instances may further override the circuit
temperature through the specification of TEMP and DTEMP parameters on the instance. The two options are not independent even if you can specify both
on the instance line, the TEMP option overrides DTEMP. The algorithm to compute instance temperature is described below:
For details of the BSIM temperature adjustment, see [6] and [7]. Temperature appears explicitly in the exponential terms of the BJT and diode model
equations. In addition, saturation currents have a built-in temperature dependence. The temperature dependence of the saturation current in the BJT
models is determined by:
𝑇
𝑋𝑇𝐼 𝐸𝑔 𝑞(𝑇1 − 𝑇0 )
𝐼𝑆 (𝑇1 ) = 𝐼𝑆 (𝑇0 )( 1 ) exp ( )
𝑇0 𝑘(𝑇1 𝑇0 )
where 𝑘 is Boltzmann's constant, 𝑞 is the electronic charge, 𝐸𝑔 is the energy gap model parameter, and 𝑋𝑇𝐼 is the saturation current temperature
exponent (also a model parameter, and usually equal to 3).
The temperature dependence of forward and reverse beta is according to the formula:
𝑇
𝑋𝑇𝐵
𝐵(𝑇1 ) = 𝐵(𝑇0 )( 1 )
𝑇0
where 𝑇0 and 𝑇1 are in degrees Kelvin, and 𝑋𝑇𝐵 is a user-supplied model parameter. Temperature effects on beta are carried out by appropriate
adjustment to the values of 𝐵𝐹 , 𝐼𝑆𝐸 , 𝐵𝑅 , and 𝐼𝑆𝐶 (SPICE model parameters BF, ISE, BR, and ISC, respectively).
Temperature dependence of the saturation current in the junction diode model is determined by:
𝑋𝑇𝐼
𝑇 𝑁 𝐸𝑔 𝑞(𝑇1 − 𝑇0 )
𝐼𝑆 (𝑇1 ) = 𝐼𝑆 (𝑇0 )( 1 ) exp ( )
𝑇0 𝑁𝑘(𝑇1 𝑇0 )
where 𝑁 is the emission coefficient model parameter, and the other symbols have the same meaning as above. Note that for Schottky barrier diodes,
the value of the saturation current temperature exponent, 𝑋𝑇𝐼, is usually 2. Temperature appears explicitly in the value of junction potential, U (in
Ngspice PHI), for all the device models.
𝑘𝑇 𝑁 𝑁
𝑈(𝑇) = ln ( 𝑎 𝑑2 )
𝑞 𝑁 (𝑇) 𝑖
where 𝑘 is Boltzmann's constant, 𝑞 is the electronic charge, 𝑁𝑎 is the acceptor impurity density, 𝑁𝑑 is the donor impurity density, 𝑁𝑖 is the intrinsic
carrier concentration, and 𝐸𝑔 is the energy gap. Temperature appears explicitly in the value of surface mobility, 𝑀0 (or 𝑈0 ), for the MOSFET model.
⎛ ⎞
⎜ ⎟ 𝑀 (𝑇0 )
𝑀0 ⎜𝑇⎟ = 0 1.5
𝑇
⎜ ⎟ ( )
⎝ ⎠ 𝑇0
The effects of temperature on resistors, capacitor and inductors is modeled by the formula:
where 𝑇 is the circuit temperature, 𝑇0 is the nominal temperature, and 𝑇𝐶1 and 𝑇𝐶2 are the first and second order temperature coefficients.
The temperature of an individual device may be determined by the instance parameters temp or dtemp.
M1 d g s b MOSN temp=35
will set the temperature of the specific MOS device to 35 °C.
M2 d g s b MOSN dtemp=20
will set the temperature of device M2 at a delta of 20° above the overall temperature.
The temperatures thus set are static throughout the simulation. It is possible, however, to sweep the temperature by a command like
.dc temp 25 49 2
starting at 25 °C, stopping at 49 °C with a step of 2° (see 15.3.2).
The current overall temperature may be assessed by the variable TEMPER, which can be used as part of an equation in B sources (5.1.2) or behavioral
E, G, R, L, C sources (e.g. 5.2). A typical example may look like
Bt1 1 2 V='5 + TEMPER*TEMPER'
The nominal temperature, a reference temperature where device model parameters have been measured, is called tnom.
.options tnom=25
will set the nominal temperature for all devices to 25 °C (15.1.1). Tnom sometimes may be set as a model parameter in a .model line (3.2.2),
depending on the specific class of devices and its model parameter set.
1.4 Convergence
Ngspice uses the Newton-Raphson algorithm to solve nonlinear equations arising from circuit description. The NR algorithm is interactive and
terminates when both of the following conditions hold:
1. The nonlinear branch currents converge to within a tolerance of 0.1% or 1 picoamp (1.0e-12 Amp), whichever is larger.
2. The node voltages converge to within a tolerance of 0.1% or 1 microvolt (1.0e-6 Volt), whichever is larger.
The algorithm has reached convergence when the difference between the last iteration 𝑘 and the current one (𝑘 + 1)
1.4.1 Voltage convergence criterion
where
The RELTOL (RELative TOLerance) parameter, which default value is 10−3 , specifies how small the solution update must be, relative to the node
voltage, to consider the solution to have converged. The VNTOL (absolute convergence) parameter, which has 1𝜇𝑉 as default value, becomes important
when node voltages have near zero values. The relative parameter alone, in such case, would need too strict tolerances, perhaps lower than computer
round-off error, and thus convergence would never be achieved. VNTOL forces the algorithm to consider as converged any node whose solution update
is lower than its value.
Ngspice computes the difference between the value of the nonlinear function computed for the last voltage and the linear approximation of the same
current computed with the actual voltage
| (𝑘 ^+ 1) |
|𝑖𝑏𝑟𝑎𝑛𝑐ℎ − 𝑖(𝑏𝑟𝑎𝑛𝑐ℎ
𝑘)
| ≤ 𝚁𝙴𝙻𝚃𝙾𝙻𝑖𝑏𝑟 + 𝙰𝙱𝚂𝚃𝙾𝙻,
|| || 𝑚𝑎𝑥
where
^
𝑖𝑏𝑟𝑚𝑎𝑥 = max (𝑖𝑏𝑟𝑎𝑛𝑐ℎ , 𝑖𝑏𝑟𝑎𝑛𝑐ℎ ).
(𝑘 + 1) (𝑘)
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, plus a newline delimiter.
The order of the remaining lines is alomost arbitrary (except, of course, that continuation lines must immediately follow the line being continued,
.subckt ... .ends, .if ... .endif, or .control ... .endc have to enclose their specific lines). Leading white spaces in a line are ignored, as well as
empty lines.
The lines described in sections 2.1 to 2.12 are typically used in the core of the input file, outside of a .control section (see 16.4.3). An exception is
the .include includefile line (2.7) that may be placed anywhere in the input file. The contents of includefile will be inserted exactly in place of
the .include line.
For example, a resistor instance 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 in a following section 3. Table 2.1 lists the element types available in ngspice, sorted
by their first letter.
2.1.4.2 Numbers
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:
1000Hz, 1e3, 1.0e3, 1kHz, and 1k all represent the same number. Note that `M' or `m' denote `milli', i.e. 10−3 . Suffix meg has to be used for 106 . If
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,
compatibility mode LT (16.14.6) is set, ngspice will accept the RKM notation for entering resistance or capacitance values, e.g. 2K7 or 100R.
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).
.AC
start an ac simulation (15.3.1).
.CONTROL
start a .control section (16.4.3).
.CSPARAM
define parameter(s) made available in a control section (2.11).
.DC
start a dc simulation (15.3.2).
.DISTO
start a distortion analysis simulation (15.3.3).
.ELSE
conditional branching in the netlist (2.13).
.ELSEIF
conditional branching in the netlist (2.13).
.END
end of the netlist (2.3.2).
.ENDC
end of the .control section (16.4.3).
.ENDIF
conditional branching in the netlist (2.13).
.ENDS
end of subcircuit definition (2.5.2).
.FOUR
Fourier analysis of transient simulation output (15.6.4).
.FUNC
define a function (2.10).
.GLOBAL
define global nodes (2.6).
.IC
set initial conditions (15.2.2).
.IF
conditional branching in the netlist (2.13).
.INCLUDE
include part of the netlist (2.7).
.LIB
include a library (2.8).
.MEAS
measurements during the simulation (15.4).
.MODEL
list of device model parameters (2.4).
.NODESET
set initial conditions (15.2.1).
.NOISE
start a noise simulation (15.3.4).
.OP
start an operating point simulation (15.3.5).
.OPTIONS
set simulator options (15.1).
.PARAM
define parameter(s) (2.9).
.PLOT
printer plot during batch simulation (15.6.3).
.PRINT
tabular listing during batch simulation (15.6.2).
.PROBE
save device currents, voltages and differential voltages (15.6.5).
.PSS
start a periodic steady state analysis (15.3.12).
.PZ
start a pole-zero analysis simulation (15.3.6).
.SAVE
name simulation result vectors to be saved (15.6.1).
.SENS
start a sensitivity analysis (15.3.7).
.SP
S parameter analysis (15.3.8).
.SUBCKT
start of subcircuit definitions (2.5).
.TEMP
set the ciruit temperature (2.12).
.TF
start a transfer function analysis (15.3.9).
.TITLE
title of the netlist (2.3.1).
.TRAN
start a transient simulation (15.3.10).
.WIDTH
width of printer plot (15.6.7).
Examples:
The title line must be the first in the input file. Its contents are printed verbatim as the heading for each section of output.
As an alternative, you may place a .TITLE <any title> line anywhere in your input deck. The first line of your input deck will be overridden by the
contents of this line following the .TITLE statement.
******************************
* additional lines following
*...
.TITLE Test of CAM cell
* additional lines following
*...
Examples:
.end
The .end line must always be the last in the input file. Note that the period is an integral part of the name.
2.3.3 Comments
General Form:
* <any comment>
Examples:
The asterisk in the first column indicates that this line is a comment line. Comment lines may be placed anywhere in the circuit description.
Examples:
ngspice supports comments that begin with double characters `$ ' (dollar plus space) or `//'. For readability you should precede each comment
character with a space. ngspice will accept the single character `$'.
Please note that the `$' character is not a valid end-of-line comment delimiter, if the PSPICE compatibility mode (16.14.5) has been chosen. Then '$'
becomes an ordinary character.
<any command>
+ <continuation of any command> ; some comment
+ <further continuation of any command>
If input lines get overly long, they may be split into two or more lines (e.g. for better readability). Internally they will be merged into a single line.
Each follow-up line starts with character '+' plus additional space. Follow-up lines have to follow immediately after each other. End-of-line comments
will be ignored. Lines may also be continued by ending the line with two backslashes, as used in Unix shells. The following lines do not allow using
continuation lines: .title, .lib, and .include.
Examples:
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 the device is connected to, and the device model
name. In addition, other optional parameters may be specified for some devices: geometric factors and an initial condition (see the following section
on Transistors (8 to 11) and Diodes (7) for more details). mname in the above is the model name, and type is one of the following fifteen types:
The subcircuit is defined in the input deck by a grouping of element cards delimited by the .subckt and the .ends cards (or the keywords defined by
the substart and subend options (see 17.7)); 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 that begins with the letter `X'. A complete
example of all three of these cards follows:
Example:
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. An example of subcircuit usage is given in
Chapt. 21.6.
General form:
Examples:
.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 that 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) that is always global. If you use parameters, the .SUBCKT line will be
extended (see 2.9.3).
General form:
.ENDS <SUBNAM>
Examples:
.ENDS OPAMP
The .ENDS 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. The name is needed only when nested subcircuit definitions are being made.
General form:
Examples:
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 (see 2.9.3).
2.6 .GLOBAL
General form:
Examples:
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.
2.7 .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.
There is no restriction on the file name imposed by ngspice beyond those imposed by the local operating system.
2.8 .LIB
General form:
Examples:
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.
If the compatibility mode (16.14) is set to 'ps' by set ngbehavior=ps (17.7) in spinit (16.5) or .spiceinit (16.6), then a simplified syntax .LIB
filename is available: a warning is issued and filename is simply included as described in Chapt. 2.7.
General form:
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 characters. The
variables time, temper, and hertz (see 5.1.1) are not valid identifier names. Other restrictions on naming conventions apply as well, see 2.9.6.
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.
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.
General form:
{ <expr> }
Examples:
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 (see Chapt. 2.9.5). 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.
General form:
Examples:
<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.
General form:
Examples:
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> } .
* Param-example
.param amplitude= 1V
*
.subckt myfilter in out rval=100k cval=100nF
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
As expected, atoms, built-in function calls and stuff within parentheses are evaluated before the other operators. The operators are evaluated following
a list of precedence close to the one of the C language. For equal precedence binary ops, evaluation goes left to right. Functions operate on real values
only!
The evaluation of the power functions ** or ^ depends on the compatibility mode (16.14.1) chosen.
The number zero is used to represent boolean False. Any other number represents boolean True. The result of logical operators is 1 or 0. An example
input file is shown below:
* Logical operators
v1or 1 0 {1 || 0}
v1and 2 0 {1 && 0}
v1not 3 0 {! 1}
v1mod 4 0 {5 % 3}
v1div 5 0 {5 \ 3}
v0not 6 0 {! 0}
.control
op
print allv
.endc
.end
min(x, y)
max(x, y)
sgn(x) 1.0 for x > 0, 0.0 for x == 0, -1.0 for x < 0
ternary_fcn(x, y, z) x ? y : z
gauss(nom, rvar, sigma) nominal value plus variation drawn from Gaussian
distribution with mean 0 and standard deviation rvar
(relative to nominal), divided by sigma
agauss(nom, avar, sigma) nominal value plus variation drawn from Gaussian
distribution with mean 0 and standard deviation avar
(absolute), divided by sigma
unif(nom, rvar) nominal value plus relative variation (to nominal)
uniformly distributed between +/-rvar
aunif(nom, avar) nominal value plus absolute variation uniformly
distributed between +/-avar
limit(nom, avar) nominal value +/-avar, depending on random number in
[-1, 1[ being > 0 or < 0
suffix value
g 1e9
meg 1e6
k 1e3
m 1e-3
u 1e-6
n 1e-9
p 1e-12
f 1e-15
Note: there are intentional redundancies in expression syntax, e.g. x^y , x**y and pwr(x,y) all have nearly the same result.
Confusion may arise in ngspice because of its multiple numerical expression features. The .param lines and the brace expressions (see Chapt. 2.10)
are evaluated in the front-end, that is, just after the subcircuit expansion. (Technically, the X lines are kept as comments in the expanded circuit so that
the actual parameters can be correctly substituted). Therefore, after the netlist expansion and before the internal data setup, all number attributes in the
circuit are known constants. However, there are circuit elements in Spice that accept arithmetic expressions not evaluated at this point, but only later
during circuit analysis. These are the arbitrary current and voltage sources (B-sources, 5), as well as E- and G-sources and R-, L-, or C-devices. The
syntactic difference is that `compile-time' expressions are within braces, but `run-time' expressions have no braces. To make things more complicated,
the back-end ngspice scripting language accepts arithmetic/logic expressions that operate only on its own scalar or vector data sets (17.2). Please see
Chapt. 2.14.
It would be desirable to have the same expression syntax, operator and function set, and precedence rules, for the three contexts mentioned above. In
the current Numparam implementation, that goal is not achieved.
2.10 .FUNC
This keyword defines a function. The syntax of the expression is the same as for a .param (2.9.5).
General form:
Examples:
.func will initiate a replacement operation. After reading the input files, and before parameters are evaluated, all occurrences of the icos(x) function
will be replaced by cos(x)-1. All occurrences of f(x,y) will be replaced by x*y. Function statements may be nested to a depth of t.b.d..
2.11 .CSPARAM
Create a constant vector (see 17.8.2) from a parameter in plot (17.3) const.
General form:
Examples:
.param pippo=5
.param pp=6
.csparam pippp={pippo + pp}
.param p={pp}
.csparam pap='pp+p'
In the example shown, vectors pippp, and pap are added to the constants that already reside in plot const, having length one and real values. These
vectors are generated during circuit parsing and thus cannot be changed later (same as with ordinary parameters). They may be used in ngspice scripts
and .control sections (see Chapt. 17).
The use of .csparam is still experimental and has to be tested. A simple usage is shown below.
* test csparam
.param TEMPS = 27
.csparam newt = {3*TEMPS}
.csparam mytemp = '2 + TEMPS'
.control
echo $&newt $&mytemp
.endc
.end
2.12 .TEMP
Sets the circuit temperature in degrees Celsius.
General form:
.temp value
Examples:
.temp 27
This card overrides the circuit temperature given in an .option line (15.1.1).
General form:
.if(boolean expression)
...
.elseif(boolean expression)
...
.else
...
.endif
Example 1:
v1 1 0 1
R1 1 0 2
Example 2:
M1 1 2 3 4 N1 W=1 L=0.5
.if(m0==1)
.model N1 NMOS level=49 Version=3.1
.elseif(m1==1)
.model N1 NMOS level=49 Version=3.2.4 $ <-- selected
.else
.model N1 NMOS level=49 Version=3.3.0
.endif
Nesting of .IF-.ELSE(IF)-.ENDIF blocks is possible. Several .elseif (but of course only one .else)are allowed per block (please see example
ngspice/tests/regression/misc/if-elseif.cir). However some restrictions apply, as the following netlist components are not supported within the
.IF-.ENDIF block: .SUBCKT, .INC, .LIB, and .PARAM.
2.14.1 Parameters
Parameters (Chapt. 2.9.1) and functions, either defined within the .param statement or with the .func statement (Chapt. 2.10) are evaluated before
any simulation is started, that is during the setup of the input and the circuit. Therefore these statements may not contain any simulation output
(voltage or current vectors), because it is simply not yet available. The syntax is described in Chapt. 2.9.5. During the circuit setup all functions are
evaluated, all parameters are replaced by their resulting numerical values. Thus it will not be possible to get feedback from a later stage (during or
after simulation) to change any of the parameters.
If you want to use parameters from 2.9.1 inside your control script, you may use .csparam (2.11) or apply a trick by defining a voltage source with
the parameter as its value, and then have it available as a vector (e.g. after a transient simulation) with a then constant output (the parameter). A
feedback from here back into parameters (2.14.1) is never possible. Also you cannot access non-linear sources of the preceding simulation. However
you may start a first simulation inside your control script, then evaluate its output using expressions, change some of the element or model parameters
with the alter and altermod statements (see Chapt. 17.5.3) and then automatically start a new simulation.
Expressions and scripting are powerful tools within ngspice, and we will enhance the examples given in Chapt. 21 continuously to describe these
features.
bipolar amplifier
VCC vcc 0 5
Vin in 0 dc 0 ac 1 sin(0 1m 500)
After the first line, which is always a title line only, the netlist starts. Each line here is a device instance (except for lines starting with a dot '.'). We
have simple circuit elements that consist of a single line only, e.g. resistors like R3. In its simplest implementation, the resistor model does not need
any model parameters except for the resistance value (same for capacitors like Cout). Netlist lines like R3 vcc intc 10k are called instance lines, as
each line is the representation of an instance of a generic model hard-coded into the ngspice simulator (here: resistor). R3 denotes the device name. Its
first character R denotes a resistor. The next two tokens vcc intc are the two nodes of the resistor, 10k is the resistance value. Equal node names on
different devices denote a connection between these nodes.
A more complex device is described by the instance line Q1 intc intb 0 BC546B. Q denotes a bipolar transistor, intc intb 0 are the three nodes
collector, base, and emitter. BC546B is the name of a model parameter set, named after a real transistor and describing (together with the
implemented bipolar transistor model) its electrical behavior. The associated model parameters are given in the line .model BC546B npn
(IS=7.59E-15 ...). This is not an instance line, because starting with a dot. It contains the model parameters as supplied by the device manufacturer or
by people having them extracted from the electrical behavior and data sheet (to be found e.g. on his or her web pages). BC546B is the name of the
model parameter set and relates it to the device instance. npn is the type of the device. The parameters (name=value) are given in brackets.
The instance Q1... requires model parameters. For a quick test one may do without device maker's model parameters.
If you enter the bipolar transistor instance as shown above, you make use of a default model parameter set supplied by ngspice. defaultmod is an
arbitrary name. This procedure models a generic bipolar transistor, not resembling any commercial device. The default parameter values may be
assessed by the command showmod Q1.
You will get more information on devices, instances and models in the following chapters 3.3 to 12.
d1 2 0 mydiode m=10
d01 1 0 mydiode
d02 1 0 mydiode
d03 1 0 mydiode
d04 1 0 mydiode
d05 1 0 mydiode
d06 1 0 mydiode
d07 1 0 mydiode
d08 1 0 mydiode
d09 1 0 mydiode
d10 1 0 mydiode
...
The d1 instance connected between nodes 2 and 0 is equivalent to the 10 parallel devices d01-d10 connected between nodes 1 and 0.
Example 1:
.param madd = 6
X1 a b sub1 m=5
.subckt sub1 a1 b1
Cs1 a1 b1 C=5p m='madd-2'
.ends
Example 2:
.param madd = 4
X1 a b sub1 m=3
.subckt sub1 a1 b1
X2 a1 b1 sub2 m='madd-2'
.ends
.subckt sub2 a2 b2
Cs2 a2 b2 3p m=2
.ends
Using m may fail to correctly describe geometrical properties for real devices like MOS transistors.
because the former may suffer from small width (or edge) effects, whereas the latter is simply a wide transistor.
The model line starts with the token .model, followed by the model name, the model type and at least one model parameter, here tc1=0.001. There are
complex models with more than 100 model parameters.
Instance parameters are listed in each of the following device descriptions. Model parameters sometimes are given below as well, for complex models
like the BSIM transistor models, they are available in the model makers documentation. Instance parameters may also be placed in the .model line.
Thus they are recognized by each device instance referring to that model. Their values may be overridden for a specific instance of a device by
placing them additionally onto its instance line.
The .NODESET control line (see Chapt. 15.2.1) serves a similar purpose as the OFF option. The .NODESET option is easier to apply and is the preferred
means to aid convergence. The second form of initial conditions are specified for use with the transient analysis. These are true `initial conditions' as
opposed to the convergence aids above. See the description of the .IC control line (Chapt. 15.2.2) and the .TRAN control line (Chapt. 15.3.10) for a
detailed explanation of initial conditions.
General form:
Examples:
R1 1 2 100
RC1 12 17 1K
R2 5 7 1K ac=2K
RL 1 4 2K m=2
Ngspice has a fairly complex model for resistors. It can simulate both discrete and semiconductor resistors. Semiconductor resistors in ngspice means:
resistors described by geometrical parameters. So, do not expect detailed modeling of semiconductor effects.
n+ and n- are the two element nodes, value is the resistance (in ohms) and may be positive or negative1 but not zero.
Simulating small valued resistors: If you need to simulate very small resistors (0.001 Ohm or less), you should use
CCVS (transresistance). It is less efficient but improves overall numerical accuracy. Consider a small resistance as a
large conductance.
Ngspice can assign a resistor instance a different value for AC analysis, specified using the ac keyword. This value must not be zero as described
above. The AC resistance is used in AC analysis only (neither Pole-Zero nor Noise). If you do not specify the ac parameter, it is defaulted to value.
V A L U E s cal e
𝑅𝑛𝑜𝑚 =
𝑚
ac s cal e
𝑅𝑎𝑐𝑛𝑜𝑚 = .
𝑚
If you want to simulate temperature dependence of a resistor, you need to specify its temperature coefficients, using a .model line or as instance
parameters, like in the examples below:
Examples:
The temperature coefficients tc1 and tc2 describe a quadratic temperature dependence (see equation 6) of the resistance. If given in the instance line
(the R... line) their values will override the tc1 and tc2 of the .model line (3.3.3). Ngspice has an additional temperature model equation 12
parameterized by tce given in model or instance line. If all parameters are given (quadratic and exponential) the exponential temperature model is
chosen.
where 𝑇 is the circuit temperature, 𝑇0 is the nominal temperature, and 𝑇𝐶𝐸 is the exponential temperature coefficients.
Instance temperature is useful even if resistance does not vary with it, since the thermal noise generated by a resistor depends on its absolute
temperature. Resistors in ngspice generates two different noises: thermal and flicker. While thermal noise is always generated in the resistor, to add a
flicker noise2 source you have to add a .model card defining the flicker noise parameters. It is possible to simulate resistors that do not generate any
kind of noise using the noisy (or noise) keyword and assigning zero to it, as in the following example:
Example:
If you are interested in temperature effects or noise equations, read the next section on semiconductor resistors.
General form:
Examples:
RLOAD 2 10 10K
RMOD 3 7 RMODEL L=10u W=1u
This is the more general form of the resistor presented before (3.3.1) and allows the modeling of temperature effects and for the calculation of the
actual resistance value from strictly geometric information and the specifications of the process. If value is specified, it overrides the geometric
information and defines the resistance. If mname is specified, then the resistance may be calculated from the process information in the model mname
and the given length and width. If value is not specified, then mname and length must be specified. If width is not specified, then it is taken from
the default width given in the model.
The (optional) temp value is the temperature at which this device is to operate, and overrides the temperature specification on the .option control line
and the value specified in dtemp.
Ω
Name Parameter Units Default Example
°𝐶
TC1 first order temperature coeff. 0.0 -
Ω
°𝐶2
TC2 second order temperature coeff. 0.0 -
Ω
□
RSH sheet resistance - 50
The sheet resistance is used with the narrowing parameter and l and w from the resistor device to determine the nominal resistance by the formula:
𝑙 − S HORT
𝑅𝑛𝑜𝑚 = r sh
𝑤 − N A RROW
DEFW is used to supply a default value for w if one is not specified for the device. If either rsh or l is not specified, then the standard default resistance
value of 1 mOhm is used. TNOM is used to override the circuit-wide value given on the .options control line where the parameters of this model have
been measured at a different temperature. After the nominal resistance is calculated, it is adjusted for temperature by the formula:
2
𝑅(𝑇) = 𝑅(TNO M )(1 + 𝑇𝐶1 (𝑇 − TNO M ) + 𝑇𝐶2 (𝑇 − TNO M ) )
where 𝑅(T NOM ) = 𝑅𝑛𝑜𝑚 | 𝑅𝑎𝑐𝑛𝑜𝑚 . In the above formula, `𝑇' represents the instance temperature, which can be explicitly set using the temp keyword
1
or calculated using the circuit temperature and dtemp, if present. If both temp and dtemp are specified, the latter is ignored. Ngspice improves SPICE's
𝑓
resistors noise model, adding flicker noise ( ) to it and the noisy (or noise) keyword to simulate noiseless resistors. The thermal noise in resistors
is modeled according to the equation:
4𝑘𝑇
𝑖‾𝑅2 = ∆𝑓
𝑅
where `𝑘' is the Boltzmann's constant, and `𝑇' the instance temperature.
K F 𝐼𝑅AF
𝑖𝑅𝑓𝑛
2‾
= 𝑊𝐹 𝐿𝐹 𝐸𝐹 ∆ 𝑓
𝑊 𝐿 𝑓
Ω
□
A small list of sheet resistances (in ) for conductors is shown below. The table represents typical values for MOS processes in the 0.5 - 1 um
range. The table is taken from: N. Weste, K. Eshraghian - Principles of CMOS VLSI Design 2nd Edition, Addison Wesley.
General form:
Examples:
Expression may be an equation or an expression containing node voltages or branch currents (in the form of i(vm)) and any other terms as given for
the B source and described in Chapt. 5.1. It may contain parameters (2.9.1) and the special variables time, temper, and hertz (5.1.2). An example file
is given below. Small signal noise in the resistor (15.3.4) may be evaluated as white noise, depending on resistance, temperature and tc1, tc2. To
enable noise calculation, add the flag noisy=1 to the instance line. As a default the behavioral resistor is noiseless.
Non-linear resistor
.param R0=1k Vi=1 Vt=0.5
* resistor depending on control voltage V(rr)
R1 rr 0 r = 'V(rr) < {Vt} ? {R0} : {2*R0}'
* control voltage
V1 rr 0 PWL(0 0 100u {Vi})
.control
unset askquit
tran 100n 100u uic
plot i(V1)
.endc
.end
For now a detailed description is available in the Verilog A source code file to be found a src/spicelib/devices/adms/r2_cmc/admsva/r2_cmc.va.
r2_cmc
v1 1 0 10
Rr2_cmc 1 0 rmodel w=1u l=20u isnoisy=1
.model rmodel r(level=2 rsh=200 xl=0.2u xw=-0.05u
+ p3=0.12 q3=1.6 p2=0.015 q2=3.8 tc1=1.5e-4 tc2=7e-7)
.control
op
let res = v(1) / -v1#branch
print res .endc
.end
3.3.6 Capacitors
General form:
Examples:
CBYP 13 0 1UF
COSC 17 23 10U IC=3V
Ngspice provides a detailed model for capacitors. Capacitors in the netlist can be specified giving their capacitance or their geometrical and physical
characteristics. Following the original SPICE3 `convention', capacitors specified by their geometrical or physical characteristics are called
`semiconductor capacitors' and are described in the next section.
In this first form n+ and n- are the positive and negative element nodes, respectively and value is the capacitance in Farads.
Capacitance can be specified in the instance line as in the examples above or in a .model line, as in the example below:
C1 15 5 cstd
C2 2 7 cstd
.model cstd C cap=3n
If you want to simulate temperature dependence of a capacitor, you need to specify its temperature coefficients, using a .model line, like in the
example below:
The (optional) initial condition is the initial (time zero) value of capacitor voltage (in Volts). Note that the initial conditions (if any) apply only if the
uic option is specified on the .tran control line.
The temperature coefficients tc1 and tc2 describe a quadratic temperature dependence (see equation83) of the capacitance. If given in the instance
line (the C... line) their values will override the tc1 and tc2 of the .model line (3.3.8).
General form:
Examples:
CLOAD 2 10 10P
CMOD 3 7 CMODEL L=10u W=1u
This is the more general form of the Capacitor presented in section (3.3.6), and allows for the calculation of the actual capacitance value from strictly
geometric information and the specifications of the process. If value is specified, it defines the capacitance and both process and geometrical
information are discarded. If value is not specified, the capacitance is calculated from information contained model mname and the given length and
width (l, w keywords, respectively).
It is possible to specify mname only, without geometrical dimensions and set the capacitance in the .model line (3.3.6).
𝑚2
CJ junction bottom capacitance - 5e-5
𝐹
𝑚
CJSW junction sidewall capacitance - 2e-11
°𝐶
TC1 first order temperature coeff. 0.0 0.001
𝐹
°𝐶2
TC2 second order temperature coeff. 0.0 0.0001
𝑚
DI relative dielectric constant - 1
𝐶𝑛𝑜𝑚 = C A P ⋅ s cal e ⋅ 𝑚
If neither value nor CAP are specified, then geometrical and physical parameters are take into account:
CJ can be explicitly given on the .model line or calculated by physical parameters. When CJ is not given, is calculated as:
D I𝜀0
C𝐽 = if D Iis sp e ci fi e d,
T HI C K
𝜀𝑆𝑖𝑂2
CJ = o th e r wis e .
T HI C K
𝐹
If the relative dielectric constant is not specified the one for SiO2 is used. The values of the constants are 𝜀0 = 8.854214871𝑒 − 12 and
𝑚
𝐹
𝜀𝑆𝑖𝑂2 = 3.4531479969𝑒 − 11 . The nominal capacitance is then computed as:
𝑚
𝐶𝑛𝑜𝑚 = 𝐶0 s cal e 𝑚
After the nominal capacitance is calculated, it is adjusted for temperature by the formula:
2
𝐶(𝑇) = 𝐶(TNO M )(1 + 𝑇𝐶1 (𝑇 − TNO M ) + 𝑇𝐶2 (𝑇 − TNO M ) )
In the above formula, `𝑇' represents the instance temperature, which can be explicitly set using the temp keyword or calculated using the circuit
temperature and dtemp, if present.
General form:
Examples:
Expression may be an equation or an expression containing node voltages or branch currents (in the form of i(vm)) and any other terms as given for
the B source and described in Chapt. 5.1. It may contain parameters (2.9.1) and the special variables time, temper, and hertz (5.1.2).
Behavioral Capacitor
.param Cl=5n Ch=1n Vt=1m Il=100n
.ic v(cc) = 0 v(cc2) = 0
* capacitor depending on control voltage V(cc)
C1 cc 0 c = 'V(cc) < {Vt} ? {Cl} : {Ch}'
I1 0 1 {Il}
Exxx n1-copy n2 n2 cc2 1
Cxxx n1-copy n2 1
Bxxx cc2 n2 I = '(V(cc2) < {Vt} ? {Cl} : {Ch})' * i(Exxx)
I2 n2 22 {Il}
vn2 n2 0 DC 0
* measure charge by integrating current
aint1 %id(1 cc) 2 time_count
aint2 %id(22 cc2) 3 time_count
.model time_count int(in_offset=0.0 gain=1.0
+ out_lower_limit=-1e12 out_upper_limit=1e12
+ limit_range=1e-9 out_ic=0.0)
.control
unset askquit
tran 100n 100u
plot v(2)
plot v(cc) v(cc2)
.endc
.end
3.3.10 Inductors
General form:
Examples:
LLINK 42 69 1UH
LSHUNT 23 51 10U IC=15.7MA
The inductor device implemented into ngspice has many enhancements over the original one.n+ and n- are the positive and negative element nodes,
respectively. value is the inductance in Henry. The initial condition (a curremt through L) becomes effective when the uic parameter is set on the
.tran line. Inductance can be specified in the instance line as in the examples above or in a .model line, as in the example below:
L1 15 5 indmod1
L2 2 7 indmod1
.model indmod1 L ind=3n
The nt is used in conjunction with a .model line, and is used to specify the number of turns of the inductor. If you want to simulate temperature
dependence of an inductor, you need to specify its temperature coefficients, using a .model line, like in the example below:
The (optional) initial condition is the initial (time zero) value of inductor current (in Amps) that flows from n+, through the inductor, to n-. Note that
the initial conditions (if any) apply only if the UIC option is specified on the .tran analysis line.
v alu e s cal e
𝐿𝑛𝑜𝑚 =
𝑚
°𝐶
TC1 first order temperature coeff. 0.0 0.001
𝐻
°𝐶2
TC2 second order temperature coeff. 0.0 0.0001
v alu e s cal e
𝐿𝑛𝑜𝑚 =
𝑚
IND s cal e
𝐿𝑛𝑜𝑚 =
𝑚
If neither value nor IND are specified, then geometrical and physical parameters are taken into account. In the following formulas
NT refers to both instance and model parameter (instance parameter overrides model parameter):
M U 𝜇0 NT 2 𝜋D I A 2
𝐿𝑛𝑜𝑚 = i f D I A is sp e cifi e d,
4L E N G T H
{
M U 𝜇0 NT 2 C S E C T
𝐿𝑛𝑜𝑚 = o th e r wis e .
LENGTH
𝜇𝐻
with 𝜇0 = 1.25663706143592 . DIA takes preference over CSECT. 𝑘𝑙 is the geometry correction factor according to Lundin (see D. W. Knight, pp.
𝑚
35-36), which is important when inductor length and diameter have the same order of magnitude. After the nominal inductance is calculated, it is
adjusted for temperature by the formula
2
𝐿(𝑇) = 𝐿(TNOM)(1 + 𝑇𝐶1 (𝑇 − TNO M ) + 𝑇𝐶2 (𝑇 − TNO M ) ) ,
where 𝐿(T NOM ) = 𝐿𝑛𝑜𝑚 . In the above formula, `𝑇' represents the instance temperature, which can be explicitly set using the temp keyword or
calculated using the circuit temperature and dtemp, if present.
General form:
Examples:
LYYYYYYY and LZZZZZZZ are the names of the two coupled inductors, and value is the coefficient of coupling, K, which must be greater than 0
and less than or equal to 1. Using the `dot' convention for drawing the coupled inductors, place a `dot' on the first node of each inductor. If you have
more than two inductors interacting, pairwise coupling is supported.
L1 1 0 10u
L2 2 0 11u
L3 3 0 10u
K12 L1 L2 0.99
K23 L2 L3 0.99
K13 L1 L3 0.98
When there are more than two inductors coupled for interaction, some combination of coupling constants are not possible physically because the
magnetic fields then would violate energy conservation. ngspice checks the coupling matrix for such conditions and issues a warning.
General form:
Examples:
Expression may be an equation or an expression containing node voltages or branch currents (in the form of i(vm)) and any other terms as given for
the B source and described in Chapt. 5.1. It may contain parameters (2.9.1) and the special variables time, temper, and hertz (5.1.2).
Variable inductor
.param Ll=0.5m Lh=5m It=50u Vi=2m
.ic v(int21) = 0
* fixed inductor
L3 33 331 {Ll}
* measure current through inductor
vm33 331 0 dc 0
* voltage on inductor
V3 33 0 {Vi}
.control
unset askquit
tran 1u 100u uic
plot i(Vm) i(vm33)
plot i(vm21) i(vm33)
plot i(vm)-i(vm21)
.endc
.end
3.3.15 Switches
model CSW). A switching hysteresis may be defined, as well as on- and off-resistances (0 < 𝑅 < ∞).
Two types of switches are available: a voltage controlled switch (type SXXXXXX, model SW) and a current controlled switch (type WXXXXXXX,
General form:
Examples:
s1 1 2 3 4 switch1 ON
s2 5 6 3 0 sm2 off
Switch1 1 2 10 0 smodel1
w1 1 2 vclock switchmod1
W2 3 0 vramp sm1 ON
wreset 5 6 vclck lossyswitch OFF
Nodes 1 and 2 are the nodes between which the switch terminals are connected. The model name is mandatory while the initial conditions are
optional. For the voltage controlled switch, nodes 3 and 4 are the positive and negative controlling nodes respectively. For the current controlled
switch, the controlling current is that through the specified voltage source. The direction of positive controlling current flow is from the positive node,
through the source, to the negative node.
The instance parameters ON or OFF are required, when the controlling voltage (current) starts inside the range of the hysteresis loop (different
outputs during forward vs. backward voltage or current ramp). Then ON or OFF determine the initial state of the switch.
(*) Or 1/𝐺𝑀𝐼𝑁, if you have set 𝐺𝑀𝐼𝑁 to any other value, see the .OPTIONS control line (15.1.2) for a description of 𝐺𝑀𝐼𝑁, its default value results
in an off-resistance of 1.0e+12 ohms.
The use of an ideal element that is highly nonlinear such as a switch can cause large discontinuities to occur in the circuit node voltages. A rapid
change such as that associated with a switch changing state can cause numerical round-off or tolerance problems leading to erroneous results or time
step difficulties. The user of switches can improve the situation by taking the following steps:
First, it is wise to set the ideal switch impedance just high or low enough to be negligible with respect to other circuit elements. Using switch
impedances that are close to `ideal' in all cases aggravates the problem of discontinuities mentioned above. Of course, when modeling real
devices such as MOSFETS, the on resistance should be adjusted to a realistic level depending on the size of the device being modeled.
If a wide range of ON to OFF resistance must be used in the switches (ROFF/RON > 1e+12), then the tolerance on errors allowed during
transient analysis should be decreased by using the .OPTIONS control line and specifying TRTOL to be less than the default value of 7.0.
When switches are placed around capacitors, then the option CHGTOL should also be reduced. Suggested values for these two options are 1.0
and 1e-16 respectively. These changes inform ngspice to be more careful around the switch points so that no errors are made due to the rapid
change in the circuit.
Switch test
.tran 2us 5ms
*switch control voltage
v1 1 0 DC 0.0 PWL(0 0 2e-3 2 4e-3 0)
*switch control voltage starting inside hysteresis window
*please note influence of instance parameters ON, OFF
v2 2 0 DC 0.0 PWL(0 0.9 2e-3 2 4e-3 0.4)
*switch control current
i3 3 0 DC 0.0 PWL(0 0 2e-3 2m 4e-3 0) $ <--- switch control current
*load voltage
v4 4 0 DC 2.0
*input load for current source i3
r3 3 33 10k
vm3 33 0 dc 0 $ <--- measure the current
* ouput load resistors
r10 4 10 10k
r20 4 20 10k
r30 4 30 10k
r40 4 40 10k
*
s1 10 0 1 0 switch1 OFF
s2 20 0 2 0 switch1 OFF
s3 30 0 2 0 switch1 ON
.model switch1 sw vt=1 vh=0.2 ron=1 roff=10k
*
w1 40 0 vm3 wswitch1 off
.model wswitch1 csw it=1m ih=0.2m ron=1 roff=10k
*
.control
run
plot v(1) v(10)
plot v(10) vs v(1) $ <-- get hysteresis loop
plot v(2) v(20) $ <--- different initial values
plot v(20) vs v(2) $ <-- get hysteresis loop
plot v(2) v(30) $ <--- different initial values
plot v(30) vs v(2) $ <-- get hysteresis loop
plot v(40) vs vm3#branch $ <--- current controlled switch hysteresis
.endc
.end
Examples:
VCC 10 0 DC 6
VIN 13 2 0.001 AC 1 SIN(0 1 1MEG)
ISRC 23 21 AC 0.333 45.0 SFFM(0 1 10K 5 1K)
VMEAS 12 9
VCARRIER 1 0 DISTOF1 0.1 -90.0
VMODULATOR 2 0 DISTOF2 0.01
IIN1 1 5 AC 1 DISTOF1 DISTOF2 0.001
n+ and n- are the positive and negative nodes, respectively. Note that voltage sources need not be grounded. Positive current is assumed to flow from
the positive node, through the source, to the negative node. A current source of positive value forces current to flow out of the n+ node, through the
source, and into the n- node. Voltage sources, in addition to being used for circuit excitation, are the `ammeters' for ngspice, that is, zero valued
voltage sources may be inserted into the circuit for the purpose of measuring current. They of course have no effect on circuit operation since they
represent short-circuits.
DC/TRAN is the dc and transient analysis value of the source. If the source value is zero both for dc and transient analyses, this value may be omitted. If
the source value is time-invariant (e.g., a power supply), then the value may optionally be preceded by the letters DC.
The keyword AC together with its value ACMAG (and optional value ACPHASE) are required when the voltage or current source is intended to become the
small signal source in an ac simulation. ACMAG is the ac magnitude and ACPHASE is the ac phase. The voltage or current source then will become a
reference for all nodes. All small signal node amplitude values obtained after the simulation have been divided by the reference ACMAG. A typcal ACMAG
value thus may be unity. Any measured phase has been shifted by ACPHASE. If ACPHASE is omitted, a value of zero is assumed. If the source is not an
ac small-signal input, the keyword AC and the ac values are to be avoided.
DISTOF1 and DISTOF2 are the keywords that specify that the independent source has distortion inputs at the frequencies F1 and F2 respectively (see the
description of the .DISTO control line). The keywords may be followed by an optional magnitude and phase. The default values of the magnitude and
phase are 1.0 and 0.0 respectively.
Any independent source can be assigned a time-dependent value for transient analysis. If a source is assigned a time-dependent value, the time-zero
value is used for dc analysis. There are nine independent source functions:
pulse,
exponential,
sinusoidal,
piece-wise linear,
single-frequency FM,
AM,
transient noise,
random voltages or currents,
external data (only with ngspice shared library),
and RF port
If parameters other than source values are omitted or set to zero, the default values shown are assumed. TSTEP is the printing increment and TSTOP is
the final time – see the .TRAN control line for an explanation.
4.1.1 Pulse
General form:
Examples:
A single pulse, without repetition count or phase offset, is described by the following table:
Time Value
0 V1
TD V1
TD+TR V2
TD+TR+PW V2
TD+TR+PW+TF V1
TSTOP V1
*) NP set to 0 or omitted denotes unlimited pulses. If compatibility mode (see 16.14.1) set ngbehavior=xs is set in .spiceinit, the 8th parameter is
the phase of the pulse signal (in degrees), which results in forward running (pos. value) or a delay (neg. value) of the pulse sequence.
4.1.2 Sinusoidal
General form:
Examples:
1
TD Delay 0.0 sec
𝑠𝑒𝑐
THETA Damping factor 0.0
𝑉0 if 0 ≤ t < 𝑇𝐷
𝑉(𝑡) = {
𝑉0 + 𝑉𝐴e −(𝑡 − 𝑇𝐷)𝑇𝐻𝐸𝑇𝐴 sin (2𝜋 ⋅ 𝐹𝑅𝐸𝑄 ⋅ (𝑡 − 𝑇𝐷) + 𝑃𝐻𝐴𝑆𝐸) i f 𝑇𝐷 ≤ 𝑡 < 𝑇𝑆𝑇𝑂𝑃.
4.1.3 Exponential
General form:
Examples:
⎛⎞ ⎧ 𝑉1 i f 0 ≤ 𝑡 < 𝑇𝐷1,
⎜⎟ ⎪
⎪
(𝑡 − 𝑇𝐷1)
⎜⎟ ⎪ 𝑉1 + 𝑉21(1 − 𝑒 𝑇𝐴𝑈1 ) if 𝑇𝐷1 ≤ 𝑡 < 𝑇𝐷2,
−
𝑉⎜𝑡⎟ =
⎜⎟ ⎨ ⎪ (𝑡 − 𝑇𝐷1) (𝑡 − 𝑇𝐷2)
⎜ ⎟ ⎪ 𝑉1 + 𝑉21(1 − 𝑒 ) + 𝑉12(1 − 𝑒 𝑇𝐴𝑈2 ) if 𝑇𝐷2 ≤ 𝑡 < 𝑇𝑆𝑇𝑂𝑃.
− −
𝑇𝐴𝑈1
⎜⎝ ⎟⎠ ⎪
⎩
General form:
Examples:
Each pair of values (𝑇𝑖 , 𝑉𝑖 ) specifies that the value of the source is 𝑉𝑖 (in Volts or Amps) at time = 𝑇𝑖 . The value of the source at intermediate values
the whole sequence of values (𝑇𝑖 , 𝑉𝑖 ) is issued once only, then the output stays at its final value. If r = 0, the whole sequence from time 0 to time Tn is
of time is determined by using linear interpolation on the input values. The parameter r determines a repeat time point. If r is set to -1 or is not given,
repeated forever. If r = 10ns, the sequence between 10ns and 50ns is repeated forever. The r value has to be one of the time points T1 to Tn of the
PWL sequence. If td is given, the whole PWL sequence is delayed by the value of td. Please note that for now r and td are available only with the
voltage source, not with the current source.
4.1.5 Single-Frequency FM
General Form:
Examples:
1
MDI Modulation index -
𝐻𝑧
𝑇𝑆𝑇𝑂𝑃
FS Signal frequency
General form:
AM(VA VO MF FC TD PHASES)
Examples:
TD Signal delay - 𝑠
PHASES Phase 0.0 degrees
General form:
Examples:
Transient noise is an experimental feature allowing (low frequency) transient noise injection and analysis. See Chapt. 15.3.11 for a detailed
description. NA is the Gaussian noise rms voltage amplitude, NT is the time between sample values (breakpoints will be enforced on multiples of this
value). NALPHA (exponent to the frequency dependency), NAMP (rms voltage or current amplitude) are the parameters for 1/f noise, RTSAM the random
telegraph signal amplitude, RTSCAPT the mean of the exponential distribution of the trap capture time, and RTSEMT its emission time mean. White
Gaussian, 1/f, and RTS noise may be combined into a single statement.
If you set NT and RTSAM to 0, the noise option TRNOISE ... is ignored. Thus you may switch off the noise contribution of an individual voltage source
VNOI by the command
set notrnoise
to your .spiceinit file (for all your simulations) or into your control section in front of the next run or tran command (for this specific and all
following simulations). The command
unset notrnoise
The noise generators are implemented into the independent voltage (vsrc) and current (isrc) sources.
General form:
Examples:
TYPE determines the random variates generated: 1 is uniformly distributed, 2 Gaussian, 3 exponential, 4 Poisson. TS is the duration of an individual
voltage value. TD is a time delay with 0 V output before the random voltage values start up. PARAM1 and PARAM2 depend on the type selected.
EXTERNAL
Examples:
Vex 1 0 dc 0 external
Iex i1 i2 dc 0 external <m = xx>
Voltages or currents may be set from the calling process, if ngspice is compiled as a shared library and loaded by the process. See Chapt. 19.6.3 for an
explanation.
4.1.11 RF Port
A voltage source VSRC may be defined as RF Port. To do so, there are at least two more parameters required. The first is portnum (integer) which
defines the VSRC as a RF Port. Portnum of all VSRCs defined as RF ports must start from 1 and count up to the number of RF ports. You cannot
have duplicate portnums. Then you have Z0 (real) which defines the internal impedance. If not provided, its default value is 50Ohm. When declaring
a RF ports, the VSRC now become a VSRC with Z0 Ohm in series. This extra resistor affects all simulations.
General form:
Examples:
V1 in 0 dc 0 ac 1 portnum 1 z0 100
At least two ports are required for the S-parameter simulation with the command .sp (15.3.8). If portnum is not provided, the voltage source VRSC
behaves as normal.
𝑖 = 𝑔𝑣 𝑣 = 𝑒𝑣 𝑖 = 𝑓𝑖 𝑣 = ℎ𝑖
where 𝑔, 𝑒, 𝑓, and ℎ are constants representing transconductance, voltage gain, current gain, and transresistance, respectively. Non-linear dependent
sources for voltages or currents (B, E, G) are described in Chapt. 5.
General form:
Examples:
G1 2 0 5 0 0.1
n+ and n- are the positive and negative nodes, respectively. Current flow is from the positive node, through the source, to the negative
node. nc+ and nc- are the positive and negative controlling nodes, respectively. value is the transconductance (in mhos). m is an optional multiplier to
the output current. val may be a numerical value or an expression according to 2.9.5 containing references to other parameters. Instance parameters
are listed in chapt. 31.3.6.
General form:
Examples:
E1 2 3 14 1 2.0
n+ is the positive node, and n- is the negative node. nc+ and nc- are the positive and negative controlling nodes, respectively. value is the voltage
gain. Instance parameters are listed in chapt. 31.3.7.
General form:
Examples:
F1 13 5 VSENS 5 m=2
n+ and n- are the positive and negative nodes, respectively. Current flow is from the positive node, through the source, to the negative node. vnam is
the name of a voltage source through which the controlling current flows. The direction of positive controlling current flow is from the positive node,
through the source, to the negative node of vnam. value is the current gain. m is an optional multiplier to the output current. Instance parameters are
listed in chapt. 31.3.4.
General form:
Examples:
HX 5 17 VZ 0.5K
n+ and n- are the positive and negative nodes, respectively. vnam is the name of a voltage source through which the controlling current flows. The
direction of positive controlling current flow is from the positive node, through the source, to the negative node of vnam. value is the transresistance
(in ohms). Instance parameters are listed in chapt. 31.3.5.
General form:
Examples:
B1 0 1 I=cos(v(1))+sin(v(2))
B2 0 1 V=ln(cos(log(v(1,2)^2)))-v(3)^4+v(2)^v(1)
B3 3 4 I=17
B4 3 4 V=exp(pi^i(vdd))
B5 2 0 V = V(1) < {Vlow} ? {Vlow} :
+ V(1) > {Vhigh} ? {Vhigh} : V(1)
n+ is the positive node, and n- is the negative node. The values of the V and I parameters determine the voltages and currents across and through the
device, respectively. If I is given then the device is a current source, and if V is given the device is a voltage source. One and only one of these
parameters must be given. All instance parameters are listed in chapter 31.3.1.
or
2
𝑉(𝑇) = 𝑉(TNO M)(1 + 𝑇𝐶1 (𝑇 − TNO M) + 𝑇𝐶2 (𝑇 − TNO M ) )
In the above formula, `𝑇' represents the instance temperature, which can be explicitly set using the temp keyword or calculated using the circuit
temperature and dtemp, if present. If both temp and dtemp are specified, the latter is ignored.
The small-signal AC behavior of the nonlinear source is a linear dependent source (or sources) with a proportionality constant equal to the derivative
(or derivatives) of the source at the DC operating point. The expressions given for V and I may be any function of voltages and currents through
voltage sources in the system.
Trigonometric functions:
cos, sin, tan, acos, asin, atan
Hyperbolic functions:
cosh, sinh, acosh, asinh, atanh
Exponential and logarithmic:
exp, ln, log, log10 (ln, log with base e, log10 with base 10)
Other:
abs, sqrt, u, u2, uramp, floor, ceil, i
Functions
of two variables are min, max, pow, **, pwr, ^
Functions
of three variables are a ? b:c
For convergence reasons the `exp' function has a limit of 14 for its argument, beyond that value it will increase linearily. The function `u' is the unit
step function, with a value of one for arguments greater than zero, a value of 0.5 at zero, and a value of zero for arguments less than zero. The
function `u2' returns a value of zero for arguments less than zero, one for arguments greater than one and assumes the value of the argument between
these limits. The function `uramp' is the integral of the unit step: for an input x, the value is zero if x is less than zero, or, if x is greater than or equal to
zero, the value is x. These three functions are useful in synthesizing piece-wise non-linear functions, though convergence may be adversely affected.
The function i(xyz) returns the current through the first node of device instance xyz.
Logical operators are !=, <>, >=, <=, ==, >, <, ||, &&, ! .
A ternary function is defined as a ? b : c , which means IF a, THEN b, ELSE c. Be sure to place a space in front of `?' to allow the parser
distinguishing it from other tokens.
The B source functions pow, **, ^, and pwr need some special care to avoid undefined regions in x1, as they differ from the common mathematical
usage (and from the functions depicted in chapt. 2.9.5).
The functions y = pow(x1,x2), x1**x2, and x1^x2 , all of them describing 𝑦 = 𝑥1𝑥2 , resolve to the following:
y = pow(fabs(x1), x2)
pow in the preceding line is the standard C math library function.
If the argument of log, ln, or sqrt becomes less than zero, the absolute value of the argument is used. If a divisor becomes zero or the argument of log
or ln becomes zero, an error will result. Other problems may occur when the argument for a function in a partial derivative enters a region where that
function is undefined.
Parameters may be used like {Vlow} shown in the example above. Parameters will be evaluated upon set up of the circuit, vectors like V(1) will be
evaluated during the simulation.
To get time into the expression you can integrate the current from a constant current source with a capacitor and use the resulting voltage (don't forget
to set the initial voltage across the capacitor).
Non-linear resistors, capacitors, and inductors may be synthesized with the nonlinear dependent source. Nonlinear resistors, capacitors and inductors
are implemented with their linear counterparts by a change of variables implemented with the nonlinear dependent source. The following subcircuit
will implement a nonlinear capacitor:
Bx 1 0 V = v(pos,neg)*v(pos,neg)
Non-linear resistors or inductors may be described in a similar manner. An example for a nonlinear resistor using this template is shown below.
5.1.3 par('expression')
The B source syntax may also be used in output lines like .plot as algebraic expressions for output (see Chapt.15.6.6 ).
Example: pwl_current
v(A) is the independent variable x. Each pair of values following describes the x,y functional relation: In this example at node A voltage of 0V the
current of 0A is generated - next pair gives 10mA flowing from ground to node 1 at 33V on node A and so forth.
Example: pwl_voltage
Monotony of the independent variable in the pwl definition is checked - non-monotonic x entries will stop the program execution. v(1) may be
−2 * 𝑖(𝑉𝑖𝑛 ). The value pairs may also be parameters, and have to be predefined by a .param statement. An example for the pwl function using all of
replaced by a controlling current source, or it may be replaced by time (for transient simulations). v(1) may also be replaced by an expression, e.g.
Rint2 2 0 1
Rint3 3 0 1
Rint4 4 0 1
Rint5 5 0 1
.control
dc Vin -6 6 0.2
plot v(2) v(3) v(4)-0.5 v(5)+0.5
.endc
.end
One characteristic to note: What happens when the controlling input (V(1) or −2 * 𝑖(𝑉𝑖𝑛 )) is outside of the given limits, e.g. smaller than x0 or larger
of the output curve, e.g. with (𝑦3 − 𝑦2)/(𝑥3 − 𝑥2), as seen with v(2) from example Btest2. If you want to limit the function, keeping the last y
than x3 in the example given above? New y values outside of the given range will be determined by adding x,y pairs calculated by extending the slope
value, e.g. y3, you have to add another point (x,y pair) with slightly extended x and y kept constant, e.g. 𝑥3 + 1,y3.
This gets important when we are for example using a behavioral resistor with pwl. In the example below, RR1 quickly moves towards (and beyond) 0,
which is unphysical and leads the transient simulation to fail, because the current through RR1 is unbounded. RR2 with its limit given by the
15.1ms,1 couple avoids such malfunctioning.
.control
option noinit
run
display
set xbrushwidth=2
plot rr1#branch rr2#branch ylimit 7 17
.endc
.end
General form:
EXXXXXXX n+ n- vol='expr'
Examples:
Expression may be an equation or an expression containing node voltages or branch currents (in the form of i(vm)) and any other terms as given for
the B source and described in Chapt. 5.1. It may contain parameters (2.9.1) and the special variables time, temper, hertz (5.1.2). ' or { } may be
used to delimit the function.
5.2.2 VALUE
Optional syntax:
EXXXXXXX n+ n- value={expr}
Examples:
5.2.3 TABLE
Data may be entered from the listings of a data table similar to the pwl B-Source (5.1.4). Data are grouped into x, y pairs. Expression may be an
equation or an expression containing node voltages or branch currents (in the form of i(vm)) and any other terms as given for the B source and
described in Chapt. 5.1. It may contain parameters (2.9.1). ' or { } may be used to delimit the function. Expression delivers the x-value, which is
used to generate a corresponding y-value according to the tabulated value pairs, using linear interpolation. If the x-value is below x0 , y0 is returned,
above x2 y2 is returned (limiting function). The value pairs have to be real numbers, parameters are not allowed.
5.2.4 POLY
see E-Source at Chapt. 5.5.
5.2.5 LAPLACE
Currently ngspice does not offer a direct E-Source element with the LAPLACE option. There is however a XSPICE code model equivalent called
s_xfer (see Chapt. 12.2.18), which you may invoke manually. The XSPICE option has to be enabled (32.1). AC (15.3.1) and transient analysis
(15.3.10) is supported.
where you have the voltage of node 1 as input, an intermediate output node int_4 and an E-source as buffer to keep the name `ELOPASS' available if
further processing is required.
If the controlling expression is more complex than just a voltage node, you may add a B-Source (5.1) for evaluating the expression before entering the
A-device.
5.2.6 FREQ
Currently ngspice does not offer a direct E-Source element with the FREQ option but it is implemented by a XSPICE code model equivalent called
xfer (see 12.2.19) that is automatically invoked by rewriting the netlist. The XSPICE option has to be enabled (32.1) and only AC (15.3.1) analysis is
supported.
This E-Source:
produces a complex voltage determined by multiplying an input differential voltage (v(20, 21)) by a complex-valued PWL function of the
simulation frequency (transfer function). The DB keyword indicates that the second column is gain in db and the third is phase in degrees.
Alternative keywords are MAG (linear gain), RAD (phase in radians), DEG (phase in degrees, already the default) or R_I (real and imaginary
parts).
5.2.7 AND/OR/NAND/NOR
This form of E-source provides simple behavioural implementations of basic logic gates with analog inputs and output. It is implemented by a
XSPICE code model called multi_input_pwl (see 12.2.10) that is automatically invoked by rewriting the netlist. The XSPICE option has to be
enabled (32.1).
This E-Source:
produces a differential output voltage determined by selecting the smallest of any number of differential input voltages, and applying a PWL
output function. Here “and(2)” determines the logic function and number of PWL points: output is zero for minimum input voltage less than 0.5
and 3.3 for inputs greater than 2.8, with a linear ramp between. The other three functions are similar: “or” selects the maximum input and
“nand/nor” reverse the order of PWL points. Only two points are supported.
General form:
Examples:
Expression may be an equation or an expression containing node voltages or branch currents (in the form of i(vm)) and any other terms as given for
the B source and described in Chapt. 5.1. It may contain parameters (2.9.1) and special variables (5.1.2). m is an optional multiplier to the output
current. val may be a numerical value or an expression according to 2.9.5 containing only references to other parameters (no node voltages or branch
currents!), because it is evaluated before the simulation commences.
5.3.2 VALUE
Optional syntax:
Examples:
5.3.3 TABLE
A data entry by a tabulated listing is available with syntax similar to the E-Source (see Chapt. 5.2.3).
m is an optional multiplier to the output current. val may be a numerical value or an expression according to 2.9.5 containing only references to other
parameters (no node voltages or branch currents!), because it is evaluated before the simulation commences. An '=' sign may follow the keyword
TABLE.
5.3.4 POLY
see E-Source at Chapt. 5.5.
5.3.5 LAPLACE
See E-Source, Chapt. 5.2.5 , for an equivalent code model replacement.
5.3.6 FREQ
See E-Source, Chapt.5.2.6 , for an equivalent code model replacement.
5.3.7 Example
An example file is given below.
B source debugging
V1 1 0 1
V2 2 0 -2
.control
tran 1 1
.endc
.end
In this trivial example, the reason and location for the bug is obvious. However, if you have several equations using behavioral sources, and several
occurrences of the log function, then debugging is nearly impossible.
However, if the variable ngdebug (see 17.7) is set (e.g. in file .spiceinit), a more distinctive error message is issued that (after some closer
investigation) will reveal the location and value of the buggy parameter.
If variable strict_errorhandling (see 17.7) is set, ngspice exits after this message. If not, gmin and source stepping may be started, typically
without success.
General form:
Example:
POLY(ND) Specifies the number of dimensions of the polynomial. The number of pairs of controlling nodes must be equal to the number of
dimensions.
(N+) and (N-) nodes are output nodes. Positive current flows from the (+) node through the source to the (-) node.
The <NC1+> and <NC1-> are in pairs and define a set of controlling voltages. A particular node can appear more than once, and the output and
controlling nodes need not be different.
The example yields a voltage output controlled by two input voltages v(3,0) and v(4,0). Four polynomial coefficients are given. The equivalent
function to generate the output is:
0 + 13.6 * v(3) + 0.2 * v(4) + 0.005 * v(3) * v(3)
Generally you will set the equation according to
POLY(1) y = p0 + p1*X1 + p2*X1*X1 + p3*X1*X1*X1 + ...
POLY(2) y = p0 + p1*X1 + p2*X2 +
+ p3*X1*X1 + p4*X2*X1 + p5*X2*X2 +
+ p6*X1*X1*X1 + p7*X2*X1*X1 + p8*X2*X2*X1 +
+ p9*X2*X2*X2 + ...
POLY(3) y = p0 + p1*X1 + p2*X2 + p3*X3 +
+ p4*X1*X1 + p5*X2*X1 + p6*X3*X1 +
+ p7*X2*X2 + p8*X2*X3 + p9*X3*X3 + ...
where X1 is the voltage difference of the first input node pair, X2 of the second pair and so on. Keeping track of all polynomial coefficient is rather
tedious for large polynomials.
General form:
Example:
FNONLIN 100 101 POLY(2) VDD Vxx 0 0.0 13.6 0.2 0.005
POLY(ND) Specifies the number of dimensions of the polynomial. The number of controlling sources must be equal to the number of dimensions.
(N+) and (N-) nodes are output nodes. Positive current flows from the (+) node through the source to the (-) node.
V1 (V2 V3 ...) are the controlling voltage sources. Control variable is the current through these sources.
Examples:
T1 1 0 2 0 Z0=50 TD=10NS
n1 and n2 are the nodes at port 1; n3 and n4 are the nodes at port 2. z0 is the characteristic impedance. The length of the line may be expressed in
either of two forms. The transmission delay, td, may be specified directly (as td=10ns, for example). Alternatively, a frequency f may be given,
together with nl, the normalized electrical length of the transmission line with respect to the wavelength in the line at the frequency `f'. If a frequency
is specified but nl is omitted, 0.25 is assumed (that is, the frequency is assumed to be the quarter-wave frequency). Note that although both forms for
expressing the line length are indicated as optional, one of the two must be specified.
Note that this element models only one propagating mode. If all four nodes are distinct in the actual circuit, then two modes may be excited. To
simulate such a situation, two transmission-line elements are required. (see the example in Chapt. 21.7 for further clarification.) The (optional) initial
condition specification consists of the voltage and current at each of the transmission line ports. Note that the initial conditions (if any) apply only if
the UIC option is specified on the .TRAN control line.
Note that a lossy transmission line (see below) with zero loss may be more accurate than the lossless transmission line due to implementation details.
OXXXXXXX n1 n2 n3 n4 mname
Examples:
O23 1 0 2 0 LOSSYMOD
OCONNECT 10 5 20 5 INTERCONNECT
This is a two-port convolution model for single conductor lossy transmission lines. n1 and n2 are the nodes at port 1; n3 and n4 are the nodes at port 2.
Note that a lossy transmission line with zero loss may be more accurate than the lossless transmission line due to implementation details.
Ω
Name Parameter Units/Type Default Example
𝑢𝑛𝑖𝑡
R resistance/length 0.0 0.2
𝐻
𝑢𝑛𝑖𝑡
L inductance/length 0.0 9.13e-9
𝑚ℎ𝑜𝑠
𝑢𝑛𝑖𝑡
G conductance/length 0.0 0.0
𝐹
𝑢𝑛𝑖𝑡
C capacitance/length 0.0 3.65e-12
The option most worth experimenting with for increasing the speed of simulation is REL. The default value of 1 is usually safe from the point of view
of accuracy but occasionally increases computation time. A value greater than 2 eliminates all breakpoints and may be worth trying depending on the
nature of the rest of the circuit, keeping in mind that it might not be safe from the viewpoint of accuracy.
Breakpoints may usually be entirely eliminated if it is expected the circuit will not display sharp discontinuities. Values between 0 and 1 are usually
not required but may be used for setting many breakpoints.
COMPACTREL may also be experimented with when the option TRYTOCOMPACT is specified in a .OPTIONS card. The legal range is between 0 and 1.
Larger values usually decrease the accuracy of the simulation but in some cases improve speed. If TRYTOCOMPACT is not specified on a .OPTIONS card,
history compaction is not attempted and accuracy is high.
NO CONTROL, TRUNCDONTCUT and NOSTEPLIMIT also tend to increase speed at the expense of accuracy.
Examples:
U1 1 2 0 URCMOD L=50U
URC2 1 12 2 UMODL l=1MIL N=6
n1 and n2 are the two element nodes the RC line connects, while n3 is the node the capacitances are connected to. mname is the model name, len is the
length of the RC line in meters. lumps, if specified, is the number of lumped segments to use in modeling the RC line (see the model description for
the action taken if this parameter is omitted).
middle of the URC line, with 𝐾 as a proportionality constant. The number of lumped segments used, if not specified for the URC line device, is
line into a network of lumped RC segments with internally generated nodes. The RC segments are in a geometric progression, increasing toward the
| | (𝐾 − 1)| 2|
𝑅𝐶
log ||𝐹max 2𝜋𝐿2 | | ||
| 𝐿𝐿 || 𝐾 || |
𝑁=
log 𝐾
The URC line is made up strictly of resistor and capacitor segments unless the ISPERL parameter is given a nonzero value, in which case the
capacitors are replaced with reverse biased diodes with a zero-bias junction capacitance equivalent to the capacitance replaced, and with a saturation
current of ISPERL amps per meter of transmission line and an optional series resistance equivalent to RSPERL ohms per meter.
𝑚
RPERL Resistance per unit length 1000 10 -
𝐹
𝑚
CPERL Capacitance per unit length 10e-15 1 p -
S. Lin and E. S. Kuh, `Pade Approximation Applied to Transient Simulation of Lossy Coupled Transmission Lines,' Proc. IEEE Multi-Chip
Module Conference, 1992, pp. 52-55.
S. Lin, M. Marek-Sadowska, and E. S. Kuh, `SWEC: A StepWise Equivalent Conductance Timing Simulator for CMOS VLSI Circuits,'
European Design Automation Conf., February 1991, pp. 142-148.
S. Lin and E. S. Kuh, `Transient Simulation of Lossy Interconnect,' Proc. Design Automation Conference, Anaheim, CA, June 1992, pp. 81-
86.
6.4.1 Single Lossy Transmission Line (TXL)
General form:
Example:
Y1 1 0 2 0 ymod LEN=2
.MODEL ymod txl R=12.45 L=8.972e-9 G=0 C=0.468e-12 length=16
Typically 𝑢𝑛𝑖𝑡 is given in meters. len will override the model parameter length for the specific instance only.
n1and n2 are the nodes of the two ports. The optional instance parameter len is the length of the line and may be expressed in multiples of [𝑢𝑛𝑖𝑡].
Ω
Name Parameter Units/Type Default Example
𝑢𝑛𝑖𝑡
R resistance/length 0.0 0.2
𝐻
𝑢𝑛𝑖𝑡
L inductance/length 0.0 9.13e-9
𝑚ℎ𝑜𝑠
𝑢𝑛𝑖𝑡
G conductance/length 0.0 0.0
𝐹
𝑢𝑛𝑖𝑡
C capacitance/length 0.0 3.65e-12
Model parameter length must be specified as a multiple of 𝑢𝑛𝑖𝑡. Typically 𝑢𝑛𝑖𝑡 is given in [m]. For transient simulation only.
General form:
Example:
and may be expressed in multiples of [𝑢𝑛𝑖𝑡]. Typically 𝑢𝑛𝑖𝑡 is given in meters. len will override the model parameter length for the specific instance
ni1 ... nix are the nodes at port 1 with gnd1; no1 ... nox are the nodes at port 2 with gnd2. The optional instance parameter len is the length of the line
only.
Ω
Name Parameter Units/Type Default Example
𝑢𝑛𝑖𝑡
R resistance/length 0.0 0.2
𝐻
𝑢𝑛𝑖𝑡
L inductance/length 0.0 9.13e-9
𝑚ℎ𝑜𝑠
𝑢𝑛𝑖𝑡
G conductance/length 0.0 0.0
𝐹
𝑢𝑛𝑖𝑡
C capacitance/length 0.0 3.65e-12
All RLGC parameters are given in Maxwell matrix form. For the R and G matrices the diagonal elements must be specified, for L and C matrices the
lower or upper triangular elements must specified. The parameter LENGTH is a scalar and is mandatory. For transient simulation only.
Chapter 7 Diodes
7.1 Junction Diodes
General form:
Examples:
DBRIDGE 2 10 DIODE1
DCLMP aa cc DMOD AREA=3.0 IC=0.2
The pn junction (diode) implemented in ngspice expands the one found in SPICE3f5. Perimeter effects and high injection level have been introduced
into the original model and temperature dependence of some parameters has been added. n+ and n- are the positive (anode) and negative (cathode)
nodes, respectively. mname is the model name. Instance parameters may follow, dedicated to only the diode described on the respective line. area is
the area scale factor, which may scale the saturation current given by the model parameters (and others, see table below). pj is the perimeter scale
factor, scaling the sidewall saturation current and its associated capacitance. m is a multiplier of area and perimeter, and off indicates an (optional)
starting condition on the device for dc analysis. If the area factor is omitted, a value of 1.0 is assumed. The (optional) initial condition specification
using ic is intended for use with the uic option on the .tran control line, when a transient analysis is desired starting from other than the quiescent
operating point. You should supply the initial voltage across the diode there. The (optional) temp value is the temperature at which this device is to
operate, and overrides the temperature specification on the .option control line. The temperature of each instance can be specified as an offset to the
circuit temperature with the dtemp option.
To fulfill requirements of modern process design kits (PDK) the basic spice3 model was extended with the capability of modeling parasitic effects like
sidewall junction currents and capacitances, tunnel currents and metal and polysilicon overlap capacitances. Latter effect can be activated by level=3
model parameter or by setting element parameters lm, wm, lp and wp. If both are given, element parameters have priority.
With the (new in ngspice-39) OpenVAF/OSDI approach (see 13), all modern diode models, written in Verilog-A, become available, like JUNCAP
etc..
General form:
Examples:
with a user defined model name mname, and the model type D.
A basic model statement using only the internal default model parameters is
.model DMOD D
The dc characteristics of the diode are determined by the parameters is and n. An ohmic resistance, rs, is included. Charge storage effects are
modeled by a transit time, tt, and a nonlinear depletion layer capacitance that is determined by the parameters cjo, vj, and m. The temperature
dependence of the saturation current is defined by the parameters eg, the energy, and xti, the saturation current temperature exponent. The nominal
temperature where these parameters were measured is tnom, which defaults to the circuit-wide value specified on the .options control line. Reverse
breakdown is modeled by an exponential increase in the reverse diode current and is determined by the parameters bv and ibv (both of which are
positive numbers).
Junction DC parameters
Name Parameter Units Default Example Scale factor
IS (JS) Saturation current 𝐴 1.0e-14 1.0e-16 area
JSW Sidewall saturation current 𝐴 0.0 1.0e-15 perimeter
1
N Emission coefficient - 1 1.5
Ω
𝑎𝑟𝑒𝑎
RS Ohmic resistance 0.0 100
Temperature effects
Name Parameter Units Default Example
𝑒𝑉 1.11 S i
0.69 S bd
EG Activation energy 1.11
0.67 G e
TNOM (TREF) Parameter measurement °𝐶 27 50
1
temperature
°𝐶
TRS1 (TRS) 1st order tempco for RS 0.0 -
1
°𝐶2
TRS2 2nd order tempco for RS 0.0 -
1
°𝐶
TM1 1st order tempco for MJ 0.0 -
1
°𝐶2
TM2 2nd order tempco for MJ 0.0 -
1
°𝐶
TTT1 1st order tempco for TT 0.0 -
1
°𝐶2
TTT2 2nd order tempco for TT 0.0 -
3.0 pn
2.0 S bd
XTI Saturation current - 3.0
temperature exponent
TLEV Diode temperature equation - 0
selector
TLEVC Diode capac. temperature - 0
°𝐶
CTA (CTC) 0.0 -
1
coefficient
°𝐶
CTP Perimeter junct. cap. 0.0 -
1
temperature coefficient
°𝐶
TCV Breakdown voltage 0.0 -
temperature coefficient
Noise modeling
Name Parameter Units Default Example Scale factor
KF Flicker noise coefficient - 0
AF Flicker noise exponent - 1
Forward bias: the anode is more positive than the cathode, the diode is `on' and can conduct large currents. To avoid convergence problems
and unrealistic high current, it is prudent to specify a series resistance to limit current with the rs model parameter.
Reverse bias: the cathode is more positive than the anode and the diode is `off'. A reverse bias diode conducts a small leakage current.
Breakdown: the breakdown region is modeled only if the bv model parameter is given. When a diode enters breakdown the current increases
exponentially (remember to limit it); bv is a positive value.
Parameters Scaling
Model parameters are scaled using the unit-less parameters area and pj and the multiplier m as depicted below:
𝐴𝑅𝐸𝐴𝑒𝑓𝑓 = A RE A 𝑚
𝑃𝐽𝑒𝑓𝑓 = PJ 𝑚
𝐼𝐵𝑉𝑒𝑓𝑓 = I BV 𝐴𝑅𝐸𝐴𝑒𝑓𝑓
𝐼𝐾𝑒𝑓𝑓 = I K𝐴𝑅𝐸𝐴𝑒𝑓𝑓
𝐼𝐾𝑅𝑒𝑓𝑓 = I KR𝐴𝑅𝐸𝐴𝑒𝑓𝑓
𝐶𝐽𝑒𝑓𝑓 = C J 0𝐴𝑅𝐸𝐴𝑒𝑓𝑓
𝐶𝐽𝑃𝑒𝑓𝑓 = C J P𝑃𝐽𝑒𝑓𝑓
⎧ 𝑞𝑉𝐷
𝑁𝑘𝑇
⎪ 𝐼𝑆𝑒𝑓𝑓 (𝑒𝑁𝑘𝑇 − 1) + 𝑉𝐷 ⋅ 𝐺𝑀𝐼𝑁, i f 𝑉𝐷 ≥ − 3
⎪ 𝑞
⎪
⎪ −𝐼𝑆 [1 + (3𝑁𝑘𝑇)3 ] + 𝑉 ⋅ 𝐺𝑀𝐼𝑁, i f − 𝐵𝑉 < 𝑉 < − 3𝑁𝑘𝑇
𝐼𝐷 = 𝑒𝑓𝑓
𝑞𝑉𝐷 𝑒 𝐷 𝑒𝑓𝑓 𝐷
𝑞
⎨
⎪
⎪
−𝑞(𝐵𝑉𝑒𝑓𝑓 + 𝑉𝐷 )
⎪ −𝐼𝑆𝑒𝑓𝑓 (𝑒 𝑁𝑘𝑇 ) + 𝑉𝐷 ⋅ 𝐺𝑀𝐼𝑁, i f 𝑉𝐷 ≤ − 𝐵𝑉𝑒𝑓𝑓
⎪
⎩
Two secondary effects are modeled if the appropriate parameters (see table Junction DC parameters) are given: Recombination current and bottom
and sidewall tunnel current.
The breakdown region must be described with more depth since the breakdown is not modeled physically. As written before, the breakdown modeling
is based on two model parameters: the `nominal breakdown voltage' bv and the current at the onset of breakdown ibv. For the diode model to be
consistent, the current value cannot be arbitrarily chosen, since the reverse bias and breakdown regions must match. When the diode enters
breakdown region from reverse bias, the current is calculated using the formula1:
−𝑞BV
𝐼𝑏𝑑𝑤𝑛 = − 𝐼𝑆𝑒𝑓𝑓 (𝑒 𝑁𝑘𝑇 − 1)
The computed current is necessary to adjust the breakdown voltage making the two regions match. The algorithm is a little bit convoluted and only a
brief description is given here:
𝐼𝐵𝑉𝑒𝑓𝑓
else
𝐵𝑉𝑒𝑓𝑓 = B V − N𝑉𝑡 ln ( )
𝐼𝑏𝑑𝑤𝑛
⎧ 𝐼𝐷 𝑁𝑘𝑇
, if 𝑉𝐷 ≥ − 3
⎪ 𝐼𝐷 𝑞
⎪ 1+
√𝐼𝐾𝑒𝑓𝑓
𝐼𝐷𝑒𝑓𝑓 =⎪
⎨ 𝐼𝐷
⎪ , o th e r wis e .
⎪1+ 𝐼𝐷
⎪ √𝐼𝐾𝑅𝑒𝑓𝑓
⎩
Depletion capacitance
Diffusion capacitance
Depletion capacitance is composed by two different contributes, one associated to the bottom of the junction (bottom-wall depletion capacitance) and
the other to the periphery (sidewall depletion capacitance). The basic equations are
𝐶𝐷𝑖𝑜𝑑𝑒 = 𝐶𝑑𝑖𝑓𝑓𝑢𝑠𝑖𝑜𝑛 + 𝐶𝑑𝑒𝑝𝑙𝑒𝑡𝑖𝑜𝑛
The diffusion capacitance, due to the injected minority carriers, is modeled with the transit time tt:
𝜕𝐼𝐷𝑒𝑓𝑓
𝐶𝑑𝑖𝑓𝑓𝑢𝑠𝑖𝑜𝑛 = T T
𝜕𝑉𝐷
The depletion capacitance is more complex to model, since the function used to approximate it diverges when the diode voltage become greater than
the junction built-in potential. To avoid function divergence, the capacitance function is approximated with a linear extrapolation for applied voltage
greater than a fraction of the junction built-in potential.
𝑉𝐷 − MJ
𝐶𝐽𝑒𝑓𝑓 (1 − ) , i f 𝑉𝐷 < F 𝐶 ⋅ V𝐽
VJ
𝑉𝐷
𝐶𝑑𝑒𝑝𝑙𝑏𝑤 = { 1 − F C (1 + M J) + M J
VJ
𝐶𝐽𝑒𝑓𝑓 , o th e r wis e .
(1 + MJ )
(1 − F C )
⎧ 𝑉𝐷 −MJ SW
⎪ 𝐶𝐽𝑃 (1 − ) , i f V D < F C S ⋅ PHP
𝑒𝑓𝑓
PHP
⎪
⎪ 𝑉
𝐶𝑑𝑒𝑝𝑙𝑠𝑤 = 1 − F C S (1 + M J S W ) + M J S W ⋅ 𝐷
⎨ 𝐶𝐽𝑃 PHP
⎪ 𝑒𝑓𝑓 , o th e r wis e .
(1 + MJ SW)
⎪ (1 − F C S )
⎪
⎩
Temperature dependence
The temperature affects many of the parameters in the equations above, and the following equations show how. One of the most significant
parameters that varies with the temperature for a semiconductor is the band-gap energy:
TNOM 2
𝐸𝐺𝑛𝑜𝑚 = 1.16 − 7.02𝑒 −4
TNO M + 1108.0
𝑇2
𝐸𝐺(𝑇) = 1.16 − 7.02𝑒 −4
TNO M + 1108.0
𝑙𝑜𝑔𝑓𝑎𝑐𝑡𝑜𝑟
𝐼𝑆(𝑇) = IS𝑒 N
𝑙𝑜𝑔𝑓𝑎𝑐𝑡𝑜𝑟
𝐽𝑆𝑊(𝑇) = J S W𝑒 N
EG EG 𝑇
𝑙𝑜𝑔𝑓𝑎𝑐𝑡𝑜𝑟 = − + XT I ln ( )
𝑉𝑡 (TNO M) 𝑉𝑡 (𝑇) TNO M
𝑇 𝑇 E G 𝑛𝑜𝑚 E G(𝑇)
𝑉𝐽(𝑇) = V J( ) − 𝑉𝑡 (𝑇)[3 ⋅ ln ( )+ − ]
TNO M TNO M 𝑉𝑡 (TNO M) 𝑉𝑡 (𝑇)
𝑇 𝑇 E G 𝑛𝑜𝑚 E G(𝑇)
𝑃𝐻𝑃(𝑇) = PHP( ) − 𝑉𝑡 (𝑇)[3 ⋅ ln ( )+ − ]
TNOM TNO M 𝑉𝑡 (TNO M) 𝑉𝑡 (𝑇)
𝑉𝐽(𝑇)
𝐶𝐽(𝑇) = C J[1 + M J(4.0𝑒− 4 (𝑇 − TNO M) − + 1)]
VJ
𝑃𝐻𝑃(𝑇)
𝐶𝐽𝑆𝑊(𝑇) = C J S W[1 + M J S W(4.0𝑒−4 (𝑇 − TNO M) − + 1)]
PHP
Noise model
The diode has three noise contribution, one due to the presence of the parasitic resistance rs and the other two (shot and flicker) due to the pn
junction.
4𝑘𝑇 ∆ 𝑓
𝑖𝑅𝑆 =
2¯
𝑅𝑆
𝐾𝐹 ⋅ 𝐼𝐴𝐹
𝑖𝑑2̄ = 2𝑞𝐼𝐷 ∆ 𝑓 + 𝐷 ∆𝑓
𝑓
Compared to the standard diode we have a third node tj and a flag thermal on element line. In the model description we have to set rthh0 and cth0
model parameter.
Example model:
Chapter 8 BJT
8.1 Bipolar Junction Transistors (BJTs)
General form:
Examples:
nc, nb, and ne are the collector, base, and emitter nodes, respectively. ns is the (optional) substrate node. When unspecified, ground is used. tj is the
(optional) junction temperature node, available in the VBIC model (see 8.2.2). mname is the model name, area, areab, areac are the area factors
(emitter, base and collector respectively), and off indicates an (optional) initial condition on the device for the dc analysis. If the area factor is
omitted, a value of 1.0 is assumed.
The (optional) initial condition specification using ic=vbe,vce is intended for use with the uic option on a .tran control line, when a transient
analysis is desired to start from other than the quiescent operating point. See the .ic control line description for a better way to set transient initial
conditions. The (optional) temp value is the temperature where this device is to operate, and overrides the temperature specification on the .option
control line. Using the dtemp option one can specify the instance's temperature relative to the circuit temperature.
These are the minimal versions, using default parameters supplied by ngspice. Further optional parameters listed in the table below may replace the
ngspice default parameters. The level keyword specifies the model to be used:
level=1: This is the original SPICE BJT model, and it is the default model if the level keyword is not specified on the .model line. By
activating certain parameter a modified version of the original SPICE BJT that models both vertical and lateral devices, includes temperature
corrections of collector, emitter and base resistors and allow modeling of quasi-saturation effects.
level=4: Advanced VBIC model (see 8.2.2 and http://www.designers-guide.org/VBIC/ for details)
level=8: HICUM/L2 model (see 8.2.4 and the official website for details)
With the (new in ngspice-39) OpenVAF/OSDI approach (see 13), all modern bipolar models, written in Verilog-A, become available, like VBIC,
Mextram and HICUM.
The dc model is defined by the parameters IS, BF, NF, ISE, IKF, and NE, which determine the forward current gain characteristics, IS, BR, NR, ISC, IKR,
and NC, which determine the reverse current gain characteristics, and VAF and VAR, which determine the output conductance for forward and reverse
regions.
A more accurate model for transport current components is possible by specification of model parameter IBE and IBC instead of IS.
Parameter NKF(NK)was introduced for more accurate high current beta rolloff modelling.
The BJT model has among the standard temperature parameters an extension compatible with most foundry provided process design kits (see
parameter table below TLEV).
The BJT model includes the substrate saturation current ISS. Three ohmic resistances RB, RC, and RE are included, where RB can be high current
dependent. Base charge storage is modeled by forward and reverse transit times, TF and TR, where the forward transit time TF can be bias dependent if
desired. Nonlinear depletion layer capacitances are defined with CJE, VJE, and NJE for the B-E junction, CJC, VJC, and NJC for the B-C junction and
CJS, VJS, and MJS for the C-S (collector-substrate) junction.
The BJT model support a substrate capacitance that is connected to the device's base or collector, to model lateral or vertical devices dependent on the
parameter SUBS. The temperature dependence of the saturation currents, IS and ISS, is determined by the energy-gap, EG, and the saturation current
temperature exponent, XTI.
In the new model, additional base current temperature dependence is modeled by the beta temperature exponent XTB. The values specified are
assumed to have been measured at the temperature TNOM, which can be specified on the .options control line or overridden by a specification on the
.model line.
The BJT parameters used in the modified Gummel-Poon model are listed below. The parameter names used in earlier versions of SPICE2 are still
accepted.
1
on TF
2𝜋𝑇𝐹
PTF Excess phase at freq= Hz deg 0
1
selector
°𝐶
TRE1 1st order temperature coefficient 0.0 1e-3
1
for RE
°𝐶2
TRE2 2nd order temperature coefficient 0.0 1e-5
1
for RE
°𝐶
TRC1 1st order temperature coefficient 0.0 1e-3
1
for RC
°𝐶2
TRC2 2nd order temperature coefficient 0.0 1e-5
1
for RC
°𝐶
TRB1 1st order temperature coefficient 0.0 1e-3
1
for RB
°𝐶2
TRB2 2nd order temperature coefficient 0.0 1e-5
1
for RB
°𝐶
TRBM1 1st order temperature coefficient 0.0 1e-3
1
for RBM
°𝐶 2
TRBM2 2nd order temperature coefficient 0.0 1e-5
1
for RBM
°𝐶
TBF1 1st order temperature coefficient 0.0 1e-3
1
for BF
°𝐶2
TBF2 2nd order temperature coefficient 0.0 1e-5
1
for BF
°𝐶
TBR1 1st order temperature coefficient 0.0 1e-3
1
for BR
°𝐶2
TBR2 2nd order temperature coefficient 0.0 1e-5
1
for BR
°𝐶
TIKF1 1st order temperature coefficient 0.0 1e-3
1
for IKF
°𝐶2
TIKF2 2nd order temperature coefficient 0.0 1e-5
1
for IKF
°𝐶
TIKR1 1st order temperature coefficient 0.0 1e-3
1
for IKR
°𝐶2
TIKR2 2nd order temperature coefficient 0.0 1e-5
1
for IKR
°𝐶
TIRB1 1st order temperature coefficient 0.0 1e-3
1
for IRB
°𝐶2
TIRB2 2nd order temperature coefficient 0.0 1e-5
1
for IRB
°𝐶
TNC1 1st order temperature coefficient 0.0 1e-3
1
for NC
°𝐶2
TNC2 2nd order temperature coefficient 0.0 1e-5
1
for NC
°𝐶
TNE1 1st order temperature coefficient 0.0 1e-3
1
for NE
°𝐶2
TNE2 2nd order temperature coefficient 0.0 1e-5
1
for NE
°𝐶
TNF1 1st order temperature coefficient 0.0 1e-3
1
for NF
°𝐶2
TNF2 2nd order temperature coefficient 0.0 1e-5
1
for NF
°𝐶
TNR1 1st order temperature coefficient 0.0 1e-3
1
for IKF
°𝐶2
TNR2 2nd order temperature coefficient 0.0 1e-5
1
for IKF
°𝐶
TVAF1 1st order temperature coefficient 0.0 1e-3
1
for VAF
°𝐶2
TVAF2 2nd order temperature coefficient 0.0 1e-5
1
for VAF
°𝐶
TVAR1 1st order temperature coefficient 0.0 1e-3
1
for VAR
°𝐶2
TVAR2 2nd order temperature coefficient 0.0 1e-5
1
for VAR
°𝐶
CTC 1st order temperature coefficient 0.0 1e-3
1
for CJC
°𝐶
CTE 1st order temperature coefficient 0.0 1e-3
1
for CJE
°𝐶
CTS 1st order temperature coefficient 0.0 1e-3
1
for CJS
°𝐶2
TVJC 1st order temperature coefficient 0.0 1e-5
1
for VJC
°𝐶
TVJE 1st order temperature coefficient 0.0 1e-3
1
for VJE
°𝐶
TITF1 1st order temperature coefficient 0.0 1e-3
1
for ITF
°𝐶 2
TITF2 2nd order temperature coefficient 0.0 1e-5
1
for ITF
°𝐶
TTF1 1st order temperature coefficient 0.0 1e-3
1
for TF
°𝐶2
TTF2 2nd order temperature coefficient 0.0 1e-5
1
for TF
°𝐶
TTR1 1st order temperature coefficient 0.0 1e-3
1
for TR
°𝐶2
TTR2 2nd order temperature coefficient 0.0 1e-5
1
for TR
°𝐶
TMJE1 1st order temperature coefficient 0.0 1e-3
1
for MJE
°𝐶 2
TMJE2 2nd order temperature coefficient 0.0 1e-5
1
for MJE
°𝐶
TMJC1 1st order temperature coefficient 0.0 1e-3
1
for MJC
°𝐶2
TMJC2 2nd order temperature coefficient 0.0 1e-5
for MJC
The Collector current output characteristic shows a special moderate transition in the BJT saturation region, see figure 8.1. Furthermore DC current
gain and the unity gain frequency fT falls sharply.
The simple thermal network of the VBIC model is shown in Fig. 8.2.
How to instantiate the bipolar VBIC model (only minimal version) with self-heating:
vc c 0 0
vb b 0 1
ve e 0 0
vs s 0 0
Q1 c b e s dt mod1 area=1
.model mod1 npn Level=4 selft=1 rth=100
Of course it is possible to connect an more accurate thermal network to the node dt. The following example is showing a simplified thermal network
covering the thermal resistances and capacitances of junction-case and case-ambient transitions induced by a heat-sink.
Q1 c b e s dt mod2
.model mod2 npn Level=9 selft=1 rth=20
X1 dt tamb junction-ambient
VTamb tamb 0 30
.subckt junction-ambient jct amb
rjc jct 1 0.4
ccs 1 0 5m
rcs 1 2 0.1
csa 2 0 30m
rsa 2 amb 1.3
.ends
Mextram has proven excellent for Si and SiGe processes, including analog, mixed-signal, high speed RF as well as high voltage high power
technologies. It accounts for high injection effects with a dedicated epi-layer model, self heating, avalanche, low-frequency and high frequency noises
in physical manners, and is formulated with minimal interactions between DC and AC characteristics that simplifies parameter extraction.
Ngspice has implemented version 504.12.1 in his experimental ADMS tree. It will be activated by the BJT model parameter level=6.
HICUML2 captures most to all known physical effects relevant in HBTs, in example:
substrate transistor
avalanche effect
physics based transfer current model
self-heating
accurate modeling of the temperature dependence
excess phase between base and collector current
Note that the noise correlation network is not implemented in Ngspice. More information regarding the model and its parameters can be found on the
website.
The equivalent circuit of the model is shown in fig. 8.2.4. The model is employed in many PDKs for state-of-the-art SiGe and InP HBTs and is
actively developed at TU Dresden.
By connecting the T and S nodes of the model to other circuit elements, the thermal and substrate network can be modified by the user. Note that both
self-heating and the avalanche effect may cause convergency issues if the operating region is too extreme.
vc c 0 0
vb b 0 1
ve e 0 0
vs s 0 0
Q1 c b e s dt mod1 area=1
.model mod1 npn Level=8
Self-heating is activated by model parameters FLSH, RTH and connecting T node of the device instance. FLSH = 1 will only consider main thermal
contributions of IC and IB, FLSH = 2 include all power dissipations of the transistor.
Chapter 9 JFETs
9.1 Junction Field-Effect Transistors (JFETs)
General form:
Examples:
J1 7 2 3 JM1 OFF
nd, ng, and ns are the drain, gate, and source nodes, respectively. mname is the model name, area is the area factor, and off indicates an (optional)
initial condition on the device for dc analysis. If the area factor is omitted, a value of 1.0 is assumed. The (optional) initial condition specification,
using ic=VDS,VGS is intended for use with the uic option on the .TRAN control line, when a transient analysis is desired starting from other than the
quiescent operating point. See the .ic control line for a better way to set initial conditions. The (optional) temp value is the temperature where this
device is to operate, and overrides the temperature specification on the .option control line.
𝛽𝑝 = 𝐵𝐸𝑇𝐴(1 + 𝐿𝐴𝑀𝐵𝐷𝐴𝑣𝑑𝑠)
1−𝐵
𝑏𝑓𝑎𝑐 =
𝑃𝐵 − 𝑉𝑇𝑂
Note that in Spice3f and later, the fitting parameter B has been added by Parker and Skellern. For details, see [9]. If parameter B is set to 1 equation
above simplifies to
𝑉"
BETA Transconductance parameter (𝛽) 1.0e-4 1.0e-3 area
1
𝑉
LAMBDA Channel-length modulation 0 1.0e-4
parameter (𝜆)
RD Drain ohmic resistance Ω 0 100 1/area
RS Source ohmic resistance Ω 0 100 1/area
Zero-bias G-S junction capacitance 𝐹
𝐶𝑔𝑠
CGS 0 5pF area
𝐹
capacitance 𝐶𝑔𝑑
CGD Zero-bias G-D junction 0 1pF area
1
temperature
°𝐶
TCV Threshold voltage temperature 0.0 0.01
1
coefficient
°𝐶
VTOTC Threshold voltage temperature 0.0 -2.5m
coefficient (alternative model)
BEX Mobility temperature exponent - 0.0 1.1
°𝐶
BETATCE Mobility temperature exponent 0.0 -0.5
(alternative model)
XTI Gate saturation current - 3.0
temperature coefficient
EG Bandgap voltage 1.11
Additional to the standard thermal and flicker noise model an alternative thermal channel noise model is implemented and is selectable by setting
NLEV parameter to 3. This leads to a correct channel thermal noise description in the linear region.
2 (1 + α + 𝛼2 )
𝑆𝑛𝑜𝑖𝑠𝑒 = 4𝑘𝑇 ⋅ 𝐵𝐸𝑇𝐴 ⋅ 𝑉𝑔𝑠𝑡 𝐺𝐷𝑆𝑁𝑂𝐼
3 1+𝛼
with
𝑣𝑑𝑠
1− , if 𝑣𝑔𝑠 − 𝑉𝑇𝑂 ≥ 𝑣𝑑𝑠
𝛼={ 𝑣𝑔𝑠 − 𝑉𝑇𝑂
0, e ls e
JFET level 1 model has an alternative temperature model for main parameter VTO and BETA:
𝑇𝑒𝑚𝑝 𝐵𝐸𝑋
BETATCE not given:
𝐵𝐸𝑇𝐴(𝑇𝑒𝑚𝑝) = 𝐵𝐸𝑇𝐴 * ( )
𝑇𝑁𝑂𝑀
The description maintains strict continuity in its high-order derivatives, which is essential for prediction of distortion and intermodulation.
Frequency dependence of output conductance and transconductance is described as a function of bias.
Both drain-gate and source-gate potentials modulate the pinch-off potential, which is consistent with S-parameter and pulsed-bias
measurements.
Self-heating varies with frequency.
Extreme operating regions - subthreshold, forward gate bias, controlled resistance, and breakdown regions - are included.
Parameters provide independent fitting to all operating regions. It is not necessary to compromise one region in favor of another.
Strict drain-source symmetry is maintained. The transition during drain-source potential reversal is smooth and continuous.
The model equations are described in this pdf document and in [19].
𝑊
DELTA Thermal reduction coefficient 0
1
HFETA High-frequency VGS feedback parameter - 0
𝑉
HFE1 HFGAM modulation by VGD 0
1
𝑉
HFE2 HFGAM modulation by VGS 0
1
HFGAM High-frequency VGD feedback parameter - 0
𝑉
HFG1 HFGAM modulation by VSG 0
1
𝑉
HFG2 HFGAM modulation by VDG 0
1
LFGAM Low-frequency feedback parameter - 0
𝑉
LFG1 LFGAM modulation by VSG 0
1
𝑉
LFG2 LFGAM modulation by VDG 0
1
𝑉
MVST Subthreshold modulation 0
Chapter 10 MESFETs
10.1 MESFETs
General form:
Examples:
Z1 7 2 3 ZM1 OFF
These model statements will use the default parameters ( level 1 listed below).
⎧ 𝛽(𝑉 − 𝑉 )2 ⎡ 3 ⎤⎛ ⎞
⎪ 𝑔𝑠 𝑇𝑂 𝑉
⎢1 − − 𝛼 𝑑𝑠 ⎥⎜1 + 𝜆𝑉 ⎟ 3
⎪ ⎢ (1 ) ⎥ f o r 0 < 𝑉𝑑𝑠 <
⎪ 1 + 𝐵(𝑉 − 𝑉 )
𝑇𝑂 ⎢
3 ⎜
𝑑𝑠
⎟ 𝛼
𝑔𝑠 ⎥
⎪ ⎣ ⎦⎝ ⎠
𝐼𝑑 =
⎨ 2
⎪ 𝛽(𝑉𝑔𝑠 𝑉𝑇𝑂 ) ⎛
− ⎞
⎜1 + 𝜆𝑉𝑑𝑠 ⎟ 3
⎪ f o r 𝑉𝑑𝑠 ≥
⎪ 1 + 𝐵(𝑉𝑔𝑠 − 𝑉𝑇𝑂 )⎜ ⎟ 𝛼
⎪ ⎝ ⎠
⎩
Two ohmic resistances, rd and rs, are included. Charge storage is modeled by total gate charge as a function of gate-drain and gate-source voltages
and is defined by the parameters cgs, cgd, and pb.
𝑉2
BETA Transconductance parameter 1.0e-4 1.0e-3 *
1
𝑉
B Doping tail extending parameter 0.3 0.3 *
1
𝑉
ALPHA Saturation voltage parameter 2 2 *
1
𝑉
LAMBDA Channel-length modulation parameter 0 1.0e-4
Device instance:
z1 2 3 0 mesmod area=1.4
Model:
to be written
M. Shur, T.A. Fjeldly, T. Ytterdal, K. Lee, "Unified GaAs MESFET Model for Circuit Simulation", Int. Journal of High Speed Electronics, vol. 3, no.
2, pp. 201-233, 1992
10.2.4 hfet1
level 5
Heterostructure Field Effect Transistor model as described in section 4.6 of the book
K. Lee, M. Shur, T. A. Fjeldly and T. Ytterdal, Semiconductor Device Modeling for VLSI, 1993, Prentice Hall, New Jersey.
Model parameters, equivalent circuit diagrams and device equations are also described in the AIM-Spice reference manual, section Device Models A.
10.2.5 hfet2
level6
The HFET level 2 model is a simplified version of the level 1 model. The model is optimized for speed and is suitable for simulation of digital
circuits. To increase the speed, some of the features included in the level 1 model is not implemented for the level 2 model.
Chapter 11 MOSFETs
Ngspice supports all the original MOSFET models present in SPICE3f5 and almost all the newer ones that have been published and made open-
source. Both bulk and SOI (Silicon on Insulator) models are available. When compiled with the cider option, ngspice implements the four terminals
numerical model that can be used to simulate a MOSFET (please refer to numerical modeling documentation for additional information and
examples).
Examples:
M1 24 2 0 20 TYPE1
M31 2 17 6 10 MOSN L=5U W=2U
M1 2 9 3 0 MOSP L=10U W=5U AD=100P AS=100P PD=40U PS=40U
Note the suffixes in the example: the suffix `u' specifies microns (1e-6 m ) and `p' sq-microns (1e-12 m 2 ).
The instance card for MOS devices starts with the letter 'M'. nd, ng, ns, and nb are the drain, gate, source, and bulk (substrate) nodes, respectively.
mname is the model name and m is the multiplicity parameter, which simulates `m' paralleled devices. All MOS models support the `m' multiplier
If any of l, w, ad, or as are not specified, default values are used. The use of defaults simplifies input file preparation, as well as the editing required if
device geometries are to be changed. pd and ps are the perimeters of the drain and source junctions, in meters. nrd and nrs designate the equivalent
number of squares of the drain and source diffusions; these values multiply the sheet resistance rsh specified on the .model control line for an
accurate representation of the parasitic series drain and source resistance of each transistor. pd and ps default to 0.0 while nrd and nrs to 1.0. off
indicates an (optional) initial condition on the device for dc analysis. The (optional) initial condition specification using ic=vds,vgs,vbs is intended
for use with the uic option on the .tran control line, when a transient analysis is desired starting from other than the quiescent operating point. See
the .ic control line for a better and more convenient way to specify transient initial conditions. The (optional) temp value is the temperature at which
this device is to operate, and overrides the temperature specification on the .option control line.
The temperature specification is ONLY valid for level 1, 2, 3, and 6 MOSFETs, not for level 4 or 5 (BSIM) devices.
BSIM3 (v3.2 and v3.3.0), BSIM4 (v4.7 and v4.8) and BSIMSOI models are also supporting the instance parameter delvto and mulu0 for local
mismatch and NBTI (negative bias temperature instability) modeling:
The model name MOSN corresponds to the model name in the instance card (see 11.1). Parameter NMOS selects an n-channel device, PMOS would
point to a p-channel transistor. The level and version parameters select the specific model. Further model parameters are optional and replace
ngspice default values. Due to the large number of parameters (more than 100 for modern models), model cards may be stored in extra files and
loaded into the netlist by the .include (2.7) command. Model cards are specific for a an IC manufacturing process and are typically provided by the IC
foundry. Some generic parameter sets, not linked to a specific process, are made available by the model developers, e.g. UC Berkeley's Device Group
for BSIM4 and BSIMSOI.
Ngspice provides several MOSFET device models, which differ in the formulation of the I-V characteristic, and are of varying complexity. Models
available are listed in table 11.1. Current models for IC design are BSIM3 (11.2.10, down to channel length of 0.25 µm), BSIM4 (11.2.11, below 0.25
µm), BSIMSOI (11.2.12, silicon-on-insulator devices), HiSIM2 and HiSIM_HV (11.2.14, surface potential models for standard and high voltage/high
power MOS devices).
With its OSDI interface all MOS models written in Verilog-A and compiled with OpenVAF are available
OSDI see 13.2
Examples: BSIMBULK, BSIM-CMG, BSIM-IMG, PSP, HiSIM (see VA-Models).
Table 11.1: MOSFET model summary
With the (new in ngspice-39) OpenVAF/OSDI approach (see 13), all modern MOS models, written in Verilog-A, become available, like BSIMBULK,
BSIM-CMG and BSIM-IMG, PSP, HiSim etc..
This model is described in [26]. The model can express the current characteristics of short-channel MOSFETs at least down to 0.25 𝜇𝑚 channel-
11.2.4 MOS Level 6
length, GaAs FET, and resistance inserted MOSFETs. The model evaluation time is about 1/3 of the evaluation time of the SPICE3 mos level 3
model. The model also enables analytical treatments of circuits in short-channel region and makes up for a missing link between a complicated
MOSFET current characteristics and circuit behaviors in the deep submicron region.
Charge storage is modeled by three constant capacitors, cgso, cgdo, and cgbo, which represent overlap capacitances, by the nonlinear thin-oxide
capacitance that is distributed among the gate, source, drain, and bulk regions, and by the nonlinear depletion-layer capacitances for both substrate
junctions divided into bottom and periphery, which vary as the mj and mjsw power of junction voltage respectively, and are determined by the
parameters cbd, cbs, cj, cjsw, mj, mjsw and pb.
Charge storage effects are modeled by the piecewise linear voltages-dependent capacitance model proposed by Meyer. The thin-oxide charge-storage
effects are treated slightly different for the level 1 model. These voltage-dependent capacitances are included only if tox is specified in the input
description and they are represented using Meyer's formulation.
𝐴
𝑚2
There is some overlap among the parameters describing the junctions, e.g. the reverse current can be input either as is (in A) or as js (in ).
Whereas the first is an absolute value the second is multiplied by ad and as to give the reverse current of the drain and source junctions respectively.
𝐹
This methodology has been chosen since there is no sense in relating always junction characteristics with ad and as entered on the device line; the
𝑚
areas can be defaulted. The same idea applies also to the zero-bias junction capacitances cbd and cbs (in F) on one hand, and cj (in 2 ) on the other.
The parasitic drain and source series resistance can be expressed as either rd and rs (in ohms) or rsh (in ohms/sq.), the latter being multiplied by the
number of squares nrd and nrs input on the device line.
𝑉 2
KP Transconductance parameter 2.0e-5 3.1e-5
𝑉
LAMBDA Channel length modulation (MOS1 and 0.0 0.02
MOS2 only) (𝜆)
RD Drain ohmic resistance Ω 0.0 1.0
RS Source ohmic resistance Ω 0.0 1.0
CBD Zero-bias B-D junction capacitance 𝐹 0.0 20fF
CBS Zero-bias B-S junction capacitance 𝐹 0.0 20fF
IS Bulk junction saturation current (𝐼𝑆 ) 𝐴 1.0e-14 1.0e-15
𝑉
𝐹
PB Bulk junction potential 0.8 0.87
𝑚
CGSO Gate-source overlap capacitance per meter 0.0 4.0e-11
𝐹
channel width
𝑚
CGDO Gate-drain overlap capacitance per meter 0.0 4.0e-11
𝐹
channel width
𝑚
CGBO Gate-bulk overlap capacitance per meter 0.0 2.0e-11
Ω
channel width
□
RSH Drain and source diffusion sheet resistance 0.0 10
𝐹
MJ Bulk junction bottom grading coeff. - 0.5 0.5
𝑚
CJSW Zero-bias bulk junction sidewall cap. per 0.0 1.0e-9
meter of junction perimeter
MJSW Bulk junction sidewall grading coeff. - 0.50 (l e v e l1)
0.33 (l e v e l2, 3)
𝑉 ⋅ 𝑠𝑒𝑐
UO Surface mobility 600 700
𝑉
𝑐𝑚
UCRIT Critical field for mobility degradation 1.0e4 1.0e4
(MOS2 only)
UEXP Critical field exponent in mobility - 0.0 0.1
degradation (MOS2 only)
UTRA Transverse field coeff. (mobility) (deleted - 0.0 0.3
𝑚
for MOS2)
𝑠
VMAX Maximum drift velocity of carriers 0.0 5.0e4
1
and MOS3)
𝑉
THETA Mobility modulation (MOS3 only) 0.0 0.1
In general, all parameters of BSIM models are obtained from process characterization, in particular level 4 and level 5 (BSIM1 and BSIM2)
parameters can be generated automatically. J. Pierret [4] describes a means of generating a `process' file, and the program ngproc2mod provided with
ngspice converts this file into a sequence of BSIM1 .model lines suitable for inclusion in an ngspice input file.
Parameters marked below with an * in the l/w column also have corresponding parameters with a length and width dependency. For example, vfb is
the basic parameter with units of Volts, and lvfb and wvfb also exist and have units of Volt-meter.
The formula
𝑃𝐿 𝑃𝑊
𝑃 = 𝑃0 + +
𝐿effective 𝑊effective
is used to evaluate the parameter for the actual device specified with
𝐿effective = 𝐿input − 𝐷𝐿
𝑊effective = 𝑊input − 𝐷𝑊
Note that unlike the other models in ngspice, the BSIM models are designed for use with a process characterization system that provides all the
parameters, thus there are no defaults for the parameters, and leaving one out is considered an error. For an example set of parameters and the format
of a process file, see the SPICE2 implementation notes [3]. For more information on BSIM2, see reference [5]. BSIM3 (11.2.10) and BSIM4 (11.2.11)
represent state of the art for submicron and deep submicron IC design.
𝑉
Name Parameter Units l/w
VFB Flat-band voltage *
PHI Surface inversion potential 𝑉 *
K1 Body effect coefficient √𝑉 *
K2 Drain/source depletion charge-sharing coefficient - *
𝑐𝑚2
ETA Zero-bias drain-induced barrier-lowering coefficient - *
𝑉 ⋅ 𝑠𝑒𝑐
MUZ Zero-bias mobility
DL Shortening of channel 𝜇𝑚
𝜇𝑚
1
DW Narrowing of channel
𝑉
U0 Zero-bias transverse-field mobility degradation coefficient *
𝜇
𝑉
U1 Zero-bias velocity saturation coefficient *
𝑐𝑚2
𝑉2 ⋅ 𝑠𝑒𝑐
X2MZ Sens. of mobility to substrate bias at v=0 *
1
𝑉
X2E Sens. of drain-induced barrier lowering effect to substrate bias *
1
𝑉 2
X2U0 Sens. of transverse field mobility degradation effect to substrate bias *
𝜇𝑚
𝑉 2
X2U1 Sens. of velocity saturation effect to substrate bias *
𝜇𝑚
𝑉 2
X3U1 Sens. of velocity saturation effect on drain bias at Vds=Vdd *
𝑚
CGDO Gate-drain overlap capacitance per meter channel width
𝐹
𝑚
CGSO Gate-source overlap capacitance per meter channel width
𝐹
𝑚
CGBO Gate-bulk overlap capacitance per meter channel length
Ω
ND Sens. of subthreshold slope to drain bias - *
□
RSH Drain and source diffusion sheet resistance
𝐴
𝑚2
JS Source drain junction current density
𝐹
MJSW Grading coefficient of source drain junction sidewall -
𝑚2
CJ Source drain junction capacitance per unit area
𝐹
𝑚
CJSW source drain junction sidewall capacitance per unit length
xpart = 0 selects a 40/60 drain/source charge partition in saturation, while xpart=1 selects a 0/100 drain/source charge partition. nd, ng, and ns are
the drain, gate, and source nodes, respectively. mname is the model name, area is the area factor, and off indicates an (optional) initial condition on
the device for dc analysis. If the area factor is omitted, a value of 1.0 is assumed. The (optional) initial condition specification, using ic=vds,vgs is
intended for use with the uic option on the .tran control line, when a transient analysis is desired starting from other than the quiescent operating
point. See the .ic control line for a better way to set initial conditions.
The following table summarizes the story of this model and their available ngspice versions:
BSIM3v2 and 3v3 models have been proven for accurate use in 0.18 𝜇𝑚 technologies. The model is publicly available as source code form from
University of California, Berkeley.
We recommend that you use only the most recent BSIM3 models (version 3.3.0), because it contains corrections to all known bugs. To achieve that,
change the version parameter in your modelcard files to
VERSION = 3.3.0.
If no version number is given in the .model card, this (newest) version is selected as the default.
A basic model card using only the intrinsic default parameters may look like
.model n1 nmos level=49 version=3.3.0
.model p1 pmos level=49 version=3.3.0
Unfortunately, due to historical reasons, these purely intrinsic parameters do not describe realistic devices. A better minimum model configuration,
roughly describing 0.35µm transistors, is
.model n1 nmos level=49 version=3.3.0 tox=10n nch=1e17 nsub=5e16
.model p1 pmos level=49 version=3.3.0 tox=10n nch=1e17 nsub=5e16
BSIM3v3.2.4 supports the extra model parameter lmlt on channel length scaling and is still used by many foundries today.
The older BSIM3 models will not be supported, they are made available for reference only.
**) Parallel processing using OpenMP support is available for this model.
Details of any revision are to be found in the Berkeley user's manuals, a pdf download of the most recent edition is to be found here.
We recommend that you use only the most recent BSIM4 model (version 4.8.2), because it contains corrections to all known bugs. To achieve that,
change the version parameter in your modelcard files to
VERSION = 4.8.2
If no version number is given in the .model card, this (newest) version is selected as the default. The older models will typically not be supported,
they are made available for reference only.
The basic model card, using only the intrinsic default parameters, already delivers reasonable device characteristics.
.model n1 nmos level=54 version=4.8.2
.model p1 pmos level=54 version=4.8.2
1. HiSIM2 model: Surface-Potential-Based MOSFET Model for Circuit Simulation version 2.8.0 - level 68 (see link to HiSIM2 for source
code and manual).
2. HiSIM_HV model: Surface-Potential-Based HV/LD-MOSFET Model for Circuit Simulation version 1.2.4 and 2.2.0 - level 73 (see link to
HiSIM_HV for source code and manual).
11.2.15 MOS models available via OpenVAF/OSDI
With its integrated OSDI interface and the OpenVAF compiler (see chapter 13 for details), ngspice makes available several Verilog-A compact MOS
models. To obtain the sources you may visit the github repository VA-Models which assembles most of the publicly available Verilog-A compact
models. To just name a few models:
PSP is a surface-potential based MOS Model, containing all relevant physical effects to model present-day and upcoming deep-submicron bulk
CMOS technologies:
mobility reduction
velocity saturation drain induced barrier lowering DIBL
gate current
lateral doping gradient effects
STI stress
The source/drain junction model, c.q. the JUNCAP2 model, is fully integrated in PSP. Detailes information and the most recent version of the model
documentation are available on the the CEA-Leti web site, see also the PSP Summary.
The following 'parameters' in the .model line are no model parameters, but serve information purposes for the user: mfg=..., Vds=..., Ron=...,
and Qg=... They are ignored by ngspice.
General form:
Example:
M1 24 2 0 IXTH48P20P
.MODEL IXTH48P20P VDMOS Pchan Vds=200 VTO=-4 KP=10 Lambda=5m
+ Mtriode=0.3 Ksubthres=120m Rs=10m Rd=20m Rds=200e6
+ Cgdmax=6000p Cgdmin=100p A=0.25 Cgs=5000p Cjo=9000p
+ Is=2e-6 Rb=20m BV=200 IBV=250e-6 NBV=4 TT=260e-9
𝑉 2
KP Transconductance parameter 1.0 5.9
𝑉
1
PHI Surface potential
𝑉
LAMBDA Channel length modulation (𝜆) 0.0 0.001
1
𝑉
THETA Vgs influence on mobility 0.0 0.015
1
°𝐶
TCVTH (VTOTC) Linear Vth0 temperature coefficient 0.0 0.0065
1
TEXP1 Drain resistance rd1 temperature exponent - 0.3
°𝐶
TRD1 Drain resistance linear temperature 0.0
1
coefficient
2
(°𝐶)
TRD2 Drain resistance quadratic temperature 0.0
coefficient
1
°𝐶
TRG1 Gate resistance linear temperature 0.0
1
coefficient
2
(°𝐶)
TRG2 Gate resistance quadratic temperature 0.0
coefficient
1
°𝐶
TRS1 Source resistance linear temperature 0.0
1
coefficient
2
(°𝐶)
TRS2 Source resistance quadratic temperature 0.0
coefficient
1
°𝐶
TRB1 Body resistance linear temperature 0.0
1
coefficient
2
(°𝐶)
TRB2 Body resistance quadratic temperature 0.0
coefficient
1
°𝐶
TKSUBTHRES1 Linear temperature coefficient of ksubthres 0.0
1
2
(°𝐶)
TKSUBTHRES2 Quadratic temperature coefficient of 0.0
ksubthres
𝐾
𝑊
RTHJC Thermal resistance junction-case 1.0 0.4
𝐽
𝐾
CTHJ Thermal capacitance 10e-6 5e-3
𝐾
𝑊
RTHCA Thermal resistance case-ambient (w/o 1000
heatsink)
The ngspice VDMOS model has introduced an electro-thermal approach by stamping additional elements into the circuit matrix and by iteration the
additional current control inside the spice solver.
The transistor now has 5 nodes. Besides D, G, and S we have TJ and TCASE. The additional nodes must be activated by the device switch
THERMAL. Heat is generated in the MOS channel and peripheral elements like resistors, its temperature is available and may be measured at node
TJ, and is fed back internally into the device equations. Within the transistor package the heat is flowing from the channel to the metal surface of the
case, at node TCASE. Here you may connect a heat sink, to offer a flow path for the heat away from the device. The internal heat resistance is RTHJC
(junction to case), a typical data sheet value. The model also includes the heat capacitance CTHJ of the semiconductor die and package (typically not
available in the data sheet, so to be estimated only).
The following example show the usage of ngspice electro-thermal model including a simple heat sink:
General form:
Example:
M1 24 2 0 tj tc IXTH48P20P thermal
rcs tc 1 0.1
csa 1 0 30m
rsa 1 amb 1.3
VTamb tamb 0 25
.MODEL IXTH48P20P VDMOS Pchan Vds=200 VTO=-4 KP=10 Lambda=5m
+ Mtriode=0.3 Ksubthres=120m Rs=10m Rd=20m Rds=200e6
+ Cgdmax=6000p Cgdmin=100p A=0.25 Cgs=5000p Cjo=9000p
+ Is=2e-6 Rb=20m BV=200 IBV=250e-6 NBV=4 TT=260e-9
+ Rthjc=0.4 Cthj=5e-3
This chapter describes the predefined models available in ngspice, stemming from the original XSPICE simulator or being added to enhance the
usability. The instructions for writing new code models are given in Chapt. 28.
To make use of the XSPICE extensions, you need to compile them in. Linux, CYGWIN, MINGW and other users may add the flag --enable-xspice
to their ./configure command and then recompile. The pre-built ngspice for Windows distribution has XSPICE already enabled. For detailed
compiling instructions see Chapt. 32.1.
a1 1 2 amp
.model amp gain(gain=5.0)
In this example the numerical values picked up from single-ended (i.e. ground referenced) input node 1 and output to single-ended output node 2 will
be voltages, since in the Interface Specification File for this code model (i.e., gain), the default port type is specified as a voltage (more on this later).
However, if you didn't know this, the following modifications to the instance card could be used to insure it:
Example:
The specification %v preceding the input and output node numbers of the instance card indicate to the simulator that the inputs to the model should be
single-ended voltage values. Other possibilities exist, as described later.
Some of the other features of the instance and .MODEL cards are worth noting. Of particular interest is the portion of the .MODEL card that specifies
gain=5.0. This portion of the card assigns a value to a parameter of the `gain' model. There are other parameters that can be assigned values for this
model, and in general code models will have several. In addition to numeric values, code model parameters can take non-numeric values (such as
TRUE and FALSE), and even vector values. All of these topics will be discussed at length in the following pages. In general, however, the instance
and .MODEL cards that define a code model will follow the abstract form described below. This form illustrates that the number of inputs and outputs
and the number of parameters that can be specified is relatively open-ended and can be interpreted in a variety of ways (note that angle-brackets `<'
and `>' enclose optional inputs):
Example:
Square brackets ([ ]) are used to enclose vector input nodes. In addition, these brackets are used to delineate vectors of parameters.
The literal string `null', when included in a node list, is interpreted as no connection at that input to the model. `Null' is not allowed as the name of a
model's input or output if the model only has one input or one output. Also, `null' should only be used to indicate a missing connection for a code
model; use on other XSPICE component is not interpreted as a missing connection, but will be interpreted as an actual node name.
The tilde, `~', when prepended to a digital node name, specifies that the logical value of that node be inverted prior to being passed to the code model.
This allows for simple inversion of input and output polarities of a digital model in order to handle logically equivalent cases and others that
frequently arise in digital system design. The following example defines a NAND gate, one input of which is inverted:
a1 [~1 2] 3 nand1
.model nand1 d_nand (rise_delay=0.1 fall_delay=0.2)
The optional symbols %v, %i, %vd, etc. specify the type of port the simulator is to expect for the subsequent port or port vector. The meaning of each
symbol is given in Table 12.1.
%vd [1 2 3 4]
The parameter names listed on the .MODEL card must be identical to those named in the code model itself. The parameters for each predefined code
model are described in detail in Sections 12.2 (analog), 12.3 (Hybrid, A/D) and 12.4 (digital). The steps required in order to specify parameters for
user-defined models are described in Chapter 28.
12.1.2 Examples
The following is a list of instance card and associated .MODEL card examples showing use of predefined models within an XSPICE deck:
a1 1 2 amp
.model amp gain(in_offset=0.1 gain=5.0 out_offset=-0.01)
a2 %i[1 2] 3 sum1
.model sum1 summer(in_offset=[0.1 -0.2] in_gain=[2.0 1.0]
+ out_gain=5.0 out_offset=-0.01)
a5 1 2 limit5
.model limit5 limit(in_offset=0.1 gain=2.5
+ out_lower_limit=-5.0 out_upper_limit=5.0 limit_range=0.10
+ fraction=FALSE)
a7 2 %id(4 7) xfer_cntl1
.model xfer_cntl1 pwl(x_array=[-2.0 -1.0 2.0 4.0 5.0]
+ y_array=[-0.2 -0.2 0.1 2.0 10.0]
+ input_domain=0.05 fraction=TRUE)
a8 3 %gd(6 7) switch3
.model switch3 aswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e6
+ r_on=10.0 log=TRUE)
Infile_Path/<path/filename> (Infile_Path is the path of the input file *.sp containing the netlist)
NGSPICE_INPUT_DIR/<path/filename> (where an additional path is set by the environmental variable)
<path/filename> (where the search is relative to the current directory (OS dependent))
If you don't want to make use of spinit, you may run a script in ngspice, before loading any circuit, which contains the codemodel commands. When
using shared ngspice, one may issue the codemodel commands directly after initialization, with absolute path or path relative to the current working
directory.
In a standard ngspice installation in MS Windows, the codemodels are located in ../lib/ngspice, e.g. in C:\Spice64\lib\ngspice (see also 32.2.1).
In Linux, it depends on the OS invocation. In openSUSE you may find the codemodels in /usr/local/lib64/ngspice, while ngspice resides in
/usr/local/bin.
12.2.1 Gain
NAME_TABLE:
C_Function_Name: cm_gain
Spice_Model_Name: gain
Description: "A simple gain block"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: v v
Allowed_Types: [v,vd,i,id,vnam] [v,vd,i,id]
Vector: no no
Vector.Bounds: - -
Null.Allowed: no no
PARAMETER_TABLE:
Parameter_Name: in_offset gain out_offset
Description: "input offset" "gain" "output offset"
Data_Type: real real real
Default_Value: 0.0 1.0 0.0
Limits: - - -
Vector: no no no
Vector_Bounds: - - -
Null_Allowed: yes yes yes
Description:
This function is a simple gain block with optional offsets on the input and the output. The input offset is added to the input, the sum is then
multiplied by the gain, and the result is produced by adding the output offset. This model will operate in DC, AC, and Transient analysis modes.
Example:
a1 1 2 amp
.model amp gain(in_offset=0.1 gain=5.0
+ out_offset=-0.01)
12.2.2 Summer
NAME_TABLE:
C_Function_Name: cm_summer
Spice_Model_Name: summer
Description: "A summer block"
PORT_TABLE:
Port Name: in out
Description: "input vector" "output"
Direction: in out
Default_Type: v v
Allowed_Types: [v,vd,i,id,vnam] [v,vd,i,id]
Vector: yes no
Vector_Bounds: - -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: in_offset in_gain
Description: "input offset vector" "input gain vector"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: yes yes
Vector_Bounds: in in
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: out_gain out_offset
Description: "output gain" "output offset"
Data_Type: real real
Default_Value: 1.0 0.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
Description:
This function is a summer block with 2-to-N input ports. Individual gains and offsets can be applied to each input and to the output. Each input
is added to its respective offset and then multiplied by its gain. The results are then summed, multiplied by the output gain and added to the
output offset. This model will operate in DC, AC, and Transient analysis modes.
Example usage:
a2 [1 2] 3 sum1
.model sum1 summer(in_offset=[0.1 -0.2] in_gain=[2.0 1.0]
+ out_gain=5.0 out_offset=-0.01)
12.2.3 Multiplier
NAME_TABLE:
C_Function_Name: cm_mult
Spice_Model_Name: mult
Description: "multiplier block"
PORT_TABLE:
Port_Name: in out
Description: "input vector" "output"
Direction: in out
Default_Type: v v
Allowed_Types: [v,vd,i,id,vnam] [v,vd,i,id]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: in_offset in_gain
Description: "input offset vector" "input gain vector"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: yes yes
Vector_Bounds: in in
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: out_gain out_offset
Description: "output gain" "output offset"
Data_Type: real real
Default_Value: 1.0 0.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
Description:
This function is a multiplier block with 2-to-N input ports. Individual gains and offsets can be applied to each input and to the output. Each
input is added to its respective offset and then multiplied by its gain. The results are multiplied along with the output gain and are added to the
output offset. This model will operate in DC, AC, and Transient analysis modes. However, in ac analysis it is important to remember that results
are invalid unless only one input of the multiplier is connected to a node that i connected to an AC signal (this is exemplified by the use of a
multiplier to perform a potentiometer function: one input is DC, the other carries the AC signal).
Example SPICE Usage:
a3 [1 2 3] 4 sigmult
.model sigmult mult(in_offset=[0.1 0.1 -0.1]
+ in_gain=[10.0 10.0 10.0] out_gain=5.0 out_offset=0.05)
12.2.4 Divider
NAME_TABLE:
C_Function_Name: cm_divide
Spice_Model_Name: divide
Description: "divider block"
PORT_TABLE:
Port_Name: num den out
Description: "numerator" "denominator" "output"
Direction: in in out
Default_Type: v v v
Allowed_Types: [v,vd,i,id,vnam] [v,vd,i,id,vnam] [v,vd,i,id]
Vector: no no no
Vector_Bounds: - - -
Null_Allowed: no no no
PARAMETER_TABLE:
Parameter_Name: num_offset num_gain
Description: "numerator offset" "numerator gain"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: den_offset den_gain
Description: "denominator offset" "denominator gain"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: den_lower_limit
Description: "denominator lower limit"
Data_Type: real
Default_Value: 1.0e-10
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: den_domain
Description: "denominator smoothing domain"
Data_Type: real
Default_Value: 1.0e-10
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: fraction
Description: "smoothing fraction/absolute value switch"
Data_Type: boolean
Default_Value: false
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: out_gain out_offset
Description: "output gain" "output offset"
Data_Type: real real
Default_Value: 1.0 0.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
Description:
This function is a two-quadrant divider. It takes two inputs; num (numerator) and den (denominator). Divide offsets its inputs, multiplies them
by their respective gains, divides the results, multiplies the quotient by the output gain, and offsets the result. The denominator is limited to a
value above zero via a user specified lower limit. This limit is approached through a quadratic smoothing function, the domain of which may be
specified as a fraction of the lower limit value (default), or as an absolute value. This model will operate in DC, AC and Transient analysis
modes. However, in ac analysis it is important to remember that results are invalid unless only one input of the divider is connected to a node
that is connected to an ac signal (this is exemplified by the use of the divider to perform a potentiometer function: one input is dc, the other
carries the ac signal).
Example SPICE Usage:
a4 1 2 4 divider
.model divider divide(num_offset=0.1 num_gain=2.5 den_offset=-0.1
+ den_gain=5.0 den_lower_limit=1e-5 den_domain=1e-6
+ fraction=FALSE out_gain=1.0 out_offset=0.0)
12.2.5 Limiter
NAME_TABLE:
C_Function_Name: cm_limit
Spice_Model_Name: limit
Description: "limit block"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: v v
Allowed_Types: [v,vd,i,id] [v,vd,i,id]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: in_offset gain
Description: "input offset" "gain"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: out_lower_limit out_upper_limit
Description: "output lower limit" "output upper limit"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: limit_range
Description: "upper & lower smoothing range"
Data_Type: real
Default_Value: 1.0e-6
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: fraction
Description: "smoothing fraction/absolute value switch"
Data_Type: boolean
Default_Value: FALSE
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
The Limiter is a single input, single output function similar to the Gain Block. However, the output of the Limiter function is restricted to the
range specified by the output lower and upper limits. This model will operate in DC, AC and Transient analysis modes. Note that the limit
range is the value below the upper limit and above the lower limit at which smoothing of the output begins. For this model, then, the limit range
volts, the output will begin to smooth out at ±0.9 volts, which occurs when the input value is at ±0.4.
represents the delta with respect to the output level at which smoothing occurs. Thus, for an input gain of 2.0 and output limits of 1.0 and -1.0
Description:
The Controlled Limiter is a single input, single output function similar to the Gain Block. However, the output of the Limiter function is
that the limit range is the value below the 𝑐𝑛𝑡𝑙𝑢𝑝𝑝𝑒𝑟 limit and above the 𝑐𝑛𝑡𝑙𝑙𝑜𝑤𝑒𝑟 limit at which smoothing of the output begins (minimum
restricted to the range specified by the output lower and upper limits. This model will operate in DC, AC, and Transient analysis modes. Note
positive value of voltage must exist between the 𝑐𝑛𝑡𝑙𝑢𝑝𝑝𝑒𝑟 input and the 𝑐𝑛𝑡𝑙𝑙𝑜𝑤𝑒𝑟 input at all times). For this model, then, the limit range
volts, the output will begin to smooth out at ±0.9 volts, which occurs when the input value is at ±0.4. Note also that the Controlled Limiter
represents the delta with respect to the output level at which smoothing occurs. Thus, for an input gain of 2.0 and output limits of 1.0 and -1.0
code tests the input values of 𝑐𝑛𝑡𝑙𝑢𝑝𝑝𝑒𝑟 and 𝑐𝑛𝑡𝑙𝑙𝑜𝑤𝑒𝑟 to make sure that they are spaced far enough apart to guarantee the existence of a linear
range between them. The range is calculated as the difference between (𝑐𝑛𝑡𝑙𝑢𝑝𝑝𝑒𝑟 − 𝑢𝑝𝑝𝑒𝑟𝑑𝑒𝑙𝑡𝑎 − 𝑙𝑖𝑚𝑖𝑡𝑟𝑎𝑛𝑔𝑒) and (
𝑐𝑛𝑡𝑙𝑙𝑜𝑤𝑒𝑟 + 𝑙𝑜𝑤𝑒𝑟𝑑𝑒𝑙𝑡𝑎 + 𝑙𝑖𝑚𝑖𝑡𝑟𝑎𝑛𝑔𝑒) and must be greater than or equal to zero. Note that when the limit range is specified as a fractional
value, the limit range used in the above is taken as the calculated fraction of the difference between 𝑐𝑛𝑡𝑙𝑢𝑝𝑝𝑒𝑟 and 𝑐𝑛𝑡𝑙𝑙𝑜𝑤𝑒𝑟. Still, the potential
exists for too great a limit range value to be specified for proper operation, in which case the model will return an error message.
Example SPICE Usage:
a6 3 6 8 4 varlimit
.
.
.model varlimit climit(in_offset=0.1 gain=2.5 upper_delta=0.0
+ lower_delta=0.0 limit_range=0.10 fraction=FALSE)
Description:
The Piece-Wise Linear Controlled Source is a single input, single output function similar to the Gain Block. However, the output of the PWL
Source is not necessarily linear for all values of input. Instead, it follows an I/O relationship specified by you via the x_array and y_array
coordinates. This is detailed below.
The x_array and y_array values represent vectors of coordinate points on the x and y axes, respectively. The x_array values are progressively
increasing input coordinate points, and the associated y_array values represent the outputs at those points. There may be as few as two
(x_array[n], y_array[n]) pairs specified, or as many as memory and simulation speed allow. This permits you to very finely approximate a
non-linear function by capturing multiple input-output coordinate points.
Two aspects of the PWL Controlled Source warrant special attention. These are the handling of endpoints and the smoothing of the described
transfer function near coordinate points.
In order to fully specify outputs for values of in outside of the bounds of the PWL function (i.e., less than x_array[0] or greater than
x_array[n], where n is the largest user-specified coordinate index), the PWL Controlled Source model extends the slope found between the
lowest two coordinate pairs and the highest two coordinate pairs. This has the effect of making the transfer function completely linear for in
less than x_array[0] and in greater than x_array[n]. It also has the potentially subtle effect of unrealistically causing an output to reach a very
large or small value for large inputs. You should thus keep in mind that the PWL Source does not inherently provide a limiting capability.
In order to diminish the potential for non-convergence of simulations when using the PWL block, a form of smoothing around the x_array,
y_array coordinate points is necessary. This is due to the iterative nature of the simulator and its reliance on smooth first derivatives of transfer
functions in order to arrive at a matrix solution. Consequently, the input_domain and fraction parameters are included to allow you some
control over the amount and nature of the smoothing performed.
Fraction is a switch that is either TRUE or FALSE. When TRUE (the default setting), the simulator assumes that the specified input domain
value is to be interpreted as a fractional figure. Otherwise, it is interpreted as an absolute value. Thus, if fraction=TRUE and
input_domain=0.10, The simulator assumes that the smoothing radius about each coordinate point is to be set equal to 10% of the length of
either the x_array segment above each coordinate point, or the x_array segment below each coordinate point. The specific segment length
chosen will be the smallest of these two for each coordinate point.
On the other hand, if fraction=FALSE and input_domain=0.10, then the simulator will begin smoothing the transfer function at 0.10 volts (or
amperes) below each x_array coordinate and will continue the smoothing process for another 0.10 volts (or amperes) above each x_array
coordinate point. Since the overlap of smoothing domains is not allowed, checking is done by the model to ensure that the specified input
domain value is not excessive.
One subtle consequence of the use of the fraction=TRUE feature of the PWL Controlled Source is that, in certain cases, you may
inadvertently create extreme smoothing of functions by choosing inappropriate coordinate value points. This can be demonstrated by
considering a function described by three coordinate pairs, such as (-1,-1), (1,1), and (2,1). In this case, with a 10% input_domain value
specified (fraction=TRUE, input_domain=0.10), you would expect to see rounding occur between in=0.9 and in=1.1, and nowhere else. On
the other hand, if you were to specify the same function using the coordinate pairs (-100,-100), (1,1) and (201,1), you would find that rounding
occurs between in=-19 and in=21. Clearly in the latter case the smoothing might cause an excessive divergence from the intended linearity
above and below in=1.
Example SPICE Usage:
a7 2 4 xfer_cntl1
.model xfer_cntl1 pwlts(x_array=[-2.0 -1.0 2.0 4.0 5.0]
+ y_array=[-0.2 -0.2 0.1 2.0 10.0]
+ input_domain=0.05 fraction=TRUE)
Description:
The Piece-Wise Linear Time Controlled Source is a time input, single output function. The output follows an time/output relationship specified
by you via the x_array and y_array coordinates. This is detailed below.
The x_array and y_array values represent vectors of coordinate points on the x and y axes, respectively. The x_array values are progressively
increasing positive input coordinate points (minimum is 0), and the associated y_array values represent the outputs at those points. There may
be as few as two (x_array[n], y_array[n]) pairs specified, or as many as memory and simulation speed allow. This permits you to very finely
approximate a non-linear time dependent waveform by capturing multiple input-output coordinate points.
Two aspects of the PWLTS Controlled Source warrant special attention. These are the handling of endpoints and the smoothing of the described
transfer function near coordinate points.
In order to fully specify outputs for values of in outside of the bounds of the PWLTS function (i.e., less than x_array[0] (with x_array[0] >= 0
always) or greater than x_array[n], where n is the largest user-specified coordinate index), the PWLTS Time Controlled Source model extends
the slope found between the lowest two coordinate pairs and the highest two coordinate pairs. This has the effect of making the transfer function
completely linear for times less than x_array[0] and times greater than x_array[n]. It also has the potentially subtle effect of unrealistically
causing an output to reach a very large or small value for large input times.
In order to diminish the potential for non-convergence of simulations when using the PWL block, a form of smoothing around the x_array,
y_array coordinate points is necessary. This is due to the iterative nature of the simulator and its reliance on smooth first derivatives of transfer
functions in order to arrive at a matrix solution. Consequently, the input_domain and fraction parameters are included to allow you some
control over the amount and nature of the smoothing performed.
Fraction is a switch that is either TRUE or FALSE. When TRUE (the default setting), the simulator assumes that the specified input domain
value is to be interpreted as a fractional figure. Otherwise, it is interpreted as an absolute value. Thus, if fraction=TRUE and
input_domain=0.10, the simulator assumes that the smoothing radius about each coordinate point is to be set equal to 10% of the length of
either the x_array segment above each coordinate point, or the x_array segment below each coordinate point. The specific segment length
chosen will be the smallest of these two for each coordinate point.
On the other hand, if fraction=FALSE and input_domain=0.10, then the simulator will begin smoothing the transfer function at 0.10 seconds
below each x_array coordinate and will continue the smoothing process for another 0.10 seconds above each x_array coordinate point. Since
the overlap of smoothing domains is not allowed, checking is done by the model to ensure that the specified input domain value is not
excessive.
One subtle consequence of the use of the fraction=TRUE feature of the PWL Time Controlled Source is that, in certain cases, you may
inadvertently create extreme smoothing of functions by choosing inappropriate coordinate value points. This can be demonstrated by
considering a function described by three coordinate pairs, such as (0,-1), (2,1), and (3,1). In this case, with a 10% input_domain value
specified (fraction=TRUE, input_domain=0.10), you would expect to see rounding occur between time=1.9 and time=2.1, and nowhere else.
On the other hand, if you were to specify the same function using the coordinate pairs (0,-100), (101,1) and (301,1), you would find that
rounding occurs between time=81 and time=121. Clearly in the latter case the smoothing might cause an excessive divergence from the
intended linearity above and below time=101.
Example SPICE Usage:
a8 out pwl_cntl1
Description:
The File Source is similar to the Piece-Wise Linear (PWL) Source, except that the waveform data is read from a file instead of being taken from
parameter vectors. The file format is line oriented ASCII. `#' and `;' are comment characters; all characters from a comment character until the
end of the line are ignored. Each line consists of two or more real values. The first value is the time; subsequent values correspond to the
outputs. Values are separated by spaces. Time values are absolute and must be monotonically increasing, unless timerelative is set to TRUE, in
which case the values specify the interval between two samples and must be positive. Waveforms may be scaled and shifted in the time
dimension by setting timescale and timeoffset.
Amplitudes can also be scaled and shifted using amplscale and amploffset. Amplitudes are normally interpolated between two samples,
unless amplstep is set to TRUE.
Note:
The file named by the parameter filename in file="filename" is sought after according to a search list described in12.1.3.
Example SPICE Usage:
a8 %vd([1 0 2 0]) filesrc
.
.
.model filesrc filesource (file="sine.m" amploffset=[0 0] amplscale=[1 1]
+ timeoffset=0 timescale=1
+ timerelative=false amplstep=false)
12.2.10 Multi_input_PWL_block
NAME_TABLE:
C_Function_Name: cm_multi_input_pwl
Spice_Model_Name: multi_input_pwl
Description: "multi_input_pwl block"
PORT_TABLE:
Port_Name: in out
Description: "input array" "output"
Direction: in out
Default_Type: vd vd
Allowed_Types: [vd,id] [vd,id]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: x y
Description: "x array" "y array"
Data_Type: real real
Default_Value: 0.0 0.0
Limits: - -
Vector: yes yes
Vector_Bounds: [2 -] [2 -]
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: model
Description: "model type"
Data_Type: string
Default_Value: "and"
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
Multi-input gate voltage controlled voltage source that supports and or or gating. The x's and y's represent the piecewise linear variation of
output (y) as a function of input (x). The type of gate is selectable by the parameter model. In case the model is and, the smallest input
determines the output value (i.e. the and function). In case the model is or, the largest input determines the output value (i.e. the or function).
The inverse of these functions (i.e. nand and nor) is constructed by complementing the y array.
Example SPICE Usage:
a82 [1 0 2 0 3 0] 7 0 pwlm
.
.
.model pwlm multi_input_pwl((x=[-2.0 -1.0 2.0 4.0 5.0]
+ y=[-0.2 -0.2 0.1 2.0 10.0]
+ model="and")
Description:
The Analog Switch is a resistor that varies either logarithmically or linearly between specified values of a controlling input voltage or current.
Note that the input is not internally limited when parameter limit is not given. Therefore, if the controlling signal exceeds the specified OFF
state or ON state value, the resistance may become excessively large or excessively small (in the case of logarithmic dependence), or may
become negative (in the case of linear dependence). For the experienced user, these excursions may prove valuable for modeling certain
devices, but in most cases you are advised to add limiting of the controlling input if the possibility of excessive control value variation exists.
Alternatively you may set the parameter limit to TRUE. Then the resulting resistance is limited to r_on or r_off if the controlling voltage
exceeds the given boundaries cntl_on or cntl_off. At these boundaries sharp edges in the R(control) characteristics will occur which may
lead to convergence problems.
Example SPICE Usage:
a8 3 %gd(6 7) switch3
.
.
.model switch3 aswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e6
+ r_on=10.0 log=TRUE limit=TRUE)
Description:
The Alternative Analog Switch is a resistor that varies either logarithmically or linearly between specified values of a controlling input voltage
or current. An input resistance r_cntl_in may be specified. The output resistance is limited to r_on or r_off. At the control boundaries
cntl_on or cntl_off the R(control) characteristics are slightly rounded. This behaviour is PSPICE-compatible and instances of this device are
generated when parsing PSPICE netlists in compatability mode.
Example SPICE Usage:
a9 %g 13 %gd(16 17) switch4
.
.
.model switch4 pswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e6
+ r_on=10.0 r_cntl_in=1e11 log=TRUE)
Description:
The Zener Diode models the DC characteristics of most zeners. This model differs from the Diode/Rectifier by providing a user-defined
dynamic resistance in the reverse breakdown region. The forward characteristic is defined by only a single point, since most data sheets for
zener diodes do not give detailed characteristics in the forward region.
The first three parameters define the DC characteristics of the zener in the breakdown region and are usually explicitly given on the data sheet.
The saturation current refers to the relatively constant reverse current that is produced when the voltage across the zener is negative, but
breakdown has not been reached. The reverse leakage current determines the slight increase in reverse current as the voltage across the zener
becomes more negative. It is modeled as a resistance parallel to the zener with value v breakdown / i rev.
Note that the limit switch parameter engages an internal limiting function for the zener. This can, in some cases, prevent the simulator from
converging to an unrealistic solution if the voltage across or current into the device is excessive. If use of this feature fails to yield acceptable
results, the convlimit option should be tried (add the following statement to the SPICE input deck: .options convlimit)
Example SPICE Usage:
a9 3 4 vref10
.
.
.model vref10 zener(v_breakdown=10.0 i_breakdown=0.02
+ r_breakdown=1.0 i_rev=1e-6 i_sat=1e-12)
Description:
The Current Limiter models the behavior of an operational amplifier or comparator device at a high level of abstraction. All of its pins act as
inputs; three of the four also act as outputs. The model takes as input a voltage value from the in connector. It then applies an offset and a gain,
and derives from it an equivalent internal voltage (veq), which it limits to fall between pos_pwr and neg_pwr. If veq is greater than the output
voltage seen on the out connector, a sourcing current will flow from the output pin. Conversely, if the voltage is less than vout, a sinking
current will flow into the output pin.
Depending on the polarity of the current flow, either a sourcing or a sinking resistance value (r_out_source, r_out_sink) is applied to govern
the vout/i_out relationship. The chosen resistance will continue to control the output current until it reaches a maximum value specified by
either i_limit_source or i_limit_sink. The latter mimics the current limiting behavior of many operational amplifier output stages.
During all operation, the output current is reflected either in the pos_pwr connector current or the neg_pwr current, depending on the polarity of
i_out. Thus, realistic power consumption as seen in the supply rails is included in the model.
vneg_pwr inputs beyond which 𝑣𝑒𝑞 = 𝑔𝑎𝑖𝑛(𝑣𝑖𝑛 + 𝑣𝑜𝑓𝑓𝑠𝑒𝑡 ) is smoothed; i_source_range specifies the current below i_limit_source at which
The user-specified smoothing parameters relate to model operation as follows: v_pwr_range controls the voltage below vpos_pwr and above
smoothing begins, as well as specifying the current increment above i_out=0.0 at which i_pos_pwr begins to transition to zero; i_sink_range
serves the same purpose with respect to i_limit_sink and i_neg_pwr that i_source_range serves for i_limit_source and i_pos_pwr;
r_out_domain specifies the incremental value above and below (veq-vout)=0.0 at which r_out will be set to r_out_source and r_out_sink,
respectively. For values of (veq-vout) less than r_out_domain and greater than -r_out_domain, r_out is interpolated smoothly between
r_out_source and r_out_sink.
Description:
The Hysteresis block is a simple buffer stage that provides hysteresis of the output with respect to the input. The in low and in high parameter
values specify the center voltage or current inputs about which the hysteresis effect operates. The output values are limited to out lower limit
and out upper limit. The value of hyst is added to the in low and in high points in order to specify the points at which the slope of the hysteresis
function would normally change abruptly as the input transitions from a low to a high value. Likewise, the value of hyst is subtracted from the
in high and in low values in order to specify the points at which the slope of the hysteresis function would normally change abruptly as the
input transitions from a high to a low value. In fact, the slope of the hysteresis function is never allowed to change abruptly but is smoothly
varied whenever the input domain smoothing parameter is set greater than zero.
Example SPICE Usage:
a11 1 2 schmitt1
.
.
.model schmitt1 hyst(in_low=0.7 in_high=2.4 hyst=0.5
+ out_lower_limit=0.5 out_upper_limit=3.0
+ input_domain=0.01 fraction=TRUE)
12.2.16 Differentiator
NAME_TABLE:
C_Function_Name: cm_d_dt
Spice_Model_Name: d_dt
Description: "time-derivative block"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: v v
Allowed_Types: [v,vd,i,id] [v,vd,i,id]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: gain out_offset
Description: "gain" "output offset"
Data_Type: real real
Default_Value: 1.0 0.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: out_lower_limit out_upper_limit
Description: "output lower limit" "output upper limit"
Data_Type: real real
Default_Value: - -
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: limit_range
Description: "upper & lower limit smoothing range"
Data_Type: real
Default_Value: 1.0e-6
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
The Differentiator block is a simple derivative stage that approximates the time derivative of an input signal by calculating the incremental
slope of that signal since the previous time point. The block also includes gain and output offset parameters to allow for tailoring of the required
signal, and output upper and lower limits to prevent convergence errors resulting from excessively large output values. The incremental value of
output below the output upper limit and above the output lower limit at which smoothing begins is specified via the limit range parameter. In
AC analysis, the value returned is equal to the radian frequency of analysis multiplied by the gain.
Note that since truncation error checking is not included in the d_dt block, it is not recommended that the model be used to provide an
integration function through the use of a feedback loop. Such an arrangement could produce erroneous results. Instead, you should make use of
the "integrate" model, which does include truncation error checking for enhanced accuracy.
Example SPICE Usage:
a12 7 12 slope_gen
.
.
.model slope_gen d_dt(out_offset=0.0 gain=1.0
+ out_lower_limit=1e-12 out_upper_limit=1e12
+ limit_range=1e-9)
12.2.17 Integrator
NAME_TABLE:
C_Function_Name: cm_int
Spice_Model_Name: int
Description: "time-integration block"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: v v
Allowed_Types: [v,vd,i,id] [v,vd,i,id]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: in_offset gain
Description: "input offset" "gain"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: out_lower_limit out_upper_limit
Description: "output lower limit" "output upper limit"
Data_Type: real real
Default_Value: - -
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: limit_range
Description: "upper & lower limit smoothing range"
Data_Type: real
Default_Value: 1.0e-6
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: out_ic
Description: "output initial condition"
Data_Type: real
Default_Value: 0.0
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
The Integrator block is a simple integration stage that approximates the integral with respect to time of an input signal. The block also includes
gain and input offset parameters to allow for tailoring of the required signal, and output upper and lower limits to prevent convergence errors
resulting from excessively large output values. Note that these limits specify integrator behavior similar to that found in an operational
amplifier-based integration stage, in that once a limit is reached, additional storage does not occur. Thus, the input of a negative value to an
integrator that is currently driving at the out upper limit level will immediately cause a drop in the output, regardless of how long the integrator
was previously summing positive inputs. The incremental value of output below the output upper limit and above the output lower limit at
which smoothing begins is specified via the limit range parameter. In AC analysis, the value returned is equal to the gain divided by the radian
frequency of analysis.
Note that truncation error checking is included in the int block. This should provide for a more accurate simulation of the time integration
function, since the model will inherently request smaller time increments between simulation points if truncation errors would otherwise be
excessive.
Example SPICE Usage:
a13 7 12 time_count
.model time_count int(in_offset=0.0 gain=1.0
+ out_lower_limit=-1e12 out_upper_limit=1e12
+ limit_range=1e-9 out_ic=0.0)
Description:
The s-domain transfer function is a single input, single output transfer function in the Laplace transform variable `s' that allows for flexible
modulation of the frequency domain characteristics of a signal. Ac and transient simulations are supported. The code model may be configured
to produce an arbitrary s-domain transfer function with the following restrictions:
1. The degree of the numerator polynomial cannot exceed that
of the denominator polynomial in the variable "s".
2. The coefficients for a polynomial must be stated
explicitly. That is, if a coefficient is zero, it must be
included as an input to the num coeff or den coeff vector.
The order of the coefficient parameters is from that associated with the highest-powered term decreasing to that of the lowest. Thus, for the coefficient
parameters specified below, the equation in `s' is shown:
.model filter s_xfer(gain=0.139713
+ num_coeff=[1.0 0.0 0.7464102]
+ den_coeff=[1.0 0.998942 0.001170077]
+ int_ic=[0 0])
It specifies a transfer function of the form
𝑠2 + 0.7464102
𝑁(𝑠) = 0.139713 ⋅ 2
𝑠 + 0.998942𝑠 + 0.00117077
The s-domain transfer function includes gain and in_offset (input offset) parameters to allow for tailoring of the required signal. There are no limits
on the internal signal values or on the output value of the s-domain transfer function, so you are cautioned to specify gain and coefficient values that
will not cause the model to produce excessively large values. In AC analysis, the value returned is equal to the real and imaginary components of the
total s-domain transfer function at each frequency of interest.
The denormalized_freq term allows you to specify coefficients for a normalized filter (i.e. one in which the frequency of interest is 1 rad/s). Once
these coefficients are included, specifying the denormalized frequency value `shifts' the corner frequency to the actual one of interest. As an example,
the following transfer function describes a Chebyshev low-pass filter with a corner (pass-band) frequency of 1 rad/s:
1.0
𝑁(𝑠) = 0.139713 ⋅
𝑠2 + 1.09773𝑠 + 1.10251
In order to define an s_xfer model for the above, but with the corner frequency equal to 1500 rad/s (239 Hz), the following instance and model lines
would be needed:
a12 node1 node2 cheby1
.model cheby1 s_xfer(num_coeff=[1] den_coeff=[1 1.09773 1.10251]
+ int_ic=[0 0] denormalized_freq=1500)
In the above, you add the normalized coefficients and scale the filter through the use of the denormalized freq parameter. Similar results could have
been achieved by performing the denormalization prior to specification of the coefficients, and setting denormalized freq to the value 1.0 (or not
specifying the frequency, as the default is 1.0 rad/s) Note in the above that frequencies are always specified as radians/second.
Truncation error checking is included in the s-domain transfer block. This should provide for more accurate simulations, since the model will
inherently request smaller time increments between simulation points if truncation errors would otherwise be excessive.
The int_ic parameter is an array that must be of size one less as the array of values specified for the den_coeff parameter. Even if a 0 start value is
required, you have to add the specific int_ic vector to the set of coefficients (see the examples above and below).
Example SPICE Usage:
a14 9 22 cheby_LP_3kHz
.
.
.model cheby_LP_3kHz s_xfer(in_offset=0.0 gain=1.0 int_ic=[0 0]
+ num_coeff=[1.0]
+ den_coeff=[1.0 1.42562 1.51620])
The data is treated as consisting of rows, each of “span” real numbers. The first number is the frequency of a PWL corner and a pair of numbers at the
“offset” position in the row supply the data. That allows a single Touchstone file to be shared by several instances of this code model, as such files for
an n-port device will contain logical rows of 2*n^2+1 numbers: one frequency value and the components of an NxN complex matrix. The format of
the data pairs is determined by the “db”, “rad” and “r_i” parameters. If any of these are set, they override the internal indicators in a Touchstone file
which themselves override the parameter defaults.
Examples of using this model are in the examples/sp directory: netlist file.sp shows direct use, while filter.sp uses the E-source wrapper (5.2.6).
Description:
This function is a simple slew rate block that limits the absolute slope of the output with respect to time to some maximum or value. The actual
slew rate effects of over-driving an amplifier circuit can thus be accurately modeled by cascading the amplifier with this model. The units used
to describe the maximum rising and falling slope values are expressed in volts or amperes per second. Thus a desired slew rate of 0.5 V/𝜇𝑠 will
be expressed as 0.5e+6, etc.
The slew rate block will continue to raise or lower its output until the difference between the input and the output values is zero. Thereafter, it
will resume following the input signal, unless the slope again exceeds its rise or fall slope limits. The range input specifies a smoothing region
above or below the input value. Whenever the model is slewing and the output comes to within the input + or - the range value, the partial
derivative of the output with respect to the input will begin to smoothly transition from 0.0 to 1.0. When the model is no longer slewing (output
= input), dout/din will equal 1.0.
Example SPICE Usage:
a15 1 2 slew1
.model slew1 slew(rise_slope=0.5e6 fall_slope=0.5e6)
Description:
This function is a conceptual model that is used as a building block to create a wide variety of inductive and magnetic circuit models. This
function is normally used in conjunction with the core model, but can also be used with resistors, hysteresis blocks, etc. to build up systems
that mock the behavior of linear and nonlinear components.
The lcouple takes as an input (on the `l' port), a current. This current value is multiplied by the num_turns value, N, to produce an output value
(a voltage value that appears on the mmf_out port). The mmf_out acts similar to a magnetomotive force in a magnetic circuit; when the lcouple
is connected to the core model, or to some other resistive device, a current will flow. This current value (which is modulated by whatever the
lcouple is connected to) is then used by the lcouple to calculate a voltage `seen' at the l port. The voltage is a function of the derivative with
respect to time of the current value seen at mmf_out.
The most common use for lcouples will be as a building block in the construction of transformer models. To create a transformer with a single
input and a single output, you would require two lcouple models plus one core model. The process of building up such a transformer is
described under the description of the core model, below.
Example SPICE Usage:
a150 (7 0) (9 10) lcouple1
.model lcouple1 lcouple(num_turns=10.0)
Description:
This function is a conceptual model that is used as a building block to create a wide variety of inductive and magnetic circuit models. This
function is almost always expected to be used in conjunction with the lcouple model to build up systems that mock the behavior of linear and
nonlinear magnetic components. There are two fundamental modes of operation for the core model. These are the pwl mode (which is the
default, and which is the most likely to be of use to you) and the hysteresis mode. These are detailed below.
The core model in PWL mode takes as input a voltage that it treats as a magnetomotive force (mmf) value. This value is divided by the total effective
length of the core to produce a value for the Magnetic Field Intensity, H. This value of H is then used to find the corresponding Flux Density, B, using
the piecewise linear relationship described by you in the H array / B array coordinate pairs. B is then multiplied by the cross-sectional area of the core
to find the Flux value, which is output as a current. The pertinent mathematical equations are listed below:
𝑚𝑚𝑓
𝐻= , 𝑤ℎ𝑒𝑟𝑒 𝐿 = 𝐿𝑒𝑛𝑔𝑡ℎ
𝐿
Here H, the Magnetic Field Intensity, is expressed in ampere-turns/meter.
𝐵 = 𝑓(𝐻)
The B value is derived from a piecewise linear transfer function described to the model via the (H_array[],B_array[]) parameter coordinate pairs. This
transfer function does not include hysteretic effects; for that, you would need to substitute a HYST model for the core.
𝜑 = 𝐵𝐴, 𝑤ℎ𝑒𝑟𝑒 𝐴 = 𝐴𝑟𝑒𝑎
The final current allowed to flow through the core is equal to 𝜑. This value in turn is used by the "lcouple" code model to obtain a value for the
voltage reflected back across its terminals to the driving electrical circuit.
The following example code shows the use of two lcouple models and one core model to produce a simple primary/secondary transformer.
Example SPICE Usage:
a1 (2 0) (3 0) primary
.model primary lcouple (num_turns = 155)
a2 (3 4) iron_core
.model iron_core core (H_array = [-1000 -500 -375 -250 -188 -125 -63 0
+ 63 125 188 250 375 500 1000]
+ B_array = [-3.13e-3 -2.63e-3 -2.33e-3 -1.93e-3
+ -1.5e-3 -6.25e-4 -2.5e-4 0 2.5e-4
+ 6.25e-4 1.5e-3 1.93e-3 2.33e-3
+ 2.63e-3 3.13e-3]
+ area = 0.01 length = 0.01)
a3 (5 0) (4 0) secondary
.model secondary lcouple (num_turns = 310)
HYSTERESIS Mode (mode = 2)
The core model in HYSTERESIS mode takes as input a voltage that it treats as a magnetomotive force (mmf) value. This value is used as input to the
equivalent of a hysteresis code model block. The parameters defining the input low and high values, the output low and high values, and the amount
of hysteresis are as in that model. The output from this mode, as in PWL mode, is a current value that is seen across the mc port. An example of the
core model used in this fashion is shown below:
Example SPICE Usage:
a1 (2 0) (3 0) primary
.model primary lcouple (num_turns = 155)
a2 (3 4) iron_core
.model iron_core core (mode = 2 in_low=-7.0 in_high=7.0
+ out_lower_limit=-2.5e-4 out_upper_limit=2.5e-4
+ hyst = 2.3 )
a3 (5 0) (4 0) secondary
.model secondary lcouple (num_turns = 310)
One final note to be made about the two core model nodes is that certain parameters are available in one mode, but not in the other. In particular, the
in_low, in_high, out_lower_limit, out_upper_limit, and hysteresis parameters are not available in PWL mode. Likewise, the H_array, B_array, area,
and length values are unavailable in HYSTERESIS mode. The input domain and fraction parameters are common to both modes (though their
behavior is somewhat different; for explanation of the input domain and fraction values for the HYSTERESIS mode, you should refer to the
hysteresis code model discussion).
Description:
This function is a controlled sine wave oscillator with parametrizable values of low and high peak output. It takes an input voltage or current
value. This value is used as the independent variable in the piecewise linear curve described by the coordinate points of the cntl array and freq
array pairs. From the curve, a frequency value is determined, and the oscillator will output a sine wave at that frequency. From the above, it is
easy to see that array sizes of 2 for both the cntl array and the freq array will yield a linear variation of the frequency with respect to the control
input. Any sizes greater than 2 will yield a piecewise linear transfer characteristic. For more detail, refer to the description of the piecewise
linear controlled source, which uses a similar method to derive an output value given a control input.
Example SPICE Usage:
asine 1 2 in_sine
.model in_sine sine(cntl_array = [-1 0 5 6]
+ freq_array=[10 10 1000 1000] out_low = -5.0
+ out_high = 5.0)
Description:
This function is a controlled triangle/ramp wave oscillator with parametrizable values of low and high peak output and rise time duty cycle. It
takes an input voltage or current value. This value is used as the independent variable in the piecewise linear curve described by the coordinate
points of the cntl_array and freq_array pairs.
From the curve, a frequency value is determined, and the oscillator will output a triangle wave at that frequency. From the above, it is easy to
see that array sizes of 2 for both the cntl_array and the freq_array will yield a linear variation of the frequency with respect to the control input.
Any sizes greater than 2 will yield a piecewise linear transfer characteristic. For more detail, refer to the description of the piecewise linear
controlled source, which uses a similar method to derive an output value given a control input.
Example SPICE Usage:
ain 1 2 ramp1
.model ramp1 triangle(cntl_array = [-1 0 5 6]
+ freq_array=[10 10 1000 1000] out_low = -5.0
+ out_high = 5.0 duty_cycle = 0.9)
Description:
This function is a controlled square wave oscillator with parametrizable values of low and high peak output, duty cycle, rise time, and fall time.
It takes an input voltage or current value. This value is used as the independent variable in the piecewise linear curve described by the
coordinate points of the cntl_array and freq_array pairs. From the curve, a frequency value is determined, and the oscillator will output a square
wave at that frequency.
From the above, it is easy to see that array sizes of 2 for both the cntl_array and the freq_array will yield a linear variation of the frequency with
respect to the control input. Any sizes greater than 2 will yield a piecewise linear transfer characteristic. For more detail, refer to the description
of the piecewise linear controlled source, which uses a similar method to derive an output value given a control input.
Example SPICE Usage:
ain 1 2 pulse1
.model pulse1 square(cntl_array = [-1 0 5 6]
+ freq_array=[10 10 1000 1000] out_low = 0.0
+ out_high = 4.5 duty_cycle = 0.2
+ rise_time = 1e-6 fall_time = 2e-6)
Description:
This function is a controlled oneshot with parametrizable values of low and high peak output, input trigger value level, delay, and output rise
and fall times. It takes an input voltage or current value. This value is used as the independent variable in the piecewise linear curve described
by the coordinate points of the cntl_array and pw_array pairs. From the curve, a pulse width value is determined. The one-shot will output a
pulse of that width, triggered by the clock signal (rising or falling edge), delayed by the delay value, and with specified rise and fall times. A
positive slope on the clear input will immediately terminate the pulse, which resets with its fall time.
From the above, it is easy to see that array sizes of 2 for both the cntl_array and the pw_array will yield a linear variation of the pulse width
with respect to the control input. Any sizes greater than 2 will yield a piecewise linear transfer characteristic. For more detail, refer to the
description of the piecewise linear controlled source, which uses a similar method to derive an output value given a control input.
Example SPICE Usage:
ain 1 2 3 4 pulse2
.model pulse2 oneshot(cntl_array = [-1 0 10 11]
+ pw_array=[1e-6 1e-6 1e-4 1e-4]
+ clk_trig = 0.9 pos_edge_trig = FALSE
+ out_low = 0.0 out_high = 4.5
+ rise_delay = 20.0e-9 fall_delay = 35.0e-9)
Description:
The capacitance meter is a sensing device that is attached to a circuit node and produces as an output a scaled value equal to the total
capacitance seen on its input multiplied by the gain parameter. This model is primarily intended as a building block for other models that must
sense a capacitance value and alter their behavior based upon it.
Example SPICE Usage:
atest1 1 2 ctest
.model ctest cmeter(gain=1.0e12)
Description:
The inductance meter is a sensing device that is attached to a circuit node and produces as an output a scaled value equal to the total inductance
seen on its input multiplied by the gain parameter. This model is primarily intended as a building block for other models that must sense an
inductance value and alter their behavior based upon it.
Example SPICE Usage:
atest2 1 2 ltest
.model ltest lmeter(gain=1.0e6)
12.2.29 Memristor
NAME_TABLE:
C_Function_Name: cm_memristor
Spice_Model_Name: memristor
Description: "Memristor Interface"
PORT_TABLE:
Port_Name: memris
Description: "memristor terminals"
Direction: inout
Default_Type: gd
Allowed_Types: [gd]
Vector: no
Vector_Bounds: -
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: rmin rmax
Description: "minimum resistance" "maximum resistance"
Data_Type: real real
Default_Value: 10.0 10000.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: rinit vt
Description: "initial resistance" "threshold"
Data_Type: real real
Default_Value: 7000.0 0.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: alpha beta
Description: "model parameter 1" "model parameter 2"
Data_Type: real real
Default_Value: 0.0 1.0
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
Description:
The memristor is a two-terminal resistor with memory, whose resistance depends on the time integral of the voltage across its terminals. rmin
and rmax provide the lower and upper limits of the resistance, rinit is its starting value (no voltage applied so far). The voltage has to be above a
threshold vt to become effective in changing the resistance. alpha and beta are two model parameters. The memristor code model is derived
from a SPICE subcircuit published in [23].
Example SPICE Usage:
amen 1 2 memr
.model memr memristor (rmin=1k rmax=10k rinit=7k
+ alpha=0 beta=2e13 vt=1.6)
Description:
The 2D table model reads a matrix from file "file name" (default 2D-table-model.txt) which has x columns and y rows. Each x,y pair,
derivatives. Parameters offset (default 0) and gain (default 1) modify the output table values according to 𝑜𝑓𝑓𝑠𝑒𝑡 + 𝑔𝑎𝑖𝑛 𝑜𝑢𝑡. Parameter
addressed by inx and iny, yields an output value out. Linear interpolation is used for out, eno (essentially non oscillating) interpolation for its
order (default 3) influences the calculation of the derivatives. Parameter verbose (default 0) yields test outputs, if set to 1 or 2. The table
format is shown below. Be careful to include the data point inx = 0, iny = 0 into your table, because ngspice uses these during .OP
computations. The x horizontal and y vertical address values have to increase monotonically.
Table Example:
* table source
* number of columns (x)
8
* number of rows (y)
9
* x horizontal (column) address values (real numbers)
-1 0 1 2 3 4 5 6
* y vertical (row) address values (real numbers)
-0.6 0 0.6 1.2 1.8 2.4 3.0 3.6 4.2
* table with output data (horizontally addressed by x, vertically by y)
1 0.9 0.8 0.7 0.6 0.5 0.4 0.3
1 1 1 1 1 1 1 1
1 1.2 1.4 1.6 1.8 2 2.2 2.4
1 1.5 2 2.5 3 3.5 4 4.5
1 2 3 4 5 6 7 8
1 2.5 4 5.5 7 8.5 10 11.5
1 3 5 7 9 11 13 15
1 3.5 6 8.5 11 13.5 16 18.5
1 4 7 10 13 16 19 22
Description:
The usage example consists of two input voltages referenced to ground and a current source output with two floating nodes.
Example SPICE Usage:
atab inx iny %id(out1 out2) tabmod
.model tabmod table2d (offset=0.0 gain=1 order=3 file="table-simple.txt")
Description:
The 3D table model reads a matrix from file "file name" (default 3D-table-model.txt) which has x columns, y rows per table and z tables.
Each x,y,z triple, addressed by inx, iny, and inz, yields an output value out. Linear interpolation is used for out, eno (essentially non oscillating)
𝑜𝑓𝑓𝑠𝑒𝑡 + 𝑔𝑎𝑖𝑛 𝑜𝑢𝑡. Parameter order (default 3) influences the calculation of the derivatives. Parameter verbose (default 0) yields test outputs,
interpolation for its derivatives. Parameters offset (default 0) and gain (default 1) modify the output table values according to
if set to 1 or 2. The table format is shown below. Be careful to include the data point inx = 0, iny = 0, inz = 0 into your table, because ngspice
needs these to for the .OP calculation. The x horizontal, y vertical, and z table address values have to increase monotonically.
Table Example:
* 3D table for nmos bsim 4, W=10um, L=0.13um
*x
39
*y
39
*z
11
*x (drain voltage)
-0.1 -0.05 0 0.05 0.1 0.15 0.2 0.25 ...
*y (gate voltage)
-0.1 -0.05 0 0.05 0.1 0.15 0.2 0.25 ...
*z (substrate voltage)
-1.8 -1.6 -1.4 -1.2 -1 -0.8 -0.6 -0.4 -0.2 0 0.2
*table -1.8
-4.50688E-10 -4.50613E-10 -4.50601E-10 -4.50599E-10 ...
-4.49622E-10 -4.49267E-10 -4.4921E-10 -4.49202E-10 ...
-4.50672E-10 -4.49099E-10 -4.48838E-10 -4.48795E-10 ...
-4.55575E-10 -4.4953E-10 -4.48435E-10 -4.48217E-10 ...
...
*table -1.6
-3.10015E-10 -3.09767E-10 -3.0973E-10 -3.09724E-10 ...
-3.09748E-10 -3.08524E-10 -3.08339E-10 -3.08312E-10 ...
...
*table -1.4
-2.04848E-10 -2.04008E-10 -2.03882E-10 ...
-2.07275E-10 -2.03117E-10 -2.02491E-10 ...
...
Description:
The usage example simulates a NMOS transistor with independent drain, gate and bulk nodes, referenced to source. Parameter gain may be
used to emulate transistor width, with respect to the table transistor.
Example SPICE Usage:
amos1 %vd(d s) %vd(g s) %vd(b s) %id(d s) mostable1
.model mostable1 table3d (offset=0.0 gain=0.5 order=3
+ verbose=1 file="table-3D-bsim4n.txt")
Description:
During a transient simulation the input voltage at node in and its associated time value are stored in a ring buffer. buffer_size allows to set the
size of the buffer, the default is 1024 time steps. There are two modes to read out the buffer contents with a delay and obtain the delayed values
at port out, determined by has_delay_cnt. If has_delay_cnt is TRUE, then you may vary the delay time between delmin and delmax by a
control voltage between 0 and 1 at the input terminal cntrl. Parameter delay is ignored. If has_delay_cnt has been set to FALSE, then the
signal is delayed by the time value given by delay .
Example SPICE Usage:
adelay1 in out cntrl mydel1
.model mydel1 delay(delay=2m buffer_size=2048)
adelay2 in out cntrl mydel2
.model mydel2 delay(has_delay_cnt=TRUE delmin=5u delmax=8u)
Due to the fact that time steps are not constant during a transient simulation, but optimized by the simulator, the delayed values are sometimes slightly
deviating from the original, depending on the number of steps. So in a sinusoidal wave we will see a distortion < 0.3% for 1000 steps per sin cycle.
12.2.34 Potentiometer
NAME_TABLE:
Spice_Model_Name: potentiometer
C_Function_Name: cm_potentiometer
Description: "potentiometer"
PORT_TABLE:
Port_Name: r0 wiper
Description: "pot connection 0" "wiper contact"
Direction: inout inout
Default_Type: g g
Allowed_Types: [g] [g]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PORT_TABLE:
Port_Name: r1
Description: "pot connection 1"
Direction: inout
Default_Type: g
Allowed_Types: [g]
Vector: no
Vector_Bounds: -
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: position
Description: "position of wiper connection (0.0 to 1.0)"
Data_Type: real
Default_Value: 0.5
Limits: [0.0 1.0]
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: log r
Description: "log-linear switch" "total resistance"
Data_Type: boolean real
Default_Value: FALSE 1.0e5
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: log_multiplier
Description: "multiplier constant for log resistance"
Data_Type: real
Default_Value: 1.0
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
resistance. Rlower is located between r0 and wiper, Rupper between wiper and r1. If log is set to FALSE, 𝑅𝑙𝑜𝑤𝑒𝑟 = 𝑝𝑜𝑠𝑖𝑡𝑖𝑜𝑛 * 𝑟. If log is set
A resistance potentiometer with three connections: r0, wiper , and r1. Parameter position determines the lower and upper portions of the
to TRUE, then 𝑅𝑙𝑜𝑤𝑒𝑟 = 𝑟 * 10−𝑝𝑜𝑠𝑖𝑡𝑖𝑜𝑛 * 𝑙𝑜𝑔𝑚𝑢𝑙𝑡𝑖𝑝𝑙𝑖𝑒𝑟 . For Rupper we always have 𝑅𝑢𝑝𝑝𝑒𝑟 = 𝑟 − 𝑅𝑙𝑜𝑤𝑒𝑟. 𝑝𝑜𝑠𝑖𝑡𝑖𝑜𝑛 < = 0 is resolved to
𝑝𝑜𝑠𝑖𝑡𝑖𝑜𝑛 = 1𝑒 − 9, 𝑝𝑜𝑠𝑖𝑡𝑖𝑜𝑛 > = 1 is resolved to 𝑝𝑜𝑠𝑖𝑡𝑖𝑜𝑛 = 0.999999999.
Example SPICE Usage:
Apot r0 w r1 potmod
.model potmod potentiometer(position=0.45 r=1k log=FALSE log_multiplier=1)
A note should be made with respect to the use of hybrid models for other than simple digital-to-analog and analog-to-digital translations. The hybrid
models represented in this section address that specific need, but in the development of user-defined nodes you may find a need to translate not only
between digital and analog nodes, but also between real and digital, real and int, etc. In most cases such translations will not need to be as involved or
as detailed as shown in the following.
Description:
The dac_bridge is the first of three node bridge devices designed to allow for the ready transfer of digital information to analog values and
back again. The second device is the adc_bridge (which takes an analog value and maps it to a digital one).The dac_bridge takes as input a
digital value from a digital node. This value by definition may take on only one of the values `0', `1' or `U'. The dac_bridge then outputs the
value out_low, out_high or out_undef, or ramps linearly toward one of these `final' values from its current analog output level. The speed at
which this ramping occurs depends on the values of t_rise and t_fall. These parameters are interpreted by the model such that the rise or fall
slope generated is always constant. Note that the dac_bridge includes test code in its cfunc.mod file for determining the presence of the
out_undef parameter. If this parameter is not specified by you, and if out_high and out_low values are specified, then out_undef is assigned
the value of the arithmetic mean of out_high and out_low. This simplifies coding of output buffers, where typically a logic family will include
an out_low and out_high voltage, but not an out_undef value. This model also posts an input load value (in farads) based on the parameter
input load.
Example SPICE Usage:
abridge1 [7] [2] dac1
.model dac1 dac_bridge(out_low = 0.7 out_high = 3.5 out_undef = 2.2
+ input_load = 5.0e-12 t_rise = 50e-9
+ t_fall = 20e-9)
Description:
The adc_bridge is one of three node bridge devices designed to allow for the ready transfer of analog information to digital values and back
again. The second device is the dac_bridge (which takes a digital value and maps it to an analog one). The adc_bridge takes as input an
analog value from an analog node. This value by definition may be in the form of a voltage, or a current. If the input value is less than or equal
to in_low, then a digital output value of `0' is generated. If the input is greater than or equal to in_high, a digital output value of `1' is generated.
If neither of these is true, then a digital `UNKNOWN' value is output. Note that unlike the case of the dac_bridge, no ramping time or delay is
associated with the adc_bridge. Rather, the continuous ramping of the input value provides for any associated delays in the digitized signal.
Example SPICE Usage:
abridge2 [1] [8] adc_buff
.model adc_buff adc_bridge(in_low = 0.3 in_high = 3.5)
Description:
The bidi_bridge is the third and most complex of three analog/digital node bridges. It is capable of effectively simultaneous output to both
analog and digital ports, depending on the state of the other side. That requires the use of an analog transconductance port, which may cause
convergence problems when there is high impedance on a connected analog node. Non-zero values for the smooth parameter may be helpful if
such problems occur. For digital nodes that are always strongly driven but also have digital inputs, the simpler dac_bridge may be preferred.
Otherwise, bidi_bridge has some additional features that may make it preferable to the other bridges. The analog output characteristics change
with the digital drive strength, with strong output behaving similarly to a very crude model of a CMOS output driver. The low input threshold
may be higher than the high threshold, producing Schmitt Trigger behavior.
Example SPICE Usage:
abridge2 [1 2 3] [8 9 10] null bidi_buff
.model bidi_buff bidi_bridge(in_low = 2 in_high = 1.5)
Description:
The digital oscillator is a hybrid model that accepts as input a voltage or current. This input is compared to the voltage-to-frequency transfer
characteristic specified by the cntl_array/freq_array coordinate pairs, and a frequency is obtained that represents a linear interpolation or
extrapolation based on those pairs. A digital time-varying signal is then produced with this fundamental frequency.
The output waveform, which is the equivalent of a digital clock signal, has rise and fall delays that can be specified independently. In addition,
the duty cycle and the phase of the waveform are also variable and can be set by you.
Example SPICE Usage:
a5 1 8 var_clock
.model var_clock d_osc(cntl_array = [-2 -1 1 2]
+ freq_array = [1e3 1e3 10e3 10e3]
+ duty_cycle = 0.4 init_phase = 180.0
+ rise_delay = 10e-9 fall_delay=8e-9)
Description:
The digital pulse-width modulated oscillator is a hybrid model that accepts as control input a voltage or current. This input is compared to the
voltage-to-duty cycle transfer characteristic specified by the cntl_array/dc_array coordinate pairs, and a duty cycle is obtained that
represents a linear interpolation or extrapolation based on those pairs. A digital duty cycle-varying signal is then produced. The duty cycle is
limited between 0 and 1 (excluding the limits).
The digital output waveform has rise and fall delays that can be specified independently. In addition, the oscillator frequency and the phase of
the waveform are variable and user selectable.
Example SPICE Usage:
a5 cin dout pwm_osc
.model pwm_osc d_pwm(cntl_array = [-2 -1.99 1.99 2]
+ dc_array = [0.01 0.01 0.99 0.99]
+ frequency = 1.2Meg init_phase = 90.0
+ rise_delay = 10e-9 fall_delay=8e-9)
Currently there are some limits or bugs: a duty cycle < 1% or larger than 99% may generate false output (e.g. a 50% duty cycle signal). Sometimes
spurious missing pulses occur. To obtain false results by extrapolation during evaluation of the cntl_array, it is recommended to force a flat output if
input signals are above or below the outer limits of the cntl_array data (see the example shown above).
Some information common to all digital models and/or digital nodes is included here. The following are general rules that should make working with
digital nodes and models more straightforward:
1. All digital nodes are initialized to ZERO at the start of a simulation (i.e., when INIT=TRUE). This means that a model need not post an
explicit value to an output node upon initialization if its output would normally be a ZERO (although posting such would certainly cause no
harm).
2. Digital nodes may have one out of twelve possible node values. See 12.5.1 for details.
3. Digital models typically have defined their rise and fall delays for their output signals. A capacitive input load value may be defined as well
to determine a load-dependent delay, but is currently not used in any code model (see 28.7.1.5).
4. Several commands are available for outputting data, e.g. eprint, edisplay, and eprvcd. Digital inputs may be read from files. Please see
Chapt. 12.5.4 for more details.
5. Hybrid models (see Chapt. 12.3) provide an interface between the digital event driven world and the analog world of ngspice to enable true
mixed mode simulation.
There are some common parameters that are used by many of the digital models. To avoid repetition they are omitted from the individual Interface
Description Files listed here and their availabilty is noted at the end of the file for each model. The common parameters are:
inertial_delay
When this boolean parameter is set, output pulses that are shorter than the current delay time for the port are suppressed, and the output remains
unchanged until the next state transition that completes its delay period. The default value is "false", giving transport delay behavior: all
changes reach the output. An interpreter variable, digital_delay_type, can be used to override the default. A value of 1 changes the default to
"true"; 2 forces all relevant XSPICE elements to use transport delay; 3 forces inertial delay.
This parameter is used by PSpice-compatible U-devices (14). In ngspice-40 these XSPICE digital devices:
have the inertial_delay parameter. When the circuits in the examples/digital/digital_devices directory are run, subcircuits with PSpice U* device
instances are translated to XSPICE primitives. Also, .model statements are generated containing inertial_delay=true. This causes the circuits to
run with inertial delays (suppress glitches) rather than transport delays (propagate glitches). Most digital simulators model gates using inertial
delays.
If you run the examples in ngspice-39 and ngspice-40 then compare waveforms produced by circuits behav-tristate-pulse.cir and behav-283.cir,
you will see how glitches are suppressed by the inertial delay mechanism. To obtain transport delay behavior with ngspice-40, add the
following line:
set digital_delay_type=2
These common parameters appear in individual Interface Specification Files in these forms:
PARAMETER_TABLE:
Parameter_Name: rise_delay fall_delay
Description: "rise delay" "fall delay"
Data_Type: real real
Default_Value: 1.0e-9 1.0e-9
Limits: [1.0e-12 -] [1.0e-12 -]
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: input_load
Description: "input load value (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: inertial_delay family
Description: "swallow short pulses" "Logic family for bridging"
Data_Type: boolean string
Default_Value: false -
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
12.4.1 Buffer
NAME_TABLE:
C_Function_Name: cm_d_buffer
Spice_Model_Name: d_buffer
Description: "digital one-bit-wide buffer"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The buffer is a single-input, single-output digital buffer that produces as output a time-delayed copy of its input.
Example SPICE Usage:
a6 1 8 buff1
.model buff1 d_buffer(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.2 Inverter
NAME_TABLE:
C_Function_Name: cm_d_inverter
Spice_Model_Name: d_inverter
Description: "digital one-bit-wide inverter"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The inverter is a single-input, single-output digital inverter that produces as output an inverted, time-delayed copy of its input.
Example SPICE Usage:
a6 1 8 inv1
.model inv1 d_inverter(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.3 And
NAME_TABLE:
C_Function_Name: cm_d_and
Spice_Model_Name: d_and
Description: "digital `and' gate"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The digital and gate is an n-input, single-output and gate that produces an active `1' value if, and only if, all of its inputs are also `1' values. If
ANY of the inputs is a `0', the output will also be a `0'; if neither of these conditions holds, the output will be unknown.
Example SPICE Usage:
a6 [1 2] 8 and1
.model and1 d_and(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.4 Nand
NAME_TABLE:
C_Function_Name: cm_d_nand
Spice_Model_Name: d_nand
Description: "digital `nand' gate"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The digital nand gate is an n-input, single-output nand gate that produces an active `0' value if and only if all of its inputs are `1' values. If ANY
of the inputs is a `0', the output will be a `1'; if neither of these conditions holds, the output will be unknown.
Example SPICE Usage:
a6 [1 2 3] 8 nand1
.model nand1 d_nand(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.5 Or
NAME_TABLE:
C_Function_Name: cm_d_or
Spice_Model_Name: d_or
Description: "digital `or' gate"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The digital or gate is an n-input, single-output or gate that produces an active `1' value if at least one of its inputs is a `1' value. The gate
produces a `0' value if all inputs are `0'; if neither of these two conditions holds, the output is unknown.
Example SPICE Usage:
a6 [1 2 3] 8 or1
.model or1 d_or(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.6 Nor
NAME_TABLE:
C_Function_Name: cm_d_nor
Spice_Model_Name: d_nor
Description: "digital `nor' gate"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The digital nor gate is an n-input, single-output nor gate that produces an active `0' value if at least one of its inputs is a `1' value. The gate
produces a `0' value if all inputs are `0'; if neither of these two conditions holds, the output is unknown.
Example SPICE Usage:
anor12 [1 2 3 4] 8 nor12
.model nor12 d_nor(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.7 Xor
NAME_TABLE:
C_Function_Name: cm_d_xor
Spice_Model_Name: d_xor
Description: "digital exclusive-or gate"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The digital xor gate is an n-input, single-output xor gate that produces an active `1' value if an odd number of its inputs are also `1' values. The
delays associated with an output rise and those associated with an output fall may be specified independently. Note also that to maintain the
technology-independence of the model, any UNKNOWN input, or any floating input causes the output to also go UNKNOWN.
Example SPICE Usage:
a9 [1 2] 8 xor3
.model xor3 d_xor(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.8 Xnor
NAME_TABLE:
C_Function_Name: cm_d_xnor
Spice_Model_Name: d_xnor
Description: "digital exclusive-nor gate"
PORT_TABLE:
Port Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [2 -] -
Null_Allowed: no no
Common parameters: inertial_delay, family, rise_delay, fall_delay, input_load.
Description:
The digital xnor gate is an n-input, single-output xnor gate that produces an active `0' value if an odd number of its inputs are also `1' values. It
produces a `1' output when an even number of `1' values occurs on its inputs. Note also that to maintain the technology-independence of the
model, any UNKNOWN input, or any floating input causes the output to also go UNKNOWN.
Example SPICE Usage:
a9 [1 2] 8 xnor3
.model xnor3 d_xnor(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+ input_load = 0.5e-12)
12.4.9 Tristate
NAME_TABLE:
C_Function_Name: cm_d_tristate
Spice_Model_Name: d_tristate
Description: "digital tristate buffer"
PORT_TABLE:
Port Name: in enable out
Description: "input" "enable" "output"
Direction: in in out
Default_Type: d d d
Allowed_Types: [d] [d] [d]
Vector: no no no
Vector_Bounds: - - -
Null_Allowed: no no no
PARAMETER_TABLE:
Parameter_Name: delay
Description: "delay"
Data_Type: real
Default_Value: 1.0e-9
Limits: [1.0e-12 -]
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: enable_load
Description: "enable load value (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Common parameters: inertial_delay, family, input_load.
Description:
The digital tristate is a simple tristate gate that can be configured to allow for open-collector behavior, as well as standard tristate behavior. The
state seen on the input line is reflected in the output. The state seen on the enable line determines the strength of the output. Thus, a ONE forces
the output to its state with a STRONG strength. A ZERO forces the output to go to a HI_IMPEDANCE strength. The delays associated with an
output state or strength change cannot be specified independently, nor may they be specified independently for rise or fall conditions; other gate
models may be used to provide such delays if needed. The model posts input and enable load values (in farads) based on the parameters input
load and enable. Note also that to maintain the technology-independence of the model, any UNKNOWN input, or any floating input causes the
output to also go UNKNOWN. Likewise, any UNKNOWN input on the enable line causes the output to go to an UNDETERMINED strength
value.
Example SPICE Usage:
a9 1 2 8 tri7
.model tri7 d_tristate(delay = 0.5e-9 input_load = 0.5e-12
+ enable_load = 0.5e-12)
12.4.10 Pullup
NAME_TABLE:
C_Function_Name: cm_d_pullup
Spice_Model_Name: d_pullup
Description: "digital pullup resistor"
PORT_TABLE:
Port Name: out
Description: "output"
Direction: out
Default_Type: d
Allowed_Types: [d]
Vector: no
Vector_Bounds: -
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: load
Description: "load value (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
The digital pullup resistor is a device that emulates the behavior of an analog resistance value tied to a high voltage level. The pullup may be
used in conjunction with tristate buffers to provide open-collector wired or constructs, or any other logical constructs that rely on a resistive
pullup common to many tristated output devices. The model posts an input load value (in farads) based on the parameter load.
Example SPICE Usage:
a2 9 pullup1
.model pullup1 d_pullup(load = 20.0e-12)
12.4.11 Pulldown
NAME_TABLE:
C_Function_Name: cm_d_pulldown
Spice_Model_Name: d_pulldown
Description: "digital pulldown resistor"
PORT_TABLE:
Port Name: out
Description: "output"
Direction: out
Default_Type: d
Allowed_Types: [d]
Vector: no
Vector_Bounds: -
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: load
Description: "load value (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
The digital pulldown resistor is a device that emulates the behavior of an analog resistance value tied to a low voltage level. The pulldown may
be used in conjunction with tristate buffers to provide open-collector wired or constructs, or any other logical constructs that rely on a resistive
pulldown common to many tristated output devices. The model posts an input load value (in farads) based on the parameter load.
Example SPICE Usage:
a4 9 pulldown1
.model pulldown1 d_pulldown(load = 20.0e-12)
Description:
The digital d-type flip flop is a one-bit, edge-triggered storage element that will store data whenever the clk input line transitions from low to
high (ZERO to ONE). In addition, asynchronous set and reset signals exist, and each of the three methods of changing the stored output of the
d_dff have separate load values and delays associated with them. Additionally, you may specify separate rise and fall delay values that are
added to those specified for the input lines; these allow for more faithful reproduction of the output characteristics of different IC fabrication
technologies.
Note that any UNKNOWN input on the set or reset lines immediately results in an UNKNOWN output.
Example SPICE Usage:
a7 1 2 3 4 5 6 flop1
.model flop1 d_dff(clk_delay = 13.0e-9 set_delay = 25.0e-9
+ reset_delay = 27.0e-9 ic = 2 rise_delay = 10.0e-9
+ fall_delay = 3e-9)
Description:
The digital jk-type flip flop is a one-bit, edge-triggered storage element that will store data whenever the clk input line transitions from low to
high (ZERO to ONE). In addition, asynchronous set and reset signals exist, and each of the three methods of changing the stored output of the
d_jkff have separate load values and delays associated with them. Additionally, you may specify separate rise and fall delay values that are
added to those specified for the input lines; these allow for more faithful reproduction of the output characteristics of different IC fabrication
technologies.
Note that any UNKNOWN inputs other than j or k cause the output to go UNKNOWN automatically.
Example SPICE Usage:
a8 1 2 3 4 5 6 7 flop2
.model flop2 d_jkff(clk_delay = 13.0e-9 set_delay = 25.0e-9
+ reset_delay = 27.0e-9 ic = 2 rise_delay = 10.0e-9
+ fall_delay = 3e-9)
Description:
The digital toggle-type flip flop is a one-bit, edge-triggered storage element that will toggle its current state whenever the clk input line
transitions from low to high (ZERO to ONE). In addition, asynchronous set and reset signals exist, and each of the three methods of changing
the stored output of the d_tff have separate load values and delays associated with them. Additionally, you may specify separate rise and fall
delay values that are added to those specified for the input lines; these allow for more faithful reproduction of the output characteristics of
different IC fabrication technologies.
Note that any UNKNOWN inputs other than t immediately cause the output to go UNKNOWN.
Example SPICE Usage:
a8 2 12 4 5 6 3 flop3
.model flop3 d_tff(clk_delay = 13.0e-9 set_delay = 25.0e-9
+ reset_delay = 27.0e-9 ic = 2 rise_delay = 10.0e-9
+ fall_delay = 3e-9 t_load = 0.2e-12)
Description:
The digital sr-type flip flop is a one-bit, edge-triggered storage element that will store data whenever the clk input line transitions from low to
high (ZERO to ONE). The value stored (i.e., the out value) will depend on the s and r input pin values, and will be:
out=ONE if s=ONE and r=ZERO;
out=ZERO if s=ZERO and r=ONE;
out=previous value if s=ZERO and r=ZERO;
out=UNKNOWN if s=ONE and r=ONE;
In addition, asynchronous set and reset signals exist, and each of the three methods of changing the stored output of the d_srff have separate load
values and delays associated with them. You may also specify separate rise and fall delay values that are added to those specified for the input lines;
these allow for more faithful reproduction of the output characteristics of different IC fabrication technologies.
Note that any UNKNOWN inputs other than s and r immediately cause the output to go UNKNOWN.
12.4.16 D Latch
NAME_TABLE:
C_Function_Name: cm_d_dlatch
Spice_Model_Name: d_dlatch
Description: "digital d-type latch"
PORT_TABLE:
Port Name: data enable
Description: "input data" "enable input"
Direction: in in
Default_Type: d d
Allowed_Types: [d] [d]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PORT_TABLE:
Port Name: set reset
Description: "set" "reset"
Direction: in in
Default_Type: d d
Allowed_Types: [d] [d]
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PORT_TABLE:
Port Name: out Nout
Description: "data output" "inverter data output"
Direction: out out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: no no
Vector_Bounds: - -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: data_delay
Description: "delay from data"
Data_Type: real
Default_Value: 1.0e-9
Limits: [1.0e-12 -]
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: enable_delay set_delay
Description: "delay from enable" "delay from SET"
Data_Type: real real
Default_Value: 1.0e-9 1.0e-9
Limits: [1.0e-12 -] [1.0e-12 -]
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: reset_delay ic
Description: "delay from RESET" "output initial state"
Data_Type: real boolean
Default_Value: 1.0e-9 0
Limits: [1.0e-12 -] -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: data_load enable_load
Description: "data load (F)" "enable load value (F)"
Data_Type: real real
Default_Value: 1.0e-12 1.0e-12
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: set_load reset_load
Description: "set load value (F)" "reset load (F)"
Data_Type: real real
Default_Value: 1.0e-12 1.0e-12
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
Common parameters: rise_delay, fall_delay.
Description:
The digital d-type latch is a one-bit, level-sensitive storage element that will output the value on the data line whenever the enable input line is
high (ONE). The value on the data line is stored (i.e., held on the out line) whenever the enable line is low (ZERO).
In addition, asynchronous set and reset signals exist, and each of the four methods of changing the stored output of the d_dlatch (i.e., data
changing with enable=ONE, enable changing to ONE from ZERO with a new value on data, raising set and raising reset) have separate delays
associated with them. You may also specify separate rise and fall delay values that are added to those specified for the input lines; these allow
for more faithful reproduction of the output characteristics of different IC fabrication technologies.
Note that any UNKNOWN inputs other than on the data line when enable=ZERO immediately cause the output to go UNKNOWN.
Example SPICE Usage:
a4 12 4 5 6 3 14 latch1
.model latch1 d_dlatch(data_delay = 13.0e-9 enable_delay = 22.0e-9
+ set_delay = 25.0e-9
+ reset_delay = 27.0e-9 ic = 2
+ rise_delay = 10.0e-9 fall_delay = 3e-9)
Description:
The digital sr-type latch is a one-bit, level-sensitive storage element that will output the value dictated by the state of the s and r pins whenever
the enable input line is high (ONE). This value is stored (i.e., held on the out line) whenever the enable line is low (ZERO). The particular value
chosen is as shown below:
s=ZERO, r=ZERO => out=current value (i.e., not change in output)
s=ZERO, r=ONE => out=ZERO
s=ONE, r=ZERO => out=ONE
s=ONE, r=ONE => out=UNKNOWN
Asynchronous set and reset signals exist, and each of the four methods of changing the stored output of the d srlatch (i.e., s/r combination changing
with enable=ONE, enable changing to ONE from ZERO with an output-changing combination of s and r, raising set and raising reset) have separate
delays associated with them. You may also specify separate rise and fall delay values that are added to those specified for the input lines; these allow
for more faithful reproduction of the output characteristics of different IC fabrication technologies.
Note that any UNKNOWN inputs other than on the s and r lines when enable=ZERO immediately cause the output to go UNKNOWN.
Example SPICE Usage:
a4 12 4 5 6 3 14 16 latch2
.model latch2 d_srlatch(sr_delay = 13.0e-9 enable_delay = 22.0e-9
+ set_delay = 25.0e-9
+ reset_delay = 27.0e-9 ic = 2
+ rise_delay = 10.0e-9 fall_delay = 3e-9)
Description:
The digital state machine provides for straightforward descriptions of clocked combinational logic blocks with a variable number of inputs and
outputs and with an unlimited number of possible states. The model can be configured to behave as virtually any type of counter or clocked
combinational logic block and can be used to replace very large digital circuit schematics with an identically functional but faster
representation.
The d state model is configured through the use of a state definition file (state.in) that resides in a directory of your choosing. The file defines
all states to be understood by the model, plus input bit combinations that trigger changes in state. An example state.in file is shown below:
----------- begin file -------------
* This is an example state.in file. This file
* defines a simple 2-bit counter with one input. The
* value of this input determines whether the counter counts
* up (in = 1) or down (in = 0).
0 0s 0s 0 -> 3
1 -> 1
1 0s 1z 0 -> 0
1 -> 2
2 1z 0s 0 -> 1
1 -> 3
3 1z 1z 0 -> 2
3 1z 1z 1 -> 0
------------------ end file ---------------
Several attributes of the above file structure should be noted. First, all lines in the file must be one of four types. These are
The order of the output and input bits in the file is important; the first column is always interpreted to refer to the 'zeroth' bit of input and output. Thus,
in the file above, the output from state 1 sets out[0] to 0s, and out[1] to 1z.
The state numbers need not be in any particular order, but a state definition (which consists of the sum total of all lines that define the state, its
outputs, and all methods by which a state can be exited) must be made on contiguous line numbers; a state definition cannot be broken into sub-blocks
and distributed randomly throughout the file. On the other hand, the state definition can be broken up by as many comment lines as you desire.
Header files may be used throughout the state.in file, and continuation lines can be discarded completely if you so choose: continuation lines are
primarily provided as a convenience.
Example SPICE Usage:
a4 [2 3 4 5] 1 12 [22 23 24 25 26 27 28 29] state1
.model state1 d_state(clk_delay = 13.0e-9 reset_delay = 27.0e-9
+ state_file = "newstate.txt" reset_state = 2)
Note:
The file named by the parameter filename in state_file="filename" is sought after according to a search list described in12.1.3.
Description:
The digital frequency divider is a programmable step-down divider that accepts an arbitrary divisor (div_factor), a duty-cycle term
(high_cycles), and an initial count value (i_count). The generated output is synchronized to the rising edges of the input signal.
Example SPICE Usage:
a4 3 7 divider
.model divider d_fdiv(div_factor = 5 high_cycles = 3
+ i_count = 4 rise_delay = 23e-9
+ fall_delay = 9e-9)
12.4.20 RAM
NAME_TABLE:
C_Function_Name: cm_d_ram
Spice_Model_Name: d_ram
Description: "digital random-access memory"
PORT_TABLE:
Port Name: data_in data_out
Description: "data input line(s)" "data output line(s)"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes yes
Vector_Bounds: [1 -] data_in
Null_Allowed: no no
PORT_TABLE:
Port Name: address write_en
Description: "address input line(s)" "write enable line"
Direction: in in
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [1 -] -
Null_Allowed: no no
PORT_TABLE:
Port Name: select
Description: "chip select line(s)"
Direction: in
Default_Type: d
Allowed_Types: [d]
Vector: yes
Vector_Bounds: [1 16]
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: select_value
Description: "decimal active value for select line comparison"
Data_Type: int
Default_Value: 1
Limits: [0 32767]
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: ic
Description: "initial bit state @ dc"
Data_Type: int
Default_Value: 2
Limits: [0 2]
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: read_delay
Description: "read delay from address/select/write.en active"
Data_Type: real
Default_Value: 100.0e-9
Limits: [1.0e-12 -]
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: data_load address_load
Description: "data_in load value (F)" "addr. load value (F)"
Data_Type: real real
Default_Value: 1.0e-12 1.0e-12
Limits: - -
Vector: no no
Vector_Bounds: - -
Null_Allowed: yes yes
PARAMETER_TABLE:
Parameter_Name: select_load
Description: "select load value (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: enable_load
Description: "enable line load value (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
Description:
The digital RAM is an M-wide, N-deep random access memory element with programmable select lines, tristated data out lines, and a single
write/~read line. The width of the RAM words (M) is set through the use of the word width parameter. The depth of the RAM (N) is set by the
2𝑃 = 𝑁
number of address lines input to the device. The value of N is related to the number of address input lines (P) by the following equation:
There is no reset line into the device. However, an initial value for all bits may be specified by setting the ic parameter to either 0 or 1. In
reading a word from the ram, the read delay value is invoked, and output will not appear until that delay has been satisfied. Separate rise and
fall delays are not supported for this device.
Note that UNKNOWN inputs on the address lines are not allowed during a write. In the event that an address line does indeed go unknown
during a write, the entire contents of the ram will be set to unknown. This is in contrast to the data in lines being set to unknown during a write;
in that case, only the selected word will be corrupted, and this is corrected once the data lines settle back to a known value. Note that protection
is added to the write en line such that extended UNKNOWN values on that line are interpreted as ZERO values. This is the equivalent of a read
operation and will not corrupt the contents of the RAM. A similar mechanism exists for the select lines. If they are unknown, then it is assumed
that the chip is not selected.
Detailed timing-checking routines are not provided in this model, other than for the enable delay and select delay restrictions on read
operations. You are advised, therefore, to carefully check the timing into and out of the RAM for correct read and write cycle times, setup and
hold times, etc. for the particular device they are attempting to model.
Example SPICE Usage:
a4 [3 4 5 6] [3 4 5 6] [12 13 14 15 16 17 18 19] 30 [22 23 24] ram2
.model ram2 d_ram(select_value = 2 ic = 2 read_delay = 80e-9)
Description:
The digital source provides for straightforward descriptions of digital signal vectors in a tabular format. The model reads input from the input
file and, at the times specified in the file, generates the inputs along with the strengths listed. The format of the input file is as shown below.
Note that comment lines are delineated through the use of a single `*' character in the first column of a line. This is similar to the way the
SPICE program handles comments.
* T c n n n . . .
* i l o o o . . .
* m o d d d . . .
* e c e e e . . .
* k a b c . . .
0.0000 Uu Uu Us Uu . . .
1.234e-9 0s 1s 1s 0z . . .
1.376e-9 0s 0s 1s 0z . . .
2.5e-7 1s 0s 1s 0z . . .
2.5006e-7 1s 1s 1s 0z . . .
5.0e-7 0s 1s 1s 0z . . .
Note that in the example shown, whitespace (any combination of blanks, tabs, commas) is used to separate the time and state/strength tokens. The
order of the input columns is important; the first column is always interpreted to mean `time'. The second through the N'th columns map to the out[0]
through out[N-2] output nodes. A non-commented line that does not contain enough tokens to completely define all outputs for the digital source will
cause an error. Also, time values must increase monotonically or an error will result in reading the source file.
Errors will also occur if a line exists in source.txt that is neither a comment nor vector line. The only exception to this is in the case of a line that is
completely blank; this is treated as a comment (note that such lines often occur at the end of text within a file; ignoring these in particular prevents
nuisance errors on the part of the simulator).
Example SPICE Usage:
a3 [2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17] input_vector
.model input_vector d_source(input_file = "source_simple.text")
Note:
The file named by the parameter filename in input_file="filename" is sought after according to a search list described in12.1.3.
12.4.22 LUT
NAME_TABLE:
C_Function_Name: cm_d_lut
Spice_Model_Name: d_lut
Description: "digital n-input look-up table gate"
PORT_TABLE:
Port_Name: in out
Description: "input" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: [1 -] -
Null_Allowed: no no
PARAMETER_TABLE:
Parameter_Name: table_values
Description: "lookup table values"
Data_Type: string
Default_Value: "0"
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: no
Common parameters: rise_delay, fall_delay, input_load.
Description:
The lookup table provides a way to map any arbitrary n-input, 1-output combinational logic block to XSPICE. The inputs are mapped to the
output using a string of length 2^n. The string may contain values "0", "1" or "X", corresponding to an output of low, high, or unknown,
respectively. The outputs are only mapped for inputs which are valid logic levels. Any unknown bit in the input vector will always produce an
unknown output. The first character of the string table_values corresponds to all inputs value zero, and the last (2^n) character corresponds to
all inputs value one, with the first signal in the input vector being the least significant bit. For example, a 2-input lookup table representing the
function (A * B) (that is, A AND B), with input vector [A B] can be constructed with a table_values string of "0001"; function (~A * B) with
input vector [A B] can be constructed with a table_values string of "0010".
Example SPICE Usage:
* LUT encoding 3-bit parity function
a4 [1 2 3] 5 lut_pty3_1
.model lut_pty3_1 d_lut(table_values = "01101001"
+ input_load 2.0e-12)
Description:
The lookup table provides a way to map any arbitrary n-input, m-output combinational logic block to XSPICE. The inputs are mapped to the
output using a string of length m * (2^n). The string may contain values "0", "1", "X", or "Z", corresponding to an output of low, high,
unknown, or high-impedance, respectively. The outputs are only mapped for inputs which are valid logic levels. Any unknown bit in the input
vector will always produce an unknown output. The character string is in groups of (2^n) characters, one group corresponding to each output
pin, in order. The first character of a group in the string table_values corresponds to all inputs value zero, and the last (2^n) character in the
group corresponds to all inputs value one, with the first signal in the input vector being the least significant bit. For example, a 2-input lookup
table representing the function (A * B) (that is, A AND B), with input vector [A B] can be constructed with a table_values string of "0001";
function (~A * B) with input vector [A B] can be constructed with a "table_values" string of "0010". The delays associated with each output
pin's rise and those associated with each output pin's fall may be specified independently. The model also posts independent input load values
per input pin (in farads) based on the parameter input_load. The parameter input_delay provides a way to specify additional delay between
each input pin and the output. This delay is added to the rise- or fall-time of the output. The output of this model does not respond to the total
loading it sees on the output; it will always drive the output strongly with the specified delays.
Example SPICE Usage:
* LUT encoding 3-bit parity function
a4 [1 2 3] [5] lut_pty3_1
.model lut_pty3_1 d_genlut(table_values = "01101001"
+ input_load [2.0e-12])
* LUT encoding a tristate inverter function (en in out)
a2 [1 2] [3] lut_triinv_1
.model lut_triinv_1 d_genlut(table_values = "Z1Z0")
* LUT encoding a half-adder function (A B Carry Sum)
a8 [1 2] [3 4] lut_halfadd_1
.model lut_halfadd_1 d_genlut(table_values = "00010110"
+ rise_delay [ 1.5e-9 1.0e-9 ] fall_delay [ 1.5e-9 1.0e-9 ])
12.4.24 D_process
NAME_TABLE:
C_Function_Name: cm_d_process
Spice_Model_Name: d_process
Description: "digital process"
PORT_TABLE:
Port_Name: in clk
Description: "input" "clock"
Direction: in in
Default_Type: d d
Allowed_Types: [d] [d]
Vector: yes no
Vector_Bounds: - -
Null_Allowed: yes no
PORT_TABLE:
Port_Name: reset out
Description: "reset" "output"
Direction: in out
Default_Type: d d
Allowed_Types: [d] [d]
Vector: no yes
Vector_Bounds: - [1 -]
Null_Allowed: yes no
PARAMETER_TABLE:
Parameter_Name: clk_delay
Description: "delay from CLK"
Data_Type: real
Default_Value: 1.0e-9
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: process_file
Description: "file name of the executable process"
Data_Type: string
Default_Value: "process"
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: process_params
Description: "parameters to be passed to an executable process"
Data_Type: string
Default_Value: -
Limits: -
Vector: yes
Vector_Bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: input_load
Description: "input loading capacitance (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: clk_load
Description: "clock loading capacitance (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: no
PARAMETER_TABLE:
Parameter_Name: reset_load
Description: "reset loading capacitance (F)"
Data_Type: real
Default_Value: 1.0e-12
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: no
Description:
The digital d_process model runs an external program, specified by the process_file parameter, to read the input signals when the clock changes
to ONE and then produces the output signals after the clk_delay. There can be zero (null) or more inputs, and one or more outputs. The
maximum number of inputs or outputs is 255 bits wide. If a reset signal is specified and has the value ONE when the clock changes to ONE, the
external program is notified of the reset by sending it a negative time value. The output signals are initialized to Uz. The strength (s, r, z, u) of
an input signal is ignored. After time 0.0 initialization, outputs are driven with STRONG (s) strength. The input and output states are binary
ONE or ZERO. If an input value is UNKNOWN (U) then a ONE or ZERO is chosen at random.
The external program is started by fork/exec or spawn, and connections are established using pipes. The external program is written in C, and
first of all, in main() the argc, argv parameters can be read. These command line parameters are those specified in the process_params field of
the d_process .model statement. A header is sent from ngspice to the external program which acknowledges that the number of inputs and
outputs match. Thereafter, the external program executes a loop: while (read data from the input pipe and if it is OK) { compute output data for
that input write the output data to the output pipe } In the meantime the cm_d_process code in ngspice is writing data to its output pipe at each
clock change to ONE, then reading on its input pipe the response from the external program.
Please see examples/xspice/d_process for a simple example and study the source code in the .c files. The d_process model was developed by
Uros Platise and he has provided a non-trivial example and detailed descriptions at:
https://www.isotel.eu/mixedsim/embedded/motorforce/index.html.
Example SPICE Usage:
a1 [d1] clk1 reset1 [o1 o2 o3 o4] proc1
.model proc1 d_process (process_file="prog1in4out"
+ clk_delay = 2.5e-9)
12.4.25 d_cosim
NAME_TABLE:
Spice_Model_Name: d_cosim
C_Function_Name: ucm_d_cosim
Description: "Bridge to an irreversible digital model"
PORT_TABLE:
Port_Name: d_in
Description: "digital input"
Direction: in
Default_Type: d
Allowed_Types: [d]
Vector: yes
Vector_Bounds: [0 -]
Null_Allowed: yes
PORT_TABLE:
Port_Name: d_out
Description: "digital output"
Direction: out
Default_Type: d
Allowed_Types: [d]
Vector: yes
Vector_Bounds: [0 -]
Null_Allowed: yes
PORT_TABLE:
Port_Name: d_inout
Description: "digital bidirectional port"
Direction: inout
Default_Type: d
Allowed_Types: [d]
Vector: yes
Vector_Bounds: [0 -]
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: delay
Description: "output delay time"
Data_Type: real
Default_Value: 1.0e-9
Limits: [1e-12 -]
Vector: no
Vector_bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: simulation
Description: "A shared library containing a digital model"
Data_Type: string
Default_Value: -
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: no
/* Instances maintain an internal input event queue that should be at least
* as large as the number of inputs. Performance with clocked logic may
* be improved by making it larger than (2 * F) / MTS, where F is
* the clock frequency and MTS is the maximum timestep for .tran.
*/
PARAMETER_TABLE:
Parameter_Name: queue_size
Description: "input queue size"
Data_Type: int
Default_Value: 128
Limits: [1 -]
Vector: no
Vector_bounds: -
Null_Allowed: yes
PARAMETER_TABLE:
Parameter_Name: irreversible
Description: "Parameter passed to library function cm_irreversible()"
Data_Type: int
Default_Value: 1
Limits: -
Vector: no
Vector_Bounds: -
Null_Allowed: yes
STATIC_VAR_TABLE:
Static_Var_Name: cosim_instance
Data_Type: pointer
Description: "Per-instance structure"
The d_cosim code model is similar to d_process, as it also requires external software to define the behaviour of a code model instance. An important
difference is that with d_cosim such software runs inside the ngspice process. This code model is intended as a container for other types of digital
simulation and to provide a simplified programming interface for devices whose behaviour is defined purely by conventional software. In particular, it
is intended to act as a container for sub-simulations that can not discard any time steps that fail in the main simulator; that is, they are irreversible.
The actual behaviour of any d_cosim instance is defined by a shared library or Windows DLL that is set by the 'simulation' parameter and
dynamically loaded. Input changes are relayed to a function in this library and any outputs reported by the library are relayed to the simulated circuit.
The interface between this code model and the library that it hosts is defined in C-language header file cosim.h, included in the Ngspice source code
and in directory share/ngspice/scripts/src/ngspice in a binary package. This interface is simpler than the XSPICE programming interface, but that has
a cost: without special care only one d_cosim instance should exist in a circuit. For more information, see the description of cm_irreversible() in
section 28.7.2.7.
I/O for event nodes (digital, real, int, and UDNs) is offered by the following tools: For output you may use the plot (17.5.53) or eprint (17.5.26)
commands, as well as edisplay (17.5.25) and eprvcd (17.5.27). The latter writes all node data to a VCD file (a digital standard interface) that may be
analyzed by viewers like gtkwave. For input, you may create a test bench with existing code models (oscillator (12.3.4), frequency divider (12.4.19),
state machine (12.4.18) etc.). Reading data from a file is offered by d_source (12.4.21). Some comments and hints have been provided by Sdaau. You
may also use the analog input from file, (filesource 12.2.9) and convert its analog input to the digital type by the adc_bridge (12.3.2). If you want
reading data from a VCD file, please have a look at ngspice tips and examples forum and apply a python script provided by Sdaau to translate the
VCD data to d_source or filesource input.
Bridges are inserted automatically whenever an analog and a digital node have the same name, so they are not required to be included in the netlist. To
examine the inserted bridging devices, use the command “listing e”. The extra devices appear at the end of the netlist. Automatic bridging may be
disabled by setting the interpreter variable auto_bridge to zero.
The code models used for analog/digital bridges are described in section 12.3. The default models are:
* Model for bridging digital node with inputs only.
.model auto_adc adc_bridge(in_low = 1.65 in_high = 1.65)
* Model for bridging digital node with outputs only.
.model auto_dac dac_bridge(out_low = 0 out_high = 3.3)
* Model for bridging digital node with either an inout connection or
* both inputs and outputs.
.model auto_bidi bidi_bridge(out_high=3.3 in_low=1.65 in_high=1.65)
A 3.3 volt supply has been assumed. That may be overriden by setting a parameter, vcc, to the supply voltage. When bridges are inserted in a
subcircuit the local value of the parameter is used, so subcircuits may have differing supply voltages. An alternative name for the parameter may be
set as the value of the interpreter variable auto_bridge_parm_d.
If the defaults are unsatisfactory, they may be overridden by setting interpreter variables:
* Override the default DAC bridge for TTL levels
.control
pre_set auto_bridge_d_out =
+ ( ".model auto_dac dac_bridge(out_low = 0.4 out_high = 3.6)"
+ "auto_bridge%d [ %s ] [ %s ] auto_dac" )
.endc
The variable name is formed from a fixed part (auto_bridge_), the type of the event node (d is the internal name for "digital") and the bridging
direction (in, out or inout). The first string is the model definition and the second is expanded into an instance of the bridging device. Note that the
pre_set command is used so that the variable is set before the circuit is parsed.
13.2 OSDI/OpenVAF
OSDI is a simulator independent interface for device models. Since release 39 ngspice contains an integrated adapter to serve this interface and
communicate with the compiled shared library device models. The shared library models are linked into ngspice dynamically at runtime with the osdi
or pre_osdi (see 17.5.55) .control language commands.
OpenVAF compiles Verilog-A compact device model files into shared libraries that conform to the OSDI interface. The model descriptions have to
comply with the standard Verilog-AMS LRM 2.x. Since ngspice-42, the small signal noise simulation (15.3.4) is implemented. Noise simulation ,
however, is only available with the Sparse 1.3 matrix solver, not with KLU (see 15.1.1). Other restrictions may apply. Please consult the OpenVAF
web pages for further information. QA actions are not possible due to CMC refusing to provide data.
There is a github repository VA-Models with most of the public available Verilog-A compact models. The models are checked against the LRM 2.4.0
and prepared for ngspice simulation. A script for generation of the osdi files is provided and each model has more or less simple ngspice netlist files to
show main capabilities. So this web site should be a good starting point for beginners.
Where to place *.osdi? Basically in any directory of your choice, the osdi or pre-osdi commands (13.3.1.6) may be prepended by an absolute or
relative path to that directory. For a permanent location a bulk model install to libs/ngspice is recommended (to the folder where you also find the
XSPICE code model libs *.cm).
To simplify making suitable *.osdi models for the example netlists provided in ngspice/examples/osdi, the appropriate Verilog-A models and short
scripts (for Linux and Windows) are available for download as VAforOSDI.7z from our release directory. The following steps are required to compile
the shared library models:
General form:
Examples:
So to prepare the .model line, select an appropriate model parameter set, comment out the version and level parameters, add the type parameter,
and change the modeltype to the Verilog-A module name.
Local usage of a *.osdi which are residing in an arbitrary directory is possible from within a .control section (16.4.3) by the pre_osdi command. A
relative path (as in the example below) or an absolute path to that directory may be chosen.
pre_osdi ../osdi_libs/bsimbulk107.osdi
The reference designator for the OSDI devices is the letter N. Instance lines starting with N are recognized as OSDI devices. The model name mname
has to point to the .model line which contains the parameter set to be selected.
Examples:
NMOS and PMOS devices are selected by their respective model names BSIMBULK_osdi_N and BSIMBULK_osdi_P. The number and role of the nodes
has been defined in the VA code in its module statement (module bsimbulk(d, g, s, b, t); in the BSIMBULK example). Instance parameters
(like l, w, as etc.) are allowed, as defined by the VA code.
Example folders bsimbulk, bsimbulk-local, bsimcmg, mixed-models, and psp103 contain MOS devices with their dc characteristics, CMOS
inverters, CMOS ring oscillators, or even the 7552_ann benchmark CMOS circuit with 15.000 transistors and may more passives. Hicuml0, or
mextram contain bipolar devices with output characteristics, Gummel-plot and some circuits. r2_cmc is a special resistor model.
These U devices are not meant to immediately describe digital circuits like the 74xx or 40xx series. However they are used in subcircuits to generate
models for such circuits (see chapter 14.2). Their syntax is mostly compatible to the Micro-Cap and PSPICE simulators.
General form:
Example:
.MODEL M2 UGATE ()
.MODEL IOM2 UIO (INLD=0 OUTLD=0 DRVH=50 DRVL=50
+ ATOD1="ATOD1" DTOA1="DTOD1" ATOD2="ATOD2" DTOA2="DTOD2"
+ ATOD3="ATOD3" DTOA3="DTOD3" ATOD4="ATOD4" DTOA4="DTOD4"
+ TSWLH1=0 TSWLH2=0 TSWLH3=0 TSWLH4=0
+ TSWHL1=0 TSWHL2=0 TSWHL3=0 TSWHL4=0 DIGPOWER="DIGPOWER")
U-devices require the compatibility mode flag (16.14.1) set to PS. In addition U devices are recognized only when they occur inside of a
subcircuit. Finally the basic type (second token in the U instance line) has to fit to the list of basic types given in the table above.
URC in any other case ngspice will assume an URC (uniformly distributed) transmission line.
.ENDS 74LV08A
The circuit example ex4.cir in ngspice/examples/digital/digital_devices, together with the stimulus file ex4.stim presents a fully digital, event
based full-adder simulation with 74xx series ICs. The internal plotting capability of ngspice is used. ex5.cir with the stimulus file ex5.stim
demonstrates the conversion of a D-Type Flip-Flop. ex283.cir is a 74283 4-bit full adder, with stimulus and involving GTKWave for plotting. Also,
there are several new examples illustrating LOGICEXP and PINDLY.
A set of such models for the 74xx devices currently supported by ngspice is available from the ngspice models as 74xx-models.7z, derived from the
Micro-Cap library.
The steps for using such a digital device are these: write HDL code whose top-level module defines the device behaviour; the HDL file is compiled
into a shared library/DLL acceptable by d_cosim; and the netlist contains device and model lines to include the new device in a circuit. Example
netlist and Verilog code can be found at examples/xspice/verilator.
The compilation step is not straightforward, as “glue code” must be added to the C++ software created by Verilator so that it can be attached to a
d_cosim instance. A script is provided to make this step easier:
Ngspice is used to run the script, vlnggen, passing the Verilog source file, source.v, as input. The output will be a shared library/DLL called
source.so/source.DLL that may be used in the netlist as:
(Here “null” represents possible “inout” ports that Verilator does not fully support.)
Additional arguments to vlnggen may be other HDL source files or any Verilator options: everything is passed to Verilator. The output file is named
from the first Verilog source file (*.v) that is listed, or is “verilated.so”/”verilated.DLL”.
or when the default input source is redirected from a file (see also Chapt. 16.4.1).
In batch mode, the analyses specified by the control lines in the input file (e.g. .ac, .tran, etc.) are immediately executed. If the -r rawfile option is
given then all data generated is written to a ngspice rawfile. The rawfile may later be read by the interactive mode of ngspice using the load command
(see 17.5.45). In this case, the .save line (see 15.6) may be used to record the value of internal device variables (see Appendix, Chapt. 31).
If a rawfile is not specified, then output plots (in `line-printer' form) and tables can be printed according to the .print, .plot, and .four control lines,
described in Chapt. 15.6.
ngspice circuitfile.cir
and no control section (.control ... .endc, see 16.4.3) is provided in the circuit file, the dot commands are not executed immediately, but are waiting
for manually receiving the command run.
General form:
Examples:
The options line allows the user to reset program control and user options for specific simulation purposes. Options specified to ngspice via the
option command (see17.5.52) are also passed on as if specified on a .options line. Any combination of the following options may be included, in
any order. `x' (below) represents some positive number.
SPARSE
selects the Sparse 1.3 matrix solver, which is also the standard when no option is given. It is prefgerable for simulating behavioural device
models. This option is required with noise (15.3.4) or CIDER (30) simulation.
KLU
selects the KLU matrix solver, which is preferable (yielding faster simulation) when (large) circuits containing MOS devices are to be
simulated. Small signal noise (15.3.4) or CIDER (30) simulations are not (yet) supported.
ACCT
causes accounting and run time statistics to be printed.
NOACCT
no printing of statistics, no printing of the Initial Transient Solution.
NOINIT
suppresses only printing of the Initial Transient Solution, maybe combined with ACCT.
LIST
causes the summary listing of the input data to be printed.
NOMOD
suppresses the printout of the model parameters.
NOPAGE
suppresses page ejects.
NODE
causes the printing of the node table.
NOREFVALUE
suppresses printing of reference values, when ngspice has been compiled with configure option --enable-ndev.
OPTS
causes the option values to be printed.
SEED=val|random
Sets the seed value of the random number generator. val may be any integer number greater than 0. As an alternative, random will set the seed
value to the current Unix epoch time, which is the time in seconds since 1.1.1970 excluding leap seconds.
SEEDINFO
will print the seed value when it has been set to a new integer number.
Resets the operating temperature of the circuit. The default value is 27 °𝐶 (300K). TEMP can be overridden per device by a temperature
TEMP=x
specification on any temperature dependent instance. May also be generally overridden by a .TEMP card (2.12).
resets the nominal temperature at which device parameters are measured. The default value is 27 °𝐶 (300 deg K). TNOM can be overridden by
TNOM=x
ABSTOL=x
resets the absolute current error tolerance of the program. The default value is 1 pA.
GMIN=x
resets the value of GMIN, the minimum conductance allowed by the program. The default value is 1.0e-12.
GMINSTEPS=x
[*] sets the number of Gmin steps to be attempted. If the value is set to zero, the standard gmin stepping algorithm is skipped. The standard
behavior is that gmin stepping is tried before going to the source stepping algorithm.
ITL1=x
resets the dc iteration limit. The default is 100.
ITL2=x
resets the dc transfer curve iteration limit. The default is 50.
KEEPOPINFO
Retain the operating point information when either an AC, Distortion, or Pole-Zero analysis is run. This is particularly useful if the circuit is
large and you do not want to run a (redundant) .OP analysis.
NOOPITER
Go directly to gmin stepping, skipping the first iteration.
PIVREL=x
algorithm the allowed minimum pivot value is determined by 𝙴𝙿𝚂𝚁𝙴𝙻 = 𝙰𝙼𝙰𝚇𝟷(𝙿𝙸𝚅𝚁𝙴𝙻 ⋅ 𝙼𝙰𝚇𝚅𝙰𝙻, 𝙿𝙸𝚅𝚃𝙾𝙻) where MAXVAL is the
resets the relative ratio between the largest column entry and an acceptable pivot value. The default value is 1.0e-3. In the numerical pivoting
resets the absolute voltage error tolerance of the program. The default value is 1 𝜇𝑉.
VNTOL=x
to some high resistance (e.g. 1000𝖬 Ω or greater) so that the operation of the circuit is essentially unaffected but the matrix problems are corrected. If
option to help eliminate this problem. The option inserts resistors to ground at all the analog nodes in the circuit. In general, the value of rshunt is set
a `no DC path to ground' or a `matrix is nearly singular' error message is encountered, add the following .option card to the circuit deck:
Usually a value of 1𝖳 Ω is sufficient to correct the problem. In bad cases one can try lowering the value to 10𝖦 Ω or even 1𝖦 Ω .
.option rshunt = 1.0e12
A different matrix conditioning problem occurs if an inductor is placed in parallel to a voltage source. The AC simulation will fail, because it is
In such a case, adding a small resistor (e.g. 0.1𝗆 Ω ) in series to the inductor will help to obtain convergence.
preceded by an OP analysis. Option NOOPAC (15.1.3) will help if the circuit is linear. However, if the circuit is non-linear the OP analysis is essential.
NOOPAC
Do not run an operating point (OP) analysis prior to an AC analysis. This option requires that the circuit is linear, i.e. consists only of R, L, and
C devices, independent V, I sources and linear dependent E, G, H, and F sources (without poly statement, non-behavioral). If a non-linear
device is detected, the OP analysis is executed automatically. This option is of interest e.g. in nested LC circuits where no series resistance for L
devices is present. During the OP analysis an ill-formed matrix may be encountered, causing the simulator to abort with an error message. It is
also useful if you have very large linear arrays (10000 nodes and more), where simulation speedup by a factor of 10 may be achieved.
AUTOSTOP
stops a transient analysis after successfully calculating all functions (15.4) specified with the dot command .meas. Autostop is not available
with the meas (17.5.47) command used in control mode.
CHGTOL=x
resets the charge tolerance of the program. The default value is 1.0e-14.
CONVSTEP=x
relative step limit applied to code models.
CONVABSSTEP=x
absolute step limit applied to code models.
INTERP
interpolates output data onto fixed time steps on a TSTEP grid (15.3.10). Uses linear interpolation between previous and next time values.
Simulation itself is not influenced by this option. This option can be used in all simulation modes (batch, control or interactive, 16.4). It may
drastically reduce memory requirements in control mode, and file size in batch mode, but care is needed not to undersample the output data. See
also the command linearize (17.5.43) that achieves a similar result by post-processing the data in control mode. The
Ngspice/examples/xspice/delta-sigma/delta-sigma-1.cir example demonstrates how INTERP reduces memory requirements and speeds up
plotting.
ITL3=x
resets the lower transient analysis iteration limit. The default value is 4. (Note: not implemented in Spice3).
ITL4=x
resets the transient analysis time-point iteration limit. The default is 10.
ITL5=x
resets the transient analysis total iteration limit. The default is 5000. Set ITL5=0 to omit this test. (Note: not implemented in Spice3).
ITL6=x
[*] synonym for SRCSTEPS.
MAXEVTITER=x
sets the maximum number of event iterations per analysis point.
MAXOPALTER=x
specifies the maximum number of analog/event alternations that the simulator will use to solve a hybrid circuit.
MAXORD=x
[*] specifies the maximum order for the numerical integration method used by SPICE. Possible values for the Gear method are from 2 (the
default) to 6. Using the value 1 with the trapezoidal method specifies backward Euler integration.
METHOD=name
sets the numerical integration method used by SPICE. Possible names are `Gear' or `trapezoidal' (or just `trap'). The default is trapezoidal.
NOOPALTER=TRUE|FALSE
if set to false, alternations between analog and event calls to XSPICE models are enabled during initial DC operating analysis.
RAMPTIME=x
During source stepping, this option sets the rate of change of independent supplies. It also affects code model inductors and capacitors that have
initial conditions specified.
SRCSTEPS=x
[*] a non-zero value causes SPICE to use a source-stepping method to find the DC operating point. The value specifies the number of steps.
TRTOL=x
resets the transient error tolerance. The default value is 7. This parameter is an estimate of the factor by which SPICE overestimates the actual
truncation error. If XSPICE is configured and 'A' devices are included, the value is internally set to 1 for higher precision. This slows down
transient analysis by a factor of two.
XMU=x
sets the damping factor for trapezoidal integration. The default value is XMU=0.5. A value < 0.5 may be chosen. Even a small reduction, e.g. to
0.495, may already suppress trap ringing. The reduction has to be set carefully in order not to excessively damp circuits that are prone to ringing
or oscillation, which might lead the user to believe that the circuit is stable.
BADMOS3
Use the older version of the MOS3 model with the `kappa' discontinuity.
DEFAD=x
resets the value for MOS drain diffusion area; the default is 0.
DEFAS=x
resets the value for MOS source diffusion area; the default is 0.
resets the value for MOS channel length; the default is 100 𝜇𝑚.
DEFL=x
resets the value for MOS channel width; the default is 100 𝜇𝑚.
DEFW=x
SCALE=x
instance parameter W=10 will result in a width of 10𝜇𝑚 for this device. An area parameter AD=20 will result in 20𝖾 − 12𝗆𝟤 . Following instance
set the element scaling factor for geometric element parameters whose default unit is meters. As an example: scale=1u and a MOSFET
TRYTOCOMPACT
Applicable only to the LTRA model (see 6.2.1). When specified, the simulator tries to condense an LTRA transmission line's past history of
input voltages and currents.
You may set options in the init files spinit or .spiceinit via the option command (see 17.5.52). The values given there will supersede the default
values. If you set options via the .options line in your input file, their values will supersede the default and init file data. Finally, if you set options
inside a .control ... .endc section, these values will again supersede any simulator variables given so far.
General form:
Examples:
The .nodeset line helps the program find the DC or initial transient solution by making a preliminary pass with the specified nodes held to the given
voltages. The restrictions are then released and the iteration continues to the true solution. The .nodeset line may be necessary for convergence on
bistable or astable circuits. .nodeset all=val sets all starting node voltages (except for the ground node) to the same value. In general, the .nodeset
line should not be necessary.
General form:
Examples:
The .ic line is for setting transient initial conditions. It has two different interpretations, depending on whether the uic parameter is specified on the
.tran control line, or not. One should not confuse this line with the .nodeset line. The .nodeset line is only to help DC convergence, and does not
affect the final bias solution (except for multi-stable circuits). The two indicated interpretations of this line are as follows:
1. When the uic parameter is specified on the .tran line, the node voltages specified on the .ic control line are used to compute the capacitor,
diode, BJT, JFET, and MOSFET initial conditions. This is equivalent to specifying the ic=... parameter on each device line, but is much
more convenient. The ic=... parameter can still be specified and takes precedence over the .ic values. Since no dc bias (initial transient)
solution is computed before the transient analysis, one should take care to specify all dc source voltages on the .ic control line if they are to
be used to compute device initial conditions.
2. When the uic parameter is not specified on the .tran control line, the DC bias (initial transient) solution is computed before the transient
analysis. In this case, the node voltages specified on the .ic control lines are forced to the desired initial values during the bias solution.
During transient analysis, the constraint on these node voltages is removed. This is the preferred method since it allows Ngspice to compute
a consistent dc solution.
15.3 Analyses
15.3.1 .AC: Small-Signal AC Analysis
General form:
Examples:
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.
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
.ac dec 10 .01 10
.plot ac vdb(2) xlog
.end
In this AC (or 'small signal') analysis, all non-linear devices are linearized around their actual DC operating point. All L and C devices get their
imaginary value that depends on the actual frequency step. Each output vector will be calculated relative to the input voltage (current) given by the
AC value (𝑉𝑖𝑛 equals 1 in the example above). The resulting node voltages (and branch currents) are complex vectors. Therefore one has to be careful
using the plot command, specifically, one may use the variants of vxx(node) described in Chapt. 15.6.2 like vdb(2) (see also the above example).
If one wants to simulate ac on a large linear array, the option noopac (15.1.3) may be useful. Linear circuits are containing only linear device
instances starting with letters r, l, c, i, v, e, g, f, h, k. The instances e, g, f, h have to be the simple ones, as of chapt. 4.2, not the polynomial nor the
behavioral variants. If the option noopac is set, ngspice tests for the absence of any other devices. If successful, the often lengthy op calculation is
skipped, ac is started immediately. Considerable simulation time savings may result.
General form:
Examples:
The .dc line defines the dc transfer curve source and sweep limits (with capacitors open and inductors shorted). srcnam is the name of an independent
The first example causes the value of the voltage source 𝑉𝐼𝑁 to be swept from 0.25 Volts to 5.0 Volts with steps of 0.25 Volt. A second source (src2)
voltage or current source, a resistor, or the circuit temperature. vstart, vstop, and vincr are the starting, final, and incrementing values, respectively.
may optionally be specified with its own associated sweep parameters. In such a case the first source is swept over its own range for each value of the
second source. This option is useful for obtaining semiconductor device output characteristics. See the example on transistor characterization (21.3).
General form:
Examples:
The .disto line does a small-signal distortion analysis of the circuit. A multi-dimensional Volterra series analysis is done using multi-dimensional
Taylor series to represent the nonlinearities at the operating point. Terms of up to third order are used in the series expansions.
input frequency 𝐹1 , which is swept as specified by arguments of the .disto command exactly as in the .ac command. Inputs at this frequency may be
If the optional parameter f2overf1 is not specified, .disto does a harmonic analysis - i.e., it analyses distortion in the circuit using only a single
present at more than one input source, and their magnitudes and phases are specified by the arguments of the distof1 keyword in the input file lines
for the input sources (see the description for independent sources). (The arguments of the distof2 keyword are not relevant in this case).
The analysis produces information about the AC values of all node voltages and branch currents at the harmonic frequencies 2𝐹1 and , vs. the input
frequency 𝐹1 as it is swept. (A value of 1 (as a complex distortion output) signifies cos (2𝜋(2𝐹1 )𝑡) at 2𝐹1 and cos (2𝜋(3𝐹1 )𝑡) at 3𝐹1 , using the
convention that 1 at the input fundamental frequency is equivalent to cos (2𝜋𝐹1 𝑡).) The distortion component desired (2𝐹1 or 3𝐹1 ) can be selected
using interactive or control commands in ngspice, and then printed or plotted. (Normally, one is interested primarily in the magnitude of the harmonic
components, and are not equal to HD2 and HD3. To obtain HD2 and HD3, one must divide by the corresponding AC values at 𝐹1 , obtained from an
components, so the magnitude of the AC distortion value is looked at). It should be noted that these are the AC values of the actual harmonic
.ac line. This division can be done again using interactive or control commands.
analysis. It considers the circuit with sinusoidal inputs at two different frequencies 𝐹1 and 𝐹2 . 𝐹1 is swept according to the .disto control line options
If the optional f2overf1 parameter is specified, it should be a real number between (and not equal to) 0.0 and 1.0; in this case, .disto does a spectral
exactly as in the .ac control line. 𝐹2 is kept fixed at a single frequency as 𝐹1 sweeps - the value at which it is kept fixed is equal to f2overf1 times
fstart. Each independent source in the circuit may potentially have two (superimposed) sinusoidal inputs for distortion, at the frequencies 𝐹1 and 𝐹2 .
The magnitude and phase of the 𝐹1 component are specified by the arguments of the distof1 keyword in the source's input line (see the description of
independent sources); the magnitude and phase of the 𝐹2 component are specified by the arguments of the distof2 keyword. The analysis produces
plots of all node voltages/branch currents at the intermodulation product frequencies 𝐹1 + 𝐹2 , 𝐹1 − 𝐹2 , and (2𝐹1 ) − 𝐹2 , vs the swept frequency 𝐹1 .
The IM product of interest may be selected using the setplot command, and displayed with the print and plot commands. It is to be noted as in the
harmonic analysis case, the results are the actual AC voltages and currents at the intermodulation frequencies, and need to be normalized with respect
to .ac values to obtain the IM parameters.
If the distof1 or distof2 keywords are missing from the description of an independent source, then that source is assumed to have no input at the
corresponding frequency. The default values of the magnitude and phase are 1.0 and 0.0 respectively. The phase should be specified in degrees.
It should be carefully noted that the number f2overf1 should ideally be an irrational number, and that since this is not possible in practice, efforts
𝐴
represented as a fraction , where 𝐴 and 𝐵 are integers with no common factors, 𝐵 should be as large as possible; note that 𝐴 < 𝐵 because f2overf1
should be made to keep the denominator in its fractional representation as large as possible, certainly above 3, for accurate results (i.e., if f2overf1 is
𝐵
is constrained to be < 1). To illustrate why, consider the cases where f2overf1 is 49/100 and 1/2. In a spectral analysis, the outputs produced are at
𝐹1 + 𝐹2 , 𝐹1 − 𝐹2 and 2𝐹1 − 𝐹2 . In the latter case, 𝐹1 − 𝐹2 = 𝐹2 , so the result at the 𝐹1 − 𝐹2 component is erroneous because there is the strong
fundamental 𝐹2 component at the same frequency. Also, 𝐹1 + 𝐹2 = 2𝐹1 − 𝐹2 in the latter case, and each result is erroneous individually. This problem
is not there in the case where f2overf1 = 49/100, because 𝐹1 − 𝐹2 = 51/100 𝐹1 < > 49/100 𝐹1 = 𝐹2 . In this case, there are two very closely spaced
frequency components at 𝐹2 and 𝐹1 − 𝐹2 . One of the advantages of the Volterra series technique is that it computes distortions at mix frequencies
expressed symbolically (i.e. 𝑛𝐹1 + 𝑚𝐹2 ), therefore one is able to obtain the strengths of distortion components accurately even if the separation
between them is very small, as opposed to transient analysis for example. The disadvantage is of course that if two of the mix frequencies coincide,
the results are not merged together and presented (though this could presumably be done as a postprocessing step). Currently, the interested user
should keep track of the mix frequencies himself or herself and add the distortions at coinciding mix frequencies together should it be necessary.
Only a subset of the ngspice nonlinear device models supports distortion analysis. These are
Diodes (DIO),
BJT,
JFET (level 1),
MOSFETs (levels 1, 2, 3, 9, and BSIM1),
MESFET (level 1).
15.3.4 .NOISE: Noise Analysis
General form:
.noise v(output <,ref>) src ( dec | lin | oct ) pts fstart fstop
+ <pts_per_summary>
Examples:
The .noise line does a noise analysis of the circuit. output is the node at which the total output noise is desired; if ref is specified, then the noise
voltage v(output) - v(ref) is calculated. By default, ref is assumed to be ground. src is the name of an independent source to which input noise is
referred. pts, fstart and fstop are .ac type parameters that specify the frequency range over which plots are desired. pts_per_summary is an
optional integer; if specified, the noise contributions of each noise generator is produced every pts_per_summary frequency points. The .noise
control line produces two plots, which can selected by setplot command:
𝑉 𝐴
√𝐻𝑧 √𝐻𝑧
one for the Voltage or Current Noise Spectral Density (in or respective the input is a voltage or current source) curves (e.g. after
one for the Total Integrated Noise (in 𝑉 or 𝐴) over the specified frequency range (e.g. after setplot noise2). There are two vectors which
inoise_spectrum: This the equivalent input noise = output noise divided by the gain of the circuit.
𝑉2 𝐴2
𝐻𝑧 𝐻𝑧
set sqrnoise: will deliver results in squared form, means the unit is or . This value refers more to the convenient Power Spectral
Density.
Default setting of ngspice is unset sqrnoise, which delivers Voltage or Current Noise Spectral Density. This is more practical from designers point
of view.
The KLU matrix solver (15.1.1) is not compatible with noise simulation.
General form:
.op
Compute the DC operating point of the circuit with inductors shorted and capacitors opened.
A DC solution can be difficult to find for some circuits, including those with floating nodes or active devices that are non-conducting. After an
attempt at an initial DC solution (may be suppressed by .option noopiter), ngspice uses the following convergence aids, in order, to try to obtain a
DC solution:
1. gmin stepping (gminsteps option). Inserts small conductances across active devices.
gminsteps = 0: No gmin
gminsteps = 1: Two gmin stepping processes in series (default)
gminsteps = 2: Original SPICE 3 gmin
2. source stepping (srcsteps option)
srcsteps = 0: No source stepping
srcsteps = 1: Gillespie source stepping (default)
srcsteps = 2: Original SPICE 3 source stepping
3. transient operating point (optional)
DC analysis is complete as soon as one successful step is found, according to some convergence criteria..
The default behaviour during gmin stepping is the following: Switch gmin to a start value (1e-3), followed by a first trial of gmin stepping, using the
true device gmin, then try dynamic gmin stepping with diagonal parallel gmin elements. If variable dyngmin is set, only dynamic gmin stepping is
used.
Source stepping sets all supply voltages and currents to zero, then ramps them up dynamically to 100%.
The transient op calculation uses a transient simulation, with default parameters set by ngspice (initial iteration, gmin and source stepping enabled,
optran step size 10n, total optran time 10u). The results of this transient simulation then are used as the operating point for starting any other
simulation (tran, ac, noise, pz etc.). No other data of this transient op are stored anywhere.
General form:
Example 1:
Example 1 changes the defaults to: no inital op iteration, no gmin stepping, no source stepping, i.e. directly move to transient op with transient step
and stop times given. Flag supramp ins currently not used. The optran command may be put into one of the initialization files .spiceinit or spinit.
or into the .control section.
Example 2:
Note: an operating point analysis is automatically performed prior to a transient analysis (if the parameter uic is not selected) to determine the
transient initial conditions, and prior to an AC small-signal, Noise, and Pole-Zero analysis to determine the linearized, small-signal models for
nonlinear devices. These data are not stored, except for setting the KEEPOPINFO variable 15.1.2, that prompts creating an OP plot in addition to the
TRAN, AC, Noise, or PZ plots.
General form:
Examples:
cur stands for a transfer function of the type (output voltage)/(input current) while vol stands for a transfer function of the type (output
voltage)/(input voltage). pol stands for pole analysis only, zer for zero analysis only and pz for both. This feature is provided mainly because if there
is a non-convergence in finding poles or zeros, then, at least the other can be found. Finally, node1 and node2 are the two input nodes and node3 and
node4 are the two output nodes. Thus, there is complete freedom regarding the output and input ports and the type of transfer function.
In interactive mode, the command syntax is the same except that the first field is pz instead of .pz. To print the results, one should use the command
print all.
General form:
.SENS OUTVAR
.SENS OUTVAR AC DEC ND FSTART FSTOP
.SENS OUTVAR AC OCT NO FSTART FSTOP
.SENS OUTVAR AC LIN NP FSTART FSTOP
Examples:
.SENS V(1,OUT)
.SENS V(OUT) AC DEC 10 100 100k
.SENS I(VTEST)
The sensitivity of OUTVAR to all non-zero device parameters is calculated when the SENS analysis is specified. OUTVAR is a circuit variable (node
voltage or voltage-source branch current). The first form calculates sensitivity of the DC operating-point value of OUTVAR. The second form
calculates sensitivity of the AC values of OUTVAR. The parameters listed for AC sensitivity are the same as in an AC analysis (see .AC above). The
output values are in dimensions of change in output per unit change of input (as opposed to percent change in output or per percent change of input).
General form:
Examples:
SP Simulation Syntax is identical to .AC (15.3.1) except that you have one more optional parameter donoise (0|1). SP does always linear S-Matrix
simulation and, as outputs, it gives
S
Matrix (size nport x nport where nport is the count of RF ports) which is the Scattering Parameters. It may be used to export Touchstone files
(to be implemented yet)...
Y
Matrix (size nport x nport where nport is the count of RF ports) which is the Admittance Matrix
Z
Matrix (size nport x nport where nport is the count of RF ports) which is the Impedance Matrix
All S|Y|Z output are S_i_j where i and j are integer identifiers of the ports. They refer to the portnum identifier of corresponding RF port of the
VSRC (4.1.11).
If donoise = 1, SP simulation performs also SP Noise. In this case: you have one more output which is the Noise Current Correlation Matrix: Cy_i_j
Cy_i_j = <in(i), in*(j)=""> which is the correlation between equivalent input noise current at port i and equivalent input noise current at port j. *
stands for conjugate</in(i),>
When donoise = 1 and you have a two port networks, 4 more outputs are provided:
Rn
input noise resistance (unnormalized)
NF
(dB): noise figure of the 2-ports network
NFmin
(dB): minimum noise figure
SOpt:
optimum input reflection coefficient for noise
General form:
Examples:
The .tf line defines the small-signal output and input for the dc small-signal analysis. outvar is the small signal output variable and insrc is the
small-signal input source. If this line is included, ngspice computes the dc small-signal value of the transfer function (output/input), input resistance,
and output resistance. For the first example, ngspice would compute the ratio of V(5, 3) to VIN, the small-signal input resistance at VIN, and the
small signal output resistance measured across nodes 5 and 3.
General form:
Examples:
tstep is the printing or plotting increment for line-printer output. For use with the post-processor, tstep is the suggested computing increment. tstop
is the final time, and tstart is the initial time. If tstart is omitted, it is assumed to be zero. The transient analysis always begins at time zero. In the
interval [zero, tstart), the circuit is analyzed (to reach a steady state), but no outputs are stored. In the interval [tstart, tstop], the circuit is
analyzed and outputs are stored. tmax is the maximum stepsize that ngspice uses; for default, the program chooses either tstep or (tstop-
tstart)/50.0, whichever is smaller. tmax is useful when one wishes to guarantee a computing interval that is smaller than the printer increment,
tstep.
An initial transient operating point at time zero is calculated according to the following procedure: all independent voltages and currents are applied
with their time zero values, all capacitances are opened, inductances are shorted, the non linear device equations are solved iteratively.
uic (use initial conditions) is an optional keyword that indicates that the user does not want ngspice to solve for the quiescent operating point before
beginning the transient analysis. If this keyword is specified, ngspice uses the values specified using IC=... on the various elements as the initial
transient condition and proceeds with the analysis. If the .ic control line has been specified (see 15.2.2), then the node voltages on the .ic line are
used to compute the initial conditions for the devices. IC=... will take precedence over the values given in the .ic control line. If neither IC=... nor the
.ic control line is given for a specific node, node voltage zero is assumed.
Look at the description on the .ic control line (15.2.2) for its interpretation when uic is not specified.
Transient noise analysis deals with noise currents or voltages added to your circuits as a time dependent signal of randomly generated voltage
excursion on top of a fixed dc voltage. The sequence of voltage values has random amplitude, but equidistant time intervals, selectable by the user
(parameter NT). The resulting voltage waveform is differentiable and thus does not require any modifications of the matrix solving algorithms.
White noise is generated by the ngspice random number generator, applying the Box-Muller transform. Values are generated on the fly, each time
when a breakpoint is hit.
The 1/f noise is generated with an algorithm provided by N. J. Kasdin (`Discrete simulation of colored noise and stochastic processes and 1/𝑓𝑎 power
law noise generation', Proceedings of the IEEE, Volume 83, Issue 5, May 1995 Page(s):802–827). The noise sequence (one for each voltage/current
simulation time divided by NT, rounded up the the nearest power of 2. Each time a breakpoint (𝑛 ★ 𝑁𝑇, relevant to the noise signal) is hit, the next
source with 1/f selected) is generated upon start up of the simulator and stored for later use. The number of points is determined by the total
If you want a random, but reproducible sequence, you may select a seed value for the random number generator by adding
setseed nn
The transient noise analysis will allow the simulation of the three most important noise sources. Thermal noise is described by the Gaussian white
noise. Flicker noise (pink noise or 1 over f noise) with an exponent between 0 and 2 is provided as well. Shot noise is dependent on the current
flowing through a device and may be simulated by applying a non-linear source as demonstrated in the following example:
Example:
.tran 1n 20u
.control
run
plot (-1)*i(vdev)
.endc
.end
The selection of the delta time step (NT) is worth discussing. Gaussian white noise has unlimited bandwidth and thus unlimited energy content. This is
unrealistic. The bandwidth of real noise is limited, but it is still called `White' if it is the same level throughout the frequency range of interest, e.g. the
bandwidth of your system. Thus you may select NT to be a factor of 10 smaller than the frequency limit of your circuit. A thorough analysis is still
needed to clarify the appropriate factor. The transient method is probably most suited to circuits including switches, which are not amenable to the
small signal .NOISE analysis (Chapt. 15.3.4).
There is a price you have to pay for transient noise analysis: the number of required time steps, and thus the simulation time, increases.
In addition to white and 1/f noise the independent voltage and current sources offer a random telegraph signal (RTS) noise source, also known as burst
noise or popcorn noise, again for transient analysis. For each voltage (current) source offering RTS noise an individual noise amplitude is required for
input, as well as a mean capture time and a mean emission time. The amplitude resembles the influence of a single trap on the current or voltage. The
capture and emission times emulate the filling and emptying of the trap, typically following a Poisson process. They are generated from an random
exponential distribution with respective mean values given by the user. To simulate an ensemble of traps, you may combine several current or voltage
sources with different parameters.
All three sources (white, 1/f, and RTS) may be combined in a single command line.
* voltage source
VRTS2 13 12 DC 0 trnoise(0 0 0 0 5m 18u 30u)
VRTS3 11 0 DC 0 trnoise(0 0 0 0 10m 20u 40u)
VALL 12 11 DC 0 trnoise(1m 1u 1.0 0.1m 15m 22u 50u)
* current source
IRTS2 10 0 DC 0 trnoise(0 0 0 0 5m 18u 30u)
IRTS3 10 0 DC 0 trnoise(0 0 0 0 10m 20u 40u)
IALL 10 0 DC 0 trnoise(1m 1u 1.0 0.1m 15m 22u 50u)
R10 10 0 1
* sample points
.tran 1u 500u
.control
run
plot v(13) v(21)
plot v(10) v(9)
.endc
.end
Some details on RTS noise modeling are available in a recent article [20], available here.
General form:
Examples:
rgfreq on the fundamental. If gfreq is out of ±10% with respect to rgfreq then gfreq is discarded.
gfreq is guessed frequency of fundamental suggested by user. When performing transient analysis the PSS algorithm tries to infer a new rough guess
tstab is stabilization time before the shooting begin to search for the PSS. It has to be noticed that this parameter heavily influence the possibility to
reach the PSS. Thus is a good practice to ensure a circuit to have a right tstab, e.g. performing a separate TRAN analysis before to run PSS analysis.
oscnob is the node or branch where the oscillation dynamic is expected. PSS analysis will give a brief report of harmonic content at this node or
branch.
psspoints is number of step in evaluating predicted period after convergence is reached. It is useful only in Time Domain plots. However this
number should be higher than 2 times the requested harms. Otherwise the PSS analysis will properly adjust it.
steady_coeff is the weighting coefficient for calculating the Global Convergence Error (GCE), which is the reference value in order to infer is
convergence is reached. The lower steady_coeff is set, the higher the accuracy of predicted frequency can be reached but at longer analysis time and
sciter number. Default is 1e-3.
uic (use initial conditions) is an optional keyword that indicates that the user does not want ngspice to solve for the quiescent operating point before
beginning the transient analysis. If this keyword is specified, ngspice uses the values specified using IC=... on the various elements as the initial
transient condition and proceeds with the analysis. If the .ic control line has been specified, then the node voltages on the .ic line are used to
compute the initial conditions for the devices. Look at the description on the .ic control line for its interpretation when uic is not specified.
If you need batch like operation, you may add a .control ... .endc section to the input file:
Example:
*input file
...
.tran 1ns 1000ns
...
*********************************
.control
run
write outputfile data
.endc
*********************************
.end
ngspice inputfile .
.meas<ure> then prints its user-defined data analysis to the standard output. The analysis includes propagation, delay, rise time, fall time, peak-to-
peak voltage, minimum or maximum voltage, the integral or derivative over a specified period and several other user defined values.
result will be a vector containing the result of the measurement. trig_variable, targ_variable, and out_variable are vectors stemming from the
simulation, e.g. a voltage vector v(out).
VAL=val expects a real number val. It may be as well a parameter delimited by '' or {} expanding to a real number.
TD=td and AT=time expect a time value if measure type is tran. For ac and sp, AT will be a frequency value, TD is ignored. For dc analysis, AT is a
voltage (or current), TD is ignored as well.
CROSS=# requires an integer number #. CROSS=LAST is possible as well. The same is expected by RISE and FALL.
Frequency and time values may start at 0 and extend to positive real numbers. Voltage (or current) inputs for the independent (scale) axis in a dc
analysis may start or end at arbitrary real valued numbers.
Please note that not all of the .measure commands have been implemented.
15.4.4 Input
In the following lines you will get some explanation on the .measure commands. A simple simulation file with two sines of different frequencies may
serve as an example. The transient simulation delivers time as the independent variable and two voltages as output (dependent variables).
Input file:
File: simple-meas-tran.sp
* Simple .measure examples
* transient simulation of two sine
* signals with different frequencies
vac1 1 0 DC 0 sin(0 1 1k 0 0)
vac2 2 0 DC 0 sin(0 1.2 0.9k 0 0)
.tran 10u 5m
*
.measure tran ... $ for the different inputs see below!
*
.control
run
plot v(1) v(2)
.endc
.end
After displaying the general syntax of the .measure statement, some examples are posted, referring to the input file given above.
General form 1:
Measure statement example (for use in the input file given above):
.measure tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 RISE=2
measures the time difference between v(1) reaching 0.5 V for the first time on its first rising slope (TRIG) versus reaching 0.5 V again on its second
rising slope (TARG), i.e. it measures the signal period.
Output:
.measure tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 RISE=3
measures the time difference between v(1) reaching 0.5 V for the first time on its rising slope versus reaching 0.5 V on its rising slope for the third
time (i.e. two periods).
Measure statement:
.measure tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 FALL=1
measures the time difference between v(1) reaching 0.5V for the first time on its rising slope versus reaching 0.5 V on its first falling slope.
Measure statement:
.measure tran tdiff TRIG v(1) VAL=0 FALL=3 TARG v(2) VAL=0 FALL=3
measures the time difference between v(1) reaching 0V its third falling slope versus v(2) reaching 0 V on its third falling slope.
Measure statement:
.measure tran tdiff TRIG v(1) VAL=-0.6 CROSS=1 TARG v(2) VAL=-0.8 CROSS=1
measures the time difference between v(1) crossing -0.6 V for the first time (any slope) versus v(2) crossing -0.8 V for the first time (any slope).
Measure statement:
measures the time difference between the time point 1ms versus the time when v(2) crosses -0.8 V for the third time (any slope).
General form 2:
Measure statement:
measures the time point when v(2) crosses 0.7 V for the last time (any slope).
General form 3:
Measure statement:
measures the time point when v(2) and v(1) are equal, v(2) rising for the last time.
General form 4:
Measure statement:
returns the dependent (y) variable drawn from v(2) at the time point when v(1) equals a value of -0.4, v(1) falling for the last time.
General form 5:
Measure statement:
returns the dependent (y) variable drawn from v(2) at the time point when v(1) crosses v(3), v(1) falling for the second time.
General form 6:
Measure statement:
returns the dependent (y) variable drawn from v(2) at the time point 2 ms (given by AT=time).
15.4.7 AVG|MIN|MAX|PP|RMS|MIN_AT|MAX_AT
General form 7:
Measure statements:
returns the maximum value of v(2) inside the time interval between 2 ms and 3 ms.
returns the time point of the maximum value of v(2) inside the time interval between 2 ms and 3 ms.
returns the peak to peak value of v(1) inside the time interval between 2 ms and 4 ms.
returns the root mean square value of v(1) inside the time interval between 2 ms and 4 ms.
returns the average value of v(1) inside the time interval between 2 ms and 4 ms.
15.4.8 Integ
General form 8:
Measure statement:
returns the area under v(2) inside the time interval between 2 ms and 3 ms.
15.4.9 param
General form 9:
Measure statement:
.param fval=5
will evaluate the given expression fval + 7 and return the value 12.
'Expression' is evaluated according to the rules given in Chapt. 2.9.5 during start up of ngspice. It may contain parameters defined with the .param
statement. It may also contain parameters resulting from preceding .meas statements.
.param vout_diff=50u
...
will evaluate the given ternary function and return the value 1 in bw_chk, if tdiff measured is smaller than parameter vout_diff.
The expression may not contain vectors like v(10), e.g. anything resulting directly from a simulation. This may be handled with the following .meas
command option.
15.4.10 par('expression' )
The par('expression') option (15.6.6) allows the use of algebraic expressions on the .measure lines. Every out_variable may be replaced by
par('expression') using the general forms 1…9 described above. Internally par('expression') is substituted by a vector according to the rules of the B
source (Chapt. 5.1). A typical example of the general form is shown below:
returns the product of the two voltages at time point 2.3 ms.
Note that a B-source, and therefore the par('...') feature, operates on values of type complex in AC analysis mode.
Both param and par are not available for the meas command (17.5.47) inside of a .control section, where meas with par or param may be replaced by
let (17.5.42).
15.4.11 Deriv
General form:
Other examples:
The check is executed after Newton-Raphson iteration is finished i.e. in transient analysis in each time step. The user can specify an additional
.option maxwarns (default: 5) to limit the count of messages.
The output goes on default to stdout or alternatively to a file specified by command line option --soa-log=filename.
To achive SOA checking, add some or all of these parameters with suitable limit values to the .model line of the respective device.
If self-heating (54) is switched on, and Te_max, tnom and rth0 are given, then a derating for the maximam allowed power dissipation is calculated,
and power and current temperature are checked against their max. allowed values.
If self-heating is switched off, and rth0 and tnom are given, then a static max. power derating is calculated, taking the device temperature (set by its
default value 27 °C, or the global .temp value, or the device specific instance parameter temp) into account. The reference temperature is tnom.
If rth0 or tnom are not given, no derating is calculated, the power disspation is simply checked against Pd_max.
If rth0 and tnom are given, then a static max. power derating is calculated, taking the device temperature (set by its default value 27 °C, or the global
.temp value, or the device specific instance parameter temp) into account. The reference temperature is tnom.
If rth0 or tnom are not given, no derating is calculated, the power disspation is simply checked against Pd_max.
If .option warn=2 is set, the following parameters (defaults are set to 0.2 V) may be used to determine the current operation point of the device.
op conditions
off Vbe <= vbefwd and Vbc <= vbcfwd
saturation Vbe > vbefwd and Vbc > vbcfwd
forward Vbe > vbefwd and Vbc <= vbcfwd
reverse Vbe <= vbefwd and Vbc > vbcfwd
Substrate leakage due to forward conduction of the collector-substrate diode may be detected using:
If you start ngspice in batch mode using the -b command line option, the outputs of .print, .plot, and .four are printed to the console output. You
may use the output redirection of your shell to direct this printout into a file (not available with MS Windows GUI). As an alternative, you may extend
the ngspice command by specifying an output file:
If you however add the command line option -r to create a rawfile, .print and .plot are ignored. If you want to involve the graphics plot output of
ngspice, use the control mode (16.4.3) instead of the -b batch mode option.
General form:
Examples:
The vectors listed on the .SAVE line are recorded in the rawfile for use later with ngspice. The standard vector names are accepted. Node voltages may
be saved by giving the nodename or v(nodename). Currents through an independent voltage source are given by i(sourcename) or
sourcename#branch. Internal device data are accepted as @dev[param].
If no .SAVE line is given, then the default set of vectors is saved (node voltages and voltage source branch currents). If .SAVE lines are given, only
those vectors specified are saved. For more discussion on internal device data, e.g. @m1[id], see Appendix, Chapt. 31.1. If you want to save internal
data in addition to the default vector set, add the parameter all to the additional vectors to be saved. If the command .save vm(out) is given, and you
store the data in a rawfile, only the original data v(out) are stored. The request for storing the magnitude is ignored, because this may be added later
during rawfile data evaluation with ngspice. See also the section on the interactive command interpreter (Chapt. 17.5) for information on how to use
the rawfile.
General form:
Examples:
The .print line defines the contents of a tabular listing of one to eight output variables. prtype is the type of the analysis (DC, AC, TRAN, NOISE, or
DISTO) for which the specified outputs are desired. The form for voltage or current output variables is the same as given in the previous section for the
print command; Spice2 restricts the output variable to the following forms (though this restriction is not enforced by ngspice):
VR Real part
VI Imaginary part
VM Magnitude
VP Phase
VDB 20lo g10(𝑚𝑎𝑔𝑛𝑖𝑡𝑢𝑑𝑒)
Output variables for the noise and distortion analyses have a different general form from that of the other analyses. There is no limit on the number of
.print lines for each type of analysis. The par('expression') option (15.6.6) allows the use of algebraic expressions in the .print lines. .width
(15.6.7) selects the maximum number of characters per line.
General form:
.plot pltype ov1 <(plo1, phi1)> <ov2 <(plo2, phi2)> ... ov8>
Examples:
The .plot line defines the contents of one plot of from one to eight output variables. pltype is the type of analysis (DC, AC, TRAN, NOISE, or DISTO) for
which the specified outputs are desired. The syntax for the ovi is identical to that for the .print line and for the plot command in the interactive
mode.
The overlap of two or more traces on any plot is indicated by the letter `X'. When more than one output variable appears on the same plot, the first
variable specified is printed as well as plotted. If a printout of all variables is desired, then a companion .print line should be included. There is no
limit on the number of .plot lines specified for each type of analysis. The par('expression') option (15.6.6) allows the use of algebraic expressions in
the .plot lines.
General form:
Examples:
The .four (or Fourier) line controls whether ngspice performs a Fourier analysis as a part of the transient analysis. freq is the fundamental frequency,
and ov1 is the desired vector to be analyzed. The Fourier analysis is performed over the interval <TSTOP-period, TSTOP>, where TSTOP is the final
time specified for the transient analysis, and period is one period of the fundamental frequency. The dc component and the first nine harmonics are
determined. For maximum accuracy, TMAX (see the .tran line) should be set to period/100.0 (or less for very high-Q circuits). The par('expression')
option (15.6.6) allows the use of algebraic expressions in the .four lines.
As .four is available only when ngspice is executed in batch mode (16.4.1), and no rawfile selected, you may consider the spec (17.5.84) or fft
(17.5.30) commands, when using ngspice in .control mode (with a .control section, 16.4.3).
15.6.5 .PROBE: Save device node currents, device power dissipation, or differential voltages between arbitrary nodes
Command .probe enables current measurement at user specified device nodes, as well as (differential) voltage measurements between device nodes.
Besides standard devices you may also measure currents at X instance lines (subcircuit calls). If the subcircuit definition (.subckt line) uses named
nodes, these are used instead of node numbers (see device u1 in the example below).
Be careful when .probe alli is given, because the many output vectors generated automatically may require a large amount of memory to store all
the current measurement vectors.
.probe alli
.probe I(device)
General form for current measurements on a multi-terminal device (one command per terminal):
.probe I(device,node)
Examples:
r1#branch
mq4:s#branch
Resulting output vectors for .probe all (excerpt only, example file 555-timer-2.cir):
...
ra#branch : current, real, 14579 long
rb#branch : current, real, 14579 long
rl#branch : current, real, 14579 long
time : time, real, 14579 long [default scale]
xu1:cont#branch : current, real, 14579 long
xu1:disc#branch : current, real, 14579 long
xu1:gnd#branch : current, real, 14579 long
xu1:out#branch : current, real, 14579 long
xu1:reset#branch : current, real, 14579 long
xu1:thres#branch : current, real, 14579 long
xu1:trig#branch : current, real, 14579 long
xu1:vcc#branch : current, real, 14579 long
xu2:1#branch : current, real, 14579 long
xu2:19#branch : current, real, 14579 long
...
Compared to the approach using command .options savecurrents the resulting vectors from a .probe command are available for every simulation
type including AC simulation. A slight disadvantage may be that new nodes are added to the instance matrix, increasing simulation time (typically a
little bit only).
.probe v(node1)
.probe vd(device:node1:node2)
.probe vd(device1:node1, device2:node2)
device, device1, and device2 are device names (first token in an instance line). node1, node2 are either numbers (according to the node sequence
in the instance line, e.g. 1, 2, 3, ...), or are node names of known devices (d, g, s, b for MOS of JFET, c, b, e for bipolar.
Examples:
nR1
vd_R1
vd_m4:d:0
vd_m4:d:s
vd_m3:d_m5:s
.probe p(device)
Examples:
xu1:power
mq1:power
All new items are added to the list of vectors named by .SAVE (see 15.6.1). If .save is not given, only the newly generated .PROBE vectors are saved.
General form:
par('expression')
output=par('expression') $ not in .measure ac
Examples:
With the output lines .four, .plot, .print, .save and in .measure evaluation, it is possible to add algebraic expressions for output, in addition
to vectors. All of these output lines accept par('expression'), where expression is any expression valid for a B source (see Chapt. 5.1). Thus
expression may contain predefined functions, numerical values, constants, simulator output like v(n1) or i(vdb), parameters predefined by a .param
statement, and the variables hertz, temper, and time. Note that a B-source, and therefore the par('...') feature, operates on values of type complex
in AC analysis mode.
Internally the expression is replaced by a generated voltage node that is the output of a B source, one node, and the B source implementing par('...').
Several par('...') are allowed in each line, up to 99 per input file. The internal nodes are named pa_00 to pa_99. An error will occur if the input file
contains any of these reserved node names.
The syntax of output=par(expression) is strict: no spaces are allowed between par and ('or between ( and '. Also,(' and ') both are required.
There is not much error checking on your input, so if there is a typo, for example, an error may pop up at an unexpected place.
15.6.7 .width
Set the width of a print-out or plot with the following card:
Parameter out yields the maximum number of characters plotted in a row, if printing in columns or an ASCII-plot is selected.
.save @r1[i]
.save @r2[i]
to your input file information read during circuit parsing. These newly created vectors contain the terminal currents of the devices R1 and R2.
You will find information of the nomenclature in Chapt. 31, also how to plot these vectors. The following devices are supported: M, J, Q, D, R, C, L,
B, F, G, W, S, I (see 2.1.3). For MOSFETdevices only a subset of MOS1 to MOS9 current parameters are included per default (but see options
below). Devices in subcircuits are supported as well. The advantage of the data obtained by .options savecurrents is that no extra nodes are
required, because the data are retrieved from internal nodes already existing.
This option however cannot be used in AC simulations, because complex data are not supported. Vectors thus created will be empty after an AC
simulation. So for AC you might use one of the two methods (.probe or series voltage source) as previously described.
Be careful when choosing savecurrents in larger circuits, because 1 to 4 additional output vectors are created per device and this may consume lots
of memory.
Also note that the data thus retrieved may be delayed by on time step after a transient simulation.
For MOS1, BSIM3 and BSIM4 three special options are available, listing all currents as described in chapters 31.6.1, 31.6.8 and 31.6.9 of the ngspice
manual:
The usual way to run ngspice is by a console command, passing options and at least one netlist file as a parameter. Multiple netlists are concatenated
and treated as one, except when the first file is a pure script with parameters (17.8).
Ngspice on Linux (and OSs like MacOS, Cygwin, BSD, Solaris ...) uses the X Window System for plotting (see Chapt. 18.3) if the environment
variable DISPLAY is available. (An X11 server must first be installed on MacOS.) Otherwise, a console mode (non-graphical) interface is used. If you
are using X on a workstation, the DISPLAY variable should already be set; if you want to display graphics on a system different from the one you are
running ngspice or ngutmeg on, DISPLAY should be of the form machine:0.0. See the appropriate documentation on the X Window System for more
details.
The MS Windows GUI version of ngspice has a native graphics interface (see Chapt. 18.1).
The front-end may be run as a separate `stand-alone' program under the name ngnutmeg. ngnutmeg is a subset of ngspice dedicated to data evaluation,
still optionally compilable (Linux, Mingw) for historical reasons. Ngnutmeg will read in the `raw' data output file created by ngspice -r or by the
write command during an interactive ngspice session.
If you want to check out the source code that is actually under development, you may have a look at the ngspice source code repository, which is
stored using the Git Source Code Management (SCM) tool. The Git repository may be browsed on the Git web page, also useful for downloading
individual files. You may however download (or clone) the complete repository including all source code trees from the console window (Linux,
CYGWIN or MSYS/MINGW) by issuing the command (in a single line)
You need to have Git installed, which is available for all three OSs. The whole source tree is then available in <current directory>/ngspice.
Compilation and local installation is again described in INSTALL (or Chapt. 32). If you later want to update your files and download the recent
changes from SourceForge into your local repository, cd into the ngspice directory and just type
git pull
git pull will not overwrite modified files in your working directory. To drop your local changes first, you can run
To learn more about git, which can be both powerful and difficult to master, please consult http://git-scm.com/, especially: http://git-
scm.com/documentation, which has pointers to documentation and tutorials.
Command Synopsis:
Further arguments to ngspice are taken to be ngspice input files, which are read and saved (if running in batch mode then they are run immediately).
Ngspice accepts Spice3 (and also most Spice2) input files, and outputs ASCII plots, Fourier analyses, and node printouts as specified in .plot, .four,
and .print cards. If an out parameter is given on a .width card (15.6.7), the effect is the same as set width = .... Since ngspice ASCII plots do not
use multiple ranges, however, if vectors together on a .plot card have different ranges they do not provide as much information as they do in a
scalable graphics plot.
For ngnutmeg, further arguments are taken to be data files in binary or ASCII raw file format (generated with -r in batch mode or the write (see
17.5.104) command) that are loaded into ngnutmeg. If the file is in binary format, it may be only partially completed (useful for examining output
before the simulation is finished). One file may contain any number of data sets from different analyses.
ngspice will start, simulate according to the .tran command and store the output data in a rawfile adder.raw. Comments, warnings and info messages
go to log file adder.log. Commands for batch mode operation are described in Chapt. 15.
ngspice
ngspice will start, load spinit (16.5) and .spiceinit (16.6, if available), and then waits for your manual input. Any of the commands described in 17.5
may be chosen, but many of them are useful only after a circuit has been loaded by
ngspice 2 ->run
ngspice 3 ->plot allv
If you call ngspice from the command line with a circuit file as parameter:
ngspice adder-mos.cir
ngspice will start, load the circuit file, parse the circuit (same circuit file as above, containing only dot commands (see Chapt. 15) for analysis and
output control). ngspice then just waits for your input. You may start the simulation by issuing the run command. Following completion of the
simulation you may analyze the data by any of the commands given in Chapt. 17.5.
16.4.3 Control mode (Interactive mode with control file or control section)
If you add the following control section to your input file adder-mos.cir, you may call
ngspice adder-mos.cir
from the command line and see ngspice starting, simulating and then plotting immediately.
Control section:
Any suitable command listed in Chapt. 17.5 may be added to the control section, as well as control structures described in Chapt. 17.6. Batch-like
behavior may be obtained by changing the control section to
If you put this control section into a file, say adder-start.sp, you may just add the line
.include adder-start.sp
to your input file adder-mos.cir to obtain the batch-like behavior. In the following example the line .tran ... from the input file is overridden by
the tran command given in the control section.
The commands within the .control section are executed in the order they are listed and only after the circuit has been read in and parsed. If you
want to have a command being executed before circuit parsing, you may use the prefix pre_ (17.5.54) to the command.
A warning is due however: If your circuit file contains such a control section (.control ... .endc), you should not start ngspice in batch mode (with -
b as parameter). The outcome may be unpredictable!
spinit contains a script, made of commands from Chapt. 17.5, that is run upon start up of ngspice. Aliases (name equivalences) can be set. The
asterisk `*' comments out a line. If used by ngspice, spinit will then load the XSPICE code models from a path relative to the current directory where
the ngspice executable resides, as well as OpenVAF compiled compact devices models. You may also define absolute paths.
If the standard path for the libraries (see standard spinit above or /usr/local/lib/spice under CYGWIN and Linux) is not adequate, you can add
the ./configure options --prefix=/usr --libdir=/usr/lib64 to set the codemodel search path to /usr/lib64/spice. Besides the standard lib
only lib64 is acknowledged.
if $?sharedmode
unset interactive
unset moremode
else
set interactive
set x11lineararcs
end
Special care has to be taken when using the ngspice shared library. If you use ngspice.dll under Windows OS, the standard is to use relative paths for
the code models as shown above. However, the path is relative to the calling program, not to the dll. This is fine when ngspice.dll and the calling
program reside in the same directory. If ngspice.dll is placed in a different directory, please check Chapt. 32.2.
.spiceinit will be read in and executed after spinit, but before any other input file is read. It may contain further scripts, set variables, or issue
commands from Chapt.17.5 to override commands given in spinit. For example set filetype=ascii will yield ASCII output in the output data file
(rawfile), instead of the compact binary format that is used by default. set ngdebug will yield a lot of additional debug output. Any other contents of
the script, e.g. plotting preferences, may be included here also. If the command line option -n is used upon ngspice start up, this file will be ignored.
.spiceinit for simulating IC designs with MOS transistor data from PDKs may contain:
set num_threads=8 should be set to the number of physical cores of the computer in use (here for example 8 cores), set ngbehavior=hsa will ensure
HSPICE compatibility with some important and essential tweaks for the PDK, set ng_nomodcheck will suppress some unwanted warnings, option
noinit will suppress the (often lengthy) printing of the operating point results. option klu often will yield simulation speed up by a factor of 2 or
more. optran ... will skip usual operating point iterations, which for very large circuits consume much time, and replace it by time integrated
operating point estimation.
.spiceinit for simulating circuits containing PSPICE-compatible behavioural models may contain:
set ngbehavior = ltpsa will provide PSPICE compatibility. option sparse sometimes is much faster than klu.
Some editors on MS Windows refuse to save files with leading dot in their names. An alternative name to .spiceinit is therefore spice.rc.
SPICE_LIB_DIR
default: /usr/local/share/ngspice (Linux, CYGWIN), C:\Spice\share\ngspice (Windows)
SPICE_EXEC_DIR
default: /usr/local/bin (Linux, CYGWIN), C:\Spice\bin (Windows)
SPICE_BUGADDR
default: https://ngspice.sourceforge.io/bugrep.html
Where to send bug reports on ngspice.
SPICE_EDITOR
default: vi (Linux, CYGWIN), notepad.exe (MINGW, Visual Studio)
Set the editor called in the edit command. Always overrides the EDITOR env. variable.
SPICE_ASCIIRAWFILE
default: 0
Format of the rawfile. 0 for binary, and 1 for ascii.
SPICE_NEWS
default: $SPICE_LIB_DIR/news
A file that is copied verbatim to stdout when ngspice starts in interactive mode.
SPICE_HELP_DIR
default: $SPICE_LIB_DIR/helpdir
Help directory, not used in Windows mode
SPICE_HOST
default: empty string
Used in the rspice command (probably obsolete, to be documented)
SPICE_SCRIPTS
default: $SPICE_LIB_DIR/scripts
In this directory the spinit file will be searched.
SPICE_PATH
default: $SPICE_EXEC_DIR/ngspice
Used in the aspice command (probably obsolete, to be documented)
NGSPICE_MEAS_PRECISION
default: 5
Sets the number of digits if output values are printed by the meas(ure) command.
SPICE_NO_DATASEG_CHECK
default: undefined
If defined, will suppress memory resource info (probably obsolete, not used on Windows or where the /proc information system is available.)
NGSPICE_INPUT_DIR
default: undefined
If defined, using a valid directory name, will add the given directory to the search path when looking for input files (*.cir, *.inc, *.lib).
SPICE_USERINIT_DIR
default: undefined
If defined, using a valid directory name, this is the first place to search for the user-defined initialization file .spiceinit (or spice.rc). The search
sequence then following is: current directory, HOME directory, USERPROFILE directory
If you start ngspice in interactive mode or interactively with control section, all data will be kept in memory, to be available for later evaluation. A
large circuit may outgrow even Gigabytes of memory. The same may happen after a very long simulation run with many vectors and many time steps
to be stored. Issuing the save <nodes> command will help to reduce memory requirements by saving only the data defined by the command. You
may also choose option INTERP (15.1.4) to reduce memory usage.
16.9 Simulation time
Simulating large circuits may take an considerable amount of CPU time. If this is of importance, you should compile ngspice with the flags for
optimum speed, set during configuring ngspice compilation. Under Linux, MINGW, and CYGWIN you should select the following option to disable
the debug mode, which slows down ngspice:
./configure --disable-debug
Adding --disable-debug will set the -O2 optimization flag for compiling and linking.
Under MS Visual Studio, you will have to select the release version, which includes optimization for speed.
If you have selected XSPICE (see Chapt. 12 and II) as part of your compilation configuration (by adding the option --enable-xspice to your
./configure command), the value of trtol (see 15.1.4) is set internally to 1 (instead of default 7) for higher precision if XSPICE code model 'A'
devices included in the circuit. This may double or even triple the CPU time needed for any transient simulation, because the amount of time steps
and thus iteration steps is more than doubled. For MS Visual Studio compilation there is currently no simple way to exclude XSPICE during
compilation.
You may enforce higher speed during XSPICE usage by setting the variable xtrtol in your .spiceinit initialization file or in the .control section in
front of the tran command (via set xtrtol=2 using the set command 17.5.70) and override the above trtol reduction. Beware however of precision or
convergence issues if you use XSPICE 'A' devices, especially if xtrtol is set to values larger than 2.
If your circuit is composed mostly of MOS transistors, and you have a multi-core processor at hand, you may benefit from OpenMP parallel
processing, as described next (16.10).
Using circuits containing mostly transistors and e.g. the BSIM3 model, around 2/3 of the CPU time is spent in evaluating the model equations (e.g. in
the BSIM3Load() function). The same happens with other advanced transistor models. Thus, such functions should be parallelized, if possible.
Solving the matrix takes about 10% to 50% of the CPU time, so parallel processing in the matrix solver is sometimes of secondary interest only!
Further, such paralellization is difficult to achieve with our Sparse Matrix and KLU solvers.
Another alternative is using CUSPICE, that is ngspice (current version 27) designed for running massively parallel on NVIDIA GPUs. CUDA
enhancements to C code are applied. For LINUX, please see the user guide. For MS Windows, an executable is available at the ngspice download
pages.
16.10.2 Internals
A publication [1] has described a way to exactly do that using OpenMP, which is available on many platforms and is easy to use, especially if you
want to perform parallel processing of a for-loop.
To explain the implemented approach BSIM3 version 3.3.0 model was chosen, located in the BSIM3 directory, as the first example. The BSIM3load()
function in b3ld.c contains two nested for-loops using linked lists (models and instances, e.g. individual transistors). Unfortunately OpenMP requires
a loop with an integer index. So in file B3set.c an array is defined, filled with pointers to all instances of BSIM3 and stored in model-
>BSIM3InstanceArray.
BSIM3load() is now a wrapper function, calling the for-loop, which runs through functions BSIM3LoadOMP(), once per instance. Inside
BSIM3LoadOMP() the model equations are calculated.
Typically it is necessary to use synchronization constructs such as mutexes when multiple threads write to a common memory location. To avoid the
performance degradation of such synchronization, temporary per-thread memory locations are used within the for loop of the BSIM3LoadOMP()
function as defined in bsim3def.h. After all threads complete the for-loop, the update to the matrix is done in an extra function BSIM3LoadRhsMat()
in the main thread.
This of course is made possible only thanks to the OpenMP guys and the clever trick on no synchronization introduced by the above cited authors.
The time-measuring function getrusage() used with Linux or Cygwin to determine the CPU time usage (with the rusage option enabled) counts tics
from every core, adds them up, and thus reports a CPU time value enlarged by a factor of 8 if 8 threads have been chosen. So now ngspice is forced to
use ftime for time measuring if OpenMP is selected.
Windows Linux
1 65.4 69.3
2 46.7 47.4
4 37.2 36.9
6 33.6 33.6
8 32.4 32.4
12 35.7 31.7
16 38.2 34.3
Table 16.1: OpenMP performance
So we see a ngspice speed up of more than a factor of two! Even on an Windows 7 notebook with a dual core i7 processor, more than 1.5x
improvement using two threads was attained. This is consistent with the fact that roughly half of the CPU time is used for evaluating the device
model, half of the time for solving the matrix. Only the device evaluation is parallelized by OpenMP. The time for doing this becomes negligible with
8 or more threads. Allowing more than 8 threads (using the 8 physical cores) does not yield much improvement, even leads to a slight increase of
simulation time, because the code is not optimized for hyperthreading.
16.10.4 Usage
To state it clearly: OpenMP is installed inside the model equations of a particular model. It is available in BSIM3 versions 3.3.0 and 3.2.4, but not in
any other BSIM3 model, in BSIM4 versions 4.5, 4.6.5, 4.7 or 4.8, but not in any other BSIM4 model, and in B4SOI, version 4.4, not in any other
SOI model. Older parameter files of version 4.6.x (x any number up to 5) are accepted, you have to check for compatibility.
./autogen.sh
make install
The same has been tested under MS Windows with CYGWIN and MINGW as well and delivers similar results.
Under MS Windows with Visual Studio Professional the preprocessor flag USE_OMP, and the /openmp flag in Visual Studio are enabled by default.
Visual Studio 2015 and later offer OpenMP support inherently.
set num_threads=4
into spinit or .spiceinit or in the control section of the SPICE input file. If OpenMP is enabled, but num_threads not set, a default value
num_threads=2 is set internally.
If you simulate a circuit, please keep in mind to select BSIM3 (levels 8, 49) version 3.2.4 or 3.3.0 (11.2.10), by placing this version number into your
parameter files, BSIM4 (levels 14, 54) version 4.5, 4.6.5, 4.7 or 4.8 (11.2.11), or B4SOI (levels 10, 58) version 4.4 (11.2.12). All other transistor
models run as usual (without multithreading support).
If you run ./configure without --enable-openmp (or without USE_OMP preprocessor flag under MS Windows), you will get only the standard, not
paralleled BSIM3 and BSIM4 models, as has been available from Berkeley. If OpenMP is selected and the number of threads set to 1, there will be
only a very slight CPU time disadvantage (typ. 3%) compared to the old, non OpenMP build.
16.10.5 Literature
[1] R.K. Perng, T.-H. Weng, and K.-C. Li: "On Performance Enhancement of Circuit Simulation Using Multithreaded Techniques", IEEE
International Conference on Computational Science and Engineering, 2009, pp. 158-165
Under MS Windows you will need to compile ngspice as a console application (see Chapt. 32.2.4) for this server mode usage.
test -s
v1 1 0 1
r1 1 0 2k
.options filetype=ascii
.save i(v1)
.dc v1 -1 1 0.5
.end
Title: test -s
Date: Sun Jan 15 18:57:13 2012
Plotname: DC transfer characteristic
Flags: real
No. Variables: 2
No. Points: 0
Variables:
No. of Data Columns : 2
0 v(v-sweep) voltage
1 i(v1) current
Values:
0 -1.000000000000000e+000
5.000000000000000e-004
1 -5.000000000000000e-001
2.500000000000000e-004
2 0.000000000000000e+000
0.000000000000000e+000
3 5.000000000000000e-001
-2.500000000000000e-004
4 1.000000000000000e+000
-5.000000000000000e-004
@@@ 122 5
The number 5 of the last line @@@ 122 5 shows the number of data points, which is missing in the above line No. Points: 0 because at the time of
writing to the console it has not yet been available.
ctrl Z is not usable here in Linux, a patch to install ctrl D instead is being evaluated.
Under MS Windows you will need to compile ngspice as a console application (see Chapt. 32.2.4) for this pipe mode usage.
*pipe-circuit.cir
source circuit.cir
tran 10u 2m
write pcir.raw all
* Circuit.cir
V1 n0 0 SIN(0 10 1kHz)
C1 n1 n0 3.3nF
R1 0 n1 1k
.end
The raw file pcir.raw will contain the final simulation results.
#!/usr/bin/env bash
NGSPICE_COMMAND="ngspice"
rm input.fifo
rm output.fifo
mkfifo input.fifo
mkfifo output.fifo
exec 3>input.fifo
echo "I can write to input.fifo"
exec 3>&-
exec 4>&-
The bash script listed above (tested under Linux and Cygwin)
Circuit.cir:
* Circuit.cir
V1 n0 0 SIN(0 10 1kHz)
C1 n1 n0 3.3nF
R1 0 n1 1k
.end
16.14 Compatibility
ngspice is a direct derivative of spice3f5 from UC Berkeley and thus inherits all of the commands available in its predecessor. Thanks to the open
source policy of UCB (original spice3 from 1994 is still available here), several commercial variants have sprung off, either being more dedicated to
IC design or more concentrating on simulating discrete and board level electronics. None of the commercial and almost none of the freely
downloadable SPICE providers publishes the source code. All of them have proceeded with the development, by adding functionality, or by adding a
more dedicated user interface. Some have kept the original SPICE syntax for their netlist description, others have quickly changed some if not many
of the commands, functions and procedures. Thus it is difficult, if not impossible, to offer a simulator that acknowledges all of these netlist dialects.
ngspice includes some features that enhance compatibility that are included automatically. This selection may be controlled to some extend by setting
the compatibility mode. Others may be invoked by the user by small additions to the netlist input file. Some of them are listed in this chapter, some
will be integrated into ngspice at a later stage, others will be added if they are reported by users.
The command 'unset ngbehavior' will remove the variable ngbehavior, thus resetting the compatibility mode to the default (no compat mode is
set).
16.14.3 Devices
16.14.3.1 E Source with LAPLACE
see 5.2.5.
16.14.3.2 VSwitch
The VSwitch
S1 2 3 11 0 SW
.MODEL SW VSWITCH(VON=5V VOFF=0V RON=0.1 ROFF=100K)
may become
a1 %v(11) %gd(2 3) sw
.MODEL SW aswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e5
+ r_on=0.1 log=TRUE)
The XSPICE option has to be enabled.
16.14.4.2 .step
Repeated analysis in ngspice is offered by a short script inside of a .control section (see Chapt. 17.8.8) added to the input file. A simple application
(multiple dc sweeps) is shown below.
parameter sweep
* resistive divider, R1 swept from start_r to stop_r
* replaces .STEP R1 1k 10k 1k
R1 1 2 1k
R2 2 0 1k
VDD 1 0 DC 1
.dc VDD 0 1 .1
.control
let start_r = 1k
let stop_r = 10k
let delta_r = 1k
let r_act = start_r
* loop
while r_act le stop_r
alter r1 r_act
run
write dc-sweep.out v(2)
set appendwrite
let r_act = r_act + delta_r
end
plot dc1.v(2) dc2.v(2) dc3.v(2) dc4.v(2) dc5.v(2)
+ dc6.v(2) dc7.v(2) dc8.v(2) dc9.v(2) dc10.v(2)
.endc
.end
Currently we offer only a subset of the documented or undocumented functions (uplim, dnlim, uplim_tanh, dnlim_tanh). More user input is definitely
required here!
This compatibility mode also adds a simple diode using the sidiode code model ( 12.2.32). The diode model
d1 a k ds1
.model ds1 d(Roff=1000 Ron=0.7 Rrev=0.2 Vfwd=1
+ Vrev=10 Revepsilon=0.2 Epsilon=0.2 Ilimit=7 Revilimit=15)
is translated automatically to the equivalent code model diode
ad1 a k ads1
.model ads1 sidiode(Roff=1000 Ron=0.7 Rrev=0.2 Vfwd=1
+ Vrev=10 Revepsilon=0.2 Epsilon=0.2 Ilimit=7 Revilimit=15)
RKM code compatibility:
In LT compatibility mode ngspice will follow the RKM code notation. In addition to the standard notation, resistor (R) and capacitor (C)
values may also be entered according to the following listings (the internally translated value is given after the ;):
R1 1 0 4K7 ; 4.7k
R2 1 0 4R7 ; 4.7
R3 1 0 R47 ; 0.47
R4 1 0 470R ; 470
R5 1 0 47K ; 47k
R6 1 0 47K3 ; 47.3k
R7 1 0 470K ; 470k
R8 1 0 4Meg7 tc1=1e-6 tc2=1e-9 dtemp=6
* ; 4.7Meg <-- Not defined in the RKM notation
R9 1 0 4L7 ; 4.7m
R10 1 0 470L ; 470m
R11 1 0 4M7 ; 4.7m <-- This deviates fom the RKM notation
C1 1 0 4p7 ; 4.7p
C2 1 0 4n7 ; 4.7n
C3 1 0 4u7 ; 4.7u
C4 1 0 4m7 ; 4.7m
C5 1 0 4F7 ; 4.7f <-- This deviates fom the RKM notation
C6 1 0 47p3 ; 4.73p
C7 1 0 470p ; 470p
C8 1 0 4u76 tc1=1e-6 tc2=1e-9 dtemp=6
* ; 4.76u
C9 1 0 4m7 ; 4.7m
C10 1 0 470nF ; 470n
C11 1 0 47fF ; 47f <-- This deviates fom the RKM notation
all letters may be entered upper or lower case, and will internally be transformed to lower case.
m, M always denote milli (1e-3).
f, F denote femto (1e-15), fF will be again femto
meg, Meg denotes mega (1e6)
16.14.7 LTSPICE/PSPICE Compatibility mode
If the variable (17.7) ngbehavior is set to 'ltps' or 'ltpsa' with the commands
set ngbehavior=ltps
or
set ngbehavior=ltpsa
in spinit or .spiceinit, ngspice will translate all files that have been read into ngspice netlist by the .include command (ltps) or the complete netlist
(ltpsa) 16.14.6, 16.14.5 from LTSPICE and PSPICE syntax to ngspice. This feature allows reading of LTSPICE and PSPICE compatible device
libraries or complete netlists.
16.15 Tests
The ngspice distribution is accompanied by a suite of test input and output files, located in the directory ngspice/tests. Originally this suite was
meant to see if ngspice with all models was made and installed properly. It is started by
$ make check
from within your compilation and development shell. A sequence of simulations is thus started, its outputs compared to given output files by
comparisons string by string. This feature is momentarily used to check for some basic procedures and the XSPICE extension (12) as a regression test.
Several other input files located in directory ngspice/tests may serve as light-weight examples for invoking devices and simple circuits.
Today's very complex device models (BSIM3 (11.2.10), BSIM4 (see 11.2.11), HiSIM (see 11.2.14) and others) require a different strategy for
verification. Under development for ngspice is the CMC Regression test by Colin McAndrew, which accompanies every new model. These tests
cover a large range of different DC, AC and noise simulations with different geometry ranges and operating conditions and are more meaningful the
transient simulations with their step size dependencies. A major advantage is the scalability of the diff comparisons, which check for equality within a
given tolerance. A set of Perl modules cares for input, output and comparisons of the models. Currently BSIM3, BSIM4, BSIMSOI4, HICUM2,
HiSIM, and HiSIM_HV models implement the QA test. You may invoke it by running the command given above or by
-i will cause make to ignore any errors, and tee will provide console output as well as printing to file 'results'. Be aware that under MS Windows you
will need the console binary (see 32.2.4) to run the CMC tests, and you have to have Perl installed!
As these tests may consume a considerable amount of CPU time, there is a configure option --enable-shortcheck 32.1.8.1 available, providing a
strongly reduced runtime, because besides some regression tests only BSIM3 and BSM4 devices are checked.
Other tests have been developed, there are also some benchmark circuit compilations available. Please have a look at our Tests and Quality Assurance
web page.
So for now there will be listed here only a few 'tools' offered by ngspice to aid debugging.
Transient simulations are governed by another set of options (see 15.1.4). Careful variation of the parameters, as described in the literature, may
enable convergence in incritical situations (not guaranteed, however).
During a transient simulation a vector 'speedcheck' is generated in the current tran plot. The independent variable is the scale vector 'time', the
dependent variable is the wall clock time with a resolution of about 100 ms. So you may monitor the simulation progress of a (lengthy) transient
simulation and detect critical (simulated) times where the simulation may be slowed down.
16.16.4 miscellaneous
Debugging the equations of a B source are described in chapt. 5.4.
Compiling ngspice with the ./configure flag --enable-ftedebug or (for MS Visual Studio: adding a preprocessor flag FTEDEBUG) will enable some
additional warning messages.
Compiling ngspice with the ./configure flag --enable-stepdebug or (for MS Visual Studio: adding a preprocessor flag STEPDEBUG) yields a very
powerful tool for analysing the steps of a transient simulation. The amount of messages printed however is overwhelming and may be interpreted by
an insider only.
If you happen to experience an error during the usage of ngspice, please send a report to the development team. Ngspice is hosted on SourceForge, the
preferred place to post a bug report is the ngspice bug tracker. We would prefer to have your bug tested against the actual source code available at Git,
but of course a report using the most recent ngspice release is welcome! Please provide the following information with your report:
Ngspice version
Operating system
You may type in expressions, functions (17.2) or commands (17.5) into the input console to elaborate on data already achieved from the interactive
simulation session.
Sequences of commands, functions and control structures (17.6) may be assembled as a script (17.8) into a file, and then activated by just typing the
file name into the console input of an interactive ngspice session.
Finally, and most useful, is to add a script to the input file, in addition the the netlist and dot commands. This is achieved by enclosing the script into
.control ... .endc (see 16.4.3, and 17.8.8 for an example). This feature enables a wealth of control options. You may set internal (17.7) and other
variables, start a simulation, evaluate the simulation output, start a new simulation based on these data, and finally make use of many options for
outputting the data (graphically or into output files).
Historical note: The final releases of Berkeley Spice introduced a command shell and scripting possibilities. The former releases were not interactive.
The choice for the scripting language was an early version of `csh', the C-shell, which was en vogue back then as an improvement over the ubiquitous
Bourne Shell. Berkeley Spice incorporated a modified csh source code that, instead of invoking the unix `exec' system call, executed internal SPICE
C subroutines. Apart from bug fixes, this is still how ngspice works.
One important difference from C-shell is that ngspice does not support multiple commands on one line, separated by ';'. In ngspice, semi-colons
introduce a comment.
The csh-like scripting language is active in .control sections. It works on `strings', and does string substitution of `environment' variables. You see
the csh at work in ngspice with set foo = "bar"; set baz = "bar$foo", and in if, repeat, for, ... constructs. However, ngspice processes mainly
numerical data, and support for this was not available in the c-sh implementation. Therefore, Berkeley implemented an additional type of variables,
with different syntax, to access double and complex double vectors (possibly of length 1). This new variable type is modified with let, and can be
used without special syntax in places where a numerical expression is expected: let bar = 4 * 5; let zoo = bar * 4 works. Unfortunately,
occasionally one has to cross the boundary between the numeric and the string domain. For this purpose the $& construct is available – it queries a
variable in the numerical let domain, and expands it to a c-sh string denoting the value. This lets you do do something like set another = "this
is $&bar". It is important to remember that set can only operate on (c-sh) strings, and that let operates only on numeric data contained in vectors.
Convert from numeric to string with $&, and from string to numeric with $.
An expression is an algebraic formula involving vectors and scalars (a scalar is a vector of length 1) and the following operations:
+ - * / ^ % ,
% is the modulo operator, and the comma operator has two meanings: if it is present in the argument list of a user definable function, it serves to
separate the arguments. Otherwise, the term x , y is synonymous with x + j(y). Also available are the logical operations & (and), | (or), ! (not), and
the relational operations <, >, >=, <=, =, and <> (not equal). If used in an algebraic expression they work like they would in C, producing values of 0
or 1. The relational operators have the following synonyms:
Operator Synonym
gt >
lt <
ge >=
le <=
ne <>
and &
or |
not !
eq =
The operators are useful when < and > might be confused with the internal IO redirection (see 17.4, which is almost always happening). It is however
safe to use < and > with the define command (17.5.16).
Name Function
mag(vector) Magnitude of vector (same as abs(vector)).
ph(vector) Phase of complex vector, in radians.
cph(vector) Phase of complex vector, in radians. Continuous values,
no discontinuity at ±𝜋.
unwrap(vector) Phase of vector with real phase vector in degrees as input
and output. Continuous values, no discontinuity at ±180.
j(vector) i (sqrt(-1)) times vector.
real(vector) The real component of vector.
imag(vector) The imaginary part of vector.
conj(vector) The complex conjugate of a vector
db(vector) 20 log10(mag(vector)).
log10(vector) The logarithm (base 10) of vector.
ln(vector) The natural logarithm (base e) of vector.
exp(vector) e to the vector power.
abs(vector) The absolute value of vector (same as mag).
sqrt(vector) The square root of vector.
sin(vector) The sine of vector.
cos(vector) The cosine of vector.
tan(vector) The tangent of vector.
atan(vector) The inverse tangent of vector.
sinh(vector) The hyperbolic sine of vector.
cosh(vector) The hyperbolic cosine of vector.
tanh(vector) The hyperbolic tangent of vector.
atanh(vector) The inverse hyperbolic tangent of vector.
floor(vector) Largest integer that is less than or equal to vector.
ceil(vector) Smallest integer that is greater than or equal to vector.
norm(vector) The vector normalized to 1 (i.e, the largest magnitude of
any component is 1).
mean(vector) The result is a scalar (a length 1 vector) that is the mean of
the elements of vector (elements values added, divided by
number of elements).
avg(vector) The average of a vector.
Returns a vector where each element is the mean of the
preceding elements of the input vector (including the
actual element).
stddev(vector) The result is a scalar (a length 1 vector) that is the standard
deviation of the elements of vector .
group_delay(vector) Calculates the group delay −𝑑𝑝ℎ𝑎𝑠𝑒[𝑟𝑎𝑑]/𝑑𝜔[𝑟𝑎𝑑/𝑠].
Input is the complex vector of a system transfer function
versus frequency, resembling damping and phase per
frequency value. Output is a vector of group delay values
(real values of delay times) versus frequency.
vector(number) The result is a vector of length number, with elements 0, 1,
... number - 1. If number is a vector then just the first
element is taken, and if it isn't an integer then the floor of
the magnitude is used.
cvector(number) Return a vector of length number, containing complex
elements, with the real part values increasing from 0 to
number-1, the imaginary values are set to 0.
unitvec(number) The result is a vector of length number, all elements
having a value 1.
Name Function
length(vector) The length of vector.
interpolate(plot.vector) The result of interpolating the named vector onto the scale
of the current plot. This function uses the variable
polydegree to determine the degree of interpolation.
integ(vector) Integrates over the given vector (versus the real
component of the scale vector), using the trapeziodal
method. The result is another vector, showing the integral
up to the current scale value. See also 15.4.8 for
measuring the integral sum for a section of a vector, and
12.2.17 for integration on the fly during a transient
simulation.
deriv(vector) Calculates the derivative of the given vector. This uses
deriv(vector) Calculates the derivative of the given vector. This uses
numeric differentiation by interpolating a polynomial. The
degree of the polynomal may be set by the variable
dpolydegree (default is 2). The procedure may not
produce satisfactory results (particularly with iterated
differentiation). The implementation only calculates the
derivative with respect to the real component of that
vector's scale.
vecd(vector) Compute the differential of a vector.
vecmin(vector) Returns the value of the vector element with minimum
value. Same as minimum.
minimum(vector) Returns the value of the vector element with minimum
value. Same as vecmin.
vecmax(vector) Returns the value of the vector element with maximum
value. Same as maximum.
maximum(vector) Returns the value of the vector element with maximum
value. Same as vecmax.
fft(vector) fast fourier transform (17.5.30)
ifft(vector) inverse fast fourier transform (17.5.30)
sortorder(vector) Returns a vector with the positions of the elements in a
real vector after they have been sorted into increasing
order using a stable method (qsort).
timer(vector) Returns CPU-time minus the value of the first vector
element.
clock(vector) Returns wall-time minus the value of the first vector
element.
Several functions offering statistical procedures are listed in the following table:
Name Function
rnd(vector) A vector with each component a random integer between 0
and the absolute value of the input vector's corresponding
integer element value.
sgauss(vector) Returns a vector of random numbers drawn from a
Gaussian distribution (real value, mean = 0 , standard
deviation = 1). The length of the vector returned is
determined by the input vector. The contents of the input
vector will not be used. A call to sgauss(0) will return a
single value of a random number as a vector of length 1.
sunif(vector) Returns a vector of random real numbers uniformly
distributed in the interval [-1 .. 1[. The length of the vector
returned is determined by the input vector. The contents of
the input vector will not be used. A call to sunif(0) will
return a single value of a random number as a vector of
length 1.
poisson(vector) Returns a vector with its elements being integers drawn
An input vector may be either the name of a vector already defined or a floating-point number (a scalar). A scalar will result in an output vector of
length 1. A number may be written in any format acceptable to ngspice, such as 14.6Meg or -1.231e-4. Note that you can either use scientific notation
or one of the abbreviations like MEG or G, but not both. As with ngspice, a number may have trailing alphabetic characters.
The notation expr [num] denotes the num'th element of expr. For multi-dimensional vectors, a vector of one less dimension is returned. Also for
multi-dimensional vectors, the notation expr[m][n] will return the nth element of the mth subvector. To get a subrange of a vector, use the form
expr[lower, upper]. To reference vectors in a plot that is not the current plot (see the setplot command, below), the notation plotname.vecname
can be used. Either a plotname or a vector name may be the wildcard all. If the plotname is all, matching vectors from all plots are specified, and if the
vector name is all, all vectors in the specified plots are referenced. Note that you may not use binary operations on expressions involving wildcards - it
is not obvious what all + all should denote, for instance. Some (contrived) examples of expressions are shown below.
Expressions examples:
cos(TIME) + db(v(3))
sin(cos(log([1 2 3 4 5 6 7 8 9 10])))
TIME * rnd(v(9)) - 15 * cos(vin#branch) ^ [7.9e5 8]
not ((ac3.FREQ[32] & tran1.TIME[10]) gt 3)
(sunif(0) ge 0) ? 1.0 : 2.0
mag(fft(v(18)))
Vector names in ngspice may look like @dname[param], where dname is either the name of a device instance or of a device model. The vector
contains the value of the parameter of the device or model. See Appendix, Chapt. 31 for details of which parameters are available. The returned value
is a vector of length 1. Please note that finding the value of device and device model parameters can also be done with the show command (e.g. show
v1 : dc).
There are a number of pre-defined constants in ngspice, which you may use by their name. They are stored in plot (17.3) const and are listed in the
table below:
𝐽
echarge q (the charge of an electron) 1.60219e-19 C
𝐾
boltz k (Boltzmann's constant) 1.38062e-23
These constants are all given in MKS units. If you define another variable with a name that conflicts with one of these then it takes precedence.
Additional constants may be generated during circuit setup (see .csparam, 2.11).
17.3 Plots
The output vectors of any analysis are stored in plots, a traditional SPICE notion. A plot is a group of vectors. A first tran command will generate
several vectors within a plot tran1. A subsequent tran command will store their vectors in tran2. Then a linearize command will linearize all
vectors from tran2 and store them in tran3, which then becomes the current plot. A fft will generate a plot spec1, again now the current plot. The
display command always will show all vectors in the current plot. Echo $plots followed by Return lists all plots generated so far. Setplot
followed by Return will show all plots and ask for a (new) plot to become current. A simple Return will end the command. Setplot name will change
the current plot to 'name' (e.g. setplot tran2 will make tran2 the current plot). A sequence name.vector may be used to access the vector from a
foreign plot.
You may generate plots by yourself: setplot new will generate a new plot named unknown1, set curplottitle=”a new plot” will set a title, set
curplotname=myplot will set its name as a short description, set curplotdate=”Sat Aug 28 10:49:42 2010” will set its date. Note that strings with
spaces have to be given with double quotes.
Of course the notion 'plot' will be used by this manual also in its more common meaning, denoting a graphics plot or being a plot command. Be
careful to get the correct meaning.
17.4.2 Scripts
If a word is typed as a command, and there is no built-in command with that name, the directories in the sourcepath list are searched in order for a
file with the name given by the word. If it is found, it is read in as a input file (as if it were sourced). Such a file will often be a pure script containing
only interpreter commands. Such files can be written to externd the command set. Full details of scripting are in (17.8).
There are various command scripts installed in /usr/local/lib/spice/scripts (or whatever the path is on your machine), and the default
sourcepath (17.7) includes this directory, so you can use these command files (almost) like built-in commands.
Example:
.control
pre_set strict_errorhandling
unset ngdebug
*save outputs and specials
save x1.x1.x1.7 V(9) V(10) V(11) V(12) V(13)
run
display
* plot the inputs, use offset to plot on top of each other
plot v(1) v(2)+4 v(3)+8 v(4)+12 v(5)+16 v(6)+20 v(7)+24 v(8)+28
* plot the outputs, use offset to plot on top of each other
plot v(9) v(10)+4 v(11)+8 v(12)+12 v(13)+16
.endc
17.5 Commands
Commands marked with a * are only available in ngspice, not in ngnutmeg.
General Form:
Do an small signal ac analysis (see also Chapt. 15.3.1) over the specified frequency range.
OCT stands for octave variation, and N is the number of points per octave.
Note that in order for this analysis to be meaningful, at least one independent source must have been specified with an ac value.
In this ac analysis all non-linear devices are linearized around their actual dc operating point. Each Ls and Cs gets its imaginary value based on the
actual frequency step. Each output vector will be calculated relative to the input voltage (current) given by the ac value (Iin equals to 1 in the example
below). The resulting node voltages (and branch currents) are complex vectors. Therefore you have to be careful using the plot command.
Example:
* AC test
Iin 1 0 AC 1
R1 1 2 100
L1 2 0 1
.control
AC LIN 101 10 10K
plot v(2) $ real part !
plot mag(v(2)) $ magnitude
plot db(v(2)) $ same as vdb(2)
plot imag(v(2)) $ imaginary part of v(2)
plot real(v(2)) $ same as plot v(2)
plot phase(v(2)) $ phase in rad
plot cph(v(2)) $ phase in rad, continuous beyond pi
plot 180/PI*phase(v(2)) $ phase in degrees
set units = degrees
plot phase(v(2)) $ phase in degrees
.endc
.end
In addition to the plot examples given above you may use the variants of vxx(node) described in Chapt. 15.6.2 like vdb(2). If you apply this notion to
another plot ac3, the term vdb(ac3.2) is o.k., however ac3.vdb(2) is not.
An option to suppress OP analysis before AC may be set for linear circuits (15.1.3).
General Form:
Causes word to be aliased to text. History substitutions may be used, as in C-shell aliases.
General Form:
<expression> must be real (complex isn't handled right now, integer is fine though, but no strings. For booleans, use 0/1).
Using the old style, its first form is used by simple devices that have one principal value (resistors, capacitors, etc.) where the second form is for more
complex devices (bjt's, etc.). Model parameters can be changed with the second form if the name contains a `#'. For specifying a list of parameters as
values, start it with `[', followed by the values in the list, and end with `]'. Be sure to place a space between each of the values and before and after the
`[' and `]'.
alter vd = 0.1
alter vg dc = 0.6
alter @m1[w]= 15e-06
alter @vg[sin] [ -1 1.5 2MEG ]
alter @Vi[pwl] = [ 0 1.2 100p 0 ]
You may change a parameter of a device residing in a subcircuit, e.g. of MOS transistor msub1 in subcircuit xm1 (see also Chapt. 31.1).
General form:
Example:
Altermod operates on models and is used to change model parameters. The above example will change the parameter tox in all devices using the
model nc1, which is defined as
*** BSIM3v3 model
.MODEL nc1 nmos LEVEL=8 version = 3.2.2
+ acm = 2 mobmod = 1 capmod = 1 noimod = 1
+ rs = 2.84E+03 rd = 2.84E+03 rsh = 45
+ tox = 20E-9 xj = 0.25E-6 nch = 1.7E+17
+ ...
If you invoke the model by the MOS device
The model parameter tox will be modified, however not only for device M1, but for all devices using the associated MOS model nc1!
If you want to run corner simulations within a single simulation flow, the following option of altermod may be of help. The existing models are
defined during circuit setup at start up of ngspice. Model parameter sets have been included by .model statements (2.4) in your input file or included
by the .include command. The parameter set with name nc1 may be overrun by the altermod command specifying a model file. All parameter
values fitting to the existing model nc1 will be modified. As usual the 'reset' command (see 17.5.62) restores the original values. The model file (see
2.4) has to use the standard specifications for an input file, the .model section is the relevant part. However the first line in the model file will be
ignored by the input parser, so it should contain only some title information. The .model statement should appear then in the second or any later line.
More than one .model section may reside in the file.
General form:
Example:
Be careful that the new model file corresponds to the existing model selected by token nc1. In the example given above, the models nc1 (or nc1 and
pc1) have to be already included in the netlist before calling altermod. If they are not found in the active circuit, ngspice will terminate with an error
message. The file BSIM3_nmos.mod has to include a .model line starting with .MODEL nc1 nmos.... There is no checking however of the version
and level parameters! So you have to be responsible for offering model data of the same model name (nc1) and level (e.g. level 8 for BSIM3). Thus
no new model is selectable by altermod, but the parameters of the existing model(s) (here nc1 and pc1) may be changed (partially, completely,
temporarily).
General form:
alterparam paramname=pvalue
alterparam subname paramname=pvalue
.param npar = 5
...
alterparam npar = 7 $ change npar from 5 to 7
reset
.subckt sname
.param subpar = 13
...
.ends
...
alterparam sname subpar = 11 $ change subpar from 13 to 11
reset
Alterparam operates on global parameters or on parameters in a subcircuit defined by the .param ... statement. A subsequent call to reset
(17.5.62) is required for the parameter value change to become effective.
General Form:
asciiplot plotargs
Produce a line printer plot of the vectors. The plot is sent to the standard output, or you can put it into a file with asciiplot args ... > file. The set
options width, height, and nobreak determine the width and height of the plot, and whether there are page breaks, respectively. The 'more' mode is the
standard mode if printing to the screen, that is after a number of lines given by height, and after a page break printing stops with request for answering
the prompt by <return>, 'c' or 'q'. If everything shall be printed without stopping, put the command set nomoremode into .spiceinit 16.6 (or spinit
16.5). Note that you will have problems if you try to asciiplot something with an X-scale that isn't monotonic (i.e, something like sin(TIME) ),
because asciiplot uses a simple-minded linear interpolation. The asciiplot command doesn't deal with log scales or the delta keywords.
General Form:
Start an ngspice run, and when it is finished load the resulting data. The raw data is kept in a temporary file. If output-file is specified then the
diagnostic output is directed into that file, otherwise it is thrown away.
General Form:
bug
Get URL to file a bug report. Please go the the URL provided by this command when you have a bug report to file. Include a short summary of the
problem, the version number and name of the operating system that you are running, the version of ngspice that you are running, and any relevant
ngspice input and output files.
General Form:
cd [directory]
Change the current working directory to directory, or to the user's home directory (Linux: HOME, MS Windows: USERPROFILE), if none is given.
General Form:
cdump
Dumps the control sequence to the screen (all statements inside the .control ... .endc structure before the line with cdump). Indentations show the
structure of the sequence. The example below is printed if you add cdump to /examples/Monte_Carlo/MonteCarlo.sp.
Example (abbreviated):
let mc_runs=5
let run=0
...
define agauss(nom, avar, sig) (nom + avar/sig * sgauss(0))
define limit(nom, avar) (nom + ((sgauss(0) >=0) ? avar : -avar))
dowhile run < mc_runs
alter c1=unif(1e-09, 0.1)
...
ac oct 100 250k 10meg
meas ac bw trig vdb(out) val=-10 rise=1 targ vdb(out)
+ val=-10 fall=1
set run="$&run"
...
let run=run + 1
end
plot db({$scratch}.allv)
echo
print {$scratch}.bwh
cdump
General Form:
circbyline line
Enter a circuit line by line. line is any circuit line, as found in the *.cir ngspice input files. The first line is a title line. The entry will be finished by
entering .end. Circuit parsing is then started automatically.
Example:
General Form:
Load a XSPICE code model shared library file (e.g. analog.cm ...). Only available if ngspice is compiled with the XSPICE option (--enable-
xspice) or with the Windows executable distributed since ngspice21. This command has to be called from spinit (see Chapt. 16.5) (or .spiceinit for
personal code models, 16.6).
The general form 1 takes the values and creates a new vector, where the values may be arbitrary expressions. If negative numbers or expressions
starting with '-' are to be entered, put them into brackets, e.g. (-2.364) or (-5*PI).
The forms 2 - 5 create a new vector according the following possible parameters:
Form 6 creates a vector fron the saved history of an XSPICE event node with similar results to plotting or printing an event node.
General Form:
Cut out part of each vector of the current tran plot, from times cut-tstart to cut-tstop and copy these into a new tran plot. A new scale vector 'time' will
be generated as well. Vectors that are shorter than the new scale vector will not be copied. If cut-start or cut-stop are not given, the starting or end
times of the current plot are used.
So the simple command cutout may be used to get rid of 0-length vectors in a new tran plot that may occur if for example something like generating
m1[id] is not served in an AC simulation.
General Form:
Do a dc transfer curve analysis. See the previous Chapt. 15.3.2 for more details. Several options may be set (15.1.2).
General Form:
Define the function with the name function and arguments arg1, arg2, ... to be expression, which may involve the arguments. When the function is
later used, the arguments it is given are substituted for the formal parameters when it was parsed. If expression is not present, any existing definition
for function is printed, and if there are no arguments then expressions for all currently active definitions are printed. Note that you may have different
functions defined with the same name but different arities. Some useful definitions are
Example:
When defining the function, the tokens used (here x, y, nom, or avar) should not have been defined elsewhere, e.g. as vectors. Otherwise strange
errors may result.
General Form:
defines types for vectors and plots. abbrev will be used to parse things like abbrev(name) and to label axes with M<abbrev>, instead of numbers.
Also, the command `deftype p plottype pattern ...' will assign plottype as the name for any plot with one of the patterns in its Name: field.
Example:
deftype v capacitance F
settype capacitance moscap
plot moscap vs v(cc)
General Form:
Delete the specified saved nodes and parameters, breakpoints and traces. The debug numbers are those shown by the status command (unless you do
status > file, in which case the debug numbers are not printed).
General Form:
Release the memory holding the output data (the given plot or all plots) for the specified runs. The initial plot, "const", can not be destroyed.
General Form:
Devhelp command shows the user information about the devices available in the simulator. If called without arguments, it simply displays the list of
available devices in the simulator. The name of the device is the name used inside the simulator to access that device. If the user specifies a device
name, then all the parameters of that device (model and instance parameters) will be printed. Parameter description includes the internal ID of the
parameter (id#), the name used in the model card or on the instance line (Name), the direction (Dir) and the description of the parameter
(Description). All the fields are self-explanatory, except the `direction'. Direction can be in, out or inout and corresponds to a `write-only', `read-
only' or a `read/write' parameter. Read-only parameters can be read but not set, write only can be set but not read and read/write can be both set and
read by the user.
The -type option prints the type of each parameter, for example real, integer, string. Values ending with vec indicate vectors.
The -csv option prints the fields, separated by a commas, for direct import into a spreadsheet. This option is used to generate the simulator
documentation.
The -flags option prints the internal Spice flags for each parameter. A specific string is appended to the result for each flag:
X
the parameter is not used in sensitivity analysis.
Q
the parameter must be non-zero for sensitivity analysis of the subsequent parameter.
Z
the previous parameter must be non-zero for sensitivity analysis.
QO
Like Q, but or-ed with the previous Q value.
A
the parameter is significant for time-varying (non-DC) analyses.
P
the parameter is a principal of the device. Used for naming output variables in sensitivity.
AA
the parameter is significant for AC analyses only.
N
the parameter is significant for noise analyses only.
U
the parameter is not shown in the default show command output.
R
redundant parameter name (e.g.vto vs.vt0).
Example:
devhelp
devhelp resistor
devhelp capacitor ic
devhelp -flags -type bjt
General Form:
Compare all the vectors in the specified plots, or only the named vectors if any are given. If there are different vectors in the two plots, or any values
in the vectors differ significantly, the difference is reported. The variables diff_abstol, diff_reltol, and diff_vntol are used to determine a significant
difference.
General Form:
Prints a summary of currently defined vectors, or of the names specified. The vectors are sorted by name unless the variable nosort is set. The
information given is the name of the vector, the length, the type of the vector, and whether it is real or complex data. Additionally, one vector is
labeled [scale]. When a command such as plot is given without a vs argument, this scale is used for the X-axis. It is always the first vector in a
rawfile, or the first vector defined in a new plot. If you undefine the scale (i.e, let TIME = []), one of the remaining vectors becomes the new scale
(which one is unpredictable). You may set the scale to another vector of the plot with the command setscale (17.5.74).
General Form:
Echos all text, variables and vectors to the screen or the redirected output location. If -n included as the first argument, a newline will not be printed.
Otherwise one will be appended to the output.
General Form:
edit [ file-name ]
Print the current ngspice input file into a file, call up the editor on that file and allow the user to modify it, and then read it back in, replacing the
original file. If a file-name is given, then edit that file and load it, making the circuit the current one. The editor may be defined in .spiceinit or spinit
by a command line like
set editor=emacs
Using MS Windows, to allow the edit command calling an editor, you will have to add the editor's path to the PATH variable of the command prompt
windows (see here). edit then calls cmd.exe with e.g. notepad++ and file-name as parameter, if you have set
set editor=notepad++.exe
in .spiceinit or spinit.
General Form:
edisplay
Print the node names, node types, and number of events per node of all event driven nodes generated or used by XSPICE 'A' devices. See eprint,
eprvcd, and 27.2.2 for an example.
General Form:
Print an event driven node generated or used by an XSPICE 'A' device. These nodes are vectors not organized in plots. See edisplay, eprvcd, and
Chapt. 27.2.2 for an example. Output redirection into a file is available.
General Form:
Dump the data of the specified event driven nodes and others to a .vcd file (see also 18.6.1.4). Such files may be viewed with an vcd viewer, for
example gtkwave. Values for analog nodes and expressions (as for plot ) may be included, but expressions may not contain spaces. Option “-t” sets
the VCD file's time unit; values are rounded to a negative power of 10. If not used the unit is chosen to fit the simulation's maximum timestep. Analog
values are examined only when an XSPICE event values changes unless option “-a” is used to dump them at each timestep. Also see edisplay,
eprint.
General Form:
Save a set of event node outputs, discarding the rest (if keyword all is not given). May be used to dramatically reduce memory (RAM) requirements
when only a few useful nodes' events are saved.
For backward compatibility, if there are no esave commands given, all outputs are saved. If you want to eprint (17.5.26) or eprvcd (17.5.27) a node,
you have to save it explicitly, except for all given or no save command at all.
Don't save anything:
esave none
Useful if you do not need to examine the event data separately from the normal plot.
General Form:
fclose handle
This command closes an open file identified by the integer 'handle'. It ignores values less than 3 and any file that was not opened by fopen or read by
fread.
General Form:
This analysis provides a fast Fourier transform of the input vector(s) in forward direction. fft is much faster than spec (17.5.85) (about a factor of 50
to 100 for larger vectors).
The fft command will create a new plot consisting of the Fourier transforms of the vectors given on the command line. Each vector given should be
a transient analysis result, i.e. it should have time as a scale. You will have gotten these vectors by the tran Tstep Tstop Tstart command.
The vector should have a linear equidistant time scale. Therefore linearization using the linearize command is recommended before running fft. Be
careful selecting a Tstep value small enough for good interpolation, e.g. much smaller than any signal period to be resolved by fft (see linearize
command). The Fast Fourier Transform will be computed using a window function as given with the specwindow variable. A new plot named specx
will be generated with a new vector (having the same name as the input vector, see command above) containing the transformed data.
1. Standard code is based on the FFT function provided by John Green `FFTs for RISC 2.0`, downloaded 2012, now to be found here. These
are a power-of-two routines for fft and ifft. If the input size doesn't fit this requirement the remaining data will be zero padded up to the next
2𝑁 field size. You have to take care of the correlated change in the scale vector.
2. If available on the operating system (see Chapter 32) ngspice can be linked to the famous FFTW-3 package, found here. This high
performance package has advantages in speed and accuracy compared to most of the freely available FFT libraries. It makes arbitrary size
transforms for even and odd data.
Linearize will create a new vector V(2) in a new plot tran2. The command fft V(2) will create a new plot spec1 with vector V(2) holding the
resulting data.
The variables listed in the following table control operation of the fft command. Each can be set with the set command before calling fft.
specwindow:
This variable is set to one of the following strings, which will determine the type of windowing used for the Fourier transform in the spec and fft
command. If not set, the default is hanning.
none
No windowing
rectangular
Rectangular window
bartlet
Bartlett (also triangle) window
blackman
Blackman window
hanning
Hanning (also hann or cosine) window
hamming
Hamming window
gaussian
Gaussian window
flattop
Flat top window
This can be set to an integer in the range 2-8. This sets the order when the Gaussian window is used in the spec and fft commands. If not set, order 2
is used.
General Form:
The named file is opened and a numeric handle is returned in variable 'handle', or -1 on error. This is a simple wrapper around the standard C-library
function with the same name, so the meaning of string 'mode' is as defined by your OS documentation. By default the file is opened for reading only.
If interpreter variable "silent_fileio" is set, no message is printed on error.
General Form:
Fourier is used to analyze the output vector(s) of a preceding transient analysis (see 17.5.95). It does a Fourier analysis of each of the given values,
using the first 10 multiples of the fundamental frequency (or the first nfreqs multiples, if that variable is set (see 17.7). The printed output is like that
of the .four ngspice line (Chapt. 15.6.4). The expressions may be any valid expression (see 17.2), e.g. v(2). The evaluated expression values are
interpolated onto a fixed-space grid with the number of points given by the fourgridsize variable, or 200 if it is not set. The interpolation is of degree
polydegree if that variable is set, or 1 otherwise. If polydegree is 0, then no interpolation is done. This is likely to give erroneous results if the time
scale is not monotonic.
The fourier command not only issues a printout, but also generates vectors, one per expression. The size of the vector is 3 x nfreqs (per default 3 x
10). The name of the new vector is fouriermn, where m is set by the mth call to the fourier command, n is the nth expression given in the actual
fourier command. fouriermn[0] is the vector of the 10 (nfreqs) frequency values, fouriermn[1] contains the 10 (nfreqs) magnitude values,
fouriermn[2] the 10 (nfreqs) phase values of the result.
Example:
The plot command from the example plots the vector of the magnitude values, obtained by the first call to fourier and evaluating the first expression
in this call, against the vector of the frequency values.
General Form:
This command sets the string variable 'result' by reading one line from the open file specified by the integer 'handle'. Terminating characters are
stripped and the length returned in variable 'length', if given. The handle will usually have been set by the fopen command, but any valid file
descriptor may be used.
The length will be -1 if attempting to read at end-of-file or -2 on error. If interpreter variable "silent_fileio" is set, no message is printed on error.
General Form:
getcwd
General Form:
Like plot, but using gnuplot for graphics output and further data manipulation. ngspice creates a file called file.plt containing the gnuplot command
sequence, a file called file.data containing the data to be plotted. On Linux, gnuplot may be called directly or via called via xterm, and offers a
Gnuplot console to manipulate the data. On Windows, a plot window is opened and the command console window is available with a mouse click. Of
course you have to have gnuplot installed on your system. Please see chapter 18.7 for more details.
General Form:
Just like plot, except that it creates a file called file containing the plot. Various output formats are available, depending on the variable
hcopydevtype. It may be set to postscript or svg. See also Chapt. 18.6 for more details (color etc.).
General Form:
Print out the history of the last (first if -r is specified) number commands typed at the keyboard.
A history substitution enables you to reuse a portion of a previous command as you type the current command. History substitutions save typing. This
feature is disabled by default, as it may interfere with use of '!' in expressions. To enable, set variable histsubst. A history substitution normally
starts with a '!'. A history substitution has three parts: an event that specifies a previous command, a selector that selects one or more words of the
event, and some modifiers that modify the selected words. The selector and modifiers are optional. A history substitution has the form ![event]
[:]selector[:modifier] …] The event is required unless it is followed by a selector that does not start with a digit. The ':' can be omitted before
the selector if this selector does not begin with a digit. History substitutions are interpreted before anything else — even before quotations and
command substitutions. The only way to quote the '!' of a history substitution is to escape it with a preceding backslash. A '!' need not be escaped
if it is followed by whitespace, '=', or '('.
Ngspice saves each command that you type in a history list, provided that the command contains at least one word. The commands in the history list
are called events. The events are numbered, with the first command that you issue when you start Ngspice being number one. The history variable
specifies how many events are retained in the history list.
!! The preceding event. Typing '!!' is an easy way to reissue the previous command.
!n Event number n.
!-n The nth previous event. For example, !-1 refers to the immediately preceding event and
is equivalent to !!.
!str The unique previous event whose name starts with str.
!?str[?] The unique previous event containing the string str. The closing '?' can be omitted if it
is followed by a newline.
You can modify the words of an event by attaching one or more modifiers. Each modifier must be preceded by a colon. The following modifiers
assume that the first selected word is a file name:
:r Removes the trailing .str extension from the first selected word.
:h Removes a trailing path name component from the first selected word.
:t Removes all leading path name components from the first selected word.
:e Remove all but the trailing suffix.
:p Print the new command but do not execute it.
s/old/new Substitute new for the first occurrence of old in the event line. Any delimiter may be
used in place of `/'. The delimiter may be quoted in old and new with a single
backslash. If `&' appears in new, it is replaced by old. A single backslash will quote the
`&'. The final delimiter is optional if it is the last character on the input line.
& Repeat the previous substitution.
g a Cause changes to be applied over the entire event line. Used in conjunction with `s', as
in gs/old/new/, or with `&'.
G Apply the following `s' modifier once to each word in the event.
For example, if the command ls /usr/elsa/toys.txt has just been executed, then the command echo !!^:r !!^:h !!^:t !!^:t:r produces the output
/usr/elsa/toys /usr/elsa toys.txt toys . The '^' command is explained in the table below.
You can select a subset of the words of an event by attaching a selector to the event. A history substitution without a selector includes all of the words
of the event. These are the possible selectors for selecting words of the event:
The colon preceding a selector can be omitted if the selector does not start with a digit.
The following additional special conventions provide abbreviations for commonly used forms of history substitution:
An event specification can be omitted from a history substitution if it is followed by a selector that does not start with a digit. In this case the
event is taken to be the event used in the most recent history reference on the same line if there is one, or the preceding event otherwise. For
example, the command echo !?qucs?^ !$ echoes the first and last arguments of the most recent command containing the string qucs .
If the first non-blank character of an input line is '^', the '^' is taken as an abbreviation for !:s^ . This form provides a convenient way to
correct a simple spelling error in the previous line. For example, if by mistake you typed the command cat /etc/lasswd you could re-
execute the command with lasswd changed to passwd by typing ^l^p .
You can enclose a history substitution in braces to prevent it from absorbing the following characters. In this case the entire substitution
except for the starting '!' must be within the braces. For example, suppose that you previously issued the command cp accounts ../money .
Then the command !cps looks for a previous command starting with cps while the command !{cp}s turns into a command cp accounts
../moneys .
Some characters are handled specially as follows:
The wildcard characters *, ?, [, and ] can be used, but only if you unset noglob first. This makes them rather useless for typing algebraic expressions,
so you should set noglob again after you are done with wildcard expansion.
When the environment variable HOME exists (on Unix, Linux, or CYGWIN), history permanently stores previous command lines in the file
$HOME/._ngspice_history. When this variable does not exist (typically on Windows when the readline library is not officially installed), the history
file is called .history and put in the current working directory.
The history command is part of the readline or editline package. The readline program provides a command line editor that is configurable through
the file .inputrc. The path to this configuration file is either found in the shell variable INPUTRC, or it is (on Unix/Linux/CYGWIN) the file
~/.inputrc in the user's home directory. On Windows systems, the configuration file is /Users/<username>/.inputrc, unless the readline library was
officially installed. In that case the filename is taken from the Windows registry and points to a location that the user specified during installation. See
https://web.archive.org/web/20190527085247/https://tiswww.case.edu/php/chet/readline/rltop.html for detailed documentation. Some useful
commands are below.
General Form:
inventory
This commands accepts no argument and simply prints the number of instances of a particular device in a loaded netlist.
General Form:
Incrementally plot the values of the nodes while ngspice runs. The iplot command can be used with the where command to find trouble spots in a
transient simulation. The “-d” options sets the delay (in simulation steps) between the start of the simulation and the appearance of the window. It can
be used to suppress flicker when new values cause rapid resizing at the start of the simulation. The “-w” option sets a fixed width for the window in
simulation units (time, frequency etc). When the output does not fit, only the latest output values are shown.
The @name[param] notation (31.1) and XSPICE event nodes do not work yet.
General Form:
jobs
Report on the asynchronous ngspice jobs currently running. Ngnutmeg checks to see if the jobs are finished every time you execute a command. If it
is done then the data is loaded and becomes available.
General Form:
Creates a new vector called name with the value specified by expr, an expression as described above. If expr is [] (a zero-length vector) then the
vector becomes undefined. Individual elements of a vector may be modified by appending a subscript to name (ex. name[0]). If there are no
arguments, let is the same as display.
The command let creates a vector in the current plot. Use setplot (17.5.73) to create a new plot.
There is no straightforward way to initialize a new vector. In general, one might want to have let initialize a slice (i.e. name[4:4,21:23] = [ 1 2 3 ]) of
a multi-dimensional matrix of arbitrary type (i.e. real, complex ..), where all values and indexes are arbitrary expressions. This will fail. The
procedure is to first allocate a real vector of the appropriate size with either vector(), unitvec(), or [ n1 n2 n3 ... ]. The second step is to
optionally change the type of the new vector (to complex) with the j() function. The third step reshapes the dimensions, and the final step
(re)initializes the contents, like so:
let a = j(vector(10))
reshape a [2][5]
let a[0][0] = (pi,pi)
Initialization of real vectors can be done quite efficiently with compose:
General Form:
Create a new plot with all of the vectors in the current plot, or only those mentioned as arguments to the command, all data linearized onto an
equidistant time scale.
Linearize will redo the vectors vec or renew all vectors of the current plot (e.g. tran3) if no arguments are given and store them into a new plot (e.g.
tran4). The new vectors are interpolated onto a linear time scale, which is determined by the values of tstep, tstart, and tstop in the currently
active transient analysis. The currently loaded input file must include a transient analysis (a tran command may be run interactively before the last
reset, alternately), and the current plot must be from this transient analysis. The length of the new vector is floor((tstop - tstart) / tstep +
1.5). This command is needed for example if you want to do an FFT analysis (17.5.30). Please note that the parameter tstep of your transient
analysis (see Chapt. 15.3.10) has to be small enough to get adequate resolution, otherwise the command linearize will do sub-sampling of your
signal. If no circuit is loaded and the data have been acquired by the load (17.5.45) command, Linearize will take time data from transient analysis
scale vector.
The linearize command may be used to create a linearized cutout of the original vector by defining the vectors lin-tstart, lin-tstop, and lin-
tstep before issuing the linearize command. At least lin-tstart or lin-tstop has to be defined. This may be used to plot just a portion of a
vector, or to prepare a better fft by skipping the start-up phase of a ring oscillator.
The linearize command should explicitly name the vectors of interest. Otherwise warning messages pop up that the vectors lin-tstart etc cannot be
linearized.
General Form:
If the logical argument is given, the listing is with all continuation lines collapsed into one line, and if the physical argument is given the lines are
printed out as they were found in the file. The default is logical. A deck listing is just like the physical listing, except without the line numbers it
recreates the input file verbatim (except that it does not preserve case). If the word expand is present, the circuit is printed with all subcircuits
expanded. Argument runnable will list the circuit netlist expanded, but without additional line numbers, ready to be sourced again and run in ngspice.
The option param allows printing all parameters and their actual values.
Example:
source d:\myngspice\inputs\decade_counter.cir
listing r > $inputdir/decade_counter_runnable.cir
All options (except for param) may be invoked by just entering their first letter. The example sources a ngspice netlist, the listing r command will
save the expanded netlist (all parameters evaluated, subcircuits flattened, .control sections removed) into a file within the same directory.
If you are using CIDER (30), listing r will not create a runnable netlist, because some data lines which have been created internally are missing.
General Form:
Loads either binary or ascii format rawfile data from the files named. The default file name is rawspice.raw, or the argument to the -r flag if there was
one.
General Form:
mc_source
Upon reading a netlist, after its preprocessing is finished, the modified netlist is stored internally. This command will reload this netlist and create a
new circuit inside ngspice. This command is used in conjunction with the alterparam command.
Most of the input forms found in 15.4 may be used here with the command meas instead of .meas(ure). Using meas inside the .control ... .endc
section offers additional features compared to the .meas use. meas will print the results as usual, but in addition will store its measurement result
(typically the token result given in the command line) in a vector. This vector may be used in following command lines of the script as an input
value of another command. For details of the command see Chapt. 15.4. The measurement type SP is only available here, because a fft command
will prepare the data for SP measurement. Option autostop (15.1.4) is not available.
Unfortunately par('expression') (15.4.10, 15.6.6) and param (15.4.9) will not work here, i.e. inside the .control section. You may use an expression
by the let command (17.5.42) instead, giving let vec_new = expression.
General Form:
mdump <filename>
If <filename> is given, the output will be stored in file <filename>, otherwise dumped to your console.
17.5.49 Mrdump*: Dump the matrix right hand side values to a file (or to console)
General Form:
mrdump <filename>
If <filename> is given, the output will be appended to file <filename>, otherwise dumped to your console.
You may create a loop using the control structures (Chapt. 17.6).
The noise command will generate two plots (typically named noise1 and noise2) with Noise Spectral Density Curves and Integrated Noise data. To
write these data into output file(s), you may use the following command sequence:
.control
tran 1e-6 1e-3
write test_tran.raw
noise V(out) vinp dec 333 1 1e8 16
print inoise_total onoise_total
*first option to get all of the output (two files)
setplot noise1
write test_noise1.raw all
setplot noise2
write test_noise2.raw all
* second option (all in one raw-file)
write testall.raw noise1.all noise2.all
.endc
General Form:
op
General Form:
Set any of the simulator variables as listed in Chapt. 15.1. See this chapter also for more information on the available options. The option command
without any argument lists the current options set in the simulator. It shows the current options, while new values are set to be used in the next
analysis run. That means that changed options will not be visible immediately. Multiple options may be set in a single line.
The following example demonstrates a control section, which may be added to your circuit file to test the influence of variable trtol on the number of
iterations and on the simulation time.
.control
set noinit
option trtol=1
echo
echo trtol=1
run
rusage traniter trantime
reset
option trtol=3
echo
echo trtol=3
run
rusage traniter trantime
reset
option trtol=5
echo
echo trtol=5
run
rusage traniter trantime
reset
option trtol=7
echo
echo trtol=7
run
rusage traniter trantime
plot tran1.v(out25) tran1.v(out50) v(out25) v(out50)
.endc
General Form:
Plot the given vectors or exprs on the screen (if you are on a graphics terminal). The xlimit and ylimit arguments determine the high and low x- and
y-limits of the axes, respectively. The xindices arguments determine what range of points are to be plotted - everything between the xilo'th point
and the xihi'th point is plotted. The xcompress argument specifies that only one out of every comp points should be plotted. If an xdelta or a ydelta
parameter is present, it specifies the spacing between grid lines on the X- and Y-axis. These parameter names may be abbreviated to xl, yl, xind,
xcomp, xdel, and ydel respectively.
The scal_expr argument(s) are expressions to use as the scale on the x-axis instead of the default scale for the plot. If xlog or ylog are present, then
the X or Y scale, respectively, are logarithmic (loglog is the same as specifying both). The xlabel and ylabel arguments cause the specified labels
to be used for the X and Y axes, respectively.
If samep is given, the values of the other parameters from the previous plot, hardcopy, or asciiplot command are used even if they are redefined
on the command line.
The title argument is used in the headline of the plot window and replaces the default text, which is `actual plot: first line of input file'.
The linear keyword is used to override a default logscale plot (as in the output for an AC analysis).
The keywords linplot, combplot and pointplot select different plot styles. The keyword nointerp turns off interpolation of the vector data, nogrid
suppresses the drawing of gridlines. retraceplot may be required if the scale vector (the x axis) has values which do not grow monothonically (e.g.
plotting a circle or the hyseresis loop of a memristor). Without this keyword retracing values (x values moving forth and back) are suppressed.
Finally, the keyword polar generates a polar plot. To produce a Smith plot, use the keyword smith. Note that the data is transformed, so for Smith
2 2
plots you will see the data a + jb transformed to
𝑎 = (𝑎2 + 𝑏2 − 1) / ((𝑎 + 1) + 𝑏2 ) 𝑏 = (2 * 𝑏)/((𝑎 + 1) + 𝑏2 )
To produce a polar plot with a Smith grid but without performing the Smith transform, use the keyword smithgrid.
Keyword retraceplot may be useful if the x-axis values are non-monotonic. Whereas time is always growing monotonically, during plotting ynew
vs xnew xnew may partially increase, then decrease again. If this occurs, plotting is suppressed as per default. retraceplot will enable plotting all
data.
If you specify plot all, all vectors (including the scale vector) are plotted versus the scale vector (see commands display (17.5.22) or setscale
(17.5.74) on viewing the vectors of the current plot). The command plot ally will not plot the scale vector, but all other 'real' y values. The
command plot alli selects all current vectors, the command plot allv all voltage vectors.
If the vector name to be plotted contains - , / or other tokens that may be taken for operators of an expression, and plotting fails, try enclosing the
name in double quotes, e.g. plot “/vout”.
Plotting of complex vectors, as may occur after an ac simulation, requires special considerations. Please see Chapt. 17.5.1 for details.
Keyword kicad will enable plotting vectors with leading character / (see 16.14.8) by placing double quotes around the token, keyword plainplot
will allow this by suppressing the evaluation of any expression containing such characters. vc1 vs vc2 is not supported with using plainplot. The
same effect may be generated by setting the variable plainplot.
digitop will assemble all digital (event) nodes into a single graph, arranged on top of each other.
Plot all analog nodes [all], all voltage nodes only [allv], all current nodes, [alli], all nodes except for the scale [ally], all event nodes [alle].
General Form:
pre_<command>
All commands in a .control ... .endc section are executed after the circuit has been parsed. If you need command execution before circuit parsing,
you may add these commands to the general spinit or local .spiceinit files. Another possibility is adding a leading pre_ to a command within the
.control section of an ordinary input file, which forces the command to be executed before circuit parsing. Basically <command> may be any
command listed in Chapt. 17.5, however only a few commands are indeed useful here. Some examples are given below:
Examples:
pre_unset ngdebug
pre_set strict_errorhandling
pre_codemodel mymod.cm
pre_<command> is available only in the .control mode (see 16.4.3), not in interactive mode, where the user may determine when a circuit is to be
parsed, using the source command (17.5.83) .
Examples:
General Form:
Prints the vector(s) described by the expression expr. If the col argument is present, print the vectors named side by side. If line is given, the
vectors are printed horizontally. col is the default, unless all the vectors named have a length of one, in which case line is the default. The options
width (default 80) and height (default 24) are effective for this command (see asciiplot 17.5.6). The 'more' mode is the standard mode if printing
to the screen, that is after a number of lines given by height, and after a page break printing stops with request for answering the prompt by <return>
(print next page), 'c' (print rest) or 'q' (quit printing). If everything shall be printed with stopping after each page (only useful in interactive mode,
because need manual continuation), use the command set moremode before printing or put it into .spiceinit 16.6 (or spinit 16.5). If the expression is
all, all of the vectors available are printed. Thus print col all > filename prints everything into the file filename in SPICE2 format. The scale
vector (time, frequency) is always in the first column unless the variable noprintscale is true. You may use the vectors alli, allv, ally with the
print command, but then the scale vector will not be printed.
Examples:
print all
set width=300
print v(1) > outfile.out
General Form:
Calculate the single sided power spectral density of signals (vectors) resulting from a transient analysis. Windowing is available as described in the fft
command (17.5.30). The FFT data are squared, summarized, weighted and printed as total noise power up to Nyquist frequency, and as noise voltage
or current.
ave is the number of points used for averaging and smoothing in a postprocess, useful for noisy data. A new plot vector is created that holds the
averaged results of the FFT, weighted by the frequency bin. The result can be plotted and has the units V^2/Hz or A^2/Hz, depending on the the input
vector.
quit
quit [exitcode]
Quit ngspice. Ngspice will ask for an acknowledgment if parameters have not been saved. If unset askquit is specified, ngspice will terminate
immediately.
The optional parameter exitcode is an integer that sets the exit code for ngspice. This is useful to return a success/fail value to the operating system.
General Form:
rehash
Recalculate the internal hash tables used when looking up UNIX commands, and make all UNIX commands in the user's PATH available for
command completion. This is useless unless you have set unixcom first (see above).
General Form:
remcirc
This command removes the current circuit from the list of circuits sourced into ngspice. To select a specific circuit, use setcirc (17.5.72). To load
another circuit, refer to source (17.5.83). The new active circuit will be the circuit on top of the list of the remaining circuits.
General Form:
remzerovec
This command removes vectors of length zero from the current plot.
General Form:
reset
Throw out any intermediate data in the circuit (e.g, after a breakpoint or after one or more analyses have been done), and re-parse the input file. The
circuit can then be re-run from it's initial state, overriding the effect of any set or alter commands. These two need to be repeated after the reset
command.
Reset may be required in simulation loops preceding any run (or tran ...) command.
Reset is required after an alterparam command (17.5.5) for making the parameter change effective.
General Form:
This command changes the dimensions of a vector or a set of vectors. The final dimension may be left off and it will be filled in automatically. If no
dimensions are specified, then the dimensions of the first vector are copied to the other vectors. An error message of the form 'dimensions of x were
inconsistent' can be ignored.
Example:
General Form:
resume
General Form:
Runs a ngspice remotely taking the input file as a ngspice input file, or the current circuit if no argument is given. Ngspice waits for the job to
complete, and passes output from the remote job to the user's standard output. When the job is finished the data is loaded in as with aspice. If the
variable rhost is set, ngnutmeg connects to this host instead of the default remote ngspice server machine. This command uses the rsh command and
thereby requires authentication via a .rhosts file or other equivalent method. Note that rsh refers to the `remote shell' program, which may be remsh
on your system; to override the default name of rsh, set the variable remote_shell. If the variable rprogram is set, then rspice uses this as the
pathname to the program to run on the remote system.
Note: rspice will not acknowledge elements that have been changed via the alter or altermod commands.
General Form:
run [rawfile]
Run the simulation as specified in the input file. If there were any of the control lines .ac, .op, .tran, or .dc, they are executed. The output is put in
rawfile if it was given, in addition to being available interactively.
General Form:
Print resource usage statistics. If any resources are given, just print the usage of that resource. Most resources require that a circuit be loaded.
Currently valid resources are
time
Total Analysis Time
cputime
The amount of time elapsed since the last rusage cputime call.
totalcputime
Total elapsed time used so far.
decklineno
Number of lines in deck
netloadtime
Nelist loading time
netparsetime
Netlist parsing time
faults
Number of page faults and context switches (BSD only).
space
Data space used (output is depending on the operating system).
temp
Operating temperature.
tnom
Temperature at which device parameters were measured.
equations
Number of circuit equations
totiter
Total iterations
accept
Accepted time-points
rejected
Rejected time-points
loadtime
Time spent loading the circuit matrix and RHS.
reordertime
Matrix reordering time
lutime
L-U decomposition time
solvetime
Matrix solve time
trantime
Transient analysis time
tranpoints
Transient time-points
traniter
Transient iterations
trancuriters
Transient iterations for the last time point
tranlutime
Transient L-U decomposition time
transolvetime
Transient matrix solve time
everything
All of the above.
all
All of the above.
If rusage is given without any parameter, a sequence of outputs is printed using the following rusage parameters: time, totalcputime, space.
General Form:
Save a set of outputs, discarding the rest (if keyword all is not given). May be used to dramatically reduce memory (RAM) requirements if only a few
useful node voltages or branch currents are saved.
Node voltages may be saved by giving the nodename or v(nodename). Currents through an independent voltage source are given by i(sourcename) or
sourcename#branch. Internal device data (31.1) are accepted as @dev[param]. The syntax is identical to the .save command (15.6.1).
Note: In the .control .... .endc section save must occur before the run or tran command to become effective.
If a node has been mentioned in a save command, it appears in the working plot after a run has completed, or in the rawfile written by the write
(17.5.104) command. For backward compatibility, if there are no save commands given, all outputs are saved. If you want to trace (17.5.94) or plot
(17.5.53) a node, you have to save it explicitly, except for all given or no save command at all.
When the keyword all appears in the save command, all node voltages, voltage source currents and inductor currents are saved in addition to any
other vectors listed.
Save allows storing and later access of internal device parameters. e.g. in a command like
saves all standard analysis output data plus gm of transistor mn1 to internal memory (see also 31.1).
save may store data from nodes or devices residing inside of a subcircuit:
Save voltage on node 3 (top level), node 8 (from inside subcircuit x2) and current through vmeas (from subcircuit x1):
save @m.xmos3.mn1[gm]
Use commands listing expand (17.5.44, before the simulation) or display (17.5.22, after simulation) to obtain a list of all nodes and currents
available. Please see Chapt. 31 for an explanation of the syntax for internal parameters.
Entering several save lines in a single .control section will accumulate the nodes and parameters to be saved. If you want to exclude a node, you
have to get its number by calling status (17.5.86) and then calling delete number (17.5.18).
save none
Useful if shared ngspice library is used and data are immediately transferred to the caller via the shared ngspice interface.
General Form:
sens output_variable
sens output_variable ac ( DEC | OCT | LIN ) N Fstart Fstop
Perform a Sensitivity analysis. output_variable is either a node voltage (ex. v(1) or v(A,out)) or a current through a voltage source (e.g.
i(vtest)). The first form calculates DC sensitivities, the second form AC sensitivities. The output values are in dimensions of change in output per
unit change of input (as opposed to percent change in output or per percent change of input).
General Form:
set [word]
set [word = value] ...
set [word = ( list of values )] ...
Set the value of word to value, if it is present. You can set any word to be any value: numeric, string or list. If no value is given then the value is the
Boolean `true'. If you enter a string, you have to enclose it in double quotes. Set saves the lower case version of a word string but the setcs variant of
the command preserves case. If a variable is set to a list of values that are enclosed in parentheses (which must be separated from their values by
white space), the value of the variable is the list.
The value of word may be inserted into a command by writing $word,or $word[index]for an individual list element. The index may itself be a
substitution: $word[$index].
If a variable has the same name as a simulator option, setting it will also attempt to set the option.
Set entered without any parameter will list all variables set, and their values, if applicable.
Be advised that set sets the lower case variant of word. An exceptions to this rule is the variable sourcepath.
Set automatically tries to distinguish between values given as numbers, strings or lists. If a string starts with a numerical value, like 2N5401_C and is
not enclosed in double quotes, it is interpreted as a real number 2n, i.e. 2e-9. The rest of the string is discarded.
Example:
infile.txt:
Another option to set a variable from outside is the I/O redirection by backquotes or backticks (see 17.10), if you run ngspice as a console application.
General Form:
setcs [word]
setcs [word = value] ...
Set the value of word to value, if it is present. You can set any word to be any value, numeric or string. If no value is given then the value is the
Boolean `true'. If you enter a string, you have to enclose it in double quotes. Setcs keeps the case of a word string.
The value of word may be inserted into a command by writing $word. If a variable is set to a list of values that are enclosed in parentheses (which
must be separated from their values by white space), the value of the variable is the list.
Setcs entered without any parameter will list all variables set, and their values, if applicable.
Setcs automatically tries to distinguish between values given as numbers, strings or lists. If a string starts with a numerical value, like 2N5401_C and
is not enclosed in double quotes, it is interpreted as a real number 2n, i.e. 2e-9. The rest of the string is discarded.
General Form:
The current circuit is the one that is used for the simulation commands below. When a circuit is loaded with the source command (see below, 17.5.83)
it becomes the current circuit.
Setcirc followed by 'return' without any parameters lists all circuits loaded.
General Form:
setplot
setplot [plotname]
setplot previous
setplot next
setplot new
Set the current plot to the plot with the given name, or if no name is given, prompt the user with a list of all plots generated so far. (Note that the plots
are named as they are loaded, with names like tran1 or op2. These names are shown by the setplot and display commands and are used by diff,
below.) If the `New' item is selected, a new plot is generated that has no vectors defined.
Note that here the word plot refers to a group of vectors that are the result of one ngspice run. When more than one file is loaded in, or more than one
plot is present in one file, ngspice keeps them separate and only shows you the vectors in the current plot with the display (17.5.22) command.
setplot previous will show the previous plot in the plot list, if available, setplot next the next plot. If not available, a warning is issued and the
current plot stays active. Setplot will also allow selecting the digital event nodes that have been created during the simulation that made the analog
plot.
17.5.74 Setscale: Set the scale vector for the current plot
General Form:
The scale vector provides the values for the x-axis in a 2D plot. If no argument is given, the current scale vector is printed. With one argument,
defines the default scale vector for the current plot. With two arguments, sets the specific scale vector of vector1 to be vector2. If vector2 is “none”
the scale vector for vector1 reverts to the plot's default.
17.5.75 Setseed: Set the seed value for the random number generator
General Form:
setseed [number]
When this command is given, the seed value for the random number generator is set to number. Number has to be an integer greater than 0. The
random numbers retrieved after this command are a sequence of pseudo random numbers with a huge period. Setting the seed value will provide a
reproducible sequence of random numbers, i.e. the same seed results in the same sequence. See also the options SEED and SEEDINFO in chapt.
15.1.1and chapt. 22 on statistical circuit analysis..
General Form:
Change the type of the named vectors to type. Type names can be found in the following table.
General Form:
shell [ command ]
Call the operating system's command interpreter; execute the specified command or call for interactive use. The status returned by the command is
stored in variable shellstatus.
General Form:
If varname is the name of a list variable, it is shifted to the left by number elements (i.e, the number leftmost elements are removed). The default
varname is argv, and the default number is 1.
General Form:
The show command prints out tables summarizing the operating condition of selected devices. If devices is missing, a default set of devices are
listed, if devices is a single letter, devices of that type are listed. A device's full name may be specified to list only that device. Finally, devices may
be selected by model by using the form #modelname.
Because the output format is tabular, long strings, including device names, may be truncated. The command “set altshow” selects an alternative
output format without truncations.
If no parameters are specified, the values for a standard set of parameters are listed. If the list of parameters contains a `+', the default set of
parameters is listed along with any other specified parameters.
For both devices and parameters, the word all has the obvious meaning.
Note: there must be spaces around the `:' that divides the device list from the parameter list.
General Form:
The showmod command operates like the show command (above) but prints out model parameter values. The applicable forms for models are a single
letter specifying the device type letter (e.g. m, or c), a device name (e.g. m.xbuf22.m4b), or #modelname (e.g. #p1).
Note: there must be spaces around the `:' that divides the device list from the parameter list.
op is required to set the data (otherwise all reported values are 0). The combination of the default parameters and the parameters given in the .model
line (This is what the simulator finally uses.) are obtainable by showmod only after a simulation command (e.g. op).
General Form:
snload reads the snapshot file generated by snsave (17.5.82). circuit-file is the original circuit input file. After reading, the simulation may be
continued by resume (17.5.64).
An input script for loading circuit and intermediate data, resuming simulation and plotting is shown below:
Typical usage:
.control
* cd to where all files are located
cd D:\Spice_general\ngspice\examples\snapshot
* load circuit and snpashot file
snload adder_mos_circ.cir adder500.snap
* continue simulation
resume
* plot some node voltages
plot v(10) v(11) v(12)
.endc
Due to a bug we currently need the term 'script' in the title line (first line) of the script.
General Form:
snsave file
If you run a transient simulation and interrupt it by e.g. a stop breakpoint (17.5.88), you may resume simulation immediately (17.5.64) or store the
intermediate status in a snapshot file by snsave for resuming simulation later (using snload (17.5.81)), even with a new instance of ngspice.
Typical usage:
.include adder_mos_circ.cir
.control
*cd to where all files are located
cd D:\Spice_general\ngspice\examples\snapshot
unset askquit
set noinit
*interrupt condition for the simulation
stop when time > 500n
* simulate
run
* store snapshot to file
snsave adder500.snap
quit
.endc
.END
adder_mos_circ.cir is a circuit input file, including the netlist, .model and .tran statements.
Unfortunately snsave/snload will not work if you have XSPICE devices (or V/I sources with polynomial statements) in your input deck.
General Form:
source infile
For ngspice: read the ngspice input file infile, containing a circuit netlist. Ngspice control commands may be included in the file, and must be
enclosed between the lines .control and .endc. These commands are executed immediately after the circuit is loaded, so a control line of ac ...
works the same as the corresponding .ac card. The first line in any input file is considered a title line and not parsed but kept as the name of the
circuit. Thus, a ngspice command script in infile must begin with a blank line and then with a .control line. Also, any line starting with the string
`*#' is considered as a control line (.control and .endc is placed around this line automatically.). The exception to these rules are the files spinit
(16.5) and .spiceinit (16.6).
For ngutmeg: reads commands from the file infile. Lines beginning with the character `*' are considered comments and are ignored.
The following search path is executed to find infile: current directory (OS dependent), <prefix>/share/ngspice/scripts, env. variable
NGSPICE_INPUT_DIR (if defined), see 16.7. This sequence may be overridden by setting the internal sourcepath variable (see 17.7) before calling
source infile.
General form:
Examples:
sp dec 10 1 10K
sp dec 10 1K 100MEG 1
sp lin 100 1 100HZ
For details please see chapter 15.3.8. the ports required are available as an option to the independent voltage source VSRC (see4.1.11 ).
General Form:
Calculates a new complex vector containing the Fourier transform of the input vector (typically the linearized result of a transient analysis). The
default behavior is to use a Hanning window, but this can be changed by setting the variables specwindow and specwindoworder appropriately.
Typical usage:
Possible values for specwindow are none, hanning, cosine, rectangular, hamming, triangle, bartlet, blackman, gaussian and flattop. In
the case of a Gaussian window specwindoworder is a number specifying its order. For a list of window functions see 17.5.30.
General Form:
status
Display all of the saved nodes and parameters, traces and breakpoints currently in effect.
General Form:
step [ number ]
General Form:
Set a breakpoint. The argument after n means stop after iteration number `n', and the argument when value cond value means stop when the first
value is in the given relation with the second value, the possible relations being
Symbol or alias may be used alternatively. All stop commands have to be given in the control flow before the run command. The values above may
be node names in the running circuit, or real values. If more than one condition is given, e.g.
the conjunction of the conditions is implied. If the condition is met, the simulation and control flow are interrupted, and ngspice waits for user input.
In a transient simulation the `=' or eq will only work with vector time in commands like
Internally, a breakpoint will be set at the time requested. Multiple breakpoints may be set. If the first stop condition is met, the simulation is
interrupted, the commands following run or tran (e.g. alter or altermod) are executed, then the simulation may continue at the first resume
command. The next breakpoint requires another resume to continue automatically. Otherwise the simulation stops and ngspice waits for user input.
(or similar) during a transient simulation, you probably will miss this point, because it is not very likely that at any time step the vector v(1) will have
the exact value of 1. Then ngspice simply will not stop.
General Form:
The command compares two strings, either given by a variable (string1) or as a string in quotes (`string2'). _flag is set as an output variable to '0', if
both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; and a
value less than zero indicates the opposite (like the C strcmp function).
General Form:
This command sets variable 'result' to be a portion of string 'input' starting at the given offset and with the requested length. Offset and length should
be integers. If offset is negative, it is counted from the end of the input string.
General Form:
The command searches string variable 'haystack' for a copy of string 'needle'. If successful, variable 'result' is set to the offset of the first match.
Otherwise, the result is -1. As a special case, if 'needle' is the empty string, the result is the length of $haystack.
General Form:
sysinfo
The command prints system information useful for sending bug report to developers. Information consists of
This command has been tested under Windows OS and Linux. It may not be available in your operating system environment.
General Form:
tf output_node input_source
* Tf test circuit
vs 1 0 dc 5
r1 1 2 100
r2 2 3 50
r3 3 0 150
r4 2 0 200
.control
tf v(3,5) vs
print all
.endc
.end
transfer_function = 3.750000e-001
output_impedance_at_v(3,5) = 6.662500e+001
vs#input_impedance = 2.000000e+002
17.5.94 Trace*: Trace nodes
General Form:
For every step of an analysis, the value of the node is printed. Several traces may be active at once. Tracing is not applicable for all analyses. To
remove a trace, use the delete (17.5.18) command.
General Form:
Perform a transient analysis. See Chapt. 15.3.10 of this manual for more details.
An interactive transient analysis may be interrupted by issuing a ctrl-c (control-C) command. The analysis then can be resumed by the resume
command (17.5.64). Several options may be set to control the simulation (15.1.4).
General Form:
This command transposes a multidimensional vector. No analysis in ngspice produces multidimensional vectors, although the DC transfer curve may
be run with two varying sources. You must use the reshape command to reform the one-dimensional vectors into two dimensional vectors. In
addition, the default scale is incorrect for plotting. You must plot versus the vector corresponding to the second source, but you must also refer only to
the first segment of this second source vector. For example (circuit to produce the transfer characteristic of a MOS transistor):
General Form:
General Form:
Definitions for the named user-defined functions are deleted. If * is given, all user-defined functions are deleted.
General Form:
General Form:
Clear the value of the specified variable(s) (word). If * is specified, all variables are cleared.
General Form:
Print out the version of ngspice that is running, if invoked without argument or with -s or -f. If the argument is a <version id> (any string different
from -s or -f is considered a <version id> ), the command checks to make sure that the arguments match the current version of ngspice. (This is
mainly used as a Command: line in rawfiles.)
Options description:
No option: The output of the command is the message you can see when running ngspice from the command line, no more no less.
-s(hort): A shorter version of the message you see when calling ngspice from the command line.
-f(ull): You may want to use this option if you want to know what extensions are included into the simulator and what compilation switches
are active. A list of compilation options and included extensions is appended to the normal (not short) message. May be useful when sending
bug reports.
The following example shows what the command returns in some situations:
Note for developers: The option listing returned when version is called with the -f flag is built at compile time using #ifdef blocks. When
new compile switches are added, if you want them to appear on the list, you have to modify the code in misccoms.c.
17.5.102 Where*: Identify troublesome node or device
General Form:
where
When performing a transient or operating point analysis, the name of the last node or device to cause non-convergence is saved. The where command
prints out this information so that you can examine the circuit and either correct the problem or generate a bug report. You may do this either in the
middle of a run or after the simulator has given up on the analysis. For transient simulation, the iplot command can be used to monitor the progress of
the analysis. When the analysis slows down severely or hangs, interrupt the simulator (with control-C) and issue the where command. Note that only
one node or device is printed; there may be problems with more than one node.
General Form:
<set wr_singlescale>
<set wr_vecnames>
<option numdgt=7>
...
wrdata [file] [vecs]
This is a very simple printout of data in array form. Variables are written in pairs: scale vector, value vector. If variable is complex, a triple is printed
(scale, real, imag). If more than one vector is given, the third column again is the default scale, the fourth the data of the second vector. The default
format is ASCII. All vectors have to stem from the same plot, otherwise a segfault may occur. Setting wr_singlescale as variable, the scale vector
will be printed only once, if scale vectors are of the same length (you have to take care of that yourself). Setting wr_vecnames as variable, scale and
data vector names are printed on the first row. The number of significant digits is set with option numdgt.
General Form:
First vectors are grouped together by plots, and written out as such (i.e. if the expression list contained three vectors from one plot and two from
another, then two plots are written, one with three vectors and one with two). Additionally, if the scale for a vector isn't present it is automatically
written out as well.
The default format is a compact binary, but this can be changed to ASCII with the set filetype=ascii command. The default file name is either
rawspice.raw or the argument of the optional -r flag on the command line, and the default expression list is all.
General Form:
wrnodev [file]
Writes out the values of all voltage nodes to file. The format is .ic=xx. Thus the file may be included into another simulation of the same circuit and
deliver initial conditions for all voltage nodes. For example you may start a transient simulation, stop it and use the current data to start an ac
simulation.
output example:
The following control section snippet serves to save node voltage data at time 3.9 s and after the end of the transient simulation.
The data may be reused by an .include command: The simulation now starts with the initial condition given in the file.
.include F5ic1.txt
...
General Form:
wrs2p [file]
In the active plot the following is required: vectors frequency, S11 S12 S21 S22, all having the same length and complex values (as a result of an ac
analysis), and vector Rbase. For details how to generate these data see Chapt. 17.9.
The file format is Touchstone® Version 1, ASCII, frequency in Hz, real and imaginary parts of Snn versus frequency.
output example:
General Form:
while condition
statement
...
end
Example:
let loopindex = 0
while loopindex < 5
echo index is $&loopindex
let loopindex = loopindex + 1
end
Comment: let creates a vector. Convert vector loopindex to number (as required by echo) by $&loopindex. The condition statement compares
vectors.
General Form:
repeat [number]
statement
...
end
Example:
set loops = 7
repeat $loops
echo How many loops? $loops
end
Comment: set creates a variable. repeat requires a number as parameter, either a plain number or converted from vector by $&loopvec or converted
from variable by $loops.
General Form:
dowhile condition
statement
...
end
The same as while, except that the condition is tested after the statements are executed.
Example:
let loopindex = 0
dowhile loopindex <> 5
echo index is $&loopindex
let loopindex = loopindex + 1
end
General Form:
The statements are executed once for each of the values, each time with the variable var set to the current value. (var can be accessed by the $var
notation - see below).
Examples:
General Form:
if condition
statement
...
else
statement
...
end
If the condition is non-zero then the first set of statements are executed, otherwise the second set. The else and the second set of statements may be
omitted.
Example:
Comment: The condition may be evaluated by numbers or vectors. Variables have to be parsed to numbers like $val.
17.6.6 Label
General Form:
label word
If a statement of the form goto word is encountered, control is transferred to this point, otherwise this is a no-op.
17.6.7 Goto
General Form:
goto word
If a statement of the form label word is present in the block or an enclosing block, control is transferred there. Note that if the label is at the top
level, it must be before the goto statement (i.e, a forward goto may occur only within a block). A block to just include goto on the top level may look
like the following example.
if (1)
...
goto gohere
...
label gohere
end
17.6.8 Continue
General Form:
continue [n]
If there is a while, dowhile, or foreach block n levels of loops above the enclosing this statement, control passes to the test controlling that loop, or
in the case of foreach, the next value for that loop is taken. If n is not specified, it is assumed to be 1 and acts on the loop immediately enclosing the
continue command. If the value of 0 is given, it treated as a no-op.
17.6.9 Break
General Form:
break [n]
If there is a while, dowhile, or foreach block n levels of loops above the enclosing this statement, control passes out of the block. If n is not
specified, it is assumed to be 1 and acts on the loop immediately enclosing the break command. If the value of 0 is given, it treated as a no-op.
Of course, control structures may be nested. When a block is entered and the input is the terminal, the prompt becomes a number of >'s corresponding
to the number of blocks the user has entered. The current control structures may be examined with the debugging command cdump (see 17.5.10).
The following list is in alphabetical order. All of these variables are acknowledged by ngspice. Frontend variables (e.g. on circuits and simulation) are
not defined in ngnutmeg. The predefined variables that may be set or altered by the set command are
addcontrol
Set by ngspice if run with the -a command line parameter. When set, additional lines are added to netlists to ensure that a simulation is run.
altshow
When set, an alternate, non-tabular output format is used by the show and showmod commands.
appendwrite
Append to the file when a write command is issued, if one already exists.
askquit
Check to make sure that there are circuits suspended or plots unsaved. ngspice warns the user when he tries to quit if this is the case.brief If set
to FALSE, the netlist will be printed.
auto_bridge
When set to zero, automatic insertion of bridging devices (12.6) is disabled.
auto_bridge_xxxx
Variables of this general format are used to control insertion of automatic bridging devices. See section 12.6.
batchmode
Set by ngspice if run with the -b command line parameter. May be used in input files to suppress plotting if ngspice runs in batch mode.
brief
Suppresses automatic display of the processed netlist. It is set by default.
colorN
These variables determine the colors used during plotting. Color values may be entered as RGB values from 0 to 255 (hex or decimal) or stating
a color name. The identification number N may be an integer between 0 and 22. Color0 is the background, color1 is the grid and text color,
and color ids from 2 through 22 are used for graphs (vectors) plotted. Hex color coding is done according to set colorN=rgb:r/g/b, where r,
g, and b may range from 00 to FF each. For example green is selected by set color3=rgb:00/FF/00. Decimal coding is available as set
colorN=rgbd:rd/gd/bd, where rd, gd, and bd may range from 0 to 255. If X11 is being run (Linux, macOS, Cygwin), the value of the color
variables may be any of the standard X-Server color names, which may be found in file /usr/lib/rgb.txt. ngspice GUI for Windows supports
color names according to the Naming Common Colors project. Details with more than 140 color names are to be found in file
wincolornames.h. An example is set color3=blue. If no color id is set, then a predefined set of colors is applied automatically.
controlswait
(only available with shared ngspice, chapt. 19.4.1.4) If the simulation is started with the background thread (command bg_run), the .control
section commands are executed immediately after bg_run has been given, i.e. typically before the simulation has finished. This often is not very
useful because you want to evaluate the simulation results. If controlswait is set in .spiceinit or spice.rc, the command execution is delayed until
the background thread has returned (aka the simulation has finished). If set controlswait is given inside of the .control section, only the
commands following this statement are delayed.
cpdebug
Print control debugging information.
csnumprec
Allows setting the precision of values derived from vectors and variables (by $var, $&vec) as arguments to functions listet in chapter 17.5.
Default is 6, as has been standard up to now. If functions are using directly a vector as input (without the tranfer to number by $&), full double
precision is used.
curplot
(read only) Returns <type><no.> of the current plot. Type is one of tran, ac, op, sp, dc, unknown, no. is a number, sequentially set internally.
This information is used to uniquely identify each plot.
curplotdate
Sets the date of the current plot.
curplotname
Sets the name of the current plot.
curplottitle
Sets the title (a short description) of the current plot.
debug
If set then a lot of debugging information is printed.
device
The name (/dev/tty??) of the graphics device. If this variable isn't set then the user's terminal is used. To do plotting on another monitor you
probably have to set both the device and term variables. (If device is set to the name of a file, nutmeg dumps the graphics control codes into this
file – this is useful for saving plots.)
diff_abstol
The relative tolerance used by the diff command (default is 1e-12).
diff_reltol
The relative tolerance used by the diff command (default is 0.001).
diff_vntol
The absolute tolerance for voltage type vectors used by the diff command (default is 1e-6).
digital_delay_type
Controls the behaviour of XSPICE digital elements that support the Section 12.4 parameter.
echo
Print out each command before it is executed.
editor
The editor to use for the edit command.
enable_noisy_r
A user definable variable (for .spiceinit) to enable noise calculation for all behavioral resistors. May locally be switched off by instance
parameter noisy=0. If enable_noisy_r is not set, noise simulation may locally be enabled by instance parameter noisy=1.
filetype
This can be either ascii or binary, and determines the format of the raw file (compact binary or text editor readable ascii). The default is
binary. CIDER output (30.14) may be binary or ascii as well.
fourgridsize
How many points to use for interpolating into when doing Fourier analysis.
gridsize
If this variable is set to an integer, this number is used as the number of equally spaced points to use for the Y axis when plotting. Otherwise the
current scale is used (which may not have equally spaced points). If the current scale isn't strictly monotonic, then this option has no effect.
gridstyle
Sets the grid during plotting with the plot command. Will be overridden by direct entry of gridstyle in the plot command. A linear grid is
standard for both x and y axis. Allowed values are lingrid loglog xlog ylog smith smithgrid polar nogrid.
hcopydev
If this is set, when the hardcopy command is run the resulting file is automatically printed on the printer named hcopydev with the command
lpr -Phcopydev -g file.
hcopyfont
This variable specifies the font name for hardcopy output plots. The value is device dependent.
hcopyfontsize
This is a scaling factor for the font used in hardcopy plots.
hcopydevtype
This variable specifies the type of the printer output to use in the hardcopy command. If hcopydevtype is not set, Postscript format is assumed.
plot (5) is recognized as an alternative output format. When used in conjunction with hcopydev, hcopydevtype should specify a format
supported by the printer.
hcopyscale
This is a scaling factor for the font used in hardcopy plots (between 0 and 10).
hcopywidth
Sets width of the hardcopy plot.
hcopyheight
Sets height of the hardcopy plot.
hcopypscolor
Sets the color of the hardcopy output. If not set, black & white plotting is assumed with different linestyles for each output vector. A valid color
integer value yields a colored plot background (0: black 1: white, others see below). and colored solid lines. This is valid for Postscript only.
hcopypstxcolor
This variable sets the color of the text in the Postscript hardcopy output. If not set, black on white background is assumed, else it will be white
on black background. Valid colors are 0: black 1: white 2: red 3: blue 4: orange 5: green 6: pink 7: brown 8: khaki 9: plum 10: orchid 11: violet
12: maroon 13: turquoise 14: sienna 15: coral 16: cyan 17: magenta 18: gray (for smith grid) 19: gray (for smith grid) 20: gray (for normal
grid).
height
The length of the page for asciiplot and print col.
history
The number of events to save in the history list.
histsubst
Set to enable history substitution in the command interpreter (17.5.38).
inputdir
The directory path of the last input file. It may be used to direct outputs into a directory relative to the input (even the into the same directory)
by e.g. the command write $inputdir/outfile.raw vec1 vec2.
interactive
If interactive is set, numparam error handling may be done manually with user input from the console. If not, ngspice will exit upon a
numparam error.
keep#branch
If keep#branch is set, the rawfile output for branch currents is 1 v1#branch current for example, not 1 i(v1) current. This retains
compatibility with software like ICCAP.
lprplot5
This is a printf(3s) style format string used to specify the command to use for sending plot(5)-style plots to a printer or plotter. The first
parameter supplied is the printer name, the second parameter is a file name containing the plot. Both parameters are strings.
lprps
This is a printf(3s) style format string used to specify the command to use for sending Postscript plots to a printer or plotter. The first
parameter supplied is the printer name, the second parameter is the file name containing the plot. Both parameters are strings.
measoutfile
Add command set measoutfile=<path/filename> to .spiceinit or to a .control section in the netlist to save .measure results from batch mode
in a file.
modelcard
The name of the model card (normally .MODEL)
moremode
If moremode is set, whenever a large amount of data is being printed to the screen (e.g, the print or asciiplot commands), the output is
stopped every screenful and continues when a carriage return is typed. If moremode is unset, then data scrolls off the screen without pausing.
nfreqs
The number of frequencies to compute in the Fourier command. (Defaults to 10.)
ngbehavior
Sets the compatibility mode of ngspice. Default value is 'all'. To be set in spinit (16.5) or .spiceinit (16.6). A value of 'all' improves
compatibility with commercial simulators. Full compatibility is however not the intention of ngspice! The values 'ps', 'psa', 'lt', 'lta',
'hs' and 'spice3' are available. See Chapt. 16.14.
ngdebug
enables several debugging printouts (see 16.16).
nginfo
Enables a status report during simulation (currently available only with MS Windows GUI version).
ng_nomodcheck
Suppresses any model parameter check, if set.
no_auto_gnd
Setting this boolean variable by set no_auto_gnd in spinit or .spiceinit, ngspice will refrain from replacing all nodes named gnd by node 0. In
using this setting, you will have to take care of proper zeroing appropriate ground nodes. If you fail to do so, ngspice may crash, or deliver
wrong results.
nobreak
Don't have asciiplot and print col break between pages.
noasciiplotvalue
Don't print the first vector plotted to the left when doing an asciiplot.
nobjthack
BJTs can have either 3 or 4 nodes, which makes it difficult for the subcircuit expansion routines to decide what to rename. If the fourth
parameter has been declared as a model name, then it is assumed that there are 3 nodes, otherwise it is considered a node. To disable this, you
can set the variablenobjthack and force BJTs to have 4 nodes (for the purposes of subcircuit expansion, at least).
noclobber
Don't overwrite existing files when doing IO redirection.
noglob
Don't expand the global characters `*', `?', `[', and `]'. This is the default.
nolegend
Don't plot the legend, when using the plot command..
nonomatch
If noglob is unset and a global expression cannot be matched, use the global characters literally instead of complaining.
noparse
Don't attempt to parse input files when they are read in (useful for debugging). Of course, they cannot be run if they are not parsed.
noprintscale
Don't print the scale in the leftmost column when a print col command is given.
nosavecurrents
If set by 'set nosavecurrents' and followed by 'reset', the setting of internal current vectors (.options savecurrents) is suppressed. This is
useful in ac simulation which does not support 'options savecurrents' and you have a mix of several simulations in a single script.
nosort
Don't let display sort the variable names.
nostepsizelimit
The maximum step size during transient simulation is per default limited to tstep given by .tran tstep tstop <tstart <tmax>> (15.3.10,
17.5.95). It may be overridden and set to a value of (tstop - tstart)/50 by adding 'set nostepsizelimit' to .spiceinit. Both may be overriden
by setting tmax on the .tran line.
nosubckt
Don't expand subcircuits.
notrnoise
Switch off the transient noise sources (Chapt. 4.1.7).
nounits
Plotting of the units token for the x and y axes of a graph is suppressed. Units may be added manually to the y and x labels for SI conformity.
numdgt
The number of digits to use when printing tables of data (print col). The default precision is 6 digits. On the PC, approximately 16 decimal
digits are available using double precision, so p should not be more than 16. If the number is negative, one fewer digit is printed to ensure
constant widths in tables.
num_threads
The number of of threads to be used if OpenMP (see Chapt. 16.10) is selected. The default value is 2.
oscompiled
is set during ngspice compilation and returns a number corresponding to the operating environment used during compilation. 0 Other, 1
MINGW for MS Windows, 2 Cygwin for MS Windows, 3 FreeBSD, 4 OpenBSD, 5 Solaris, 6 Linux, 7 macOS, 8 Visual Studio for MS
Windows .
osdi_enabled
is set by ngspice upon start-up when the OSDI interface (13.2) is compiled in.
plainlet
Command let (17.5.42) will executed without evaluating any expression in its command line. This is useful if characters like '/' are part of the
vector names, e.g. as issued by KiCad. Setting plainlet may be used to rename a vector including such math characters into a vector using
only standard characters. Then standard plot, print, and write commands may be applied to this renamed vector.
plainplot
Command plot (17.5.53) will executed without evaluating any expression in its command line. This is useful if characters like '/' are part of the
vector names.
plainwrite
Command write (17.5.104) will executed without evaluating any expression in its command line. This is useful if characters like '/' are part of
the vector names.
plotstyle
This should be one of linplot, combplot, or pointplot. linplot, the default, causes points to be plotted as parts of connected lines. combplot
causes a comb plot to be done. It plots vectors by drawing a vertical line from each point to the X-axis, as opposed to joining the points.
pointplot causes each point to be plotted separately.
pointchars
Set a string as a list of characters to be used as points in a point plot. Standard is `ox*+#abcdefhgijklmnpqrstuvwyz'. Some characters are
forbidden.
polydegree
The degree of the polynomial that the plot command should fit to the data. If polydegree is N, then ngspice fits a degree N polynomial to
every set of N points and draws 10 intermediate points in between each end point. If the points aren't monotonic, then ngspice tries to rotate the
curve and reduce the degree until a fit is achieved.
polysteps
The number of points to interpolate between every pair of points available when doing curve fitting. The default is 10.
program
The name of the current program (argv[0]).
prompt
The prompt, with the character `!' replaced by the current event number. Single quotes ' ' are required around the specified string unless you
really want it expanded.
rawfile
The default name for created rawfiles.
remote_shell
Overrides the name used for generating rspice runs (default is rsh).
renumber
Renumber input lines when an input file has .includes.
rndseed
Seed value for random number generator (used by sgauss, sunif, and rnd functions). It is set by the option command 'option
seed=val|random'.
rhost
The machine to use for remote ngspice runs, instead of the default one (see the description of the rspice command, below).
rprogram
The name of the remote program to use in the rspice command.
sharedmode
Variable is set when ngspice runs in its shared mode (from ngspice.dll or ngspice_xx.so). May be used in universal input files to suppress
plotting because a graphics interface is lacking.
shellstatus
Contains the status returned by the last “shell” command.
silent_fileio
If set, the fopen and fread commands do not print error messages. Errors are still reported by setting a variable.
sim_status
will bet set to 0 when the simulation starts. If there is an error and the simulation fails with 'xx simulation(s) aborted', then sim_status is set to
1. The variable can be used in scripted loops within a transient simulation to allow special handling e.g. in case of non-convergence.
sourcepath
A list of the directories to search when a source command is given. The default is the current directory and the standard ngspice library
(/usr/local/lib/ngspice, or whatever LIBPATH is #defined to in the ngspice source). The command
setcs sourcepath = ( e:/ D:/ . c:/Spice/Examples )
will overwrite the default. setcs is used to keep upper case letters. The search sequence now is: current directory, e:/, D:/, current directory
(again due to .), c:/Spice/Examples. 'Current directory' is depending on the OS. The command
setcs sourcepath = ( D:/mypath/input $sourcepath )
will add another path entry in front of the already existing list of paths. This feature may be used with shared ngspice (19) to send a input path
to code models which require file input, like d_source. Only the first entry in the sourcepath list is sent to the code models, however.
specwindow
Windowing for commands spec (17.5.85) or fft (17.5.30). May be one of the following: bartlet blackman cosine gaussian hamming
hanning none rectangular triangle.
specwindoworder
Integer value 2 - 8 (default 2), used by commands spec or fft.
spicepath
The program to use for the aspice command. The default is /cad/bin/spice.
If set, noise data outputs will be given as 𝑉2 /𝐻𝑧 or 𝐴2 /𝐻𝑧, otherwise as the usual 𝑉/ √𝐻𝑧 or 𝐴/ √𝐻𝑧.
sqrnoise
strict_errorhandling
If set by the user, an error detected during circuit parsing will immediately lead ngspice to exit with exit code 1 (see 18.5). May be set in files
spinit (16.5) or .spiceinit (16.6) only.
subend
The card to end subcircuits (normally .ends).
subinvoke
The prefix to invoke subcircuits (normally X).
substart
The card to begin subcircuits (normally .subckt).
term
The mfb name of the current terminal.
ticchar
A character applied as a tic mark (replaces the default 'x').
ticmarks
An integer value n, every n data points a tic (default: a small 'x') will be set on your graph.
ticlist
A list of integers, e.g. ( 4 14 24 ), selects data points to set tics (small 'x') on your graph.
units
If this is degrees, then all the trig functions will use degrees instead of radians.
unixcom
If a command isn't defined, try to execute it as a UNIX command. Setting this option has the effect of giving a rehash command, below. This is
useful for people who want to use ngspice as a login shell.
wfont
Set the font for the graphics plot in MS Windows. Typical fonts are courier, times, arial and all others found on your machine. Default is
courier.
wfont_size
The size of the windows font. The default depends on system settings.
width
The width of the page for asciiplot and print col (see also 15.6.7).
win_console
is set when ngspice runs in a console under Windows.
wr_onespace
Command wrdata: Print data with one space only in between, not by collumns with fixed width.
wr_singlescale
Command wrdata: The scale vector will be printed only once, if all scale vectors are of the same length.
wr_vecnames
Command wrdata: Scale and data vector names are printed on the first row.
x11lineararcs
Some X11 implementations have poor arc drawing. If you set this option, ngspice will plot using an approximation to the curve using straight
lines.
xbrushwidth
Linewidth for graph (see xgridwidth for border and grid). Valid for MS Windows GUI, X11, gnuplot and Postscript.
xgridwidth
Linewidth for border and grid. Valid for MS Windows GUI, X11, gnuplot and Postscript.
xfont
Set the font for text (x and y labels, axis values) in the graphics plot in X11 (Linux, Cygwin, macOS etc.). The command fc-list | cut -f2
-d: | sort -u | less -r lists the font names that are installed on the computer and are suited for this variable. Use xfont with the setcs
command to keep lower case and upper case characters, e.g. in setcs xfont='Noto Sans CJK JP'. The'Noto Sans' font family is very well
suited, covering Western and Asian fonts. Also valid for gnuplot and Postscript.
xfont_size
The size of the X11 font. The default depends on system settings.
xspice_enabled
is set by ngspice upon start-up, when the XSPICE option (II) for using code models is compiled in.
xtrtol
Set trtol, e.g. to 7, to avoid the default speed reduction (accuracy increase) for XSPICE (see 16.9). Be aware of potential precision
degradation or convergence issues using this option.
17.8 Scripts
Ngspice is started in batch or interactive mode with an input file on the command line. Input files may also be sourced later with the source command
or by using the script name as a command. The ngspice input file contains the usual circuit netlist, model cards, and may also contain a command
script, enclosed in a .control .. .endc section. Expressions, functions, constants, commands, variables, vectors, and control structures may be
assembled into such scripts.
Scripting allows automation of any ngspice task: simulations to perform, output data to analyze, repeat simulations with modified parameters,
assemble output plot vectors. The ngspice scripting language is not very powerful, but well integrated into the simulation flow. After reading the input
file, any command sequences are immediately processed. Variables or vectors set by previous commands may be referenced by the commands
following them. Data can be stored, plotted or grouped into new vectors for either plotting or other means of data evaluation.
An input file may contain only a title and the .control .. .endc section: it is a pure script. The need for a title (that may be blank) is an unfortunate
result of the source command being used for both circuit input and command file execution. Note that this does allow the user to merely type the
name of a circuit file as a command and it is automatically run. The commands are executed immediately, without running any analyses that may be
specified in the circuit (to execute the analyses before the script executes, include a run command in the script).
An alternative way to indicate a pure script is to put *ng_script in the first line, the rest of the file is then treated as if it were inside a control section.
As a special case, if a script file begins with *ng_script_with_params and it was the first non-option argument on the ngspice command line, then
remaining command arguments are treated as script arguments, not additional netlists.
Before a script is read, the variables argc and argv are set to the number of words following the file-name on the command line, and a list of those
words respectively. Individual script arguments may be accessed as $1, $2 etc. After the file is finished, these variables are unset. Note that if a
command file calls another, it must save its argv and argc since they are altered. Also, command files may not be re-entrant since there are no local
variables. Of course, the procedures may explicitly manipulate a stack ...; that way one can write scripts analogous to shell scripts for ngspice.
17.8.1 Variables
Variables are defined and initialized with the set command (17.5.70). set output=10 defines the variable output and sets it to the number 10.
Predefined variables, which are used inside ngspice for specific purposes, are listed in Chapt. 17.7. Variables are accessible globally. The values of
variables may be used in commands by writing $varname where the value of the variable is to appear, e.g. $output. If a variable is substituted that is
not defined internally, but is defined in the program environment, then the external value is used. The special variable $$ refers to the process ID of
the program. With $< a line of input is read from the terminal.
If a variable is assigned with $&word, then word must be a vector (see below), and word's numeric value is taken to be the new value of the variable.
Variables may have a value that is a list of values. If foo is a valid variable, and is of type list, then the expression $foo[low-high] expands to a
range of elements. Either the upper or lower index may be left out, and in addition to slicing also reversing of a list is possible through $foo[len-0]
(len is the length of the list, the first valid index is always 1).
Furthermore, the notation $?foo evaluates to 1 if the variable foo is defined, 0 otherwise, and $#foo evaluates to the number of elements in foo if it is
a list, 1 if it is a number or string, and 0 if it is a Boolean variable.
17.8.2 Vectors
Ngspice data is in the form of vectors: time, voltage, etc. Each vector has a type, and vectors can be operated on and combined algebraically in ways
consistent with their types. Vectors are normally created as a result of a transient or dc simulation. They are also established when a data file is read in
(see the load command 17.5.45), or they are created with the let command 17.5.42 inside a script. If a variable x is assigned something of the form
$&word, then word has to be a vector, and the numeric value of word is transferred into the variable x.
.end
Subcircuit instance Xsub1 calls subcircuit sub1 which contains a subcircuit instance Xsub2 calling sub2 which contains node int2.
r.xsub1.xsub2.r21 a xsub1.xsub2.int2 1k
r.xsub1.xsub2.r22 b xsub1.xsub2.int2 1k
r.xsub1.r11 a xsub1.int1 1k
r.xsub1.r12 b xsub1.int1 1k
After expansion the subcircuits have disappeared. We now have extended node (aka vector) names like xsub1.int1 or xsub1.xsub2.int2. The top
level subcircuit call name is followed by node name, separated by a dot. Or the top level subcircuit call name is followed second level subciruit call
name, then followed by node name, each again separated by a dot. You may now assess the node int2 values in a script by
print v(xsub1.xsub2.int2)
Also the device instances have got their subcircuit information added to their names in a similar way. In addition the type identifier letter (e.g. R for
resistor) has been put in front. So the resistor instances now are called r.xsub1.r11 or r.xsub1.xsub2.r22.
17.8.4 Commands
Commands have been described in Chapt. 17.5.
.control
As a suitable input for spectrum you may run a ring-oscillator, delivered with ngspice in e.g. test/bsim3soi/ring51_41.cir. For an adequate resolution
a simulation time of 1𝜇s is needed. A small control script starts ngspice by loading the R.O. simulation data and executing spectrum.
Small script to start ngspice, read the simulation data and start spectrum:
let part = 0
dowhile part < no_buck
let value = bucket[part] - 1
set value = "$&value"
* print the bucket's contents
echo $value
let part = part + 1
end
.endc
.end
parameter sweep
* resistive divider, R1 swept from start_r to stop_r
VDD 1 0 DC 1
R1 1 2 1k
R2 2 0 1k
.control
let start_r = 1k
let stop_r = 10k
let delta_r = 1k
let r_act = start_r
* loop
while r_act le stop_r
alter r1 r_act
op
print v(2)
let r_act = r_act + delta_r
end
.endc
.end
M1 3 2 0 0 N1 L=1u W=4u
Rsource 1 2 100k
Rload 3 vdd 25k
Vdd vdd 0 1.8
Vin 1 0 1.2 ac 0.1
.control
ac dec 10 100 1000Meg
plot v(2) v(3)
let flen = length(frequency) $ length of the vector
let loopcounter = 0
echo output test > text.txt $ start new file test.txt
* loop
while loopcounter lt flen
let vout2 = v(2)[loopcounter] $ generate a single point
$ complex vector
let vout2re = real(vout2) $ generate a single point
$ real vector
let vout2im = imag(vout2) $ generate a single point
$ imaginary vector
let vout3 = v(3)[loopcounter] $ generate a single
$ point complex vector
let vout3re = real(vout3) $ generate a single point
$ real vector
let vout3im = imag(vout3) $ generate a single point
$ imaginary vector
let freq = frequency[loopcounter] $ generate a single point vector
echo bbb "$&freq" "$&vout2re" "$&vout2im"
+ "$&vout3re" "$&vout3im" >> text.txt
$ append text and
$ data to file
$ (continued from line above)
let loopcounter = loopcounter + 1
end
.endc
Intrinsic commands (.sp, see 15.3.8 and sp, see 17.5.84) will generate S-parameters versus frequency from any suitable multi-port circuit at varying
frequencies. Besides the s matrix (with S_1_1, S_2_1, S_1_2, and S_2_2 for a two-port circuit), the Y and T matrix vector values are calculated and
saved as well.
A command line script, available from the ngspice distribution at examples/control_structs/s-param.cir, creates S-parameters S_1_1, S_2_1,
S_1_2, and S_2_2 of any two port circuit.
The printed output using wrs2p (see Chapt. 17.5.106) is a Touchstone® version 1 format file. The file follows the format according to The
Touchstone File Format Specification, Version 2.0, available from here. An example is given as number 13 on page 15 of that specification.
S-parameters allow a two-port description not just by permuting 𝐼1 , 𝑈1 , 𝐼2 , 𝑈2 , but using a superposition, leading to a power view of the port (We only
17.9.2 S-parameter measurement basics
You may start with the effective power, being negative or positive
𝑃=𝑢⋅𝑖
The value of 𝑃 may be the difference of two real numbers, with 𝐾 being another real number.
𝐾−1 𝑢 = 𝑎 + 𝑏
𝐾𝑖 = 𝑎 − 𝑏
and finally
𝑢 + 𝐾2 𝑖
𝑎=
2𝐾
𝑢 − 𝐾2 𝑖
𝑏=
2𝐾
By introducing the reference resistance 𝑍0 : = 𝐾2 > 0 we get finally the Heaviside transformation
𝑢 + 𝑍0 𝑖 𝑢 − 𝑍0 𝑖
𝑎= , 𝑏=
𝑍
2√ 0 2√𝑍0
𝑈1 + 𝑍0 𝐼1 𝑈1 − 𝑍0 𝐼1
𝑎1 = 𝑏1 =
2√𝑍0 2√𝑍0
𝑈2 + 𝑍0 𝐼2 𝑈2 − 𝑍0 𝐼2
𝑎2 = 𝑏2 =
2√𝑍0 2√𝑍0
𝑏1 𝑠 𝑠 𝑎
( ) = ( 11 12 ) ( 1 )
𝑏2 𝑠21 𝑠22 𝑎2
Two obtain 𝑠11 we have to set 𝑎2 = 0. This is accomplished by loading the output port exactly with the reference resistance 𝑍0 , which sinks a current
𝐼2 = − 𝑈2 /𝑍0 from the port.
𝑏
𝑠11 = ( 1 )
𝑎1 𝑎
2 =0
𝑈1 − 𝑍0 𝐼1
𝑠11 =
𝑈1 + 𝑍0 𝐼1
Loading the input port from an ac source 𝑈0 via a resistor with resistance value 𝑍0 , we obtain the relation
𝑈0 = 𝑍0 𝐼1 + 𝑈1
2𝑈1 − 𝑈0
𝑠11 =
𝑈0
𝑏
𝑠21 = ( 2 )
𝑎1 𝑎 =0
2
𝑈2 − 𝑍0 𝐼2 2𝑈2
𝑠21 = =
𝑈1 + 𝑍0 𝐼1 𝑈0
Equations 85 and 87 now tell us how to measure 𝑠11 and 𝑠21 : Measure 𝑈1 at the input port, multiply by 2 using an E source, subtracting 𝑈0 , which for
simplicity is set to 1, and divide by 𝑈0 . At the same time measure 𝑈2 at the output port, multiply by 2 and divide by 𝑈0 . Biasing and measuring is
done by subcircuit S_PARAM. To obtain 𝑠22 and 𝑠12 , you have to exchange the input and output ports of your two-port and do the same measurement
again. This is achieved by switching resistors from low (1𝑚 Ω ) to high (1𝑇 Ω ) and thus switching the input and output ports.
The reference resistance (often called characteristic impedance) for the measurements is added as a parameter
.param Rbase=50
The bias voltages at the input and output ports of the circuit are set as parameters as well:
Place your circuit at the appropriate place in the input file, e.g. replacing the existing example circuits. The input port of your circuit has two nodes in,
0. The output port has the two nodes out, 0. The bias voltages are connected to your circuit via the resistances of value Rbase at the input and output
respectively. This may be of importance for the operating point calculations if your circuit draws a large dc current.
Now edit the ac commands (see 17.5.1) according to the circuit provided, e.g.
Be careful to keep both ac lines in the .control ... .endc section the same and only change both in equal measure!
Select the plot commands (lin/log, or smithgrid) or the 'write to file' commands (write, wrdata, or wrs2p) according to your needs.
ngspice s-param.cir
Example:
The following is valid only if you are working with ngspice as a console app (Linux, Cygwin). In interactive mode or from a .control section you may
transfer the return of a command from the shell into an ngspice variable by backquote or backtick substitution. Any text between backquotes is
replaced by the result of executing the text as a command to the shell.
Example:
17.11 MISCELLANEOUS
C-shell type quoting with ' and " may be used. Within single quotes, no further substitution (like history substitution) is done, and within double
quotes, the words are kept together but further substitution is done.
History substitutions, similar to C-shell history substitutions, are also available - see the C-shell manual page for all of the details. The characters ~,
@{, and @} have the same effects as they do in the C-Shell, i.e., home directory and alternative expansion. It is possible to use the wildcard
characters *, ?, [, and ] also, but only if you unset noglob first. This makes them rather useless for typing algebraic expressions, so you should set
noglob again after you are done with wildcard expansion. Note that the pattern [^abc] matches all characters except a, b, and c.
If X is being used, the cursor may be positioned at any point on the screen when the window is up and characters typed at the keyboard are added to
the window at that point. The window may then be sent to a printer using the xpr(1) program.
17.12 Bugs
When defining aliases like alias pdb plot db( !:1 - !:2 ) you must be careful to quote the argument list substitutions in this manner. If you quote
the whole argument it might not work properly.
In a user-defined function, the arguments cannot be part of a name that uses the plot.vec syntax. For example: define check(v(1))
cos(tran1.v(1)) does not work.
Input file:
The GUI consists of an I/O port (lower window) and a graphics window, created by the plot command.
In the plot window there is the upper left button, which activates a drop down menu. You may select to print the plot window shown (a simple printer
interface), set up any of the printers available on your computer, or issue a postscript file or a SVG file of the active plot window.
A left-click in the plot window will print the coordinates of that point in the text window, allowing data to be captured from the plot. Click, drag and
release will show both start and end points, as well as the slope of the line joining them. Click and drag with the right button outlines a rectangle; on
release a new window opens with a“zoomed” plot of that rectangular area.
Instead of plotting with black background, you may set the background to any other color, preferably to `white' using the command shown below.
.control
run
* white background
set color0=white
* black grid and text (only needed with X11, automatic with MS Win)
set color1=black
* wider plot lines
set xbrushwidth=2
plot vss#branch
.endc
As ngspice supports UNICODE text, fonts supporting other letterings than plain English may be selected, e.g. Korean, Japanese, Chinese, Cyrillic,
Arabic etc..
Only on the ngspice console binary in MS Windows input/output redirection is possible, if ngspice is called (e.g. within a MSYS shell or from a shell
script) like
This feature is used in the new CMC model test suite (to be described elsewhere), thus requires a console binary.
You still may generate graphics output plots or prints by gnuplot (17.5.35), if installed properly (18.7), or by selecting a suitable printing option
(18.6).
18.3 Linux
The standard user interface is a console for input and the X11 graphics system for output with the interactive plot (17.5.53) command. If ngspice is
compiled with the –without-x flag for ./configure, a console application without graphical interface results. For more sophisticated input user
interfaces please have a look at Chapt. 18.8.
The X11 UI has buttons to save the plot in formats suitable for printing or inclusion in a web page. The mouse actions in the plot window are the same
as the Windows UI. In addition, when the pointer is in the plot, keyboard input is inserted at the pointer position so that the plot can be annotated.
Annotations are included in saved files.
18.4 CygWin
The CygWin interface is similar to the Linux interface (18.3), i.e. console input and X11 graphics output. To avoid the warning of a missing graphical
user interface, you have to start the X11 window manager by issuing the commands
$ export DISPLAY=:0.0
Error messages may occur with the token `Error:'. Often the errors are non-recoverable and will lead to exiting ngspice with error code 1. Sometimes,
however, you will get an error message, but ngspice will continue, and may either bail out later because the error has propagated into the simulation,
sometimes ngspice will continue, deliver wrong results and exit with error code 0 (no error detected!).
In addition ngspice may issue warning messages like `Warning: ...'. These should cover recoverable errors only.
So there is still work to be done to define a consistent error messaging, recovery or exiting. A first step is the user definable variable
strict_errorhandling. This variable may be set in files spinit (16.5) or .spiceinit (16.6) to immediately stop ngspice, after an error is detected
during parsing the circuit. An error message is sent, the ngspice exit code is 1. This behavior deviates from traditional SPICE error handling and thus
is introduced as an option only.
Various SVG settings are given by setting the following two variables:
svg_intopts
Sets the plot parameters by numbers "svgwidth", "svgheight", "svgfont-size", "svgfont-width", "svguse-color", "svgstroke-width", "svggrid-
width", .
svg_stropts
Sets the plot parameters by strings "svgbackground", "svgfont-family", "svgfont" . Use command setcs to keep upper and lower case.
Usage
.control
set svg_intopts = ( 512 384 20 0 1 2 0 )
setcs svg_stropts = ( blue Arial Arial )
.endc
The following variables may override some of the above mentioned parameters or provide more details.
hcopyfont
This variable specifies the font name for hardcopy output plots. The value is device dependent.
hcopyfontsize
This is a scaling factor for the font used in hardcopy plots.
hcopydevtype
The variable specifies the type of the printer output to use in the hardcopy command. It has to be set to set hcopydevtype=svg.
hcopyscale
This is a scaling factor for the font used in hardcopy plots (between 0 and 10).
hcopywidth
Sets width of the hardcopy plot.
hcopyheight
Sets height of the hardcopy plot.
colorN
These variables determine the colors used during plotting. Color values may be entered as RGB values from 0 to 255 (hex or decimal) or stating
a color name. The identification number N may be an integer between 0 and 20. Color0 is the background, color1 is the grid and text color,
and color ids from 2 through 20 are used for graphs (vectors) plotted. The available color strings are (use the string inside of the hyphens):
"black", "white", "red", "blue", "#FFA500" (orange), "green", "#FFC0C5" (pink), "#A52A2A" (brown), "#F0E68C" (khaki), "#DDA0DD"
(plum), "#DA70D6" (orchid), "#EE82EE" (violet), "#B03060" (maroon); "#40E0D0" (turqoise), "#A0522D" (sienna), "#FF7F50" (coral),
"cyan", "magenta", "#666" (gray for smith grid), "#949494" (gray for smith grid), "#888" (gray for normal grid). Examples are set
color3=blue or set color3="#EE82EE". If no color id is set, then the above mentioned, predefined set of colors is applied automatically.
xbrushwidth
Linewidth for graph (see xgridwidth for border and grid). Valid for MS Windows GUI, X11, gnuplot and Postscript.
xgridwidth
Linewidth for border and grid. Valid for MS Windows GUI, X11, gnuplot and Postscript.
hardcopy file vector <vectors> <title text> <xlabel text> <ylabel text>
Usage
.control
* simulation commands here
set hcopydevtype = svg
set svg_intopts = ( 512 384 20 0 1 2 0 )
setcs svg_stropts = ( yellow Arial Arial )
set color1=blue
set color2=green
hardcopy plot_1.svg vss#branch title 'Plot no. 4'
+ xlabel 'Drain voltage' ylabel 'Drain current'
* plot to screen commands here
.endc
Plot-to-screen
The file contents may be plotted to the screen. For MS Windows you may use the Internet Explorer or EDGE, linked to the .svg file extension. Under
Cygwin or Linux you may install the program feh for plotting with the following commands:
18.6.1.2 PostScript
How to prepare a plot
Variables to modify the PostScript plot are listed below. Background and text colors may be set. The colors of the graphs are then chosen
automatically, starting with red. Valid colors are 0: black 1: white 2: red 3: blue 4: orange 5: green 6: pink 7: brown 8: khaki 9: plum 10: orchid 11:
violet 12: maroon 13: turquoise 14: sienna 15: coral 16: cyan 17: magenta 18: gray (for smith grid) 19: gray (for smith grid) 20: gray (for normal
grid).
hcopypscolor
Sets the color of the hardcopy output byselecting a integer number. If not set, black & white plotting is assumed with different linestyles for
each output vector. A valid color integer value yields a colored plot background (0: black 1: white, others see above). and colored solid lines.
hcopypstxcolor
This variable sets the color of the text in the Postscript hardcopy output. If not set, black on white background is assumed, if the background is
colored or black, white text is printed.
hcopyfont
This variable specifies the font name for hardcopy output plots. The value is device dependent.
hcopyfontsize
This is a scaling factor for the font used in hardcopy plots.
hcopydevtype
The variable specifies the type of the printer output to use in the hardcopy command. It has to be set to set hcopydevtype=svg.
hcopyscale
This is a scaling factor for the font used in hardcopy plots (between 0 and 10).
hcopywidth
Sets width of the hardcopy plot.
hcopyheight
Sets height of the hardcopy plot.
xbrushwidth
Linewidth for graph (see xgridwidth for border and grid). Valid for MS Windows GUI, X11, gnuplot and Postscript.
xgridwidth
Linewidth for border and grid. Valid for MS Windows GUI, X11, gnuplot and Postscript.
The corresponding input file for the examples given below is listed in Chapt. 21.1. Just add the .control section to this file and run in interactive
mode by
$ ngspice xspice_c1_print.cir
One way is to setup your printing like this will yield a black&white plot:
.control
set hcopydevtype=postscript
op
run
plot vcc coll emit
hardcopy temp.ps vcc coll emit
.endc
Then print the postscript file temp.ps to the screen. This may be done by a ngspice shell command, depending on the operating system and the
installed viewer tools (like gv or others):
* for MS Windows only
if $oscompiled = 1 | $oscompiled = 8
shell Start /B temp.ps
* for CYGWIN
else
shell gv temp.ps &
end
You can add color traces to it if you wish:
.control
set hcopydevtype=postscript
* allow color and set background color if set to value >= 0
set hcopypscolor=1 ; white
set hcopypstxcolor = 3 ; blue
* The colors of the graphs are set automatically.
set xgridwidth=2
set xbrushwidth=3
run
hardcopy temp.ps vcc coll emit
.endc
Then print the postscript file temp.ps to a postscript printer.
You can also direct your output directly to a designated printer (not available in MS Windows):
.control
set hcopydevtype=postscript
*send output to the printer kec3112-clr
set hcopydev=kec3112-clr
hardcopy out.tmp vcc coll emit
.endc
18.6.1.3 PNG
There is no png driver integrated into ngspice. One may use the gnuplot interface (see 18.7) to create a png file.
Usage
.control
* simulation commands here
set gnuplot_terminal=png/quit
gnuplot plot_1 vss#branch vss2#branch
+ title 'Drain current versus drain voltage'
+ xlabel 'Drain voltage / V' ylabel 'Drain current / uA'
* plot to screen commands here
.endc
This command sequence will generate a png file plot_1.png in the current directory. You will need to have gnuplot installed.
A few remarks are due: Generally you should use a text editor for the input files that allows to set the character encoding to utf-8. you may give a true
µA in the label text, not only the uA. Otherwise a µ in the input file may lead ngspice to fail the utf-8 syntax test. For sake of having not enough
characters per line available in the final pdf manual to fitting the gnuplot command, the line continuation is used in the above example with a +
character in the first column. Unfortunately this has a strange side effect in a real ngspice input file, in that all letters become lower case in the
continuation lines. So better create a single (long) line containing the complete gnuplot command.
Plotting the png file to the screen can be achieved from within the .control section by
You will need to install a suitable viewer program (e.g. irfanview or feh).
18.6.1.4 VCD
Value Change Dump (VCD) (also known less commonly as "Variable Change Dump") is an ASCII-based format for dumpfiles generated by event
based logic simulation. The eprvcd command is used by ngspice to print out the digital event nodes and real-valued expressions versus time.
General Form:
Example usage:
Values for analog nodes and expressions (as for plot ) may be included, but expressions may not contain spaces. Option “-t” sets the VCD file's time
unit; values are rounded to a negative power of 10. If not used the unit is chosen to fit the simulation's maximum timestep. Analog values are
examined only when an XSPICE event values changes unless option “-a” is used to dump them at each timestep.
The file addr_x.vcd may be displayed by the following .control section (gtkwave has to be installed):
nggtk.tcl
# tcl script for gtkwave: show vcd file data created by ngspice
set nfacs [ gtkwave::getNumFacs ]
for {set i 0} {$i < $nfacs } {incr i} {
set facname [ gtkwave::getFacName $i ]
set num_added [ gtkwave::addSignalsFromList $facname ]
}
gtkwave::/Edit/UnHighlight_All
gtkwave::/Time/Zoom/Zoom_Full
filetype
This can be either ascii or binary, and determines the format of the raw file (compact binary or text editor readable ascii). The default is
binary.
All simulations (e.g. if .tran follow .ac) will be saved consecutively. If using the write command, setting variable appendwrite will allow storing
several sim outputs in a single file.
appendwrite
Append to the file when a write command is issued, if one already exists.
appendwrite
Append to the file when a write command is issued, if one already exists.
numdgt
The number of digits to use when printing tables of data (print col). The default precision is 6 digits. On the PC, approximately 16 decimal
digits are available using double precision, so p should not be more than 16. If the output number is negative, one digit less is printed to ensure
constant widths in tables.
wr_singlescale
The scale vector will be printed only once, if all scale vectors are of the same length.
wr_vecnames
Scale and data vector names are printed on the first row.
Example usage:
noclobber
Don't overwrite existing files when doing IO redirection.
Example usage:
* variable
setcs myvar=great
set empty=""
* vector
let lineno=1
* empty line
echo
* vectors and variables may be included
echo This is a $myvar output with $&lineno line(s).
* no line feed, empty var to allow blank
echo -n This is still a $myvar output $empty
echo with $&lineno line(s).
General Form:
Prints the vector(s) described by the expression expr. Please see 17.5.56 for details. Expression expr. may be a list of vectors, but also a mathematical
expression combining vectors and constants according to 17.2.
Example:
appendwrite
Append to the file when a write command is issued, if one already exists.
moremode
If moremode is set, whenever a large amount of data is being printed to the screen (e.g, the print or asciiplot commands), the output is
stopped every screenful and continues when a carriage return is typed. If moremode is unset, then data scrolls off the screen without pausing.
noprintscale
Don't print the scale in the leftmost column when a print col command is given.
numdgt
The number of digits to use when printing tables of data (print col). The default precision is 6 digits. On the PC, approximately 16 decimal
digits are available using double precision, so p should not be more than 16. If the output number is negative, one digit less is printed to ensure
constant widths in tables.
18.7 Gnuplot
18.7.1 Using Gnuplot to produce 1D graphs of (electrical) simulation results
Plotting with Gnuplot is directly available from the ngspice .control section or interactive command. Install Gnuplot (on Linux available from the
distribution, on Windows available here). On Windows, expand the zip file to a directory of your choice, add the path <any directory>/gnuplot/bin
to the PATH variable, and off you go... The command to invoke Gnuplot (17.5.35) is limited to x/y plots (no polar etc.).
General Form:
plotargs is a list of vectors to be plotted. file may either be temp or tmp or a file name (without file extension).
ngspice generates temporary data and command files for Gnuplot, calls Gnuplot for openening the plot windows and then discards the temporary files.
Gnuplot command file newplot.plt and data file newplot.data are generated to stay in the current directory. The command file may be modified to alter
the plot, and then called by gnuplot newplot.plt to draw the modified plot.
gnuplot_terminal
May be one of the following: png (write png file and plot to screen), png/quit (write png file but no plot, see 18.6.1.3), eps (write
PostScript file and plot to screen), eps/quit (write PostScript file, but no plot), xterm (open gnuplot in an xterm window).
xbrushwidth
Linewidth for graph (see xgridwidth for border and grid). Valid for MS Windows GUI, X11, gnuplot and Postscript.
xgridwidth
Linewidth for border and grid. Valid for MS Windows GUI, X11, gnuplot and Postscript.
plotstyle
This should be one of linplot, combplot, or pointplot. linplot, the default, causes points to be plotted as parts of connected lines. combplot
causes a comb plot to be done. It plots vectors by drawing a vertical line from each point to the X-axis, as opposed to joining the points.
pointplot causes each point to be plotted separately.
nolegend
Don't plot the legend, when using the plot command.
General Form:
The xycontour switch is ignored if the data is not from a 2D Cider model. expr is a single plotarg expression which specifies the vector to be plotted.
file has the same meaning as in section 18.7.1 previously. The only variable which affects the gnuplot xycontour option is gnuplot_terminal.
Before a plot can be created, the Cider solution file containing the data you are interested in must be loaded with the LOAD (17.5.45) command. The
example later in this section demonstrates the steps to be followed.
The Cider OUTPUT command (see 30.14) explains how to get solution files for a Cider model. It is important to include a 'rootfile' parameter in the
OUTPUT command which specifies a subdirectory to hold the solution files themselves. Depending on the analysis type, solution files have a prefix OP,
DC, or TR. There can be many of these files created, one per DC sweep value or per TR time step, so it is essential the 'rootfile' subdirectory is
created prior to running ngspice to generate the solution files. In addition, device instances D*, Q*, and M* of Cider models need to have the 'SAVE'
parameter set.
The 2D Cider models are NUMD level 2 (see 30.17), NBJT level 2 (see 30.18), and NUMOS (see 30.19). 1D Cider models are level 1 NUMD and
NBJT. The solution files for 1D models can be plotted as the normal curves using PLOT (17.5.53) and GNUPLOT (without xycontour, 17.5.35 and
18.7.1).
mkdir ./j1root
ngspice -b jfet1.cir
1. The QJ1 instance line has the 'SAVE' parameter, and the 'rootfile' subdirectory is specified on the output statement.
2. A Cider solution file is loaded after the simulation has run and before the gnuplot commands:
load ./j1root/DC.12.qj1
The currently active vectors are listed after the load.
3. The sleep commands (or timeout /t on Windows) give the display time to draw the contours. This is only necessary when executing a batch
script; for an interactive session they are not required.
4. The contours of a single vector phin are plotted by:
gnuplot gplot1 xycontour phin
5. The contours of the electric field magnitude are plotted by:
gnuplot gplot2 xycontour sqrt((ex * ex) + (ey * ey))
6. The gnuplot_terminal variable controls the output from gnuplot:
set gnuplot_terminal=png/quit
7. Following this, gnuplot commands will send the plot to a .png file.
.control
dc vgg 0.0 -2.0001 -0.1
print i(vss)
load ./j1root/DC.12.qj1
shell 'sleep 1'
gnuplot gplot1 xycontour phin
shell 'sleep 1'
gnuplot gplot2 xycontour sqrt((ex * ex) + (ey * ey))
shell 'sleep 1'
set gnuplot_terminal=png/quit
gnuplot gplot3 xycontour phin
shell 'sleep 1'
gnuplot gplot4 xycontour sqrt((ex * ex) + (ey * ey))
shell 'sleep 1'
quit
.endc
.end
18.8.1 KiCad
KiCad is a cross platform and open source electronics design automation suite. Its schematic editor Eeschema fully integrates shared ngspice (see
Chapt. 19) as the simulation tool. On the ngspice web pages there is a tutorial available which presents an introduction to using ngspice from within
KiCad..
18.8.2 Xschem
Xschem is a schematic capture program, it allows to create a hierarchical representation of circuits with a top down approach . By focusing on
interconnections, hierarchy and properties a complex system (IC) can be described in terms of simpler building blocks. A VHDL, Verilog or ngspice
netlist can be generated from the drawn schematic, allowing the simulation of the circuit.
18.8.4 XCircuit
CYGWIN and especially Linux users may find XCircuit valuable to establish a development flow including schematic capture and circuit simulation.
18.8.5 GEDA
The gEDA project is developing a full GPL‘d suite and toolkit of Electronic Design Automation tools for use with a Linux. Ngspice may be integrated
into the development flow. Two web sites offer tutorials using gschem and gnetlist with ngspice:
http://geda-project.org/wiki/geda:csygas
http://geda-project.org/wiki/geda:ngspice_and_gschem
18.8.6 MSEspice
A graphical front end to ngspice, using the Free Pascal cross platform RAD environment MSEide+MSEgui.
So you may send an input `file' with a netlist to ngspice, start the simulation in a separate thread, read back simulation data at each time point, stop the
simulator depending on some condition, alter device or model parameters and then resume the simulation.
Shared ngspice does not have any user interface. The calling process is responsible for this. It may offer a graphical user interface, add plotting
capability or any other interactive element. You may develop and optimize these user interface elements without a need to alter the ngspice source
code itself, using a console application or GUIs like gtk, Delphi, Qt or others.
Other operation systems (Mac OS, BSD, ...) have not been tested so far. Your input is welcome!
vector_info
The next two structures are used by the callback function SendInitData (see 19.3.3.5). Each time a new plot is generated during simulation, e.g. when
a sequence of op, ac or tran is used, or commands like linearize or fft are invoked, the function is called once by ngspice. Among its parameters
you find a pointer to a struct vecinfoall, which includes an array of vecinfo, one for each vector. Pointers to the struct dvec, containing the vector, are
included.
vecinfo
vecinfoall
} vecinfoall, *pvecinfoall;
The next two structures are used by the callback function SendData (see 19.3.3.4). Each time a new data point (e.g. time value and simulation output
value(s)) is added to the vector structure of the current plot, the function SendData is called by ngspice, among its parameters the actual pointer
pvecvaluesall, which contains an array of pointers to pvecvalues, one for each vector. Logic return values are of type NG_BOOL, which is typedefed to
int.
vecvalues
vecvaluesall
SendChar*
callback function for reading printf, fprintf, fputs (NULL allowed)
SendStat*
callback function for reading status string and percent value (NULL allowed)
ControlledExit*
callback function for transferring a flag to caller, generated by ngspice upon a call to function controlled_exit. May be used by caller to detach
ngspice.dll, if dynamically loaded or to try any other recovery method, or to exit. (required)
SendData*
callback function for sending an array of structs containing data values of all vectors in the current plot (simulation output) (NULL allowed)
SendInitData*
callback function for sending an array of structs containing info on all vectors in the current plot (immediately before simulation starts) (NULL
allowed)
BGThreadRunning*
callback function for sending a boolean signal (true if thread is running) (NULL allowed)
void*
Using the void pointer, you may send the object address of the calling function ('self' or 'this' pointer) to ngspice.dll. This pointer will be
returned unmodified by any callback function (see the *void pointers in Chapt. 19.3.3). Callback functions are to be defined in the global
section of the caller. Because they now have got the object address of the calling function, they may direct their actions to the calling object.
Sending ngSpice_Command(NULL) will clear the internal control structures. Each command sent to ngspice is stored in the control structures. If you
run scripts with 10.000 or more commands, sending NULL from time to time will release this memory.
SendEvtData*
data for a specific event node at time 'step'
SendInitEvtData*
single line entry of event node dictionary (list)
void*
pointer to user-defined data, will not be modified, but handed over back to caller during Callback, e.g. address of calling object
If XSPICE is enabled, additional callback functions are made accessible by ngSpice_Init_Evt(...) to obtain digital event node data.
If ngspice is run in the background thread (19.4.2), the callback functions (defined in the caller) also are called from within that thread. One has to be
carefully judging how this behavior might influence the caller, where now you have the primary and the background thread running in parallel. So
make the callback function thread safe. The integer identification number is only used if you run several shared libraries in parallel (see Chapt. 19.6).
Three additional callback function are described in Chapt. 19.6.3.
char*
string to be sent to caller output
int
identification number of calling ngspice shared lib (default is 0, see Chapt. 19.6)
void*
return pointer received from caller during initialization, e.g. pointer to object having sent the request
Sending output from stdout, stderr to caller. ngspice printf, fprintf, fputs, fputc functions are redirected to this function. The char* string is generated
by assembling the print outputs of the above mentioned functions according to the following rules: The string commences with `stdout ', if directed
to stdout by ngspice (with `stderr ' respectively); all tokens are assembled in sequence, taking the printf format specifiers into account, until `\n' is
hit. If set addescape is given in .spiceinit, the escape character \ is added to any character from $[]\" found in the string.
Each callback function has a void pointer as the last parameter. This is useful in object oriented programming. You may have sent the this (or self)
pointer of the caller's class object to ngspice.dll during calling ngSpice_Init (19.3.2.1). The pointer is returned unmodified by each callback, so the
callback function may identify the class object that has initialized ngspice.dll.
char*
simulation status and value (in percent) to be sent to caller
int
identification number of calling ngspice shared lib (default is 0, see Chapt. 19.6)
void*
return pointer received from caller
int
exit status
NG_BOOL
if true: immediate unloading dll, if false: just set flag, unload is done when function has returned
NG_BOOL
if true: exit upon 'quit', if false: exit due to ngspice.dll error
int
identification number of calling ngspice shared lib (default is 0, see Chapt. 19.6)
void*
return pointer received from caller
vecvaluesall*
pointer to array of structs containing actual values from all vectors
int
number of structs (one per vector)
int
identification number of calling ngspice shared lib (default is 0, see Chapt. 19.6)
void*
return pointer received from caller
vecinfoall*
pointer to array of structs containing data from all vectors right after initialization
int
identification number of calling ngspice shared lib (default is 0, see Chapt. 19.6)
void*
return pointer received from caller
NG_BOOL
false if background thread is running, otherwise true
int
identification number of calling ngspice shared lib (default is 0, see Chapt. 19.6)
void*
return pointer received from caller
19.3.3.7 typedef int (SendEvtData)(int, double, double, char *, void *, int, int, int, void*)
int
node index
double
actual simulation time
double
a real value for specified structure component for plotting purposes
char*
a string value for specified structure component for printing
void*
a binary data structure
int
size of the binary data structure
int
the mode (op, dc, tran) we are in
int
identification number of calling ngspice shared lib
void*
return pointer received from caller
int
node index
int
maximum node index, number of nodes
char*
node name
char*
udn-name, node type
int
identification number of calling ngspice shared lib
void*
return pointer received from caller
Upon initialization, called once per event node to build up a dictionary of nodes.
Typically you should not include a .control section in your input file. Any script described in a .control section for standard ngspice should better
be emulated by the caller and be sent directly to ngspice.dll. Start the simulation according to Chapt. 19.4.2 in an extra thread.
As an alternative, only the netlist has to be entered (without analysis command), then you may use any interactive command as listed in Chapt. 17.5
(except for the plot command).
However, for users without direct access to source code commands (e.g. KiCad users), it might be advantageous to add a .control section to their
netlist simulation dot commands. please be careful and check for chapter 19.4.1.4.
The `typical usage' examples given below are part of a caller written in C.
Typical usage:
ngSpice_Command("source ../examples/adder_mos.cir");
Typical usage:
The first line is a title line, which will be ignored during circuit parsing. As soon as the line .end has been sent to ngspice, circuit parsing commences.
Typical usage:
An array of char pointers is malloc'd, each netlist line is then copied to the array. strdup will care for the memory allocation. The first entry to the
array is a title line, the last entry has to contain NULL. ngSpice_Circ(circarray); sends the array to ngspice, where circuit parsing is started
immediately. Don't forget to free the array after sending it, to avoid a memory leak.
For the latter two options to load a netlist, there is some caveat though. When sending the netlist from caller to shared ngspice, ngspice will not get
any automatic notion of a potential input directory, as is possible and useed with standard ngspice. You will either have to set the environmental
variable NGSPICE_INPUT_DIR to the input file path, especially when in the netlist other .include ./nextinput.inc commands with relative paths
are used or you are using XSPICE code models that require loading an input file. Or you may set the variable sourcepath (17.7) in .spiceinit. The
command
set sourcepath = ( D:/mypath/input $sourcepath )
will add D:/mypath/input to the front of the path list, only this leading path entry is sent to the code models.
Typical usage:
ngSpice_Command("bg_run");
...
ngSpice_Command("bg_halt");
...
ngSpice_Command("bg_resume");
Basically you may send the commands 'run' or 'resume' (no prefix bg_), starting ngspice within the main thread. The caller then has to wait until
ngspice returns from simulation. A command 'halt' is not available then.
After simulation is finished (test with callback 19.3.3.6), you may send other commands from Chapt. 17.5, emulating any .control script. These
commands are executed in the main thread, which should be okay because execution time is typically short.
Each time a new plot is generated during simulation, e.g. when a sequence of op, ac and tran is used or commands like linearize or fft are invoked,
the callback SendInitData is called by ngspice. Immediately after setting up the vector structure of the new plot, the function is called once. Its
parameter is a pointer to the structure vecinfoall (19.3.1), which contains an array of structures vecinfo, one for each vector in the actual plot. You
may simply use vecname to get the name of any vector. This time the vectors are still empty, but pointers to the vector structure are available.
Each time a new data point (e.g. time value and simulation output value(s)) is added to the vector structure of the current plot, the function SendData
is called by ngspice. This allows you to immediately access the simulation output synchronized with the simulation time, e.g. to interface it to a
runtime plot or to use it for some controlled simulation by stopping the simulation based on a condition, altering parameters and resume the
simulation. SendData returns a structure vecvaluesall as parameter, which contains an array of structures vecvalues, one for each vector.
Some code to demonstrate the callback function usage is referenced below (19.5).
Again some code to demonstrate the callback function usage is referenced below (19.5).
During simulation, after each time step ngspice checks if a node has changed. If so, SendEvtData is called for each node that changed, returning the
simulation time, the node number, and the node value as a char* string, consisting of one out of 0s, 1s, Us, 0r, 1r, Ur, 0z, 1z, Uz, 0u, 1u, Uu (see
12.5.1). The double real value and the void* binary data structure arguments are for future enhancements of the data interface. The int mode returns 0
for op, 1 for dc, 2 for ac , and 3 for tran simulation. The final int is useful to identify the ngspice lib by number if you run several in parallel (see
19.6). The final *void just returns the pointer received from caller. e.g. to identify the calling object.
19.4.5 Output
After the simulation is finished, use the ngspice commands write (17.5.104) or wrdata (17.5.103) to output data to a file as usual, use the print
command (17.5.56) to retrieve data via callback SendChar (19.3.3.1), or refer to accessing the data as described in Chapt. 19.4.3.
Typical usage:
If ngspice has been linked at runtime by dlopen/LoadLibrary (see 19.2.2), the callback may close all threads, and then detach ngspice.dll by
invoking dlclose/FreeLibrary. The caller may then restart ngspice by another loading and initialization (19.3.2.1).
If ngspice is included during linking the caller (see 19.2.1), there is not yet a good and general solution to error handling, if the error is non-
recoverable from inside ngspice.
ng_start.exe is a MS Windows application loading ngspice.dll dynamically. All functions and callbacks of the interface are assessed. The source
code, generated with Turbo Delphi 2006, may be found here, the binaries compiled for 32 Bit are here.
Two console applications, compilable with Linux, CYGWIN, MINGW or MS Visual Studio, are available here, demonstrating either linking upon
start-up or loading shared ngspice dynamically at runtime. A simple feedback loop is shown in tests 3 and 4, where a device parameter is changed
upon having an output vector value crossing a limit.
An XSPICE event node example may be assessed at ngspice/visualc/ng_shared_xspice_v, currently tested only with MS Windows and compiled with
Visual Studio.
19.6.1 Go parallel!
A simple way to run several invocations of ngspice in parallel for transient simulation is to define a caller that loads two or more ngspice shared
libraries. There is one prerequisite however to do so: the shared libraries have to have different names. So compile ngspice shared lib (see 19.1), then
copy and rename the library file, e.g. ngspice.dll may become ngspice1.dll, ngspice2.dll etc. Then dynamically load ngspice1.dll, retrieve its
address, initialize it by calling ngSpice_init() (see 19.3.2.1), then continue initialization by calling ngSpice_init_Sync() (see 19.6.2.1). An integer
identification number may be sent during this step to later uniquely identify each invocation of the shared library, e.g. by having any callback use this
identifier. Repeat the sequence with ngspice2.dll and so on.
Inter-process communication and synchronization is now done by using three callback functions. To understand their interdependence, it might be
useful to have a look at the transient simulation sequence as defined in the ngspice source file dctran.c. The following listing includes the shared
library option (It differs somewhat from standard procedure) and disregards XSPICE.
1. initialization
2. calculation of operating point
3. next time step: set new breakpoints (VSRC, ISRC, TRA, LTRA)
4. send simulation data to output, callback function SendData* datfcn
5. check for autostop and other end conditions
6. check for interrupting simulation (e.g. by bg_halt)
7. breakpoint handling (e.g. enforce breakpoint, set new small cktdelta if directly after the breakpoint)
8. calling ngspice internal function sharedsync() that invokes callback function GetSyncData* getsync with location flag loc = 0
9. save the previous states
10. start endless loop
11. save cktdelta to olddelta, set new time point by adding cktdelta to ckttime
12. new iteration of circuit at new time point, which uses callback functions GetVSRCData* getvdat and GetISRCData* getidat to retrieve
external voltage or current inputs, returns redostep=0, if converged, redostep=1 if not converged
13. if not converged, divide cktdelta by 8
14. check for truncation error with all non-linear devices, if necessary create a new (smaller) cktdelta to limit the error, optionally change
integration order
15. calling ngspice internal function sharedsync() that invokes callback function GetSyncData* getsync with location flag loc = 1: as a result
either goto 3 (next time step) or to 10 (loop start), depending on ngspice and user data, see the next paragraph.
The code of the synchronization procedure is handled in the ngspice internal function sharedsync() and its companion user defined callback function
GetSyncData* getsync. The actual setup is as follows:
If no synchronization is asked for (GetSyncData* set to NULL), program control jumps to 'next time step' (3) if redostep==0, or subtracts olddelta
from ckttime and jumps to 'loop start' (9) if redostep <> 0. This is the standard ngspice behavior.
If GetSyncData* has been set to a valid address by ngSpice_Init_Sync(), the callback function getsync is involved. If redostep <> 0, olddelta is
subtracted from ckttime, getsync is called, either the cktdelta time suggested by ngspice is kept or the user provides his own deltatime, and the
program execution jumps to (9) for redoing the last step with the new deltatime. The return value of getsync is not used. If redostep == 0, getsync is
called. The user may keep the deltatime suggested by ngspice or define a new value. If the user sets the return value of getsync to 0, the program
execution then jumps to 'next time step' (3). If the return value of getsync is 1, olddelta is subtracted from ckttime, and the program execution jumps
to (9) for redoing the last step with the new deltatime. Typically the user provided deltatime should be smaller than the value suggested by ngspice.
GetVSRCData*
callback function for retrieving a voltage source value from caller (NULL allowed)
GetISRCData*
callback function for retrieving a current source value from caller (NULL allowed)
GetSyncData*
callback function for synchronization (NULL allowed)
More pointers
int*
pointer to integer unique to this shared library (defaults to 0)
void*
pointer to user-defined data, will not be modified, but handed over back to caller during Callback, e.g. address of calling object. If NULL is sent
here, userdata info from ngSpice_Init() will be kept, otherwise userdata will be overridden by new value from here.
double*
return voltage value
double
actual time
char*
node name
int
identification number of calling ngspice shared lib
void*
return pointer received from caller
Ask for a VSRC EXTERNAL voltage value. The independent voltage source (see Chapt. 4.1) with EXTERNAL option sets a voltage value to the
node defined in the netlist and named here at the time returned by the simulator.
double*
return current value
double
actual time
char*
node name
int
identification number of calling ngspice shared lib
void*
return pointer received from caller
Ask for ISRC EXTERNAL value. The independent current source (see Chapt. 4.1) with EXTERNAL option allows setting a current value to the node
defined by the netlist and named here at the time returned by the simulator.
double
actual time (ckt->CKTtime)
double*
delta time (ckt->CKTdelta)
double
old delta time (olddelta)
int
identification number of calling ngspice shared lib
int
location of call for synchronization in dctran.c
void*
return pointer received from caller
Ask for new delta time depending on synchronization requirements. See 19.6.1 for an explanation.
Chapter 20 TCLspice
Spice historically comes as a simulation engine with a Command Line Interface. The Spice engine can also be used with a Graphical User Interface.
Tclspice represents a third approach to interfacing ngspice simulation functionality. Tclspice is nothing more than a new way of compiling and using
SPICE source code. Spice is no longer considered as a standalone program but as a library invoked by a TCL interpreter. It either permits direct
simulation in a TCL shell (this is quite analogous to the command line interface of ngspice), or it permits the elaboration of more complex, more
specific, or more user friendly simulation programs, by writing TCL scripts.
Making tclspice (see 20.6) produces two files: libspice.so and pkgIndex.tcl. libspice.so is the executable binary that the TCL interpreter calls to
handle SPICE commands. pkgIndex.tcl take place in the TCL directory tree, providing the SPICE package1 to the TCL user.
BLT is a TCL package. It is quite well documented. It permits handling mathematical vector data structures for calculus and display, in a Tk
interpreter like wish.
20.3 spicetoblt
Tclspice opens its doors to TCL and BLT with a single specific command spicetoblt.
TCLspice gets its identity in the command spice::vectoblt . This command copies data computed by the simulation engine into a tcl variable. vectoblt
is composed of three words: vec, to and blt. Vec means SPICE vector data. To is the English preposition, and blt is a useful tcl package providing a
vector data structure. Example:
Here an empty blt vector is created. It is then filled with the vector representation of the current flowing out of source Vex. Vex#branch is native
SPICE syntax. Iex is the name of the BLT vector.
The reverse operation is handled by native SPICE commands, such as alter, let and set.
load /somepath/libspice.so
package require spice
Then you can execute any native SPICE command by preceding it with spice::. For example if you want to source the testCapa.cir netlist, type the
following:
spice::source testCapa.cir
spice::spicetoblt example...
Plotting data is not a matter of SPICE, but of tcl. Once the data is stored in a blt vector, it can be plotted. Example:
and not the least, plots the function 𝐶𝑖𝑚 = 𝑓(𝑉𝑐𝑚𝑑 ), where 𝐶𝑖𝑚 and 𝑉𝑐𝑚𝑑 are two BLT vectors.
With blt::graph a plotting structure is allocated in memory. With pack it is placed into the output window, and becomes visible. The last command,
20.5 examples
20.5.1 Active capacitor measurement
graph representing virtual capacitance versus a control voltage. The function 𝐶 = 𝑓(𝑉) is calculated point by point. For each control voltage value,
This is a crude implementation of a circuit described by Marc Kodrnja, in his PhD thesis that was found on the Internet. The simulation outputs a
the virtual capacitance is calculated in a frequency simulation. A control value that should be as close to zero as possible is calculated to assess
simulation success.
20.5.1.1 Invocation:
This script can be invoked by typing wish testbench1.tcl
20.5.1.2 testbench1.tcl
This line loads the simulator capabilities
This is a comment (Quite useful if you intend to live with other Human beings)
spice::source "testCapa.cir"
BLT vector is the structure used to manipulate data. Instantiate the vectors
Data is, in my coding style, plotted into graph objects. Instantiate the graph
pack .freqanal
Plot
pack .cimvd
.cimvd element create line1 -xdata Vcmd -ydata Cim
pack .checkvd
.checkvd element create line1 -xdata Vcmd -ydata check
The temperature response of a CTN is exponential. It is thus nonlinear. In a battery charger application floating voltage varies linearly with
temperature. A TL431 voltage reference sees its output voltage controlled by two resistors (r10, r12) and a thermistor (r11). The simulation is run at a
given temperature. The thermistor is modeled in SPICE by a regular resistor. Its resistivity is assessed by the TCL script. It is set with a spice::alter
command before running the simulation. This script uses an iterative optimization approach to try to converge to a set of two resistor values that
minimizes the error between the expected floating voltage and the TL431 output.
20.5.2.1 Invocation:
This script can be executed by the user by simply executing the file in a terminal.
./testbench3.tcl
During optimization loop, graphical display of the current temperature response is not yet possible and I don't know why. Each time a
simulation is performed, some memory is allocated for it.
The simulation result remains in memory until the libspice library is unloaded (typically: when the tcl script ends) or when a spice::clean
command is performed. In this kind of simulation, not cleaning the memory space will freeze your computer and you'll have to restart it. Be
aware of that.
20.5.2.2 testbench3.tcl
This calls the shell sh who then runs wish with the file itself.
#!/bin/sh
# WishFix \
exec wish "$0" ${1+"$@"}
#
#
#
Here the important line is source differentiate.tcl that contains the optimization library
source differentiate.tcl
generates thermistor resistivity as a vector, typically run: thermistance_calc res B [ temperatures_calc temp_inf temp_sup points ]
generates the expected floating value as a vector, typically run: tref_calc res B [ temperatures_calc temp_inf temp_sup points ]
In the optimization algorithm, this function computes the effective floating voltage at the given temperature.
### NOTE:
### As component values are modified by a spice::alter
### Component values can be considered as global variable.
### R10 and R12 are not passed to iteration function
### because it is expected to be correct, i.e. to
### have been modified soon before
proc iteration { t } { set tzero 273.15 spice::alter
r11 = [ thermistance_calc 10000 3900 $t ]
# Temperature simulation often crashes. Comment it out...
#spice::set temp = [ expr " $tzero + $t " ]
spice::op
spice::vectoblt vref_temp tref_tmp
### NOTE:
### As the library is executed once for the
### whole script execution, it is important to manage the memory
### and regularly destroy unused data set. The data
### computed here will not be reused. Clean it
spice::destroy all return [ tref_tmp range 0 0 ] }
This is the cost function optimization algorithm will try to minimize. It is a 2-norm (Euclidean norm) of the error across the temperature range
[-25:75]°C.
This function displays the expected and effective value of the voltage, as well as the r10 and r12 resistor values
#
# Optimization
# blt::vector create tref_tmp
blt::vector create tref_blt
blt::vector create expected_blt
blt::vector create temperatures_blt temperatures_blt
append [ temperatures_calc -25 75 30 ] expected_blt
append [ tref_calc [temperatures_blt range 0
+ [ expr " [ temperatures_blt length ] - 1" ] ] ]
blt::graph .g
pack .g -side top -fill both -expand true
.g element create real -pixels 4 -xdata temperatures_blt
+ -ydata tref_blt
.g element create expected -fill red -pixels 0 -dashes
+ dot -xdata temperatures_blt -ydata expected_blt
Source the circuit and optimize it. The result is retrieved in the variable r10r12e and put into r10 and r12 with a regular expression. A bit ugly.
spice::source FB14.cir
set r10r12 [ ::math::optimize::minimumSteepestDescent
+ cost { 10000 10000 } 0.1 50 ]
regexp {([0-9.]*) ([0-9.]*)} $r10r12 r10r12 r10 r12
#
# Results
# spice::alter r10 = $r10
spice::alter r12 = $r12
foreach point [ temperatures_blt range 0
+ [ expr " [temperatures_blt length ] - 1" ] ] {
tref_blt append [ iteration $point ]
}
disp_curve $r10 $r12
20.5.3.1 testbench2.tcl
#!/bin/sh
# WishFix \
exec wish -f "$0" ${1+"$@"}
###
package require BLT package require spice
A strip chart with labels but without data is created and displayed (packed)
stripchart .chart
pack .chart -side top -fill both -expand true
.chart axis configure x -title "Time" spice::source example.cir
spice::bg
run after 1000 vector
create a0 vector
create b0 vectorry
create a1 vector
create b1 vector
create stime
proc bltupdate {} {
puts [spice::spice_data]
spice::spicetoblt a0 a0
spice::spicetoblt b0 b0
spice::spicetoblt a1 a1
spice::spicetoblt b1 b1
spice::spicetoblt time stime
after 100 bltupdate }
bltupdate .chart element create a0 -color red -xdata
+ stime -ydata a0
.chart element create b0 -color blue -xdata stime -ydata b0
.chart element create a1 -color yellow -xdata stime -ydata a1
.chart element create b1 -color black -xdata stime -ydata b1
20.6 Compiling
20.6.1 Linux
Get tcl8.4 from your distribution. You will need the blt plotting package (compatible to the old tcl 8.4 only) from here. See also the actual blt wiki.
./configure --with-tcl ..
make
sudo make install
20.6.2 MS Windows
Can be done, but is tedious. Here it is described by a procedure on Windows 7, 64 Bit Home Edition.
20.6.2.1 Downloads
download tcl8.6b2-src.zip from http://www.tcl.tk/software/tcltk/download.html
download tk8.6b2-src.zip
20.6.2.2 Tcl
double click on D:\software\tcl8.6b2\win\tcl.dsw
20.6.2.3 Tk
edit D:\software\tk8.6b2\win\buildall.vc.bat
line 31 to
line 53 to
cd to
d:\software\tk8.6b2\win>
then
20.6.2.4 blt
blt source files have been downloaded from the blt web page and modified for compatibility with TCL8.6. To facilitate making blt24.dll, the modified
source code is available as a 7z compressed file, including a project file for MS Visual Studio 2008.
20.6.2.5 tclspice
ngspice is compiled and linked into a dll called spice.dll that may be loaded by wish86t.exe. MS Visual Studio 2008 is the compiler applied. A
project file may be downloaded as a 7z compressed file. Expand this file in the ngspice main directory. The links to tcl and tk are hard-coded, so both
have to be installed in the places described above (d:\software\...). spice.dll may be generated in Debug, Release or ReleaseOMP mode.
The first example uses the simple one-transistor amplifier circuit illustrated in Fig. 21.1. This circuit is constructed entirely with ngspice compatible
devices and is used to introduce basic concepts, including:
Example:
To simulate this circuit, move into a directory under your user account and copy the file xspice_c1.cir from directory /examples/xspice/. This file
stems from the original XSPICE introduction, therefore its name, but you do not need to have a version of ngspice with the XSPICE option to run it.
$ cp /examples/xspice/xspice_c1.cir xspice_c1.cir
Now invoke the simulator on this circuit as follows:
$ ngspice xspice_c1.cir
After a few moments, you should see the ngspice prompt:
ngspice 1 ->
At this point, ngspice has read-in the circuit description and checked it for errors. If any errors had been encountered, messages describing them
would have been output to your terminal. Since no messages were printed for this circuit, the syntax of the circuit description was correct.
To see the circuit description read by the simulator you can issue the following command:
ngspice 1 -> listing
The simulator shows you the circuit description currently in memory:
a berkeley spice3 compatible circuit
1 : a berkeley spice3 compatible circuit
2 : .global gnd
10 : .tran 1e-5 2e-3
12 : vcc vcc 0 12.0
13 : vin 1 0 0.0 ac 1.0 sin(0 1 1k)
14 : ccouple 1 base 10uf
15 : rbias1 vcc base 100k
16 : rbias2 base 0 24k
17 : q1 coll base emit generic
18 : rcollector vcc coll 3.9k
19 : remitter emit 0 1k
21 : .model generic npn
24 : .end
The title of this circuit is `A Berkeley SPICE3 compatible circuit'. The circuit description contains a transient analysis control command .TRAN 1E-5
2E-3 requesting a total simulated time of 2ms with a maximum time-step of 10us. The remainder of the lines in the circuit description describe the
circuit of Fig. 21.1.
To examine the results of this transient analysis, we can use the plot command. First we will plot the nodes labeled `1' and `base'.
ngspice 2 -> plot v(1) base
The simulator responds by displaying an X Window System plot similar to that shown in Fig. 21.2.
If we had desired to plot the difference between the voltage at node `base' and node `1', we would need to enclose the node name `1' in the
construction v( ) producing a command such as plot (base - v(1)).
Now, issue the following command to examine the voltages on two of the internal nodes of the transistor amplifier circuit:
ngspice 3 -> plot vcc coll emit
The plot shown in Fig. 21.3 should appear. Notice in the circuit description that the power supply voltage source and the node it is connected to both
have the name `vcc'. The plot command above has plotted the node voltage `vcc'. However, it is also possible to plot branch currents through voltage
sources in a circuit. ngspice always adds the special suffix #branch to voltage source names. Hence, to plot the current into the voltage source named
vcc, we would use a command such as plot vcc#branch.
To run the DC simulation of the transistor amplifier, issue the following command:
ngspice 4 -> op
After a moment the ngspice prompt returns. Now issue the print command to examine the emitter, base, and collector DC bias voltages.
ngspice 5 -> print emit base coll
ngspice responds with:
emit = 1.293993e+00 base = 2.074610e+00 coll = 7.003393e+00
To run an AC analysis, enter the following command:
ngspice 6 -> ac dec 10 0.01 100
This command runs a small-signal swept AC analysis of the circuit to compute the magnitude and phase responses. In this example, the sweep is
logarithmic with `decade' scaling, 10 points per decade, and lower and upper frequencies of 0.01 Hz and 100 Hz. Since the command sweeps through
a range of frequencies, the results are vectors of values and are examined with the plot command. Issue to the following command to plot the
response curve at node `coll':
ngspice 7 -> plot coll
This plot shows the AC gain from input to the collector. (Note that our input source in the circuit description `vin' contained parameters of the form
`AC 1.0' designating that a unit-amplitude AC signal was applied at this point.) For plotting data from an AC analysis, ngspice chooses automatically
a logarithmic scaling for the frequency (x) axis.
To produce a more traditional `Bode' gain phase plot (again with automatic logarithmic scaling on the frequency axis), we use the expression
capability of the plot command and the built-in ngspice functions db( ) and ph( ):
ngspice 8 -> plot db(coll) ph(coll)
The last analysis supported by ngspice is a swept DC analysis. To perform this analysis, issue the following command:
ngspice 9 -> dc vcc 0 15 0.1
This command sweeps the supply voltage `vcc' from 0 to 15 volts in 0.1 volt increments. To plot the results, issue the command:
ngspice 10 -> plot emit base coll
Finally, to exit the simulator, use the quit command, and you will be returned to the operating system prompt.
ngspice 11 -> quit
So long.
Example:
Example:
Example:
Example:
.SUBCKT ONEBIT 1 2 3 4 5 6
* NODES: INPUT(2), CARRY-IN, OUTPUT, CARRY-OUT, VCC
X1 1 2 7 6 NAND
X2 1 7 8 6 NAND
X3 2 7 9 6 NAND
X4 8 9 10 6 NAND
X5 3 10 11 6 NAND
X6 3 11 12 6 NAND
X7 10 11 13 6 NAND
X8 12 13 4 6 NAND
X9 11 7 5 6 NAND
.ENDS ONEBIT
.SUBCKT TWOBIT 1 2 3 4 5 6 7 8 9
* NODES: INPUT - BIT0(2) / BIT1(2), OUTPUT - BIT0 / BIT1,
* CARRY-IN, CARRY-OUT, VCC
X1 1 2 7 5 10 9 ONEBIT
X2 3 4 10 6 8 9 ONEBIT
.ENDS TWOBIT
.SUBCKT FOURBIT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
* NODES: INPUT - BIT0(2) / BIT1(2) / BIT2(2) / BIT3(2),
* OUTPUT - BIT0 / BIT1 / BIT2 / BIT3, CARRY-IN, CARRY-OUT, VCC
X1 1 2 3 4 9 10 13 16 15 TWOBIT
X2 5 6 7 8 11 12 16 14 15 TWOBIT
.ENDS FOURBIT
Example:
*** POWER
VCC 99 0 DC 3.3V
*** INPUTS
VIN1A 1 0 DC 0 PULSE(0 3 0 5NS 5NS 20NS 50NS)
VIN1B 2 0 DC 0 PULSE(0 3 0 5NS 5NS 30NS 100NS)
VIN2A 3 0 DC 0 PULSE(0 3 0 5NS 5NS 50NS 200NS)
VIN2B 4 0 DC 0 PULSE(0 3 0 5NS 5NS 90NS 400NS)
VIN3A 5 0 DC 0 PULSE(0 3 0 5NS 5NS 170NS 800NS)
VIN3B 6 0 DC 0 PULSE(0 3 0 5NS 5NS 330NS 1600NS)
VIN4A 7 0 DC 0 PULSE(0 3 0 5NS 5NS 650NS 3200NS)
VIN4B 8 0 DC 0 PULSE(0 3 0 5NS 5NS 1290NS 6400NS)
*** DEFINE NOMINAL CIRCUIT
X1 1 2 3 4 5 6 7 8 9 10 11 12 0 13 99 FOURBIT
.option acct
.save V(1) V(2) V(3) V(4) V(5) V(6) V(7) V(8) $ INPUTS
.save V(9) V(10) V(11) V(12) V(13) $ OUTPUTS
.END
Example:
Transmission-line inverter
v1 1 0 pulse(0 1 0 0.1n)
r1 1 2 50
x1 2 0 0 4 tline
r2 4 0 50
.subckt tline 1 2 3 4
t1 1 2 3 4 z0=50 td=1.5ns
t2 2 0 4 0 z0=100 td=1ns
.ends tline
To obtain circuits operating reliably under varying parameters, it might be necessary to simulate them taking certain parameter spreads into account.
ngspice offers several methods supporting this task. A powerful random number generator is working in the background. It is not providing true
random numbers, but a long sequence of pseudo random numbers. This sequence depends on a seed value. The same seed value will deliver the same
sequence of random numbers.
ngspice offers several methods to set this seed value. If no input is given, then ngspice sets the seed (stored in variable rndseed) to 1 upon start up.
With the option SEED you may either set a value to rndseed upon start up of ngspice (option SEED=nn, nn is an integer greater than 0), or obtain a
“random” number as seed, that is the number of seconds since 01.01.1970 (option SEED=random). This command is best set in .spiceinit (16.6). With
the command setseed (see chapt.17.5.75) you may choose any other seed value (integer greater than 0).
The following three chapters offer a short introduction to the statistical methods available in ngspice. The diversity of approaches stems from
historical reasons, and from some efforts to make ngspice compatible to other simulators.
The frontend parser evaluates all .param or .func statements upon start-up of ngspice, before the circuit is evaluated. The parameters aga, aga2, lim
obtain their numerical values once. If the random function appears in a device card (e.g. v11 11 0 'agauss(1,2,3)'), a new random number is
generated.
So v1, v2, and v3 will get the same value, whereas v4 might differ. v11, v12, and v13 will get different values, v14, v15, and v16 will obtain the
values set above in the .param statements. .func will start its replacement algorithm, rgauss(a,b,c) will be replaced everywhere by
5*agauss(a,b,c).
Thus device and model parameters may obtain statistically distributed starting values. You simply set a model parameter not to a fixed numerical
value, but insert a 'parameter' instead, which may consist of a token defined in a .param card, by calling .func or by using a built-in function,
including the statistical functions described above. The parameter values will be evaluated once immediately after reading the input file.
An example circuit, a Wien bridge oscillator from input file /examples/Monte_Carlo/OpWien.sp is distributed with ngspice or available at Git. The
two frequency determining pairs of R and C are varied statistically using four independent Gaussian voltage sources as the controlling units. An
excerpt of this command sequence is shown below. The total simulation time ttime is divided into 100 equally spaced blocks. Each block will get a
new set of control voltages, e.g. VR2, which is Gaussian distributed, mean 0 and absolute deviation 1. The resistor value is calculated with ±10%
spread, the factor 0.033 will set this 10% to be a deviation of 1 sigma from nominal value.
* random resistor
.param res = 10k
.param ttime=12000m
.param varia=100
.param ttime10 = 'ttime/varia'
* random control voltage (Gaussian distribution)
VR2 r2 0 dc 0 trrandom (2 'ttime10' 0 1)
* behavioral resistor
R2 4 6 R = 'res + 0.033 * res*V(r2)'
So within a single simulation run you will obtain 100 different frequency values issued by the Wien bridge oscillator. The voltage sequence VR2 is
shown below.
The statistical functions provided for scripting are listed in the following table:
Name Function
rnd(vector) A vector with each component a random integer between 0
and the absolute value of the input vector's corresponding
integer element value.
sgauss(vector) Returns a vector of random numbers drawn from a
Gaussian distribution (real value, mean = 0 , standard
deviation = 1). The length of the vector returned is
determined by the input vector. The contents of the input
vector will not be used. A call to sgauss(0) will return a
single value of a random number as a vector of length 1..
sunif(vector) Returns a vector of random real numbers uniformly
distributed in the interval [-1 .. 1]. The length of the vector
returned is determined by the input vector. The contents of
the input vector will not be used. A call to sunif(0) will
return a single value of a random number as a vector of
length 1.
poisson(vector) Returns a vector with its elements being integers drawn
22.5.1 Example 1
The first examples is a LC band pass filter, where L and C device parameters will be changed 100 times. Each change is followed by an ac analysis.
All graphs of output voltage versus frequency are plotted. The file is available in the distribution as /examples/Monte_Carlo/MonteCarlo.sp as
well as from the git repository .
Monte-Carlo example 1
.end
22.5.2 Example 2
A more sophisticated input file for Monte Carlo simulation is distributed with the file /examples/Monte_Carlo/MC_ring.sp (or git repository). Due
to its length it is not reproduced here, but some comments on its enhancements over example 1 (22.5.1) are presented in the following.
A 25-stage ring oscillator is the circuit used with a transient simulation. It comprises of CMOS inverters, modeled with BSIM3. Several model
parameters (vth, u0, tox, L, and W) shall be varied statistically between each simulation run. The frequency of oscillation will be measured by a fft
and stored. Finally a histogram of all measured frequencies will be plotted.
The function calls to sunif(0) and sgauss(0) return uniformly or Gaussian distributed random numbers. A function unif, defined by the line
will return a value with mean nom and deviation var relative to nom.
The line
set n1vth0=@n1[vth0]
will store the threshold voltage vth0, given by the model parameter set, into a variable n1vth0, ready to be used by unif, aunif, gauss, or agauss
function calls.
In the simulation loop the altermod command changes the model parameters before a call to tran. After the transient simulation the resulting vector is
linearized, a fft is calculated, and the maximum of the fft signal is measured by the meas command and stored in a vector maxffts. Finally the contents
of the vector maxffts is plotted in a histogram.
For more details, please have a look at the strongly commented input file MC_ring.sp.
22.5.3 Example 3
The next example is contained in the files MC_2_control.sp and MC_2_circ.sp from folder /examples/Monte_Carlo/. MC_2_control.sp is a
ngspice script (see 17.8). It starts a loop by setting the random number generator seed value to the value of the loop counter, sources the circuit file
MC_2_circ.sp, runs the simulation, stores a raw file, makes an fft, saves the oscillator frequency thus measured, deletes all outputs, increases the
loop counter and restarts the loop. The netlist file MC_2_circ.sp contains the circuit, which is the same ring oscillator as of example 2. However,
now the MOS model parameter set, which is included with this netlist file, inherits some AGAUSS functions (see 2.9.5) to vary threshold voltage,
mobility and gate oxide thickness of the NMOS and PMOS transistors. This is an approach similar to what commercial foundries deliver within their
device libraries. So this example may be your source for running Monte Carlo with commercial libs. Start example 3 by calling
Open and run the command file in the Gnuplot command line window by
load 'pl-v4mag.p'
A Gaussian curve will be fitted to the simulation data. The mean oscillator frequency and its deviation are printed in the curve fitting log in the
Gnuplot window.
pl4mag.data is the simulation data, f2(x) the starting curve, f1(x) the fitted Gaussian distribution.
This is just a simple example. You might explore the powerful built-in functions of Gnuplot to do a much more sophisticated statistical data analysis.
You have to choose circuit variables as parameters to be varied during optimization (e.g. device size, component values, bias inputs etc.). Then you
may pose performance constraints onto you circuits (e.g. Vnode < 1.2V, gain > 50 etc.). Optimization objectives are the variables to be minimized or
maximized. The n objectives and m constraints are assembled into a cost function.
The optimization flow is now the following: The circuit is loaded. Several (perhaps only one) simulations are started with a suitable starter set of
variables. Measurements are done on the simulator output to check for the performance constraints and optimization objectives. These data are fed
into the optimizer to evaluate the cost function. A sophisticated algorithm now determines a new set of circuit variables for the next simulator run(s).
Stop conditions have to be defined by the user to tell the simulator when to finish (e.g. fall below a cost function value, parameter changes fall below
a certain threshold, number of iterations exceeded).
The optimizer algorithms, its parameters and the starting point influence the convergence behavior. The algorithms have to provide measures to
reaching the global optimum, not to stick to a local one, and thus are tantamount for the quality of the optimizer.
ngspice does not have an integral optimization processor. Thus this chapter will rely on work done by third parties to introduce ngspice optimization
capability. ngspice provides the simulation engine, a script or program controls the simulator and provides the optimizer functionality.
Four optimizers are presented here, using ngspice scripting language, using tclspice, using a Python script, and using ASCO, a c-coded optimization
program.
The simple example given in the scripts is OK with current ngspice. Real circuits have still to be tested.
ASCO is a standalone executable, which communicates with ngspice via ngspice input and output files. Several optimization examples, originally
provided by J. Ramos for other simulators, are prepared for use with ngspice. Parallel processing on a multi-core computer has been tested using MPI
(MPICH2) under MS Windows. A processor network will be supported as well. A MS Windows console application ngspice_c.exe is included in
the archive. Several stand alone tools are provided, but not tested yet.
Setting up an optimization project with ASCO requires advanced know-how of using ngspice. There are several sources of information. First of all the
examples provided with the distribution give hints how to start with ASCO. The original ASCO manual is provided as well, or is available here. It
elaborates on the examples, using a commercial simulator, and provides a detailed description how to set up ASCO. Installation of ASCO and MPI
(under Windows) is described in a file INSTALL.
Some remarks on how to set up ASCO for ngspice are given in the following sections (more to be added). These a meant not as a complete
description, but are an addition the the ASCO manual.
amp3.cfg
This file contains all configuration data for this optimization. Of special interest is the following section, which sets the required measurements and
the constraints on the measured parameters:
# Measurements #
ac_power:VDD:MIN:0
dc_gain:VOUT:GE:122
unity_gain_frequency:VOUT:GE:3.15E6
phase_margin:VOUT:GE:51.8
phase_margin:VOUT:LE:70
amp3_slew_rate:VOUT:GE:0.777E6
#
Each of these entries is linked to a file in the /extract subdirectory, having exactly the same names as given here, e.g. ac_power, dc_gain,
unity_gain, phase_margin, and amp3_slew_rate. Each of these files contains an # Info # section, which is currently not used. The # Commands
# section may contain a measurement command (including ASCO parameter #SYMBOL#, see file /extract/unity_gain_frequency). It also may
contain a .control section (see file /extract/phase_margin_min). During set-up #SYMBOL# is replaced by the file name, a leading `z', and a
trailing number according to the above sequence, starting with 0.
amp3.sp
This is the basic circuit description. Entries like #LM2# are ASCO-specific, defined in the # Parameters # section of file amp3.cfg. ASCO will
replace these parameter placeholders with real values for simulation, determined by the optimization algorithm. The .control ... .endc section is
specific to ngspice. Entries to this section may deliver workarounds of some commands not available in ngspice, but used in other simulators. You
may also define additional measurements, get access to variables and vectors, or define some data manipulation. In this example the .control section
contains an op measurement, required later for slew rate calculation, as well as the ac simulation, which has to occur before any further data
evaluation. Data from the op simulation are stored in a plot op1. Its name is saved in variable dt. The ac measurements sets another plot ac1. To
retrieve op data from the former plot, you have to use the {$dt}.<vector> notation (see file /extract/amp3_slew_rate).
n.typ, p.typ
from the console window. Several files will be created during checking. If you look at <computer-name>.sp: this is the input file for ngspice_c,
generated by ASCO. You will find the additional .measure commands and .control sections. The quit command will be added automatically just
before the .endc command in its own .control section. asco-test will display error messages on the console, if the simulation or communication with
ASCO is not ok. The output file <computer-name>.out, generated by ngspice during each simulation, contains symbols like zac_power0,
zdc_gain1, zunity_gain_frequency2, zphase_margin3, zphase_margin4, and zamp3_slew_rate5. These are used to communicate the ngspice
output data to ASCO. ASCO is searching for something like zdc_gain1 =, and then takes the next token as the input value. Calling phase_margin
twice in amp3.cfg has lead to two measurements in two .control sections with different symbols (zphase_margin3, zphase_margin4).
A failing test may result in an error message from ASCO. Sometimes, however, ASCO freezes after some output statements. This may happen if
ngspice issues an error message that cannot be handled by ASCO. Here it may help calling ngspice directly with the input file generated by ASCO:
$ ngspice_c <computer-name>.sp
The following graph 23.1 shows the acceleration of the optimization simulation on a multi-core processor (i7 with 4 real or 8 virtual cores), 500
generations, if -n is varied. Speed is tripled, a mere 15 min suffices to optimize 21 parameters of the amplifier.
𝐴𝐵𝑒𝑡𝑎 𝑊
inv.cfg section #Monte Carlo#. According to the paper by Pelgrom on MOS transistor matching [22] the AGAUSS parameters are calculated as
𝑊 = 𝐴𝐺𝐴𝑈𝑆𝑆(𝑊, ⋅ ⋅ 10−6 , 1)
√2 ⋅ 𝑊 ⋅ 𝐿 ⋅ 𝑚 100
𝐴𝑉𝑇
𝑑𝑒𝑙𝑣𝑡𝑜 = 𝐴𝐺𝐴𝑈𝑆𝑆(0, ⋅ 10−9 , 1)
√2 ⋅ 𝑊 ⋅ 𝐿 ⋅ 𝑚
The .ALTER command is not available in ngspice. However, a new option in ngspice to the altermod command (17.5.4) enables the simulation of
design corners. The #Alter# section in inv.cfg gives details. Specific to ngspice, again several .control section are used.
# ALTER #
.control
* gate oxide thickness varied
altermod nm pm file [b3.min b3.typ b3.max]
.endc
.control
* power supply variation
alter vdd=[2.0 2.1 2.2]
.endc
.control
run
.endc
#
NMOS (nm) and PMOS (pm) model parameter sets are loaded from three different model files, each containing both NMOS and PMOS sets. b3.typ
is assembled from the original parameter files n.typ and p.typ, provided with original ASCO, with some adaptation to ngspice BSIM3. The min and
max sets are artificially created in that only the gate oxide thickness deviates ±1 nm from what is found in model file b3.typ. In addition the power
supply voltage is varied, so in total you will find 3 x 3 simulation combinations in the input file <computer-name>.sp (after running asco-test).
23.5.3 Bandpass
This example is taken from Chapt. 6.2.4 Tutorial #4 from the ASCO manual. S11 in the passband is to be maximised. S21 is used to extract side lobe
parameters. The .net command is not available in ngspice, so S11 and S21 are derived with a script in file bandpass.sp as described in Chapt. 17.9.
The measurements requested in bandpass.cfg as
# Measurements #
Left_Side_Lobe:---:LE:-20
Pass_Band_Ripple:---:GE:-1
Right_Side_Lobe:---:LE:-20
S11_In_Band:---:MAX:---
#
are realized as 'measure' commands inside of control sections (see files in directory extract). The result of a measure statement is a vector, which may
be processed by commands in the following lines. In file extract/S1_In_Band #Symbol# is made available only after a short calculation (inversion
of sign), using the print command. quit has been added to this entry because it will become the final control section in <computer-name>.sp. A
disadvantage of measure inside of a .control section is that parameters from .param statements may not be used (as is done in example 23.5.4).
The bandpass example includes the calculation of RF parasitic elements defined in rfmodule.cfg (see Chapt. 7.5 of the ASCO manual). This
calculation is invoked by setting
ExecuteRF:yes $Execute or no the RF module to add RF parasitics?
in bandpass.cfg. The two subcircuits LBOND_sub and CSMD_sub are generated in <computer-name>.sp to simulate these effects.
Chapter 24 Notes
24.1 Glossary
card
A logical SPICE input line. A card may be extended through the use of the `+' sign in SPICE, thereby allowing it to take up multiple lines in a
SPICE deck.
code
model A model of a device, function, component, etc. which is based solely on a C programming language-based function. In addition to the
code models included with the XSPICE option of the ngspice simulator, you can use code models that you develop for circuit modeling.
deck
A collection of SPICE cards that together specify all input information required in order to perform an analysis. A `deck' of `cards' will in fact
be contained within a file on the host computer system.
element
card A single, logical line in an ngspice circuit deck that describes a circuit element. Circuit elements are connected to each other to form
circuits (e.g., a logical card that describes a resistor, such as R1 2 0 10K, is an element card).
instance
A unique occurrence of a circuit element. See `element card', in which the instance R1 is specified as a unique element (instance) in a
hypothetical circuit description.
macro
A macro, in the context of this document, refers to a C language macro that supports the construction of user-defined models by simplifying
input/output and parameter-passing operations within the Model Definition File.
.mod
Refers to the Model Definition File in XSPICE. The file suffix reflects the file-name of the model definition file: cfunc.mod.
.model
Refers to a model card associated with an element card in ngspice. A model card allows for data defining an instance to be conveniently located
in the ngspice deck such that the general layout of the elements is more readable.
Nutmeg
The ngspice post-processor (now obsolete). This provides a simple stand-alone simulator interface that can be used with the ngspice simulator
to display and plot simulator raw files.
subcircuit
A `device' within an ngspice deck that is defined in terms of a group of element cards and that can be referenced in other parts of the ngspice
deck through element cards.
24.3 To Do
1. Review of Chapt. 1.3
2. hfet1,2 model descriptions
3. MOS level 9 description
Bibliography
[1] A. Vladimirescu and S. Liu, `The Simulation of MOS Integrated Circuits Using SPICE2' ERL Memo No. ERL M80/7, Electronics Research
Laboratory University of California, Berkeley, October 1980
[2] T. Sakurai and A. R. Newton, `A Simple MOSFET Model for Circuit Analysis and its application to CMOS gate delay analysis and series-
connected MOSFET Structure' ERL Memo No. ERL M90/19, Electronics Research Laboratory, University of California, Berkeley, March
1990
[3] B. J. Sheu, D. L. Scharfetter, and P. K. Ko, `SPICE2 Implementation of BSIM' ERL Memo No. ERL M85/42, Electronics Research
Laboratory University of California, Berkeley, May 1985
[4] J. R. Pierret, `A MOS Parameter Extraction Program for the BSIM Model' ERL Memo Nos. ERL M84/99 and M84/100, Electronics Research
Laboratory University of California, Berkeley, November 1984
[5] Min-Chie Jeng, `Design and Modeling of Deep Submicrometer MOSFETSs' ERL Memo Nos. ERL M90/90, Electronics Research Laboratory,
University of California, Berkeley, October 1990
[6] Soyeon Park, `Analysis and SPICE implementation of High Temperature Effects on MOSFET', Master's thesis, University of California,
Berkeley, December 1986.
[7] Clement Szeto, `Simulation of Temperature Effects in MOSFETs (STEIM)', Master's thesis, University of California, Berkeley, May 1988.
[8] J.S. Roychowdhury and D.O. Pederson, `Efficient Transient Simulation of Lossy Interconnect', Proc. of the 28th ACM/IEEE Design
Automation Conference, June 17-21 1991, San Francisco
[9] A. E. Parker and D. J. Skellern, `An Improved FET Model for Computer Simulators', IEEE Trans CAD, vol. 9, no. 5, pp. 551-553, May 1990.
[10] R. Saleh and A. Yang, Editors, `Simulation and Modeling', IEEE Circuits and Devices, vol. 8, no. 3, pp. 7-8 and 49, May 1992.
[11] H.Statz et al., `GaAs FET Device and Circuit Simulation in SPICE', IEEE Transactions on Electron Devices, V34, Number 2, February
1987, pp160-169.
[12] Weidong Liu et al.: `BSIM3v3.2.2 MOSFET Model User's Manual', BSIM3v3.2.2
[13] Weidong Lui et al.: `BSIM3.v3.3.0 MOSFET Model User's Manual', BSIM3v3.3.0
[14] `SPICE3.C1 Nutmeg Programmer's Manual', Department of Electrical Engineering and Computer Sciences, University of California,
Berkeley, California, April, 1987.
[15] Thomas L. Quarles: SPICE3 Version 3C1 User's Guide, Department of Electrical Engineering and Computer Sciences, University of
California, Berkeley, California, April, 1989.
[16] Brian Kernighan and Dennis Ritchie: `The C Programming Language', Second Edition, Prentice-Hall, Englewood Cliffs, New Jersey, 1988.
[17] `Code-Level Modeling in XSPICE', F.L. Cox, W.B. Kuhn, J.P. Murray, and S.D. Tynor, published in the Proceedings of the 1992
International Symposium on Circuits and Systems, San Diego, CA, May 1992, vol 2, pp. 871-874.
[18] `A Physically Based Compact Model of Partially Depleted SOI MOSFETs for Analog Circuit Simulation', Mike S. L. Lee, Bernard M.
Tenbroek, William Redman-White, James Benson, and Michael J. Uren, IEEE JOURNAL OF SOLID-STATE CIRCUITS, VOL. 36, NO. 1,
JANUARY 2001, pp. 110-121
[19] `A Realistic Large-signal MESFET Model for SPICE', A. E. Parker, and D. J. Skellern, IEEE Transactions on Microwave Theory and
Techniques, vol. 45, no. 9, Sept. 1997, pp. 1563-1571.
[20] `Integrating RTS Noise into Circuit Analysis', T. B. Tang and A. F. Murray, IEEE ISCAS, 2009, Proc. of IEEE ISCAS, Taipei, Taiwan, May
2009, pp 585-588
[21] R. Storn, and K. Price: `Differential Evolution', technical report TR-95-012, ICSI, March 1995, see report download, or the DE web page
[22] M. J. M. Pelgrom e.a.: `Matching Properties of MOS Transistors', IEEE J. Sol. State Circ, vol. 24, no. 5, Oct. 1989, pp. 1433-1440
[23] Y. V. Pershin, M. Di Ventra: `SPICE model of memristive devices with threshold', arXiv:1204.2600v1 [physics.comp-ph] 12 Apr 2012,
http://arxiv.org/pdf/1204.2600.pdf
[24] George M. Kull e.a. `A Unified Circuit Model for Bipolar Transistors Including Quasi-Saturation Effects', IEEE TRANSACTIONS ON
ELECTRON DEVICES, VOL. ED-32, NO. 6, JUNE 1985
[25] Matthias Bucher, Christophe Lallement, Christian Enz, Fabien Théodoloz, François Krummenacher, `The EPFL-EKV MOSFET Model
Equations for Simulation', Technical Report, Revision II, July 1998, Electronics Laboratories, Swiss Federal Institute of Technology
(EPFL), Lausanne, Switzerland
[26] Kenneth Kundert, Sparse Matrix Techniques, in Circuit Analysis, Simulation and Design, Albert Ruehli (Ed.), North-Holland, 1986
[27] T. A. Davis and Ekanathan Palamadai Natarajan. 2010. Algorithm 907: KLU, A Direct Sparse Solver for Circuit Simulation Problems.
ACM Trans. Math. Softw. 37, 3, Article 36 (September 2010), 17 pages. https://dl.acm.org/doi/abs/10.1145/1824801.1824814
[28] F. Lannutti, P. Nenzi and M. Olivieri, "KLU sparse direct linear solver implementation into NGSPICE," Proceedings of the 19th
International Conference Mixed Design of Integrated Circuits and Systems - MIXDES 2012, Warsaw, Poland, 2012, pp. 69-73.
Plain ngspice is designed for analog simulation and is based exclusively on matrix solution techniques. The XSPICE option adds even-driven
simulation capabilities. Thus, designs that contain significant portions of digital circuitry can be efficiently simulated together with analog
components. ngspice with XSPICE option also includes a `User-Defined Node' capability that allows event-driven simulations to be carried out with
any type of data.
The XSPICE option has been developed by the Computer Science and Information Technology Laboratory at Georgia Tech Research Institute of the
Georgia Institute of Technology, Atlanta, Georgia 30332 at around 1990 and enhanced by the ngspice team. The manual is based on the original
XSPICE user's manual, no longer available from Georgia Tech, but from the ngspice web site.
In the following, the term `XSPICE' may be read as `ngspice with XSPICE code model subsystem enabled'. You may enable the option by adding --
enable-xspice to the ./configure command. The MS Windows distribution already contains the XSPICE option.
The ngspice simulator at the core of XSPICE includes built-in models for discrete components commonly found within integrated circuits. These
`model primitives' include components such as resistors, capacitors, diodes, and transistors. The XSPICE Code Model Subsystem extends this set of
primitives in two ways. First, it provides a library of over 40 additional primitives, including summers, integrators, digital gates, controlled oscillators,
s-domain transfer functions, and digital state machines. See Chapt. 12 for a description of the library entries. Second, it adds a code model generator
to ngspice that provides a set of programming utilities to make it easy for you to create your own models by writing them in the C programming
language.
The code models are generated upon compiling ngspice. They are stored in shared libraries, which may be distributed independently from the ngspice
sources. During runtime initialization, ngspice will load the code model libraries and make the code model instances available for simulation.
This section will introduce you to the creation of circuit description input files using the control language user interface. Note that this material is
presented in an overview form. Details of circuit description syntax are given later in this chapter and in the previous chapters of this manual.
The first line of the file is always interpreted as the title of the circuit. The title may consist of any text string.
Lines that provide user comments, but no circuit information, are begun by an asterisk.
A circuit device is specified by a device name, followed by the node(s) to which it is connected, and then by any required parameter
information.
The first character of a device name tells the simulator what kind of device it is (e.g. R = resistor, C = capacitor, E = voltage controlled
voltage source).
Nodes may be labeled with any alphanumeric identifier. The only specific labeling requirement is that 0 must be used for ground.
A line that begins with a dot is a `control directive' Control directives are used most frequently for specifying the type of analysis the
simulator is to carry out.
An .end statement must be included at the end of the file.
With the exception of the Title and .end statements, the order in which the circuit file is defined is arbitrary.
All identifiers are case insensitive - the identifier `npn' is equivalent to `NPN' and to `nPn'.
Spaces and parenthesis are treated as white space.
Long lines may be continued on a succeeding line by beginning the next line with a `+' in the first column.
In this example, the title of the circuit is `Small Signal Amplifier'. Three comment lines are included before the actual circuit description begins. The
first device in the circuit is voltage source Vin, which is connected between node Input and `0' (ground). The parameters after the nodes specify that
the source has an initial value of 0, a wave shape of SIN, and a DC offset, amplitude, and frequency of 0, .1, and 500 respectively. The next device in
the circuit is resistor R_Source, which is connected between nodes Input and Amp_In, with a value of 100 Ohms. The remaining device lines in the
file are interpreted similarly.
The control directive that begins with .tran specifies that the simulator should carry out a simulation using the Transient analysis mode. In this
example, the parameters to the transient analysis control directive specify that the maximum time-step allowed is 1 microsecond and that the circuit
should be simulated for 0.01 seconds of circuit time.
Other control cards are used for other analysis modes. For example, if a frequency response plot is desired, perhaps to determine the effect of the
capacitor in the circuit, the following statement will instruct the simulator to perform a frequency analysis from 100 Hz to 10 MHz in decade intervals
with ten points per decade.
.ac dec 10 100 10meg
To determine the quiescent operating point of the circuit, the following statement may be inserted in the file.
.op
A fourth analysis type supported by ngspice is swept DC analysis. An example control statement for the analysis mode is
.dc Vin -0.1 0.2 .05
This statement specifies a DC sweep that varies the source Vin from -100 millivolts to +200 millivolts in steps of 50 millivolts.
Vin Input 0 DC 0
R_source Input Amp_In 100
D_Neg 0 Amp_In 1n4148
D_Pos Amp_In 0 1n4148
C1 Amp_In 0 1uF
X1 Amp_In 0 Amp_Out Amplifier
R_Load Amp_Out 0 1000
.end
Device Models
used to define the silicon diodes. Electrically, the diodes serve to limit the voltage at the amplifier input to values between about ±700 millivolts. The
Device models allow you to specify, when required, many of the parameters of the devices being simulated. In this example, model statements are
diode is simulated by first declaring the `instance' of each diode with a device statement. Instead of attempting to provide parameter information
separately for both diodes, the label `1n4148' alerts the simulator that a separate model statement is included in the file that provides the necessary
electrical specifications for the device (`1n4148' is the part number for the type of diode the model is meant to simulate).
The model statement always begins with the string .model followed by an identifier and the model type (D for diode, NPN for NPN transistors, etc).
The optional parameters (`is', `rs', `n', …) shown in this example configure the simulator's mathematical model of the diode to match the specific
behavior of a particular part (e.g. a `1n4148').
Subcircuits
In some applications, describing a device by embedding the required elements in the main circuit file, as is done for the amplifier in Fig. 26.1, is not
desirable. A hierarchical approach may be taken by using subcircuits. An example of a subcircuit statement is shown in the second circuit file:
X1 Amp_In 0 Amp_Out
Amplifier Subcircuits are always identified by a device label beginning with `X'. Just as with other devices, all of the connected nodes are specified.
Notice, in this example, that three nodes are used. Finally, the name of the subcircuit is specified. Elsewhere in the circuit file, the simulator looks for
a statement of the form:
This statement specifies that the lines that follow are part of the Amplifier subcircuit, and that the three nodes listed are to be treated wherever they
occur in the subcircuit definition as referring, respectively, to the nodes on the main circuit from which the subcircuit was called. Normal device,
model, and comment statements may then follow. The subcircuit definition is concluded with a statement of the form:
.ends <Name>
To address these problems, XSPICE allows you to create Code Models that simulate complex, non-ideal effects without the need to develop a
subcircuit design. For example, the following file provides simulation of the circuit in Fig. 26.2, but with the subcircuit amplifier replaced with a
Code Model called `Amp' that models several non-ideal effects including input and output impedance and input offset voltage.
Vin Input 0 DC 0
R_source Input Amp_In 100
D_Neg 0 Amp_In 1n4148
D_Pos Amp_In 0 1n4148
C1 Amp_In 0 1uF
A1 Amp_In 0 Amp_Out Amplifier
R_Load Amp_Out 0 1000
A statement with a device label beginning with `A' alerts the simulator that the device uses a Code Model. The model statement is similar in form to
the one used to specify the diode. The model label `Amp' directs XSPICE to use the code model with that name. Parameter information has been
added to specify a gain of -10, an input offset of 1 millivolt, an input impedance of 1 meg ohm, and an output impedance of 0.4 ohm. Subsequent
sections of this document detail the steps required to create such a Code Model and include it in the XSPICE simulator.
In XSPICE, models developed for the express purpose of translating between the different algorithms or between different User-Defined Node types
are called `Node Bridge' models. For translations between the built-in analog and digital types, predefined node bridge models are included in the
XSPICE Code Model Library.
If you find that you cannot easily design a subcircuit to accomplish your goal using the available primitives, then you should turn to the code
modeling approach. Because they are written in a general purpose programming language (C), code models enable you to simulate virtually any
behavior for which you can develop a set of equations or algorithms.
The previous sections presented example circuit description input files. The following sections provide more detail on XSPICE circuit descriptions
with particular emphasis on the syntax for creating and using models. First, the language and syntax of the ngspice simulator are described and
references to additional information are given. Next, XSPICE extensions to the ngspice syntax are detailed. Finally, various enhancements to ngspice
operation are discussed including polynomial sources, arbitrary phase sources, supply ramping, matrix conditioning, convergence options, and
debugging support.
You should have downloaded ngspice, either the most recent distribution or from the Git repository, and compiled and installed it properly according
to your operating system and the instructions given in Chapt. 32 of the Appendix, especially Chapt. 32.1.4 (for Linux users), or Chapt. 32.2.2 for
MINGW and MS Windows. (MS Visual Studio will not do, because we have not yet integrated the code model generator into this compiler! You may
however use all code models later with any ngspice executable.) Then change into directory ngspice/src/xspice/icm/xtradev.
mkdir d_xxor
Copy the two files cfunc.mod and ifspec.ifs from ngspice/src/xspice/icm/digital/d_xor to ngspice/src/xspice/icm/xtradev/d_xxor. These two
files may serve as a template for your new model!
For simplicity reasons we do only a very simple editing to these files here, in fact the functionality is not changed, just the name translated to a new
model. Edit the new cfunc.mod: In lines 5, 28, 122, 138, 167, 178 replace the old name (d_xor) by the new name d_xxor. Edit the new ifspec.ifs: In
lines 16, 23, 24 replace cm_d_xor by cm_d_xxor and d_xor by d_xxor.
make
And that's it! In ngspice/release/src/xspice/icm/xtradev/ you now will find cfunc.c and ifspec.c and the corresponding object files. The new
code model d_xxor resides in the shared library xtradev.cm, and is available after ngspice is started. As a test example you may edit
ngspice/src/xspice/examples/digital_models1.deck, and change line 60 to the new model:
An analog input, delivered by the pwl voltage sources, is transformed into the digital domain by an adc_bridge, processed by the new code model
d_xxor, and then translated back into the analog domain.
If you want to change the functionality of the new model, you have to edit ifspec.ifs for the code model interface and cfunc.mod for the detailed
functionality of the new model. Please see Chapt. 28, especially Chapt. 28.6 ff. for any details. And of course you may take the existing analog,
digital, mixed signal and other existing code models (to be found in the subdirectories to ngspice/release/src/xspice/icm) as stimulating examples
for your work.
The next example, shown in Fig. 27.1, illustrates many of the more advanced features offered by XSPICE. This circuit is a mixed-mode design
incorporating digital data, analog data, and User-Defined Node data together in the same simulation. Some of the important features illustrated
include:
The examples also assume that you are running under Linux and will use standard Linux commands such as cp for copying files, etc. If you are using
a different set up, with different operating system command names, you should be able to translate the commands shown into those suitable for your
installation. Finally, file system path-names given in the examples assume that ngspice + XSPICE has been installed on your system in directory
/usr/local/xspice-1-0. If your installation is different, you should substitute the appropriate root path-name where appropriate.
Example:
Notice the component `aamp'. This is an XSPICE code model device. All XSPICE code model devices begin with the letter `a' to distinguish them
from other ngspice devices. The actual code model used is referenced through a user-defined identifier at the end of the line - in this case gain_block.
The type of code model used and its parameters appear on the associated .model card. In this example, the gain has been specified as -3.9 to
approximate the gain of the transistor amplifier, and the output offset (out_offset) has been set to 7.003 according to the DC bias point information
obtained from the DC analysis in Example 1 from Chapter 26.
Notice also that input and output impedances of the one-transistor amplifier circuit are modeled with the resistors `rzin' and `rzout', since the gain
code model defaults to an ideal voltage-input, voltage-output device with infinite input impedance and zero output impedance.
Lastly, note that a special resistor `rbig' with value `1e12' has been included at the opposite side of the output impedance resistor `rzout'. This resistor
is required by ngspice's matrix solution formula. Without it, the resistor `rzout' would have only one connection to the circuit, and an ill-formed matrix
could result. One way to avoid such problems without adding resistors explicitly is to use the ngspice `rshunt' option described in this document under
ngspice Syntax Extensions/General Enhancements.
To simulate this circuit, copy the file xspice_c2.cir from the directory /src/xspice/examples into a directory in your account.
$ cp /examples/xspice/xspice_c2.cir xspice_c2.cir
Invoke the simulator on this circuit:
$ ngspice xspice_c2.cir
After a few moments, you should see the ngspice prompt:
ngspice 1 ->
Now issue the run command and when the prompt returns, issue the plot command to examine the voltage at the node `coll'.
ngspice 1 -> run
ngspice 2 -> plot coll
The resulting waveform closely matches that from the original transistor amplifier circuit simulated in Example 1.
When you are done, enter the quit command to leave the simulator and return to the command line.
ngspice 3 -> quit
Using the rusage command, you can verify that this abstract model of the transistor amplifier runs somewhat faster than the full circuit of Example 1.
This is because the code model is less complex computationally. This demonstrates one important use of XSPICE code models - to reduce run time by
modeling circuits at a higher level of abstraction. Speed improvements vary and are most pronounced when a large amount of low-level circuitry can
be replaced by a small number of code models and additional components.
Example:
Mixed IO types
* This circuit contains a mixture of IO types, including
* analog, digital, user-defined (real), and 'null'.
*
* The circuit demonstrates the use of the digital and
* user-defined node capability to model system-level designs
* such as sampled-data filters. The simulated circuit
* contains a digital oscillator enabled after 100us. The
* square wave oscillator output is divided by 8 with a
* ripple counter. The result is passed through a digital
* filter to convert it to a sine wave.
*
.tran 1e-5 1e-3
*
v1 1 0 0.0 pulse(0 1 1e-4 1e-6)
r1 1 0 1k
*
abridge1 [1] [enable] atod
.model atod adc_bridge
*
aclk [enable clk] clk nand
.model nand d_nand (rise_delay=1e-5 fall_delay=1e-5)
*
adiv2 div2_out clk NULL NULL NULL div2_out dff
adiv4 div4_out div2_out NULL NULL NULL div4_out dff
adiv8 div8_out div4_out NULL NULL NULL div8_out dff
.model dff d_dff
Example (continued):
Example (continued):
This circuit is a high-level design of a sampled-data filter. An analog step waveform (created from a ngspice pulse waveform) is introduced as `v1'
and converted to digital by code model instance `abridge'. This digital data is used to enable a Nand-Gate oscillator (`aclk') after a short delay. The
Nand-Gate oscillator generates a square-wave clock signal with a period of approximately two times the gate delay, which is specified as 1e-5
seconds. This 50 kHz clock is divided by a series of D Flip Flops (`adiv2', `adiv4', `adiv8') to produce a square-wave at approximately 6.25 kHz. Note
particularly the use of the reserved word `NULL' for certain nodes on the D Flip Flops. This tells the code model that there is no node connected to
these ports of the flip flop.
The divide-by-8 and enable waveforms are converted by the instance `abridge2' to the format required by the User-Defined Node type `real', which
expected real-valued data. The output of this instance on node filt_in is a real valued square wave that oscillates between values of -1 and 1. Note
that the associated code model d_to_real is not part of the original XSPICE code model library but has been added later to ngspice.
This signal is then passed through subcircuit `xfilter' that contains a digital low-pass filter clocked by node `clk'. The result of passing this square-
wave through the digital low-pass filter is the production of a sampled sine wave (the filter passes only the fundamental of the square-wave input) on
node filt_out. This signal is then converted back to ngspice analog data on node a_out by node bridge instance `abridge3'.
The resulting analog waveform is then passed through an op-amp-based low-pass analog filter constructed around subcircuit `xlpf' to produce the final
output at analog node `lpf_out'.
Plotting nodes internal to subcircuits works for both analog and event-driven nodes.
Note that the eprint command also gives statistics from the event-driven algorithm portion of XSPICE. For this example, the simulator alternated
between the analog solution algorithm and the event-driven algorithm one time while performing the initial DC operating point solution prior to the
start of the transient analysis. During this operating point analysis, 37 total calls were made to event-driven code model functions, and two separate
event passes or iterations were required before the event nodes obtained stable values. Once the transient analysis commenced, there were 4299 total
calls to event-driven code model functions. Lastly, the analog simulation algorithm performed 87 time-step backups that forced the event-driven
simulator to backup its state data and its event queues.
A similar output is obtained when printing the values of digital nodes. For example, print the values of the node `div8 out' as follows:
ngspice 5 -> eprint div8_out
**** Results Data ****
Time or Step
div8_out
0.000000000e+000 1s
1.810070000e-004 0s
2.610070000e-004 1s
...
9.010070000e-004 1s
9.810070000e-004 0s
**** Messages ****
**** Statistics ****
Operating point analog/event alternations: 1
Operating point load calls: 37
Operating point event passes: 2
Transient analysis load calls: 4299
Transient analysis timestep backups: 87
From this printout, we see that digital node values are composed of a two character string. The first character (0, 1, or U) gives the state of the node
(logic zero, logic one, or unknown logic state). The second character (s, r, z, u) gives the `strength' of the logic state (strong, resistive, hi-impedance,
or undetermined).
If you wish, examine other nodes in this circuit with either the plot or eprint commands. When you are done, enter the quit command to exit the
simulator and return to the operating system prompt:
ngspice 6 -> quit
So long.
The original manual cited an XSPICE `Code Model Toolkit' that enabled one to define new models and node data types to be passed between them
offline, independent from ngspice. Whereas this Toolkit is still available in the original source code distribution at the XSPICE web page, it is neither
required nor supported any more.
So we make use of the existing XSPICE infrastructure provided with ngspice to create new code models. With an 'intelligent' copy and paste, and the
many available code models serving as a guide you will be quickly able to create your own models. You have to have a compiler (gcc) available under
Linux, MS Windows (Cygwin, MINGW), maybe also for other OSs, including supporting software (Flex, Bison, and the autotools if you start from
Git sources). The compilation procedures for ngspice are described in detail in Chapt. 32. Adding a code model may then require defining the
functionality, interface, and eventually user defined nodes. Compiling into a shared library is only a simple 'make', loading the shared lib(s) into
ngspice is done by the ngspice command codemodel... (see Chapt. 17.5.12). This will allow you to either add some code model to an existing library,
or you may generate a new library with your own code models. The latter is of interest if you want to distribute your code models independently from
the ngspice sources or executables.
These new code models are handled by ngspice in a manner analogous to its treating of SPICE devices and XSPICE Predefined Code Models. The
basic steps required to create sources for new code models or User-Defined Nodes, compile them and load them into ngspice are similar. They consist
of 1) creating the code model or UserDefined Node (UDN) directory and its associated model or data files, 2) inform ngspice about the code model or
UDN directories that have to be compiled and linked into ngspice, 3) compile them into a shared lib, and 4) load them into the ngspice simulator upon
runtime. All code models finally reside in dynamically linkable shared libraries (*.cm), which in fact are .so files under Linux or dlls under MS
Windows. Currently we have 5 of them (analog.cm, digital.cm, spice2poly.cm, xtradev.cm, xtraevt.cm). Upon start up of ngspice they are
dynamically loaded into the simulator by the ngspice codemodel command (which is located in file spinit (see Chapt. 16.5) for the standard code
models). Once you have added your new code model into one of these libraries (or have created a new library file, e.g. my-own.cm), instances of the
model can be placed into any simulator deck that describes a circuit of interest and simulated along with all of the other components in that circuit.
A quick entry to get a new code model has already been presented in Chapt. 26.3. You may find the details of the XSPICE language in Chapt. 28.6 ff.
Boolean_t
The Boolean type is an enumerated type that can take on values of FALSE (integer value 0) or TRUE (integer value 1). Alternative names for these
enumerations are MIF FALSE and MIF TRUE, respectively.
Complex_t
The Complex type is a structure composed of two double values. The first of these is the .real field, and the second is the .imag field. Typically these
values are accessed as shown:
For complex value `data', the real portion is `data.real', and the imaginary portion is `data.imag'.
Digital_State_t
The Digital State type is an enumerated value that can be either ZERO (integer value 0), ONE (integer value 1), or UNKNOWN (integer value 2).
Digital_Strength_t
The Digital Strength type is an enumerated value that can be either STRONG (integer value 0), RESISTIVE (integer value 1), HI IMPEDANCE
(integer value 2) or UNDETERMINED (integer value 3).
Digital_t
The Digital type is a composite of the Digital_State_t and Digital_Strength_t enumerated data types. The actual variable names within the Digital type
are .state and .strength and are accessed as shown below:
For Digital_t value `data', the state portion is `data.state', and the strength portion is `data.strength'.
The Interface Specification File is a text file that describes, in a tabular format, information needed for the code model to be properly interpreted by
the simulator when it is placed with other circuit components into a SPICE deck. This information includes such things as the parameter names,
parameter default values, and the name of the model itself. The specific format presented to you in the Interface Specification File template must be
followed exactly, but is quite straightforward. A detailed description of the required syntax, along with numerous examples, is included in Section
28.6.
The Model Definition File contains a C programming language function definition. This function specifies the operations to be performed within the
model on the data passed to it by the simulator. Special macros are provided that allow the function to retrieve input data and return output data.
Similarly, macros are provided to allow for such things as storage of information between iteration time-points and sending of error messages. Section
28.7 describes the form and function of the Model Definition File in detail and lists the support macros provided within the simulator for use in code
models.
To allow compiling and linking (see Chapt. 28.5) you have at least to adapt the names of the functions inside of the two copied files to get unique
function and model names. If for example you have chosen ifspec.ifs and cfunc.mod from model d_fdiv as your template, simply replace all entries
d_fdiv by d_counter inside of the two files.
Because of the need of electrical engineers to have ready access to both digital and analog simulation capabilities, the digital node type is provided
as a built-in node type along with standard SPICE analog nodes. For digital nodes, extensive support is provided in the form of macros and
functions so that you can treat this node type as a standard type analogous to standard SPICE analog nodes when creating and using code models. In
addition to analog and digital nodes, the node types real and int are also provided with the simulator. These were created using the User-Defined
Node (UDN) creation facilities described below and may serve as a template for further node types.
The first step in creating a new node type within XSPICE is to set up a node type directory along with the appropriate template files needed.
cd ngspice/src/xspice/icm/xtraevt
mkdir <directory name>
<directory name> should be the name of the new type to be defined. Copy file udnfunc.c from /icm/xtraevt/int into the new directory. Edit this file
according to the new type you want to create.
The UDN Definition File contains a set of C language functions. These functions perform operations such as allocating space for data structures,
initializing them, and comparing them to each other. Section 28.8 describes the form and function of the User-Defined Node Definition File in detail
and includes an example UDN Definition File.
Edit file ngspice/src/xspice/icm/GNUmakefile.in, add <directory name> to the end of line 10, which starts with CMDIRS = ... .
That's all you have to do about a new library! Of course it is empty right now, so you have to define at least one code model according to the
procedure described in Chapt. 28.2.
Thus the code model libraries are not linked into ngspice at compile time, but may be loaded at runtime using the codemodel command (see Chapt.
17.5.12). This is done automatically for the predefined code model libraries upon starting ngspice. The appropriate commands are provided in the start
up file spinit (see Chapt. 16.5). So if you have added a new code model inside of one of the existing libraries, nothing has to be done, you will have
immediate access to your new model.
If you have generated a new code model library, e.g. new_lib.cm, then you have to add the line
@XSPICEINIT@ codemodel @prefix@/@libname@/spice/new_lib.cm
to spinit.in in ngspice/src. This will create a new spinit if ngspice is recompiled from scratch.
To avoid the need for recompilation of ngspice, you also may directly edit the file spinit by adding the line
codemodel C:/Spice/lib/spice/new_lib.cm
(OS MS Windows) or the appropriate Linux equivalent. Upon starting ngspice, the new library will be loaded and you have access to the new code
model(s). The codemodel command has to be executed upon start-up of ngspice, so that the model information is available as soon as the circuit is
parsed. Failing to do so will lead to an error message of a model missing. So spinit (or .spiceinit for personal code model libraries) is the correct
place for codemodel.
Description
The description string is used to describe the purpose and function of the code model. It is introduced by the Description: keyword followed by a C
string literal.
28.6.2.2 Description
The description string is used to describe the purpose and function of the port. It is introduced by the Description: keyword followed by a C string
literal.
28.6.2.3 Direction
The direction of a port specifies the data flow direction through the port. A direction must be one of n, out, or inout. It is introduced by the
Direction: keyword followed by a valid direction value.
28.6.2.6 Vector
A port that is a vector can be thought of as a bus. The Vector field is introduced with the Vector: keyword followed by a Boolean value: YES, TRUE,
NO or FALSE.
Default Types
Type Description Valid Directions
d digital any
g conductance (VCCS) inout
gd differential conductance (VCCS) inout
h resistance (CCVS) inout
hd differential resistance (CCVS) inout
i current in or out
id differential current in or out
v voltage in or out
vd differential voltage in or out
<identifier> user-defined type any
Table 28.1: Port Types
The values YES and TRUE are equivalent and specify that this port is a vector. Likewise, NO and FALSE specify that the port is not a vector. Vector
ports must have a corresponding vector bounds field that specifies valid sizes of the vector port.
28.6.3.2 Description
The description string is used to describe the purpose and function of the parameter. It is introduced by the `Description:' keyword followed by a
string literal.
28.6.3.6 Limits
Integer and real parameters may be constrained to accept a limited range of values. The following range syntax is used whenever such a range of
values is required. A range is specified by a square bracket followed by a value representing a lower bound separated by space from another value
representing an upper bound and terminated with a closing square bracket (e.g.”[0 10]”). The lower and upper bounds are inclusive. Either the lower
or the upper bound may be replaced by a hyphen (`-') to indicate that the bound is unconstrained (e.g. `[10 -]' is read as `the range of values greater
than or equal to 10'). For a totally unconstrained range, a single hyphen with no surrounding brackets may be used. The parameter value limit is
introduced by the `Limits:' keyword and is followed by a range.
28.6.3.7 Vector
The Vector field is used to specify whether a parameter is a vector or a scalar. Like the PORT TABLE Vector field, it is introduced by the `Vector:'
keyword and followed by a boolean value. `TRUE' or `YES' specify that the parameter is a vector. `FALSE' or `NO' specify that it is a scalar.
28.6.4.1 Name
The Static variable name is a valid C identifier that will be used in the code model to refer to this static variable. It is introduced by the
`Static_Var_Name:' keyword followed by a valid C identifier.
28.6.4.2 Description
The description string is used to describe the purpose and function of the static variable. It is introduced by the `Description:' keyword followed by
a string literal.
Note that pointer types are used to specify vector values; in such cases, the allocation of memory for vectors must be handled by the code model
through the use of the malloc() or calloc() C function. Such allocation must only occur during the initialization cycle of the model (which is
identified in the code model by testing the INIT macro for a value of TRUE). Otherwise, memory will be unnecessarily allocated each time the model
is called.
Following is an example of the method used to allocate memory to be referenced by a static pointer variable `x' and subsequently use the allocated
memory. The example assumes that the value of `size' is at least 2, else an error would result. The references to STATIC_VAR(x) that appear in the
example illustrate how to set the value of, and then access, a static variable named `x'. In order to use the variable `x' in this manner, it must be
declared in the Static Variable Table of the code model's Interface Specification File.
/* Assign the value from the static pointer value to the local */
/* pointer variable. */
local_x = STATIC_VAR(x);
28.7.1 Macros
The use of the accessor macros is illustrated in the following example. Note that the argument to most accessor macros is the name of a parameter or
port as defined in the Interface Specification File. Note also that all accessor macros except `ARGS' resolve to an lvalue (C language terminology for
something that can be assigned a value). Accessor macros do not implement expressions or assignments.
ARGS
is a macro that is passed in the argument list of every code model. It is there to provide a way of referencing each model to all of the remaining
macro values. It must be present in the argument list of every code model; it must also be the only argument present in the argument list of
every code model.
CALL_TYPE
is a macro that returns one of two possible symbolic constants. These are EVENT and ANALOG. Testing may be performed by a model using
CALL TYPE to determine whether it is being called by the analog simulator or the event-driven simulator. This will, in general, only be of
value to a hybrid model such as the adc bridge or the dac bridge. Some expected behaviours of the code model, such as setting output values,
depend on the CALL TYPE. For code models that request it (see 28.7.2.7) a third value, STEP_PENDING, is used when the call indicates that
the simulator is about to complete an analog time step.
INIT
is an integer (int) that takes the value 1 or 0 depending on whether this is the first call to the code model instance or not, respectively.
ANALYSIS
is an enumerated integer that takes values of DC, AC, or TRANSIENT.
FIRST_TIMEPOINT
is an integer that takes the value 1 or 0 depending on whether this is the first call for this instance at the current analysis step (i.e., time-point) or
not, respectively.
TIME
is a double representing the current analysis time in a transient analysis. T(n) is a double vector giving the analysis time for a specific analog
time-point in a transient analysis, where n takes the value 0 or 1. T(0) is equal to TIME. T(1) is the last accepted time-point. (T(0) - T(1)) is the
time-step (i.e., the delta-time value) associated with the current time. The T(x) macro is valid only during ANALOG calls (CALL TYPE ==
ANALOG). The difference between the TIME values in two successive calls to a code model function may be zero, or even negative if the
analog simulator reduces the time-step while seeking convergence. TIME will never be less than any current or previous valid T(1).
RAD_FREQ
is a double representing the current analysis frequency in an AC analysis expressed in units of radians per second.
TEMPERATURE
is a double representing the current analysis temperature.
CALLBACK
is a variable of type Mif_Callback_t, a function pointer defined in the header file miftypes.h. A function may be supplied by assigning to
CALLBACK in the INIT call to the code model. That function will then be called during reset or deletion of instances of the code model. It is
expected to release any extra resources such as dynamic memory or open files that have been allocated during simulation. Most code models
will not need this as storage for variables allocated through the library are released automatically. When the function is called, the first argument
is ARGS and the second is a reason code: currently the only value is MIF_CB_DESTROY. That should be checked in case new call reasons are
introduced. The set of macros that can be used in the function is restricted to those for ports, parameters and static variables.
PARAM(gain)
(indexed) resolves to the value of the scalar (i.e., non-vector) parameter `gain' that was defined in the Interface Specification File tables. The
macro evaluation has the type given in the ifspec.ifs file and can be used regardless of type. If `gain' is a string, then PARAM(gain) resolves to a
read-only character pointer.
PARAM_SIZE(gain)
resolves to an integer (int) representing the size of the `gain' vector (which was dynamically determined when the SPICE deck was read).
PARAM_SIZE(gain) is undefined if `gain' is a scalar.
PARAM_NULL(gain)
resolves to an integer with value 0 or 1 depending on whether a value was specified for gain, or whether the value is defaulted, respectively.
PORT_SIZE(a)
resolves to an integer (int) representing the size of the `a' vector port (which was dynamically determined when the SPICE deck was read).
PORT_SIZE(a) is undefined if gain is a scalar.
PORT_NULL(a)
resolves to an integer (int) with value 0 or 1 depending on whether the SPICE deck has a node specified for this port, or has specified that the
port is null, respectively.
LOAD(a)
(indexed) is used in a digital model to post a capacitive load value to a particular input or output port during the INIT pass of the simulator. All
values posted for a particular event-driven node using the LOAD() macro are summed, producing a total load value.
TOTAL_LOAD(a)
(indexed) returns a double value that represents the total capacitive load seen on a specified node to which a digital code model is connected.
This information may be used after the INIT pass by the code model to modify the delays it posts with its output states and strengths. Note that
this macro can also be used by non-digital event-driven code models (see LOAD(), above).
INPUT(a)
resolves to the value of the scalar input a that was defined in the Interface Specification File tables. The macro evaluates to a real (double) value
for analog ports and a pointer to the internal representation for event ports (digital, integer, real or user-defined). The same accessor macro can
be used regardless of type.
INPUT_STATE(a)
resolves to the state value defined for digital node types. These will be one of the symbolic constants ZERO, ONE, or UNKNOWN.
INPUT_STRENGTH(a)
resolves to the strength with which a digital input node is being driven. This is determined by a resolution algorithm that looks at all outputs to a
node and determines its final driven strength. This value in turn is passed to a code model when requested by this macro. Possible strength
values are
1. STRONG
2. RESISTIVE
3. HI_IMPEDANCE
4. UNDETERMINED
OUTPUT(y)
resolves to the value of the scalar output `y' that was defined in the Interface Specification File tables. The macro evaluates to a real l-value (it
can be assigned to) for analog ports and a pointer to the internal representation (dereference before assigning a value) for event ports (digital,
integer, real or user-defined). The same accessor macro can be used regardless of type. Event simulator port values must only be set in EVENT
calls. All analog simulator ports should be set in ANALOG calls, otherwise the value reverts to zero. Setting analog ports in an EVENT call
does nothing. To handle the case where a new output for the“other” simulator is produced, schedule a re-entry to that simulator using
cm_event_queue() or cm_analog_set_temp_breakpoint(), as appropriate, passing TIME as the argument.
OUTPUT_CHANGED(a)
may be assigned one of two values for any particular output to an event simulator port. If assigned the value TRUE (the default), then an output
state, strength (if digital) and delay must be posted by the model during the call. If, on the other hand, no change has occurred during that pass,
the OUTPUT_CHANGED(a) value for an output can be set to FALSE. In this case, no state, strength or delay values need be posted by the
model. Remember that this macro applies to a single output port. If a model has multiple outputs that have not changed,
OUTPUT_CHANGED(a) must be set to FALSE for each of them.
OUTPUT_DELAY(y)
may be assigned a double value representing a delay associated with a particular event simulator port. Note that this macro must be set for each
digital or User-Defined Node output from a model during each pass, unless the OUTPUT_CHANGED(a) macro is set to FALSE. Note also that
a positive value must be assigned to OUTPUT_DELAY(). Assigning a value of zero (or a negative value) will cause an error.
OUTPUT_STATE(a)
may be assigned a state value for a digital output node. Valid values are ZERO, ONE, and UNKNOWN. This is the normal way of posting an
output state from a digital code model. This is a convenient alternative to constructing a full digital value (state and strength) and assigning to
*OUTPUT(a).
OUTPUT_STRENGTH(a)
may be assigned a strength value for a digital output node. This is the normal way of posting an output strength from a digital code model. Valid
values are
1. STRONG
2. RESISTIVE
3. HI_IMPEDANCE
4. UNDETERMINED
PARTIAL(y,a)
(indexed) resolves to the value of the partial derivative of scalar output `y' with respect to scalar input `a'. The type is always double since
partial derivatives are only defined for nodes with real valued quantities (i.e., analog nodes).
The remaining uses of PARTIAL are shown for the cases in which either the output, the input, or both are vectors.
Partial derivatives are required by the simulator to allow it to solve the non-linear equations that describe circuit behavior for analog nodes. Since
coding of partial derivatives can become difficult and error-prone for complex analog models, you may wish to consider using the
cm_analog_auto_partial() code model support function instead of using this macro.
PARTIAL(a, a) is valid for an inout port and its use may greatly improve convergence.
28.7.1.9 AC Gains
AC_GAIN(y,a)
AC_GAIN(y[n],a)
AC_GAIN(y,a[m])
AC_GAIN(y[n],a[m])
AC_GAIN(y,a)
(indexed) resolves to the value of the AC analysis gain of scalar output `y' from scalar input `a'. The type is always a structure (Complex_t)
defined in the standard code model header file:
typedef struct Complex_s {
double real; /* The real part of the complex number */
double imag; /* The imaginary part of the complex number */
} Complex_t;
The remaining uses of AC_GAIN are shown for the cases in which either the output, the input, or both are vectors.
STATIC_VAR(x)
resolves to an lvalue for a scalar or pointer as defined in the Interface Specification File. Unlike C language static and global variables, these
values are local to a specific instance of the code model. The type of `x' is that given in the Interface Specification File. The same accessor
macro can be used regardless of type since it simply resolves to an lvalue. To store a C structure or vector, the declared type should be 'pointer'
and the code model is responsible for allocating storage and assigning the pointer to the allocated storage to STATIC_VAR(x). That is usually
done in the INIT call. The code model is also responsible for freeing the storage, in a function that is declared by the CALLBACK macro.
void
cm_smooth_discontinuity(x_input, x_lower, y_lower, x_upper, y_upper
y_output, dy_dx)
double
cm_smooth_pwl(x_input, x, y, size, input_domain, dout_din)
cm_smooth_discontinuity() allows you to obtain a smoothly-transitioning output (*y_output) that varies between two static values (y_lower,
y_upper) as an independent variable (x_input) transitions between two values (x_lower, x_upper). This function is useful in interpolating between
resistances or voltage levels that change abruptly between two values.
cm_smooth_pwl() duplicates much of the functionality of the predefined pwl code model. The cm smooth pwl() takes an input value plus x-
coordinate and y-coordinate vector values along with the total number of coordinate points used to describe the piecewise linear transfer function and
returns the interpolated or extrapolated value of the output based on that transfer function. More detail is available by looking at the description of the
pwl code model. Note that the output value is the function's returned value.
cm_analog_get_ptr() and cm_event_get_ptr() retrieve the pointer location of the rotational storage space previously allocated by
cm_analog_alloc() or cm_event_alloc(). Important notice: These functions must be called only after all memory allocation (all calls to
cm_analog_alloc() or cm_event_alloc()) have been done. All pointers returned between calls to memory allocation will become obsolete (point to
freed memory because of an internal realloc). The functions take the integer `tag' used to allocate the space, and an integer from 0 to 1 that specifies
the time-point with which the desired state variable is associated (e.g. timepoint = 0 will retrieve the address of storage for the current time-point;
timepoint = 1 will retrieve the address of storage for the last accepted time-point). Note that once a model is exited, storage to the current time-
point state storage location (i.e., timepoint = 0) will, upon the next time-point iteration, be rotated to the previous location (i.e., timepoint = 1).
When rotation is done, a copy of the old `timepoint = 0' storage value is placed in the new `timepoint = 1' storage location. Thus, if a value does not
change for a particular iteration, specific writing to `timepoint = 0' storage is not required. These features allow a model coder to constantly know
which piece of state information is being dealt with within the model function at each time-point.
Rotation and copying for cm_analog_get_ptr() occurs when the circuit state converges and the simulator accepts the new timepoint. Rotation and
copying are done for cm_event_get_ptr() before each EVENT call. When simulation time moves backward, newer EVENT data is discarded and
the next copy is made from the oldest data with time-stamp less than TIME.
int cm_analog_converge(state)
void cm_analog_not_converged()
void cm_analog_auto_partial()
double cm_ramp_factor()
cm_analog_integrate() takes as input the integrand (the input to the integrator) and produces as output the integral value and the partial of the
integral with respect to the integrand. The integration itself is with respect to time, and the pointer to the integral value must have been previously
allocated using cm_analog_alloc() and *cm_analog_get_ptr(). This is required because of the need for the integrate routine itself to have access to
previously-computed values of the integral.
cm_analog_converge() takes as an input the address of a state variable that was previously allocated using cm_analog_alloc() and
*cm_analog_get_ptr(). The function itself serves to notify the simulator that for each time-step taken, that variable must be iterated upon until it
converges.
cm_analog_not_converged() is a function that can and should be called by an analog model whenever it performs internal limiting of one or more of
its inputs to aid in reaching convergence. This causes the simulator to call the model again at the current time-point and continue solving the circuit
matrix. A new time-point will not be attempted until the code model returns without calling the cm_analog_not_converged() function. For circuits
that have trouble reaching a converged state (often due to multiple inputs changing too quickly for the model to react in a reasonable fashion), the use
of this function is virtually mandatory.
cm_analog_auto_partial() may be called at the end of a code model function in lieu of calculating the values of partial derivatives explicitly in the
function. When this function is called, no values should be assigned to the PARTIAL macro since these values will be computed automatically by the
simulator. The automatic calculation of partial derivatives can save considerable time in designing and coding a model, since manual computation of
partial derivatives can become very complex and error-prone for some models. However, the automatic evaluation may also increase simulation run
time significantly. Function cm_analog_auto_partial() causes the model to be called N additional times (for a model with N inputs) with each input
varied by a small amount (1e-6 for voltage inputs and 1e-12 for current inputs). The values of the partial derivatives of the outputs with respect to the
inputs are then approximated by the simulator through divided difference calculations.
cm_analog_ramp_factor() will then return a value from 0.0 to 1.0 that indicates whether or not a ramp time value requested in the SPICE analysis
deck (with the use of .option ramptime=<duration>) has elapsed. If the RAMPTIME option is used, then cm_analog_ramp_factor returns a 0.0
value during the DC operating point solution and a value that is between 0.0 and 1.0 during the ramp. A 1.0 value is returned after the ramp is over or
if the RAMPTIME option is not used. This value is intended as a multiplication factor to be used with all model outputs that would ordinarily
experience a `power-up' transition. Currently, all sources within the simulator are automatically ramped to the `final' time-zero value if a RAMPTIME
option is specified.
int cm_analog_set_temp_bkpt(time)
cm_analog_set_temp_bkpt() takes as input a time value. This value is posted to the simulator and is used to force the simulator, for the next time-
step only, to not exceed the passed time value. The simulator may choose as the next time-point a value less than the input, but not greater. In
addition, once the next time-step is chosen, the posted value is removed regardless of whether it caused the break at the given time-point. This
function is useful in the event that a time-point needs to be retracted after its first posting in order to recalculate a new breakpoint based on new input
data (for controlled oscillators, controlled one-shots, etc), since temporary breakpoints automatically `go away' if not reposted each time-step. Note
that a breakpoint may also be set for a time prior to the current time, but this will result in an error if the posted breakpoint is prior to the last accepted
time (i.e., T(1)).
It is not certain that a future call will be made with TIME exactly equal to the function argument, but there will be a close match. Arithmetic rounding
may occur and the simulator may make only one call when requests are very closely spaced. The closeness depends on the minimum timestep of the
simulation.
cm_event_queue() is similar to cm_analog_set_perm_bkpt(), but functions with event-driven models. When invoked, this function causes the
model to be queued for calling at the specified time, with CALL_TYPE == EVENT. There is no combining of closly-spaced events. All other details
applicable to cm_analog_set_perm_bkpt() apply to this function as well.
double cm_netlist_get_c()
double cm_netlist_get_l()
char* cm_get_path()
CKTcircuit *cm_get_circuit()
const char *cm_get_node_name(const char *port_name, unsigned int index)
bool cm_probe_node(conn_index, port_index, value)
unsigned int conn_index; /* Connection index */
unsigned int port_index; /* Port index within connection */
void *value; /* Pointer to event value, input and return */
bool cm_schedule_output(unsigned int conn_index, unsigned int port_index, double delay, void *vp)
unsigned int conn_index; /* Connection index */
unsigned int port_index; /* Port index within connection */
double delay; /* Delay time, similar to OUTPUT_DELAY */
void *vp; /* Pointer to the event value, like OUTPUT */
bool cm_getvar(char *name, enum cp_types type, void *retval, size_t rsize)
char *name; /* Variable name */
enum cp_types type; /* Type of data requested */
void *retval; /* Buffer for data returned */
size_t rsize; /* Buffer size */
void cm_cexit(int exitcode)
int exitcode; /* Number returned upon exiting */
void cm_irreversible(unsigned int priority)
unsigned int priority; /* Relative priority of code model instance */
cm_climit_fcn() is a very specific function that mimics the behavior of the climit code model (see the Predefined Models section). In brief, the
cm_climit_fcn() takes as input an in value, an offset, and controlling upper and lower values. Parameter values include delta values for the
controlling inputs, a smoothing range, gain, and fraction switch values. Outputs include the final value, plus the partial derivatives of the output with
respect to signal input, and both control inputs. These all operate identically to the similarly-named inputs and parameters of the climit model.
The function performs a limit on the in value, holding it to within some delta of the controlling inputs, and handling smoothing, etc. The
cm_climit_fcn() was originally used in the ilimit code model to handle much of the primary limiting in that model, and can be used by a code model
developer to take care of limiting in larger models that require it. See the detailed description of the climit model a for more in-depth description.
cm_netlist_get_c() and cm_netlist_get_l() functions search the analog circuitry to which their input is connected, and total the capacitance or
inductance, respectively, found at that node. The functions, as they are currently written, assume they are called by a model that has only one single-
ended analog input port.
cm_get_path() fetches the path of the first netlist input file found on the ngspice command line or in the source command, which ngspice saves to
the global variable Infile_Path.
cm_get_circuit() returns a pointer to the (fundamental) ngspice circuit structure. This allows accessing a wealth of data, as defined by
CKTcircuit structure in cktdefs.h. To build complex custom-built XSPICE-models, access to such parameters (e.g. maximum step size) may be
needed to get reasonable results from a simulation. This may be necessary when SPICE interacts with an external sensor-simulator and the results of
that external simulator do not have a direct impact on the SPICE circuit. Then, modifying the maximum step size on the fly may help to improve the
simulation results.
cm_get_node_name() returns the name of the node attached to a port. The second argument is the index for vector ports.
cm_probe_node() performs a speculative resolution of a node attached to a port. Given a port and an event value, it returns what the value on the
attached node would be, if the port was attempting to output the original value. It is used by the bidi_bridge to discover how the node is being
driven by the other attached digital ports.
cm_schedule_output() queues an output event for a port, with the same effect as assigning to the OUTPUT_DELAY and OUPUT macros, but
without returning from the code model function. It allows more than one event to be queued to a port in a single call. To prevent one event overriding
another on the same port they should be queued with increasing delays.
cm_getvar() obtains the value of a command interpreter variable. It has the same interface as the internal function cp_getvar() as defined in the
header file src/include/ngspice/cpextern.h.
A call to cm_irreversible()has several effects that work together to support code models that contain a sub-simulation. Such a sub-simulation will
usually be irreversible: in transient analysis it will not store enough data to allow a completed time step to be abandoned. However, analog simulation
in Ngspice frequently abandons time steps so that they can be retried with a shorter period to achieve convergence. If the inputs to the sub-simulation
are different in the final analog solution and the original attempt, the sub-simulation may be permanently left in an incorrect state.
A solution to this problem is to delay advancing time in the sub-simulation until Ngspice is committed to the current timestep. This can work fully
only for a single instance, but under some conditions it may be possible to support several irreversible sub-simulations in one circuit.
The effects of a call are: the code model instance is added to the hybrids list if it is not already a member; its position in the list is adjusted using the
passed priority; and just before a time step is accepted a special call is made to the code model. The hybrids list initially contains all code model
instances that have both analog and event ports. Code models instances on the list receive an event call just before a time step is accepted. Setting
priority to 1 ensures that an instance will be called last, an instance with priority 2 will be called just before that, and so on. Each instance must use a
separate priority value, but the values used need not be consecutive. The final effect of cm_irreversible() is that when the call is made, CALL_TYPE
will have the special value STEP_PENDING, not the usual value, EVENT.
A code model using cm_irreversible() may schedule an analog breakpoint in such calls, so that the current time step does not proceed, although it was
acceptable to the simulator core. In that case no futher STEP_PENDING calls are made for the step.
cm_complex_add(), cm_complex_sub(), cm_complex_mult(), and cm_complex_div() each take two complex values as inputs and return the result
of a complex addition, subtraction, multiplication, or division, respectively.
When you create a directory for a new User-Defined Node, e.g. /ngspice/src/xspice/icm/xtraevt/new_type/, add a new User-Defined Node
Definition File udnfunc.c (see the example in Chapt. 28.8.3), and place a structure of type 'Evt_Udn_Info_t' at its bottom.
This structure contains the type name for the node, a description string, and pointers to each of the functions that define the node. This structure is
complete except for a text string that describes the node type. This string is stubbed out and may be edited by you if desired.
28.8.1 Macros
Name Type Description
MALLOCED_PTR void * Assign pointer to allocated structure
to this macro
STRUCT_PTR void * A pointer to a structure of the defined
type
STRUCT_PTR_1 void * A pointer to a structure of the defined
type
STRUCT_PTR_2 void * A pointer to a structure of the defined
type
EQUAL Mif_Boolean_t Assign TRUE or FALSE to this
macro according to the results of
structure comparison
INPUT_STRUCT_PTR void * A pointer to a structure of the defined
type
OUTPUT_STRUCT_PTR void * A pointer to a structure of the defined
type
INPUT_STRUCT_PTR_ARRAY void ** An array of pointers to structures of
the defined type
INPUT_STRUCT_PTR_ARRAY_SIZE int The size of the array
STRUCT_MEMBER_ID char * A string naming some part of the
structure
PLOT_VAL double The value of the specified structure
member for plotting purposes
PRINT_VAL char * The value of the specified structure
member for printing purposes
Table 28.4: User-Defined Node Macros
You must code the functions described in the following section using the macros appropriate for the particular function. You may elect whether not to
provide the optional functions.
It is an error to use a macro not defined for a function. Note that a review of the sample directories for the real and int UDN types will make the
function usage clearer.
The macros used in the User-Defined Node Definition File to access and assign data values are defined in Table 28.4. The translations of the macros
and of macros used in the function argument lists are defined in the Interface Design Document for the XSPICE Simulator.
Required functions:
create Allocate data structure used as inputs and outputs to
code models.
Assign OUTPUT_STRUCT_PTR to a pointer variable of the defined type. Scan through the array of structures, compute the resolved value, and
assign it into the output structure.
If the string is not static, a new string should be allocated on each call. Do not free the allocated strings.
Assign to IPC_VAL_SIZE an integer representing the size of the binary data in bytes.
#include <stdio.h>
#include "ngspice/cm.h"
#include "ngspice/evtudn.h"
void *tmalloc(size_t);
#define TMALLOC(t,n) (t*) tmalloc(sizeof(t)*(size_t)(n))
/* ************************************************* */
/* ************************************************* */
/* ************************************************* */
/* Initialize to zero */
*int_struct = 0;
}
/* ************************************************* */
/* ************************************************* */
/* ************************************************* */
int sum;
int i;
/* ************************************************* */
/* ************************************************* */
/* ************************************************* */
/* ************************************************* */
Evt_Udn_Info_t udn_int_info = {
"int",
"integer valued data",
NULL,
udn_int_create,
udn_int_dismantle,
udn_int_initialize,
udn_int_invert,
udn_int_copy,
udn_int_resolve,
udn_int_compare,
udn_int_plot_val,
udn_int_print_val,
udn_int_ipc_val
};
1. Error messages generated during the development of a code model (Preprocessor Error Messages).
2. Error messages generated by the simulator during a simulation run (Simulator Error Messages).
3. Error messages generated by individual code models (Code Model Error Messages).
These messages will be explained in detail in the following subsections.
The counted number of tokens in one of the file's input lines does not equal that required to define either a state header or a continuation line
(Note that all comment lines are ignored, so these will never cause the error to occur).
An output state value was defined using a symbol that was invalid (i.e., it was not one of the following: 0s, 1s, Us, 0r, 1r, Ur, 0z, 1z, Uz, 0u,
1u, Uu).
An input value was defined using a symbol that was invalid (i.e., it was not one of the following: 0, 1, X, or x).
index_error:
***ERROR***
D_STATE: An error exists in the ordering of states values
in the states->state[] array. This is usually caused
by non-contiguous state definitions in the state.in file
This error is caused by the different state definitions in the input file being non-contiguous. In general, it will refer to the different states not being
defined uniquely, or being `broken up' in some fashion within the state.in file.
30.1 SPECIFICATION
Overview of numerical-device specification
The input to CIDER consists of a SPICE-like description of a circuit, its analyses and its compact device models, and PISCES-like descriptions of
numerically analyzed device models. For a description of the SPICE input format, consult the SPICE3 Users Manual [JOHN92]. The KLU matrix
solver (15.1.1) is not supported.
To simulate devices numerically, two types of input must be added to the input file. The first is a model description in which the common
characteristics of a device class are collected. In the case of numerical models, this provides all the information needed to construct a device cross-
section, such as, for example, the doping profile. The second type of input consists of one or more element lines that specify instances of a numerical
model, describe their connection to the rest of the circuit, and provide additional element-specific information such as device layout dimensions ans
initial bias information.
The format of a numerical device model description differs from the standard approach used for SPICE3 compact models. It begins the same way
with one line containing the .MODEL keyword followed by the name of the model, device type and modeling level. However, instead of providing a
single long list of parameters and their values, numerical model parameters are grouped onto cards. Each type of card has its own set of valid
parameters. In all cases, the relative ordering of different types of cards is unimportant. However, for cards of the same type (such as mesh-
specification cards), their order in the input file can be important in determining the device structure.
Each card begins on a separate line of the input file. In order to let CIDER know that card lines are continuations of a numerical model description,
each must begin with the continuation character `+'. If there are too many parameters on a given card to allow it fit on a single line, the card can be
continued by adding a second `+' to the beginning of the next line. However, the name and value of a parameter should always appear on the same
line.
Several features are provided to make the numerical model format more convenient.
Blank space can follow the initial `+' to separate it from the name of a card or the card continuation `+'. Blank lines are also permitted, as long as they
also begin with an initial `+'. Parentheses and commas can be used to visually group or separate parameter definitions. In addition, while it is common
to add an equal sign between a parameter and its value, this is not strictly necessary.
The name of any card can be abbreviated, provided that the abbreviation is unique. Parameter name abbreviations can also be used if they are unique
in the list of a card's parameters. Numeric parameter values are treated identically as in SPICE3, so exponential notation, engineering scale factors and
units can be attached to parameter values: tau=10ns, nc=3.0e19cm^-3. In SPICE3, the value of a FLAG model parameter is changed to TRUE
simply by listing its name on the model line. In CIDER, the value of a numerical model FLAG parameter can be turned back to FALSE by preceding
it by a caret `^'. This minimizes the amount of input change needed when features such as debugging are turned on and off. In certain cases it is
necessary to include file names in the input description and these names may contain capital letters. If the file name is part of an element line, the
inout parser will convert these capitals to lowercase letters. To protect capitalization at any time, simply enclose the string in double quotes `”'.
The remainder of this manual describes how numerically analyzed elements and models can be used in CIDER simulations. The manual consists of
three parts. First, all of the model cards and their parameters are described. This is followed by a section describing the three basic types of numerical
models and their corresponding element lines. In the final section, several complete examples of CIDER simulations are presented.
Several conventions are used in the card descriptions. In the card synopses, the name of a card is followed by a list of parameter classes. Each class is
represented by a section in the card parameter table, in the same order as it appears in the synopsis line. Classes that contain optional parameters are
surrounded by brackets: [...]. Sometimes it only makes sense for a single parameter to take effect. (For example, a material can not simultaneously be
both Si and SiO2.) In such cases, the various choices are listed sequentially, separated by colons. The same parameter often has a number of different
acceptable names, some of which are listed in the parameter tables.1 These aliases are separated by vertical bars: `|'. Finally, in the card examples, the
model continuation pluses have been removed from the card lines for clarity's sake.
30.1.1 Examples
The model description for a two-dimensional numerical diode might look something like what follows. This example demonstrates many of the
features of the input format described above. Notice how the .MODEL line and the leading pluses form a border around the model description:
The element line for an instance of this model might look something like the following. Double quotes are used to protect the file name from
decapitalization:
SYNOPSIS
30.2.1 DESCRIPTION
The boundary and interface cards are used to set surface physics parameters along the boundary of a specified domain. Normally, the parameters
apply to the entire boundary, but there are two ways to restrict the area of interest. If a neighboring domain is also specified, the parameters are only
set on the interface between the two domains. In addition, if a bounding box is given, only that portion of the boundary or interface inside the
bounding box will be set.
If a semiconductor-insulator interface is specified, then an estimate of the width of any inversion or accumulation layer that may form at the interface
can be provided. If the surface mobility model (cf. models card) is enabled, then the model will apply to all semiconductor portions of the device
within this estimated distance of the interface. If a point lies within the estimated layer width of more than one interface, it belong to the interface
specified first in the input file. If the layer width given is less than or equal to zero, it is automatically replaced by an estimate calculated from the
doping near the interface. As a consequence, if the doping varies so will the layer width estimate.
Each edge of the bounding box can be specified in terms of its location or its mesh-index in the relevant dimension, or defaulted to the respective
boundary of the simulation mesh.
30.2.2 PARAMETERS
Name Type Description Units
Domain Integer ID number of primary domain
Neighbor Integer ID number of neighboring domain
X.Low Real Lowest X location of bounding box 𝜇𝑚
: IX.Low Integer Lowest X mesh-index of bounding box
X.High Real Highest X location of bounding box 𝜇𝑚
: IX.High Integer Highest X mesh-index of bounding box
Y.Low Real Lowest Y location of bounding box 𝜇𝑚
: IY.Low Integer Lowest Y mesh-index of bounding box
Y.High Real Highest Y location of bounding box 𝜇𝑚
𝐶
: IY.High Integer Highest Y mesh-index of bounding box
𝑐𝑚2
Qf Real Fixed interface charge
30.2.3 EXAMPLES
The following shows how the surface recombination velocities at an Si-SiO2 interface might be set:
The inversion layer width in the previous example can be automatically determined by setting the estimate to 0.0:
30.3 COMMENT
Add explanatory comments to a device definition.
SYNOPSIS
comment [text]
* [text]
$ [text]
# [text]
30.3.1 DESCRIPTION
Annotations can be added to a device definition using the comment card. All text on a comment card is ignored. Several popular commenting
characters are also supported as aliases: `*' from SPICE, `$' from PISCES, and `#' from Linux shell scripts.
30.3.2 EXAMPLES
A SPICE-like comment is followed by a PISCES-like comment and shell script comment:
30.4 CONTACT
Specify properties of an electrode
SYNOPSIS
30.4.1 DESCRIPTION
The properties of an electrode can be set using the contact card. The only changeable property is the work-function of the electrode material and this
only affects contacts made to an insulating material. All contacts to semiconductor material are assumed to be ohmic in nature.
30.4.2 PARAMETERS
Name Type Description
Number Integer ID number of the electrode
Work-function Real Work-function of electrode material. ( eV )
30.4.3 EXAMPLES
The following shows how the work-function of the gate contact of a MOSFET might be changed to a value appropriate for a P+ polysilicon gate:
SYNOPSIS
30.5.1 DESCRIPTION
A device is divided into one or more rectilinear domains, each of which has a unique identification number and is composed of a particular material.
Domain (aka region) cards are used to build up domains by associating a material type with a box-shaped section of the device. A single domain may
be the union of multiple boxes. When multiple domain cards overlap in space, the one occurring last in the input file will determine the ID number
and material type of the overlapped region.
Each edge of a domain box can be specified in terms of its location or mesh-index in the relevant dimension, or defaulted to the respective boundary
of the simulation mesh.
30.5.2 PARAMETERS
Name Type Description
Number Integer ID number of this domain
Material Integer ID number of material used by this domain
X.Low Real Lowest X location of domain box, ( 𝜇𝑚 )
: IX.Low Integer Lowest X mesh-index of domain box
X.High Real Highest X location of domain box, ( 𝜇𝑚 )
: IX-High Integer Highest X mesh-index of domain box
Y.Low Real Lowest Y location of domain box, ( 𝜇𝑚 )
: IY.Low Integer Lowest Y mesh-index of domain box
Y.High Real Highest Y location of domain box, ( 𝜇𝑚 )
: IY.High Integer Highest Y mesh-index of domain box
30.5.3 EXAMPLES
Create a 4.0 pm wide by 2.0 pm high domain out of material #1:
The next example defines the two domains that would be typical of a planar MOSFET simulation. One occupies all of the mesh below y = 0 and the
other occupies the mesh above y = 0. Because the x values are left unspecified, the low and high x boundaries default to the edges of the mesh:
30.6 DOPING
Add dopant to regions of a device
SYNOPSIS
30.6.1 DESCRIPTION
Doping cards are used to add impurities to the various domains of a device. Initially each domain is dopant-free. Each new doping card creates a new
doping profile that defines the dopant concentration as a function of position. The doping at a particular location is then the sum over all profiles of
the concentration values at that position. Each profile can be restricted to a subset of a device's domains by supplying a list of the desired domains.
A profile has uniform concentration inside the constant box. Outside this region, it varies according to the primary an lateral profile shapes. In 1D
devices the lateral shape is unused and in 2D devices the y-axis is the default axis for the primary profile. Several analytic functions can be used to
define the primary profile shape. Alternatively, empirical or simulated profile data can be extracted from a file. For the analytic profiles, the doping is
the product of a profile function (e.g. Gaussian) and a reference concentration, which is either the constant concentration of a uniform profile, or the
peak concentration for any of the other functions. If concentration data is used instead take from an ASCII file containing a list of location-
concentration pairs or a SUPREM3 exported file, the name of the file must be provided. If necessary, the final concentration at a point is then found
by multiplying the primary profile concentration by the value of the lateral profile function at that point. Empirical profiles must first be normalized
by the value at 0.0 to provide a usable profile functions. Alternatively, the second dimension can be included by assigning the same concentration to
all points equidistant from the edges of the constant box. The contours of the profile are the circular.
Unless otherwise specified, the added impurities are assumes to be N type. However, the name of a specific dopant species is needed when extracting
concentration information for that impurity from a SUPREM3 exported file.
Several parameters are used to adjust the basic shape of a profile functions so that the final, constructed profile, matches the doping profile in the real
device. The constant box region should coincide with a region of constant concentration in the device. For uniform profiles its boundaries default to
the mesh boundaries. For the other profiles the constant box starts as a point and only acquires width or height if both the appropriate edges are
specified. The location of the peak of the primary profile can be moved away from the edge of the constant box. A positive location places the peak
outside the constant box (cf. Fig. 30.1), and a negative value puts it inside the constant box (cf. Fig. 30.2). The concentration in the constant box is
terms of the characteristic length (by default equal to 1𝜇𝑚). The longer this length, the more gradually the profile will change. For example, in Fig.
then equal to the value of the profile when it intersects the edge of the constant box. The argument of the profile function is a distance expressed in
30.1 and Fig. 30.2, the profiles marked (a) have characteristic lengths twice those of the profiles marked (b). The location and characteristic length for
the lateral profile are multiplied by the lateral ratio. This allows the use of different length scales for the primary and lateral profiles. For rotated
profiles, this scaling is taken into account, and the profile contours are elliptical rather than circular.
This first example adds a uniform background P-type doping of 1.0 × 1016 𝑐𝑚− 3 to an entire device:
30.6.3 EXAMPLES
A Gaussian implantation with rotated lateral falloff, such as might be used for a MOSFET source, is then added:
confined between 𝑋 = 1𝜇𝑚 and 𝑋 = 3𝜇𝑚. The profile begins at 𝑌 = 0𝜇𝑚 (the high Y value defaults equal to the low Y value):
Finally, the MOSFET channel implant is extracted from an ASCII-format SUPREM3 file. The lateral profile is uniform, so that the implant is
30.7 ELECTRODE
Set location of a contact to the device
SYNOPSIS
30.7.1 DESCRIPTION
Each device has several electrodes that are used to connect the device to the rest of the circuit. The number of electrodes depends on the type of
device. For example, a MOSFET needs 4 electrodes. A particular electrode can be identified by its position in the list of circuit nodes on the device
element line. For example, the drain node of a MOSFET is electrode number 1, while the bulk node is electrode number 4. Electrodes for which an ID
number has not been specified are assigned values sequentially in the order they appear in the input file.
For lD devices, the positions of two of the electrodes are predefined to be at the ends of the simulation mesh. The first electrode is at the low end of
the mesh, and the last electrode is at the high end. The position of the special lD BJT base contact is set on the options card. Thus, electrode cards are
used exclusively for 2D devices.
Each card associates a portion of the simulation mesh with a particular electrode. In contrast to domains, which are specified only in terms of boxes,
electrodes can also be specified in terms of line segments. Boxes and segments for the same electrode do not have to overlap. If they don’t, it is
assumed that the electrode is wired together outside the area covered by the simulation mesh. However, pieces of different electrodes must not
overlap, since this would represent a short circuit. Each electrode box or segment can be specified in terms of the locations or mesh-indices of its
boundaries. A missing value defaults to the corresponding mesh boundary.
30.7.2 PARAMETERS
Name Type Description
Number Integer ID number of this domain
X.Low Real Lowest X location of electrode, (𝜇𝑚)
: IX.Low Integer Lowest X mesh-index of electrode
X.High Real Highest X location of electrode, (𝜇𝑚)
: IX.High Integer Highest X mesh-index of electrode
Y.Low Real Lowest Y location of electrode, (𝜇𝑚)
: IY.Low Integer Lowest Y mesh-index of electrode
Y.High Real Highest Y location of electrode, (𝜇𝑚)
: IY.High Integer Highest Y mesh-index of electrode
30.7.3 EXAMPLES
The following shows how the four contacts of a MOSFET might be specified:
* DRAIN
electrode x.l=0.0 x.h=0.5 y.l=0.0 y.h=0.0
* GATE
electrode x.l=1.0 x.h=3.0 iy.l=0 iy.h=0
* SOURCE
electrode x.l=3.0 x.h=4.0 y.l=0.0 y.h=0.0
* BULK
electrode x.l=0.0 x.h=4.0 y.l=2.0 y.h=2.0
The numbering option can be used when specifying bipolar transistors with dual base contacts:
* EMITTER
electrode num=3 x.l=1.0 x.h=2.0 y.l=0.0 y.h=0.0
* BASE
electrode num=2 x.l=0.0 x.h=0.5 y.l=0.0 y.h=0.0
electrode num=2 x.l=2.5 x.h=3.0 y.l=0.0 y.h=0.0
* COLLECTOR
electrode num=1 x.l=0.0 x.h=3.0 y.l=1.0 y.h=1.0
30.8 END
Terminate processing of a device definition
SYNOPSIS
end
30.8.1 DESCRIPTION
The end card stops processing of a device definition. It may appear anywhere within a definition. Subsequent continuation lines of the definition will
be ignored. If no end card is supplied, all the cards will be processed.
30.9 MATERIAL
Specify physical properties of a material
SYNOPSIS
30.9.1 DESCRIPTION
The material card is used to create an entry in the list of materials used in a device. Each entry needs a unique identification number and the type of
the material. Default values are assigned to the physical properties of the material. Most material parameters are accessible either here or on the
mobility or contact cards. However, some parameters remain inaccessible (e.g. the ionization coefficient parameters). Parameters for most physical
effect models are collected here. Mobility parameters are handled separately by the mobility card. Properties of electrode materials are set using the
contact card.
30.9.2 PARAMETERS
Name Type Description
Number Integer ID number of this material
Semiconductor : Silicon Flag Type of this material
: Polysilicon : GaAs
: Insulator : Oxide
: Nitride
𝐹
Affinity Real Electron affinity (eV)
𝑐𝑚
Permittivity Real Dielectric permittivity ()
𝑒𝑉
Eg Real Energy band gap (eV)
°𝐾
dEg.dT Real Bandgap narrowing with temperature ( )
𝑒𝑉
Eg.Tref Real Bandgap reference temperature, ( °K )
𝑐𝑚−3
dEg.dN Real Bandgap narrowing with N doping, ( )
𝑐𝑚
dEg.dP Real Bandgap narrowing with P doping, ( −3 )
𝑐𝑚6
𝑠𝑒𝑐
CP Real
Auger coefficient - holes ( )
𝐴
𝑐𝑚2
ARichN Real Richardson constant - electrons, ( )
°𝐾2
𝐴
𝑐𝑚 2
ARichP Real Richardson constant - holes, ( )
°𝐾2
30.9.3 EXAMPLES
Set the type of material #1 to silicon, then adjust the values of the temperature-dependent bandgap model parameters:
The recombination lifetimes can be set to extremely short values to simulate imperfect semiconductor material:
30.10 METHOD
Choose types and parameters of numerical methods
SYNOPSIS
30.10.1 DESCRIPTION
The method card controls which numerical methods are used during a simulation and the parameters of these methods. Most of these methods are
optimizations that reduce run time, but may sacrifice accuracy or reliable convergence.
For majority-carrier devices such as MOSFETs, one carrier simulations can be used to save simulation time. The systems of equations in AC analysis
may be solved using either direct or successive-over-relaxation techniques. Successive-over-relaxation is faster, but at high frequencies, it may fail to
converge or may converge to the wrong answer. In some cases, it is desirable to obtain AC parameters as functions of DC bias conditions. If
necessary, a one-point AC analysis is performed at a predefined frequency in order to obtain these small-signal parameters. The default for this
frequency is 1 Hz. The Jacobian matrix for DC and transient analyses can be simplified by ignoring the derivatives of the mobility with respect to the
solution variables. However, the resulting analysis may have convergence problems. Additionally, if they are ignored during AC analyses, incorrect
results may be obtained.
A damped Newton method is used as the primary solution technique for the device-level partial differential equations. This algorithm is based on an
iterative loop that terminates when the error in the solution is small enough or the iteration limit is reached. Error tolerances are used when
determining if the error is `small enough'. The tolerances are expressed in terms of an absolute, solution-independent error and a relative, solution-
dependent error. The absolute-error limit can be set on this card. The relative error is computed by multiplying the size of the solution by the circuit
level SPICE parameter RELTOL.
30.10.2 Parameters
Name Type Description
OneCarrier Flag Solve for majority carriers only
AC analysis String AC analysis method, ( either DIRECT or SOR)
NoMobDeriv Flag Ignore mobility derivatives
Frequency Real AC analysis frequency, ( Hz )
ItLim Integer Newton iteration limit
DevTol Real Maximum residual error in device equations
30.10.3 Examples
Use one carrier simulation for a MOSFET, and choose direct method AC analysis to ensure accurate, high frequency results:
Tolerate no more than 10− 10 as the absolute error in device-level equations, and perform no more than 15 Newton iterations in any one loop:
30.11 Mobility
Specify types and parameters of mobility models
SYNOPSIS
30.11.1 Description
The mobility model is one of the most complicated models of a material's physical properties. As a result, separate cards are needed to set up this
model for a given material.
Mobile carriers in a device are divided into a number of different classes, each of which has different mobility modeling. There are three levels of
division. First, electrons and holes are obviously handled separately. Second, carriers in surface inversion or accumulation layers are treated
differently than carriers in the bulk. Finally, bulk carriers can be either majority or minority carriers.
For surface carriers, the normal-field mobility degradation model has three user-modifiable parameters. For bulk carriers, the ionized impurity
scattering model has four controllable parameters. Different sets of parameters are maintained for each of the four bulk carrier types: majority-
electron, minority-electron, majority-hole and minority-hole. Velocity saturation modeling can be applied to both surface and bulk carriers. However,
only two sets of parameters are maintained: one for electrons and one for holes. These must be changed on a majority carrier card (i.e. when the
majority flag is set).
Several models for the physical effects are available, along with appropriate default values. Initially, a universal set of default parameters usable with
all models is provided. These can be overridden by defaults specific to a particular model by setting the initialization flag. These can then be changed
directly on the card itself. The bulk ionized impurity models are the Caughey-Thomas (CT) model and the Scharfetter-Gummel (SG) model
[CAUG671, [SCHA69]. Three alternative sets of defaults are available for the Caughey-Thomas expression. They are the Arora (AR) parameters for
Si [AROR82], the University of Florida (UF) parameters for minority carriers in Si [SOLL90], and a set of parameters appropriate for GaAs (GA).
The velocity-saturation models are the Caughey-Thomas (CT) and Scharfetter-Gummel (SG) models for Si, and the PISCES model for GaAs (GA).
There is also a set of Arora (AR) parameters for the Caughey-Thomas model.
30.11.2 Parameters
Name Type Description
Material Integer ID number of material
Electron : Hole Flag Mobile carrier
Majority : Minority Flag Mobile carrier type
MUS Real Maximum surface mobility, ( cm2/Vs )
EC.A Real Surface mobility 1st-order critical field, ( V/cm )
EC.B Real Real Surface mobility 2nd-order critical field, ( V2/cm2 )
MuMax Real Maximum bulk mobility, ( cm2/Vs )
MuMin Real Minimum bulk mobility, ( cm2/Vs)
NtRef Real Ionized impurity reference concentration, ( cm-3 )
NtExp Real Ionized impurity exponent
Vsat Real Saturation velocity, ( cm/s )
Vwarm Real Warm carrier reference velocity, ( cm/s )
ConcModel String Ionized impurity model, ( CT, AR, UF, SG, Dr GA )
FieldModel String Velocity saturation model, ( CT, AR, SG, or GA )
Init Flag Copy model-specific defaults
30.11.3 Examples
The following set of cards completely updates the bulk mobility parameters for material #1:
Finally, the default Scharfetter-Gummel parameters can be used in Si with the GaAs velocity-saturation model (even though it doesn't make physical
sense!):
30.11.5 BUGS
The surface mobility model does not include temperature-dependence for the transverse-field parameters. Those parameters will need to be adjusted
by hand.
30.12 MODELS
Specify which physical models should be simulated
SYNOPSIS
30.12.1 DESCRIPTION
The models card indicates which physical effects should be modeled during a simulation. Initially, none of the effects are included. A flag can be set
false by preceding by a caret.
30.12.2 Parameters
Name Type Description
BGN Flag Bandgap narrowing
SRH Flag Shockley-Reed-Hall recombination
ConcTau Flag Concentration-dependent SRH lifetimes
Auger Flag Auger recombination
Avalanche Flag Local avalanche generation
TempMob Flag Temperature-dependent mobility
ConcMob Flag Concentration-dependent mobility
FieldMob Flag Lateral-field-dependent mobility
TransMob Flag Transverse-field-dependent surface mobility
SurfMob Flag Activate surface mobility model
30.12.3 Examples
Turn on bandgap narrowing, and all of the generation-recombination effects:
Amend the first card by turning on lateral- and transverse-field-dependent mobility in surface charge layers, and lateral-field-dependent mobility in
the bulk. Also, this line turns avalanche generation modeling off.
30.12.5 Bugs
The local avalanche generation model for 2D devices does not compute the necessary contributions to the device-level Jacobian matrix. If this model
is used, it may cause convergence difficulties and it will cause AC analyses to produce incorrect results.
30.13 OPTIONS
Provide optional device-specific information
SYNOPSIS
30.13.1 DESCRIPTION
The options card functions as a catch-all for various information related to the circuit-device interface. The type of a device can be specified here, but
will be defaulted if none is given. Device type is used primarily to determine how to limit the changes in voltage between the terminals of a device. It
also helps determine what kind of boundary conditions are used as defaults for the device electrodes.
A previously calculated state, stored in the named initial-conditions file, can be loaded at the beginning of an analysis. If it is necessary for each
instance of a numerical model to start in a different state, then the unique flag can be used to generate unique filenames for each instance by
appending the instance name to the given filename. This is the same method used by CIDER to generate unique filenames when the states are
originally saved. If a particular state file does not fit. this pattern, the filename can be entered directly on the instance line.
Mask dimension defaults can be set so that device sizes can be specified in terms of area or width. Dimensions for the special lD BJT base contact can
also be controlled. The measurement temperature of material parameters, normally taken to be the circuit default, can be overridden.
30.13.2 Parameters
Name Type Description
Resistor Flag Resistor
: Capacitor Flag Capacitor
: Diode Flag Diode
: Bipolar|BJT Flag Bipolar transistor
: MOSFET Flag MOS field-effect transistor
: JFET Flag Junction field-effect transistor
: MESFET Flag MES field-effect transistor
IC.File String Initial-conditions filename
Unique Flag Append instance name to filename
DefA Real Default Mask Area, (m²)
DefW Real Default Mask Width, (m)
DefL Real Default Mask Length, (m)
Base.Area Real lD BJT base area relative to emitter area
Base.Length Real Real lD BJT base contact length, (µm)
Base.Depth Real lD BJT base contact depth, (µm)
TNom Real Nominal measurement temperature, (°C)
30.13.3 Examples
Normally, a 'numos' device model is used for MOSFET devices. However, it can be changed into a bipolar-with-substrate-contact model, by
specifying a bipolar structure using the other cards, and indicating the device-structure type as shown here. The default length is set to 1.0 µm so that
when mask area is specified on the element line it can be divided by this default to obtain the device width.
Specify that a 1D BJT has base area 1/10th that of the emitter, has an effective depth of 0.2 µm and a length between the internal and external base
contacts
If a circuit contains two instances of a bipolar transistor model named 'q1' and 'q2', the following line tells the simulator to look for initial conditions
in the 'OP1.q2', respectively. The period in the middle of the names is added automatically:
30.14 OUTPUT
Identify information to be printed or saved
SYNOPSIS
30.14.1 DESCRIPTION
The output card is used to control the amount of information that is either presented to or saved for the user. Three types of information are available.
Debugging information is available as a means to monitor program execution. This is useful during long simulations when one is unsure about
whether the program has become trapped at some stage of the simulation. General information about a device such as material parameters and
resource usage can be obtained. Finally, information about the internal and external states of a device is available. Since this data is best interpreted
using a post-processor, a facility is available for saving device solutions in auxiliary output files. Solution filenames are automatically generated by
the simulator. If the named file already exists, the file will be overwritten. A filename unique to a particular circuit or run can be generated by
providing a root filename. This root name will be added onto the beginning of the automatically generated name. This feature can be used to store
solutions in a directory other than the current one by specifying the root filename as the path of the desired directory. Solutions are only saved for
those devices that specify the ‘save’ parameter on their instance lines.
The various physical values that can be saved are named below. By default, the following values are saved: the doping, the electron and hole
concentrations, the potential, the electric field, the electron and hole current densities, and the displacement current density. Values can be added to or
deleted from this list by turning the appropriate flag on or off. For vector-valued quantities in two dimensions, both the X and Y components are
saved. The vector magnitude can be obtained during post-processing.
Saved solutions can be used in conjunction with the options card and instance lines to reuse previously calculated solutions as initial guesses for new
solutions. For example, it is typical to initialize the device to a known state prior to beginning any DC transfer curve or operating point analysis. This
state is an ideal candidate to be saved for later use when it is known that many analyses will be performed on a particular device structure.
Depending on the global variable filetype the outputs may be stored as (compact) binary or text processor readable ascii formatted data.
30.14.2 Parameters
Name Type Description
All.Debug Flag Debug all analyses
OP.Debug Flag .OP analyses
DC.Debug Flag .DC analyses
TRAN.Debug Flag .TRAN analyses
AC.Debug Flag .AC analyses
PZ.Debug Flag .PZ analyses
Material Flag Physical material information
Statistics | Resources Flag Resource usage information
RootFile String Root of output file names
Psi Flag Potential ( V )
Equ.Psi Flag Equilibrium potential ( V )
Vac.Psi Flag Vacuum potential ( V )
Doping Flag Net doping ( cm³ )
N.Conc Flag Electron concentration ( cm³ )
P.Conc Flag Hole concentration ( cm³ )
PhiN Flag Electron quasi-fermi potential ( V )
PhiP Flag Hole quasi-fermi potential ( V )
PhiC Flag Conduction band potential ( V )
PhiV Flag Valence band potential ( V )
E.Field Flag Electric field ( V/cm )
JC Flag Conduction current density ( A/cm² )
JD Flag Displacement current density ( A/cm² )
JN Flag Electron current density ( A/cm² )
JP Flag Hole current density ( A/cm² )
JT Flag Total current density ( A/cm² )
Unet Flag Net recombination ( 1/cm³ s )
MuN Flag Electron mobility (low-field) ( cm²/Vs )
MuP Flag Hole mobility (low-field) ( cm²/Vs )
30.14.3 Examples
The following example activates all potentially valuable diagnostic output:
Energy band diagrams generally contain the potential, the quasi-fermi levels, the energies and the vacuum energy. The following example enables
saving of the r values needed to make energy band diagrams:
( Ψ , n, and p ) need to be saved. This example turns off the nonessential default values (and indicates the essential ones explicitly):
Sometimes it is desirable to save certain key solutions, and then reload them for use in subsequent simulations. In such cases only the essential values
30.15 TITLE
Provide a label for this device’s output
SYNOPSIS
title [text]
30.15.1 DESCRIPTION
The title card provides a label for use as a heading in various output files. The text can be any length, but titles that fit on a single line will produce
more aesthetically pleasing output.
30.15.2 EXAMPLES
Set the title for a minimum gate length NMOSFET in a 1.0µm BiCMOS process
30.15.3 BUGS
The title is currently treated like a comment.
SYNOPSIS
30.16.1 DESCRIPTION
The domains of a device are discretized onto a rectangular finite-difference mesh using x.mesh cards for 1D devices, or x.mesh and y.mesh cards for
2D devices. Both uniform and non-uniform meshes can be specified.
The location of a reference line in the mesh must either be given explicitly (using Location) or defined implicitly relative to the location of the
previous reference line (by using Width). (If the first card in either direction is specified using Width, an initial reference line is automatically
generated at location 0.0.) The line number of the reference line can be given explicitly, in which case the automatic lines are evenly spaced within the
interval, and the number of lines is determined from the difference between the current line number and that of the previous reference line. However,
if the interval width is given, then the line number is interpreted directly as the number of additional lines to add to the mesh.
For a nonuniformly spaced interval, the number of automatic lines has to be determined using the mesh spacing parameters. Nonuniform spacing is
triggered by providing a desired ratio for the lengths of the spaces between adjacent pairs of lines. This ratio should always be greater than one,
indicating the ratio of larger spaces to smaller spaces. In addition to the ratio, one or both of the space widths at the ends of the interval must be
provided. If only one is given, it will be the smallest space and the largest space will be at the opposite end of the interval. If both are given, the
largest space will be in the middle of the interval. In certain cases it is desirable to limit the growth of space widths in order to control the solution
accuracy. This can be accomplished by specifying a maximum space size, but this option is only available when one of the two end lengths is given.
Note that once the number of new lines is determined using the desired ratio, the actual spacing ratio may be adjusted so that the spaces exactly fill
the interval.
30.16.2 Parameters
Name Type Description
Location Real Location of this mesh line, ( µm )
:Width Real Width between this and previous mesh lines, ( µm )
Number | Node Integer Number of this mesh line
:Ratio Real Ratio of sizes of adjacent spaces
H.Start | H1 Real Space size at start of interval, ( µm )
H.End | H2 Real Space size at end of interval, ( µm )
H.Max | H3 Real Maximum space size inside interval, ( µm )
30.16.3 EXAMPLES
A 50 node, uniform mesh for a 5 µm long semiconductor resistor can be specified as:
An accurate mesh for a 1D diode needs fine spacing near the junction. In this example, the junction is assumed to be 0.75 µm deep. The spacing near
the diode ends is limited to a maximum of 0.1 µm:
The vertical mesh spacing of a MOSFET can generally be specified as uniform through the gate oxide, very fine for the surface inversion layer,
moderate down to the so source/drain junction depth, and then increasing all the way to the bulk contact:
30.17 NUMD
Diode / two-terminal numerical models and elements
SYNOPSIS Model:
SYNOPSIS Element:
SYNOPSIS Output:
30.17.1 DESCRIPTION
NUMD is the name for a diode numerical model. In addition, this same model can be used to simulate other two-terminal structures such as
semiconductor resistors and MOS capacitors. See the options card for more information on how to customize the device type.
Both 1D and 2D devices are supported. These correspond to the LEVEL=l and LEVEL=2 models, respectively. If left unspecified, it is assumed that
the device is one-dimensional.
All numerical two-terminal element names begin with the letter ‘D. The element name is then followed by the names of the positive (n1) and negative
(n2) nodes. After this must come the name of the model used for the element. The remaining information can come in any order. The layout
dimensions of an element are specified relative to the geometry of a default device. For 1D devices, the default device has an area of 1m², and for 2D
devices, the default device has a width of 1 m. However, these defaults can be overridden on an options card. The operating temperature of a device
can be set independently from that of the rest of the circuit in order to simulate non-isothermal circuit operation. Finally, the name of a file containing
an initial state for the device can be specified. Remember that if the filename contains capital letters, they must be protected by surrounding the
filename with double quotes. Alternatively, the device can be placed in an OFF state (thermal equilibrium) at the beginning of the analysis. For more
information on the use of initial conditions, see the ngspice User’s Manual, Chapt. 7.1.
In addition to the element input parameters, there are output-only parameters that can be shown using the ngspice show command (17.5.79) or
and admittance (Y) matrices where 𝑌 = 𝐺 + 𝑗𝜔𝐶. By default, the parameters are computed at 1 Hz. Each element is accessed using the name of the
captured using the save/.SAVE (17.5.68/15.6.1) command. These parameters are the elements of the indefinite conductance (G), capacitance (C),
matrix (g, c or y) followed by the node indices of the output terminal and the input terminal (e.g. g11). Beware that names are case-sensitive for
save/show, so lower-case letters must be used.
30.17.2 Parameters
Name Type Description
Level Integer Dimensionality of numerical model
Area Real Multiplicative area factor
W Real Multiplicative width factor
Temp Real Element operating temperature
IC.File String Initial-conditions filename
Off Flag Device initially in OFF state
gIJ Flag Conductance element 𝐺𝑖𝑗 , ( Ω )
cIJ Flag Capacitance element 𝐶𝑖𝑗 , ( F )
yIJ Flag Admittance element 𝑌𝑖𝑗 , ( Ω )
30.17.3 EXAMPLES
A one-dimensional numerical switching-diode element/model pair with an area twice that of the default device (which has a size of l µm x 1 µm) can
be specified using:
A two-dimensional two-terminal MOS capacitor with a width of 20 µm and an initial condition of 3 V is created by:
The next example shows how both the width and area factors can be used to create a power diode with area twice that of a 6µm-wide device (i.e. a
12µm-wide device). The device is assumed to be operating at a temperature of 100°C:
This example saves all the small-signal parameters of the previous diode:
30.17.5 BUGS
Convergence problems may be experienced when simulating MOS capacitors due to singularities in the current-continuity equations.
30.18 NBJT
Bipolar / three-terminal numerical models and elements
SYNOPSIS Model:
SYNOPSIS Element:
SYNOPSIS Output:
30.18.1 DESCRIPTION
NBJT is the name for a bipolar transistor numerical model. In addition, the 2D model can be used to simulate other three-terminal structures such as a
JFET or MESFET. However, the 1D model is customized with a special base contact, and cannot be used for other purposes. See the options card for
more information on how to customize the device type and setup the 1D base contact.
Both 1”and 2D devices are supported. These correspond to the LEVEL=l and models, respectively. If left unspecified, it is assumed that the device is
one-dimensional.
All numerical three-terminal element names begin with the letter 'Q'. If the device is a bipolar transistor, then the nodes are specified in the order:
collector (nl), base (n2), emitter (n3). For a JFET or MESFET, the node order is: drain (n1), gate (n2), source (n3). After this must come the name of
the model used for the element. The remaining information can come in any order. The layout dimensions of an element are specified relative to the
geometry of a default device. For the 1D BJT, the default device has an area of lm², and for 2D devices, the default device has a width of lm. In
addition, it is assumed that the default 1D BJT has a base contact with area equal to the emitter area, length of 1µm and a depth automatically
determined from the device doping profile. However, all these defaults can be overridden on an options card.
The operating temperature of a device can be set independently from the rest of that of the circuit in order to simulate non-isothermal circuit
operation. Finally, the name of a file containing an initial state for the device can be specified. Remember that if the filename contains capital letters,
they must be protected by surrounding the filename with double quotes. Alternatively, the device can be placed in an OFF state (thermal equilibrium)
at the beginning of the analysis. For more information on the use of initial conditions, see the ngspice User’s Manual.
In addition to the element input parameters, there are output-only parameters that can be shown using the SPICE show command or captured using the
𝑌 = 𝐺 + 𝑗𝜔𝐶. By default, the parameters are computed at 1Hz. Each element is accessed using the name of the matrix (g, c or y) followed by the
save/.SAVE command. These parameters are the elements of the indefinite conductance (G), capacitance (C), and admittance (Y) matrices where
node indices of the output terminal and the input terminal (e.g. g11). Beware that parameter names are case-sensitive for save/show, so lower-case
letters must be used.
30.18.2 Parameters
Name Type Description
Level Integer Dimensionality of numerical model
Area Real Multiplicative area factor
W Real Multiplicative width factor
Temp Real Element operating temperature
IC.File String Initial-conditions filename
Off Flag Device initially in OFF state
gIJ Flag Conductance element 𝐺𝑖𝑗 , ( Ω )
cIJ Flag Capacitance element 𝐶𝑖𝑗 , ( F )
yIJ Flag Admittance element 𝑌𝑖𝑗 , ( Ω )
30.18.3 EXAMPLES
A one-dimensional numerical bipolar transistor with an emitter stripe 4 times as wide as the default device is created using:
Q2 1 2 3 M_BJT AREA=4
This example saves the output conductance (go), transconductance (gm) and input conductance (gpi) of the previous transistor in that order:
The second example is for a two-dimensional JFET with a width of 5pm and initial conditions obtained from file IC.jfet:
A final example shows how to use symmetry to simulate half of a 2D BJT, avoiding having the user double the area of each instance:
30.18.5 BUGS
MESFETs cannot be simulated properly yet because Schottky contacts have not been implemented.
30.19 NUMOS
MOSFET / four-terminal numerical models and elements
SYNOPSIS Model:
SYNOPSIS Element:
SYNOPSIS Output:
30.19.1 DESCRIPTION
NUMOS is the name for a MOSFET numerical model. In addition, the 2D model can be used to simulate other four-terminal structures such as
integrated bipolar and JFET devices with substrate contacts. However, silicon controlled rectifiers (SCRs) cannot be simulated because of the
snapback in the transfer characteristic. See the options card for more information on how to customize the device type. The LEVEL parameter of two-
and three-terminal devices is not needed, because only 2D devices are supported. However, it will accepted and ignored if provided.
All numerical four-terminal element names begin with the letter ‘M’. If the device is a MOSFET, or JFET with a bulk contact, then the nodes are
specified in the order: drain (n1), gate (n2), source (n3), bulk (n4). If the device is a BJT, the node order is: collector (n1), base (n2), emitter (n3),
substrate (n4). After this must come the name of the model 1used for the element. The remaining information can come in any order. The layout
dimensions of an element are specified relative to the geometry of a default device. The default device has a width of lm. However, this default can be
overridden on an options card. In addition, the element line will accept a length parameter, L, but does not use it in any calculations. This is provided
to enable somewhat greater compatibility between numerical MOSFET models and the standard SPICE3 compact MOSFET models.
The operating temperature of a device can be set independently from that of the rest of the circuit in order to simulate non-isothermal circuit
operation. Finally, the name of a file containing an initial state for the device can be specified. Remember that if the filename contains capital letters,
they must be protected by surrounding the filename with double quotes. Alternatively, the device can be placed in an OFF state (thermal equilibrium)
at the beginning of the analysis. For more information on the use of initial conditions, see the ngspice User’s Manual.
In addition to the element input parameters, there are output-only parameters that can be shown using the SPICE show command or captured using the
save/.SAVE command.
These parameters are the elements of the indefinite conductance (G), capacitance (C), and admittance (Y) matrices where 𝑌 = 𝐺 + 𝑗𝜔𝐶. By default,
the parameters are computed at 1 Hz. Each element is accessed using the name of the matrix (g, c or y) followed by the node indices of the output
terminal and the input terminal (e.g. g11). Beware that parameter names are case-sensitive for save/show, so lower-case letters must be used.
30.19.2 Parameters
Name Type Description
Level Integer Dimensionality of numerical model
Area Real Multiplicative area factor
W Real Multiplicative width factor
L Real Unused length factor
Temp Real Element operating temperature
IC.File String Initial-conditions filename
Off Flag Device initially in OFF state
gIJ Flag Conductance element 𝐺𝑖𝑗 , ( Ω )
cIJ Flag Capacitance element 𝐶𝑖𝑗 , ( F )
yIJ Flag Admittance element 𝑌𝑖𝑗 , ( Ω )
30.19.3 EXAMPLES
A numerical MOSFET with a gate width of 5µm and length of 1µm is described below. However, the model can only be used for lµm length devices,
so the length parameter is redundant. The device is initially biased near its threshold by taking an initial state from the file NM1.vth.
This example saves the definite admittance matrix of the previous MOSFET where the source terminal (3) is used as the reference. (The definite
admittance matrix is formed by deleting the third row and column from the indefinite admittance matrix.)
Bipolar transistors are usually specified in terms of their area relative to a unit device. The following example creates a unit-sized device:
MQ1 NC NB NE NS N_BJT
.MODEL M_BJT NUMOS LEVEL=2
+ options bipolar defw=5um
+ ...
Part IV Miscellaneous
save @m1[cgs]
given before a transient simulation causes the specified capacitance value to be saved at each time-point, and a subsequent command such as
plot @m1[cgs]
produces the desired plot. (Note that the show command does not use this format).
Some variables are listed as both input and output, and their output simply returns the previously input value, or the default value after the simulation
has been run. Some parameters are input only because the output system can not handle variables of the given type yet, or the need for them as output
variables has not been apparent. Many such input variables are available as output variables in a different format, such as the initial condition vectors
that can be retrieved as individual initial condition values. Finally, internally derived values are output only and are provided for debugging and
operating point output purposes.
If you want to access a device parameter of a device used inside of a subcircuit, you may use the syntax as shown below.
General form:
@device_identifier.subcircuit_name.<subcircuit_name_nn>
+.device_name[parameter]
The device identifier is the first letter extracted from the device name, e.g. m for a MOS transistor.
Please note that the parameter tables presented below do not provide the detailed information available about the parameters provided in the section
on each device and model, but are provided as a quick reference guide.
31.5 BJTs
31.5.1 BJT - Bipolar Junction Transistor
31.5.1.1 BJT instance parameters
# Name Direction Type Description
2 off InOut flag Device initially off
3 icvbe InOut real Initial B-E voltage
4 icvce InOut real Initial C-E voltage
1 area InOut real (Emitter) Area factor
10 areab InOut real Base area factor
11 areac InOut real Collector area factor
9 m InOut real Parallel Multiplier
5 ic In real vector Initial condition vector
6 sens_area In flag flag to request sensitivity WRT area
202 colnode Out integer Number of collector node
203 basenode Out integer Number of base node
204 emitnode Out integer Number of emitter node
205 substnode Out integer Number of substrate node
206 colprimenode Out integer Internal collector node
207 baseprimenode Out integer Internal base node
208 emitprimenode Out integer Internal emitter node
211 ic Out real Current at collector node
212 ib Out real Current at base node
236 ie Out real Emitter current
237 is Out real Substrate current
209 vbe Out real B-E voltage
210 vbc Out real B-C voltage
215 gm Out real Small signal transconductance
213 gpi Out real Small signal input conductance - pi
214 gmu Out real Small signal conductance - mu
225 gx Out real Conductance from base to internal base
216 go Out real Small signal output conductance
227 geqcb Out real d(Ibe)/d(Vbc)
228 gcsub Out real Internal Subs. cap. equiv. cond.
243 gdsub Out real Internal Subs. Diode equiv. cond.
229 geqbx Out real Internal C-B-base cap. equiv. cond.
239 cpi Out real Internal base to emitter capactance
240 cmu Out real Internal base to collector capactiance
241 cbx Out real Base to collector capacitance
242 csub Out real Substrate capacitance
218 cqbe Out real Cap. due to charge storage in B-E jct.
220 cqbc Out real Cap. due to charge storage in B-C jct.
222 cqsub Out real Cap. due to charge storage in Subs. jct.
224 cqbx Out real Cap. due to charge storage in B-X jct.
226 cexbc Out real Total Capacitance in B-X junction
217 qbe Out real Charge storage B-E junction
219 qbc Out real Charge storage B-C junction
221 qsub Out real Charge storage Subs. junction
223 qbx Out real Charge storage B-X junction
238 p Out real Power dissipation
235 sens_dc Out real dc sensitivity
230 sens_real Out real real part of ac sensitivity
231 sens_imag Out real dc sens. & imag part of ac sens.
232 sens_mag Out real sensitivity of ac magnitude
233 sens_ph Out real sensitivity of ac phase
234 sens_cplx Out complex ac sensitivity
7 temp InOut real instance temperature
8 dtemp InOut real instance temperature delta from circuit
31.6 MOSFETs
31.6.1 MOS1 - Level 1 MOSFET model with Meyer capacitance model
31.6.1.1 MOS1 instance parameters
# Name Direction Type Description
21 m InOut real Multiplier
2 l InOut real Length
1 w InOut real Width
4 ad InOut real Drain area
3 as InOut real Source area
6 pd InOut real Drain perimeter
5 ps InOut real Source perimeter
8 nrd InOut real Drain squares
7 nrs InOut real Source squares
9 off In flag Device initially off
12 icvds InOut real Initial D-S voltage
13 icvgs InOut real Initial G-S voltage
11 icvbs InOut real Initial B-S voltage
20 temp InOut real Instance temperature
22 dtemp InOut real Instance temperature difference
10 ic In real vector Vector of D-S, G-S, B-S voltages
15 sens_l In flag flag to request sensitivity WRT length
14 sens_w In flag flag to request sensitivity WRT width
215 id Out real Drain current
18 is Out real Source current
17 ig Out real Gate current
16 ib Out real Bulk current
217 ibd Out real B-D junction current
216 ibs Out real B-S junction current
231 vgs Out real Gate-Source voltage
232 vds Out real Drain-Source voltage
230 vbs Out real Bulk-Source voltage
229 vbd Out real Bulk-Drain voltage
203 dnode Out integer Number of the drain node
204 gnode Out integer Number of the gate node
205 snode Out integer Number of the source node
206 bnode Out integer Number of the node
207 dnodeprime Out integer Number of int. drain node
208 snodeprime Out integer Number of int. source node
211 von Out real
212 vdsat Out real Saturation drain voltage
213 sourcevcrit Out real Critical source voltage
214 drainvcrit Out real Critical drain voltage
258 rs Out real Source resistance
209 sourceconductance Out real Conductance of source
259 rd Out real Drain conductance
210 drainconductance Out real Conductance of drain
219 gm Out real Transconductance
220 gds Out real Drain-Source conductance
218 gmb Out real Bulk-Source transconductance
218 gmbs Out real
221 gbd Out real Bulk-Drain conductance
222 gbs Out real Bulk-Source conductance
223 cbd Out real Bulk-Drain capacitance
224 cbs Out real Bulk-Source capacitance
233 cgs Out real Gate-Source capacitance
236 cgd Out real Gate-Drain capacitance
239 cgb Out real Gate-Bulk capacitance
235 cqgs Out real Capacitance due to gate-source charge storage
238 cqgd Out real Capacitance due to gate-drain charge storage
241 cqgb Out real Capacitance due to gate-bulk charge storage
243 cqbd Out real Capacitance due to bulk-drain charge storage
245 cqbs Out real Capacitance due to bulk-source charge storage
225 cbd0 Out real Zero-Bias B-D junction capacitance
226 cbdsw0 Out real
227 cbs0 Out real Zero-Bias B-S junction capacitance
228 cbssw0 Out real
234 qgs Out real Gate-Source charge storage
237 qgd Out real Gate-Drain charge storage
240 qgb Out real Gate-Bulk charge storage
242 qbd Out real Bulk-Drain charge storage
244 qbs Out real Bulk-Source charge storage
19 p Out real Instaneous power
256 sens_l_dc Out real dc sensitivity wrt length
246 sens_l_real Out real real part of ac sensitivity wrt length
247 sens_l_imag Out real imag part of ac sensitivity wrt length
248 sens_l_mag Out real sensitivity wrt l of ac magnitude
249 sens_l_ph Out real sensitivity wrt l of ac phase
250 sens_l_cplx Out complex ac sensitivity wrt length
257 sens_w_dc Out real dc sensitivity wrt width
251 sens_w_real Out real real part of ac sensitivity wrt width
252 sens_w_imag Out real imag part of ac sensitivity wrt width
253 sens_w_mag Out real sensitivity wrt w of ac magnitude
254 sens_w_ph Out real sensitivity wrt w of ac phase
255 sens_w_cplx Out complex ac sensitivity wrt width
# Name Direction Type Description
31.6.8 BSIM3
The accessible device parameters (see Chapt. 31.1 for the syntax) are listed here.
The parameters are available in the BSIM3 models (level=8 or level=49) version=3.2.4 and version=3.3.0 only. Negative capacitance values may
occur, depending on the internal calculation. Please see the note in Chapt. 31.6.9.1.
31.6.9 BSIM4
The accessible device parameters (see Chapt. 31.1 for the syntax) are listed here.
The parameters are available in all BSIM4 models (level=14 or level=54) version=4.2.1 to version=4.8.
Negative capacitance values may occur, depending on the internal calculation. To compare with measured data, please just use the absolute values of
the capacitance data. For an explanation of negative values and the basics on how capacitance values are evaluated in a BSIM model, please refer to
the book BSIM4 and MOSFET Modeling for IC Simulation by Liu and Hu, Chapt. 5.2.
Some special considerations are required when Verilog-A models are to be included (see chapter 13.2).
The following software must be installed in your system to compile ngspice: bison, flex, and X11 (and Xaw, Xmu, Xext, Xft, FontConfig,
Xrender, and freetype) headers (e.g. libX11-devel) and libs (e.g. libX11-6).
The X11 headers and libraries are typically available in an X11 development package from your Linux distribution.
If you want to compile the source code from Git, you will need additional software: autoconf, automake, libtool.
For your convenience you always should add readline (or editline) libs and headers.
If you intend to make tclspice (see chapt. 20), you will need tcl/tk and blt.
If you want to have high performance and accurate FFT's you should install: fftw-3. The ngspice configure script will find the library and will induce
the build process to link against it.
Download source from Git as described on the sourceforge ngspice Git page. Define and enter a directory of your choice, e.g.
/home/myname/software/. Download the complete ngspice repository from Git, for example by anonymous access issuing the command
The project uses the GNU build process. You should be able to do the following:
$ ./compile_linux.sh
This script will run autogen.sh, create a release directory, run ./configure, clean, make and make install, all with suitable parameters to compile a 64
bit version of ngspice, including the XSPICE code models.
A suitable manual approach for compiling (without release directory) might be:
$ ./autogen.sh
$ make clean
$ make
See the section titled 'Advanced Install' (32.1.8) for instructions about arguments that can be passed to ./configure to customize the build and
installation. The following arguments are already used here and may be called sort of `standard':
--with-readline=yes Include an editor for the input command line (command history, backspace, insert etc.). If readline is not available, editline
may be used.
--enable-openmp Compile ngspice for multi-core processors. Paralleling is done by OpenMP (see Chapt. 16.10), and is enabled for certain MOS
models.
–enable-osdi Enable the OSDI interface for loading Verilog-A compact device models compiled by OpenVAF (see 13.2)
CFLAGS="-m64 -O2" LDFLAGS="-m64 -s" will enable a 64 bit build (-m64) and stress the optmisation (-O2). -s will yield a minimum size executable
(debug information stripped). On most systems --disable-debug will have the same effect. A 32bit build can be made if all 32 bit tools (compiler
etc.) are installed and -m32 is given instead of -m64.
$make clean may sometimes help avoiding mixing up old and newly created object files.
For your convenience a shell script compile_linux.sh is available in ngspice directory. to be started with ./compile_linux.sh 64 for a 64 bit build.
If a problem is found with the build process, please submit a report to the Ngspice development team. Please provide information about your system
and any ./configure arguments you are using, together with any error messages. Ideally you would have tried to fix the problem yourself first. If you
have fixed the problem then the development team will love to hear from you.
If you need updating your local source code tree from Git, just enter ngspice directory and issue the command
git pull
git pull will not overwrite modified files in your working directory. To drop your local changes first, you can run
git reset --hard
To learn more about Git, which can be both powerful and difficult to master, please consult http://git-scm.com/, especially: http://git-
scm.com/documentation, which has links to documentation and tutorials.
Now change directories in to the top-level source directory (where this text from the INSTALL file can be found).
$ make clean
$ make
See the section titled 'Advanced Install' (32.1.8) for instructions about arguments that can be passed to ./configure to customize the build and
installation.
32.1.4 Compilation using an user defined directory tree for object files
The procedures described above will store the *.o files (output of the compilation step) into the directories where the sources (*.c) are located. This
may not be the best option if you want for example to maintain a debug version and in parallel a release version of ngspice (./configure --
disable-debug). So if you intend to create a separate object file tree like ngspice/ngbuild/release, you may do the following, starting from the
default directory ngspice:
mkdir -p release
cd release
make install
This will create an object file directory tree, similar to the source file directory tree, the object files are now separated from the source files. For the
debug version, you may do the same as described above, replacing 'release' by 'debug', and obtain another separated object file directory tree. If you
already have run ./configure in ngspice, you have to do a maintainer-clean, before the above procedure will work. The script ./compile_linux.sh
is made according to the procedure described above.
$ make clean
$ make
you will get the ngspice shared library. A file ngspice.pc for pkg-config is generated.
$make clean may sometimes help avoiding mixing up old and newly created object files. It is required if you make both shared and standard ngspice
from the same setup.
$ ./autogen.sh
$ make clean
$ make
$ ./configure --enable-relpath
It sets relative search paths for the file spinit and the XSPICE code models *.cm. spinit will be look up in ../share/ngspice/scripts. The search
path for the code models (as set by the parameter to the codemodel command in spinit) is set to ../lib/ngspice. The binary is found in ../bin. All
these paths are relative to the current directory. Under MS Windows, this is the directory of ngspice.exe as per default, but may be set to any other
directory with the cd (chapt. 17.5.9) command.
The install path for the ngspice executable is determined by the –-prefix flag of ./configure.
The current directory for the ngspice shared library is determined by the calling program.
32.1.7 Installation on Red Hat or Oracle Linux (and similar, e.g. Centos)
These OSs, widely distributed among commercial users, require some special considerations. There is an extra document, NGSPICE on Red Hat
Like Distributions.pdf, provided by Justin Fisher, available with the ngspice distribution.
$ ./configure --help
Some of these options are generic to the GNU build process that is used by Ngspice, other are specific to Ngspice.
The following sections provide some guidance and descriptions for many, but not all, of these options.
--enable-xspice Enable XSPICE enhancements, yielding a mixed signal simulator integrated into ngspice with codemodel dynamic loading
support. See Chapt. 12 and section II for details.
–enable-osdi Enable the OSDI interface for loading Verilog-A compact device models compiled by OpenVAF (see 13.2)
--with-readline=yes Enable GNU readline support for the command line interface.
--enable-cider Cider is a mixed-level simulator that couples Spice3 and DSIM to simulate devices from their technological parameters. This part of
the simulator is not compiled by default.
--without-x Disable the X-Windows graphical system. Compile without needing X headers and X libraries. The plot command (17.5.53) is now
disabled. You may use Gnuplot (17.5.35) instead.
--with-tcl=tcldir When configured with this option the tcl module `tclspice' is compiled and installed instead of plain ngspice.
--with-ngshared This option will create a shared library (*.so in Linux) or dynamic link library (*.dll) instead of plain ngspice.
--enable-relpath This options introduces a search path for spinit relative to the calling executable (ngspice or the caller using the ngspice shared
library) as ../share/ngspice. In spinit the search path for code models is also set as relative as ../lib. This option may be effective especially when
not using standard installation paths in Linux, but especially for ngspice.dll under MS Windows, if to be installed in other directories than in
C:\Spice64.
--disable-debug This option will remove the '-g' option passed to the compiler. This speeds up execution time, creates a small executable, and is
recommended for normal use. If you want to run ngspice in a debugger (e.g. gdb), you should not select this option.
--enable-oldapps Beginning with ngspice-28, only ngspice executable is made. If you need old apps like ngnutmeg, ngmakeidx, ngmultidec,
ngproc2mod, ngsconvert, use this ./configure flag.
--with-fftw3=no Do not check for and use the fftw fast fourier transform library (www.fftw.org). Use an internal fft algorithm instead. Default is
yes.
--disable-utf8 Switch off UNICODE support, use extended ASCII with Western character support instead.
--disable-sp Switch off RF support: no integrated S-parameter simulation, no RF noise simulation (15.3.8).
--enable-shortcheck Enables a 'make check' with strongly reduced runtime. Besides some regression tests only BSIM3 and BSM4 devices are
checked.
--enable-adms ADMS is a deprecated model compiler that translates Verilog-A compact models into C code that can be compiled into ngspice. This
is no longer supported, and only working with some limitations to the models (e.g. no noise models, bugs). If you want to use it, please refer to the
ADMS section on ngspice web site .
--enable-capbypass Bypass calculation of cbd/cbs in the mosfets if the vbs/vbd voltages are unchanged.
--enable-capzerobypass Bypass all the cbd/cbs calculations if Czero is zero. This is enabled by default since rework-18.
--enable-cluster Clustering code for distributed simulation. This is a contribution never tested. This code comes from TCLspice implementation
and is implemented for transient analysis only.
--enable-expdevices Enable experimental devices. This option is used by developers to mask devices under development. Almost useless for users.
--enable-experimental This may be used to enable some experimental code. The code has to be encapsuated into #ifdef EXPERIMENTAL_CODE ...
#endif constructs. Currently there is no such code available.
--enable-nosqrt Use always log/exp for non-linear capacitances --enable-predictor Enable a predictor method for convergence
--enable-ansi Configure will try to find an option for your compiler so that it expects ansi-C.
CC=c89
CFLAGS=-O2
LIBS=-lposix
./configure
Or on systems that have the env program, you can do it like this:
env CPPFLAGS=-I/usr/local/include
LDFLAGS=-s
./configure
If you have to use a make that does not supports the VPATH variable, you have to compile the package for one architecture at a time in the source
code directory. After you have installed the package for one architecture, use make distclean before reconfiguring for another architecture.
You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you give configure the option –
exec-prefix=PATH, the package will use PATH as the prefix for installing programs and libraries. Documentation and other data files will still use
the regular prefix.
In addition, if you use an unusual directory layout you can give options like –bindir=PATH to specify different values for particular kinds of files.
Run configure –help for a list of the directories you can set and what kinds of files go in them.
If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving configure the option –
program-prefix=PREFIX or –program-suffix=SUFFIX.
When installed on MinGW with MSYS alternative paths are not fully supported. See `How to make ngspice with MINGW and MSYS' (32.2.2) for
details.
For packages that use the X Window System, configure can usually find the X include and library files automatically, but if it doesn't, you can use the
configure options –x-includes=DIR and –x-libraries=DIR to specify their locations.
See the file config.sub for the possible values of each field. If config.sub isn't included in this package, then this package doesn't need to know the
host type.
If you are building compiler tools for cross-compiling, you can also use the –target=TYPE option to select the type of system they will produce code
for and the –build=TYPE option to select the type of system on which you are compiling the package.
--cache-file=FILE Use and save the results of the tests in FILE instead of ./config.cache. Set FILE to /dev/null to disable caching, for debugging
configure.
--quiet --silent -q Do not print messages saying which checks are being made. To suppress all normal output, redirect it to /dev/null (any error
messages will still be shown).
--srcdir=DIR Look for the package's source code in directory DIR. Usually configure can determine that directory automatically.
--version Print the version of Autoconf used to generate the configure script, and exit.
CIDER and XSPICE are included, as well as the code models for XSPICE (*.cm). Verilog-A models compiled with ADMS however are not available.
After compilation the executable, code models and initialization files are available in directory C:\ as C:\Spice, C:\Spice64, C:\Spice64, or
C:\Spice64d, depending on 32 or 64 bit and release or debug. A typical installation tree (64-bit, release) is shown below. A true Windows installer is
however not yet available. The project's 'home' directory for Windows OS (ngspice/visualc) with its files vngspice.sln (solution) and
vngspice.vcxproj (project) allows compiling and linking ngspice with MS Visual Studio.
On Windows 10 with its strict security model, some complications will arise. A normal user is not allowed to create directories in C:\. You will need
admin access rights. So how to cope with this situation? Three different methods are listed below:
Install Microsoft Visual Studio 2022. The MS Visual Studio Community Edition (which is available at no cost from https://www.visualstudio.com/) is
fully adequate. It will generate a 64 bit Release with or without OpenMP support and a Debug version of ngspice, using the x64 flag. In addition you
may select a console version without graphics interface. Making ngspice with 32 bit is still possible, but is not recommended. 32 bit is available with
flag Win32. Standard for everyday use are the ReleaseOMP variants (GUI or console) for 64 bit.
Compilation of the ngspice and XSPICE codes requires the installation of FLEX and BISON. They may be downloaded as Windows executables
from winflexbison. Please unzip the zip file and copy its content into a directory named flex-bison at the same level as the ngspice directory. The
resulting source tree then is:
D:\MySpiceSources\
ngspice\
visualc\
...
flex-bison\
...
Table 32.1: ngspice source tree under MS Windows
Procedure:
Download ngspice. You may obtain a snapshot from ngspice git page at SourceForge, where you will find on top of the page a link named 'Download
Snapshot'. On the left you may select any of the branches which are of interest. Branch 'master' is the most mature code selection, branch 'pre-master'
is an actual development branch. Another approach is to install 'git' from git for Windows and installing ngspice source code with the command
git clone git://git.code.sf.net/p/ngspice/ngspice
as described in chapter 32.1.2.
Go to directory /ngspice/visualc.
Start MS Visual Studio as admin if you need to create C:\Spice etc and open the input file vngspice.sln. Or start MS Visual Studio by double click
on vngspice.sln if C:\Spice etc. already exist or your have selected any other accessible stroage location (see comment from above). After MS
Visual Studio opens, select the debug or release version (with or without OpenMP support) by checking Build, Configuration-Manager, Debug,
Release or ReleaseOMP. Start making ngspice.exe by selecting Build and Build Solution. The executable will be created and stored in
visualc/vngspice/<configuration.platform>. Object files will be stored to visualc/vngspice/<configuration.platform>/obj.
C:\Spice\
bin\
ngspice.exe
vcomp14xx.dll
lib\
ngspice\
analog.cm
digital.cm
spice2poly.cm
extradev.cm
extravt.cm
table.cm
share\
ngspice\
scripts\
spinit
Table 32.2: ngspice Visual Studio installation tree under MS Windows
The exact directory names depend on the configuration and platform you have selected (C:\Spice, C:\Spice64, C:\Spiced, C:\Spice64d). If you
intend to install ngspice into another directory, e.g. D:\MySpice, you may simply copy the contents from C:\Spice to the new location. This becomes
possible because the paths to the code models or spinit are set relative to ngspice.exe. As an alternative, you may edit make-install-vngspice.bat
and alter the following entries from:
set dst=c:\Spice
set dst=c:\Spice64
to
set dst=D:\MySpice
set dst=D:\MySpice64
To use the FFTW-3 library for a 'calibrated' fast Fourier analysis with the fft command (see 17.5.30), download the precompiled MS Windows
FFTW distribution (either 32 bit or 64 bit) from http://www.fftw.org/install/windows.html. Extract at least the files fftw3.h, libfftw3-3.def, and
libfftw3-3.dll to directory ../../fftw-3.3-dll32 (from 32 bit fftw3 for ngspice 32 bit), or to directory ../../fftw-3.3-dll64 (from 64 bit fftw3 for ngspice 64
bit). So both directories are at the same level as the ngspice directory. Then select the MS VC++ project file visualc/vngspice-fftw.vcxproj for
starting VC++, select the appropriate configuration and platform, and off you go. This is how the installed directory tree looks like:
D:\MySpiceSources\
ngspice\
visualc\
...
flex-bison\
...
fftw-3.3-dll32\
...
fftw-3.3-dll64\
...
Table 32.3: ngspice source tree under MS Windows (including fftw)
If you use the debugging features of Visual Studio, ngspice is started with a special spinit file located in visualc\vngspice\share\ngspice\scripts.
Your user-defined start-up commands are best addressed in a .spiceinit file located in C:\users\<username>.
For compiling ngspice as a dll (shared library) there is a dedicated project file coming with the source code to generate ngspice.dll. Go to the
directory visualc and start the project with double clicking on sharedspice.vcxproj.
64-bit ngspice is now the standard, making 32-bit ngspice is still possible if a suitable gcc is installed, but is not tested any more. The procedure of
compiling a distribution (for example, the most recent stable distribution from the ngspice website, e.g. ngspice-39.tar.gz), is as follows:
$ cd ngspice
$ mkdir release
$ cd release
$ make
$ make install
--enable-xspice
--enable-osdi
--enable-openmp
--enable-cider
An option to make is
-j8
If you have a processor with 4 real (or 8 logical) cores, this will speed up compilation considerably.
A complete ngspice (release version, no debug info, 64-bit optimized executable) may be made available just by
$ cd ngspice
$ ./compile_min.sh
$ ./compile_min.sh d
–disable-debug will give O2 optimization (versus O0 for debug) and removes all debugging info.
–adms and –enable-adms ADMS is a deprecated model compiler that translates Verilog-A compact models into C code that can be compiled into
ngspice. This is replaced by OSDI/OpenVAF (see chapter .
The install script will copy all files to C:\Spice or C:\Spice64, the code models for XSPICE will be stored in C:\Spice\lib\spice or
C:\Spice64\lib\spice respectively.
If you don't use the tarball, you may download the ngspice source code from the ngspice Git distribution as described on the sourceforge ngspice Git
page. Define and enter a directory of your choice, e.g. /d/spice/. Download the complete ngspice repository from Git, for example by anonymous
access issuing the command
git clone git://git.code.sf.net/p/ngspice/ngspice
You will find the sources in directory /d/spice/ngspice/. Now enter the ngspice top level directory ngspice. For compilation using
$ ./compile_min.sh
you have to edit this script and uncomment the two lines enabling ./autogen.sh. If you want to compile ngspice manually, follow the procedure
described below:
$ cd ngspice
$ ./autogen.sh
$ mkdir release
$ cd release
$ make -j8
$ make install
The user defined build tree saves the object files, instead of putting them into the source tree, in a release (and a debug) tree. Please see Chapt. 32.1.4
for instructions.
If you need updating your local source code tree from Git, just enter ngspice directory and issue the command
git pull
git pull will not overwrite modified files in your working directory. To drop your local changes first, you can run
git reset --hard
To learn more about Git, which can be both powerful and difficult to master, please consult http://git-scm.com/, especially: http://git-
scm.com/documentation, which has pointers to documentation and tutorials.
The script ./compile_min.sh or the command make install will create a directory tree with 64-bit ngspice as shown below:
C:\Spice64\
bin\
ngspice.exe
cmpp.exe
lib\
ngspice\
analog.cm
digital.cm
spice2poly.cm
extradev.cm
extravt.cm
share\
info\
dir
ngspice.info
ngspice.info-1
..
ngspice.info-10
man\
man1\
ngspice.1
ngspice\
scripts\
ciderinit
devaxis
devload
setplot
spectrum
spinit
Table 32.4: ngspice standard installation tree under MS Windows
The ./configure flag --enable-relpath may be useful if the install path (e.g. C:\Spice64) is only preliminary, because a Windows installer is
preferred. Then all search paths for spinit and code models are made relative to the executable (either ngspice.exe or the caller to ngspice.dll), see
32.1.8.
For compiling ngspice as a dll (shared library) use the configure option --with-ngshared instead of --with-wingui. In addition you might add
(optionally) --enable-relpath to avoid absolute paths when searching for code models. You may edit compile_min.sh accordingly and compile
using this script in the MSYS2 window.
$ ./autogen.sh
$ mkdir release-cyg
$ cd release-cyg
The (optional) statement -j8 (or -jn, n is the number of logical cores available) will speed up compilation considerably.
The CYGWIN console executable you have been creating is an X11 application. This is a not a Windows native environment. So you have to add an
X11 graphics interface by installing the XServer from the CYGWIN project. Before starting ngspice, you have to start the XServer by the following
commands within the CYGWIN window:
$ export DISPLAY=:0.0
If you don't have libdl.a you may need to link libcygwin.a to libdl.a symbolically, for example:
32.3.1 Prerequisites
Ngspice is written in C and thus a complete C/C++ compilation environment is needed. Ngspice is developed with autotools, gcc, and GNU make.
The graphics interface is using X11. Several additional libraries have to be installed. As a first step install the Xquartz system, which enables X11
support. Sevral additional tools and libraries need to by downloaded and installed, either from Brew or MacPorts.
Libraries are: readline, Xft2, Freetype, ncurses, fftw (optional), and several X11 extensions: Xaw, Xmu, Xt, Xext, Xrender, SM, ICE.
The standard gcc provided by Apple Xcode (in fact a link to a clang/llvm compiler) does not (yet?) support OpenMP, so you may use gcc-11 from
Homebrew.
The following table lists the libraries required by ngspice. Libs located in /usr/local/opt/ and the compiler gcc-11 stem from Homebrewrew, the
other libs are from macPorts.
/usr/local/opt/ncurses/lib/libncursesw.6.dylib
/usr/local/opt/gcc/lib/gcc/11/libstdc++.6.dylib
/usr/local/opt/fftw/lib/fftw3.3.dylib
/usr/local/opt/readline/lib/libreadline.8.dylib
/opt/local/lib/libXaw.7.dylib
/opt/local/lib/libXmu.6.dylib
/opt/local/lib/libXt.6.dylib
/opt/local/lib/libXext.6.dylib
/opt/local/lib/libX11.6.dylib
/opt/local/lib/libfontconfig.1.dylib
/opt/local/lib/libXrender.1.dylib
/opt/local/lib/libfreetype.6.dylib
/opt/local/lib/libSM.6.dylib
/opt/local/lib/libICE.6.dylib
/usr/local/opt/gcc/lib/gcc/11/libgomp.1.dylib
/usr/lib/libSystem.B.dylib
/usr/local/lib/gcc/11/libgcc_s.1.dylib
ngspice is also available from MacPorts, Homebrew or Fink, partially as source code, partially as an executable. ngspice from Homebrew for example
currently does not offer the graphics interface to X11 (thus not needing the above mentioned Quartz installation and X11 runtime libraries).
/usr/local/opt/gcc/lib/gcc/11/libstdc++.6.dylib
/usr/local/opt/fftw/lib/libfftw3.3.dylib
/usr/local/opt/gcc/lib/gcc/11/libgomp.1.dylib
/usr/lib/libSystem.B.dylib
/usr/local/lib/gcc/11/libgcc_s.1.dylib
Currently no work has been done to create a package and have the package certified by Apple.
If you happen to experience an error during compilation of ngspice, please send a report to the development team. Ngspice is hosted on SourceForge,
the preferred place to post a bug report is the ngspice bug tracker. We would prefer to have your bug tested against the actual source code available at
Git, but of course a report using the most recent ngspice release is welcome! Please provide the following information with your report: Ngspice
version, Operating system, Small input file to reproduce the bug (if to report a runtime error), Actual output versus the expected output.
ngspice adopts this `Modified' BSD license for all of its source code except for tclspice, admst, and numparam that are under LGPLv2, and XSPICE,
which is in the public domain. Some adms device models have company specific licenses and thus are not part of the standard distribution (see file
COPYING for details) . The ngspice licences are compliant with the DFSG (Debian Free Software Guidelines).
Share — copy and redistribute the material in any medium or format Adapt — remix, transform, and build upon the material for any purpose, even
commercially.
The licensor cannot revoke these freedoms as long as you follow the license terms.
Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable
manner, but not in any way that suggests the licensor endorses you or your use.
ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license
permits.
Notices:
You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable
exception or limitation. No warranties are given. The license may not give you all of the permissions necessary for your intended use. For example,
other rights such as publicity, privacy, or moral rights may limit how you use the material.
Disclaimer:
This deed highlights only some of the key features and terms of the actual license. It is not a license and has no legal value. You should carefully
review all of the terms and conditions of the actual license before using the licensed material.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
(Source)
Copyright © 1992 Georgia Tech Research Corporation All Rights Reserved. This material may be reproduced by or for the U.S. Government pursuant
to the copyright license under the clause at DFARS 252.227-7013 (Oct. 1988)
Refer to U.C. Berkeley and Georgia Tech license agreements for additional information.
Software is distributed as is, completely without warranty or service support. The University of California and its employees are not liable for the
condition or performance of the software.
The University does not warrant that it owns the copyright or other proprietary rights to all software and documentation provided under this
agreement, notwithstanding any copyright notice, and shall not be liable for any infringement of copyright or proprietary rights brought by third
parties against the recipient of the software and documentation provided under this agreement.
THE UNIVERSITY OF CALIFORNIA HEREBY DISCLAIMS ALL IMPLIED WARRANTIES, INCLUDING THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE UNIVERSITY IS NOT LIABLE FOR ANY DAMAGES
INCURRED BY THE RECIPIENT IN USE OF THE SOFTWARE AND DOCUMENTATION, INCLUDING DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES.
The University of California grants the recipient the right to modify, copy, and redistribute the software and documentation, both within the recipient's
organization and externally, subject to the following restrictions:
(a) The recipient agrees not to charge for the University of California code itself. The recipient may, however, charge for additions, extensions, or
support.
(b) In any product based on the software, the recipient agrees to acknowledge the research group that developed the software. This acknowledgment
shall appear in the product documentation.
(c) The recipient agrees to obey all U.S. Government restrictions governing redistribution or export of the software and documentation.
All BSD licenses have been changed to the `modified' BSD license by UCB in 1999 (see Chapt. 33.4.3).
As you know, certain of the Berkeley Software Distribution (`BSD') source code files require that further distributions of products containing all or
portions of the software, acknowledge within their advertising materials that such products contain software developed by UC Berkeley and its
contributors.
`3. All advertising materials mentioning features or use of this software must display the following acknowledgment: This product includes software
developed by the University of California, Berkeley and its contributors.'
Effective immediately, licensees and distributors are no longer required to include the acknowledgment within advertising materials. Accordingly, the
foregoing paragraph of those BSD Unix files containing it is hereby deleted in its entirety.
William Hoskins
33.4.4 XSPICE
According to https://web.archive.org/web/20161030172156/http://users.ece.gatech.edu/~mrichard/Xspice/ (as of Feb. 2012) the XSPICE source code
and documentation have been put into the public domain by the Georgia Institute of Technology.
33.4.5 OSDI
The OSDI interface to OpenVAF-compiled device models is licensed according to the Mozilla Public License, v. 2.0.(see
https://mozilla.org/MPL/2.0/).
According to http://www.gnu.org/licenses/license-list.html, the modified BSD license, thus also the ngspice license, belongs to the family of GPL-
Compatible Free Software Licenses. Therefore the linking restrictions to readline, which have existed with the old BSD license, are no longer in
effect.