Table of Contents

SPICE on gEDA HOWTO

Introduction

The purpose of this document is to explain how to use the gEDA tools (running on Linux) to perform SPICE simulations. In particular, this HOWTO documents the usage of spice-sdb, which is an advanced backend for the gEDA netlister (gnetlist) used to create SPICE netlists. This HOWTO also provides advice about using LTSpice and/or ngspice to simulate a circuit netlisted with spice-sdb. I assume that you are already familiar with electronic design, the mechanics of schematic capture using EDA tools, and SPICE simulation in general. I also assume that you are reasonably familiar with the Linux operating system and its development environment.

Overview

From the top level, SPICE simulation in gEDA proceeds via the following steps:

  1. Creation and gathering of schematic symbols and SPICE model files. Oftentimes, the SPICE model files are obtained from the component vendor.
  2. Schematic capture using symbols and SPICE models created in step 1.
  3. Netlist generation from the schematic created in step 2.
  4. SPICE simulation of the circuit described by the netlist created in step 3.

To create a SPICE netlist, the netlister (gnetlist) iterates through the entire schematic and looks at several parts of each component’s symbol in order to create a blob of SPICE code. In general, each component can generate one or more lines of SPICE code. Component information needed by the netlister is held in two places:

  1. The symbol itself, in the “device” attribute, which is attached when the symbol is created, and is typically accessed through the symbol editor.
  2. In attributes manually attached to the component during schematic capture using gschem.

Since there are two places the netlister looks for information, you must make sure that the required information is available in both places.

Spice-sdb netlister installation and configuration

This document was originally written around gEDA/gaf 20030223, and the SPICE netlister spice-SDB. Starting with gEDA/gaf 20030525, my netlister was incorporated into the main gEDA distribution, and renamed spice-sdb (lower case sdb). For smoothest operation, you are best off just downloading and installing the latest version of gEDA. However, if you have a gEDA version predating 20030525, and you want to hack, you can download and install spice-SDB using the instructions provided on http://www.brorson.com/gEDA/SPICE/SPICEonLinux.html. In any event, it’s a good idea to make sure that the file gnet-spice-sdb.scm is present in your scheme directory (usually ${prefix}/geda/share/gEDA/scheme) if you are interested in performing SPICE simulations with gEDA as described in this HOWTO.

Design/simulation flow summary

The detailed steps required to create a circuit and simulate it with gEDA look like this:

  1. Schematic symbol creation with correct “device” attribute. (Usually, the symbols have already been created with the correct “device” attribute, but if you are having problems, it doesn’t hurt to check them.)
  2. Schematic capture using gschem.
  3. Assignment of SPICE attributes (value, model, file, type, etc.) to components using gschem.
  4. Assignment of refdes using e.g. refdes_renum.
  5. Creation of netlist using “gnetlist -g spice-sdb”.
  6. Check netlist for correctness (manually open and inspect netlist).
  7. Run spice using a simulator such as LTSpice or ngspice.
  8. Plot/analyze results (often plotting/analysis tools are incorporated in the simulator).

The purpose of this HOWTO is to provide the detailed understanding necessary to successfully navigate this process.

Preliminary notes about symbols and SPICE model files

Symbol creation for SPICE netlisting.

The SPICE netlister recognizes a particular symbol in two ways:

  1. The symbol’s “device” attribute
  2. The symbol’s refdes. Both of these attributes are attached to the symbol when the symbol is created.

Each symbol has a device attribute attached to it. The device attribute is the first thing the netlister examines when processing the symbol. There are a number of devices which are native to the netlister, meaning that the netlister knows exactly how to deal with these types of devices. Native device types include RESISTOR, CAPACITOR, NPN_TRANSISTOR, etc. The entire list of native devices is present in the Appendix.
The device attribute is hidden during normal use of gschem. Most often, the symbol’s creator has already given the symbol the correct device attribute. However, because the device attribute is hidden from the ordinary user, it can sometimes cause problems with SPICE netlist creation when it is set to an unexpected value. To view the device attribute, go into the symbol editor (select the symbol to edit, and do “Hierarchy” → “down symbol”), and turn on invisible attributes (Edit → show/hide inv text). If the device attribute is incorrect, you may change it by editing the symbol itself using a text editor.
If a symbol is not native (i.e. the netlister doesn’t recognize it as a built-in type), the netlister relies upon the first letter of the refdes to determine how to process the symbol. The refdes prefix is also built into the symbol when it is created. Example refdes prefixes are R for resistors, C for capacitors, Q for transistors, etc. refdes prefixes correct for SPICE are listed in the Appendix. Note that relying upon the refdes to identify the component for SPICE is not foolproof – for example, the netlister cannot distinguish between NPN and PNP transistors based upon the refdes. Therefore, it is always best to use a native “device” in your symbols.

SPICE file configuration

Files holding complicated SPICE models or other SPICE code may be incorporated into the final SPICE netlist by including appropriate symbols into the schematic. SPICE model files are usually obtained from component vendors. Dealing with these files is straightforward. However, some issues should be kept in mind when preparing models for use during schematic capture:

Schematic capture

Schematic capture is the process by which one uses a special-purpose drawing program to draw a schematic diagram of the circuit under design. In the gEDA environment, the schematic capture program is called “gschem”. I assume you already know how to use gschem. For the purposes of creating SPICE netlists, you must use gschem to attach attributes to components, and possibly also incorporate other SPICE directives into your netlist. After you are done with schematic capture, you create the SPICE netlist by running gEDA’s netlister “gnetlist” on your design.

Gschem attributes for spice netlisting

There are several ways that spice attributes may be associated with a component using gschem. The way you choose to do this depends upon many factors, including the type of component, and the size and format of the SPICE model.

Component attributes and meanings

The following attributes are meaningful for SPICE netlisting, and may be attached from within gschem:

refdesThe reference designator of the component. Valid values depend upon the component type and are given in the appendix.
valueFor passives, this is the component value. For actives, this is the type (model no) of the component (e.g. 2N3904, uA741). When a model for an active is instantiated separately from the component itself, the “value” attribute holds the name of the spice model.
modelThis holds a one line spice model for the component.
fileThis holds the name of a file. Typically, this is a file holding e.g. a SPICE .MODEL, .SUBCKT, or other SPICE code.
model-nameThis holds the name of the spice model referred to in a .MODEL or .SUBCKT statement. “model-name” is mainly used to identify the spice model name in the symbol “spice-model-1.sym”. Active components should call out this name in the “device” attribute to associate the component with its particular spice model or subcircuit.
typeThis specifies the type of component and is used by spice when interpreting the model parameters. Valid values depend upon the device being modeled.

refdes conventions

As a prerequisite to handling SPICE-related attributes, the SPICE netlister requires that all components must have a refdes attached to them. The refdes may be attached either by hand (which is laborious), or using the program refdes_renum included in the gEDA distribution.
Note that the first letter of the refdes must correspond to the appropriate letter for spice simulation. The refdes convention is given in the Appendix.

Passives

Basic passives

The most basic components which one encounters in spice are passive components like resistors and capacitors which have numeric values, but no other modeling attributes. In this case the following attributes must be filled in:

refdesThe correct refdes for the component.
valueFor passives, this is the numeric value of the component (e.g. 100pF). For actives, this attribute may be filled in, but if no model attribute is available elsewhere in the schematic, the value is not used (in SPICE netlisting, anyway).

If only a refdes and value attribute are encountered, the netlister will write a single line into the output file.
Example resistor:

refdes = R2
value = 220
SPICE line generated: R2 0 4 220

Note that “0” and “4” correspond to the net nodes connected to the component, and are generated automatically by gnetlist.
Example capacitor:

refdes = C22
value = 1UF
SPICE line generated: C22 4 23 1UF
Passives with additional attributes

Oftentimes, passive components have additional attributes attached to them for spice simulation. Examples of such attributes are temperature coefficients (for resistors) and initial conditions (for reactive components). These additional components may be incorporated into the SPICE file by simply attaching them to the component’s “model” attribute. Specifically, the required attributes are:

refdesCorrect component refdes.
valueNumerical component value, as always.
modelOne line string holding additional parameters, formatted as a valid SPICE string.

This string is placed after the component value in the line generated by gnetlist. Therefore, it is important to format the string placed in the model line to be valid SPICE code. Otherwise, you will risk causing the SPICE simulator to barf.
Example resistor:

refdes = R5
value = 1MEG
model = TC=0.001,0.015
SPICE line generated: R2 0 4 220 TC=0.001,0.015

Transistors and diodes

Transistors and diodes are generally accompanied by a device-specific model – otherwise, SPICE simulation is pointless. The SPICE model may be either a short, one-line string of parameters, or a multi-line set of SPICE parameters. A typical one-line parameter string is a short list of parameters describing a small-signal diode. Typical multi-line models come from component vendors, who often provide models for their components in a text file. Since there are two broad formats of SPICE information, there are two approaches to incorporating these parameters into the schematic:

One line string of SPICE parameters

To incorporate a one line string of SPICE parameters into the netlist, the following attributes must be attached to the component:

refdesCorrect component refdes.
valueThe model number or part number of the component.
model-nameThe name you wish to give the SPICE model. This is usually the model number or part number of the component. If you have already attached a “value” attribute to the component, this parameter is optional.
modelOne line string holding additional parameters. Do not place the model parameters in parentheses – gnetlist will do this for you.

Example diode:

refdes = D5
model-name = 1N1004
model = IS=0.5UA RS=6 BV=5.20
SPICE lines generated:
D5 2 6 1N1004
MODEL 1N1004 D (IS=0.5UA RS=6 BV=5.20)
SPICE model file

To incorporate a file-full of SPICE parameters into the netlist, the following attributes must be attached to the component:

refdesCorrect component refdes.
valueThe model number or part number of the component.
model-nameThe name you wish to give the SPICE model. This is usually the model number or part number of the component. If you have already attached a “value” attribute to the component, this parameter is optional.
fileThe file name of the SPICE model which you wish to incorporate into the netlist. This file name may specify either a relative or an absolute path, but it is probably better to use an absolute path to avoid problems if you ever move your schematic directory.

Note that you need to make sure that the model name held in your SPICE model file is the same as the value or model-name attributes you attached to the component. It is also a good idea to verify that the pin assignments in the model file correspond to the pin assignments made by the component symbol.

Actives -- integrated circuits

Integrated circuits are incorporated into the netlist similarly to transistors and diodes. As such, you may incorporate the spice information either as a one-line parameter string, or as a model file.

One line string of SPICE parameters

To incorporate a one line string of SPICE parameters into the netlist, the following attributes must be attached to the component:

refdesCorrect component refdes.
valueThe model number or part number of the component.
model-namethe name you wish to give the SPICE model. This is usually the model number or part number of the component. If you have already attached a “value” attribute to the component, this parameter is optional.
modelOne line string holding additional parameters. Do not place the model parameters in parentheses – gnetlist will do this for you.
SPICE .MODEL or .SUBCKT file

To incorporate a file-full of SPICE parameters into the netlist, the following attributes must be attached to the component:

refdesCorrect component refdes. Note that if the file holds a .MODEL, the refdes should start with U; if the file holds a .SUBCKT, the refdes should start with X. The netlister checks for the file type and tries to “do the right thing”, but problems can arise if you don’t follow this rule.
valueThe model number or part number of the component.
model-nameThe name you wish to give the SPICE model. This is usually the model number or part number of the component. If you have already attached a “value” attribute to the component, this parameter is optional.
fileThe name of the file holding the SPICE .MODEL or .SUBCKT which you wish to incorporate into the netlist. This file name may specify either a relative or an absolute path, but it is probably better to use an absolute path to avoid problems if you ever move your schematic directory.

Independent sources

