PySpice-org / PySpice

Simulate electronic circuit using Python and the Ngspice / Xyce simulators
https://pyspice.fabrice-salvaire.fr
GNU General Public License v3.0
661 stars 175 forks source link

Bug when using "save all" #342

Open medwatt opened 1 year ago

medwatt commented 1 year ago

Environment (OS, Python version, PySpice version, simulator)

OS: Manjaro Linux Python version: 3.10 Pyspice version: 1.5 Simulator: ngspice

from PySpice.Spice.Netlist import Circuit # for creating circuits

circuit = Circuit('MOS circuit')
circuit.V('GG', 'VGG', 0, 2.5)
circuit.V('DD', 'VDD', 0, 5)
circuit.R('D', 'VDD', 'VD', 1e3)
circuit.M('n', 'VD', 'VGG', 0, 0, model='NMOS-SH', l=1e-6, w=10e-6)
circuit.model('NMOS-SH', 'nmos', Kp=190E-6, Vto=0.57, Lambda=0.16, Gamma=0.50, Phi=0.7)

simulator = circuit.simulator(temperature=25, nominal_temperature=25)
parameter_names = ["gm", "gds", "id"]
simulator.save_internal_parameters(*[f'@mn[{param}]' for param in parameter_names])
analysis = simulator.dc(VGG=slice(0, 5, 0.1))

The correct netlist above should be:

.title MOS circuit
VGG VGG 0 2.5
VDD VDD 0 5
RD VDD VD 1000.0
Mn VD VGG 0 0 NMOS-SH l=1e-06 w=1e-05
.model NMOS-SH nmos (Gamma=0.5 Kp=0.00019 Lambda=0.16 Phi=0.7 Vto=0.57)
.options TEMP = 25C
.options TNOM = 25C
.save all @mn[gm] @mn[gds] @mn[id]
.dc VG 0 5 0.1
.end

The netlist that is produced by the python code is the same as the above except that instead of .save all @mn[gm] @mn[gds] @mn[id], it has .save @mn[gm] @mn[gds] @mn[id]. The all is removed from the netlist.

I tracked down the cause and it seems that you are making two calls to the __str__ function here. The first call removes the word all (see here) from self._saved_nodes. The call before the circuit is passed to the simulator (see here) also makes a call the __str__ method to build the netlist. At this point, the "all" in "save all" is completely lost.

medwatt commented 1 year ago

This issue can be solved by replacing this line with:

saved_nodes = self._saved_nodes.copy()