Giter Club home page Giter Club logo

ahkab's Introduction

Monkeying around ahkab

a SPICE-like electronic circuit simulator written in Python

The code should be easy to read and modify, the main language is Python -- 2 or 3 -- and it is platform-independent.

News

  • It's with a heavy heart that I write that @ggventurini passed away on September 15th, 2015, at the age of thirty-two. He will be remembered fondly as a friendly and helpful engineer, always excited about his work at CERN and his numerous labors to improve the accessibility of tools for science, research, and development.
  • Ahkab v0.18 was released on July 12 2015, including new features, bugfixes and improved documentation. It is recommended to upgrade. Check out the release notes for more!
  • The whole codebase has been going through a (yet incomplete) refactoring and documenting effort. The new documentation is available on RTD.

If you are interested in the project or the technology, have an issue with an example, or you would like to contribute by requesting, refactoring or documenting a particular feature, please reach out to us on GitHub!

Build Status Coverage Status PyPi version GPLv2 license DOI

Supported simulations:

  • Numeric:
    • Operating point, with guess computation to speed up the solution. See example: Downscaling current mirror
    • DC sweep
    • Transient analysis, available differentiation formulas: implicit Euler, trapezoidal, gear orders from 2 to 5. See for example the simulation of a Colpitts Oscillator.
    • AC analysis
    • PZ analysis
    • Periodic steady state analysis of non-autonomous circuits, time domain shooting and brute-force algorithms.
  • Symbolic:

The results are saved to disk, plotted or printed to stdout and can be read/processed by the most common tools (eg. Octave, gnuplot, Matlab, gwave and others)

Install

The program requires:

  • the Python interpreter version 2 or 3 (at least v.2.6 for Python2, v.3.3 for Python3),
  • numpy>=1.7.0, scipy>=0.14.0, sympy>=0.7.6 and tabulate>=0.7.3.

Matplotlib is strongly recommended and no plotting will work without.

If you need more information about the dependencies, check the Install notes.

Usage

1. ahkab can be run as a Python library

Example schematic: a 5th order 1kHz band-pass Butterworth filter

from ahkab import new_ac, run
from ahkab.circuit import Circuit
from ahkab.plotting import plot_results # calls matplotlib for you
import numpy as np

# Define the circuit
cir = Circuit('Butterworth 1kHz band-pass filter')
cir.add_vsource('V1', 'n1', cir.gnd, dc_value=0., ac_value=1.)
cir.add_resistor('R1', 'n1', 'n2', 50.)
cir.add_inductor('L1', 'n2', 'n3', 0.245894)
cir.add_capacitor('C1', 'n3', 'n4', 1.03013e-07)
cir.add_inductor('L2', 'n4', cir.gnd, 9.83652e-05)
cir.add_capacitor('C2', 'n4', cir.gnd, 0.000257513)
cir.add_inductor('L3', 'n4', 'n5', 0.795775)
cir.add_capacitor('C3', 'n5', 'n6', 3.1831e-08)
cir.add_inductor('L4', 'n6', cir.gnd, 9.83652e-05)
cir.add_capacitor('C4', 'n6', cir.gnd, 0.000257513)
cir.add_capacitor('C5', 'n7', 'n8', 1.03013e-07)
cir.add_inductor('L5', 'n6', 'n7', 0.245894)
cir.add_resistor('R2', 'n8', cir.gnd, 50.)

# Define the analysis
ac1 = new_ac(.97e3, 1.03e3, 1e2, x0=None)

# run it
res = run(cir, ac1)

# plot the results
plot_results('5th order 1kHz Butterworth filter', [('|Vn8|',"")], res['ac'],
             outfilename='bpf_transfer_fn.png')

Example: AC simulation results

2. ahkab can be run from the command line with a netlist file

The syntax is:

`$ python ahkab -o graph.dat <netlist file>`

See ahkab --help for command line switches, also online on the documentation pages.

Documentation

The documentation is available on RTD.

There, you can find a documentation and examples regarding how to simulate from a Python script.

Refer to the netlist syntax page if you prefer to write netlist files that describe the circuit.

Experience with running SPICE or related commercial simulators can be very useful: this is not for the faint of heart.

Development model

  • The development happens on the github repository,
  • Mostly on the master branch, with feature branch being created only for special purposes or non-trivial features.
  • Snapshots are released on a (hopefully) regular basis and are available on the Releases pages, complete with changelog, and on PYPI.

Patches and pull requests are welcome!

How this project was born

Writes @ggventurini:

"This project was born when I was an enthusistic undergrad, apparently with plenty of free time, attending "Simulazione Circuitale" (Circuit Simulation) taught by Prof. A. Brambilla back in Italy at the Polytechnic University of Milan.

I am grateful to prof. Brambilla for teaching one of the most interesting courses of my university years. -GV"

Bugs and patches

Does it work? Bugs? Do you have patches? Did you run some noteworthy simulation? Let us know on GitHub! You can also reach the maintainer at @itdaniher @gmail.com, he's happy to talk about Python.

Support the development with a donation

If you wish to support the development of ahkab, please donate to cancer research:

or

Credits

