Using NgSpice in Python Jupyter for circuit simulation

TL;DR check https://github.com/chenshuo/notes/blob/master/notebooks/AnalogCircuits.ipynb for example.

Disclaimer: I am a electronic hobbist, not a professional electronic engineer. I enjoy studying / soldering circuits for fun in my spare time, but do not make a living on it.

There are many free / online tools for circuit simulation, among those, I think LTspice is the best free tool after all. It's a professional tool, not a toy. According to SPICE Differentiation by Michael Engelhardt (Jun 19, 2015), LTspice's simulation result is sometimes better than other commercial SPICE descendants.

However, it doesn't quite fit my needs

  1. It runs on Windows, I'd like to use it on Linux. It's runnable on Wine, though.
  2. Its schematic capture doesn't look pretty.
  3. Screenshots for taking notes.

1 & 2 are not problems for professional engineers, but 3 are really not convenient for studying variants of a circult (tweaking parameters or topology), or running a series of simulations of the same circult (DC, tran, ac). Because screenshots are not searchable.

For undergradude level circuit analysis and analog circuit courses, I found NgSpice + Python Jupyter are a good combination.

  1. Jupyter Notebook (JupyterLab)
    • Note taking using Markdown with TeX for math formulas.
    • A series of simulations in one notebook file, instead of spliting into many small schematic.
    • No need to learn and use the awkward scripting language from SPICE, instead, use Python for control and glue.
    • Visulization with matplotlib, manipulating data using NumPy.
    • Analysis data using NumPy, e.g. linear regession, polynomial fitting, parameter optimization.
  2. Text format (The Importance of Being Textual)
    • Version control, using git(1), and hosted on GitHub, easy for sharing and collaboration. No proprietary software needed to view, just any web broswer.
    • Easy to copy and make a few changes of the same circuit, and more importantly, easy to diff what has changes between two versions.
  3. NgSpice (via ignamv's ngspyce binding library)
    • Runs well on Linux and Windows (and maybe Mac). It's loaded as a shared library (or dynamic linked library on Windows) into Python "kernel", and communicates with Python code seemlessly, input is text (Python string), output is NumPy arrays.
    • It takes some efforts to find models, but it's worth the time as the models are just text files, and can be embeded in the Jupyter notebook.
However, drawing schematic is a bit difficiult, if you don't want to lean Circuitikz, you will probably need to paste in screenshots of some schematic software, like KiCAD. Also, you have to describe the circuit to SPICE using text format.  If you prefer graphic user interfaces, this might not work for you.

Anyway, I found it quite suitable for myself, here's a basic example:

https://github.com/chenshuo/notes/blob/master/notebooks/AnalogCircuits.ipynb

0 comments: