PYTHON - P2prod/Filter-Modeling-Simulation GitHub Wiki

Python is a good tool for simulating filters and performing mathematical calculations. It has specialised packages that offer a syntax similar to that of MATLAB, with very close instructions and identical rendering of curves. The advantage is that it is free.

These packages are :

  • control (Python Control Systems), control.matlab, slycot or scipy for calculations (non-exhaustive list),

  • seaborn for scientific displays.

You will also need to load packages such as numpy and matplot.lib.

The examples below, relating to the calculation and display of the step response of advance-delay filters, illustrate all this.

1st example with control.matlab packages

#-------------------------------------------------------------------------------
# Name:        Lead Lag Filter Step Response with control.matlab
# Created:     07/11/2024
#-------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
import control.matlab as control

T1 = 10 # lead time constant
T2 = 5  # lag time constant

H = control.tf([T1,1],[T2, 1]) # transfer function creation
print(H) # show the transfer function equation

y,t = control.step(H) # creation of the system (values are stored in y,t)
# Syntax is remarkably simple
# It is also possible to get the impulse response by replacing step by impulse

print(t,y) # allow to get the values for each computed point

# plot of the step response
plt.plot(t,y)
plt.xlabel('Time')
plt.title('Step Response')
plt.show()

2nd example with Control package

#-------------------------------------------------------------------------------
# Name:        Lead Lag Filter Step response from Transfer Function with control
# Created:     07/11/2024
#-------------------------------------------------------------------------------

import control as ct
import numpy as np
import matplotlib.pyplot as plt

T1 = 10
T2 = 5

# Create a variable 's' to allow algebra operations for SISO systems
s = ct.tf('s')
H  = (T1*s + 1)/(T2*s + 1) # Creation of the transfer function
t, y = ct.step_response(H) # computation of the step response and store in yout

plt(t,y)
plt.grid()
plt.show()

3rd example : variant with Control.matlab package

#-------------------------------------------------------------------------------
# Name:        Lead Lag Filter Step response from Transfer Function (2)
# Created:     07/11/2024
#-------------------------------------------------------------------------------

import numpy as np
import matplotlib.pyplot as plt
from control.matlab import *

num = [10,1] # tf numerator
den = [5,1]  # tf denominator

sys = tf(num, den) # transfer function creation
y,T=step(sys) # step response computation and store in y,T

# plot
plt.plot(T.T,y.T) # T.T is the variable Time, y.T is the output of the filter
plt.show()

4th example with SciPy package


```#-------------------------------------------------------------------------------
# Name:        Lead Lag Filter Step response with SciPy
# Created:     07/11/2024
#-------------------------------------------------------------------------------

from scipy import signal
import matplotlib.pyplot as plt

T1 = 10
T2 = 5

num = [T1, 1] # tf numerator
den = [T2, 1]  # tf denominator

sys = signal.TransferFunction(num, den)
t, y = signal.step(sys)

plt.plot(t, y)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.title('Step response for Lead Lag Filter')
plt.grid()
plt.show()

# 5th example with State space Model approach
```python
#-------------------------------------------------------------------------------
# Name:        Lead Lag Filter step response with odeint
# Created:     09/11/2024
#-------------------------------------------------------------------------------
# Theory (reminder)
# with State Space Modeling approach we get:
#
# x' = -x/T2 + u/T2
# y = (1 - T1/T2).x + T1/T2.u
#
# with x = state variable, y = filter output voltage, u = input voltage
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns x'
def leadlag(x,t,u,T2):
    dxdt = -x/T2 + u/T2
    return dxdt
# input voltage u(t)
u = 1 #(unit step)

# time constants
T1 = 10
T2 = 5
# initial condition
x0 = 0
# time points
t = np.linspace(0,40)
# solve ODE (get x(t))
x = odeint(leadlag,x0,t,args=(u,T2))
# get y(t)
y = (1 - (T1/T2))*x + (T1/T2)*u
# plot results
plt.plot(t,y)
plt.grid()
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()

5th example with State space Model approach with SymPy dsolve

#-------------------------------------------------------------------------------
# Name:        Solving symbolically Lead lag Filter with sympy dsolve
# Purpose:     solve x'(t) = (u(t) - x(t))/T2 with ic = {x(0)=0}
# Author:      Pascal
# Created:     09/11/2024
#-------------------------------------------------------------------------------
# Reminder :
# Lead Lag Filter SSM equation are :
# x' = (u - x)/T2 where x' is the state space variable
# y = x (1 -T1/T2) + u (T1/T2) where y is the filter output

import sympy as sp
from sympy import * #Function, dsolve, Derivative, checkodesol
from sympy.abc import t

T1 = 10
T2 = 5
u = 1 # unit step
x = Function('x') # Defines x for dsolve below
# Solve the ODE
result = dsolve

print(result)
print(result.rhs) # Get the Right Hand Side of the result
# Plot x(t)
plot(result.rhs,(t,0,40),title="x(t) curve") # SymPy's plot instruction replaces matplotlib plt.

# Get y plot and values 
y = result.rhs*(1 - (T1/T2)) + u*(T1/T2)
print(y) # Get the numerical values
plot(y,(t,0,40),title="Lead Lag Filter Step Response (solved with SymPy dsolve)")