Authors: Giuseppe Venturini, with contributions from Ian Daniher, Rob Crowther, and KOLANICH.

Maintainer: Ian Daniher

Code: the module py3compat.py is (c) 2013 - the Jinja team.

Dependencies: many thanks to the authors of numpy, scipy, sympy, matplotlib and tabulate!

ahkab's People

Contributors

endolith avatar ggventurini avatar itdaniher avatar kolanich avatar mightyiam avatar satels 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ahkab's Issues

how to use the ahkab.results class ?

I want to use ahkab.results class to get AC simulation result data , but there is something wrong with it .

OS : win7 x64 sp1
python: Python 3.4.3

python code:

-- coding: utf-8 --

from ahkab import results , circuit
import ahkab

cir = circuit.Circuit('Butterworth 1kHz band-pass filter')
cir.add_vsource('V1', 'n1', cir.gnd, dc_value=0., ac_value=1.)
cir.add_resistor('R1', 'n1', 'n2', 50.)
cir.add_inductor('L1', 'n2', 'n3', 0.245894)
cir.add_capacitor('C1', 'n3', 'n4', 1.03013e-07)
cir.add_inductor('L2', 'n4', cir.gnd, 9.83652e-05)
cir.add_capacitor('C2', 'n4', cir.gnd, 0.000257513)
cir.add_inductor('L3', 'n4', 'n5', 0.795775)
cir.add_capacitor('C3', 'n5', 'n6', 3.1831e-08)
cir.add_inductor('L4', 'n6', cir.gnd, 9.83652e-05)
cir.add_capacitor('C4', 'n6', cir.gnd, 0.000257513)
cir.add_capacitor('C5', 'n7', 'n8', 1.03013e-07)
cir.add_inductor('L5', 'n6', 'n7', 0.245894)
cir.add_resistor('R2', 'n8', cir.gnd, 50.)

opa = ahkab.new_op()

outfile = "E:\Python_File\spice_test\outfilea"

rst = results.ac_solution(cir, .97e3, 1.03e3, 1e2, "LOG", opa, "outfile")

rst["f"]


Plot circuit

Hey,

is there a way to plot / print the circuit to get an output like the one in the README.md?

factor display code out of analysis processing?

The ticker class is instantiated in all of the analyses processing functions, but it doesn't display unless the verbosity level is high enough. As more thought is put into making Ahkab a robust library for interacting with circuit semantics, might it be worthwhile to factor stuff that does weird stuff to stdout into its own library?

Support for Frequency-Dependent Components?

What would it take to add frequency-dependent resistors and inductors? I'm looking at modeling Coilcraft inductors in SPICE (http://www.coilcraft.com/modelsltpice.cfm), and they suggest using a Laplace directive to create the component. I don't think Ahkab currently supports this.

Would this require modifying the AC analysis routine to be more complicated? I think you could no longer just do the invert-multiply per step.

circuit.find_vde broken?

But it's not a huge deal. It's just used one place in dc_analysis.py.

Small tweak at a67993c, look at it if you get a chance, but I'm speculating this branch of code probably doesn't see much execution.

Ahkab floods /tmp/ directory

I am using Ahkab to model circuits for to test some optimization strategies. So, I am running an Ahkab simulation hundreds or thousands of times very quickly. This quickly leads to my program crashing due to having too many open files. It turns out that every time I run an analysis, Ahkab creates a file in /tmp/.

I've looked through the source and it seems that if you set "outfile" to None in new_ac it will create a temp file for the output.

from ahkab.py, in each new_ function.

    if guess is None:
        guess = options.dc_use_guess
    if outfile is None or outfile == 'stdout':
        if options.cli:
            outfile = 'stdout'
        else:
            ofi, outfile = tempfile.mkstemp(suffix='.op')
            _of.append(ofi)  # keep the file open until quitting

The fd is stored in the _of list, but I haven't found anywhere they get closed.

I also am unsure about why it's necessary to write to this temp file in the first place?

As far as I can tell, there is no obvious way to disable writing to these temp files.

Ultimately this isn't a huge issue, I just specified a single hidden outfile which gets overwritten after each analysis. But possibly some documentation about this, or an explanation of what the outfile is for would be useful?

Custom nonlinear components

Hello!

I am trying to implement a resistor with a voltage drop following the formula U=const.*I^2. It is needed for the simulation of a transient process.
I made a class like the description in the device file, but I when I try run it there is only the error message Missing attribute 'get_output_ports' from the circuit file. I do not understand what the circuit file exactly wants. Are there any documentations or examples for the use of nonlinear elements?

Best regards

Voltage controlled switch model

A voltage controlled switch may be employed instead of a transistor in several circuits to evaluate ideal circuit behavior and compare it to operation with transistors. It also potentially shortens simulation time.

RL circuit vs. LR circuit: different output

Thanks for your time reading this thread. I hope you could give me some suggestions regarding Ahkab library.

I am an engineer specialised in inkjet printhead design. I am trying to use Python Ahkab library to simulate a printhead design where the equivalent flow resistance, inertance, and capacitance are not constant, but variables depending on flow development profile in microfluidic channels. Ahkab is a perfect library for such a job.

