Giter Site home page Giter Site logo

pyspice-org / pyspice Goto Github PK

View Code? Open in Web Editor NEW
629.0 32.0 167.0 3.5 MB

Simulate electronic circuit using Python and the Ngspice / Xyce simulators

Home Page: https://pyspice.fabrice-salvaire.fr

License: GNU General Public License v3.0

Python 99.16% C 0.28% Shell 0.40% AMPL 0.17%
spice python circuit-simulation pyspice ngspice xyce spice-simulator python3

pyspice's Introduction

PySpice : Simulate Electronic Circuit using Python and the Ngspice / Xyce Simulators

PySpice license PySpice python version

PySpice last version

Anaconda last version Anaconda donwloads

PySpice build status @travis-ci.org

Quick Links

2024 Update

Disclaimer: PySpice is developed on my free time actually, so I could be busy with other tasks and less reactive.

The free Discourse forum was closed some time ago due to a lack of activity. A HTML backup is stored in the directory pyspice-discourse-backup.

On Devel HEAD

  • fixed the ngspice library loading for recent cffi
  • fixed simulation aborting due to a message from newer ngspice
  • fixes for Spice parser
  • added support for Pint unit library
  • implemented SpiceLibrary
  • code cleanup but must check for typo...

An issue was found with NgSpice Shared, we must setlocale(LC_NUMERIC, "C"); see https://sourceforge.net/p/ngspice/bugs/490/

Overview

What is PySpice ?

PySpice is a Python module which interface Python_ to the Ngspice_ and Xyce_ circuit simulators.

Where is the Documentation ?

The documentation is available on the PySpice Home Page_.

Note: This site is hosted on my own infrastructure, if the site seems done, please create an issue to notify me.

Where to get help or talk about PySpice ?

Thanks to Discourse, PySpice now has a Forum hosted at https://pyspice.discourse.group

What are the main features ?

  • support Ngspice and Xyce circuit simulators
  • support Linux, Windows and Mac OS X platforms
  • licensed under GPLv3 therms
  • implement an Ngspice shared library binding using CFFI which support external sources
  • implement (partial) SPICE netlist parser
  • implement an Oriented Object API to define circuit
  • export simulation output to Numpy_ arrays
  • plot using Matplotlib_
  • handle units
  • work with Kicad schematic editor
  • implement a documentation generator
  • provides many examples

How to install it ?

Look at the installation section in the documentation.

Pull Request Recommendation

To make it easier to merge your pull request, you should divide your PR into smaller and easier-to-verify units.

Please do not make a pull requests with a lot of modifications which are difficult to check. If I merge pull requests blindly then there is a high risk this software will become a mess quickly for everybody.

Credits

Authors: Fabrice Salvaire and contributors

News

V1.6.0 (development release)

  • KiCadTools a proof of concept module to read KiCad 6 .kicad_sch schema file and compute the netlist. This module can be used to perform any kind of processings on a KiCad schema. It is actually hosted in the source but could become a standalone project. For PySpice, it provides a very flexible way to draft a circuit with the help of KiCad and then generate the netlist without using the netlist export feature of KiCad. And thus leverage the writing of fastidious cicruit.

V1.5.0 (production release) 2021-05-15

  • Support Ngspice up to version 34
  • Renamed custom dunders "__dunder__" to "CONSTANT" or "_private" class attributes
  • Fixed typo in documentation (thanks to endolith and brollb)
  • Add DC temperature sweep support #272 (thanks to Fatsie)
  • PWL support improvements #271 (thanks to Fatsie)
  • Assign units on creation of temperature-sweep vectors #263 (thanks to ARF1)
  • Prevent memory leaks by freeing ngspice command log #260 thanks to ARF1)
  • Performance optimization: dispatch multiple alter commands jointly #259 (thanks to ARF1)
  • Added spice library support #258 (thanks to Fatsie)
  • Allow to specify DC value for PWL #257 (thanks to Fatsie)
  • Support for .nodeset type initial condition #256 (thanks to Fatsie)
  • Fix accuracy problems #254 (thanks to sotw1957)
  • Changes to make it easier to use PySpice with a large archive of SPICE models medium diff #249 (thanks to xesscorp)
  • `Netlist.py`: Fix wrong method when joining parameters during netlist parse #245 (thanks to cyber-g)
  • Unit: add Pickle support
  • Add Parser code from #136 (thanks to jmgc) but not yet merged
  • Unit: add np.mean

