[Python] Rearranging Expression to a Standard Form for Transfer Function

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I'm a newcomer to Python/Sympy and I'm hoping it can make life easier understanding control system topics. A common requirement for me is to cross-check equations developed in the literature against my own derivations. When it comes to transfer functions, the denominator is typically ordered with the higher orders of s on the left, with order decreasing moving to the right. The highest order s term has a unity coefficient.

    Here's an example (taken from here):

    [​IMG]

    I've developed my own transfer function using sympy and I'd like to rearrange it in the fashion just described.

    import sympy as sp
    from sympy import simplify
    from IPython.display import display

    s, tau_1, tau_2 = sp.symbols('s,tau_1,tau_2')
    F = (1+s*tau_2)/(1+s*(tau_1+tau_2));

    k_0, k_d, N = sp.symbols('k_0,k_d,N')
    H = (k_0*k_d*F)/(s+((k_0*k_d*F/N)))

    display(H.simplify())


    Which yields:

    [​IMG]

    Now, I'm not really expecting simplify to know which format I'd like the expression displayed, but I'm hoping there's an existing function or set of functions that will help me to arrange it the way I'd like. Is there?

    FURTHER UPDATE:

    After a bit of manipulation, I've managed to isolate the highest power and divide across by the coefficient top & bottom to leave the highest order term without a coefficient, as I wanted. It's not perfect by any stretch. An improvement would be to have each term stand alone and ordered highest to lowest as with most polynomial presentations. I notice that collect() doesn't order the power terms as you'd expect. What's that all about!?

    import sympy as sp
    from sympy import simplify
    from sympy import poly
    from sympy import degree
    from IPython.display import display

    s, tau_1, tau_2 = sp.symbols('s,tau_1,tau_2')
    F = (1+s*tau_2)/(1+s*(tau_1+tau_2));
    display(F)

    k_0, k_d, N = sp.symbols('k_0,k_d,N')
    H = (k_0*k_d*F)/(s+((k_0*k_d*F/N)))
    display(H)

    def normTF(expr):
    H_c = expr.ratsimp().collect(s)
    n,d=sp.fraction(H_c)
    collected = sp.Poly(d, s).as_expr()
    degree = sp.degree(collected, gen=s)
    terms = dict(i.as_independent(s)[::-1] for i in sp.Add.make_args(collected))
    sn=(n/terms[s**degree]).ratsimp().collect(s)
    sd=(d/terms[s**degree]).ratsimp().collect(s)
    return sn/sd

    display(normTF(H))

    Continue reading...

Compartilhe esta Página