However, I found something really hard to comprehend (py file is attached). For a simple RL circuit, the time constant should be L/R. However, the simulated result is not so. Also, by switching the positions of the R and the L components, the result is different for the current running through the inductor. By comparing them with the result from LTSpice model, both ones are not completely correct.

Could you give me some suggestions as to what might have gone wrong with my coding or the library itself?

Many thanks,

Xi

#code:

import numpy as np 
import scipy as sp 
import pylab as plt
import tabulate 
import matplotlib 
import ahkab
from ahkab import new_ac, run
from ahkab.circuit import Circuit
from ahkab.plotting import plot_results # calls matplotlib for you
from ahkab import circuit, printing, time_functions
#########################################################################
DeltaPressure = 1 # wasn't in the orig source
cir = circuit.Circuit('Cylinder')
#V_const = time_functions.pulse(v1=0, v2=DeltaPressure, td=1e-12, tr=1e-12, pw=1E-3, tf=1e-12, per=1E-1)
V_const = time_functions.pulse(v1=0, v2=DeltaPressure, td=0., tr=0., pw=1E-3, tf=0., per=1E-1)
#cir.add_vsource('Vconst', 'n1', cir.gnd, dc_value=0., ac_value=0., function=V_const)
#it's the same result using this one. 
#cir.add_vsource('Vconst', 'n1', cir.gnd, dc_value=30000, ac_value=0., function=V_const)
#using DC_Value still the same 
cir.add_vsource('Vconst', 'n1', cir.gnd, dc_value=30000, ac_value=0)
#cir.add_resistor('RnozSS', 'n1', 'n2', 1.45069e+12)      
#cir.add_inductor('LnozSS', 'n2', cir.gnd, 1.14282e+07)  
#######change the positions of Lnoz and Rnoz, the results are different #################
cir.add_inductor('LnozSS', 'n1', 'n2', 1.14282e+07)  
cir.add_resistor('RnozSS', 'n2', cir.gnd, 1.45069e+12)      
#########################################################################################
print(cir)
T = 20e-5    
deltaT = 20e-9  
#initialise IC
ic = {'V(n1)':0, #30000, 
      'V(n2)':0., 
      'I(LnozSS)':0., 
     }
cylinder_ic = ahkab.new_x0(cir, ic)  
tran_analysis = ahkab.new_tran(tstart=0, 
                               tstop=T, 
                               tstep=deltaT, 
                               x0=cylinder_ic, 
                               #method='GEAR6',
                               #use_step_control=False)                               
                               use_step_control=True)
  
#############################################################################
r = ahkab.run(cir, an_list=tran_analysis)
#print(r['tran']['T'].size)
#print(r['tran']['VN1'][-1])d
#print(r['tran']['VN2'][-1])
#print(r['tran']['I(LnozSS)'][-1])
fig = plt.figure()
plt.title(cir.title + " - TRAN Simulation")
plt.plot(r['tran']['T']*1E+6, r['tran']['I(LnozSS)']*1E+9, label="SPICE")
#plt.plot(temp_timeList*1E+6, temp_flowRateList*1E+9, label="White's Formula")
plt.legend()
plt.grid(True)
plt.xlim([0,T*1E+6])
plt.ylim([0,r['tran']['I(LnozSS)'][-1]*1.05*1E+9])
plt.ylabel('Flow rate [nA]')
plt.xlabel('Time [us]')
fig.savefig('tran_plot.png')
plt.show() 

(This is the LTSpice circuit and output for the current through the inductor)
image
image 1

(Below two images are for the current through the inductor using Python Ahkab library. However, the positions of R and L are switched in the circuit. Results are not the same. The bottom image gives the correct final current value but the time constant is wrong.)
capture1
capture2

Butterworth 1kHz band-pass filter example (on git page) does not plot results correctly

The 'Butterworth 1kHz band-pass filter' example (on git page) does not plot results correctly. It appears that the plot is generated in angluar frequency units rather than frequency units (as is displayed on your home git page). Using the below code I am able to reproduce the example plot. See lines 26 and 36 for the changes I had to make.

from ahkab import new_ac, run
from ahkab.circuit import Circuit
from ahkab.plotting import plot_results # calls matplotlib for you
from ahkab.plotting import show_plots
import numpy as np

# Define the circuit
cir = Circuit('Butterworth 1kHz band-pass filter')
cir.add_vsource('V1', 'n1', cir.gnd, dc_value=0., ac_value=1.)
cir.add_resistor('R1', 'n1', 'n2', 50.)
cir.add_inductor('L1', 'n2', 'n3', 0.245894)
cir.add_capacitor('C1', 'n3', 'n4', 1.03013e-07)
cir.add_inductor('L2', 'n4', cir.gnd, 9.83652e-05)
cir.add_capacitor('C2', 'n4', cir.gnd, 0.000257513)
cir.add_inductor('L3', 'n4', 'n5', 0.795775)
cir.add_capacitor('C3', 'n5', 'n6', 3.1831e-08)
cir.add_inductor('L4', 'n6', cir.gnd, 9.83652e-05)
cir.add_capacitor('C4', 'n6', cir.gnd, 0.000257513)
cir.add_capacitor('C5', 'n7', 'n8', 1.03013e-07)
cir.add_inductor('L5', 'n6', 'n7', 0.245894)
cir.add_resistor('R2', 'n8', cir.gnd, 50.)