V1.4.3 2020-07-04

A huge effort, thanks to @stuarteberg Stuart Berg, has been made to make Ngspice and PySpice available on Anaconda (conda-forge) for the Window, OSX and Linux platforms. Thanks to the conda-forge continuous integration platform, we can now run unit tests and the examples on theses platforms automatically. Hope this will make the software more robust and easier to run !

  • PySpice is now available on Anaconda(conda-forge) as well as a wheel on PyPI
  • Added a post installation tool to download the Ngspice DLL on Windows and to check the installation. It should now simplify considerably the PySpice installation on Windows.
  • This tool can also download the examples and the Ngspice PDF manual.
  • On Linux and OSX, a Ngspice package is now available on Anaconda(conda-forge). Note that theses two platforms do not download a binary from Ngspice since a compiler can easily be installed on theses platforms.
  • Updated installation documentation for Linux, the main distributions now provide a ngspice shared package.
  • Added a front-end web site so as to keep older releases documentation available on the web.
  • fixed and rebuilt all examples (but mistakes could happen ...)
  • examples are now available as Python files and Jupyter notebooks (but some issues must be fixed, e.g. due to the way Jupyter handles Matplotlib plots)
  • support NgSpice 32 API (no change)
  • removed @substitution@ in PySpice/__init__.py, beacause it breaks pip install from git
  • fixed some logging spams
  • fixed NonLinearVoltageSource
  • fixed Unicode issue with °C (° is Extended ASCII)
  • fixed ffi_string_utf8 for UnicodeDecodeError
  • fixed logging formater for OSX (removed ANSI codes)
  • reworded "Invalid plot name" exception
  • removed diacritics in example filenames
  • cir2py has been converted to an entry point so as to work on all platforms
  • updated Matplotlib subplots in examples
  • added a unit example
  • added a NMOS example (thanks to cyber-g) cf. #221

V1.4.0 2020-05-05

This release is yanked due to broken Windows support.

  • fixed nasty issue with NgSpice shared for setlocale(LC_NUMERIC, "C"); cf. #172
  • fixed AC AC_MAG AC_PASAE SIN for new NgSpice syntax
  • fixed initial_state for VoltageControlledSwitch
  • fixed LosslessTransmissionLine #169
  • fixed docstrings for element shortcut methods (thanks to Kyle Dunn) #178
  • fixed parser for leading whitespace (thanks to Matt Huszagh) #182
  • fix for PyYAML newer API
  • support NgSpice 31 API (no change)
  • added check for CoupledInductor #157
  • added check-installation tool to help to fix broken installation
  • added pole-zero, noise, distorsion, transfer-function analyses (thanks to Peter Garrone) #191
  • added .measure support (thanks to ceprio) #160
  • added log_desk parameter to CircuitSimulator
  • added listing command method to NgSpiceShared
  • added Xyce Mosfet nfin #177

V1.3.2 2019-03-11

  • support Ngspice 30 and Xyce 6.10
  • fixed NgSpice and Xyce support on Windows 10
  • bug fixes

V1.2.0 2018-06-07

  • Initial support of the Xyce_ simulator. Xyce is an open source, SPICE-compatible, high-performance analog circuit simulator, capable of solving extremely large circuit problems developed at Sandia National Laboratories. Xyce will make PySpice suitable for industry and research use.
  • Fixed OSX support
  • Splitted G device
  • Implemented partially A XSPICE device
  • Implemented missing transmission line devices
  • Implemented high level current sources Notice: Some classes were renamed !
  • Implemented node kwarg e.g. circuit.Q(1, base=1, collector=2, emitter=3, model='npn')
  • Implemented raw spice pass through (see User FAQ)
  • Implemented access to internal parameters (cf. save @device[parameter])
  • Implemented check for missing ground node
  • Implemented a way to disable an element and clone netlist
  • Improved SPICE parser
  • Improved unit support:
    • Implemented unit prefix cast U_μV(U_mV(1)) to easily convert values
    • Added U_mV, ... shortcuts
    • Added Numpy array support to unit, see UnitValues Notice: this new feature could be buggy !!!
    • Rebased WaveForm to UnitValues
  • Fixed node order so as to not confuse users Now PySpice matches SPICE order for two ports elements !
  • Fixed device shortcuts in Netlist class
  • Fixed model kwarg for BJT Notice: it must be passed exclusively as kwarg !
  • Fixed subcircuit nesting
  • Outsourced documentation generator to Pyterate_
  • Updated setup.py for wheel

