GithubHelp home page GithubHelp logo

mph- / lcapy Goto Github PK

View Code? Open in Web Editor NEW
223.0 22.0 44.0 41.65 MB

Lcapy is a Python package for symbolic linear circuit analysis and signal processing. It uses SymPy for symbolic mathematics.

License: GNU Lesser General Public License v2.1

Python 99.93% Makefile 0.07%

lcapy's Introduction

Lcapy is a Python package for linear circuit analysis. It uses SymPy for symbolic mathematics.

Run tests and checks Binder Documentation

Lcapy can symbolically analyse circuits described with netlists or by series/parallel combinations of components. It can also manipulate continuous-time and discret-time expressions.

Comprehensive documentation can be found at https://lcapy.readthedocs.io/en/latest/

Circuit analysis

The circuit is described using netlists, similar to SPICE, with arbitrary node names (except for the ground node which is labelled 0). The netlists can be loaded from a file or created at run-time. For example:

>>> from lcapy import Circuit, s, t
>>> cct = Circuit("""
... Vs 2 0 {5 * u(t)}
... Ra 2 1
... Rb 1 0
... """)

The circuit can then be interrogated to determine branch currents, branch voltages, and node voltages (with respect to the ground node 0). For example:

>>> cct[1].V(t)
5⋅R_b⋅u(t)
──────────
 Rₐ + R_b
>>> cct.Ra.I(t)
 5⋅u(t)
────────
Rₐ + R_b
>>> cct.Ra.V(s)
   5⋅Rₐ
────────────
s⋅(Rₐ + R_b)

One-port networks

One-port networks can be created by series and parallel combinations of other one-port networks. The primitive one-port networks are the following ideal components:

  • V independent voltage source
  • I independent current source
  • R resistor
  • C capacitor
  • L inductor

These components are converted to s-domain models and so capacitor and inductor components can be specified with initial voltage and currents, respectively, to model transient responses.

The components have the following attributes:

  • Zoc open-circuit impedance
  • Ysc short-circuit admittance
  • Voc open-circuit voltage
  • Isc short-circuit current

The component values can be specified numerically or symbolically using strings, for example,

>>> from lcapy import Vdc, R, L, C, s, t
>>> R1 = R('R_1')
>>> L1 = L('L_1')
>>> a = Vdc(10) + R1 + L1

Here a is the name of the network formed with a 10 V DC voltage source in series with R1 and L1.

The s-domain open circuit voltage across the network can be printed with:

>>> a.V(s)
10/s

The time domain open circuit voltage is given by:

>>> a.V(t)
10

The s-domain short circuit current through the network can be printed with:

>>> a.Isc(s)
10/(L_1*s**2 + R_1*s)

The time domain short circuit current is given by:

>>> a.Isc(t)
10/R_1

If you want units displayed:

>>> state.show_units=True
>>> a.Isc(t)
10/R_1.A

Two-port networks

One-port networks can be combined to form two-port networks. Methods are provided to determine transfer responses between the ports.

Here's an example of creating a voltage divider (L section)

>>> from lcapy import *
>>> a = LSection(R('R_1'), R('R_2'))

Limitations

  1. Non-linear components cannot be modelled (apart from a linearisation around a bias point).

  2. High order systems can go crazy.

  3. Some two-ports generate singular matrices.

Schematics

LaTeX schematics can be generated using circuitikz from the netlist. Additional drawing hints, such as direction and size are required.

>>> from lcapy import Circuit
>>> cct = Circuit("""
... P1 1 0; down
... R1 1 3; right
... L1 3 2; right
... C1 3 0_1; down
... P2 2 0_2; down
... W 0 0_1; right
... W 0_1 0_2; right""")
>>> cct.draw(filename='pic.tex')

In this example, P denotes a port (open-circuit) and W denotes a wire (short-circuit). The drawing hints are separated from the netlist arguments by a semicolon. They are a comma separated list of key-value pairs except for directions where the dir keyword is optional. The symbol label can be changed using the l keyword; the voltage and current labels are specified with the v and i keywords. For example,

>>> from lcapy import Circuit
>>> cct = Circuit("""
... V1 1 0; down
... R1 1 2; left=2, i=I_1, v=V_{R_1}
... R2 1 3; right=2, i=I_2, v=V_{R_2}
... L1 2 0_1; down, i=I_1, v=V_{L_1}
... L2 3 0_3; down, i=I_1, v=V_{L_2}
... W 0 0_3; right
... W 0 0_1; left""")
>>> cct.draw(scale=3, filename='pic2.svg')

The drawing direction is with respect to the positive node; i.e., the drawing is performed from the positive to the negative node. Since lower voltages are usually lower in a schematic, then the direction of voltage sources and ports is usually down.

By default, component (and current) labels are drawn above horizontal components and to the right of vertical components. Voltage labels are drawn below horizontal components and to the left of vertical components.

Node names containing a dot or underscore are not displayed.

Jupyter notebooks

Lcapy can be used with Jupyter Notebooks. For a number of examples see https://github.com/mph-/lcapy/tree/master/doc/examples/notebooks . These include:

Installation in Google Colab

To use Lcapy in Google Colab, run the following commands in the Colab notebook:

!pip install pdflatex
!sudo apt-get install texlive-latex-recommended
!sudo apt install texlive-latex-extra
!sudo apt install dvipng
!pip install lcapy

This will install all the required packages to run Lcapy on Colab.

Open In Colab

Documentation

For comprehensive documentation, see http://lcapy.readthedocs.io/en/latest (alternatively, the documentation can be viewed in a web browser after running 'make doc' in the top-level directory).

For release notes see http://lcapy.readthedocs.io/en/latest/releases.html

For another view on Lcapy see https://blog.ouseful.info/2018/08/07/an-easier-approach-to-electrical-circuit-diagram-generation-lcapy/

Citation

To cite Lcapy in publications use

Hayes M. 2022. Lcapy: symbolic linear circuit analysis with Python. PeerJ Computer Science 8:e875 https://doi.org/10.7717/peerj-cs.875

A BibTeX entry for LaTeX users is