# Define the analysis
f0 = 0.97e3
f1 = 1.03e3
ac1 = new_ac(2*np.pi*f0, 2*np.pi*f1, 1e2, x0=None)

# run it
res = run(cir, ac1)

# plot the results
import pylab as plt
import numpy as np

fig = plt.figure()
plt.semilogx(res['ac']['w']/(2*np.pi), np.abs(res['ac']['Vn8']), 'o-')
plt.xlim( (f0, f1) )
plt.ylim( (0, 1) )
plt.xlabel('f[Hz]')
plt.ylabel('V[V]')
plt.show()

Unintended integer arithmetic in EKV implementation

Nice to see you working on this project again. Thank you :)

There is still an old open issue which I reported a while ago. The original report is at http://code.google.com/p/ahkab/issues/detail?id=5 , including an (outdated) patch. There is possibly a similar issue in mosq.py, it has the same constant.

Orignal text:

When I tried to track down why my circuits didn't converge I found this:

the default value ekv.GAMMA_DEFAULT was set to the (integer) value 1. This led to an integer division GAMMA/2 which resulted in 0. Changing the 2 to 2.0 solved the problem already.

To be on the safe side I changed all lines which looked suspicious to use explicit floating point literals. Most of them don't actually need this, but I think the explicit way prevents such errors in future.

Better error for missing ground

import ahkab

mycir = ahkab.Circuit('Simple Example Circuit')
mycir.add_isource('Isource', 'nA', 'nD', dc_value=1)
mycir.add_resistor('Rad', 'nA', 'nD', value=5)

opa = ahkab.new_op()
r = ahkab.run(mycir, opa)['op']

produces error:

  File "C:\Anaconda3\lib\site-packages\ahkab\dc_analysis.py", line 1007, in generate_mna_and_N
    N[elem.n2, 0] = N[elem.n2, 0] - elem.I()

IndexError: index 2 is out of bounds for axis 0 with size 2

Adding a ground makes it work:

import ahkab

mycir = ahkab.Circuit('Simple Example Circuit')
mycir.add_isource('Isource', 'nA', 'nD', dc_value=1)
mycir.add_resistor('Rad', 'nA', 'nD', value=5)
mycir.add_vsource('Vgnd', mycir.gnd, 'nC', dc_value=0)

opa = ahkab.new_op()
r = ahkab.run(mycir, opa)['op']

Is it possible to make this error more helpful?

voltage pulse source for a MOS inverter + questions

Hi all,

I'm working on simple CMOS inverter now, and cannot figure out how to add a pulse source for the inverter.

Currently, I'm using a sin source instead of the pulse:

inv = ahkab.Circuit('MOS Inverter')
#add models
inv.add_model('ekv', 'nmos', dict(TYPE='n', VTO=0.4, KP=10e-6))
inv.add_model('ekv', 'pmos', dict(TYPE='n', VTO=-0.4, KP=1e-6))

inv.add_vsource('vdd', n1='dd', n2=inv.gnd, dc_value=3.3)

#add MOSFETs

inv.add_mos('m1', nd='output1', ng='in1', ns='dd', nb='dd',
            model_label='pmos', w=600e-6, l=100e-9)
inv.add_mos('m2', nd='output1', ng='in1', ns=inv.gnd, nb=inv.gnd,
            model_label='nmos', w=600e-6, l=100e-9)
#voltage sin source function
mys = lambda t: 1 if not t else math.sin(math.pi*1e4*t)/(math.pi*1e4*t)

inv.add_vsource('V1', 'in1', inv.gnd, 1, function=mys)

op = ahkab.new_op()
print(op)
res = ahkab.run(inv, op)
print(res)
x0 = res['op'].asarray()
x0[-1, 0] += -1e-9

tran = ahkab.new_tran(tstart=0., tstop=1e-6, tstep=.01e-9, method='trap',
                       x0=x0)
res = ahkab.run(inv, tran)['tran']

And then I'm trying to plot my input signal:

Questions:

  • Are there ways to improve the performance of computations for tran simulations?
    Because it's unbelievable slow, f.i. about 7 minutes for the tran simulation with tstop=1e-6.
  • How to add a pulse source to the circuit? I found in documentations you can create your own time function, but it seams to me it does not really work now, anyway I need some hints how to make it.
  • Also, I would like to add my inverter to the example folder, is it ok guys?

Travis-CI Broken

It looks as if Travis has undergone at least one breaking API change in the last year or two, requiring some TLC to get our test suites up again. I should probably prioritise this above most other bugfixes....

Documentation User defined element

Hey,

Great package! I am really glad that I found your package. I want to simulate nonlinear devices and their transient behaviour. Therefore, I would need two types of elements CCVS and VCVS. If I understand it correct the CCVS and VCVS are linear elements which cannot be changed (easily).
I thought that a user defined element would be perfect. Unfortunately the documentation is very little so far
" """
Adds a user defined element.

    In order for this to work, you should write a module that supplies the
    elem class.

    XXX WRITE DOC

