mph- / lcapy

Lcapy is a Python package for symbolic linear circuit analysis and signal processing. It uses SymPy for symbolic mathematics.
GNU Lesser General Public License v2.1
240 stars 46 forks source link

The state/output equations are being printed out of the normal order #72

Open joaoantoniocardoso opened 2 years ago

joaoantoniocardoso commented 2 years ago

Hi! Sorry bothering again, this one I would say that is a very low priority one - the state_equations() / output_equations() are printing in a non common fashion:

Expected:

dx(t)/dt = A*x(t) + B*u(t)
y(t) = C*x(t) + D*u(t)

Getting:

dx(t)/dt = B*u(t) + A*x(t)
y(t) = D*u(t) + C*x(t)

Example:

image

mph- commented 2 years ago

I'm afraid this is a side-effect of how SymPy stores and prints expressions. It has bothered me as well but I have been unable to come up with a workaround.

For example,

 from sympy import symbols
 x, u = symbols('x u')
 x + u

prints as u + x since SymPy uses lexicographical ordering.

joaoantoniocardoso commented 2 years ago

Yeah, I see. I did a quick search and I couldn't find anything that really helps.

For the moment I'm not relying on the sympy equation to print it, but crafting a latex string, I don't really understand the limitations of the custom printers, but maybe we could do something like this in our custom printer?


def display_lcapy_ss(ss: lca.StateSpace):
    eq_states = sym.latex(ss.dotx.expr.expand())
    eq_states += " &= " + sym.latex(ss.A.expr.expand())
    eq_states += " \, " + sym.latex(ss.x.expr.expand())
    eq_states += " + " + sym.latex(ss.B.expr.expand())
    eq_states += " \, " + sym.latex(ss.u.expr.expand())

    eq_outputs = sym.latex(ss.y.expr.expand())
    eq_outputs += " &= " + sym.latex(ss.C.expr.expand())
    eq_outputs += " \, " + sym.latex(ss.x.expr.expand())
    eq_outputs += " + " + sym.latex(ss.D.expr.expand())
    eq_outputs += " \, " + sym.latex(ss.u.expr.expand())

    latex = r"\begin{aligned}" + eq_states + r" \\ " + eq_outputs + r"\end{aligned}"

    display(Math(latex))

The output:

image

Thanks

mph- commented 2 years ago

It might be better to have StateSpaceSystemEquation and StateSpaceOutputEquation classes. These could have their own printers that would do the right thing.

Note, all Lcapy objects have .latex() and .pretty() methods so you do not need to use sym.latex