Ngspice Users Manual
Version 26plus
(Describes actual ngspice source code at git)

Paolo Nenzi, Holger Vogt

February 7, 2014


2

Locations

The project and download pages of ngspice may be found at

Ngspice home page http://ngspice.sourceforge.net/

Project page at sourceforge http://sourceforge.net/projects/ngspice/

Download page at sourceforge http://sourceforge.net/projects/ngspice/f i les/

Git source download http://sourceforge.net/scm/?type=cvs&group_id=38962

Status

This manual is a work in progress. Some to-dos are listed in the following. More is surely
needed. You are invited to report bugs, missing items, wrongly described items, bad English
style etc.

To Do

1. Review of chapt. 1.3

2. hfet1,2 model descriptions

How to use this manual

The manual is a “work in progress”. It may accompany a specif i c ngspice release, e.g. ngspice-
24 as manual version 24. If its name contains “Version xxplus”, it describes the actual code
status, foundatthedateofissueintheGit SourceCode Management(SCM) tool. Themanual is
intended to provide a complete description of the ngspice functionality, its features, commands,
or procedures. It is not a book about learning spice usage, but the novice user may f i nd some
hints how to start using ngspice. Chapter 21.1 gives a short introduction how to set up and
simulate a small circuit. Chapter 32 is about compiling and installing ngspice from a tarball or
the actual Git source code, which you may f i nd on the ngspice web pages. If you are running a
specif i c LINUX distribution, you may check if it provides ngspice as part of the package. Some
are listed here.


Part I

Ngspice User Manual

3



Contents

INgspice User Manual3

1Introduction33

1.1Simulation Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34

1.1.1Analog Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . .34

1.1.2Digital Simulation. . . . . . . . . . . . . . . . . . . . . . . . . . . .35

1.1.3Mixed-Mode Simulation . . . . . . . . . . . . . . . . . . . . . . . . .35

1.1.4Mixed-Level Simulation . . . . . . . . . . . . . . . . . . . . . . . . .36

1.2Supported Analyses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37

1.2.1DC Analyses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37

1.2.2AC Small-Signal Analysis . . . . . . . . . . . . . . . . . . . . . . . .38

1.2.3Transient Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . .38

1.2.4Pole-Zero Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . .38

1.2.5Small-Signal Distortion Analysis. . . . . . . . . . . . . . . . . . . .39

1.2.6Sensitivity Analysis. . . . . . . . . . . . . . . . . . . . . . . . . . .39

1.2.7Noise Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40

1.2.8Periodic Steady State Analysis. . . . . . . . . . . . . . . . . . . . .40

1.3Analysis at Different Temperatures . . . . . . . . . . . . . . . . . . . . . . . .40

1.4Convergence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42

1.4.1Voltage convergence criterion. . . . . . . . . . . . . . . . . . . . . .42

1.4.2Current convergence criterion. . . . . . . . . . . . . . . . . . . . . .43

1.4.3Convergence failure. . . . . . . . . . . . . . . . . . . . . . . . . . .43

2Circuit Description45

2.1General Structure and Conventions . . . . . . . . . . . . . . . . . . . . . . . .45

2.1.1Input f i le structure. . . . . . . . . . . . . . . . . . . . . . . . . . . .45

2.1.2Circuit elements (device instances). . . . . . . . . . . . . . . . . . .45

2.1.3Some naming conventions . . . . . . . . . . . . . . . . . . . . . . . .47

5


6CONTENTS

2.2Basic lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48

2.2.1.TITLE line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48

2.2.2.END Line. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48

2.2.3Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49

2.2.4End-of-line comments . . . . . . . . . . . . . . . . . . . . . . . . . .49

2.3.MODEL Device Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49

2.4.SUBCKT Subcircuits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50

2.4.1.SUBCKT Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51

2.4.2.ENDS Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52

2.4.3Subcircuit Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52

2.5.GLOBAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52

2.6.INCLUDE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52

2.7.LIB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53

2.8.PARAM Parametric netlists. . . . . . . . . . . . . . . . . . . . . . . . . . .53

2.8.1.param line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53

2.8.2Brace expressions in circuit elements: . . . . . . . . . . . . . . . . . .54

2.8.3Subcircuit parameters . . . . . . . . . . . . . . . . . . . . . . . . . . .54

2.8.4Symbol scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55

2.8.5Syntax of expressions. . . . . . . . . . . . . . . . . . . . . . . . . .55

2.8.6Reserved words. . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

2.8.7Alternative syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . .58

2.9.FUNC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

2.10 .CSPARAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59

2.11 .TEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59

2.12 .IF Condition-Controlled Netlist . . . . . . . . . . . . . . . . . . . . . . . . .60

2.13 Parameters, functions, expressions, and command scripts . . . . . . . . . . . .61

2.13.1 Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61

2.13.2 Nonlinear sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61

2.13.3 Control commands, Command scripts . . . . . . . . . . . . . . . . . .61

3Circuit Elements and Models63

3.1General options and information . . . . . . . . . . . . . . . . . . . . . . . . .63

3.1.1Simulating more devices in parallel. . . . . . . . . . . . . . . . . . .63

3.1.2Technology scaling . . . . . . . . . . . . . . . . . . . . . . . . . . . .64

3.1.3Model binning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64


CONTENTS7

3.1.4Multiplier m, initial conditions . . . . . . . . . . . . . . . . . . . . . .64

3.2Elementary Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65

3.2.1Resistors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65

3.2.2Semiconductor Resistors . . . . . . . . . . . . . . . . . . . . . . . . .66

3.2.3Semiconductor Resistor Model (R). . . . . . . . . . . . . . . . . . .66

3.2.4Resistors, dependent on expressions (behavioral resistor) . . . . . . . .68

3.2.5Capacitors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68

3.2.6Semiconductor Capacitors . . . . . . . . . . . . . . . . . . . . . . . .69

3.2.7Semiconductor Capacitor Model (C) . . . . . . . . . . . . . . . . . . .69

3.2.8Capacitors, dependent on expressions (behavioral capacitor) . . . . . .71

3.2.9Inductors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

3.2.10 Inductor model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

3.2.11 Coupled (Mutual) Inductors . . . . . . . . . . . . . . . . . . . . . . .73

3.2.12 Inductors, dependent on expressions (behavioral inductor) . . . . . . .74

3.2.13 Capacitor or inductor with initial conditions. . . . . . . . . . . . . .75

3.2.14 Switches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76

3.2.15 Switch Model (SW/CSW) . . . . . . . . . . . . . . . . . . . . . . . .77

4Voltage and Current Sources79

4.1Independent Sources for Voltage or Current . . . . . . . . . . . . . . . . . . .79

4.1.1Pulse. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .80

4.1.2Sinusoidal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81

4.1.3Exponential . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81

4.1.4Piece-Wise Linear. . . . . . . . . . . . . . . . . . . . . . . . . . . .82

4.1.5Single-Frequency FM. . . . . . . . . . . . . . . . . . . . . . . . . .82

4.1.6Amplitude modulated source (AM). . . . . . . . . . . . . . . . . . .83

4.1.7Transient noise source . . . . . . . . . . . . . . . . . . . . . . . . . .83

4.1.8Random voltage source . . . . . . . . . . . . . . . . . . . . . . . . . .84

4.1.9External voltage or current input . . . . . . . . . . . . . . . . . . . . .84

4.1.10 Arbitrary Phase Sources . . . . . . . . . . . . . . . . . . . . . . . . .85

4.2Linear Dependent Sources. . . . . . . . . . . . . . . . . . . . . . . . . . . .85

4.2.1Gxxxx: Linear Voltage-Controlled Current Sources (VCCS) . . . . . .85

4.2.2Exxxx: Linear Voltage-Controlled Voltage Sources (VCVS) . . . . . .86

4.2.3Fxxxx: Linear Current-Controlled Current Sources (CCCS). . . . . .86

4.2.4Hxxxx: Linear Current-Controlled Voltage Sources (CCVS) . . . . . .86

4.2.5Polynomial Source Compatibility. . . . . . . . . . . . . . . . . . . .87


8CONTENTS

5Non-linear Dependent Sources (Behavioral Sources)89

5.1Bxxxx: Nonlinear dependent source (ASRC). . . . . . . . . . . . . . . . . .89

5.1.1Syntax and usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89

5.1.2Special B-Source Variables time, temper, hertz . . . . . . . . . . . . .92

5.1.3par(’expression’) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .92

5.1.4Piecewise Linear Function: pwl . . . . . . . . . . . . . . . . . . . . .92

5.2Exxxx: non-linear voltage source* . . . . . . . . . . . . . . . . . . . . . . . .95

5.2.1VOL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

5.2.2VALUE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

5.2.3TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

5.2.4POLY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95

5.2.5LAPLACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96

5.3Gxxxx: non-linear current source* . . . . . . . . . . . . . . . . . . . . . . . .97

5.3.1CUR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97

5.3.2VALUE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97

5.3.3TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97

5.3.4POLY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98

5.3.5LAPLACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98

5.3.6Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98

5.4Debugging a behavioral source . . . . . . . . . . . . . . . . . . . . . . . . . .99

6Transmission Lines101

6.1Lossless Transmission Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

6.2Lossy Transmission Lines. . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

6.2.1Lossy Transmission Line Model (LTRA). . . . . . . . . . . . . . . . 102

6.3Uniform Distributed RC Lines . . . . . . . . . . . . . . . . . . . . . . . . . . 104

6.3.1Uniform Distributed RC Model (URC). . . . . . . . . . . . . . . . . 104

6.4KSPICE Lossy Transmission Lines . . . . . . . . . . . . . . . . . . . . . . . . 105

6.4.1Single Lossy Transmission Line (TXL) . . . . . . . . . . . . . . . . . 105

6.4.2Coupled Multiconductor Line (CPL) . . . . . . . . . . . . . . . . . . . 106

7Diodes107

7.1Junction Diodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

7.2Diode Model (D) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

7.3Diode Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109


CONTENTS9

8BJTs115

8.1Bipolar Junction Transistors (BJTs). . . . . . . . . . . . . . . . . . . . . . . 115

8.2BJT Models (NPN/PNP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

9JFETs121

9.1Junction Field-Effect Transistors (JFETs). . . . . . . . . . . . . . . . . . . . 121

9.2JFET Models (NJF/PJF). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

9.2.1JFET level 1 model with Parker Skellern modif i cation. . . . . . . . . 121

9.2.2JFET level 2 Parker Skellern model . . . . . . . . . . . . . . . . . . . 123

10 MESFETs125

10.1 MESFETs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

10.2 MESFET Models (NMF/PMF) . . . . . . . . . . . . . . . . . . . . . . . . . . 125

10.2.1 Model by Statz e.a. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

10.2.2 Model by Ytterdal e.a. . . . . . . . . . . . . . . . . . . . . . . . . . . 126

10.2.3 hfet1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

10.2.4 hfet2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

11 MOSFETs127

11.1 MOSFET devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

11.2 MOSFET models (NMOS/PMOS) . . . . . . . . . . . . . . . . . . . . . . . . 128

11.2.1 MOS Level 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128

11.2.2 MOS Level 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

11.2.3 MOS Level 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

11.2.4 MOS Level 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

11.2.5 Notes on Level 1-6 models . . . . . . . . . . . . . . . . . . . . . . . . 130

11.2.6 BSIM Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

11.2.7 BSIM1 model (level 4) . . . . . . . . . . . . . . . . . . . . . . . . . . 133

11.2.8 BSIM2 model (level 5) . . . . . . . . . . . . . . . . . . . . . . . . . . 136

11.2.9 BSIM3 model (levels 8, 49). . . . . . . . . . . . . . . . . . . . . . . 136

11.2.10BSIM4 model (levels 14, 54) . . . . . . . . . . . . . . . . . . . . . . . 137

11.2.11EKV model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

11.2.12BSIMSOI models (levels 10, 58, 55, 56, 57) . . . . . . . . . . . . . . . 138

11.2.13SOI3 model (level 60). . . . . . . . . . . . . . . . . . . . . . . . . . 138

11.2.14HiSIM models of the University of Hiroshima . . . . . . . . . . . . . . 138


10CONTENTS

12 Mixed-Mode and Behavioral Modeling with XSPICE139

12.1 Code Model Element & .MODEL Cards. . . . . . . . . . . . . . . . . . . . 139

12.1.1 Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

12.1.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

12.1.3 Search path for f i le input . . . . . . . . . . . . . . . . . . . . . . . . . 143

12.2 Analog Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

12.2.1 Gain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

12.2.2 Summer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

12.2.3 Multiplier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

12.2.4 Divider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

12.2.5 Limiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

12.2.6 Controlled Limiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

12.2.7 PWL Controlled Source. . . . . . . . . . . . . . . . . . . . . . . . . 152

12.2.8 Filesource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

12.2.9 multi_input_pwl block . . . . . . . . . . . . . . . . . . . . . . . . . . 155

12.2.10Analog Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

12.2.11Zener Diode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158

12.2.12Current Limiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

12.2.13Hysteresis Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

12.2.14Differentiator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

12.2.15Integrator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

12.2.16S-Domain Transfer Function . . . . . . . . . . . . . . . . . . . . . . . 166

12.2.17Slew Rate Block. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

12.2.18Inductive Coupling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

12.2.19Magnetic Core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

12.2.20Controlled Sine Wave Oscillator . . . . . . . . . . . . . . . . . . . . . 174

12.2.21Controlled Triangle Wave Oscillator . . . . . . . . . . . . . . . . . . . 175

12.2.22Controlled Square Wave Oscillator . . . . . . . . . . . . . . . . . . . . 177

12.2.23Controlled One-Shot . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

12.2.24Capacitance Meter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180

12.2.25Inductance Meter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

12.2.26Memristor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

12.3 Hybrid Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

12.3.1 Digital-to-Analog Node Bridge. . . . . . . . . . . . . . . . . . . . . 183

12.3.2 Analog-to-Digital Node Bridge. . . . . . . . . . . . . . . . . . . . . 185


CONTENTS11

12.3.3 Controlled Digital Oscillator . . . . . . . . . . . . . . . . . . . . . . . 186

12.3.4 Node bridge from digital to real with enable . . . . . . . . . . . . . . . 187

12.3.5 A Z**-1 block working on real data . . . . . . . . . . . . . . . . . . . 188

12.3.6 A gain block for event-driven real data . . . . . . . . . . . . . . . . . . 188

12.3.7 Node bridge from real to analog voltage . . . . . . . . . . . . . . . . . 189

12.4 Digital Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

12.4.1 Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

12.4.2 Inverter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

12.4.3 And . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

12.4.4 Nand. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

12.4.5 Or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

12.4.6 Nor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

12.4.7 Xor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

12.4.8 Xnor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

12.4.9 Tristate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

12.4.10Pullup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199

12.4.11Pulldown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

12.4.12D Flip Flop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

12.4.13JK Flip Flop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

12.4.14Toggle Flip Flop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

12.4.15Set-Reset Flip Flop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

12.4.16D Latch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

12.4.17Set-Reset Latch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

12.4.18State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

12.4.19Frequency Divider . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

12.4.20RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218

12.4.21Digital Source. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

12.5 Predef i ned Node Types for event driven simulation. . . . . . . . . . . . . . . 222

12.5.1 Digital Node Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . 222

12.5.2 Real Node Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

12.5.3 Int Node Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

12.5.4 (Digital) Input/Output. . . . . . . . . . . . . . . . . . . . . . . . . . 223


12CONTENTS

13 Verilog A Device models225

13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

13.2 adms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

13.3 How to integrate a Verilog-A model into ngspice. . . . . . . . . . . . . . . . 225

13.3.1 How to setup a *.va model for ngspice . . . . . . . . . . . . . . . . . . 225

13.3.2 Adding admsXml to your build environment. . . . . . . . . . . . . . 225

14 Mixed-Level Simulation (ngspice with TCAD)227

14.1 Cider. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

14.2 GSS, Genius . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

15 Analyses and Output Control (batch mode)229

15.1 Simulator Variables (.options). . . . . . . . . . . . . . . . . . . . . . . . . . 229

15.1.1 General Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

15.1.2 DC Solution Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

15.1.3 AC Solution Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 232

15.1.4 Transient Analysis Options . . . . . . . . . . . . . . . . . . . . . . . . 232

15.1.5 ELEMENT Specif i c options . . . . . . . . . . . . . . . . . . . . . . . 233

15.1.6 Transmission Lines Specif i c Options . . . . . . . . . . . . . . . . . . . 234

15.1.7 Precedence of option and .options commands . . . . . . . . . . . . . . 234

15.2 Initial Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

15.2.1 .NODESET: Specify Initial Node Voltage Guesses . . . . . . . . . . . 234

15.2.2 .IC: Set Initial Conditions. . . . . . . . . . . . . . . . . . . . . . . . 235

15.3 Analyses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

15.3.1 .AC: Small-Signal AC Analysis. . . . . . . . . . . . . . . . . . . . . 235

15.3.2 .DC: DC Transfer Function . . . . . . . . . . . . . . . . . . . . . . . . 236

15.3.3 .DISTO: Distortion Analysis . . . . . . . . . . . . . . . . . . . . . . . 237

15.3.4 .NOISE: Noise Analysis . . . . . . . . . . . . . . . . . . . . . . . . . 238

15.3.5 .OP: Operating Point Analysis . . . . . . . . . . . . . . . . . . . . . . 239

15.3.6 .PZ: Pole-Zero Analysis. . . . . . . . . . . . . . . . . . . . . . . . . 239

15.3.7 .SENS: DC or Small-Signal AC Sensitivity Analysis . . . . . . . . . . 240

15.3.8 .TF: Transfer Function Analysis . . . . . . . . . . . . . . . . . . . . . 240

15.3.9 .TRAN: Transient Analysis . . . . . . . . . . . . . . . . . . . . . . . . 241

15.3.10Transient noise analysis (at low frequency). . . . . . . . . . . . . . . 241

15.3.11.PSS: Periodic Steady State Analysis. . . . . . . . . . . . . . . . . . 244

15.4 Measurements after AC, DC and Transient Analysis . . . . . . . . . . . . . . . 245


CONTENTS13

15.4.1 .meas(ure) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

15.4.2 batch versus interactive mode. . . . . . . . . . . . . . . . . . . . . . 246

15.4.3 General remarks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

15.4.4 Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

15.4.5 Trig Targ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

15.4.6 Find ... When . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

15.4.7 AVG|MIN|MAX|PP|RMS|MIN_AT|MAX_AT . . . . . . . . . . . . . . 250

15.4.8 Integ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

15.4.9 param . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

15.4.10par(’expression’) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

15.4.11Deriv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

15.4.12More examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

15.5 Safe Operating Area (SOA) warning messages . . . . . . . . . . . . . . . . . . 252

15.5.1 Resistor and Capacitor SOA model parameters . . . . . . . . . . . . . 253

15.5.2 Diode SOA model parameter . . . . . . . . . . . . . . . . . . . . . . . 253

15.5.3 BJT SOA model parameter . . . . . . . . . . . . . . . . . . . . . . . . 253

15.5.4 MOS SOA model parameter . . . . . . . . . . . . . . . . . . . . . . . 253

15.6 Batch Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

15.6.1 .SAVE: Name vector(s) to be saved in raw f i le . . . . . . . . . . . . . . 254

15.6.2 .PRINT Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

15.6.3 .PLOT Lines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255

15.6.4 .FOUR: Fourier Analysis of Transient Analysis Output . . . . . . . . . 256

15.6.5 .PROBE: Name vector(s) to be saved in raw f i le . . . . . . . . . . . . . 256

15.6.6 par(’expression’): Algebraic expressions for output . . . . . . . . . . . 256

15.6.7 .width . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257

15.7 Measuring current through device terminals . . . . . . . . . . . . . . . . . . . 257

15.7.1 Adding a voltage source in series. . . . . . . . . . . . . . . . . . . . 257

15.7.2 Using option ’savecurrents’. . . . . . . . . . . . . . . . . . . . . . . 258

16 Starting ngspice259

16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

16.2 Where to obtain ngspice. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

16.3 Command line options for starting ngspice and ngnutmeg . . . . . . . . . . . . 260

16.4 Starting options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262

16.4.1 Batch mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262


14CONTENTS

16.4.2 Interactive mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262

16.4.3 Control mode (Interactive mode with control f i le or control section) . . 263

16.5 Standard conf i guration f i le spinit . . . . . . . . . . . . . . . . . . . . . . . . . 264

16.6 User def i ned conf i guration f i le .spiceinit . . . . . . . . . . . . . . . . . . . . . 265

16.7 Environmental variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

16.7.1 Ngspice specif i c variables. . . . . . . . . . . . . . . . . . . . . . . . 265

16.7.2 Common environment variables . . . . . . . . . . . . . . . . . . . . . 266

16.8 Memory usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266

16.9 Simulation time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266

16.10Ngspice on multi-core processors using OpenMP . . . . . . . . . . . . . . . . 267

16.10.1Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

16.10.2Some results. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268

16.10.3Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268

16.10.4Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

16.11Server mode option -s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

16.12Ngspice control via input, output f i fos . . . . . . . . . . . . . . . . . . . . . . 270

16.13Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

16.13.1Compatibility mode. . . . . . . . . . . . . . . . . . . . . . . . . . . 272

16.13.2Missing functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

16.13.3Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273

16.13.4Controls and commands . . . . . . . . . . . . . . . . . . . . . . . . . 273

16.14Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274

16.15Reporting bugs and errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

17 Interactive Interpreter277

17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

17.2 Expressions, Functions, and Constants . . . . . . . . . . . . . . . . . . . . . . 277

17.3 Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282

17.4 Command Interpretation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

17.4.1 On the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

17.4.2 Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

17.4.3 Add-on to circuit f i le . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

17.5 Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284

17.5.1 Ac*: Perform an AC, small-signal frequency response analysis . . . . . 284

17.5.2 Alias: Create an alias for a command. . . . . . . . . . . . . . . . . . 285


CONTENTS15

17.5.3 Alter*: Change a device or model parameter. . . . . . . . . . . . . . 285

17.5.4 Altermod*: Change model parameter(s). . . . . . . . . . . . . . . . 286

17.5.5 Asciiplot: Plot values using old-style character plots. . . . . . . . . . 287

17.5.6 Aspice*: Asynchronous ngspice run . . . . . . . . . . . . . . . . . . . 288

17.5.7 Bug: Mail a bug report . . . . . . . . . . . . . . . . . . . . . . . . . . 288

17.5.8 Cd: Change directory . . . . . . . . . . . . . . . . . . . . . . . . . . . 288

17.5.9 Cdump: Dump the control f l ow to the screen. . . . . . . . . . . . . . 288

17.5.10Circbyline*: Enter a circuit line by line . . . . . . . . . . . . . . . . . 289

17.5.11Codemodel*: Load an XSPICE code model library . . . . . . . . . . . 289

17.5.12Compose: Compose a vector . . . . . . . . . . . . . . . . . . . . . . . 290

17.5.13Dc*: Perform a DC-sweep analysis. . . . . . . . . . . . . . . . . . . 290

17.5.14Def i ne: Def i ne a function . . . . . . . . . . . . . . . . . . . . . . . . . 290

17.5.15Deftype: Def i ne a new type for a vector or plot . . . . . . . . . . . . . 290

17.5.16Delete*: Remove a trace or breakpoint . . . . . . . . . . . . . . . . . . 291

17.5.17Destroy: Delete an output data set . . . . . . . . . . . . . . . . . . . . 291

17.5.18Devhelp: information on available devices . . . . . . . . . . . . . . . . 291

17.5.19Diff: Compare vectors . . . . . . . . . . . . . . . . . . . . . . . . . . 292

17.5.20Display: List known vectors and types . . . . . . . . . . . . . . . . . . 292

17.5.21Echo: Print text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292

17.5.22Edit*: Edit the current circuit. . . . . . . . . . . . . . . . . . . . . . 292

17.5.23Eprint*: Print an event driven node (only used with XSPICE option) . . 293

17.5.24FFT: fast Fourier transform of vectors . . . . . . . . . . . . . . . . . . 293

17.5.25Fourier: Perform a Fourier transform. . . . . . . . . . . . . . . . . . 295

17.5.26Gnuplot: Graphics output via Gnuplot . . . . . . . . . . . . . . . . . . 296

17.5.27Hardcopy: Save a plot to a f i le for printing. . . . . . . . . . . . . . . 296

17.5.28Help: Print summaries of Ngspice commands. . . . . . . . . . . . . 297

17.5.29History: Review previous commands. . . . . . . . . . . . . . . . . . 297

17.5.30Inventory: Print circuit inventory . . . . . . . . . . . . . . . . . . . . . 297

17.5.31Iplot*: Incremental plot. . . . . . . . . . . . . . . . . . . . . . . . . 297

17.5.32Jobs*: List active asynchronous ngspice runs . . . . . . . . . . . . . . 297

17.5.33Let: Assign a value to a vector . . . . . . . . . . . . . . . . . . . . . . 298

17.5.34Linearize*: Interpolate to a linear scale. . . . . . . . . . . . . . . . . 298

17.5.35Listing*: Print a listing of the current circuit. . . . . . . . . . . . . . 298

17.5.36Load: Load rawf i le data. . . . . . . . . . . . . . . . . . . . . . . . . 299

17.5.37Meas*: Measurements on simulation data . . . . . . . . . . . . . . . . 299


16CONTENTS

17.5.38Mdump*: Dump the matrix values to a f i le (or to console) . . . . . . . 299

17.5.39Mrdump*: Dump the matrix right hand side values to a f i le (or to console)300

17.5.40Noise*: Noise analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 300

17.5.41Op*: Perform an operating point analysis . . . . . . . . . . . . . . . . 301

17.5.42Option*: Set a ngspice option. . . . . . . . . . . . . . . . . . . . . . 301

17.5.43Plot: Plot values on the display . . . . . . . . . . . . . . . . . . . . . . 302

17.5.44Pre_<command>: execute commands prior to parsing the circuit . . . . 302

17.5.45Print: Print values. . . . . . . . . . . . . . . . . . . . . . . . . . . . 303

17.5.46Quit: Leave Ngspice or Nutmeg . . . . . . . . . . . . . . . . . . . . . 303

17.5.47Rehash: Reset internal hash tables . . . . . . . . . . . . . . . . . . . . 304

17.5.48Remcirc*: Remove the current circuit . . . . . . . . . . . . . . . . . . 304

17.5.49Reset*: Reset an analysis . . . . . . . . . . . . . . . . . . . . . . . . . 304

17.5.50Reshape: Alter the dimensionality or dimensions of a vector . . . . . . 304

17.5.51Resume*: Continue a simulation after a stop. . . . . . . . . . . . . . 305

17.5.52Rspice*: Remote ngspice submission . . . . . . . . . . . . . . . . . . 305

17.5.53Run*: Run analysis from the input f i le . . . . . . . . . . . . . . . . . . 305

17.5.54Rusage: Resource usage . . . . . . . . . . . . . . . . . . . . . . . . . 306

17.5.55Save*: Save a set of outputs . . . . . . . . . . . . . . . . . . . . . . . 307

17.5.56Sens*: Run a sensitivity analysis . . . . . . . . . . . . . . . . . . . . . 308

17.5.57Set: Set the value of a variable . . . . . . . . . . . . . . . . . . . . . . 308

17.5.58Setcirc*: Change the current circuit . . . . . . . . . . . . . . . . . . . 308

17.5.59Setplot: Switch the current set of vectors. . . . . . . . . . . . . . . . 308

17.5.60Setscale: Set the scale vector for the current plot. . . . . . . . . . . . 309

17.5.61Settype: Set the type of a vector . . . . . . . . . . . . . . . . . . . . . 309

17.5.62Shell: Call the command interpreter . . . . . . . . . . . . . . . . . . . 309

17.5.63Shift: Alter a list variable . . . . . . . . . . . . . . . . . . . . . . . . . 309

17.5.64Show*: List device state . . . . . . . . . . . . . . . . . . . . . . . . . 310

17.5.65Showmod*: List model parameter values . . . . . . . . . . . . . . . . 310

17.5.66Snload*: Load the snapshot f i le. . . . . . . . . . . . . . . . . . . . . 310

17.5.67Snsave*: Save a snapshot f i le. . . . . . . . . . . . . . . . . . . . . . 311

17.5.68Source: Read a ngspice input f i le. . . . . . . . . . . . . . . . . . . . 312

17.5.69Spec: Create a frequency domain plot . . . . . . . . . . . . . . . . . . 313

17.5.70Status*: Display breakpoint information . . . . . . . . . . . . . . . . . 313

17.5.71Step*: Run a f i xed number of time-points . . . . . . . . . . . . . . . . 313

17.5.72Stop*: Set a breakpoint . . . . . . . . . . . . . . . . . . . . . . . . . . 313


CONTENTS17

17.5.73Strcmp: Compare two strings. . . . . . . . . . . . . . . . . . . . . . 314

17.5.74Sysinfo*: Print system information. . . . . . . . . . . . . . . . . . . 314

17.5.75Tf*: Run a Transfer Function analysis . . . . . . . . . . . . . . . . . . 315

17.5.76Trace*: Trace nodes. . . . . . . . . . . . . . . . . . . . . . . . . . . 316

17.5.77Tran*: Perform a transient analysis. . . . . . . . . . . . . . . . . . . 316

17.5.78Transpose: Swap the elements in a multi-dimensional data set . . . . . 316

17.5.79Unalias: Retract an alias . . . . . . . . . . . . . . . . . . . . . . . . . 317

17.5.80Undef i ne: Retract a def i nition. . . . . . . . . . . . . . . . . . . . . . 317

17.5.81Unlet: Delete the specif i ed vector(s) . . . . . . . . . . . . . . . . . . . 317

17.5.82Unset: Clear a variable . . . . . . . . . . . . . . . . . . . . . . . . . . 317

17.5.83Version: Print the version of ngspice . . . . . . . . . . . . . . . . . . . 318

17.5.84Where*: Identify troublesome node or device . . . . . . . . . . . . . . 319

17.5.85Wrdata: Write data to a f i le (simple table) . . . . . . . . . . . . . . . . 319

17.5.86Write: Write data to a f i le (Spice3f5 format) . . . . . . . . . . . . . . . 319

17.5.87Wrs2p: Write scattering parameters to f i le (Touchstone® format). . . 320

17.5.88Xgraph: use the xgraph(1) program for plotting.. . . . . . . . . . . . 320

17.6 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

17.6.1 While - End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

17.6.2 Repeat - End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

17.6.3 Dowhile - End. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

17.6.4 Foreach - End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

17.6.5 If - Then - Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

17.6.6 Label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

17.6.7 Goto. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

17.6.8 Continue. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

17.6.9 Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323

17.7 Internally predef i ned variables . . . . . . . . . . . . . . . . . . . . . . . . . . 323

17.8 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

17.8.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

17.8.2 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

17.8.3 Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329

17.8.4 control structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329

17.8.5 Example script ’spectrum’ . . . . . . . . . . . . . . . . . . . . . . . . 332

17.8.6 Example script for random numbers . . . . . . . . . . . . . . . . . . . 334

17.8.7 Parameter sweep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335


18CONTENTS

17.8.8 Output redirection. . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

17.9 Scattering parameters (s-parameters) . . . . . . . . . . . . . . . . . . . . . . . 336

17.9.1 Intro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336

17.9.2 S-parameter measurement basics . . . . . . . . . . . . . . . . . . . . . 337

17.9.3 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338

17.10MISCELLANEOUS (old stuff, has to be checked for relevance). . . . . . . . 339

17.11Bugs (old stuff, has to be checked for relevance) . . . . . . . . . . . . . . . . . 339

18 Ngspice User Interfaces341

18.1 MS Windows Graphical User Interface . . . . . . . . . . . . . . . . . . . . . . 341

18.2 MS Windows Console. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343

18.3 LINUX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

18.4 CygWin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

18.5 Error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

18.6 Postscript printing options. . . . . . . . . . . . . . . . . . . . . . . . . . . . 345

18.7 Gnuplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

18.8 Integration with CAD software and “third party” GUIs. . . . . . . . . . . . . 346

18.8.1 KJWaves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

18.8.2 GNU Spice GUI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

18.8.3 XCircuit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

18.8.4 GEDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

18.8.5 CppSim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

18.8.6 NGSPICE Online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

18.8.7 Spicy Schematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

18.8.8 MSEspice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

18.8.9 PartSim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

19 ngspice as shared library or dynamic link library349

19.1 Compile options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349

19.1.1 How to get the sources . . . . . . . . . . . . . . . . . . . . . . . . . . 349

19.1.2 LINUX, MINGW, CYGWIN . . . . . . . . . . . . . . . . . . . . . . . 349

19.1.3 MS Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349

19.2 Linking shared ngspice to a calling application. . . . . . . . . . . . . . . . . 350

19.2.1 Linking during creating the caller. . . . . . . . . . . . . . . . . . . . 350

19.2.2 Loading at runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350

19.3 Shared ngspice API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350


CONTENTS19

19.3.1 structs and types def i ned for transporting data . . . . . . . . . . . . . . 350

19.3.2 Exported functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352

19.3.3 Callback functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354

19.4 General remarks on using the API. . . . . . . . . . . . . . . . . . . . . . . . 356

19.4.1 Loading a netlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356

19.4.2 Running the simulation . . . . . . . . . . . . . . . . . . . . . . . . . . 357

19.4.3 Accessing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

19.4.4 Altering model or device parameters . . . . . . . . . . . . . . . . . . . 358

19.4.5 Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

19.4.6 Error handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

19.5 Example applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

19.6 ngspice parallel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

19.6.1 Go parallel! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360

19.6.2 Additional exported functions . . . . . . . . . . . . . . . . . . . . . . 361

19.6.3 Additional callback functions. . . . . . . . . . . . . . . . . . . . . . 362

19.6.4 Parallel ngspice example . . . . . . . . . . . . . . . . . . . . . . . . . 363

20 TCLspice365

20.1 tclspice framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365

20.2 tclspice documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365

20.3 spicetoblt. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365

20.4 Running TCLspice. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366

20.5 examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366

20.5.1 Active capacitor measurement . . . . . . . . . . . . . . . . . . . . . . 366

20.5.2 Optimization of a linearization circuit for a Thermistor . . . . . . . . . 369

20.5.3 Progressive display . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373

20.6 Compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374

20.6.1 LINUX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374

20.6.2 MS Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374

20.7 MS Windows 32 Bit binaries . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

21 Example Circuits377

21.1 AC coupled transistor amplif i er . . . . . . . . . . . . . . . . . . . . . . . . . . 377

21.2 Differential Pair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383

21.3 MOSFET Characterization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383

21.4 RTL Inverter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383

21.5 Four-Bit Binary Adder (Bipolar) . . . . . . . . . . . . . . . . . . . . . . . . . 384

21.6 Four-Bit Binary Adder (MOS) . . . . . . . . . . . . . . . . . . . . . . . . . . 386

21.7 Transmission-Line Inverter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387


20CONTENTS

22 Statistical circuit analysis389

22.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389

22.2 Using random param(eters) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389

22.3 Behavioral sources (B, E, G, R, L, C) with random control. . . . . . . . . . . 391

22.4 ngspice scripting language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392

22.5 Monte-Carlo Simulation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393

22.5.1 Example 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393

22.5.2 Example 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395

22.5.3 Example 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395

22.6 Data evaluation with Gnuplot . . . . . . . . . . . . . . . . . . . . . . . . . . . 395

23 Circuit optimization with ngspice399

23.1 Optimization of a circuit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399

23.2 ngspice optimizer using ngspice scripts. . . . . . . . . . . . . . . . . . . . . 400

23.3 ngspice optimizer using tclspice. . . . . . . . . . . . . . . . . . . . . . . . . 400

23.4 ngspice optimizer using a Python script. . . . . . . . . . . . . . . . . . . . . 400

23.5 ngspice optimizer using ASCO . . . . . . . . . . . . . . . . . . . . . . . . . . 400

23.5.1 Three stage operational amplif i er . . . . . . . . . . . . . . . . . . . . . 401

23.5.2 Digital inverter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402

23.5.3 Bandpass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404

23.5.4 Class-E power amplif i er. . . . . . . . . . . . . . . . . . . . . . . . . 404

24 Notes405

24.1 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405

24.2 Acronyms and Abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . . . 406

IIXSPICE Software User’s Manual409

25 XSPICE Basics411

25.1 ngspice with the XSPICE option . . . . . . . . . . . . . . . . . . . . . . . . . 411

25.2 The XSPICE Code Model Subsystem. . . . . . . . . . . . . . . . . . . . . . 411

25.3 XSPICE Top-Level Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . 412

26 Execution Procedures413

26.1 Simulation and Modeling Overview. . . . . . . . . . . . . . . . . . . . . . . 413

26.1.1 Describing the Circuit. . . . . . . . . . . . . . . . . . . . . . . . . . 413

26.2 Circuit Description Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419

26.2.1 XSPICE Syntax Extensions. . . . . . . . . . . . . . . . . . . . . . . 419

26.3 How to create code models . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421


CONTENTS21

27 Example circuits425

27.1 Amplif i er with XSPICE model “gain” . . . . . . . . . . . . . . . . . . . . . . 425

27.2 XSPICE advanced usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427

27.2.1 Circuit example C3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427

27.2.2 Running example C3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 430

28 Code Models and User-Def i ned Nodes435

28.1 Code Model Data Type Def i nitions . . . . . . . . . . . . . . . . . . . . . . . . 436

28.2 Creating Code Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436

28.3 Creating User-Def i ned Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 437

28.4 Adding a new code model library . . . . . . . . . . . . . . . . . . . . . . . . . 438

28.5 Compiling and loading the new code model (library). . . . . . . . . . . . . . 438

28.6 Interface Specif i cation File . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439

28.6.1 The Name Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441

28.6.2 The Port Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441

28.6.3 The Parameter Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 443

28.6.4 Static Variable Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 444

28.7 Model Def i nition File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446

28.7.1 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446

28.7.2 Function Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455

28.8 User-Def i ned Node Def i nition File . . . . . . . . . . . . . . . . . . . . . . . . 462

28.8.1 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463

28.8.2 Function Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463

28.8.3 Example UDN Def i nition File . . . . . . . . . . . . . . . . . . . . . . 466

29 Error Messages471

29.1 Preprocessor Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 471

29.2 Simulator Error Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . 476

29.3 Code Model Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 477

29.3.1 Code Model aswitch . . . . . . . . . . . . . . . . . . . . . . . . . . . 477

29.3.2 Code Model climit . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478

29.3.3 Code Model core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478

29.3.4 Code Model d_osc . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478

29.3.5 Code Model d_source. . . . . . . . . . . . . . . . . . . . . . . . . . 479

29.3.6 Code Model d_state. . . . . . . . . . . . . . . . . . . . . . . . . . . 479

29.3.7 Code Model oneshot . . . . . . . . . . . . . . . . . . . . . . . . . . . 480


22CONTENTS

29.3.8 Code Model pwl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480

29.3.9 Code Model s_xfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480

29.3.10Code Model sine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481

29.3.11Code Model square. . . . . . . . . . . . . . . . . . . . . . . . . . . 481

29.3.12Code Model triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . 482

IIICIDER483

30 CIDER User’s Manual485

30.1 SPECIFICATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485

30.1.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486

30.2 BOUNDARY, INTERFACE. . . . . . . . . . . . . . . . . . . . . . . . . . . 487

30.2.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487

30.2.2 PARAMETERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488

30.2.3 EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488

30.3 COMMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488

30.3.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

30.3.2 EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

30.4 CONTACT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

30.4.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

30.4.2 PARAMETERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

30.4.3 EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

30.4.4 SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

30.5 DOMAIN, REGION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490

30.5.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490

30.5.2 PARAMETERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490

30.5.3 EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490

30.5.4 SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491

30.6 DOPING. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491

30.6.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491

30.6.2 PARAMETERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494

30.6.3 EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494

30.6.4 SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495

30.7 ELECTRODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495

30.7.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495


CONTENTS23

30.7.2 PARAMETERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496

30.7.3 EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496

30.7.4 SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496

30.8 END. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496

30.8.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497

30.9 MATERIAL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497

30.9.1 DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497

30.9.2 PARAMETERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498

30.9.3 EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498

30.9.4 SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498

30.10METHOD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499

30.10.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499

30.10.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499

30.10.3Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499

30.11Mobility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500

30.11.1Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500

30.11.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501

30.11.3Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501

30.11.4SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501

30.11.5BUGS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502

30.12MODELS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502

30.12.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502

30.12.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502

30.12.3Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502

30.12.4See also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503

30.12.5Bugs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503

30.13OPTIONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503

30.13.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503

30.13.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504

30.13.3Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504

30.13.4See also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504

30.14OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505

30.14.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505

30.14.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506

30.14.3Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506


24CONTENTS

30.14.4SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

30.15TITLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

30.15.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

30.15.2EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

30.15.3BUGS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

30.16X.MESH, Y.MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

30.16.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508

30.16.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

30.16.3EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

30.16.4SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

30.17NUMD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510

30.17.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510

30.17.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511

30.17.3EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511

30.17.4SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512

30.17.5BUGS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512

30.18NBJT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512

30.18.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512

30.18.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513

30.18.3EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513

30.18.4SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514

30.18.5BUGS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514

30.19NUMOS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514

30.19.1DESCRIPTION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514

30.19.2Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515

30.19.3EXAMPLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515

30.19.4SEE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516

30.20Cider examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516

IVAppendices517

31 Model and Device Parameters519

31.1 Accessing internal device parameters . . . . . . . . . . . . . . . . . . . . . . . 519

31.2 Elementary Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521

31.2.1 Resistor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521


CONTENTS25

31.2.2 Capacitor - Fixed capacitor . . . . . . . . . . . . . . . . . . . . . . . . 523

31.2.3 Inductor - Fixed inductor . . . . . . . . . . . . . . . . . . . . . . . . . 524

31.2.4 Mutual - Mutual Inductor . . . . . . . . . . . . . . . . . . . . . . . . . 525

31.3 Voltage and current sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526

31.3.1 ASRC - Arbitrary source . . . . . . . . . . . . . . . . . . . . . . . . . 526

31.3.2 Isource - Independent current source . . . . . . . . . . . . . . . . . . . 527

31.3.3 Vsource - Independent voltage source . . . . . . . . . . . . . . . . . . 528

31.3.4 CCCS - Current controlled current source . . . . . . . . . . . . . . . . 529

31.3.5 CCVS - Current controlled voltage source . . . . . . . . . . . . . . . . 529

31.3.6 VCCS - Voltage controlled current source . . . . . . . . . . . . . . . . 530

31.3.7 VCVS - Voltage controlled voltage source . . . . . . . . . . . . . . . . 530

31.4 Transmission Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531

31.4.1 CplLines - Simple Coupled Multiconductor Lines . . . . . . . . . . . . 531

31.4.2 LTRA - Lossy transmission line . . . . . . . . . . . . . . . . . . . . . 532

31.4.3 Tranline - Lossless transmission line . . . . . . . . . . . . . . . . . . . 533

31.4.4 TransLine - Simple Lossy Transmission Line . . . . . . . . . . . . . . 534

31.4.5 URC - Uniform R. C. line. . . . . . . . . . . . . . . . . . . . . . . . 535

31.5 BJTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536

31.5.1 BJT - Bipolar Junction Transistor. . . . . . . . . . . . . . . . . . . . 536

31.5.2 BJT - Bipolar Junction Transistor Level 2 . . . . . . . . . . . . . . . . 539

31.5.3 VBIC - Vertical Bipolar Inter-Company Model . . . . . . . . . . . . . 542

31.6 MOSFETs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546

31.6.1 MOS1 - Level 1 MOSFET model with Meyer capacitance model . . . . 546

31.6.2 MOS2 - Level 2 MOSFET model with Meyer capacitance model . . . . 549

31.6.3 MOS3 - Level 3 MOSFET model with Meyer capacitance model. . . 553

31.6.4 MOS6 - Level 6 MOSFET model with Meyer capacitance model. . . 557

31.6.5 MOS9 - Modif i ed Level 3 MOSFET model . . . . . . . . . . . . . . . 560

31.6.6 BSIM1 - Berkeley Short Channel IGFET Model. . . . . . . . . . . . 564

31.6.7 BSIM2 - Berkeley Short Channel IGFET Model. . . . . . . . . . . . 567

31.6.8 BSIM3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571

31.6.9 BSIM4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572


26CONTENTS

32 Compilation notes575

32.1 Ngspice Installation under LINUX (and other ’UNIXes’) . . . . . . . . . . . . 575

32.1.1 Prerequisites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575

32.1.2 Install from Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575

32.1.3 Install from a tarball, e.g. ngspice-rework-25.tgz. . . . . . . . . . . . 577

32.1.4 Compilation using an user def i ned directory tree for object f i les. . . . 577

32.1.5 Advanced Install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577

32.1.6 Compilers and Options . . . . . . . . . . . . . . . . . . . . . . . . . . 579

32.1.7 Compiling For Multiple Architectures . . . . . . . . . . . . . . . . . . 580

32.1.8 Installation Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580

32.1.9 Optional Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580

32.1.10Specifying the System Type . . . . . . . . . . . . . . . . . . . . . . . 581

32.1.11Sharing Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581

32.1.12Operation Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581

32.2 Ngspice Compilation under WINDOWS OS. . . . . . . . . . . . . . . . . . 581

32.2.1 How to make ngspice with MINGW and MSYS. . . . . . . . . . . . 581

32.2.2 64 Bit executables with MINGW-w64 . . . . . . . . . . . . . . . . . . 583

32.2.3 make ngspice with MS Visual Studio 2008 or 2010 . . . . . . . . . . . 584

32.2.4 make ngspice with pure CYGWIN . . . . . . . . . . . . . . . . . . . . 586

32.2.5 ngspice mingw or cygwin console executable w/o graphics . . . . . . . 586

32.2.6 make ngspice with CYGWIN and external MINGW32 . . . . . . . . . 587

32.2.7 make ngspice with CYGWIN and internal MINGW32 (use conf i g.h
made above). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587

32.3 Reporting errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588

33 Copyrights and licenses589

33.1 Documentation license . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589

33.1.1 Spice documentation copyright . . . . . . . . . . . . . . . . . . . . . . 589

33.1.2 XSPICE SOFTWARE (documentation) copyright . . . . . . . . . . . . 589

33.1.3 CIDERRESEARCHSOFTWAREAGREEMENT(supersededby33.2.1)590

33.2 ngspice license. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590

33.2.1“Modif i ed” BSD license . . . . . . . . . . . . . . . . . . . . . . . . . 591

33.2.2 XSPICE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592

33.2.3 tclspice, numparam . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592

33.2.4 Linking to GPLd libraries (e.g. readline, fftw):. . . . . . . . . . . . . 592


Prefaces

Preface to the f i rst edition

This manual has been assembled from different sources:

1. The spice3f5 manual,

2. the XSPICE user’s manual,

3. the CIDER user’s manual

and some original material needed to describe the new features and the newly implemented
models. This cut and paste approach, while not being orthodox, allowed ngspice to have a full
manual in a fraction of the time that writing a completely new text would have required. The use
of LaTex and Lyx instead of TeXinfo, which was the original encoding for the manual, further
helped to reduce the writing effort and improved the quality of the result, at the expense of an
on-line version of the manual but, due to the complexity of the software I hardly think that users
will ever want to read an on-line text version.

In writing this text I followed the cut of 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 f i rst 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 dome Emmanuel Rouat and Arno W. Peters for converting to
TEXinfo the original spice3f documentation, their effort gave ngspice users the only available
documentation that described the changes for many years. A good source of ideas for this
manual comes from the on-line spice3f manual written by Charles D.H. Williams (Spice3f5
User Guide), constantly updated and useful for some insight that he gives in it.

As always, errors, omissions and unreadable phrases are only my fault.

Paolo Nenzi

Roma, March 24th 2001

27


28CONTENTS

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 Kings Ale

Preface to the actual edition (as of January 2013)

Due to the wealth of new material and options in ngspice the actual order of chapters has been
revised. Several new chapters have been added. The LYX text processor has allowed adding
internal cross references. The PDF format has become the standard format for distribution of
the manual. Within each new ngspice distribution (starting with ngspice-21) a manual edition
is provided ref l ecting the ngspice status at the time of distribution. At the same time, located
at ngspice manuals, the manual is constantly updated. Every new ngspice feature should enter
this manual as soon as it has been made available in the Git source code.

Holger Vogt

Mülheim, 2013


Acknowledgments

ngspice contributors

Spice was 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.

The following people have contributed in some way:

Vera Albrecht,

Cecil Aswell,

Giles C. Billingsley,

Phil Barker,

Steven Borley,

Stuart Brorson,

Mansun Chan,

Wayne A. Christopher,

Al Davis,

Glao S. Dezai,

Jon Engelbert,

Daniele Foci,

Noah Friedman,

David A. Gates,

Alan Gillespie,

John Heidemann,

Jeffrey M. Hsu,

JianHui Huang,

S. Hwang,

Chris Inbody,

Gordon M. Jacobs,

Min-Chie Jeng,

29


30CONTENTS

Beorn Johnson,

Stefan Jones,

Kenneth H. Keller,

Francesco Lannutti,

Robert Larice,

Mathew Lew,

Robert Lindsell,

Weidong Liu,

Kartikeya Mayaram,

Richard D. McRoberts,

Manfred Metzger,

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,

Steve Tell,

Andrew Tuckey,

Andreas Unger,

Holger Vogt,

Dietmar Warning,

Michael Widlok,


CONTENTS31

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 omis-
sion 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.

XSPICE

The XSPICE simulator is based on the SPICE3 program developed by the Electronics Research
Laboratory, Department of Electrical Engineering and Computer Sciences, University of Cali-
fornia at Berkeley. The authors of XSPICE gratefully acknowledge UC Berkeley’s development
and distribution of this software, and their licensing policies which promote further improve-
ments to simulation technology.

We also gratefully acknowledge the participation and support of our U.S. Air Force spon-
sors, the Aeronautical Systems Center and the Warner Robins Air Logistics Command, without
which the development of XSPICE would not have been possible.


32CONTENTS


Chapter 1

Introduction

Ngspice is a general-purpose circuit simulation program for nonlinear and linear analyses. Cir-
cuits may contain resistors, capacitors, inductors, mutual inductors, independent or dependent
voltageandcurrentsources, loss-lessand lossy transmission lines, switches, uniform distributed
RC lines, and the f i ve most common semiconductor devices: diodes, BJTs, JFETs, MESFETs,
and MOSFETs.

Some introductory remarks on how to use ngspice may be found in chapter 21.

NgspiceisanupdateofSpice3f5, thelastBerkeley’sreleaseofSpice3simulatorfamily. Ngspice
is being developed to include new features to existing Spice3f5 and to f i x 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 f i xing and code refactoring.

Ngspice has built-in models for the semiconductor devices, and the user need specify only the
pertinent model parameter values. There are three models for bipolar junction transistors, all
based on the integral-charge model of Gummel and Poon; however, if the Gummel-Poon param-
eters are not specif i ed, the basic model (BJT) reduces to the simpler Ebers-Moll model. In either
case and in either models, charge storage effects, ohmic resistances, and a current-dependent
output conductance may be included. The second bipolar model BJT2 adds dc current com-
putation in the substrate diode. The third model (VBIC) contains further enhancements for
advanced bipolar devices.

The semiconductor diode model can be used for either junction diodes or Schottky barrier
diodes. There are two models for JFET: the f i rst (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 [1] is an analytical model, while MOS3 [1] is a semi-empirical model; MOS6 [2] is a
simple analytic model accurate in the short channel region; MOS9, is a slightly modif i ed 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] one.
There is partial support for a couple of HFET models and one model for MESA devices.

33


34CHAPTER 1. INTRODUCTION

Ngspice supports mixed-level simulation and provides a direct link between technology param-
eters 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. The mixed-
level extensions to ngspice are two:

• CIDER: a mixed-level circuit and device simulator integrated into ngspice code. CIDER
was originally the name of the mixed-level extension made to spice3f5.

• GSS: GSS (now called GENIUS) TCAD is a 2D simulator developed independently from
ngspice. The device simulator itself is free and not included into ngspice, but a socket
interface is provided.

Ngspice supports mixed-signal simulation through the integration of XSPICE code into it.
XSPICE software, developed as an extension to Spice3C1 from GeorgiaTech, has been ported
to ngspice to provide “board” level and mixed-signal simulation.

New devices can be added to ngspice by two means: the XSPICE code-model interface and the
ADMS interface based on Verilog-A and XML.

Finally, numerous small bugs have been discovered and f i xed, and the program has been ported
to a wider variety of computing platforms.

1.1Simulation Algorithms

Computer-based circuit simulation is often used as a tool by designers, test engineers, and
others who want to analyze the operation of a design without examining the physical circuit.
Simulation allows you to change quickly the parameters of many of the circuit elements to
determine how they affect the circuit response. Often it is diff i cult or impossible to change
these parameters in a physical circuit.

However, to be practical, a simulator must execute in a reasonable amount of time. The key to
eff i cient 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.

1.1.1Analog Simulation

Analog simulation focuses on the linear and non-linear behavior of a circuit over a continuous
time or frequency interval. The circuit response is obtained by iteratively solving Kirchhoff’s
Laws for the circuit at time steps selected to ensure the solution has converged to a stable value
and that numerical approximations of integrations are suff i ciently accurate. Since Kirchhoff’s
laws form a set of simultaneous equations, the simulator operates by solving a matrix of equa-
tions at each time point. This matrix processing generally results in slower simulation times
when compared to digital circuit simulators.


1.1. SIMULATION ALGORITHMS35

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 def i ne 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.

1.1.2Digital Simulation

Digital circuit simulation differs from analog circuit simulation in several respects. A primary
difference is that a solution of Kirchhoff’s laws is not required. Instead, the simulator must only
determine whether a change in the logic state of a node has occurred and propagate this change
to connected elements. Such a change is called an “event”.

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 ref l ected in the
signif i cantly greater speed of digital simulations.

1.1.3Mixed-Mode Simulation

Modern circuits often contain a mix of analog and digital circuits. To simulate such circuits
eff i ciently and accurately a mix of analog and digital simulation techniques is required. When
analog simulation algorithms are combined with digital simulation algorithms, the result is
termed “mixed-mode simulation”.

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 algo-
rithm 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 def i ne 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 modif i cation.

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-def i ned collection
of the most common analog and digital functions, and provide an extensible base on which to
build additional models.


36CHAPTER 1. INTRODUCTION

1.1.3.1User-Def i ned Nodes

Ngspice supports creation of “User-Def i ned Node” types. User-Def i ned Node types allow you
to specify nodes that propagate data other than voltages, currents, and digital states. Like digital
nodes, User-Def i ned Nodes use event-driven simulation, but the state value may be an arbitrary
data type. A simple example application of User-Def i ned Nodes is the simulation of a digital
signal processing f i lter algorithm. In this application, each node could assume a real or integer
value. More complex applications may def i ne types that involve complex data such as digital
data vectors or even non-electronic data.

Ngspice digital simulation is actually implemented as a special case of this User-Def i ned Node
capability where the digital state is def i ned by a data structure that holds a Boolean logic state
and a strength value.

1.1.4Mixed-Level Simulation

Ngspice can simulate numerical device models for diodes and transistors in two different ways,
either through the integrated DSIM simulator or interfacing to GSS TCAD system. DSIM is
an internal C-based device simulator which is part of the CIDER simulator, the mixed-level
simulator based on spice3f5. CIDER within ngspice provides circuit analyses, compact models
for semiconductor devices, and one- or two-dimensional numerical device models.

1.1.4.1CIDER (DSIM)

DSIM provides accurate, one- and two-dimensional numerical device models based on the so-
lution of Poisson’s equation, and the electron and hole current-continuity equations. DSIM
incorporates many of the same basic physical models found in the Stanford two-dimensional
device simulator PISCES. 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. CIDER is based on the mixed-level circuit and device simulator CODECS, and is a
replacement for this program. The basic algorithms of the two programs are the same. Some of
the differences between CIDER and CODECS are described below. The CIDER input format
has greater f l exibility 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 trans-
verse f i eld mobility degradation important in scaled-down MOSFETs and a polysilicon model
for poly-emitter bipolar transistors. Temperature dependence has been included over the range
from -50C to 150C. The numerical models can be used to simulate all the basic types of semi-
conductor 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 ngnutmeg user interface.

1.1.4.2GSS TCAD

GSS is a TCAD software which enables two-dimensional numerical simulation of semiconduc-
tor device with well-known drift-diffusion and hydrodynamic method. GSS has Basic DDM


1.2. SUPPORTED ANALYSES37

(drift-diffusion method) solver, Lattice Temperature Corrected DDM solver, EBM (energy bal-
ance method) solver and Quantum corrected DDM solver which based on density-gradient the-
ory. The GSS program is directed via input statements by a user specif i ed disk f i le. Supports
triangle mesh generation and adaptive mesh ref i nement. Employs PMI (physical model inter-
face) to support various materials, including compound semiconductor materials such as SiGe
and AlGaAs. Supports DC sweep, transient and AC sweep calculations. The device can be
stimulated by voltage or current source(s).

GSS is no longer updated, but is still available as open source as a limited edition of the com-
mercial GENIUS TCAD tool.

1.2Supported Analyses

The ngspice simulator supports the following different types of analysis:

1. DC Analysis (Operating Point and DC Sweep)

2. AC Small-Signal Analysis

3. Transient Analysis

4. Pole-Zero Analysis

5. Small-Signal Distortion Analysis

6. Sensitivity Analysis

7. Noise Analysis

Applications that are exclusively analog can make use of all analysis modes with the exception
of Code Model subsystem that do not implements Pole-Zero, Distortion, Sensitivity and Noise
analyses. Event-driven applications that include digital and User-Def i ned Node types may make
use of DC (operating point and DC sweep) and Transient only.

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.1DC Analyses

Thedcanalysisportionofngspicedeterminesthedcoperatingpointofthecircuitwithinductors
shorted and capacitors opened. The dc analysis options are specif i ed on the .DC, .TF, and .OP
control lines.

There is assumed to be no time dependence on any of the sources within the system description.
The simulator algorithm subdivides the circuit into those portions which require the analog
simulator algorithm and those which 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.


38CHAPTER 1. INTRODUCTION

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-
signalmodelsfornonlineardevices. Ifrequested, thedcsmall-signalvalueofatransferfunction
(ratioofoutputvariabletoinputsource), inputresistance, andoutputresistanceisalsocomputed
as a part of the dc solution. The dc analysis can also be used to generate dc transfer curves: a
specif i ed independent voltage, current source, resistor or temperature1is stepped over a user-
specif i ed range and the dc output variables are stored for each sequential source value.

1.2.2AC Small-Signal Analysis

AC analysis is limited to analog nodes and represents the small signal, sinusoidal solution of the
analog system described at a particular frequency or set of frequencies. This analysis is similar
to the DC analysis in that it represents the steady-state behavior of the described system with a
single input node at a given set of stimulus frequencies.

The program f i rst 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-specif i ed 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.

1.2.3Transient Analysis

Transient analysis is an extension of DC analysis to the time domain. A transient analysis be-
gins by obtaining a DC solution to provide a point of departure for simulating time-varying
behavior. Once the DC solution is obtained, the time-dependent aspects of the system are rein-
troduced, and the two simulator algorithms incrementally solve for the time varying behavior of
the entire system. Inconsistencies in node values are resolved by the two simulation algorithms
such that the time-dependent waveforms created by the analysis are consistent across the entire
simulated time interval. Resulting time-varying descriptions of node behavior for the specif i ed
time interval are accessible to you.

All sources which are not time dependent (for example, power supplies) are set to their dc value.
The transient time interval is specif i ed on a .TRAN control line.

1.2.4Pole-Zero Analysis

The pole-zero analysis portion of Ngspice computes the poles and/or zeros in the small-signal
ac transfer function. The program f i rst computes the dc operating point and then determines
the linearized, small-signal models for all the nonlinear devices in the circuit. This circuit is

1Temperature (TEMP) and resistance sweeps have been introduced in Ngspice, they were not available in the

original code of Spice3f5.


1.2. SUPPORTED ANALYSES39

then used to f i nd the poles and zeros of the transfer function. Two types of transfer functions
are allowed: one of the form (output voltage)/(input voltage) and the other of the form (output
voltage)/(input current). These two types of transfer functions cover all the cases and one can
f i nd the poles/zeros of functions like input/output impedance and voltage gain. The input and
output ports are specif i ed as two pairs of nodes. The pole-zero analysis works with resistors,
capacitors, inductors, linear-controlled sources, independent sources, BJTs, MOSFETs, JFETs
and diodes. Transmission lines are not supported. The method used in the analysis is a sub-
optimal numerical search. For large circuits it may take a considerable time or fail to f i nd all
poles and zeros. For some circuits, the method becomes "lost" and f i nds an excessive number
of poles or zeros.

1.2.5Small-Signal Distortion Analysis

The distortion analysis portion of Ngspice computes steady-state harmonic and intermodulation
products for small input signal magnitudes. If signals of a single frequency are specif i ed as the
input to the circuit, the complex values of the second and third harmonics are determined at
every point in the circuit. If there are signals of two frequencies input to the circuit, the analysis
f i nds out the complex values of the circuit variables at the sum and difference of the input
frequencies, and at the difference of the smaller frequency from the second harmonic of the
larger frequency. Distortion analysis is supported for the following nonlinear devices:

• 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
statement and evaluate the output per scripting.

1.2.6Sensitivity Analysis

Ngspice will calculate either the DC operating-point sensitivity or the AC small-signal sen-
sitivity of an output variable with respect to all circuit variables, including model parameters.
Ngspicecalculatesthedifferenceinanoutputvariable(eitheranodevoltageorabranchcurrent)
by perturbing each parameter of each device independently. Since the method is a numerical
approximation, the results may demonstrate second order affects in highly sensitive parameters,
or may fail to show very low but non-zero sensitivity. Further, since each variable is perturb
by a small fraction of its value, zero-valued parameters are not analyzed (this has the benef i t of
reducing what is usually a very large amount of data).


40CHAPTER 1. INTRODUCTION

1.2.7Noise Analysis

The noise analysis portion of Ngspice does analysis device-generated noise for the given cir-
cuit. When provided with an input source and an output port, the analysis calculates the noise
contributions of each device (and each noise generator within the device) to the output port
voltage. It also calculates the input noise to the circuit, equivalent to the output noise referred
to the specif i ed input source. This is done for every frequency point in a specif i ed range - the
calculated value of the noise corresponds to the spectral density of the circuit variable viewed as
a stationary Gaussian stochastic process. After calculating the spectral densities, noise analysis
integrates these values over the specif i ed frequency range to arrive at the total noise voltage/cur-
rent (over this frequency range). This calculated value corresponds to the variance of the circuit
variable viewed as a stationary Gaussian process.

1.2.8Periodic Steady State Analysis

(Experimental code, not yet made publicly available!)

PSS is a radio frequency periodical large-signal dedicated analysis. The implementation is
based on a time domain shooting like method which make use of Transient analysis. As it is in
early development stage, PSS performs analysis only on autonomous circuits, meaning that it is
only able to predict fundamental frequency and amplitude (and also harmonics) for oscillators,
VCOs, etc.. The algorithm is based on a minimum search of the error vector taken as the
difference of RHS vectors between two occurrences of an estimated period. The convergence
is reached when the mean of error vector decrease below a given threshold that can be set as a
analysisparameter. Resultsofthisanalysis are the basis of every periodical large-signal analysis
as PAC or PNoise.

1.3Analysis at Different Temperatures

Temperature, in ngspice, is a property associated to the entire circuit, rather than an analysis op-
tion. Circuit temperature has a default (nominal) value of 27°C (300.15 K) that can be changed
using the TEMP option in an .option control line (see 15.1.1) or by the .TEMP line (see 2.11),
which has precedence over the .option TEMP line. All analyses are, thus, performed at circuit
temperature, and if you want to simulate circuit behavior at different temperatures you should
prepare a netlist for each temperature.

All input data for ngspice is assumed to have been measured at the circuit nominal tempera-
ture. This value can further be overridden for any device which models temperature effects by
specifying the TNOM parameter on the .model itself. Individual instances may further override
the circuit temperature through the specif i cation 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:


1.3. ANALYSIS AT DIFFERENT TEMPERATURES41

Algorithm 1.1 Instance temperature computation
IF TEMP is specif i ed THEN
instance_temperature = TEMP
ELSE IF
instance_temperature = circuit_temperature + DTEMP
END IF

Temperature dependent support is provided for all devices except voltage and current sources
(either independent and controlled) and BSIM models. BSIM MOSFETs have an alternate tem-
perature dependency scheme which adjusts all of the model parameters before input to ngspice.

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:

IS(T1) = IS(T0)

?T
1
T0

?XTI
exp

?E
gq(T1T0)
k(T1−T0)

?
(1.1)

where k is Boltzmann’s constant, q is the electronic charge, Egis the energy gap which is a
model parameter, and XTI is the saturation current temperature exponent (also a model param-
eter, and usually equal to 3).

The temperature dependence of forward and reverse beta is according to the formula:

B(T1) = B(T0)

?T
1
T0

?XTB
(1.2)

where T0and T1are in degrees Kelvin, and XTB is a user-supplied model parameter. Tempera-
ture effects on beta are carried out by appropriate adjustment to the values of BF, ISE, BR, and
ISC(spice model parameters BF, ISE, BR, and ISC, respectively).

Temperature dependence of the saturation current in the junction diode model is determined by:

IS(T1) = IS(T0)

?T
1
T0

?XTI

N
exp

?

Egq(T1T0)
Nk(T1−T0)

?
(1.3)

where N is the emission coeff i cient, which is a 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, XTI, is usually 2. Temperature appears explicitly in the value of
junction potential, U (in Ngspice PHI), for all the device models.

The temperature dependence is determined by:

U (T) =

kT
q

ln

 
NaNd

Ni(T)2

!

(1.4)

where k is Boltzmann’s constant, q is the electronic charge, Nais the acceptor impurity den-
sity, Ndis the donor impurity density, Niis the intrinsic carrier concentration, and Egis the


42CHAPTER 1. INTRODUCTION

energy gap. Temperature appears explicitly in the value of surface mobility, M0(or U0), for the
MOSFET model.

The temperature dependence is determined by:

M0(T) =

M0(T0)

?
T
T0

?1.5

(1.5)

The effects of temperature on resistors, capacitor and inductors is modeled by the formula:

R(T) = R(T0)

h
1+TC1(T −T0)+TC2(T −T0)2

i
(1.6)

where T is the circuit temperature, T0is the nominal temperature, and TC1and TC2are the f i rst
and second order temperature coeff i cients.

1.4Convergence

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 condi-
tions 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.

1.4.1Voltage convergence criterion

The algorithm has reached convergence if the difference between the last iteration k and the
current one (k+1):

?

?

?v

(k+1)

n

−v(k)

n

?

?

? ≤ RELTOL∗vnmax+VNTOL

(1.7)

where

vnmax= max

??

?

?v

(k+1)

n

?

?

?,

?

?

?v

(k)

n

?

?

?

?
(1.8)

The RELTOL (RELative TOLerance) parameter, which default value is 10−3, specif i es how small
the solution update must be, relative to the node voltage, to consider the solution to have con-
verged. The VNTOL (absolute convergence) parameter, which has 1µV as default becomes im-
portant 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 conver-
gence would never be achieved. VNTOL forces the algorithm to consider as converged any node
whose solution update is lower than its value.


1.4. CONVERGENCE43

1.4.2Current convergence criterion

Ngspicecheckstheconvergenceonthenon-linearfunctionsthatdescribethenon-linearbranches
in circuit elements. In semiconductor devices the functions def i nes currents through the device
and thus the name of the criterion.

Ngspice computes the difference between the value of the nonlinear function computed for last
voltage and the linear approximation of the same current computed with the actual voltage:

?

?

?

?

\

i(k+1)

branch−i

(k)
branch

?

?

?

?

≤ RELTOL∗ibrmax+ABSTOL(1.9)

where

ibrmax= max

?\
i(k+1)

branch,i

(k)
branch

?
(1.10)

In the two expressions above, the\ibranchindicates the linear approximation of the current.

1.4.3Convergence failure

Although the algorithm used in ngspice has been found to be very reliable, in some cases it fails
to converge to a solution. When this failure occurs, the program terminates the job. Failure
to converge in dc analysis is usually due to an error in specifying circuit connections, element
values, or model parameter values. Regenerative switching circuits or circuits with positive
feedback probably will not converge in the dc analysis unless the OFF option is used for some
ofthe devicesinthefeedbackpath, .nodesetcontrolline isusedtoforce thecircuitto converge
to the desired state.


44CHAPTER 1. INTRODUCTION


Chapter 2

Circuit Description

2.1General Structure and Conventions

2.1.1Input f i le structure

The circuit to be analyzed is described to ngspice by a set of element instance lines, which
def i ne the circuit topology and element instance values, and a set of control lines, which def i ne
the model parameters and the run controls. All lines are assembled in an input f i le to be read by
ngspice. Two lines are essential:

• The f i rst line in the input f i le must be the title, which is the only comment line that does
not need any special character in the f i rst place.

• The last line must be .end.

The order of the remaining lines is arbitrary (except, of course, that continuation lines must
immediately follow the line being continued). This feature in the ngspice input language dates
back to the punched card times where elements were written on separate cards (and cards fre-
quently fell off). Leading white spaces in a line are ignored, as well as empty lines.

The lines decribed in sections 2.1 to 2.12 are typically used in the core of the input f i le, outside
of a .control section (see 16.4.3). An exception is the .include includefile line (2.6) which
maybeplacedanywhereintheinputf i le. Thecontentsof includefilewillbeinsertedexactly
in place of the .include line.

2.1.2Circuit elements (device instances)

Each element in the circuit is a device instance specif i ed by an instance line that contains:

• the element instance name,

• the circuit nodes to which the element is connected,

• and the values of the parameters that determine the electrical characteristics of the ele-
ment.

45


46CHAPTER 2. CIRCUIT DESCRIPTION

The f i rst letter of the element instance name specif i es the element type. The format for the
ngspice element types is given in the following manual chapters. In the rest of the manual, the
strings XXXXXXX, YYYYYYY, and ZZZZZZZ denote arbitrary alphanumeric strings.

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 which are
available in ngspice, sorted by the f i rst letter.

First letterElement descriptionComments, links

AXSPICE code model

12
analog (12.2)
digital (12.4)
mixed signal (12.3)
BBehavioral (arbitrary) source5.1
CCapacitor3.2.5
DDiode7

EVoltage-controlled voltage source (VCVS)

linear (4.2.2),
non-linear (5.2)
FCurrent-controlled current source (CCCs)linear (4.2.3)

GVoltage-controlled current source (VCCS)

linear (4.2.1),
non-linear (5.3)
HCurrent-controlled voltage source (CCVS)linear (4.2.4)
ICurrent source4.1
JJunction f i eld effect transistor (JFET)9
KCoupled (Mutual) Inductors3.2.11
LInductor3.2.9

MMetal oxide f i eld effect transistor (MOSFET)

11
BSIM3 (11.2.9)
BSIM4 (11.2.10)
NNumerical device for GSS14.2
OLossy transmission line6.2
PCoupled multiconductor line (CPL)6.4.2
QBipolar junction transistor (BJT)8
RResistor3.2.1
SSwitch (voltage-controlled)3.2.14
TLossless transmission line6.1
UUniformly distributed RC line6.3
VVoltage source4.1
WSwitch (current-controlled)3.2.14
XSubcircuit2.4.3
YSingle lossy transmission line (TXL)6.4.1
ZMetal semiconductor f i eld effect transistor (MESFET)10

Table 2.1: ngspice element types


2.1. GENERAL STRUCTURE AND CONVENTIONS47

2.1.3Some naming conventions

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

Suff i xNameFactor
TTera1012
GGiga109
MegMega106
KKilo103
milMil25.4×10−6
mmilli10−3
umicro10−6
nnano10−9
ppico10−12
ffemto10−15

Table 2.2: Ngspice scale factors

Letters immediately following a number that are not scale factors are ignored, and letters im-
mediately following a scale factor are ignored. Hence, 10, 10V, 10Volts, and 10Hz all represent
the same number, and M, MA, MSec, and MMhos all represent the same scale factor. Note that
1000, 1000.0, 1000Hz, 1e3, 1.0e3, 1kHz, and 1k all represent the same number. Note that M or
m denote ’milli’, i.e. 10−3. Suff i x meg has to be used for 106.

Nodes names may be arbitrary character strings and are case insensitive, if ngspice is used in
batch mode (16.4.1). If in interactive (16.4.2) or control (16.4.3) mode, node names may either
be plain numbers or arbitrary character strings, not starting with a number. The ground node
must be named “0” (zero). For compatibility reason “gnd” is accepted as ground node, and
will internally be treated as a global node and be converted to “0”. Each circuit has to have a
groundnode(gndor0)! Notethedifferenceinngspicewherethenodesaretreatedascharacter
strings and not evaluated as numbers, thus “0” and “00” are distinct nodes in ngspice but not in
SPICE2.

Ngspice requires that the following topological constraints are satisf i ed:

• 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).


48CHAPTER 2. CIRCUIT DESCRIPTION

2.2Basic lines

2.2.1.TITLE line

Examples:

POWER AMPLIFIER CIRCUIT
*

additionallinesfollowing
*. . .

Testof CAM cell
*

additionallinesfollowing
*. . .

The title line must be the f i rst in the input f i le. 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 f i rst line of your input deck will be overridden by the contents of this line following the
.TITLE statement.

.TITLE line example:

******************************
*

additionallinesfollowing
*. . .
. TITLE Testof CAM cell
*

additionallinesfollowing
*. . .

will internally be replaced by

Internal input deck:

Testof CAM cell
*

additionallinesfollowing
*. . .
*TITLE Test

of CAM cell
*

additionallinesfollowing
*. . .

2.2.2.END Line

Examples:

. end

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


2.3. .MODEL DEVICE MODELS49

2.2.3Comments

General Form:

*

<any comment>

Examples:

*

RF=1K Gainshouldbe 100
*

Check open−loopgainandphasemargin

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

2.2.4End-of-line comments

General Form:

<any command> ;<any comment>
<any command> $ <any comment>

Examples:

RF2=1K ; Gainshouldbe 100
C1=10p $ Check open−loopgainandphasemargin
. param n1=1/ / new value

ngspice supports comments that begin with single characters ’;’ or double characters ’$ ’ (dollar
plus space) or ’//’. For readability you should precede each comment character with a space.
ngspice will accept the single character ’$’, but only outside of a .control section.

2.3.MODEL Device Models

General form:

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

Examples:

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

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

For these more complex device types, each device element line contains the device name, the
nodes to which the device is connected, and the device model name. In addition, other optional
parameters may be specif i ed 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 f i fteen types:


50CHAPTER 2. CIRCUIT DESCRIPTION

CodeModel Type
RSemiconductor resistor model
CSemiconductor capacitor model
LInductor model
SWVoltage controlled switch
CSWCurrent controlled switch
URCUniform distributed RC model
LTRALossy transmission line model
DDiode model
NPNNPN BJT model
PNPPNP BJT model
NJFN-channel JFET model
PJFP-channel JFET model
NMOSN-channel MOSFET model
PMOSP-channel MOSFET model
NMFN-channel MESFET model
PMFP-channel MESFET model

Table 2.3: Ngspice model types

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

2.4.SUBCKT Subcircuits

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

The subcircuit is def i ned in the input deck by a grouping of element cards delimited by the
.subckt and the .ends cards (or the keywords def i ned by the substart and subend options
(see 17.7)); the program then automatically inserts the def i ned group of elements wherever the
subcircuit is referenced. Instances of subcircuits within a larger circuit are def i ned through the
use of an instance card which begins with the letter “X”. A complete example of all three of
these cards follows:


2.4. .SUBCKT SUBCIRCUITS51

Example:

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

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

The above specif i es 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 chapter 21.6.

2.4.1.SUBCKT Line

General form:

.SUBCKT subnam N1 <N2 N3 ... >

Examples:

.SUBCKT OPAMP 1 2 3 4

Acircuitdef i nitionisbegunwitha.SUBCKTline. SUBNAMisthesubcircuitname, andN1, N2,
... are the external nodes, which cannot be zero. The group of element lines which immediately
follow the .SUBCKT line def i ne the subcircuit. The last line in a subcircuit def i nition is the
.ENDS line (see below). Control lines may not appear within a subcircuit def i nition; however,
subcircuit def i nitions may contain anything else, including other subcircuit def i nitions, device
models, and subcircuit calls (see below). Note that any device models or subcircuit def i nitions
included as part of a subcircuit def i nition are strictly local (i.e., such models and def i nitions
are not known outside the subcircuit def i nition). Also, any element nodes not included on the
.SUBCKT line are strictly local, with the exception of 0 (ground) which is always global. If you
use parameters, the .SUBCKT line will be extended (see 2.8.3).


52CHAPTER 2. CIRCUIT DESCRIPTION

2.4.2.ENDS Line

General form:

.ENDS <SUBNAM>

Examples:

.ENDS OPAMP

The .ENDS line must be the last one for any subcircuit def i nition. The subcircuit name, if
included, indicates which subcircuit def i nition is being terminated; if omitted, all subcircuits
being def i ned are terminated. The name is needed only when nested subcircuit def i nitions are
being made.

2.4.3Subcircuit Calls

General form:

XYYYYYYY N1 <N2 N3 ... > SUBNAM

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 modif i ed (see 2.8.3).

2.5.GLOBAL

General form:

.GLOBAL nodename

Examples:

.GLOBAL gnd vcc

Nodes def i ned in the .GLOBAL statement are available to all circuit and subcircuit blocks inde-
pendently from any circuit hierarchy. After parsing the circuit, these nodes are accessible from
top level.

2.6.INCLUDE

General form:

.INCLUDE filename

Examples:

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


2.7. .LIB53

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

There is no restriction on the f i le name imposed by ngspice beyond those imposed by the local
operating system.

2.7.LIB

General form:

. LIB filenamelibname

Examples:

. LIB/ users / spice /common/ mosfets . libmos1

The .LIB statement allows to include library descriptions into the input f i le. Inside the *.lib
f i le a library libname will be selected. The statements of each library inside the *.lib f i le are
enclosed in .LIB libname <...> .ENDL statements.

If the compatibility mode (16.13) is set to ’ps’ by set ngbehavior=ps (17.7) in spinit (16.5)
or .spiceinit (16.6), then a simplif i ed syntax .LIB filename is available: a warning is issued
and filename is simply included as described in chapt. 2.6.

2.8.PARAM Parametric netlists

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

2.8.1.param line

General form:

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

Examples:

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

This line assigns numerical values to identif i ers. More than one assignment per line is possible
using a space as separator. Parameter identif i er names must begin with an alphabetic character.
The other characters must be either alphabetic, a number, or ! # $ % [ ] _ as special charac-
ters. The variables time, temper, and hertz (see 5.1.1) are no valid identif i er names. Other
restrictions on naming conventions apply as well, see 2.8.6.


54CHAPTER 2. CIRCUIT DESCRIPTION

The .param lines inside subcircuits are copied per call, like any other line. All assignments are
executed sequentially through the expanded circuit. Before its f i rst use, a parameter name must
have been assigned a value. Expression def i ning a parameter have to be put into braces {p+p2},
alternatively into single quotes ’AGAUSS(pippo, 1, 1.67)’.

2.8.2Brace expressions in circuit elements:

General form:

{ <expr > }

Examples:

These are allowed in .model lines and in device lines. A spice number is a f l oating point
number with an optional scaling suff i x, immediately glued to the numeric tokens (see chapt.
2.8.5). Brace expressions ({..}) cannot be used to parametrize node names or parts of names.
All identif i ers used within an <expr> must have known values at the time when the line is
evaluated, else an error is f l agged.

2.8.3Subcircuit parameters

General form:

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

Examples:

. subcktmyfilterinoutrval =100k cval =100nF

<identn> is the name of the subcircuit given by the user.node is an integer number or an
identif i er, for one of the external nodes. The f i rst <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 identif i er that was def i ned on a .param control line. The <value> parts
are supposed to be default values of the parameters. However, in the current version of , they
are not used and each invocation of the subcircuit must supply the _exact_ number of actual
parameters.

The syntax of a subcircuit call (invocation) is:

General form:

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

Examples:

X1 inputoutputmyfilterrval =1k cval=1n

Here <name> is the symbolic name given to that instance of the subcircuit, <identn> is the
name of a subcircuit def i ned 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> } .
The sequence of <value> items on the X line must exactly match the number and the order of
formal parameters of the subcircuit.


2.8. .PARAM PARAMETRIC NETLISTS55

Subcircuit example with parameters:

*

Param−example
. paramamplitude= 1V
*
. subcktmyfilterinoutrval =100kcval =100nF
Ra inp1{2*rval }
Rb p1 out{2*rval }
C1 p1 0{2*cval }
Ca inp2{ cval }
Cb p2 out{ cval }
R1 p2 0{ rval }
. endsmyfilter
*
X1 inputoutputmyfilterrval =1k cval=1n
V1 input0 AC {amplitude}
. end

2.8.4Symbol scope

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

A word of caution: Ngspice allows to def i ne circuits with nested subcircuits. Currently it is
not possible however to issue .param statements inside of a .subckt ... .ends section, when there
are additional, nested .subckt ... .ends in the same section. This is a bug, which will be removed
asap.

2.8.5Syntax of expressions

<expr> ( optional parts within [ ...] ):

An expression may be one of:

<atom> where <atom> iseitheraspicenumberorani d e n t i f i e r
<unary−operator > <atom>
<function −name> ( <expr > [, <expr >. . . ])
<atom> <binary−operator > <expr >
( <expr > )

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


56CHAPTER 2. CIRCUIT DESCRIPTION

of the C language. For equal precedence binary ops, evaluation goes left to right. Functions
operate on real values only!

OperatorAliasPrecedenceDescription
-1unary -
!1unary not
**^2power, like pwr
*3multiply
/3divide
%3modulo
\3integer divide
+4add
-4subtract
==5equality
!=<>5non-equal
<=5less or equal
>=5greater or equal
<5less than
>5greater than
&&6boolean and
||7boolean or
c?x:y8ternary operator

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 f i le is shown below:

Example input f i le with logical operators:

*

Logicaloperators

v1or1 0{1| |0}
v1and2 0{1 && 0}
v1not3 0{!1}
v1mod4 0{5 % 3}
v1div5 0{5\3}
v0not6 0{!0}

. control
op
printallv
. endc

. end


2.8. .PARAM PARAMETRIC NETLISTS57

Built-in functionNotes
sqr(x)y = x * x
sqrt(x)y = sqrt(x)
sin(x), cos(x), tan(x)
sinh(x), cosh(x), tanh(x)
asin(x), acos(x), atan(x)
asinh(x), acosh(x), atanh(x)
arctan(x)atan(x), kept for compatibility
exp(x)
ln(x), log(x)
abs(x)
nint(x)Nearest integer, half integers towards even
int(x)Nearest integer rounded towards 0
f l oor(x)Nearest integer rounded towards -∞
ceil(x)Nearest integer rounded towards +∞
pow(x,y)x raised to the power of y (pow from C runtime library)
pwr(x,y)pow(fabs(x), y)
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

The scaling suff i xes (any decorative alphanumeric string may follow):

suff i xvalue
g1e9
meg1e6
k1e3
m1e-3
u1e-6
n1e-9
p1e-12
f1e-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.


58CHAPTER 2. CIRCUIT DESCRIPTION

2.8.6Reserved words

In addition to the above function names and to the verbose operators ( not and or div mod ),
other words are reserved and cannot be used as parameter names: and, or, not, div, mod, def i ned,
sqr, sqrt, sin, cos, exp, ln, arctan, abs, pwr, time, temper, hertz.

2.8.7Alternative syntax

The & sign is tolerated to provide some “historical” parameter notation: & as the f i rst character
of a line is equivalent to: .param.

Inside a line, the notation &(....) is equivalent to {....}, and &identifier means the same
thing as {identifier} .

Comments in the style of C++ line trailers (//) are detected and erased.

Warning: this is NOT possible in embedded .control parts of a source f i le, these lines are outside
of this scope.

Now, there is some possible confusion in ngspice because of multiple numerical expression
features. The .param lines and the braces expressions (see next chapter 2.9) 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 correctly be substituted).
So, after the netlist expansion and before the internal data setup, all number attributes in the
circuit are known constants. However, there are some circuit elements in Spice which accept
arithmeticexpressionsthatareNOTevaluatedatthispoint, butonlylaterduringcircuitanalysis.
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 also accepts arithmetic/logic expressions that operate on its own
scalar or vector data sets (17.2). Please see also chapt. 2.13.

It would be desirable to have the same expression syntax, operator and function set, and prece-
dence rules, for the three contexts mentioned above. In the current Numparam implementation,
that goal is not yet achieved...

2.9.FUNC

With this line a function may be def i ned. The syntax of its expression is equivalent to the
expression syntax from the .param line (2.8.5).

General form:

. func <ident > { <expr > }

Examples:

. funcicos (x) {cos (x) − 1}
. funcf (x , y) {x*y}

.func will initiate a replacement operation. After reading the input f i les, and before parameters
are evaluated, all occurrences of the icos(x) function will be replaced by cos(x)-1. All


2.10. .CSPARAM59

occurrences of f(x,y) will be replaced by x*y. Function statements may be nested to a depth
of t.b.d..

2.10.CSPARAM

Create a constant vector (see 17.8.2) from a parameter in plot (17.3) “const”.

General form:

. csparam <ident > = <expr >

Examples:

. parampippo=5
. param pp=6
. csparampippp={pippo + pp}
. param p={pp}
. csparam pap=’pp+p ’

In the example shown, vectors pippp, and pap are added to the constants, which already reside
in plot “const”, with 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.11.TEMP

Sets the circuit temperature in degrees Celsius.

General form:

. tempvalue

Examples:

. temp 27

This card overrides the circuit temperature given in an .option line (15.1.1).


60CHAPTER 2. CIRCUIT DESCRIPTION

2.12.IF Condition-Controlled Netlist

A simple IF-ELSE block allows condition-controlling of the netlist. boolean expression is
any expression according to chapt. 2.8.5 which evaluates parameters and returns a boolean 1
or 0. The netlist block in between the .if ... .endif statements may contain device instances or
.model cards which are selected according to the logic condition.

General form:

. if ( booleanexpression )
. . .
. e l s e i f ( booleanexpression )
. . .
. endif

Example 1:

*

deviceinstanceinIF−ELSE block
. param ok=0 ok2=1

v1 1 0 1
R1 1 0 2

. if(ok && ok2 )
R11 1 0 2
. else
R11 1 0 0.5; <−− selected
. endif

Example 2:

*

. modelinIF−ELSE block
. param m0=0 m1=1

M1 1 2 3 4 N1 W=1 L=0.5

. if (m0==1)
. model N1 NMOS level =49 Version =3.1
. e l s e i f (m1==1)
. model N1 NMOS level =49 Version =3.2.4; <−− selected
. else
. model N1 NMOS level =49 Version =3.3.0
. endif

For now this is a very restricted version of an IF-ELSE block, so several netlist components are
currently not supported within the IF-ELSE block: .SUBCKT, .INC, .LIB, .PARAM. Nesting
of IF-ELSE blocks is not possible. Only one .elseif is allowed per block.


2.13. PARAMETERS, FUNCTIONS, EXPRESSIONS, AND COMMAND SCRIPTS61

2.13Parameters, functions, expressions, andcommandscripts

In ngspice there are several ways to describe functional dependencies. In fact there are three
independent function parsers, being active before, during, and after the simulation. So it might
be due to have a few words on their interdependence.

2.13.1Parameters

Parameters (chapt. 2.8.1) and functions, either def i ned within the .param statement or with
the .func statement (chapt. 2.9) 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 simu-
lation output (voltage or current vectors), because it is simply not yet available. The syntax is
described in chapt. 2.8.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.

2.13.2Nonlinear sources

During the simulation, the B source (chapt. 5) and their associated E and G sources, as well
as some devices (R, C, L) may contain expressions. These expressions may contain parameters
from above (evaluated immediately upon ngspice start up), numerical data, predef i ned func-
tions, but also node voltages and branch currents which are resulting from the simulation. The
source or device values are continuously updated during the simulation. Therefore the sources
are powerful tools to def i ne non-linear behavior, you may even create new ’devices’ by yourself.
Unfortunately the expression syntax (see chapt. 5.1) and the predef i ned functions may deviate
from the ones for parameters listed in 2.8.1.

2.13.3Control commands, Command scripts

Commands, as described in detail in chapt. 17.5, may be used interactively, but also as a com-
mand script enclosed in .control ....endc lines. The scripts may contain expressions
(see chapt. 17.2). The expressions may work upon simulation output vectors (of node volt-
ages, branch currents), as well as upon predef i ned or user def i ned vectors and variables, and are
invoked after the simulation. Parameters from 2.8.1 def i ned by the .param statement are not
allowed in these expressions. However you may def i ne such parameters with .csparam (2.10).
Again the expression syntax (see chapt. 17.2) will deviate from the one for parameters or B
sources listed in 2.8.1 and 5.1.

If you want to use parameters from 2.8.1 inside your control script, you may use .csparam
(2.10) or apply a trick by def i ning 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.13.1) is never possible. Also you
cannot access non-linear sources of the preceding simulation. However you may start a f i rst
simulation inside your control script, then evaluate its output using expressions, change some
oftheelementormodelparameterswiththealterandaltermodstatements(seechapt. 17.5.3)
and then automatically start a new simulation.


62CHAPTER 2. CIRCUIT DESCRIPTION

Expressions and scripting are powerful tools within ngspice, and we will enhance the examples
given in chapt. 21 continuously to describe these features.


Chapter 3

Circuit Elements and Models

Data f i elds that are enclosed in less-than and greater-than signs (’< >’) are optional. All indi-
cated punctuation (parentheses, equal signs, etc.) is optional but indicate the presence of any
delimiter. Further, future implementations may require the punctuation as stated. A consis-
tent style adhering to the punctuation shown here makes the input easier to understand. With
respect to branch voltages and currents, ngspice uniformly uses the associated reference con-
vention (current f l ows in the direction of voltage drop).

3.1General options and information

3.1.1Simulating more devices in parallel

If you need to simulate more devices of the same kind in parallel, you can use the “m” (often
called parallel multiplier) option which is available for all instances except transmission lines
and sources (both independent and controlled). The parallel multiplier is implemented by mul-
tiplying the value of m the element’s matrix stamp, thus it cannot be used to accurately simulate
larger devices in integrated circuits. The netlist below show how to correctly use the parallel
multiplier:

Multiple device example:

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 parallel d01-d10 con-
nected between 1 and 0.

63


64CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

3.1.2Technology scaling

Still to be implemented and written.

3.1.3Model binning

Binning is a kind of range partitioning for geometry dependent models like MOSFET’s. The
purpose is to cover larger geometry ranges (Width and Length) with higher accuracy then the
model built-in geometry formulas. Each size range described by the additional model parame-
ters LMIN, LMAX, WMIN and WMAX has its own model parameter set. These model cards
are def i ned by a number extension, like “nch.1”. NGSPICE has a algorithm to choose the right
model card by the requested W and L.

This is implemented for BSIM3 (11.2.9) and BSIM4 (11.2.10) models.

3.1.4Multiplier m, initial conditions

The area factor “m” (often called parallel multiplier) used on the diode, BJT, JFET, and MES-
FET devices determines the number of equivalent parallel devices of a specif i ed model. The
affected parameters are marked with an asterisk under the heading “area” in the model descrip-
tions (see the various chapters on models below). Several geometric factors associated with the
channel and the drain and source diffusions can be specif i ed on the MOSFET device line.

Two different forms of initial conditions may be specif i ed for some devices. The f i rst form
is included to improve the dc convergence for circuits that contain more than one stable state.
If a device is specif i ed OFF, the dc operating point is determined with the terminal voltages
for that device set to zero. After convergence is obtained, the program continues to iterate to
obtain the exact value for the terminal voltages. If a circuit has more than one dc stable state,
the OFF option can be used to force the solution to correspond to a desired state. If a device
is specif i ed OFF when in reality the device is conducting, the program still obtains the correct
solution (assuming the solutions converge) but more iterations are required since the program
must independently converge to two separate solutions.

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 specif i ed 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.9) for a detailed explanation of
initial conditions.


3.2. ELEMENTARY DEVICES65

3.2Elementary Devices

3.2.1Resistors

General form:

RXXXXXXX n+ n− value <ac=val > <m=val > <scale=val > <temp=val >
+ <dtemp=val > <tc1=val > <tc2=val > <noisy =0|1>

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 semicon-
ductor 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
negative1but not zero.

Simulating small valued resistors: If you need to simulate very small resis-
tors (0.001 Ohm or less), you should use CCVS (transresistance), it is less
eff i cient but improves overall numerical accuracy. Think about that a small
resistance is a large conductance.
Ngspice can assign a resistor instance a different value for AC analysis, specif i ed using the ac
keyword. This value must not be zero as described above. The AC resistance is used in AC
analysis only (not Pole-Zero nor noise). If you do not specify the ac parameter, it is defaulted
to value. If you want to simulate temperature dependence of a resistor, you need to specify its
temperature coeff i cients, using a .model line, like in the example below:

Example:

RE1 1 2 800 newres dtemp=5

.MODEL newres R tc1 =0.001

The temperature coeff i cients tc1 and tc2 describe a quadratic temperature dependence (see
equation17.12) 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.2.3). 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 f l icker.
While thermal noise is always generated in the resistor, to add a f l icker noise2source you have
to add a .model card def i ning the f l icker noise parameters. It is possible to simulate resistors
that do not generate any kind of noise using the noisy keyword and assigning zero to it, as in
the following example:

Example:

Rmd 134 571.5k noisy=0

1A negative resistor modeling an active element can cause convergence problems, please avoid it.

2Flicker noise can be used to model carbon resistors.


66CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

Ngspice calculates the nominal resistance as described below:

Rnom=

VALUE∗scale
m
Racnom=

ac∗scale
m

(3.1)

If you are interested in temperature effects or noise equations, read the next section on semi-
conductor resistors.

3.2.2Semiconductor Resistors

General form:

RXXXXXXX n+ n− <value > <mname> <l=length > <w=width > <temp=val >
+ <dtemp=val > <m=val > <ac=val > <scale=val > <noisy = 0|1 >

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.2.1) and allows the modeling of
temperature effects and for the calculation of the actual resistance value from strictly geometric
information and the specif i cations of the process. If value is specif i ed, it overrides the geo-
metric information and def i nes the resistance. If mname is specif i ed, then the resistance may be
calculated from the process information in the model mname and the given length and width.
If value is not specif i ed, then mname and length must be specif i ed. If width is not specif i ed,
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 specif i cation on the .option control line and the value specif i ed in dtemp.

3.2.3Semiconductor Resistor Model (R)

The resistor model consists of process-related device data that allow the resistance to be calcu-
lated from geometric information and to be corrected for temperature. The parameters available
are:
NameParameterUnitsDefaultExample
TC1f i rst order temperature coeff.

Ω/◦C

0.0-
TC2second order temperature coeff.

Ω/◦C2

0.0-
RSHsheet resistance

Ω/?

-50
DEFWdefault widthm1e-62e-6
NARROWnarrowing due to side etchingm0.01e-7
SHORTshortening due to side etchingm0.01e-7
TNOMparameter measurement temperature

◦C

2750
KFf l icker noise coeff i cient0.01e-25
AFf l icker noise exponent0.01.0
R (RES)default value if element value not givenW-1000

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:


3.2. ELEMENTARY DEVICES67

Rnom= rsh

l−SHORT
w−NARROW

(3.2)

DEFW is used to supply a default value for w if one is not specif i ed for the device. If either rsh
or l is not specif i ed, 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:

R(T) = R(TNOM)

?
1+TC1(T −TNOM)+TC2(T −TNOM)2

?
(3.3)

where R(TNOM) = Rnom|Racnom. In the above formula, “T” represents the instance tempera-
ture, which can be explicitly set using the temp keyword or calculated using the circuit tem-
perature and dtemp, if present. If both temp and dtemp are specif i ed, the latter is ignored.
Ngspice improves spice’s resistors noise model, adding f l icker noise (1/f) to it and the noisy
keyword to simulate noiseless resistors. The thermal noise in resistors is modeled according to
the equation:

¯

i2

R

=

4kT
R

∆f(3.4)

where "k" is the Boltzmann’s constant, and "T" the instance temperature.

Flicker noise model is:

¯

i2

Rfn

=

KFIAF

R
f

∆f(3.5)

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.

MaterialMin.Typ.Max.
Inter-metal (metal1 - metal2)0.0050.0070.1
Top-metal (metal3)0.0030.0040.05
Polysilicon (poly)152030
Silicide236
Diffusion (n+, p+)1025100
Silicided diffusion2410
n-well100020005000


68CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

3.2.4Resistors, dependent on expressions (behavioral resistor)

General form:

RXXXXXXX n+ n− R = ’ expression ’ <tc1=value > <tc2=value >
RXXXXXXX n+ n− ’ expression ’ <tc1=value > <tc2=value >

Examples:

R1 rr0 r = ’V( rr ) < {Vt} ? {R0}:{2*R0}’tc1=2e−03 tc2 =3.3e−06
R2 r2rrr = {5k + 50*TEMPER}

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 chapter
5.1. It may contain parameters (2.8.1) and the special variables time, temper, and hertz (5.1.2).
An example f i le is given below.

Example input f i le for non-linear resistor:

Non−linearr e s i s t o r
. param R0=1k Vi=1 Vt=0.5
*

r e s i s t o rdepending oncontrolvoltage V( rr )
R1 rr0 r = ’V( rr ) < {Vt} ? {R0}:{2*R0}’
*

controlvoltage
V1 rr0 PWL(0 0 100u {Vi})
. control
setnoaskquit
tran100n 100u uic
ploti (V1)
. endc
. end

3.2.5Capacitors

General form:

CXXXXXXX n+ n− <value > <mname> <m=val > <scale=val > <temp=val >
+ <dtemp=val > <tc1=val > <tc2=val > <ic=init_condition >

Examples:

CBYP 13 0 1UF
COSC 17 23 10U IC=3V

Ngspice provides a detailed model for capacitors. Capacitors in the netlist can be specif i ed
giving their capacitance or their geometrical and physical characteristics. Following the original
SPICE3 "convention", capacitors specif i ed by their geometrical or physical characteristics are
called "semiconductor capacitors" and are described in the next section.

In this f i rst form n+ and n- are the positive and negative element nodes, respectively and value
is the capacitance in Farads.

Capacitance can be specif i ed in the instance line as in the examples above or in a .model line,
as in the example below:


3.2. ELEMENTARY DEVICES69

C1 15 5cstd
C2 2 7cstd
. modelcstd C cap=3n

Both capacitors have a capacitance of 3nF.
If you want to simulate temperature dependence of a capacitor, you need to specify its temper-
ature coeff i cients, using a .model line, like in the example below:

CEB 1 2 1u cap1 dtemp=5
.MODEL cap1 C tc1 =0.001

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 specif i ed on the .tran
control line.

Ngspice calculates the nominal capacitance as described below:

Cnom= value∗scale∗m(3.6)

The temperature coeff i cients tc1 and tc2 describe a quadratic temperature dependence (see
equation17.12) 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.2.7).

3.2.6Semiconductor Capacitors

General form:

CXXXXXXX n+ n− <value > <mname> <l=length > <w=width > <m=val >
+ <scale=val > <temp=val > <dtemp=val > <ic=init_condition >

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.2.5), and allows for the
calculation of the actual capacitance value from strictly geometric information and the speci-
f i cations of the process. If value is specif i ed, it def i nes the capacitance and both process and
geometrical information are discarded. If value is not specif i ed, the capacitance is calculated
from information contained model mname and the given length and width (l, w keywords, re-
spectively).

It is possible to specify mname only, without geometrical dimensions and set the capacitance in
the .model line (3.2.5).

3.2.7Semiconductor Capacitor Model (C)

The capacitor model contains process information that may be used to compute the capacitance
from strictly geometric information.


70CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

NameParameterUnitsDefaultExample
CAPmodel capacitanceF0.01e-6
CJjunction bottom capacitance

F/m2

-5e-5
CJSWjunction sidewall capacitance

F/m

-2e-11
DEFWdefault device widthm1e-62e-6
DEFLdefault device lengthm0.01e-6
NARROWnarrowing due to side etchingm0.01e-7
SHORTshortening due to side etchingm0.01e-7
TC1f i rst order temperature coeff.

F/◦C

0.00.001
TC2second order temperature coeff.

F/◦C2

0.00.0001
TNOMparameter measurement temperature

◦C

2750
DIrelative dielectric constant

F/m

-1
THICKinsulator thicknessm0.01e-9

The capacitor has a capacitance computed as:

If value is specif i ed on the instance line then

Cnom= value∗scale∗m(3.7)

If model capacitance is specif i ed then

Cnom= CAP∗scale∗m(3.8)

If neither value nor CAP are specif i ed, then geometrical and physical parameters are take into
account:

C0= CJ(l−SHORT)(w−NARROW)+2CJSW(l−SHORT+w−NARROW)(3.9)

CJ can be explicitly given on the .model line or calculated by physical parameters. When CJ is
not given, is calculated as:

If THICK is not zero:

CJ =

DI∗ε0
THICK

ifDIisspecif i ed,
CJ =

εSiO2
THICK

otherwise.

(3.10)

If the relative dielectric constant is not specif i ed the one for SiO2 is used. The values of the
constants are: ε0= 8.854214871e−12F

m

and εSiO2= 3.4531479969e−11F

m. The nominal

capacitance is then computed as:

Cnom=C0∗scale∗m(3.11)

After the nominal capacitance is calculated, it is adjusted for temperature by the formula:

C(T) =C(TNOM)

?
1+TC1(T −TNOM)+TC2(T −TNOM)2

?
(3.12)


3.2. ELEMENTARY DEVICES71

whereC(TNOM) =Cnom.

In the above formula, “T” represents the instance temperature, which can be explicitly set using
the temp keyword or calculated using the circuit temperature and dtemp, if present.

3.2.8Capacitors, dependent on expressions (behavioral capacitor)

General form:

CXXXXXXX n+ n− C = ’ expression ’ <tc1=value > <tc2=value >
CXXXXXXX n+ n− ’ expression ’ <tc1=value > <tc2=value >

Examples:

C1 cc 0 c = ’V( cc ) < {Vt} ? {C1}:{Ch}’tc1=−1e−03 tc2 =1.3e−05

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 chapter
5.1. It may contain parameters (2.8.1) and the special variables time, temper, and hertz (5.1.2).

Example input f i le:

BehavioralCapacitor
. param Cl=5n Ch=1n Vt=1m Il =100n
. icv( cc ) = 0v( cc2 ) = 0
*

capacitordepending oncontrolvoltage V( cc )
C1 cc 0 c = ’V( cc ) < {Vt} ? {Cl}:{Ch}’
*C1 cc 0 c ={Ch}
I1 0 1 { Il }
Exxxn1−copy n2n2 cc21
Cxxxn1−copy n21
Bxxxcc2 n2I =’(V( cc2 ) < {Vt} ? {Cl}:{Ch}) ’

*

i (Exxx)
I2 n2 22 { Il }
vn2 n2 0 DC 0
*

measurechargebyintegratingcurrent
aint1 %id (1cc ) 2 time_count
aint2 %id (22cc2 ) 3 time_count
. modeltime_countint ( in_offset =0.0gain =1.0
+ out_lower_limit=−1e12out_upper_limit =1e12
+ limit_range =1e−9 out_ic =0.0)
. control
setnoaskquit
tran100n 100u
plotv (2)
plotv( cc ) v( cc2 )
. endc
. end


72CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

3.2.9Inductors

General form:

LYYYYYYY n+ n− <value > <mname> <nt=val > <m=val > <scale=val > <temp=val >
+ <dtemp=val > <tc1=val > <tc2=val > <m=val > <ic=init_condition >

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. Inductance can be specif i ed 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

Both inductors have an inductance of 3nH.

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 coeff i cients, using a .model line, like in the example below:

Lload 1 2 1u ind1dtemp=5
.MODEL ind1 L tc1 =0.001

The (optional) initial condition is the initial (time zero) value of inductor current (in Amps) that
f l ows from n+, through the inductor, to n-. Note that the initial conditions (if any) apply only if
the UIC option is specif i ed on the .tran analysis line.

Ngspice calculates the nominal inductance as described below:

Lnom=

value∗scale
m

(3.13)

3.2.10Inductor model

The inductor model contains physical and geometrical information that may be used to compute
the inductance of some common topologies like solenoids and toroids, wound in air or other
material with constant magnetic permeability.


3.2. ELEMENTARY DEVICES73

NameParameterUnitsDefaultExample
INDmodel inductanceH0.01e-3
CSECTcross sectionm20.01e-3
LENGTHlengthm0.01e-2
TC1f i rst order temperature coeff.

H/◦C

0.00.001
TC2second order temperature coeff.

H/◦C2

0.00.0001
TNOMparameter measurement temperature

◦C

2750
NTnumber of turns-0.010
MUrelative magnetic permeability

H/m

0.0-

The inductor has an inductance computed as:

If value is specif i ed on the instance line then

Lnom=

value∗scale
m

(3.14)

If model inductance is specif i ed then

Lnom=

IND∗scale
m

(3.15)

If neither value nor IND are specif i ed, then geometrical and physical parameters are take into
account. In the following formulas

NT refers to both instance and model parameter (instance parameter overrides model parameter):

If LENGTH is not zero:

(
Lnom=

MU∗µ0∗NT2∗CSECT
LENGTH

ifMUisspecif i ed,

Lnom=

µ0∗NT2∗CSECT
LENGTH

otherwise.

(3.16)

with:µ0= 1.25663706143592e−6H

m. After the nominal inductance is calculated, it is adjusted

for temperature by the formula:

L(T) = L(TNOM)

?
1+TC1(T −TNOM)+TC2(T −TNOM)2

?
(3.17)

where L(TNOM)=Lnom. In the above formula, “T” represents the instance temperature, which
can be explicitly using the temp keyword or calculated using the circuit temperature and dtemp,
if present.

3.2.11Coupled (Mutual) Inductors

General form:

KXXXXXXX LYYYYYYY LZZZZZZZ value

Examples:

K43 LAA LBB 0.999
KXFRMR L1 L2 0.87


74CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

LYYYYYYY and LZZZZZZZ are the names of the two coupled inductors, and value is the
coeff i cient of coupling, K, which must be greater than 0 and less than or equal to 1. Using the
“dot” convention, place a “dot” on the f i rst node of each inductor.

3.2.12Inductors, dependent on expressions (behavioral inductor)

General form:

LXXXXXXX n+ n− L = ’ expression ’ <tc1=value > <tc2=value >
LXXXXXXX n+ n− ’ expression ’ <tc1=value > <tc2=value >

Examples:

L1 l2l l lL = ’ i (Vm) < { It } ? {Ll}:{Lh}’tc1=−4e−03 tc2=6e−05

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 chapter
5.1. It may contain parameters (2.8.1) and the special variables time, temper, and hertz (5.1.2).


3.2. ELEMENTARY DEVICES75

Example input f i le:

Variableinductor
. param Ll =0.5m Lh=5m It =50u Vi=2m
. icv( int21 ) = 0

*

variableinductordepending oncontrolcurrenti (Vm)
L1 l2l l lL = ’ i (Vm) < { It } ? {Ll}:{Lh}’
*

measurecurrentthroughinductor
vml l l0 dc 0
*

voltageoninductor
V1 l2 0 {Vi}

*

fixedinductor
L3 33 331 {Ll}
*

measurecurrentthroughinductor
vm33 331 0 dc 0
*

voltageoninductor
V3 33 0 {Vi}

*

nonlinearinductor( discretesetup )
F21int210 B21 −1
L21int210 1
B21 n1 n2 V =’( i (Vm21) < { It } ? {Ll}:{Lh}) ’

*

v( int21 )
*

measurecurrentthroughinductor
vm21 n2 0 dc 0
V21 n1 0 {Vi}

. control
setnoaskquit
tran1u 100u uic
ploti (Vm)i (vm33)
ploti (vm21)i (vm33)
ploti (vm)−i (vm21)
. endc
. end

3.2.13Capacitor or inductor with initial conditions

The simulator supports the specif i cation of voltage and current initial conditions on capacitor
and inductor models, respectively. These models are not the standard ones supplied with
SPICE3, but are in fact code models which can be substituted for the SPICE models when
realistic initial conditions are required. For details please refer to chapt. 12. A XSPICE deck
example using these models is shown below:

*
* This circuit contains a capacitor and an inductor with
* initial conditions on them. Each of the components


76CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

* has a parallel resistor so that an exponential decay
* of the initial condition occurs with a time constant of
* 1 second.
*
a1 1 0 cap
.model cap capacitor (c=1000uf ic=1)
r1 1 0 1k
*
a2 2 0 ind
.model ind inductor (l=1H ic=1)
r2 2 0 1.0
*
.control
tran 0.01 3
plot v(1) v(2)
.endc
.end

3.2.14Switches

Two types of switches are available: a voltage controlled switch (type SXXXXXX, model SW)
and a current controlled switch (type WXXXXXXX, model CSW). A switching hysteresis may
be def i ned, as well as on- and off-resistances (0 < R < ∞).

General form:

SXXXXXXX N+ N− NC+ NC− MODEL <ON><OFF>
WYYYYYYY N+ N− VNAM MODEL <ON><OFF>

Examples:

s1 1 2 3 4 switch1 ON
s2 5 6 3 0 sm2 off
Switch1 1 2 10 0 smodel1
w1 1 2 vclockswitchmod1
W2 3 0 vramp sm1 ON
wreset 5 6 vclcklossyswitch 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 specif i ed voltage source. The
direction of positive controlling current f l ow 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.


3.2. ELEMENTARY DEVICES77

3.2.15Switch Model (SW/CSW)

The switch model allows an almost ideal switch to be described in ngspice. The switch is not
quite ideal, in that the resistance can not change from 0 to inf i nity, but must always have a f i nite
positive value. By proper selection of the on and off resistances, they can be effectively zero
and inf i nity in comparison to other circuit elements. The parameters available are:

NameParameterUnitsDefaultSwitch model
VTthreshold voltageV0.0SW
ITthreshold currentA0.0CSW
VHhysteresis voltageV0.0SW
IHhysteresis currentA0.0CSW
RONon resistanceΩ1.0SW,CSW
ROFFoff resistanceΩ1.0e+12 (*)SW,CSW

(*) Or 1/GMIN, if you have set GMIN to any other value, see the .OPTIONS control line
(15.1.2) for a description of GMIN, 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 discontinu-
ities 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 diff i culties. The user of switches can improve the situation by taking the following
steps:

• First, it is wise to set ideal switch impedances 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 real-
istic 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 de-
creased 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 re-
duced. 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.


78CHAPTER 3. CIRCUIT ELEMENTS AND MODELS

Example input f i le:

Switcht e s t
. tran2us 5ms
*switch

controlvoltage
v1 1 0 DC 0.0 PWL(0 0 2e−3 2 4e−3 0)
*switch

controlvoltagest a r t i n ginsidehysteresiswindow
*please

noteinfluenceofinstanceparameters ON, OFF
v2 2 0 DC 0.0 PWL(00.9 2e−3 2 4e−3 0.4)
*switch

controlcurrent
i3 3 0 DC 0.0 PWL(0 0 2e−3 2m 4e−3 0) $ <−−− switchcontrolcurrent
*load

voltage
v4 4 0 DC 2.0
*input

loadforcurrentsourcei3
r3 3 33 10k
vm3 33 0 dc 0 $ <−−− measurethecurrent
*

ouputloadr e s i s t o r s
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
. modelswitch1 sw vt=1 vh=0.2ron=1roff =10k
*
w1 40 0 vm3 wswitch1off
. model wswitch1 cswi t =1m ih =0.2m ron=1roff =10k
*
. control
run
plotv (1)v(10)
plotv(10)vs v (1)$ <−− gethysteresisloop
plotv (2)v(20) $ <−−− differenti n i t i a lvalues
plotv(20)vs v (2)$ <−− gethysteresisloop
plotv (2)v(30) $ <−−− differenti n i t i a lvalues
plotv(30)vs v (2)$ <−− gethysteresisloop
plotv(40)vs vm3#branch $ <−−− currentcontrolledswitchhysteresis
. endc
. end


Chapter 4

Voltage and Current Sources

4.1Independent Sources for Voltage or Current

General form:

VXXXXXXX N+ N− <<DC> DC/TRAN VALUE> <AC <ACMAG <ACPHASE>>>
+ <DISTOF1 <F1MAG <F1PHASE>>> <DISTOF2 <F2MAG <F2PHASE>>>
IYYYYYYY N+ N− <<DC> DC/TRAN VALUE> <AC <ACMAG <ACPHASE>>>
+ <DISTOF1 <F1MAG <F1PHASE>>> <DISTOF2 <F2MAG <F2PHASE>>>

Examples:

VCC 10 0 DC 6
VIN 13 2 0.001 AC 1 SIN(0 1 1MEG)
ISRC 23 21 AC 0.33345.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 f l ow from the positive node, through the source, to
the negative node. A current source of positive value forces current to f l ow 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.

ACMAG is the ac magnitude and ACPHASE is the ac phase. The source is set to this value in the
ac analysis. If ACMAG is omitted following the keyword AC, a value of unity is assumed. 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 omitted.

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).

79


80CHAPTER 4. VOLTAGE AND CURRENT SOURCES

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

• and external data (only with ngspice shared library).

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 f i nal time (see the .TRAN control
line for explanation)).

4.1.1Pulse

General form:

PULSE(V1 V2 TD TR TF PW PER)

Examples:

VIN 3 0 PULSE(−1 1 2NS 2NS 2NS 50NS 100NS)

NameParameterDefault ValueUnits
V1Initial value-V, A
V2Pulsed value-V, A
TDDelay time0.0sec
TRRise timeTSTEPsec
TFFall timeTSTEPsec
PWPulse widthTSTOPsec
PERPeriodTSTOPsec

A single pulse so specif i ed is described by the following table:


4.1. INDEPENDENT SOURCES FOR VOLTAGE OR CURRENT81

TimeValue
0V1
TDV1
TD+TRV2
TD+TR+PWV2
TD+TR+PW+TFV1
TSTOPV1

Intermediate points are determined by linear interpolation.

4.1.2Sinusoidal

General form:

SIN(VO VA FREQ TD THETA)

Examples:

VIN 3 0 SIN(0 1 100MEG 1NS 1E10)

NameParameterDefault ValueUnits
VOOffset-V, A
VAAmplitude-V, A
FREQFrequency

1/TSTOP

Hz
TDDelay0.0sec
THETADamping factor0.0

1/sec

The shape of the waveform is described by the following formula:

V (t) =

(
V0if 0 ≤ t < TD
V0+VAe−(t−TD)THETAsin(2πFREQ(t −TD))if TD ≤t < TSTOP

(4.1)

4.1.3Exponential

General Form:

EXP(V1 V2 TD1 TAU1 TD2 TAU2)

Examples:

VIN 3 0 EXP(−4 −1 2NS 30NS 60NS 40NS)

NameParameterDefault ValueUnits
V1Initial value-V, A
V2pulsed value-V, A
TD1rise delay time0.0sec
TAU1rise time constantTSTEPsec
TD2fall delay timeTD1+TSTEPsec
TAU2fall time constantTSTEPsec

The shape of the waveform is described by the following formula:


82CHAPTER 4. VOLTAGE AND CURRENT SOURCES

LetV21 =V2−V1V12 =V1−V2:

V (t) =















V1if 0 ≤t < TD1,

V1+V21

?
1−e−

(t−TD1)
TAU1

?
if TD1 ≤t < TD2,

V1+V21

?
1−e−

(t−TD1)
TAU1

?
+V12

?
1−e−

(t−TD2)
TAU2

?
if TD2 ≤t < TSTOP.

(4.2)

4.1.4Piece-Wise Linear

General Form:

PWL(T1 V1 <T2 V2 T3 V3 T4 V4 ... >)<r=value > <td=value >

Examples:

VCLOCK 7 5 PWL(0 −7 10NS −7 11NS −3 17NS −3 18NS −7 50NS −7) r=0 td =15NS

Each pair of values (Ti, Vi) specif i es that the value of the source is Vi(in Volts or Amps) at
time = Ti. The value of the source at intermediate values of time is determined by using linear
interpolation on the input values. The parameter r determines a repeat time point. If r is not
given, the whole sequence of values (Ti, Vi) is issued once, then the output stays at its f i nal
value. If r = 0, the whole sequence from time = 0 to time = Tn is 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 a
delay time time = td. The current source still needs to be patched, td and r are not yet available.

4.1.5Single-Frequency FM

General Form:

SFFM(VO VA FC MDI FS)

Examples:

V1 12 0 SFFM(0 1M 20K 5 1K)

NameParameterDefault valueUnits
VOOffset-V, A
VAAmplitude-V, A
FCCarrier frequency

1/TSTOP

Hz
MDIModulation index-
FSSignal frequency

1/TSTOP

Hz

The shape of the waveform is described by the following equation:

V(t) =VO+VAsin(2πFCt +MDIsin(2πFSt))(4.3)


4.1. INDEPENDENT SOURCES FOR VOLTAGE OR CURRENT83

4.1.6Amplitude modulated source (AM)

General Form:

AM(VA VO MF FC TD)

Examples:

V1 12 0 AM(0.51 20K 5MEG 1m)

NameParameterDefault valueUnits
VAAmplitude-V, A
VOOffset-V, A
MFModulating frequency-Hz
FCCarrier frequency

1/TSTOP

Hz
TDSignal delay-s

The shape of the waveform is described by the following equation:

V(t) =VA∗(VO+sin(2πMFt))∗sin(2πFCt)(4.4)

4.1.7Transient noise source

General Form:

TRNOISE(NA NT NALPHA NAMP RTSAM RTSCAPT RTSEMT)

Examples:

VNoiw 1 0 DC 0 TRNOISE(20n 0.5n 0 0)$ white
VNoi1of 1 0 DC 0 TRNOISE(0 10p 1.112p)$ 1/ f
VNoiw1of 1 0 DC 0 TRNOISE(20 10p 1.112p) $ whiteand1/ f
IALL 10 0 DC 0trnoise (1m 1u 1.00.1m 15m 22u 50u) $ white ,1/ f , RTS

Transientnoiseisanexperimentalfeature allowing (lowfrequency) transientnoise injectionand
analysis. See chapter 15.3.10 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.

NameParameterDefault valueUnits
NARms noise amplitude (Gaussian)-V, A
NTTime step-sec
NALPHA1/f exponent0 < α < 2-
NAMPAmplitude (1/f)-V, A
RTSAMAmplitude-V, A
RTSCAPTTrap capture time-sec
RTSEMTTrap emission time-sec


84CHAPTER 4. VOLTAGE AND CURRENT SOURCES

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

alter @vnoi[trnoise] = [ 0 0 0 0 ] $ no noise

alter @vrts[trnoise] = [ 0 0 0 0 0 0 0] $ no noise

See chapt. 17.5.3 for the alter command.

You may switch off all TRNOISE noise sources by setting

set notrnoise

to your .spiceinit f i le (for all your simulations) or into your control section in front of the next
run or tran command (for this specif i c and all following simulations). The command

unset notrnoise

will reinstate all noise sources.

The noise generators are implemented into the independent voltage (vsrc) and current (isrc)
sources.

4.1.8Random voltage source

TheTRRANDOMoptionyieldsstatisticallydistributedvoltagevalues, derivedfromthengspice
random number generator. These values may be used in the transient simulation directly within
a circuit, e.g. for generating a specif i c noise voltage, but especially they may be used in the con-
trolofbehavioralsources(B,E,Gsources5, voltagecontrollableAsources12, capacitors3.2.8,
inductors 3.2.12, or resistors 3.2.4) to simulate the circuit dependence on statistically varying
device parameters. A Monte-Carlo simulation may thus be handled in a single simulation run.

General Form:

TRRANDOM(TYPE TS <TD <PARAM1 <PARAM2>>>)

Examples:

VR1 r10 dc 0 trrandom(2 10m 0 1) $ Gaussian

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.

TYPEdescriptionPARAM1defaultPARAM2default
1UniformRange1Offset0
2GaussianStandard Dev.1Mean0
3ExponentialMean1Offset0
4PoissonLambda1Offset0

4.1.9External voltage or current input

General Form:

EXTERNAL


4.2. LINEAR DEPENDENT SOURCES85

Examples:

Vex 10 dc 0external
Iexi1i2dc 0external <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.10Arbitrary Phase Sources

The XSPICE option supports arbitrary phase independent sources that output at TIME=0.0 a
value corresponding to some specif i ed phase shift. Other versions of SPICE use the TD (delay
time) parameter to set phase-shifted sources to their time-zero value until the delay time has
elapsed. The XSPICE phase parameter is specif i ed in degrees and is included after the SPICE3
parameters normally used to specify an independent source. Partial XSPICE deck examples of
usage for pulse and sine waveforms are shown below:

* Phase shift is specified after Berkeley defined parameters
* on the independent source cards. Phase shift for both of the
* following is specified as +45 degrees
*
v1 1 0 0.0 sin(0 1 1k 0 0 45.0)
r1 1 0 1k
*
v2 2 0 0.0 pulse(-1 1 0 1e-5 1e-5 5e-4 1e-3 45.0)
r2 2 0 1k
*

4.2Linear Dependent Sources

Ngspice allows circuits to contain linear dependent sources characterized by any of the four
equations

i = gvv = evi = fiv = hi

where g, e, f, and h 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 chapter 5.

4.2.1Gxxxx: Linear Voltage-Controlled Current Sources (VCCS)

General form:

GXXXXXXX N+ N− NC+ NC− VALUE <m=val >

Examples:

G1 2 0 5 0 0.1


86CHAPTER 4. VOLTAGE AND CURRENT SOURCES

n+ and n- are the positive and negative nodes, respectively. Current f l ow 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.8.5 containing references to other parameters.

4.2.2Exxxx: Linear Voltage-Controlled Voltage Sources (VCVS)

General form:

EXXXXXXX N+ N− NC+ NC− VALUE

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.

4.2.3Fxxxx: Linear Current-Controlled Current Sources (CCCS)

General form:

FXXXXXXX N+ N− VNAM VALUE <m=val >

Examples:

F1 13 5 VSENS 5 m=2

n+ and n- are the positive and negative nodes, respectively. Current f l ow 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 f l ows. The direction of positive controlling current f l ow 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.

4.2.4Hxxxx: Linear Current-Controlled Voltage Sources (CCVS)

General form:

HXXXXXXX n+ n− vnam value

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 f l ows. The direction of positive controlling current f l ow
is from the positive node, through the source, to the negative node of vnam. value is the
transresistance (in ohms).


4.2. LINEAR DEPENDENT SOURCES87

4.2.5Polynomial Source Compatibility

Dependent polynomial sources available in SPICE2G6 are fully supported in ngspice using the
XSPICE extension (25.1). The form used to specify these sources is shown in Table 4.1. For
details on its usage please see chapter 5.2.4.

Dependent Polynomial Sources
Source TypeInstance Card
POLYNOMIAL VCVSEXXXXXXX N+ N- POLY(ND) NC1+ NC1- P0 (P1...)
POLYNOMIAL VCCSGXXXXXXX N+ N- POLY(ND) NC1+ NC1- P0 (P1...)
POLYNOMIAL CCCSFXXXXXXX N+ N- POLY(ND) VNAM1 !VNAM2...? P0 (P1...)
POLYNOMIAL CCVSHXXXXXXX N+ N- POLY(ND) VNAM1 !VNAM2...? P0 (P1...)

Table 4.1: Dependent Polynomial Sources


88CHAPTER 4. VOLTAGE AND CURRENT SOURCES


Chapter 5

Non-linear Dependent Sources (Behavioral
Sources)

The non-linear dependent sources B ( see chapt. 5.1), E (see 5.2), G see (5.3) described in
this chapter allow to generate voltages or currents which result from evaluating a mathematical
expression. Internally E and G sources are converted to the more general B source. All three
sources may be used to introduce behavioral modeling and analysis.

5.1Bxxxx: Nonlinear dependent source (ASRC)

5.1.1Syntax and usage

General form:

BXXXXXXX n+ n− <i=expr > <v=expr > <tc1=value > <tc2=value >
+ <temp=value > <dtemp=value >

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.

A simple model is implemented for temperature behavior by the formula:

I(T) = I(TNOM)

?
1+TC1(T −TNOM)+TC2(T −TNOM)2

?
(5.1)

or

89


90CHAPTER 5. NON-LINEAR DEPENDENT SOURCES (BEHAVIORAL SOURCES)

V(T) =V(TNOM)

?
1+TC1(T −TNOM)+TC2(T −TNOM)2

?
(5.2)

In the above formula, “T” 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 specif i ed, 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.

The following functions of a single real variable are def i ned:

Trigonometric functions: cos, sin, tan, acos, asin, atan

Hyperbolic functions: cosh, sinh, acosh, asinh, atanh

Exponential and logarithmic: exp, ln, log

Other: abs, sqrt, u, u2, uramp, f l oor, ceil

Functions of two variables are: min, max, pow

Functions of three variables are: a ? b:c

The function “u” is the unit step function, with a value of one for arguments greater than 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 zero the value is x. These
three functions are useful in synthesizing piece-wise non-linear functions, though convergence
may be adversely affected.

The following standard operators are def i ned: +, -, *, /, ^, unary -

Logical operators are !=, <>, >=, <=, ==, >, <, ||, &&, ! .

A ternary function is def i ned 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.

Example: Ternary function

*

B sourcet e s tClampedvoltagesource
*

C. P.Basso " Switched−mode powersupplies " , New York ,2008
. param Vhigh = 4.6
. param Vlow = 0.4
Vin1 1 0 DC 0 PWL(0 0 1u 5)
Bcl 2 0 V = V(1) < Vlow ? Vlow : V(1) > Vhigh ? Vhigh: V(1)
. control
setnoaskquit
tran5n 1u
plot V(2)vs V(1)
. endc
. end


5.1. BXXXX: NONLINEAR DEPENDENT SOURCE (ASRC)91

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 undef i ned.

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 counter-
parts by a change of variables implemented with the nonlinear dependent source. The following
subcircuit will implement a nonlinear capacitor:

Example: Non linear capacitor

. Subcktnlcappos neg
*

Bx:calculatef ( inputvoltage )
Bx 1 0 v = f (v( pos , neg ))
*

Cx:linearcapacitance
Cx 2 0 1
*

Vx:Ammeter tomeasurecurrentintothecapacitor
Vx 2 1 DC 0Volts
*

Drivethecurrentthrough Cx backintothec i r c u i t
Fx pos neg Vx 1
. ends

Example for f(v(pos,neg)):

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.

Example: Non linear resistor

*

useof’ hertz ’variableinnonlinearr e s i s t o r
*. param

rbase=1k
*

somet e s t s
B11 0V = hertz*v(33)
B22 0 V = v(33)*hertz
b33 0 V = 6.283 e3 /( hertz +6.283e3 )*v(33)
V1 33 0 DC 0 AC 1
***

Translate R1 10 0 R=’1k / sqrt (HERTZ) ’to B source

***
. Subcktnlrespos negrb=rbase
*

Bx:calculatef ( inputvoltage )
Bx10v = −1 /{rb}/sqrt (HERTZ)

*

v( pos ,neg )
*

Rx:linearresistance
Rx201


92CHAPTER 5. NON-LINEAR DEPENDENT SOURCES (BEHAVIORAL SOURCES)

Example: Non linear resistor (continued)

*

Vx:Ammeter tomeasurecurrentintother e s i s t o r
Vx21DC 0Volts
*

Drivethecurrentthrough Rx backintothec i r c u i t
FxposnegVx 1
. ends
Xres 33 10nlresrb=1k
*Rres 33 10 1k
Vres 10 0 DC 0
. control
definecheck (a , b)vecmax ( abs ( a − b ))
aclin10 100 1k
*

some checks
printv (1)v (2)v (3)
ifcheck (v (1) ,frequency ) < 1e−12
echo "INFO:ok"
end
plotvres#branch
. endc
. end

5.1.2Special B-Source Variables time, temper, hertz

The special variables ’time’ and ’temper’ are available in a transient analysis, ref l ecting the
actual simulation time and circuit temperature. ’temper’ returns the circuit temperature, given
in degree C (see 2.11). The variable ’hertz’ is available in an AC analysis. ’time’ is zero in
the AC analysis, ’hertz’ is zero during transient analysis. Using the variable ’hertz’ may cost
some CPU time if you have a large circuit, because for each frequency the operating point has
to be determined before calculating the AC response.

5.1.3par(’expression’)

The B source syntax may also be used in output lines like .plot as algebraic expressions for
output (see chapt.15.6.6 ).

5.1.4Piecewise Linear Function: pwl

Both B source types may contain a piece-wise linear dependency of one network variable:

Example: pwl_current

Bdio 1 0 I = pwl (v(A) ,0 ,0 ,33 ,10m,100 ,33m,200 ,50m)

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 f l owing from ground to node 1 at 33V on node A and so forth.

The same is possible for voltage sources:


5.1. BXXXX: NONLINEAR DEPENDENT SOURCE (ASRC)93

Example: pwl_voltage

Blimit b 0 V = pwl (v (1) ,−4,0,−2,2,2 ,4 ,4 ,5 ,6 ,5)

Monotonyoftheindependentvariableinthepwldef i nitionischecked-non-monotonicxentries
will stop the program execution. v(1) may be replaced by a controlling current source. v(1) may
alsobereplacedbyanexpression, e.g. -2*i(Vin). Thevaluepairsmayalsobeparameters, which
have to be def i ned before by a .param statement. An example for the pwl function using all of
these options is shown below:


94CHAPTER 5. NON-LINEAR DEPENDENT SOURCES (BEHAVIORAL SOURCES)

Example: pwl function in B source

Demonstratesusageofthepwlfunctioninan B source(ASRC)
*

Alsoemulatesthe TABLE functionwithlimits

. param x0=−4 y0=0
. param x1=−2 y1=2
. param x2=2 y2=−2
. param x3=4 y3=1
. param xx0=x0−1
. param xx3=x3+1

Vin1 0DC=0V
R 1 0 2

*

nolimitsoutsideofthetabulatedx values( continuesl i n e a r i l y )
Btest2 2 0I = pwl (v (1) ,’x0 ’ , ’y0 ’ ,’x1 ’ , ’y1 ’ ,’x2 ’ , ’y2 ’ ,’x3 ’ , ’y3 ’)

*

like TABLE functionwithlimits :
Btest3 3 0I = (v (1) < ’x0 ’)?’y0 ’:(v (1) < ’x3 ’)?
+ pwl (v (1) ,’x0 ’ , ’y0 ’ ,’x1 ’ , ’y1 ’ ,’x2 ’ , ’y2 ’ ,’x3 ’ , ’y3 ’):’y3 ’

*

moree f f i c i e n tandelegant TABLE functionwithlimits
*( voltage

controlled ):
Btest4 4 0I = pwl (v (1) ,
+ ’xx0 ’ , ’y0 ’ ,’x0 ’ , ’y0 ’ ,
+’x1 ’ , ’y1 ’ ,
+’x2 ’ , ’y2 ’ ,
+’x3 ’ , ’y3 ’ ,’xx3 ’ , ’y3 ’)
*
*

moree f f i c i e n tandelegant TABLE functionwithlimits
*

( controlledbycurrent ):
Btest5 5 0I = pwl(−2*i ( Vin ) ,
+ ’xx0 ’ , ’y0 ’ ,’x0 ’ , ’y0 ’ ,
+’x1 ’ , ’y1 ’ ,
+’x2 ’ , ’y2 ’ ,
+’x3 ’ , ’y3 ’ ,’xx3 ’ , ’y3 ’)

Rint2 2 0 1
Rint3 3 0 1
Rint4 4 0 1
Rint5 5 0 1
. control
dcVin−6 60.2
plotv (2)v (3)v(4) −0.5 v (5)+0.5
. endc

. end


5.2. EXXXX: NON-LINEAR VOLTAGE SOURCE*95

5.2Exxxx: non-linear voltage source*

5.2.1VOL

General form:

EXXXXXXX n+ n− vol =’expr ’

Examples:

E41 4 0 vol = ’V(3)*V(3)−Offs ’

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 chapter
5.1. It may contain parameters (2.8.1) and the special variables time, temper, hertz (5.1.2). ’ or
{, } may be used to delimit the function.

5.2.2VALUE

Optional syntax:

EXXXXXXX n+ n− value={expr}

Examples:

E41 4 0 value = {V(3)*V(3)− Offs}

5.2.3TABLE

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 chapter 5.1. It may contain parameters (2.8.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!

Syntax for data entry from table:

Exxx n1 n2 TABLE { expression } = (x0 ,y0 )(x1 ,y1 )(x2 ,y2 )

Example (simple comparator):

ECMP 11 0 TABLE {V(10 ,9)} = (−5MV,0V)(5MV,5V)

5.2.4POLY

Polynomial sources are only available when the XSPICE option (see 32) is enabled.


96CHAPTER 5. NON-LINEAR DEPENDENT SOURCES (BEHAVIORAL SOURCES)

General form:

EXXXX N+ N− POLY(ND) NC1+ NC1− (NC2+ NC2−...)P0 (P1 . . . )

Example:

ENONLIN 100 101 POLY(2)3 0 4 0 0.013.60.20.005

POLY(ND) Specif i es 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 f l ows from the (+) node through the
source to the (-) node.

The <NC1+> and <NC1-> are in pairs and def i ne 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 coeff i cients 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 + k1*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 f i rst input node pair, X2 of the second pair and so
on. Keeping track of all polynomial coeff i cient obviously becomes rather tedious for larger
polynomials.

5.2.5LAPLACE

Currently ngspice does not offer a direct E-Source element with the LAPLACE option. There
is however, a XSPICE code model equivalent called x_fer (see chapt. 12.2.16), which you may
invoke manually. The XSPICE option has to enabled (32.1). AC (15.3.1) and transient analysis
(15.3.9) is supported.

The following E-Source:

ELOPASS 4 0 LAPLACE {V(1)}{10/( s /6800 + 1)}

may be replaced by:

AELOPASS 1int_4f i l t e r 1
. modelf i l t e r 1x_fer ( gain=10int_ic =[00]num_coeff =[1]
+den_coeff =[11.47e−4]
ELOPASS 4 0int_40 1


5.3. GXXXX: NON-LINEAR CURRENT SOURCE*97

where you have the voltage of node 1 as input, an intermediate output node int_4 and an E-
source as buffer, so 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.

E-Source with complex controlling expression:

ELOPASS 4 0 LAPLACE {V(1)*v (2)}{10/( s /6800 + 1)}

may be replaced by:

BELOPASS int_10 V=V(1)*v (2)
AELOPASS int_1int_4f i l t e r 1
. modelf i l t e r 1x_fer ( gain=10int_ic =[00]num_coeff =[1]
+den_coeff =[11.47e−4]
ELOPASS 4 0int_40 1

5.3Gxxxx: non-linear current source*

5.3.1CUR

General form:

GXXXXXXX n+ n− cur =’expr ’ <m=val >

Examples:

G51 55 225cur = ’V(3)*V(3)−Offs ’

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 chapter
5.1. It may contain parameters (2.8.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.8.5 con-
taining only references to other parameters (no node voltages or branch currents!), because it is
evaluated before the simulation commences.

5.3.2VALUE

Optional syntax:

GXXXXXXX n+ n− value =’expr ’ <m=val >

Examples:

G51 55 225value = ’V(3)*V(3)−Offs ’

5.3.3TABLE

A data entry by a tabulated listing is available with syntax similar to the E-Source (see chapt.
5.2.3).


98CHAPTER 5. NON-LINEAR DEPENDENT SOURCES (BEHAVIORAL SOURCES)

Syntax for data entry from table:

Gxxx n1 n2 TABLE { expression } = (x0 ,y0 )(x1 ,y1 )(x2 ,y2 ) <m=val >

Example (simple comparator with current output and voltage control):

GCMP 0 11 TABLE {V(10 ,9)} = (−5MV,0V)(5MV,5V)
R 11 0 1k

m is an optional multiplier to the output current. val may be a numerical value or an expression
according to 2.8.5 containing only references to other parameters (no node voltages or branch
currents!), because it is evaluated before the simulation commences.

5.3.4POLY

see E-Source at chapt. 5.2.4.

5.3.5LAPLACE

See E-Source, chapt. 5.2.5 , for an equivalent code model replacement.

5.3.6Example

An example f i le is given below.


5.4. DEBUGGING A BEHAVIORAL SOURCE99

Example input f i le:

VCCS, VCVS,non−lineardependency
. param Vi=1
. paramOffs = ’0.01*Vi ’
*

VCCS depending on V(3)
B21int10 V = V(3)*V(3)
G1 21 22int10 1
*

measurecurrentthrough VCCS
vm 22 0 dc 0
R21 21 0 1
*

new VCCS depending on V(3)
G51 55 225cur = ’V(3)*V(3)−Offs ’
*

measurecurrentthrough VCCS
vm5 225 0 dc 0
R51 55 0 1
*

VCVS depending on V(3)
B31int20 V = V(3)*V(3)
E1 1 0int20 1
R1 1 0 1
*

new VCVS depending on V(3)
E41 4 0 vol = ’V(3)*V(3)−Offs ’
R4 4 0 1
*

controlvoltage
V1 3 0 PWL(0 0 100u {Vi})
. control
setnoaskquit
tran10n 100u uic
ploti (E1)i (E41)
ploti (vm)i (vm5)
. endc
. end

*) To get this functionality, the compatibility mode has to be set in spinit or .spiceinit by set
ngbehavior=all.

5.4Debugging a behavioral source

The B, E, G, sources and the behavioral R, C, L elements are powerful tools to set up user
def i ned models. Unfortunately debugging these models is not very comfortable.


100CHAPTER 5. NON-LINEAR DEPENDENT SOURCES (BEHAVIORAL SOURCES)

Example input f i le with bug (log(-2)):

B sourcedebugging

V1 1 0 1
V2 2 0 −2

E41 4 0 vol = ’V(1)*log (V(2)) ’

. control
tran1 1
. endc

. end

The input f i le given above results in an error message:

Error:-2 out of range for log

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 f i le .spiceinit), a more distinctive
error message is issued, which (after some closer investigation) will reveal the location and
value of the buggy parameter.

Detailed error message for input f i le with bug (log(-2)):

Error : −2 outofrangeforlog
callingPTeval ,tree =
(v0)

*

( log(v1 ))
d/d v0:log(v1 )
d/d v1:(v0 )

*

((0.434294)/( v1 ))
values :var0 = 1
var1 = −2

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.


Chapter 6

Transmission Lines

Ngspice implements both the original SPICE3f5 transmission lines models and the one intro-
duced with KSPICE. The latter provide an improved transient analysis of lossy transmission
lines. Unlike SPICE models, which uses the state-based approach to simulate lossy transmis-
sion lines, KSPICE simulates lossy transmission lines and coupled multiconductor line systems
using the recursive convolution method. The impulse response of an arbitrary transfer function
can be determined by deriving a recursive convolution from the Pade approximations of the
function. We use this approach for simulating each transmission line’s characteristics and each
multiconductor line’s modal functions. This method of lossy transmission line simulation has
been proved to give a speedup of one to two orders of magnitude over SPICE3f5.

6.1Lossless Transmission Lines

General form:

TXXXXXXX N1 N2 N3 N4 Z0=VALUE <TD=VALUE> <F=FREQ <NL=NRMLEN>>
+ <IC=V1,I1 , V2,I2 >

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 specif i ed 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 specif i ed 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 specif i ed.

Notethatthiselementmodelsonlyonepropagatingmode. Ifallfournodesaredistinctintheac-
tual 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 clarif i cation.) The (optional)
initial condition specif i cation 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 specif i ed on the
.TRAN control line.

101


102CHAPTER 6. TRANSMISSION LINES

Note that a lossy transmission line (see below) with zero loss may be more accurate than the
lossless transmission line due to implementation details.

6.2Lossy Transmission Lines

General form:

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.

6.2.1Lossy Transmission Line Model (LTRA)

The uniform RLC/RC/LC/RG transmission line model (referred to as the LTRA model hence-
forth) models a uniform constant-parameter distributed transmission line. The RC and LC cases
may also be modeled using the URC and TRA models; however, the newer LTRA model is usu-
ally faster and more accurate than the others. The operation of the LTRA model is based on the
convolution of the transmission line’s impulse responses with its inputs (see [8]). The LTRA
model takes a number of parameters, some of which must be given and some of which are
optional.


6.2. LOSSY TRANSMISSION LINES103

NameParameterUnits/TypeDefaultExample
Rresistance/length

Ω/unit

0.00.2
Linductance/length

H/unit

0.09.13e-9
Gconductance/length

mhos/unit

0.00.0
Ccapacitance/length

F/unit

0.03.65e-12
LENlength of lineunitno default1.0
RELbreakpoint controlarbitrary unit10.5
ABSbreakpoint control15
NOSTEPLIMITdon’t limit time-step to less
than line delay

f l agnot setset

NO CONTROLdon’t do complex time-step
control

f l agnot setset

LININTERPuse linear interpolationf l agnot setset
MIXEDINTERPuse linear when quadratic
seems bad

f l agnot setset

COMPACTRELspecial reltol for history
compaction

RELTOL1.0e-3

COMPACTABSspecial abstol for history
compaction

ABSTOL1.0e-9

TRUNCNRuse Newton-Raphson method
for time-step control

f l agnot setset

TRUNCDONTCUTdon’t limit time-step to keep
impulse-response errors low

f l agnot setset

The following types of lines have been implemented so far:

• RLC (uniform transmission line with series loss only),

• RC (uniform RC line),

• LC (lossless transmission line),

• RG (distributed series resistance and parallel conductance only).

Any other combination will yield erroneous results and should not be tried. The length LEN
of the line must be specif i ed. NOSTEPLIMIT is a f l ag that will remove the default restriction
of limiting time-steps to less than the line delay in the RLC case. NO CONTROL is a f l ag that
prevents the default limiting of the time-step based on convolution error criteria in the RLC and
RC cases. This speeds up simulation but may in some cases reduce the accuracy of results.
LININTERP is a f l ag that, when specif i ed, will use linear interpolation instead of the default
quadratic interpolation for calculating delayed signals. MIXEDINTERP is a f l ag that, when spec-
if i ed, uses a metric for judging whether quadratic interpolation is not applicable and if so uses
linear interpolation; otherwise it uses the default quadratic interpolation. TRUNCDONTCUT is a
f l ag that removes the default cutting of the time-step to limit errors in the actual calculation of
impulse-response related quantities. COMPACTREL and COMPACTABS are quantities that control
the compaction of the past history of values stored for convolution. Larger values of these lower
accuracy but usually increase simulation speed. These are to be used with the TRYTOCOMPACT
option, described in the .OPTIONS section. TRUNCNR is a f l ag that turns on the use of Newton-
Raphson iterations to determine an appropriate time-step in the time-step control routines. The


104CHAPTER 6. TRANSMISSION LINES

default is a trial and error procedure by cutting the previous time-step in half. REL and ABS are
quantities that control the setting of breakpoints.

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 specif i ed 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 specif i ed
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.

6.3Uniform Distributed RC Lines

General form:

UXXXXXXX n1 n2 n3 mname l=len <n=lumps>

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 to which the
capacitances are connected. mname is the model name, len is the length of the RC line in
meters. lumps, if specif i ed, 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).

6.3.1Uniform Distributed RC Model (URC)

The URC model is derived from a model proposed by L. Gertzberg in 1974. The model is
accomplished by a subcircuit type expansion of the URC line into a network of lumped RC
segments with internally generated nodes. The RC segments are in a geometric progression,
increasing toward the middle of the URC line, with K as a proportionality constant. The num-
ber of lumped segments used, if not specif i ed for the URC line device, is determined by the
following formula:

N =

log

?

?

?

?Fmax

R
L

C
L2πL

2

?

?

?(K−1)

K

?

?

?

2??

?

?

logK

(6.1)

The URC line is made up strictly of resistor and capacitor segments unless the ISPERL parame-
ter is given a nonzero value, in which case the capacitors are replaced with reverse biased diodes


6.4. KSPICE LOSSY TRANSMISSION LINES105

with a zero-bias junction capacitance equivalent to the capacitance replaced, and with a satu-
ration current of ISPERL amps per meter of transmission line and an optional series resistance
equivalent to RSPERL ohms per meter.

NameParameterUnitsDefaultExampleArea
KPropagation Constant-2.01.2-
FMAXMaximum Frequency of interestHz1.0 G6.5 Meg-
RPERLResistance per unit length

Ω/m

100010-
CPERLCapacitance per unit length

F/m

10e-151 p-
ISPERLSaturation Current per unit length

A/m

0--
RSPERLDiode Resistance per unit length

Ω/m

0--

6.4KSPICE Lossy Transmission Lines

Unlike SPICE3, which uses the state-based approach to simulate lossy transmission lines,
KSPICE simulates lossy transmission lines and coupled multiconductor line systems using the
recursive convolution method. The impulse response of an arbitrary transfer function can be
determined by deriving a recursive convolution from the Pade approximations of the function.
NGSPICEisusingthisapproachforsimulatingeachtransmissionline’scharacteristicsandeach
multiconductor line’s modal functions. This method of lossy transmission line simulation has
shown to give a speedup of one to two orders of magnitude over SPICE3E. Please note that the
following two models will support only transient simulation, no ac.

Additional Documentation Available:

• 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 Conduc-
tance 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 Au-
tomation Conference, Anaheim, CA, June 1992, pp. 81-86.

6.4.1Single Lossy Transmission Line (TXL)

General form:

YXXXXXXX N1 0 N2 0 mname <LEN=LENGTH>

Example:

Y1 1 0 2 0 ymod LEN=2
.MODEL ymodtxl R=12.45 L=8.972e−9 G=0 C=0.468e−12 length =16

n1 and 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 [unit]. Typically unit is given in meters. len will
override the model parameter length for the specif i c instance only.


106CHAPTER 6. TRANSMISSION LINES

The TXL model takes a number of parameters:

NameParameterUnits/TypeDefaultExample
Rresistance/length

Ω/unit

0.00.2
Linductance/length

H/unit

0.09.13e-9
Gconductance/length

mhos/unit

0.00.0
Ccapacitance/length

F/unit

0.03.65e-12
LENGTHlength of lineunitno default1.0

Model parameter length must be specif i ed as a multiple of unit. Typically unit is given in [m].
For transient simulation only.

6.4.2Coupled Multiconductor Line (CPL)

The CPL multiconductor line model is in theory similar to the RLGC model, but without fre-
quency dependent loss (neither skin effect nor frequency-dependent dielectric loss). Up to 8
coupled lines are supported in NGSPICE.

General form:

PXXXXXXX NI1 NI2 . . . NIX GND1 NO1 NO2 . . .NOX GND2 mname <LEN=LENGTH>

Example:

P1 in1in2 0 b1 b2 0 PLINE
. model PLINE CPL length ={Len}
+R=1 0 1
+L={L11} {L12} {L22}
+G=0 0 0
+C={C11} {C12} {C22}
. param Len=1 Rs=0
+ C11=9.143579E−11 C12=−9.78265E−12 C22=9.143578E−11
+ L11=3.83572E−7 L12=8.26253E−8 L22=3.83572E−7

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 and may be expressed in multiples
of [unit]. Typically unit is given in meters. len will override the model parameter length for
the specif i c instance only.

The CPL model takes a number of parameters:

NameParameterUnits/TypeDefaultExample
Rresistance/length

Ω/unit

0.00.2
Linductance/length

H/unit

0.09.13e-9
Gconductance/length

mhos/unit

0.00.0
Ccapacitance/length

F/unit

0.03.65e-12
LENGTHlength of lineunitno default1.0

All RLGC parameters are given in Maxwell matrix form. For the R and G matrices the diagonal
elements must be specif i ed, for L and C matrices the lower or upper triangular elements must
specif i ed. The parameter LENGTH is a scalar and is mandatory. For transient simulation only.


Chapter 7

Diodes

7.1Junction Diodes

General form:

DXXXXXXX n+ n− mname <area=val > <m=val > <pj=val > <off > <ic=vd>
+ <temp=val > <dtemp=val >

Examples:

DBRIDGE 2 10 DIODE1
DCLMP 3 7 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 and negative nodes,
respectively. mname is the model name. Instance parameters may follow, dedicated to only
the diode described in 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 it’s associated capacitance. m
is a multiplier to 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 specif i cation 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 specif i cation
on the .option control line. The temperature of each instance can be can be specif i ed as an
offset to the circuit temperature with the dtemp option.

7.2Diode Model (D)

The dc characteristics of the diode are determined by the parameters is and n. An ohmic resis-
tance, rs, is included. Charge storage effects are modeled by a transit time, tt, and a nonlinear
depletion layer capacitance which is determined by the parameters cjo, vj, and m. The temper-
ature dependence of the saturation current is def i ned by the parameters eg, the energy and xti,

107


108CHAPTER 7. DIODES

the saturation current temperature exponent. The nominal temperature at which these parame-
ters were measured is tnom, which defaults to the circuit-wide value specif i ed 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

NameParameterUnitsDefaultExampleScale factor
BVReverse breakdown voltageV∞40
IBVCurrent at breakdown voltageA1.0e-31.0e-4
IK (IKF)Forward knee currentA1.0e-31.0e-6
IKRReverse knee currentA1.0e-31.0e-6
IS (JS)Saturation currentA1.0e-141.0e-16area
JSWSidewall saturation currentA1.0e-141.0e-15perimeter
NEmission coeff i cient-11.5
RSOhmic resistanceΩ0.0100

1/area

Junction capacitance parameters

NameParameterUnitsDefaultExampleScale factor
CJO (CJ0)Zero-bias junction bottom-wall
capacitance

F0.02pFarea

CJP (CJSW)Zero-bias junction sidewall
capacitance

F0.0.1pFperimeter

FCCoeff i cient for forward-bias
depletion bottom-wall capacitance
formula

-0.5-

FCSCoeff i cient for forward-bias
depletion sidewall capacitance
formula

-0.5-

M (MJ)Area junction grading coeff i cient-0.50.5
MJSWPeriphery junction grading
coeff i cient

-0.330.5

VJ (PB)Junction potentialV10.6
PHPPeriphery junction potentialV10.6
TTTransit-timesec00.1ns


7.3. DIODE EQUATIONS109

Temperature effects

NameParameterUnitsDefaultExampleScale factor

EGActivation energyeV1.11

1.11Si
0.69Sbd
0.67Ge
TM11st order tempco for MJ

1/◦C

0.0-
TM22nd order tempco for MJ

1/◦C2

0.0-
TNOM (TREF)Parameter measurement temperature

◦C

2750
TRS1 (TRS)1st order tempco for RS

1/◦C

0.0-
TRS22nd order tempco for RS

1/◦C2

0.0-
TM11st order tempco for MJ

1/◦C

0.0-
TM22nd order tempco for MJ

1/◦C2

0.0-
TTT11st order tempco for TT

1/◦C

0.0-
TTT22nd order tempco for TT

1/◦C2

0.0-

XTISaturation current temperature exponent-3.0

3.0pn
2.0Sbd
TLEVDiode temperature equation selector-0
TLEVCDiode capac. temperature equation selector-0
CTA (CTC)Area junct. cap. temperature coeff i cient

1/◦C

0.0-
CTPPerimeter junct. cap. temperature coeff i cient

1/◦C

0.0-
TCVBreakdown voltage temperature coeff i cient

1/◦C

0.0-

Noise modeling

NameParameterUnitsDefaultExampleScale factor
KFFlicker noise coeff i cient-0
AFFlicker noise exponent-1

Diode models may be described in the input f i le (or an f i le included by .inc) according to the
following example:

General form:

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

Examples:

. model DMOD D ( bf=50is =1e−13 vbf =50)

7.3Diode Equations

The junction diode is the basic semiconductor device and the simplest one modeled in ngspice,
but it’s model is quite complex, even if not all the physical phenomena affecting a pn junction
are modeled. The diode is modeled in three different regions:

• 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
better to specify a series resistance to limit current with rs model parameter.


110CHAPTER 7. DIODES

• 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 model led only if the bv model parameter is given.
When a diode enters breakdown the current increase 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:

AREAef f= AREA·M

PJef f= PJ·M

ISef f= IS·AREAef f+JSW∗PJef f

IBVef f= IBV·AREAef f

IKef f= IK·AREAef f

IKRef f= IKR·AREAef f

CJef f= CJ0·AREAef f

CJPef f= CJP·PJef f

Diode DC, Transient and AC model equations

ID=















ISef f(e

qVD
NkT−1)+VD∗GMIN,

ifVD≥ −3NkT

q
−ISef f[1+(3NkT

qVDe)

3]+VD∗GMIN,

if −BVef f<VD< −3NkT

q

−ISef f(e

−q(BVef f+VD)
NkT

)+VD∗GMIN,ifVD≤ −BVef f

(7.1)

The breakdown region must be described with more depth since the breakdown is not modeled
in 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 arbitrary chosen, since the reverse bias
andbreakdownregionsmustmatch. Whenthediodeentersbreakdownregionfromreversebias,
the current is calculated using the formula1:

Ibdwn= −ISef f(e

−qBV
NkT

−1)(7.2)

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:

Most real diodes shows a current increase that, at high current levels, does not follow the expo-
nential relationship given above. This behavior is due to high level of carriers injected into the
junction. High injection effects (as they are called) are modeled with ik and ikr.

1if you look at the source code in f i le diotemp.c you will discover that the exponential relation is replaced

with a f i rst order Taylor series expansion.


7.3. DIODE EQUATIONS111

Algorithm 7.1 Diode breakdown current calculation
if IBVef f< Ibdwnthen
IBVef f= Ibdwn
BVef f= BV
else
BVef f= BV−NVtln(

IBVef f
Ibdwn

)

IDef f=


















ID

1+

r
ID
IKef f

,ifVD≥ −3NkT

q

ID

1+

r
ID
IKRef f

,otherwise.

(7.3)

Diode capacitance is divided into two different terms:

• 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:

CDiode=Cdif fusion+Cdepletion

Where the depletion capacitance i def i ned as:

Cdepletion=Cdeplbw+Cdeplsw

The diffusion capacitance, due to the injected minority carriers is modeled with the transit time
tt:

Cdif fusion= TT∂IDef f

∂VD

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.

Cdeplbw=






CJef f·(1−

VD
VJ)

−MJ,

ifVD< FC·VJ

CJef f·

1−FC·(1+MJI)+MJ·VD

VJ
(1−FC)(1+MJ)

,otherwise.

(7.4)

Cdeplsw=






CJPef f·(1−

VD
PHP)

−MJSW,

if VD< FCS·PHP

CJPef f·

1−FCS·(1+MJSW)+MJSW·

VD
PHP
(1−FCS)(1+MJSW)

,otherwise.

(7.5)


112CHAPTER 7. DIODES

Temperature dependence

The temperature affects many of the parameters in the equations above, the following equa-
tions show how. One of the most signif i cant parameter that varies with the temperature for a
semiconductor is the band-gap energy:

EGnom= 1.16−7.02e−4·

TNOM2
TNOM+1108.0

(7.6)

EG(T) = 1.16−7.02e−4·

T2
TNOM+1108.0

(7.7)

The leakage currents temperature dependence is:

IS(T) = IS·e

logfactor
N

(7.8)

JSW(T) = JSW·e

logfactor
N

(7.9)

where "logfactor" is def i ned:

logfactor =

EG
Vt(TNOM)

−

EG
Vt(T)

+XTI·ln(

T
TNOM)

(7.10)

The contact potentials (bottom-wall an sidewall) temperature dependence is:

VJ(T) = VJ·(

T
TNOM)−Vt(T)·

?
3·ln(

T
TNOM)+

EGnom
Vt(TNOM)

−

EG(T)
Vt(T)

?
(7.11)

PHP(T) = PHP·(

T
TNOM)−Vt(T)·

?
3·ln(

T
TNOM)+

EGnom
Vt(TNOM)

−

EG(T)
Vt(T)

?
(7.12)

The depletion capacitances temperature dependence is:

CJ(T) = CJ·

?
1+MJ·(4.0e−4·(T −TNOM)−

VJ(T)
VJ

+1)

?
(7.13)

CJSW(T) = CJSW·

?
1+MJSW·(4.0e−4·(T −TNOM)−

PHP(T)
PHP

+1)

?
(7.14)

The transit time temperature dependence is:

TT(T) = TT·(1+TTT1·(T −TNOM)+TTT2·(T −TNOM)2)(7.15)

The junction grading coeff i cient temperature dependence is:

MJ(T) = MJ·(1+TM1·(T −TNOM)+TM2·(T −TNOM)2)(7.16)

The series resistance temperature dependence is:

RS(T) = RS·(1+TRS·(T −TNOM)+TRS2·(T −TNOM)2)(7.17)


7.3. DIODE EQUATIONS113

Noise model

The diode has three noise contribution, one due to the presence of the parasitic resistance rs
and the other two (shot and f l icker) due to the pn junction.

The thermal noise due to the parasitic resistance is:

i2

RS

=

4kT∆f
RS

(7.18)

The shot and f l icker noise contributions are:

i2

d

= 2qID∆f +

KF ∗IAF

D
f

∆f(7.19)


114CHAPTER 7. DIODES


Chapter 8

BJTs

8.1Bipolar Junction Transistors (BJTs)

General form:

QXXXXXXX nc nb ne <ns> mname <area=val > <areac=val > <areab=val >
+ <m=val > <off > <ic=vbe , vce> <temp=val > <dtemp=val >

Examples:

Q23 10 24 13 QMOD IC=0.6 ,5.0
Q50A 11 26 4 20 MOD1

nc, nb, and ne are the collector, base, and emitter nodes, respectively. ns is the (optional)
substrate node. If unspecif i ed, ground is used. 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 specif i cation using ic=vbe,vce is intended for use with the
uic option on a .tran control line, when a transient analysis is desired starting 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 at which this device
is to operate, and overrides the temperature specif i cation on the .option control line. Using
dtemp option you can specify instance’s temperature relative to the circuit temperature.

8.2BJT Models (NPN/PNP)

Ngspice provides three BJT device models, which are selected by the .model card.

.model QMOD1 BJT level=2

This is the minimal version, further optional parameters listed in the table below may replace
the ngspice default parameters. The level keyword specif i es 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 specif i ed on the .model line.

115


116CHAPTER 8. BJTS

• level=2 : This is a modif i ed version of the original SPICE BJT that models both vertical
and lateral devices and includes temperature corrections of collector, emitter and base
resistors.

• level=4: Advanced VBIC model (see http://www.designers-guide.org/VBIC/ for details)

The bipolar junction transistor model in ngspice is an adaptation of the integral charge control
model of Gummel and Poon. This modif i ed Gummel-Poon model extends the original model
to include several effects at high bias levels. The model automatically simplif i es to the simpler
Ebers-Moll model when certain parameters are not specif i ed. The parameter names used in the
modif i ed Gummel-Poon model have been chosen to be more easily understood by the program
user, and to ref l ect better both physical and circuit design thinking.

The dc model is def i ned 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.

Level 1 model has among the standard temperature model a extension which is compatible with
most foundry provided process design kits (see parameter table below tlev).

Level 1 and 2 model includes 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
byforwardandreversetransittimes, tfandtr, theforwardtransittimetfbeingbiasdependent
if desired, and nonlinear depletion layer capacitances which are determined by 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.

Level 1 and 2 model def i nes a substrate capacitance that will be connected to device’s base or
collector, to model lateral or vertical devices dependent from the parameter subs. The temper-
ature dependence of the saturation currents, is and iss (for level 2 model), is determined by
the energy-gap, eg, and the saturation current temperature exponent, xti.

Additionally base current temperature dependence is modeled by the beta temperature exponent
xtb in the new model. The values specif i ed are assumed to have been measured at the tempera-
ture tnom, which can be specif i ed on the .options control line or overridden by a specif i cation
on the .model line.

Level 4 model (VBIC) has the following improvements beyond the GP models: Improved Early
effect modeling, Quasi-saturation modeling, Parasitic substrate transistor modeling, Parasitic
f i xed (oxide) capacitance modeling, Includes an avalanche multiplication model, Improved tem-
perature modeling, Base current is decoupled from collector current, Electrothermal modeling,
Smooth, continuous mode.

The BJT parameters used in the modif i ed Gummel-Poon model are listed below. The parameter
names used in earlier versions of SPICE2 are still accepted.

Gummel-Poon BJT Parameters (incl. model extensions)

NameParametersUnitsDefaultExampleScale factor


8.2. BJT MODELS (NPN/PNP)117

SUBSSubstrate connection: for vertical
geometry, -1 for lateral geometry
(level 2 only).

1

ISTransport saturation current.A1.0e-161.0e-15area
ISSReverse saturation current,
substrate-to-collector for vertical
device or substrate-to-base for
lateral (level 2 only).

A1.0e-161.0e-15area

BFIdeal maximum forward beta.-100100
NFForward current emission
coeff i cient.

-1.01

VAF (VA)Forward Early voltage.V∞200
IKFCorner for forward beta current
roll-off.

A∞0.01area

NKFHigh current Beta rolloff exponent-0.50.58
ISEB-E leakage saturation current.A0.01e-13area
NEB-E leakage emission coeff i cient.-1.52
BRIdeal maximum reverse beta.-10.1
NRReverse current emission
coeff i cient.

-11

VAR (VB)Reverse Early voltage.V∞200
IKRCorner for reverse beta high
current roll-off.

A∞0.01area

ISCB-C leakage saturation current
(area is "areab" for vertical devices
and "areac" for lateral).

A0.01e-13area

NCB-C leakage emission coeff i cient.-21.5
RBZero bias base resistance.Ω0100area
IRBCurrent where base resistance falls
halfway to its min value.

A∞0.1area

RBMMinimum base resistance at high
currents.

ΩRB10area

REEmitter resistance.Ω01area
RCCollector resistance.Ω010area
CJEB-E zero-bias depletion
capacitance.

F02pFarea

VJE (PE)B-E built-in potential.V0.750.6
MJE (ME)B-E junction exponential factor.-0.330.33
TFIdeal forward transit time.sec00.1ns
XTFCoeff i cient for bias dependence of
TF.

-0

VTFVoltage describing VBC
dependence of TF.

V∞

ITFHigh-current parameter for effect
on TF.

A0-area


118CHAPTER 8. BJTS

PTFExcess phase at freq=1.0/(TF*2PI)
Hz.

deg0

CJCB-C zero-bias depletion
capacitance (area is "areab" for
vertical devices and "areac" for
lateral).

F02pFarea

VJC (PC)B-C built-in potential.V0.750.5
MJCB-C junction exponential factor.-0.330.5
XCJCFraction of B-C depletion
capacitance connected to internal
base node.

-1

TRIdeal reverse transit time.sec010ns
CJSZero-bias collector-substrate
capacitance (area is "areac" for
vertical devices and"areab" for
lateral).

F02pFarea

VJS (PS)Substrate junction built-in
potential.

V0.75

MJS (MS)Substrate junction exponential
factor.

-00.5

XTBForward and reverse beta
temperature exponent.

-0

EGEnergy gap for temperature effect
on IS.

eV1.11

XTITemperature exponent for effect on
IS.

-3

KFFlicker-noise coeff i cient.-0
AFFlicker-noise exponent.-1
FCCoeff i cient for forward-bias
depletion capacitance formula.

-0.50

TNOM (TREF)Parameter measurement
temperature.

◦C

2750

TLEVBJT temperature equation selector-0
TLEVCBJT capac. temperature equation
selector

-0

TRE11st order temperature coeff i cient
for RE.

1/◦C

0.01e-3

TRE22nd order temperature coeff i cient
for RE.

1/◦C2

0.01e-5

TRC11st order temperature coeff i cient
for RC .

1/◦C

0.01e-3

TRC22nd order temperature coeff i cient
for RC.

1/◦C2

0.01e-5

TRB11st order temperature coeff i cient
for RB.

1/◦C

0.01e-3


8.2. BJT MODELS (NPN/PNP)119

TRB22nd order temperature coeff i cient
for RB.

1/◦C2

0.01e-5

TRBM11st order temperature coeff i cient
for RBM

1/◦C

0.01e-3

TRBM22nd order temperature coeff i cient
for RBM

1/◦C2

0.01e-5

TBF11st order temperature coeff i cient
for BF

1/◦C

0.01e-3

TBF22nd order temperature coeff i cient
for BF

1/◦C2

0.01e-5

TBR11st order temperature coeff i cient
for BR

1/◦C

0.01e-3

TBR22nd order temperature coeff i cient
for BR

1/◦C2

0.01e-5

TIKF11st order temperature coeff i cient
for IKF

1/◦C

0.01e-3

TIKF22nd order temperature coeff i cient
for IKF

1/◦C2

0.01e-5

TIKR11st order temperature coeff i cient
for IKR

1/◦C

0.01e-3

TIKR22nd order temperature coeff i cient
for IKR

1/◦C2

0.01e-5

TIRB11st order temperature coeff i cient
for IRB

1/◦C

0.01e-3

TIRB22nd order temperature coeff i cient
for IRB

1/◦C2

0.01e-5

TNC11st order temperature coeff i cient
for NC

1/◦C

0.01e-3

TNC22nd order temperature coeff i cient
for NC

1/◦C2

0.01e-5

TNE11st order temperature coeff i cient
for NE

1/◦C

0.01e-3

TNE22nd order temperature coeff i cient
for NE

1/◦C2

0.01e-5

TNF11st order temperature coeff i cient
for NF

1/◦C

0.01e-3

TNF22nd order temperature coeff i cient
for NF

1/◦C2

0.01e-5

TNR11st order temperature coeff i cient
for IKF

1/◦C

0.01e-3

TNR22nd order temperature coeff i cient
for IKF

1/◦C2

0.01e-5

TVAF11st order temperature coeff i cient
for VAF

1/◦C

0.01e-3

TVAF22nd order temperature coeff i cient
for VAF

1/◦C2

0.01e-5


120CHAPTER 8. BJTS

TVAR11st order temperature coeff i cient
for VAR

1/◦C

0.01e-3

TVAR22nd order temperature coeff i cient
for VAR

1/◦C2

0.01e-5

CTC1st order temperature coeff i cient
for CJC

1/◦C

0.01e-3

CTE1st order temperature coeff i cient
for CJE

1/◦C

0.01e-3

CTS1st order temperature coeff i cient
for CJS

1/◦C

0.01e-3

TVJC1st order temperature coeff i cient
for VJC

1/◦C2

0.01e-5

TVJE1st order temperature coeff i cient
for VJE

1/◦C

0.01e-3

TITF11st order temperature coeff i cient
for ITF

1/◦C

0.01e-3

TITF22nd order temperature coeff i cient
for ITF

1/◦C2

0.01e-5

TTF11st order temperature coeff i cient
for TF

1/◦C

0.01e-3

TTF22nd order temperature coeff i cient
for TF

1/◦C2

0.01e-5

TTR11st order temperature coeff i cient
for TR

1/◦C

0.01e-3

TTR22nd order temperature coeff i cient
for TR

1/◦C2

0.01e-5

TMJE11st order temperature coeff i cient
for MJE

1/◦C

0.01e-3

TMJE22nd order temperature coeff i cient
for MJE

1/◦C2

0.01e-5

TMJC11st order temperature coeff i cient
for MJC

1/◦C

0.01e-3

TMJC22nd order temperature coeff i cient
for MJC

1/◦C2

0.01e-5


Chapter 9

JFETs

9.1Junction Field-Effect Transistors (JFETs)

General form:

JXXXXXXX nd ng ns mname <area > <off > <ic=vds , vgs> <temp=t >

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
specif i cation, 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 at which this device is to operate, and overrides the temperature specif i cation
on the .option control line.

9.2JFET Models (NJF/PJF)

9.2.1JFET level 1 model with Parker Skellern modif i cation

The level 1 JFET model is derived from the FET model of Shichman and Hodges. The dc
characteristics are def i ned by the parameters VTO and BETA, which determine the variation
of drain current with gate voltage, LAMBDA, which determines the output conductance, and
IS, the saturation current of the two gate junctions. Two ohmic resistances, RD and RS, are
included.

vgst = vgs−VTO(9.1)

βp= BETA∗(1+LAMBDA∗vds)(9.2)

121


122CHAPTER 9. JFETS

bfac =

1−B
PB−VTO

(9.3)

IDrain=










vds∗GMIN,if vgst ≤ 0
βp∗vds∗(vds∗(bfac∗vds−B)∗vgst ∗(2∗B+3∗bfac∗(vgst −vds)))+vds∗GMIN,if vgst ≥ vds
βp∗vgst2∗(B+vgst ∗bfac)+vds∗GMIN,if vgst < vds
(9.4)

Note that in Spice3f and later, the f i tting parameter B has been added by Parker and Skellern.
For details, see [9]. If parameter B is set to 1 equation above simplif i es to

IDrain=










vds∗GMIN,if vgst ≤ 0
βp∗vds∗(2∗vgst −vds)+vds∗GMIN,if vgst ≥ vds
βp∗vgst2+vds∗GMIN,if vgst < vds

(9.5)

Charge storage is modeled by nonlinear depletion layer capacitances for both gate junctions
which vary as the −1/2power of junction voltage and are def i ned by the parameters CGS, CGD,
and PB.

NameParameterUnitsDefaultExampleScaling factor
VTOThreshold voltageVT0V-2.0-2.0
BETATransconductance parameter (β)

A/V”

1.0e-41.0e-3area
LAMBDAChannel-length modulation
parameter (λ)

1/V

01.0e-4

RDDrain ohmic resistanceΩ0100area
RSSource ohmic resistanceΩ0100area
CGSZero-bias G-S junction capacitance
Cgs

F05pFarea

CGDZero-bias G-D junction
capacitanceCgd

F01pFarea

PBGate junction potentialV10.6
ISGate saturation current ISA1.0e-141.0e-14area
BDoping tail parameter-11.1
KFFlicker noise coeff i cient-0
AFFlicker noise exponent-1
NLEVNoise equation selector-13
GDSNOIChannel noise coeff i cient for
nlev=3

1.02.0

FCCoeff i cient for forward-bias
depletion capacitance formula

0.5

TNOMParameter measurement
temperature

◦C

2750

TCVThreshold voltage temperature
coeff i cient

1/°C

0.00.1

BEXMobility temperature exponent-0.01.1


9.2. JFET MODELS (NJF/PJF)123

Additional to the standard thermal and f l icker noise model an alternative thermal channel noise
model is implemented and is selectable by setting NLEV parameter to 3. This follows in a
correct channel thermal noise in the linear region.

Snoise=

2
3

∗4∗k∗T ∗BETA∗Vgst ∗

(1+α +α2)
1+α

∗GDSNOI(9.6)

with

α =

(
1−

vds
vgs−VTO,

if vgs−VTO ≥ vds

0,else

(9.7)

9.2.2JFET level 2 Parker Skellern model

The level 2 model is an improvement to level 1. Details are available from Macquarie Univer-
sity. Some important items are:

• 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 con-
sistent 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 f i tting 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].


124CHAPTER 9. JFETS

NameDescriptionUnit TypeDefault
IDDevice IDTextTextPF1
ACGAMCapacitance modulationNone0
BETALinear-region transconductance scaleNone10−4
CGDZero-bias gate-source capacitanceCapacitance0 F
CGSZero-bias gate-drain capacitanceCapacitance0 F
DELTAThermal reduction coeff i cientNone0 W
FCForward bias capacitance parameterNone0.5
HFETAHigh-frequency VGS feedback parameterNone0
HFE1HFGAM modulation by VGDNone0V−1
HFE2HFGAM modulation by VGSNone0 V−1
HFGAMHigh-frequency VGD feedback parameterNone0
HFG1HFGAM modulation by VSGNone0 V−1
HFG2HFGAM modulation by VDGNone0 V−1
IBDGate-junction breakdown currentCurrent0 A
ISGate-junction saturation currentCurrent10−14A
LFGAMLow-frequency feedback parameterNone0
LFG1LFGAM modulation by VSGNone0 V−1
LFG2LFGAM modulation by VDGNone0 V−1
MVSTSubthreshold modulationNone0 V−1
NGate-junction ideality factorNone1
PLinear-region power-law exponentNone2
QSaturated-region power-law exponentNone2
RSSource ohmic resistanceResistance0 Ohm
RDDrain ohmic resistanceResistance0 Ohm
TAUDRelaxation time for thermal reductionTime0 s
TAUGRelaxation time for gamma feedbackTime0 s
VBDGate-junction breakdown potentialVoltage1 V
VBIGate-junction potentialVoltage1 V
VSTSubthreshold potentialVoltage0 V
VTOThreshold voltageVoltage-2.0 V
XCCapacitance pinch-off reduction factorNone0
XISaturation-knee potential factorNone1000
ZKnee transition parameterNone0.5
RGGate ohmic resistanceResistance0 Ohm
LGGate inductanceInductance0 H
LSSource inductanceInductance0 H
LDDrain inductanceInductance0 H
CDSSFixed Drain-source capacitanceCapacitance0 F
AFACGate-width scale factorNone1
NFINGNumber of gate f i ngers scale factorNone1
TNOMNominal Temperature (Not implemented)Temperature300 K
TEMPTemperatureTemperature300 K


Chapter 10

MESFETs

10.1MESFETs

General form:

ZXXXXXXX ND NG NS MNAME <AREA> <OFF> <IC=VDS, VGS>

Examples:

Z1 7 2 3 ZM1 OFF

10.2MESFET Models (NMF/PMF)

10.2.1Model by Statz e.a.

The MESFET model level 1 is derived from the GaAs FET model of Statz et al. as described in
[11]. The dc characteristics are def i ned by the parameters VTO, B, and BETA, which determine
the variation of drain current with gate voltage, ALPHA, which determines saturation voltage,
and LAMBDA, which determines the output conductance. The formula are given by:

Id=











B(Vgs−VT)2
1+b(Vgs−VT)

?

?

?

?1−

?

?

?1−AVds

3

?

?

?

3??

?

?(1+LVds)

for 0 <Vds<

3
A

B(Vgs−VT)2
1+b(Vgs−VT)(1+LVds)

forV >

3
A

(10.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 def i ned by the parameters cgs, cgd,
and pb.

125


126CHAPTER 10. MESFETS

NameParameterUnitsDefaultExampleArea
VTOPinch-off voltageV-2.0-2.0
BETATransconductance parameter

A/V2

1.0e-41.0e-3*
BDoping tail extending parameter

1/V

0.30.3*
ALPHASaturation voltage parameter

1/V

22*
LAMBDAChannel-length modulation parameter

1/V

01.0e-4
RDDrain ohmic resistanceΩ0100*
RSSource ohmic resistanceΩ0100*
CGSZero-bias G-S junction capacitanceF05pF*
CGDZero-bias G-D junction capacitanceF01pF*
PBGate junction potentialV10.6
KFFlicker noise coeff i cient-0
AFFlicker noise exponent-1
FCCoeff i cient for forward-bias depletion
capacitance formula

-0.5

Device instance:

z1 2 3 0 mesmod area =1.4

Model:

. model mesmod nmflevel =1 rd=46rs =46 vt0=−1.3
+ lambda =0.03alpha=3 beta =1.4e−3

10.2.2Model by Ytterdal e.a.

level 2 (and levels 3,4) Copyright 1993: T. Ytterdal, K. Lee, M. Shur and T. A. Fjeldly

to be written

M. Shur, T.A. Fjeldly, T. Ytterdal, K. Lee, "Unif i ed GaAs MESFET Model for Circuit Simula-
tion", Int. Journal of High Speed Electronics, vol. 3, no. 2, pp. 201-233, 1992

10.2.3hfet1

level 5

to be written

no documentation available

10.2.4hfet2

level6

to be written

no documentation available


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 Insula-
tor) 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).

11.1MOSFET devices

General form:

MXXXXXXX nd ng ns nb mname <m=val > <l=val > <w=val >
+ <ad=val > <as=val > <pd=val > <ps=val > <nrd=val >
+ <nrs=val > <off > <ic=vds ,vgs ,vbs> <temp=t >

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 suff i xes in the example: the suff i x “u” specif i es microns (1e-6 m) and “p” sq-microns
(1e-12 m2).

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 parameter. Instance parameters l and w, channel length and width respectively,
are expressed in meters. The areas of drain and source diffusions: ad and as, in squared meters
(m2).

If any of l, w, ad, or as are not specif i ed, default values are used. The use of defaults simplif i es
input f i le 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 specif i ed 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

127


128CHAPTER 11. MOSFETS

and nrs to 1.0. off indicates an (optional) initial condition on the device for dc analysis. The
(optional) initial condition specif i cation 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
thanthequiescentoperatingpoint. Seethe.iccontrollineforabetterandmoreconvenientway
to specify transient initial conditions. The (optional) temp value is the temperature at which this
device is to operate, and overrides the temperature specif i cation on the .option control line.

The temperature specif i cation is ONLY valid for level 1, 2, 3, and 6 MOSFETs, not for level 4
or 5 (BSIM) devices.

BSIM3.2 version is also supporting the instance parameter delvto and mulu0 for local mis-
match and NBTI (negative bias temperature instability) modeling:

NameParameterUnitsDefaultExample
delvtoThreshold voltage shiftV0.00.07
mulu0Low-f i eld mobility multiplier (U0)-1.00.9

11.2MOSFET models (NMOS/PMOS)

MOSFET models are the central part of ngspice, probably because they are the most widely
used devices in the electronics world. Ngspice provides all the MOSFETs implemented in the
original Spice3f and adds several models developed by UC Berkeley’s Device Group and other
independent groups.

Each model is invoked with a .model card. A minimal version is:

.model MOSN NMOS level=8 version=3.3.0

The model name MOSN corresponds to the model name in the instance card (see 11.1). Pa-
rameter NMOS selects an n-channel device, PMOS would point to a p-channel transistor. The
level and version parameters select the specif i c model. Further model parameters are op-
tional 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 f i les and loaded into the netlist by
the .include (2.6) command. Model cards are specif i c for a an IC manufacturing process and
are typically provided by the IC foundry. Some generic parameter sets, not linked to a specif i c
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.9, down to channel length of 0.35 µm), BSIM4 (11.2.10,
below 0.35 µ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).

11.2.1MOS Level 1

This model is also known as the “Shichman-Hodges” model. This is the f i rst model written and
the one often described in the introductory textbooks for electronics. This model is applicable
only to long channel devices. The use of Meyer’s model for the C-V part makes it non charge
conserving.


11.2. MOSFET MODELS (NMOS/PMOS)129

LevelNameModelVersionDeveloperReferencesNotes
1MOS1Shichman-Hodges-BerkeleyThis is the classical quadratic model.
2MOS2Grove-Frhoman-BerkeleyDescribed in [2]
3MOS3BerkeleyA semi-empirical model (see [1])
4BSIM1BerkeleyDescribed in [3]
5BSIM2BerkeleyDescribed in [5]
6MOS6BerkeleyDescribed in [2]
9MOS9Alan Gillespie
8, 49BSIM3v03.0Berkeleyextensions by Alan Gillespie
8, 49BSIM3v13.1Berkeleyextensions by Serban Popescu
8, 49BSIM3v323.2 - 3.2.4BerkeleyMulti version code
8, 49BSIM33.3.0BerkeleyDescribed in [13]
10, 58B4SOI4.3.1Berkeley
14, 54BSIM4v44.0 - 4.4BerkeleyMulti version code
14, 54BSIM4v54.5.0Berkeley
14, 54BSIM4v64.6.5Berkeley
14, 54BSIM44.7.0Berkeley
44EKVEPFLadms conf i gured
45PSP1.0.2Gildenblattadms conf i gured
55B3SOIFDBerkeley
56B3SOIDDBerkeley
57B3SOIPDBerkeley
60STAGSOI3Southampton
61, 68HiSIM22.7.0Hiroshima
62, 73HiSIM_HV1.2.2HiroshimaHigh Voltage Version for LDMOS

Table 11.1: MOSFET model summary


130CHAPTER 11. MOSFETS

11.2.2MOS Level 2

This model tries to overcome the limitations of the Level 1 model addressing several short-
channel effects, like velocity saturation. The implementation of this model is complicated and
this leads to many convergence problems. C-V calculations can be done with the original Meyer
model (non charge conserving).

11.2.3MOS Level 3

This is a semi-empirical model derived from the Level 2 model. In the 80s this model has often
been used for digital design and, over the years, has proved to be robust. A discontinuity in the
model with respect to the KAPPA parameter has been detected (see [10]). The supplied f i x has
been implemented in Spice3f2 and later. Since this f i x may affect parameter f i tting, the option
“badmos3“ may be set to use the old implementation (see the section on simulation variables
and the “.options” line). Ngspice level 3 implementation takes into account length and width
mask adjustments (xl and xw) and device width narrowing due to diffusion (wd).

11.2.4MOS Level 6

This model is described in [2]. The model can express the current characteristics of short-
channelMOSFETsatleastdownto0. 25 µmchannel-length, GaAsFET,andresistanceinserted
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.

11.2.5Notes on Level 1-6 models

The dc characteristics of the level 1 through level 3 MOSFETs are def i ned by the device param-
eters vto, kp, lambda, phi and gamma. These parameters are computed by ngspice if process
parameters (nsub, tox, ...) are given, but users specif i ed values always override. vto is pos-
itive (negative) for enhancement mode and negative (positive) for depletion mode N-channel
(P-channel) devices.

Charge storage is modeled by three constant capacitors, cgso, cgdo, and cgbo which represent
overlap capacitances, by the nonlinear thin-oxide capacitance which 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 differ-
ent for the level 1 model. These voltage-dependent capacitances are included only if tox is
specif i ed in the input description and they are represented using Meyer’s formulation.

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 (inA/m2). Whereas the f i rst is an absolute value the


11.2. MOSFET MODELS (NMOS/PMOS)131

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 charac-
teristics 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
F/m2) 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.

NGSPICE level 1, 2, 3 and 6 parameters

NameParameterUnitsDefaultExample
LEVELModel index-1
VTOZero-bias threshold voltage
(VT0)

V0.01.0

KPTransconductance
parameter

A/V2

2.0e-53.1e-5

GAMMABulk threshold parameter

√V

0.00.37
PHISurface potential (U)V0.60.65
LAMBDAChannel length modulation
(MOS1 and MOS2 only)
(λ)

1/V

0.00.02

RDDrain ohmic resistanceΩ0.01.0
RSSource ohmic resistanceΩ0.01.0
CBDZero-bias B-D junction
capacitance

F0.020fF

CBSZero-bias B-S junction
capacitance

F0.020fF

ISBulk junction saturation
current (IS)

A1.0e-141.0e-15

PBBulk junction potentialV0.80.87
CGSOGate-source overlap
capacitance per meter
channel width

F/m

0.04.0e-11

CGDOGate-drain overlap
capacitance per meter
channel width

F/m

0.04.0e-11

CGBOGate-bulk overlap
capacitance per meter
channel width

F/m

0.02.0e-11

RSHDrain and source diffusion
sheet resistance

Ω/?

0.010


132CHAPTER 11. MOSFETS

NameParameterUnitsDefaultExample
CJZero-bias bulk junction
bottom cap. per sq-meter of
junction area

F/m2

0.02.0e-4

MJBulk junction bottom
grading coeff.

-0.50.5

CJSWZero-bias bulk junction
sidewall cap. per meter of
junction perimeter

F/m

0.01.0e-9

MJSWBulk junction sidewall
grading coeff.

-

0.50(level1)
0.33(level2,3)

JSBulk junction saturation
current
TOXOxide thicknessm1.0e-71.0e-7
NSUBSubstrate dopingcm−30.04.0e15
NSSSurface state densitycm−20.01.0e10
NFSFast surface state densitycm−20.01.0e10
TPGType of gate material: +1
opp. to substrate, -1 same as
substrate, 0 Al gate

-1.0

XJMetallurgical junction depthm0.01M
LDLateral diffusionm0.00.8M
UOSurface mobility

cm2/V·sec

600700
UCRITCritical f i eld for mobility
degradation (MOS2 only)

V/cm

1.0e41.0e4

UEXPCritical f i eld exponent in
mobility degradation
(MOS2 only)

-0.00.1

UTRATransverse f i eld coeff.
(mobility) (deleted for
MOS2)

-0.00.3

VMAXMaximum drift velocity of
carriers

m/s

0.05.0e4

NEFFTotal channel-charge (f i xed
and mobile) coeff i cient
(MOS2 only)

-1.05.0

KFFlicker noise coeff i cient-0.01.0e-26
AFFlicker noise exponent-1.01.2
FCCoeff i cient for forward-bias
depletion capacitance
formula

-0.5

DELTAWidth effect on threshold
voltage (MOS2 and MOS3)

-0.01.0

THETAMobility modulation
(MOS3 only)

1/V

0.00.1

ETAStatic feedback (MOS3
only)

-0.01.0


11.2. MOSFET MODELS (NMOS/PMOS)133

NameParameterUnitsDefaultExample
KAPPASaturation f i eld factor
(MOS3 only)

-0.20.5

TNOMParameter measurement
temperature

◦C

2750

11.2.6BSIM Models

Ngspice implements many of the BSIM models developed by Berkeley’s BSIM group. BSIM
stands for Berkeley Short-Channel IGFET Model and groups a class of models that is continu-
ously updated. In general, all parameters of BSIM models are obtained from process character-
ization, in particular level 4 and level 5 (BSIM1 and BSIM2) parameters are can be generated
automatically. J. Pierret [4] describes a means of generating a “process” f i le, and the program
ngproc2mod provided with ngspice converts this f i le into a sequence of BSIM1 ”.model” lines
suitable for inclusion in an ngspice input f i le.

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

P = P0+

PL
Leffective

+

PW
Weffective

(11.1)

is used to evaluate the parameter for the actual device specif i ed with

Leffective= Linput−DL(11.2)

Weffective=Winput−DW(11.3)

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 f i le, see the SPICE2 implementation notes[3]. For more information
on BSIM2, see reference [5]. BSIM3 (11.2.9) and BSIM4 (11.2.10) represent state of the art
for submicron and deep submicron IC design.

11.2.7BSIM1 model (level 4)

BSIM1 model (the f i rst is a long series) is an empirical model. Developers placed less empha-
sis on device physics and based the model on parametrical polynomial equations to model the
various physical effects. This approach pays in terms of circuit simulation behavior but the ac-
curacy degrades in the submicron region. A known problem of this model is the negative output
conductance and the convergence problems, both related to poor behavior of the polynomial
equations.


134CHAPTER 11. MOSFETS

Ngspice BSIM (level 4) parameters


11.2. MOSFET MODELS (NMOS/PMOS)135

NameParameterUnitsl/w
VFBFlat-band voltageV*
PHISurface inversion potentialV*
K1Body effect coeff i cient

√V

*
K2Drain/source depletion charge-sharing
coeff i cient

-*

ETAZero-bias drain-induced barrier-lowering
coeff i cient

-*

MUZZero-bias mobility

cm2/V·sec
DLShortening of channelµm
DWNarrowing of channelµm
U0Zero-bias transverse-f i eld mobility degradation
coeff i cient

1/V

*

U1Zero-bias velocity saturation coeff i cient

µ/V

*
X2MZSens. of mobility to substrate bias at v=0

cm2/V2·sec

*
X2ESens. of drain-induced barrier lowering effect
to substrate bias

1/V

*

X3ESens. of drain-induced barrier lowering effect
to drain bias atVds=Vdd

1/V

*

X2U0Sens. of transverse f i eld mobility degradation
effect to substrate bias

1/V2

*

X2U1Sens. of velocity saturation effect to substrate
bias

µm/V2

*

MUSMobility at zero substrate bias and atVds=Vdd

cm2/V2sec
X2MSSens. of mobility to substrate bias atVds=Vdd

cm2/V2sec

*
X3MSSens. of mobility to drain bias atVds=Vdd

cm2/V2sec

*
X3U1Sens. of velocity saturation effect on drain bias
at Vds=Vdd

µm/V2

*

TOXGate oxide thicknessµm
TEMPTemperature at which parameters were
measured

◦C

VDDMeasurement bias rangeV
CGDOGate-drain overlap capacitance per meter
channel width

F/m

CGSOGate-source overlap capacitance per meter
channel width

F/m

CGBOGate-bulk overlap capacitance per meter
channel length

F/m

XPARTGate-oxide capacitance-charge model f l ag-
N0Zero-bias subthreshold slope coeff i cient-*
NBSens. of subthreshold slope to substrate bias-*
NDSens. of subthreshold slope to drain bias-*
RSHDrain and source diffusion sheet resistance

Ω/?
JSSource drain junction current density

A/m2
PBBuilt in potential of source drain junctionV
MJGrading coeff i cient of source drain junction-


136CHAPTER 11. MOSFETS

NameParameterUnitsl/w
PBSWBuilt in potential of source, drain junction
sidewall

V

MJSWGrading coeff i cient of source drain junction
sidewall

-

CJSource drain junction capacitance per unit area

F/m2
CJSWsource drain junction sidewall capacitance per
unit length

F/m

WDFSource drain junction default widthm
DELLSource drain junction length reductionm

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 specif i cation, 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.

11.2.8BSIM2 model (level 5)

This model contains many improvements over BSIM1 and is suitable for analog simulation.
Nevertheless, even BSIM2 breaks transistor operation into several distinct regions and this leads
to discontinuities in the f i rst derivative in C-V and I-V characteristics that can cause numerical
problems during simulation.

11.2.9BSIM3 model (levels 8, 49)

BSIM3 solves the numerical problems of previous models with the introduction of smoothing
functions. It adopts a single equation to describe device characteristics in the operating regions.
This approach eliminates the discontinuities in the I-V and C-V characteristics. The origi-
nal model, BSIM3 evolved through three versions: BSIM3v1, BSIM3v2 and BSIM3v3. Both
BSIM3v1 and BSIM3v2 had suffered from many mathematical problems and were replaced by
BSIM3v3. The latter is the only surviving release and has itself a long revision history

The following table summarizes the story of this model:

ReleaseDateNotesVersion f l ag
BSIM3v3.010/30/19953.0
BSIM3v3.112/09/19963.1
BSIM3v3.206/16/1998Revisions available: BSIM3v3.2.2,
BSIM3v3.2.3, and BSIM3v3.2.4

3.2, 3.2.2,
3.2.3, 3.2.4
BSIM3v3.307/29/2005Parallel processing with OpenMP is available
for this model.

3.3.0

BSIM3v2 and 3v3 models has proved for accurate use in 0.18 µm technologies. The model is
publicly available as source code form from University of California, Berkeley.


11.2. MOSFET MODELS (NMOS/PMOS)137

A detailed description is given in the user’s manual available from here .

We recommend that you use only the most recent BSIM3 model (version 3.3.0), because it
contains corrections to all known bugs. To achieve that, change the version parameter in your
modelcard f i les to

VERSION = 3.3.0.

If no version number is given in the .model card, this (newest) version is selected as the default.
The older models will not be supported, they are made available for reference only.

11.2.10BSIM4 model (levels 14, 54)

This is the newest class of the BSIM family and introduces noise modeling and extrinsic para-
sitics. BSIM4, as the extension of BSIM3 model, addresses the MOSFET physical effects into
sub-100nm regime. It is a physics-based, accurate, scalable, robust and predictive MOSFET
SPICE model for circuit simulation and CMOS technology development. It is developed by
the BSIM Research Group in the Department of Electrical Engineering and Computer Sciences
(EECS) at the University of California, Berkeley (see BSIM4 home page). BSIM4 has a long
revision history, which is summarized below.

ReleaseDateNotesVersion f l ag
BSIM4.0.003/24/2000
BSIM4.1.010/11/2000
BSIM4.2.004/06/2001
BSIM4.2.110/05/2001*4.2.1
BSIM4.3.005/09/2003*4.3.0
BSIM4.4.003/04/2004*4.4.0
BSIM4.5.007/29/2005*4.5.0
BSIM4.6.012/13/2006
...
BSIM4.6.509/09/2009* **4.6.5
BSIM4.7.004/08/2011* **4.7

*) supported in ngspice, using e.g. the version=<version flag> f l ag in the parameter f i le.

**) 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.7.0), because it
contains corrections to all known bugs. To achieve that, change the version parameter in your
modelcard f i les to

VERSION = 4.7.

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.

11.2.11EKV model

Level 44 model (EKV) is not available in the standard distribution since it is not released in
source form by the EKV group. To obtain the code please refer to the (EKV model home page,


138CHAPTER 11. MOSFETS

EKV group home page). A verilog-A version is available contributed by Ivan Riis Nielsen
11/2006.

11.2.12BSIMSOI models (levels 10, 58, 55, 56, 57)

BSIMSOI is a SPICE compact model for SOI (Silicon-On-Insulator) circuit design, created by
University of California at Berkeley . This model is formulated on top of the BSIM3 frame-
work. It shares the same basic equations with the bulk model so that the physical nature and
smoothness of BSIM3v3 are retained. Four models are supported in ngspice, those based on
BSIM3 and modeling fully depleted (FD, level 55), partially depleted (PD, level 57) and both
(DD, level 56), as well as the modern BSIMSOI version 4 model (levels 10, 58). Detailed de-
scriptions are beyond the scope of this manual, but see e.g. BSIMSOIv4.4 User Manual for a
very extensive description of the recent model version. OpenMP support is available for levels
10, 58, version 4.4.

11.2.13SOI3 model (level 60)

see literature citation [18] for a description.

11.2.14HiSIM models of the University of Hiroshima

There are two model implementations available - see also HiSIM Research Center:

1. HiSIM2 model: Surface-Potential-Based MOSFET Model for Circuit Simulation version
2.7.0 - level 61 & 68 (see link to HiSIM2 for source code and manual).

2. HiSIM_HV model: Surface-Potential-Based HV/LD-MOSFET Model for Circuit Simu-
lation version 1.2.2 - level 62 & 73 (see link to HiSIM_HV for source code and manual).


Chapter 12

Mixed-Mode and Behavioral Modeling
with XSPICE

Ngspice implements XSPICE extensions for behavioral and mixed-mode (analog and digital)
modeling. In the XSPICE framework this is referred to as code level modeling. Behavioral
modeling may benef i t dramatically because XSPICE offers a means to add analog functionality
programmed in C. Many examples (amplif i ers, oscillators, f i lters ...) are presented in the follow-
ing. Even more f l exibility is available because you may def i ne your own models and use them
in addition and in combination with all the already existing ngspice functionality. Mixed mode
simulation is speeded up signif i cantly by simulating the digital part in an event driven manner,
in that state equations use only a few allowed states and are evaluated only during switching,
and not continuously in time and signal as in a pure analog simulator.

This chapter describes the predef i ned models available in ngspice, stemming from the original
XSPICE simulator. The instructions for writing new code models are given in chapter 28.

To make use of the XSPICE extensions, you need to compile them in. LINUX, CYGWIN,
MINGW and other users may add the f l ag --enable-xspice to their ./configure command
and then recompile. The prebuilt ngspice for Windows distribution has XSPICE already en-
abled. For detailed compiling instructions see chapter 32.1.

12.1Code Model Element & .MODEL Cards

12.1.1Syntax

Ngspice includes a library of predef i ned “Code Models” that can be placed within any circuit
description in a manner similar to that used to place standard device models. Code model
instance cards always begin with the letter “A”, and always make use of a .MODEL card to
describe the code model desired. Section 28 of this document goes into greater detail as to how
a code model similar to the predef i ned models may be developed, but once any model is created
and linked into the simulator it may be placed using one instance card and one .MODEL card
(note here we conform to the SPICE custom of referring to a single logical line of information
as a “card”). As an example, the following uses the predef i ned “gain” code model which takes
as an input some value on node 1, multiplies it by a gain of 5.0, and outputs the new value to
node 2. Note that, by convention, input ports are specif i ed f i rst on code models. Output ports
follow the inputs.

139


140CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Example:

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
Specif i cation File for this code model (i.e., gain), the default port type is specif i ed as a voltage
(more on this later). However, if you didn’t know this, the following modif i cations to the
instance card could be used to insure it:

Example:

a1 %v(1) %v(2) amp
.model amp gain(gain=5.0)

The specif i cation "%v" preceding the input and output node numbers of the instance card indi-
cate 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 which specif i es gain=5.0. This portion of the
card assigns a value to a parameter of the "gain" model. There are other parameters which 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 which def i ne a code model will
follow the abstract form described below. This form illustrates that the number of inputs and
outputsandthenumberofparameterswhichcanbespecif i edisrelativelyopen-endedandcanbe
interpreted in a variety of ways (note that angle-brackets “<” and “>” enclose optional inputs):

Example:

AXXXXXXX<%v,%i,%vd,%id,%g,%gd,%h,%hd, or %d>
+ <[> <~><%v,%i,%vd,%id,%g,%gd,%h,%hd, or %d>
+ <NIN1 or +NIN1 -NIN1 or "null">
+<~>...<NIN2.. <]> >
+ <%v,%i,%vd,%id,%g,%gd,%h,%hd,%d or %vnam>
+ <[> <~><%v,%i,%vd,%id,%g,%gd,%h,%hd,
or %d><NOUT1 or +NOUT1 -NOUT1>
+<~>...<NOUT2.. <]>>
+ MODELNAME

.MODEL MODELNAMEMODELTYPE
+ <( PARAMNAME1= <[> VAL1 <VAL2... <]>> PARAMNAME2..>)>


12.1. CODE MODEL ELEMENT & .MODEL CARDS141

Square brackets ([ ]) are used to enclose vector input nodes. In addition, these brackets are used
to delineate vectors of parameters.

Theliteralstring“null”, whenincludedinanodelist, isinterpretedasnoconnectionatthatinput
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, specif i es 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 def i nes 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.

The symbols described in Table 12.1 may be omitted if the default port type for the model is
desired. Note that non-default port types for multi-input or multi-output (vector) ports must be
specif i ed by placing one of the symbols in front of EACH vector port. On the other hand, if all
ports of a vector port are to be declared as having the same non-default type, then a symbol may
be specif i ed immediately prior to the opening bracket of the vector. The following examples
should make this clear:

Example 1: - Specifies two differential voltage connections, one
to nodes 1 & 2, and one to nodes 3 & 4.

%vd [1 2 3 4]

Example 2: - Specifies two single-ended connections to node 1 and
at node 2, and one differential connection to
nodes 3 & 4.

%v [1 2 %vd 3 4]

Example 3: - Identical to the previous example...parenthesis
are added for additional clarity.

%v [1 2 %vd(3 4)]

Example 4: - Specifies that the node numbers are to be treated in the
default fashion for the particular model.
If this model had “%v” as a default for this
port, then this notation would represent four single-ended
voltage connections.

[1 2 3 4]


142CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Port Type Modif i ers
Modif i erInterpretation
%vrepresents a single-ended voltage port - one node name or number is expected
for each port.
%irepresents a single-ended current port - one node name or number is expected
for each port.
%grepresents a single-ended voltage-input, current-output (VCCS) port - one
node name or number is expected for each port. This type of port is auto-
matically an input/output.
%hrepresents a single-ended current-input, voltage-output (CCVS) port - one
node name or number is expected for each port. This type of port is auto-
matically an input/output.
%drepresents a digital port - one node name or number is expected for each port.
This type of port may be either an input or an output.
%vnamrepresents the name of a voltage source, the current through which is taken as
an input. This notation is provided primarily in order to allow models def i ned
using SPICE2G6 syntax to operate properly in XSPICE.
%vdrepresents a differential voltage port - two node names or numbers are ex-
pected for each port.
%idrepresents a differential current port - two node names or numbers are ex-
pected for each port.
%gdrepresentsadifferentialVCCSport-twonodenamesornumbersareexpected
for each port.
%hdrepresentsadifferentialCCVSport-twonodenamesornumbersareexpected
for each port.

Table 12.1: Port Type Modif i ers


12.1. CODE MODEL ELEMENT & .MODEL CARDS143

The parameter names listed on the .MODEL card must be identical to those named in the code
model itself. The parameters for each predef i ned 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-def i ned models are described in Chapter 28.

12.1.2Examples

The following is a list of instance card and associated .MODEL card examples showing use of
predef i ned 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)
a21 %i[1 %vd(2 5) 7 10] 3 sum2
.model sum2 summer(out_gain=10.0)
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_domain=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)

12.1.3Search path for f i le input

Several code models (f i lesource 12.2.8, d_source 12.4.21, d_state 12.4.18) call additional f i les
for supply of input data. A call to file="path/filename" (or input_f i le=, state_f i le=) in the
.model card will start a search sequence for f i nding the f i le.path may be an absolute path. If
path is omitted or is a relative path, filename is looked for according to the following search
list:

Infile_Path/<path/filename> (Inf i le_Path is the path of the input f i le *.sp containing the
netlist)

NGSPICE_INPUT_DIR/<path/filename> (where an additional path is set by the environmen-
tal variable)

<path/filename> (where the search is relativ to the current directory (OS dependant))


144CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

12.2Analog Models

The following analog models are supplied with XSPICE. The descriptions included consist
of the model Interface Specif i cation File and a description of the model’s operation. This is
followed by an example of a simulator-deck placement of the model, including the .MODEL
card and the specif i cation of all available parameters.

12.2.1Gain

NAME_TABLE:
C_Function_Name:cm_gain
Spice_Model_Name:gain
Description:"A simplegainblock"

PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id,vnam][v,vd,i,id]
Vector:nono
Vector.Bounds:--
Null.Allowed:nono

PARAMETER_TABLE:
Parameter_Name:in_offsetgainout_offset
Description:"inputoffset""gain""outputoffset"
Data_Type:realrealreal
Default_Value:0.01.00.0
Limits:---
Vector:nonono
Vector_Bounds:---
Null_Allowed:yesyesyes

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. ANALOG MODELS145

12.2.2Summer

NAME_TABLE:
C_Function_Name:cm_summer
Spice_Model_Name:summer
Description:"A summer block"

PORT_TABLE:
Port Name:inout
Description:"input vector""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id,vnam][v,vd,i,id]
Vector:yesno
Vector_Bounds:--
Null_Allowed:nono

PARAMETER_TABLE:
Parameter_Name:in_offsetin_gain
Description:"input offset vector""input gain vector"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:yesyes
Vector_Bounds:inin
Null_Allowed:yesyes

PARAMETER_TABLE:
Parameter_Name:out_gainout_offset
Description:"output gain""output offset"
Data_Type:realreal
Default_Value:1.00.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

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)


146CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

12.2.3Multiplier

NAME_TABLE:
C_Function_Name:cm_mult
Spice_Model_Name:mult
Description:"multiplier block"
PORT_TABLE:
Port_Name:inout
Description:"input vector""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id,vnam][v,vd,i,id]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_offsetin_gain
Description:"input offset vector""input gain vector"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:yesyes
Vector_Bounds:inin
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:out_gainout_offset
Description:"output gain""output offset"
Data_Type:realreal
Default_Value:1.00.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

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 which bears
an AC signal (this is exemplif i ed by the use of a multiplier to perform a potentiometer
function: one input is DC, the other carries the AC signal).


12.2. ANALOG MODELS147

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.4Divider

NAME_TABLE:
C_Function_Name:cm_divide
Spice_Model_Name:divide
Description:"divider block"
PORT_TABLE:
Port_Name:numdenout
Description:"numerator""denominator""output"
Direction:ininout
Default_Type:vvv
Allowed_Types:[v,vd,i,id,vnam][v,vd,i,id,vnam][v,vd,i,id]
Vector:nonono
Vector_Bounds:---
Null_Allowed:nonono
PARAMETER_TABLE:
Parameter_Name:num_offsetnum_gain
Description:"numerator offset""numerator gain"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:den_offsetden_gain
Description:"denominator offset""denominator gain"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:den_lower_limit
Description:"denominator lower limit"
Data_Type:real
Default_Value:1.0e-10
Limits:-
Vector:no


148CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

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_gainout_offset
Description:"output gain""output offset"
Data_Type:realreal
Default_Value:1.00.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

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 specif i ed lower limit. This limit is
approached through a quadratic smoothing function, the domain of which may be spec-
if i ed 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 im-
portant to remember that results are invalid unless only ONE INPUT of the divider is
connected to a node which bears an AC signal (this is exemplif i ed by the use of the di-
vider 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. ANALOG MODELS149

12.2.5Limiter

NAME_TABLE:
C_Function_Name:cm_limit
Spice_Model_Name:limit
Description:"limit block"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_offsetgain
Description:"input offset""gain"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:out_lower_limitout_upper_limit
Description:"output lower limit""output upper limit"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
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


150CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

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 specif i ed 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 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 volts,
the output will begin to smooth out at ±0.9 volts, which occurs when the input value is at
±0.4.

Example SPICE Usage:
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)

12.2.6Controlled Limiter

NAME_TABLE:
C_Function_Name:cm_climit
Spice_Model_Name:climit
Description:"controlled limiter block"
PORT_TABLE:
Port_Name:incntl_upper
Description:"input""upper lim. control input"
Direction:inin
Default_Type:vv
Allowed_Types:[v,vd,i,id,vnam][v,vd,i,id,vnam]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PORT_TABLE:
Port_Name:cntl_lowerout
Description:"lower limit control input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id,vnam][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_offsetgain
Description:"input offset""gain"
Data_Type:realreal
Default_Value:0.01.0
Limits:--


12.2. ANALOG MODELS151

Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:upper_deltalower_delta
Description:"output upper delta""output lower delta"
Data_Type:realreal
Default_Value:0.00.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:limit_rangefraction
Description:"upper & lower sm. range""smoothing %/abs switch"
Data_Type:realboolean
Default_Value:1.0e-6FALSE
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: TheControlledLimiterisasingleinput, singleoutputfunctionsimilartotheGain
Block. However, the output of the Limiter function is restricted to the range specif i ed by
the output lower and upper limits. This model will operate in DC, AC, and Transient anal-
ysis modes. Note that the limit range is the value BELOW THE CNTL_UPPER LIMIT
AND ABOVE THE CNTL_LOWER LIMIT at which smoothing of the output begins
(minimum positive value of voltage must exist between the CNTL_UPPER input and the
CNTL_LOWER input at all times). For this model, then, the limit range 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 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 code tests the input values of cntl_lower and cntl_upper to make
sure that they are spaced far enough apart to guarantee the existence of a linear range be-
tween them. The range is calculated as the difference between (cntl_upper - upper_delta
- limit_range) and (cntl_lower + lower_delta + limit_range) and must be greater than or
equal to zero. Note that when the limit range is specif i ed as a fractional value, the limit
range used in the above is taken as the calculated fraction of the difference between cntl
upper and cntl lower. Still, the potential exists for too great a limit range value to be
specif i ed 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)


152CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

12.2.7PWL Controlled Source

NAME_TABLE:
C_Function_Name:cm_pwl
Spice_Model_Name:pwl
Description:"piecewise linear controlled source"
PORT_TABLE:
Port_Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id,vnam][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:x_arrayy_array
Description:"x-element array""y-element array"
Data_Type:realreal
Default_Value:--
Limits:--
Vector:yesyes
Vector_Bounds:[2 -][2 -]
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:input_domainfraction
Description:"input sm. domain""smoothing %/abs switch"
Data_Type:realboolean
Default_Value:0.01TRUE
Limits:[1e-12 0.5]-
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
STATIC_VAR_TABLE:
Static_Var_Name:last_x_value
Data_Type:pointer Description:"iteration holding
variable for limiting"

Description: The Piece-Wise Linear Controlled Source is a single input, single output func-
tion 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 specif i ed 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 specif i ed, or as many as memory and simulation
speed allow. This permits you to very f i nely approximate a non-linear function by captur-
ing multiple input-output coordinate points.
Two aspects of the PWL Controlled Source warrant special attention. These are the han-


12.2. ANALOG MODELS153

dling 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-
specif i ed 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 neces-
sary. This is due to the iterative nature of the simulator and its reliance on smooth f i rst
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 specif i ed input domain value is to be interpreted as a frac-
tional f i gure. 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 co-
ordinate 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 specif i c
segment length chosen will be the smallest of these two for each coordinate point.
On the other hand, if fraction=FALSE and input=0.10, then the simulator will begin
smoothing the transfer function at 0.10 volts (or amperes) below each x_array coordi-
nate 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 specif i ed input domain value is not ex-
cessive.
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 func-
tions 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 specif i ed (fraction=TRUE, input do-
main=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 f i nd that rounding occurs be-
tween 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 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)


154CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

12.2.8Filesource

NAME_TABLE:
C_Function_Name:cm_filesource
Spice_Model_Name:filesource
Description:"File Source"
PORT_TABLE:
Port_Name:out
Description:"output"
Direction:out
Default_Type:v
Allowed_Types:[v,vd,i,id]
Vector:yes
Vector_Bounds:[1 -]
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:timeoffsettimescale
Description:"time offset""timescale"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:timerelativeamplstep
Description:"relative time""step amplitude"
Data_Type:booleanboolean
Default_Value:FALSEFALSE
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:amploffsetamplscale
Description:"ampl offset""amplscale"
Data_Type:realreal
Default_Value:--
Limits:--
Vector:yesyes
Vector_Bounds:[1 -][1 -]
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:file
Description:"file name"
Data_Type:string
Default_Value:"filesource.txt"
Limits:-
Vector:no


12.2. ANALOG MODELS155

Vector_Bounds:-
Null_Allowed:yes

Description: The File Source is similar to the Piece-Wise Linear Source, except that the wave-
form data is read from a f i le instead of being taken from parameter vectors.
The f i le 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 f i rst 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 f i le named by the parameter filename in file="filename" is sought after accord-
ing 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)

Example input file:
# name: sine.m
# two output ports
# column 1: time
# columns 2, 3: values
0 0 1
3.90625e-09 0.02454122852291229 0.9996988186962042
7.8125e-09 0.04906767432741801 0.9987954562051724
1.171875e-08 0.07356456359966743 0.9972904566786902
...

12.2.9multi_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:


156CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Port_Name:inout
Description:"input array""output"
Direction:inout
Default_Type:vdvd
Allowed_Types:[vd,id][vd,id]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:xy
Description:"x array""y array"
Data_Type:realreal
Default_Value:0.00.0
Limits:--
Vector:yesyes
Vector_Bounds:[2 -][2 -]
Null_Allowed:nono
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). Only one input determines the state of the outputs, seleczable by the parameter
model. and: the smallest value of all the inputs is chosen as the controlling input and
determines the output value, or: the smallest value of all the inputs is chosen as the
controlling input and determines the output value.

Example SPICE Usage:
a82 [1 0 2 0 3 0] 7 0 pwlm
.
.
.model pwlm multi_input_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]
+model="and")

12.2.10Analog Switch

NAME_TABLE:
C_Function_Name:cm_aswitch
Spice_Model_Name:aswitch
Description:"analog switch"


12.2. ANALOG MODELS157

PORT_TABLE:
Port Name:cntl_inout
Description:"input""resistive output"
Direction:inout
Default_Type:vgd
Allowed_Types:[v,vd,i,id][gd]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:cntl_offcntl_on
Description:"control ‘off’ value" "control ‘on’ value"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:r_offlog
Description:"off resistance""log/linear switch"
Data_Type:realboolean
Default_Value:1.0e12TRUE
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:r_on
Description:"on resistance"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The Analog Switch is a resistor that varies either logarithmically or linearly be-
tween specif i ed values of a controlling input voltage or current. Note that the input is
not internally limited. Therefore, if the controlling signal exceeds the specif i ed 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 de-
pendence). 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.

Example SPICE Usage:
a8 3 (6 7) switch3


158CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

.
.
.model switch3 aswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e6
+r_on=10.0 log=TRUE)

12.2.11Zener Diode

NAME_TABLE:
C_Function_Name:cm_zener
Spice_Model_Name:zener
Description:"zener diode"
PORT_TABLE:
Port Name:z
Description:"zener"
Direction:inout
Default_Type:gd
Allowed_Types:[gd]
Vector:no
Vector_Bounds:-
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:v_breakdowni_breakdown
Description:"breakdown voltage""breakdown current"
Data_Type:realreal
Default_Value:-2.0e-2
Limits:[1.0e-6 1.0e6][1.0e-9 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:noyes
PARAMETER_TABLE:
Parameter_Name:i_satn_forward
Description:"saturation current""forward emission coefficient"
Data_Type:realreal
Default_Value:1.0e-121.0
Limits:[1.0e-15 -][0.1 10]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:limit_switch
Description:"switch for on-board limiting (convergence aid)"
Data_Type:boolean
Default_Value:FALSE
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
STATIC_VAR_TABLE:


12.2. ANALOG MODELS159

Static_Var_Name:previous_voltage
Data_Type:pointer
Description:"iteration holding variable for limiting"

Description: The Zener Diode models the DC characteristics of most zeners. This model
differs from the Diode/Rectif i er by providing a user-def i ned dynamic resistance in the
reverse breakdown region. The forward characteristic is def i ned by only a single point,
since most data sheets for zener diodes do not give detailed characteristics in the forward
region.
The f i rst three parameters def i ne 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)

12.2.12Current Limiter

NAME_TABLE:
C_Function_Name:cm_ilimit
Spice_Model_Name:ilimit
Description:"current limiter block"
PORT_TABLE:
Port Name:inpos_pwr
Description:"input""positive power supply"
Direction:ininout
Default_Type:vg
Allowed_Types:[v,vd][g,gd]
Vector:nono
Vector_Bounds:--
Null_Allowed:noyes
PORT_TABLE:
Port Name:neg_pwrout
Description:"negative power supply""output"
Direction:inoutinout


160CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Default_Type:gg
Allowed_Types:[g,gd][g,gd]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesno
PARAMETER_TABLE:
Parameter_Name:in_offsetgain
Description:"input offset""gain"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:r_out_sourcer_out_sink
Description:"sourcing resistance""sinking resistance"
Data_Type:realreal
Default_Value:1.01.0
Limits:[1.0e-9 1.0e9][1.0e-9 1.0e9]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:i_limit_source
Description:"current sourcing limit"
Data_Type:real
Default_Value:-
Limits:[1.0e-12 -]
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:i_limit_sink
Description:"current sinking limit"
Data_Type:real
Default_Value:-
Limits:[1.0e-12 -]
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:v_pwr_rangei_source_range
Description:"upper & lower power"sourcing current
supply smoothing range"smoothing range"
Data_Type:realreal
Default_Value:1.0e-61.0e-9
Limits:[1.0e-15 -][1.0e-15 -]


12.2. ANALOG MODELS161

Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:i_sink_range
Description:"sinking current smoothing range"
Data_Type:real
Default_Value:1.0e-9
Limits:[1.0e-15 -]
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:r_out_domain
Description:"internal/external voltage delta smoothing range"
Data_Type:real
Default_Value:1.0e-9
Limits:[1.0e-15 -]
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The Current Limiter models the behavior of an operational amplif i er or compara-
tor 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 f l ow from the output pin.
Conversely, if the voltage is less than vout, a sinking current will f l ow into the output pin.
Depending on the polarity of the current f l ow, 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 specif i ed by either i_limit_source or i_limit_sink. The latter mimics the current
limiting behavior of many operational amplif i er output stages.
During all operation, the output current is ref l ected either in the pos_pwr connector cur-
rent 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.
Theuser-specif i edsmoothingparametersrelatetomodeloperationasfollows: v_pwr_range
controls the voltage below vpos_pwr and above vneg_pwr inputs beyond which veq [=
gain*(vin+voffset)]issmoothed; i_source_rangespecif i esthecurrentbelowi_limit_source
at which 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 &
i_pos_pwr; r_out_domainspecif i estheincrementalvalueaboveandbelow(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 & r_out_sink.

Example SPICE Usage:


162CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

a10 3 10 20 4 amp3
.
.
.model amp3 ilimit(in_offset=0.0 gain=16.0 r_out_source=1.0
+r_out_sink=1.0 i_limit_source=1e-3
+i_limit_sink=10e-3 v_pwr_range=0.2
+i_source_range=1e-6 i_sink_range=1e-6
+r_out_domain=1e-6)

12.2.13Hysteresis Block

NAME_TABLE:
C_Function_Name:cm_hyst
Spice_Model_Name:hyst
Description:"hysteresis block"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_lowin_high
Description:"input low value""input high value"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:hystout_lower_limit
Description:"hysteresis""output lower limit"
Data_Type:realreal
Default_Value:0.10.0
Limits:[0.0 -]-
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:out_upper_limitinput_domain
Description:"output upper limit""input smoothing domain"
Data_Type:realreal
Default_Value:1.00.01
Limits:--


12.2. ANALOG MODELS163

Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:fraction
Description:"smoothing fraction/absolute value switch"
Data_Type:boolean
Default_Value:TRUE
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: TheHysteresisblockisasimplebufferstagethatprovideshysteresisoftheoutput
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.14Differentiator

NAME_TABLE:
C_Function_Name:cm_d_dt
Spice_Model_Name:d_dt
Description:"time-derivative block"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono


164CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

PARAMETER_TABLE:
Parameter_Name:gainout_offset
Description:"gain""output offset"
Data_Type:realreal
Default_Value:1.00.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:out_lower_limitout_upper_limit
Description:"output lower limit""output upper limit"
Data_Type:realreal
Default_Value:--
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
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 conver-
gence 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 specif i ed 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 rec-
ommended 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. ANALOG MODELS165

12.2.15Integrator

NAME_TABLE:
C_Function_Name:cm_int
Spice_Model_Name:int
Description:"time-integration block"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_offsetgain
Description:"input offset""gain"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:out_lower_limitout_upper_limit
Description:"output lower limit""output upper limit"
Data_Type:realreal
Default_Value:--
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
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


166CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

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 amplif i er-
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 which 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 specif i ed 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)

12.2.16S-Domain Transfer Function

NAME_TABLE:
C_Function_Name:cm_s_xfer
Spice_Model_Name:s_xfer
Description:"s-domain transfer function"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_offsetgain
Description:"input offset""gain"
Data_Type:realreal
Default_Value:0.01.0


12.2. ANALOG MODELS167

Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:num_coeff
Description:"numerator polynomial coefficients"
Data_Type:real
Default_Value:-
Limits:-
Vector:yes
Vector_Bounds:[1 -]
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:den_coeff
Description:"denominator polynomial coefficients"
Data_Type:real
Default_Value:-
Limits:-
Vector:yes
Vector_Bounds:[1 -]
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:int_ic
Description:"integrator stage initial conditions"
Data_Type:real
Default_Value:0.0
Limits:-
Vector:yes
Vector_Bounds:den_coeff
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:denormalized_freq
Description:"denorm. corner freq.(radians) for 1 rad/s coeffs"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The s-domain transfer function is a single input, single output transfer function
in the Laplace transform variable “s” that allows for f l exible modulation of the frequency
domain characteristics of a signal. Ac and transient simulations are supported. The code
model may be conf i gured to produce an arbitrary s-domain transfer function with the
following restrictions:

1. The degree of the numerator polynomial cannot exceed that


168CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

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 coeff i cient parameters is from that associated with the highest-powered term
decreasing to that of the lowest. Thus, for the coeff i cient parameters specif i ed below, the equa-
tion in “s” is shown:

.model filter s_xfer(gain=0.139713 int_ic=[0 0 0]
+ num_coeff=[1.0 0.0 0.07464102]
+ den_coeff=[1.0 0.998942 0.01170077])
...specifies a transfer function of the form...

N(s) = 0.139713·{

s2+0.7464102
s2+0.998942s+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
coeff i cient 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 coeff i cients for a normalized f i lter (i.e. one
in which the frequency of interest is 1 rad/s). Once these coeff i cients 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 f i lter with a corner
(pass-band) frequency of 1 rad/s:

N(s) = 0.139713·{

1.0
s2+1.09773s+1.10251}

In order to def i ne an s_xfer model for the above, but with the corner frequency equal to 1500
rad/s (9425 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 0] denormalized_freq=1500)

In the above, you add the normalized coeff i cients and scale the f i lter through the use of the
denormalized freq parameter. Similar results could have been achieved by performing the de-
normalization prior to specif i cation of the coeff i cients, 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 the same size as the array of values specif i ed
for the den_coeff parameter. Even if a 0 start value is required, you have to add the specif i c
int_ic vector to the set of coeff i cients (see the examples above and below).


12.2. ANALOG MODELS169

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 0]
+num_coeff=[1.0]
+den_coeff=[1.0 1.42562 1.51620])

12.2.17Slew Rate Block

NAME_TABLE:
C_Function_Name:cm_slew
Spice_Model_Name:slew
Description:"A simple slew rate follower block"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_slope
Description:"maximum rising slope value"
Data_Type:real
Default_Value:1.0e9
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:fall_slope
Description:"maximum falling slope value"
Data_Type:real
Default_Value:1.0e9
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:range
Description:"smoothing range"
Data_Type:real
Default_Value:0.1
Limits:-
Vector:no


170CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Vector_Bounds:-
Null_Allowed:yes

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 amplif i er circuit can thus be accurately modeled by cascading the ampli-
f i er 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/µs
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 sig-
nal, unless the slope again exceeds its rise or fall slope limits. The range input specif i es
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)

12.2.18Inductive Coupling

NAME_TABLE:
C_Function_Name:cm_lcouple
Spice_Model_Name:lcouple
Description:"inductive coupling (for use with ’core’ model)"
PORT_TABLE:
Port_Name:lmmf_out
Description:"inductor""mmf output (in ampere-turns)"
Direction:inoutinout
Default_Type:hdhd
Allowed_Types:[h,hd][hd]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:num_turns
Description:"number of inductor turns"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: This function is a conceptual model which is used as a building block to create a
wide variety of inductive and magnetic circuit models. This function is normally used in


12.2. ANALOG MODELS171

conjunction with the “core” model, but can also be used with resistors, hysteresis blocks,
etc. to build up systems which mock the behavior of linear and nonlinear components.
Thelcoupletakesasaninput(onthe“l”port)acurrent. Thiscurrentvalueismultipliedby
the num_turns value, N, to produce an output value (a voltage value which 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 f l ow. 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)

12.2.19Magnetic Core

NAME_TABLE:
C_Function_Name:cm_core
Spice_Model_Name:core
Description:"magnetic core"
PORT_TABLE:
Port_Name:mc
Description:"magnetic core"
Direction:inout
Default_Type:gd
Allowed_Types:[g,gd]
Vector: no
Vector_Bounds:-
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:H_arrayB_array
Description:"magnetic field array""flux density array"
Data_Type:realreal
Default_Value:--
Limits:--
Vector:yesyes
Vector_Bounds:[2 -][2 -]
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:arealength
Description:"cross-sectional area""core length"
Data_Type:realreal
Default_Value:--


172CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:input_domain
Description:"input sm. domain"
Data_Type:real
Default_Value:0.01
Limits:[1e-12 0.5]
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:fraction
Description:"smoothing fraction/abs switch"
Data_Type:boolean
Default_Value:TRUE
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:mode
Description:"mode switch (1 = pwl, 2 = hyst)"
Data_Type:int
Default_Value:1
Limits:[1 2]
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:in_lowin_high
Description:"input low value""input high value"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:hystout_lower_limit
Description:"hysteresis""output lower limit"
Data_Type:realreal
Default_Value:0.10.0
Limits:[0 -]-
Vector:nono
Vector_Bounds:--


12.2. ANALOG MODELS173

Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:out_upper_limit
Description:"output upper limit"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: This function is a conceptual model which 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 which
mock the behavior of linear and nonlinear magnetic components. There are two funda-
mental 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.

PWL Mode (mode = 1)

The core model in PWL mode takes as input a voltage which 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 f i nd 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 f i nd the Flux
value, which is output as a current. The pertinent mathematical equations are listed below:

H = mmf =L, where L = Length

Here H, the Magnetic Field Intensity, is expressed in ampere-turns/meter.

B = f (H)

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.

φ = BA, where A = Area

The f i nal current allowed to f l ow through the core is equal to φ. This value in turn is used by
the "lcouple" code model to obtain a value for the voltage ref l ected 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.


174CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

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 which it treats as a magnetomo-
tive force (mmf) value. This value is used as input to the equivalent of a hysteresis code model
block. The parameters def i ning 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 which 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 f i nal note to be made about the two core model nodes is that certain parameters are avail-
able 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).

12.2.20Controlled Sine Wave Oscillator

NAME_TABLE:
C_Function_Name:cm_sine
Spice_Model_Name:sine
Description:"controlled sine wave oscillator"


12.2. ANALOG MODELS175

PORT_TABLE:
Port Name:cntl_inout
Description:"control input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:cntl_arrayfreq_array
Description:"control array""frequency array"
Data_Type:realreal
Default_Value:0.01.0e3
Limits:-[0 -]
Vector:yesyes
Vector_Bounds:[2 -]cntl_array
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:out_lowout_high
Description:"output peak low value" "output peak high value"
Data_Type:realreal
Default_Value:-1.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

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)

12.2.21Controlled Triangle Wave Oscillator

NAME_TABLE:


176CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

C_Function_Name:cm_triangle
Spice_Model_Name:triangle
Description:"controlled triangle wave oscillator"
PORT_TABLE:
Port Name:cntl_inout
Description:"control input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:cntl_arrayfreq_array
Description:"control array""frequency array"
Data_Type:realreal
Default_Value:0.01.0e3
Limits:-[0 -]
Vector:yesyes
Vector_Bounds:[2 -]cntl_array
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:out_lowout_high
Description:"output peak low value" "output peak high value"
Data_Type:realreal
Default_Value:-1.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:duty_cycle
Description:"rise time duty cycle"
Data_Type:real
Default_Value:0.5
Limits:[1e-10 0.999999999]
Vector:no
Vector_Bounds:-
Null_Allowed:yes

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 charac-


12.2. ANALOG MODELS177

teristic. 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)

12.2.22Controlled Square Wave Oscillator

NAME_TABLE:
C_Function_Name:cm_square
Spice_Model_Name:square
Description:"controlled square wave oscillator"
PORT_TABLE:
Port Name:cntl_inout
Description:"control input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:cntl_arrayfreq_array
Description:"control array""frequency array"
Data_Type:realreal
Default_Value:0.01.0e3
Limits:-[0 -]
Vector:yesyes
Vector_Bounds:[2 -]cntl_array
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:out_lowout_high
Description:"output peak low value" "output peak high value"
Data_Type:realreal
Default_Value:-1.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER.TABLE:
Parameter_Name:duty_cyclerise_time
Description:"duty cycle""output rise time"
Data_Type:realreal
Default_Value:0.51.0e-9
Limits:[1e-6 0.999999]-


178CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Vector: no
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:fall_time
Description:"output fall time"
Data_Type:real
Default_Value:1.0e-9
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

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)

12.2.23Controlled One-Shot

NAME_TABLE:
C_Function_Name:cm_oneshot
Spice_Model_Name:oneshot
Description:"controlled one-shot"
PORT_TABLE:
Port Name:clkcntl_in
Description:"clock input""control input"
Direction:inin
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:noyes
PORT_TABLE:


12.2. ANALOG MODELS179

Port Name:clearout
Description:"clear signal""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesno
PARAMETER_TABLE:
Parameter_Name:clk_trigretrig
Description:"clock trigger value""retrigger switch"
Data_Type:realboolean
Default_Value:0.5FALSE
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:noyes
PARAMETER_TABLE:
Parameter_Name:pos_edge_trig
Description:"positive/negative edge trigger switch"
Data_Type:boolean
Default_Value:TRUE
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:cntl_arraypw_array
Description:"control array""pulse width array"
Data_Type:realreal
Default_Value:0.01.0e-6
Limits:-[0.00 -]
Vector:yesyes
Vector_Bounds:-cntl_array
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:out_lowout_high
Description:"output low value""output high value"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:fall_timerise_time
Description:"output fall time""output rise time"
Data_Type:realreal


180CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Default_Value:1.0e-91.0e-9
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delay
Description:"output delay from trigger"
Data_Type:real
Default_Value:1.0e-9
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:fall_delay
Description:"output delay from pw"
Data_Type:real
Default_Value:1.0e-9
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

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 specif i ed 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.0-9 fall_delay = 35.0e-9)

12.2.24Capacitance Meter

NAME_TABLE:


12.2. ANALOG MODELS181

C_Function_Name:cm_cmeter
Spice_Model_Name:cmeter
Description:"capacitance meter"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:gain
Description:"gain"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The capacitance meter is a sensing device which 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 which 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)

12.2.25Inductance Meter

NAME_TABLE:
C_Function_Name:cm_lmeter
Spice_Model_Name:lmeter
Description:"inductance meter"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:


182CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Parameter_Name:gain
Description:"gain"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The inductance meter is a sensing device which 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 which 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.26Memristor

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:rminrmax
Description:"minimum resistance""maximum resistance"
Data_Type:realreal
Default_Value:10.010000.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rinitvt
Description:"initial resistance""threshold"
Data_Type:realreal
Default_Value:7000.00.0


12.3. HYBRID MODELS183

Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:alphabeta
Description:"model parameter 1""model parameter 2"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:nono

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)

12.3Hybrid Models

The following hybrid models are supplied with XSPICE. The descriptions included below con-
sist of the model Interface Specif i cation File and a description of the model’s operation. This
is followed by an example of a simulator-deck placement of the model, including the .MODEL
card and the specif i cation of all available parameters.

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 specif i c need, but in the development of user-def i ned nodes you may f i nd 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.

12.3.1Digital-to-Analog Node Bridge

NAME_TABLE:
C_Function_Name:cm_dac_bridge
Spice_Model_Name:dac_bridge
Description:"digital-to-analog node bridge"
PORT_TABLE:


184CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dv
Allowed_Types:[d][v,vd,i,id,d]
Vector:yesyes
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:out_low
Description:"0-valued analog output"
Data_Type:real
Default_Value:0.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:out.high
Description:"1-valued analog output"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:out_undefinput_load
Description:"U-valued analog output""input load (F)"
Data_Type:realreal
Default_Value:0.51.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:t_riset_fall
Description:"rise time 0->1""fall time 1->0"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: The dac_bridge is the f i rst of two node bridge devices designed to allow for the
readytransferofdigitalinformationtoanalogvaluesandbackagain. Theseconddeviceis
the adc_bridge (which takes an analog value and maps it to a digital one).The dac_bridge


12.3. HYBRID MODELS185

takes as input a digital value from a digital node. This value by def i nition 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 “f i nal” values from its
currentanalogoutputlevel. Thespeedatwhichthisrampingoccursdependsonthevalues
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 f i le for determining the presence of the out_undef parameter. If this
parameter is not specif i ed by you, and if out_high and out_low values are specif i ed,
then out_undef is assigned the value of the arithmetic mean of out_high and out_low.
This simplif i es 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)

12.3.2Analog-to-Digital Node Bridge

NAME_TABLE:
C_Function_Name:cm_adc_bridge
Spice_Model_Name:adc_bridge
Description:"analog-to-digital node bridge"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:vd
Allowed_Types:[v,vd,i,id,d][d]
Vector:yesyes
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_low
Description:"maximum 0-valued analog input"
Data_Type:real
Default_Value:1.0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:in_high
Description:"minimum 1-valued analog input"
Data_Type:real
Default_Value:2.0


186CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: The adc_bridge is one of two 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 def i nition 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)

12.3.3Controlled Digital Oscillator

NAME_TABLE:
C_Function_Name:cm_d_osc
Spice_Model_Name:d_osc
Description:"controlled digital oscillator"
PORT_TABLE:
Port Name:cntl_inout
Description:"control input""output"
Direction:inout
Default_Type:vd
Allowed_Types:[v,vd,i,id][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:cntl_arrayfreq_array
Description:"control array""frequency array"
Data_Type:realreal


12.3. HYBRID MODELS187

Default_Value:0.01.0e6
Limits:-[0 -]
Vector:yesyes
Vector_Bounds:[2 -]cntl_array
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:duty_cycleinit_phase
Description:"duty cycle""initial phase of output"
Data_Type:realreal
Default_Value:0.50
Limits:[1e-6 0.999999][-180.0 +360.0]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1e-91e-9
Limits:[0 -][0 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: The digital oscillator is a hybrid model which accepts as input a voltage or cur-
rent. This input is compared to the voltage-to-frequency transfer characteristic specif i ed
by the cntl_array/freq_array coordinate pairs, and a frequency is obtained which repre-
sents 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 which can be specif i ed 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)

12.3.4Node bridge from digital to real with enable

NAME_TABLE:
Spice_Model_Name: d_to_real
C_Function_Name:ucm_d_to_real
Description: "Node bridge from digital to real with enable"
PORT_TABLE:
Port_Name:inenableout


188CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Description:"input""enable""output"
Direction:ininout
Default_Type:ddreal
Allowed_Types: [d][d][real]
Vector:nonono
Vector_Bounds:---
Null_Allowed:noyesno
PARAMETER_TABLE:
Parameter_Name: zeroonedelay
Description:"value for 0""value for 1""delay"
Data_Type:realrealreal
Default_Value:0.01.01e-9
Limits:--[1e-15 -]
Vector:nonono
Vector_Bounds:---
Null_Allowed:yesyesyes

12.3.5A Z**-1 block working on real data

NAME_TABLE:
Spice_Model_Name: real_delay
C_Function_Name: ucm_real_delay
Description: "A Z ** -1 block working on real data"
PORT_TABLE:
Port_Name:inclkout
Description:"input""clock""output"
Direction:ininout
Default_Type:realdreal
Allowed_Types:[real][d][real]
Vector:nonono
Vector_Bounds:---
Null_Allowed:nonono
PARAMETER_TABLE:
Parameter_Name:delay
Description:"delay from clk to out"
Data_Type:real
Default_Value:1e-9
Limits:[1e-15 -]
Vector:no
Vector_Bounds:-
Null_Allowed:yes

12.3.6A gain block for event-driven real data

NAME_TABLE:
Spice_Model_Name:real_gain
C_Function_Name:ucm_real_gain
Description:"A gain block for event-driven real data"


12.3. HYBRID MODELS189

PORT_TABLE:
Port_Name:inout
Description:"input""output"
Direction:inout
Default_Type:realreal
Allowed_Types:[real][real]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_offsetgainout_offset
Description:"input offset""gain""output offset"
Data_Type:realrealreal
Default_Value:0.01.00.0
Limits:---
Vector:nonono
Vector_Bounds:---
Null_Allowed:yesyesyes
PARAMETER_TABLE:
Parameter_Name:delayic
Description:"delay""initial condition"
Data_Type:realreal
Default_Value:1.0e-90.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

12.3.7Node bridge from real to analog voltage

NAME_TABLE:
Spice_Model_Name:real_to_v
C_Function_Name:ucm_real_to_v
Description:"Node bridge from real to analog voltage"
PORT_TABLE:
Port_Name:inout
Description:"input""output"
Direction:inout
Default_Type:realv
Allowed_Types:[real][v, vd, i, id]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:gaintransition_time
Description:"gain""output transition time"
Data_Type:realreal
Default_Value:1.01e-9


190CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Limits:-[1e-15 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

12.4Digital Models

The following digital models are supplied with XSPICE. The descriptions included below con-
sist of an example model Interface Specif i cation File and a description of the model’s opera-
tion. This is followed by an example of a simulator-deck placement of the model, including the
.MODEL card and the specif i cation of all available parameters. Note that these models have
not been f i nalized at this time.

Some information common to all digital models and/or digital nodes is included here. The
following are general rules which should make working with digital nodes and models more
straightforward:

1. AlldigitalnodesareinitializedtoZEROatthestartofasimulation(i.e., whenINIT=TRUE).
This means that a model need not post an explicit value to an output node upon initial-
ization if its output would normally be a ZERO (although posting such would certainly
cause no harm).

12.4.1Buffer

NAME_TABLE:
C_Function_Name:cm_d_buffer
Spice_Model_Name:d_buffer
Description:"digital one-bit-wide buffer"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:


12.4. DIGITAL MODELS191

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

Description: The buffer is a single-input, single-output digital buffer which produces as output
a time-delayed copy of its input. The delays associated with an output rise and those as-
sociated with an output fall may be different. The model also posts an input load value (in
farads) based on the parameter input load. The output of this model does NOT, however,
respond to the total loading it sees on its output; it will always drive the output strongly
with the specif i ed delays.

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.2Inverter

NAME_TABLE:
C_Function_Name:cm_d_inverter
Spice_Model_Name:d_inverter
Description:"digital one-bit-wide inverter"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:input_load
Description:"input load value (F)"


192CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Data_Type:real
Default_Value:1.0e-12
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The inverter is a single-input, single-output digital inverter which produces as
output an inverted, time-delayed copy of its input. The delays associated with an output
rise and those associated with an output fall may be specif i ed independently. The model
also posts an input load value (in farads) based on the parameter input load. The output
of this model does NOT, however, respond to the total loading it sees on its output; it will
always drive the output strongly with the specif i ed delays.

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.3And

NAME_TABLE:
C_Function_Name:cm_d_and
Spice_Model_Name:d_and
Description:"digital ‘and’ gate"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:input_load
Description:"input load value (F)"
Data_Type:real
Default_Value:1.0e-12


12.4. DIGITAL MODELS193

Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The digital ‘and’ gate is an n-input, single-output ‘and’ gate which 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. The delays associated with an output rise and those associated with an output
fall may be specif i ed independently. The model also posts an input load value (in farads)
based on the parameter input load. The output of this model does NOT, however, respond
to the total loading it sees on its output; it will always drive the output strongly with the
specif i ed delays.

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.4Nand

NAME_TABLE:
C_Function_Name:cm_d_nand
Spice_Model_Name:d_nand
Description:"digital ‘nand’ gate"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:input_load
Description:"input load value (F)"
Data_Type:real
Default_Value:1.0e-12


194CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The digital ‘nand’ gate is an n-input, single-output ‘nand’ gate which 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. The delays associated with an output rise and those associated with an output
fall may be specif i ed independently. The model also posts an input load value (in farads)
based on the parameter input load. The output of this model does NOT, however, respond
to the total loading it sees on its output; it will always drive the output strongly with the
specif i ed delays.

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.5Or

NAME_TABLE:
C_Function_Name:cm_d_or
Spice_Model_Name:d_or
Description:"digital ‘or’ gate"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:input_load
Description:"input load value (F)"
Data_Type:real
Default_Value:1.0e-12


12.4. DIGITAL MODELS195

Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The digital ‘or’ gate is an n-input, single-output ‘or’ gate which 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.
The delays associated with an output rise and those associated with an output fall may be
specif i ed independently. The model also posts an input load value (in farads) based on the
parameter input load. The output of this model does NOT, however, respond to the total
loading it sees on its output; it will always drive the output strongly with the specif i ed
delays.

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.6Nor

NAME_TABLE:
C_Function_Name:cm_d_nor
Spice_Model_Name:d_nor
Description:"digital ‘nor’ gate"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:input_load
Description:"input load value (F)"
Data_Type:real
Default_Value:1.0e-12


196CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The digital ‘nor’ gate is an n-input, single-output ‘nor’ gate which 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.
The delays associated with an output rise and those associated with an output fall may be
specif i ed independently. The model also posts an input load value (in farads) based on the
parameter input load. The output of this model does NOT, however, respond to the total
loading it sees on its output; it will always drive the output strongly with the specif i ed
delays.

Example SPICE Usage:
anor12 [1 2 3 4] 8 nor12
.model nor12 d_or(rise_delay = 0.5e-9 fall_delay = 0.3e-9
+input_load = 0.5e-12)

12.4.7Xor

NAME_TABLE:
C_Function_Name:cm_d_xor
Spice_Model_Name:d_xor
Description:"digital exclusive-or gate"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:input_load
Description:"input load value (F)"
Data_Type:real
Default_Value:1.0e-12


12.4. DIGITAL MODELS197

Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The digital ‘xor’ gate is an n-input, single-output ‘xor’ gate which 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 specif i ed indepen-
dently.
The model also posts an input load value (in farads) based on the parameter input load.
The output of this model does NOT, however, respond to the total loading it sees on its
output; it will always drive the output strongly with the specif i ed delays. Note also that
to maintain the technology-independence of the model, any UNKNOWN input, or any
f l oating 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.8Xnor

NAME_TABLE:
C_Function_Name:cm_d_xnor
Spice_Model_Name:d_xnor
Description:"digital exclusive-nor gate"
PORT_TABLE:
Port Name:inout
Description:"input""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[2 -]-
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:input_load
Description:"input load value (F)"
Data_Type:real


198CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Default_Value:1.0e-12
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The digital ‘xnor’ gate is an n-input, single-output ‘xnor’ gate which produces an
active“0”valueifanoddnumberofitsinputsarealso“1”values. Itproducesa“1”output
when an even number of “1” values occurs on its inputs. The delays associated with
an output rise and those associated with an output fall may be specif i ed independently.
The model also posts an input load value (in farads) based on the parameter input load.
The output of this model does NOT, however, respond to the total loading it sees on its
output; it will always drive the output strongly with the specif i ed delays. Note also that
to maintain the technology-independence of the model, any UNKNOWN input, or any
f l oating 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.9Tristate

NAME_TABLE:
C_Function_Name:cm_d_tristate
Spice_Model_Name:d_tristate
Description:"digital tristate buffer"
PORT_TABLE:
Port Name:inenableout
Description:"input""enable""output"
Direction:ininout
Default_Type:ddd
Allowed_Types:[d][d][d]
Vector:nonono
Vector_Bounds:---
Null_Allowed:nonono
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:input_load
Description:"input load value (F)"


12.4. DIGITAL MODELS199

Data_Type:real
Default_Value:1.0e-12
Limits:-
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

Description: The digital tristate is a simple tristate gate which can be conf i gured to allow for
open-collector behavior, as well as standard tristate behavior. The state seen on the input
line is ref l ected 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 specif i ed independently, nor may they be spec-
if i ed 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.The output of this model does NOT, however,
respond to the total loading it sees on its output; it will always drive the output with the
specif i ed delay. Note also that to maintain the technology-independence of the model,
any UNKNOWN input, or any f l oating input causes the output to also go UNKNOWN.
Likewise, any UNKNOWN input on the enable line causes the output to go to an UNDE-
TERMINED 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.10Pullup

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]


200CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

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 which 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 which rely on a resistive pullup common to many tristated output devices. The
model posts an input load value (in farads) based on the parameters “load”.

Example SPICE Usage:
a2 9 pullup1
.model pullup1 d_pullup(load = 20.0e-12)

12.4.11Pulldown

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


12.4. DIGITAL MODELS201

Description: Thedigitalpulldownresistorisadevicewhichemulatesthebehaviorofananalog
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 which rely on a resistive pulldown common to many tristated output devices.
The model posts an input load value (in farads) based on the parameters “load”.

Example SPICE Usage:
a4 9 pulldown1
.model pulldown1 d_pulldown(load = 20.0e-12)

12.4.12D Flip Flop

NAME_TABLE:
C_Function_Name:cm_d_dff
Spice_Model_Name:d_dff
Description:"digital d-type flip flop"
PORT_TABLE:
Port Name:dataclk
Description:"input data""clock"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PORT_TABLE:
Port Name:setreset
Description:"asynch. set""asynch. reset"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PORT_TABLE:
Port Name:outNout
Description:"data output""inverted data output"
Direction:outout
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:clk_delayset_delay
Description:"delay from clk""delay from set"
Data_Type:realreal
Default_Value:1.0e-91.0e-9


202CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:reset_delayic
Description:"delay from reset""output initial state"
Data_Type:realint
Default_Value:1.00
Limits:[1.0e-12 -][0 2]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:data_loadclk_load
Description:"data load value (F)""clk load value (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:set_loadreset_load
Description:"set load value (F)""reset load (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector.Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: The digital d-type f l ip f l op is a one-bit, edge-triggered storage element which 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 chang-
ing 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 specif i ed for the input lines; these allow for more faithful reproduction of the output
characteristics of different IC fabrication technologies.


12.4. DIGITAL MODELS203

Note that any UNKNOWN input on the set or reset lines immediately results in an UN-
KNOWN 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)

12.4.13JK Flip Flop

NAME_TABLE:
C_Function_Name:cm_d_jkff
Spice_Model_Name:d_jkff
Description:"digital jk-type flip flop"
PORT_TABLE:
Port Name:jk
Description:"j input""k input"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PORT_TABLE:
Port Name:clk
Description:"clock"
Direction:in
Default_Type:d
Allowed_Types:[d]
Vector:no
Vector_Bounds:-
Null_Allowed:no
PORT_TABLE:
Port Name:setreset
Description:"asynchronous set""asynchronous reset"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PORT_TABLE:
Port Name:outNout
Description:"data output""inverted data output"
Direction:outout
Default_Type:dd
Allowed_Types:[d][d]


204CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Vector:nono
Vector_Bounds--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:clk_delayset_delay
Description:"delay from clk""delay from set"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:reset_delayic
Description:"delay from reset""output initial state"
Data_Type:realint
Default_Value:1.00
Limits:[1.0e-12 -][0 2]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:jk_loadclk_load
Description:"j,k load values (F)""clk load value (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:set_loadreset_load
Description:"set load value (F)""reset load (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes


12.4. DIGITAL MODELS205

Description: The digital jk-type f l ip f l op is a one-bit, edge-triggered storage element which
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 specif i ed 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)

12.4.14Toggle Flip Flop

NAME_TABLE:
C_Function_Name:cm_d_tff
Spice_Model_Name:d_tff
Description:"digital toggle flip flop"
PORT_TABLE:
Port Name:tclk
Description:"toggle input""clock"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PORT_TABLE:
Port Name:setreset
Description:"set""reset"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PORT.TABLE:
Port Name:outNout
Description:"data output""inverted data output"
Direction:outout
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--


206CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:clk_delayset_delay
Description:"delay from clk""delay from set"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:reset_delayic
Description:"delay from reset""output initial state"
Data_Type:realint
Default_Value:1.00
Limits:[1.0e-12 -][0 2]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:t_loadclk_load
Description:"toggle load value (F)" "clk load value (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:set_loadreset_load
Description:"set load value (F)""reset load (F)"
Data_Type:realreal
Default.Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: Thedigitaltoggle-typef l ipf l opisaone-bit, edge-triggeredstorageelementwhich
willtoggleitscurrentstatewhenevertheclkinputlinetransitionsfromlowtohigh(ZERO


12.4. DIGITAL MODELS207

to ONE). In addition, asynchronous set and reset signals exist, and each of the three meth-
ods of changing the stored output of the d_tff have separate load values and delays asso-
ciated with them. Additionally, you may specify separate rise and fall delay values that
are added to those specif i ed 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 UN-
KNOWN.

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)

12.4.15Set-Reset Flip Flop

NAME_TABLE:
C_Function_Name:cm_d_srff
Spice_Model_Name:d_srff
Description:"digital set-reset flip flop"
PORT_TABLE:
Port Name:sr
Description:"set input""reset input"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PORT_TABLE:
Port Name:clk
Description:"clock"
Direction:in
Default_Type:d
Allowed_Types:[d]
Vector:no
Vector_Bounds:-
Null_Allowed:no
PORT_TABLE:
Port Name:setreset
Description:"asynchronous set""asynchronous reset"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PORT_TABLE:


208CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Port Name:outNout
Description:"data output""inverted data output"
Direction:outout
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:clk_delayset_delay
Description:"delay from clk""delay from set"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:reset_delayic
Description:"delay from reset""output initial state"
Data_Type:realint
Default_Value:1.0e-90
Limits:[1.0e-12 -][0 2]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:sr_loadclk_load
Description:"set/reset loads (F)""clk load value (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:set_loadreset_load
Description:"set load value (F)""reset load (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal


12.4. DIGITAL MODELS209

Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: The digital sr-type f l ip f l op is a one-bit, edge-triggered storage element which
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=ONEif s=ONE and r=ZERO;
out=ZEROif s=ZERO and r=ONE;
out=previous valueif s=ZERO and r=ZERO;
out=UNKNOWNif 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 specif i ed 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 UN-
KNOWN.

Example SPICE Usage:

a8 2 12 4 5 6 3 14 flop7
.model flop7 d_srff(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)

12.4.16D Latch

NAME_TABLE:
C_Function_Name:cm_d_dlatch
Spice_Model_Name:d_dlatch
Description:"digital d-type latch"
PORT_TABLE:
Port Name:dataenable
Description:"input data""enable input"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PORT_TABLE:


210CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Port Name:setreset
Description:"set""reset"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PORT_TABLE:
Port Name:outNout
Description:"data output""inverter data output"
Direction:outout
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
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_delayset_delay
Description:"delay from enable""delay from SET"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:reset_delayic
Description:"delay from RESET""output initial state"
Data_Type:realboolean
Default_Value:1.0e-90
Limits:[1.0e-12 -]-
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:data_loadenable_load
Description:"data load (F)""enable load value (F)"
Data_Type:realreal


12.4. DIGITAL MODELS211

Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:set_loadreset_load
Description:"set load value (F)""reset load (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: The digital d-type latch is a one-bit, level-sensitive storage element which 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 specif i ed 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 imme-
diately 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)

12.4.17Set-Reset Latch

NAME_TABLE:
C_Function_Name:cm_d_srlatch


212CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Spice_Model_Name:d_srlatch
Description:"digital sr-type latch"
PORT_TABLE:
Port Name:sr
Description:"set""reset"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesyes
Vector_Bounds:[2 -]r
Null_Allowed:nono
PORT_TABLE:
Port Name:enable
Description:"enable"
Direction:in
Default_Type:d
Allowed_Types:[d]
Vector:no
Vector_Bounds:-
Null_Allowed:no
PORT_TABLE:
Port Name:setreset
Description:"set""reset"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PORT_TABLE:
Port Name:outNout
Description:"data output""inverted data output"
Direction:outout
Default_Type:dd
Allowed_Types:[d][d]
Vector: no no
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:sr_delay
Description:"delay from s or r input change"
Data_Type:real
Default_Value:1.0e-9
Limits:[1.0e-12 -]
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:


12.4. DIGITAL MODELS213

Parameter_Name:enable_delayset_delay
Description:"delay from enable""delay from SET"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:reset_delayic
Description:"delay from RESET""output initial state"
Data_Type:realboolean
Default_Value:1.0e-90
Limits:[1.0e-12 -]-
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:sr_loadenable_load
Description:"s & r input loads (F)" "enable load value (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:set_loadreset_load
Description:"set load value (F)""reset load (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes

Description: The digital sr-type latch is a one-bit, level-sensitive storage element which 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:


214CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

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 re-
set) have separate delays associated with them. You may also specify separate rise and fall
delay values that are added to those specif i ed 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 immedi-
ately 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)

12.4.18State Machine

NAME_TABLE:
C_Function_Name:cm_d_state
Spice_Model_Name:d_state
Description:"digital state machine"
PORT_TABLE:
Port Name:inclk
Description:"input""clock"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[1 -]-
Null_Allowed:yesno
PORT_TABLE:
Port Name:resetout
Description:"reset""output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:noyes
Vector_Bounds:-[1 -]
Null_Allowed:yesno
PARAMETER_TABLE:


12.4. DIGITAL MODELS215

Parameter_Name:clk_delayreset_delay
Description:"delay from CLK""delay from RESET"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:Parameter_Name:state_file
Description:"state transition specification file name"
Data_Type:string
Default_Value:"state.txt"
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:reset_state
Description:"default state on RESET & at DC"
Data_Type:int
Default_Value:0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:no
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:yes
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:yes
PARAMETER_TABLE:
Parameter_Name:reset_load
Description:"reset loading capacitance (F)"
Data_Type:real
Default_Value:1.0e-12


216CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: The digital state machine provides for straightforward descriptions of clocked
combinatorial logic blocks with a variable number of inputs and outputs and with an
unlimited number of possible states. The model can be conf i gured to behave as virtually
any type of counter or clocked combinatorial 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 conf i gured through the use of a state def i nition f i le (state.in) which
resides in a directory of your choosing. The f i le def i nes all states to be understood by the
model, plus input bit combinations which trigger changes in state. An example state.in
f i le 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 f i le structure should be noted. First, ALL LINES IN THE FILE
MUST BE ONE OF FOUR TYPES. These are:

1. A comment, beginning with a “*” in the f i rst column.

2. A header line, which is a complete description of the current state, the outputs corre-
sponding to that state, an input value, and the state that the model will assume should that
input be encountered. The f i rst line of a state def i nition must ALWAYS be a header line.

3. A continuation line, which is a partial description of a state, consisting of an input value
and the state that the model will assume should that input be encountered. Note that
continuation lines may only be used after the initial header line def i nition for a state.

4. A line containing nothing but white-spaces (space, form-feed, newline, carriage return,
tab, vertical tab).

A line which is not one of the above will cause a f i le-loading error. Note that in the example
shown, whitespace (any combination of blanks, tabs, commas) is used to separate values, and
that the character "->" is used to underline the state transition implied by the input preceding it.


12.4. DIGITAL MODELS217

This particular character is not critical in of itself, and can be replaced with any other character
or non-broken combination of characters that you prefer (e.g. “==>”, “>>”, “:”, “resolves_to”,
etc.)

The order of the output and input bits in the f i le is important; the f i rst column is always inter-
preted to refer to the “zeroth” bit of input and output. Thus, in the f i le 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 def i nition (which consists of
the sum total of all lines which def i ne the state, its outputs, and all methods by which a state can
be exited) must be made on contiguous line numbers; a state def i nition cannot be broken into
sub-blocks and distributed randomly throughout the f i le. On the other hand, the state def i nition
can be broken up by as many comment lines as you desire.

Header f i les may be used throughout the state.in f i le, 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 f i le named by the parameter filename in state_file="filename" is sought after
according to a search list described in12.1.3.

12.4.19Frequency Divider

NAME_TABLE:
C_Function_Name:cm_d_fdiv
Spice_Model_Name:d_fdiv
Description:"digital frequency divider"
PORT_TABLE:
Port Name:freq_infreq_out
Description:"frequency input""frequency output"
Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:nono
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:div_factorhigh_cycles
Description:"divide factor""# of cycles for high out"
Data_Type:intint
Default_Value:21
Limits:[1 -][1 div_factor-1]
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes


218CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

PARAMETER_TABLE:
Parameter_Name:i_count
Description:"divider initial count value"
Data_Type:int
Default_Value:0
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:rise_delayfall_delay
Description:"rise delay""fall delay"
Data_Type:realreal
Default_Value:1.0e-91.0e-9
Limits:[1.0e-12 -][1.0e-12 -]
Vector:yesyes
Vector_Bounds:inin
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:freq_in_load
Description:"freq_in load value (F)"
Data_Type:real
Default_Value:1.0e-12
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:yes

Description: Thedigitalfrequencydividerisaprogrammablestep-downdividerwhichaccepts
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. Rise delay and fall delay on the outputs may also be specif i ed independently.

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.20RAM

NAME_TABLE:
C_Function_Name:cm_d_ram
Spice_Model_Name:d_ram
Description:"digital random-access memory"
PORT_TABLE:
Port Name:data_indata_out
Description:"data input line(s)""data output line(s)"


12.4. DIGITAL MODELS219

Direction:inout
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesyes
Vector_Bounds:[1 -]data_in
Null_Allowed:nono
PORT_TABLE:
Port Name:addresswrite_en
Description:"address input line(s)" "write enable line"
Direction:inin
Default_Type:dd
Allowed_Types:[d][d]
Vector:yesno
Vector_Bounds:[1 -]-
Null_Allowed:nono
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 -]


220CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

Vector:no
Vector_Bounds:-
Null_Allowed:yes
PARAMETER_TABLE:
Parameter_Name:data_loadaddress_load
Description:"data_in load value (F)" "addr. load value (F)"
Data_Type:realreal
Default_Value:1.0e-121.0e-12
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
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 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:

2P= N

Thereisnoresetlineintothedevice. However, aninitialvalueforallbitsmaybespecif i ed
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 satisf i ed. 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


12.4. DIGITAL MODELS221

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.
Detailedtiming-checkingroutinesarenotprovidedinthismodel, otherthanfortheenable
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)

12.4.21Digital Source

NAME_TABLE:
C_Function_Name:cm_d_source
Spice_Model_Name:d_source
Description:"digital signal source"
PORT_TABLE:
Port Name:out
Description:"output"
Direction:out
Default_Type:d
Allowed_Types:[d]
Vector:yes
Vector_Bounds:-
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:input_file
Description:"digital input vector filename"
Data_Type:string
Default_Value:"source.txt"
Limits:-
Vector:no
Vector_Bounds:-
Null_Allowed:no
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

Description: The digital source provides for straightforward descriptions of digital signal vec-
tors in a tabular format. The model reads input from the input f i le and, at the times
specif i ed in the f i le, generates the inputs along with the strengths listed.


222CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE

The format of the input f i le is as shown below. Note that comment lines are delineated through
the use of a single “*” character in the f i rst column of a line. This is similar to the way
the SPICE program handles comments.

* Tcnnn . . .
* ilooo . . .
* moddd . . .
* eceee . . .
*kabc . . .
0.0000Uu Uu Us Uu . . .
1.234e-90s 1s 1s 0z . . .
1.376e-90s 0s 1s 0z . . .
2.5e-71s 0s 1s 0z . . .
2.5006e-7 1s 1s 1s 0z . . .
5.0e-70s 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
f i rst 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 which does not contain
enough tokens to completely def i ne 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 f i le.

Errors will also occur if a line exists in source.txt which 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 f i le; 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 f i le named by the parameter filename in input_file="filename" is sought after
according to a search list described in12.1.3.

12.5Predef i ned Node Types for event driven simulation

The following prewritten node types are included with the XSPICE simulator. These should
provide you not only with valuable event-driven modeling capabilities, but also with examples
to use for guidance in creating new UDN (user def i ned node) types. You may access these node
data by the plot (17.5.43) or eprint (17.5.23) commands.

12.5.1Digital Node Type

The “digital” node type is directly built into the simulator. 12 digital node values are available.
They are described by a two character string (the state/strength token). The f i rst 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). So these are the values we have: 0s, 1s, Us, 0r, 1r, Ur, 0z, 1z, Uz, 0u, 1u, Uu.


12.5. PREDEFINED NODE TYPES FOR EVENT DRIVEN SIMULATION223

12.5.2Real Node Type

The “real” node type provides for event-driven simulation with double-precision f l oating point
data. This type is useful for evaluating sampled-data f i lters and systems. The type implements
all optional functions for User-Def i ned Nodes, including inversion and node resolution. For
inversion, the sign of the value is reversed. For node resolution, the resultant value at a node is
the sum of all values output to that node. The node is implemented as a user def i ned node in
ngspice/src/xspice/icm/xtraevt/real.

12.5.3Int Node Type

The “int” node type provides for event-driven simulation with integer data. This type is useful
for evaluating round-off error effects in sampled-data systems. The type implements all optional
functions for User-Def i ned Nodes, including inversion and node resolution. For inversion, the
sign of the integer value is reversed. For node resolution, the resultant value at a node is the
sum of all values output to that node. The node is implemented as a user def i ned node in
ngspice/src/xspice/icm/xtraevt/int.

12.5.4(Digital) Input/Output

The analog code models use the standard (analog) nodes provided by ngspice and thus are using
all the commands for sourcing, storing, printing, and plotting data.

I/O for event nodes (digital, real, int, and UDNs) currently is much more limited to a few tools.
For output you may use the plot (17.5.43) or eprint (17.5.23) commands. For input, you may
create a test bench with existing code models (oscillator (12.3.3), frequency divider (12.4.19),
state machine (12.4.18) etc.). Reading data from a f i le 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 f i le,
(f i lesource 12.2.8) and convert its analog input to the digital type by the adc_bridge (12.3.2). If
you want reading data from a VCD f i le, you may have a look at ngspice-users forum and apply
a python script provided by Sdaau to translate the VCD data to d_source or f i lesource input.


224CHAPTER 12. MIXED-MODE AND BEHAVIORAL MODELING WITH XSPICE


Chapter 13

Verilog A Device models

13.1Introduction

The ngspice-adms interface will implement extra HICUM level0 and level2 (HICUM model
web page), MEXTRAM(MEXTRAM model web page), EKV(EKV model web page) and
PSP(NXP MOS model 9 web page) models written in Verilog-A behavior language.

13.2adms

To compile Verilog-A compact models into ngspice-ready C models the the program admsXml
is required. Details of this software are described in adms home page.

13.3How to integrate a Verilog-A model into ngspice

13.3.1How to setup a *.va model for ngspice

The root entry for new Verilog-A models is \src\spicelib\devices\adms. Below the modelname
entry the Verilog-A code should reside in folder admsva
(e.g.: ngspice\src\spicelib\devices\adms\ekv\admsva\ekv.va). The f i le extension is f i xed to .va.

Certain f i les must modif i ed to create the interface to ngspice - see the guideline README.adms
in the ngspice root.

13.3.2Adding admsXml to your build environment

To facilitate the installation of adms, a source code package has been assembled for use with
ngspice, available as a zip f i le for download. It is based on adms source code from the subver-
sionrepositorydownloadedonAugust1st, 2010, andhasbeenslightlymodif i ed(seeChangeLog).

Under OS LINUX (tested with SUSE 11.2, 64 bit) you may expand the zip f i le and run
./autogen_lin.sh, followed by ’make’ and ’make install’.

225


226CHAPTER 13. VERILOG A DEVICE MODELS

Under OS CYGWIN (tested with actual CYGWIN on MS Windows 7, 64 bit), please use
./autogen_cyg.sh, followed by ’make’ and ’make install’.

UnderOSMINGW,adirectcompilationwouldrequiretheadditionalinstallationofperlmodule
XML-LibXML which is not as straightforward as it should be. However you may start with a
CYGWIN compile as described above. If you then go to your MSYS window, cd to the adms
top directory and start ./mingw-compile.sh, you will obtain admsXml.exe, copied to MSYS
/bin, and you are ready to go. To facilitate installation under MS Windows, a admsXml.exe
zipped binary is available. Just copy it to MSYS /bin directory and start working on your verilog
models.

A short test of a successful installation is:

$ admsXml -v

$ [usage..]release name="admsXml" version="2.3.0" date="Aug 4 2010"
time="10:24:18"

Compilation of admsXml with MS Visual Studio is not possible, because the source code has
variable declarations not only at the top of a block, but deliberately also in the following lines.
This is o.k. by the C99 standard, but not supported by MS Visual Studio.


Chapter 14

Mixed-Level Simulation (ngspice with
TCAD)

14.1Cider

Ngspice implements mixed-level simulation through the merging of its code with CIDER (de-
tails see chapt. 30).

CIDER is a mixed-level circuit and device simulator that provides a direct link between tech-
nology 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 numer-
ically modeling the critical devices in a circuit. Compact models can be used for noncritical
devices.

CIDER couples the latest version of SPICE3 (version 3F.2) [JOHN92] to a internal C-based
device simulator, DSIM. SPICE3 provides circuit analyses, compact models for semiconductor
devices, and an interactive user interface. DSIM 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. DSIM 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. For example, SPICE3F.2 input f i les
should run without modif i cation, producing identical results.

CIDER is based on the mixed-level circuit and device simulator CODECS [MAYA88] and is a
replacement for this program. The basic algorithms of the two programs are the same. Some of
the differences between CIDER and CODECS are described below. The CIDER input format
has greater f l exibility 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 trans-
verse f i eld mobility degradation [GATE90] that is important in scaled-down MOSFETs and a
polysilicon model for poly-emitter bipolar transistors. Temperature dependence has been in-
cluded 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 capaci-
tors, 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 NUTMEG user interface of SPICE3.

227


228CHAPTER 14. MIXED-LEVEL SIMULATION (NGSPICE WITH TCAD)

Previously computed states can be loaded into the program to provide accurate initial guesses
for subsequent analyses. Finally, numerous small bugs have been discovered and f i xed, and the
program has been ported to a wider variety of computing platforms.

Berkeley tradition calls for the naming of new versions of programs by aff i xing a (number,
letter, number) triplet to the end of the program name. Under this scheme, CIDER should
instead be named CODECS2A.l. However, tradition has been broken in this case because major
incompatibilities exist between the two programs and because it was observed that the acronym
CODECS is already used in the analog design community to refer to coder-decoder circuits.

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 which describes all of
the relevant background material. Comprehensive reviews of device simulation can be found
in [PINT90] and the book [SELB84]. CODECS 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].

14.2GSS, Genius

For LINUX users the cooperation of the TCAD software GSS with ngspice might be of interest,
see http://ngspice.sourceforge.net/gss.html. This project is no longer maintained however, but
has moved into the Genius simulator, still available as open source cogenda genius.


Chapter 15

Analyses and Output Control (batch
mode)

The command lines described in this chapter are specifying analyses and outputs within the
circuit description f i le. They start with a “.” (dot commands). Specifying analyses and plots
(or tables) in the input f i le with dot commands is used with batch runs. Batch mode is entered
when either the -b option is given upon starting ngspice

ngspice -b -r rawfile.raw circuitfile.cir

or when the default input source is redirected from a f i le (see also chapt. 16.4.1).

ngspice < circuitfile.cir

In batch mode, the analyses specif i ed by the control lines in the input f i le (e.g. “.ac”, “.tran”,
etc.) are immediately executed. If the -r rawf i le option is given then all data generated is
written to a ngspice rawf i le. The rawf i le may later be read by the interactive mode of ngspice
using the “load” command (see 17.5.36). In this case, the .save line (see 15.6) may be used to
record the value of internal device variables (see Appendix, chapter 31).

If a rawf i le is not specif i ed, then output plots (in “line-printer” form) and tables can be printed
according to the .print, .plot, and .four control lines, described in chapter 15.6.

If ngspice is started in interactive mode (see chapt. 16.4.2), like

ngspice circuitfile.cir

and no control section (.control ... .endc, see 16.4.3) is provided in the circuit f i le, the dot
commands are not executed immediately, but are waiting for manually receiving the command
“run”.

15.1Simulator Variables (.options)

Various parameters of the simulations available in Ngspice can be altered to control the ac-
curacy, speed, or default values for some devices. These parameters may be changed via the
“option” command (described in chapt. 17.5.42) or via the “.options” line:

229


230CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

General form:

. optionsopt1opt2. . .( oropt=optval. . . )

Examples:

. optionsr e l t o l =.005t r t o l =8

The options line allows the user to reset program control and user options for specif i c simulation
purposes. Options specif i ed to Ngspice via the “option” command (see chapt. ) are also
passed on as if specif i ed on a .options line. Any combination of the following options may
be included, in any order. “x” (below) represents some positive number.

15.1.1General Options

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.

OPTS causes the option values to be printed.

TEMP=x Resets the operating temperature of the circuit. The default value is 27

◦C (300K).

TEMP can be overridden per device by a temperature specif i cation on any temperature
dependent instance. May also be generally overridden by a .TEMP card (2.11).

TNOM=x resets the nominal temperature at which device parameters are measured. The de-
fault value is 27

◦C (300 deg K). TNOM can be overridden by a specif i cation on any

temperature dependent device model.

WARN=1|0 enables or turns of SOA (Safe Operating Area) voltage warning messages (default:
0).

MAXWARNS=x specif i es the maximum number of SOA (Safe Operating Area) warning mes-
sages per model (default: 5).

SAVECURRENTS save currents through all terminals of the following devices: M, J, Q, D,
R, C, L, B, F, G, W, S, I (see 2.1.2). Recommended only for small circuits, because
otherwise memory requirements explode and simulation speed suffers. See 15.7 for more
details.


15.1. SIMULATOR VARIABLES (.OPTIONS)231

15.1.2DC Solution Options

The following options controls properties pertaining to DC analysis and algorithms. Since
transient analysis is based on DC many of the options affect the latter one.

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.

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 Retaintheoperatingpoint 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.

PIVREL=x 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 algorithm the allowed min-
imum pivot value is determined by EPSREL=AMAX1(PIVREL*MAXVAL, PIVTOL)
where MAXVAL is the maximum element in the column where a pivot is sought (partial
pivoting).

PIVTOL=x resets the absolute minimum value for a matrix entry to be accepted as a pivot.
The default value is 1.0e-13.

RELTOL=x resets the relative error tolerance of the program. The default value is 0.001
(0.1%).

RSHUNT=x introduces a resistor from each analog node to ground. The value of the resistor
should be high enough to not interfere with circuit operations. The XSPICE option has to
be enabled (see 32.1.5) .

VNTOL=x resets the absolute voltage error tolerance of the program. The default value is 1
µV.

15.1.2.1Matrix Conditioning info

In most SPICE-based simulators, problems can arise with certain circuit topologies. One of
the most common problems is the absence of a DC path to ground at some node. This may
happen, for example, when two capacitors are connected in series with no other connection at
the common node or when certain code models are cascaded. The result is an ill-conditioned
or nearly singular matrix that prevents the simulation from completing. The XSPICE option
introduces the “rshunt” option to help eliminate this problem. When used, this option inserts
resistors to ground at all the analog nodes in the circuit. In general, the value of “rshunt” should
be set to some very high resistance (e.g. 1000 Meg Ohms or greater) so that the operation of the
circuit is essentially unaffected, but the matrix problems are corrected. If you should encounter
a “no DC path to ground” or a “matrix is nearly singular” error message with your circuit, you
should try adding the following .option card to your circuit description deck.


232CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

.option rshunt = 1.0e12

Usually a value of 1.0e12 is suff i cient to correct the matrix problems. However, if you still have
problems, you may wish to try lowering this value to 1.0e10 or 1.0e9.

Another matrix conditioning problem might occur if you try to place an inductor in parallel to
a voltage source. An ac simulation will fail, because it is preceded by an op analysis. Option
noopac (15.1.3) will help if the circuit is linear. If the circuit is non-linear, you will need the
op analysis. Then adding a small resistor (e.g. 1e-4 Ohms) in series to the inductor will help to
obtain convergence.

.option rseries = 1.0e-4

will add a series resistor to each inductor in the circuit. Be careful if you use behavioral induc-
tors (see 3.2.12), because the result may become unpredictable.

15.1.3AC Solution Options

NOOPAC Do not do an operating point (OP) analysis before the AC analysis. To become
valid, this option requires that the circuit is linear, thus 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 will
be executed automatically. This option is of interest for example in nested LC circuits,
where there is no series resistance for the L device given, which during OP analysis may
result in an ill formed matrix, yields an error message and aborts the simulation.

15.1.4Transient Analysis Options

AUTOSTOP stops a transient analysis after successfully calculating all measure functions
(15.4)specif i edwiththedotcommand.meas. autostopisnotavailablewithmeas(17.5.37)
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.

GMINSTEPS=x [*] sets number of Gmin steps to be attempted. If the value is set to zero, the
gmin stepping algorithm is disabled. In such case the source stepping algorithm becomes
the standard when the standard procedure fails to converge to a solution.

INTERP interpolates output data onto f i xed time steps, detemined by TSTEP (15.3.9). Uses
linear interpolation between previous and next time value. Simulation itself is not inf l u-
enced by this option. May be used in all simulation modes (batch, control or interactive,
16.4). This option may drastically reduce memory requirements in control mode or f i le
size in batch mode, but be careful not to choose a too large TSTEP value, otherwise your
output data may be corrupted by undersampling. See command ’linearize’ (17.5.34) in
control or interactive mode to achieve similar outputs by post-processing of data. See
ngspice/examples/xspice/delta-sigma/delta-sigma-1.cir how INTERP will reduce mem-
ory requirements and speeds up plotting.


15.1. SIMULATOR VARIABLES (.OPTIONS)233

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.

MAXEVITER=x sets the number of event iterations that are allowed at an analysis point

MAXOPALTER=x specif i es the maximum number of analog/event alternations that the sim-
ulator can use in solving a hybrid circuit.

MAXORD=x [*] specif i es 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 specif i es 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/event are enabled.

RAMPTIME=x this options sets the rate of change of independent supplies and code model
inductors and capacitors with initial conditions specif i ed.

SRCSTEPS=x [*] a non-zero value causes SPICE to use a source-stepping method to f i nd the
DC operating point. Its value specif i es the number of steps.

TRTOL=x resets the transient error tolerance. The default value is 7. This parameter is an esti-
mate of the factor by which ngspice overestimates the actual truncation error. If XSPICE
is enabled and ’A’ devices included, the value is internally set to 1 for higher precision.
This will cost a factor of two in CPU time during transient analysis.

15.1.5ELEMENT Specif i c options

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.0.

DEFAS=x resets the value for MOS source diffusion area; the default is 0.0.

DEFL=x resets the value for MOS channel length; the default is 100.0 µm.

DEFW=x resets the value for MOS channel width; the default is 100.0 µm.

SCALE=x set the element scaling factor for geometric element parameters whose default unit
is meters. As an example: scale=1u and a MOSFET instance parameter W=10 will result
in a width of 10µm for this device. An area parameter AD=20 will result in 20e-12 m2.
Following instance parameters are scaled:

• Resistors and Capacitors: W, L


234CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

• Diodes: W, L, Area

• JFET, MESFET: W, L, Area

• MOSFET: W, L, AS, AD, PS, PD, SA, SB, SC, SD

15.1.6Transmission Lines Specif i c Options

TRYTOCOMPACT Applicable only to the LTRA model (see 6.2.1). When specif i ed, the
simulator tries to condense LTRA transmission line’s past history of input voltages and
currents.

15.1.7Precedence of option and .options commands

There are various ways to set the above mentioned options in Ngspice.If no option or
.options lines are set by the user, internal default values are given for each of the simula-
tor variables.

You may set options in the init f i les spinit or .spiceinit via the option command (see chapt.
17.5.42). The values given here will supersede the default values. If you set options via the
.options line in your input f i le, their values will supersede the default and init f i le data. Finally
if you set options inside a .control ... .endc section, these values will supersede any values of
the respective simulator variables given so far.

15.2Initial Conditions

15.2.1.NODESET: Specify Initial Node Voltage Guesses

General form:

.NODESET V(NODNUM)=VAL V(NODNUM)=VAL . . .
.NODESET ALL=VAL

Examples:

.NODESET V(12)=4.5 V(4)=2.23
.NODESET ALL=1.5

The .nodeset line helps the program f i nd the dc or initial transient solution by making a pre-
liminary pass with the specif i ed nodes held to the given voltages. The restriction is then released
and the iteration continues to the true solution. The .nodeset line may be necessary for con-
vergence on bistable or a-stable circuits. .nodeset all=val allows to set all starting node
voltages (except for the ground node) in a single line. In general, the .nodeset line should not
be necessary.


15.3. ANALYSES235

15.2.2.IC: Set Initial Conditions

General form:

. icv(nodnum)= val v(nodnum)= val. . .

Examples:

. icv(11)=5 v(4)=−5 v (2)=2.2

The .ic line is for setting transient initial conditions. It has two different interpretations, de-
pending on whether the uic parameter is specif i ed on the .tran control line. Also, one should
not confuse this line with the .nodeset line. The .nodeset line is only to help dc convergence,
and does not affect f i nal bias solution (except for multi-stable circuits). The two interpretations
of this line are as follows:

1. When the uic parameter is specif i ed on the .tran line, then the node voltages specif i ed
onthe.iccontrollineareusedtocomputethecapacitor, diode, BJT,JFET,andMOSFET
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 specif i ed 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 specif i ed on the .tran control line, the dc bias (initial
transient) solution is computed before the transient analysis. In this case, the node volt-
ages specif i ed on the .ic control line is 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.3Analyses

15.3.1.AC: Small-Signal AC Analysis

General form:

. acdec ndf s t a r tfstop
. acoctnof s t a r tfstop
. aclinnpf s t a r tfstop

Examples:

. acdec 10 1 10K
. acdec 10 1K 100MEG
. aclin100 1 100HZ

dec stands for decade variation, and nd is the number of points per decade. oct stands for
octave variation, and no is the number of points per octave. lin stands for linear variation, and
np is the number of points. fstart is the starting frequency, and fstop is the f i nal frequency.
If this line is included in the input f i le, ngspice performs an AC analysis of the circuit over the
specif i ed frequency range. Note that in order for this analysis to be meaningful, at least one


236CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

independent source must have been specif i ed 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, thus diff i cult to interpret.

Example:

Basic RC c i r c u i t
r 1 2 1.0
c 2 0 1.0
vin 1 0 dc 0 ac 1$ <−−− theacsource
. optionsnoacct
. acdec 10.0110
. plotacvdb (2)xlog
. end

In this ac (or ’small signal’) analysis all non-linear devices are linearized around their actual dc
operating point. All Ls and Cs get their imaginary value, depending on the actual frequency
step. Each output vector will be calculated relative to the input voltage (current) given by the ac
value (Vin equals to 1 in the example above). The resulting node voltages (and branch currents)
are complex vectors. Therefore you have to be careful using the plot command. Especially you
may use the variants of vxx(node) described in chapter 15.6.2 like vdb(2) (see example above).

15.3.2.DC: DC Transfer Function

General form:

. dc srcnamvstartvstopvincr[ src2start2stop2incr2 ]

Examples:

. dc VIN 0.255.00.25
. dc VDS 0 10.5 VGS 0 5 1
. dc VCE 0 10.25IB 0 10U 1U
. dc RLoad 1k 2k 100
. dc TEMP −15 75 5

The .dc line def i nes the dc transfer curve source and sweep limits (again with capacitors open
and inductors shorted). srcnam is the name of an independent voltage or current source, a
resistor or the circuit temperature. vstart, vstop, and vincr are the starting, f i nal, and in-
crementing values respectively. The f i rst example causes the value of the voltage source VIN
to be swept from 0.25 Volts to 5.0 Volts in increments of 0.25 Volts. A second source (src2)
may optionally be specif i ed with associated sweep parameters. In this case, the f i rst source is
swept over its range for each value of the second source. This option can be useful for obtaining
semiconductor device output characteristics. See the example circuit description on transistor
characteristics (21.3).


15.3. ANALYSES237

15.3.3.DISTO: Distortion Analysis

General form:

. distodec ndf s t a r tfstop <f2overf1 >
. distooctnof s t a r tfstop <f2overf1 >
. distolinnpf s t a r tfstop <f2overf1 >

Examples:

. distodec 10 1kHz 100Mhz
. distodec 10 1kHz 100Mhz 0.9

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 nonlin-
earities at the operating point. Terms of up to third order are used in the series expansions.

If the optional parameter f2overf1 is not specif i ed, .disto does a harmonic analysis - i.e.,
it analyses distortion in the circuit using only a single input frequency F1, which is swept as
specif i ed by arguments of the .disto command exactly as in the .ac command. Inputs at this
frequency may be present at more than one input source, and their magnitudes and phases are
specif i ed by the arguments of the distof1 keyword in the input f i le 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 2F1and , vs. the input frequency F1as it is swept. (A value of 1
(as a complex distortion output) signif i es cos(2π(2F1)t) at 2F1and cos(2π(3F1)t) at 3F1, using
the convention that 1 at the input fundamental frequency is equivalent to cos(2πF1t).) The
distortion component desired (2F1or 3F1) can be selected using commands in ngnutmeg, and
then printed or plotted. (Normally, one is interested primarily in the magnitude of the harmonic
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 components, and are not equal to HD2 and HD3.
To obtain HD2 and HD3, one must divide by the corresponding AC values at F1, obtained from
an .ac line. This division can be done using ngnutmeg commands.

If the optional f2overf1 parameter is specif i ed, it should be a real number between (and not
equal to) 0.0 and 1.0; in this case, .disto does a spectral analysis. It considers the circuit with
sinusoidal inputs at two different frequencies F1and F2. F1is swept according to the .disto
control line options exactly as in the .ac control line. F2is kept f i xed at a single frequency
as F1sweeps - the value at which it is kept f i xed is equal to f2overf1 times fstart. Each
independent source in the circuit may potentially have two (superimposed) sinusoidal inputs
for distortion, at the frequencies F1and F2. The magnitude and phase of the F1component are
specif i ed by the arguments of the distof1 keyword in the source’s input line (see the descrip-
tion of independent sources); the magnitude and phase of the F2component are specif i ed by the
arguments of the distof2 keyword. The analysis produces plots of all node voltages/branch
currents at the intermodulation product frequencies F1+F2, F1−F2, and (2F1)−F2, vs the
swept frequency F1. 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


238CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

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 specif i ed
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 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 represented as a fraction

A/B, where A and B are integers with no common
factors, B should be as large as possible; note that A < B because f2overf1 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 F1+F2, F1−F2and 2F1−F2. In the latter case,
F1−F2= F2, so the result at the F1−F2component is erroneous because there is the strong
fundamental F2component at the same frequency. Also, F1+F2= 2F1−F2in the latter case,
and each result is erroneous individually. This problem is not there in the case where f2overf1
= 49/100, because F1−F2= 51/100 F1<> 49/100 F1= F2. In this case, there are two very
closely spaced frequency components at F2and F1−F2. One of the advantages of the Volterra
series technique is that it computes distortions at mix frequencies expressed symbolically (i.e.
nF1+mF2), 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)ptsf s t a r tfstop
+ <pts_per_summary >

Examples:

. noise v (5) VIN dec 10 1kHZ 100Mhz
. noise v (5 ,3) V1 oct 8 1.01.0 e6 1

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 specif i ed, 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


15.3. ANALYSES239

the frequency range over which plots are desired. pts_per_summary is an optional integer; if
specif i ed, the noise contributions of each noise generator is produced every pts_per_summary
frequency points. The .noise control line produces two plots:

1. one for the Noise Spectral Density curves and

2. one for the total Integrated Noise over the specif i ed frequency range.

All noise voltages/currents are in squared units (V2/HzandA2/Hzfor spectral density, V2and A2
for integrated noise).

15.3.5.OP: Operating Point Analysis

General form:

. op

The inclusion of this line in an input f i le directs ngspice to determine the dc operating point of
the circuit with inductors shorted and capacitors opened.

Note: a DC analysis is automatically performed prior to a transient analysis 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 (see the KEEPOPINFO
variable 15.1.2).

15.3.6.PZ: Pole-Zero Analysis

General form:

. pz node1 node2 node3 node4curpol
. pz node1 node2 node3 node4curzer
. pz node1 node2 node3 node4curpz
. pz node1 node2 node3 node4volpol
. pz node1 node2 NODE3 node4volzer
. pz node1 node2 node3 node4volpz

Examples:

. pz 1 0 3 0 curpol
. pz 2 3 5 0 volzer
. pz 4 1 4 1 curpz

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 nonconvergence in f i nding 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.


240CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

In interactive mode, the command syntax is the same except that the f i rst f i eld is pz instead of
.pz. To print the results, one should use the command “print all”.

15.3.7.SENS: DC or Small-Signal AC Sensitivity Analysis

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 specif i ed. OUTVAR is a circuit variable (node voltage or voltage-source branch
current). The f i rst 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).

15.3.8.TF: Transfer Function Analysis

General form:

. tfoutvarinsrc

Examples:

. tfv(5 ,3) VIN
. tfi (VLOAD) VIN

The .tf line def i nes 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 f i rst example, ngspice would compute the ratio
ofV(5, 3)toVIN,thesmall-signalinputresistanceatVIN,andthesmallsignaloutputresistance
measured across nodes 5 and 3.


15.3. ANALYSES241

15.3.9.TRAN: Transient Analysis

General form:

. trantsteptstop< t s t a r t<tmax>> <uic >

Examples:

. tran1ns 100ns
. tran1ns 1000ns 500ns
. tran10ns 1us

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 f i nal 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 which is smaller than the printer increment, tstep.

An initial transient operating point at time zero is calculated according to the following proce-
dure: all independent voltages and currents are applied with their time zero values, all capaci-
tancesareopened, inductancesareshorted, thenonlineardeviceequationsaresolvediteratively.

uic (use initial conditions) is an optional keyword which indicates that the user does not want
ngspice to solve for the quiescent operating point before beginning the transient analysis. If this
keyword is specif i ed, ngspice uses the values specif i ed using IC=... on the various elements as
the initial transient condition and proceeds with the analysis. If the .ic control line has been
specif i ed (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 specif i c 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
specif i ed.

15.3.10Transient noise analysis (at low frequency)

In contrast to the analysis types described above the transient noise simulation (noise current or
voltage versus time) is not implemented as a dot command, but is integrated with the indepen-
dent voltage source vsrc (isrc still not yet available) (see 4.1.7) and used in combination with
the .tran transient analysis (15.3.9).

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 f i xed 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 modif i cations 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 f l y, each time when a breakpoint is hit.


242CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

The 1/f noise is generated with an algorithm provided by N. J. Kasdin (“Discrete simulation of
colored noise and stochastic processes and 1/fapower 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 source with 1/f selected) is generated upon start up of the simulator and stored
for later use. The number of point is determined by the total simulation time divided by NT,
rounded up the the nearest power of 2. Each time a breakpoint (n?NT, relevant to the noise
signal) is hit, the next value is retrieved from the sequence.

If you want a random, but reproducible sequence, you may select a seed value for the random
number generator by adding

set rndseed=nn

to the spinit or .spiceinit f i le, nn being a positive integer number.

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 f l owing through a device and may be simulated by applying a non-linear source as
demonstrated in the following example:

Example:

*

Shotnoiset e s twith B source ,diode
*

voltageondevice( diode ,forward )
Vdev out 0 DC 0 PULSE(0.40.45 10u)
*

diode ,forwarddirection ,tobe modeledwithnoise
D1 mess 0 DMOD
. model DMOD D IS=1e−14 N=1
X1 0 messoutishot
*

devicebetween 1 and 2
*

new outputterminalsofdeviceincludingnoise :1 and 3
. subcktishot1 2 3
*

whitenoisesourcewith rms 1V
*

20000 samplepoints
VNG 0 11 DC 0 TRNOISE(1 1n 0 0)
*measure

thecurrenti (v1)
V1 2 3 DC 0
*

calculatetheshotnoise
*

sqrt (2*current*q*bandwidth )
BI 1 3 I=sqrt (2*abs ( i (v1 ))*1.6 e−19*1e7 )*v(11)
. endsishot

. tran1n 20u
. control
run
plot(−1)*i ( vdev )
. endc
. end

The selection of the delta time step (NT) is worth discussing. Gaussian white noise has unlim-
ited bandwidth and thus unlimited energy content. This is unrealistic. The bandwidth of real


15.3. ANALYSES243

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 clar-
ify the appropriate factor! The transient method is probably most suited for circuits including
switches, which are not amenable to the small signal .NOISE analysis (chapter 15.3.4).

This is the price you have to pay for transient noise analysis: the number of required time steps
for simulation will increase, and thus the simulation time. But modern computers deliver a lot
of speed, and it may be well worth of trying and experimenting.

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 inf l uence of a single trap on the current or voltage. The capture
and emission times emulate the f i lling and emptying of the trap, typically following a Poisson
process. They are generated from an random exponential distribution with their 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.


244CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

RTS noise example:

*

whitenoise ,1/ fnoise , RTS noise

*

voltagesource
VRTS2 13 12 DC 0trnoise (0 0 0 0 5m 18u 30u)
VRTS3 11 0 DC 0trnoise (0 0 0 0 10m 20u 40u)
VALL 12 11 DC 0trnoise (1m 1u 1.00.1m 15m 22u 50u)

VW1of 21 0 DCtrnoise (1m 1u 1.00.1m)

*

currentsource
IRTS2 10 0 DC 0trnoise (0 0 0 0 5m 18u 30u)
IRTS3 10 0 DC 0trnoise (0 0 0 0 10m 20u 40u)
IALL 10 0 DC 0trnoise (1m 1u 1.00.1m 15m 22u 50u)
R10 10 0 1

IW1of 9 0 DCtrnoise (1m 1u 1.00.1m)
Rall 9 0 1

*

samplepoints
. tran1u 500u

. control
run
plotv(13) v(21)
plotv(10) v (9)
. endc

. end

Some details on RTS noise modeling are available in a recent article [20], available here.

Anyhow this transient noise feature is still experimental!

The following questions (among others) are to be solved:

• clarify the theoretical background

• noise limit of plain ngspice (numerical solver, fft etc.)

• time step (NT) selection

• calibration of noise spectral density

• how to generate noise from a transistor model

• application benef i ts and limits

15.3.11.PSS: Periodic Steady State Analysis

(Experimental code, not yet made publicly available!)


15.4. MEASUREMENTS AFTER AC, DC AND TRANSIENT ANALYSIS245

General form:

. pssgfreqtstaboscnobpsspointsharmss c i t e rsteadycoeff <uic >

Examples:

. pss150 200e−3 2 1024 11 50 5e−3 uic
. pss624e6 1u v_plus1024 10 150 5e−3 uic
. pss624e6 500n bout1024 10 100 5e−3 uic

gfreq is guessed frequency of fundamental suggested by user. When performing transient
analysis the PSS algorithm tries to infer a new rough guess rgfreq on the fundamental. If
gfreq is out of ±10% with respect to rgfreq then gfreq is discarded.

tstab is stabilization time before the shooting begin to search for the PSS. It has to be noticed
that this parameter heavily inf l uence 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.

harms number of harmonics to be calculated as requested by the user.

sciter number of allowed shooting cycle iterations. Default is 50.

steady_coeffistheweightingcoeff i cientforcalculatingtheGlobalConvergenceError(GCE)
whichisthereferencevalueinordertoinferisconvergenceisreached. Thelowersteady_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 which indicates that the user does not want
ngspice to solve for the quiescent operating point before beginning the transient analysis. If this
keyword is specif i ed, ngspice uses the values specif i ed using IC=... on the various elements as
the initial transient condition and proceeds with the analysis. If the .ic control line has been
specif i ed, 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 specif i ed.

15.4Measurements after AC, DC and Transient Analysis

15.4.1.meas(ure)

The .meas or .measure statement (and its equivalent meas command, see chapt. 17.5.37) are
used to analyze the output data of a tran, ac, or dc simulation. The command is executed
immediately after the simulation has f i nished.


246CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

15.4.2batch versus interactive mode

.meas analysis may not be used in batch mode (-b command line option), if an output f i le
(rawf i le) is given at the same time (-r rawfile command line option). In this batch mode
ngspice will write its simulation output data directly to the output f i le. The data is not kept in
memory, thus is no longer available for further analysis. This is made to allow a very large
output stream with only a relatively small memory usage. For .meas to be active you need to
run the batch mode with a .plot or .print command. A better alternative may be to start
ngspice in interactive mode.

If you need batch like operation, you may add a .control ....endc section to the input
f i le:

Example:

*input

f i l e
. . .
. tran1ns 1000ns
. . .
*********************************
. control
run
writeoutputfiledata
. endc
*********************************
. end

and start ngspice in interactive mode, e.g. by running the command

ngspice inputfile .

.meas<ure> then prints its user-def i ned data analysis to the standard output. The analysis in-
cludes propagation, delay, rise time, fall time, peak-to-peak voltage, minimum or maximum
voltage, the integral or derivative over a specif i ed period and several other user def i ned values.

15.4.3General remarks

The measure type {DC|AC|TRAN|SP} depends on the data which are to be evaluated, either
originating from a dc analysis, an ac analysis, a transient simulation. SP to analyze a spectrum
from the spec or fft commands is only available when executed in a meas command, see
17.5.37.

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 in ” 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.


15.4. MEASUREMENTS AFTER AC, DC AND TRANSIENT ANALYSIS247

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.

*

************

Be careful because not all of the .measure commands have been implemented so far!

’deriv’ and ’error’ is missing

************

*

15.4.4Input

In the following lines you will get some explanation on the .measure commands. A simple
simulation f i le 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 f i le:

File :simple−meas−tran . sp
*

Simple. measurementexamples
*

transientsimulationof twosinesignalswithdifferent
frequencies
vac1 1 0 DC 0sin (0 1 1k 0 0)
vac2 2 0 DC 0sin (01.20.9k 0 0)
. tran10u 5m
*
. measuretran. . .$forthedifferentinputsseebelow !
*
. control
run
plotv (1)v (2)
. endc
. end

After displaying the general syntax of the .measurement statement, some examples are posted,
referring to the input f i le given above.

15.4.5Trig Targ

.measure according to general form 1 measures the difference in dc voltage, frequency or time
between two points selected from one or two output vectors. The current examples all are using
transient simulation. Measurements for tran analysis start after a delay time td. If you run other
examples with ac simulation or spectrum analysis, time may be replaced by frequency, after a
dc simulation the independent variable may become a voltage or current.


248CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

General form 1:

.MEASURE {DC|AC|TRAN| SP}resultTRIGtrig_variable VAL=val <TD=
td > <CROSS=#| CROSS=LAST> <RISE=#|RISE=LAST> <FALL=#|
FALL=LAST> <TRIG AT=time > TARG targ_variable VAL=val <TD=td >
<CROSS=#| CROSS=LAST> <RISE=#|RISE=LAST> <FALL=#| FALL=
LAST> <TARG AT=time >

Measure statement example (for use in the input f i le 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 f i rst time on its f i rst rising
slope (TRIG) versus reaching 0.5 V again on its second rising slope (TARG). I.e. it measures
the signal period.

Output:

tdiff = 1.000000e-003 targ= 1.083343e-003 trig= 8.334295e-005

Measure statement example:

.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 f i rst 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 f i rst time on its rising slope
versus reaching 0.5 V on its f i rst 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) reach-
ing 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 f i rst time (any slope) versus
v(2) crossing -0.8 V for the f i rst time (any slope).

Measure statement:

.measure tran tdiff TRIG AT=1m TARG v(2) VAL=-0.8 CROSS=3

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).

15.4.6Find ... When

The FIND and WHEN functions allow to measure any dependent or independent time, fre-
quency, or dc parameter, when two signals cross each other or a signal crosses a given value.
Measurements start after a delay TD and may be restricted to a range between FROM and TO.


15.4. MEASUREMENTS AFTER AC, DC AND TRANSIENT ANALYSIS249

General form 2:

.MEASURE {DC|AC|TRAN| SP}result WHEN out_variable=val <TD=td > <
FROM=val > <TO=val > <CROSS=#| CROSS=LAST> <RISE=#|RISE=
LAST> <FALL=#| FALL=LAST>

Measure statement:

.measure tran teval WHEN v(2)=0.7 CROSS=LAST

measures the time point when v(2) crosses 0.7 V for the last time (any slope).

General form 3:

.MEASURE {DC|AC|TRAN| SP}result WHEN out_variable=out_variable2
<TD=td > <FROM=val > <TO=val > <CROSS=#| CROSS=LAST> <RISE=#
|RISE=LAST> <FALL=#| FALL=LAST>

Measure statement:

.measure tran teval WHEN v(2)=v(1) RISE=LAST

measures the time point when v(2) and v(1) are equal, v(2) rising for the last time.

General form 4:

.MEASURE {DC|AC|TRAN| SP}resultFIND out_variable WHEN
out_variable2=val <TD=td > <FROM=val > <TO=val > <CROSS=#|
CROSS=LAST> <RISE=#|RISE=LAST> <FALL=#| FALL=LAST>

Measure statement:

.measure tran yeval FIND v(2) WHEN v(1)=-0.4 FALL=LAST

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 {DC|AC|TRAN| SP}resultFIND out_variable WHEN
out_variable2=out_variable3<TD=td > <CROSS=#| CROSS=LAST>
<RISE=#|RISE=LAST> <FALL=#|FALL=LAST>

Measure statement:

.measure tran yeval FIND v(2) WHEN v(1)=v(3) FALL=2

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 {DC|AC|TRAN| SP}resultFIND out_variable AT=val

Measure statement:

.measure tran yeval FIND v(2) AT=2m

returns the dependent (y) variable drawn from v(2) at the time point 2 ms (given by AT=time).


250CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

15.4.7AVG|MIN|MAX|PP|RMS|MIN_AT|MAX_AT

General form 7:

.MEASURE {DC|AC|TRAN| SP}result{AVG|MIN|MAX| PP |RMS|MIN_AT|
MAX_AT}out_variable <TD=td > <FROM=val > <TO=val >

Measure statements:

.measure tran ymax MAX v(2) from=2m to=3m

returns the maximum value of v(2) inside the time interval between 2 ms and 3 ms.

.measure tran tymax MAX_AT v(2) from=2m to=3m

returns the time point of the maximum value of v(2) inside the time interval between 2 ms and
3 ms.

.measure tran ypp PP v(1) from=2m to=4m

returns the peak to peak value of v(1) inside the time interval between 2 ms and 4 ms.

.measure tran yrms RMS v(1) from=2m to=4m

returns the root mean square value of v(1) inside the time interval between 2 ms and 4 ms.

.measure tran yavg AVG v(1) from=2m to=4m

returns the average value of v(1) inside the time interval between 2 ms and 4 ms.

15.4.8Integ

General form 8:

.MEASURE {DC|AC|TRAN| SP}result INTEG<RAL> out_variable <TD=td >
<FROM=val > <TO=val >

Measure statement:

.measure tran yint INTEG v(2) from=2m to=3m

returns the area under v(2) inside the time interval between 2 ms and 3 ms.

15.4.9param

General form 9:

.MEASURE {DC|AC|TRAN| SP}resultparam=’ expression ’

Measure statement:

.param fval=5

.measure tran yadd param=’fval + 7’

will evaluate the given expression fval + 7 and return the value 12.

’Expression’ is evaluated according to the rules given in chapt. 2.8.5 during start up of ngspice.
It may contain parameters def i ned with the .param statement. It may also contain parameters
resulting from preceding .meas statements.


15.4. MEASUREMENTS AFTER AC, DC AND TRANSIENT ANALYSIS251

.param vout_diff=50u

...

.measure tran tdiff TRIG AT=1m TARG v(2) VAL=-0.8 CROSS=3

.meas tran bw_chk param=’(tdiff < vout_diff) ?1 :0’

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.10par(’expression’)

The par(’expression’) option (15.6.6) allows to use algebraic expressions in the .measure
lines. Every out_variable may be replaced by par(’expression’) within the general forms 1-9
described above. Internally par(’expression’) will be 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:

General form 10:

.MEASURE {DC|AC|TRAN| SP}resultFIND par ( ’ expression ’) AT=val

Measure statement:

.measure tran vtest find par(’(v(2)*v(1))’) AT=2.3m

will return the product of the two voltages at time point 2.3 ms.

15.4.11Deriv

General form:

.MEASURE {DC|AC|TRAN| SP}result DERIV<ATIVE> out_variable AT=
val

.MEASURE {DC|AC|TRAN| SP}result DERIV<ATIVE> out_variable WHEN
out_variable2=val+ <TD=td >
+ <CROSS=#| CROSS=LAST> <RISE=#|RISE=LAST> <FALL=#|FALL=LAST>

.MEASURE {DC|AC|TRAN| SP}result DERIV<ATIVE> out_variable
+ WHEN out_variable2=out_variable3
+ <TD=td >
+ <CROSS=#| CROSS=LAST> <RISE=#|RISE=LAST> <FALL=#|FALL=LAST>

.MEASURE {DC|AC|TRAN|SP} result DERIV<ATIVE> ... is not yet available.

15.4.12More examples

Some other examples, also showing the use of parameters, are given below. Corresponding
demonstration input f i les are distributed with ngspice in folder /examples/measure.


252CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

Other examples:

. meastraninv_delay2t r i gv( in )val =’vp /2 ’td=1nf a l l =1targv
( out )
+val =’vp /2 ’rise =1
. meastrantest_data1t r i g AT = 1ntargv( out )val =’vp /2 ’rise
=3
. meastranout_slewt r i gv( out )val = ’0.2*vp ’rise =2targv( out )
+val = ’0.8*vp ’rise =2
. meastrandelay_chkparam= ’( inv_delay < 100ps )? 1:0’
. meastranskew when v( out ) =0.6
. meastranskew2 when v( out )=skew_meas
. meastranskew3 when v( out )=skew_measf a l l =2
. meastranskew4 when v( out )=skew_measf a l l =LAST
. meastranskew5 FIND v( out ) AT=2n
. meastranv0_minmini (v0 )from=’ dfall ’to =’ dfall +period ’
. meastranv0_avg avgi (v0 )from=’ dfall ’to =’ dfall +period ’
. meastranv0_integintegi ( v0 )from=’ dfall ’to =’ dfall +period ’
. meastranv0_rms rmsi (v0 )from=’ dfall ’to =’ dfall +period ’
. meas dcis_at FIND i ( vs ) AT=1
. meas dc is_max max i ( vs )from=0 to =3.5
. meas dcvds_at wheni ( vs ) =0.01
. meas acvout_at FIND v( out ) AT=1MEG
. meas acvout_atd FIND vdb ( out ) AT=1MEG
. meas ac vout_max max v( out )from=1k to=10MEG
. meas acfreq_atwhen v( out ) =0.1
. meas acvout_difft r i gv( out )val =0.1rise =1targv( out )val
=0.1f a l l =1
. meas acfixed_difft r i g AT = 10ktargv( out )val =0.1rise =1
. meas acvout_avgavgv( out )from=10k to=1MEG
. meas acvout_integintegv( out )from=20k to =500k
. meas acfreq_at2when v( out ) =0.1f a l l =LAST
. meas ac bw_chk param= ’( vout_diff < 100k)? 1:0’
. meas acvout_rms rms v( out )from=10 to=1G

15.5Safe Operating Area (SOA) warning messages

By setting the .option warn=1 the Safe Operation Area check algorithm is enabled. In this case
for .op, .dc and .tran analysis warning messages are issued if the branch voltages of devices (Re-
sistors, Capacitors, Diodes, BJTs and MOSFETs) exceed limits which are specif i ed by model
parameters. All these parameters are positive with default value of inf i nity.

The check is executed after Newton-Raphson iteration is f i nished 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 f i le specif i ed by command line option
–soa-log=f i lename.


15.6. BATCH OUTPUT253

15.5.1Resistor and Capacitor SOA model parameters

1. Bv_max:if |Vr| or |Vc| exceed Bv_max, SOA warning is issued.

15.5.2Diode SOA model parameter

1. Bv_max:if |Vj| exceeds Bv_max, SOA warning is issued.

2. Fv_max:if |Vf| exceeds Fv_max, SOA warning is issued.

15.5.3BJT SOA model parameter

1. Vbe_max:if |Vbe| exceeds Vbe_max, SOA warning is issued.

2. Vbc_max:if |Vbc| exceeds Vbc_max, SOA warning is issued.

3. Vce_max:if |Vce| exceeds Vce_max, SOA warning is issued.

4. Vcs_max:if |Vcs| exceeds Vcs_max, SOA warning is issued.

15.5.4MOS SOA model parameter

1. Vgs_max:if |Vgs| exceeds Vgs_max, SOA warning is issued.

2. Vgd_max:if |Vgd| exceeds Vgd_max, SOA warning is issued.

3. Vgb_max:if |Vgb| exceeds Vgb_max, SOA warning is issued.

4. Vds_max:if |Vds| exceeds Vds_max, SOA warning is issued.

5. Vbs_max:if |Vbs| exceeds Vbs_max, SOA warning is issued.

6. Vbd_max:if |Vbd| exceeds Vbd_max, SOA warning is issued.

15.6Batch Output

The following commands .print (15.6.2), .plot (15.6.3) and .four (15.6.4) are valid only
if ngspice is started in batch mode (see 16.4.1), whereas .save and the equivalent .probe are
aknowledged in all operating modes.

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 f i le (not available with MS Windows GUI). As an alternative
you may extend the ngspice command by specifying an output f i le:

ngspice -b -o output.log input.cir

If you however add the command line option -r to create a rawf i le, .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.


254CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

15.6.1.SAVE: Name vector(s) to be saved in raw f i le

General form:

. savevectorvectorvector. . .

Examples:

. savei ( vin )node1 v( node2 )
. save @m1[ id ]vsource#branch
. saveall @m2[ vdsat ]

The vectors listed on the .SAVE line are recorded in the rawf i le for use later with ngspice or
ngnutmeg (ngnutmeg is just the data-analysis half of ngspice, without the ability to simulate).
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 specif i ed 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
rawf i le, onlytheoriginaldatav(out)arestored. Therequestforstoringthemagnitudeisignored,
because this may be added later during rawf i le data evaluation with ngnutmeg or ngspice. See
also the section on the interactive command interpreter (chapter 17.5) for information on how
to use the rawf i le.

15.6.2.PRINT Lines

General form:

. printprtypeov1 <ov2. . .ov8>

Examples:

. printtranv (4)i ( vin )
. printdc v (2)i ( vsrc ) v(23 ,17)
. printac vm(4 ,2)vr (7)vp (8 ,3)

The.printlinedef i nesthecontentsofatabularlistingofonetoeightoutputvariables. prtype
is the type of the analysis (DC, AC, TRAN, NOISE, or DISTO) for which the specif i ed outputs
are desired. The form for voltage or current output variables is the same as given in the previ-
ous section for the print command; Spice2 restricts the output variable to the following forms
(though this restriction is not enforced by ngspice):


15.6. BATCH OUTPUT255

V(N1<,N2>)specif i es the voltage difference between nodes N1 and N2.
If N2 (and the preceding comma) is omitted, ground (0) is
assumed. See the print command in the previous section
for more details. For compatibility with SPICE2, the
following f i ve additional values can be accessed for the ac
analysis by replacing the "V" in V(N1,N2) with:
VRReal part
VIImaginary part
VMMagnitude
VPPhase
VDB20log10(magnitude)
I(VXXXXXXX)specif i es the current f l owing in the independent voltage
source named VXXXXXXX. Positive current f l ows from
the positive node, through the source, to the negative node.
(Not yet implemented: For the ac analysis, the
corresponding replacements for the letter I may be made in
the same way as described for voltage outputs.)

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 to use algebraic expressions in the .print
lines. .width (15.6.7) selects the maximum number of characters per line.

15.6.3.PLOT Lines

.plot creates a printer plot output.

General form:

. plotpltypeov1<(plo1 ,phi1 )> <ov2<(plo2 ,phi2 )>. . .ov8>

Examples:

. plotdc v (4)v (5)v (1)
. plottranv(17 ,5)(2 ,5)i ( vin ) v(17)(1 ,9)
. plotac vm(5) vm(31 ,24) vdb (5)vp (5)
. plotdistohd2 hd3 (R)sim2
. plottranv(5 ,3) v (4)(0 ,5) v (7)(0 ,10)

The .plot line def i nes 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 specif i ed 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 f i rst variable specif i ed 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 specif i ed for each type of analysis.
The par(’expression’) option (15.6.6) allows to use algebraic expressions in the .plot
lines.


256CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

15.6.4.FOUR: Fourier Analysis of Transient Analysis Output

General form:

. fourfreqov1 <ov2 ov3... >

Examples:

. four100K v (5)

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 f i nal time specif i ed for the transient analysis, and period is one period of the
fundamental frequency. The dc component and the f i rst 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 to use algebraic expressions
in the .four lines.

15.6.5.PROBE: Name vector(s) to be saved in raw f i le

General form:

. probevector <vectorvector... >

Examples:

. probei ( vin )inputoutput
. probe @m1[ id ]

Same as .SAVE (see chapt. 15.6.1).

15.6.6par(’expression’): Algebraic expressions for output

General form:

par ( ’ expression ’)
output=par ( ’ expression ’)$ notin. measure

Examples:

. four1001 sq1=par ( ’v(1)*v (1) ’)
. measuretranvtestfindpar ( ’( v(2)*v (1)) ’) AT=2.3m
. printtranoutput=par ( ’v (1)/ v (2) ’)v (1)v (2)
. plotdc v (1)diff =par ( ’( v(4)−v (2))/0.01 ’)out222

In the output lines .four, .plot, .print, .save and in the .measure evaluation it is pos-
sible to add algebraic expression for output, in addition to vectors. All of these output lines
accept par(’expression’), where expression is any expression as has already been def i ned
for the B source (see chapter 5.1). Thus expression may contain predef i ned functions, numer-
ical values, constants, simulator output like v(n1) or i(vdb), parameters predef i ned by a .param
statement, and the variables hertz, temper, and time.


15.7. MEASURING CURRENT THROUGH DEVICE TERMINALS257

Internally expression is replaced by an internally generated voltage node, which is the output
of a B source, one node and B source per par(’...’). Several par(’...’) are allowed in each line,
up to 99 per input f i le. The internal nodes are named pa_00 to pa_99. If your input f i le already
contains such node names, an error will occur, unless you rename these nodes.

In .four, .plot, .print, .save, but not in .measure, an alternative syntax
output=par(’expression’) is possible. par(’expression’) may be used as described
above. output is the name of the new node to replace the expression. So output has to be
unique and a valid node name.

The syntax of output=par(’expression’) is strict, no spaces between par and (’, or between
( and ’ are allowed, (’ and ’) both are required. Also there is not much error checking on your
input, 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:

.with out = 256

Parameter out yields the maximum number of characters plotted in a row, if printing in columns
or an ASCII-plot is selected.

15.7Measuring current through device terminals

15.7.1Adding a voltage source in series

Originally the ngspice matrix solver delivers node voltages and currents through independent
voltage sources. So to measure the currents through a resistor you may add a voltage source in
series with dc voltage 0.

Current measurement with series voltage source

*measure

currentthrough R1
V1 1 0 1
R1 1 0 5
R2 1 0 10
*

willbecome
V1 1 0 1
R1 1 11 5
Vmess 11 0 dc 0
R2 1 0 10


258CHAPTER 15. ANALYSES AND OUTPUT CONTROL (BATCH MODE)

15.7.2Using option ’savecurrents’

Current measurement with series voltage source

*measure

currentthrough R1 and R2
V1 1 0 1
R1 1 0 5
R2 1 0 10
. optionssavecurrents

The option savecurrents will add .save lines (15.6.1) like

.save @r1[i]

.save @r2[i]

to your input f i le information read during circuit parsing. These newly created vectors contain
the terminal currents of the devices R1 and R2.

You will f i nd information of the nomenclature in chapter 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.2). For M only
MOSFET models MOS1 to MOS9 are included so far. Devices in subcircuits are supported as
well. Be careful when choosing this option in larger circuits, because 1 to 4 additional output
vectors are created per device which may consume lots of memory.


Chapter 16

Starting ngspice

16.1Introduction

Ngspice consists of the simulator and a front-end for data analysis and plotting. Input to the
simulatorisanetlistf i le, includingcommands for circuit analysis and output control. Interactive
ngspice can plot data from a simulation on a PC or a workstation display.

Ngspice on LINUX (and OSs like Cygwin, BCD, Solaris ...) uses the X Window System for
plotting (see chapter 18.3) if the environment variable DISPLAY is available. Otherwise, a con-
sole 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 versions of ngspice and ngnutmeg will have a native graphics interface (see
chapter 18.1).

Thefront-endmayberunasaseparate"stand-alone"programunderthenamengnutmeg. ngnut-
meg is a subset of ngspice dedicated to data evaluation, still made available for historical rea-
sons. Ngnutmeg will read in the "raw" data output f i le created by ngspice -r or by the write
command during an interactive ngspice session.

16.2Where to obtain ngspice

The actual distribution of ngspice may be downloaded from the ngspice download web page.
The installation for LINUX or MS Windows is described in the f i le INSTALL to be found in
the top level directory. You may also have a look at chapter 32 of this manual for compiling
instructions.

If you want to check out the source code which is actually under development, you may have
a look at the ngspice source code repository, which is stored using the Git Source Code Man-
agement (SCM) tool. The Git repository may be browsed on the Git web page, also useful for
downloadingindividualf i les. Youmayhoweverdownload(orclone)thecompleterepositoryin-
cluding all source code trees from the console window (LINUX, CYGWIN or MSYS/MINGW)
by issuing the command (in a single line)

259


260CHAPTER 16. STARTING NGSPICE

git clone git://ngspice.git.sourceforge.net/gitroot/ngspice/ngspice

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 chapter 32). If you later want to update your f i les and download the
recent changes from sourceforge into your local repository, cd into the ngspice directory and
just type

git pull

git pull will deny to overwrite modif i ed f i les in your working directory. To drop your local
changes f i rst, you can run

git reset --hard

To learn more about git, which can be both powerful and diff i cult to master, please consult
http://git-scm.com/, especially: http://git-scm.com/documentation which has pointers to docu-
mentation and tutorials.

16.3Command line options for starting ngspice and ngnut-
meg

Command Synopsis:

ngspice[ −ologfile][ −rrawfile ][ −b ][ −i][inputf i l e. . .]
ngnutmeg[ − ][datafile. . .]

Options are:


16.3. COMMAND LINE OPTIONS FOR STARTING NGSPICE AND NGNUTMEG261

OptionLong optionMeaning
-Don’t try to load the default data f i le ("rawspice.raw") if no
other f i les are given (ngnutmeg only).
-n–no-spiceinitDon’t try to source the f i le ".spiceinit" upon start-up.
Normally ngspice and ngnutmeg try to f i nd the f i le in the
current directory, and if it is not found then in the user’s
home directory (obsolete).
-t TERM–terminal=TERMThe program is being run on a terminal with mfb name
term (obsolete).
-b–batchRun in batch mode. Ngspice reads the default input source
(e.g. keyboard) or reads the given input f i le and performs
the analyses specif i ed; output is either Spice2-like
line-printer plots ("ascii plots") or a ngspice rawf i le. See
the following section for details. Note that if the input
source is not a terminal (e.g. using the IO redirection
notation of "<") ngspice defaults to batch mode (-i
overrides). This option is valid for ngspice only.
-s–serverRun in server mode. This is like batch mode, except that a
temporary rawf i le is used and then written to the standard
output, preceded by a line with a single "@", after the
simulation is done. This mode is used by the ngspice
daemon. This option is valid for ngspice only.
Example for using pipes from the console window:
cat adder.cir|ngspice -s|more
-i–interactiveRun in interactive mode. This is useful if the standard input
is not a terminal but interactive mode is desired. Command
completion is not available unless the standard input is a
terminal, however. This option is valid for ngspice only.
-r FILE–rawf i le=FILEUse rawf i le as the default f i le into which the results of the
simulation are saved. This option is valid for ngspice only.
-p–pipeAllow a program (e.g., xcircuit) to act as a GUI frontend
for ngspice through a pipe. Thus ngspice will assume that
the input pipe is a tty and allows to run in interactive mode.
-o FILE–output=FILEAll logs generated during a batch run (-b) will be saved in
outf i le.
-h–helpA short help statement of the command line syntax.
-v–versionPrints a version information.
-a–autorunStart simulation immediately, as if a control section
.control
run
.endc
had been added to the input f i le.
–soa-log=FILEoutput from Safe Operating Area (SOA) check

Further arguments to ngspice are taken to be ngspice input f i les, which are read and saved (if
running in batch mode then they are run immediately). Ngspice accepts Spice3 (and also most
Spice2) input f i les, and outputs ASCII plots, Fourier analyses, and node printouts as specif i ed
in .plot, .four, and .print cards. If an out parameter is given on a .width card (15.6.7),


262CHAPTER 16. STARTING NGSPICE

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 f i les in binary or ASCII raw f i le format
(generated with -r in batch mode or the write (see 17.5.86) command) which are loaded into
ngnutmeg. If the f i le is in binary format, it may be only partially completed (useful for exam-
ining output before the simulation is f i nished). One f i le may contain any number of data sets
from different analyses.

16.4Starting options

16.4.1Batch mode

Let’s take as an example the Four-Bit binary adder MOS circuit shown in chapter 21.6, stored
in a f i le adder-mos.cir. You may start the simulation immediately by calling

ngspice -b -r adder.raw -o adder.log adder-mos.cir

ngspice will start, simulate according to the .tran command and store the output data in a rawf i le
adder.raw. Comments, warnings and infos go to log f i le adder.log. Commands for batch mode
operation are described in chapt. 15.

16.4.2Interactive mode

If you call

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 1 -> source adder-mos.cir

others require the simulation being done already (e.g. plot):

ngspice 2 ->run
ngspice 3 ->plot allv

If you call ngspice from the command line with a circuit f i le as parameter:

ngspice adder-mos.cir

ngspice will start, load the circuit f i le, parse the circuit (same circuit f i le 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 chapter 17.5.


16.4. STARTING OPTIONS263

16.4.3Control mode (Interactive mode with control f i le or control sec-
tion)

If you add the following control section to your input f i le 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:

*

ADDER − 4 BIT ALL−NAND −GATE BINARY ADDER
. control
setnoaskquit
savevcc#branch
run
plotvcc#branch
rusageall
. endc

Any suitable command listed in chapter 17.5 may be added to the control section, as well as
control structures described in chapter 17.6. Batch-like behavior may be obtained by changing
the control section to

Control section with batch-like behavior:

*

ADDER − 4 BIT ALL−NAND −GATE BINARY ADDER
. control
setnoaskquit
savevcc#branch
run
writeadder . raw vcc#branch
quit
. endc

If you put this control section into a f i le, say adder-start.sp, you may just add the line

.include adder-start.sp

to your input f i le adder-mos.cir to obtain the batch-like behavior. In the following example the
line .tran ... from the input f i le is overridden by the tran command given in the control
section.

Control section overriding the .tran command:

*

ADDER − 4 BIT ALL−NAND −GATE BINARY ADDER
. control
setnoaskquit
savevcc#branch
tran1n 500n
plotvcc#branch
rusageall
. endc


264CHAPTER 16. STARTING NGSPICE

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 pref i x pre_ (17.5.44) to the command.

A warning is due however: If your circuit f i le contains such a control section (.control ... .endc),
you should not start ngspice in batch mode (with -b as parameter). The outcome may be unpre-
dictable!

16.5Standard conf i guration f i le spinit

Upon start up ngspice reads its conf i guration f i le spinit. spinit may be found in
C:\Spice\share\ngspice\scripts(Windows)or/usr/local/share/ngspice/scripts(LINUX).Thepath
may be overridden by setting the environmental variable SPICE_SCRIPTS to a path where
spinit is located. ngspice for Windows will also search for spinit in the directory where
ngspice.exe resides. If spinit is not found, a warning message is issued, but ngspice will
continue (but of course without code models etc.).

Standard spinit contents:

*

Standardngspicei n i tf i l e
aliasexitquit
aliasacctrusageall
setx11lineararcs
*set

rndseed=12
*set

filetype = ascii
*set

ngdebug

*unset

brief

strcmp__flag$program " ngspice "
if$__flag = 0

*

For SPICE2 POLYs,editthebelowlinetopointtothelocation
*

ofyourcodemodel .
codemodel C: / Spice / lib / spice / spice2poly .cm

*

Theothercodemodels
codemodel C: / Spice / lib / spice / analog .cm
codemodel C: / Spice / lib / spice / d i g i t a l .cm
codemodel C: / Spice / lib / spice / xtradev .cm
codemodel C: / Spice / lib / spice / xtraevt .cm

end
unset__flag

spinit contains a script which is run upon start up of ngspice. You may f i nd details of scripting in
the next chapter. Aliases (name equivalences) are set. set filetype=ascii will yield ASCII
output in the output data f i le (rawf i le), a more compact binary format is used otherwise. The
asterisk’*’willcommentoutthisline. Ifusedbyngspice, spinitwillthenloadtheXSPICEcode


16.6. USER DEFINED CONFIGURATION FILE .SPICEINIT265

models from their absolute paths. You may also def i ne relative paths here.set ngdebug will
yield a lot of additional debug output. Any other contents of the script. e.g. plotting preferences,
may be included here and started automatically by ngspice. The compatibility mode of ngspice
has to be set in spinit by set ngbehavior=all.

If the standard path for the libraries (see standard spinit above or /usr/local/lib/spice un-
der CYGWIN and LINUX) is not adequate, you may add for example the ./conf i gure options
--prefix=/usr --libdir=/usr/lib64 tosetthecodemodelsearchpathto/usr/lib64/spice.
Besides the standard lib only lib64 is acknowledged.

16.6User def i ned conf i guration f i le .spiceinit

In addition to spinit you may def i ne a f i le .spiceinit and put it into the current directory
or in your home directory. This f i le will be read in and executed after spinit, but before any
other input f i le is read. It may contain any script and override the commands given in spinit.
If the command line option -n is used upon ngspice start up, this f i le will be ignored.

16.7Environmental variables

16.7.1Ngspice specif i c variables

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: http://ngspice.sourceforge.net/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 rawf i le. 0 for binary, and 1 for ascii.

SPICE_NEWS default: $SPICE_LIB_DIR/news
A f i le which 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 f i le will be searched.

SPICE_PATH default: $SPICE_EXEC_DIR/ngspice
Used in the aspice command (probably obsolete, to be documented)


266CHAPTER 16. STARTING NGSPICE

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: undef i ned
If def i ned, will suppress memory resource info (probably obsolete, not used on Windows
or where the /proc information system is available.)

NGSPICE_INPUT_DIR default: undef i ned
If def i ned, using a valid directory name„ will add the given directory to the search path
when looking for input f i les (*.cir, *.inc, *.lib).

16.7.2Common environment variables

TERM LINES COLS DISPLAY HOME PATH EDITOR SHELL POSIXLY_CORRECT

16.8Memory usage

Ngspice started with batch option (-b) and rawf i le output (-r rawf i le) will store all simulation
data immediately into the rawf i le without keeping them in memory. Thus very large circuits
may be simulated, the memory requested upon ngspice start up will depend on the circuit size,
but will not increase during simulation.

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 def i ned by the command. You may alos choose option
INTERP (15.1.4) to reduce memory usage.

16.9Simulation time

Simulatinglargecircuitsmaytakeanconsiderableamount ofCPUtime. Ifthisisofimportance,
you should compile ngspice with the f l ags for optimum speed, set during conf i guring 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 f l ag for compiling and linking.

UnderMSVisualStudio, youwillhavetoselectthereleaseversionwhichincludesoptimization
for speed.

If you have selected XSPICE (see chapters 12 and II) as part of your compilation conf i guration
(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


16.10. NGSPICE ON MULTI-CORE PROCESSORS USING OPENMP267

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 f i le or in the .control section in front of the tran command (via set
xtrtol=2 using the set command 17.5.57) 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 comprises mostly of MOS transistors, and you have a multi-core processor at
hand, you may benef i t from OpenMP parallel processing, as described next (16.10).

16.10Ngspice on multi-core processors using OpenMP

16.10.1Introduction

Today’s computers typically come with CPUs having more than one core. It will thus be useful
to enhance ngspice to make use of such multi-core processors.

Using circuits comprising mostly of 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 this function should be paralleled, if
possible. Resulting from that the parallel processing has to be within a dedicated device model.
Interestingly solving the matrix takes only about 10% of the CPU time, so paralleling the matrix
solver is of secondary interest here!

Arecentpublication[1]hasdescribedawaytoexactlydothatusingOpenMP,whichisavailable
on many platforms and is easy to use, especially if you want to parallel processing of a for-loop.

I have chosen the BSIM3 version 3.3.0 model, located in the BSIM3 directory, as the f i rst
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 f i le B3set.c an array is def i ned, f i lled 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 cal-
culated.

Typically you now need to synchronize the activities, in that storing the results into the matrix
has to be guarded. The trick offered by the authors now is that the storage is moved out of the
BSIM3LoadOMP() function. Inside BSIM3LoadOMP() the updated data are stored in extra
locations locally per instance, def i ned in bsim3def.h. Only after the complete for-loop is exer-
cised, the update to the matrix is done in an extra function BSIM3LoadRhsMat() in the main
thread after the paralleled loop. No extra synchronization is required.

Then the thread programming needed is only a single line!!

#pragma omp parallel for num_threads(nthreads) private(here)

introducing the for-loop.

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.


268CHAPTER 16. STARTING NGSPICE

Table 16.1: OpenMP performance
ThreadsCPU time [s]CPU time [s]
WindowsLINUX
1 (standard)167165
1 (OpenMP)174167
2110110
39594-120
483107
69490
89391

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.

16.10.2Some results

Some results on an inverter chain with 627 CMOS inverters, running for 200ns, compiled with
Visual Studio professional 2008 on Windows 7 (full optimization) or gcc 4.4, SUSE LINUX
11.2, -O2, on a i7 860 machine with four real cores (and 4 virtuals using hyperthreading) are
shown in table 16.1.

So we see a ngspice speed up of nearly a factor of two! Even on an older notebook with dual
core processor, I have got more than 1.5x improvement using two threads. Similar results are to
be expected from BSIM4.

16.10.3Usage

To state it clearly: OpenMP is installed inside the model equations of a particular model. So for
the moment it is available only in BSIM3 version 3.3.0, not in version 3.2.4 nor in any other
BSIM3 model, in BSIM4 versions 4.6.5 or 4.7, not in any other BSIM4 model, and in B4SOI,
version 4.3.1, not in any other SOI model. Older parameter f i les of version 4.6.x (x any number
up to 5) are accepted, you have to check for compatibility.

Under LINUX you may run

./autogen.sh

./configure ...--enable-openmp

make install

The same has been tested under MS Windows with CYGWIN and MINGW as well and deliv-
ers similar results.

Under MS Windows with Visual Studio Professional you have to place an additional pre-
processor f l ag USE_OMP, and then enable /openmp. Visual Studio Express is not suff i cient
due to lack of OpenMP support. Even Visual Studio Professional lacks debugging support
for OpenMP. There are local preprocessor f l ags (USE_OMP3 in bsim3def.h, USE_OMP4 in


16.11. SERVER MODE OPTION -S269

bsim4def.h, and USE_OMP4SOI in b4soidef.h) which you may modify individually if you
want to switch off OpenMP in only one of the models BSIM3, BSIM4, or B4SOI.

The number of threads has to be set manually by placing

set num_threads=4

intospinitor.spiceinit. IfOpenMPisenabled, butnum_threadsnotset, adefaultvaluenum_threads=2
is set internally.

If you run a circuit, please keep in mind to select BSIM3 (levels 8, 49) version 3.3.0 (11.2.9),
by placing this version number into your parameter f i les, BSIM4 (levels 14, 54) version 4.6.5
or 4.7 (11.2.10), or B4SOI (levels 10, 58) version 4.3.1 (11.2.12).

If you run ./conf i gure without --enable-openmp (or without USE_OMP preprocessor f l ag
under MS Windows), you will get the standard, not paralleled BSIM3 and BSIM4 model, 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 standard, non
OpenMP build.

16.10.4Literature

[1]R.K.Perng, T.-H.Weng, andK.-C.Li: "OnPerformanceEnhancementofCircuitSimulation
Using Multithreaded Techniques", IEEE International Conference on Computational Science
and Engineering, 2009, pp. 158-165

16.11Server mode option -s

A program may write the spice input to the console. This output is redirected to ngspice via ’|’.
ngspice called with the -s option writes its output to the console, which again is redirected to a
receiving program by ’|’. In the following simple example cat reads the input f i le and prints it
content to the console, which is redirected to ngspice by a f i rst pipe, ngspice transfers its output
(similar to a raw f i le, see below) to less via another pipe.

Example command line:

catinput . cir | ngspice −s | less

Under MS Windows you will need to compile ngspice as a console application (see chapt.
32.2.5) for this server mode usage.

Example input f i le:

t e s t −s
v1 1 0 1
r1 1 0 2k
. optionsfiletype = ascii
. savei (v1 )
. dc v1 −1 1 0.5
. end

If you start ngspice console with


270CHAPTER 16. STARTING NGSPICE

ngspice -s

you may type in the above circuit line by line (not to forget the f i rst line, which is a title and
will be ignored). If you close your input with ctrl Z, and return, you will get the following
output (this is valid for MINGW only) on the console, like a raw f i le:

Circuit: test -s

Doing analysis at TEMP = 27.000000 and TNOM = 27.000000

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
20.000000000000000e+000
0.000000000000000e+000
35.000000000000000e-001
-2.500000000000000e-004
41.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.

16.12Ngspice control via input, output f i fos

The following bash script (under LINUX)

- launches ngspice in another thread.

- writes some commands in ngspice input


16.12. NGSPICE CONTROL VIA INPUT, OUTPUT FIFOS271

- reads the output and prints them on the console.

Example:

#!/ usr / bin / envbash

NGSPICE_COMMAND=" ngspice "

rm input . fifo
rm output . fifo

mkfifoinput . fifo
mkfifooutput . fifo

$NGSPICE_COMMAND−p −i <input . fifo>output . fifo &

exec 3>input . fifo
echo " Icanwritetoinput . fifo "

echo " Startprocessing . . . "
echo""

echo " sourcec i r c u i t . cir " >&3
echo " setnoaskquit " >&3
echo " setnobreak " >&3
echo " tran0.01ms 0.1ms">&3
echo " printn0" >&3
echo " quit " >&3

echo "Trytoopenoutput . fifo. . . "
exec 4<output . fifo
echo " Icanreadfromoutput . fifo "

echo "Readytoread . . . "
whilereadoutput
do
echo$output
done <&4

exec 3>&−
exec 4>&−

echo "Endprocessing "

The input f i le for spice is:


272CHAPTER 16. STARTING NGSPICE

Circuit.cir:

*

Circuit . cir
V1 n0 0 SIN(0 10 1kHz)
C1 n1 n03.3nF
R1 0 n1 1k
. end

16.13Compatibility

ngspice is a direct derivative of spice3f5 from UC Berkeley and thus inherits all of the com-
mands available in its predecessor. Thanks to the open source policy of UCB (original spice3
from1994isstillavailablehere), severalcommercialvariantshavesprungoff, eitherbeingmore
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 diff i cult, if not impossible, to offer a simulator which acknowledges
all of these netlist dialects. ngspice includes some features which enhance compatibility which
are included automatically. This selection may be controlled to some extend by setting the com-
patibility mode. Others may be invoked by the user by small additions to the netlist input f i le.
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.

16.13.1Compatibility mode

The variable (17.7) ngbehavior sets the compatibility mode. ’all’ is set as the default value.
’spice3’ as invoked by the command

set ngbehavior=spice3

in spinit or .spiceinit will disable some of the advanced ngspice features. ’ps’ will enable
including a library by a simple .lib <lib_filename> statement which is not compatible to
the more comfortable library handling described in chapt. 2.7.

16.13.2Missing functions

You may add one or more function def i nitions to your input f i le, as listed below.

.func LIMIT(x,a,b) {min(max(x, a), b)}
.func PWR(x,a) {abs(x) ** a}
.func PWRS(x,a) {sgn(x) * PWR(x,a)}
.func stp(x) {u(x)}


16.13. COMPATIBILITY273

16.13.3Devices

16.13.3.1E Source with LAPLACE

see chapt. 5.2.5.

16.13.3.2VSwitch

The VSwitch

S1 2 3 11 0 SW
.MODEL SW VSWITCH(VON=5V VOFF=0V RON=0.1 ROFF=100K)

may become

a1 11 (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.13.4Controls and commands

16.13.4.1.lib

The ngspice .lib command (see 2.7) requires two parameters, a f i le name followed by a library
name. If no library name is given, the line

.lib filename

should be replaced by

.inc filename

Alternatively, the compatibility mode (16.13.1) may be set to ’ps’.

16.13.4.2.step

Repeated analysis in ngspice if offered by a short script inside of a .control section (see chapt.
17.8.7) added to the input f i le. A simple application (multiple dc sweeps) is shown below.


274CHAPTER 16. STARTING NGSPICE

Input f i le with parameter sweep

parametersweep
*

r e s i s t i v edivider , R1 sweptfroms t a r t _ rtostop_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
lets t a r t _ r= 1k
letstop_r = 10k
letdelta_r = 1k
letr_act =s t a r t _ r
*

loop
whiler_actlestop_r
a l t e rr1r_act
run
writedc−sweep . out v (2)
setappendwrite
le tr_act = r_act + delta_r
end
plotdc1 . 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

16.14Tests

The ngspice distribution is accompanied by a suite of test input and output f i les, 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 f i les by comparisons string by string. This feature is
momentarily used only to check for the BSIM3 model (11.2.9) and the XSPICE extension (12).
Several other input f i les located in directory ngspice/tests may serve as light-weight examples
for invoking devices and simple circuits.

Today’s very complex device models (BSIM4 (see 11.2.10), HiSIM (see 11.2.14) and others)
require a different strategy for verif i cation. Under development for ngspice is the CMC Regres-
sion test by Colin McAndrew, which accompanies every new model. A major advantage is the
scalability of the diff comparisons, which check for equality within a given tolerance. A set of


16.15. REPORTING BUGS AND ERRORS275

Perl modules cares for input, output and comparisons of the models. Currently BSIM4, BSIM-
SOI4, HiSIM, and HiSIMHV models implement the new test. You may invoke it by running
the command given above or by

$ make -i check 2>&1 | tee results

-i will make make to ignore any errors, tee will provide console output as well as printing to
f i le ’results’. Be aware that under MS Windows you will need the console binary (see 32.2.5)
to run the CMC tests, and you have to have Perl installed!

16.15Reporting bugs and errors

Ngspice is a complex piece of software. The source code contains over 1500 f i les. Various
models and simulation procedures are provided, some of them not used and tested intensively.
Therefore errors may be found, some still evolving from the original spice3f5 code, others
introduced during the ongoing code enhancements.

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

Small input f i le to reproduce the bug

Actual output versus the expected output


276CHAPTER 16. STARTING NGSPICE


Chapter 17

Interactive Interpreter

17.1Introduction

The simulation f l ow in ngspice (input, simulation, output) may be controlled by dot commands
(see chapt. 15 and 16.4.1) in batch mode. There is, however, a much more powerful control
scheme available in ngspice, traditionally coined “Interactive Interpreter”, but being much more
than just that. In fact there are several ways to use this feature, truly interactively by typing
commands to the input, but also running command sequences as scripts or as part of your input
deck in a quasi batch mode.

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 f i le, and then activated by just typing the f i le name into the console input of an
interactive ngspice session.

Finally, and most useful, is it to add a script to the input f i le, 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.7 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 f i nally make use of many options for outputting the data
(graphically or into output f i les).

17.2Expressions, Functions, and Constants

Ngspice and ngnutmeg store data 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 the output of a simulation, or when a data f i le (output raw
f i le) is read in again (ngspice, ngnutmeg, see the load command 17.5.36), or when the initial
data-f i le is loaded directly into ngnutmeg. They can also be created with the let command
817.5.33).

An expression is an algebraic formula involving vectors and scalars (a scalar is a vector of
length 1) and the following operations:

277


278CHAPTER 17. INTERACTIVE INTERPRETER

+ −

*

/^ % ,

% is the modulo operator, and the comma operator has two meanings: if it is present in the
argument list of a user def i nable 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:

OperatorSynonym
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.14).

The following functions are available:


17.2. EXPRESSIONS, FUNCTIONS, AND CONSTANTS279

NameFunction
mag(vector)Magnitude of vector (same as abs(vector)).
ph(vector)Phase of vector.
cph(vector)Phase of vector. Continuous values, no discontinuity at
±PI.
unwrap(vector)Phase of vector. Continuous values, no discontinuity at
±PI. Real phase vector in degrees as input.
j(vector)i(sqrt(-1)) times vector.
real(vectorThe real component of vector.
imag(vector)The imaginary part of vector.
db(vector)20 log10(mag(vector)).
log(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.
f l oor(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).
group_delay(vector)Calculates the group delay -dphase[rad]/dw[rad/s]. 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 f i rst
element is taken, and if it isn’t an integer then the f l oor of
the magnitude is used.
unitvec(number)The result is a vector of length number, all elements having
a value 1.


280CHAPTER 17. INTERACTIVE INTERPRETER

NameFunction
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.
deriv(vector)Calculates the derivative of the given vector. This uses
numeric differentiation by interpolating a polynomial and
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.24)
ifft(vector)inverse fast fourier transform (17.5.24)
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).

Several functions offering statistical procedures are listed in the following table:


17.2. EXPRESSIONS, FUNCTIONS, AND CONSTANTS281

NameFunction
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
from a Poisson distribution. The elements of the input
vector (real numbers) are the expected numbers l.
Complex vectors are allowed, real and imaginary values
are treated separately.
exponential(vector)Returns a vector with its elements (real numbers) drawn
from an exponential distribution. The elements of the input
vector are the respective mean values (real numbers).
Complex vectors are allowed, real and imaginary values
are treated separately.

An input vector may be either the name of a vector already def i ned or a f l oating-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
scientif i c 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 specif i ed, and if the vector name is all, all vectors in the specif i ed 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. Thus some (contrived) examples of expressions are:

Expressions examples:

cos (TIME) + db(v (3))
sin ( cos ( log ([12 3 4 5 6 7 8 910])))
TIME

*

rnd (v (9)) − 15

*

cos ( vin#branch ) ^[7.9 e58]
not(( ac3 .FREQ[32] & tran1 .TIME[10])gt3)
( sunif (0)ge0)?1.0:2.0
mag( f f t (v (18)))


282CHAPTER 17. INTERACTIVE INTERPRETER

Vector names in ngspice may have look like @dname[param], where dname is either the name
of a device instance or of a device model. This vector contains the value of the param parameter
of the device or model. See Appendix, chapt. 31 for details of which parameters are available.
The value is a vector of length 1. This function is also available with the show command, and
is available with variables for convenience for command scripts.

There are a number of pre-def i ned 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:

NameDescriptionValue
piπ3.14159...
ee (the base of natural logarithms)2.71828...
cc (the speed of light)299,792,500m/sec
ii (the square root of -1)

√−1

kelvin(absolute zero in centigrade)-273.15◦C
echargeq (the charge of an electron)1.60219e-19 C
boltzk (Boltzmann’s constant)1.38062e-23J/K
planckh (Planck’s constant)6.62620e-34
yesboolean1
noboolean0
TRUEboolean1
FALSEboolean0

These constants are all given in MKS units. If you def i ne another variable with a name that
conf l icts with one of these then it takes precedence.

Additional constants may be generated during circuit setup (see .csparam, 2.10).

17.3Plots

The output vectors of any analysis are stored in plots, a traditional SPICE notion. A plot is a
group of vectors. A f i rst 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. COMMAND INTERPRETATION283

17.4Command Interpretation

17.4.1On the console

On the ngspice console window (or into the Windows GUI) you may directly type in any com-
mand from 17.5. Within a command sequence Input/output redirection is available (see chapt.
17.8.8 for an example) - the symbols >, >>, >&, >>&, and < have the same effects as in the
C-shell. This I/O-redirection is internal to ngspice commands, and should not be mixed up with
the “external” I/O-redirection offered by the usual shells (LINUX, MSYS etc.), see 17.5.62.
You may type multiple commands on one line, separated by semicolons.

17.4.2Scripts

If a word is typed as a command, and there is no built-in command with that name, the directo-
ries in the sourcepath list are searched in order for a f i le with the name given by the word. If
it is found, it is read in as a command f i le (as if it were sourced). Before it is read, however, the
variables argc and argv are set to the number of words following the f i le-name on the com-
mand line, and a list of those words respectively. After the f i le is f i nished, these variables are
unset. Note that if a command f i le calls another, it must save its argv and argc since they are
altered. Also, command f i les may not be re-entrant since there are no local variables. Of course,
the procedures may explicitly manipulate a stack.... This way one can write scripts analogous
to shell scripts for ngnutmeg and ngspice.

Note that for the script to work with ngspice, it must begin with a blank line (or whatever else,
since it is thrown away) and then a line with .control on it. This is an unfortunate result
of the source command being used for both circuit input and command f i le execution. Note
also that this allows the user to merely type the name of a circuit f i le as a command and it is
automatically run. The commands are executed immediately, without running any analyses that
may be specif i ed in the circuit (to execute the analyses before the script executes, include a
“run” command in the script).

There are various command scripts installed in /usr/local/lib/spice/scripts (or what-
ever the path is on your machine), and the default sourcepath includes this directory, so you
can use these command f i les (almost) like built-in commands.

17.4.3Add-on to circuit f i le

The problably most common way to invoke the commands described in the following chapter
17.5 is to add a .control ... .endc section to the circuit input f i le (see 16.4.3).


284CHAPTER 17. INTERACTIVE INTERPRETER

Example:

. control
pre_setstrict_errorhandling
unsetngdebug
*save

outputsandspecials
save x1 . x1 . x1 .7 V(9) V(10) V(11) V(12) V(13)
run
display
*

plottheinputs ,useoffsettoploton topofeachother
plotv (1)v(2)+4 v(3)+8 v(4)+12 v(5)+16 v(6)+20 v(7)+24 v(8)+28
*

plottheoutputs ,useoffsettoploton topofeachother
plotv (9)v(10)+4 v(11)+8 v(12)+12 v(13)+16
. endc

17.5Commands

Commands marked with a * are only available in ngspice, not in ngnutmeg.

17.5.1Ac*: Perform an AC, small-signal frequency response analysis

General Form:

ac( DEC | OCT |LIN ) N FstartFstop

Do an small signal ac analysis (see also chapter 15.3.1) over the specif i ed frequency range.

DEC decade variation, and N is the number of points per decade.

OCT stands for octave variation, and N is the number of points per octave.

LIN stands for linear variation, and N is the number of points.

fstart is the starting frequency, and fstop is the f i nal frequency.

Note that in order for this analysis to be meaningful, at least one independent source must have
been specif i ed with an ac value.

In this ac analysis all non-linear devices are linearized around their actual dc operating point.
All Ls and Cs get their imaginary value, depending 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.


17.5. COMMANDS285

Example:

*

AC t e s t
Iin1 0 AC 1
R1 1 2 100
L1 2 0 1

. control
AC LIN 101 10 10K
plotv (2)$realpart!
plot mag(v (2))$ magnitude
plotdb(v (2))$ same as vdb (2)
plotimag (v (2))$ imaginarypartof v (2)
plotreal (v (2))$ same asplotv (2)
plotphase (v (2))$ phaseinrad
plotcph (v (2))$ phaseinrad ,continuousbeyondpi
plot180/ PI*phase (v (2))$ phaseindeg
. endc
. end

In addition to the plot examples given above you may use the variants of vxx(node) described in
chapter 15.6.2 like vdb(2). An option to suppress OP analysis before AC may be set for linear
circuits (15.1.3).

17.5.2Alias: Create an alias for a command

General Form:

alias[ word ][ text. . . ]

Causes word to be aliased to text. History substitutions may be used, as in C-shell aliases.

17.5.3Alter*: Change a device or model parameter

Alter changes the value for a device or a specif i ed parameter of a device or model.

General Form:

a l t e rdev = <expression >
a l t e rdev param = <expression >
a l t e r@dev[ param ] = <expression >

<expression> must be real (complex isn’t handled right now, integer is f i ne though, but no
strings. For booleans, use 0/1.

Old style (pre 3f4):

a l t e rdevicevalue
a l t e rdeviceparametervalue[parametervalue]

Using the old style, its f i rst form is used by simple devices which have one principal value (re-
sistors, capacitors, etc.) where the second form is for more complex devices (bjt’s, etc.). Model


286CHAPTER 17. INTERACTIVE INTERPRETER

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 "]".

Some examples are given below:

Examples (Spice3f4 style):

a l t e rvd = 0.1
a l t e rvg dc = 0.6
a l t e r @m1[w]= 15e−06
a l t e r@vg[ sin ][ −1 1.5 2MEG ]
a l t e r @Vi[ pwl ] = [ 0 1.2100p 0 ]

alter may have vectors (17.8.2) or variables (17.8.1) as parameters.

Examples (vector or variable in parameter list):

le tnewfreq = 10k
a l t e r@vg[ sin ][ −1 1.5 $&newfreq];vector
setnewperiod = 150u
a l t e r @Vi[ pwl ] = [ 0 1.2$newperiod 0 ];variable

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).

Examples (parameter of device in subcircuit):

a l t e r m.xm1. msub1 w = 20u
a l t e r @m.xm1. msub1[w] = 20u

17.5.4Altermod*: Change model parameter(s)

General form:

altermod mod param = <expression >
altermod @mod[ param ] = <expression >

Example:

altermodnc1tox = 10e−9
altermod @nc1[ tox ] = 10e−9

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 def i ned 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


17.5. COMMANDS287

M1 d g s b nc1 w=10u l=1u

you might also insert the device name M1 for mod as in

altermod M1 tox = 10e-9

The model parameter tox will be modif i ed, 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 f l ow, the following option of
altermod may be of help. The parameter set with name modn may be overrun by the altermod
command specifying a model f i le. All parameter values f i tting to the existing model which
is def i ned as modn will be modif i ed. As usual the ’reset’ command (see 17.5.49) restores the
original values. The model f i le (see 2.3) has to use the standard specif i cations for an input f i le,
the .model section is the relevant part. However the f i rst line in the model f i le 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 f i le.

General form:

altermod mod1 [mod2. .mod15]f i l e= <modelf i l ename>
altermod mod1 [mod2. .mod15]f i l e<modelf i l ename>

Example:

altermodnchf i l e= BSIM3_nmos .mod
altermodpch nchf i l eBSIM4_mos .mod

Be careful that the new model f i le corresponds to the existing model selected by modn. The ex-
isting models are def i ned during circuit setup at start up of ngspice. Models have been included
by .model statements (2.3) in your input f i le or included by the .include command. In the
example given above, the models nch (or nch and pch) have to be already available before call-
ing altermod. If they are not found in the active circuit, ngspice will terminate with an error
message. 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 level (e.g. level 8 for BSIM3). Thus
no new model is selectable by altermod, but the parameters of the existing model(s) may be
changed (partially, completely, temporarily).

17.5.5Asciiplot: Plot values using old-style character plots

General Form:

a s c i i p l o tplotargs

Produce a line printer plot of the vectors. The plot is sent to the standard output, or you can
put it into a f i le with asciiplot args ... > f i le. 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.


288CHAPTER 17. INTERACTIVE INTERPRETER

17.5.6Aspice*: Asynchronous ngspice run

General Form:

aspiceinput−f i l e[ output−f i l e ]

Start an ngspice run, and when it is f i nished load the resulting data. The raw data is kept in
a temporary f i le. If output-f i le is specif i ed then the diagnostic output is directed into that f i le,
otherwise it is thrown away.

17.5.7Bug: Mail a bug report

General Form:

bug

Send a bug report. Please 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 the relevant ngspice input f i le. (If you have def i ned BUGADDR, the mail is delivered to there.)

17.5.8Cd: Change directory

General Form:

cd[ directory ]

Change the current working directory to directory, or to the user’s home directory if none is
given.

17.5.9Cdump: Dump the control f l ow to the screen

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.


17.5. COMMANDS289

Example (abbreviated):

le tmc_runs=5
le trun=0
. . .
defineagauss (nom,avar ,sig )(nom + avar / sig

*

sgauss (0))
definelimit (nom,avar )(nom + (( sgauss (0)>=0) ?avar: −avar ))
dowhilerun < mc_runs
a l t e rc1=unif (1e−09,0.1)
. . .
acoct100 250k 10meg
meas ac bw t r i gvdb ( out )val=−10rise =1targvdb ( out )val=−10f a l l =1
setrun="$&run "
. . .
letrun=run + 1
end
plotdb({ $scratch }. allv )
echo
print{ $scratch }.bwh
cdump

17.5.10Circbyline*: Enter a circuit line by line

General Form:

circbylineline

Enter a circuit line by line. line is any circuit line, as found in the *.cir ngspice input f i les.
The f i rst line is a title line. The entry will be f i nished by entering .end. Circuit parsing is then
started automatically.

Example:

circbylinet e s tc i r c u i t
circbylinev1 1 0 1
circbyliner1 1 0 1
circbyline. dc v10.51.50.1
circbyline. end
run
ploti (v1)

17.5.11Codemodel*: Load an XSPICE code model library

General Form:

codemodel[ libraryf i l e ]

Load a XSPICE code model shared library f i le (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).


290CHAPTER 17. INTERACTIVE INTERPRETER

17.5.12Compose: Compose a vector

General Form:

compose name valuesvalue1[value2. . .]
compose name parm = val[parm = val. . .]

The f i rst form takes the values and creates a new vector, the values may be arbitrary expressions.

The second form has the following possible parameters:

start The value at which the vector should start.

stop The value at which the vector should end.

step The difference between successive elements.

lin The number of points, linearly spaced..

17.5.13Dc*: Perform a DC-sweep analysis

General Form:

dc Source−Name VstartVstopVincr[Source2Vstart2Vstop2Vincr2]

Do a dc transfer curve analysis. See the previous chapter 15.3.2 for more details. Several
options may be set (15.1.2).

17.5.14Def i ne: Def i ne a function

General Form:

definefunction ( arg1 ,arg2 ,. . . )expression

Def i ne the user-def i nable 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 arguments when it is parsed. If expression is not present,
any def i nition for function is printed, and if there are no arguments to def i ne then all currently
active def i nitions are printed. Note that you may have different functions def i ned with the same
name but different arities. Some useful def i nitions are:

Example:

define max(x , y)(x > y)

*

x + (x <= y)

*

y
definemin(x , y)(x < y)

*

x + (x >= y)

*

y
definelimit (nom,avar )(nom + (( sgauss (0) >= 0) ?avar: −avar ))

17.5.15Deftype: Def i ne a new type for a vector or plot

General Form:

deftype[v|p]typenameabbrev


17.5. COMMANDS291

def i nes 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. It may be omitted. Also, the command
"deftype p plottype pattern ..." will assign plottype as the name to any plot with one of the
patterns in its Name: f i eld.

Example:

deftypevcapacitance F
settypecapacitancemoscap
plotmoscap vs v( cc )

17.5.16Delete*: Remove a trace or breakpoint

General Form:

delete[debug−number. . .]

Delete the specif i ed saved nodes and parameters, breakpoints and traces. The debug numbers
are those shown by the status command (unless you do status > f i le, in which case the debug
numbers are not printed).

17.5.17Destroy: Delete an output data set

General Form:

destroy[ plotnames|all ]

Release the memory holding the output data (the given plot or all plots) for the specif i ed runs.

17.5.18Devhelp: information on available devices

General Form:

devhelp [[−csv ]device_name[ parameter ]]

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 spec-
if i es 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 f i elds 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 “-csv” option prints the f i elds separated by a comma, for direct import into a spreadsheet.
This option is used to generate the simulator documentation.


292CHAPTER 17. INTERACTIVE INTERPRETER

Example:

devhelp
devhelpr e s i s t o r
devhelpcapacitoric

17.5.19Diff: Compare vectors

General Form:

diffplot1plot2[ vec. . . ]

Compare all the vectors in the specif i ed 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 signif i cantly,
the difference is reported. The variables diff_abstol, diff_reltol, and diff_vntol are used to
determine a signif i cant difference.

17.5.20Display: List known vectors and types

General Form:

display[ varname. . . ]

Prints a summary of currently def i ned vectors, or of the names specif i ed. 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 f i rst vector in a rawf i le, or the f i rst vector def i ned in a new
plot. If you undef i ne 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.60).

17.5.21Echo: Print text

General Form:

echo[ text . . . ][ $variable ][" $&vector "]

Echos the given text, variable or vector to the screen. echo without parameters issues a blank
line.

17.5.22Edit*: Edit the current circuit

General Form:

edit[f i l e]

Print the current ngspice input f i le into a f i le, call up the editor on that f i le and allow the user to
modify it, and then read it back in, replacing the original f i le. If a f i le-name is given, then edit


17.5. COMMANDS293

that f i le and load it, making the circuit the current one. The editor may be def i ned 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 as parameter, if you have set

set editor=notepad++.exe

to .spiceinit or spinit.

17.5.23Eprint*: Print an event driven node (only used with XSPICE op-
tion)

General Form:

eprintnode[ node ]
eprintnode[ node ] > nodeout . txt;outputredirected

Print an event driven node generated or used by an XSPICE ’A’ device. These nodes are vectors
not organized in plots. See chapt. 27.2.2 for an example. Output redirection into a f i le is
available.

17.5.24FFT: fast Fourier transform of vectors

General Form:

f f tvector1[ vector2 ]. . .

This analysis provides a fast Fourier transform of the input vector(s) in forward direction. fft
is much faster than spec (17.5.69) (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 got these vectors by the tran Tstep Tstop Tstart
command.

Thevectorshouldhavealinearequidistanttimescale. Thereforelinearizationusingthelinearize
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 func-
tion 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.

Ngspice has two FFT implementations:

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 f i t this requirement the remaining data will be zero padded
upto the next 2N f i eld size. You have to take care of the correlated change in the scale
vector.


294CHAPTER 17. INTERACTIVE INTERPRETER

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.

How to compute the fft from a transient simulation output:

ngspice 8 −> setplottran1
ngspice 9 −> linearize V(2)
ngspice 9 −> setspecwindow=blackman
ngspice10 −> f f t V(2)
ngspice11 −> plot mag(V(2))

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

f l attop Flat top window


17.5. COMMANDS295

Figure 17.1: Spec and FFT window functions (Gaussian order = 4)

specwindoworder: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.

17.5.25Fourier: Perform a Fourier transform

General Form:

fourierfundamental_frequency[ expression. . . ]

Fourier is used to analyse the output vector(s) of a preceeding transient analysis (see 17.5.77).
It does a Fourier analysis of each of the given values, using the f i rst 10 multiples of the funda-
mental frequency (or the f i rst nfreqs multiples, if that variable is set - see 17.7). The printed
output is like that of the .four ngspice line (chapter 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 f i xed-
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. If polydegree is 0, then no
interpolation is done. This is likely to give erroneous results if the time scale is not monotonic,
though.

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.


296CHAPTER 17. INTERACTIVE INTERPRETER

Example:

*

dothetransientanalysis
tran1n 1m
*

dothefourieranalysis
fourier3.34 e6 v (2)v (3);f i r s tcall
fourier100e6 v (2)v (3);secondcall
*

getindividualvalues
le tnewt1 = fourier11 [0][1]
le tnewt2 = fourier11 [1][1]
le tnewt3 = fourier11 [2][1]
le tnewt4 = fourier12 [0][4]
le tnewt5 = fourier12 [1][4]
le tnewt6 = fourier12 [2][4]
*

plotmagnitudeofseccondexpression(v (3))
*

fromf i r s tcallversusfrequency
plotfourier12 [1]vsfourier12 [0]

The plot command from the example plots the vector of the magnitude values, obtained by
the f i rst call to fourier and evaluating the f i rst expression in this call, against the vector of the
frequency values.

17.5.26Gnuplot: Graphics output via Gnuplot

General Form:

gnuplotf i l eplotargs

Like plot, but using gnuplot for graphics output and further data manipulation. ngspice creates
a f i le called file.plt containing the gnuplot command sequence, a f i le called file.data
containing the data to be plotted, and a f i le called file.eps containing a postscript hard-copy
oftheplot. OnLINUXgnuplotiscalled via xterm, which offers a gnuplotconsole to manipulate
the data. On Windows a plot window is opened, the gnuplot command console window is
available at a mouse click. Of course you have to have gnuplot installed properly on your
system. This option is tested with Gnuplot 4.6 (as of Jan 2014).

By setting the variable gnuplot_terminal inside the control section to png, gnuplot will
generate a f i le file.png containing a compressed bitmap ready to including in text-processing
programs like Word etc.

17.5.27Hardcopy: Save a plot to a f i le for printing

General Form:

hardcopyf i l eplotargs

Just like plot, except that it creates a f i le called file containing the plot. The f i le is a postscript
image. As an alternative the plot(5) format is available by setting the hcopydevtype variable to
plot5, and can be printed by either the plot(1) program or lpr with the -g f l ag. See also chapter
18.6 for more details (color etc.).


17.5. COMMANDS297

17.5.28Help: Print summaries of Ngspice commands

Prints help. This help information, however, is spice3f5-like, stemming from 1991 and thus
is outdated. If commands are given, descriptions of those commands are printed. Otherwise
help for only a few major commands is printed. On Windows this help command is no longer
available. Spice3f5 compatible help may be found in the Spice 3 User manual. For ngspice
please use this manual.

17.5.29History: Review previous commands

General Form:

history[ number ]

Print out the history, or the last number commands typed at the keyboard.

17.5.30Inventory: Print circuit inventory

General Form:

inventory

This commands accepts no argument and simply prints the number of instances of a particular
device in a loaded netlist.

17.5.31Iplot*: Incremental plot

General Form:

iplot[node. . . ]

Incrementally plot the values of the nodes while ngspice runs. The iplot command can be used
with the where command to f i nd trouble spots in a transient simulation.

The @name[param] notation (31.1) might not work yet.

17.5.32Jobs*: List active asynchronous ngspice runs

General Form:

jobs

Report on the asynchronous ngspice jobs currently running. Ngnutmeg checks to see if the
jobs are f i nished every time you execute a command. If it is done then the data is loaded and
becomes available.


298CHAPTER 17. INTERACTIVE INTERPRETER

17.5.33Let: Assign a value to a vector

General Form:

le tname = expr

Creates a new vector called name with the value specif i ed by expr, an expression as described
above. If expr is [] (a zero-length vector) then the vector becomes undef i ned. Individual ele-
ments of a vector may be modif i ed 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.59) to create a new plot.

See also unlet (17.5.81), compose (17.5.12).

17.5.34Linearize*: Interpolate to a linear scale

General Form:

linearizevec. . .

Create a new plot with all of the vectors in the current plot, or only those mentioned as argu-
ments to the command, all data linearized onto an equidistant time scale.

How to compute the fft from a transient simulation output:

ngspice 8 −> setplottran1
ngspice 9 −> linearize V(2)
ngspice 9 −> setspecwindow=blackman
ngspice10 −> f f t V(2)
ngspice11 −> plot mag(V(2)) tstep

Linearize will redo the vectors vec or renew all vectors of the current plot (e.g. tran3) if no
argumentsaregivenandstorethemintoanewplot(e.g. tran4). Thenewvectorsareinterpolated
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 f i le 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 (tstop
- tstart) / tstep + 1.5. This command is needed for example if you want to do a fft
analysis (17.5.24). Please note that the parameter tstep of your transient analysis (see chapter
15.3.9) has to be small enough to get adequate resolution, otherwise the command linearize
will do sub-sampling of your signal.

17.5.35Listing*: Print a listing of the current circuit

General Form:

l i s t i n g[ logical ][ physical ][ deck ][ expand ][ param ]

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 f i le. The
default is logical. A deck listing is just like the physical listing, except without the line numbers


17.5. COMMANDS299

it recreates the input f i le verbatim (except that it does not preserve case). If the word expand is
present, the circuit is printed with all subcircuits expanded. The option param allows to print
all parameters and their actual values.

17.5.36Load: Load rawf i le data

General Form:

load[ filename ]. . .

Loads either binary or ascii format rawf i le data from the f i les named. The default f i le-name is
rawspice.raw, or the argument to the -r f l ag if there was one.

17.5.37Meas*: Measurements on simulation data

General Form (example):

MEAS {DC|AC|TRAN| SP}resultTRIGtrig_variable VAL=val <TD=td >
<CROSS=#| CROSS=LAST> <RISE=#|RISE=LAST> <FALL=#|FALL=LAST>
<TRIG AT=time > TARG targ_variable VAL=val <TD=td > <CROSS=#| CROSS=LAST>
<RISE=#|RISE=LAST> <FALL=#|FALL=LAST> <TRIG AT=time >

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 com-
pared to the .meas use. meas will print the results as usual, but in addition will store its mea-
surement 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.6.6) will not work here, i.e. inside the .control section.
You may use an expression by the let command instead, giving let vec_new = expression.

Replacement for par(’expression’) in meas inside the .control section

le tvdiff = v(n1)−v( n0 )
meastranvtestfindvdiffat =0.04e−3
*the

followingwillnot dohere :
*meas

tranvtestfindpar ( ’v( n1)−v( n0 ) ’)at =0.04e−3

17.5.38Mdump*: Dump the matrix values to a f i le (or to console)

General Form:

mdump <filename >

If <filename> is given, the output will be stored in f i le <filename>, otherwise dumped to
your console.


300CHAPTER 17. INTERACTIVE INTERPRETER

17.5.39Mrdump*: Dump the matrix right hand side values to a f i le (or
to console)

General Form:

mrdump <filename >

If <filename> is given, the output will be appended to f i le <filename>, otherwise dumped to
your console.

Example usage after ngspice has started:

*

Dump matrixand RHS valuesafter10 and 20steps
*

ofatransientsimulation
sourcerc . cir
step10
mdump m1. txt
mrdump mr1 . txt
step10
mdump m2. txt
mrdump mr2 . txt
*

justtocontinuetotheend
step10000

You may create a loop using the control structures (chapt. 17.6).

17.5.40Noise*: Noise analysis

See the .NOISE analysis (15.3.4) for details.

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 f i le(s), you
may use the following command sequence:

Command sequence for writing noise data to f i le(s):

. control
tran1e−6 1e−3
writetest_tran . raw
noise V( out )vinpdec 333 1 1e8 16
printinoise_totalonoise_total
*f i r s t

optiontogetalloftheoutput( twof i l e s )
setplotnoise1
writetest_noise1 . rawall
setplotnoise2
writetest_noise2 . rawall
*

secondoption( allinone raw−f i l e )
writet e s t a l l . rawnoise1 . a l lnoise2 . a l l
. endc


17.5. COMMANDS301

17.5.41Op*: Perform an operating point analysis

General Form:

op

Do an operating point analysis. See chapter 15.3.5 for more details.

17.5.42Option*: Set a ngspice option

General Form:

option[ option=val ][ option=val ]. . .

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
actual options set in the simulator (to be verif i ed). Multiple options may be set in a single line.

The following example demonstrates a control section, which may be added to your circuit f i le
to test the inf l uence of variable trtol on the number of iterations and on the simulation time.

Command sequence for testing option trtol:

. control
setnoinit

optiont r t o l =1
echo
echot r t o l =1
run
rusaget r a n i t e rtrantime
reset
optiont r t o l =3
echo
echot r t o l =3
run
rusaget r a n i t e rtrantime
reset
optiont r t o l =5
echo
echot r t o l =5
run
rusaget r a n i t e rtrantime
reset
optiont r t o l =7
echo
echot r t o l =7
run
rusaget r a n i t e rtrantime
plottran1 . v( out25 )tran1 . v( out50 ) v( out25 )v( out50 )
. endc


302CHAPTER 17. INTERACTIVE INTERPRETER

17.5.43Plot: Plot values on the display

General Form:

plotexprs[ ylimityloyhi ][ xlimitxloxhi ][ xindicesxiloxihi ]
[ xcompress comp][ xdeltaxdel ][ ydeltaydel ][ xlog ][ ylog ][ loglog ]
[ vs xname][ xlabelword ][ ylabelword ][ t i t l eword ][ samep ]
[ linear ]

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 specif i es that only one
out of every comp points should be plotted. If an xdelta or a ydelta parameter is present, it
specif i es 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 xname argument is an expression to use as the scale on the x-axis. If xlog or ylog are
present then the X or Y scale, respectively, is logarithmic (loglog is the same as specifying
both). The xlabel and ylabel arguments cause the specif i ed labels to be used for the X and Y
axes, respectively.

If samep is given, the values of the other parameters (other than xname) from the previous plot,
hardcopy, or asciiplot command is used unless re-def i ned 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: f i rst line of input f i le’.

The linear keyword is used to override a default logscale plot (as in the output for an AC analy-
sis).

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 plots you will see the data transformed
by the function (x-1)/(x+1). To produce a polar plot with a smith grid but without performing
the smith transform, use the keyword smithgrid.

If you specify plot all, all vectors (including the scale vector) are plotted versus the scale
vector (see commands display (17.5.20) or setscale (17.5.60) 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 will yield all current vectors, the command plot allv all
voltage vectors.

If the vector name to be plotted contains -, or / or other tokens which may be taken for oper-
ators 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, require some special consid-
erations. Please see chapter 17.5.1 for details.

17.5.44Pre_<command>: execute commands prior to parsing the circuit

General Form:

pre_ <command>


17.5. COMMANDS303

Allcommandsina.control... .endcsectionareexecutedafterthecircuithasbeenparsed. Ifyou
need command execution before circuit parsing, you may add these commands to the general
spinit or local .spiceinit f i les. Another possibility is adding a leading pre_ to a command within
the .control section of an ordinary input f i le, which forces the command to be executed before
circuit parsing. Basically <command> may be any command listed in chapter 17.5, however
only a few commands are indeed useful here. Some examples are given below:

Examples:

pre_unsetngdebug
pre_setstrict_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 herself when a circuit is to be parsed, using the source command
(17.5.68) .

17.5.45Print: Print values

General Form:

print[ col ][ line ]expr. . .

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.5). 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 without stopping, put the command set nomoremode 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 f i le filename in SPICE2 format. The
scale vector (time, frequency) is always in the f i rst 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:

printa ll
setwidth=300
printv (1) >outfile . out

17.5.46Quit: Leave Ngspice or Nutmeg

General Form:

quit
quit[ exitcode ]


304CHAPTER 17. INTERACTIVE INTERPRETER

Quit ngnutmeg or ngspice. Ngspice will ask for an acknowledgment if parameters have not
been saved. If ’set noaskquit’ is specif i ed, ngspice will terminate immediately.

The optional parameter exitcode is an integer which set the exit code for ngspice, useful to
return a success/fail value to the operating system.

17.5.47Rehash: Reset internal hash tables

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 f i rst (see above).

17.5.48Remcirc*: Remove the current circuit

General Form:

remcirc

This command removes the current circuit from the list of circuits sourced into ngspice. To
select a specif i c circuit, use setcirc (17.5.58). To load another circuit, refer to source (17.5.68).
The new actual circuit will be the circuit on top of the list of the remaining circuits.

17.5.49Reset*: Reset an analysis

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 already), and re-parse the input f i le. The circuit can then be re-run
from it’s initial state, overriding the affect of any set or alter commands.

Reset may be required in simulation loops preceding any run (or tran ...) command.

17.5.50Reshape: Alter the dimensionality or dimensions of a vector

General Form:

reshapevectorvector. . .
or
reshapevectorvector. . .[dimension ,dimension ,. . .]
or
reshapevectorvector. . .[dimension][dimension]. . .

This command changes the dimensions of a vector or a set of vectors. The f i nal dimension
may be left off and it will be f i lled in automatically. If no dimensions are specif i ed, then the


17.5. COMMANDS305

dimensions of the f i rst vector are copied to the other vectors. An error message of the form
’dimensions of x were inconsistent’ can be ignored.

Example:

*

generatevectorwithall( here30)elements
le tnewvec=vector (30)
*

reshapevectortoformat 3 x 10
reshapenewvec[3][10]
*

accesselementsofthereshapedvector
printnewvec [0][9]
printnewvec [1][5]
le tnewt = newvec [2][4]

17.5.51Resume*: Continue a simulation after a stop

General Form:

resume

Resume a simulation after a stop or interruption (control-C).

17.5.52Rspice*: Remote ngspice submission

General Form:

rspiceinputf i l e

Runs a ngspice remotely taking the input f i le as a ngspice input f i le, or the current circuit if no
argument is given. Ngnutmeg or ngspice waits for the job to complete, and passes output from
the remote job to the user’s standard output. When the job is f i nished 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” f i le 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: rspicewillnotacknowledgeelementsthathavebeenchangedviathe“alter”or“altermod”
commands.

17.5.53Run*: Run analysis from the input f i le

General Form:

run[ rawfile ]

Run the simulation as specif i ed in the input f i le. If there were any of the control lines .ac, .op,
.tran, or .dc, they are executed. The output is put in rawf i le if it was given, in addition to being
available interactively.


306CHAPTER 17. INTERACTIVE INTERPRETER

17.5.54Rusage: Resource usage

General Form:

rusage[ resource. . . ]

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:

decklineno Number of lines in deck

netloadtime Nelist loading time

netparsetime Netlist parsing time

elapsed The amount of time elapsed since the last rusage elapsed call.

faults Number of page faults and context switches (BSD only).

space Data space used.

time CPU time used so far.

temp Operating temperature.

tnom Temperature at which device parameters were measured.

equations Circuit Equations

time Total Analysis Time

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.

* listed incorrectly as "Transient iterations per point".


17.5. COMMANDS307

17.5.55Save*: Save a set of outputs

General Form:

save[ a ll|outvec. . . ]

Save a set of outputs, discarding the rest (if not keyword “all” is given). Maybe used to dramati-
cally 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 com-
mand 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 rawf i le written by the write (17.5.86) command. For backward compatibil-
ity, if there are no save commands given, all outputs are saved. If you want to trace (17.5.76) or
plot (17.5.43) a node, you have to save it explicitly, except for “all” given or no save command
at all.

Whenthekeyword“all”appearsinthesavecommand, allnodevoltages, voltagesourcecurrents
and inductor currents are saved in addition to any other vectors listed.

Save voltage and current:

savevd_node vs#branch v( vs_node )i ( vs2 )

Save allows to store and later access internal device parameters. e.g. in a command like

Save internal parameters:

savea ll @mn1[gm]

which saves all standard analysis output data plus gm of transistor mn1 to the 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 3 x1 . x2 . x1 . x2 .8v . x1 . x1 . x1 . vmeas#branch

Save internal parameters within subcircuit:

save @m. xmos3 .mn1[gm]

Usecommandslisting expand (17.5.35, beforethe simulation)ordisplay(17.5.20, after
simulation) to obtain a list of all nodes and currents available. Please see chapter 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.70) and then calling delete number (17.5.16).


308CHAPTER 17. INTERACTIVE INTERPRETER

17.5.56Sens*: Run a sensitivity analysis

General Form:

sensoutput_variable
sensoutput_variableac( DEC | OCT |LIN ) N FstartFstop

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 (ex. “i(vtest)”). The f i rst form calculates
DC sensitivities, the second form calculates AC sensitivities. The output values are in dimen-
sions of change in output per unit change of input (as opposed to percent change in output or
per percent change of input).

17.5.57Set: Set the value of a variable

General Form:

set[ word ]
set[ word = value ]. . .

Set the value of word to be 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 containing
spaces, you have to enclose it with double quotes.

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.

The variables used by ngspice are listed in section 17.7.

Set entered without any parameter will list all variables set, and their values, if applicable.

17.5.58Setcirc*: Change the current circuit

General Form:

setcirc[ c i r c u i tname]

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.68) it becomes the current circuit.

Setcirc followed by ’return’ without any parameter will list all circuits loaded.

17.5.59Setplot: Switch the current set of vectors

General Form:

setplot[ plotname ]

Set the current plot to the plot with the given name, or if no name is given, prompt the user
with a menu. (Note that the plots are named as they are loaded, with names like tran1 or op2.


17.5. COMMANDS309

These names are shown by the setplot and display commands and are used by diff, below.) If
the “New plot” item is selected, the current plot becomes one with no vectors def i ned.

Note that here the word “plot” refers to a group of vectors that are the result of one ngspice run.
When more than one f i le is loaded in, or more than one plot is present in one f i le, ngspice keeps
them separate and only shows you the vectors in the current plot.

17.5.60Setscale: Set the scale vector for the current plot

General Form:

setscale[ vector ]

Def i nes the scale vector for the current plot. If no argument is given, the current scale vector is
printed. The scale vector delivers the values for the x-axis in a 2D plot.

17.5.61Settype: Set the type of a vector

General Form:

settypetypevector. . .

Change the type of the named vectors to type. Type names can be found in the following table.

TypeUnitTypeUnit
notypepole
timeszero
frequencyHzs-param
voltageVtemp-sweepCelsius
currentAres-sweepOhms
onoise-spectrum(V or A)^2/HzimpedanceOhms
onoise-integratedV or AadmittanceMhos
inoise-spectrum(V or A)^2/HzpowerW
inoise-integratedV or AphaseDegree
decibeldB

17.5.62Shell: Call the command interpreter

General Form:

shell[ command ]

Call the operating system’s command interpreter; execute the specif i ed command or call for
interactive use.

17.5.63Shift: Alter a list variable

General Form:

s h i f t[ varname ][ number ]


310CHAPTER 17. INTERACTIVE INTERPRETER

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.

17.5.64Show*: List device state

General Form:

showdevices[:parameters],. . .

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 specif i ed to list only that device. Finally,
devices may be selected by model by using the form “#modelname”.

If no parameters are specif i ed, 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 specif i ed
parameters.

For both devices and parameters, the word “all” has the obvious meaning.

Note: there must be spaces separating the “:” that divides the device list from the parameter list.

17.5.65Showmod*: List model parameter values

General Form:

showmod models[:parameters],. . .

The showmod command operates like the show command (above) but prints out model param-
eter 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).

17.5.66Snload*: Load the snapshot f i le

General Form:

snloadcircuit −f i l ef i l e

snload reads the snapshot f i le generated by snsave (17.5.67). circuit-f i le is the original circuit
input f i le. After reading the simulation may be continued by resume (17.5.51).

An input script for loading circuit and intermediate data, resuming simulation and plotting is
shown below:


17.5. COMMANDS311

Typical usage:

*

SCRIPT: ADDER − 4 BIT BINARY
*

scripttoreloadc i r c u i tandcontinuethesimulation
*

beginwitheditingthef i l elocation
*

tobestartedwith’ ngspiceadder_snload . script ’

. control
*

cdtowhereallf i l e sarelocated
cd D: \ Spice_general \ ngspice \ examples \ snapshot
*

loadc i r c u i tandsnpashotf i l e
snloadadder_mos_circ . ciradder500 . snap
*

continuesimulation
resume
*

plotsome nodevoltages
plotv(10) v(11) v(12)
. endc

Due to bug we currently need the term ’script’ in the title line (f i rst line) of the script.

17.5.67Snsave*: Save a snapshot f i le

General Form:

snsavef i l e

If you run a transient simulation and interrupt it by e.g. a stop breakpoint (17.5.72), you may
resume simulation immediately (17.5.51) or store the intermediate status in a snapshot f i le by
snsave for resuming simulation later (using snload (17.5.66)), even with a new instance of
ngspice.


312CHAPTER 17. INTERACTIVE INTERPRETER

Typical usage:

Exampleinputf i l eforsnsave
*

loadac i r c u i t( includingt r a n s i s t o rmodels and. trancommand)
*

s t a r t stransientsimulationuntilstoppoint
*

storeintermediatedatatof i l e
*

beginwitheditingthef i l elocation
*

toberunwith’ ngspiceadder_mos . cir ’

. includeadder_mos_circ . cir

. control
*cd

towhereallf i l e sarelocated
cd D: \ Spice_general \ ngspice \ examples \ snapshot
setnoaskquit
setnoinit
*interrupt

conditionforthesimulation
stop when time > 500n
*

simulate
run
*

storesnapshottof i l e
snsaveadder500 . snap
quit
. endc

.END

adder_mos_circ.cir is a circuit input f i le, including the netlist, .model and .tran statements.

Unfortunately snsave/snload will not work if you have XSPICE devices (or V/I sources with
polynomial statement) in your input deck.

17.5.68Source: Read a ngspice input f i le

General Form:

sourcei n f i l e

Forngspice: readthengspiceinputf i leinf i le, containingacircuitnetlist. Ngnutmegandngspice
commands may be included in the f i le, 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 f i rst line in any input f i le
is considered a title line and not parsed but kept as the name of the circuit. Thus, a ngspice
command script in inf i le must begin with a blank line and then with a .control line. Also, any
line starting with the characters *# is considered as a control line (.control and .endc is placed
around this line automatically.). The exception to these rules are the f i les spinit (16.5) and
.spiceinit (16.6).

For ngutmeg: reads commands from the f i le inf i le. Lines beginning with the character * are
considered comments and are ignored.


17.5. COMMANDS313

The following search path is executed to f i nd inf i le: current directory (OS dependent), <pre-
f i x>/share/ngspice/scripts, env. variable NGSPICE_INPUT_DIR (if def i ned), see 16.7. This
sequence may be overriden by setting the internal sourcepath variable (see 17.7) before calling
source infile.

17.5.69Spec: Create a frequency domain plot

General Form:

specstart_freqstop_freqstep_freqvector[ vector. . . ]

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 appropri-
ately.

Typical usage:

ngspice13 −> linearize
ngspice14 −> setspecwindow = "blackman"
ngspice15 −> spec 10 1000000 1000 v( out )
ngspice16 −> plot mag(v( out ))

Possible values for specwindow are: none, hanning, cosine, rectangular, hamming, triangle,
bartlet, blackman, gaussian and f l attop. In the case of a gaussian window specwindoworder is a
number specifying its order. For a list of window functions see 17.5.24.

17.5.70Status*: Display breakpoint information

General Form:

status

Display all of the saved nodes and parameters, traces and breakpoints currently in effect.

17.5.71Step*: Run a f i xed number of time-points

General Form:

step[ number ]

Iterate number times, or once, and then stop.

17.5.72Stop*: Set a breakpoint

General Form:

stop[aftern][ when valuecondvalue]. . .


314CHAPTER 17. INTERACTIVE INTERPRETER

Set a breakpoint. The argument after n means stop after iteration number “n”, and the argument
when value cond value means stop when the f i rst value is in the given relation with the
second value, the possible relations being

SymbolAliasMeaning
=eqequal to
<>nenot equal
>gtgreater than
<ltless than
>=gegreater than or equal to
<=leless than or equal to

Symbol or alias may be used alternatively. All stop commands have to be given in the control
f l ow 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.

stop after 4 when v(1) > 4 when v(2) < 2,

the conjunction of the conditions is implied. If the condition is met, the simulation and control
f l ow are interrupted, and ngspice waits for user input.

In a transient simulation the ’=’ or ’eq’ will only work with vector ’time’ in commands like

stop when time = 200n.

Internally a breakpoint will be set at the time requested. Multiple breakpoints may be set. If
the f i rst 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 f i rst resume
command. The next breakpoint requires another resume to continue automatically. Otherwise
the simulation stops and ngspice waits for user input.

If you try to stop at

stop when V(1) eq 1

(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.

17.5.73Strcmp: Compare two strings

General Form:

strcmp_flag$string1" string2 "

The command compares two strings, either given by a variable (string1) or as a string in quotes
(“string2”). _f l ag is set as an output variable to ’0’, if both strings are equal. A value greater
than zero indicates that the f i rst 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).

17.5.74Sysinfo*: Print system information

General Form:

sysinfo


17.5. COMMANDS315

The command prints system information useful for sending bug report to developers. Informa-
tion consists of:

• Name of the operating system,

• CPU type,

• Number of physical processors (not available under Windows OS), number of logical
processors,

• Total amount of DRAM available,

• DRAM currently available.

The example below shows the use of this command.

ngspice 1 −> sysinfo
OS: CYGWIN_NT−5.11.5.25(0.156/4/2)2008−06−12 19:34
CPU:Intel (R)Pentium (R) 4 CPU 3.40GHz
Logicalprocessors :2
Total DRAM available = 1535.480469 MB.
DRAM currentlyavailable = 984.683594 MB.
ngspice 2 −>

This command has been tested under Windows OS and LINUX. It may not be available in your
operating system environment.

17.5.75Tf*: Run a Transfer Function analysis

General Form:

tfoutput_nodeinput_source

The tf command performs a transfer function analysis, returning:

• the transfer function (output/input),

• output resistance,

• and input resistance

between the given output node and the given input source. The analysis assumes a small-signal
DC (slowly varying) input. The following example f i le


316CHAPTER 17. INTERACTIVE INTERPRETER

Example input f i le:

*

Tft e s tc i r c u i t
vs10dc 5
r112100
r22350
r330150
r420200

. control
tfv (3 ,5)vs
printall
. endc

. end

will yield the following output:

transfer_function = 3.750000e-001

output_impedance_at_v(3,5) = 6.662500e+001

vs#input_impedance = 2.000000e+002

17.5.76Trace*: Trace nodes

General Form:

trace[node. . . ]

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.16)
command.

17.5.77Tran*: Perform a transient analysis

General Form:

tranTstepTstop[Tstart[ Tmax ]][ UIC ]

Perform a transient analysis. See chapter 15.3.9 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.51). Several options may be
set to control the simulation (15.1.4).

17.5.78Transpose: Swap the elements in a multi-dimensional data set

General Form:

transposevectorvector. . .


17.5. COMMANDS317

This command transposes a multidimensional vector. No analysis in ngspice produces mul-
tidimensional 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 dimen-
sional 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 f i rst segment of
this second source vector. For example (circuit to produce the transfer characteristic of a MOS
transistor):

How to produce the transfer characteristic of a MOS transistor:

ngspice > dc vgg 0 5 1 vdd 0 5 1
ngspice > ploti ( vdd )
ngspice > reshapeall[6 ,6]
ngspice > transposei ( vdd ) v( drain )
ngspice > ploti ( vdd )vs v( drain )[0]

17.5.79Unalias: Retract an alias

General Form:

unalias[ word. . . ]

Removes any aliases present for the words.

17.5.80Undef i ne: Retract a def i nition

General Form:

undefinefunction

Def i nitions for the named user-def i ned functions are deleted.

17.5.81Unlet: Delete the specif i ed vector(s)

General Form:

unletvector[vector. . .]

Delete the specif i ed vector(s). See also let (17.5.33).

17.5.82Unset: Clear a variable

General Form:

unset[ word. . . ]

Clear the value of the specif i ed variable(s) (word).


318CHAPTER 17. INTERACTIVE INTERPRETER

17.5.83Version: Print the version of ngspice

General Form:

version [−s| −f|<versionid >]

Print out the version of ngnutmeg 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 rawf i les.)

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 com-
mand 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 is some situations:

Use of the version command:

ngspice10 −> version
******
**

ngspice −24 :Circuitlevelsimulationprogram
**

The U. C.Berkeley CAD Group
**

Copyright1985−1994, RegentsoftheUniversityofCalifornia .
**

Pleasegetyourngspicemanual from
http : / / ngspice . sourceforge . net / docs . html
**

Pleasef i l eyour bug−reportsat
http : / / ngspice . sourceforge . net / bugrep . html
**

CreationDate :Jan1 201113:36:34
******
ngspice 2 −>
ngspice11 −> version14
Note :rawfileisversion14 ( currentversionis24)
ngspice12 −> version24
ngspice13 −>

Note for developers: The option listing returned when version is called with the
-f f l ag 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. COMMANDS319

17.5.84Where*: 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 make 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.

17.5.85Wrdata: Write data to a f i le (simple table)

General Form:

wrdata[ f i l e ][ vecs ]

Writes out the vectors to file.

Thisisaverysimpleprintoutofdatainarray form. Columnoneisthedefault scale data, column
two the simulated data. 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 seg fault may occur. No further information is written to
the f i le, so you have to keep track of your multiple outputs. The format may be changed in the
near future.

output example from two vectors:

0.000000e+000-1.845890e-0060.000000e+0000.000000e+000
7.629471e+0064.243518e-0067.629471e+006-4.930171e-006
1.525894e+007-5.794628e-0061.525894e+0074.769020e-006
2.288841e+0075.086875e-0062.288841e+007-3.670687e-006
3.051788e+007-3.683623e-0063.051788e+0071.754215e-006
3.814735e+0071.330798e-0063.814735e+007-1.091843e-006
4.577682e+007-3.804620e-0074.577682e+0072.274678e-006
5.340630e+0079.047444e-0075.340630e+007-3.815083e-006
6.103577e+007-2.792511e-0066.103577e+0074.766727e-006
6.866524e+0075.657498e-0066.866524e+007-2.397679e-006
....

If variable appendwrite is set, the data may be added to an existing f i le.

17.5.86Write: Write data to a f i le (Spice3f5 format)

General Form:

write[ f i l e ][ exprs ]


320CHAPTER 17. INTERACTIVE INTERPRETER

Writes out the expressions to file.

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 f i le-
type=ascii command. The default f i le name is rawspice.raw, or the argument to the -r f l ag
on the command line, if there was one, and the default expression list is all.

If variable appendwrite is set, the data may be added to an existing f i le.

17.5.87Wrs2p: Write scattering parameters to f i le(Touchstone® format)

General Form:

wrs2p[ f i l e ]

Writes out the s-parameters of a two-port to file.

In the active plot the following is required: vectors frequency, S11 S12 S21 S22, all having the
same length and having complex values (as a result of an ac analysis), and vector Rbase. For
details how to generate these data see chapt. 17.9.

The f i le format is Touchstone® Version 1, ASCII, frequency in Hz, real and imaginary parts of
Snn versus frequency.

The default f i le name is s-param.s2p.

output example:

!2-port S-parameter file
!Title: test for scatteringparameters
!Generated by ngspice at Sat Oct 16 13:51:182010
# Hz S RI R 50
!freqReS11ImS11
ReS21...
2.500000e+006-1.358762e-003-1.726349e-002
9.966563e-001
5.000000e+006-5.439573e-003-3.397117e-002
9.867253e-001
....

17.5.88Xgraph: use the xgraph(1) program for plotting.

General Form:

xgraphf i l e[ exprs ][ plotoptions ]

The ngspice/ngnutmeg xgraph command plots data like the plot command but via xgraph, a
popular X11 plotting program. If f i le is either “temp” or “tmp” a temporary f i le is used to hold
the data while being plotted. For available plot options, see the plot command. All options
except for polar or smith plots are supported.


17.6. CONTROL STRUCTURES321

17.6Control Structures

17.6.1While - End

General Form:

whilecondition
statement
. . .
end

While condition, an arbitrary algebraic expression, is true, execute the statements.

17.6.2Repeat - End

General Form:

repeat[ number ]
statement
. . .
end

Execute the statements number times, or forever if no argument is given.

17.6.3Dowhile - End

General Form:

dowhilecondition
statement
. . .
end

The same as while, except that the condition is tested after the statements are executed.

17.6.4Foreach - End

General Form:

foreachvarvalue. . .
statement
. . .
end

The statements are executed once for each of the values, each time with the variable var set to
the current one. (var can be accessed by the $var notation - see below).


322CHAPTER 17. INTERACTIVE INTERPRETER

17.6.5If - Then - Else

General Form:

ifcondition
statement
. . .
else
statement
. . .
end

If the condition is non-zero then the f i rst set of statements are executed, otherwise the second
set. The else and the second set of statements may be omitted.

17.6.6Label

General Form:

labelword

Ifastatementoftheformgotowordisencountered, controlistransferredtothispoint, otherwise
this is a no-op.

17.6.7Goto

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

Example noop block to include forward goto on top level:

if(1)
. . .
gotogohere
. . .
labelgohere
end

17.6.8Continue

General Form:

continue

If there is a while, dowhile, or foreach block enclosing this statement, control passes to the test,
or in the case of foreach, the next value is taken. Otherwise an error results.


17.7. INTERNALLY PREDEFINED VARIABLES323

17.6.9Break

General Form:

break

If there is a while, dowhile, or foreach block enclosing this statement, control passes out of the
block. Otherwise an error results.

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.9).

17.7Internally predef i ned variables

The operation of both ngutmeg and ngspice may be affected by setting variables with the “set”
command (17.5.57).In addition to the variables mentioned below, the “set” command in
ngspice also affects the behavior of the simulator via the options previously described under
the section on “.OPTIONS” (15.1). You also may def i ne new variables or alter existing variables
inside .control ... .endc for later use in your user-def i ned script (see chapter 17.8).

The following list is in alphabetical order. All of them are acknowledged by ngspice. Frontend
variables (e.g. on circuits and simulation) are not def i ned in ngnutmeg. The predef i ned variables
which may be set or altered by the “set” command are:

appendwrite Append to the f i le when a write command is issued, if one already exists.

brief If set to FALSE, the netlist will be printed.

colorN These variables determine the colors used, if X is being run on a color display. N may
be between 0 and 15. Color 0 is the background, color 1 is the grid and text color, and
colors 2 through 15 are used in order for vectors plotted. The value of the color variables
should be names of colors, which may be found in the f i le /usr/lib/rgb.txt. ngspice
for Windows does support only white background (color0=white with black grid and text)
or or color0=black with white grid and text.

cpdebug Print control debugging information.

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 f i le, nutmeg dumps the
graphics control codes into this f i le – this is useful for saving plots.)


324CHAPTER 17. INTERACTIVE INTERPRETER

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).

echo Print out each command before it is executed.

editor The editor to use for the edit command.

f i letype This can be either ascii or binary, and determines the format of the raw f i le (com-
pact binary or text editor readable ascii). The default is binary.

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. Al-
lowed values are lingrid loglog xlog ylog smith smithgrid polar nogrid.

hcopydev If this is set, when the hardcopy command is run the resulting f i le is automatically
printed on the printer named hcopydev with the command lpr -Phcopydev -g file.

hcopyfont This variable specif i es 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 specif i es the type of the printer output to use in the hardcopy com-
mand. 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 as-
sumed with different linestyles for each output vector plotted. Setting to any 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 is assumed on white background, 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


17.7. INTERNALLY PREDEFINED VARIABLES325

height The length of the page for asciiplot and print col.

history The number of events to save in the history list.

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 f i rst parameter supplied is the printer
name, the second parameter supplied is a f i le name containing the plot. Both parameters
are strings. It is trivial to cause ngspice to abort by supplying a unreasonable format
string.

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 f i rst parameter supplied is the printer name, the
second parameter supplied is a f i le name containing the plot. Both parameters are strings.
It is trivial to cause ngspice to abort by supplying a unreasonable format string.

modelcard The name of the model card (normally .MODEL)

nfreqs The number of frequencies to compute in the Fourier command. (Defaults to 10.)

ngbehavior Sets the compatibility mode of ngspice. To be set in spinit (16.5) or .spiceinit
(16.6).Its value ’all’ will improve compatibility to commercial simulators. Full com-
patibility is however not the intention of ngspice! This value may be set as a standard in
the future. ’ps’, ’hs’ and ’spice3’ are available. See chapt. 16.13.

noaskquit Do not check to make sure that there are no circuits suspended and no plots unsaved.
Normally ngspice warns the user when he tries to quit if this is the case.

nobjthack BJTs can have either 3 or 4 nodes, which makes it diff i cult for the subcircuit ex-
pansion 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 variable "nobjthack" which forces BJTs to have 4 nodes
(for the purposes of subcircuit expansion, at least).

nobreak Don’t have asciiplot and print col break between pages.

noasciiplotvalue Don’t print the f i rst vector plotted to the left when doing an asciiplot.

nobjthack Assume that BJTs have 4 nodes.

noclobber Don’t overwrite existing f i les when doing IO redirection.

noglob Don’t expand the global characters ‘*’, ‘?’, ‘[’, and ‘]’. This is the default.

nomoremode If nomoremode is not 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 nomoremode is set then data scrolls off
the screen without check.

nonomatch If noglob is unset and a global expression cannot be matched, use the global char-
acters literally instead of complaining.

noparse Don’t attempt to parse input f i les when they are read in (useful for debugging). Of
course, they cannot be run if they are not parsed.


326CHAPTER 17. INTERACTIVE INTERPRETER

noprintscale Don’t print the scale in the leftmost column when a print col command is given.

nosort Don’t have display sort the variable names.

nosubckt Don’t expand subcircuits.

notrnoise Switch off the transient noise sources (chapt. 4.1.7).

numdgt The number of digits to print when printing tables of data (a, print col). The default
precision is 6 digits. On the VAX, 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.

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. Characters §C are not allowed.

polydegree The degree of the polynomial that the plot command should f i t to the data. If
polydegree is N, then nutmeg f i ts a degree N polynomial to every set of N points and
draw 10 intermediate points in between each end point. If the points aren’t monotonic,
then it tries rotating the curve and reducing the degree until a f i t is achieved.

polysteps The number of points to interpolate between every pair of points available when
doing curve f i tting. 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 string entered!

rawf i le The default name for rawf i les created.

remote_shell Overrides the name used for generating rspice runs (default is "rsh").

renumber Renumber input lines when an input f i le has .includes.

rndseed Seed value for random number generator (used by sgauss, sunif, and rnd functions).
If not set, the process Id is used as seed value.

rhost The machine to use for remote ngspice runs, instead of the default one (see the descrip-
tion of the rspice command, below).

rprogram The name of the remote program to use in the rspice command.


17.7. INTERNALLY PREDEFINED VARIABLES327

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 #def i ned to in the ngspice source). The command
set sourcepath = ( e:/ D:/ .c:/spice/examples )
will overwrite the default. The search sequence now is: current directory, e:/, d:/, current
directory (again due to .), c:/spice/examples. ’Current directory’ is depending on the OS.

specwindow Windowing for commands spec (17.5.69) or fft (17.5.24). 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.

strict_errorhandling If set by the user, an error detected during circuit parsing will immedi-
ately lead ngspice to exit with exit code 1 (see 18.5). May be set in f i les spinit (16.5) or
.spiceinit (16.6) only.

subend The card to end subcircuits (normally .ends).

subinvoke The pref i x to invoke subcircuits (normally X).

substart The card to begin subcircuits (normally .subckt).

term The mfb name of the current terminal.

ticmarks An integer value n, n tics (a small ’x’) will be set on your graph. (Arrangement of
the tics ?)

ticlist A list of integers, e.g. ( 4 14 24 ) to set tics (small ’x’) on your graph.(Arrangement of
the tics ?)

units If this is degrees, then all the trig functions will use degrees instead of radians.

unixcom If a command isn’t def i ned, 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 ngnutmeg 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. Default is depending on systems settings, something
like

width The width of the page for asciiplot and print col (see also 15.6.7).

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 grid, border and graph.

xfont Set the font for the graphics plot in X11 (LINUX, Cygwin, etc.). Input format has still to
be checked.


328CHAPTER 17. INTERACTIVE INTERPRETER

xtrtol Set trtol, e.g. to 7, so to avoid the speed reduction with XSPICE (see 16.9). Be aware of
potential precision degradation or convergence issues using this option.

17.8Scripts

Expressions, functions, constants, commands, variables, vectors, and control structures may be
assembled into scripts within a .control ... .endc section of the input f i le. The script allows
to automate a more complex ngspice behavior: simulations are performed, output data are the
analyzed, simulations repeated with modif i ed parameters, output vectors for plotting are as-
sembled. The ngspice scripting language is not very powerful, but easily integrated into the
simulation f l ow.

The ngspice input f i le for scripting contains the usual circuit netlist, modelcards, and a script,
enclosed in the .control .. .endc section. ngspice is started in interactive mode with the input
f i le in the command line (or sourced later with the source command). After reading the input
f i le, the command sequence is immediately processed. Variables or vectors set by previous
commands may be used in commands following their def i nition. data may be stored, plotted or
grouped into new vectors for additional charts supporting data evaluation.

17.8.1Variables

Variables are def i ned and initialized with the set command (17.5). set output=10 will de-
f i ned the variable output and set it to a (real) number 10. Predef i ned variables, which are used
inside ngspice for specif i c 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. The special variables $$ and $< refer to the process ID of
the program and a line of input which is read from the terminal when the variable is evaluated,
respectively. If a variable has a name of the form $&word, then word is considered a vector (see
below), and its value is taken to be the value of the variable. If $foo is a valid variable, and is of
type list, then the expression $foo[low-high] represents a range of elements. Either the upper
index or the lower may be left out, and the reverse of a list may be obtained with $foo[len-0].
Also, the notation $?foo evaluates to 1 if the variable foo is def i ned, 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.2Vectors

Ngspice and ngnutmeg 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 f i le is read in (see the load command 17.5.36). They can also be created with the
let command 17.5.33 inside a script. If a variable has a name of the form $&word, then ’word’
is considered a vector, and its value is taken to be the value of the variable.


17.8. SCRIPTS329

17.8.3Commands

Commands have been described in chapter 17.5.

17.8.4control structures

Control structures have been described in chapter 17.6. Some simple examples will be given
below.

Control structure examples:

Test sequences for ngspice controlstructures
*vectors are used (except foreach)
*start in interactive mode

.control

* test sequence for while, dowhile
let loop = 0
echo
echo enter loop with"$&loop"
dowhile loop < 3
echo within dowhile loop "$&loop"
let loop = loop + 1
end
echo after dowhile loop "$&loop"
echo
let loop = 0
while loop < 3
echo within while loop "$&loop"
let loop = loop + 1
end
echo after while loop "$&loop"
let loop = 3
echo
echo enter loop with"$&loop"
dowhile loop < 3
echo within dowhile loop "$&loop"$ output expected
let loop = loop + 1
end
echo after dowhile loop "$&loop"
echo
let loop = 3
while loop < 3
echo within while loop "$&loop"
$ no output expected
let loop = loop + 1
end
echo after while loop "$&loop"


330CHAPTER 17. INTERACTIVE INTERPRETER

Control structure examples (continued):

* test for while, repeat , if, break
let loop = 0
while loop < 4
let index = 0
repeat
let index = index + 1
if index > 4
break
end
end
echo index "$&index"loop "$&loop"
let loop = loop + 1
end

* test sequence for foreach
echo
foreach outvar 0 0.5 1 1.5
echo parameters: $outvar$ foreachparameters are variables ,
$ not vectors!
end

* test for if ... else ... end
echo
let loop = 0
let index = 1
dowhile loop < 10
let index = index * 2
if index < 128
echo "$&index" lt 128
else
echo "$&index"ge 128
end
let loop = loop + 1
end

* simple test for label, goto
echo
let loop = 0
label starthere
echo start "$&loop"
let loop = loop + 1
if loop < 3
goto starthere
end
echo end "$&loop"


17.8. SCRIPTS331

Control structure examples (continued):

* test for label, nested goto
echo
let loop = 0
label starthere1
echo start nested "$&loop"
let loop = loop + 1
if loop < 3
if loop < 3
goto starthere1
end
end
echo end "$&loop"

* test for label, goto
echo
let index = 0
label starthere2
let loop = 0
echo We are at start with index "$&index" and loop "$&loop"
if index < 6
label inhere
let index = index + 1
if loop < 3
let loop = loop + 1
if index > 1
echo jump2
goto starthere2
end
end
echo jump
goto inhere
end
echo We are at end with index "$&index" and loop "$&loop"


332CHAPTER 17. INTERACTIVE INTERPRETER

Control structure examples (continued):

* test goto in while loop
let loop = 0
if 1$ outer loop to allow nested forward label ’endlabel ’
while loop < 10
if loop > 5
echo jump
goto endlabel
end
let loop = loop + 1
end
echo before$ never reached
label endlabel
echo after "$&loop"
end

*test for using variables , simple test for label, goto
set loop = 0
label starthe
echo start $loop
let loop = $loop + 1$ expression needs vector at lhs
set loop = "$&loop"$ convert vector contents to variable
if $loop < 3
goto starthe
end
echo end $loop
.endc

17.8.5Example script ’spectrum’

A typical example script named spectrum is delivered with the ngspice distribution. Even if it
is made obsolete by the internal spec command (see 17.5.69) and especially by the much faster
fft command (see 17.5.24), it may act as a good example for getting acquainted with the ngspice
(or nutmeg) post-processor language.

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 you will need a simulation time of 1
µs. Then a small control script may start ngspice by loading the R.O. simulation data and start
spectrum.

Small script to start ngspice, read the simulation data and start spectrum:

*

t e s tforscript’ spectrum ’
. control
loadring51_41 . out
spectrum 10MEG 2500MEG 1MEG v( out25 ) v( out50 )
. endc


17.8. SCRIPTS333


334CHAPTER 17. INTERACTIVE INTERPRETER

17.8.6Example script for random numbers

Generation and test of random numbers with Gaussian distribution

*

agausst e s tinngspice
*

generateasequenceofgaussiandistributedrandom numbers .
*

t e s tthedistributionbysortingthenumbersinto
*

ahistogram( buckets )
. control
defineagauss (nom,avar ,sig )(nom + avar / sig

*

sgauss (0))
letmc_runs = 200
letrun = 0
letno_buck = 8$ number ofbuckets
letbucket = unitvec ( no_buck )$ eachelementcontains1
letdelta = 3e−11$ widthofeachbucket ,depends
$ onavarandsig
letlolimit= 1e−09 − 3*delta
lethilimit= 1e−09 + 3*delta

dowhilerun < mc_runs
letval = agauss (1e−09, 1e−10, 3) $ gettherandom number
if( val <lolimit )
letbucket [0] = bucket [0] + 1 $’ lowest ’bucket
end
le tpart = 1
dowhilepart < ( no_buck − 1)
if(( val < ( lolimit+ part*delta )) &
+ ( val > ( lolimit+ ( part −1)*delta ) ) )
letbucket [ part ] = bucket [ part ] + 1
break
end
le tpart = part + 1
end
if( val >hilimit )
*

’ highest ’bucket
le tbucket [ no_buck − 1] = bucket [ no_buck − 1] + 1
end
le trun = run + 1
end

le tpart = 0
dowhilepart < no_buck
letvalue = bucket [ part ] − 1
setvalue = "$&value "
*

printthebuckets ’contents
echo$value
letpart = part + 1
end

. endc
. end


17.8. SCRIPTS335

17.8.7Parameter sweep

While there is no direct command to sweep a device parameter during simulation, you may use
a script to emulate such behavior. The example input f i le contains of an resistive divider with
R1 and R2, where R1 is swept from a start to a stop value inside of the control section, using
the alter command (see 17.5.3).

Input f i le with parameter sweep

parametersweep
*

r e s i s t i v edivider , R1 sweptfroms t a r t _ rtostop_r
VDD 1 0 DC 1

R1 1 2 1k
R2 2 0 1k

. control
le ts t a r t _ r= 1k
le tstop_r = 10k
le tdelta_r = 1k
le tr_act =s t a r t _ r
*

loop
whiler_actlestop_r
a l t e rr1r_act
op
printv (2)
letr_act = r_act + delta_r
end
. endc

. end

17.8.8Output redirection

The console outputs delivered by commands like print (17.5.45), echo (17.5.21), or others may
be redirected into a text f i le. ’print vec > filename’ will generate a new f i le or overwrite
an existing f i le named ’f i lename’, ’echo text >?> filename’ will append the new data to the
f i le ’f i lename’. Output redirection may be mixed with commands like wrdata.


336CHAPTER 17. INTERACTIVE INTERPRETER

Input f i le with output redirection > and >>

**

MOSFET GainStage(AC):BenchmarkingImplementationof BSIM4.0.0
**

by Weidong Liu5/16/2000.
**

outputredirectionintof i l e

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.2ac0.1

. control
acdec 10 100 1000Meg
plotv (2)v (3)
le tflen = length ( frequency ) $lengthofthevector
le tloopcounter = 0
echooutputt e s t> text . txt$s t a r tnewf i l et e s t . txt
*

loop
whileloopcounterl tflen
letvout2 = v (2)[ loopcounter ]$generateasinglepointcomplexvector
letvout2re = real ( vout2 )$generateasinglepointrealvector
letvout2im = imag ( vout2 )$generateasinglepointimaginaryvector
letvout3 = v (3)[ loopcounter ]$generateasinglepointcomplexvector
letvout3re = real ( vout3 )$generateasinglepointrealvector
letvout3im = imag ( vout3 )$generateasinglepointimaginaryvector
letfreq = frequency [ loopcounter ] $generateasinglepointvector
echobbb "$&freq " "$&vout2re " "$&vout2im " "$&vout3re " "$&vout3im " >>
+text . txt$ appendtextanddatatof i l e( continued frommlineabove )
letloopcounter = loopcounter + 1
end
. endc

.MODEL N1 NMOS LEVEL=14 VERSION=4.3.0 TNOM=27
. end

17.9Scattering parameters (s-parameters)

17.9.1Intro

A command line script, available from the ngspice distribution at examples/control_structs/s-
param.cir, together with the command wrs2p (see chapt. 17.5.87) allows to calculate, print
and plot the scattering parameters S11, S21, S12, and S22 of any two port circuit at varying
frequencies.

The printed output using wrs2p is a Touchstone® version 1 format f i le. The f i le follows the
format according to The Touchstone File Format Specif i cation, Version 2.0, available from here.


17.9. SCATTERING PARAMETERS (S-PARAMETERS)337

An example is given as number 13 on page 15 of that specif i cation.

17.9.2S-parameter measurement basics

S-parameters allow a two-port description not just by permuting I1, U1, I2, U2, but using a
superposition, leading to a power view of the port (We only look at two-ports here, because
multi-ports are not (yet?) implemented.).

You may start with the effective power, being negative or positive

P = u·i(17.1)

The value of P may be the difference of two real numbers, with K being another real number.

ui=P=a2−b2=(a+b)(a−b)=(a+b)(KK−1)(a−b)={K(a+b)}

?K−1(a−b)?

(17.2)

Thus you get

K−1u = a+b(17.3)

Ki = a−b(17.4)

and f i nally

a =

u+K2i
2K

(17.5)

b =

u−K2i
2K

(17.6)

ByintroducingthereferenceresistanceZ0:=K2>0wegetf i nallytheHeavisidetransformation

a =

u+Z0i
2√Z0

,b =

u−Z0i
2√Z0

(17.7)

In case of our two-port we subject our variables to a Heaviside transformation

a1=

U1+Z0I1
2√Z0

b1=

U1−Z0I1
2√Z0

(17.8)

a2=

U2+Z0I2
2√Z0

b2=

U2−Z0I2
2√Z0

(17.9)

The s-matrix for a two-port then is


338CHAPTER 17. INTERACTIVE INTERPRETER

?

b1
b2

?
=

?

s11s12
s21s22

??

a1
a2

?
(17.10)

Two obtain s11we have to set a2= 0. This is accomplished by loading the output port exactly
with the reference resistance Z0, which sinks a current I2= −U2/Z0from the port.

s11=

?b
1
a1

?

a2=0

(17.11)

s11=

U1−Z0I1
U1+Z0I1

(17.12)

Loading the input port from an ac source U0via a resistor with resistance value Z0, we obtain
the relation

U0= Z0I1+U1(17.13)

Entering this into 17.12, we get

s11=

2U1−U0
U0

(17.14)

For s21we obtain similarly

s21=

?b
2
a1

?

a2=0

(17.15)

s21=

U2−Z0I2
U1+Z0I1

=

2U2
U0

(17.16)

Equations 17.14 and 17.16 now tell us how to measure s11and s21: MeasureU1at the input port,
multiply by 2 using an E source, subtracting U0which for simplicity is set to 1, and divide by
U0. At the same time measureU2at the output port, multiply by 2 and divide byU0. Biasing and
measuring is done by subcircuit S_PARAM. To obtain s22and s12, 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 (1mΩ) to high (1TΩ) and thus switching the input and output
ports.

17.9.3Usage

Copy and then edit s-param.cir. You will f i nd this f i le in directory /examples/control_structs of
the ngspice distribution.

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:


17.10. MISCELLANEOUS (OLD STUFF, HAS TO BE CHECKED FOR RELEVANCE)339

.param Vbias_in=1 Vbias_out=2

Place your circuit at the appropriate place in the input f i le, 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.

ac lin 100 2.5MEG 250MEG $ use for Tschebyschef

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 smith grid) or the ’write to f i le’ commands (write, wrdata,
or wrs2p) according to your needs.

Run ngspice in interactive mode

ngspice s-param.cir

17.10MISCELLANEOUS (old stuff, has to be checked for
relevance)

C-shell type quoting with “ and “, and backquote substitution 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. Any text between backquotes is
replaced by the result of executing the text as a command to the shell.

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 f i rst. 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.11Bugs (old stuff, has to be checked for relevance)

When def i ning 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-def i ned function, the arguments cannot be part of a name that uses the plot.vec syntax.
For example: def i ne check(v(1)) cos(tran1.v(1)) does not work.


340CHAPTER 17. INTERACTIVE INTERPRETER


Chapter 18

Ngspice User Interfaces

ngspice offers a variety of user interfaces. For an overview (several screen shots) please have a
look at the ngspice web page.

18.1MS Windows Graphical User Interface

If compiled properly (e.g. using the –with-wingui f l ag for ./conf i gure under MINGW), ngspice
for Windows offers a simple graphical user interface. In fact this interface does not offer much
more for data input than a console would offer, e.g. command line inputs, command history
and program text output. First of all it applies the Windows api for data plotting. If you run the
sample input f i le given below, you will get an output as shown in f i g. 16.1.

Input f i le:

*****Single NMOS Transistor

For BSIM3V3.1
generalpurposecheck( Id−Vd)

***
*
***

c i r c u i tdescription

***
m1 2 1 3 0 n1 L=0.6u W=10.0u
vgs 1 0 3.5
vds 2 0 3.5
vss 3 0 0
*
. dc vds 0 3.50.05vgs 0 3.50.5
*
. control
run
plotvss#branch
. endc
*
*

UCB parameters BSIM3v3.2
. include. . / Exam_BSIM3/ Modelcards / modelcard . nmos
. include. . / Exam_BSIM3/ Modelcards / modelcard . pmos
*
. end

341


342CHAPTER 18. NGSPICE USER INTERFACES

The GUI consists of an I/O port (lower window) and a graphics window, created by the plot
command.

Figure 18.1: MS Windows GUI

The output window displays messages issued by ngspice. You may scroll the window to get
more of the text. The input box (white box) may be activated by a mouse click to accept any
of the valid ngspice commends. The lower left output bar displays the actual input f i le. ngspice
progress during setup and simulation is shown in the progress window (“–ready–”). The Quit
button allow to interrupt ngspice. If ngspice is actively simulating, due to using only a single
thread, this interrupt has to wait until the window is accessible from within ngspice, e.g. during
an update of the progress window.

In the plot window there is the upper left button, which activated a drop down menu. You may
select to print the plot window shown (a very simple printer interface, to be improved), set
up any of the printers available on your computer, or issue a postscript f i le of the actual plot
window, either black&white or colored.


18.2. MS WINDOWS CONSOLE343

Instead of plotting with black background, you may set the background to any other color,
preferably to “white” using the command shown below.

Input f i le modif i cation for white background:

. control
run
*

whitebackground
setcolor0=white
*

blackgridandtext( onlyneededwith X11 ,automaticwith MS Win)
setcolor1=black
*

widergridandplotlines
setxbrushwidth=2
plotvss#branch
. endc

Figure 18.2: Plotting with white background

18.2MS Windows Console

If the –with-wingui f l ag for ./conf i gure under MINGW is omitted (see 32.2.5) or console_debug
or console_release is selected in the MS Visual Studio conf i guration manager, then ngspice will
compile without any internal graphical input or output capability. This may be useful if you
apply ngspice in a pipe inside the MSYS window, or use it being called from another program,
and just generating output f i les from a given input. The plot (17.5.43) command will not do
and leads to an error message.


344CHAPTER 18. NGSPICE USER INTERFACES

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

$ ngspice < input.

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.26), if installed properly
(18.7), or by selecting a suitable printing option (18.6).

18.3LINUX

The standard user interface is a console for input and the X11 graphics system for output with
the interactive plot (17.5.43) command. If ngspice is compiled with the –without-x f l ag for
./conf i gure, a console application without graphical interface results. For more sophisticated
input user interfaces please have a look at chapt. 18.8.

18.4CygWin

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

$ xwin -multiwindow -clipboard &

inside of the CygWin window before starting ngspice.

18.5Error handling

Error messages and error handling in ngspice have grown over the years, include a lot of “tra-
ditional” behavior and thus are not very systematic and consistent.

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 recov-
erable errors only.

So there is still work to be done to def i ne a consistent error messaging, recovery or exiting. A
f i rst step is the user def i nable variable strict_errorhandling. This variable may be set in f i les
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.

XSPICE error messages are explained in chapter 29.


18.6. POSTSCRIPT PRINTING OPTIONS345

18.6Postscript printing options

This info is compiled from Roger L. Traylor’s web page. All the commands and variables you
can set are described in chapt. 17.5. The corresponding input f i le for the examples given below
is listed in chapt. 21.1. Just add the .control section to this f i le and run in interactive mode by

$ ngspice xspice_c1_print.cir

================================================================

One way is to setup your printing like this:

.control

set hcopydevtype=postscript

op

run

plot vcc coll emit

hardcopy temp.ps vcc coll emit

.endc

Then print the postscript f i le temp.ps to a postscript printer.

================================================================

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

*color0 is background color

*color1 is the grid and text color

*colors 2-15 are for the vectors

set color0=rgb:f/f/f

set color1=rgb:0/0/0

op

run

hardcopy temp.ps vcc coll emit

.endc

Then print the postscript f i le 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


346CHAPTER 18. NGSPICE USER INTERFACES

*send output to the printer kec3112-clr

set hcopydev=kec3112-clr

hardcopy out.tmp vcc coll emit

=================================================================

18.7Gnuplot

Install Gnuplot (on LINUX available from the distribution, on Windows available here). On
Windowsexpandthezipf i letoadirectoryofyourchoice, addthepath<anydirectory>/gnuplot/bin
to the PATH variable, and go... The command to invoke Gnuplot (17.5.26) is limited however
to x/y plots (no polar etc.).

18.8Integration with CAD software and “third party” GUIs

In this chapter you will f i nd some links and comments on GUIs for ngspice offered from other
projects and on the integration of ngspice into a circuit development f l ow. The data given rely
mostly on information available from the web and thus is out of our control. It also may be far
from complete. The GUIs KJWaves and GNUSpiceGUI help you to navigate the commands
to need to perform your simulation. XCircuit and the GEDA tools gschem and gnetlist offer
integrating schematic capture and simulation.

18.8.1KJWaves

KJWaves was written to be a cross-platform SPICE tool in pure Java. It aids in viewing, mod-
ifying, and simulating SPICE CIRCUIT f i les. Output from SPICE3 (ngspice) can be read
and displayed. Resulting graphs may be printed and saved. The Java executable will run
under LINUX and Windows (and maybe other OSs). The development site is available at
http://sourceforge.net/projects/kjwaves/. Youmayf i ndtheprojecthomepageathttp://www.comef l y.us/.

18.8.2GNU Spice GUI

Another GUI, to be found at http://sourceforge.net/projects/gspiceui/.

18.8.3XCircuit

CYGWIN and especially LINUX users may f i nd XCircuit valuable to establish a development
f l ow including schematic capture and circuit simulation.


18.8. INTEGRATION WITH CAD SOFTWARE AND “THIRD PARTY” GUIS347

18.8.4GEDA

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 f l ow. Two web
sites offer tutorials using gschem and gnetlist with ngspice:

http://geda.seul.org/wiki/geda:csygas

http://geda.seul.org/wiki/geda:ngspice_and_gschem

18.8.5CppSim

A complete simulation environment called CppSim has been developed and made available for
system level simulation of complex mixed signal circuits. ngspice has been integrated into the
simulation f l ow, as described here.

18.8.6NGSPICE Online

A web browser based interface is offered here. Simulation is performed on a remote server. The
project is not directly linked to our ngspice development project.

18.8.7Spicy Schematics

An IPAD and web interface (including schematics entry) to ngspice is offered here.Simulation
is performed on a remote server.

18.8.8MSEspice

A graphical front end to ngspice, using the Free Pascal cross platform RAD environment
MSEide+MSEgui.

18.8.9PartSim

A web based guiin your browser, including schematics entry. Simulation is performed on a
remote server.


348CHAPTER 18. NGSPICE USER INTERFACES


Chapter 19

ngspice as shared library or dynamic link
library

ngspice may be compiled as a shared library. This allows adding ngspice to an application
which then gains control over the simulator. The shared module offers an interface which
exports functions controlling the simulator and callback functions for feedback.

Soyoumaysendaninput"f i le"withanetlisttongspice, startthesimulationinaseparatethread,
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.

19.1Compile options

19.1.1How to get the sources

Currently (as of ngspice-25 being the actual release), you will have to use the direct loading of
the sources from the git repository (see chapt. 32.1.2).

19.1.2LINUX, MINGW, CYGWIN

Compilationisdoneasdescribedinchapts. 32.1or 32.2.1. Usetheconf i gureoption --with-ngshared
instead of --with-x or --with-wingui.

Other operation systems (Mac OS, BSD, ...) have not been tested so far. Your input is welcome!

19.1.3MS Visual Studio

Compilation is similar to what has been described in chapt. 32.2.3. There is however a ded-
icated project f i le coming with the source code to generate ngspice.dll. Go to the directory
visualc-shared and start the project with double clicking on sharedspice.sln.

349


350CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY

19.2Linking shared ngspice to a calling application

Basicallythere aretwomethods(as with all *.so, *.dll libraries). The caller may link to a (small)
library f i le during compiling/linking, and then immediately search for the shared library upon
being started. It is also possible to dynamically load the ngspice shared library at runtime using
the dlopen/LoadLibrary mechanisms.

19.2.1Linking during creating the caller

While creating the ngspice shared lib, not only the *.so (*.dll) f i le is created, but also a small
library f i le, which just includes references to the exported symbols. Depending on the OS, these
may be called libngspice.dll.a, ngspice.lib. Linux and MINGW also allow linking to the shared
object itself. The shared object is not included into the executable component but is tied to the
execution.

19.2.2Loading at runtime

dlopen (LINUX) or LoadLibrary (MS Windows) will load libngspice.so or ngspice.dll into the
address space of the caller at runtime. The functions return a handle which may be used to
acquire the pointers to the functions exported by libngspice.so. Detaching ngspice at runtime is
equally possible (using dlclose/FreeLibrary), after the background thread has been stopped and
all callbacks have returned.

19.3Shared ngspice API

The sources for the ngspice shared library API are contained in a single c f i le (sharedspice.c)
and a corresponding header f i le sharedspice.h. The type and function declarations are contained
in sharedspice.h, which may be directly added to the calling application, if written in C or C++.

19.3.1structs and types def i ned for transporting data

pvector_info is returned by the exported function ngGet_Vec_Info (see 19.3.2.5). Adresses of
the vector name, type, real or complex data are transferred and may be read asynchronously
during or after the simulation.

vector_info

typedefstructvector_info{
char

*v_name ;

/*Same asso_vname .

*/
intv_type ;/*Same asso_vtype .

*/
shortv_flags ;/*Flags( acombinationof VF_*).

*/
double

*v_realdata ;

/*Realdata .

*/
ngcomplex_t

*v_compdata ;/*

Complexdata .

*/
intv_length ;/*Lengthofthevector .

*/
}vector_info ,

*pvector_info ;


19.3. SHARED NGSPICE API351

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 and tran is used
or commands like linearize or fft are invoked, the function is called once by ngspice. Among
its parameters you f i nd 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. This struct is
declared in header f i le src/include/ngspice/dvec.h.

vecinfo

typedefstructvecinfo
{
intnumber ;/*numberofvector ,aspostioninthe
linkedl i s tofvectors ,s t a r t swith 0

*/
char

*vecname ;

/*name oftheactualvector

*/
boolis_real ;/*TRUE iftheactualvectorhasrealdata

*/
void

*pdvec ;

/*avoidpointertostructdvec

*d ,

the
actualvector

*/
void

*pdvecscale ;

/*avoidpointertostructdvec

*ds ,
thescalevector

*/
} vecinfo ,

*pvecinfo ;

vecinfoall

typedefstructvecinfoall
{
/*theplot

*/
char

*name ;
char

*t i t l e ;
char

*date ;
char

*type ;
intveccount ;

/*thedataasanarrayofvecinfowith
lengthequaltothenumber ofvectors
intheplot

*/
pvecinfo

*vecs ;

}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.


352CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY

vecvalues

typedefstructvecvalues{
char*name ;/*name of aspecificvector

*/
doublecreal ;/*actualdatavalue

*/
doublecimag ;/*actualdatavalue

*/
boolis_scale ;/*if’name ’isthescalevector

*/
boolis_complex ;/*ifthedataarecomplex numbers

*/
} vecvalues ,

*pvecvalues ;

Pointer vecvaluesall to be found as parameter to callback function SendData.

vecvaluesall

typedefstructvecvaluesall{
intveccount ;/*number ofvectorsinplot

*/
intvecindex ;/*indexofactualsetofvectors ,i . e .
thenumber ofaccepteddatapoints

*/
pvecvalues

*vecsa ;

/*valuesofactualsetofvectors ,
indexedfrom 0 toveccount − 1

*/
}vecvaluesall ,

*pvecvaluesall ;

19.3.2Exported functions

The functions listed in this chapter are the (only) symbols exported by the shared library.

19.3.2.1int ngSpice_Init(SendChar*, SendStat*, ControlledExit*, SendData*, SendInit-
Data*, BGThreadRunning*, void)

Aftercallerhasloadedngspice.dll, thesimulatorhastobeinitializedbycallingngSpice_Init(...).
Address pointers of several callback functions (see 19.3.3), which are to be def i ned in the caller,
are sent to ngspice.dll. The int return value is not used.

Pointers to callback functions (details see 19.3.3):

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 f l ag to caller, generated by ngspice upon
a call to function controlled_exit. May be used by caller to detach ngspice.dll, if dynami-
cally 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 vec-
tors 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)


19.3. SHARED NGSPICE API353

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 unmodif i ed by any callback
function (see the *void pointers in chapter 19.3.3). Callback functions are to be def i ned
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.

19.3.2.2int ngSpice_Init_Sync(GetVSRCData* , GetISRCData* , GetSyncData* , int*,
void*)

see chapt. 19.6.

19.3.2.3int ngSpice_Command(char*)

Send a valid command (see the control or interactive commands) from caller to ngspice.dll.
Will be executed immediately (as if in interactive mode). Some commands are rejected (e.g.
’plot’, because there is no graphics interface). Command ’quit’ will remove internal data, and
then send a notice to caller via ngexit(). The function returns a ’1’ upon error, otherwise ’0’.

19.3.2.4bool ngSpice_running (void)

Checks if ngspice is running in its background thread (returning ’true’).

19.3.2.5pvector_info ngGet_Vec_Info(char*)

uses the name of a vector (may be in the form ’vectorname’ or <plotname>.vectorname) as
parameter and returns a pointer to a vector_info struct. The caller may then directly assess the
vector data (but better should not modify them).

19.3.2.6int ngSpice_Circ(char**)

sends an array of null-terminated char* to ngspice.dll. Each char* contains a single line of a
circuit (Each line is like it is found in an input f i le *.sp.). The last entry to char** has to be
NULL. Upon receiving the array, ngspice.dll will immediately parse the input and set up the
circuit structure (as if the circuit is loaded from a f i le by the ’source’ command). The function
returns a ’1’ upon error, otherwise ’0’.

19.3.2.7char* ngSpice_CurPlot(void)

returns to the caller a pointer to the name of the current plot. For a def i nition of the term ’plot’
see chapt. 17.3.


354CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY

19.3.2.8char** ngSpice_AllPlots(void)

returns to the caller a pointer to an array of all plots (listed by their typename).

19.3.2.9char** ngSpice_AllVecs(char*)

returns to the caller a pointer to an array of all vector names in the plot named by the string in
the argument.

19.3.2.10bool ngSpice_SetBkpt(double)

see chapt. 19.6.

19.3.3Callback functions

Callback functions are a means to return data from ngspice to the caller. These functions are
def i ned as global functions in the caller, so to be reachable by the C-coded ngspice. They are
declared according to the typedefs given below. ngspice receives their addresses from the caller
upon initialization with the ngSpice_Init(...) function (see 19.3.2.1). If the caller will not make
use of a callback, it may send NULL instead of the address (except for ControlledExit, which
is always required).

If ngspice is run in the background thread (19.4.2), the callback functions (def i ned in the caller)
also are called from within that thread. One has to be carefully judging how this behavior might
inf l uence the caller, where now you have the primary and the background thread running in
parallel. So make the callback function thread safe. The integer identif i cation 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.

19.3.3.1typedef int (SendChar)(char*, int, void*)

char* string to be sent to caller output

int identif i cation 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 specif i ers 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 ori-
ented 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 unmodif i ed by each
callback, so the callback function may identify the class object which has initialized ngspice.dll.


19.3. SHARED NGSPICE API355

19.3.3.2typedef int (SendStat)(char*, int, void*)

char* simulation status and value (in percent) to be sent to caller

int identif i cation number of calling ngspice shared lib (default is 0, see chapt. 19.6)

void* return pointer received from caller

sending simulation status to caller, e.g. the string ’tran 34.5%’.

19.3.3.3typedef int (ControlledExit)(int, bool, bool, int, void*)

int exit status

bool if true: immediate unloading dll, if false: just set f l ag, unload is done when function has
returned

bool if true: exit upon ’quit’, if false: exit due to ngspice.dll error

int identif i cation number of calling ngspice shared lib (default is 0, see chapt. 19.6)

void* return pointer received from caller

asking for a reaction after controlled exit.

19.3.3.4typedef int (SendData)(pvecvaluesall, int, int, void*

vecvaluesall* pointer to array of structs containing actual values from all vectors

int number of structs (one per vector)

int identif i cation number of calling ngspice shared lib (default is 0, see chapt. 19.6)

void* return pointer received from caller

send back actual vector data.

19.3.3.5typedef int (SendInitData)(pvecinfoall, int, void*)

vecinfoall* pointer to array of structs containing data from all vectors right after initialization

int identif i cation number of calling ngspice shared lib (default is 0, see chapt. 19.6)

void* return pointer received from caller

send back initialization vector data.


356CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY

19.3.3.6typedef int (BGThreadRunning)(bool, int, void*)

bool true if background thread is running

int identif i cation number of calling ngspice shared lib (default is 0, see chapt. 19.6)

void* return pointer received from caller

indicate if background thread is running

19.4General remarks on using the API

19.4.1Loading a netlist

Basically the input to shared ngspice is the same as if you would start a ngspice batch job, e.g.
you enter a netlist and the simulation command (any .dot analysis command like .tran, .op, or
.dc etc. as found in chapt. 15.3), as well as suitable options.

Typically you should not include a .control section in your input f i le. 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).

The “typical usage” examples given below are excerpted from a caller written in C.

19.4.1.1Loading from f i le

As with interactive ngspice, you may use the ngspice internal command source (17.5.68) to
load a complete netlist from a f i le.

Typical usage:

ngSpice_Command (" source. . / examples / adder_mos . cir ");

19.4.1.2Loading line by line

As with interactive ngspice, you may use the ngspice internal command circbyline (17.5.10) to
send a netlist line by line to the ngspice circuit parser.

Typical usage:

ngSpice_Command (" circbylinef a i lt e s t ");
ngSpice_Command (" circbyline V1 1 01");
ngSpice_Command (" circbyline R1 1 01");
ngSpice_Command (" circbyline. dc V1 0 10.1");
ngSpice_Command (" circbyline. end ");

The f i rst 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.


19.4. GENERAL REMARKS ON USING THE API357

19.4.1.3Loading as a string array

Typical usage:

circarray= ( char**) malloc ( sizeof ( char*)

*

7);
circarray [0] = strdup (" t e s tarray ");
circarray [1] = strdup ("V1 1 01");
circarray [2] = strdup ("R1 1 21");
circarray [3] = strdup ("C1 2 0 1ic =0");
circarray [4] = strdup ( " . tran10u 3 uic ");
circarray [5] = strdup ( " . end ");
circarray [6] = NULL;
ngSpice_Circ ( circarray );

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 f i rst 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.

19.4.2Running the simulation

The following commands are used to start the simulator in its own thread, halt the simulation
and resume it again. The extra (background) thread enables the caller to continue with other
tasks in the main thread, e.g. watching its own event loop. Of course you have to take care
that the caller will not exit before ngspice is f i nished, otherwise you immediately will loose all
data. After having halted the simulator by suspending the background thread, you may assess
data, change ngspice parameters, or read output data using the caller’s main thread, before you
resume simulation using a background thread again. While the background thread is running,
ngspice will reject any other command sent by ngSpice_Command.

Typical usage:

ngSpice_Command (" bg_run ");
. . .
ngSpice_Command (" bg_halt ");
. . .
ngSpice_Command (" bg_resume ");

Basically you may send the commands ’run’ or ’resume’ (no pref i x 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 f i nished (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 o.k., because execution time is typically short.


358CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY

19.4.3Accessing data

19.4.3.1Synchronous access

The callback functions SendInitData (19.3.3.5) and SendData (19.3.3.4) allow access to sim-
ulator output data synchronized with the simulation progress.

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).

19.4.3.2Asynchronous access

During simulation, while the background thread is running, or after it is f i nished, you may
use the functions ngSpice_CurPlot (19.3.2.7), ngSpice_AllPlots (19.3.2.8), ngSpice_AllVecs
(19.3.2.9)toretrieveinformationaboutvectorsavailable, andfunctionngGet_Vec_Info(19.3.2.5)
to obtain data from a vector and its corresponding scale vector. The timing of the caller and the
simulation progress are independent from each other and not synchronized.

Again some code to demonstrate the callback function usage is referenced below (19.5).

19.4.4Altering model or device parameters

After halting ngspice by stopping the background thread (19.4.2), nearly all ngspice commands
are available. Especially alter (17.5.3) and altermod (17.5.4) may be used to change device
or model parameters. After the modif i cation, the simulation may be resumed immediately.
Changes to a circuit netlist, however, are not possible. You would need to load a complete new
netlist (19.4.1) and restart the simulation from the beginning.

19.4.5Output

After the simulation is f i nished, use the ngspice commands write (17.5.86) or wrdata (17.5.85)
to output data to a f i le as usual, use the print command (17.5.45) to retrieve data via callback
SendChar (19.3.3.1), or refer to accessing the data as described in chapter 19.4.3.


19.5. EXAMPLE APPLICATIONS359

Typical usage:

ngSpice_Command (" writetestout . raw V( 2 ) " ) ;
ngSpice_Command (" print V( 2 ) " ) ;

19.4.6Error handling

There are several occasions where standard ngspice suffers from an error, cannot recover in-
ternally and then exits. If this is happening to the shared module this would mean that the
parent application, the caller, is also forced to exit. Therefore (if not suffering form a seg fault)
ngspice.dll will call the function ’controlled_exit’ as usual, this now calls the callback function
’ControlledExit’ (19.3.3.3), which hands over the request for exiting to the caller. The caller
now has the task to handle the exit code for ngspice.

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.

19.5Example applications

Three executables (coming with source code) serve as examples for controlling ngspice. These
are not meant to be "productive" programs, but just give some commented example usages of
the interface.

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 dynam-
ically 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.

19.6ngspice parallel

The following chapter describes an offer to the advanced user and developer community. If you
are interested in evaluating the parallel and synchronized operation of several ngspice instances,
this may be one way to go. However, no ready to use implementation is available. You will
f i nd a toolbox and some hints how to use it. Parallelization and synchronization is your task by
developing a suitable caller! And of course another major input has to come from partitioning
the circuit into suitable, loosely coupled pieces, each with its own netlist, one netlist per ngspice
instance. And you have to def i ne the coupling between the circuit blocks. Both are not provided
by ngspice, but are again your responsibility. Both are under active research, and the toolbox
described below is an offer to join that research.


360CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY

19.6.1Go parallel!

A simple way to run several invocations of ngspice in parallel for transient simulation is to
def i ne a caller which loads two or more ngspice shared libraries. There is one prerequisite how-
ever 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 f i le, 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 identif i cation number may be sent during this step to later uniquely iden-
tify each invocation of the shared library, e.g. by having any callback use this identif i er. Repeat
the sequence with ngspice2.dll and so on.

Inter-process communication and synchronization is now done by using three callback func-
tions. To understand their interdependency, it might be useful to have a look at the transient
simulation sequence as def i ned in the ngspice source f i le dctran.c. The following listing in-
cludes 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() which calls callback function GetSync-
Data* getsync with location f l ag 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() which calls callback function GetSync-
Data* getsync with location f l ag loc = 1: as a result either goto 3 (next time step) or to
10 (loop start), depending on ngspice and user data, see next paragraph.


19.6. NGSPICE PARALLEL361

Thecodeofthesynchronizationprocedureishandledinthengspiceinternalfunctionsharedsync()
and its companion user def i ned 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 def i ne 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.

19.6.2Additional exported functions

The following functions (exported or callback) are designed to support the parallel action of
several ngspice invocations. They may be useful, however, also when only a single library is
loaded into a caller, if you want to use external voltage or current sources or ’play’ with the
advancing simulation time.

19.6.2.1int ngSpice_Init_Sync(GetVSRCData* , GetISRCData* , GetSyncData* , int*,
void*)

Pointers to callback functions (details see 19.3.3):

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 al-
lowed)

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-def i ned data, will not be modif i ed, but handed over back to caller dur-
ing 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.


362CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY

19.6.2.2bool ngSpice_SetBkpt(double)

Sets a breakpoint in ngspice, a time point which the simulator is enforced to hit during the
transient simulation. After the breakpoint time has been hit, the next delta time starts with a
small value and is ramped up again. A breakpoint should be set only when the background
thread in ngspice is not running (before the simulation has started, or after the simulation has
been paused by bg_halt). The time sent to ngspice should be larger than the current time (which
is either 0 before start or given by the callback GetSyncData (19.6.3.3). Several breakpoints
may be set.

19.6.3Additional callback functions

19.6.3.1typedef int (GetVSRCData)(double*, double, char*, int, void*)

double* return voltage value

double actual time

char* node name

int identif i cation 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 allows to set a voltage value to the node def i ned in the netlist and
named here at the time returned by the simulator.

19.6.3.2typedef int (GetISRCData)(double*, double, char*, int, void*)

double* return current value

double actual time

char* node name

int identif i cation 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 EX-
TERNAL option allows to set a current value to the node def i ned by the netlist and named here
at the time returned by the simulator.


19.6. NGSPICE PARALLEL363

19.6.3.3typedef int (GetSyncData)(double, double*, double, int, void*)

double actual time (ckt->CKTtime)

double* delta time (ckt->CKTdelta)

double old delta time (olddelta)

int identif i cation 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 explana-
tion.

19.6.4Parallel ngspice example

A f i rst example is available as a compacted 7z archive. It contains the source code of a control-
ling application, as well as its compiled executable and ngspice.dll (for MS Windows). As the
input circuit an inverter chain has been divided into three parts. Three ngspice shared libraries
are loaded, each simulates one partition of the circuit. Interconnections between the partitions
are provided via a callback function. The simulation time is synchronized among the three
ngspice invocations by another callback function.


364CHAPTER 19. NGSPICE AS SHARED LIBRARY OR DYNAMIC LINK LIBRARY


Chapter 20

TCLspice

Spice historically comes as a simulation engine with a Command Line Interface. Spice engine
now can be used with friendly Graphical User Interfaces. Tclspice represent 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 friendly
TCL shell (this is quite analogous to the command line interface of ngspice), or it permits the
elaboration of more complex, more specif i c, or more user friendly simulation programs, by
writing TCL scripts.

20.1tclspice framework

The technical difference between the ngspice CLI interface and tclspice is that the CLI interface
is compiled as a standalone program, whereas tclspice is a shared object. Tclspice is designed to
work with tools that expand the capabilities of ngspice: TCL for the scripting and programming
language interface and BLT for data processing and display. This two tools give tclspice all of
its relevance, with the insurance that the functionality is maintained by competent people.

Making tclspice (see 20.6) produces two f i les: 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 package1to the TCL user.

BLT is a TCL package. It is quite well documented. It permits to handle mathematical vector
data structure for calculus and display, in a Tk interpreter like wish.

20.2tclspice documentation

A detailed documentation on tclspice commands is available on the original tclspice web page.

20.3spicetoblt

Tclspice opens its doors to TCL and BLT with a single specif i c command spicetoblt.

1package has to be understood as the TCL package

365


366CHAPTER 20. TCLSPICE

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:

blt : : vectorcreateIex
spice : : vectobltVex#branchIex

Here an empty blt vector is created. It is then f i lled with the vector representation of the current
f l owing out of source Vex. Vex#branch is native spices syntax. Iex is the name of the BLT
vector.

The reverse operation is handled by native spice commands, such as alter, let and set.

20.4Running TCLspice

TCLspice consists of a library or a package to include in your tcl console or script:

load/ somepath / libspice . so
packagerequirespice

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 : : sourcetestCapa . cir
spice : : spicetobltexample . . .

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:

blt : : graph. cimvd −t i t l e"Cim = f (Vd)"
pack. cimvd
. cimvdelementcreateline1 −xdata Vcmd −ydata Cim

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, and not the least, plots the function Cim =
f(Vcmd), where Cim and Vcmd are two BLT vectors.

20.5examples

20.5.1Active capacitor measurement

In this crude implementation of a circuit described by Marc KODRNJA, in his PhD thesis that
I found on the Internet. This simulation outputs a graph representing the virtual capacitance
versus the command voltage. The function C = f(V) is calculated point by point. For each


20.5. EXAMPLES367

control voltage value, the virtual capacitance is calculated with the voltage and intensity across
the output port 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.1Invocation:

This script can be invoked by typing wish testbench1.tcl

20.5.1.2testbench1.tcl

This line loads the simulator capabilities

packagerequirespice

This is a comment (Quite useful if you intend to live with other Human beings)

# Testofvirtualcapacitorec i r c u i t
# Varythecontrolvoltageandlogtheresultingcapacitance

A good example of the calling of a spice command: precede it with spice::

spice : : source" testCapa . cir "

This reminds that any regular TCL command is of course possible

setn 30setdv0.2
setvmax [ expr$dv /2]
setvmin[ expr −1

*

$dv /2]
setpas[ expr$dv /$n]

BLT vector is the structure used to manipulate data. Instantiate the vectors

blt : : vectorcreateCtmp
blt : : vectorcreate Cim
blt : : vectorcreatecheck
blt : : vectorcreate Vcmd

Data is, in my coding style, plotted into graph objects. Instantiate the graph


368CHAPTER 20. TCLSPICE

blt : : graph. cimvd −t i t l e"Cim = f (Vd)"
blt : : graph. checkvd −t i t l e"Rim = f (Vd)"
blt : : vectorcreateIex
blt : : vectorcreatefreq
blt : : graph. freqanal −t i t l e" Analysefrequentielle "
#
#Firstsimulation : A simple AC plot
#
setv [ expr {$vmin + $n

*

$pas/4}]
spice : : a l t e rvd = $v
spice : : op
spice : : acdec 10 100 100k

Retrieve a the intensity of the current across Vex source

spice : : vectoblt{Vex#branch} Iex

Retrieve the frequency at which the current have been assessed

spice : : vectoblt{frequency }freq

Room the graph in the display window

pack. freqanal

Plot the function Iex =f(V)

. freqanalelementcreateline1 −xdatafreq −ydataIex
#
# Secondsimulation :Capacitanceversusvoltagecontrol
#for{ seti0}{[ expr $n − $i ]} { incri}
#{setv [ expr {$vmin + $i

*

$pas }]
spice : : a l t e rvd = $v
spice : : opspice : : acdec 10 100 100k

Image capacitance is calculated by spice, instead of TCL there is no objective reason

spice : : letCim = real (mean(Vex#branch /(2*Pi*i*frequency*(V(5)−V( 6 ) ) ) ) )
spice : : vectoblt Cim Ctmp

Build function vector point by point

Cim append $Ctmp (0: end )

Build a control vector to check simulation success


20.5. EXAMPLES369

spice : : leterr = real (mean( sqrt (( Vex#branch−
(2*Pi*i*frequency*Cim*V(5)−V( 6 ) ) ) ^ 2 ) ) )
spice : : vectoblterrCtmp check
append $Ctmp (0: end )

Build abscissa vector

FALTA ALGO. . .Vcmd append $v }

Plot

pack. cimvd
. cimvdelementcreateline1 −xdata Vcmd −ydata Cim
pack. checkvd
. checkvdelementcreateline1 −xdata Vcmd −ydatacheck

20.5.2Optimization of a linearization circuit for a Thermistor

This example is both the f i rst and the last optimization program I wrote for an electronic circuit.
It is far from perfect.

The temperature response of a CTN is exponential. It is thus nonlinear. In a battery charger
application f l oating 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 which minimizes the error between the expected f l oating voltage and the
TL431 output.

20.5.2.1Invocation:

This script can be executed by the user by simply executing the f i le in a terminal.

. / testbench3 . tcl

Two issues are important to point out2:

2For those who are really interested in optimizing circuits: Some parameters are very important for quick and

correct convergence. The optimizer walks step by step to a local minimum of the cost function you def i ne. Starting
from an initial vector YOU provide, it converges step by step. Consider trying another start vector if the result is
not the one you expected.
The optimizer will carry on walking until it reaches a vector which resulting cost is smaller than the target cost
YOU provide it. You will also provide a maximum iteration count in case the target can not be achieved. Balance
your time, specif i cations, and every other parameters. For a balance between quick and accurate convergence
adjust the "factor" variable, at the beginning of minimumSteepestDescent in the f i le differentiate.tcl.


370CHAPTER 20. TCLSPICE

• 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.2testbench3.tcl

This calls the shell sh who then runs wish with the f i le itself.

#!/ bin / sh
# WishFix\
execwish "$0" ${1+"$@"}
#
#
#

Regular package for simulation

packagerequirespice

Here the important line is source differentiate.tcl which contains optimization library

sourced i f f e r e n t i a t e . tcl

Generates a temperature vector

proctemperatures_calc{temp_inftemp_suppoints } {
settstep[expr"($temp_sup − $temp_inf)/$points"]
sett$temp_inf
settemperatures""
for{seti0 } {$i < $points} {incri} {
sett[expr {$t + $tstep} ]
settemperatures" $temperatures$t "
}
return$temperatures}

generates thermistor resistivity as a vector, typically run: thermistance_calc res B [ tempera-
tures_calc temp_inf temp_sup points ]


20.5. EXAMPLES371

procthermistance_calc{res B points} {
settzero273.15
sett r e f25
setthermistance""
foreacht$points{
setres_temp[ expr"$res

*

exp( $B

*

( 1/( $tzero + $t ) − 1
/($tzero +$tref)))"]
setthermistance" $thermistance$res_temp "
}
return$thermistance}

generates the expected f l oating value as a vector, typically run: tref_calc res B [ tempera-
tures_calc temp_inf temp_sup points ]

proctref_calc{points} {
sett r e f""
foreacht$points{
sett r e f"$tref[expr" 6

*

(2.275 −0.005*( $t − 20)) − 9"]"
}
return$tref}

In the optimization algorithm, this function computes the effective f l oating voltage at the given
temperature.

### NOTE:
### As componentvaluesaremodified by aspice : : a l t e r
Componentvaluescan beconsideredasglobalvariable .
### R10 and R12 arenotpassedtoi t e r a t i o nfunctionbecausei t
isexpectedtobecorrect ,ietohavebeenmodifiedsoon
beforeproci t e r a t i o n{t} {settzero273.15spice : : a l t e r
r11 = [thermistance_calc10000 3900$t]
# Temperaturesimulationoftencrashes .Commenti tout . . .
# spice : : settemp = [expr"$tzero + $t"]
spice : : op
spice : : vectobltvref_temptref_tmp
###NOTE:
###As thelibraryisexecutedonceforthewholescript
execution ,i tisimportanttomanagethe memory
###andregularlydestroyunuseddataset .Thedatacomputed
herewillnotbereused .Cleani t
spice : : destroyallreturn[tref_tmprange 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.


372CHAPTER 20. TCLSPICE

proccost{ r10r12 } {
t r e f _ b l tlength0
spice : : a l t e rr10 = $r10
spice : : a l t e rr12 = $r12
foreachpoint[temperatures_bltrange 0 [expr"[
temperatures_bltlength] − 1"]] {
t r e f _ b l tappend[i t e r a t i o n$point]
}
setresult[blt : : vectorexpr" 1000

*

sum ((t r e f _ b l t −
expected_blt) ^2) "]
disp_curve$r10$r12
return$result}

This function displays the expected and effective value of the voltage, as well as the r10 and r12
resistor values

procdisp_curve{ r10r12 } {. gconfigure −t i t l e" Valeurs
optimales : R10 = $r10 R12 = $r12 " }

Main loop starts here

#
# Optimization
#blt : : vectorcreatetref_tmp
blt : : vectorcreatet r e f _ b l t
blt : : vectorcreateexpected_blt
blt : : vectorcreatetemperatures_blttemperatures_blt
append[temperatures_calc −25 75 30 ]expected_blt
append[tref_calc[ temperatures_bltrange 0 [expr"[
temperatures_bltlength] − 1"]]]
blt : : graph. g
pack. g −sidetop −f i l lboth −expandtrue
. g elementcreatereal −pixels4 −xdatatemperatures_blt −ydata
t r e f _ b l t
. g elementcreateexpected −f i l lred −pixels0 −dashesdot −
xdatatemperatures_blt −ydataexpected_blt

Source the circuit and optimize it, result is retrieved in r10r12 variable and affected to r10 and
r12 with a regular expression. A bit ugly.

spice : : source FB14 . cir
setr10r12[: : math : : optimize : : minimumSteepestDescentcost{
10000 10000 } 0.150]
regexp{([0 −9.]*)([0 −9.]*) } $r10r12r10r12r10r12

Outputs optimization result


20.5. EXAMPLES373

#
#Results
#spice : : a l t e rr10 = $r10
spice : : a l t e rr12 = $r12
foreachpoint[temperatures_bltrange 0 [expr"[
temperatures_bltlength] − 1"]] {
t r e f _ b l tappend[i t e r a t i o n$point]
}
disp_curve$r10$r12

20.5.3Progressive display

This example is quite simple but it is very interesting. It displays a transient simulation result
on the f l y. You may now be familiar with most of the lines of this script. It uses the ability of
BLT objects to automatically update. When the vector data is modif i ed, the strip-chart display
is modif i ed accordingly.

20.5.3.1testbench2.tcl

#!/ bin / sh
# WishFix\
execwish −f"$0" ${1+"$@"}
###
packagerequire BLT packagerequirespice

this avoids to type blt:: before the blt class commands

namespaceimportblt ::*
wm t i t l e." VectorTestscript "
wm geometry.800x600+40+40 packpropagate.false

A strip chart with labels but without data is created and displayed (packed)


374CHAPTER 20. TCLSPICE

s t r i p c h a r t. chart
pack. chart −sidetop −f i l lboth −expandtrue
. chartaxisconfigurex −t i t l e"Time"spice : : sourceexample . cir
spice : : bg
runafter1000vector
createa0vector
createb0vectorry
createa1vector
createb1vector
createstime
procbltupdate{} {
puts[ spice : : spice_data ]
spice : : spicetoblta0 a0
spice : : spicetobltb0 b0
spice : : spicetoblta1 a1
spice : : spicetobltb1 b1
spice : : spicetoblttimestime
after100bltupdate}
bltupdate. chartelementcreatea0 −colorred −xdatastime −ydataa0
. chartelementcreateb0 −colorblue −xdatastime −ydatab0
. chartelementcreatea1 −coloryellow −xdatastime −ydataa1
. chartelementcreateb1 −colorblack −xdatastime −ydatab1

20.6Compiling

20.6.1LINUX

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.2MS Windows

Can be done, but is tedious. I will describe my procedure on Windows 7, 64 Bit Home Edition.

20.6.2.1Downloads

download tcl8.6b2-src.zip from http://www.tcl.tk/software/tcltk/download.html

download tk8.6b2-src.zip

download blt from http://ngspice.sourceforge.net/experimental/blt2.4z.7z

expand all to d:\software


20.7. MS WINDOWS 32 BIT BINARIES375

20.6.2.2Tcl

double click on D:\software\tcl8.6b2\win\tcl.dsw

convert to MS visual Studio 2008 project

select release or debug

create tcl as tcl86t.dll.

20.6.2.3Tk

edit D:\software\tk8.6b2\win\buildall.vc.bat

line 31 to

call "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"

line 53 to

if "%TCLDIR%" == "" set TCLDIR=..\..\tcl8.6b2

open cmd window

cd to

d:\software\tk8.6b2\win>

then

d:\software\tk8.6b2\win> buildall.vc.bat debug

tk will be made as tk86t.dll, in addition wish86t.exe is generated.

20.6.2.4blt

blt sorce f i les have been downloaded from the blt web page and modif i ed for compatibility with
TCL8.6. To facilitate making blt24.dll, the modif i ed source code is available as a 7z compressed
f i le, including a project f i le for MS Visual Studio 2008.

20.6.2.5tclspice

ngspice is compiled and linked into a dll called spice.dll which may be loaded by wish86t.exe.
MS Visual Studio 2008 is the compiler applied. A project f i le may be downloaded as a 7z
compressed f i le. Expand this f i le 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.

20.7MS Windows 32 Bit binaries

You may download the compiled binaries, including tcl, tk, blt and tclspice, plus the examples,
slightly modif i ed, from http://ngspice.sourceforge.net/experimental/tclspice-25.7z.


376CHAPTER 20. TCLSPICE


Chapter 21

Example Circuits

This section starts with an ngspice example to walk you through the basic features of ngspice
using its command line user interface. The operation of ngspice will be illustrated through
several examples (chapters 20.1 to 20.7).

The f i rst example uses the simple one-transistor amplif i er circuit illustrated in Figure 21.1. This
circuit is constructed entirely with ngspice compatible devices and is used to introduce basic
concepts, including:

• Invoking the simulator:

• Running simulations in different analysis modes

• Printing and plotting analog results

• Examining status, including execution time and memory usage

• Exiting the simulator

The remainder of the section (from chapter 21.2 onwards) lists several circuits, which have been
accompanying any ngspice distribution, and may be regarded as the “classical” SPICE circuits.

21.1AC coupled transistor amplif i er

The circuit shown in Figure 21.1 is a simple one-transistor amplif i er. The input signal is ampli-
f i ed with a gain of approximately -(Rc/Re) = -(3.9K/1K) = -3.9. The circuit description f i le for
this example is shown below.

377


378CHAPTER 21. EXAMPLE CIRCUITS

Figure 21.1: Transistor Amplif i er Simulation Example

Example:

A Berkeley SPICE3 compatiblec i r c u i t
*
*

Thisc i r c u i tcontainsonlyBerkeley SPICE3 components .
*
*

Thec i r c u i tisan AC coupledt r a n s i s t o ramplifierwith
*

a sinewaveinputatnode"1" ,againofapproximately−3.9,
*

andoutputon node " coll ".
*
. tran1e−5 2e−3
*
vccvcc 0 12.0
vin 1 0 0.0ac1.0sin (0 1 1k)
ccouple 1 base 10uF
rbias1vccbase100k
rbias2base 0 24k
q1collbaseemitgeneric
rcollectorvcccoll3.9k
remitteremit 0 1k
*
. modelgenericnpn
*
. end

Tosimulatethiscircuit, moveintoadirectoryunderyouruseraccountandcopythef i lexspice_c1.cir
from directory /examples/xspice/. This f i le stems from the original XSPICE introduction,


21.1. AC COUPLED TRANSISTOR AMPLIFIER379

therefore its name, but you do not need installing 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 Figure 21.1.

Now, execute the simulation by entering the “run” command:

ngspice 1 -> run


380CHAPTER 21. EXAMPLE CIRCUITS

The simulator will run the simulation and when execution is completed, will return with the
ngspice prompt. When the prompt returns, issue the rusage command again to see how much
time and memory has been used now.

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 Figure
21.2.

Figure 21.2: node 1 and node ’base’ versus time

Notice that we have named one of the nodes in the circuit description with a number (“1”),
while the others are words (“base”). This was done to illustrate ngspice’s special requirements
for plotting nodes labeled with numbers. Numeric labels are allowed in ngspice for backwards
compatibility with SPICE2. However, they require special treatment in some commands such
as “plot”. The “plot” command is designed to allow expressions in its argument list in addition
to names of results data to be plotted. For example, the expression plot (base - 1) would
plot the result of subtracting 1 from the value of node “base”.

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 amplif i er circuit:


21.1. AC COUPLED TRANSISTOR AMPLIFIER381

ngspice 3 -> plot vcc coll emit

The plot shown in Figure 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 suff i x "#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.

Figure 21.3: VCC, Collector and Emitter Voltages

Now let’s run a simple DC simulation of this circuit and examine the bias voltages with the
"print" command. One way to do this is to quit the simulator using the "quit" command, edit
the input f i le to change the ".tran" line to ".op" (for ’operating point analysis’), re-invoke the
simulator, and then issue the "run" command. However, ngspice allows analysis mode changes
directly from the ngspice prompt. All that is required is to enter the control line, e.g. op (without
the leading "."). ngspice will interpret the information on the line and start the new analysis run
immediately, without the need to enter a new "run" command.

To run the DC simulation of the transistor amplif i er, 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


382CHAPTER 21. EXAMPLE CIRCUITS

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
Nutmeg 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.


21.2. DIFFERENTIAL PAIR383

21.2Differential Pair

The following deck determines the dc operating point of a simple differential pair. In addition,
the ac small-signal response is computed over the frequency range 1Hz to 100MEGHz.

Example:

SIMPLE DIFFERENTIAL PAIR
VCC 7 0 12
VEE 8 0 −12
VIN 1 0 AC 1
RS1 1 2 1K
RS2 6 0 1K
Q1 3 2 4 MOD1
Q2 5 6 4 MOD1
RC1 7 3 10K
RC2 7 5 10K
RE 4 8 10K
.MODEL MOD1 NPN BF=50 VAF=50 IS =1.E−12 RB=100 CJC=.5PF TF=.6NS
.TF V(5) VIN
.AC DEC 10 1 100MEG
.END

21.3MOSFET Characterization

The following deck computes the output characteristics of a MOSFET device over the range
0-10V for VDS and 0-5V for VGS.

Example:

MOS OUTPUT CHARACTERISTICS
.OPTIONS NODE NOPAGE
VDS 3 0
VGS 2 0
M1 1 2 0 0 MOD1 L=4U W=6U AD=10P AS=10P
*

VIDS MEASURES ID , WE COULD HAVE USED VDS, BUT ID WOULD BE NEGATIVE
VIDS 3 1
.MODEL MOD1 NMOS VTO=−2 NSUB=1.0E15 UO=550
.DC VDS 0 10.5 VGS 0 5 1
.END

21.4RTL Inverter

The following deck determines the dc transfer curve and the transient pulse response of a simple
RTL inverter. The input is a pulse from 0 to 5 Volts with delay, rise, and fall times of 2ns and
a pulse width of 30ns. The transient interval is 0 to 100ns, with printing to be done every
nanosecond.


384CHAPTER 21. EXAMPLE CIRCUITS

Example:

SIMPLE RTL INVERTER
VCC 4 0 5
VIN 1 0 PULSE 0 5 2NS 2NS 2NS 30NS
RB 1 2 10K
Q1 3 2 0 Q1
RC 3 4 1K
.MODEL Q1 NPN BF 20 RB 100 TF .1NS CJC 2PF
.DC VIN 0 5 0.1
.TRAN 1NS 100NS
.END

21.5Four-Bit Binary Adder (Bipolar)

The following deck simulates a four-bit binary adder, using several subcircuits to describe vari-
ous pieces of the overall circuit.

Example:

ADDER − 4 BIT ALL−NAND −GATE BINARY ADDER
***

SUBCIRCUIT DEFINITIONS
.SUBCKT NAND 1 2 3 4
*

NODES: INPUT(2) , OUTPUT, VCC
Q1 9 5 1 QMOD
D1CLAMP 0 1 DMOD
Q2 9 5 2 QMOD
D2CLAMP 0 2 DMOD
RB 4 5 4K
R1 4 6 1.6K
Q3 6 9 8 QMOD
R2 8 0 1K
RC 4 7 130
Q4 7 6 10 QMOD
DVBEDROP 10 3 DMOD
Q5 3 8 0 QMOD
.ENDS NAND


21.5. FOUR-BIT BINARY ADDER (BIPOLAR)385

Continue 4 Bit adder :

.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

***

DEFINE NOMINAL CIRCUIT
.MODEL DMOD D
.MODEL QMOD NPN(BF=75 RB=100 CJE=1PF CJC=3PF)
VCC 99 0 DC 5V
VIN1A 1 0 PULSE(0 3 0 10NS 10NS 10NS 50NS)
VIN1B 2 0 PULSE(0 3 0 10NS 10NS 20NS 100NS)
VIN2A 3 0 PULSE(0 3 0 10NS 10NS 40NS 200NS)
VIN2B 4 0 PULSE(0 3 0 10NS 10NS 80NS 400NS)
VIN3A 5 0 PULSE(0 3 0 10NS 10NS 160NS 800NS)
VIN3B 6 0 PULSE(0 3 0 10NS 10NS 320NS 1600NS)
VIN4A 7 0 PULSE(0 3 0 10NS 10NS 640NS 3200NS)
VIN4B 8 0 PULSE(0 3 0 10NS 10NS 1280NS 6400NS)
X1 1 2 3 4 5 6 7 8 9 10 11 12 0 13 99 FOURBIT
RBIT0 9 0 1K
RBIT1 10 0 1K
RBIT2 11 0 1K
RBIT3 12 0 1K
RCOUT 13 0 1K

***

(FOR THOSE WITH MONEY (AND MEMORY) TO BURN)
.TRAN 1NS 6400NS
.END


386CHAPTER 21. EXAMPLE CIRCUITS

21.6Four-Bit Binary Adder (MOS)

The following deck simulates a four-bit binary adder, using several subcircuits to describe vari-
ous pieces of the overall circuit.

Example:

ADDER − 4 BIT ALL−NAND −GATE BINARY ADDER
***

SUBCIRCUIT DEFINITIONS
.SUBCKT NAND in1in2out VDD
*

NODES:INPUT(2) , OUTPUT, VCC
M1 outin2 Vdd Vdd p1 W=7.5u L=0.35u pd=13.5u ad =22.5p ps =13.5u as =22.5p
M2 net .1in2 0 0 n1W=3uL=0.35u pd=9uad=9p
ps=9uas=9p
M3 outin1 Vdd Vdd p1 W=7.5u L=0.35u pd=13.5u ad =22.5p ps =13.5u as =22.5p
M4 outin1net .10 n1 W=3uL=0.35u pd=9uad=9p
ps=9uas=9p
.ENDS NAND
.SUBCKT ONEBIT 1 2 3 4 5 6 AND
X21786NAND
X32796NAND
X489 106NAND
X53 10 116NAND
X63 11 126NAND
X710 11 136NAND
X812 1346NAND
X911756NAND
.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
X11275 109ONEBIT
X234 10689ONEBIT
.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
X112349 10 13 16 15TWOBIT
X25678 11 12 16 14 15TWOBIT
.ENDS FOURBIT


21.7. TRANSMISSION-LINE INVERTER387

Continue 4 Bit adder MOS:

***

POWER
VCC990DC 3.3V
***

INPUTS
VIN1A10DC 0 PULSE(0 3 0 5NS 5NS20NS50NS)
VIN1B20DC 0 PULSE(0 3 0 5NS 5NS30NS100NS)
VIN2A30DC 0 PULSE(0 3 0 5NS 5NS50NS200NS)
VIN2B40DC 0 PULSE(0 3 0 5NS 5NS90NS400NS)
VIN3A50DC 0 PULSE(0 3 0 5NS 5NS170NS800NS)
VIN3B60DC 0 PULSE(0 3 0 5NS 5NS330NS 1600NS)
VIN4A70DC 0 PULSE(0 3 0 5NS 5NS650NS 3200NS)
VIN4B80DC 0 PULSE(0 3 0 5NS 5NS 1290NS 6400NS)
***

DEFINE NOMINAL CIRCUIT
X1123456789 10 11 120 13 99 FOURBIT

. optionacct
. 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

.TRAN 1NS 6400NS

*

use BSIM3 modelwithdefaultparameters
. model n1 nmoslevel =49version =3.3.0
. model p1 pmoslevel =49version =3.3.0

.END

21.7Transmission-Line Inverter

The following deck simulates a transmission-line inverter. Two transmission-line elements are
required since two propagation modes are excited. In the case of a coaxial line, the f i rst line
(T1) models the inner conductor with respect to the shield, and the second line (T2) models the
shield with respect to the outside world.

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
.TRAN 0.1NS 20NS
.END


388CHAPTER 21. EXAMPLE CIRCUITS


Chapter 22

Statistical circuit analysis

22.1Introduction

Real circuits do not operate in a world with f i xed values of device parameters, power supplies
and environmental data. Even if a ngspice output offers 5 digits or more of precision, this
should not mislead you thinking that your circuits will behave exactly the same. All physical
parameters inf l uencing a circuit (e.g. MOS Source/drain resistance, threshold voltage, transcon-
ductance) are distributed parameters, often following a Gaussian distribution with a mean value
µand a standard deviation σ.

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. Its seed value
is derived from the process id upon start-up of ngspice. If you need reproducible random num-
bers, you may start ngspice setting the command set rndseed=<int value> into spinit or
.spiceinit. 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.

22.2Using random param(eters)

The ngspice frontend (with its ’numparam’ parser) contains the .param (see chapt. 2.8.1) and
.func (see chapt. 2.9) commands. Among the built-in functions supported (see 2.8.5) you will
f i nd the following statistical functions:

389


390CHAPTER 22. STATISTICAL CIRCUIT ANALYSIS

Built-in functionNotes
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

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.

Random number example using parameters:

* random number tests
.param aga = agauss(1,2,3)
.param aga2=’2*aga’
.param lim=limit(0,1.2)
.func rgauss(a,b,c) ’5*agauss(a,b,c)’
* always same value as defined above
v1 1 0’lim’
v2 2 0’lim’
* may be a different value
v3 3 0’limit(0,1.2)’
* always new random values
v11 11 0 ’agauss(1,2,3)’
v12 12 0 ’agauss(1,2,3)’
v13 13 0 ’agauss(1,2,3)’
* same value as defined above
v14 14 0 ’aga’
v15 15 0 ’aga’
v16 16 0 ’aga2’
* using .func, new random values
v17 17 0 ’rgauss(0,2,3)’
v18 18 0 ’rgauss(0,2,3)’
.op
.control
run
print v(1) v(2) v(3) v(11) v(12) v(13)
print v(14) v(15) v(16) v(17) v(18)
.endc
.end


22.3. BEHAVIORAL SOURCES (B, E, G, R, L, C) WITH RANDOM CONTROL391

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 f i xed numerical value, but insert a ’parameter’ instead,
which may consist of a token def i ned 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 f i le.

22.3Behavioral sources (B, E, G, R, L, C) with random con-
trol

All sources listed in the section header may contain parameters, which will be evaluated before
simulation starts, as described in the previous section (22.2). In addition the nonlinear voltage
or current sources (B-source, 5) as well as their derivatives E and G, but also the behavioral R,
L, and C may be controlled during simulation by a random independent voltage source V with
TRRANDOM option (chapt. 4.1.8).

Anexamplecircuit, aWienbridgeoscillatorfrominputf i le/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.

Examples for control of a behavioral resistor:

*

randomr e s i s t o r
. paramres = 10k
. paramttime =12000m
. paramvaria =100
. paramttime10 = ’ ttime / varia ’
*

randomcontrolvoltage( Gaussiandi stribution )
VR2 r20 dc 0 trrandom(2’ ttime10 ’ 0 1)
*

behavioralr e s i s t o r
R2 4 6R = ’ 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.


392CHAPTER 22. STATISTICAL CIRCUIT ANALYSIS

22.4ngspice scripting language

The ngspice scripting language is described in detail in chapter 17.8. All commands listed in
chapter 17.5 are available, as well as the built-in functions decried in chapter 17.2, the control
structures listed in chapter 17.6, and the predef i ned variables from chapt. 17.7. Variables and
functions are typically evaluated after a simulation run. You may created loops with several
simulation runs and change device and model parameters with the alter (17.5.3) or altermod
(17.5.4) commands, as shown in the next section 22.5. You may even interrupt a simulation run
by proper usage of the stop (17.5.72) and resume (17.5.51) commands. After stop you may
change device or model parameters and then go on with resume, continuing the simulation with
the new parameter values.

The statistical functions provided for scripting are listed in the following table:


22.5. MONTE-CARLO SIMULATION393

NameFunction
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
from a Poisson distribution. The elements of the input
vector (real numbers) are the expected numbers l.
Complex vectors are allowed, real and imaginary values
are treated separately.
exponential(vector)Returns a vector with its elements (real numbers) drawn
from an exponential distribution. The elements of the input
vector are the respective mean values (real numbers).
Complex vectors are allowed, real and imaginary values
are treated separately.

22.5Monte-Carlo Simulation

The ngspice scripting language may be used to run Monte-Carlo simulations with statistically
varying device or model parameters. Calls to the functions sgauss(0) or sunif(0) (see 17.2) will
return Gaussian or uniform distributed random numbers (real numbers), stored in a vector. You
may def i ne (see 17.5.14) your own function using sgauss or sunif, e.g. to change the mean or
range. In a loop (see 17.6) then you may call the alter (17.5.3) or altermod (17.5.4) statements
with random parameters followed by an analysis like op, dc, ac, tran or other.

22.5.1Example 1

Thef i rstexamplesisaLCbandpassf i lter, whereLandCdeviceparameterswillbechanged100
times. Each change is followed by an ac analysis. All graphs of output voltage versus frequency
are plotted. The f i le is available in the distribution as /examples/Monte_Carlo/MonteCarlo.sp
as well as from the CVS repository.


394CHAPTER 22. STATISTICAL CIRCUIT ANALYSIS

Monte-Carlo example 1

Perform Monte Carlosimulationinngspice
V1 N001 0 AC 1 DC 0
R1 N002 N001 141
*
C1 OUT 0 1e−09
L1 OUT 0 10e−06
C2 N002 0 1e−09
L2 N002 0 10e−06
L3 N003 N002 40e−06
C3 OUT N003 250e−12
*
R2 0 OUT 141
*
. control
letmc_runs = 100
letrun = 1
setcurplot = new$createa newplot
setscratch = $curplot$storei t sname to’ scratch ’
*
defineunif (nom,var )(nom + nom*var

*

sunif (0))
defineaunif (nom,avar )(nom + avar

*

sunif (0))
definegauss (nom,var ,sig )(nom + nom*var / sig

*

sgauss (0))
defineagauss (nom,avar ,sig )(nom + avar / sig

*

sgauss (0))
*
dowhilerun <= mc_runs
*

a l t e rc1 = unif (1e−09,0.1)
*

a l t e rl1 = aunif (10e−06, 2e−06)
*

a l t e rc2 = aunif (1e−09, 100e−12)
*

a l t e rl2 = unif (10e−06,0.2)
*

a l t e rl3 = aunif (40e−06, 8e−06)
*

a l t e rc3 = unif (250e−12,0.15)
a l t e rc1 = gauss (1e−09,0.1 ,3)
a l t e rl1 = agauss (10e−06, 2e−06, 3)
a l t e rc2 = agauss (1e−09, 100e−12, 3)
a l t e rl2 = gauss (10e−06,0.2 ,3)
a l t e rl3 = agauss (40e−06, 8e−06, 3)
a l t e rc3 = gauss (250e−12,0.15 ,3)
acoct100 250K 10Meg
setrun ="$&run "$createavariablefromthevector
setdt = $curplot$storethecurrentplottodt
setplot$scratch$ make’ scratch ’theactiveplot
*

storetheoutputvectortoplot’ scratch ’
le tvout{$run}={$dt }. v( out )
setplot$dt$ go backtothepreviousplot
le trun = run + 1
end
plotdb({ $scratch }. all )
. endc

. end


22.6. DATA EVALUATION WITH GNUPLOT395

22.5.2Example 2

A more sophisticated input f i le for Monte Carlo simulation is distributed with the f i le /exam-
ples/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 ran-
dom numbers. A function unif, def i ned by the line

define unif(nom, var) (nom + (nom*var) * sunif(0))

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 f i le MC_ring.sp.

22.5.3Example 3

The next example is contained in the f i les MC_2_control.sp and MC_2_circ.sp from folder /ex-
amples/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 f i le
MC_2_circ.sp, runs the simulation, stores a raw f i le, makes an fft, saves the oscillator frequency
thus measured, deletes all outputs, increases the loop counter and restarts the loop. The netlist
f i le MC_2_circ.sp contains the circuit, which is the same ring oscillator as of example 2. How-
ever, now the MOS model parameter set, which is included with this netlist f i le, inherits some
AGAUSS functions (see 2.8.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

ngspice -o MC_2_control.log MC_2_control.sp

22.6Data evaluation with Gnuplot

Run the example f i le /examples/Monte_Carlo/OpWien.sp, described in chapt. 22.3. Generate a
plot with Gnuplot by the ngspice command


396CHAPTER 22. STATISTICAL CIRCUIT ANALYSIS

gnuplot pl4mag v4mag xlimit 500 1500

Open and run the command f i le in the Gnuplot command line window by

load ’pl-v4mag.p’

A Gaussian curve will be f i tted to the simulation data. The mean oscillator frequency and its
deviation are printed in the curve f i tting log in the Gnuplot window.

Gnuplot script for data evaluation:

# This file: pl-v4mag.p
# ngspice file OpWien.sp
# ngspice command:
# gnuplot pl4mag v4mag xlimit 500 1500
# a gnuplot manual:
# http://www.duke.edu/~hpgavin/gnuplot.html

# Gauss function to be fitted
f1(x)=(c1/(a1*sqrt(2*3.14159))*exp(-((x-b1)**2)/(2*a1**2)))
# Gauss function to plot start graph
f2(x)=(c2/(a2*sqrt(2*3.14159))*exp(-((x-b2)**2)/(2*a2**2)))
# start values
a1=50 ; b1=900 ; c1=50
# keep start values ina2, b2, c2
a2=a1 ; b2=b1 ; c2=c1
# curve fitting
fit f1(x) ’pl4mag.data’ using 1:2 via a1, b1, c1
# plot original and fitted curves with new a1, b1, c1
plot "pl4mag.data" using 1:2 with lines, f1(x), f2(x)


22.6. DATA EVALUATION WITH GNUPLOT397

pl4mag.dataisthesimulationdata, f2(x)thestartingcurve, f1(x)thef i ttedGaussiandistribution.

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.


398CHAPTER 22. STATISTICAL CIRCUIT ANALYSIS


Chapter 23

Circuit optimization with ngspice

23.1Optimization of a circuit

Your circuit design (analog, maybe mixed-signal) has already the best circuit topology. There
might be still some room for parameter selection, e.g. the geometries of transistors or values of
passive elements, to best f i t the specif i c purpose. This is, what (automatic) circuit optimization
will deliver. In addition you may f i ne-tune, optimize and verify the circuit over voltage, process
or temperature corners. So circuit optimization is a valuable tool in the hands of an experienced
designer. It will relieve you from the routine task of ’endless’ repetitions of re-simulating your
design.

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 f l ow 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 def i ned by the user to tell the simulator when to f i nish (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 inf l uence the convergence be-
havior. 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 simula-
tion 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.

399


400CHAPTER 23. CIRCUIT OPTIMIZATION WITH NGSPICE

23.2ngspice optimizer using ngspice scripts

Friedrich Schmidt (see his web site) has intensively used circuit optimization during his devel-
opment of Nonlinear loadf l ow computation with Spice based simulators. He has provided an
optimizer using the internal ngspice scripting language (see chapt. 17.8). His original scripts
are found here. A slightly modif i ed and concentrated set of his scripts is available from the
ngspice optimizer directory.

The simple example given in the scripts is o.k. with current ngspice. Real circuits have still to
be tested.

23.3ngspice optimizer using tclspice

ngspice offers another scripting capability, namely the tcl/tk based tclspice option (see chapt.
20). An optimization procedure may be written using a tcl script. An example is provided in
chapter 20.5.2.

23.4ngspice optimizer using a Python script

Werner Hoch has developed a ngspice optimization procedure based on the ’differential evolu-
tion’ algorithm [21]. On his web page he provides a Python script containing the control f l ow
and algorithms.

23.5ngspice optimizer using ASCO

The ASCO optimizer, developed by Joao Ramos, also applies the ’differential evolution’ al-
gorithm [21]. An enhanced version 0.4.7.1, adding ngspice as a simulation engine, may be
downloaded here (7z archive format). Included are executable f i les (asco, asco-mpi, ngspice-c
for MS Windows). The source code should also compile and function under LINUX (not yet
tested).

ASCO is a standalone executable, which communicates with ngspice via ngspice input and out-
put f i les. 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 distribu-
tion 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 f i le INSTALL.


23.5. NGSPICE OPTIMIZER USING ASCO401

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.

23.5.1Three stage operational amplif i er

This example is taken from chapter 6.2.2 “Tutorial #2” from the ASCO manual. The directory
examples/ngspice/amp3 contains four f i les:

amp3.cfgThis f i le contains all conf i guration data for this optimization. Of special interest is
thefollowingsection, whichsetstherequiredmeasurementsandtheconstraintsonthemeasured
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 f i le 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 f i les contains an # Info # section, which is currently not used. The # Com-
mands # section may contain a measurement command (including ASCO parameter #SYM-
BOL#, see f i le /extract/unity_gain_frequency). It also may contain a .control section (see f i le
/extract/phase_margin_min). During set-up #SYMBOL# is replaced by the f i le name, a leading
’z’, and a trailing number according to the above sequence, starting with 0.

amp3.spThis is the basic circuit description. Entries like #LM2# are ASCO-specif i c, def i ned
in the # Parameters # section of f i le amp3.cfg. ASCO will replace these parameter placeholders
with real values for simulation, determined by the optimization algorithm. The .control ... .endc
section is specif i c to ngspice. Entries to this section may deliver workarounds of some com-
mands not available in ngspice, but used in other simulators. You may also def i ne additional
measurements, get access to variables and vectors, or def i ne some data manipulation. In this
example the .control section contains an op measurement, required later for slew rate calcula-
tion, 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 mea-
surements sets another plot ac1. To retrieve op data from the former plot, you have to use the
{$dt}.<vector> notation (see f i le /extract/amp3_slew_rate).

n.typ, p.typMOSFET parameter f i les, to be included by amp3.sp.


402CHAPTER 23. CIRCUIT OPTIMIZATION WITH NGSPICE

Testing the set-up

Copy asco-test.exe and ngspice_c.exe (console executable of ngspice) into the directory, and
run

$ asco-test -ngspice amp3

fromtheconsolewindow. Severalf i leswillbecreatedduringchecking. Ifyoulookat<computer-
name>.sp: this is the input f i le for ngspice_c, generated by ASCO. You will f i nd the additional
.measure commands and .control sections. The ’quit’ command will be added automatically
just before the .end command in its own .control section. asco-test will display error mes-
sages on the console, if the simulation or communication with ASCO is not o.k.. The out-
put f i le <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 which cannot
be handled by ASCO. Here it may help calling ngspice directly with the input f i le generated by
ASCO:

$ ngspice_c <computer-name>.sp

Thus you may evaluate the ngspice messages directly.

Running the simulation

Copy (w)asco.exe, (w)asco-mpi.exe and ngspice_c.exe (console executable of ngspice) into the
directory, and run

$ asco -ngspice amp3

or alternatively (if MPICH is installed)

$ mpiexec -n 7 asco-mpi -ngspice amp3

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 suff i ces to optimize 21 parameters of the amplif i er.

23.5.2Digital inverter

This example is taken from chapter 6.2.1 “Tutorial #1” from the ASCO manual. In addition
to the features already mentioned above, it adds Monte-Carlo and corner simulations. The f i le
inv.cfg contains the following section:

#Optimization Flow#
Alter:yes$do we want to do corner analysis?
MonteCarlo:yes$do we want to do MonteCarlo analysis?


23.5. NGSPICE OPTIMIZER USING ASCO403

Figure 23.1: Optimization speed

AlterMC cost:3.00 $point at which we want to start ALTER and/or
MONTECARLO
ExecuteRF:no$Execute or no the RF module to add RF parasitics?
SomethingElse:$
#

Monte Carlo is switched on. It uses the AGAUSS function (see chapt. 22.2). Its parameters are
generated by ASCO from the data supplied by the inv.cfg section #Monte Carlo#. According to
the paper by Pelgrom on MOS transistor matching [22] the AGAUSS parameters are calculated
as

W = AGAUSS

?
W,

ABeta

√2·W ·L·m·

W
100

·10−6,1

?
(23.1)

delvto = AGAUSS

?
0,

AVT

√2·W ·L·m·10−9,1

?
(23.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. Specif i c 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


404CHAPTER 23. CIRCUIT OPTIMIZATION WITH NGSPICE

run
.endc
#

NMOS (nm) and PMOS (pm) model parameter sets are loaded from three different model f i les,
each containing both NMOS and PMOS sets. b3.typ is assembled from the original parameter
f i les n.typ and p.typ, provided with original ASCO, with some adaptation to ngspice BSIM3.
The min and max sets are artif i cially created in that only the gate oxide thickness deviates ±1
nm from what is found in model f i le b3.typ. In addition the power supply voltage is varied, so
in total you will f i nd 3 x 3 simulation combinations in the input f i le <computer-name>.sp (after
running asco-test).

23.5.3Bandpass

This example is taken from chapter 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
notavailable inngspice, so S11andS21 are derived with a script in f i le 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 f i les in directory extract).
The result of a ’measure’ statement is a vector, which may be processed by commands in the
following lines. In f i le extract/S1_In_Band #Symbol# is made available only after a short calcu-
lation (inversion of sign), using the ’print’ command. ’quit’ has been added to this entry because
it will become the f i nal 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 def i ned 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?

inbandpass.cfg. Thetwo subcircuitsLBOND_sub and CSMD_sub are generated in <computer-
name>.sp to simulate these effects.

23.5.4Class-E power amplif i er

This example is taken from chapter 6.2.3 “Tutorial #3” from the ASCO manual. In this example
the ASCO post processing is applied in f i le extract/P_OUT (see chapter 7.4 of the ASCO man-
ual.). In this example .measurement statements are used. They allow using parameters from
.param statements, because they will be located outside of .control sections, but do not allow to
do data post processing inside of ngspice. You may use ASCO post processing instead.


Chapter 24

Notes

24.1Glossary

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 which together specify all input information required in
order to perform an analysis. A “deck” of “cards” will in fact be contained within a f i le
on the host computer system.

element card A single, logical line in an ngspice circuit description deck which describes a
circuit element. Circuit elements are connected to each other to form circuits (e.g., a
logical card which 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 specif i ed 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 which sup-
ports the construction of user-def i ned models by simplifying input/output and parameter-
passing operations within the Model Def i nition File.

.mod Refers to the Model Def i nition File in XSPICE. The f i le suff i x ref l ects the f i le-name of
the model def i nition f i le: cfunc.mod.

.model Refers to a model card associated with an element card in ngspice. A model card allows
for data def i ning an instance to be conveniently located in the ngspice deck such that the
general layout of the elements is more readable.

Nutmeg The ngspice default post-processor. This provides a simple stand-alone simulator
interface which can be used with the ngspice simulator to display and plot simulator raw
f i les.

405


406CHAPTER 24. NOTES

subcircuit A “device” within an ngspice deck which is def i ned in terms of a group of element
cards and which can be referenced in other parts of the ngspice deck through element
cards.

24.2Acronyms and Abbreviations

ATE Automatic Test Equipment

CAE Computer-Aided Engineering

CCCS Current Controlled Current Source.

CCVS Current Controlled Voltage Source.

FET Field Effect Transistor

IDD Interface Design Document

IFS Refers to the Interface Specif i cation File. The abbreviation ref l ects the f i le name of the
Interface Specif i cation File: ifspec.ifs.

MNA Modif i ed Nodal Analysis

MOSFET Metal Oxide Semiconductor Field Effect Transistor

PWL Piece-Wise Linear

RAM Random Access Memory

ROM Read Only Memory

SDD Software Design Document

SI Simulator Interface

SPICE Simulation Program with Integrated Circuit Emphasis. This program was developed at
the University of California at Berkeley and is the origin of ngspice.

SPICE3 Version 3 of SPICE.

SRS Software Requirements Specif i cation

SUM Software User’s Manual

UCB University of California at Berkeley

UDN User-Def i ned Node(s)

VCCS Voltage Controlled Current Source.

VCVS Voltage Controlled Voltage Source

XSPICE Extended SPICE; option to ngspice integrating predef i ned or user def i ned code mod-
els for event-driven mixed-signal simulation.


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.SakuraiandA.R.Newton, ASimpleMOSFETModelforCircuitAnalysisanditsappli-
cation 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 MOS-
FET, Master’s thesis, University of California, Berkeley, December 1986.

[7]Clement Szeto, Simulation of Temperature Effects in MOSFETs (STEIM), Master’s the-
sis, University of California, Berkeley, May 1988.

[8]J.S. Roychowdhury and D.O. Pederson, Eff i cient Transient Simulation of Lossy Intercon-
nect, 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.3 MOSFET Model User’s Manual”, BSIM3v3.2.3

407


408BIBLIOGRAPHY

[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 En-
gineering 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 Sys-
tems, San Diego, CA, May 1992, vol 2, pp. 871-874.

[18] ”APhysicallyBasedCompactModelofPartiallyDepletedSOIMOSFETsforAnalogCir-
cuit 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 (link)

[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


Part II

XSPICE Software User’s Manual

409



Chapter 25

XSPICE Basics

25.1ngspice with the XSPICE option

TheXSPICEoptionallowsyoutoaddevent-drivensimulationcapabilitiestoNGSPICE.NGSPICE
now is the main software program that performs mathematical simulation of a circuit specif i ed
by you, the user. It takes input in the form of commands and circuit descriptions and produces
output data (e.g. voltages, currents, digital states, and waveforms) that describe the circuit’s
behavior.

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 signif i cant portions of digital circuitry can be eff i ciently simulated together with analog
components. NGSPICE with XSPICE option also includes a “User-Def i ned 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, made available from Georgia Tech.

In the following, the term “XSPICE” may be read as “NGSPICE with XSPICE code model sub-
system enabled”. You may enable the option by adding --enable-xspiceto the ./configure
command. The MS Windows distribution already contains the XSPICE option.

25.2The XSPICE Code Model Subsystem

The new component of ngspice, the Code Model Subsystem, provides the tools needed to model
the various parts of your system. While NGSPICE is targeted primarily at integrated circuit (IC)
analysis, XSPICE includes features to model and simulate board-level and system-level designs
as well. The Code Model Subsystem is central to this new capability, providing XSPICE with
an extensive set of models to use in designs and allowing you to add your own models to this
model set.

The NGSPICE simulator at the core of XSPICE includes built-in models for discrete com-
ponents commonly found within integrated circuits. These “model primitives” include compo-
nents such as resistors, capacitors, diodes, and transistors. The XSPICE Code Model Subsystem

411


412CHAPTER 25. XSPICE BASICS

extends this set of primitives in two ways. First, it provides a library of over 40 additional prim-
itives, including summers, integrators, digital gates, controlled oscillators, s-domain transfer
functions, and digital state machines. See chapter 12 for a description of the library entries.
Second, it adds a code model generator to ngspice which provides a set of programming utili-
ties 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. Upon runtime ngspice will
load the code model libraries and make the code model instances available for simulation.

25.3XSPICE Top-Level Diagram

A top-level diagram of the XSPICE system integrated into ngspice is shown in Figure 25.1.
The XSPICE Simulator is made up of the NGSPICE core, the event-driven algorithm, circuit
description syntax parser extensions, a loading routine for code models, and the Nutmeg user
interface. The XSPICE Code Model Subsystem consists of the Code Model Generator, 5 stan-
dard code model library sources with more than 40 code models, the sources for Node Type
Libraries, and all the interfaces to User-Def i ned Code Models and to User-Def i ned Node Types.

Figure 25.1: ngspice/XSPICE Top-Level Diagram


Chapter 26

Execution Procedures

This chapter covers operation of the XSPICE simulator and the Code Model Subsystem. It
begins with background material on simulation and modeling and then discusses the analysis
modes supported in XSPICE and the circuit description syntax used for modeling. Detailed
descriptions of the predef i ned Code Models and Node Types provided in the XSPICE libraries
are also included.

26.1Simulation and Modeling Overview

This section introduces the concepts of circuit simulation and modeling. It is intended primarily
for users who have little or no previous experience with circuit simulators, and also for those
who have not used circuit simulators recently. However, experienced SPICE users may wish to
scan the material presented here since it provides background for new Code Model and User-
Def i ned Node capabilities of the XSPICE option.

26.1.1Describing the Circuit

This section provides an overview of the circuit description syntax expected by the XSPICE
simulator. A general understanding of circuit description syntax will be helpful to you should
you encounter problems with your circuit and need to examine the simulator’s error messages,
or should you wish to develop your own models.

This section will introduce you to the creation of circuit description input f i les using the Nutmeg
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.

26.1.1.1Example Circuit Description Input

Although different SPICE-based simulators may include various enhancements to the basic
version from the University of California at Berkeley, most use a similar approach in describing
circuits. This approach involves capturing the information present in a circuit schematic in
the form of a text f i le that follows a def i ned format. This format requires the assignment of
alphanumeric identif i ers to each circuit node, the assignment of component identif i ers to each

413


414CHAPTER 26. EXECUTION PROCEDURES

Figure 26.1: Example Circuit 1

circuit device, and the def i nition of the signif i cant parameters for each device. For example, the
circuit description below shows the equivalent input f i le for the circuit shown in Figure26.1.

Small Signal Amplifier
*
*This circuit simulates a simple small signal amplifier.
*
VinInput 00 SIN(0 .1 500Hz)
R_sourceInput Amp_In100
C1Amp_In 01uF
R_Amp_InputAmp_In 01MEG
E1(Amp:Out 0) (Amp_In 0)-10
R_LoadAmp_Out 01000
*
.Tran 1.0u 0.01
*
.end

This f i le exhibits many of the most important properties common to all SPICE circuit descrip-
tion f i les including the following:

• The f i rst line of the f i le is always interpreted as the title of the circuit. The title may
consist of any text string.

• Lines which provide user comments, but no circuit information, are begun by an asterisk.

• A circuit device is specif i ed by a device name, followed by the node(s) to which it is
connected, and then by any required parameter information.

• The f i rst 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 identif i er. The only specif i c labeling re-
quirement 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.


26.1. SIMULATION AND MODELING OVERVIEW415

• An “.end” statement must be included at the end of the f i le.

• With the exception of the Title and .end statements, the order in which the circuit f i le is
def i ned is arbitrary.

• All identif i ers are case insensitive - the identif i er ‘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 f i rst column.

In this example, the title of the circuit is ‘Small Signal Amplif i er’. Three comment lines are
included before the actual circuit description begins. The f i rst 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 f i le are interpreted similarly.

The control directive that begins with ‘.Tran’ specif i es 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 in-
serted in the f i le.

.op

A fourth analysis type supported by ngspice is swept DC analysis. An example control state-
ment for the analysis mode is

.dc Vin -0.1 0.2 .05

This statement specif i es a DC sweep which varies the source Vin from -100 millivolts to +200
millivolts in steps of 50 millivolts.


416CHAPTER 26. EXECUTION PROCEDURES

Figure 26.2: Example Circuit 2

26.1.1.2Models and Subcircuits

The f i le discussed in the previous section illustrated the most basic syntax rules of a circuit
description f i le. However, ngspice (and other SPICE-based simulators) include many other
features which allow for accurate modeling of semiconductor devices such as diodes and tran-
sistors and for grouping elements of a circuit into a macro or ‘subcircuit’ description which can
be reused throughout a circuit description. For instance, the f i le shown below is a representation
of the schematic shown in Figure 26.2.

Small Signal Amplifier with Limit Diodes
*
*This circuit simulates a small signal amplifier
*with a diode limiter.
*
.dc Vin -1 1 .05
*
VinInput 0 DC0
R_sourceInput Amp_In100
*
D_Neg0 Amp_In1n4148
D_PosAmp_In 01n4148
*
C1Amp_In 01uF
X1Amp_In 0 Amp.OutAmplifier
R_LoadAmp_Out 01000
*
.model 1n4148 D (is=2.495E-09 rs=4.755E-01 n=1.679E+00
+ tt=3.030E-09 cjo=1.700E-12 vj=1 m=1.959E-01 bv=1.000E+02
+ ibv=1.000E-04)
*
.subckt Amplifier Input Common Output
E1(Output Common) (Input Common) -10
R_InputInputCommon 1meg
.ends Amplifier
*
.end


26.1. SIMULATION AND MODELING OVERVIEW417

This is the same basic circuit as in the initial example, with the addition of two components and
some changes to the simulation f i le. The two diodes have been included to illustrate the use of
device models, and the amplif i er is implemented with a subcircuit. Additionally, this f i le shows
the use of the swept DC control card.

Device ModelsDevice models allow you to specify, when required, many of the parameters
of the devices being simulated. In this example, model statements are used to def i ne the silicon
diodes. Electrically, the diodes serve to limit the voltage at the amplif i er input to values between
about ±700 millivolts. The diode is simulated by f i rst 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 f i le which provides the necessary electrical specif i cations for the device (“1n4148” is the
part number for the type of diode the model is meant to simulate).

The model statement that provides this information is:

.model 1n4148 D (is=2.495E-09 rs=4.755E-01 n=1.679E+00
+tt=3.030E-09 cjo=1.700E-12 vj=1 m=1.959E-01
+bv=1.000E+02 ibv=1.000E-04)

The model statement always begins with the string “.model” followed by an identif i er and the
model type (D for diode, NPN for NPN transistors, etc).

The optional parameters (‘is’, ‘rs’, ‘n’, ‘etc.’) shown in this example conf i gure the simulator’s
mathematical model of the diode to match the specif i c behavior of a particular part (e.g. a
“1n4148”).

SubcircuitsIn some applications, describing a device by embedding the required elements in
the main circuit f i le, as is done for the amplif i er in Figure 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 f i le:

X1 Amp_In 0 Amp_Out

Amplif i er Subcircuits are always identif i ed by a device label beginning with “X”. Just as with
other devices, all of the connected nodes are specif i ed. Notice, in this example, that three nodes
are used. Finally, the name of the subcircuit is specif i ed. Elsewhere in the circuit f i le, the
simulator looks for a statement of the form:

.subckt <Name> <Node1> <Node2> <Node3> ...

Thisstatementspecif i esthatthelinesthatfollowarepartoftheAmplif i ersubcircuit, andthatthe
three nodes listed are to be treated wherever they occur in the subcircuit def i nition 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 def i nition is concluded
with a statement of the form:

.ends <Name>


418CHAPTER 26. EXECUTION PROCEDURES

26.1.1.3XSPICE Code Models

Inthepreviousexample, thespecif i cationoftheamplif i erwasaccomplishedbyusingaNGSPICE
Voltage Controlled Voltage Source device. This is an idealization of the actual amplif i er. Prac-
tical amplif i ers include numerous non-ideal effects, such as offset error voltages and non-ideal
input and output impedances. The accurate simulation of complex, real-world components can
lead to cumbersome subcircuit f i les, long simulation run times, and diff i culties in synthesizing
the behavior to be modeled from a limited set of internal devices known to the simulator.

Toaddresstheseproblems, XSPICEallowsyoutocreateCodeModelswhichsimulatecomplex,
non-idealeffectswithouttheneedtodevelopasubcircuitdesign. Forexample, thefollowingf i le
provides simulation of the circuit in Figure 26.2, but with the subcircuit amplif i er replaced with
a Code Model called ‘Amp’ that models several non-ideal effects including input and output
impedance and input offset voltage.

Small Signal Amplifier
*
*This circuit simulates a small signal amplifier
*with a diode limiter.
*
.dc Vin -1 1 .05
*
VinInput 0DC 0
R_sourceInput Amp_In100
*
D_Neg 0Amp_In1n4148
D_PosAmp_In 01n4148
*
C1Amp_In 01uF
A1Amp_In 0 Amp_OutAmplifier
R_LoadAmp_Out 01000
*
.model 1n4148 D (is=2.495E-09 rs=4.755E-01 n=1.679E+00
+ tt=3.030E-09 cjo=1.700E-12 vj=1 m=1.959E-01 bv=1.000E+02
+ ibv=1.000E-04)
*
.model Amplifier Amp (gain = -10 in_offset = 1e-3
+rin = 1meg rout = 0.4)
*
.end

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.


26.2. CIRCUIT DESCRIPTION SYNTAX419

26.1.1.4Node Bridge Models

When a mixed-mode simulator is used, some method must be provided for translating data
between the different simulation algorithms. XSPICE’s Code Model support allows you to
develop models that work under the analog simulation algorithm, the event-driven simulation
algorithm, or both at once.

In XSPICE, models developed for the express purpose of translating between the different al-
gorithms or between different User-Def i ned Node types are called “Node Bridge” models. For
translations between the built-in analog and digital types, predef i ned node bridge models are
included in the XSPICE Code Model Library.

26.1.1.5Practical Model Development

In practice, developing models often involves using a combination of NGSPICE passive de-
vices, device models, subcircuits, and XSPICE Code Models. XSPICE’s Code Models may be
seen as an extension to the set of device models offered in standard NGSPICE. The collection
of over 40 predef i ned Code Models included with XSPICE provides you with an enriched set of
modeling primitives with which to build subcircuit models. In general, you should f i rst attempt
to construct your models from these available primitives. This is often the quickest and easiest
method.

If you f i nd 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.

26.2Circuit Description Syntax

If you need to debug a simulation, if you are planning to develop your own models, or if you
are using the XSPICE simulator through the Nutmeg user interface, you will need to become
familiar with the circuit description language.

The previous sections presented example circuit description input f i les. 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
ngspicesyntaxaredetailed. Finally, variousenhancementstoNGSPICEoperationarediscussed
including polynomial sources, arbitrary phase sources, supply ramping, matrix conditioning,
convergence options, and debugging support.

26.2.1XSPICE Syntax Extensions

In the preceding discussion, NGSPICE syntax was reviewed, and those features of NGSPICE
that are specif i cally supported by the XSPICE simulator were enumerated. In addition to these
features, there exist extensions to the NGSPICE capabilities that provide much more f l exibility
in describing and simulating a circuit. The following sections describe these capabilities, as
well as the syntax required to make use of them.


420CHAPTER 26. EXECUTION PROCEDURES

26.2.1.1Convergence Debugging Support

When a simulation is failing to converge, the simulator can be asked to return convergence diag-
nosticinformationthatmaybeusefulinidentifyingtheareasofthecircuitinwhichconvergence
problems are occurring. When running through the Nutmeg user interface, these messages are
written directly to the terminal.

26.2.1.2Digital Nodes

Support is included for digital nodes that are simulated by an event-driven algorithm. Because
the event-driven algorithm is faster than the standard SPICE matrix solution algorithm, and
because all “digital”, “real”, “int” and User-Def i ned Node types make use of the event-driven
algorithm, reduced simulation time for circuits that include these models can be anticipated
compared to simulation of the same circuit using analog code models and nodes.

26.2.1.3User-Def i ned Nodes

Support is provided for User Def i ned Nodes that operate with the event-driven algorithm. These
nodes allow the passing of arbitrary data structures among models. The real and integer node
types supplied with XSPICE are actually predef i ned User-Def i ned Node types.

26.2.1.4Supply Ramping

A supply ramping function is provided by the simulator as an option to a transient analysis
to simulate the turn-on of power supplies to a board level circuit. To enable this option, the
compile time f l ag XSPICE_EXP has to be set, e.g. by adding CFLAGS="-DXSPICE_EXP" to
the ./conf i gure command line. The supply ramping function linearly ramps the values of all
independent sources and the capacitor and inductor code models (code model extension) with
initial conditions toward their f i nal value at a rate which you def i ne. A complete ngspice deck
example of usage of the ramptime option is shown below.


26.3. HOW TO CREATE CODE MODELS421

Example:

Supply ramping option
*
* This circuitdemonstrates the use of the option
* "ramptime" which ramps independentsources and the
* capacitor and inductor initialconditions from
* zero to their final value during the time period
* specified.
*
*
.tran 0.1 5
.option ramptime=0.2
* a1 1 0 cap
.model cap capacitor (c=1000uf ic=1)
r1 1 0 1k
*
a2 2 0 ind
.model ind inductor (l=1H ic=1)
r2 2 0 1.0
*
v1 3 0 1.0
r3 3 0 1k
*
i1 4 0 1e-3
r4 4 0 1k
*
v2 5 0 0.0 sin(0 1 0.3 0 0 45.0)
r5 5 0 1k
*
.end

26.3How to create code models

The following instruction to create an additional code model uses the ngspice infrastructure and
some ’intelligent’ copy and paste. As an example an extra code model d_xxor is created in the
xtradev shared library, reusing the existing d_xor model from the digital library. More detailed
information will be made available in chapter 28.

You should have downloaded ngspice, either the most recent distribution or from the Git reposi-
tory, and compiled and installed it properly according to your operating system and the instruc-
tions given in chapter 32 of the Appendix, especially chapt. 32.1.4 (for LINUX users), or chapt.
32.2.1 for MINGW and MS Windows (MS Visual Studio will not do, because we not yet have
integrated the code model generator into this compiler! You may however use all code models
later with any ngspice executable.) . Then Cd into directory ngspice/src/xspice/icm/xtradev.


422CHAPTER 26. EXECUTION PROCEDURES

Create a new directory

mkdir d_xxor

Copythetwof i lescfunc.modandifspec.ifsfromngspice/src/xspice/icm/digital/d_xortongspice/s-
rc/xspice/icm/xtradev/d_xxor. These two f i les may serve as a template for your new model!

For simplicity reasons we do only a very simple editing to these f i les here, in fact the function-
ality 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 ngspice aware of the new code model by editing f i le
ngspice/src/xspice/icm/xtradev/modpath.lst:

Add a line with the new model name d_xxor.

Redo ngspice by entering directory ngspice/release, and issuing the commands:

make

sudo make install

And that’s it! In ngspice/release/src/xspice/icm/xtradev/ you now will f i nd cfunc.c and ifspec.c
and the corresponding object f i les. 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:

.model d_xor1 d_xxor (rise_delay=1.0e-6 fall_delay=2.0e-6 input_load=1.0e-12)

The complete input f i le follows:


26.3. HOW TO CREATE CODE MODELS423

Code Model Test: new xxor
*
*** analysis type ***
.tran .01s 4s
*
*** input sources ***
*
v2 200 0 DC PWL( (0 0.0) (2 0.0) (2.0000000001 1.0) (3 1.0) )
*
v1 100 0 DC PWL( (0 0.0) (1.0 0.0) (1.0000000001 1.0) (2 1.0)
+(2.0000000001 0.0) (3 0.0) (3.0000000001 1.0) (4 1.0) )
*
*** resistors to ground ***
r1 100 0 1k
r2 200 0 1k
*
*** adc_bridge blocks ***
aconverter [200 100] [2 1] adc_bridge1
.model adc_bridge1adc_bridge (in_low=0.1 in_high=0.9
+rise_delay=1.0e-12 fall_delay=1.0e-12)
*
*** xor block ***
a7 [1 2] 70 d_xor1
.model d_xor1 d_xxor (rise_delay=1.0e-6 fall_delay=2.0e-6
+input_load=1.0e-12)
*
*** dac_bridge blocks ****
abridge1 [70] [out] 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)
*
*** simulation and plotting ***
.control
run
plot allv
.endc
*
.end

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
chapter 28, especially chapters 28.6 ff. for any details. And of course you may take the existing


424CHAPTER 26. EXECUTION PROCEDURES

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.


Chapter 27

Example circuits

The following chapter is designed to demonstrate XSPICE features. The f i rst example circuit
models the circuit of Figure 26.2 using the XSPICE gain block code model to substitute for
the more complex and computationally expensive ngspice transistor model. This example illus-
trates one way in which XSPICE code models can be used to raise the level of abstraction in
circuit modeling to improve simulation speed.

The next example, shown in Figure 27.1, illustrates many of the more advanced features of-
fered by XSPICE. This circuit is a mixed-mode design incorporating digital data, analog data,
and User-Def i ned Node data together in the same simulation. Some of the important features
illustrated include:

• Creating and compiling Code Models

• Creating an XSPICE executable that incorporates these new models

• The use of "node bridge" models to translate data between the data types in the simulation

• Plotting analog and event-driven (digital and User-Def i ned Node) data

• Using the "eprint" command to print event-driven data

Throughout these examples, we assume that ngspice with XSPICE option has already been
installed on your system and that your user account has been set up with the proper search path
and environment variable data.

The examples also assume that you are running under LINUX and will use standard LINUX
commands such as “cp” for copying f i les, 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, f i le system path-names given in the examples as-
sume 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.

27.1Amplif i er with XSPICE model “gain”

The circuit, as has been shown in Figure 26.2, is extended here by using the XSPICE code
model "gain". The ngspice circuit description for this circuit is shown below.

425


426CHAPTER 27. EXAMPLE CIRCUITS

Example:

A t r a n s i s t o ramplifierc i r c u i t
*
. tran1e−5 2e−3
*
vin 1 0 0.0ac1.0sin (0 1 1k)
*
ccouple 1 in10uF
rzinin 0 19.35k
*
aamp inaoutgain_block
. modelgain_blockgain( gain = −3.9out_offset = 7.003)
*
rzoutaoutcoll3.9k
rbigcoll0 1e12
*
. end

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-def i ned identif i er 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 specif i ed as -3.9 to approximate the gain of the
transistor amplif i er, 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.

Notice also that input and output impedances of the one-transistor amplif i er circuit are modeled
with the resistors "rzin" and "rzout", since the "gain" code model defaults to an ideal voltage-
input, voltage-output device with inf i nite 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 f i le 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 ->


27.2. XSPICE ADVANCED USAGE427

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 amplif i er circuit sim-
ulated in Example 1.

When you are done, enter the "quit" command to leave the simulator and return to the command
line.

ngspice 3 -> quit

So long.

Using the "rusage" command, you can verify that this abstract model of the transistor amplif i er
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.

27.2XSPICE advanced usage

27.2.1Circuit example C3

An equally important use of code models is in creating models for circuits and systems that do
not easily lend themselves to synthesis using standard ngspice primitives (resistors, capacitors,
diodes, transistors, etc.). This occurs often when trying to create models of ICs for use in simu-
latingboard-leveldesigns. Creatingmodelsofoperationalamplif i erssuchasanLM741ortimer
ICs such as an LM555 is greatly simplif i ed through the use of XSPICE code models. Another
example of code model use is shown in the next example where a complete sampled-data system
is simulated using XSPICE analog, digital, and User-Def i ned Node types simultaneously.

The circuit shown in Figure 27.1 is designed to demonstrate several of the more advanced
features of XSPICE. In this example, you will be introduced to the process of creating code
models and linking them into ngspice. You will also learn how to print and plot the results of
event-driven analysis data. The ngspice/XSPICE circuit description for this example is shown
below.


428CHAPTER 27. EXAMPLE CIRCUITS

Figure 27.1: Example Circuit C3

Example:

Mixed IO types
*

Thisc i r c u i tcontainsamixtureof IO types ,including
*

analog ,digital ,user−defined( real ) ,and’ null ’ .
*
*

Thec i r c u i tdemonstratestheuseofthed i g i t a land
*

user−definednodecapabilitytomodel system−leveldesigns
*

suchassampled−dataf i l t e r s .Thesimulatedc i r c u i t
*

containsad i g i t a lo s c i l l a t o renabledafter100us .The
*

squarewaveo s c i l l a t o routputisdividedby 8 witha
*

ripplecounter .Theresultispassedthroughad i g i t a l
*

f i l t e rtoconverti ttoasinewave .
*
. tran1e−5 1e−3
*
v1 1 0 0.0pulse (0 1 1e−4 1e−6)
r1 1 0 1k
*
abridge1[1][ enable ]atod
. modelatodadc_bridge
*
aclk[ enableclk ]clknand
. model nand d_nand( rise_delay =1e−5 fall_delay =1e−5)
*
adiv2div2_outclk NULL NULL NULL div2_outdff
adiv4div4_outdiv2_out NULL NULL NULL div4_outdff
adiv8div8_outdiv4_out NULL NULL NULL div8_outdff
. modeldffd_dff


27.2. XSPICE ADVANCED USAGE429

Example (continued):

abridge2div8_outenablef i l t _ i nnode_bridge2
. modelnode_bridge2d_to_real( zero=−1 one=1)
*
x f i l t e rf i l t _ i nclkf i l t _ o u td i g _ f i l t e r
*
abridge3f i l t _ o u ta_outnode_bridge3
. modelnode_bridge3real_to_v
*
rlpf1a_outoa_minus 10k
*
xlpf0 oa_minuslpf_outopamp
*
rlpf2oa_minuslpf_out10k
clpflpf_outoa_minus0.01uF
***************************************
. subcktd i g _ f i l t e rf i l t _ i nclkf i l t _ o u t
. model n0real_gain( gain =1.0)
. model n1real_gain( gain =2.0)
. model n2real_gain( gain =1.0)
. model g1real_gain( gain =0.125)
. model zm1 real_delay
. model d0areal_gain( gain =−0.75)
. model d1areal_gain( gain =0.5625)
. model d0breal_gain( gain =−0.3438)
. model d1breal_gain( gain =1.0)
*
an0af i l t _ i nx0a n0
an1af i l t _ i nx1a n1
an2af i l t _ i nx2a n2
*
az0ax0aclkx1a zm1
az1ax1aclkx2a zm1
*
ad0a x2a x0a d0a
ad1a x2a x1a d1a
*
az2ax2afilt1_outg1
az3afilt1_outclkf i l t 2 _ i nzm1
*
an0bf i l t 2 _ i nx0b n0
an1bf i l t 2 _ i nx1b n1
an2bf i l t 2 _ i nx2b n2
*
az0b x0bclkx1b zm1
az1b x1bclkx2b zm1
*
ad0 x2b x0b d0b
ad1 x2b x1b d1b
*
az2b x2bclkf i l t _ o u tzm1
. endsd i g _ f i l t e r


430CHAPTER 27. EXAMPLE CIRCUITS

Example (continued):

. subckt opamp plusminusout
*
r1plusminus 300k
a1 %vd( plusminus )outintlim
. modellimlimit( out_lower_limit = −12 out_upper_limit = 12
+fraction= truelimit_range = 0.2gain =300e3 )
r3outintout50.0
r2out 0 1e12
*
. ends opamp
*
. end

This circuit is a high-level design of a sampled-data f i lter. 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 specif i ed 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 f l ip f l op.

The divide-by-8 and enable waveforms are converted by the instance "abridge2" to the format
required by the User-Def i ned Node type "real", which expected real-valued data. The output of
this instance on node "f i lt_in" is a real valued square wave which 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 "xf i lter" which contains a digital low-pass f i lter
clocked by node "clk". The result of passing this square-wave through the digital low-pass f i lter
is the production of a sampled sine wave (the f i lter passes only the fundamental of the square-
wave input) on node "f i lt_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 f i lter
constructed around subcircuit "xlpf" to produce the f i nal output at analog node "lpf_out".

27.2.2Running example C3

Now copy the f i le "xspice_c3.cir" from directory /examples/xspice/ into the current directory:

$ cp /examples/xspice/xspice_c3.cir xspice_c3.cir

and invoke the new simulator executable as you did in the previous examples.

$ ngspice xspice_c3.cir


27.2. XSPICE ADVANCED USAGE431

Execute the simulation with the "run" command.

ngspice 1 -> run

After a short time, the ngspice prompt should return. Results of this simulation are examined in
the manner illustrated in the previous two examples. You can use the "plot" command to plot
either analog nodes, event-driven nodes, or both. For example, you can plot the values of the
sampled-data f i lter input node and the analog low-pass f i lter output node as follows:

ngspice 2 -> plot filt_in lpf_out

The plot shown in Figure 27.2 should appear.

Figure 27.2: Nutmeg Plot of Filter Input and Output

You can also plot data from nodes inside a subcircuit. For example, to plot the data on node
"x1a" in subcircuit "xf i lter", create a pathname to this node with a dot separator.

ngspice 3 -> plot xfilter.x1a


432CHAPTER 27. EXAMPLE CIRCUITS

The output from this command is shown in Figure 27.3. Note that the waveform contains
vertical segments. These segments are caused by the non-zero delays in the "real gain" models
used within the subcircuit. Each vertical segment is actually a step with a width equal to the
model delay (1e-9 seconds).

Plotting nodes internal to subcircuits works for both analog and event-driven nodes.

Figure 27.3: Nutmeg Plot of Subcircuit Internal Node

To examine data such as the closely spaced events inside the subcircuit at node "xf i lter.x1a", it
is often convenient to use the "eprint" command to produce a tabular listing of events. Try this
by entering the following command:

ngspice 4 -> eprint xfilter.x1a
**** Results Data ****
Time or Step
xfilter.x1a
0.000000000e+000 0.000000e+0001.010030000e-004 2.000000e+000
1.010040000e-004 2.562500e+0001.210020000e-004 2.812500e+000
1.210030000e-004 4.253906e+0001.410020000e-004 2.332031e+000
1.410030000e-004 3.283447e+0001.610020000e-004 2.014893e+000


27.2. XSPICE ADVANCED USAGE433

1.610030000e-004 1.469009e+0001.810020000e-004 2.196854e+000
1.810030000e-004 1.176232e+000
...
9.610030000e-004 3.006294e-0019.810020000e-004 2.304755e+000
9.810030000e-004 9.506230e-0019.810090000e-004 -3.049377e+000
9.810100000e-004 -4.174377e+000
**** 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

This command produces a tabular listing of event-times in the f i rst column and node values in
the second column. The 1 ns delays can be clearly seen in the f i fth decimal place of the event
times.

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
priortothestartofthetransientanalysis. Duringthisoperatingpointanalysis, 37totalcallswere
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


434CHAPTER 27. EXAMPLE CIRCUITS

From this printout, we see that digital node values are composed of a two character string. The
f i rst 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.


Chapter 28

Code Models and User-Def i ned Nodes

ThefollowingsectionsexplainthestepsrequiredtocreatecodemodelsandUser-Def i nedNodes
(UDNs), store them in shared libraries and load them into the simulator at runtime. The ngspice
simulator already includes XSPICE libraries of predef i ned models and node types that span the
analog and digital domains. These have been detailed earlier in this document (see Sections
12.2, 12.3, and 12.4). However, the real power of the XSPICE is in its support for extending
these libraries with new models written by users. ngspice includes an XSPICE code model
generator. Adding code models to ngspice will require a model def i nition plus some simple f i le
operations, which are explained in this chapter.

The original manual cited an XSPICE “Code Model Toolkit” that enabled one to def i ne new
models and node data types to be passed between them off l ine, 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 chapter 32. Adding a code
model may then require def i ning the functionality , interface, and eventually user def i ned 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.11). 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 Predef i ned Code Models. The basic steps required to create sources for
new code models or User-Def i ned Nodes, compile them and load them into ngspice are similar.
They consist of 1) creating the code model or UserDef i ned Node (UDN) directory and its asso-
ciated model or data f i les, 2) inform ngspice about which code model or UDN directories 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 f i nally reside in dynamically linkable
shared libraries (*.cm), which in fact are .so f i les under LINUX or dlls under MS Windows.
Currently we have 5 of them (analog.cm, digital.cm, spice2poly.cm, xtradev.cm, xtraevt.cm).

435


436CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

Upon start up of ngspice they are dynamically loaded into the simulator by the ngspice code-
model command (which is located in f i le .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 f i le, 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 chapter 26.3. You may
f i nd the details of the XSPICE language in chapters 28.6 ff.

28.1Code Model Data Type Def i nitions

There are three data types which you can incorporate into a model and which have already
been used extensively in the code model library included with the simulator. These are detailed
below:

Boolean_tThe Boolean type is an enumerated type which 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_tThe Complex type is a structure composed of two double values. The f i rst of
these is the .real type, and the second is the .imag type. Typically these values are accessed as
shown:

Forcomplexvalue“data”, therealportionis“data.real”, andtheimaginaryportionis“data.imag”.

Digital_State_tThe Digital State type is an enumerated value which can be either ZERO
(integer value 0), ONE (integer value 1), or UNKNOWN (integer value 2).

Digital_Strength_tThe Digital Strength type is an enumerated value which can be either
STRONG (integer value 0), RESISTIVE (integer value 1), HI IMPEDANCE (integer value 2)
or UNDETERMINED (integer value 3).

Digital_tThe Digital type is a composite of the Digital_State_t and Digital_Strength_t enu-
merated data types. The actual variable names within the Digital type are .state and .strength
and are accessed as shown below:

ForDigital_tvalue“data”, thestateportionis“data.state”, andthestrengthportionis“data.strength”.

28.2Creating Code Models

The following description deals with extending one of the f i ve existing code model libraries.
Adding a new library is described in chapter 28.4. The f i rst step in creating a new code model
within XSPICE is to create a model directory inside of the selected library directory. The new
directory name is the name of the new code model. As an example you may add a directory
d_counter to the library directory digital.


28.3. CREATING USER-DEFINED NODES437

cd ngspice/src/xspice/icm/digital
mkdir d_counter

Into this new directory you copy the following template f i les:

• Interface Specif i cation File (ifspec.ifs)

• Model Def i nition File (cfunc.mod)

You may choose any of the existing f i les which are similar to the new code model you intend
to integrate. The template Interface Specif i cation File (ifspec.ifs) is edited to def i ne the model’s
inputs, outputs, parameters, etc (see chapt. 28.6). You then edit the template Model Def i nition
File (cfunc.mod) to include the C-language source code that def i nes the model behavior (see
chapt. 28.7). As a f i nal step you have to notify ngspice of the new code model. You have to edit
the f i le modpath.lst which resides in the library directory ngspice/src/xspice/icm/digital. Just
add the entry d_counter to this f i le.

The Interface Specif i cation File is a text f i le 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 specif i c
format presented to you in the Interface Specif i cation 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 Def i nition File contains a C programming language function def i nition. This func-
tion specif i es 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 Def i nition 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 f i les 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 f i les.

28.3Creating User-Def i ned Nodes

In addition to providing the capability of adding new models to the simulator, a facility exists
which allows node types other than those found in standard SPICE to be created. Models
may be constructed which pass information back and forth via these nodes. Such models are
constructed in the manner described in the previous sections, with appropriate changes to the
Interface Specif i cation and Model Def i nition 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


438CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

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-Def i ned Node (UDN) creation facilities described below and may
serve as a template for further node types.

The f i rst step in creating a new node type within XSPICE is to set up a node type directory
along with the appropriate template f i les needed.

cd ngspice/src/xspice/icm/xtraevt
mkdir <directory name>

<directory name> should be the name of the new type to be def i ned. Copy f i le udnfunc.c from
/icm/xtraevt/int into the new directory. Edit this f i le according to the new type you want to
create.

Notify ngspice about this new UDN directory by editing
ngspice/src/xspice/icm/xtraevt/udnpath.lst. Add a new line containing <directory name>. For
compiling and linking see chapt. 28.5.

The UDN Def i nition 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-Def i ned Node Def i nition
File in detail and includes an example UDN Def i nition File.

28.4Adding a new code model library

A group of code models may be assembled into a library. A new library is a means to distribute
new code models, independently from the existing ones. This is the way to generate a new code
model library:

cd ngspice/src/xspice/icm/
mkdir <directory name>

<directory name> is the name of the new library. Copy empty f i les modpath.lst and udnpath.lst
into this directory.

Edit f i le ngspice/src/xspice/icm/GNUmakef i le.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
def i ne at least one code model according to the procedure described in chapt. 28.2.

28.5Compiling and loading the new code model (library)

Compiling is now as simple as issuing the commands


28.6. INTERFACE SPECIFICATION FILE439

cd ngspice/release
make
sudo make install

if you have installed ngspice according to chapter 32.1.4. This procedure will install the code
model libraries into a directory <pref i x>/lib/spice/, e.g. C:/Spice/lib/spice/ for standard Win-
dows install or /usr/local/lib/spice/ for LINUX.

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.11). This is done automatically for the
predef i ned code model libraries upon starting ngspice. The appropriate commands are provided
in the start up f i le 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 f i le spinit by
adding the line

codemodel C:/Spice/lib/spice/new_lib.cm

(OSMSWindows)ortheappropriateLINUXequivalent. Uponstartingngspice, thenewlibrary
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.

28.6Interface Specif i cation File

The Interface Specif i cation (IFS) f i le is a text f i le that describes the model’s naming informa-
tion, its expected input and output ports, its expected parameters, and any variables within the
model that are to be used for storage of data across an entire simulation. These four types
of data are described to the simulator in IFS f i le sections labeled NAME TABLE, PORT TA-
BLE, PARAMETER TABLE and STATIC VAR TABLE, respectively. An example IFS f i le is
given below. The example is followed by detailed descriptions of each of the entries, what they
signify, and what values are acceptable for them. Keywords are case insensitive.

NAME_TABLE:
C_Function_Name:ucm_xfer
Spice_Model_Name:xfer
Description:"arbitrary transfer function"
PORT_TABLE:


440CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

Port_Name:inout
Description:"input""output"
Direction:inout
Default_Type:vv
Allowed_Types:[v,vd,i,id][v,vd,i,id]
Vector: no no
Vector_Bounds:--
Null_Allowed:nono
PARAMETER_TABLE:
Parameter_Name:in_offsetgain
Description:"input offset" "gain"
Data_Type:realreal
Default_Value:0.01.0
Limits:--
Vector:nono
Vector_Bounds:--
Null_Allowed:yesyes
PARAMETER_TABLE:
Parameter_Name:num_coeff
Description:"numerator polynomial coefficients"
Data_Type:real
Default_Value:-
Limits:-
Vector:yes
Vector_Bounds:[1 -]
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:den_coeff
Description:"denominator polynomial coefficients"
Data_Type:real
Default_Value:-
Limits:-
Vector:yes
Vector_Bounds:[1 -]
Null_Allowed:no
PARAMETER_TABLE:
Parameter_Name:int_ic
Description:"integrator stage initial conditions"
Data_Type:real
Default_Value:0.0
Limits:-
Vector:yes
Vector_Bounds:den_coeff
Null_Allowed:yes
STATIC_VAR_TABLE:
Static_Var_Name:x
Data_Type:pointer
Description:"x-coefficient array"


28.6. INTERFACE SPECIFICATION FILE441

28.6.1The Name Table

The name table is introduced by the “Name_Table:” keyword. It def i nes the code model’s C
function name, the name used on a .MODEL card, and an optional textual description. The
following sections def i ne the valid f i elds that may be specif i ed in the Name Table.

28.6.1.1C Function Name

The C function name is a valid C identif i er which is the name of the function for the code
model. It is introduced by the “C_Function_Name:” keyword followed by a valid C identif i er.
To reduce the chance of name conf l icts, it is recommended that user-written code model names
usethepref i x“ucm_”forthisentry. Thus, intheexamplegivenabove, themodelnameis“xfer”,
but the C function is “ucm_xfer”. Note that when you subsequently write the model function in
the Model Def i nition File, this name must agree with that of the function (i.e., “ucm_xfer”), or
an error will result in the linking step.

28.6.1.2SPICE Model Name

The SPICE model name is a valid SPICE identif i er that will be used on SPICE .MODEL cards
to refer to this code model. It may or may not be the same as the C function name. It is
introduced by the “Spice_Model_Name:” keyword followed by a valid SPICE identif i er.

DescriptionThe 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.2The Port Table

The port table is introduced by the “Port_Table:” keyword. It def i nes the set of valid ports
available to the code model. The following sections def i ne the valid f i elds that may be specif i ed
in the port table.

28.6.2.1Port Name

The port name is a valid SPICE identif i er. It is introduced by the “Port_Name:” keyword
followed by the name of the port. Note that this port name will be used to obtain and return
input and output values within the model function. This will be discussed in more detail in the
next section.

28.6.2.2Description

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.


442CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

Default Types
TypeDescriptionValid Directions
ddigitalin or out
gconductance (VCCS)inout
gddifferential conductance (VCCS)inout
hresistance (CCVS)inout
hddifferential resistance (CCVS)inout
icurrentin or out
iddifferential currentin or out
vvoltagein or out
vddifferential voltagein or out
<identif i er>user-def i ned typein or out

Table 28.1: Port Types

28.6.2.3Direction

The direction of a port specif i es the data f l ow direction through the port. A direction must be
one of “in”, “out”, or “inout”. It is introduced by the “Direction:” keyword followed by a valid
direction value.

28.6.2.4Default Type

The Default_Type f i eld specif i es the type of a port. These types are identical to those used to
def i ne the port types on a SPICE deck instance card (see Table 12.1), but without the percent
sign (%) preceding them. Table 28.1 summarizes the allowable types.

28.6.2.5Allowed Types

A port must specify the types it is allowed to assume. An allowed type value must be a list of
type names (a blank or comma separated list of names delimited by square brackets, e.g. “[v vd
i id]” or “[d]”). The type names must be taken from those listed in Table 28.1.

28.6.2.6Vector

A port which is a vector can be thought of as a bus. The Vector f i eld is introduced with the
“Vector:” keyword followed by a Boolean value: “YES”, “TRUE”, “NO” or “FALSE”.

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 f i eld that specif i es valid sizes of the vector port.

28.6.2.7Vector Bounds

If a port is a vector, limits on its size must be specif i ed in the vector bounds f i eld. The Vector
Bounds f i eld specif i es the upper and lower bounds on the size of a vector. The Vector Bounds


28.6. INTERFACE SPECIFICATION FILE443

f i eld is usually introduced by the “Vector_Bounds:” keyword followed by a range of integers
(e.g. “[1 7]” or “[3, 20]”). The lower bound of the vector specif i es the minimum number of
elementsinthevector; theupperbound specif i es themaximumnumberofelements. Iftherange
is unconstrained, or the associated port is not a vector, the vector bounds may be specif i ed by
a hyphen (“-”). Using the hyphen convention, partial constraints on the vector bound may be
def i ned (e.g., “[2, -]” indicates that the least number of port elements allowed is two, but there
is no maximum number).

28.6.2.8Null Allowed

In some cases, it is desirable to permit a port to remain unconnected to any electrical node in a
circuit. The Null_Allowed f i eld specif i es whether this constitutes an error for a particular port.
The Null_Allowed f i eld is introduced by the “Null_Allowed:” keyword and is followed by a
boolean constant: “YES”, “TRUE”, “NO” or “FALSE”. The values “YES” and “TRUE” are
equivalent and specify that it is legal to leave this port unconnected. “NO” or “FALSE” specify
that the port must be connected.

28.6.3The Parameter Table

The parameter table is introduced by the “Parameter_Table:” keyword. It def i nes the set of
valid parameters available to the code model. The following sections def i ne the valid f i elds that
may be specif i ed in the parameter table.

28.6.3.1Parameter Name

The parameter name is a valid SPICE identif i er which will be used on SPICE .MODEL cards
to refer to this parameter. It is introduced by the “Parameter_Name:” keyword followed by a
valid SPICE identif i er.

28.6.3.2Description

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.3Data Type

The parameter’s data type is specif i ed by the Data Type f i eld. The Data Type f i eld is introduced
by the keyword “Data_Type:” and is followed by a valid data type. Valid data types include
boolean, complex, int, real, and string.

28.6.3.4Null Allowed

The Null_Allowed f i eld is introduced by the “Null_Allowed:” keyword and is followed by a
boolean literal. A value of “TRUE” or “YES” specify that it is valid for the corresponding
SPICE .MODEL card to omit a value for this parameter. If the parameter is omitted, the default


444CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

value is used. If there is no default value, an undef i ned value is passed to the code model, and
the PARAM_NULL( ) macro will return a value of “TRUE” so that defaulting can be handled
within the model itself. If the value of Null_Allowed is “FALSE” or “NO”, then the simulator
will f l ag an error if the SPICE .MODEL card omits a value for this parameter.

28.6.3.5Default Value

If the Null_Allowed f i eld specif i es “TRUE” for this parameter, then a default value may be
specif i ed. This value is supplied for the parameter in the event that the SPICE .MODEL card
doesnotsupplyavaluefortheparameter. The default value mustbe of the correct type. The De-
fault Value f i eld is introduced by the “Default_Value:” keyword and is followed by a numeric,
boolean, complex, or string literal, as appropriate.

28.6.3.6Limits

Integer and real parameters may be constrained to accept a limited range of values. The follow-
ing range syntax is used whenever such a range of values is required. A range is specif i ed 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.7Vector

The Vector f i eld is used to specify whether a parameter is a vector or a scalar. Like the PORT
TABLE Vector f i eld, 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.3.8Vector Bounds

The valid sizes for a vector parameter are specif i ed in the same manner as are port sizes (see
Section 28.6.2.7). However, in place of using a numeric range to specify valid vector bounds it
is also possible to specify the name of a port. When a parameter’s vector bounds are specif i ed
in this way, the size of the vector parameter must be the same as the associated vector port.

28.6.4Static Variable Table

The Static Variable table is introduced by the “Static_Var_Table:” keyword. It def i nes the set of
valid static variables available to the code model. These are variables whose values are retained
between successive invocations of the code model by the simulator. The following sections
def i ne the valid f i elds that may be specif i ed in the Static Variable Table.


28.6. INTERFACE SPECIFICATION FILE445

28.6.4.1Name

The Static variable name is a valid C identif i er 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
identif i er.

28.6.4.2Description

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.

28.6.4.3Data Type

The static variable’s data type is specif i ed by the Data Type f i eld. The Data Type f i eld is in-
troduced by the keyword “Data_Type:” and is followed by a valid data type. Valid data types
include boolean, complex, int, real, string and pointer.

Notethat pointertypes areused tospecify 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 identif i ed 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 Specif i cation File.

/* Define local pointer variable */
double *local.x;

/* Allocate storage to be referenced by the static variable x. */
/* Do this only if this is the initial call of the code model. */
if (INIT == TRUE) {
STATIC_VAR(x) = calloc(size, sizeof(double));
}

/* Assign the value from the static pointer value to the local */
/* pointer variable. */
local_x = STATIC_VAR(x);

/* Assign values to first two members of the array */
local_x[0] = 1.234;
local_x[1] = 5.678;


446CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

28.7Model Def i nition File

The Model Def i nition File is a C source code f i le that def i nes a code model’s behavior given
input values which are passed to it by the simulator. The f i le itself is always given the name
“cfunc.mod”. In order to allow for maximum f l exibility, passing of input, output, and simulator-
specif i c information is handled through accessor macros, which are described below. In addi-
tion, certain predef i ned library functions (e.g. smoothing interpolators, complex arithmetic rou-
tines) are included in the simulator in order to ease the burden of the code model programmer.
These are also described below.

28.7.1Macros

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 def i ned in the Interface Specif i -
cation 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.

void code.model(ARGS) /* privatestructureaccessed by
accessor macros
*/
{
/* The following code fragments are intended to show how
information in the argument list is accessed. The reader
should not attempt to relate one fragment to another.
Consider each fragment as a separate example.
*/

double p,/* variable for use in the following code fragments */
x,/* variable for use in the following code fragments */
y;/* variable for use in the following code fragments */

int i,/* indexingvariable for use in the following */
j;/* indexing variable for use in the following */

UDN_Example_Type *a_ptr, /* A pointer used to access a
User-Defined Node type */
*y_ptr; /* A pointer used to access a
User-Defined Node type */

/* Initializing and outputting a User-Defined Node result */
if(INIT) {
OUTPUT(y) = malloc(sizeof(user.defined.struct));
y_ptr = OUTPUT(y);
y_ptr->component1 = 0.0;
y_ptr->component2 = 0.0;


28.7. MODEL DEFINITION FILE447

}
else {
y_ptr = OUTPUT(y);
y_ptr->component1 = x1;
y_ptr->component2 = x2;
}

/* Determininganalysis type */
if(ANALYSIS == AC) {
/* Perform AC analysis -dependentoperations here */
}

/* Accessing a parameter value from the .model card */
p = PARAM(gain);

/* Accessing a vector parameter from the .model card */
for(i = 0; i < PARAM_SIZE(in_offset); i++)
p = PARAM(in_offset[i]);

/* Accessing the value of a simple real-valued input */
x = INPUT(a);

/* Accessing a vector input and checking for null port */
if( ! PORT_NULL(a))
for(i = 0; i < PORT_SIZE(a); i++)
x = INPUT(a[i]);

/* Accessing a digital input */
x = INPUT(a);

/* Accessing the value of a User-Defined Node input...
*/
/* This node type includes two elements in its definition. */
a_ptr = INPUT(a);
x = a_ptr->component1;
y = a_ptr->component2;

/* Outputting a simple real-valued result */
OUTPUT(out1) = 0.0;

/* Outputting a vector result and checking for null */
if( ! PORT_NULL(a))
for(i = 0; i < PORT.SIZE(a); i++)
OUTPUT(a[i]) = 0.0;

/* Outputting the partial of output out1 w.r.t. input a */
PARTIAL(out1,a) = PARAM(gain);


448CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

/* Outputting the partial of output out2(i) w.r.t. input b(j) */
for(i = 0; i < PORT_SIZE(out2); i++) {
for(j = 0; j < PORT_SIZE(b); j++) {
PARTIAL(out2[i],b[j]) = 0.0;
}
}

/* Outputting gain from input c to output out3 in an
AC analysis */
complex_gain_real = 1.0;
complex_gain_imag = 0.0;
AC_GAIN(out3,c) = complex_gain;

/* Outputting a digital result */
OUTPUT_STATE(out4) = ONE;

/* Outputting the delay for a digital or user-defined output */
OUTPUT_DELAY(out5) = 1.0e-9;
}

28.7.1.1Macro Def i nitions

The full set of accessor macros is listed below. Arguments shown in parenthesis are examples
only. Explanations of the accessor macros are provided in the subsections below.

Circuit Data:
ARGS
CALL_TYPE
INIT
ANALYSIS
FIRST_TIMEPOINT
TIME
T(n)
RAD_FREQ
TEMPERATURE
Parameter Data:
PARAM(gain)
PARAM_SIZE(gain)
PARAM_NULL(gain)
Port Data:
PORT_SIZE(a)
PORT_NULL(a)
LOAD(a)
TOTAL_LOAD(a)
Input Data:
INPUT(a)
INPUT_STATE(a)


28.7. MODEL DEFINITION FILE449

INPUT_STRENGTH(a)
Output Data:
OUTPUT(y)
OUTPUT_CHANGED(a)
OUTPUT_DELAY(y)
OUTPUT_STATE(a)
OUTPUT_STRENGTH(a)
Partial Derivatives:
PARTIAL(y,a)
AC Gains:
AC_GAIN(y,a)
Static Variable:
STATIC_VAR(x)

28.7.1.2Circuit Data

ARGS
CALL_TYPE
INIT
ANALYSIS
FIRST_TIMEPOINT
TIME
T(n)
RAD_FREQ
TEMPERATURE

ARGS is a macro which 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 which 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.

INIT is an integer (int) that takes the value 1 or 0 depending on whether this is the f i rst 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
f i rst 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 specif i ed 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.


450CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

RAD_FREQ is a double representing the current analysis frequency in an AC analysis ex-
pressed in units of radians per second.

TEMPERATURE is a double representing the current analysis temperature.

28.7.1.3Parameter Data

PARAM(gain)
PARAM_SIZE(gain)
PARAM_NULL(gain)

PARAM(gain) resolves to the value of the scalar (i.e., non-vector) parameter “gain” which
was def i ned in the Interface Specif i cation File tables. The type of “gain” is the type given
in the ifspec.ifs f i le. The same accessor macro can be used regardless of type. If “gain” is
a string, then PARAM(gain) would resolve to a pointer. PARAM(gain[n]) resolves to the
value of the nth element of a vector parameter “gain”.

PARAM_SIZE(gain) resolves to an integer (int) representing the size of the “gain” vector
(whichwasdynamicallydeterminedwhentheSPICEdeckwasread). PARAM_SIZE(gain)
is undef i ned if gain is a scalar.

PARAM_NULL(gain) resolves to an integer with value 0 or 1 depending on whether a value
was specif i ed for gain, or whether the value is defaulted, respectively.

28.7.1.4Port Data

PORT_SIZE(a)
PORT_NULL(a)
LOAD(a)
TOTAL_LOAD(a)

PORT_SIZE(a) resolves to an integer (int) representing the size of the “a” port (which was
dynamically determined when the SPICE deck was read). PORT_SIZE(a) is undef i ned if
gain is a scalar.

PORT_NULL(a) resolvestoaninteger(int)withvalue0or1dependingonwhethertheSPICE
deck has a node specif i ed for this port, or has specif i ed that the port is null, respectively.

LOAD(a) isusedinadigitalmodeltopostacapacitive loadvalue toaparticular inputoroutput
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 which

TOTAL_LOAD(a) returns a double value which represents the total capacitive load seen on
a specif i ed 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).


28.7. MODEL DEFINITION FILE451

28.7.1.5Input Data

INPUT(a)
INPUT_STATE(a)
INPUT_STRENGTH(a)

INPUT(a) resolves to the value of the scalar input “a” that was def i ned in the Interface Spec-
if i cation File tables (“a” can be either a scalar port or a port value from a vector; in the
latter case, the notation used would be “a[i]”, where “i” is the index value for the port).
The type of “a” is the type given in the ifspec.ifs f i le. The same accessor macro can be
used regardless of type.

INPUT_STATE(a) resolves to the state value def i ned 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 which looks at all outputs to a node
and determines its f i nal 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

28.7.1.6Output Data

OUTPUT(y)
OUTPUT_CHANGED(a)
OUTPUT_DELAY(y)
OUTPUT_STATE(a)
OUTPUT_STRENGTH(a)

OUTPUT(y) resolves to the value of the scalar output “y” that was def i ned in the Interface
Specif i cation File tables. The type of “y” is the type given in the ifspec.ifs f i le. The same
accessor macro can be used regardless of type. If “y” is a vector, then OUTPUT(y) would
resolve to a pointer.

OUTPUT_CHANGED(a) may be assigned one of two values for any particular output from
a digital code model. If assigned the value TRUE (the default), then an output state,
strength 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 subsequently
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 digital or User-Def i ned Node output port. Note that this macro must be set
for each digital or User-Def i ned Node output from a model during each pass, unless the


452CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

OUTPUT_CHANGED(a) macro is invoked (see above). Note also that a non-zero 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.

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

28.7.1.7Partial Derivatives

PARTIAL(y,a)
PARTIAL(y[n],a)
PARTIAL(y,a[m])
PARTIAL(y[n],a[m])

PARTIAL(y,a) 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 def i ned
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
diff i cult 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.

28.7.1.8AC 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) 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”) def i ned in the standard code
model header f i le:

typedef struct Complex_s {
double real; /* The real part of the complex number */
double imag; /* The imaginary part of the complex number */
}Complex_t;


28.7. MODEL DEFINITION FILE453

The remaining uses of AC_GAIN are shown for the cases in which either the output, the input,
or both are vectors.

28.7.1.9Static Variables

STATIC_VAR(x)

STATIC_VAR(x) resolves to an lvalue or a pointer which is assigned the value of some scalar
code model result or state def i ned in the Interface Spec File tables, or a pointer to a value
or a vector of values. The type of “x” is the type given in the Interface Specif i cation
File. The same accessor macro can be used regardless of type since it simply resolves
to an lvalue. If “x” is a vector, then STATIC_VAR(x) would resolve to a pointer. In this
case, the code model is responsible for allocating storage for the vector and assigning the
pointer to the allocated storage to STATIC_VAR(x).

28.7.1.10Accessor Macros

Table28.3describestheaccessormacros availableto the Model Def i nitionFile programmer and
their C types. The PARAM and STATIC_VAR macros, whose types are labeled CD (context
dependent), return the type def i ned in the Interface Specif i cation File. Arguments listed with
“[i]” take an optional square bracket delimited index if the corresponding port or parameter is a
vector. The index may be any C expression - possibly involving calls to other accessor macros
(e.g.,” OUTPUT(out[PORT_SIZE(out)-1])”)

NameTypeArgsDescription
AC_GAINComplex_ty[i],x[i]AC gain of output y with respect to
input x.
ANALYSISenum<none>Type of analysis: DC, AC,
TRANSIENT.
ARGSMif_Private_t<none>Standard argument to all code
model function.
CALL_TYPEenum<none>Type of model evaluation call:
ANALOG or EVENT.
INITBoolean_t<none>Is this the f i rst call to the model?
INPUTdouble or void*name[i]Value of analog input port, or value
of structure pointer for
User-Def i ned Node port.
INPUT_STATEenumname[i]State of a digital input: ZERO,
ONE, or UNKNOWN.
INPUT_STRENGHTenumname[i]Strength of digital input:
STRONG, RESISTIVE, HI
IMPEDANCE, or
UNDETERMINED.
INPUT_TYPEchar*name[i]The port type of the input.
LOADdoublename[i]The digital load value placed on a
port by this model.


454CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

Table 28.3: Accessor macros

MESSAGEchar*name[i]A message output by a model on
an event-driven node.
OUTPUTdouble or void*name[i]Value of the analog output port or
value of structure pointer for
User-Def i ned Node port.
OUTPUT_CHANGEDBoolean_tname[i]Has a new value been assigned to
this event-driven output by the
model?
OUTPUT_DELAYdoublename[i]Delay in seconds for an
event-driven output.
OUTPUT_STATEenumname[i]State of a digital output: ZERO,
ONE, or UNKNOWN.
OUTPUT_STRENGTHenumname[i]Strength of digital output:
STRONG, RESISTIVE,
HI_IMPEDANCE, or
UNDETERMINED.
OUTPUT_TYPEchar*name[i]The port type of the output.
PARAMCDname[i]Value of the parameter.
PARAM_NULLBoolean_tname[i]Was the parameter not included on
the SPICE .model card ?
PARAM_SIZEintnameSize of parameter vector.
PARTIALdoubley[i],x[i]Partial derivative of output y with
respect to input x.
PORT_NULLMif_Boolean_tnameHas this port been specif i ed as
unconnected?
PORT_SIZEintnameSize of port vector.
RAD_FREQdouble<none>Current analysis frequency in
radians per second.
STATIC_VARCDnameValue of a static variable.
STATIC_VAR_SIZEintnameSize of static var vector (currently
unused).
T(n)intindexCurrent and previous analysis
times (T(0) = TIME = current
analysis time, T(1) = previous
analysis time).
TEMPERATUREdouble<none>Current analysis temperature.
TIMEdouble<none>Current analysis time (same as
T(0)).
TOTAL_LOADdoublename[i]The total of all loads on the node
attached to this event driven port.


28.7. MODEL DEFINITION FILE455

28.7.2Function Library

28.7.2.1Overview

Aside from the accessor macros, the simulator also provides a library of functions callable from
within code models. The header f i le containing prototypes to these functions is automatically
inserted into the Model Def i nition File for you. The complete list of available functions follows:

Smoothing Functions:
void cm_smooth_corner
void cm_smooth_discontinuity
double cm_smooth_pwl
Model State Storage Functions:
void cm_analog_alloc
void cm_event_alloc
void *cm_analog_get_ptr
void *cm_event_get_ptr
Integration and Convergence Functions:
int cm_analog_integrate
int cm_analog_converge
void cm_analog_not_converged
void cm_analog_auto_partial
double cm_analog_ramp_factor
Message Handling Functions:
char *cm_message_get_errmsg
void cm_message_send
Breakpoint Handling Functions:
int cm_analog_set_temp_bkpt
int cm_analog_set_perm_bkpt
int cm_event_queue
Special Purpose Functions:
void cm_climit_fcn
double cm_netlist_get_c
double cm_netlist_get_l
char *cm_get_path
Complex Math Functions:
complex_t cm_complex_set
complex_t cm_complex_add
complex_t cm_complex_sub
complex_t cm_complex_mult
complex_t cm_complex_div

28.7.2.2Smoothing Functions

void
cm_smooth_corner(x_input, x_center, y_center, domain,
lower_slope, upper_slope, y_output, dy_dx)


456CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

double x_input;/* The value of the x input */
double x_center;/* The x intercept of the two slopes */
double y_center;/* The y intercept of the two slopes */
double domain;/* The smoothing domain */
double lower_slope; /* The lower slope */
double upper_slope; /* The upper slope */
double *y_output;/* The smoothed y output */
double *dy_dx;/* The partial of y wrt x */

void
cm_smooth_discontinuity(x_input, x_lower, y_lower, x_upper, y_upper
y_output, dy_dx)

double x_input;/* The x value at which to compute y */
double x_lower;/* The x value of the lower corner */
double y_lower;/* The y value of the lower corner */
double x_upper;/* The x value of the upper corner */
double y_upper;/* The y value of the upper corner */
double *y_output; /* The computed smoothed y value */
double *dy_dx;/* The partial of y wrt x */

double
cm_smooth_pwl(x_input, x, y, size, input_domain, dout_din)

double x_input;/* The x input value */
double *x;/* The vector of x values */
double *y;/* The vector of y values */
int size;/* The size of the xy vectors */
double input_domain; /* The smoothing domain */
double *dout_din;/* The partial of the output wrt the input */

cm_smooth_corner() automates smoothing between two arbitrarily-sloped lines that meet at a
single center point. You specify the center point (x_center, y_center), plus a domain (x-valued
delta) above and below x_center. This def i nes a smoothing region about the center point. Then,
the slopes of the meeting lines outside of this smoothing region are specif i ed (lower_slope,
upper_slope). The function then interpolates a smoothly-varying output (*y_output) and its
derivative (*dy_dx) for the x_input value. This function helps to automate the smoothing of
piecewise-linear functions, for example. Such smoothing aids the simulator in achieving con-
vergence.

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 predef i ned 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.


28.7. MODEL DEFINITION FILE457

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.

28.7.2.3Model State Storage Functions

void cm_analog_alloc(tag, size)

int tag;/* The user-specified tag for this block of memory */
int size; /* The number of bytes to allocate */

void cm_event_alloc(tag, size)

int tag; /* The user-specified tag for the memory block */
int size; /* The number of bytes to be allocated */

void *cm_analog_get_ptr(tag, timepoint)

int tag; /* The user-specified tag for this block of memory */
int timepoint; /* The timepoint of interest - 0=current 1=previous */

void *cm_event_get_ptr(tag, timepoint)

int tag; /* The user-specified tag for the memory block */
int timepoint; /* The timepoint - 0=current, 1=previous */

cm_analog_alloc() and cm_event_alloc() allow you to allocate storage space for analog and
event-driven model state information. The storage space is not static, but rather represents a
storage vector of two values which rotate with each accepted simulator time-point evaluation.
This is explained more fully below. The “tag” parameter allows you to specify an integer tag
when allocating space. This allows more than one rotational storage location per model to be
allocated. The “size” parameter specif i es the size in bytes of the storage (computed by the C
language “sizeof()” operator). Both cm_analog_alloc() and cm_event_alloc() will not return
pointers to the allocated space, as has been available (and buggy) from the original XSPICE
code. cm_analog_alloc() should be used by an analog model; cm_event_alloc() should be used
by an event-driven model.

*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 no-
tice: Thesefunctionsmustbecalledonlyafterallmemoryallocation(allcallstocm_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 which specif i es 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 stor-
age 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 itera-
tion, 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 = 0” storage location.
Thus, if a value does not change for a particular iteration, specif i c writing to “timepoint = 0”


458CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

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.

28.7.2.4Integration and Convergence Functions

int cm_analog_integrate(integrand, integral, partial)

double integrand; /* The integrand */
double *integral; /* The current and returned value of integral */
double *partial;/* The partial derivative of integral wrt integrand */

int cm_analog_converge(state)

double *state; /* The state to be converged */

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 be-
cause 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 conver-
gence. 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 re-
turns without calling the cm_analog_not_converged() function. For circuits which 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 calcu-
lating 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 automat-
ically 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 be-
come very complex and error-prone for some models. However, the automatic evaluation may
also increase simulation run time signif i cantly. 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 par-
tial derivatives of the outputs with respect to the inputs are then approximated by the simulator
through divided difference calculations.


28.7. MODEL DEFINITION FILE459

cm_analog_ramp_factor() will then return a value from 0.0 to 1.0, which indicates whether
or not a ramp time value requested in the SPICE analysis deck (with the use of .option ramp-
time=<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 which 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
which would ordinarily experience a “power-up” transition. Currently, all sources within the
simulator are automatically ramped to the "f i nal" time-zero value if a RAMPTIME option is
specif i ed.

28.7.2.5Message Handling Functions

char *cm_message_get_errmsg()
int cm_message_send(char *msg)
char *msg; /* The message to output. */

*cm_message_get_errmsg() is a function designed to be used with other library functions to
provide a way for models to handle error situations. More specif i cally, whenever a library func-
tion which returns type “int” is executed from a model, it will return an integer value, n. If this
value is not equal to zero (0), then an error condition has occurred (likewise, functions which
return pointers will return a NULL value if an error has occurred). At that point, the model can
invoke *cm_message_get_errmsg to obtain a pointer to an error message. This can then in turn
be displayed to the user or passed to the simulator interface through the cm_message_send()
function. The C code required for this is as follows:

err = cm_analog_integrate(in, &out, &dout_din);
if (err) {
cm_message_send(cm_message_get_errmsg());
}
else { ...

cm_message_send() sends messages to either the standard output screen or to the simulator
interface, depending on which is in use.

28.7.2.6Breakpoint Handling Functions

int cm_analog_set_perm_bkpt(time)

double time; /* The time of the breakpoint to be set */

int cm_analog_set_temp_bkpt(time)

double time; /* The time of the breakpoint to be set */

int cm_event_queue(time)

double time; /* The time of the event to be queued */


460CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

cm_analog_set_perm_bkpt() takes as input a time value. This value is posted to the analog
simulator algorithm and is used to force the simulator to choose that value as a breakpoint at
some time in the future. The simulator may choose as the next time-point a value less than the
input, but not greater. Also, regardless of how many time-points pass before the breakpoint is
reached, it will not be removed from posting. Thus, a breakpoint is guaranteed at the passed
time value. 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)).

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 f i rst 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)).

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 specif i ed
time. All other details applicable to cm_analog_set_perm_bkpt() apply to this function as well.

28.7.2.7Special Purpose Functions

void
cm_climit_fcn(in, in_offset, cntl_upper, cntl_lower, lower_delta, upper_delta,
limit_range, gain, fraction, out_final, pout_pin_final,
pout_pcntl_lower_final, pout_pcntl_upper_final)

double in;/* The input value */
double in-offset;/* The input offset */
double cntl_upper;/* The upper control input value */
double cntl_lower;/* The lower control input value */
double lower_delta; /* The delta from control to limit value */
double upper_delta; /* The delta from control to limit value */
double limit_range; /* The limiting range */
double gain;/* The gain from input to output */
int percent;/* The fraction vs. absolute range flag */
double *out_final;/* The output value */
double *pout_pin_final; /* The partial of output wrt input */
double *pout_pcntl_lower_final; /* The partial of output wrt lower
control input */
double *pout_pcntl_upper:final; /* The partial of output wrt upper
control input */

double cm_netlist_get_c()

double cm_netlist_get_l()
char* cm_get_path()


28.7. MODEL DEFINITION FILE461

cm_climit_fcn() is a very specif i c function that mimics the behavior of the climit code model
(see the Predef i ned 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 f i nal 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.

Thefunctionperformsalimitonthe“in”value, holdingittowithinsomedeltaofthecontrolling
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 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 which has only one
single-ended analog input port.

char* cm_get_path() fetches the path of the f i rst netlist input f i le found on the ngspice com-
mand line or in the ’source’ command, which ngspice saves to the global variable Inf i le_Path.

28.7.2.8Complex Math Functions

Complex_t cm_complex_set (real_part, imag_part)

double real_part; /* The real part of the complex number */
double imag_part; /* The imaginary part of the complex number */

Complex_t cm_complex_add (x, y)

Complex_t x; /* The first operand of x + y */
Complex_t y; /* The second operand of x + y */

Complex_t cm_complex_sub (x, y)

Complex_t x; /* The first operand of x - y */
Complex_t y; /* The second operand of x - y */

Complex_t cm_complex_mult (x, y)

Complex_t x; /* The first operand of x * y */
Complex_t y; /* The second operand of x * y */

Complex_t cm_complex_div (x, y)

Complex_t x; /* The first operand of x / y */
Complex_t y; /* The second operand of x / y */

cm_complex_set() takes as input two doubles, and converts these to a Complex_t. The f i rst
double is taken as the real part, and the second is taken as the imaginary part of the resulting


462CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

complex value.

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.

28.8User-Def i ned Node Def i nition File

The User-Def i ned Node Def i nition File (udnfunc.c) def i nes the C functions which implement
basic operations on user-def i ned nodes such as data structure creation, initialization, copying,
and comparison. Unlike the Model Def i nition File which uses the Code Model Preprocessor to
translate Accessor Macros, the User-Def i ned Node Def i nition f i le is a pure C language f i le. This
f i le uses macros to isolate you from data structure def i nitions, but the macros are def i ned in a
standard header f i le (EVTudn.h), and translations are performed by the standard C Preprocessor.

WhenyoucreateadirectoryforanewUser-Def i nedNode, e.g. /ngspice/src/xspice/icm/xtraevt/new_type/,
add a new User-Def i ned Node Def i nition 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 def i ne 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. USER-DEFINED NODE DEFINITION FILE463

28.8.1Macros

NameTypeDescription
MALLOCED_PTRvoid *Assign pointer to allocated structure
to this macro
STRUCT_PTRvoid *A pointer to a structure of the def i ned
type
STRUCT_PTR_1void *A pointer to a structure of the def i ned
type
STRUCT_PTR_2void *A pointer to a structure of the def i ned
type
EQUALMif_Boolean_tAssign TRUE or FALSE to this macro
according to the results of structure
comparison
INPUT_STRUCT_PTRvoid *A pointer to a structure of the def i ned
type
OUTPUT_STRUCT_PTRvoid *A pointer to a structure of the def i ned
type
INPUT_STRUCT_PTR_ARRAYvoid **An array of pointers to structures of
the def i ned type
INPUT_STRUCT_PTR_ARRAY_SIZEintThe size of the array
STRUCT_MEMBER_IDchar *A string naming some part of the
structure
PLOT_VALdoubleThe value of the specif i ed structure
member for plotting purposes
PRINT_VALchar *The value of the specif i ed structure
member for printing purposes

Table 28.4: User-Def i ned 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 def i ned 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-Def i ned Node Def i nition File to access and assign data values
are def i ned in Table 28.4. The translations of the macros and of macros used in the function
argument lists are def i ned in the Interface Diesign Document for the XSPICE Simulator.

28.8.2Function Library

The functions (required and optional) that def i ne a User-Def i ned Node are listed below. For
optional functions not used, the pointer in the Evt_Udn_Info_t structure can be changed to
NULL.

Required functions:


464CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

createAllocate data structure used as inputs and outputs to
code models.

initializeSet structure to appropriate initial value for first use as
model input.

copyMake a copy of the contents into created but possibly
uninitialized structure.

compareDetermine if two structures are equal in value.

Optional functions:

dismantleFree allocations inside structure (but not structure itself).

invertInvert logical value of structure.

resolveDetermine the resultant when multiple outputs are connected
to a node.

plot_valOutput a real value for specified structure component for
plotting purposes.

print_valOutput a string value for specified structure component for
printing.

ipc_valOutput a binary representation of the structure suitable
for sending over the IPC channel.

The required actions for each of these functions are described in the following subsections. In
each function, you have to replace the XXX with the node type name specif i ed. The macros
used in implementing the functions are described in a later section.

28.8.2.1Function udn_XXX_create

Allocate space for the data structure def i ned for the User-Def i ned Node to pass data between
models. Thenassignpointercreatedbythestorageallocator(e.g. malloc)toMALLOCED_PTR.

28.8.2.2Function udn_XXX_initialize

Assign STRUCT_PTR to a pointer variable of def i ned type and then initialize the value of the
structure.


28.8. USER-DEFINED NODE DEFINITION FILE465

28.8.2.3Function udn_XXX_compare

Assign STRUCT_PTR_1 and STRUCT_PTR_2 to pointer variables of the def i ned type. Com-
pare the two structures and assign either TRUE or FALSE to EQUAL.

28.8.2.4Function udn_XXX_copy

Assign INPUT_STRUCT_PTR and OUTPUT_STRUCT_PTR to pointer variables of the de-
f i ned type and then copy the elements of the input structure to the output structure.

28.8.2.5Function udn_XXX_dismantle

Assign STRUCT_PTR to a pointer variable of def i ned type and then free any allocated sub-
structures (but not the structure itself!). If there are no substructures, the body of this function
may be left null.

28.8.2.6Function udn_XXX_invert

Assign STRUCT_PTR to a pointer variable of the def i ned type, and then invert the logical value
of the structure.

28.8.2.7Function udn_XXX_resolve

Assign INPUT_STRUCT_PTR_ARRAY to a variable declared as an array of pointers of the
def i ned type - e.g.:

<type> **struct_array;
struct_array = INPUT_STRUCT_PTR_ARRAY;

Then, the number of elements in the array may be determined from the integer valued IN-
PUT_STRUCT_PTR_ARRAY_SIZE macro.

Assign OUTPUT_STRUCT_PTR to a pointer variable of the def i ned type. Scan through the
array of structures, compute the resolved value, and assign it into the output structure.

28.8.2.8Function udn_XXX_plot_val

Assign STRUCT_PTR to a pointer variable of the def i ned type. Then, access the member of
the structure specif i ed by the string in STRUCT_MEMBER_ID and assign some real valued
quantity for this member to PLOT_VALUE.

28.8.2.9Function udn_XXX_print_val

Assign STRUCT_PTR to a pointer variable of the def i ned type. Then, access the member of
the structure specif i ed by the string in STRUCT_MEMBER_ID and assign some string valued
quantity for this member to PRINT_VALUE.

If the string is not static, a new string should be allocated on each call. Do not free the allocated
strings.


466CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

28.8.2.10Function udn_XXX_ipc_val

Use STRUCT_PTR to access the value of the node data. Assign to IPC_VAL a binary repre-
sentation of the data. Typically this can be accomplished by simply assigning STRUCT_PTR
to IPC_VAL.

Assign to IPC_VAL_SIZE an integer representing the size of the binary data in bytes.

28.8.3Example UDN Def i nition File

The following is an example UDN Def i nition File which is included with the XSPICE system. It
illustratesthedef i nitionofthefunctionsdescribedaboveforaUser-Def i nedNodetype“int”(for
“integer”nodetype), tobefoundinf i le/ngspice/src/xspice/icm/xtraevt/int/udnfunc.c.

#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))

/* macro to ignore unused variables and parameters */
#define NG_IGNORE(x)(void)x

/* ************************************************* */

static void udn_int_create(CREATE_ARGS)
{
/* Malloc space for an int */
MALLOCED_PTR = TMALLOC(int, 1);
}

/* ************************************************* */

static void udn_int_dismantle(DISMANTLE_ARGS)
{
NG_IGNORE(STRUCT_PTR);
/* Do nothing.There are no internally malloc ’ed
things to dismantle */
}

/* ************************************************* */

static void udn_int_initialize(INITIALIZE_ARGS)
{
int*int_struct = (int *) STRUCT_PTR;

/* Initialize to zero */


28.8. USER-DEFINED NODE DEFINITION FILE467

*int_struct = 0;
}

/* ************************************************* */

static void udn_int_invert(INVERT_ARGS)
{
int*int_struct = (int *) STRUCT_PTR;

/* Invert the state */
*int_struct = -(*int_struct);
}

/* ************************************************* */

static void udn_int_copy(COPY_ARGS)
{
int*int_from_struct = (int *) INPUT_STRUCT_PTR;
int*int_to_struct= (int *) OUTPUT_STRUCT_PTR;

/* Copy the structure */
*int_to_struct = *int_from_struct;
}

/* ************************************************* */

static void udn_int_resolve(RESOLVE_ARGS)
{
int **array= (int**)INPUT_STRUCT_PTR_ARRAY;
int *out= (int *) OUTPUT_STRUCT_PTR;
int num_struct = INPUT_STRUCT_PTR_ARRAY_SIZE;

intsum;
inti;

/* Sum the values */
for(i = 0, sum = 0; i < num_struct; i++)
sum += *(array[i]);

/* Assign the result */
*out = sum;
}

/* ************************************************* */

static void udn_int_compare(COMPARE_ARGS)
{
int*int_struct1 = (int *) STRUCT_PTR_1;


468CHAPTER 28. CODE MODELS AND USER-DEFINED NODES

int*int_struct2 = (int *) STRUCT_PTR_2;

/* Compare the structures */
if((*int_struct1) == (*int_struct2))
EQUAL = TRUE;
else
EQUAL = FALSE;
}

/* ************************************************* */

static void udn_int_plot_val(PLOT_VAL_ARGS)
{
int*int_struct = (int *) STRUCT_PTR;
NG_IGNORE(STRUCT_MEMBER_ID);

/* Output a value for the int struct */
PLOT_VAL = *int_struct;
}

/* ************************************************* */

static void udn_int_print_val(PRINT_VAL_ARGS)
{
int*int_struct = (int *) STRUCT_PTR;
NG_IGNORE(STRUCT_MEMBER_ID);

/* Allocate space for the printed value */
PRINT_VAL = TMALLOC(char, 30);

/* Print the value into the string */
sprintf(PRINT_VAL , "%8d", *int_struct);
}

/* ************************************************* */

static void udn_int_ipc_val(IPC_VAL_ARGS)
{
/* Simply return the structure and its size */
IPC_VAL = STRUCT_PTR;
IPC_VAL_SIZE = sizeof(int);
}

Evt_Udn_Info_tudn_int_info = {
"int",
"integer valued data",

udn_int_create ,


28.8. USER-DEFINED NODE DEFINITION FILE469

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
};


470CHAPTER 28. CODE MODELS AND USER-DEFINED NODES


Chapter 29

Error Messages

Error messages may be subdivided into three categories. These are:

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 Mes-
sages).

3. Error messages generated by individual code models (Code Model Error Messages).

These messages will be explained in detail in the following subsections.

29.1Preprocessor Error Messages

The following is a list of error messages that may be encountered when invoking the directory-
creation and code modeling preprocessor tools. These are listed individually, and explanations
follow the name/listing.

Usage: cmpp [-ifs] [-mod [<filename>]] [-lst]

The Code Model Preprocessor (cmpp) command was invoked incorrectly.

ERROR - Too few arguments

The Code Model Preprocessor (cmpp) command was invoked with too few arguments.

ERROR - Too many arguments

The Code Model Preprocessor (cmpp) command was invoked with too many arguments.

ERROR - Unrecognized argument

471


472CHAPTER 29. ERROR MESSAGES

The Code Model Preprocessor (cmpp) command was invoked with an invalid argument.

ERROR - File not found: s<filename>

The specif i ed f i le was not found, or could not be opened for read access.

ERROR - Line <line number> of <filename> exceeds XX characters

The specif i ed line was too long.

ERROR - Pathname on line <line number> of <filename>
exceeds XX characters.

The specif i ed line was too long.

ERROR - No pathnames found in file: <filename>

The indicated modpath.lst f i le does not have pathnames properly listed.

ERROR - Problems reading ifspec.ifs in directory <pathname>

The Interface Specif i cation File (ifspec.ifs) for the code model could not be read.

ERROR - Model name <model name> is same as internal SPICE model name

A model has been given the same name as an intrinsic SPICE device.

ERROR - Model name ’<model name>’ in directory: <pathname>
is same as
model name ’<model name>’ in directory: <pathname>

Two models in different directories have the same name.

ERROR - C function name ’<function name>’ in directory: <pathname>,
is same as
C function name ’<function name>’ in directory: <pathname>

Two C language functions in separate model directories have the same names; these would
cause a collision when linking the f i nal executable.

ERROR - Problems opening CMextrn.h for write


29.1. PREPROCESSOR ERROR MESSAGES473

The temporary f i le CMextern.h used in building the XSPICE simulator executable could not be
created or opened. Check permissions on directory.

ERROR - Problems opening CMinfo.h for write

The temporary f i le CMinfo.h used in building the XSPICE simulator executable could not be
created or opened. Check permissions on directory.

ERROR - Problems opening objects.inc file for write

The temporary f i le objects.inc used in building the XSPICE simulator executable could not be
created or opened. Check permissions on directory.

ERROR - Could not open input .mod file: <filename>

The Model Def i nition File that contains the def i nition of the Code Model’s behavior (usually
cfunc.mod) was not found or could not be read.

ERROR - Could not open output .c: <filename>

The indicated C language f i le that the preprocessor creates could not be created or opened.
Check permissions on directory.

Error parsing .mod file: <filename>

Problems were encountered by the preprocessor in interpreting the indicated Model Def i nition
File.

ERROR - File not found: <filename>

The indicated f i le was not found or could not be opened.

Error parsing interface specification file

Problems were encountered by the preprocessor in interpreting the indicated Interface Specif i -
cation File.

ERROR - Can’t create file: <filename>

The indicated f i le could not be created or opened. Check permissions on directory.

ERROR - write.port.info() - Number of allowed types cannot be zero

There must be at least one port type specif i ed in the list of allowed types.


474CHAPTER 29. ERROR MESSAGES

illegal quoted character in string (expected "\" or "\\")

A string was found with an illegal quoted character in it.

unterminated string literal

A string was found that was not terminated.

Unterminated comment

A comment was found that was not terminated.

Port ’<port name>’ not found

The indicated port name was not found in the Interface Specif i cation File.

Port type ’vnam’ is only valid for ’in’ ports

The port type ‘vnam’ was used for a port with direction ‘out’ or ‘inout’. This type is only
allowed on ‘in’ ports.

Port types ’g’, ’gd’, ’h’, ’hd’ are only valid for ’inout’ ports

Port type ‘g’, ‘gd’, ‘h’, or ‘hd’ was used for a port with direction ‘out’ or ‘in’. These types are
only allowed on ‘inout’ ports.

Invalid parameter type - POINTER type valid only for STATIC_VARs

The type POINTER was used in a section of the Interface Specif i cation f i le other than the
STATIC_VAR section.

Port default type is not an allowed type

A default type was specif i ed that is not one of the allowed types for the port.

Incompatible port types in ‘allowed_types’ clause

Port types listed under ‘Allowed_Types’ in the Interface Specif i cation File must all have the
same underlying data type. It is illegal to mix analog and eventdriven types in a list of allowed
types.

Invalid parameter type (saw <parameter type 1> - expected <parameter type 2>)


29.1. PREPROCESSOR ERROR MESSAGES475

A parameter value was not compatible with the specif i ed type for the parameter.

Named range not allowed for limits

A name was found where numeric limits were expected.

Direction of port ’<port number>’ in <port name>()
is not <IN or OUT> or INOUT

A problem exists with the direction of one of the elements of a port vector.

Port ’<port name>’ is an array - subscript required

A port was referenced that is specif i ed as an array (vector) in the Interface Specif i cation File. A
subscript is required (e.g. myport[i])

Parameter ’<parameter name>’ is an array - subscript required

A parameter was referenced that is specif i ed as an array (vector) in the Interface Specif i cation
File. A subscript is required (e.g. myparam[i])

Port ’<port name>’ is not an array - subscript prohibited

A port was referenced that is not specif i ed as an array (vector) in the Interface Specif i cation
File. A subscript is not allowed.

Parameter ’<parameter name>’ is not an array - subscript prohibited

A parameter was referenced that is not specif i ed as an array (vector) in the Interface Specif i ca-
tion File. A subscript is not allowed.

Static variable ’<static variable name>’ is not an array - subscript prohibited

Array static variables are not supported. Use a POINTER type for the static variable.

Buffer overflow - try reducing the complexity of CM-macro array subscripts

The argument to a code model accessor macro was too long.

Unmatched )

An open ( was found with no corresponding closing ).

Unmatched ]

An open [ was found with no corresponding closing ].


476CHAPTER 29. ERROR MESSAGES

29.2Simulator Error Messages

The following is a list of error messages that may be encountered while attempting to run a
simulation (with the exception of those error messages generated by individual code models).
Most of these errors are generated by the simulator while attempting to parse a SPICE deck.
These are listed individually, and explanations follow the name/listing.

ERROR - Scalar port expected, [ found

A scalar connection was expected for a particular port on the code model, but the symbol [
which is used to begin a vector connection list was found.

ERROR - Unexpected ]

A ] was found where not expected. Most likely caused by a missing [.

ERROR - Unexpected [ - Arrays of arrays not allowed

A [ character was found within an array list already begun with another [ character.

ERROR - Tilde not allowed on analog nodes

The tilde character ~ was found on an analog connection. This symbol, which performs state
inversion, is only allowed on digital nodes and on User-Def i ned Nodes only if the node type
def i nition allows it.

ERROR - Not enough ports

An insuff i cient number of node connections was supplied on the instance line. Check the Inter-
face Specif i cation File for the model to determine the required connections and their types.

ERROR - Expected node/instance identifier

A special token (e.g. [ ] < > ...) was found when not expected.

ERROR - Expected node identifier

A special token (e.g. [ ] < > ...) was found when not expected.

ERROR - unable to find definition of model <name>

A .model line for the referenced model was not found.

ERROR - model: %s - Array parameter expected - No array delimiter found


29.3. CODE MODEL ERROR MESSAGES477

An array (vector) parameter was expected on the .model card, but enclosing [ ] characters were
not found to delimit its values.

ERROR - model: %s - Unexpected end of model card

The end of the indicated .model line was reached before all required information was supplied.

ERROR - model: %s - Array parameter must have at least one value

An array parameter was encountered that had no values.

ERROR - model: %s - Bad boolean value

A bad values was supplied for a Boolean. Value used must be TRUE, FALSE, T, or F.

ERROR - model: %s - Bad integer, octal, or hex value

A badly formed integer value was found.

ERROR - model: %s - Bad real value

A badly formed real value was found.

ERROR - model: %s - Bad complex value

A badly formed complex number was found. Complex numbers must be enclosed in < > delim-
iters.

29.3Code Model Error Messages

The following is a list of error messages that may be encountered while attempting to run a
simulation with certain code models. These are listed alphabetically based on the name of the
code model, and explanations follow the name and listing.

29.3.1Code Model aswitch

cntl_error:
*****ERROR*****
ASWITCH: CONTROL voltage delta less than 1.0e-12

This message occurs as a result of the cntl_off and cntl_on values being less than 1.0e-12 volt-
s/amperes apart.


478CHAPTER 29. ERROR MESSAGES

29.3.2Code Model climit

climit_range_error:
**** ERROR ****
* CLIMIT function linear range less than zero. *

This message occurs whenever the difference between the upper and lower control input values
are close enough that there is no effective room for proper limiting to occur; this indicates an
error in the control input values.

29.3.3Code Model core

allocation_error:
***ERROR***
CORE: Allocation calloc failed!

This message is a generic message related to allocating suff i cient storage for the H and B array
values.

limit_error:
***ERROR***
CORE: Violation of 50% rule in breakpoints!

This message occurs whenever the input domain value is an absolute value and the H coordinate
points are spaced too closely together (overlap of the smoothing regions will occur unless the
H values are redef i ned).

29.3.4Code Model d_osc

d_osc_allocation_error:
**** Error ****
D_OSC: Error allocating VCO block storage

Generic block storage allocation error.

d_osc_array_error:
**** Error ****
D_OSC: Size of control array different than frequency array

Error occurs when there is a different number of control array members than frequency array
members.

d_osc_negative_freq_error:
**** Error ****
D_OSC: The extrapolated value for frequency
has been found to be negative...
Lower frequency level has been clamped to 0.0 Hz.

Occurs whenever a control voltage is input to a model which would ordinarily (given the speci-
f i ed control/freq coordinate points) cause that model to attempt to generate an output oscillating
at zero frequency. In this case, the output will be clamped to some DC value until the control
voltage returns to a more reasonable value.


29.3. CODE MODEL ERROR MESSAGES479

29.3.5Code Model d_source

loading_error:
***ERROR***
D_SOURCE: source.txt file was not read successfully.

This message occurs whenever the d source model has experienced any diff i culty in loading the
source.txt (or user-specif i ed) f i le. This will occur with any of the following problems:

• Width of a vector line of the source f i le is incorrect.

• A time-point value is duplicated or is otherwise not monotonically increasing.

• One of the output values was not a valid 12-State value (0s, 1s, Us, 0r, 1r, Ur, 0z, 1z, Uz,
0u, 1u, Uu).

29.3.6Code Model d_state

loading_error:
***ERROR***
D_STATE: state.in file was not read successfully.
The most common cause of this problem is a trailing
blank line in the state.in file

This error occurs when the state.in f i le (or user-named state machine input f i le) has not been
read successfully. This is due to one of the following:

• The counted number of tokens in one of the f i le’s input lines does not equal that required
to def i ne 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 def i ned using a symbol which 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 def i ned using a symbol which 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 def i nitions in the input f i le being non-contiguous. In
general, it will refer to the different states not being def i ned uniquely, or being “broken up” in
some fashion within the state.in f i le.


480CHAPTER 29. ERROR MESSAGES

29.3.7Code Model oneshot

oneshot_allocation_error:
**** Error ****
ONESHOT: Error allocating oneshot block storage

Generic storage allocation error.

oneshot_array_error:
**** Error ****
ONESHOT: Size of control array different than pulse-width array

This error indicates that the control array and pulse-width arrays are of different sizes.

oneshot_pw_clamp:
**** Warning ****
ONESHOT: Extrapolated Pulse-Width Limited to zero

This error indicates that for the current control input, a pulse-width of less than zero is indicated.
The model will consequently limit the pulse width to zero until the control input returns to a
more reasonable value.

29.3.8Code Model pwl

allocation_error:
***ERROR***
PWL: Allocation calloc failed!

Generic storage allocation error.

limit_error:
***ERROR***
PWL: Violation of 50% rule in breakpoints!

This error message indicates that the pwl model has an absolute value for its input domain, and
that the x_array coordinates are so close together that the required smoothing regions would
overlap. To f i x the problem, you can either spread the x_array coordinates out or make the input
domain value smaller.

29.3.9Code Model s_xfer

num_size_error:
***ERROR***
S_XFER: Numerator coefficient array size greater than
denominator coefficient array size.

This error message indicates that the order of the numerator polynomial specif i ed is greater
than that of the denominator. For the s_xfer model, the orders of numerator and denominator
polynomials must be equal, or the order of the denominator polynomial must be greater than
that or the numerator.


29.3. CODE MODEL ERROR MESSAGES481

29.3.10Code Model sine

allocation_error:
**** Error ****
SINE: Error allocating sine block storage

Generic storage allocation error.

sine_freq_clamp:
**** Warning ****
SINE: Extrapolated frequency limited to 1e-16 Hz

This error occurs whenever the controlling input value is such that the output frequency ordi-
narily would be set to a negative value. Consequently, the output frequency has been clamped
to a near-zero value.

array_error:
**** Error ****
SINE: Size of control array different than frequency array

This error message normally occurs whenever the controlling input array and the frequency
array are different sizes.

29.3.11Code Model square

square_allocation_error:
**** Error ****
SQUARE: Error allocating square block storage

Generic storage allocation error.

square_freq_clamp:
**** WARNING ****
SQUARE: Frequency extrapolation limited to 1e-16

This error occurs whenever the controlling input value is such that the output frequency ordi-
narily would be set to a negative value. Consequently, the output frequency has been clamped
to a near-zero value.

square_array_error:
**** Error ****
SQUARE: Size of control array different than frequency array

This error message normally occurs whenever the controlling input array and the frequency
array are different sizes.


482CHAPTER 29. ERROR MESSAGES

29.3.12Code Model triangle

triangle_allocation_error:
**** Error ****
TRIANGLE: Error allocating triangle block storage

Generic storage allocation error.

triangle_freq_clamp:
**** Warning ****
TRIANGLE: Extrapolated Minimum Frequency Set to 1e-16 Hz

This error occurs whenever the controlling input value is such that the output frequency ordi-
narily would be set to a negative value. Consequently, the output frequency has been clamped
to a near-zero value.

triangle_array_error:
**** Error ****
TRIANGLE: Size of control array different than frequency array

This error message normally occurs whenever the controlling input array and the frequency
array are different sizes.


Part III

CIDER

483



Chapter 30

CIDER User’s Manual

The CIDER User’s Manual that follows is derived from the original manual being part of the
PhD thesis from David A. Gates from UC Berkeley. Unfortunately the manual here is not yet
complete, so please refer to the thesis for detailed information. Literature on CODECS, the
predecessor of CIDER, is available here from UCB: TechRpt ERL-90-96 and TechRpt ERL-
88-71.

30.1SPECIFICATION

Overview of numerical-device specif i cation

The input to CIDER consists of a SPICE-like description of a circuit, its analyses and its com-
pact 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].

To simulate devices numerically, two types of input must be added to the input f i le. The f i rst
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 prof i le. 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-specif i c 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-specif i cation cards), their order in the input f i le can be important in determining
the device structure.

Each card begins on a separate line of the input f i le. 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 f i t 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.

485


486CHAPTER 30. CIDER USER’S MANUAL

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 con-
tinuation “+”. 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 def i nitions. 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
nameabbreviationscanalsobeusediftheyareuniqueinthelistofacard’sparameters. 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 f i le names in the input description and these names may contain capital letters. If
the f i le 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 f i nal 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 which 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.1These 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.1Examples

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 descrip-
tion:

1Some of the possibilities are not listed in order to shorten the lengths of the parameter tables. This makes

the use of parameter abbreviations somewhat troublesome since an unlisted parameter may abbreviate to the same
name as one that is listed. CIDER will produce a warning when this occurs. Many of the undocumented parameter
names are the PISCES names for the same parameters. The adventurous soul can discover these names by delving
through the “cards” directory of the source code distribution looking for the C parameter tables.


30.2. BOUNDARY, INTERFACE487

Example: Numerical diode

.MODEL M_NUMERICAL NUPD LEVEL=2
+ cardnamelnumberl=val1( number2val2 ) ,( number3 = val3 )
+ cardname2numberl=val1string1 = name1
+
+ cardname3numberl=val1 ,flag1 ,^ flag2
+ + number2=val2 ,flag3

The element line for an instance of this model might look something like the following. Double
quotes are used to protect the f i le name from decapitalization:

dl 1 2 M_NUMERICAL area=lOOpm^2ic . f i l e= " diode . IC"

30.2BOUNDARY, INTERFACE

Specify properties of a domain boundary or the interface between two boundaries

SYNOPSIS

boundary domain[ bounding−box ][ properties ]
interfacedomainneighbor[ bounding−box ][ properties ]

30.2.1DESCRIPTION

The boundary and interface cards are used to set surface physics parameters along the boundary
of a specif i ed 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 specif i ed, 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 specif i ed, 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 specif i ed f i rst in the input f i le.
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 specif i ed in terms of its location or its mesh-index in the
relevant dimension, or defaulted to the respective boundary of the simulation mesh.


488CHAPTER 30. CIDER USER’S MANUAL

30.2.2PARAMETERS

NameTypeDescriptionUnits
DomainIntegerID number of primary domain
NeighborIntegerID number of neighboring domain
X.LowRealLowest X location of bounding boxµm
: IX.LowIntegerLowest X mesh-index of bounding box
X.HighRealHighest X location of bounding boxµm
: IX.HighIntegerHighest X mesh-index of bounding box
Y.LowRealLowest Y location of bounding boxµm
: IY.LowIntegerLowest Y mesh-index of bounding box
Y.HighRealHighest Y location of bounding boxµm
:IY.HighIntegerHighest Y mesh-index of bounding box
QfRealFixed interface charge

C/cm2
SNRealSurface recombination velocity - electrons

cm/s
SPRealSurface recombination velocity - holes

cm/s
Layer.WidthRealWidth of surface layerµm

30.2.3EXAMPLES

The following shows how the surface recombination velocities at an Si-SiO2 interface might be
set:

interface dom=lneigh=2 sn=l . Oe4 sp=l . Oe4

In a MOSFET with a 2.0µm gate width and 0.1µm source and drain overlap, the surface channel
can be restricted to the region between the metallurgical junctions and within 100

˙

A ( 0.01 µm
) of the interface:

interface dom=lneigh=2 x . l=l . lx . h=2.9layer .w=0.01

The inversion layer width in the previous example can be automatically determined by setting
the estimate to 0.0:

interface dom=lneigh=% x . l=l . lx . h=2.9layer .w=0.0

30.3COMMENT

Add explanatory comments to a device def i nition

SYNOPSIS

comment [ text ]
*

[ text ]
$ [ text ]
# [ text ]


30.4. CONTACT489

30.3.1DESCRIPTION

Annotations can be added to a device def i nition 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.2EXAMPLES

A SPICE-like comment is followed by a PISCES-like comment and shell script comment:

*

CIDER and SPICE wouldignorethisinputline
$ CIDER and PISCES wouldignorethis,but SPICE wouldn ’ t
# CIDER and LINUX Shellscriptswouldignorethisinputline

30.4CONTACT

Specify properties of an electrode

SYNOPSIS

contactnumber[ workfunction ]

30.4.1DESCRIPTION

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.2PARAMETERS

NameTypeDescription
NumberIntegerID number of the electrode
Work-functionRealWork-function of electrode material. ( eV )

30.4.3EXAMPLES

Thefollowingshowshowthework-functionofthegatecontactofaMOSFETmightbechanged
to a value appropriate for a P+ polysilicon gate:

contact num=2 workf =5.29

30.4.4SEE ALSO

electrode, material


490CHAPTER 30. CIDER USER’S MANUAL

30.5DOMAIN, REGION

Identify material-type for section of a device

SYNOPSIS

domain numbermaterial[ position ]
regionnumbermaterial[ position ]

30.5.1DESCRIPTION

A device is divided into one or more rectilinear domains, each of which has a unique identif i ca-
tion 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 0f multiple boxes. When
multiple domain cards overlap in space, the one occurring last in the input f i le will determine
the ID number and material type of the overlapped region.

Each edge of a domain box can be specif i ed in terms of its location or mesh-index in the relevant
dimension, or defaulted to the respective boundary of the simulation mesh.

30.5.2PARAMETERS

NameTypeDescription
NumberIntegerID number of this domain
MaterialIntegerID number of material used by this domain
X.LowRealLowest X location of domain box, ( µm )
:IX.LowIntegerLowest X mesh-index of domain box
X.HighRealHighest X location of domain box, ( µm )
:IX-HighIntegerHighest X mesh-index of domain box
Y.LowRealLowest Y location of domain box, ( µm )
:IY.LowIntegerLowest Y mesh-index of domain box
Y.HighRealHighest Y location of domain box, ( µm )
:IY.HighIntegerHighest Y mesh-index of domain box

30.5.3EXAMPLES

Create a 4.0 pm wide by 2.0 pm high domain out of material #1:

domain num=lmaterial=lx . l=O.O x . h=4.0 y . l=O.O y . h=2.0

The next example def i nes the two domains that would be typical of a planar MOSFET simula-
tion. One occupies all of the mesh below y = 0 and the other occupies the mesh above y = 0.
Because the x values are left unspecif i ed, the low and high x boundaries default to the edges of
the mesh:


30.6. DOPING491

domain n=l m=ly . l=O.O
domain n=2 m=2 y . h=O.O

30.5.4SEE ALSO

x.mesh, material

30.6DOPING

Add dopant to regions of a device

SYNOPSIS

doping[ domains ]profile −type[ lateral −profile −type ][ axis ]
[ impurity−type1[ constant −box ][ profile −specifications ]

30.6.1DESCRIPTION

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 prof i le that def i nes the
dopant concentration as a function of position. The doping at a particular location is then the
sum over all prof i les of the concentration values at that position. Each prof i le can be restricted
to a subset of a device’s domains by supplying a list of the desired domains.

Otherwise, all domains are doped by each prof i le.

A prof i le has uniform concentration inside the constant box. Outside this region, it varies ac-
cording to the primary an lateral prof i le shapes. In 1D devices the lateral shape is unused and in
2D devices the y-axis is the default axis for the primary prof i le. Several analytic functions can
be used to def i ne the primary prof i le shape. Alternatively, empirical or simulated prof i le data
can be extracted from a f i le. For the analytic prof i les, the doping is the product of a prof i le func-
tion (e.g. Gaussian) and a reference concentration, which is either the constant concentration
of a uniform prof i le, or the peak concentration for any of the other functions. If concentration
data is used instead take from an ASCII f i le containing a list of location-concentration pairs
or a SUPREM3 exported f i le, the name of the f i le must be provided. If necessary, the f i nal
concentration at a point is then found by multiplying the primary prof i le concentration by the
value of the lateral prof i le function at that point. Empirical prof i les must f i rst be normalized by
the value at 0.0 to provide a usable prof i le 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 prof i le are the circular.

Unless otherwise specif i ed, the added impurities are assumes to be N type. However, the name
of a specif i c dopant species is needed when extracting concentration information for that impu-
rity from a SUPREM3 exported f i le.

Several parameters are used to adjust the basic shape of a prof i le functions so that the f i nal,
constructed prof i le, matches the doping prof i le in the real device. The constant box region


492CHAPTER 30. CIDER USER’S MANUAL

Figure 30.1: 1D doping prof i les with location > 0.

should coincide with a region of constant concentration in the device. For uniform prof i les its
boundaries default to the mesh boundaries. For the other prof i les the constant box starts as a
point and only acquires width or height if both the appropriate edges are specif i ed. The location
of the peak of the primary prof i le 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 then
equal to the value of the prof i le when it intersects the edge of the constant box. The argument
of the prof i le function is a distance expressed in terms of the characteristic length (by default
equal to 1µm). The longer this length, the more gradually the prof i le will change. For example,
in Fig. A.1 and Fig A.2, the prof i les marked (a) have characteristic lengths twice those of the
prof i les marked (b). The location and characteristic length for the lateral prof i le are multiplied
by the lateral ratio. This allows the use of different length scales for the primary and lateral
prof i les. For rotated prof i les, this scaling is taken into account, and the prof i le contours are
elliptical rather than circular.


30.6. DOPING493

Figure 30.2: 1D doping prof i les with location < 0.


494CHAPTER 30. CIDER USER’S MANUAL

30.6.2PARAMETERS

NameTypeDescription
DomainsInt ListList of domains to dope
Uniform:FlagPrimary prof i le type
Linear:
Erfc:
Exponential:
Suprem3:
Ascii:
Ascii Suprem3
InFileStringName of Suprem3, Ascii or Ascii Suprem3 input f i le
Lat.Rotate:FlagLateral prof i le type
Lat.Unif:
Lat.Lin:
Lat.Gauss:
Lat.Erfc:
Lat.Exp
X.Axis:Y.AxisFlagPrimary prof i le direction
N.Type: P.Type:FlagImpurity type
Donor: Acceptor:
Phosphorus:
Arsenic:
Antimony:
Boron
X.LowRealLowest X location of constant box, (µm)
X.HighRealHighest X location of constant box, (µm)
Y.LowRealLowest Y location of constant box, (µm)
Y.HighRealHighest Y location of constant box, (µm)
Conic | Peak.conicRealDopant concentration, (cm−3)
Location | RangeRealLocation of prof i le edge/peak, (µm)
Char.LengthRealCharacteristic length of prof i le, (µm)
Ratio.LatRealRatio of lateral to primary distances

30.6.3EXAMPLES

This f i rst example adds a uniform background P-type doping of 1.0×1016cm−3to an entire
device:

dopinguniform p . typeconc=l .0 el6

A Gaussian implantation with rotated lateral falloff, such as might be used for a MOSFET
source, is then added:

dopinggausslat . rotaten . typeconc=l .0 el9
+ x . l =0.0 x . h=0.5 y . l =0.0 y . h=0.2ratio =0.7


30.7. ELECTRODE495

Alternatively, an error-function falloff could be used:

dopinggausslat . erfcconc=l .0 el9
+ x . l =0.0 x . h=0.5 y . l =0.0 y . h=0.2ratio =0.7

Finally, the MOSFET channel implant is extracted from an ASCII-format SUPREM3 f i le. The
lateral prof i le is uniform, so that the implant is conf i ned between X = 1µm and X = 3µm. The
prof i le begins atY = 0µm (the high Y value defaults equal to the low Y value):

dopingasciisuprem3i n f i l e =implant . s3l a t . unifboron
+ x . l =1.0 x . h=3.0 y . l =0.0

30.6.4SEE ALSO

domain, mobility, contact, boundary

30.7ELECTRODE

Set location of a contact to the device

SYNOPSIS

electrode[ number ][ position ]

30.7.1DESCRIPTION

Each device has several electrodes which 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 identif i ed 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
specif i ed are assigned values sequentially in the order they appear in the input f i le.

For lD devices, the positions of two of the electrodes are predef i ned to be at the ends of the
simulation mesh. The f i rst 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 specif i ed only in terms of boxes, electrodes can also be specif i ed 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 specif i ed in terms of the locations or
mesh-indices of its boundaries. A missing value defaults to the corresponding mesh boundary.


496CHAPTER 30. CIDER USER’S MANUAL

30.7.2PARAMETERS

NameTypeDescription
NumberIntegerID number of this domain
X.LowRealLowest X location of electrode, (µm)
:IX.LowIntegerLowest X mesh-index of electrode
X.HighRealHighest X location of electrode, (µm)
:IX.HighIntegerHighest X mesh-index of electrode
Y.LowRealLowest Y location of electrode, (µm)
:IY.LowIntegerLowest Y mesh-index of electrode
Y.HighRealHighest Y location of electrode, (µm)
:IY.HighIntegerHighest Y mesh-index of electrode

30.7.3EXAMPLES

The following shows how the four contacts of a MOSFET might be specif i ed:

*

DRAIN
electrodex . l =0.0 x . h=0.5 y . l =0.0 y . h=0.0
*

GATE
electrodex . l =1.0 x . h=3.0iy . l =0 iy . h=0
*

SOURCE
electrodex . l =3.0 x . h=4.0 y . l =0.0 y . h=0.0
*

BULK
electrodex . 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.7.4SEE ALSO

domain, contact

30.8END

Terminate processing of a device def i nition

SYNOPSIS

end


30.9. MATERIAL497

30.8.1DESCRIPTION

Theendcardstopsprocessingofadevicedef i nition. Itmayappearanywherewithinadef i nition.
Subsequent continuation lines of the def i nition will be ignored. If no end card is supplied, all
the cards will be processed.

30.9MATERIAL

Specify physical properties of a material

SYNOPSIS

materialnumbertype[ physical −constants ]

30.9.1DESCRIPTION

The material card is used to create an entry in the list of materials used in a device. Each entry
needs a unique identif i cation 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 coeff i cient 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.


498CHAPTER 30. CIDER USER’S MANUAL

30.9.2PARAMETERS

NameTypeDescription
NumberIntegerID number of this material
Semiconductor : SiliconFlagType of this material
: Polysilicon : GaAs
: Insulator : Oxide
: Nitride
Aff i nityRealElectron aff i nity (eV)
PermittivityRealDielectric permittivity (F/cm)
NcRealConduction band density (cm−3)
NvRealValence band density (cm−3)
EgRealEnergy band gap (eV)
dEg.dTRealBandgap narrowing with temperature (eV/◦K)
Eg.TrefRealBandgap reference temperature, ( °K )
dEg.dNRealBandgap narrowing with N doping, (eV/cm−3)
Eg.NrefRealBandgap reference concentration - N type, (cm−3)
dEg.dPRealBandgap narrowing with P doping, (eV/cm−3)
Eg.PrefRealBandgap reference concentration - P type, (cm−3)
TNRealSRH lifetime - electrons, (sec)
SRH.NrefRealSRH reference concentration - electrons (cm−3)
TPRealSRH lifetime - holes, (sec)
SRH.PrefRealSRH reference concentration - holes (cm−3)
CNRealAuger coeff i cient - electrons (cm6/sec)
CPRealAuger coeff i cient - holes (cm6/sec)
ARichNRealRichardson constant - electrons, (A/cm2

◦K2)
ARichPRealRichardson constant - holes, (A/cm2

◦K2)

30.9.3EXAMPLES

Set the type of material #1 to silicon, then adjust the values of the temperature-dependent
bandgap model parameters:

material num=1siliconeg=1.12deg . dt =4.7e−4 eg . t r e f =640.0

The recombination lifetimes can be set to extremely short values to simulate imperfect semi-
conductor material:

material num=2silicontn=1pstp=1ps

30.9.4SEE ALSO

domain, mobility, contact, boundary


30.10. METHOD499

30.10METHOD

Choose types and parameters of numerical methods

SYNOPSIS

method[ types ][ parameters ]

30.10.1DESCRIPTION

The method card controls which numerical methods are used during a simulation and the pa-
rameters of these methods. Most of these methods are optimizations that reduce run time, but
may sacrif i ce 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 fre-
quencies, 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 predef i ned frequency in order to obtain these small-signal param-
eters. The default for this frequency is 1 Hz. The Jacobian matrix for DC and transient analyses
can be simplif i ed by ignoring the derivatives of the mobility with respect to the solution vari-
ables. 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
differentialequations. Thisalgorithmisbasedonaniterativeloopthatterminateswhentheerror
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.2Parameters

NameTypeDescription
OneCarrierFlagSolve for majority carriers only
AC analysisStringAC analysis method, ( either DIRECT or SOR)
NoMobDerivFlagIgnore mobility derivatives
FrequencyRealAC analysis frequency, ( Hz )
ItLimIntegerNewton iteration limit
DevTolRealMaximum residual error in device equations

30.10.3Examples

Use one carrier simulation for a MOSFET, and choose direct method AC analysis to ensure
accurate, high frequency results:


500CHAPTER 30. CIDER USER’S MANUAL

method onecac . an= direct

Tolerate no more than 10−10as the absolute error in device-level equations, and perform no
more than 15 Newton iterations in any one loop:

methoddevtol =1e−10 itlim =15

30.11Mobility

Specify types and parameters of mobility models

SYNOPSIS

mobilitymaterial[ carrier ][ parameters ][ models ][ i n i t i a l i z e ]

30.11.1Description

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 modelling. 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-f i eld mobility degradation model has three user-modif i able pa-
rameters. For bulk carriers, the ionized impurity scattering model has four controllable pa-
rameters. Different sets of parameters are maintained for each of the four bulk carrier types:
majority-electron, minority-electron, majority-holeandminority-hole. Velocitysaturationmod-
eling 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 f l ag 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 specif i c to a particular model by setting the initialization f l ag. 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
alternativesetsofdefaultsareavailablefortheCaughey-Thomasexpression. TheyaretheArora
(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. MOBILITY501

30.11.2Parameters

NameTypeDescription
MaterialIntegerID number of material
Electron : HoleFlagMobile carrier
Majority : MinorityFlagMobile carrier type
MUSRealMaximum surface mobility, ( cm2/Vs )
EC.ARealSurface mobility 1st-order critical f i eld, ( V/cm )
EC.BRealReal Surface mobility 2nd-order critical f i eld, ( V2/cm2 )
MuMaxRealMaximum bulk mobility, ( cm2/Vs )
MuMinRealMinimum bulk mobility, ( cm2/Vs)
NtRefRealIonized impurity reference concentration, ( cm-3 )
NtExpRealIonized impurity exponent
VsatRealSaturation velocity, ( cm/s )
VwarmRealWarm carrier reference velocity, ( cm/s )
ConcModelStringIonized impurity model, ( CT, AR, UF, SG, Dr GA )
FieldModelStringVelocity saturation model, ( CT, AR, SG, or GA )
InitFlagCopy model-specif i c defaults

30.11.3Examples

The following set of cards completely updates the bulk mobility parameters for material #1:

mobilitymat=lconcmod=sgfieldmod=sg
mobilitymat=lelecmajor mumax=1000.0 mumin=l00 .0
+ntref =l .0 el6ntexp =0.8vsat=l .0 e7 vwarm=3.0 e6
mobilitymat=lelecminor mumax=1000.0 mumin=200.O
+ntref =l .0 el7ntexp =0.9
mobilitymat=lholemajor mumax=500.0 mumin=50.0
+ntref =l .0 el6ntexp =0.7vsat =8.0 e6 vwarm=l .0 e6
mobilitymat=lholeminor mumax=500.0 mumin=150.0
+ntref =l .0 el7ntexp =0.8

The electron surface mobility is changed by the following:

mobilitymat=lelec mus=800.0ec . a=3.0 e5 ec . b=9.0 e5

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!):

mobilitymat=li n i telecmajorfieldmodel=sg
mobilitymat=li n i tholemajorfieldmodel=sg
mobilitymat=lfieldmodel=ga

30.11.4SEE ALSO

material


502CHAPTER 30. CIDER USER’S MANUAL

30.11.5BUGS

The surface mobility model does not include temperature-dependence for the transverse-f i eld
parameters. Those parameters will need to be adjusted by hand.

30.12MODELS

Specify which physical models should be simulated

SYNOPSIS

models[ modelflags ]

30.12.1DESCRIPTION

The models card indicates which physical effects should be modeled during a simulation. Ini-
tially, none of the effects are included. A f l ag can be set false by preceding by a caret.

30.12.2Parameters

NameTypeDescription
BGNFlagBandgap narrowing
SRHFlagShockley-Reed-Hall recombination
ConcTauFlagConcentration-dependent SRH lifetimes
AugerFlagAuger recombination
AvalancheFlagLocal avalanche generation
TempMobFlagTemperature-dependent mobility
ConcMobFlagConcentration-dependent mobility
FieldMobFlagLateral-f i eld-dependent mobility
TransMobFlagTransverse-f i eld-dependent surface mobility
SurfMobFlagActivate surface mobility model

30.12.3Examples

Turn on bandgap narrowing, and all of the generation-recombination effects:

models bgnsrhconctauaugeraval

Amend the f i rst card by turning on lateral- and transverse-f i eld-dependent mobility in surface
charge layers, and lateral-f i eld-dependent mobility in the bulk. Also, this line turns avalanche
generation modeling off.

modelssurfmobtransmobfieldmob ^ aval


30.13. OPTIONS503

30.12.4See also

material, mobility

30.12.5Bugs

The local avalanche generation model for 2D devices does not compute the necessary contri-
butions to the device-level Jacobian matrix. If this model is used, it may cause convergence
diff i culties and it will cause AC analyses to produce incorrect results.

30.13OPTIONS

Provide optional device-specif i c information

SYNOPSIS

options[ device−type ][ i n i t i a l −state ][ dimensions ]
[ measurement−temperature ]

30.13.1DESCRIPTION

The options card functions as a catch-all for various information related to the circuit-device
interface. The type of a device can be specif i ed 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 f i le, 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 f l ag can be used to generate unique f i lenames for each instance
by appending the instance name to the given f i lename. This is the same method used by CIDER
to generate unique f i lenames when the states are originally saved. If a particular state f i le does
not f i t. this pattern, the f i lename can be entered directly on the instance line.

Mask dimension defaults can be set so that device sizes can be specif i ed 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.


504CHAPTER 30. CIDER USER’S MANUAL

30.13.2Parameters

NameTypeDescription
ResistorFlagResistor
: CapacitorFlagCapacitor
: DiodeFlagDiode
: Bipolar|BJTFlagBipolar transistor
: MOSFETFlagMOS f i eld-effect transistor
: JFETFlagJunction f i eld-effect transistor
: MESFETFlagMES f i eld-effect transistor
IC.FileStringInitial-conditions f i lename
UniqueFlagAppend instance name to f i lename
DefARealDefault Mask Area, (m²)
DefWRealDefault Mask Width, (m)
DefLRealDefault Mask Length, (m)
Base.AreaReallD BJT base area relative to emitter area
Base.LengthRealReal lD BJT base contact length, (µm)
Base.DepthReallD BJT base contact depth, (µm)
TNomRealNominal measurement temperature, (°C)

30.13.3Examples

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 specif i ed on the element line it can be divided by this default to
obtain the device width.

optionsbipolardefl =1.0

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

optionsbase . area =0.1base . depth =0.2base . len =1.5

If a circuit contains two instances of a bipolar transistor model named ’q1’ and ’q2’, the fol-
lowing 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:

optionsuniqueic . f i l e ="OP1"

30.13.4See also

numd, nbjt, numos


30.14. OUTPUT505

30.14OUTPUT

Identify information to be printed or saved

SYNOPSIS

output[ debugging−flags ][ general−info ][ saved−solutions ]

30.14.1DESCRIPTION

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 f i les. Solution f i lenames are automatically generated by the simulator. If the
named f i le already exists, the f i le will be overwritten. A f i lename unique to a particular circuit
or run can be generated by providing a root f i lename. 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 f i lename 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 f i eld, 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 f l ag 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.


506CHAPTER 30. CIDER USER’S MANUAL

30.14.2Parameters

NameTypeDescription
All.DebugFlagDebug all analyses
OP.DebugFlag.OP analyses
DC.DebugFlag.DC analyses
TRAN.DebugFlag.TRAN analyses
AC.DebugFlag.AC analyses
PZ.DebugFlag.PZ analyses
MaterialFlagPhysical material information
Statistics | ResourcesFlagResource usage information
RootFileStringRoot of output f i le names
PsiFlagPotential ( V )
Equ.PsiFlagEquilibrium potential ( V )
Vac.PsiFlagVacuum potential ( V )
DopingFlagNet doping ( cm³ )
N.ConcFlagElectron concentration ( cm³ )
P.ConcFlagHole concentration ( cm³ )
PhiNFlagElectron quasi-fermi potential ( V )
PhiPFlagHole quasi-fermi potential ( V )
PhiCFlagConduction band potential ( V )
PhiVFlagValence band potential ( V )
E.FieldFlagElectric f i eld ( V/cm )
JCFlagConduction current density ( A/cm² )
JDFlagDisplacement current density ( A/cm² )
JNFlagElectron current density ( A/cm² )
JPFlagHole current density ( A/cm² )
JTFlagTotal current density ( A/cm² )
UnetFlagNet recombination ( 1/cm³ s )
MuNFlagElectron mobility (low-f i eld) ( cm²/Vs )
MuPFlagHole mobility (low-f i eld) ( cm²/Vs )

30.14.3Examples

The following example activates all potentially valuable diagnostic output:

outputall . debugmaters t a t

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:

outputphinphjpphicphivvac . psi

Sometimes it is desirable to save certain key solutions, and then reload them for use in subse-
quent simulations. In such cases only the essential values ( Y, n, and p ) need to be saved. This
example turns off the nonessential default values (and indicates the essential ones explicitly):


30.15. TITLE507

outputpsin . conc p . conc ^e . f ^ jn^ jp^ jd

30.14.4SEE ALSO

options, numd, nbjt, numos

30.15TITLE

Provide a label for this device’s output

SYNOPSIS

t i t l e[ text ]

30.15.1DESCRIPTION

The title card provides a label for use as a heading in various output f i les. The text can be any
length, but titles that f i t on a single line will produce more aesthetically pleasing output.

30.15.2EXAMPLES

Set the title for a minimum gate length NMOSFET in a 1.0µm BiCMOS process

t i t l eL=1.0um NMOS Device ,1.0um BiCMOS Process

30.15.3BUGS

The title is currently treated like a comment.

30.16X.MESH, Y.MESH

Def i ne locations of lines and nodes in a mesh

SYNOPSIS

x . meshpositionnumbering−method[ spacing−parameters ]
y . meshpositionnumbering−method[ spacing−parameters ]


508CHAPTER 30. CIDER USER’S MANUAL

30.16.1DESCRIPTION

The domains of a device are discretized onto a rectangular f i nite-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 specif i ed.

A typical mesh for a 2D device is shown in Figure 30.3.

Figure 30.3: Typical mesh for 2D devices

The mesh is divided into intervals by the reference lines. The other lines in each interval are
automatically generated by CIDER using the mesh spacing parameters. In general, each new
mesh card adds one reference line and multiple automatic lines to the mesh. Conceptually, a 1D
mesh is similar to a 2D mesh except that there are no reference or automatic lines needed in the
second dimension.

The location of a reference line in the mesh must either be given explicitly (using Location) or
def i ned implicitly relative to the location of the previous reference line (by using Width). (If the
f i rst card in either direction is specif i ed 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


30.16. X.MESH, Y.MESH509

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 f i ll
the interval.

30.16.2Parameters

NameTypeDescription
LocationRealLocation of this mesh line, ( µm )
:WidthRealWidth between this and previous mesh lines, ( µm )
Number | NodeIntegerNumber of this mesh line
:RatioRealRatio of sizes of adjacent spaces
H.Start | H1RealSpace size at start of interval, ( µm )
H.End | H2RealSpace size at end of interval, ( µm )
H.Max | H3RealMaximum space size inside interval, ( µm )

30.16.3EXAMPLES

A 50 node, uniform mesh for a 5 µm long semiconductor resistor can be specif i ed as:

x . meshloc =0.0 n=1
x . meshloc =5.0 n=50

An accurate mesh for a 1D diode needs f i ne spacing near the junction. In this example, the junc-
tion is assumed to be 0.75 µm deep. The spacing near the diode ends is limited to a maximum
of 0.1 µm:

x . mesh w=0.75 h . e=0.001 h .m=0. lratio =1.5
x . mesh w=2.25 h . s =0.001 h .m=0. lratio =1.5

The vertical mesh spacing of a MOSFET can generally be specif i ed as uniform through the gate
oxide, very f i ne for the surface inversion layer, moderate down to the so source/drain junction
depth, and then increasing all the way to the bulk contact:

y . meshloc =−0.04 node=1
y . meshloc =0.0node=6
y . mesh width =0.5 h . s t a r t =0.001 h .max=.05ratio =2.0
y . mesh width =2.5 h . s t a r t =0.05ratio =2.0

30.16.4SEE ALSO

domain


510CHAPTER 30. CIDER USER’S MANUAL

30.17NUMD

Diode / two-terminal numerical models and elements

SYNOPSIS Model:

.MODEL model−name NUMD [ level ]
+. . .

SYNOPSIS Element:

DXXXXXXX nln2 model−name [ geometry ][ temperature ][ i n i t i a l −conditions ]

SYNOPSIS Output:

.SAVE [ small−signalvalues ]

30.17.1DESCRIPTION

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 unspecif i ed, 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 specif i ed 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 f i le containing an initial state
for the device can be specif i ed. Remember that if the f i lename contains capital letters, they
must be protected by surrounding the f i lename 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
usingtheNGSPICEshowcommand(17.5.64)orcapturedusingthesave/.SAVE (17.5.55/15.6.1)
command. These parameters are the elements of the indef i nite conductance (G), capacitance
(C), and admittance (Y) matrices where Y = G+ jωC. By default, the parameters are com-
puted 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 names are
case-sensitive for save/show, so lower-case letters must be used.


30.17. NUMD511

30.17.2Parameters

NameTypeDescription
LevelIntegerDimensionality of numerical model
AreaRealMultiplicative area factor
WRealMultiplicative width factor
TempRealElement operating temperature
IC.FileStringInitial-conditions f i lename
OffFlagDevice initially in OFF state
gIJFlagConductance element Gij, ( Ω )
cIJFlagCapacitance elementCij, ( F )
yIJFlagAdmittance elementYij, ( Ω )

30.17.3EXAMPLES

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 specif i ed using:

DSWITCH 1 2 M_SWITCH_DIODE AREA=2
.MODEL M_SWITCH_DIODE NUMD
+ optionsdefa=1p. . .
+. . .

A two-dimensional two-terminal MOS capacitor with a width of 20 µm and an initial condition
of 3 V is created by:

DMOSCAP 11 12 M_MOSCAP W=20um IC=3v
.MODEL M_MOSCAP NUMD LEVEL=2
+ optionsmoscap defw=1m
+. . .

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:

D1 POSN NEGN POWERMOD AREA=2 W=6um TEMP=100.0
.MODEL POWERMOD NUMD LEVEL=2
+. . .

This example saves all the small-signal parameters of the previous diode:

.SAVE @d1[ g11 ] @d1[ g12 ] @d1[ g21 ] @d1[ g22 ]
.SAVE @d1[ c11 ] @d1[ c12 ] @d1[ c21 ] @d1[ c22 ]
.SAVE @d1[ y11 ] @d1[ y12 ] @d1[ y21 ] @d1[ y22 ]


512CHAPTER 30. CIDER USER’S MANUAL

30.17.4SEE ALSO

options, output

30.17.5BUGS

Convergence problems may be experienced when simulating MOS capacitors due to singulari-
ties in the current-continuity equations.

30.18NBJT

Bipolar / three-terminal numerical models and elements

SYNOPSIS Model:

.MODEL model−name NBJT [ level ]
+. . .

SYNOPSIS Element:

QXXXXXXX nln2 n3 model−name [ geometry ]
+ [ temperature ][ i n i t i a l −conditions ]

SYNOPSIS Output:

.SAVE [ small−signalvalues ]

30.18.1DESCRIPTION

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, respec-
tively. If left unspecif i ed, 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 specif i ed 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 specif i ed 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 prof i le. However, all these defaults can be overridden on an options card.

Theoperatingtemperatureofadevicecanbesetindependentlyfromtherestofthatofthecircuit
in order to simulate non-isothermal circuit operation. Finally, the name of a f i le containing an


30.18. NBJT513

initial state for the device can be specif i ed. Remember that if the f i lename contains capital
letters, they must be protected by surrounding the f i lename 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 param-
eters are the elements of the indef i nite conductance (G), capacitance (C), and admittance (Y)
matrices where Y = G +jwC. 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 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.2Parameters

NameTypeDescription
LevelIntegerDimensionality of numerical model
AreaRealMultiplicative area factor
WRealMultiplicative width factor
TempRealElement operating temperature
IC.FileStringInitial-conditions f i lename
OffFlagDevice initially in OFF state
gIJFlagConductance element Gij, ( Ω )
cIJFlagCapacitance elementCij, ( F )
yIJFlagAdmittance elementYij, ( Ω )

30.18.3EXAMPLES

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:

.SAVE @q2[ g11 ] @q2[ g12 ] @q2[ g22 ]

The second example is for a two-dimensional JFET with a width of 5pm and initial conditions
obtained from f i le "IC.jfet":

QJ1 11 12 13 M_JFET W=5um IC . FILE="IC . j f e t "
.MODEL M_JFET NBJT LEVEL=2
+ optionsj f e t
+. . .


514CHAPTER 30. CIDER USER’S MANUAL

A f i nal example shows how to use symmetry to simulate half of a 2D BJT, avoiding having the
user double the area of each instance:

Q2 NC2 NB2 NE2 BJTMOD AREA=1
Q3 NC3 NB3 NE3 BJTMOD AREA=1
.MODEL BJTMOD NBJT LEVEL=2
+ optionsdefw=2um
+

*

Definehalfofthedevice now
+. . .

30.18.4SEE ALSO

options, output

30.18.5BUGS

MESFETs cannot be simulated properly yet because Schottky contacts have not been imple-
mented.

30.19NUMOS

MOSFET / four-terminal numerical models and elements

SYNOPSIS Model:

.MODEL model−name NUMOS [ level ]
+. . .

SYNOPSIS Element:

MXXXXXXX nln2 n3 n4 model−name [ geometry ]
+ [ temperature ][ i n i t i a l −conditions ]

SYNOPSIS Output:

.SAVE [ small−signalvalues ]

30.19.1DESCRIPTION

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 rectif i ers (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.


30.19. NUMOS515

Allnumericalfour-terminalelementnamesbeginwiththeletter‘M’.IfthedeviceisaMOSFET,
or JFET with a bulk contact, then the nodes are specif i ed 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
specif i ed 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.

Theoperatingtemperatureofadevicecanbesetindependentlyfromthatoftherestofthecircuit
in order to simulate non-isothermal circuit operation. Finally, the name of a f i le containing an
initial state for the device can be specif i ed. Remember that if the f i lename contains capital
letters, they must be protected by surrounding the f i lename 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 indef i nite conductance (G), capacitance (C), and ad-
mittance (Y) matrices where Y = G+jwC. 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.2Parameters

NameTypeDescription
LevelIntegerDimensionality of numerical model
AreaRealMultiplicative area factor
WRealMultiplicative width factor
LRealUnused length factor
TempRealElement operating temperature
IC.FileStringInitial-conditions f i lename
OffFlagDevice initially in OFF state
gIJFlagConductance element Gij, ( Ω )
cIJFlagCapacitance elementCij, ( F )
yIJFlagAdmittance elementYij, ( Ω )

30.19.3EXAMPLES

A numerical MOSFET with a gate width of 5µm and length of 1µm is described below. How-
ever, 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 f i le "NM1.vth".


516CHAPTER 30. CIDER USER’S MANUAL

M1 1 2 3 4 M_NMOS_1UM W=5um L=1um IC . FILE="NM1. vth "
.MODEL MNMOS_1UM NUMOS
+

*

Descriptionofa lumdevice
+. . .

This example saves the def i nite admittance matrix of the previous MOSFET where the source
terminal (3) is used as the reference. (The def i nite admittance matrix is formed by deleting the
third row and column from the indef i nite admittance matrix.)

.SAVE @m1[ y11 ] @m1[ y12 ] @ml[ y14 ]
.SAVE @m1[ y21 ] @m1[ y22 ] @ml[ y24 ]
.SAVE @m1[ y41 ] @m1[ y42 ] @ml[ y44 ]

Bipolar transistors are usually specif i ed 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
+ optionsbipolardefw=5um
+. . .

30.19.4SEE ALSO

options, output

30.20Cider examples

The original Cider User’s manual, in its Appendix A, lists a lot of examples, starting at page
226. We do not reproduce these pages here, but ask you to refer to the original document. If
you experience any diff i culties downloading it, please send a note to the ngspice users’ mailing
list.


Part IV

Appendices

517



Chapter 31

Model and Device Parameters

The following tables summarize the parameters available on each of the devices and models in
ngspice. There are two tables for each type of device supported by ngspice. Input parameters
to instances and models are parameters that can occur on an instance or model def i nition line in
the form keyword=value where keyword is the parameter name as given in the tables. Default
input parameters (such as the resistance of a resistor or the capacitance of a capacitor) obviously
do not need the keyword specif i ed.

31.1Accessing internal device parameters

Output parameters are those additional parameters which are available for many types of in-
stances for the output of operating point and debugging information. These parameters are
specif i ed as @device[keyword] and are available for the most recent point computed or, if
specif i ed in a .save statement, for an entire simulation as a normal output vector. Thus, to
monitor the gate-to-source capacitance of a MOSFET, a command

save @m1[ cgs ]

given before a transient simulation causes the specif i ed 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).

Somevariables arelisted asboth inputand 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.

519


520CHAPTER 31. MODEL AND DEVICE PARAMETERS

General form:

@device_identifier . subcircuit_name .< subcircuit_name_nn >
+. device_name [ parameter ]

Example input f i le:

*

t r a n s i s t o routputc h a r a c t e r i s t i c s
*

twonestedsubcircuits
vdd d1 0 2.0
vssvsss 0 0
vsigg1vsss 0
xmos1 d1 g1vssslevel1
. subcktlevel1d3 g3 v3
xmos2d3 g3 v3level2
. ends
. subcktlevel2d4 g4 v4
m1 d4 g4 v4 v4 nmos w=1e−5 l =3.5e−007
. ends
. dc vdd 0 5 0.1vsig 0 5 1
. control
savea ll @m. xmos1 . xmos2 .m1[ vdsat ]
run
plotvss#branch$currentmeasuredatthetoplevel
plot @m. xmos1 . xmos2 .m1[ vdsat ]
. endc
.MODEL NMOS NMOSLEVEL= 8
+VERSION = 3.2.4TNOM= 27TOX= 7.4E−9
. end

The device identif i er is the f i rst letter extracted from the device name, e.g. m for a MOS tran-
sistor.

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 pro-
vided as a quick reference guide.


31.2. ELEMENTARY DEVICES521

31.2Elementary Devices

31.2.1Resistor

31.2.1.1Resistor instance parameters

#NameDirectionTypeDescription
1resistanceInOutrealResistance
10acInOutrealAC resistance value
8tempInOutrealInstance operating temperature
14dtempInOutrealInstance temperature difference
with the rest of the circuit
3lInOutrealLength
2wInOutrealWidth
12mInOutrealMultiplication factor
16tcInOutrealFirst order temp. coeff i cient
16tc1InOutrealFirst order temp. coeff i cient
17tc2InOutrealSecond order temp. coeff i cient
13scaleInOutrealScale factor
15noisyInOutintegerResistor generate noise
5sens_resistInf l agf l ag to request sensitivity WRT
resistance
6iOutrealCurrent
7pOutrealPower
206sens_dcOutrealdc sensitivity
201sens_realOutrealdc sensitivity and real part of ac
sensitivity
202sens_imagOutrealdc sensitivity and imag part of ac
sensitivity
203sens_magOutrealac sensitivity of magnitude
204sens_phOutrealac sensitivity of phase
205sens_cplxOutcomplexac sensitivity


522CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.2.1.2Resistor model parameters

#NameDirectionTypeDescription
103rshInOutrealSheet resistance
106narrowInOutrealNarrowing of resistor
106dwInOutreal
109shortInOutrealShortening of resistor
109dlrInOutreal
101tc1InOutrealFirst order temp. coeff i cient
102tc2InOutrealSecond order temp. coeff i cient
104defwInOutrealDefault device width
104wInOutrealDefault device width
105lInOutrealDefault device length
110kfInOutrealFlicker noise coeff i cient
111afInOutrealFlicker noise exponent
108tnomInOutrealParameter measurement temperature
107rInOutrealResistance
107resInOutrealResistance

rInf l agDevice is a resistor model


31.2. ELEMENTARY DEVICES523

31.2.2Capacitor - Fixed capacitor

31.2.2.1Capacitor instance parameters

#NameDirectionTypeDescription
1capacitanceInOutrealDevice capacitance
1capInOutrealDevice capacitance
1cInOutrealDevice capacitance
2icInOutrealInitial capacitor voltage
8tempInOutrealInstance operating temperature
9dtempInOutrealInstance temperature difference
from the rest of the circuit
3wInOutrealDevice width
4lInOutrealDevice length
11mInOutrealParallel multiplier
10scaleInOutrealScale factor
5sens_capInf l agf l ag to request sens. WRT cap.
6iOutrealDevice current
7pOutrealInstantaneous device power
206sens_dcOutrealdc sensitivity
201sens_realOutrealreal part of ac sensitivity
202sens_imagOutrealdc sens. & imag part of ac sens.
203sens_magOutrealsensitivity of ac magnitude
204sens_phOutrealsensitivity of ac phase
205sens_cplxOutcomplexac sensitivity

31.2.2.2Capacitor model parameters

#NameDirectionTypeDescription
112capInOutrealModel capacitance
101cjInOutrealBottom Capacitance per area
102cjswInOutrealSidewall capacitance per meter
103defwInOutrealDefault width
113def lInOutrealDefault length
105narrowInOutrealwidth correction factor
106shortInOutreallength correction factor
107tc1InOutrealFirst order temp. coeff i cient
108tc2InOutrealSecond order temp. coeff i cient
109tnomInOutrealParameter measurement temperature
110diInOutrealRelative dielectric constant
111thickInOutrealInsulator thickness
104cInf l agCapacitor model


524CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.2.3Inductor - Fixed inductor

31.2.3.1Inductor instance parameters

#NameDirectionTypeDescription
1inductanceInOutrealInductance of inductor
2icInOutrealInitial current through inductor
5sens_indInf l agf l ag to request sensitivity WRT
inductance
9tempInOutrealInstance operating temperature
10dtempInOutrealInstance temperature difference with the
rest of the circuit
8mInOutrealMultiplication Factor
11scaleInOutrealScale factor
12ntInOutrealNumber of turns
3f l uxOutrealFlux through inductor
4vOutrealTerminal voltage of inductor
4voltOutreal
6iOutrealCurrent through the inductor
6currentOutreal
7pOutrealinstantaneous power dissipated by the
inductor
206sens_dcOutrealdc sensitivity sensitivity
201sens_realOutrealreal part of ac sensitivity
202sens_imagOutrealdc sensitivity and imag part of ac
sensitivty
203sens_magOutrealsensitivity of AC magnitude
204sens_phOutrealsensitivity of AC phase
205sens_cplxOutcomplexac sensitivity

31.2.3.2Inductor model parameters

#NameDirectionTypeDescription
100indInOutrealModel inductance
101tc1InOutrealFirst order temp. coeff i cient
102tc2InOutrealSecond order temp. coeff i cient
103tnomInOutrealParameter measurement temperature
104csectInOutrealInductor cross section
105lengthInOutrealInductor length
106ntInOutrealModel number of turns
107muInOutrealRelative magnetic permeability
108lInf l agInductor model


31.2. ELEMENTARY DEVICES525

31.2.4Mutual - Mutual Inductor

31.2.4.1Mutual instance parameters

#NameDirectionTypeDescription
401kInOutrealMutual inductance
401coeff i cientInOutreal
402inductor1InOutinstanceFirst coupled inductor
403inductor2InOutinstanceSecond coupled inductor
404sens_coeffInf l agf l ag to request sensitivity WRT coupling factor
606sens_dcOutrealdc sensitivity
601sens_realOutrealreal part of ac sensitivity
602sens_imagOutrealdc sensitivity and imag part of ac sensitivty
603sens_magOutrealsensitivity of AC magnitude
604sens_phOutrealsensitivity of AC phase
605sens_cplxOutcomplexmutual model parameters:


526CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.3Voltage and current sources

31.3.1ASRC - Arbitrary source

31.3.1.1ASRC instance parameters

#NameDirectionTypeDescription
2iInparsetreeCurrent source
1vInparsetreeVoltage source
7iOutrealCurrent through source
6vOutrealVoltage across source
3pos_nodeOutintegerPositive Node
4neg_nodeOutintegerNegative Node


31.3. VOLTAGE AND CURRENT SOURCES527

31.3.2Isource - Independent current source

31.3.2.1Isource instance parameters

#NameDirectionTypeDescription
1dcInOutrealDC value of source
2acmagInOutrealAC magnitude
3acphaseInOutrealAC phase
5pulseInreal vectorPulse description
6sineInreal vectorSinusoidal source description
6sinInreal vectorSinusoidal source description
7expInreal vectorExponential source description
8pwlInreal vectorPiecewise linear description
9sffmInreal vectorSingle freq. FM description
21amInreal vectorAmplitude modulation description
10neg_nodeOutintegerNegative node of source
11pos_nodeOutintegerPositive node of source
12acrealOutrealAC real part
13acimagOutrealAC imaginary part
14functionOutintegerFunction of the source
15orderOutintegerOrder of the source function
16coeffsOutreal vectorCoeff i cients of the source
20vOutrealVoltage across the supply
17pOutrealPower supplied by the source
4acInreal vectorAC magnitude,phase vector
1cInrealCurrent through current source
22currentOutrealCurrent in DC or Transient mode
18distof1Inreal vectorf1 input for distortion
19distof2Inreal vectorf2 input for distortion


528CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.3.3Vsource - Independent voltage source

31.3.3.1Vsource instance parameters

#NameDirectionTypeDescription
1dcInOutrealD.C. source value
3acmagInOutrealA.C. Magnitude
4acphaseInOutrealA.C. Phase
5pulseInreal vectorPulse description
6sineInreal vectorSinusoidal source description
6sinInreal vectorSinusoidal source description
7expInreal vectorExponential source description
8pwlInreal vectorPiecewise linear description
9sffmInreal vectorSingle freq. FM descripton
22amInreal vectorAmplitude modulation descripton
16pos_nodeOutintegerPositive node of source
17neg_nodeOutintegerNegative node of source
11functionOutintegerFunction of the source
12orderOutintegerOrder of the source function
13coeffsOutreal vectorCoeff i cients for the function
14acrealOutrealAC real part
15acimagOutrealAC imaginary part
2acInreal vectorAC magnitude, phase vector
18iOutrealVoltage source current
19pOutrealInstantaneous power
20distof1Inreal vectorf1 input for distortion
21distof2Inreal vectorf2 input for distortion
23rInrealpwl repeat start time value
24tdInrealpwl delay time value


31.3. VOLTAGE AND CURRENT SOURCES529

31.3.4CCCS - Current controlled current source

31.3.4.1CCCS instance parameters

#NameDirectionTypeDescription
1gainInOutrealGain of source
2controlInOutinstanceName of controlling source
6sens_gainInf l agf l ag to request sensitivity WRT gain
4neg_nodeOutintegerNegative node of source
3pos_nodeOutintegerPositive node of source
7iOutrealCCCS output current
9vOutrealCCCS voltage at output
8pOutrealCCCS power
206sens_dcOutrealdc sensitivity
201sens_realOutrealreal part of ac sensitivity
202sens_imagOutrealimag part of ac sensitivity
203sens_magOutrealsensitivity of ac magnitude
204sens_phOutrealsensitivity of ac phase
205sens_cplxOutcomplexac sensitivity

31.3.5CCVS - Current controlled voltage source

31.3.5.1CCVS instance parameters

#NameDirectionTypeDescription
1gainInOutrealTransresistance (gain)
2controlInOutinstanceControlling voltage source
7sens_transInf l agf l ag to request sens. WRT transimpedance
3pos_nodeOutintegerPositive node of source
4neg_nodeOutintegerNegative node of source
8iOutrealCCVS output current
10vOutrealCCVS output voltage
9pOutrealCCVS power
206sens_dcOutrealdc sensitivity
201sens_realOutrealreal part of ac sensitivity
202sens_imagOutrealimag part of ac sensitivity
203sens_magOutrealsensitivity of ac magnitude
204sens_phOutrealsensitivity of ac phase
205sens_cplxOutcomplexac sensitivity


530CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.3.6VCCS - Voltage controlled current source

31.3.6.1VCCS instance parameters

#NameDirectionTypeDescription
1gainInOutrealTransconductance of source (gain)
8sens_transInf l agf l ag to request sensitivity WRT transconductance
3pos_nodeOutintegerPositive node of source
4neg_nodeOutintegerNegative node of source
5cont_p_nodeOutintegerPositive node of contr. source
6cont_n_nodeOutintegerNegative node of contr. source
2icInrealInitial condition of controlling source
9iOutrealOutput current
11vOutrealVoltage across output
10pOutrealPower
206sens_dcOutrealdc sensitivity
201sens_realOutrealreal part of ac sensitivity
202sens_imagOutrealimag part of ac sensitivity
203sens_magOutrealsensitivity of ac magnitude
204sens_phOutrealsensitivity of ac phase
205sens_cplxOutcomplexac sensitivity

31.3.7VCVS - Voltage controlled voltage source

31.3.7.1VCVS instance parameters

#NameDirectionTypeDescription
1gainInOutrealVoltage gain
9sens_gainInf l agf l ag to request sensitivity WRT gain
2pos_nodeOutintegerPositive node of source
3neg_nodeOutintegerNegative node of source
4cont_p_nodeOutintegerPositive node of contr. source
5cont_n_nodeOutintegerNegative node of contr. source
7icInrealInitial condition of controlling source
10iOutrealOutput current
12vOutrealOutput voltage
11pOutrealPower
206sens_dcOutrealdc sensitivity
201sens_realOutrealreal part of ac sensitivity
202sens_imagOutrealimag part of ac sensitivity
203sens_magOutrealsensitivity of ac magnitude
204sens_phOutrealsensitivity of ac phase
205sens_cplxOutcomplexac sensitivity


31.4. TRANSMISSION LINES531

31.4Transmission Lines

31.4.1CplLines - Simple Coupled Multiconductor Lines

31.4.1.1CplLines instance parameters

#NameDirectionTypeDescription
1pos_nodesInOutstring vectorin nodes
2neg_nodesInOutstring vectorout nodes
3dimensionInOutintegernumber of coupled lines
4lengthInOutreallength of lines

31.4.1.2CplLines model parameters

#NameDirectionTypeDescription
101rInOutreal vectorresistance per length
104lInOutreal vectorinductance per length
102cInOutreal vectorcapacitance per length
103gInOutreal vectorconductance per length
105lengthInOutreallength
106cplInf l agDevice is a cpl model


532CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.4.2LTRA - Lossy transmission line

31.4.2.1LTRA instance parameters

#NameDirectionTypeDescription
6v1InOutrealInitial voltage at end 1
8v2InOutrealInitial voltage at end 2
7i1InOutrealInitial current at end 1
9i2InOutrealInitial current at end 2
10icInreal vectorInitial condition vector:v1,i1,v2,i2
13pos_node1OutintegerPositive node of end 1 of t-line
14neg_node1OutintegerNegative node of end 1 of t.line
15pos_node2OutintegerPositive node of end 2 of t-line
16neg_node2OutintegerNegative node of end 2 of t-line

31.4.2.2LTRA model parameters

#NameDirectionTypeDescription
0ltraInOutf l agLTRA model
1rInOutrealResistance per meter
2lInOutrealInductance per meter
3gInOutreal
4cInOutrealCapacitance per meter
5lenInOutreallength of line
11relOutrealRel. rate of change of deriv. for bkpt
12absOutrealAbs. rate of change of deriv. for bkpt
28nocontrolInOutf l agNo timestep control
32steplimitInOutf l agalways limit timestep to 0.8*(delay of line)
33nosteplimitInOutf l agdon’t always limit timestep to 0.8*(delay of
line)
34lininterpInOutf l aguse linear interpolation
35quadinterpInOutf l aguse quadratic interpolation
36mixedinterpInOutf l aguse linear interpolation if quadratic results look
unacceptable
46truncnrInOutf l aguse N-R iterations for step calculation in
LTRAtrunc
47truncdontcutInOutf l agdon’t limit timestep to keep impulse response
calculation errors low
42compactrelInOutrealspecial reltol for straight line checking
43compactabsInOutrealspecial abstol for straight line checking


31.4. TRANSMISSION LINES533

31.4.3Tranline - Lossless transmission line

31.4.3.1Tranline instance parameters

#NameDirectionTypeDescription
1z0InOutrealCharacteristic impedance
1zoInOutreal
4fInOutrealFrequency
2tdInOutrealTransmission delay
3nlInOutrealNormalized length at frequency given
5v1InOutrealInitial voltage at end 1
7v2InOutrealInitial voltage at end 2
6i1InOutrealInitial current at end 1
8i2InOutrealInitial current at end 2
9icInreal vectorInitial condition vector:v1,i1,v2,i2
10relOutrealRel. rate of change of deriv. for bkpt
11absOutrealAbs. rate of change of deriv. for bkpt
12pos_node1OutintegerPositive node of end 1 of t. line
13neg_node1OutintegerNegative node of end 1 of t. line
14pos_node2OutintegerPositive node of end 2 of t. line
15neg_node2OutintegerNegative node of end 2 of t. line
18delaysOutreal vectorDelayed values of excitation


534CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.4.4TransLine - Simple Lossy Transmission Line

31.4.4.1TransLine instance parameters

#NameDirectionTypeDescription
1pos_nodeInintegerPositive node of txl
2neg_nodeInintegerNegative node of txl
3lengthInOutreallength of line

31.4.4.2TransLine model parameters

#NameDirectionTypeDescription
101rInOutrealresistance per length
104lInOutrealinductance per length
102cInOutrealcapacitance per length
103gInOutrealconductance per length
105lengthInOutreallength
106txlInf l agDevice is a txl model


31.4. TRANSMISSION LINES535

31.4.5URC - Uniform R. C. line

31.4.5.1URC instance parameters

#NameDirectionTypeDescription
1lInOutrealLength of transmission line
2nInOutrealNumber of lumps
3pos_nodeOutintegerPositive node of URC
4neg_nodeOutintegerNegative node of URC
5gndOutintegerGround node of URC

31.4.5.2URC model parameters

#NameDirectionTypeDescription
101kInOutrealPropagation constant
102fmaxInOutrealMaximum frequency of interest
103rperlInOutrealResistance per unit length
104cperlInOutrealCapacitance per unit length
105isperlInOutrealSaturation current per length
106rsperlInOutrealDiode resistance per length
107urcInf l agUniform R.C. line model


536CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.5BJTs

31.5.1BJT - Bipolar Junction Transistor

31.5.1.1BJT instance parameters

#NameDirectionTypeDescription
2offInOutf l agDevice initially off
3icvbeInOutrealInitial B-E voltage
4icvceInOutrealInitial C-E voltage
1areaInOutreal(Emitter) Area factor
10areabInOutrealBase area factor
11areacInOutrealCollector area factor
9mInOutrealParallel Multiplier
5icInreal vectorInitial condition vector
6sens_areaInf l agf l ag to request sensitivity WRT area
202colnodeOutintegerNumber of collector node
203basenodeOutintegerNumber of base node
204emitnodeOutintegerNumber of emitter node
205substnodeOutintegerNumber of substrate node
206colprimenodeOutintegerInternal collector node
207baseprimenodeOutintegerInternal base node
208emitprimenodeOutintegerInternal emitter node
211icOutrealCurrent at collector node
212ibOutrealCurrent at base node
236ieOutrealEmitter current
237isOutrealSubstrate current
209vbeOutrealB-E voltage
210vbcOutrealB-C voltage
215gmOutrealSmall signal transconductance
213gpiOutrealSmall signal input conductance - pi
214gmuOutrealSmall signal conductance - mu
225gxOutrealConductance from base to internal base
216goOutrealSmall signal output conductance
227geqcbOutreald(Ibe)/d(Vbc)
228gccsOutrealInternal C-S cap. equiv. cond.
229geqbxOutrealInternal C-B-base cap. equiv. cond.
239cpiOutrealInternal base to emitter capactance
240cmuOutrealInternal base to collector capactiance
241cbxOutrealBase to collector capacitance
242ccsOutrealCollector to substrate capacitance
218cqbeOutrealCap. due to charge storage in B-E jct.
220cqbcOutrealCap. due to charge storage in B-C jct.
222cqcsOutrealCap. due to charge storage in C-S jct.
224cqbxOutrealCap. due to charge storage in B-X jct.
226cexbcOutrealTotal Capacitance in B-X junction


31.5. BJTS537

217qbeOutrealCharge storage B-E junction
219qbcOutrealCharge storage B-C junction
221qcsOutrealCharge storage C-S junction
223qbxOutrealCharge storage B-X junction
238pOutrealPower dissipation
235sens_dcOutrealdc sensitivity
230sens_realOutrealreal part of ac sensitivity
231sens_imagOutrealdc sens. & imag part of ac sens.
232sens_magOutrealsensitivity of ac magnitude
233sens_phOutrealsensitivity of ac phase
234sens_cplxOutcomplexac sensitivity
7tempInOutrealinstance temperature
8dtempInOutrealinstance temperature delta from circuit

31.5.1.2BJT model parameters

#NameDirectionTypeDescription
309typeOutstringNPN or PNP
101npnInOutf l agNPN type device
102pnpInOutf l agPNP type device
103isInOutrealSaturation Current
104bfInOutrealIdeal forward beta
105nfInOutrealForward emission coeff i cient
106vafInOutrealForward Early voltage
106vaInOutreal
107ikfInOutrealForward beta roll-off corner current
107ikInOutreal
108iseInOutrealB-E leakage saturation current
110neInOutrealB-E leakage emission coeff i cient
111brInOutrealIdeal reverse beta
112nrInOutrealReverse emission coeff i cient
113varInOutrealReverse Early voltage
113vbInOutreal
114ikrInOutrealreverse beta roll-off corner current
115iscInOutrealB-C leakage saturation current
117ncInOutrealB-C leakage emission coeff i cient
118rbInOutrealZero bias base resistance
119irbInOutrealCurrent for base resistance=(rb+rbm)/2
120rbmInOutrealMinimum base resistance
121reInOutrealEmitter resistance
122rcInOutrealCollector resistance
123cjeInOutrealZero bias B-E depletion capacitance
124vjeInOutrealB-E built in potential
124peInOutreal
125mjeInOutrealB-E junction grading coeff i cient
125meInOutreal


538CHAPTER 31. MODEL AND DEVICE PARAMETERS

126tfInOutrealIdeal forward transit time
127xtfInOutrealCoeff i cient for bias dependence of TF
128vtfInOutrealVoltage giving VBC dependence of TF
129itfInOutrealHigh current dependence of TF
130ptfInOutrealExcess phase
131cjcInOutrealZero bias B-C depletion capacitance
132vjcInOutrealB-C built in potential
132pcInOutreal
133mjcInOutrealB-C junction grading coeff i cient
133mcInOutreal
134xcjcInOutrealFraction of B-C cap to internal base
135trInOutrealIdeal reverse transit time
136cjsInOutrealZero bias C-S capacitance
136ccsInOutrealZero bias C-S capacitance
137vjsInOutrealSubstrate junction built in potential
137psInOutreal
138mjsInOutrealSubstrate junction grading coeff i cient
138msInOutreal
139xtbInOutrealForward and reverse beta temp. exp.
140egInOutrealEnergy gap for IS temp. dependency
141xtiInOutrealTemp. exponent for IS
142fcInOutrealForward bias junction f i t parameter
301invearlyvoltfOutrealInverse early voltage:forward
302invearlyvoltrOutrealInverse early voltage:reverse
303invrollofffOutrealInverse roll off - forward
304invrolloffrOutrealInverse roll off - reverse
305collectorconductOutrealCollector conductance
306emitterconductOutrealEmitter conductance
307transtimevbcfactOutrealTransit time VBC factor
308excessphasefactorOutrealExcess phase fact.
143tnomInOutrealParameter measurement temperature
145kfInOutrealFlicker Noise Coeff i cient
144afInOutrealFlicker Noise Exponent


31.5. BJTS539

31.5.2BJT - Bipolar Junction Transistor Level 2

31.5.2.1BJT2 instance parameters

#NameDirectionTypeDescription
2offInOutf l agDevice initially off
3icvbeInOutrealInitial B-E voltage
4icvceInOutrealInitial C-E voltage
1areaInOutreal(Emitter) Area factor
10areabInOutrealBase area factor
11areacInOutrealCollector area factor
9mInOutrealParallel Multiplier
5icInreal vectorInitial condition vector
6sens_areaInf l agf l ag to request sensitivity WRT area
202colnodeOutintegerNumber of collector node
203basenodeOutintegerNumber of base node
204emitnodeOutintegerNumber of emitter node
205substnodeOutintegerNumber of substrate node
206colprimenodeOutintegerInternal collector node
207baseprimenodeOutintegerInternal base node
208emitprimenodeOutintegerInternal emitter node
211icOutrealCurrent at collector node
212ibOutrealCurrent at base node
236ieOutrealEmitter current
237isOutrealSubstrate current
209vbeOutrealB-E voltage
210vbcOutrealB-C voltage
215gmOutrealSmall signal transconductance
213gpiOutrealSmall signal input conductance - pi
214gmuOutrealSmall signal conductance - mu
225gxOutrealConductance from base to internal base
216goOutrealSmall signal output conductance
227geqcbOutreald(Ibe)/d(Vbc)
228gcsubOutrealInternal Subs. cap. equiv. cond.
243gdsubOutrealInternal Subs. Diode equiv. cond.
229geqbxOutrealInternal C-B-base cap. equiv. cond.
239cpiOutrealInternal base to emitter capactance
240cmuOutrealInternal base to collector capactiance
241cbxOutrealBase to collector capacitance
242csubOutrealSubstrate capacitance
218cqbeOutrealCap. due to charge storage in B-E jct.
220cqbcOutrealCap. due to charge storage in B-C jct.
222cqsubOutrealCap. due to charge storage in Subs. jct.
224cqbxOutrealCap. due to charge storage in B-X jct.
226cexbcOutrealTotal Capacitance in B-X junction
217qbeOutrealCharge storage B-E junction
219qbcOutrealCharge storage B-C junction


540CHAPTER 31. MODEL AND DEVICE PARAMETERS

221qsubOutrealCharge storage Subs. junction
223qbxOutrealCharge storage B-X junction
238pOutrealPower dissipation
235sens_dcOutrealdc sensitivity
230sens_realOutrealreal part of ac sensitivity
231sens_imagOutrealdc sens. & imag part of ac sens.
232sens_magOutrealsensitivity of ac magnitude
233sens_phOutrealsensitivity of ac phase
234sens_cplxOutcomplexac sensitivity
7tempInOutrealinstance temperature
8dtempInOutrealinstance temperature delta from circuit

31.5.2.2BJT2 model parameters

#NameDirectionTypeDescription
309typeOutstringNPN or PNP
101npnInOutf l agNPN type device
102pnpInOutf l agPNP type device
147subsInOutintegerVertical or Lateral device
103isInOutrealSaturation Current
146issInOutrealSubstrate Jct. Saturation Current
104bfInOutrealIdeal forward beta
105nfInOutrealForward emission coeff i cient
106vafInOutrealForward Early voltage
106vaInOutreal
107ikfInOutrealForward beta roll-off corner current
107ikInOutreal
108iseInOutrealB-E leakage saturation current
110neInOutrealB-E leakage emission coeff i cient
111brInOutrealIdeal reverse beta
112nrInOutrealReverse emission coeff i cient
113varInOutrealReverse Early voltage
113vbInOutreal
114ikrInOutrealreverse beta roll-off corner current
115iscInOutrealB-C leakage saturation current
117ncInOutrealB-C leakage emission coeff i cient
118rbInOutrealZero bias base resistance
119irbInOutrealCurrent for base resistance=(rb+rbm)/2
120rbmInOutrealMinimum base resistance
121reInOutrealEmitter resistance
122rcInOutrealCollector resistance
123cjeInOutrealZero bias B-E depletion capacitance
124vjeInOutrealB-E built in potential
124peInOutreal
125mjeInOutrealB-E junction grading coeff i cient
125meInOutreal


31.5. BJTS541

126tfInOutrealIdeal forward transit time
127xtfInOutrealCoeff i cient for bias dependence of TF
128vtfInOutrealVoltage giving VBC dependence of TF
129itfInOutrealHigh current dependence of TF
130ptfInOutrealExcess phase
131cjcInOutrealZero bias B-C depletion capacitance
132vjcInOutrealB-C built in potential
132pcInOutreal
133mjcInOutrealB-C junction grading coeff i cient
133mcInOutreal
134xcjcInOutrealFraction of B-C cap to internal base
135trInOutrealIdeal reverse transit time
136cjsInOutrealZero bias Substrate capacitance
136csubInOutreal
137vjsInOutrealSubstrate junction built in potential
137psInOutreal
138mjsInOutrealSubstrate junction grading coeff i cient
138msInOutreal
139xtbInOutrealForward and reverse beta temp. exp.
140egInOutrealEnergy gap for IS temp. dependency
141xtiInOutrealTemp. exponent for IS
148tre1InOutrealTemp. coeff i cient 1 for RE
149tre2InOutrealTemp. coeff i cient 2 for RE
150trc1InOutrealTemp. coeff i cient 1 for RC
151trc2InOutrealTemp. coeff i cient 2 for RC
152trb1InOutrealTemp. coeff i cient 1 for RB
153trb2InOutrealTemp. coeff i cient 2 for RB
154trbm1InOutrealTemp. coeff i cient 1 for RBM
155trbm2InOutrealTemp. coeff i cient 2 for RBM
142fcInOutrealForward bias junction f i t parameter
301invearlyvoltfOutrealInverse early voltage:forward
302invearlyvoltrOutrealInverse early voltage:reverse
303invrollofffOutrealInverse roll off - forward
304invrolloffrOutrealInverse roll off - reverse
305collectorconductOutrealCollector conductance
306emitterconductOutrealEmitter conductance
307transtimevbcfactOutrealTransit time VBC factor
308excessphasefactorOutrealExcess phase fact.
143tnomInOutrealParameter measurement temperature
145kfInOutrealFlicker Noise Coeff i cient
144afInOutrealFlicker Noise Exponent


542CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.5.3VBIC - Vertical Bipolar Inter-Company Model

31.5.3.1VBIC instance parameters

#NameDirectionTypeDescription
1areaInOutrealArea factor
2offInOutf l agDevice initially off
3icInreal vectorInitial condition vector
4icvbeInOutrealInitial B-E voltage
5icvceInOutrealInitial C-E voltage
6tempInOutrealInstance temperature
7dtempInOutrealInstance delta temperature
8mInOutrealMultiplier
212collnodeOutintegerNumber of collector node
213basenodeOutintegerNumber of base node
214emitnodeOutintegerNumber of emitter node
215subsnodeOutintegerNumber of substrate node
216collCXnodeOutintegerInternal collector node
217collCInodeOutintegerInternal collector node
218baseBXnodeOutintegerInternal base node
219baseBInodeOutintegerInternal base node
220baseBPnodeOutintegerInternal base node
221emitEInodeOutintegerInternal emitter node
222subsSInodeOutintegerInternal substrate node
223vbeOutrealB-E voltage
224vbcOutrealB-C voltage
225icOutrealCollector current
226ibOutrealBase current
227ieOutrealEmitter current
228isOutrealSubstrate current
229gmOutrealSmall signal transconductance dIc/dVbe
230goOutrealSmall signal output conductance dIc/dVbc
231gpiOutrealSmall signal input conductance dIb/dVbe
232gmuOutrealSmall signal conductance dIb/dVbc
233gxOutrealConductance from base to internal base
247cbeOutrealInternal base to emitter capacitance
248cbexOutrealExternal base to emitter capacitance
249cbcOutrealInternal base to collector capacitance
250cbcxOutrealExternal Base to collector capacitance
251cbepOutrealParasitic Base to emitter capacitance
252cbcpOutrealParasitic Base to collector capacitance
259pOutrealPower dissipation
243geqcbOutrealInternal C-B-base cap. equiv. cond.
246geqbxOutrealExternal C-B-base cap. equiv. cond.
234qbeOutrealCharge storage B-E junction
235cqbeOutrealCap. due to charge storage in B-E jct.
236qbcOutrealCharge storage B-C junction


31.5. BJTS543

237cqbcOutrealCap. due to charge storage in B-C jct.
238qbxOutrealCharge storage B-X junction
239cqbxOutrealCap. due to charge storage in B-X jct.
258sens_dcOutrealDC sensitivity
253sens_realOutrealReal part of AC sensitivity
254sens_imagOutrealDC sens. & imag part of AC sens.
255sens_magOutrealSensitivity of AC magnitude
256sens_phOutrealSensitivity of AC phase
257sens_cplxOutcomplexAC sensitivity

31.5.3.2VBIC model parameters

#NameDirectionTypeDescription
305typeOutstringNPN or PNP
101npnInOutf l agNPN type device
102pnpInOutf l agPNP type device
103tnomInOutrealParameter measurement temperature
104rcxInOutrealExtrinsic coll resistance
105rciInOutrealIntrinsic coll resistance
106voInOutrealEpi drift saturation voltage
107gammInOutrealEpi doping parameter
108hrcfInOutrealHigh current RC factor
109rbxInOutrealExtrinsic base resistance
110rbiInOutrealIntrinsic base resistance
111reInOutrealIntrinsic emitter resistance
112rsInOutrealIntrinsic substrate resistance
113rbpInOutrealParasitic base resistance
114isInOutrealTransport saturation current
115nfInOutrealForward emission coeff i cient
116nrInOutrealReverse emission coeff i cient
117fcInOutrealFwd bias depletion capacitance limit
118cbeoInOutrealExtrinsic B-E overlap capacitance
119cjeInOutrealZero bias B-E depletion capacitance
120peInOutrealB-E built in potential
121meInOutrealB-E junction grading coeff i cient
122ajeInOutrealB-E capacitance smoothing factor
123cbcoInOutrealExtrinsic B-C overlap capacitance
124cjcInOutrealZero bias B-C depletion capacitance
125qcoInOutrealEpi charge parameter
126cjepInOutrealB-C extrinsic zero bias capacitance
127pcInOutrealB-C built in potential
128mcInOutrealB-C junction grading coeff i cient
129ajcInOutrealB-C capacitance smoothing factor
130cjcpInOutrealZero bias S-C capacitance
131psInOutrealS-C junction built in potential
132msInOutrealS-C junction grading coeff i cient


544CHAPTER 31. MODEL AND DEVICE PARAMETERS

133ajsInOutrealS-C capacitance smoothing factor
134ibeiInOutrealIdeal B-E saturation current
135wbeInOutrealPortion of IBEI from Vbei, 1-WBE from Vbex
136neiInOutrealIdeal B-E emission coeff i cient
137ibenInOutrealNon-ideal B-E saturation current
138nenInOutrealNon-ideal B-E emission coeff i cient
139ibciInOutrealIdeal B-C saturation current
140nciInOutrealIdeal B-C emission coeff i cient
141ibcnInOutrealNon-ideal B-C saturation current
142ncnInOutrealNon-ideal B-C emission coeff i cient
143avc1InOutrealB-C weak avalanche parameter 1
144avc2InOutrealB-C weak avalanche parameter 2
145ispInOutrealParasitic transport saturation current
146wspInOutrealPortion of ICCP
147nfpInOutrealParasitic fwd emission coeff i cient
148ibeipInOutrealIdeal parasitic B-E saturation current
149ibenpInOutrealNon-ideal parasitic B-E saturation current
150ibcipInOutrealIdeal parasitic B-C saturation current
151ncipInOutrealIdeal parasitic B-C emission coeff i cient
152ibcnpInOutrealNonideal parasitic B-C saturation current
153ncnpInOutrealNonideal parasitic B-C emission coeff i cient
154vefInOutrealForward Early voltage
155verInOutrealReverse Early voltage
156ikfInOutrealForward knee current
157ikrInOutrealReverse knee current
158ikpInOutrealParasitic knee current
159tfInOutrealIdeal forward transit time
160qtfInOutrealVariation of TF with base-width modulation
161xtfInOutrealCoeff i cient for bias dependence of TF
162vtfInOutrealVoltage giving VBC dependence of TF
163itfInOutrealHigh current dependence of TF
164trInOutrealIdeal reverse transit time
165tdInOutrealForward excess-phase delay time
166kfnInOutrealB-E Flicker Noise Coeff i cient
167afnInOutrealB-E Flicker Noise Exponent
168bfnInOutrealB-E Flicker Noise 1/f dependence
169xreInOutrealTemperature exponent of RE
170xrbInOutrealTemperature exponent of RB
171xrbiInOutrealTemperature exponent of RBI
172xrcInOutrealTemperature exponent of RC
173xrciInOutrealTemperature exponent of RCI
174xrsInOutrealTemperature exponent of RS
175xvoInOutrealTemperature exponent of VO
176eaInOutrealActivation energy for IS
177eaieInOutrealActivation energy for IBEI
179eaicInOutrealActivation energy for IBCI/IBEIP


31.5. BJTS545

179eaisInOutrealActivation energy for IBCIP
180eaneInOutrealActivation energy for IBEN
181eancInOutrealActivation energy for IBCN/IBENP
182eansInOutrealActivation energy for IBCNP
183xisInOutrealTemperature exponent of IS
184xiiInOutrealTemperature exponent of IBEI,IBCI,IBEIP,IBCIP
185xinInOutrealTemperature exponent of IBEN,IBCN,IBENP,IBCNP
186tnfInOutrealTemperature exponent of NF
187tavcInOutrealTemperature exponent of AVC2
188rthInOutrealThermal resistance
189cthInOutrealThermal capacitance
190vrtInOutrealPunch-through voltage of internal B-C junction
191artInOutrealSmoothing parameter for reach-through
192ccsoInOutrealFixed C-S capacitance
193qbmInOutrealSelect SGP qb formulation
194nkfInOutrealHigh current beta rolloff
195xikfInOutrealTemperature exponent of IKF
196xrcxInOutrealTemperature exponent of RCX
197xrbxInOutrealTemperature exponent of RBX
198xrbpInOutrealTemperature exponent of RBP
199isrrInOutrealSeparate IS for fwd and rev
200xisrInOutrealTemperature exponent of ISR
201dearInOutrealDelta activation energy for ISRR
202eapInOutrealExitivation energy for ISP
203vbbeInOutrealB-E breakdown voltage
204nbbeInOutrealB-E breakdown emission coeff i cient
205ibbeInOutrealB-E breakdown current
206tvbbe1InOutrealLinear temperature coeff i cient of VBBE
207tvbbe2InOutrealQuadratic temperature coeff i cient of VBBE
208tnbbeInOutrealTemperature coeff i cient of NBBE
209ebbeInOutrealexp(-VBBE/(NBBE*Vtv))
210dtempInOutrealLocale Temperature difference
211versInOutrealRevision Version
212vrefInOutrealReference Version


546CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.6MOSFETs

31.6.1MOS1 - Level 1 MOSFET model with Meyer capacitance model

31.6.1.1MOS1 instance parameters

#NameDirectionTypeDescription
21mInOutrealMultiplier
2lInOutrealLength
1wInOutrealWidth
4adInOutrealDrain area
3asInOutrealSource area
6pdInOutrealDrain perimeter
5psInOutrealSource perimeter
8nrdInOutrealDrain squares
7nrsInOutrealSource squares
9offInf l agDevice initially off
12icvdsInOutrealInitial D-S voltage
13icvgsInOutrealInitial G-S voltage
11icvbsInOutrealInitial B-S voltage
20tempInOutrealInstance temperature
22dtempInOutrealInstance temperature difference
10icInreal vectorVector of D-S, G-S, B-S voltages
15sens_lInf l agf l ag to request sensitivity WRT length
14sens_wInf l agf l ag to request sensitivity WRT width
215idOutrealDrain current
18isOutrealSource current
17igOutrealGate current
16ibOutrealBulk current
217ibdOutrealB-D junction current
216ibsOutrealB-S junction current
231vgsOutrealGate-Source voltage
232vdsOutrealDrain-Source voltage
230vbsOutrealBulk-Source voltage
229vbdOutrealBulk-Drain voltage
203dnodeOutintegerNumber of the drain node
204gnodeOutintegerNumber of the gate node
205snodeOutintegerNumber of the source node
206bnodeOutintegerNumber of the node
207dnodeprimeOutintegerNumber of int. drain node
208snodeprimeOutintegerNumber of int. source node
211vonOutreal
212vdsatOutrealSaturation drain voltage
213sourcevcritOutrealCritical source voltage
214drainvcritOutrealCritical drain voltage
#NameDirectionTypeDescription


31.6. MOSFETS547

#NameDirectionTypeDescription
258rsOutrealSource resistance
209sourceconductanceOutrealConductance of source
259rdOutrealDrain conductance
210drainconductanceOutrealConductance of drain
219gmOutrealTransconductance
220gdsOutrealDrain-Source conductance
218gmbOutrealBulk-Source transconductance
218gmbsOutreal
221gbdOutrealBulk-Drain conductance
222gbsOutrealBulk-Source conductance
223cbdOutrealBulk-Drain capacitance
224cbsOutrealBulk-Source capacitance
233cgsOutrealGate-Source capacitance
236cgdOutrealGate-Drain capacitance
239cgbOutrealGate-Bulk capacitance
235cqgsOutrealCapacitance due to gate-source charge storage
238cqgdOutrealCapacitance due to gate-drain charge storage
241cqgbOutrealCapacitance due to gate-bulk charge storage
243cqbdOutrealCapacitance due to bulk-drain charge storage
245cqbsOutrealCapacitance due to bulk-source charge storage
225cbd0OutrealZero-Bias B-D junction capacitance
226cbdsw0Outreal
227cbs0OutrealZero-Bias B-S junction capacitance
228cbssw0Outreal
234qgsOutrealGate-Source charge storage
237qgdOutrealGate-Drain charge storage
240qgbOutrealGate-Bulk charge storage
242qbdOutrealBulk-Drain charge storage
244qbsOutrealBulk-Source charge storage
19pOutrealInstaneous power
256sens_l_dcOutrealdc sensitivity wrt length
246sens_l_realOutrealreal part of ac sensitivity wrt length
247sens_l_imagOutrealimag part of ac sensitivity wrt length
248sens_l_magOutrealsensitivity wrt l of ac magnitude
249sens_l_phOutrealsensitivity wrt l of ac phase
250sens_l_cplxOutcomplexac sensitivity wrt length
257sens_w_dcOutrealdc sensitivity wrt width
251sens_w_realOutrealreal part of ac sensitivity wrt width
252sens_w_imagOutrealimag part of ac sensitivity wrt width
253sens_w_magOutrealsensitivity wrt w of ac magnitude
254sens_w_phOutrealsensitivity wrt w of ac phase
255sens_w_cplxOutcomplexac sensitivity wrt width
#NameDirectionTypeDescription

31.6.1.2MOS1 model parameters


548CHAPTER 31. MODEL AND DEVICE PARAMETERS

#NameDirectionTypeDescription
133typeOutstringN-channel or P-channel MOS
101vtoInOutrealThreshold voltage
101vt0InOutreal
102kpInOutrealTransconductance parameter
103gammaInOutrealBulk threshold parameter
104phiInOutrealSurface potential
105lambdaInOutrealChannel length modulation
106rdInOutrealDrain ohmic resistance
107rsInOutrealSource ohmic resistance
108cbdInOutrealB-D junction capacitance
109cbsInOutrealB-S junction capacitance
110isInOutrealBulk junction sat. current
111pbInOutrealBulk junction potential
112cgsoInOutrealGate-source overlap cap.
113cgdoInOutrealGate-drain overlap cap.
114cgboInOutrealGate-bulk overlap cap.
122rshInOutrealSheet resistance
115cjInOutrealBottom junction cap per area
116mjInOutrealBottom grading coeff i cient
117cjswInOutrealSide junction cap per area
118mjswInOutrealSide grading coeff i cient
119jsInOutrealBulk jct. sat. current density
120toxInOutrealOxide thickness
121ldInOutrealLateral diffusion
123u0InOutrealSurface mobility
123uoInOutreal
124fcInOutrealForward bias jct. f i t parm.
128nmosInf l agN type MOSfet model
129pmosInf l agP type MOSfet model
125nsubInOutrealSubstrate doping
126tpgInOutintegerGate type
127nssInOutrealSurface state density
130tnomInOutrealParameter measurement temperature
131kfInOutrealFlicker noise coeff i cient
132afInOutrealFlicker noise exponent


31.6. MOSFETS549

31.6.2MOS2 - Level 2 MOSFET model with Meyer capacitance model

31.6.2.1MOS 2 instance parameters

#NameDirectionTypeDescription
80mInOutrealMultiplier
2lInOutrealLength
1wInOutrealWidth
4adInOutrealDrain area
3asInOutrealSource area
6pdInOutrealDrain perimeter
5psInOutrealSource perimeter
34idOutrealDrain current
34cdOutreal
36ibdOutrealB-D junction current
35ibsOutrealB-S junction current
18isOutrealSource current
17igOutrealGate current
16ibOutrealBulk current
50vgsOutrealGate-Source voltage
51vdsOutrealDrain-Source voltage
49vbsOutrealBulk-Source voltage
48vbdOutrealBulk-Drain voltage
8nrdInOutrealDrain squares
7nrsInOutrealSource squares
9offInf l agDevice initially off
12icvdsInOutrealInitial D-S voltage
13icvgsInOutrealInitial G-S voltage
11icvbsInOutrealInitial B-S voltage
77tempInOutrealInstance operating temperature
81dtempInOutrealInstance temperature difference
10icInreal vectorVector of D-S, G-S, B-S voltages
15sens_lInf l agf l ag to request sensitivity WRT
length
14sens_wInf l agf l ag to request sensitivity WRT
width
22dnodeOutintegerNumber of drain node
23gnodeOutintegerNumber of gate node
24snodeOutintegerNumber of source node
25bnodeOutintegerNumber of bulk node
26dnodeprimeOutintegerNumber of internal drain node
27snodeprimeOutintegerNumber of internal source node
30vonOutreal
31vdsatOutrealSaturation drain voltage
32sourcevcritOutrealCritical source voltage
33drainvcritOutrealCritical drain voltage
78rsOutrealSource resistance


550CHAPTER 31. MODEL AND DEVICE PARAMETERS

28sourceconductanceOutrealSource conductance
79rdOutrealDrain resistance
29drainconductanceOutrealDrain conductance
38gmOutrealTransconductance
39gdsOutrealDrain-Source conductance
37gmbOutrealBulk-Source transconductance
37gmbsOutreal
40gbdOutrealBulk-Drain conductance
41gbsOutrealBulk-Source conductance
42cbdOutrealBulk-Drain capacitance
43cbsOutrealBulk-Source capacitance
52cgsOutrealGate-Source capacitance
55cgdOutrealGate-Drain capacitance
58cgbOutrealGate-Bulk capacitance
44cbd0OutrealZero-Bias B-D junction
capacitance
45cbdsw0Outreal
46cbs0OutrealZero-Bias B-S junction capacitance
47cbssw0Outreal
54cqgsOutrealCapacitance due to gate-source
charge storage
57cqgdOutrealCapacitance due to gate-drain
charge storage
60cqgbOutrealCapacitance due to gate-bulk
charge storage
62cqbdOutrealCapacitance due to bulk-drain
charge storage
64cqbsOutrealCapacitance due to bulk-source
charge storage
53qgsOutrealGate-Source charge storage
56qgdOutrealGate-Drain charge storage
59qgbOutrealGate-Bulk charge storage
61qbdOutrealBulk-Drain charge storage
63qbsOutrealBulk-Source charge storage
19pOutrealInstantaneous power
75sens_l_dcOutrealdc sensitivity wrt length
70sens_l_realOutrealreal part of ac sensitivity wrt length
71sens_l_imagOutrealimag part of ac sensitivity wrt
length
74sens_l_cplxOutcomplexac sensitivity wrt length
72sens_l_magOutrealsensitivity wrt l of ac magnitude
73sens_l_phOutrealsensitivity wrt l of ac phase
76sens_w_dcOutrealdc sensitivity wrt width
65sens_w_realOutrealdc sensitivity and real part of ac
sensitivity wrt width


31.6. MOSFETS551

66sens_w_imagOutrealimag part of ac sensitivity wrt
width
67sens_w_magOutrealsensitivity wrt w of ac magnitude
68sens_w_phOutrealsensitivity wrt w of ac phase
69sens_w_cplxOutcomplexac sensitivity wrt width

31.6.2.2MOS2 model parameters

#NameDirectionTypeDescription
141typeOutstringN-channel or P-channel MOS
101vtoInOutrealThreshold voltage
101vt0InOutreal
102kpInOutrealTransconductance parameter
103gammaInOutrealBulk threshold parameter
104phiInOutrealSurface potential
105lambdaInOutrealChannel length modulation
106rdInOutrealDrain ohmic resistance
107rsInOutrealSource ohmic resistance
108cbdInOutrealB-D junction capacitance
109cbsInOutrealB-S junction capacitance
110isInOutrealBulk junction sat. current
111pbInOutrealBulk junction potential
112cgsoInOutrealGate-source overlap cap.
113cgdoInOutrealGate-drain overlap cap.
114cgboInOutrealGate-bulk overlap cap.
122rshInOutrealSheet resistance
115cjInOutrealBottom junction cap per area
116mjInOutrealBottom grading coeff i cient
117cjswInOutrealSide junction cap per area
118mjswInOutrealSide grading coeff i cient
119jsInOutrealBulk jct. sat. current density
120toxInOutrealOxide thickness
121ldInOutrealLateral diffusion
123u0InOutrealSurface mobility
123uoInOutreal
124fcInOutrealForward bias jct. f i t parm.
135nmosInf l agN type MOSfet model
136pmosInf l agP type MOSfet model
125nsubInOutrealSubstrate doping
126tpgInOutintegerGate type
127nssInOutrealSurface state density
129deltaInOutrealWidth effect on threshold
130uexpInOutrealCrit. f i eld exp for mob. deg.
134ucritInOutrealCrit. f i eld for mob. degradation
131vmaxInOutrealMaximum carrier drift velocity
132xjInOutrealJunction depth


552CHAPTER 31. MODEL AND DEVICE PARAMETERS

133neffInOutrealTotal channel charge coeff.
128nfsInOutrealFast surface state density
137tnomInOutrealParameter measurement temperature
139kfInOutrealFlicker noise coeff i cient
140afInOutrealFlicker noise exponent


31.6. MOSFETS553

31.6.3MOS3 - Level 3 MOSFET model with Meyer capacitance model

31.6.3.1MOS3 instance parameters

#NameDirectionTypeDescription
80mInOutrealMultiplier
2lInOutrealLength
1wInOutrealWidth
4adInOutrealDrain area
3asInOutrealSource area
6pdInOutrealDrain perimeter
5psInOutrealSource perimeter
34idOutrealDrain current
34cdOutrealDrain current
36ibdOutrealB-D junction current
35ibsOutrealB-S junction current
18isOutrealSource current
17igOutrealGate current
16ibOutrealBulk current
50vgsOutrealGate-Source voltage
51vdsOutrealDrain-Source voltage
49vbsOutrealBulk-Source voltage
48vbdOutrealBulk-Drain voltage
8nrdInOutrealDrain squares
7nrsInOutrealSource squares
9offInf l agDevice initially off
12icvdsInOutrealInitial D-S voltage
13icvgsInOutrealInitial G-S voltage
11icvbsInOutrealInitial B-S voltage
10icInOutreal vectorVector of D-S, G-S, B-S voltages
77tempInOutrealInstance operating temperature
81dtempInOutrealInstance temperature difference
15sens_lInf l agf l ag to request sensitivity WRT length
14sens_wInf l agf l ag to request sensitivity WRT width
22dnodeOutintegerNumber of drain node
23gnodeOutintegerNumber of gate node
24snodeOutintegerNumber of source node
25bnodeOutintegerNumber of bulk node
26dnodeprimeOutintegerNumber of internal drain node
27snodeprimeOutintegerNumber of internal source node
30vonOutrealTurn-on voltage
31vdsatOutrealSaturation drain voltage
32sourcevcritOutrealCritical source voltage
33drainvcritOutrealCritical drain voltage
78rsOutrealSource resistance
28sourceconductanceOutrealSource conductance
79rdOutrealDrain resistance


554CHAPTER 31. MODEL AND DEVICE PARAMETERS

29drainconductanceOutrealDrain conductance
38gmOutrealTransconductance
39gdsOutrealDrain-Source conductance
37gmbOutrealBulk-Source transconductance
37gmbsOutrealBulk-Source transconductance
40gbdOutrealBulk-Drain conductance
41gbsOutrealBulk-Source conductance
42cbdOutrealBulk-Drain capacitance
43cbsOutrealBulk-Source capacitance
52cgsOutrealGate-Source capacitance
55cgdOutrealGate-Drain capacitance
58cgbOutrealGate-Bulk capacitance
54cqgsOutrealCapacitance due to gate-source charge storage
57cqgdOutrealCapacitance due to gate-drain charge storage
60cqgbOutrealCapacitance due to gate-bulk charge storage
62cqbdOutrealCapacitance due to bulk-drain charge storage
64cqbsOutrealCapacitance due to bulk-source charge storage
44cbd0OutrealZero-Bias B-D junction capacitance
45cbdsw0OutrealZero-Bias B-D sidewall capacitance
46cbs0OutrealZero-Bias B-S junction capacitance
47cbssw0OutrealZero-Bias B-S sidewall capacitance
63qbsOutrealBulk-Source charge storage
53qgsOutrealGate-Source charge storage
56qgdOutrealGate-Drain charge storage
59qgbOutrealGate-Bulk charge storage
61qbdOutrealBulk-Drain charge storage
19pOutrealInstantaneous power
76sens_l_dcOutrealdc sensitivity wrt length
70sens_l_realOutrealreal part of ac sensitivity wrt length
71sens_l_imagOutrealimag part of ac sensitivity wrt length
74sens_l_cplxOutcomplexac sensitivity wrt length
72sens_l_magOutrealsensitivity wrt l of ac magnitude
73sens_l_phOutrealsensitivity wrt l of ac phase
75sens_w_dcOutrealdc sensitivity wrt width
65sens_w_realOutrealreal part of ac sensitivity wrt width
66sens_w_imagOutrealimag part of ac sensitivity wrt width
67sens_w_magOutrealsensitivity wrt w of ac magnitude
68sens_w_phOutrealsensitivity wrt w of ac phase
69sens_w_cplxOutcomplexac sensitivity wrt width


31.6. MOSFETS555


556CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.6.3.2MOS3 model parameters

#NameDirectionTypeDescription
144typeOutstringN-channel or P-channel MOS
133nmosInf l agN type MOSfet model
134pmosInf l agP type MOSfet model
101vtoInOutrealThreshold voltage
101vt0InOutreal
102kpInOutrealTransconductance parameter
103gammaInOutrealBulk threshold parameter
104phiInOutrealSurface potential
105rdInOutrealDrain ohmic resistance
106rsInOutrealSource ohmic resistance
107cbdInOutrealB-D junction capacitance
108cbsInOutrealB-S junction capacitance
109isInOutrealBulk junction sat. current
110pbInOutrealBulk junction potential
111cgsoInOutrealGate-source overlap cap.
112cgdoInOutrealGate-drain overlap cap.
113cgboInOutrealGate-bulk overlap cap.
114rshInOutrealSheet resistance
115cjInOutrealBottom junction cap per area
116mjInOutrealBottom grading coeff i cient
117cjswInOutrealSide junction cap per area
118mjswInOutrealSide grading coeff i cient
119jsInOutrealBulk jct. sat. current density
120toxInOutrealOxide thickness
121ldInOutrealLateral diffusion
145xlInOutrealLength mask adjustment
146wdInOutrealWidth Narrowing (Diffusion)
147xwInOutrealWidth mask adjustment
148delvtoInOutrealThreshold voltage Adjust
148delvt0InOutreal
122u0InOutrealSurface mobility
122uoInOutreal
123fcInOutrealForward bias jct. f i t parm.
124nsubInOutrealSubstrate doping
125tpgInOutintegerGate type
126nssInOutrealSurface state density
131vmaxInOutrealMaximum carrier drift velocity
135xjInOutrealJunction depth
129nfsInOutrealFast surface state density
138xdInOutrealDepletion layer width
139alphaInOutrealAlpha
127etaInOutrealVds dependence of threshold voltage
128deltaInOutrealWidth effect on threshold
140input_deltaInOutreal
130thetaInOutrealVgs dependence on mobility
132kappaInOutrealKappa
141tnomInOutrealParameter measurement temperature
142kfInOutrealFlicker noise coeff i cient
143afInOutrealFlicker noise exponent


31.6. MOSFETS557

31.6.4MOS6 - Level 6 MOSFET model with Meyer capacitance model

31.6.4.1MOS6 instance parameters

#NameDirectionTypeDescription
2lInOutrealLength
1wInOutrealWidth
22mInOutrealParallel Multiplier
4adInOutrealDrain area
3asInOutrealSource area
6pdInOutrealDrain perimeter
5psInOutrealSource perimeter
215idOutrealDrain current
215cdOutrealDrain current
18isOutrealSource current
17igOutrealGate current
16ibOutrealBulk current
216ibsOutrealB-S junction capacitance
217ibdOutrealB-D junction capacitance
231vgsOutrealGate-Source voltage
232vdsOutrealDrain-Source voltage
230vbsOutrealBulk-Source voltage
229vbdOutrealBulk-Drain voltage
8nrdInOutrealDrain squares
7nrsInOutrealSource squares
9offInf l agDevice initially off
12icvdsInOutrealInitial D-S voltage
13icvgsInOutrealInitial G-S voltage
11icvbsInOutrealInitial B-S voltage
20tempInOutrealInstance temperature
21dtempInOutrealInstance temperature difference
10icInreal vectorVector of D-S, G-S, B-S voltages
15sens_lInf l agf l ag to request sensitivity WRT length
14sens_wInf l agf l ag to request sensitivity WRT width
203dnodeOutintegerNumber of the drain node
204gnodeOutintegerNumber of the gate node
205snodeOutintegerNumber of the source node
206bnodeOutintegerNumber of the node
207dnodeprimeOutintegerNumber of int. drain node
208snodeprimeOutintegerNumber of int. source node
258rsOutrealSource resistance
209sourceconductanceOutrealSource conductance
259rdOutrealDrain resistance
210drainconductanceOutrealDrain conductance
211vonOutrealTurn-on voltage
212vdsatOutrealSaturation drain voltage
213sourcevcritOutrealCritical source voltage


558CHAPTER 31. MODEL AND DEVICE PARAMETERS

214drainvcritOutrealCritical drain voltage
218gmbsOutrealBulk-Source transconductance
219gmOutrealTransconductance
220gdsOutrealDrain-Source conductance
221gbdOutrealBulk-Drain conductance
222gbsOutrealBulk-Source conductance
233cgsOutrealGate-Source capacitance
236cgdOutrealGate-Drain capacitance
239cgbOutrealGate-Bulk capacitance
223cbdOutrealBulk-Drain capacitance
224cbsOutrealBulk-Source capacitance
225cbd0OutrealZero-Bias B-D junction capacitance
226cbdsw0Outreal
227cbs0OutrealZero-Bias B-S junction capacitance
228cbssw0Outreal
235cqgsOutrealCapacitance due to gate-source charge storage
238cqgdOutrealCapacitance due to gate-drain charge storage
241cqgbOutrealCapacitance due to gate-bulk charge storage
243cqbdOutrealCapacitance due to bulk-drain charge storage
245cqbsOutrealCapacitance due to bulk-source charge storage
234qgsOutrealGate-Source charge storage
237qgdOutrealGate-Drain charge storage
240qgbOutrealGate-Bulk charge storage
242qbdOutrealBulk-Drain charge storage
244qbsOutrealBulk-Source charge storage
19pOutrealInstaneous power
256sens_l_dcOutrealdc sensitivity wrt length
246sens_l_realOutrealreal part of ac sensitivity wrt length
247sens_l_imagOutrealimag part of ac sensitivity wrt length
248sens_l_magOutrealsensitivity wrt l of ac magnitude
249sens_l_phOutrealsensitivity wrt l of ac phase
250sens_l_cplxOutcomplexac sensitivity wrt length
257sens_w_dcOutrealdc sensitivity wrt width
251sens_w_realOutrealreal part of ac sensitivity wrt width
252sens_w_imagOutrealimag part of ac sensitivity wrt width
253sens_w_magOutrealsensitivity wrt w of ac magnitude
254sens_w_phOutrealsensitivity wrt w of ac phase
255sens_w_cplxOutcomplexac sensitivity wrt width


31.6. MOSFETS559

31.6.4.2MOS6 model parameters

#NameDirectionTypeDescription
140typeOutstringN-channel or P-channel MOS
101vtoInOutrealThreshold voltage
101vt0InOutreal
102kvInOutrealSaturation voltage factor
103nvInOutrealSaturation voltage coeff.
104kcInOutrealSaturation current factor
105ncInOutrealSaturation current coeff.
106nvthInOutrealThreshold voltage coeff.
107psInOutrealSat. current modif i cation par.
108gammaInOutrealBulk threshold parameter
109gamma1InOutrealBulk threshold parameter 1
110sigmaInOutrealStatic feedback effect par.
111phiInOutrealSurface potential
112lambdaInOutrealChannel length modulation param.
113lambda0InOutrealChannel length modulation param. 0
114lambda1InOutrealChannel length modulation param. 1
115rdInOutrealDrain ohmic resistance
116rsInOutrealSource ohmic resistance
117cbdInOutrealB-D junction capacitance
118cbsInOutrealB-S junction capacitance
119isInOutrealBulk junction sat. current
120pbInOutrealBulk junction potential
121cgsoInOutrealGate-source overlap cap.
122cgdoInOutrealGate-drain overlap cap.
123cgboInOutrealGate-bulk overlap cap.
131rshInOutrealSheet resistance
124cjInOutrealBottom junction cap per area
125mjInOutrealBottom grading coeff i cient
126cjswInOutrealSide junction cap per area
127mjswInOutrealSide grading coeff i cient
128jsInOutrealBulk jct. sat. current density
130ldInOutrealLateral diffusion
129toxInOutrealOxide thickness
132u0InOutrealSurface mobility
132uoInOutreal
133fcInOutrealForward bias jct. f i t parm.
137nmosInf l agN type MOSfet model
138pmosInf l agP type MOSfet model
135tpgInOutintegerGate type
134nsubInOutrealSubstrate doping
136nssInOutrealSurface state density
139tnomInOutrealParameter measurement temperature


560CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.6.5MOS9 - Modif i ed Level 3 MOSFET model

31.6.5.1MOS9 instance parameters

#NameDirectionTypeDescription
80mInOutrealMultiplier
2lInOutrealLength
1wInOutrealWidth
4adInOutrealDrain area
3asInOutrealSource area
6pdInOutrealDrain perimeter
5psInOutrealSource perimeter
34idOutrealDrain current
34cdOutrealDrain current
36ibdOutrealB-D junction current
35ibsOutrealB-S junction current
18isOutrealSource current
17igOutrealGate current
16ibOutrealBulk current
50vgsOutrealGate-Source voltage
51vdsOutrealDrain-Source voltage
49vbsOutrealBulk-Source voltage
48vbdOutrealBulk-Drain voltage
8nrdInOutrealDrain squares
7nrsInOutrealSource squares
9offInf l agDevice initially off
12icvdsInOutrealInitial D-S voltage
13icvgsInOutrealInitial G-S voltage
11icvbsInOutrealInitial B-S voltage
10icInOutreal vectorVector of D-S, G-S, B-S voltages
77tempInOutrealInstance operating temperature
81dtempInOutrealInstance operating temperature difference
15sens_lInf l agf l ag to request sensitivity WRT length
14sens_wInf l agf l ag to request sensitivity WRT width
22dnodeOutintegerNumber of drain node
23gnodeOutintegerNumber of gate node
24snodeOutintegerNumber of source node
25bnodeOutintegerNumber of bulk node
26dnodeprimeOutintegerNumber of internal drain node
27snodeprimeOutintegerNumber of internal source node
30vonOutrealTurn-on voltage
31vdsatOutrealSaturation drain voltage
32sourcevcritOutrealCritical source voltage
33drainvcritOutrealCritical drain voltage
78rsOutrealSource resistance
28sourceconductanceOutrealSource conductance
79rdOutrealDrain resistance


31.6. MOSFETS561

29drainconductanceOutrealDrain conductance
38gmOutrealTransconductance
39gdsOutrealDrain-Source conductance
37gmbOutrealBulk-Source transconductance
37gmbsOutrealBulk-Source transconductance
40gbdOutrealBulk-Drain conductance
41gbsOutrealBulk-Source conductance
42cbdOutrealBulk-Drain capacitance
43cbsOutrealBulk-Source capacitance
52cgsOutrealGate-Source capacitance
55cgdOutrealGate-Drain capacitance
58cgbOutrealGate-Bulk capacitance
54cqgsOutrealCapacitance due to gate-source charge storage
57cqgdOutrealCapacitance due to gate-drain charge storage
60cqgbOutrealCapacitance due to gate-bulk charge storage
62cqbdOutrealCapacitance due to bulk-drain charge storage
64cqbsOutrealCapacitance due to bulk-source charge storage
44cbd0OutrealZero-Bias B-D junction capacitance
45cbdsw0OutrealZero-Bias B-D sidewall capacitance
46cbs0OutrealZero-Bias B-S junction capacitance
47cbssw0OutrealZero-Bias B-S sidewall capacitance
63qbsOutrealBulk-Source charge storage
53qgsOutrealGate-Source charge storage
56qgdOutrealGate-Drain charge storage
59qgbOutrealGate-Bulk charge storage
61qbdOutrealBulk-Drain charge storage
19pOutrealInstantaneous power
76sens_l_dcOutrealdc sensitivity wrt length
70sens_l_realOutrealreal part of ac sensitivity wrt length
71sens_l_imagOutrealimag part of ac sensitivity wrt length
74sens_l_cplxOutcomplexac sensitivity wrt length
72sens_l_magOutrealsensitivity wrt l of ac magnitude
73sens_l_phOutrealsensitivity wrt l of ac phase
75sens_w_dcOutrealdc sensitivity wrt width
65sens_w_realOutrealreal part of ac sensitivity wrt width
66sens_w_imagOutrealimag part of ac sensitivity wrt width
67sens_w_magOutrealsensitivity wrt w of ac magnitude
68sens_w_phOutrealsensitivity wrt w of ac phase
69sens_w_cplxOutcomplexac sensitivity wrt width


562CHAPTER 31. MODEL AND DEVICE PARAMETERS


31.6. MOSFETS563

31.6.5.2MOS9 model parameters

#NameDirectionTypeDescription
144typeOutstringN-channel or P-channel MOS
133nmosInf l agN type MOSfet model
134pmosInf l agP type MOSfet model
101vtoInOutrealThreshold voltage
101vt0InOutreal
102kpInOutrealTransconductance parameter
103gammaInOutrealBulk threshold parameter
104phiInOutrealSurface potential
105rdInOutrealDrain ohmic resistance
106rsInOutrealSource ohmic resistance
107cbdInOutrealB-D junction capacitance
108cbsInOutrealB-S junction capacitance
109isInOutrealBulk junction sat. current
110pbInOutrealBulk junction potential
111cgsoInOutrealGate-source overlap cap.
112cgdoInOutrealGate-drain overlap cap.
113cgboInOutrealGate-bulk overlap cap.
114rshInOutrealSheet resistance
115cjInOutrealBottom junction cap per area
116mjInOutrealBottom grading coeff i cient
117cjswInOutrealSide junction cap per area
118mjswInOutrealSide grading coeff i cient
119jsInOutrealBulk jct. sat. current density
120toxInOutrealOxide thickness
121ldInOutrealLateral diffusion
145xlInOutrealLength mask adjustment
146wdInOutrealWidth Narrowing (Diffusion)
147xwInOutrealWidth mask adjustment
148delvtoInOutrealThreshold voltage Adjust
148delvt0InOutreal
122u0InOutrealSurface mobility
122uoInOutreal
123fcInOutrealForward bias jct. f i t parm.
124nsubInOutrealSubstrate doping
125tpgInOutintegerGate type
126nssInOutrealSurface state density
131vmaxInOutrealMaximum carrier drift velocity
135xjInOutrealJunction depth
129nfsInOutrealFast surface state density
138xdInOutrealDepletion layer width
139alphaInOutrealAlpha
127etaInOutrealVds dependence of threshold voltage
128deltaInOutrealWidth effect on threshold
140input_deltaInOutreal
130thetaInOutrealVgs dependence on mobility
132kappaInOutrealKappa
141tnomInOutrealParameter measurement temperature
142kfInOutrealFlicker noise coeff i cient
143afInOutrealFlicker noise exponent


564CHAPTER 31. MODEL AND DEVICE PARAMETERS

31.6.6BSIM1 - Berkeley Short Channel IGFET Model

31.6.6.1BSIM1 instance parameters

#NameDirectionTypeDescription
2lInOutrealLength
1wInOutrealWidth
14mInOutrealParallel Multiplier
4adInOutrealDrain area
3asInOutrealSource area
6pdInOutrealDrain perimeter
5psInOutrealSource perimeter
8nrdInOutrealNumber of squares in drain
7nrsInOutrealNumber of squares in source
9offInOutf l agDevice is initially off
11vdsInOutrealInitial D-S voltage
12vgsInOutrealInitial G-S voltage
10vbsInOutrealInitial B-S voltage
13icInunknown vectorVector of DS,GS,BS initial voltages

31.6.6.2BSIM1 Model Parameters

#NameDirectionTypeDescription
101vfbInOutrealFlat band voltage
102lvfbInOutrealLength dependence of vfb
103wvfbInOutrealWidth dependence of vfb
104phiInOutrealStrong inversion surface potential
105lphiInOutrealLength dependence of phi
106wphiInOutrealWidth dependence of phi
107k1InOutrealBulk effect coeff i cient 1
108lk1InOutrealLength dependence of k1
109wk1InOutrealWidth dependence of k1
110k2InOutrealBulk effect coeff i cient 2
111lk2InOutrealLength dependence of k2
112wk2InOutrealWidth dependence of k2
113etaInOutrealVDS dependence of threshold voltage
114letaInOutrealLength dependence of eta
115wetaInOutrealWidth dependence of eta
116x2eInOutrealVBS dependence of eta
117lx2eInOutrealLength dependence of x2e
118wx2eInOutrealWidth dependence of x2e
119x3eInOutrealVDS dependence of eta
120lx3eInOutrealLength dependence of x3e
121wx3eInOutrealWidth dependence of x3e
122dlInOutrealChannel length reduction in um
123dwInOutrealChannel width reduction in um


31.6. MOSFETS565

124muzInOutrealZero f i eld mobility at VDS=0 VGS=VTH
125x2mzInOutrealVBS dependence of muz
126lx2mzInOutrealLength dependence of x2mz
127wx2mzInOutrealWidth dependence of x2mz
128musInOutrealMobility at VDS=VDD VGS=VTH, channel length modulation
129lmusInOutrealLength dependence of mus
130wmusInOutrealWidth dependence of mus
131x2msInOutrealVBS dependence of mus
132lx2msInOutrealLength dependence of x2ms
133wx2msInOutrealWidth dependence of x2ms
134x3msInOutrealVDS dependence of mus
135lx3msInOutrealLength dependence of x3ms
136wx3msInOutrealWidth dependence of x3ms
137u0InOutrealVGS dependence of mobility
138lu0InOutrealLength dependence of u0
139wu0InOutrealWidth dependence of u0
140x2u0InOutrealVBS dependence of u0
141lx2u0InOutrealLength dependence of x2u0
142wx2u0InOutrealWidth dependence of x2u0
143u1InOutrealVDS depence of mobility, velocity saturation
144lu1InOutrealLength dependence of u1
145wu1InOutrealWidth dependence of u1
146x2u1InOutrealVBS depence of u1
147lx2u1InOutrealLength depence of x2u1
148wx2u1InOutrealWidth depence of x2u1
149x3u1InOutrealVDS depence of u1
150lx3u1InOutrealLength dependence of x3u1
151wx3u1InOutrealWidth depence of x3u1
152n0InOutrealSubthreshold slope
153ln0InOutrealLength dependence of n0
154wn0InOutrealWidth dependence of n0
155nbInOutrealVBS dependence of subthreshold slope
156lnbInOutrealLength dependence of nb
157wnbInOutrealWidth dependence of nb
158ndInOutrealVDS dependence of subthreshold slope
159lndInOutrealLength dependence of nd
160wndInOutrealWidth dependence of nd
161toxInOutrealGate oxide thickness in um
162tempInOutrealTemperature in degree Celcius
163vddInOutrealSupply voltage to specify mus
164cgsoInOutrealGate source overlap capacitance per unit channel width(m)
165cgdoInOutrealGate drain overlap capacitance per unit channel width(m)
166cgboInOutrealGate bulk overlap capacitance per unit channel length(m)
167xpartInOutrealFlag for channel charge partitioning
168rshInOutrealSource drain diffusion sheet resistance in ohm per square
169jsInOutrealSource drain junction saturation current per unit area


566CHAPTER 31. MODEL AND DEVICE PARAMETERS

170pbInOutrealSource drain junction built in potential
171mjInOutrealSource drain bottom junction capacitance grading coeff i cient
172pbswInOutrealSource drain side junction capacitance built in potential
173mjswInOutrealSource drain side junction capacitance grading coeff i cient
174cjInOutrealSource drain bottom junction capacitance per unit area
175cjswInOutrealSource drain side junction capacitance per unit area
176wdfInOutrealDefault width of source drain diffusion in um
177dellInOutrealLength reduction of source drain diffusion
180kfInOutrealFlicker noise coeff i cient
181afInOutrealFlicker noise exponent
178nmosInf l agFlag to indicate NMOS
179pmosInf l agFlag to indicate PMOS


31.6. MOSFETS567

31.6.7BSIM2 - Berkeley Short Channel IGFET Model

31.6.7.1BSIM2 instance parameters

#NameDirectionTypeDescription
2lInOutrealLength
1wInOutrealWidth
14mInOutrealParallel Multiplier
4adInOutrealDrain area
3asInOutrealSource area
6pdInOutrealDrain perimeter
5psInOutrealSource perimeter
8nrdInOutrealNumber of squares in drain
7nrsInOutrealNumber of squares in source
9offInOutf l agDevice is initially off
11vdsInOutrealInitial D-S voltage
12vgsInOutrealInitial G-S voltage
10vbsInOutrealInitial B-S voltage
13icInunknown vectorVector of DS,GS,BS initial voltages

31.6.7.2BSIM2 model parameters

#NameDirectionTypeDescription
101vfbInOutrealFlat band voltage
102lvfbInOutrealLength dependence of vfb
103wvfbInOutrealWidth dependence of vfb
104phiInOutrealStrong inversion surface potential
105lphiInOutrealLength dependence of phi
106wphiInOutrealWidth dependence of phi
107k1InOutrealBulk effect coeff i cient 1
108lk1InOutrealLength dependence of k1
109wk1InOutrealWidth dependence of k1
110k2InOutrealBulk effect coeff i cient 2
111lk2InOutrealLength dependence of k2
112wk2InOutrealWidth dependence of k2
113eta0InOutrealVDS dependence of threshold voltage at VDD=0
114leta0InOutrealLength dependence of eta0
115weta0InOutrealWidth dependence of eta0
116etabInOutrealVBS dependence of eta
117letabInOutrealLength dependence of etab
118wetabInOutrealWidth dependence of etab
119dlInOutrealChannel length reduction in um
120dwInOutrealChannel width reduction in um
121mu0InOutrealLow-f i eld mobility, at VDS=0 VGS=VTH
122mu0bInOutrealVBS dependence of low-f i eld mobility
123lmu0bInOutrealLength dependence of mu0b


568CHAPTER 31. MODEL AND DEVICE PARAMETERS

124wmu0bInOutrealWidth dependence of mu0b
125mus0InOutrealMobility at VDS=VDD VGS=VTH
126lmus0InOutrealLength dependence of mus0
127wmus0InOutrealWidth dependence of mus
128musbInOutrealVBS dependence of mus
129lmusbInOutrealLength dependence of musb
130wmusbInOutrealWidth dependence of musb
131mu20InOutrealVDS dependence of mu in tanh term
132lmu20InOutrealLength dependence of mu20
133wmu20InOutrealWidth dependence of mu20
134mu2bInOutrealVBS dependence of mu2
135lmu2bInOutrealLength dependence of mu2b
136wmu2bInOutrealWidth dependence of mu2b
137mu2gInOutrealVGS dependence of mu2
138lmu2gInOutrealLength dependence of mu2g
139wmu2gInOutrealWidth dependence of mu2g
140mu30InOutrealVDS dependence of mu in linear term
141lmu30InOutrealLength dependence of mu30
142wmu30InOutrealWidth dependence of mu30
143mu3bInOutrealVBS dependence of mu3
144lmu3bInOutrealLength dependence of mu3b
145wmu3bInOutrealWidth dependence of mu3b
146mu3gInOutrealVGS dependence of mu3
147lmu3gInOutrealLength dependence of mu3g
148wmu3gInOutrealWidth dependence of mu3g
149mu40InOutrealVDS dependence of mu in linear term
150lmu40InOutrealLength dependence of mu40
151wmu40InOutrealWidth dependence of mu40
152mu4bInOutrealVBS dependence of mu4
153lmu4bInOutrealLength dependence of mu4b
154wmu4bInOutrealWidth dependence of mu4b
155mu4gInOutrealVGS dependence of mu4
156lmu4gInOutrealLength dependence of mu4g
157wmu4gInOutrealWidth dependence of mu4g
158ua0InOutrealLinear VGS dependence of mobility
159lua0InOutrealLength dependence of ua0
160wua0InOutrealWidth dependence of ua0
161uabInOutrealVBS dependence of ua
162luabInOutrealLength dependence of uab
163wuabInOutrealWidth dependence of uab
164ub0InOutrealQuadratic VGS dependence of mobility
165lub0InOutrealLength dependence of ub0
166wub0InOutrealWidth dependence of ub0
167ubbInOutrealVBS dependence of ub
168lubbInOutrealLength dependence of ubb
169wubbInOutrealWidth dependence of ubb


31.6. MOSFETS569

170u10InOutrealVDS depence of mobility
171lu10InOutrealLength dependence of u10
172wu10InOutrealWidth dependence of u10
173u1bInOutrealVBS depence of u1
174lu1bInOutrealLength depence of u1b
175wu1bInOutrealWidth depence of u1b
176u1dInOutrealVDS depence of u1
177lu1dInOutrealLength depence of u1d
178wu1dInOutrealWidth depence of u1d
179n0InOutrealSubthreshold slope at VDS=0 VBS=0
180ln0InOutrealLength dependence of n0
181wn0InOutrealWidth dependence of n0
182nbInOutrealVBS dependence of n
183lnbInOutrealLength dependence of nb
184wnbInOutrealWidth dependence of nb
185ndInOutrealVDS dependence of n
186lndInOutrealLength dependence of nd
187wndInOutrealWidth dependence of nd
188vof0InOutrealThreshold voltage offset AT VDS=0 VBS=0
189lvof0InOutrealLength dependence of vof0
190wvof0InOutrealWidth dependence of vof0
191vofbInOutrealVBS dependence of vof
192lvofbInOutrealLength dependence of vofb
193wvofbInOutrealWidth dependence of vofb
194vofdInOutrealVDS dependence of vof
195lvofdInOutrealLength dependence of vofd
196wvofdInOutrealWidth dependence of vofd
197ai0InOutrealPre-factor of hot-electron effect.
198lai0InOutrealLength dependence of ai0
199wai0InOutrealWidth dependence of ai0
200aibInOutrealVBS dependence of ai
201laibInOutrealLength dependence of aib
202waibInOutrealWidth dependence of aib
203bi0InOutrealExponential factor of hot-electron effect.
204lbi0InOutrealLength dependence of bi0
205wbi0InOutrealWidth dependence of bi0
206bibInOutrealVBS dependence of bi
207lbibInOutrealLength dependence of bib
208wbibInOutrealWidth dependence of bib
209vghighInOutrealUpper bound of the cubic spline function.
210lvghighInOutrealLength dependence of vghigh
211wvghighInOutrealWidth dependence of vghigh
212vglowInOutrealLower bound of the cubic spline function.
213lvglowInOutrealLength dependence of vglow
214wvglowInOutrealWidth dependence of vglow
215toxInOutrealGate oxide thickness in um


570CHAPTER 31. MODEL AND DEVICE PARAMETERS

216tempInOutrealTemperature in degree Celcius
217vddInOutrealMaximum Vds
218vggInOutrealMaximum Vgs
219vbbInOutrealMaximum Vbs
220cgsoInOutrealGate source overlap capacitance per unit channel width(m)
221cgdoInOutrealGate drain overlap capacitance per unit channel width(m)
222cgboInOutrealGate bulk overlap capacitance per unit channel length(m)
223xpartInOutrealFlag for channel charge partitioning
224rshInOutrealSource drain diffusion sheet resistance in ohm per square
225jsInOutrealSource drain junction saturation current per unit area
226pbInOutrealSource drain junction built in potential
227mjInOutrealSource drain bottom junction capacitance grading coeff i cient
228pbswInOutrealSource drain side junction capacitance built in potential
229mjswInOutrealSource drain side junction capacitance grading coeff i cient
230cjInOutrealSource drain bottom junction capacitance per unit area
231cjswInOutrealSource drain side junction capacitance per unit area
232wdfInOutrealDefault width of source drain diffusion in um
233dellInOutrealLength reduction of source drain diffusion
236kfInOutrealFlicker noise coeff i cient
237afInOutrealFlicker noise exponent
234nmosInf l agFlag to indicate NMOS
235pmosInf l agFlag to indicate PMOS


31.6. MOSFETS571

31.6.8BSIM3

The accessible device parameters (see chapt. 31.1 for the syntax) are listed here.

31.6.8.1BSIM3 accessible instance parameters

#NameDirectionTypeDescription
1idOutrealDrain current
2vgsOutrealGate-Source voltage
3vdsOutrealDrain-Source voltage
4vbsOutrealBulk-Source voltage
5gmOutrealTransconductance
6gdsOutrealDrain-Source conductance
7gmbsOutrealBulk-Source transconductance
8vdsatOutrealSaturation voltage
9vthOutrealThreshold voltage
10ibdOutreal
11ibsOutreal
12gbdOutreal
13gbsOutreal
14qbOutrealQbulk
15cqbOutreal
16qgOutrealQgate
17cqgOutreal
18qdOutrealQdrain
19cqdOutreal
20cggOutreal
21cgdOutreal
22cgsOutreal
23cdgOutreal
24cddOutreal
25cdsOutreal
26cbgOutreal
27cbdOutreal
28cbsOutreal
29capbdOutrealDiode capacitance
30capbsOutrealDiode capacitance

The parameters are available in the BSIM3 models (level=8 or level=49) version=3.2.4 and ver-
sion=3.3.0 only. Negative capacitance values may occur, depending on the internal calculation.
Please see the note in chapter 31.6.9.1.

31.6.8.2BSIM3 manual

Further detailed descriptions will not be given here. Unfortunately the details on these param-
eters are not documented, even not in the otherwise excellent pdf manual (tarred) issued by


572CHAPTER 31. MODEL AND DEVICE PARAMETERS

University of California at Berkeley.

31.6.9BSIM4

The accessible device parameters (see chapt. 31.1 for the syntax) are listed here.

31.6.9.1BSIM4 accessible instance parameters

#NameDirectionTypeDescription
gmbsOutrealBody effect (Back gate) transconductance
gmOutrealTransconductance
gdsOutrealDrain-Source conductance
vdsatOutrealSaturation voltage
vthOutrealThreshold voltage
idOutrealDrain current
ibdOutrealDiode current
ibsOutrealDiode current
gbdOutrealDiode conductance
gbsOutrealDiode conductance
isubOutrealSubstrate current
igidlOutrealGate-Induced Drain Leakage current
igislOutrealGate-Induced Source Leakage current
igsOutrealGate-Source current
igdOutrealGate-drain current
igbOutrealGate-Bulk current
igcsOutreal
vbsOutrealBulk-Source voltage
vgsOutrealGate-Source voltage
vdsOutrealDrain-Source voltage
cggOutreal
cgsOutreal
cgdOutreal
cbgOutreal
cbdOutreal
cbsOutreal
cdgOutreal
cddOutreal
cdsOutreal
csgOutreal
csdOutreal
cssOutreal
cgbOutreal
cdbOutreal
csbOutreal
cbbOutreal


31.6. MOSFETS573

capbdOutrealDiode capacitance
capbsOutrealDiode capacitance
qgOutrealGate charge
qbOutrealBulk charge
qdOutrealDrain charge
qsOutreal
qinvOutreal
qdefOutreal
gcrgOutreal
gtauOutreal

The parameters are available in all BSIM4 models (level=14 or level=54) version=4.2.1 to ver-
sion=4.7.

Negative capacitance values may occur, depending on the internal calculation. To comparing
with measured data, please just use the absolute values of the capacitance data. For an expla-
nation 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 by Liu and Hu, chapter 5.2.

31.6.9.2BSIM4 manual

Detailed descriptions will not be given here. Unfortunately the details on these parameters
are not documented, even not in the otherwise excellent pdf manual issued by University of
California at Berkeley.


574CHAPTER 31. MODEL AND DEVICE PARAMETERS


Chapter 32

Compilation notes

This f i le describes the procedures to install ngspice from sources.

32.1NgspiceInstallationunderLINUX(andother’UNIXes’)

32.1.1Prerequisites

Ngspice is written in C and thus a complete C compilation environment is needed. Almost
any UNIX comes with a complete C development environment.Ngspice is developed on
GNU/Linux with gcc and GNU make.

The following software must be installed in your system to compile ngspice: bison, f l ex, and
X11 headers and libs.

The X11 headers and libraries are typically available in an X11 development package from your
LINUX distribution.

If you want to compile the Git source you need additional software: autoconf, automake,
libtool, texinfo.

The following software may be needed when enabling additional features: readline, editline,
tcl/tk, blt.

If you want have high performance and accurate FFT’s you should install: fftw-3. Ngspice
conf i gure script will f i nd the library and will induce the build process to link against it.

32.1.2Install from Git

This section describes how to install from source code taken direct from Git. This will give
you access to the most recent enhancements and corrections. However be careful as the code
in Git may be under development and thus still unstable. For user install instructions using
source from released distributions, please see the sections titled ’Install from tarball’ (32.1.3)
and ’Advanced Install’ (32.1.5).

Download source from Git as described on the sourceforge ngspice Git page. Def i ne 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

575


576CHAPTER 32. COMPILATION NOTES

git clone git://git.code.sf.net/p/ngspice/ngspice

or via http protocol

git clone http://git.code.sf.net/p/ngspice/ngspice

You will f i nd the sources in directory /home/myname/software/ngspice. Now enter the
ngspice top level directory ngspice (where the installation instruction f i le INSTALL can be
found).

The project uses the GNU build process. You should be able to do the following:

$ ./autogen.sh

$ ./configure --enable-xspice --enable-cider
--disable-debug --with-readline=yes

$ make

$ sudo make install

See the section titled ’Advanced Install’ (32.1.5) 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”:

--enable-xspice Include the XSPICE extensions (see chapters 12 and 28)

--enable-cider Include CIDER numerical device simulator (see chapter 30)

--disable-debug No debugging information included (optimized and compact code)

--with-readline=yesIncludeaneditorfortheinputcommandline(commandhistory, 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.

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 f i x the problem
yourself f i rst. If you have f i xed 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 deny to overwrite modif i ed f i les in your working directory. To drop your local
changes f i rst, you can run

git reset --hard

To learn more about Git, which can be both powerful and diff i cult to master, please consult
http://git-scm.com/, especially: http://git-scm.com/documentation which has pointers to docu-
mentation and tutorials.


32.1. NGSPICE INSTALLATION UNDER LINUX (AND OTHER ’UNIXES’)577

32.1.3Install from a tarball, e.g. ngspice-rework-25.tgz

This covers installation from a tarball (for example ngspice-rework-25.tgz, to be found at
http://sourceforge.net/projects/ngspice/f i les/). After downloading the tar ball to a local direc-
tory unpack it using:

$ tar -zxvf ngspice-rework-25.tgz

Now change directories in to the top-level source directory (where this text from the INSTALL
f i le can be found).

You should be able to do:

$ ./configure --enable-xspice --disable-debug --with-readline=yes

$ make

$ sudo make install

The default install dir is /usr/local/bin

See the section titled ’Advanced Install’ (32.1.5) for instructions about arguments that can be
passed to ./configure to customize the build and installation.

32.1.4Compilation using an user def i ned directory tree for object f i les

The procedures described above will store the *.o f i les (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). Soifyouintendtocreateaseparateobjectf i letreelikengspice/ngbuild/re-
lease, you may do the following, starting from the default directory ngspice:

mkdir -p release

cd release

../configure --enable-xspice --disable-debug --with-readline=yes <more options>

make install

This will create an object f i le directory tree, similar to the source f i le directory tree, the object
f i les are now separated from the source f i les. For the debug version, you may do the same
as described above, replacing ’release’ by ’debug’, and obtain another separated object f i le
directory tree. If you already have run ./configure in ngspice, you have to do a maintainer-
clean, before the above procedure will work.

32.1.5Advanced Install

Some extra options can be provided to ’./conf i gure’. To get all available options do:

$ ./configure --help

Some of these options are generic to the GNU build process that is used by Ngspice, other are
specif i c to Ngspice.

The following sections provide some guidance and descriptions for many, but not all, of these
options.


578CHAPTER 32. COMPILATION NOTES

32.1.5.1Options Specif i c to Using Ngspice

--enable-openmp Compile ngspice for multi-core processors. Paralleling is done by OpenMP
(see chapt. 16.10).

--enable-xspice Enable XSPICE enhancements, yielding a mixed signal simulator inte-
grated into ngspice with codemodel dynamic loading support. See chapter 12 and section II
for details.

--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.

--enable-adms ADMS is an experimental model compiler that translates Verilog-A compact
models into C code that can be compiled into ngspice. This is still experimental, but working
with some limitations to the models (e.g. no noise models). If you want to use it, please refer
to the ADMS section on ngspice web site .

--with-editline=yes Enables the use of the BSD editline library (libedit).
See http://www.thrysoee.dk/editline/.

--without-x Disable the X-Windows graphical system. Compile without needing X headers
and X libraries. The plot command (17.5.43) is now disabled. You may use gnuplot (17.5.26)
instead.

--with-tcl=tcldir When conf i gured 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.

The following options are seldom used today, not tested, some may even no longer be imple-
mented.

--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 en-
abled 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 anal-
ysis only.

--enable-expdevices Enable experimental devices. This option is used by developers to
mask devices under development. Almost useless for users.

--enable-experimental This enables some experimental code. Specif i cally it enables: *
support for altering options in interactive mode by adding the interactive keyword ’options’. *
The ability to save and load snapshots: adds interactive keywords ’savesnap’ and ’loadsnap’.

--enable-help Force building nghelp. This is deprecated.

--enable-newpred Enable the NEWPRED symbol in the code.

--enable-newtrunc Enable the newtrunc option


32.1. NGSPICE INSTALLATION UNDER LINUX (AND OTHER ’UNIXES’)579

--enable-ndev Enable NDEV interface, (experimental) A TCP/IP interface to external device
simulator such as GSS. For more information, please visit the homepage of GSS at http://gss-
tcad.sourceforge.net

--enable-nodelimiting Experimental damping scheme

--enable-nobypass Don’t bypass recalculations of slowly changing variables

--enable-nosqrt Use always log/exp for non-linear capacitances –enable-predictor Enable a
predictor method for convergence

--enable-sense2 Use spice2 sensitivity analysis

--enable-xgraph Compile the Xgraph plotting program. Xgraph is a plotting package for
X11 and was once very popular.

32.1.5.2Options Useful for Debugging Ngspice

--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.

The following options are seldom used today, not tested, some may even no longer be imple-
mented.

--enable-ansi Conf i gure will try to f i nd an option for your compiler so that it expects ansi-C.

--enable-asdebug Debug sensitivity code *ASDEBUG*.

--enable-blktmsdebug Debug distortion code *BLOCKTIMES*

--enable-checkergcc Option for compilation with checkergcc.

--enable-cpdebug Enable ngspice shell code debug.

--enable-ftedebug Enable ngspice frontend debug.

--enable-gc Enable the Boehm-Weiser Conservative Garbage Collector.

--enable-pzdebug Debug pole/zero code.

--enable-sensdebug Debug sensitivity code *SENSDEBUG*.

--enable-smltmsdebug Debug distortion code *SMALLTIMES*

--enable-smoketest Enable smoketest compile.

--enable-stepdebug Turns on debugging of convergence steps in transient analysis

32.1.6Compilers and Options

Some systems require unusual options for compilation or linking that the ‘conf i gure’ script
does not know about. You can give ‘conf i gure’ initial values for variables by setting them in the
environment. Using a Bourne-compatible shell, you can do that on the command line like this:

CC=c89

CFLAGS=-O2

LIBS=-lposix


580CHAPTER 32. COMPILATION NOTES

./configure

Or on systems that have the ‘env’ program, you can do it like this:

env CPPFLAGS=-I/usr/local/include

LDFLAGS=-s

./configure

32.1.7Compiling For Multiple Architectures

You can compile the package for more than one kind of computer at the same time, by placing
the object f i les for each architecture in their own directory. To do this, you must use a version
of ‘make’ that supports the ‘VPATH’ variable, such as GNU ‘make’. ‘cd’ to the directory
where you want the object f i les and executables to go and run the ‘conf i gure’ script. ‘conf i gure’
automatically checks for the source code in the directory that ‘conf i gure’ is in and in ‘..’.

Ifyouhavetousea‘make’thatdoesnotsupportsthe‘VPATH’variable, youhavetocompilethe
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 reconf i guring for another architecture.

32.1.8Installation Names

By default, ‘make install’ will install the package’s f i les in ‘/usr/local/bin’, ‘/usr/local/man’, etc.
You can specify an installation pref i x other than ‘/usr/local’ by giving ‘conf i gure’ the option ‘–
pref i x=PATH’.

You can specify separate installation pref i xes for architecture-specif i c f i les and architecture-
independent f i les. If you give ‘conf i gure’ the option ‘–exec-pref i x=PATH’, the package will use
PATH as the pref i x for installing programs and libraries. Documentation and other data f i les
will still use the regular pref i x.

In addition, if you use an unusual directory layout you can give options like ‘–bindir=PATH’
to specify different values for particular kinds of f i les. Run ‘conf i gure –help’ for a list of the
directories you can set and what kinds of f i les go in them.

If the package supports it, you can cause programs to be installed with an extra pref i x or suf-
f i x on their names by giving ‘conf i gure’ the option ‘–program-pref i x=PREFIX’ or ‘–program-
suff i x=SUFFIX’.

When installed on MinGW with MSYS alternative paths are not fully supported. See ’How to
make ngspice with MINGW and MSYS’ below for details.

32.1.9Optional Features

Some packages pay attention to ‘–enable-FEATURE’ options to ‘conf i gure’, where FEATURE
indicates an optional part of the package. They may also pay attention to ‘–with-PACKAGE’
options, where PACKAGE is something like ‘gnu-as’ or ‘x’ (for the X Window System). The
‘README’ should mention any ‘–enable-’ and ‘–with-’ options that the package recognizes.

For packages that use the X Window System, ‘conf i gure’ can usually f i nd the X include and li-
braryf i lesautomatically, butifitdoesn’t, youcanusethe‘conf i gure’options‘–x-includes=DIR’
and ‘–x-libraries=DIR’ to specify their locations.


32.2. NGSPICE COMPILATION UNDER WINDOWS OS581

32.1.10Specifying the System Type

There may be some features ‘conf i gure’ can not f i gure out automatically, but needs to determine
bythetypeofhostthepackagewillrunon. Usually‘conf i gure’canf i gurethatout, butifitprints
a message saying it can not guess the host type, give it the ‘–host=TYPE’ option. TYPE can
either be a short name for the system type, such as ‘sun4’, or a canonical name with three f i elds:
CPU-COMPANY-SYSTEM

See the f i le ‘conf i g.sub’ for the possible values of each f i eld. If ‘conf i g.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.

32.1.11Sharing Defaults

If you want to set default values for ‘conf i gure’ scripts to share, you can create a site shell script
called ‘conf i g.site’ that gives default values for variables like ‘CC’, ‘cache_f i le’, and ‘pref i x’.
‘conf i gure’ looks for ‘PREFIX/share/conf i g.site’ if it exists, then ‘PREFIX/etc/conf i g.site’ if it
exists. Or, you can set the ‘CONFIG_SITE’ environment variable to the location of the site
script. A warning: not all ‘conf i gure’ scripts look for a site script.

32.1.12Operation Controls

‘conf i gure’ recognizes the following options to control how it operates.

‘--cache-file=FILE’UseandsavetheresultsofthetestsinFILEinsteadof‘./conf i g.cache’.
Set FILE to ‘/dev/null’ to disable caching, for debugging ‘conf i gure’.

‘--help’ Print a summary of the options to ‘conf i gure’, and exit.

‘--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 ‘conf i gure’
can determine that directory automatically.

‘--version’ Print the version of Autoconf used to generate the ‘conf i gure’ script, and exit.

‘configure’ also accepts some other, not widely useful, options.

32.2Ngspice Compilation under WINDOWS OS

32.2.1How to make ngspice with MINGW and MSYS

CreatingngspicewithMINGWisnowastraightforwardprocedure, ifyouhaveMSYS/MINGW
installed properly. Unfortunately the installation is rather tedious because you will need several
enhancements to the standard install, especially if you want to include XSpice. Some links are
given below which describe the procedures. The default installation location of ngspice is the


582CHAPTER 32. COMPILATION NOTES

Windows path C:\spice. The install path can be altered by passing --prefix=NEWPATH as an
argument to ./configure during the build process.

Put the install path you desire inside "", e.g. "D:/NewSpice". Be careful to use forward slashes
"/", notbackwardslashes"\"(somethingstilltobef i xed). Thenadd--prefix="D:/NewSpice"
as an argument to ./configure in the normal way.

The procedure of compiling a distribution (for example, a the most recent stable distribution
from the ngspice website, e.g. ngspice-25.tar.gz), is as follows:

$ cd ngspice

$ cd release

$ ../configure --with-wingui ...and other options

$ make

$ make install

The useful options are:

--enable-xspice (this requires FLEX and BISON available in MSYS, see below).

--enable-cider

--disable-debug (-O2 optimization, no debug information)

A complete ngspice (release version, no debug info, optimized executable) may be made avail-
able just by

$ cd ngspice

$ ./compile_min.sh

If you want to compile the Git source you need additional software packages autoconf, au-
tomake, libtool, available from the MSYS distribution and git, available for example here.

Download source from Git as described on the sourceforge ngspice Git page. Def i ne 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://ngspice.git.sourceforge.net/gitroot/ngspice/ngspice

You will f i nd the sources in directory /d/spice/ngspice/. Now enter the ngspice top level
directory ngspice. This is the procedure for compilation:

$ cd ngspice

$ ./autogen.sh

$ mkdir release

$ cd release

$ ../configure --with-wingui ...and other options

$ make

$ make install


32.2. NGSPICE COMPILATION UNDER WINDOWS OS583

The user def i ned build tree saves the object f i les, 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 deny to overwrite modif i ed f i les in your working directory. To drop your local
changes f i rst, you can run

git reset --hard

To learn more about Git, which can be both powerful and diff i cult to master, please consult
http://git-scm.com/, especially: http://git-scm.com/documentation which has pointers to docu-
mentation and tutorials.

MINGW and MSYS can be downloaded from http://www.mingw.org/. The making of the code
models *.cm for XSpice and one of the ngspice parsers require the installation of BISON and
FLEX to MSYS. A typical installation was tested with: bison-2.0-MSYS.tar.gz f l ex-2.5.4a-1-
bin.zip libiconv-1.9.2-1-bin.zip libintl-0.14.4-bin.zip

Bison 2.0 is now superseded by newer releases
(Bison2.3, seehttp://sourceforge.net/project/showf i les.php?group_id=2435&package_id=67879)

The last three are from http://sourceforge.net/project/showf i les.php?group_id=23617.

You may also look at

http://www.mingw.org/wiki/HOWTO_Install_the_MinGW_GCC_Compiler_Suite

http://www.mingw.org/wiki/MSYS

http://www.mingw.org/wiki/HOWTO_Create_an_MSYS_Build_Environment.

32.2.264 Bit executables with MINGW-w64

Procedure:

Install MSYS, plus bison, f l ex, auto tools, perl, libiconv, libintl

Install MINGW-w64, activate OpenMP support

See either http://mingw-w64.sourceforge.net/ or http://tdm-gcc.tdragon.net/

(allows to generate both 32 or 64 bit executables by setting f l ag -m32 or -m64)

Set path to compiler in msys/xx/etc/fstab (e.g. c:/MinGW64 /mingw)

Start compiling with

’./compile_min.sh’ or ’./compile_min.sh 64’

Options used in the script:

–adms and –enable-adms ADMS is an experimental model compiler that translates Verilog-A
compact models into C code that can be compiled into ngspice. This is still experimental, but


584CHAPTER 32. COMPILATION NOTES

working with some limitations to the models (e.g. no noise models). If you want to use it,
please refer to the ADMS section on ngspice web site .

CIDER, XSPICE, and OpenMP may be selected at will.

–disable-debug will give O2 optimization (versus O0 for debug) and removes all debugging
info.

The install script will copy all f i les 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.

A word of caution: Be aware that there might be some bugs in your 64 bit code. We still have
some compiler warnings about integer incompatibility (e.g. integer versus size_t etc.)! We will
take care of that for the next release.

32.2.3make ngspice with MS Visual Studio 2008 or 2010

ngspice may be compiled with MS Visual Studio 2008. Support for MS Visual Studio 2010 is
easily achieved by using the automatic project migration offered by Microsoft.

CIDER and XSPICE are included, but the code models for XSPICE (*.cm) are not (yet) made.
You may however use the code models (which in fact are dlls) created with MINGW, as e.g.
found in the ngspice binary distribution. There is currently no installation procedure provided,
you may however install the executable manually as described in the installation tree below. The
directory (visualc) with its f i les vngspice.sln (project starter) and vngspice.vcproj (project con-
tents) allows to compile and link ngspice with MS Visual Studio 2008. The project is probably
not compatible with Visual Studio 2005, but may be translated for use with 2010.

/visualc/include contains a dedicated conf i g.h f i le. It contains the preprocessor def i nitions re-
quired to properly compile the code. strings.h has been necessary during setting up the project.

Install Microsoft Visual Studio 2008 C++. The MS VS 2008 C++ Express Edition (which is
available at no cost from http://www.microsoft.com/express/product/default.aspx) is adequate,
if you do not wish to have OpenMP or 64 bit support. So the express edition will allow a 32
bit Release and a Debug version of ngspice, using the Win32 f l ag. In addition you may select
a console version without graphics interface. The professional edition will offer Release and
Debug and Console also for 64 bit (f l ag x64), as well as an OpenMP variant for 32 or 64 bit.

Procedure:

Goto /ngspice/visualc.

Start MS Visual Studio 2008 by double click onto vngspice.sln. After MS Visual Studio has
opened up, select debug or release version by checking ’Erstellen’ , ’Konf i gurations-Manager’
’Debug’ or ’Release’. Start making ngspice (called vngspice.exe) by selecting ’Erstellen’ and
’vngspice neu erstellen’. Object f i les will be created and stored in visualc/debug or visualc/re-
lease. The executable will be stored to visualc/debug/bin or visualc/release/bin.

An installation tree (as provided with MINGW make install) and also used by vngspice in its
current distribution is shown in the following table (maybe created manually):

If you intend to install vngspice into another directory, e.g. D:\MySpice, you have to edit
/visualc/include/conf i g.h and alter the following entries from:

#define NGSPICEBINDIR "C:/Spice/bin"


32.2. NGSPICE COMPILATION UNDER WINDOWS OS585

C:\Spice\
bin\
ngspice.exe
nghelp.exe
ngmakeidx.exe
ngnutmeg.exe
cmpp.exe
lib\
spice\
analog.cm
digital.cm
spice2poly.cm
extradev.cm
extravt.cm
share\
info\
dir
ngspice.info
ngspice.info-1
..
ngspice.info-10
man\
man1\
ngmultidec.1
ngnutmeg.1
ngsconvert.1
ngspice.1
ngspice\
helpdir\
ngspice.idx
ngspice.txt
scripts\
ciderinit
devaxis
devload
setplot
spectrum
spinit

Table 32.1: ngspice standard installation tree under MS Windows


586CHAPTER 32. COMPILATION NOTES

#define NGSPICEDATADIR "C:/Spice/share/ngspice"

to

#define NGSPICEBINDIR "D:/MySpice/bin"

#define NGSPICEDATADIR "D:/MySpice/share/ngspice"

nghelp.exe is deprecated and no longer offered, but still available in the binary distribution. If
the code model f i les *.cm are not available, you will get warning messages, but you may use
ngspice in the normal way (of course without XSPICE extensions). To-Do: Some commands
in how-to-ngspice-vstudio.txt and mentioned above have to be translated to English.

To use the FFTW-3 library, download the precompiled MS Windows distribution (either 32
bit or 64 bit) from http://www.fftw.org/install/windows.html. Extract at least the f i les fftw3.h,
libfftw3-3.def, and libfftw3-3.dll to directory fftw-3.3.3-dll32 (from 32 bit fftw3 for ngspice
32 bit), or to directory fftw-3.3.3-dll64 (from 64 bit fftw3 for ngspice 64 bit). Then select the
MS VC++ project f i le visualc/vngspice-fftw.vcproj for starting VC++, select the appropriate
conf i guration and platform, and off you go.

32.2.4make ngspice with pure CYGWIN

The procedure of compiling is the same as with Linux (see chapt. 32.1). After you have moved
to the ngspice directory, the following command sequence may do the work for you:

$ ./autogen.sh

$ mkdir release-cyg

$ cd release-cyg

$ ../configure --with-x --disable-debug --with-readline=yes --enable-xspice
--enable-pss --enable-cider --enable-openmp

$ make clean 2>&1 | tee make_clean.log

$ make 2>&1 | tee make.log

$ make install 2>&1 | tee make_install.log

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

$ xwin -multiwindow -clipboard &

If you don’t have libdl.a you may need to link libcygwin.a to libdl.a symbolically, for example:

$ cd /lib $ ln -s libcygwin.a libdl.a.

32.2.5ngspice mingw or cygwin console executable w/o graphics

If you omit the conf i gure f l ag “–with-wingui” or “–with-x”, you will obtain a console applica-
tion without graphics interface.


32.2. NGSPICE COMPILATION UNDER WINDOWS OS587

./configure --enable-xspice --enable-cider --enable-openmp
--disable-debug CFLAGS=-m32 LDFLAGS=-m32 prefix=C:/Spice

is an example for TDM mingw, 32 Bit ngspice console. No graphics interface is provided. A
warning message will be issued upon starting ngspice. However, you may invoke ’gnuplot’ for
plotting (see 17.5.26).

32.2.6make ngspice with CYGWIN and external MINGW32

The next two compilation options are deprecated and not tested any more!

according to http://www.geocrawler.com/lists/3/SourceForge/6013/0/7321042/

$ cd ngspice

$ export PATH="/cygdrive/g/gcc_mingw/bin:$PATH"

$ autoconf

$ rm config.cache

$ ./configure --with-wingui --prefix="/cygdrive/g/gcc_mingw/bin"

$ make clean

$ make 2> make.err

$ cp config.h config_ming.h

ngspice.exe is o.k.,but make tests does not work (cannot direct console output into f i le). Needs
to add .save "what" "where.test" to every input (*.cir) f i le. Also all given output f i les have to
be adapted to WINDOWS (CR/LF instead of only LF at each line ending) for allowing proper
comparison.

32.2.7make ngspice with CYGWIN and internal MINGW32 (use con-
f i g.h made above)

$ cd ngspice

$ rm config.cache

$ export CFLAGS="-mno-cygwin -g -O2"

$ export LDFLAGS="-L/lib/mingw"

$ export CPPFLAGS="-I/usr/include/mingw"

$ ./configure --with-wingui

$ cp config_ming.h config.h

$ make clean

$ make 2> make.err

./configure does not work correctly: It f i nds headers and libs which are not really available
in the -mno-cygwin port of MINGW32. Therefore conf i g.h is not o.k.

To-Do: f i nd appropriate presets for variables ? rewrite tests for headers and libs (search exclu-
sively in mingw directories)


588CHAPTER 32. COMPILATION NOTES

32.3Reporting errors

Setting up ngspice is a complex task. The source code contains over 1500 f i les. ngspice should
run on various operating systems. Therefore errors may be found, some still evolving from the
original spice3f5 code, others introduced during the ongoing code enhancements.

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 f i le to reproduce the bug (if to report a runtime error)

Actual output versus the expected output


Chapter 33

Copyrights and licenses

33.1Documentation license

33.1.1Spice documentation copyright

Copyright 1996 The Regents of the University of California.

Permission to use, copy, modify, and distribute this software and its documentation for educa-
tional, research and non-prof i t purposes, without fee, and without a written agreement is hereby
granted, provided that the above copyright notice, this paragraph and the following three para-
graphs appear in all copies. This software program and documentation are copyrighted by The
Regents of the University of California. The software program and documentation are supplied
"as is", without any accompanying services from The Regents. The Regents does not warrant
that the operation of the program will be uninterrupted or error-free. The end-user understands
that the program was developed for research purposes and is advised not to rely exclusively on
the program for any reason.

INNOEVENTSHALLTHEUNIVERSITYOFCALIFORNIABELIABLETOANYPARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN AD-
VISEDOFTHEPOSSIBILITYOFSUCHDAMAGE.THE UNIVERSITYOFCALIFORNIA
SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PAR-
TICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BA-
SIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

33.1.2XSPICE SOFTWARE (documentation) copyright

Code added to SPICE3 to create the XSPICE Simulator and the XSPICE Code Model Subsys-
tem was developed at the Computer Science and Information Technology Laboratory, Georgia
Tech Research Institute, Atlanta GA, and is covered by license agreement the following copy-
right:

589


590CHAPTER 33. COPYRIGHTS AND LICENSES

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.

This license is now superseded by chapt. 33.2.2

33.1.3CIDER RESEARCH SOFTWARE AGREEMENT (superseded by
33.2.1)

This chapter specif i es the terms under which the CIDER software and documentation coming
with the original distribution are provided. This agreement is superseded by 33.2.1, the “modi-
f i ed” BSD license.

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 soft-
ware 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.

THEUNIVERSITYOFCALIFORNIAHEREBYDISCLAIMSALLIMPLIEDWARRANTIES,
INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE UNIVERSITY IS NOT LIABLE FOR ANY DAM-
AGES INCURRED BY THE RECIPIENT IN USE OF THE SOFTWARE AND DOCUMEN-
TATION, INCLUDING DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUEN-
TIAL 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 “modif i ed” BSD license by UCB in 1999 (see chapt.
33.2.1).

33.2ngspice license

The SPICE license is the “Modif i ed” BSD license,
(see http://embedded.eecs.berkeley.edu/pubs/downloads/spice/index.htm).
ngspice adopts this “Modif i ed” BSD license as well for all of its source code (except of


33.2. NGSPICE LICENSE591

tclspice, and numparam which are under LGPLv2, and XSPICE, which is public domain
(see 33.2.2))!

*****************************************************************************

Copyright (c) 1985-1991 The Regents of the University of California.

All rights reserved.

Permission is hereby granted, without written agreement and without license or royalty fees, to
use, copy, modify, and distribute this software and its documentation for any purpose, provided
that the above copyright notice and the following two paragraphs appear in all copies of this
software.

INNOEVENTSHALLTHEUNIVERSITYOFCALIFORNIABELIABLETOANYPARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS
ANYWARRANTIES,INCLUDING,BUTNOTLIMITEDTO,THEIMPLIEDWARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFT-
WARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UP-
DATES, ENHANCEMENTS, OR MODIFICATIONS.

*****************************************************************************

33.2.1“Modif i ed” BSD license

All “old” BSD licenses (of SPICE or CIDER) have been changed to the “modif i ed” BSD license
according to the following publication
(see ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change):

July 22, 1999

To All Licensees, Distributors of Any Version of BSD:

As you know, certain of the Berkeley Software Distribution ("BSD") source code f i les 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 Berke-
ley and its contributors.

Specif i cally, the provision reads:

" 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 acknowl-
edgment within advertising materials. Accordingly, the foregoing paragraph of those BSD Unix
f i les containing it is hereby deleted in its entirety.

William Hoskins

Director, Off i ce of Technology Licensing

University of California, Berkeley


592CHAPTER 33. COPYRIGHTS AND LICENSES

33.2.2XSPICE

Accordingtohttp://users.ece.gatech.edu/mrichard/Xspice/(asofFeb. 2012)theXSPICEsource
code and documentation have been put into the public domain by the Georgia Institute of Tech-
nology.

33.2.3tclspice, numparam

Both software packages are copyrighted and are released under LGPLv2
(see http://www.gnu.org/licenses/lgpl-2.1.html).

33.2.4Linking to GPLd libraries (e.g. readline, fftw):

The readline manual at http://tiswww.case.edu/php/chet/readline/rltop.html states: Readline is
free software, distributed under the terms of the GNU General Public License, version 3. This
means that if you want to use Readline in a program that you release or distribute to anyone, the
program must be free software and have a GPL-compatible license.

According to http://www.gnu.org/licenses/license-list.html, the modif i ed 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.