"
Could you tell me what exactly is meant by elem class? or could you give an example of a user defined element.

Thanks a lot!

BR Stephan

Maximum iteration depth exceeded

Using the butter_worth filter example,

https://github.com/ahkab/ahkab/wiki/Example:-Python-API

and
$python2 -i script.py

result the following error

File "/usr/lib/python2.7/site-packages/matplotlib/units.py", line 148, in get_converter
converter = self.get_converter(xravel[0])
File "/usr/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 316, in getitem
out = N.ndarray.getitem(self, index)
RuntimeError: maximum recursion depth exceeded

versions:

numpy-1.8.0-1
scipy-0.13.1-1
sympy-0.7.4-1

ahkab with newest git clones.

Issue with a switch

Hello, thank you very much for you work. I have an issue with a circuit that I try to simulate. While running the code I got this error messge :

File "C:\Python27\lib\site-packages\ahkab\switch.py", line 119, in init
self.dc_guess = self.model.get_dc_guess(self.device.is_on)

AttributeError: 'str' object has no attribute 'get_dc_guess'

Could you help me to solve the problem, it seem not to be a problem of my code.

This is the code I made that is not working so far :
import ahkab
import pylab as plt
import numpy as np

ownWall = ahkab.Circuit('First Try')

"""
models need to be defined before the devices that use them
"""

ownWall.add_model('ekv', 'nmos', dict(TYPE='n', VTO=.4, KP=10e-6))
ahkab.switch.vswitch_model('Switch', VT=5, VH=2, VON=None, VOFF=None, RON=None, ROFF=None)
ahkab.diode.diode_model('diode', IS=None, N=None, ISR=None, NR=None, RS=None, CJ0=None, M=None, VJ=None, FC=None, CP=None, TT=None, BV=None, IBV=None, KF=None, AF=None, FFE=None, TEMP=None, XTI=None, EG=None, TBV=None, TRS=None, TTT1=None, TTT2=None, TM1=None, TM2=None)

"""
This code will define the PWM driving the two mosfets
"""

v1 = 0
v2 = 5

alpha = 0.6

PER=10E-6
TR=10E-9
TD1 = 0
TD2 = TD1 + alphaPER
PW1 = alpha
PER - 2TR
PW2 = (1 - alpha
PER) - 2*TR

pwm1 = ahkab.time_functions.pulse(v1, v2, TD1, TR, PW1, TR, PER)
ownWall.add_vsource("VPWM1", "sn11", 'sn22', dc_value=10, ac_value=0, function = pwm1)
pwm2 = ahkab.time_functions.pulse(v1, v2, TD2, TR, PW2, TR, PER)
ownWall.add_vsource("VPWM2", "sn12", 'sn22', dc_value=10, ac_value=0, function = pwm2)

"""
This code define the power block of the ownWall without
input and output voltage and without PWM
"""

ownWall.add_capacitor('C1', 'n2', 'n1', value=440E-6)
ownWall.add_inductor('L', 'n2', 'n3', value=100E-6)
ownWall.add_resistor('Rl', 'n3', 'n4', value=0.1)
ahkab.switch.switch_device('n1', 'n4', 'sn11', 'sn21', 'Switch' )
ahkab.switch.switch_device('n5', 'n4', 'sn12', 'sn22', 'Switch' )
ownWall.add_diode('D1', 'n1', 'n4', 'diode')
ownWall.add_diode('D2', 'n4', 'n5', 'diode')
ownWall.add_capacitor('C2', 'n5', 'n1', value=440E-6)

Thank you for your help,

Romain.

numpy.savetxt() got an unexpected keyword argument 'header'

Hello, I'm trying to run the example in README.md and am getting the following error (using the v0.10 release).

/Library/Python/2.7/site-packages/ahkab-0.10-py2.7.egg/ahkab/csvlib.pyc in write_csv(filename, data, headers, append)
90 
91     headers = SEPARATOR.join(headers) if not append else ""
---> 92     numpy.savetxt(fp, data.T, delimiter=SEPARATOR, header=headers, comments='#')
93 
94     _close_fp(fp, filename)

TypeError: savetxt() got an unexpected keyword argument 'header'

UnicodeEncodeError on win7 64bit OS

I tried to run the example on my windows OS. But i got the error message below.
(code from :https://raw.githubusercontent.com/ahkab/ahkab/master/doc/misc/script.py)

My Environment is Win7 64bit OS + Python 3.4.2 .
How could I fix this problem , thanks.

Anthony

Error message from Ipython

  • Butterworth Example circuit
    R1 n1 n2 600
    L1 n2 n3 0.01524
    C1 n3 0 1.1937e-07
    L2 n3 n4 0.06186
    C2 n4 0 1.5512e-07
    R2 n4 0 1200
    V1 n1 0 type=vdc value=5 vac=1 type=pulse v1=0 v2=1 td=5e-07 per=2 tr=1e-12 tf=1e-12 pw=1
    W: Locale appears not set! please export LANG="en_US.UTF-8" or equivalent,
    W: or ahkab's unicode support is broken.

    UnicodeEncodeError Traceback (most recent call last)
    in ()
    23 tran_analysis = ahkab.new_tran(tstart=0, tstop=1.2e-3, tstep=1e-6, x0=None)
    24
    ---> 25 r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis])
    26
    27 import pylab