V1.1.0 2017-09-06

  • Enhanced shared mode
  • Shared mode is now set as default on Linux

V1.0.0 2017-09-06

  • Bump version to v1.0.0 since it just works!
  • Support Windows platform using Ngspice shared mode
  • Fixed shared mode
  • Fixed and completed Spice parser : tested on example's libraries

V0.4.2

  • Fixed Spice parser for lower case device prefix.

V0.4.0 2017-07-31

  • Git repository cleanup: filtered generated doc and useless files so as to shrink the repository size.
  • Improved documentation generator: Implemented format for RST content and Tikz figure.
  • Improved unit support: It implements now the International System of Units. And we can now use unit helper like u_mV or compute the value of 1.2@u_kΩ / 2@u_mA. The relevant documentation is on this page.
  • Added the Simulation instance to the Analysis class.
  • Refactored simulation parameters as classes.

V0.3.2 2017-02-22

  • fixed CCCS and CCVS

V0.3.1 2017-02-22

  • fixed ngspice shared

V0.3.0 2015-12-08

  • Added an example to show how to use the NgSpice Shared Simulation Mode.
  • Completed the Spice netlist parser and added examples, we could now use a schematic editor to define the circuit. The program cir2py translates a circuit file to Python.

V0 2014-03-21

Started project

pyspice's People

Contributors

amuramatsu avatar arf1 avatar brollb avatar cyber-g avatar cypheon avatar endolith avatar fabricesalvaire avatar fatsie avatar joh avatar kdunn926 avatar matthuszagh avatar mcclurmc avatar rob-smallshire avatar sotw1957 avatar stuarteberg avatar thomaslima avatar thracesystems avatar xesscorp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyspice's Issues

Enhanced KiCad integration

Why ?

  • Plotting with GUI don't record what you are doing (or less efficiently than a script)
  • Improved plotting using Matplotlib
  • Improved scripting using Python
  • Generate netlist Python code from KiCad instead of Spice netlist
  • Nodes connected to ground is not set to 0 ???
  • More automatic process to generate the right netlist file (one click action)
  • Netlist import in KiCad using a graph algorithm to automatically layout the circuit

Question on Launchpad

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.

Several HighLevelElements (Sinusoidal, AmplitudeModulated...) should also implement currentSource

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

Problem running examples on Python 2.7

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 ?

dependencies in PyPI

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?

Subcircuit parameters not handled correctly

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

BehavorialSource not working.

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

symbolic links to /home/fabrice

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

PySpice on windows

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?

SpiceParser problem

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?

transformer example missing the Transformer module?

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'

Minor issue: Correct spelling of Behavioral

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,

Tube Library Issues

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

Logging.yml issue

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',)

Accessing internal device parameters

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!

Initial Conditions on Capacitors and Inductors attributes are not working

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()

FFI interface not used properly in ngspice shared mode

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)

Default Library Path on macOS not correct

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'

WinError 2 - Can not find file

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

Incorrect Windows path for C:\Program Files\Spice64

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

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)

Expected Behaviour

Default path for ngspice should be C:\Program Files\Spice64

Actual Behaviour

PySpice looks for C:Program Files\Spice64 instead

Steps to reproduce the behaviour

Just follow the installation steps for Windows

Suggested fix

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)

Errors on Windows install

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!

Fix multiple documentation sources on the web

  • Git repository size is 41 MB
  • html size is 8 MB
  • gh-pages update is slow due to actual repository size
  • rtd needs rst sources and extensions
  • pythonhosted use zip and not rsync !

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".

Missing introduction.txt from repository?

Missing introduction.txt from repository.

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?

Netlist viewer

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

test

test

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.