pyspice-org / pyspice Goto Github PK
View Code? Open in Web Editor NEWSimulate electronic circuit using Python and the Ngspice / Xyce simulators
Home Page: https://pyspice.fabrice-salvaire.fr
License: GNU General Public License v3.0
Simulate electronic circuit using Python and the Ngspice / Xyce simulators
Home Page: https://pyspice.fabrice-salvaire.fr
License: GNU General Public License v3.0
examples/ngspice-shared/voltage-divider.py crashes in simulation.
Ubuntu 14.04, PySpice 0.3.0, cffi.version=='1.8.3', ngspice revision 24
Shared.py:360 (called from ngspiceshared-imp)
self = ffi.from_handle(user_data) <<<<< says something about garbage data
Change(Shared.py:335)
self_c = ffi.new_handle(self) <<<<< local variable! will be garbage collected when method returns
to
self.self_c = ffi.new_handle(self)
and
ngspice_id_c = ffi.new('int *', self._ngspice_id)
to
self.ngspice_id_c = ffi.new('int *', self._ngspice_id)
Device model BAV21: Illegal parameter(s) given for level 1 diode: IKF
I don't think the transformer example is complete. The Transformer Module does not seem to be in the repository.
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
PySpice/examples/transformer/transformer.py in <module>()
17 ####################################################################################################
18
---> 19 from Transformer import Transformer
20
21 ####################################################################################################
ImportError: No module named 'Transformer'
e.g. current flowing through a resistor (Vp - Vm)/R
On http://readthedocs.org/projects/pyspice
Exception occurred:
File "/home/docs/checkouts/readthedocs.org/user_builds/pyspice/envs/latest/lib/python3.5/site-packages/sphinx/writers/latex.py", line 2238, in unknown_visit
raise NotImplementedError('Unknown node: ' + node.class.name)
NotImplementedError: Unknown node: GetTheCode
On http://pythonhosted.org/PySpice
You can now host documentation at http://pythonhosted.org/PySpice. To upload documentation, prepare a .zip file that is unpacked into this URL. Only static pages are supported. The zip file must have a top-level "index.html".
The initial condition from 'ic' parameter is not working, but initializing the voltage node works well (commented). The problem is with inductors, how can I initialize the simulation with current initial conditions?
Here the code for a RC circuit:
import matplotlib.pyplot as plt
from PySpice.Probe.Plot import plot
from PySpice.Spice.Library import SpiceLibrary
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit import *
circuit = Circuit('RCCircuit')
circuit.V('input', 'node_01', circuit.gnd, 15@u_V)
circuit.R(1, 'node_01', 'node_02', 1000@u_kΩ)
circuit.C(1,'node_02',circuit.gnd, 50@u_uF, ic=0@u_V)
Tf =300@u_s
T = 0.1@u_s
simulator = circuit.simulator(temperature=25, nominal_temperature=25)
#simulator.initial_condition(node_02=0)
analysis = simulator.transient(step_time=T/10, end_time=Tf)
figure = plt.figure(1)
plot(analysis['node_01'])
plot(analysis['node_02'])
plt.show()
Not available on Ubuntu, Fedora
Hello, I've been toying around with ngspice calls and tried to add custom .save lines to the netlists. Apparently the simulation runs, but the callbacks generate stuff PySpice can't deal with. I've seen the API of ngspice as a DLL is reasonably well documented so I'll definitely go through that too, but I'd like to know if there was something specific to PySpice regarding how it processes the returned data.
In particular I have a transistor M1 and I try to save M1[VTH] with an operating point analysis, This happens to generate a "nodes" entry with the corresponding name @m1[vth], but the data is empty. Wondering if I was getting the syntax wrong I tried M1[ID] and this time I found the drain current ID had been stored as "branches" current, although for some reason under an empty string ''. Other parameters don't seem to work.
So it seems to me PySpice only expects currents or voltages, and I was looking for advice on what I should look into first. Oh, and also if I'm reinventing the wheel and there's already a proper way of saving parameters other than temperature etc, of course (I just didn't find anything exploring the source)
Thanks!
While attempting to use Norman Koren's spice tube library[1], I ran into parsing errors.
When I try to use the full library of tube libs:
Tubes = SpiceLibrary('/home/scherbi/src/NK/')
UnboundLocalError Traceback (most recent call last)
<ipython-input-4-fdd51c0e1165> in <module>()
1 #Tubes = SpiceLibrary('/home/scherbi/projects/electronics/library')
----> 2 Tubes = SpiceLibrary('/home/scherbi/src/NK/')
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Library.py in __init__(self, root_path)
66 if path.extension.lower() in ('.lib', '.mod'):
67 self._logger.debug("Parse {}".format(path))
---> 68 spice_parser = SpiceParser(path)
69 if spice_parser.is_only_subcircuit():
70 for subcircuit in spice_parser.subcircuits:
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Parser.py in __init__(self, path, source)
556 self._find_sections()
557
--> 558 ##############################################
559
560 def _merge_lines(self, raw_lines):
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Parser.py in _parse(self, lines)
627 scope.append(element)
628
--> 629 return tokens
630
631 ##############################################
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Parser.py in __init__(self, line)
337 number_of_pins = prefix_data.number_of_pins
338 if number_of_pins:
--> 339 self._nodes, stop_location = self._line.read_words(stop_location, number_of_pins)
340 else: # Q or X
341 if prefix_data.prefix == 'Q':
UnboundLocalError: local variable 'prefix_data' referenced before assignment
If I create a new library folder with just one .lib file in it, and just one subcricuit definition in that lib file:
Tubes = SpiceLibrary('/home/scherbi/projects/electronics/library')
NameError Traceback (most recent call last)
<ipython-input-5-71e751d108d3> in <module>()
----> 1 Tubes = SpiceLibrary('/home/scherbi/projects/electronics/library')
2 #Tubes = SpiceLibrary('/home/scherbi/src/NK/')
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Library.py in __init__(self, root_path)
66 if path.extension.lower() in ('.lib', '.mod'):
67 self._logger.debug("Parse {}".format(path))
---> 68 spice_parser = SpiceParser(path)
69 if spice_parser.is_only_subcircuit():
70 for subcircuit in spice_parser.subcircuits:
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Parser.py in __init__(self, path, source)
556 self._find_sections()
557
--> 558 ##############################################
559
560 def _merge_lines(self, raw_lines):
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Parser.py in _parse(self, lines)
627 scope.append(element)
628
--> 629 return tokens
630
631 ##############################################
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Parser.py in __init__(self, line)
340 else: # Q or X
341 if prefix_data.prefix == 'Q':
--> 342 self._nodes, stop_location = self._line.read_words(stop_location, 3)
343 # Fixme: optional node
344 else: # X
/usr/local/lib/python3.4/dist-packages/PySpice/Spice/Parser.py in read_words(self, start_location, number_of_words)
470 else:
471 if start_location < stop_location:
--> 472 start_location = stop_location
473 else: # we have read a space
474 start_location += 1
NameError: Bad element line, looking for word 3/4:
G1 1 3 VALUE={(PWR(V(7),EX)+PWRS(V(7),EX))/KG1}
^
These libraries work fine with NGSpice 26.
I have the low pass filter example work inside a Jupyter notebook, and the ability to do circuit simulation in this environment is fascinating. I am hoping we can get this library to work. I am an experienced Python programmer; I will try to discover the solution(s) to these issue as I have time.
Thanks!
[1] http://www.normankoren.com/Audio/Tubemodspice_article.html
Hey,
On line 106 in Spice/Server.py,
line
is a byte object and must be decoded to a string as well.
A TypeError is being thrown at the moment.
https://github.com/FabriceSalvaire/PySpice/blob/master/PySpice/Spice/Server.py#L106
A device model is
spice -> database ???
and the Spice parameters are renamed to more expressive and longer ones.
Hi Fabrice,
I saw that you recently added Windows support, and I recently installed PySpice on Windows. I have encountered a few issues.
First was in Logging\Logging.py, lines 44-47 need unindenting if I am predicting your intention correctly.
Second is in Spice\NgSpice\Shared.py: its missing an import platform at the top.
I'll report any more that I find.
Cheers!
When running examples, there's a weird error wrt logging.yml missing.. I'm running this in Ubuntu 13.04 with Python 3.3 installed.
Command:
python3.3 examples/diode/diode-characteristic-curve.py
Error:
Traceback (most recent call last):
File "examples/diode/diode-characteristic-curve.py", line 14, in
logger = Logging.setup_logging()
File "/usr/local/lib/python3.3/dist-packages/PySpice/Logging/Logging.py", line 37, in setup_logging
logging_config_file_name = ConfigInstall.Logging.find(config_file)
File "/usr/local/lib/python3.3/dist-packages/PySpice/Config/ConfigInstall.py", line 30, in find
return PathTools.find(config_file, Logging.directories)
File "/usr/local/lib/python3.3/dist-packages/PySpice/Tools/Path.py", line 54, in find
raise NameError("File %s not found in directories %s" % (file_name, str(directories)))
NameError: File logging.yml not found in directories ('/usr/local/lib/python3.3/dist-packages/PySpice/Config',)
Windows 7
Python 3.6.1 (WinPython distribution 3.6.1.0Qt5)
PySpice 1.1.2
ngspice (whichever version http://ngspice.sourceforge.net/experimental/ngspice-26plus-scope-inpcom-6-64.7z is)
Default path for ngspice should be C:\Program Files\Spice64
PySpice looks for C:Program Files\Spice64 instead
Just follow the installation steps for Windows
Path can be redefined manually. Personally, I just edited site-packages\PySpice\Spice\NgSpice\Shared.py
The problem lies here (lines 1079+):
if ConfigInstall.OS.on_windows:
drive = os.getenv('SystemDrive') or 'C:'
...
ngspice_path = os.path.join(drive, 'Program Files', ngspice_dirname)
As exotic as this may sound, os.path.join('C:', 'Program Files') actually returns 'C:Program Files', which doesn't cut it. I fixed it as os.path.join(drive, os.sep, 'Program Files', ... ) instead, which introduces the proper separator. (To be clear, I edited it locally; I'm not familiar with github so I don't know how to contribute with source)
Hi Fabrice,
Thank you so much for developing this project. I am trying to use it here. Just a comment: the correct spelling of Behavorial is Behavioral.
I am using it instead of a G element with cur='expression'. I know it is not implemented yet, but I think these two should be equivalent.
Best,
I am a windows user and I try to install PySpice package to my local win-amd64 machine.
There is few instructions about how to install PySpice on the Documentation Page.
(1) PyYAML is required but not listed (easy to fix)
(2) Though CFFI is optional(only required if ngspice shared library method is invoked), but I can not compile successfully the source code without installation of CFFI. And Installing of CFFI on windows is not an easy task, as it requires Microsoft Visual C++ compilier installed on local machine. (I guess this is some unnecessary module import when running the examples,but if I use PySpice coding line by line, maybe this problem can be avoided.)
(3) Ngspice is not installed on windows by default. In the official release of Ngspice, I can get the program which can only runs on "ngspice window". Therefore python can not use subprocess to call it as a server. After some efforts I find an edition of Ngspice with console program from its official website.
Still it does not work for running the examples successfully. The error gives is RawFile.py cannot locate the binary data. Finnally I found that RawFile Object uses b'Binary:\n' to match against the starting point of binary data in stdout. However, on windows, every new line begins with \r\n, so it works after I changes the matching string to b'Binary:\r\n'. Maybe you do not test PySpice on windows operating system?
Hello,
I have compiled and installed ngspice (version 26) from sources, along with PySpice (Python 2.7.6) from pip (pip2.7).
When I try to execute the following:
from PySpice import Spice
I get the following error:
File "/usr/local/lib/python2.7/dist-packages/PySpice/Spice/Netlist.py", line 284
class Element(object, metaclass=ElementParameterMetaClass):
^
SyntaxError: invalid syntax
This syntax seems to be a Python3 feature (see https://www.python.org/dev/peps/pep-3115/ and http://www.pythoncentral.io/how-metaclasses-work-technically-in-python-2-and-3/). The PySpice available in pip2 contains the newer (unsupported) syntax.
Does PySpice still support Python 2.7 ?
Hi,
Running examples, but they all stop on creating analysis.
Running win 10, python 3.5 64 bit. Installed PySpice with "pip install PySpice", and then installed "cffi" after. Is more information needed?
Thanks for guidance,
analysis1 = simulator1.ac(start_frequency=100, stop_frequency=kilo(10), number_of_points=100, variation='dec')
Leaves the following error:
FileNotFoundError Traceback (most recent call last)
in ()
1
----> 2 analysis1 = simulator1.ac(start_frequency=100, stop_frequency=kilo(10), number_of_points=100, variation='dec')
c:\users\bruker\appdata\local\programs\python\python35\lib\site-packages\PySpice\Spice\Simulation.py in ac(self, *args, **kwargs)
383 def ac(self, *args, **kwargs):
384
--> 385 return self._run('ac', *args, **kwargs)
386
387 ##############################################
c:\users\bruker\appdata\local\programs\python\python35\lib\site-packages\PySpice\Spice\Simulation.py in _run(self, analysis_method, *args, **kwargs)
417 super()._run(analysis_method, *args, **kwargs)
418
--> 419 raw_file = self._spice_server(str(self))
420 self.reset_analysis()
421
c:\users\bruker\appdata\local\programs\python\python35\lib\site-packages\PySpice\Spice\Server.py in call(self, spice_input)
144 stdin=subprocess.PIPE,
145 stdout=subprocess.PIPE,
--> 146 stderr=subprocess.PIPE)
147 input_ = str(spice_input).encode('utf-8')
148 stdout, stderr = process.communicate(input_)
c:\users\bruker\appdata\local\programs\python\python35\lib\subprocess.py in init(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
674 c2pread, c2pwrite,
675 errread, errwrite,
--> 676 restore_signals, start_new_session)
677 except:
678 # Cleanup if the child failed starting.
c:\users\bruker\appdata\local\programs\python\python35\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
953 env,
954 cwd,
--> 955 startupinfo)
956 finally:
957 # Child is launched. Close the parent's copy of those pipe
FileNotFoundError: [WinError 2] Systemet finner ikke angitt fil
for useless or generated files
Several high level elements (like sinusoidal, amplitudeModulated, exponential...) are implemented as voltage only when they can also be current sources.
I suggest to implement a generic Source in BasicElement with the attribute type to select between voltage and current and use this Source in all HighLevelElements.
Apologies, this is a known issue; I have just noticed the Fixme comment in HighLevelElement.py:
# Fixme: these waveforms can be current sources as well
Regards
Matplolib Qt Backend ?
The modified call to subcuircuits with parameters is not implemented as far as I can tell.
The spice code I am trying to arrive at is:
X2 7 6 GAIN K=50m
.SUBCKT GAIN 1 2 K=20m
*Connections: In Out
*Parameters: K Gain
E1 2 0 1 0 {K}
.ENDS
I have the following Python code:
circuit = Circuit('REGULATOR2')
gain = SubCircuit('GAIN', 1, 2, 'K=20')
gain.VCVS(1, 2, 0, 1, 0, '{K}')
circuit.subcircuit(gain)
circuit.X(2, 'GAIN', 7, 6, 'K=50m')
print(str(circuit))
which gives
.title REGULATOR2
.subckt GAIN 1 2 K=20m
E1 1 0 2 0 {K}
.ends
X2 7 6 K=50m GAIN
Notice the incorrect order of the name and the parameters.
From http://ngspice.sourceforge.net/docs/ngspice26-manual.pdf
2.4.3 Subcircuit Calls
General form:
XYYYYYYY N1 <N2 N3 . . . > SUBNAM
Examples:
X1 2 4 17 3 1 MULTI
Subcircuits are used in ngspice by specifying pseudo-elements beginning with the letter X, followed by the circuit nodes to be used in expanding the subcircuit. If you use parameters, the subcircuit call will be modified (see 2.8.3).
2.8.3 Subcircuit parameters
General form:
.subckt < identn> node node . . . <ident>=<value> <ident>=<value> ...
The syntax of a subcircuit call (invocation) is:
General form:
X<name> node node . . . <identn> <ident>=<value> <ident>=<value> ...
Examples:
X2 7 6 GAIN K=50m
the setup.py in the PyPI repository has install_requires commented
# install_requires=[
# # 'numpy',
# # 'matplotlib',
# ],
also, can you check if ngspice and tclngspice are installed?
Plots show strange behaviours
Hi all,
are you planning *thinking about the pure python implementation?
From an up-to-date clone of the repo I get the following.
python setup.py build
Traceback (most recent call last):
File "setup.py", line 38, in <module>
exec(compile(open('setup_data.py').read(), 'setup_data.py', 'exec'))
File "setup_data.py", line 68, in <module>
long_description = read_readme('README.txt')
File "setup_data.py", line 62, in read_readme
text = merge_include(lines, doc_path)
File "setup_data.py", line 38, in merge_include
with open(os.path.join(doc_path, include_file_name)) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\BlahBlaBla\\doc\\sphinx\\source\\introduction.txt'
creating the missing text file allows compilation. I think it probably just needs checking in?
Either install them or update documentation.
Implement specific Xyce sensitivity analysis
I have from Kicad a simple voltage divider, Divisor.cir: https://ctrlv.it/id/45314/1698504025
I want to read it and simulate in Pyspice using the following code https://ctrlv.it/python/45312/2388326092
I get the following error:
2017-09-15 08:17:07,388 - PySpice.Spice.NgSpice.Shared.NgSpiceShared._send_char - ERROR - Warning: singular matrix: check nodes 1 and 1
2017-09-15 08:17:07,389 - PySpice.Spice.NgSpice.Shared.NgSpiceShared._send_char - ERROR - Note: Starting dynamic gmin stepping
Could you tell me what i am doing wrong?
_attribute
which should not appear__repr__
output which spoil the documentationXyce fails with Time step too small error
Well it is confusing for user
The Spice code that should be generated is:
.SUBCKT SUM2 1 2 3 K1=1 K2=1
*Connections: In1 In2 Out
*Parameters: K1 GAIN1, K2 GAIN2
B1 3 0 V = {K1}*V(1) + {K2}*V(2)
.ENDS
I can find no way of calling of calling BehavorialSource for the voltage or current expression to be included, e.g.
summer = SubCircuit('SUM2', 1, 2, K_1=1.0, K_2=1.0)
summer.BehavorialSource(1, 3, summer.gnd, 'V = {K1}*V(1) + {K2}*V(2)')
print(str(summer))
.subckt SUM2 1 2 K_2=1.0 K_1=1.0
B1 3 0
.ends
Let see if it could help to circumvent unimplemented features
forum versus mailing list ? less flood ?
https://en.wikipedia.org/wiki/Comparison_of_Internet_forum_software
Discourse is nice but it requires a docker cloud server with min 1 GB.
https://github.com/discourse/discourse/blob/master/docs/INSTALL.md
A graph is defined by nodes and vertices.
A circuit is defined by devices and connections (tracks or nodes in SPICE) between their pins/ports.
graph G
{
node[shape=record];
V1[label="{ {<p>p} | V1 | {<m>m} }"];
V2[label="{ {<p>p} | V2 | {<m>m} }"];
R1[label="{ {<p>p} | R1 | {<m>m} }"];
R2[label="{ {<p>p} | R2 | {<m>m} }"];
R3[label="{ {<p>p} | R3 | {<m>m} }"];
Q1[label="{ {<b>b} | Q1 | {<c>c|<e>e} }"];
node[shape=circle];
GND[label="0"];
N1[label="1"];
N2[label="2"];
N3[label="3"];
N4[label="4"];
N5[label="5"];
V1:m -- GND;
V1:p -- N1;
V2:m -- GND;
V2:p -- N2;
R1:p -- N1;
R1:m -- N3;
Q1:b -- N3;
Q1:e -- N5;
Q1:c -- N4;
R2:p -- N2;
R2:m -- N4;
R3:p -- N5;
R3:m -- GND;
}
neato -Tpng -otest.png graph.dot
ref. https://answers.launchpad.net/kicad/+question/658090
Wayne Stambaugh answer:
Ngspice has already been directly integrated into KiCad and will be available in the upcoming stable 5 release. I am not sure PySpice buys us anything we don't already have with Ngspice. We still do not have the schematic editor swigged out to python yet so using python in the schematic editor for simulation would have to be run externally which tends to be less than ideal for users.
Bonjour Fabrice,
Il y a des liens symboliques pour certains fichiers dans la doc de sphinx. Exemple: doc/sphinx/source/examples/fundamental-laws/millman-theorem.py pointe vers /home/fabrice/home/developpement/PySpice/examples/fundamental-laws/millman-theorem.py
Cordialement
Trying to run the examples fails with this error message:
OSError: cannot load library libngspice.so: dlopen(libngspice.so, 2): image not found. Additionally, ctypes.util.find_library() did not manage to locate a library called 'libngspice.so'
I installed ngspice with brew install libngspice
, and pyspice with pip.
I'm running macOS 10.12.
Looking through the contents of libngspice, I saw that the library installed was 'libngspice.dylib'. Updating the library path to point at that file fixed the issue.
PySpice.Spice.NgSpice.Shared.NgSpiceShared.LIBRARY_PATH = 'libngspice{}.dylib'
Don't simulate on Ngspice
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.