C:\Python34\lib\site-packages\ahkab\ahkab.py in run(circ, an_list)
657 (an_type.upper(), an_item['x0']))
658 an_item['x0'] = None
--> 659 r = analysis[an_type](circ, **an_item)
660 results.update({an_type: r})
661 if an_type == 'op':

C:\Python34\lib\site-packages\ahkab\dc_analysis.py in op_analysis(circ, x0, guess, outfile, verbose)
682
683 if opsolution and outfile != 'stdout' and outfile is not None:
--> 684 opsolution.write_to_file()
685 if opsolution and (verbose > 2 or outfile == 'stdout') and options.cli:
686 opsolution.write_to_file(filename='stdout')

C:\Python34\lib\site-packages\ahkab\results.py in write_to_file(self, filename)
466 fp.write("========================\n\n")
467 for k in sorted(self._op_info.keys()):
--> 468 fp.write(printing.table(self._op_info[k], headers=self._op_keys[k][0]))
469 fp.write('\n\n')
470 #for opi in self.op_info:

UnicodeEncodeError: 'cp950' codec can't encode character '\u03d5' in position 13: illegal multibyte sequence

Sin function bug

Before I start: thanks so much for this library. Tons of fun.

I've got the sin function going, but I see

E: Error: sin function not well defined. This is a bug.

my output is as should be, any hints on what this means?

Issue with ankab

Hi all,

I'm trying to start ahkab on mac, python 3.5, and getting these error messages:

W: Locale appears not set! please export LANG="en_US.UTF-8" or equivalent, 
W: or ahkab's unicode support is broken.
/python3.5/site-packages/ahkab/plotting.py:235: MatplotlibDeprecationWarning: pyplot.hold is deprecated.
    Future behavior will be consistent with the long-time default:
    plot commands add elements without first clearing the
    Axes and/or Figure.
  pylab.hold(True)
/python3.5/site-packages/matplotlib/__init__.py:917: UserWarning: axes.hold is deprecated. Please remove it from your matplotlibrc and/or style files.
  warnings.warn(self.msg_depr_set % key)
/anaconda/lib/python3.5/site-packages/matplotlib/rcsetup.py:152: UserWarning: axes.hold is deprecated, will be removed in 3.0
  warnings.warn("axes.hold is deprecated, will be removed in 3.0")
/anaconda/lib/python3.5/site-packages/ahkab/plotting.py:248: MatplotlibDeprecationWarning: pyplot.hold is deprecated.
    Future behavior will be consistent with the long-time default:
    plot commands add elements without first clearing the
    Axes and/or Figure.
  pylab.hold(False)

Could please help me, I can't understand why I have to change the LANG for starting the script.

RFC: SPICE3 Compatibility

Ahkab currently supports two radically different syntaxes and semantics for describing circuits and analyses:

  • a SPICE3-like netlist format, akin to what one might encounter when using pspice, ngspice, ltspice, etc, and friends
  • a reasonably Pythonic object-oriented programming paradigm where one creates a circuit object, adds connected components, and then executes analyses, storing/plotting/manipulating the results.

I have used both formats, as I suspect many of y'all have as well. It seems to me (a younger gentlemen) that ASCII SPICE3 netlists are quickly becoming an obsolete-ish aspect of circuit design and simulation. I have reviewed / attended more than one bachelors engineering program, and it seems as if textual circuit simulation (pspice, ngspice) is being usurped by "more modern" toolkits for exploration, such as ltspice (graphical,) simulink/matlab (graphical,) and labview/multisim (graphical.)

While there are a wide variety of topics to be considered here, but I wanted to start a dialog about whether SPICE3 compatibility is a valued feature (worth preserving) at the cost of limiting innovation in the Ahkab project.

There seems to be a great deal of interest in the aspects that make Ahkab unique - building rich explorations of electrical systems in native Python, and relatively less interest in using Ahkab as a competitor for SPICEs, of which there are both several libre varieties and a wide number of commercial alternatives, many of whom offer either more features, better speed, graphical frontends, etc.

So, the crux of the issue - keep maintaining .ckts as first-class citizens, building into and maintaining the 1500 SLOC of parse_netlist.py, or priortise features, demos, and tests that flex the power of integrating circuit analyses with the Python ecosystem and future.

Additional observations:

netlist parser should be able to handle model parameters provided after circuit

With ADI macromodels, it's not uncommon to include directives providing information about the parameters of specified components.

Currently:

.model dx d(is=1e-13 kf=1e-30)

gives:

NetlistParseError: Unknown model (dx) on line 159.

The diode model does include these parameters, but doesn't appear to know how to parse them from netlists.

JavaScript and other questions

Did any one tried to compile the simulator to javascript?
Is it possible to alter a component attribute and keep the simulation on? or we need to reset every time a property changed ? ex: resistance value of a component changes..

How about performance?

Is the results accurate?

Is there a list of components that is included in this simulator?

Thanks

