Using Python with ngspice

From Microlab Classes
Jump to navigation Jump to search

We can automate this process by using ngspice in batch mode, i.e. running the simulator from the command line, and reading the output file using Python, and do the processing automatically. To run ngspice at the command line, you can use ngspice <circuit file>.

One very good environment for Python3 is Spyder. You can download this for multiple platforms, and the easiest way to install Spyder is as part of the Anaconda distribution, also available for various operating systems.

Running ngspice from Python

Below is a simple Python script for running ngspice, reading its output. It uses the ngspice_link module, that contains convenient classes and functions for running ngspice from within Python.

 1 import matplotlib.pyplot as plt
 2 from si_prefix import si_format
 3 import ngspice_link as ngl
 4 
 5 cfg = {
 6         'ngspice' : '/Applications/ngspice/bin/ngspice', 
 7         'cir_dir' : '/Users/louis/Documents/UPEEEI/Classes/EE 220/2020_1/Activities/',
 8         'cir_file' : 'circuit1.sp',
 9         }
10 
11 sim1 = ngl.ngspice(cfg)
12 sim1.run_ngspice()
13 
14 vbe, [ic] = sim1.read_dc_analysis('circuit1.dat', [1])
15 
16 # define the plot parameters
17 plt_cfg = {
18         'grid_linestyle' : 'dotted',
19         'title' : r'2N2222a NPN BJT Transfer Characteristics',
20         'xlabel' : r'$V_{BE}$ [mV]',
21         'ylabel' : r'$I_C$ [mA]',
22         'legend_loc' : 'lower left',
23         'add_legend' : False,
24         'legend_title' : None
25         }
26 
27 fig = plt.figure()
28 ax = fig.add_subplot(1, 1, 1)
29 ax.plot(ngl.scale_vec(vbe, 1e-3), ngl.scale_vec(ic, 1e-3), '-')
30 
31 ngl.add_hline_text(ax, 1, 550, \
32         r'{:.1f} mA'.format(1))
33 
34 idx, icx = ngl.find_in_data(ic, 1e-3) 
35 
36 ngl.add_vline_text(ax, vbe[idx]/1e-3, 3, r'$V_{BE}=$' + \
37         si_format(vbe[idx], precision=2) + 'V')
38     
39 ngl.label_plot(plt_cfg, fig, ax)
40 plt.savefig('BJT_2n2222a_transfer.png', dpi=600)