Electrical – How does Spice parse a netlist

spice

From this discussion about Spice internals, it looks that Spice builds a matrix for a netlist. I wonder how it does it in detail, e.g. for simple circuit to write a simple parser.

E.g. :

R1  1  2  4
V1  2  1  2

How can a data structure of this circuit look like?

Best Answer

I haven't quite looked at the SPICE source code, but I've looked at GNUCAP more than a few times.

Generally, there will be a base class (or structure) for any component that you would put in a circuit. Then, components like resistors and voltage sources can inherit from this base class.

Here's what it might look like in C++

#include <vector>

// circuit base
// ctk is a common abbreviation in GNUCAP
class CtkBase
{
    std::vector<int> inputs;
    std::vector<int> outputs;
public:
    CtkBase (void);
    virtual ~CtkBase (void);
    virtual add_input (int n);
    virtual add_output (int n);
};

class Resistor final : public CtkBase
{
  double value;
public:
  Resistor (void);
  ~Resistor (void);
  void set_value (double value);
};

class VoltageSource final : public CtkBase
{
  double value;
public:
  VoltageSource (void);
  ~VoltageSource (void);
  void set_value (double value);
};

class Ctk final
{
  std::vector <CtkBase*> components;
public:
  Ctk (void);
  ~Ctk (void);
  void add_component (CtkBase *base);
};

int
main (void)
{
  auto r1 = new Resistor;
  r1->set_value(200.00);
  r1->add_input(1);
  r1->add_output(0);

  auto vcc = new VolatageSource();
  vcc->set_value(5.00);
  vcc->add_input(0);
  vcc->add_output(1);

  Ctk ctk;
  ctk.add_component(r1);
  ctk.add_component(vcc);

  // do stuff here

  return 0;
}

And the 'doing stuff' section is entirely up to you. I'd recommend learning about the Visitor design pattern, if you are going to be analyzing or modifying the circuit structure in anyway.

You could probably add another base class called Component, that will be inherited by Resistor and VoltageSource that contains the value member, and trim off a few lines of code (if you wanted to).