@article{10.7717/peerj-cs.875,
 title = {Lcapy: symbolic linear circuit analysis with {Python}},
 author = {Hayes, Michael},
 year = 2022,
 month = Feb,
 keywords = {Linear circuit analysis, symbolic computation, Python},
 pages = {e875},
 journal = {PeerJ Computer Science},
 issn = {2376-5992},
 url = {https://doi.org/10.7717/peerj-cs.875},
 doi = {10.7717/peerj-cs.875}
}

Copyright 2014--2022 Michael Hayes, UCECE

lcapy's People

Contributors

bcbnz avatar blownintospace avatar danieljfarrell avatar mje-nz avatar mph- avatar oieieio avatar vitruviansasquatch avatar yoshi74ls181 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

lcapy's Issues

Examples with ac Voltage Source

Do you have any examples of working with an ac voltage source? I notice class lcapy.Vac() takes a couple of arguments, (V, phi) which I take to be amplitude and phase shift at a standard frequency (what frequency?)? Or does the voltage need to be defined as a function of time?

As a starter example I could bootstrap from, is there a way I can take a simple potential divider:

sch='''
Vi 1 0_1 ac {sin(omega)}; down
R1 1 2 22e3; right, size=1.5
R2 2 0 1e3; down
P1 2_2 0_2; down, v=V_{o}
W 2 2_2; right, size=1.5
W 0_1 0; right
W 0 0_2; right
'''

fn="voltageDivider.sch"
with open(fn, "w") as text_file:
    text_file.write(sch)
    
cct = Circuit(fn)
cct.draw(style='american')

and plot the voltage across R2 in the time domain (e.g. over t = np.linspace(0, 0.01, 1000)) alongside that of the original AC source voltage?

Hard to understand error if GS not installed

If you use Circuit.draw() without having ghostscript installed you get the following error

C:\ProgramData\Anaconda3\lib\site-packages\lcapy\schematic.py in png_image_size(filename)
     81 
     82     if (header[:8] != b'\211PNG\r\n\032\n' and (header[12:16] != b'IHDR')):
---> 83         raise Exception('%s not a png image' % filename)
     84     w, h = struct.unpack('>LL', header[16:24])
     85     width = int(w)

Exception: C:\Users\tiqi-F24\AppData\Local\Temp\tmp7nqsmvo8.png not a png image

which took me a long time to debug. Putting some simple check in the convert_pdf_png function in system.py if ghost script is actually installed might be a good idea.

I am using lcapy version 0.46.1 on Windows 10.

Thanks, all the best,
Martin

A problem with Circuit.V1.i.evaluate()....

This circuit seems to solve ok, but I can't evaluate it to plot it.
cct3 = Circuit(""" V1 1 0 {10*u(t)}; down=1.5 R1 1 2 .5; right, i=i(t)_ L 2 3 2; right W 0 0_0; right=3 C 3 0_0 0.5; down """) cct3.draw(label_nodes='all', draw_nodes='connections') cct3.R1.i iR = cct3.R1.i.evaluate(t) plt.plot(t, iR) plt.xlabel('t (s)') plt.ylabel('Current (A)') plt.grid('on') plt.title('Driven RLC Response, $i(t)$');

gives me the error:


TypeError Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/expr.py in evaluate_expr(expr, var, arg)
937 try:
--> 938 result = func(arg0)
939 response = complex(result)

in _lambdifygenerated(t)
1 def _lambdifygenerated(t):
----> 2 return ((40/21)*sqrt(7)exp(-1/8t)*sin((3/8)*sqrt(7)*t)*Heaviside(t))

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/expr.py in exp(arg)
900 arg = 500 + 1j * arg.imag
--> 901 elif arg > 500:
902 arg = 500;

~/anaconda3/lib/python3.7/site-packages/sympy/core/relational.py in nonzero(self)
303 def nonzero(self):
--> 304 raise TypeError("cannot determine truth value of Relational")
305

TypeError: cannot determine truth value of Relational

During handling of the above exception, another exception occurred:

RuntimeError Traceback (most recent call last)
in
----> 1 iR = cct3.R1.i.evaluate(t)
2 plt.plot(t, iR)
3 plt.xlabel('t (s)')
4 plt.ylabel('Current (A)')
5 plt.grid('on')

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/expr.py in evaluate(self, arg)
1007 pass
1008
-> 1009 return evaluate_expr(expr, var, arg)
1010
1011 def has(self, subexpr):

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/expr.py in evaluate_expr(expr, var, arg)
951
952 except TypeError as e:
--> 953 raise RuntimeError('Cannot evaluate expression %s: %s' % (self, e))
954
955 if scalar:

RuntimeError: Cannot evaluate expression 40*sqrt(7)*exp(-t/8)sin(3sqrt(7)*t/8)*Heaviside(t)/21: cannot determine truth value of Relational

Other examples I tried seem to work just fine.
This may be a problem with sympy. I'm not sure.

Thanks for lcapy. It makes my exams look very professional, and I've been having a good time with it.

Rob

new sympy gives a deprecation warning

Minimal example

from lcapy import Circuit # , s, t, f, R, L, C
cct = Circuit()
cct.add('V1 1 0 {u(t)}; down')
cct.add('L 1 2 1; right=2')
cct.add('C 2 3 1e-6; down=1.5')
cct.add('W24 2 4 ; right=2')
cct.add('R 4 5 ; down=1.5, v=$\Omega$')
cct.add('W1 0 3; right')
cct.add('W35 3 5; right')

cct.draw()

gives the following warning

c:\develop\anaconda3\lib\site-packages\sympy\core\decorators.py:38: SymPyDeprecationWarning: 

simplify has been deprecated since SymPy 1.1. Use
expand(diracdelta=True, wrt=x) instead. See
https://github.com/sympy/sympy/issues/12859 for more info.

  _warn_deprecation(wrapped, 3)

Formatting of circuit and equations in notebooks

The following example shows some issues when rendering equations and circuits in a notebook:

`
import lcapy as lca
cct = lca.Circuit("""
Cabc T123 0; down=1.5
W T123 1_0; right=2.0
W 0 0_3; right
Iabc 1_0 0_3; down
Rdef 1_0 T456 ; right=1.5
W 0_3 0_5; right
Cxyz T456 0_5 ; down
Rghi T456 To ; right=1.5
W 0_5 0_7; right=1.5
Vdef To 0_7 ; down
""")

cct.draw()

ss=cct.ss
se=ss.state_equations()
se

ss.x

ss.y
`

It would be nice if node names were subscripted in the same way as component names.

Subscriptions in equations are not correctly rendered. Only first character is subscripted.

Node names in output vector is not subscripted at all.

The first element in ss.y looks suspicious.

Convergence in netlist analysis of 3-loop topology

I'd like to analyse a netlist with a 3-loop topology, e.g.
`from lcapy import Circuit, s

cct= Circuit("""
V1 1 0;
R1 1 2;
R2 2 0;
R3 1 3;
R4 3 0;
R5 2 3;
""")
H = cct.R1.V(s)`

Unfortunately, it seems like the computation does not converge. What could be the reason and how to deal with it?

Expression error when Current sources used in circuit

Code:
from lcapy import Circuit,t
cct = Circuit("""
Ia 1 0;
RBLK 1 2;
CBLK 2 0;
""")
ss=cct.ss
Error:

File "C:\Users\a0230109\AppData\Local\Continuum\anaconda3\lib\site-packages\sympy\parsing\sympy_parser.py", line 1008, in parse_expr
return eval_expr(code, local_dict, global_dict)

File "C:\Users\a0230109\AppData\Local\Continuum\anaconda3\lib\site-packages\sympy\parsing\sympy_parser.py", line 903, in eval_expr
code, global_dict, local_dict) # take local objects in preference

File "", line 1
<Symbol ('built' ,positive=True )-Symbol ('in' ,positive=True )Symbol ('method' ,positive=True )Symbol ('lower' ,positive=True )Symbol ('of' ,positive=True )Symbol ('str' ,positive=True )Symbol ('object' ,positive=True )Symbol ('at' ,positive=True )Integer (0x000002A7A9ECEDF8 )>(t )
^
SyntaxError: invalid syntax


Facing this error only when I use Current sources, No issues when voltage sources used. All package versions seem to be up-to-date.

Symbolic expression for output signal

Hello,

Is there a command to get a symbolic (in terms of s or jω) expression for a signal?
For example this completely linear circuit displays a non-linear behavior. I would like to see the symbolic expression for the output signal.

from lcapy import Circuit
import numpy as np
import matplotlib.pyplot as plt

cct = Circuit('''
... Vin 1 0 {sin(130e6*2*3.14159*t)}
... R1  1 0 1000
... C4  1 2 1.0e-5   0
... C2  2 3 39.0e-12 0
... C3  3 0 22.0e-12 0
... La  2 4 0.32e-6  0
... C1  4 0 3.0e-12  0''')

