PyParis2017 / Circuit simulation using Python, by Fabrice Salvaire
-
Upload
pole-systematic-paris-region -
Category
Technology
-
view
1.121 -
download
2
Transcript of PyParis2017 / Circuit simulation using Python, by Fabrice Salvaire
Circuit Simulation using Python
Fabrice Salvaire
PyParis 2017
R2
150
Q13
2N4236
Q14
2N4239
R1
20K
i1+
V1
−
R3
150
−
+A1
NexusSQ-10A
R14
19K
R13
91K
R6
15K −
+A2
NexusSQ-10A
Q3
2N5464
Q4
2N4239
D4
OMC-VD3
Q1
2N3819
Q2
2N4236
D1
D2
OMC-V
Q7
2N5464
Q8
2N4239
Q5
2N3819
Q6
2N4236
R11
20
D5
1N4729 C4
0.68µF
C3
0.68µF
C2
0.1µF
R5
100K
C1
1µF
R9
910
R10
910
R4
100K
Q11
2N5464
Q10
2N4239
− ECC
D6
1N4728
Q12
2N3819
Q9
2N4236
+ ECC
R12
20
i2+
V2
−R15
200
F. Salvaire 1 / 35
http://pyparis.org
https://www.fabrice-salvaire.fr/en/about/contacthttps://github.com/FabriceSalvaire/pyparis-2017
CC BY-NC-SA 3.0
https://pyspice.fabrice-salvaire.fr/pyparis-2017-talk.pdf
Outline
1 Why Python is the right language for engineering ?
2 An Introduction to Circuit Simulation
3 SPICE an Industrial Standard
4 PySpice the Bridge between SPICE and Python
5 Modelica a Language for Simulation
F. Salvaire 2 / 35
Let do engineering . . .
As computers cannot boot without an Office Pack
Students and later engineers know
You can do everything with it at work
from R&D to communication, database, accounting, . . .
You will Excel !!!
F. Salvaire 3 / 35
Mouse Algorithm
How to compute the derivative of a data set ?
1 copy the data of the first column
2 past to the second column starting from the second line
3 enter the formulae (A − B)/dt in the third column
Easy and Efficient ! Isn’t it ?
Next exercise compute an histogram . . .Python answer if you are lazy
for value in values:hist[int(value // bin_size)] += 1
F. Salvaire 4 / 35
A cabinetworker as a lot of tools : one for each task !
F. Salvaire 5 / 35
Open Source Community has also a lot of tools !
Of course if you have to build this
You need the right toolsYou have to look for solutionsAnd evaluate if it makes the job
But for teaching, learning or DIY
You can find what you are looking forAnd maybe discover alternatives
Like to simulate electronic circuitor even complex systems
You can get iteven if you live in a ghettoIt’s free and open !
F. Salvaire 6 / 35
Simulation Workflow
Steer Process Analyse
−→ −→
F. Salvaire 7 / 35
Thanks to Guido van Rossum, We have Python !
• Indentation is syntax ! So clever !Look at PhD student C++ code
• Canonical Syntax• High Level Language• Object Oriented• Transparent memory management• Easy to bind with C or Fortran• An incredible Scientific Environment
F. Salvaire 8 / 35
Simulation Workflow with Python
Steer Process Analyse
−→ −→
• JSON• YAML• Python itself !• XML• h5py : HDF5
• subprocess• CFFI• SWIG
• Numpy• SciPy• Matplotlib• IPython
We have more than we can buy learn !
F. Salvaire 9 / 35
Circuit Simulation : Nodal Analysis
Circuit ≡ Device’s Graph
i1
i4
i2
i7
i3
i5 i6
i8 i9
Roughly . . .
1 Apply Kirchhoff’s circuit laws• Current Law∑
Ik = 0 for each nodeconservation of the electron flow
• Voltage Law∑Vk = 0 for each cycle
think that is a closed path
2 Apply Device Equation f(Vk, Ik) = 0e.g. Ohm Law for resistor V = RI
Can be Complex e.g. Capacitor, Inductorand Non-Linear e.g. Diode !
F. Salvaire 10 / 35
Circuit Simulation : Nodal Analysis Example
Is1
1
R1
0
R2
2
R3
−+
Vs1
Let apply the recipes1
R1+ 1
R2− 1
R21
− 1R2
1R2
+ 1R3
−11 −1 0
V1
V2IVs1
=
Is10
Vs1
Then solve this System of Linear Equations
There are algorithms to build theses matricesUsually matrices are sparses
Complex therms for Capacitor, Inductor e.g. V ? = 1sC I?
Non linear e.g. Shockley Diode Model I = Is
(e
VnVT − 1
)To go further QUCS Technical Papers or PDF
F. Salvaire 11 / 35
Circuit Simulation : Several kinds of analyses
Principal Analyses
• DC AnalysisOperating Point and DC SweepCompute node’s voltages at t = 0 cf. infra
• AC Small-Signal AnalysisTransfer FunctionFrequency Analysis V (ω), cf. Laplace Transformsmall means Taylor Series
• Transient AnalysisSimulate over time V (t)Integrator
More specific ones
• Pole-Zero Analysis• Small-Signal Distortion Analysis• Sensitivity Analysis• Noise Analysis• etc.
F. Salvaire 12 / 35
To go further Ngspice Documentation
SPICE : Simulation Program with Integrated Circuit Emphasis
• Developed by Dr. Laurence Nagel in 1973 at Berkeley• First software to combine
DC, AC and transient analog circuit analysis capabilities• An early open source software initiative (Public Domain)• Used in undergraduate courses• Evolved to a worldwide standard• IEEE Milestone on 2011• Berkeley released spice3f5 at last on 1993• Superseded by commercial and open source forks
To go further SPICE2 : A Computer Program to Simulate Semiconductor Circuits ; Nagel, Laurence W. ; 1975The Origins of SPICE by Nagel
F. Salvaire 13 / 35
SPICE : Netlist as Input
0
Vin
1C1
2
R2
R1
6
Q1
3
RE
4C2
5
RL
RC−+ Vpwr
AC-coupled amplifierVpwr 6 0 DC 15VVin 1 0 AC 1V SIN(0V .5V 1KHz)C1 1 2 10uR1 6 2 100kR2 2 0 20kRC 6 4 10kQ1 4 2 3 bjtRE 3 0 2kC2 4 5 10uRL 5 0 1Meg.model bjt npn(bf=80 cjc=5p rb=100).ac dec 5 10m 1G*.tran .02ms 2ms 0 .01ms.controlrunplot V(1) V(5).end
F. Salvaire 14 / 35
SPICE : A Worldwide Standard for integrated circuit simulationDevice manufacturers use SPICE language to provide models as sub-circuit
1N5913B - 1N5957B SILICON ZENER DIODES
VZ : 3.3 - 240 VoltsPD : 3 Watts
FEATURES : * Complete Voltage Range 3.3 to 200 Volts * High peak reverse power dissipation * High reliability * Low leakage current * Pb / RoHS Free
MECHANICAL DATA * Case : DO-41 Molded plastic * Epoxy : UL94V-O rate flame retardant * Lead : Axial lead solderable per MIL-STD-202,
method 208 guaranteed * Polarity : Color band denotes cathode end * Mounting position : Any * Weight : 0.335 gram
MAXIMUM RATINGS Rating at 25 °C ambient temperature unless otherwise specified
Rating Symbol Value Unit Maximum Steady state Power Dissipation 3.0 W
@ TL = 75 ºC, Lead Length = 3/8"
Derate above 75 ºC
Steady State Power Dissipation 1.0 W
@ TL = 50 ºC, Lead Length = 3/8"
Derate above 50 ºC
Operating and Storage Temperature Range TJ,TSTG - 65 to + 200 °C
Page 1 of 4 Rev. 07 : June 7, 2006
6.67 mW/ºC
PD
PD
24 mW/ºC
DO - 41
Dimensions in inches and ( millimeters )
1.00 (25.4)MIN.0.108 (2.74)
0.079 (1.99)
0.205 (5.20)0.161 (4.10)
1.00 (25.4)MIN.0.034 (0.86)
0.028 (0.71)
Certificate TH97/10561QM Certificate TW00/17276EM
* http://www.onsemi.com/pub_link/Collateral/1N5919BRL.SP3.SUBCKT d1n5919brl 2 1*************************************** Model Generated by MODPEX **Copyright(c) Symmetry Design Systems** All Rights Reserved ** UNPUBLISHED LICENSED SOFTWARE ** Contains Proprietary Information ** Which is The Property of ** SYMMETRY OR ITS LICENSORS ** Modeling services provided by ** Interface Technologies www.i-t.com **************************************** Model generated on Jun 22, 2004* MODEL FORMAT: SPICE3* anode cathode*node: 2 1* Forward SectionD1 2 1 MD1.MODEL MD1 D IS=1.33275e-21 N=1 XTI=1 RS=0.1+ CJO=1e-11 TT=1e-08* Leakage CurrentR 1 2 600000 MDR.MODEL MDR R TC1=0 TC2=0* BreakdownRZ 2 3 0.520393IZG 4 3 0.3204R4 4 3 100D3 3 4 MD3.MODEL MD3 D IS=2.5e-12 N=2.40102 XTI=0 EG=0.1D2 5 4 MD2.MODEL MD2 D IS=2.5e-12 N=3.19856 XTI=0 EG=0.1EV1 1 5 6 0 1IBV 0 6 0.001RBV 6 0 5153.19 MDRBV.MODEL MDRBV R TC1=1.79e-08*-- SPICE3 DIODE MODEL DEFAULT PARAMETER* VALUES ARE ASSUMED*IS=1E-14 RS=0 N=1 TT=0 CJO=0*VJ=1 M=0.5 EG=1.11 XTI=3 FC=0.5*KF=0 AF=1 BV=inf IBV=1e-3 TNOM=27.ENDS d1n5919brl
F. Salvaire 15 / 35
SPICE Open Source Clones : Many initiatives . . . !
1 Berkeley spice3f5 1993• A Research Project• Was not developed with industrial concerns
2 Ngspice : New Generation Spice 1999• Fork of Berkeley spice3f5• Features mixed-level and mixed-signal simulation
XSpice (mixed signal), Cider1b1 and GENIUS TCAD (mixed level)• Still maintained (?) but not actively ! last release Jan. 2014
3 GnuCap : GNU Circuit Analysis Package 1993• Attempt to rewrite SPICE from scratch by Albert Davis• Davis’s Thesis "Implicit Mixed-Mode Simulation of VLSI Circuits"• No longer maintained since 2006 2013 ?
4 QUCS : Quite Universal Circuit Simulator 20035 Akhab 2006
? Open Source means Free Software, GPL . . .
F. Salvaire 16 / 35
QUCS : When Open Source fails !
QUCS : Quite Universal Circuit Simulator
• Founded by Michael Margraf in 2003 (?)
• Complete ToolchainSchematic Editor, Simulation and Plot
• IDE based on Qt3• Interesting simulation features• Margraf moved later to proprietary software ???• Slowly maintained
port to Qt4 is ongoing since . . . many years
F. Salvaire 17 / 35
QUCS : What is wrong ?
To develop an electronic CAD software,we need these skills
• Circuit Simulation• Solid State Device Modelling• State of Art Numerical Analysis• Software Architecture, Core Design• GUI Design• XML Format Design• Schematic Editor Design• Plot Library• . . .
Later, we have to maintain
• A very large code base• A GUI Qt3 → Qt4 → Qt5 → . . .
Don’t do that until you have a zillion $(industrial market)
Develop Software Components !And plug them together
F. Salvaire 18 / 35
LtSpice : Well known free but proprietary clone
Just a (quite old) marketing tool of Linear Technology (device manufacturer)
F. Salvaire 19 / 35
PySpice : The Bridge between SPICE and PythonHow it is born ?
• Come back to electronic learning• Use the most maintained SPICE flavour : NgSpice• But analysis tools are outdated : e.g. TCL Spice• I want Python !!!
=⇒ Plug NgSpice to Python
How to get it ?• https://pyspice.fabrice-salvaire.fr• https://github.com/FabriceSalvaire/PySpice• Available on PyPi• Licensed under GPLv3
F. Salvaire 20 / 35
PySpice : Workflow
Python Netlist NgSpice Python Analysis
1 Define circuit in PythonCin 1 2 470n −→ circuit.C(’in’, 1, 2, nano(470))
or include netlist as is2 Define simulation parameters3 Generate netlist code4 Execute NgSpice (server mode)
5 Get output as Numpy array6 Analyse, plot . . .
Why Python Netlist ?• More verbose, But• Can use Python to configure netlist
example• keyword argument
resistance=kilo(100)• cf. Modelica see later
F. Salvaire 21 / 35
PySpice : I hate Netlist, I want a Schematic Editor !!!No Problem, Use KiCad !
• Implement a minimal Netlist parser• But a full parser would be difficult to implement
NgSpice syntax is very complexdue to many extensions
• Tips : Use subcircuit to hide complexity
Leading Open SourceElectronics Design Automation Suite
CERN is a contributorKiCad example
F. Salvaire 22 / 35
PySpice : NgSpice as a Shared Library
• NgSpice can be used as a shared library instead of an executable• Not a big improvement, But• We can use the NgSpice Shared API
• To define external independent voltage/current sources (Input)• To get the simulation output at each step (Output)
Python / C NgSpicesources
output
We can thus extend NgSpice easily with C or Python code
• API also features a step by step simulation mode• PySpice as a CFFI Binding
NgSpice API exampleF. Salvaire 23 / 35
PySpice : Some features
Implemented• Devices handled by a powerfull
meta-class mechanism• Units• Netlist Library Manager• Oriented Object API for Netlist• Oriented Object API for Waveforms• Current Probe• Bode diagrams
Must to have• More examples• Improved API• more Analysis Tools• Additional Plots e.g. eye-diagram etc.• Full featured shared API example• KiCad integration ?
F. Salvaire 24 / 35
PySpice : Example’s Documentation Generator
PySpice has some learning materials
• Kind of Jupyter Notebook . . .but for peoples that want a True Editor
• reStrucuredText and Sphinx• Circuit_macros for diagrams• Concept : Use directive comments
to add text and figure blocks
However Notebook could be an option as well
# A source code comment#?# A comment that must not appear in the documentation
#!# ==========================#!# A Restructuredtext Title#!# ==========================
python code ...
#!##!# Some reStructuredText contents#!#
python code ...
# Insert the output of the following python codepython code ...#o#
# Add the file content as literal block#itxt# kicad-pyspice-example/kicad-pyspice-example.cir
# Add a Python file as a literal block#i# RingModulator.py
# Insert an image#lfig# kicad-pyspice-example/kicad-pyspice-example.sch.svg
# Insert Circuit_macros diagram#cm# circuit.m4
# Insert a Matplotlib figure#fig# save_figure(figure, ’my-figure.png’)
F. Salvaire 25 / 35
Diagrams with Circuit_macros . . . or Algorithms versus GUI.PScct_init
elen = 0.75epsilon = 1e-3
G: ground; dot; "0" rjustsource(up_ elen, AC); llabel(,V_in,); dot; "in" rjustcapacitor(right_ elen); llabel(,C_1,); dot; "2" rjust above{ resistor(down_ to (Here,G)); rlabel(,R_2) }{ R1: resistor(up_ elen_*1.5); llabel(,R_1); dot; "5" above }
line right_ elen_/2; up_Q1: bi_tr(,,,E) with .B at Here; llabel(,,Q_1)
Q1E: Q1.E - (0,elen_/8)line down from Q1.E to Q1E; dot; "3" ljustresistor(down_ to (Q1.E,G)); rlabel(,R_E)
Q1C: Q1.C + (0,elen_/8)dot(at Q1C); "4" ljust abovecapacitor(right_ elen from Q1C); llabel(,C_2)dot; "out" ljustresistor(down_ to (Here,G)); rlabel(,R_L)line down epsilon then to G
resistor(up_ from Q1.C to (Q1.C,R1.end)); llabel(,R_C)line up epsilon then left to (G,R1.end) then down epsilonreversed(‘source’, down_ elen, V); llabel(,V_pwr,)ground
.PE
Also circuitikz
With M4 macros inside !
m4 → dpic → tikz → LATEX
0
Vin
1C1
2
R2
R1
6
Q1
3
RE
4C2
5
RL
RC−+ Vpwr
F. Salvaire 26 / 35
Related Project : Akhab pronounced "uh, cab"
• Goal : Implement a SPICE- like in Pythonusing Numpy, SciPy, and SymPy
• Started by Giuseppe Venturini in 2006† sadly deceased at the end of 2015 †
• https://ahkab.github.io/ahkab• v0.18 released on July 2015• Interesting initiative to learn circuit simulation
F. Salvaire 27 / 35
Modelica : A Language for Modelling of Complex Physical Systems
Modelica in few words• Language + Standard Library• Object-Oriented and Equation based• Multi-domains Modelling• Non-proprietary• Developed by the non-profit Modelica Association• initiated in September 1996 by Hilding Elmqvist• First version on Sept. 1997 → 3.4 on April 2017• Commercial front-ends : e.g. Dymola• Open Source front-ends : OpenModelica and JModelica
To go further https://www.modelica.orgIntroduction to Object-Oriented Modeling and Simulation with OpenModelica - Peter Fritzson
F. Salvaire 28 / 35
Modelica : Bouncing-ball Example
model BouncingBallparameter Real e=0.7 "coefficient of restitution";parameter Real g=9.81 "gravity acceleration";Real h(start=1) "height of ball";Real v "velocity of ball";Boolean flying(start=true) "true, if ball is flying";Boolean impact;Real v_new;
equationimpact = h <= 0;der(v) = if flying then -g else 0;der(h) = v;
// Triggered when one of theses conditions are truewhen {h <= 0 and v <= 0, impact} then
v_new = if edge(impact) then -e*pre(v) else 0;flying = v_new > 0;reinit(v, v_new);
end when;
end BouncingBall;
Netwton’s Law
dh
dt= v
dv
dt= d2h
dt2 = −g
At impact, lost some energy
v′ = −ev
and go upwardsF. Salvaire 29 / 35
Modelica : Circuit with Annotations (Schema)model SimpleRectifierWithTransformer
Modelica.Electrical.Analog.Sources.SineVoltage ac_line(V = 230, freqHz = 50);Modelica.Electrical.Analog.Basic.Capacitor capacitor(C = 0.00005);Modelica.Electrical.Analog.Basic.Ground ground;Modelica.Electrical.Analog.Ideal.IdealDiode diode(Vknee = 0.5);Modelica.Electrical.Analog.Basic.Resistor load_resistor(R = 1000.0);Modelica.Electrical.Analog.Ideal.IdealTransformer transformer(n = 10, Lm1 = 1);Modelica.Electrical.Analog.Sources.SineVoltage sinevoltage1
annotation(Placement(visible = true, transformation(origin = -78.7769,-10.3538, extent = -10,-10,10,10, rotation = -90)));Modelica.Electrical.Analog.Basic.Transformer transformer1 annotation(...);Modelica.Electrical.Analog.Semiconductors.Diode diode1 annotation(...);Modelica.Electrical.Analog.Basic.Resistor resistor1 annotation(...);Modelica.Electrical.Analog.Basic.Capacitor capacitor1 annotation(...);Modelica.Electrical.Analog.Basic.Ground ground1 annotation(...);
equationconnect(resistor1.n, ground1.p)
annotation(Line(points = 22.286, -18.6196, 22.286, -25.0637, 22.5062, -25.0637, 22.5062, -25.0637));connect(capacitor1.n, transformer1.n2) annotation(...);connect(resistor1.n, capacitor1.n) annotation(...);connect(capacitor1.p, resistor1.p) annotation(...);connect(diode1.n, capacitor1.p) annotation(...);connect(transformer1.p2, diode1.p) annotation(...);connect(sinevoltage1.n, transformer1.n1) annotation(...);connect(sinevoltage1.p, transformer1.p1) annotation(...);connect(ac_line.p, transformer.p1);connect(ac_line.n, transformer.n1);connect(ac_line.n, ground.p);connect(transformer.p2, diode.p);connect(transformer.n2, ground.p);connect(diode.n, capacitor.p);connect(diode.n, load_resistor.p);connect(capacitor.n, ground.p);connect(load_resistor.n, ground.p);annotation(Diagram(coordinateSystem(extent = -100, -100, 100, 100, preserveAspectRatio = true, initialScale = 0.1, grid = 2, 2)));
end SimpleRectifierWithTransformer;
To go further SPICE3 Modelica Library
F. Salvaire 30 / 35
1 Define devices2 connect(resistor1.n, ground1.p)
! Modelica performs Transient Analysis
Modelica : Open Source Front-Ends
1 OpenModelica https://www.openmodelica.org• Supported by a non-profit organization : Open Source Modelica Consortium (OSMC)• OSMC Public License ≈ GPLv3• Provide an IDE : OMEdit• Based on C++ and Corba• V1.12 released on May 2017• Packages available on some Linux Distributions
2 JModelica http://jmodelica.org• Started at Department of Automatic Control, Lund University• Supported by Modelon AB• GPLv3• Based on C, Java and Python• V2.0 released on May 2017
! Packages are welcome since compilation can be tricky . . .F. Salvaire 31 / 35
OpenModelica : OMEdit Screenshots
F. Salvaire 32 / 35
Using OpenModelica with Python
from OMPython import ModelicaSystem
mod = ModelicaSystem(’bouncing-ball.mo’,’BouncingBall’)
mod.setSimulationOptions(stopTime=3)mod.simulate()
mod.getSolutions()t = mod.getSolutions(’time’)h = mod.getSolutions(’h’)
import pylabpylab.grid()pylab.plot(t, h)pylab.xlabel(’time [s]’)pylab.ylabel(’[height]’) 0.0 0.5 1.0 1.5 2.0 2.5 3.0
time [s]
0.2
0.0
0.2
0.4
0.6
0.8
1.0
[heig
ht]
Model is compiled to C
F. Salvaire 33 / 35
To go further OpenModelica Python InterfaceJmodelica doc
PyCpuSimulator : Simulate CPU using micro-code
https://github.com/FabriceSalvaire/PyCpuSimulator
CPU DatasheetExtractor
YAMLInstruction Set
Micro-CodeInterpreter
Features• Micro-Code Language to describe instruction• Opcode Decoder using Decision Tree• Read HEX firmware format• AVR Core CPU simulation is ongoing
If you want to play with Core . . .
F. Salvaire 34 / 35
Conclusion
Target : Learning, DIY, Hackerspace Courses . . .
I need your help• To add examples• To comment, fill issues
Why it is hard to promote ?• User are not computer scientist• Many use Windows : installation issue• Very limited interest for Industry
F. Salvaire 35 / 35