There are two independent sources: voltage sources and current sources. For incorporation into a SPICE netlist, they both work the same way. To incorporate an independent source into your SPICE netlist, do the following:

  1. Place the independent source on your schematic. (Do “Add” → “Component” → “spice” → "<independent source name>.sym”)
  2. Double click on the block and add/edit the following attributes:
    • refdes: V? or I?
    • value: A one line string in SPICE format describing the source.

Dependent sources

There are four dependent sources:

SPICE components

Spice model block

In certain situations, you may wish to embed a spice model block directly into your schematic. This is done when you have several devices with a “value” attribute calling out for a spice model. Depending upon whether the spice block is one line or multi-line, you may embed the code in one of two ways:

  1. One line SPICE model:
    1. Place a spice model block on your schematic. (Do “Add” → “Component” → “spice” → “spice-model-1.sym”)
    2. Double click on the block and add/edit the following attributes:
      • refdes: a?
      • model: model name (i.e. the model name used in the components being modeled.)
      • type: One of the valid spice component types defined in the spice spec.
      • value: The corresponding one-line spice model
  2. Multi-line SPICE model:
    1. Place a spice model block on your schematic.(Do “Add” → “Component” → “spice” → “spice-model-1.sym”)
    2. Double click on the block and add/edit the following attributes:
      • refdes: a?
      • model-name: model name
      • file: Name of file holding SPICE model code (i.e. .MODEL or .SUBCKT).
Include block

The include block places a .INCLUDE directive into your netlist.

  1. Place a spice model block on your schematic. (Do “Add” → “Component” → “spice” → “spice-include-1.sym”)
  2. Double click on the block and add/edit the following attributes:
    • refdes: a?
    • file: The name of the file to include.
SPICE directive block

Placing a SPICE directive block into your schematic creates an arbitrary block of SPICE code in the netlist. The directive may be either statements held in a file, or a one-line string held in the “model” attribute. Examples of situations where this is useful include:

To place a SPICE directive on your schematic, do the following:

  1. Place a SPICE directive block on your schematic. (Do “Add” → “Component” → “spice” → “spice-directive-1.sym”)
  2. Double click on the block and add/edit the following attributes:
    • refdes: a?
    • file: The name of the file to include.

Handling hierarchical models

In SPICE modeling, there are often situations where you wish to create a schematic representation of some particular component as a .SUBCKT, and then embed that component’s model in a higher level schematic. A common example might be as follows: You are doing a microwave simulation, and want to use a capacitor model which includes parasitic inductances and resistances, as well as the capacitance. Capacitor manufacturers often supply a printed schematic showing a circuit topology incorporating parasitics, and specify values for the parasitics. You would like to draw the capacitor model using gschem, netlist it to create a .SUBCKT, and then use the .SUBCKT to model capacitors in a higher lever schematic.
Since this kind of task is very common in SPICE simulation, gnet-spice-sdb now supports it (starting with rev 20030331). To create a lower level .SUBCKT and use it in a higher level schematic, do the following:

  1. Draw the schematic of the lower level component (e.g. the capacitor + parasitics) using gschem.
  2. On the lower level schematic, place a spice-subcircuit-LL block (spice-subcircuit-LL-1.sym). This alerts the netlister that the schematic is a Lower Level .SUBCKT. Attach the following attributes to the symbol:

    model-name = cap_with_parasitics

    (Of course, “cap_with_parasitics” is the example we use here. Use your own model name in your schematic.) Upon netlisting, this schematic symbol will cause the netlist to insert ".SUBCKT cap_with_parasitics " into the first line of the netlist file.
  3. On the lower level schematic, attach a spice-subcircuit-IO symbol (spice-subcircuit-IO-1.sym) to each IO net (i.e. connection to the upper level). Number the refdeses of the IO symbols in the same order as you would like the IO nets to be listed in the .SUBCKT line in the output file. (i.e. P1 = first, P2 = second, etc.)
  4. When you are done with the lower level schematic, netlist it in the usual way. For example, if your schematic is called cap_with_parasitics.sch, netlist it by saying:

    gnetlist -g spice-sdb -o cap_with_parasitics.cir cap_with_parasitics.sch

    This will dump the SPICE netlist into the file called “cap_with_parasitics.cir”. Visually inspect the .cir file to make sure that netlisting worked correctly.
  5. Next, create a symbol for the upper level schematic which will point to the .SUBCKT. Note that the symbol must have a refdes starting with the letter “X”. To ensure that this happens, do the following:
    • Use gschem to draw the symbol. I usually draw a box around a model symbol to distinguish it from a normal component. Make any other annotations desired.
    • In the symbol, make sure that the pins are ordered identically to the order in which you have placed the pins in the .SUBCKT. This is done by editing the symbol with a text editor and setting the “PINSEQ” attribute. The netlister will output the pins in the order determined by the “PINSEQ” attribute.
    • Using a text editor, give the symbol a “DEVICE” attribute like “capacitor-model”. Do not assign the symbol one of the native device types listed in the appendix! The goal is to create a symbol whose refdes starts with “X”, and if the “DEVICE” is a recognized type, this will not happen.
    • Using a text editor, give the symbol the “REFDES” attribute “X?"
  6. Create the upper level schematic. Place your newly created symbol on the schematic as many times as required & wire up the schematic in the usual way.
  7. To point your symbol to the lower level .SUBCKT, double click on the symbol and set the following attributes:

    file = cap_with_parasitics.cir
    model-name = cap_with_parasitics

    as well as any other attributes required (e.g. refdes).
  8. Now netlist your upper level schematic the usual way. The contents of each .SUBCKT file is dumped into the main netlist. Inspect your netlist visually using a text editor to ensure that it is correct. It is a good idea to pay particular attention to the following:
    • Verify that the ordering of the nets connecting the upper level netlist to the lower level .SUBCKT is correct.
    • Make sure that the upper level model-name and the lower level model name (on the .SUBCKT declaration line) are the same.

Once the netlist is created, you may simulate your design using any SPICE simulator desired.

One final note: The netlister writes the contents of the lower level .SUBCKT file into the main netlist every time it encounters a component with “FILE” attribute pointing to that file. Therefore, if you use the same component with the same model more than once in a design you should instantiate the model file using a “spice-model” symbol and point to it with each component. This is described in the “multi-line SPICE model block” section above.

SPICE netlist generation

Once the schematic is captured, a SPICE netlist can be generated running the gEDA utility “gnetlist” on the schematic files. Gnetlist is built to be customizable, and is able to generate a netlist of any desired format using a Scheme back-end, which does the real heavy-lifting of creating the netlist. The back-end Scheme file which implements SPICE netlisting is called gnet-spice-sdb.scm, and it lives in the ${PREFIX}/geda/share/gEDA/scheme directory.

Creating the netlist

Creating a netlist from a schematic is easy. To generate a SPICE netlist, just do the following:

Common netlisting problems

It is important to manually inspect your SPICE netlist prior to using it in simulation. Please remember that the netlister is still “alpha” quality, and some problems may still exist in netlist generation. The following list attempts to catalog common problems with the netlist and the associated fixes.

SPICE simulation

There are several options for doing SPICE simulations under Linux; I will highlight two:

There is also a GPL‘ed simulator called “gnucap”, which is based upon (or is the descendent of) Al’s Circuit Simulator (ACS). I haven’t used it at all; information about gnucap is therefore TBD.

LTSpice

LTSpice was written by Mike Englehardt at Linear Technologies, and was originally given away by LinearTech as a design aid for engineers wishing to simulate the performance of LinearTech’s switch mode power supply controllers. The package incorporates a schematic capture front end, fast and powerful SPICE engine, and the capability for plotting the results of many different types of SPICE analysis. Personally, I think the schematic capture front-end is hard to use and clunky; gschem knocks its socks off for ease of use and features. However, the SPICE engine and analysis stuff in LTSpice is simply great.
LTSpice was originally developed to run under Windows, but Mike has tweaked it so that it runs fairly well on Linux under wine. (Only the help menu system is broken – the rest of the package runs well.) Another good feature of LTSpice is that it is well supported – Mike reads the newsgroup sci.electronics.cad regularly and is generally happy to help people who experience problems with it. Therefore, despite its Windoze heritage, I recommend LTSpice as a powerful, professional-quality simulation and analysis back end for gEDA.

Installation and configuration of LTSpice

To install and configure LTSpice, do the following:

  1. Download and install wine. I have had success using Wine-20030219.
  2. Download LTSpice. It is available under http://www.linear.com/software under the name SwitcherCAD-III.
  3. Run the LTSpice installer under wine.

Running LTSpice with gEDA designs

LTSpice can read a file holding a gEDA SPICE netlist. I have had success doing LTSpice sumulations in the following way:

  1. First of all, make sure that you are logged in as a normal user – Wine doesn’t like to run when invoked by root.
  2. Create a file in your project directory called “Simulation.cmd”. In this file place your spice analysis commands (e.g. .OP, .AC, .DC, etc.)
  3. Place a SPICE include block into your schematic. For the file attribute, type in “Simulation.cmd”.
  4. Netlist your design.
  5. Create a link from your netlist “output.net” and a netlist in the directory in which SwCADIII lives. Make the netlist suffix .cir. For example: ln -s ${DESIGN_HOME}/output.net ${WINE_HOME}/.wine/fake_windows/Program Files/LTC/SwCADIII/MyDesign.cir
  6. Run LTSpice: cd into the directory where SwCADIII lives and say “wine scad3.exe”
  7. From the SwCADIII GUI, do: File → Open → (files of type netlist [.cir]), and select your file.
  8. Run the simulator by clicking on the run button, or doing: Simulate → Run.
  9. Select the variables to graph, and then click OK. SwCADIII does the rest of the work.

Naturally, it is very important to play around with LTSpice to understand how to use it effectively, but the above description should suffice to get you started.

Ngspice and tclspice

Ngspice was started at the University of Rome by Paolo Nenzi as an attempt to create a GPL‘ed version of the standard Berkeley SPICE version 3 by re-writing the entire SPICE package. Plans were also laid to create better, more robust computational algorithms for the simulation engine. More information is available at the ngspice website. Unfortunately, development on ngspice seems to have ceased at the end of 2001. Moreover, my initial experiences with ngspice were not good – it crashed and burned when run on many of my netlists, and it couldn’t deal with SPICE 2’s POLY construct in dependent sources. Dependent sources with PLOY attributes are common in vendor models, so this represents a real deficiency.

Fortunately, some friendly people at MultiGig Ltd. were busy developing a branch of ngspice which they called “tclspice”. The purpose of tclspice is to enable SPICE commands to be embedded into TCL scripts, thereby enabling automated circuit optimization. The project homepage is at http://tclspice.sourceforge.net/. Since the tclspice branch of the code was alive, I decided to work on it, instead of the seemingly dead main ngspice branch. During spring 2003, I fixed tclspice in three useful (IMNSHO) ways:

  1. I fixed the parser so that it would handle netnames with non-numeric/non-alphabetic characters like "+" or "-" which are common in real netlists (e.g. “Vin+", or “Vout1_pull-up”).
  2. I fixed the parser so that it would correctly handle hierarchical schematics, and correctly deal with the netnames inside the blocks.
  3. I got the POLY translation code (which exists in XSPICE) working so that one can now run SPICE 2 netlists with tclspice.

Tclspice seems to work nicely now (although there are still some issues with memory leaks). Moreover, because the tclspice code is a superset of ngspice, if you build tclspice, you will also build the command-line driven ngspice program. Therefore, I recommend getting and installing tclspice if you want to do Linux-native SPICE simulations.

Installation and configuration of ngspice and tclspice

To install ngspice and tclspice, do the following:

  1. Get the latest tclspice distribution from http://tclspice.sourceforge.net/. As of this writing, the latest version is tclspice-0.2.12. This version incorporates the fixes I mentioned above, as well as other improvements made by the hard-working people at MultiGig, so make sure that your version is equal or greater than 0.2.12.
  2. Do the usual “gunzip ; tar -xvf” dance to create a source directory for tclspice.
  3. First build ngspice. Do "./configure –enable-xspice –prefix=/usr/local/geda” in the source directory. Of course, "–prefix=" should point to the place where you put your geda stuff. Note that you also must do "–enable-xspice” to be able to use SPICE 2 POLYs (and other XSpice goodies).
  4. Do “make && make install” to compile and install ngspice. As always, you will probably need to be root in order to install the packages in a public directory.
  5. At this point, you should be able to use ngspice. You can test your installation by trying one of the test circuits held in the tests directory. I recommend running the TransImpedanceAmp test, since it tests the SPICE2 POLY functionality. Information how to use ngspice is provided in the next section below.
  6. If you only want to use ngspice, you can stop now. Otherwise, next build tclspice. To build tclspice, you need to have the following other packages already installed:

    * TclX (tclx8.3.5 works for me.)
    * tclreadline (tclreadline-2.1.0 works for me.)
    * BLT for TCL (blt2.4z works for me.)

    If you don’t have these packages already on your Linux box, you need to get them and build them. Note that building TclX requires having the sources for TCL and Tk, so you will also need to get those sources if you don’t have them installed already. I am running successfully with TCL/Tk 8.4.3, although 8.3.X versions are also supposed to work.
  7. Assuming you have gotten the additional packages mentioned above installed, Do "./configure –enable-xspice –prefix=/usr/local/geda –enable-tcl –enable-experimental –disable-shared” to configure the Makefiles for tclspice. (If you don’t have the additional packages installed correctly , configure will complain and barf, so this step acts as a check on your installation.)
  8. Do “make tcl && make install-tcl” to compile and install tclspice.
  9. Now you will be ready to write TCL scripts which incorporate SPICE commands. Information about using tclspice is given below.

Finally, if you are interested in hacking tclspice (or even if you are not), it’s a good idea to read the NOTES file living in the top source directory for a couple of useful pointers.

Use of ngspice

Running ngspice is very simple. Just issue the command “ngspice filename.net” at the unix command prompt, and ngspice will load the SPICE netlist called “filename.net” into its workspace, and leave you at an ngspice command prompt. You can run the simulator by saying “run”. Your results will be stored in SPICE vectors for later printing or plotting. The command set available to you is documented at http://newton.ex.ac.uk/teaching/CDHW/Electronics2/userguide/sec5.html#5.
To make use of the SPICE2 POLY codemodel, you need to load it into ngspice before you load your netlist. (If you load it after loading your netlist, POLYs in your netlist are not translated, and therefore won’t be simulated correctly.) To load the codemodel, just say “codemodel /usr/local/src/tclspice-0.2.12/src/xspice/icm/spice2poly.cm” at the ngspice prompt. Note that you must provide the absolute path to the location of the codemodel; ngspice isn’t smart enough to look for it in any default locations. (Also note that you should specify the location where spice2poly.cm lives on your machine; the path above is for mine.)
A better way to read in the spice2poly codemodel is to include it in the ngspice initialization file, “spinit”. The initialization file lives in the directory /usr/local/geda/share/ng-spice-rework/scripts (or where ever you placed your geda installation). Other ngspice customizations may also be placed into the spinit file.

Use of tclspice

The tclspice package is a superset of ngspice. Not only does the package include the ngspice interactive environment; tclspice also provides a facility which exports the ngspice command set as TCL commands for inclusion into a TCL script. This is a very powerful tool: With tclspice you can write a TCL script which runs a loop, tweaks component values, runs an analysis, and then evaluates the circuit performance with the tweaked components before looping again. Obviously, this ability can be used to perform automated, multi-dimensional circuit optimization.
To use tclspice, you just need to say “package require spice” at the beginning of your TCL program. Thereafter, to invoke a SPICE command, you just call it in the spice namesapce. For example, the following TCL program will read in a SPICE netlist, command a transient analysis, run the simulation, and then plot the voltage observed over time on net Vout:

#! tclsh
package require spice
spice::codemodel /usr/local/src/tclspice-0.2.12/src/xspice/icm/spice2poly.cm

spice::source netlistname.cir
spice::tran 0.1ns 40ns
spice::run
spice::plot Vout
puts "All done now!"

Note that since tclspice doesn’t read the ngspice initialization file “spinit”, you will need to put any initialization commands directly into the TCL program. For example, in the above example we read the spice2poly codemodel directly into the workspace. Many other commands are also available; the entire tclspice commandset is documented at http://tclspice.sourceforge.net/docs/tclspice_com.html.
A major problem with tclspice (which was inherited from ngspice) is that it leaks memory. Therefore, the time over which you may run a simulation is limited. This means that if you want to do an optimization by looping through a circuit many, many times, you may run out of memory before your program has completed its optimization. This is a known issue with tclspice, and efforts are underway to plug the leaks.
Meanwhile, there are some workarounds which can be used on moderate-sized designs to facilitate long optimization runs. One method I have employed is to have the optimizer write its current state into a file after every circuit analysis, and read its starting state from the same file. The optimizer also stores the current list of best components in another file, and reads this file at the start of every run. Then, I have a TCL program called TaskMgr.tcl which runs in a loop; at each iteration of the loop it forks a child process to run the optimizer. Meanwhile, the parent process waits for 5 minutes (a heuristically determined time), and then issues a “KILL” signal to the child before looping and starting the optimizer again. This way, the optimizer never runs long enough to consume all the memory in my machine. The TaskMgr.tcl program is shown here:

#! tclsh
package require Tclx
while {1} {

    set PID [fork]
    if {$PID} {

        # Parent
        after 300000
        puts "About to kill child PID = $PID . . . ."
        kill $PID
        wait $PID

    } else {

        # Child
        source Optimize.tcl
        # If we ever get through this, we can print out the following:
        error "We are done now!!!!!!" 

    } 

}

Note that TaskMgr.tcl needs the TclX package you already installed to run tclspice. Also, you may want to change the wait time to a different value depending upon the memory and speed of your machine. Finally, the parent has to wait on $PID because that causes the child process’s corpse to be taken off the Linux kernal’s task list when it dies. Otherwise, you will end up with a lot of zombie processes lurking around your machine as the optimizer runs – a long optimization could turn your system into “the night of the living dead”!
This method of waiting a specific amout of time for the child process is preferable if a single analysis run takes a relativly short time compared to the time required to eat all memory in the machine. If the analysis time is comparable to the time taken to eat all memory in the machine, a better approach is to have the parent keep track of the analysis state, kick off a single analysis run, and then have the run terminate after every iteration. Whether this is preferable depends upon the size and complexity of your design; you may want to experiment with your analysis to see just how long it takes and how much memory it consumes. I have found that a design comprised of six op amps (with corresponding vendor models) and 50 or so passives will run in under 10 seconds on a PIII 333MHz with 128MB RAM. Therefore, your design must be very big before a single analysis will eat a significant amount of RAM.

Appendix

Component attribute summary

Native components and their attributes are given in the table below. Bold faced attributes are required, normal typeface attributes are optional. Note that the “device” attribute is invisible, and is normally attached to the symbol when it is created. The other attributes are attached to the symbol during schematic capture using gschem.

devicerefdesvaluemodelfilemodel-nametypeComment
RESISTORR?Numeric comp. valueOne line of spice model parameters (e.g. TC) Name of model. “model” parameters are placed inside parentheses after the component value.
CAPACITORC?Numeric comp. valueOne line of spice model parameters (e.g. IC, POLY, etc.) Name of model. “model” parameters are placed inside parentheses after the component value.
POLARIZED_CAPACITORC?Numeric comp. valueOne line of spice model parameters (e.g. IC, POLY, etc.) Name of model. “model” parameters are placed inside parentheses after the component value.
INDUCTORL?Numeric comp. valueOne line of spice model parameters (e.g. IC, POLY, etc.) Name of model. “model” parameters are placed inside parentheses after the component value.
SPICE-ccvsH?String describing source behavior
SPICE-cccsF?String describing source behavior
SPICE-vcvsE?String describing source behavior
SPICE-vccsG?String describing source behavior
SPICE-nullorE?String describing source behavior
DIODED?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
PMOS_TRANSISTORM?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
NMOS_TRANSISTORM?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
PNP_TRANSISTORQ?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
NPN_TRANSISTORQ?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
PFET_TRANSISTOR (JFET)J?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
NFET_TRANSISTOR (JFET)J?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
MESFET_TRANSISTORB?Part numberOne line SPICE model.Model file name.Name of model. For modeling, one must include either “model” or “file”.
ICU?Part numberOne line SPICE model.Model file name.Name of model. IC with .MODEL file
ICX?Part number Model file name.Name of model. IC with .SUBCKT file
modelA?One line spice modelModel file name.Name of model pointed to by other components.Corresponding SPICE model type (valid types given below).For modeling, one must include either “model” or “file”.
includeA? Include file name. Places .INCLUDE directive in SPICE netlist.
optionsA?Line of options to include. Places .OPTIONS directive in SPICE netlist.
directiveA?One line string holding SPICE statements for inclusion in netlist. For modeling, one must include either “model” or “file”.
VOLTAGE_SOURCEV?One line string holding voltage source behavior. Independent voltage source
CURRENT_SOURCEI?One line string holding current source behavior. Independent current source

“Native to the netlister” means that there is a corresponding blob of scheme code which knows exactly how to handle these components and is guaranteed (almost) to generate correct spice code. Symbols having “device” attributes not on the above list are handled using the scheme function “spice-sdb:write-default-component”, which looks at the refdes of the component to make a decision about how to treat the component. In general, this function will “do the right thing” when generating spice code, but it is not guaranteed. In particular, this function cannot distinguish between N and P type transistors, and will generate an <unknown> type for the .MODEL string in the netlist. This will probably cause your SPICE simulator to barf. Therefore, it is best to make sure that all devices used have the proper “device” attribute.

Valid "type" values

The “type” attribute is a flag signaling the spice engine the component type, and prepares it to accept model parameters specific to that component type. The following values are valid SPICE “type”s:

Component“type”Comment
RESISTORRES
CAPACITORCAP
POLARIZED_CAPACITORCAP
INDUCTORIND
DIODED
PMOS_TRANSISTORPMOS
NMOS_TRANSISTORNMOS
PNP_TRANSISTORPNP
NPN_TRANSISTORNPN
PFET_TRANSISTORPJF
NFET_TRANSISTORNJF
MESFET_TRANSISTOR

Document History

Revision 1.03.10.2003SDBDocument creation.
Revision 1.13.19.2003SDBAdded .SUBCKT stuff & stuff about LTSpice
Revision 1.23.31.2003SDBAdded stuff about creating hierarchical projects (i.e. creating .SUBCKTs using gschem and incorporating a lower level .SUBCKT into a higher level schematic).
Revision 2.07.23.2003SDBSplit doc into sections. Edited netlisting stuff to correspond to gEDA-20030525, which now includes spice-sdb in the distribution. Added new section about ngspice/tclspice.

The most recent copy of this document is always available at http://www.brorson.com/gEDA/SPICE/