t = np.linspace(0, 2e-7, 1000)
Vinp = cct.Vin.v.evaluate(t)
Vout = cct.C1.v.evaluate(t)

plt.plot(t, Vinp, 'g', linewidth=2)
plt.plot(t, Vout, 'r', linewidth=2)
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.show()

Here is waveform:

[url=https://postimages.org/][img]https://i.postimg.cc/h4VbnZB2/python-simulation-nonlinear-behavior.jpg[/img][/url]

Rendering missing wires when label_node=True...

Hi Mark,
When I use label_node=True (something I find very very handy for debugging my mistake when I make up a circuit), I find the rendering of some of the wires in this example are not there.

cct2 = Circuit(""" V1 1 6 8; down R1 1 7 3; right=2 R2 7 3 1; right R3 6 0 5; right R7 3 0_0 5; down R4 1 4 4;up V2 4 5 6; right=4, i=I_a R5 5 3; down W 0 0_0; right=2 I1 7 0 2; down """) cct2.draw(label_ids=True, draw_nodes='connections', label_nodes=True)
Here is what I get on my screen.
lcapy_render_problem

Thanks for working on this package. I find it very nice for making Circuits exams.

Rob

Unable to put equality into standard form

Here's my code

cct_before = Circuit("""
C 1 0; down
W 1 1_1; right
W 0 0_1; right
R4 1_1 0_1; down
L 1_1 2; right
W 0_1 0_2; right
R5 2 0_2; down
W 2 2_1; right
W 0_2 0_3; right
Is 2_1 0_3; down

;draw_nodes=connections, cpt_size=1
""")

cct_after = Circuit("""
V1 1 0 dc Vs; down
R1 1 2; right
W 0 0_1; right
R2 2 0_1; down
W 2 2_1; right
W 0_1 0_2; right
R3 2_1 0_2; down
W 2_1 2_2; right
W 0_2 0_3; right
C 2_2 0_3; down

;draw_nodes=connections, cpt_size=1
""")
cct_before.draw()
cct_after.draw()


t1 = expr('t1', positive=True)
cct = cct_after.initialize(cct_before, t1)


n = NodalAnalysis(cct)
result = n.nodal_equations()
exp = result[2]
sympy.pprint(exp.standard()) # fails

Stack trace:

~/anaconda3/envs/school/lib/python3.9/site-packages/lcapy/expr.py in standard(self)
   2146         if self._ratfun is None:
   2147             return self.copy()
-> 2148         return self.__class__(self._ratfun.standard(), **self.assumptions)
   2149 
   2150     def mixedfrac(self):

~/anaconda3/envs/school/lib/python3.9/site-packages/lcapy/ratfun.py in standard(self, split)
    582 
    583         try:
--> 584             Q, M, D, delay, undef = self.as_QMD()
    585         except ValueError:
    586             if not split:

~/anaconda3/envs/school/lib/python3.9/site-packages/lcapy/ratfun.py in as_QMD(self)
    695         expression = (Q + M / D) * exp(-delay * var) * undef"""
    696 
--> 697         N, D, delay, undef = self.as_ratfun_delay_undef()
    698 
    699         # Perform polynomial long division so expr = Q + M / D

~/anaconda3/envs/school/lib/python3.9/site-packages/lcapy/ratfun.py in as_ratfun_delay_undef(self)
    319         Note, delay only represents a delay when var is s."""
    320 
--> 321         return as_ratfun_delay_undef(self.expr, self.var)
    322 
    323     def as_const_undef_rest(self):

~/anaconda3/envs/school/lib/python3.9/site-packages/lcapy/ratfun.py in as_ratfun_delay_undef(expr, var)
    264     undef = sym.S.One
    265 
--> 266     if expr.is_rational_function(var):
    267         N, D = as_numer_denom(expr, var)
    268         return N, D, delay, undef

AttributeError: 'Equality' object has no attribute 'is_rational_function'

.Thevenin and Norton Circuits of Circuits with Dependent Sources?

I'm wondering if I have a misunderstanding about entering current dependent voltage sources, and other dependent sources. The problem is with Thevenin/Norton circuits. I made an example which I expected to be equivalent to four Ohms.
cct1 = Circuit(''' H1 1 0 H1 -4; down=1.5, l=4i, i=i ''') cct1.draw(label_nodes=True) cct1.norton(1, 0) cct1.thevenin(1, 0)
I get an error.


ValueError Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in _branch_index(self, cpt_name)
74 try:
---> 75 index = self.unknown_branch_currents.index(cpt_name)
76 return index

ValueError: '0' is not in list

During handling of the above exception, another exception occurred:

ValueError Traceback (most recent call last)
in
3 ''')
4 cct1.draw(label_nodes=True)
----> 5 cct1.norton(1, 0)
6 #cct1.thevenin(1, 0)

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/netlist.py in norton(self, Np, Nm)
617 Np, Nm = self._parse_node_args(Np, Nm)
618 Isc = self.Isc(Np, Nm)
--> 619 Ysc = self.admittance(Np, Nm)
620
621 # Convert to time-domain to handle arbitrary sources. Either

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/netlist.py in admittance(self, Np, Nm)
640 # measure current.
641 new.add('Vin %s %s {DiracDelta(t)}' % (Np, Nm))
--> 642 If = new.Vin_.I
643 new.remove('Vin_')
644

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mnacpts.py in I(self)
269 for sources."""
270
--> 271 return self.cct.get_I(self.name)
272
273 @Property

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/netlist.py in get_I(self, name)
1375 result = Current()
1376 for sub in self.sub.values():
-> 1377 I = sub.get_I(name)
1378 result.add(I)
1379 result = result.canonical()

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/netlist.py in get_I(self, name)
1475 """Current through component"""
1476
-> 1477 self._solve()
1478 return self._Idict[name].canonical()
1479

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in _solve(self)
132 if hasattr(self, '_Vdict'):
133 return
--> 134 self._analyse()
135
136 if '0' not in self.node_map:

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in _analyse(self)
119 # Iterate over circuit elements and fill in matrices.
120 for elt in self.elements.values():
--> 121 elt.stamp(self)
122
123 # Augment the admittance matrix to form A matrix.

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mnacpts.py in stamp(self, cct)
789 cct._C[m, n2] -= 1
790
--> 791 mc = cct._branch_index(self.args[0])
792 G = cExpr(self.args[1]).expr
793 cct._D[m, mc] -= G

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in _branch_index(self, cpt_name)
76 return index
77 except ValueError:
---> 78 raise ValueError('Unknown component name %s for branch current' % cpt_name)
79
80 def _analyse(self):

ValueError: Unknown component name 0 for branch current

Did I do this right? It was a test case for the following circuit, because this case didn't give me a believable answer. I get 2.222 Ohms myself, but it comes out with $Z_TH =5$.
cct5 = Circuit(""" P1 1 0; down=3 W 1 1_0; right=1.5 W 0 0_0; right=1.5 E1 1_0 2 2 0 3; down, l=3 v_{R1} R1 2 0_0 5; down=1.5, v=v_{R1} R2 2 3 2; right=1.5 W 0_0 0_1; right 1.5 G1 3 0_1 2 0 2; down=1.5, l=2 v_{R1} """) cct5.draw(label_nodes=True, draw_nodes='connections') cct5.norton(1, 0) cct5.thevenin(1,0)

Does lcapy handle Thevenin and Norton circuits with dependent sources? Or maybe I didn't enter them correctly.
Thanks,
Rob

Ground symbol?

This is more of cosmetic question than a functional one.

I'm trying to model a voltage divider that looks like this:

I can't seem to find an immediate way to draw the ground symbol with lcapy.

I'm aware of the Voltage divider in the intro to schematics here:http://lcapy.elec.canterbury.ac.nz/schematics.html#introduction but I'm curious if this other cosmetic variety is possible.

Here is an example in circuitikz of what I'm trying to do as well:

            \begin{circuitikz}
                \draw (0,0)
                to[short] (2,0)
                to[R=$R_1$] (2, -2)
                to[R=$R_2$] (2,-4)
                to[short] node[ground] {} (2, -4);
                \draw (2,-2)
                to[short] (4, -2)
                to[R=$R_{load}$] (4, -4)
                to[short] node[ground] {} (4, -4);
            \end{circuitikz}

Little issues when running examples

Hello,

I am considering using lcapy for my course at University of Liège, Belgium. Lcapy looks very nice.
So I started browsing and running a few experiments. Many things work (e.g plotting networks, some impedance magnitude plots, etc.), but I have also little issues:

I am using commit 785e12e. I run it on a mac in a virtual environment based on python 3.6.6, with the following installed packages: requirements.txt

E.g. when I run

$ python demo/oneport/demo1.py 
Traceback (most recent call last):
  File "demo/oneport/demo1.py", line 11, in <module>
    ax.plot(t, a.V.impulse_response(t), linewidth=2)
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/oneport.py", line 117, in V
    return self.Voc()
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/oneport.py", line 519, in Voc
    return self.cct.Voc(1, 0)
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/netlist.py", line 410, in Voc
    return self.get_Vd(Np, Nm)
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/netlist.py", line 1171, in get_Vd
    Vd = sub.get_Vd(Np, Nm)
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/netlist.py", line 1211, in get_Vd
    self._solve()
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/mna.py", line 147, in _solve
    self._analyse()
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/mna.py", line 122, in _analyse
    num_nodes = len(self.node_list) - 1
  File "/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/lcapy/mna.py", line 74, in node_list
    node_list.insert(0, node_list.pop(node_list.index('0')))
ValueError: '0' is not in list

Also I have

$ python demo/oneport/series-RLC-frequency1.py 
/Users/bcr/Documents/ws/scripts_ELEC0053/cenv/lib/python3.6/site-packages/matplotlib/ticker.py:2241: UserWarning: Data has no positive values, and therefore cannot be log-scaled.
  "Data has no positive values, and therefore cannot be "

nothing shows up on the plot.

And

python demo/oneport/series-RLC.py 

runs but the plot is flat (current = 0 for all time steps.)

Can you maybe give a hint? Is my configuration not supported?

Thanks,
All the best,
Bertrand.

Rendering schematic in not showing in notebook

I was in the past able to display the schematics fine in the notebook but recently I just get broken image link images. I am on mint with a full tex install, jupyter version 4.4.0, lcapy 0.28.0

Arguments of draw() method not working as expected

hi. according to http://lcapy.elec.canterbury.ac.nz/modules.html#lcapy.netlist.NetlistMixin.draw
we should see some effects on the graphics with the following jupyter code:

`%matplotlib inline
from lcapy import R, C, Par
#http://lcapy.elec.canterbury.ac.nz/modules.html#lcapy.netlist.NetlistMixin.draw
#n = C('C1') | (R('R1') + (C('C2') | (R('R2') + (C('C3') | (R('R3') + C('C4'))))))
n = R(1e3)+Par(R(1e3),R(10e3),R(.22e3))

#n.draw()
n.draw(form='horizontal',label_ids=True,label_nodes=False)

seems no difference between horizontal, vertical, ladder? how get both terminals on left side?

#n.draw(form='vertical')
#n.draw(form='ladder')

Possible to only label the "nets" instead of all terminals ? 'pins' argument ?

n.draw(form='horizontal',label_ids=True,label_nodes=True)

n.draw(form='horizontal',label_ids=True,label_nodes='pins')`

Should not "vertical" show up different than "horizontal"?
And should not the "pins" annotate the "nets"?

Find attached a screenshot.
lcapy_question

thanks and all the best to the antipode :)

Not lowcase filenames on Windows problem

Hi,

first I want to thank you for this amazing package.

Trying to use it on Windows I noted that there are two example files (may be erroneously committed) which names differ only in case:

lcapy/doc/examples/networks/series-VRC1-Isc.py
lcapy/doc/examples/networks/series-VRC1-isc.py

Unfortunately, it looks like git-on-windows can not cope with this properly.
And after git clone ... i get immediately:

e:\Users\xyz\workplace\git\lcapy (master -> origin)
λ git status                                                               
On branch master                                                           
Your branch is up to date with 'origin/master'.                            
                                                                           
Changes not staged for commit:                                             
  (use "git add <file>..." to update what will be committed)               
  (use "git checkout -- <file>..." to discard changes in working directory)
                                                                           
        modified:   doc/examples/networks/series-VRC1-Isc.py               
                                                                           
no changes added to commit (use "git add" and/or "git commit -a")          

Do you have any plan to release/update this package on PyPi as well ?

Errors with sympy 1.7

With sympy 1.7, a lot of the tests fail with errors like this:

Traceback (most recent call last):
  File "/home/runner/work/lcapy/lcapy/lcapy/tests/test_twoport.py", line 335, in test_transforms
    self.assertEqual(A.Gparams.Aparams.simplify(), A, "A.Gparams.Aparams")
  File "/home/runner/work/lcapy/lcapy/lcapy/twoport.py", line 491, in Gparams
    return GMatrix(self.Hparams.inv())
  File "/home/runner/work/lcapy/lcapy/lcapy/matrix.py", line 86, in inv
    Minv = matrix_inverse(sym.Matrix(self), method=method)
  File "/home/runner/work/lcapy/lcapy/lcapy/matrix.py", line 188, in matrix_inverse
    return dM.inv(method=method[3:]).to_Matrix()
TypeError: inv() got an unexpected keyword argument 'method'

No module named 'sympy.physics.units.systems.si'

Hi, I just learned about lcapy from the post at https://granasat.ugr.es/2020/02/python-jupyter-electrical-circuit-diagram-generation-lcapy/, but the installation instructions don’t work for me. Perhaps sympy has changed. What (older) version of sympy does one need? I couldn’t find any info on this in the documentation, and there doesn’t seem to be a requirements.txt file.

!pip install lcapy 
from lcapy import Circuit
Requirement already satisfied: sympy in /usr/local/lib/python3.6/dist-packages (1.1.1)
Requirement already satisfied: lcapy in /usr/local/lib/python3.6/dist-packages (0.77)
Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy) (1.1.0)
Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from lcapy) (1.19.5)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from lcapy) (3.2.2)
Requirement already satisfied: wheel in /usr/local/lib/python3.6/dist-packages (from lcapy) (0.36.2)
Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from lcapy) (1.4.1)
Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from lcapy) (53.0.0)
Requirement already satisfied: IPython in /usr/local/lib/python3.6/dist-packages (from lcapy) (5.5.0)
Requirement already satisfied: networkx in /usr/local/lib/python3.6/dist-packages (from lcapy) (2.5)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->lcapy) (2.8.1)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->lcapy) (0.10.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->lcapy) (2.4.7)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->lcapy) (1.3.1)
Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from IPython->lcapy) (4.4.2)
Requirement already satisfied: pygments in /usr/local/lib/python3.6/dist-packages (from IPython->lcapy) (2.6.1)
Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.6/dist-packages (from IPython->lcapy) (1.0.18)
Requirement already satisfied: pexpect; sys_platform != "win32" in /usr/local/lib/python3.6/dist-packages (from IPython->lcapy) (4.8.0)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.6/dist-packages (from IPython->lcapy) (0.7.5)
Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.6/dist-packages (from IPython->lcapy) (0.8.1)
Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.6/dist-packages (from IPython->lcapy) (4.3.3)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.1->matplotlib->lcapy) (1.15.0)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.6/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->IPython->lcapy) (0.2.5)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.6/dist-packages (from pexpect; sys_platform != "win32"->IPython->lcapy) (0.7.0)
Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets>=4.2->IPython->lcapy) (0.2.0)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-17-3ab9595a4556> in <module>()
      1 # trying circuit-drawing for a second...
      2 get_ipython().system('pip install sympy lcapy')
----> 3 from lcapy import Circuit
      4 
      5 cct = Circuit()

3 frames
/usr/local/lib/python3.6/dist-packages/lcapy/units.py in <module>()
      8 
      9 import sympy.physics.units as u
---> 10 from sympy.physics.units.systems.si import dimsys_SI
     11 from sympy.physics.units.systems import SI
     12 from sympy.physics.units import UnitSystem

ModuleNotFoundError: No module named 'sympy.physics.units.systems.si'

Examples fail to run

Okay, now I get up to:

$ python3 ./tutorials/RCnoise/RCparallel1noise.py                  
Traceback (most recent call last):
  File "./tutorials/RCnoise/RCparallel1noise.py", line 17, in <module>
    (Vn * 1e9).plot(vf, plot_type='mag', ylabel='ASD (nV/rootHz)')
  File "/Users/matthew/Code/Uni/lcapy/lcapy/noisefexpr.py", line 72, in plot
    return plot_frequency(self, fvector, **kwargs)
  File "/Users/matthew/Code/Uni/lcapy/lcapy/plot.py", line 199, in plot_frequency
    plot(f * xscale, V * yscale, **kwargs)
  File "/Users/matthew/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/axes/_axes.py", line 1743, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "/Users/matthew/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 273, in __call__
    yield from self._plot_args(this, kwargs)
  File "/Users/matthew/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 419, in _plot_args
    for j in range(max(ncx, ncy))]
  File "/Users/matthew/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 419, in <listcomp>
    for j in range(max(ncx, ncy))]
  File "/Users/matthew/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 312, in _makeline
    seg = mlines.Line2D(x, y, **kw)
  File "/Users/matthew/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/lines.py", line 390, in __init__
    self.update(kwargs)
  File "/Users/matthew/.pyenv/versions/3.7.3/lib/python3.7/site-packages/matplotlib/artist.py", line 996, in update
    raise AttributeError(f"{type(self).__name__!r} object "
AttributeError: 'Line2D' object has no property 'plot_type'

Permission Error

Hi
I want to execute this simple example but I couldn't do it

code:

from lcapy import R, C, L
cct2= (R(1e6) + L(2e-3)) | C(3e-6)
cct2.draw()

and I get this error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'D:\OneDrive - King Fahd University of Petroleum & Minerals (KFUPM)\Electric Python\tmppg8rlavz.log'

image
All the best, Alshehri.

.dc().equations() not behaving....

I was looking at the .equations() option, and was following the example here. See below:

`from lcapy import Circuit

a = Circuit("""
... V1 1 0 {10 + v(t)}; down
... R1 1 2; right
... L1 2 3; right=1.5, i={i_L}
... R2 3 0_3; down=1.5, i={i_{R2}}, v={v_{R2}}
... W 0 0_3; right
... W 3 3_a; right
... C1 3_a 0_4; down, i={i_C}, v={v_C}
... W 0_3 0_4; right""")
a.draw(label_nodes=True)
a.dc()
a.dc().equations()`

The result I get is:


NameError Traceback (most recent call last)
in
12 a.draw(label_nodes=True)
13 a.dc()
---> 14 a.dc().equations()

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in equations(self, inverse)
257 evaluate=False))
258
--> 259 return expr(sym.Eq(self.X, sym.MatMul(sym.Pow(self._A, -1), self._Z),
260 evaluate=False))

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in X(self)
226 self._analyse()
227
--> 228 V = [self.Vname('Vn%s' % node) for node in self.node_list[1:]]
229 I = [self.Iname('I%s' % branch) for branch in self.unknown_branch_currents]
230 return Vector(V + I)

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in (.0)
226 self._analyse()
227
--> 228 V = [self.Vname('Vn%s' % node) for node in self.node_list[1:]]
229 I = [self.Iname('I%s' % branch) for branch in self.unknown_branch_currents]
230 return Vector(V + I)

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/netlist.py in Vname(self, name)
1228
1229 def Vname(self, name):
-> 1230 return Vname(name, self.kind)
1231
1232 def Iname(self, name):

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/voltage.py in Vname(name, kind, cache)
104 elif kind == 't':
105 return Vt(name + '(t)')
--> 106 elif kind in (omegasym, omega, 'ac'):
107 return Vphasor(name + '(omega)')
108 # Not caching is a hack to avoid conflicts of Vn1 with Vn1(s) etc.

NameError: name 'omegasym' is not defined

NameError Traceback (most recent call last)
in
----> 1 a.dc().equations()

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in equations(self, inverse)
257 evaluate=False))
258
--> 259 return expr(sym.Eq(self.X, sym.MatMul(sym.Pow(self._A, -1), self._Z),
260 evaluate=False))

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in X(self)
226 self._analyse()
227
--> 228 V = [self.Vname('Vn%s' % node) for node in self.node_list[1:]]
229 I = [self.Iname('I%s' % branch) for branch in self.unknown_branch_currents]
230 return Vector(V + I)

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/mna.py in (.0)
226 self._analyse()
227
--> 228 V = [self.Vname('Vn%s' % node) for node in self.node_list[1:]]
229 I = [self.Iname('I%s' % branch) for branch in self.unknown_branch_currents]
230 return Vector(V + I)

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/netlist.py in Vname(self, name)
1228
1229 def Vname(self, name):
-> 1230 return Vname(name, self.kind)
1231
1232 def Iname(self, name):

~/anaconda3/lib/python3.7/site-packages/lcapy-0.38.2-py3.7.egg/lcapy/voltage.py in Vname(name, kind, cache)
104 elif kind == 't':
105 return Vt(name + '(t)')
--> 106 elif kind in (omegasym, omega, 'ac'):
107 return Vphasor(name + '(omega)')
108 # Not caching is a hack to avoid conflicts of Vn1 with Vn1(s) etc.

NameError: name 'omegasym' is not defined

Any suggestions?

Thanks,

Rob

sExpr in lcapy: cannot be used with sympy solvers?

I am trying the lcapy package with sympy solvers and encountered the following errors,

In [27]: from lcapy import s
In [28]: from sympy import simplify, collect, solve

In [29]: simplify(s+2*s+1)
Out[29]: 3⋅s + 1

In [30]: collect(s+2*s+1,s)
Out[30]: 3⋅s + 1

In [31]: solve(s+2*s+1,s)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-266b3ed08da2> in <module>
----> 1 solve(s+2*s+1,s)

...\site-packages\sympy\solvers\solvers.py in solve(f, *symbols, **flags)
    968             continue  # neither re(x) nor im(x) will appear
    969         # if re(s) or im(s) appear, the auxiliary equation must be present
--> 970         if any(fi.has(re(s), im(s)) for fi in f):
    971             irf.append((s, re(s) + S.ImaginaryUnit*im(s)))
    972     if irf:

...\site-packages\sympy\solvers\solvers.py in <genexpr>(.0)
    968             continue  # neither re(x) nor im(x) will appear
    969         # if re(s) or im(s) appear, the auxiliary equation must be present
--> 970         if any(fi.has(re(s), im(s)) for fi in f):
    971             irf.append((s, re(s) + S.ImaginaryUnit*im(s)))
    972     if irf:

TypeError: has() takes 2 positional arguments but 3 were given

It seems that lcapy.sExpr e.g. 's' can work with sympy.simplify() and sympy.collect(), but it failed with sympy.solve(). Could it be used in this way or there is an alternative way? Thanks.

Kind regards,
Xin

ReadIn PySpice Schematics

I am wanting to try using lcapy to read back a netlist from either skidl (https://github.com/xesscorp/skidl/blob/master/examples/spice-sim-intro/spice-sim-intro.ipynb) or PySpice (https://pyspice.fabrice-salvaire.fr/examples/filter/rlc-filter.html) into a Schematic. I tried with the above PySpice RLC filter but with no luck. My self and Skidl's author have been looking for a means to translate the netlist level stuff we have been doing in python to schematics that don't generate a rats nest. We have been looking at SchemeDraw. However, after looking at your lib at first glance, it may be able to do what we have been looking for. If you can give some of the examples from Skidl and PySpice a try that would be greatly appreciated

.draw() from circuit created from network doesn't respect style= argument

The style argument works as expected in a circuit .draw() command, and generates a diagram:

from lcapy import Circuit

cct = Circuit()
cct.add("""
W _0 _1; right
W _1 _2; up,size=0.4
R _2 _3 1e6; right
L _3 _4 2e-3;right
W _4 _5; down,size=0.4
W _5 _6; right
W _5 _7; down,size=0.4
C _7 _8 3e-6; left
W _8 _1; up,size=0.4
""")

cct.draw(style='british')

returns a diagram as expected.

But if I try to use the argument when drawing a circuit created from a network, I get an error:

from lcapy import R, C, L

cct2= (R(1e6) + L(2e-3)) | C(3e-6)
cct2.draw(style='british')

I get an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-60-2d64bad9a6dc> in <module>()
      3 
      4 cct2= (R(1e6) + L(2e-3)) | C(3e-6)
----> 5 cct2.draw(style='british')

TypeError: draw() got an unexpected keyword argument 'style'

lcapy draw function not working

I have been trying to execute the following code (an example from http://lcapy.elec.canterbury.ac.nz/overview.html#schematics) using jupyter notebook:

%matplotlib inline
from lcapy import R, C, L
((R(1) + L(2)) | C(3)).draw()

I have manually installed the relevant LaTex packages such as circuitikz, pdflatex in a locally created latex folder. Once I execute this code, I end up getting the following error:

RuntimeError: (%s is not installed', 'pdflatex')

Can you tell why the draw function is not working?

VCCS?

Hi,

Would really appreciate if a VCCS could be added...

Thanks

Binding symbols in state space model does not work (or is not documented)

Is there an example of how to bind symbols in a state space model of a circuit?

cct = Circuit("""
C1 1 0; down=1.5
W 1 1_0; right=2.0
W 0 0_3; right
I1 1_0 0_3; down
R1 1_0 2 ; right=1.5
W 0_3 0_5; right
C2 2 0_5 ; down
R2 2 3 ; right=1.5
W 0_5 0_7; right=1.5
V 3 0_7 ; down
; label_nodes=alpha
""")

ss=cct.ss

se = ss.state_equations()

ss.A.free_symbols

e2 = ss.A.subs(C1, 50400.0).subs(R1, 13.65).subs(R2, 1.35).subs(C2, 5613300.0)

e2 <--- symbols still unbound

e2.evalf() <---- does not eval using symbol values.

Schematics showing very small in Jupyter notebook

Love this tool! When I create a schematic with basic operations, like (R1 + R2) | C1, in a jupy notebook, the schematic renders at a decent size. When i use a netlist passed to Circuit, I get a very tiny image in the notebook.

See attached PNG for minimal example.

Also, are you guys taking pull requests? I've run into the odd error that I could likely fix and submit, if you'll have them. (for instance: I was missing one of the conversion utilities, the error msg didn't indicate what was wrong, I could add code to detect this.)

jupy_lcapy_render_problem

Mirroring transistors does not work

Mirroring transistors on lcapy (0.63), python 3.8.0 causes them to swap the inputs but the symbol stays the same:

image

This is on a blank jupyter notebook with only that code and import lcapy on the top.

Examples fail to run

Currently, the docs fail to build because one (or more) of the examples doesn't run:

$ python3 doc/examples/netlists/tf1-pole-zero-plot.py 
Traceback (most recent call last):
  File "/Users/matthew/Code/Uni/lcapy/lcapy/plot.py", line 33, in plot_pole_zero
    p = np.array([complex(p.evalf()) for p in poles.keys()])
  File "/Users/matthew/Code/Uni/lcapy/lcapy/plot.py", line 33, in <listcomp>
    p = np.array([complex(p.evalf()) for p in poles.keys()])
TypeError: complex() first argument must be a string or a number, not 'cExpr'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "doc/examples/netlists/tf1-pole-zero-plot.py", line 5, in <module>
    H.plot()
  File "/Users/matthew/Code/Uni/lcapy/lcapy/sexpr.py", line 285, in plot
    return plot_pole_zero(self, **kwargs)
  File "/Users/matthew/Code/Uni/lcapy/lcapy/plot.py", line 36, in plot_pole_zero
    raise TypeError('Cannot plot poles and zeros of symbolic expression')
TypeError: Cannot plot poles and zeros of symbolic expression

Incorrect state space equations with current source input

Code:

from lcapy import Circuit,t

cct = Circuit("""
I1 1 0;
CBLK 1 0;
""")
ss=cct.ss

State space equations:

ss.state_equations()
Out[28]:
⎡d ⎤
⎢──(v_CBLK(t))⎥ = [0]⋅[v_CBLK(t)] + []⋅[]
⎣dt ⎦

ss.output_equations()
Out[29]:
[v₁(t)] = [1]⋅[v_CBLK(t)] + []⋅[]


I don't see Input vector to be current source here. Also ss.B vector is empty. Please help.

H(j omega).phase_degrees broken for me at least.

The examples using .phase_degrees seem broken for me. When I look at them before running them myself all is well, but after running them they are not correct. For example, RC-hpf1.ipynb looks like
phase_degrees. I'm using an up to date anaconda install on ubuntu 19.10 if that helps.

zp2tf() issue

Hello,

I am having trouble using the zp2tf() function.
It returns wih an error: AttributeError: 'int' object has no attribute 'is_Mul'

If I follow along in the tutorial with the following:

from lcapy import *
H2 = zp2tf([], [0, -0.05])

I get the following output:


AttributeError Traceback (most recent call last)
in ()
1 from lcapy import *
----> 2 H2 = zp2tf([], [0, -0.05])

/usr/lib/python3.5/site-packages/lcapy/core.py in zp2tf(zeros, poles, K, var)
1871 and from a constant gain"""
1872
-> 1873 return Hs(_zp2tf(zeros, poles, K, var))
1874
1875

/usr/lib/python3.5/site-packages/lcapy/core.py in _zp2tf(zeros, poles, K, var)
1864 pp = [1 / (var - p) ** poles[p] for p in poles]
1865
-> 1866 return uMul(K, *(zz + pp))
1867
1868

/usr/lib/python3.5/site-packages/sympy/core/mul.py in _unevaluated_Mul(*args)
70 while args:
71 a = args.pop()
---> 72 if a.is_Mul:
73 c, nc = a.args_cnc()
74 args.extend(c)

AttributeError: 'int' object has no attribute 'is_Mul'

This may just be caused by my setup but I had the same type error using Arch Linux with python 3.5 and on Ubuntu 16.04 using python 2.7.

I have been playing with the source code for a couple days to see if I could figure out the problem but have had no luck. I wish I could help with this but I am pretty inexperienced with python code.

Thank you for creating this project and all you hard work.

Eric

Difficulty Running Notebook Examples

Hi, I have just installed lcapy on my machine. The way I installed was slightly different from what is suggested in the docs because I use conda for python environment management. The main differences were that I created a new conda environment, installed sympy, numpy, ipython and matplotlib within it, then after activating that environment, I used pip install -e /path/to/lcapy/on/my/machine to install the lcapy as a package within my conda environment. So I did not run the setup.py and used the pip install instead.

This seemed to work perfectly fine. I was able to start importing lcapy within active ipython sessions. Then I tried running the python notebook examples and that's where the problem started. For example, when I run the RC-lpf1-buffer-loaded.ipynb, the first cell works fine to generate the drawing the circuit upon the cct.draw() command. But the next cell that performs H = cct.RL.V / cct.Vi.V is where the issue starts. Hitting that line, I get the error TypeError: Unsupported types for /: 'Vsuper' and 'Vsuper'.

What is the reason for this bug, and is it related to the way I have installed the package? I doubt it would be though, because the problem of the error appears to be that the / operator was not defined to divide Vsuper over Vsuper. Am I missing something here?

I'm starting on my very first analog signals and systems class within a couple of days and I really hope to get lcapy working on my machine to enrich my learning. Thank you so much for creating this library and I hope you can help me with this issue.

Invalid Latex code for state space equations ("Double Subscript Problem")

Lcapy v0.74 outputs invalid Latex code for state space equatiosn when components use subscripts.

Steps to reproduce

Take an example circuit, e.g.:

a = Circuit("""
Vstep 1 0 {v(t)};  down
R1 1 2; right
L 2 3; right=1.5, i={i_L}
R2 3 0_3; down=1.5, i={i_{R2}}, v={v_{R2}}
W 0 0_3; right
W 3 3_a; right
C 3_a 0_4; down, i={i_C}, v={v_C}
W 0_3 0_4; right""")
ss = a.ss
ss.state_equations()

Change the name of C to Coor C_o. Then print the state space equations. The result is then not displayed properly because the generated code is not valid Latex code ('double subscript' problem)

Screen Shot 2021-01-01 at 14 24 32

Replacing v_C_o with v_{C_o} fixes the Latex error. I have not found any indication in the documentation that this is actual expected behaviour so I think it is a bug. Also other components with subscripts use proper braces and only state variables are affected.

Versions

Python 3.7, lcapy v0.74

getting Heavisid() functions when calculating impedance

Hello,

When I follow along in the tutorial at on http://lcapy.elec.canterbury.ac.nz/tutorial.html
I am getting unexpected results. For example

from lcapy import *
N = R(5) | L(20) | C(10)
N
R(5) | L(20) | C(10)
N.Z

I get

⎛ Heaviside(0) 1⎞
s⋅⎜- ──────────── + ─⎟
⎝ 5 5⎠
──────────────────────
2 s 1
s + ── + ───
50 200

instead of

  20⋅s

────────────────
2
200⋅s + 4⋅s + 1

All the impedance calculations have the Heaviside() function in them.

I am not sure if it is because there is something wrong with my setup but I can provide more examples if needed if it will help in determining what is going wrong.

I am using:
Python version 3.5,2
IPython version 5.1.0
numpy version 1.11.2
sympy versions 1.0-1

Thank you for any help.

Eric

Trouble getting lcapy to work on openSUSE due to circuitikz

Hello,

I am trying to get lcapy working on an openSUSE 42.3 installation. I believe I have all the dependencies required but run into an error when running a simple file such as:

from lcapy import Circuit, s
cct = Circuit()
cct.add('V1 1 0 {u(t)}; down')
cct.add('R1 1 2 4; right=1.5')
cct.add('C1 2 3 0.1; down=1.5')
cct.add('W1 0 3; right')
cct.draw()

This returns:

RuntimeError: circuitikz is not installed

I know circuitikz is installed and can use it in a latex document.

Do you have any suggestions on how to get this working or can you help me in finding out how lcapy determines the status of circuitikz? I noticed that openSUSE and Ubuntu install their texlive sty files in different places and wonder if that could be the issue.

Thank you for any help.

Eric

Running via Binderhub

It would be useful if the repository was linked to Binderhub so that examples could be tried (and tested) interactively.

I think a minimal setup (though I haven't checked, may be:

apt.txt

texlive-xetex
asymptote

There was a tikz dependency, I think, that asymptote handles.

requirements.txt

sympy
matplotlib
git+https://github.com/mph-/lcapy.git

Please consider publish / update lcapy package on PyPi

I've had a crack at making things work for PyPi and have pushed to the test server. Would you mind trying https://test.pypi.org/project/lcapy/ ?

Well, it works as far as I can see. The functionality we use at the moment:

  • create a netlist and draw it
  • get an impedance of a network, apply subs, and evaluate in Laplace domain

Few things I would wish to see change is summarized in the attached patch of setup.py setup_py.zip:

  • usage of install_requires instead of requires to force pip to install missing packages
  • adding matplotlib to the list of required dependencies
  • usage of entry_points in preference to the scripts keyword to allow pip to create the appropriate form of executable for the target platform (for this to work, I think you should move schtex.py one directory level up in your source distribution)

The reason of the third point above is, that in this case pip creates an executable shim file that is put into the "bin" directory (.virtualenv/<myenv>/bin/schtex on Linux, <PythonRoot>/Scripts/schtex.exe on Windows ) and put schtex.py into site-packages directory so when schetex will be run in a console schetex.py will be correctly found and imported by Python.

Cannot assign nodes which are not even added to the circuit.

Hi,
I am getting the following error:

This error is showing up and it's listing nodes I have not added to my circuit.
Screenshot 2021-02-03 212752

Here is a list of which nodes I have added:
Screenshot 2021-02-03 212812

I don't really know if this is just a simple bug of if I am using the library incorrectly.

Thanks in advance

Op-Amps Unsupported?

None of the op-amp examples work with the newest version of lcapy since the Opamp class is no longer exposed for imports. Is op-amp analysis supported for simple op-amp networks?

Not looking for anything too fancy. I keep getting "MNA A matrix not invertible" errors when attempting to analyze voltage gain across simple op-amp configurations.

Another issue. How to pass parameters and in the same time specify initial conditions.

Another issue. How to pass parameters and in the same time specify initial conditions.
For example with the syntax below the simulation is erroneous.

from lcapy import Circuit
import numpy as np
import matplotlib.pyplot as plt

##cct = Circuit('''
##... Vin 1 0 {sin(130e6*2*3.14159*t)}
##... Rin 1 2 50
##... Cs  2 4 2.34e-12 0
##... La  2 3 0.32e-6 0
##... Rs  3 4 0.532
##... Rl  4 0 50''')

cct = Circuit('''
... Vin 1 0 {sin(130e6*2*3.14159*t)}
... Rin 1 2
... Cs  2 4 0
... La  2 3 0
... Rs  3 4
... Rl  4 0''')

cct1 = cct.subs({'Rin': 50, 'Cs':2.34e-12, 'La': 0.32e-6, 'Rs': 0.532, 'Rl': 50})
##H = cct.transfer(1,0,4,0)
##print(H)

t = np.linspace(0, 2e-7, 1000)
Vinp = cct1.Vin.v.evaluate(t)
Vout = cct1.Rl.v.evaluate(t)

plt.plot(t, Vinp, 'g', linewidth=2)
plt.plot(t, Vout, 'r', linewidth=2)
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.show()

Originally posted by @SanchoPansa47 in https://github.com/mph-/lcapy/issues/35#issuecomment-721104952

Can't run simple example

Hello there,
I'm sorry to bother, but I'm afraid that I'm not the only one who would face this problem.
I have little experience with programming but really liked this project, so I installed but can't run the simple example present in the documentation.

When I run this on a Jupyter Notebook (Python 3.5):

from lcapy import *
from numpy import logspace
from matplotlib.pyplot import savefig, show

N = R(10) + C(1e-4) + L(1e-3)

vf = logspace(0, 5, 400)
Z = N.Z.frequency_response().magnitude.plot(vf,0)

show()

I get

NameError Traceback (most recent call last)
in ()
6
7 vf = logspace(0, 5, 400)
----> 8 Z = N.Z.frequency_response().magnitude.plot(vf,0)
9
10 show()

C:\Anaconda3\lib\site-packages\lcapy\core.py in frequency_response(self, fvector)
1355 """
1356
-> 1357 X = self(j * 2 * pi * f)
1358
1359 if fvector is None:

C:\Anaconda3\lib\site-packages\lcapy\core.py in call(self, arg)
850 return np.array([self._subs1(self.var, arg1) for arg1 in arg])
851
--> 852 return self._subs1(self.var, arg)
853
854 def subs(self, _args, *_kwargs):

C:\Anaconda3\lib\site-packages\lcapy\core.py in _subs1(self, old, new, **kwargs)
834 old = context.symbols[name]
835
--> 836 return cls(self.expr.subs(old, expr))
837
838 def call(self, arg):

C:\Anaconda3\lib\site-packages\lcapy\core.py in init(self, val)
2131 def init(self, val):
2132
-> 2133 super(Zf, self).init(val, **assumptions)
2134 self._fourier_conjugate_class = Zt
2135

NameError: name 'assumptions' is not defined

I also tried to plot

from lcapy import *
from numpy import linspace
from matplotlib.pyplot import savefig, show

N = Vdc(20) + R(10) + C(1e-4)

tv = linspace(0, 0.01, 1000)
N.Isc.transient_response().plot(tv)

show()

but ran into the problems:

TypeError Traceback (most recent call last)
C:\Anaconda3\lib\site-packages\lcapy\core.py in evaluate(self, arg)
756 try:
--> 757 result = func(v1)
758 response = complex(result)

C:\Anaconda3\lib\site-packages\numpy__init__.py in (_Dummy_99)

C:\Anaconda3\lib\site-packages\sympy\core\relational.py in nonzero(self)
194 def nonzero(self):
--> 195 raise TypeError("cannot determine truth value of Relational")
196

TypeError: cannot determine truth value of Relational

During handling of the above exception, another exception occurred:

RuntimeError Traceback (most recent call last)
in ()
6
7 tv = linspace(0, 0.01, 1000)
----> 8 N.Isc.transient_response().plot(tv)
9
10 show()

C:\Anaconda3\lib\site-packages\lcapy\core.py in plot(self, t, *_kwargs)
1619
1620 from lcapy.plot import plot_time
-> 1621 plot_time(self, t, *_kwargs)
1622
1623 def canonical(self):

C:\Anaconda3\lib\site-packages\lcapy\plot.py in plot_time(obj, t, **kwargs)
146 t = np.linspace(t[0], t[1], 400)
147
--> 148 v = obj.evaluate(t)
149
150 ax = kwargs.pop('axes', None)

C:\Anaconda3\lib\site-packages\lcapy\core.py in evaluate(self, arg)
763 raise RuntimeError(
764 'Cannot evaluate expression %s,'
--> 765 ' due to undetermined conditional result' % self)
766
767 raise RuntimeError(

RuntimeError: Cannot evaluate expression Piecewise((-exp(-1000*t)/(Heaviside(0) - 1), t >= 0)), due to undetermined conditional result

In [ ]:

​sorry for wasting your time, I just want to help and be helped.
Thanks in advance,
Best regards, Murilo Moreira.

State space Output equations for current source input to series RLC

Hi,

For a current source input to series RLC, The current of inductor is determined by input itself and don't know if we can fit the equations of this circuit into state space model . Reports error as below for this.

cct = Circuit("""
I_in 0 1;
R_L 1 2;
L_L 2 3;
C_L 3 0;
""")
ss=cct.ss

ValueError: The MNA A matrix is not invertible for time analysis because:

  1. there may be capacitors in series;
  2. a voltage source might be short-circuited;
  3. a current source might be open-circuited;
  4. a dc current source is connected to a capacitor (use step current source).
  5. part of the circuit is not referenced to ground

V_CL will be a state variable. And the output equations will be as below for this.
V3 = V_CL
V2 = V_CL + L_L * d(I_in)/dt
V1 = V_CL + L_L * d(I_in)/dt + R_L * I_in

Is there a way to print the output equations for this case? Please help. Thanks.

Can't apply initial conditions in circuit simulation

Hello,

Here is a circuit that fails to simulate:

from lcapy import Circuit
import numpy as np
import matplotlib.pyplot as plt

cct = Circuit('''
... Vin 1 0 {sin(130e6*2*3.14159*t)}
... Rin 1 2 50
... Cs  2 4 2.34e-12 0
... La  2 3 0.32e-6 0
... Rs  3 4 0.532
... Rl  4 0 50''')

##cct1 = cct.subs({'Rin': 50, 'Cs':2.34e-12, 'La': 0.32e-6, 'Rs': 0.532, 'Rl': 50})
##H = cct.transfer(1,0,4,0)
##print(H)

t = np.linspace(0, 2e-7, 1000)
Vinp = cct.Vin.v.evaluate(t)
Vout = cct.Rl.v.evaluate(t)

plt.plot(t, Vinp, 'g', linewidth=2)
plt.plot(t, Vout, 'r', linewidth=2)
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.show()

Calculate response to sin function

When running the following circuit

from lcapy import Circuit, s, t, f, R, L, C
cct = Circuit()
cct.add('V1 1 0 {3*sin(t)}; down')
cct.add('R1 1 2 1; right=1.5')
cct.add('L1 2 3 0.25; down=1.5')
cct.add('W1 0 3; right')
cct.draw()
ax = cct.R1.i.plot() # current
ax = cct.R1.v.plot() # voltage     

the plots show a zero current and voltage. I would expect a sine function (with certain amplitude and phase). When replacing 3*sin(t) with 3*u(t) the result is as expected.

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.