Symbols for circuit elements are not assumed real in symbolic analysis

In symbolic.py there is a dictionary

enabled_assumptions = {'real':False, 'positive':False, 'complex':True}

Which is checked in the _symbol_factory function

def _symbol_factory(name, **options):
    filtered_options = {}
    for i in options:
        if options[i] and enabled_assumptions[i]:
            filtered_options.update({i:options[i]})
        else:
            pass # discarded
    return sympy.Symbol(name.upper(), **filtered_options)

This is preventing symbols from being produced with the real and positive assumptions, for example here:

R = _symbol_factory(elem.part_id.upper(), real=True,
                                      positive=True)

The fix is presumably just to enable these assumptions in the dictionary

enabled_assumptions = {'real':True, 'positive':True, 'complex':True}

Does not work with Ipython

Hi.
I have a problem with the package and ipython.
As soon as I dd
import ahkab
from ahkab import circuit, printing, devices

First thing that I get is:
W: Locale appears not set! please export LANG="en_US.UTF-8" or equivalent,
W: or ahkab's unicode support is broken.

and then when I use the up arrow key in the keyboard I get this:

In [4]: ^[[A

If I use the down arrow key I get:

In [5]: ^[[B

I use linux
Linux 3.14.14-gentoo

In [2]: for i in numpy, scipy, matplotlib:
   ...:         print i.__version__
   ...:     
1.9.2
0.14.0
1.4.3

Python 2.7.9 |Anaconda 2.1.0 (64-bit)| (default, Mar  9 2015, 16:20:48) 
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.

locale -a
gives me -

C
en_US
en_US.iso88591
en_US.utf8
POSIX

and doing export LANG="en_US" change noting.

Thanks.

Theory behind circuit simulation

Could you, please, point me to a handful books about circuit simulation? This is an interesting topic, but without a good reference not so easy to pick up. And because i'm just an electronic hobbist i do not know where to start )))

BJT model

A BJT model supporting NPN and PNP analysis would be "nice to have." BJTs are still a common building block of macromodels provided by semiconductor companies.

I'd consider implementing a pseudomodel consisting of a current controlled current source and a bunch of passives, but curious as to the pevailing thoughts on the issue.

Thanks!
Ian

Voltage-Controlled Switch Issue

image

I implement the circuit above.

  • Voltage-Controlled Switch Example

sw 0 out in 0 mysw
v1 in 0 type=pulse 0 1.0 0 0.5m 0.5m 0 1m
v2 net1 0 type=vdc vdc=3.3
r1 net1 out 1k

.model sw mysw vt=0.5 vh=0.4 ron=1 roff=1Meg
*.model sw mysw von=0.9 voff=0.1 ron=1 roff=1Meg
.tran tstep=100n tstop=3m
.plot tran v(in) v(out)
.end

image
Ver. 0.18
From the document, the resistance of the switch should changes from VT+VH to VT-VH (distance 2*VH)

image

However, the turn-on voltage is 0.9 and turn-off voltage is the same.
The hysteresis is not available.

circuit.add_model & circuit.add_diode documentation

Looks like a model has to be added:

circuit.add_model("diode", "diode", {"name": "..diode.."})

before a diode can be added:

circuit.add_diode("D1", "da", "dc", "diode")

The "model_label" argument to add_diode isn't documented in the docstring - am I doing that correctly? If you +1 that, I'll go ahead and add a note.

Thanks!

Plain text component values

Hi, I made this for parsing plain text schematic values:

https://gist.github.com/endolith/1a74477fc1659cd6bf9d138e09c72672

value_parser('100 MΩ')
Out[194]: (100000000.0, u'ohm')

value_parser('2M2')
Out[195]: (2200000.0, None)

value_parser('4n7')
Out[196]: (4.700000000000001e-09, None)

value_parser('4.7 nH')
Out[197]: (4.700000000000001e-09, u'henry')

So you could make entering components more readable and catch mistakes more easily, too:

cir.add_resistor('R1', 'n1', 'n2', '50 ohm')
cir.add_inductor('L1', 'n2', 'n3', '245.894m')
cir.add_capacitor('C1', 'n3', 'n4', '103.013 nF')
cir.add_inductor('L2', 'n4', cir.gnd, '98.3652 μH')
cir.add_vsource('V1', 'n1', cir.gnd, dc_value='0 V'., ac_value='1 V')

Is this something you'd be interested in incorporating?

For instance in Circuit.add_resistor, it would be something like this:

value, unit = value_parser(value)
if unit not in {None, 'ohm'}:
    raise Exception('Unit doesn't match component type')
if value == 0:
    raise CircuitError("ZERO-valued resistors are not allowed.")

or put the exception inside the function:

value = value_parser_and_checker(value, should_be='ohm')
if value == 0:
    raise CircuitError("ZERO-valued resistors are not allowed.")

So entering units would be optional, but would help catch errors of changing the wrong value, etc. I think most SPICE implementations ignore units.

Zener Diode

Hey, thanks very much for this work. can you please tell me how to add a zener Diode to a circuit?

Possible node / source id collision in symbolic analysis

If a circuit contains a voltage source with part_id V<something> and the circuit has a node named <something>, the symbolic solver will first create two variables equally named V<something> and then it will confuse them for referring to the same quantity, incorrectly.

See the end for a work-around.

eg. the example netlist file a.ckt quoted below:

THIS FAILS.
v1 1 0 type=vdc vdc=1
r1 1 0 1k

.symbolic

Produces:

$ahkab a.ckt
Starting symbolic AC analysis...
Building symbolic MNA, N and x...  done.
Building equations...
Performing auxiliary simplification...
Symplified sytem:
To be solved for:
[V1, I[V1]]
Solving...
Traceback (most recent call last):
  File "/home/gventuri/.local/bin/ahkab", line 9, in <module>
    load_entry_point('ahkab==0.09', 'console_scripts', 'ahkab')()
  File "/home/gventuri/work/repos/ahkab/ahkab/__main__.py", line 164, in cli
    outfile=cli_options.outfile, verbose=verbose)
  File "/home/gventuri/work/repos/ahkab/ahkab/ahkab.py", line 659, in main
    results.update(run(circ, [an]))
  File "/home/gventuri/work/repos/ahkab/ahkab/ahkab.py", line 467, in run
    r = analysis[an_type](circ, **an_item)
  File "/home/gventuri/work/repos/ahkab/ahkab/symbolic.py", line 140, in symbolic_analysis
    eq, x, manual=options.symb_sympy_manual_solver, simplify=True)
  File "/usr/lib/python2.7/dist-packages/sympy/solvers/solvers.py", line 688, in solve
    symbols=symbols)
  File "/usr/lib/python2.7/dist-packages/sympy/solvers/inequalities.py", line 487, in reduce_inequalities
    "only univariate inequalities are supported")
NotImplementedError: only univariate inequalities are supported

While, just substituting V1 with Va1, as follows:

THIS WILL NOT FAIL
va1 1 0 type=vdc vdc=1
r1 1 0 1k

.symbolic

Produces, correctly:

$ahkab a.ckt 
Starting symbolic AC analysis...
Building symbolic MNA, N and x...  done.
Building equations...
Performing auxiliary simplification...
Auxiliary simplification solved the problem.
Success!
Results:
I[VA1]   = -VA1/R1
V1   = VA1

As this bug is inside the symbolic solver, it is in dependent of whether the netlist or the Python interfaces to the simulator are used.

Work-around: If you have a voltage source named V<X>, avoid naming any node X.

Is it possible to launch runs with multiprocess?

Hi all,

I am doing a basic AC transient simulation for power distribution network. I tried launching multiple simulation runs (with different decap scenarios) using pathos.multiprocessing ProcessingPool. However, this crashes IPython. I am wondering if anyone has successful done multiprocessing with ahkab.

Thanks,
Jerry

needs unit tests

Lots of code, none of it covered by unit tests. Things are often munged fairly heavily, it'd be great to know when a commit would cause a regression.

Subcircuit call problem

I am trying to describe a cmos not gate in a netlist but every time i call the subcircuit the output seems not to be correct e.g.

* supply voltages
Vs Vss 0 type=vdc vdc=0
Vd Vdd 0 type=vdc vdc=3

*input signal
V1 vin 0 type=vdc vdc=0

.model ekv cmosn TYPE=n VTO=0.7 KP=110U GAMMA=0.4 LAMBDA=0.04 PHI=0.7
.model ekv cmosp TYPE=p VTO=-0.7 KP=50U GAMMA=0.57 LAMBDA=0.05 PHI=0.8

.subckt my_not_gate A Y
M1 Y A Vdd Vdd cmosp L=1u W=10u
M2 Y A Vss Vss cmosn L=1u W=10u
.ends

Xuut name=my_not_gate A=vin Y=inverter_result

.op
.end

running ahkab netlist_parser by the command python -m ahkab ahk.sp

Variable               Units           Value         Error    %
---------------------  -------  ------------  ------------  ---
VVSS                   V         0             0              0
VVDD                   V         3            -3e-12          0
VVIN                   V         0             0              0
VINVERTER_RESULT       V        -1.37938e-10  -2.94159e-23    0    <-- not the correct value 

On the other hand when removing the subcircuit call

* supply voltages
Vs Vss 0 type=vdc vdc=0
Vd Vdd 0 type=vdc vdc=3

*input signal
V1 A 0 type=vdc vdc=0

.model ekv cmosn TYPE=n VTO=0.7 KP=110U GAMMA=0.4 LAMBDA=0.04 PHI=0.7
.model ekv cmosp TYPE=p VTO=-0.7 KP=50U GAMMA=0.57 LAMBDA=0.05 PHI=0.8


M1 inverter_result A Vdd Vdd cmosp L=1u W=10u
M2 inverter_result A Vss Vss cmosn L=1u W=10u

.op
.end

gives the output

Variable          Units           Value         Error    %
----------------  -------  ------------  ------------  ---
VVSS              V         0             9.91425e-23    0
VVDD              V         3             8.98946e-14    0
VA                V         0             0              0
VINVERTER_RESULT  V         3            -6.08989e-12    0   <-- the correct value

Am i missing something in the netlist syntax ? i am following the documentation

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.