Discrete Systems with Python

54
Discrete Systems with Python Hans-Petter Halvorsen https://www.halvorsen.blog

Transcript of Discrete Systems with Python

Page 1: Discrete Systems with Python

Discrete Systems with Python

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 2: Discrete Systems with Python

https://www.halvorsen.blog/documents/programming/python/

Free Textbook with lots of Practical Examples

Page 3: Discrete Systems with Python

Additional Python Resources

https://www.halvorsen.blog/documents/programming/python/

Page 4: Discrete Systems with Python

β€’ Differential Equationsβ€’ Simulationβ€’ Discrete Systemsβ€’ Examples

Contents

Page 5: Discrete Systems with Python

β€’ Python has powerful features for simulation of continuous differential equations and dynamic systems.

β€’ Sometimes we want to or need to discretize a continuous system and then simulate it in Python.

β€’ This means we need to make a discrete version of our continuous differential equations.

β€’ The built-in ODE solvers in Python use different discretization methods

Simulation of Discrete Systems

Page 6: Discrete Systems with Python

Differential Equations

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 7: Discrete Systems with Python

Differential Equations𝑑𝑦𝑑𝑑

= 𝑓 𝑑, 𝑦 , 𝑦 𝑑! = 𝑦!

𝑑𝑦𝑑𝑑

= 𝑦! = οΏ½Μ‡οΏ½

Different notation is used:

𝑑𝑦𝑑𝑑

= 3y + 2, 𝑦 𝑑! = 0

Example:Initial condition

Differential Equation on general form:

ODE – Ordinary Differential Equations

Page 8: Discrete Systems with Python

Differential Equations

οΏ½Μ‡οΏ½ = π‘Žπ‘₯Example:

Where π‘Ž = βˆ’ "#, where 𝑇 is denoted as the time constant of the system

Note that οΏ½Μ‡οΏ½ = !"!#

The solution for the differential equation is found to be (learned in basic Math courses and will not be derived here):

π‘₯ 𝑑 = 𝑒!"π‘₯# Where π‘₯$ = π‘₯ 0 = π‘₯(𝑑$) is the initial condition

Where π‘₯! = π‘₯ 0 = π‘₯(𝑑!) is the initial condition

Page 9: Discrete Systems with Python

Python Codeimport math as mtimport numpy as npimport matplotlib.pyplot as plt

# ParametersT = 5a = -1/Tx0 = 1 t = 0tstart = 0tstop = 25increment = 1

x = []x = np.zeros(tstop+1)t = np.arange(tstart,tstop+1,increment)

# Define the Equationfor k in range(tstop):

x[k] = mt.exp(a*t[k]) * x0

# Plot the Resultsplt.plot(t,x)plt.title('Plotting Differential Equation Solution')plt.xlabel('t')plt.ylabel('x(t)')plt.grid()plt.axis([0, 25, 0, 1])

π‘₯ 𝑑 = 𝑒*+π‘₯,In our system we can set 𝑇 = 5 and the initial condition π‘₯! = π‘₯(0) = 1

Page 10: Discrete Systems with Python

Alt. Solutionimport numpy as npimport matplotlib.pyplot as plt

# ParametersT = 5a = -1/Tx0 = 1 t = 0

tstart = 0tstop = 25increment = 1N = 25

#t = np.arange(tstart,tstop+1,increment) #Alternative Approacht = np.linspace(tstart, tstop, N)

x = np.exp(a*t) * x0

# Plot the Resultsplt.plot(t,x)plt.title('Plotting Differential Equation Solution')plt.xlabel('t')plt.ylabel('x(t)')plt.grid()plt.axis([0, 25, 0, 1])plt.show()

π‘₯ 𝑑 = 𝑒*+π‘₯,In our system we can set 𝑇 = 5 and the initial condition π‘₯! = π‘₯(0) = 1

In this alternative solution no For Loop has been used

(without For Loop)

Page 11: Discrete Systems with Python

Summaryβ€’ Solving differential equations like shown in these

examples works fineβ€’ But the problem is that we first have to manually (by

β€œpen and paper”) find the solution to the differential equation.

β€’ An alternative is to use solvers for Ordinary Differential Equations (ODE) in Python, so-called ODE Solvers

β€’ The next approach is to find the discrete version and then implement and simulate the discrete system

Page 12: Discrete Systems with Python

β€’ The scipy.integrate library has two powerful powerfulfunctions; ode() and odeint(), for numerically solving first order ordinary differential equations (ODEs).

β€’ The ode() is more flexible, while odeint() (ODE integrator) has a simpler Python interface and works fine for most problems.

β€’ For details, see the SciPy documentation:β€’ https://docs.scipy.org/doc/scipy/reference/generated/scipy.

integrate.odeint.htmlβ€’ https://docs.scipy.org/doc/scipy-

0.14.0/reference/generated/scipy.integrate.ode.html

ODE Solvers in Python

Page 13: Discrete Systems with Python

Python Codeimport numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt

# Initializationtstart = 0tstop = 25increment = 1x0 = 1t = np.arange(tstart,tstop+1,increment)

# Function that returns dx/dtdef mydiff(x, t):

T = 5a = -1/Tdxdt = a * xreturn dxdt

# Solve ODEx = odeint(mydiff, x0, t)print(x)

# Plot the Resultsplt.plot(t,x)plt.title('Plotting Differential Equation Solution')plt.xlabel('t')plt.ylabel('x(t)')plt.grid()plt.axis([0, 25, 0, 1])plt.show()

In our system we can set 𝑇 = 5 (π‘Ž = βˆ’ "#

) and the initial condition π‘₯! = π‘₯(0) = 1

Here we use an ODE solver in SciPy

οΏ½Μ‡οΏ½ = π‘Žπ‘₯

Page 14: Discrete Systems with Python

Discrete Systems

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 15: Discrete Systems with Python

DiscretizationEuler backward method:

Euler forward method:

οΏ½Μ‡οΏ½ β‰ˆπ‘₯ π‘˜ βˆ’ π‘₯(π‘˜ βˆ’ 1)

𝑇2

οΏ½Μ‡οΏ½ β‰ˆπ‘₯ π‘˜ + 1 βˆ’ π‘₯(π‘˜)

𝑇2

Page 16: Discrete Systems with Python

β€’ Euler–Euler forward method–Euler backward method

β€’ Zero Order Hold (ZOH) β€’ Tustinβ€’ ...

Discretization MethodsWe have many different Discretization Methods

We will focus on this since it it easy to use and implement

Page 17: Discrete Systems with Python

Discrete SystemsDifferent Discrete Symbols and meanings

Present/Current Value:

Previous Value:

Next (Future) Value:

Note! Different Notation is used in different literature!

π‘₯ π‘˜ βˆ’ 1 = π‘₯$%& = π‘₯(𝑑$%&)

π‘₯ π‘˜ = π‘₯$ = π‘₯(𝑑$)

π‘₯ π‘˜ + 1 = π‘₯$'& = π‘₯(𝑑$'&)

Page 18: Discrete Systems with Python

EulerEuler backward method:

More Accurate!

Euler forward method:Simpler to use!οΏ½Μ‡οΏ½ β‰ˆ

π‘₯ π‘˜ + 1 βˆ’ π‘₯(π‘˜)𝑇(

οΏ½Μ‡οΏ½ β‰ˆπ‘₯ π‘˜ βˆ’ π‘₯(π‘˜ βˆ’ 1)

𝑇(

Where 𝑇$ is the sampling time, and π‘₯(π‘˜ + 1), π‘₯(π‘˜) and π‘₯(π‘˜ βˆ’ 1) are discrete values of π‘₯(𝑑)

(We will primary use this in the examples)

Page 19: Discrete Systems with Python

Simulation ExampleGiven the following differential equation:

οΏ½Μ‡οΏ½ = π‘Žπ‘₯where π‘Ž = βˆ’ "

#, where 𝑇 is the time constant

Note! οΏ½Μ‡οΏ½ = 565+

Find the discrete differential equation and plot the solution for this system using Python.Set 𝑇 = 5 and the initial condition π‘₯(0) = 1.We will create a script in Python where we plot the solution π‘₯ 𝑑in the time interval 0 ≀ 𝑑 ≀ 25

Page 20: Discrete Systems with Python

DiscretizationThe differential equation of the system is:

οΏ½Μ‡οΏ½ = π‘Žπ‘₯We need to find the discrete version:

We use the Euler forward method:

οΏ½Μ‡οΏ½ β‰ˆπ‘₯!"# βˆ’ π‘₯!

𝑇$

π‘₯%&" βˆ’ π‘₯%𝑇$

= π‘Žπ‘₯%

This gives:

Next:

π‘₯%&" βˆ’ π‘₯% = 𝑇$π‘Žπ‘₯%

π‘₯78" = π‘₯7 + 𝑇2π‘Žπ‘₯7

Next:

π‘₯78" = (1 + π‘Žπ‘‡2) π‘₯7

This gives the following discrete version:

Page 21: Discrete Systems with Python

Python Codeimport numpy as npimport matplotlib.pyplot as plt

# Model ParametersT = 5a = -1/T# Simulation ParametersTs = 0.01Tstop = 25xk = 1N = int(Tstop/Ts) # Simulation lengthdata = []data.append(xk)

# Simulationfor k in range(N):

xk1 = xk + Ts* a * xkxk = xk1data.append(xk1)

# Plot the Simulation Resultst = np.arange(0,Tstop+Ts,Ts)

plt.plot(t,data)plt.title('Plotting Differential Equation Solution')plt.xlabel('t')plt.ylabel('x(t)')plt.grid()plt.axis([0, 25, 0, 1])plt.show()

π‘₯%&" = (1 + π‘Žπ‘‡$)π‘₯%Simulation of Discrete System:

Differential Equation: οΏ½Μ‡οΏ½ = π‘Žπ‘₯

Page 22: Discrete Systems with Python

Alt. Codeimport numpy as npimport matplotlib.pyplot as plt

# Model ParametersT = 5a = -1/T# Simulation ParametersTs = 0.01Tstop = 25

N = int(Tstop/Ts) # Simulation lengthx = np.zeros(N+2) # Initialization the x vectorx[0] = 1 # Initial Condition

# Simulationfor k in range(N+1):

x[k+1] = (1 + a*Ts) * x[k]

# Plot the Simulation Resultst = np.arange(0,Tstop+2*Ts,Ts) # Create Time Series

plt.plot(t,x)plt.title('Plotting Differential Equation Solution')plt.xlabel('t')plt.ylabel('x(t)')plt.grid()plt.axis([0, 25, 0, 1])plt.show()

π‘₯%&" = (1 + π‘Žπ‘‡$)π‘₯%Simulation of Discrete System:

Differential Equation: οΏ½Μ‡οΏ½ = π‘Žπ‘₯(using Arrays)

Page 23: Discrete Systems with Python

More Examples

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 24: Discrete Systems with Python

Bacteria Simulation

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 25: Discrete Systems with Python

Bacteria SimulationThe model is as follows:

In this example we will simulate a simple model of a bacteria population in a jar.

Birth rate: 𝑏π‘₯Death rate: 𝑝π‘₯'

Then the total rate of change of bacteria population is:

οΏ½Μ‡οΏ½ = 𝑏π‘₯ βˆ’ 𝑝π‘₯<

Note that οΏ½Μ‡οΏ½ = ()(*

Where x is the number of bacteria in the jar

In the simulations we can set b=1/hour and p=0.5 bacteria-hour

We will simulate the number of bacteria in the jar after 1 hour, assuming that initially there are 100 bacteria present.

Page 26: Discrete Systems with Python

DiscretizationThe differential equation of the system is:

οΏ½Μ‡οΏ½ = 𝑏π‘₯ βˆ’ 𝑝π‘₯<

We need to find the discrete version:

We use the Euler forward method:

οΏ½Μ‡οΏ½ β‰ˆπ‘₯!"# βˆ’ π‘₯!

𝑇$

π‘₯%&" βˆ’ π‘₯%𝑇$

= 𝑏π‘₯% βˆ’ 𝑝π‘₯%'

This gives:

Next:

π‘₯%&" βˆ’ π‘₯% = 𝑇$(𝑏π‘₯% βˆ’ 𝑝π‘₯%')

π‘₯78" = π‘₯7 + 𝑇2(𝑏π‘₯7 βˆ’ 𝑝π‘₯7<)

This gives the following discrete version:

Page 27: Discrete Systems with Python

Python Code# Simulation of Bacteria Populationimport numpy as npimport matplotlib.pyplot as plt

# Model Parametersb = 1p = 0.5

# Simulation ParametersTs = 0.01Tstop = 1xk = 100N = int(Tstop/Ts) # Simulation lengthdata = []data.append(xk)

# Simulationfor k in range(N):

xk1 = xk + Ts* (b * xk - p * xk**2);xk = xk1data.append(xk1)

# Plot the Simulation Resultst = np.arange(0,Tstop+Ts,Ts)

plt.plot(t,data)plt.title('Simulation of Bacteria Population')plt.xlabel('t [s]')plt.ylabel('x(t)')plt.grid()plt.xlim(0, 1)plt.ylim(0, 100) plt.show()

π‘₯%&" = π‘₯% + 𝑇$(𝑏π‘₯% βˆ’ 𝑝π‘₯%')Simulation of Discrete System:

Differential Equation: οΏ½Μ‡οΏ½ = 𝑏π‘₯ βˆ’ 𝑝π‘₯'

Page 28: Discrete Systems with Python

Alt. Codeimport numpy as npimport matplotlib.pyplot as plt

# Model Parametersb = 1p = 0.5

# Simulation ParametersTs = 0.01Tstop = 1

N = int(Tstop/Ts) # Simulation lengthx = np.zeros(N+2) # Initialization the x vectorx[0] = 100 # Initial Condition

# Simulationfor k in range(N+1):

x[k+1] = x[k] + Ts * (b * x[k] - p * x[k]**2)

# Plot the Simulation Resultst = np.arange(0,Tstop+2*Ts,Ts) # Create Time Series

plt.plot(t,x)plt.title('Simulation of Bacteria Population')plt.xlabel('t [s]')plt.ylabel('x(t)')plt.grid()plt.axis([0, 1, 0, 100])plt.show()

π‘₯%&" = π‘₯% + 𝑇$(𝑏π‘₯% βˆ’ 𝑝π‘₯%')Simulation of Discrete System:

Differential Equation: οΏ½Μ‡οΏ½ = 𝑏π‘₯ βˆ’ 𝑝π‘₯'(using Arrays)

Page 29: Discrete Systems with Python

Simulations with 2 variables

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 30: Discrete Systems with Python

Simulation with 2 variablesGiven the following system:

𝑑π‘₯"𝑑𝑑

= βˆ’π‘₯<

𝑑π‘₯<𝑑𝑑

= π‘₯"

Let's find the discrete system and simulate the discrete system in Python.

Page 31: Discrete Systems with Python

DiscretizationUsing Euler:

οΏ½Μ‡οΏ½ β‰ˆπ‘₯ π‘˜ + 1 βˆ’ π‘₯(π‘˜)

𝑇2Then we get:

π‘₯" π‘˜ + 1 = π‘₯" π‘˜ βˆ’ 𝑇2π‘₯< π‘˜π‘₯< π‘˜ + 1 = π‘₯< π‘˜ + 𝑇2π‘₯" π‘˜

Which we can implement in Python

The equations will be solved in the time span [βˆ’1 1] with initial values [1, 1].

Page 32: Discrete Systems with Python

Python Codeimport numpy as npimport matplotlib.pyplot as plt

# Model and Simulation Parametersb = 1p = 0.5Ts = 0.1Tstart = -1Tstop = 1x1k = 1x2k = 1N = int((Tstop-Tstart)/Ts) # Simulation lengthdatax1 = []datax2 = []datax1.append(x1k)datax2.append(x2k)

# Simulationfor k in range(N):

x1k1 = x1k - Ts * x2kx2k1 = x2k + Ts * x1k

x1k = x1k1x2k = x2k1datax1.append(x1k1)datax2.append(x2k1)

# Plot the Simulation Resultst = np.arange(Tstart,Tstop+Ts,Ts)

plt.plot(t,datax1, t, datax2)plt.title('Simulation with 2 Variables')plt.xlabel('t [s]')plt.ylabel('x(t)')plt.grid()plt.axis([-1, 1, -1.5, 1.5])plt.show()

π‘₯! π‘˜ + 1 = π‘₯! π‘˜ βˆ’ 𝑇"π‘₯# π‘˜π‘₯# π‘˜ + 1 = π‘₯# π‘˜ + 𝑇"π‘₯! π‘˜

𝑑π‘₯!𝑑𝑑

= βˆ’π‘₯#

𝑑π‘₯#𝑑𝑑

= π‘₯!

Page 33: Discrete Systems with Python

Alt. Code# Simulation with 2 Variablesimport numpy as npimport matplotlib.pyplot as plt

# Model Parametersb = 1p = 0.5

# Simulation ParametersTs = 0.1Tstart = -1Tstop = 1N = int((Tstop-Tstart)/Ts) # Simulation lengthx1 = np.zeros(N+2)x2 = np.zeros(N+2)x1[0] = 1x2[0] = 1

# Simulationfor k in range(N+1):

x1[k+1] = x1[k] - Ts * x2[k]x2[k+1] = x2[k] + Ts * x1[k]

# Plot the Simulation Resultst = np.arange(Tstart,Tstop+2*Ts,Ts)

plt.plot(t,x1, t, x2)plt.title('Simulation with 2 Variables')plt.xlabel('t [s]')plt.ylabel('x(t)')plt.grid()plt.axis([-1, 1, -1.5, 1.5])plt.show()

π‘₯! π‘˜ + 1 = π‘₯! π‘˜ βˆ’ 𝑇"π‘₯# π‘˜π‘₯# π‘˜ + 1 = π‘₯# π‘˜ + 𝑇"π‘₯! π‘˜

𝑑π‘₯!𝑑𝑑

= βˆ’π‘₯#

𝑑π‘₯#𝑑𝑑

= π‘₯!

(using Arrays)

Page 34: Discrete Systems with Python

Simulation of 1.order System

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 35: Discrete Systems with Python

1.order Dynamic System

οΏ½Μ‡οΏ½ =1𝑇 (βˆ’π‘¦ + 𝐾𝑒)

Where 𝐾 is the Gain and 𝑇 is the Time constant

οΏ½Μ‡οΏ½ = π‘Žπ‘¦ + 𝑏𝑒 Dynamic System𝑒(𝑑) 𝑦(𝑑)

Assume the following general Differential Equation:

or

Where π‘Ž = βˆ’ "#

and 𝑏 = +#

This differential equation represents a 1. order dynamic system

Assume 𝑒(𝑑) is a step (π‘ˆ), then we can find that the solution to the differential equation is:

𝑦 𝑑 = πΎπ‘ˆ(1 βˆ’ 𝑒,*#)

Input Signal Output Signal

Page 36: Discrete Systems with Python

Step Response100%

63%

πΎπ‘ˆ

𝑑𝑇

𝑦 𝑑 = πΎπ‘ˆ(1 βˆ’ 𝑒,*#)

οΏ½Μ‡οΏ½ =1𝑇 (βˆ’π‘¦ + 𝐾𝑒)

Page 37: Discrete Systems with Python

1.order Dynamic SystemοΏ½Μ‡οΏ½ =

1𝑇 (βˆ’π‘¦ + 𝐾𝑒)

Let's find the mathematical expression for the step response

𝑠𝑦(𝑠) =1𝑇 (βˆ’π‘¦(𝑠) + 𝐾𝑒(𝑠))

We use Laplace: Note οΏ½Μ‡οΏ½ ⟺ 𝑠𝑦(𝑠)

We apply a step in the input signal 𝑒(𝑠): 𝑒 𝑠 = -$

𝑠𝑦 𝑠 +1𝑇 𝑦(𝑠) =

𝐾𝑇 𝑒(𝑠)

𝑇𝑠𝑦 𝑠 + 𝑦(𝑠) = 𝐾𝑒(𝑠)

(𝑇𝑠 + 1)𝑦 𝑠 = 𝐾𝑒(𝑠)

𝑦 𝑠 =𝐾

𝑇𝑠 + 1𝑒(𝑠)

𝑦 𝑠 =𝐾

𝑇𝑠 + 1 Dπ‘ˆπ‘ 

We use the following Laplace Transformation pair in order to find 𝑦(𝑑): π‘˜

𝑇𝑠 + 1 𝑠 ⟺ π‘˜(1 βˆ’ 𝑒,*#)

Given the differential equation:

𝑦 𝑑 = πΎπ‘ˆ(1 βˆ’ 𝑒,*#)

This gives the following step response:

Next, we use Inverse Laplace

Page 38: Discrete Systems with Python

Python Codeimport numpy as npimport matplotlib.pyplot as plt

K = 3T = 4start = 0stop = 30increment = 0.1t = np.arange(start,stop,increment)

y = K * (1-np.exp(-t/T))

plt.plot(t, y)plt.title('1.order Dynamic System')plt.xlabel('t [s]')plt.ylabel('y(t)'plt.grid()

𝑦 𝑑 = πΎπ‘ˆ(1 βˆ’ 𝑒E+#)

We start by plotting the following:

In the Python code we can set:

π‘ˆ = 1𝐾 = 3𝑇 = 4

Page 39: Discrete Systems with Python

Python Code (Alternative Code)import numpy as npimport matplotlib.pyplot as plt

def model(t):K = 3T = 4y = K * (1-np.exp(-t/T))return y

start = 0stop = 30increment = 0.1t = np.arange(start,stop,increment)

y = model(t)

plt.plot(t, y)plt.title('1.order Dynamic System')plt.xlabel('t [s]')plt.ylabel('y(t)'plt.grid()

𝑦 𝑑 = πΎπ‘ˆ(1 βˆ’ 𝑒E+#)

We start by plotting the following:

In the Python code we can set:

π‘ˆ = 1𝐾 = 3𝑇 = 4

Page 40: Discrete Systems with Python

Discretization

οΏ½Μ‡οΏ½ = π‘Žπ‘¦ + 𝑏𝑒We start with the differential equation:

We use the Euler forward method:

οΏ½Μ‡οΏ½ β‰ˆπ‘¦!"# βˆ’ 𝑦!

𝑇$

This gives:

.!"#,.!#$

= π‘Žπ‘¦% + 𝑏𝑒%

This gives the following discrete differential equation:

𝑦%&" = 𝑦% + 𝑇$ π‘Žπ‘¦% + 𝑏𝑒%

Further we get:

𝑦%&" = 𝑦% + 𝑇$π‘Žπ‘¦%+ 𝑇$𝑏𝑒%

𝑦78" = (1 + 𝑇2π‘Ž)𝑦7+ 𝑇2𝑏𝑒7

Page 41: Discrete Systems with Python

Python Code# Simulation of discrete modelimport numpy as npimport matplotlib.pyplot as plt

# Model ParametersK = 3T = 4

a = -1/Tb = K/T

# Simulation ParametersTs = 0.1Tstop = 30uk = 1 # Step Responseyk = 0 # Initial ValueN = int(Tstop/Ts) # Simulation lengthdata = []data.append(yk)

# Simulationfor k in range(N):

yk1 = (1 + a*Ts) * yk + Ts * b * ukyk = yk1data.append(yk1)

# Plot the Simulation Resultst = np.arange(0,Tstop+Ts,Ts)

plt.plot(t,data)plt.title('1.order Dynamic System')plt.xlabel('t [s]')plt.ylabel('y(t)')plt.grid()

Where π‘Ž = βˆ’ "#

and 𝑏 = +#

𝑦78" = (1 + 𝑇2π‘Ž)𝑦7+ 𝑇2𝑏𝑒7

In the Python code we can set:

Let's simulate the discrete system:

𝐾 = 3𝑇 = 4

Page 42: Discrete Systems with Python

Alt. Solution# Simulation of discrete modelimport numpy as npimport matplotlib.pyplot as plt

# Model ParametersK = 3T = 4

a = -1/Tb = K/T

# Simulation ParametersTs = 0.1 # Sampling TimeTstop = 30 # End of Simulation Timeuk = 1 # Step ResponseN = int(Tstop/Ts) # Simulation lengthy = np.zeros(N+2) # Initialization the x vectory[0] = 0

# Simulationfor k in range(N+1):

y[k+1] = (1 + a*Ts) * y[k] + Ts * b * uk

# Plot the Simulation Resultst = np.arange(0,Tstop+2*Ts,Ts) # Create Time Seriesplt.plot(t,y)# Formatting the appearance of the Plotplt.title('1.order Dynamic System')plt.xlabel('t [s]')plt.ylabel('y(t)')plt.grid()

Where π‘Ž = βˆ’ "#

and 𝑏 = +#

𝑦78" = (1 + 𝑇2π‘Ž)𝑦7+ 𝑇2𝑏𝑒7

In the Python code we can set:

Let's simulate the discrete system:

𝐾 = 3𝑇 = 4

Page 43: Discrete Systems with Python

Higher Order Systems

Hans-Petter Halvorsen

https://www.halvorsen.blog

Page 44: Discrete Systems with Python

Mass-Spring DamperGiven a so-called "Mass-Spring-Damper" system

𝐹 𝑑 βˆ’ 𝑐�̇� 𝑑 βˆ’ π‘˜π‘₯ 𝑑 = π‘šοΏ½ΜˆοΏ½(𝑑)

The system can be described by the following equation:

Where 𝑑 is the time, 𝐹(𝑑) is an external force applied to the system, 𝑐 is the damping constant, π‘˜ is the stiffness of the spring, π‘š is a mass.

x(t) is the position of the object (π‘š)

οΏ½Μ‡οΏ½ 𝑑 is the first derivative of the position, which equals the velocity/speed of the object (π‘š)

�̈�(𝑑) is the second derivative of the position, which equals the acceleration of the object (π‘š)

Newtons 2.law: βˆ‘πΉ = π‘šπ‘Ž

Page 45: Discrete Systems with Python

Mass-Spring Damper𝐹 𝑑 βˆ’ 𝑐�̇� 𝑑 βˆ’ π‘˜π‘₯ 𝑑 = π‘šοΏ½ΜˆοΏ½(𝑑)

π‘šοΏ½ΜˆοΏ½ = 𝐹 βˆ’ 𝑐�̇� βˆ’ π‘˜π‘₯

�̈� =1π‘š 𝐹 βˆ’ 𝑐�̇� βˆ’ π‘˜π‘₯

Higher order differential equations can typically be reformulated into a system of first order differential equations

We set π‘₯ = π‘₯"οΏ½Μ‡οΏ½ = π‘₯'

This gives:οΏ½Μ‡οΏ½" = π‘₯'οΏ½Μ‡οΏ½' = �̈�= "

/𝐹 βˆ’ 𝑐�̇� βˆ’ π‘˜π‘₯ = "

/𝐹 βˆ’ 𝑐π‘₯' βˆ’ π‘˜π‘₯"

�̈� =1π‘š

𝐹 βˆ’ 𝑐�̇� βˆ’ π‘˜π‘₯οΏ½Μ‡οΏ½" = π‘₯<οΏ½Μ‡οΏ½< =

"M 𝐹 βˆ’ 𝑐π‘₯< βˆ’ π‘˜π‘₯"

Finally:

π‘₯"= Positionπ‘₯'= Velocity/Speed

Page 46: Discrete Systems with Python

Python Codeimport numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt

# Initializationtstart = 0tstop = 60increment = 0.1

# Initial conditionx_init = [0,0]

t = np.arange(tstart,tstop+1,increment)

# Function that returns dx/dtdef mydiff(x, t):

c = 4 # Damping constantk = 2 # Stiffness of the springm = 20 # MassF = 5

dx1dt = x[1] dx2dt = (F - c*x[1] - k*x[0])/m

dxdt = [dx1dt, dx2dt]return dxdt

# Solve ODEx = odeint(mydiff, x_init, t)

x1 = x[:,0]x2 = x[:,1]

# Plot the Resultsplt.plot(t,x1)plt.plot(t,x2)plt.title('Simulation of Mass-Spring-Damper System')plt.xlabel('t')plt.ylabel('x(t)')plt.legend(["x1", "x2"])plt.grid()plt.show()

π‘₯"= Positionπ‘₯'= Velocity/Speed

οΏ½Μ‡οΏ½" = π‘₯'οΏ½Μ‡οΏ½' =

"/𝐹 βˆ’ 𝑐π‘₯' βˆ’ π‘˜π‘₯"

Using SciPy ODE Solver

Page 47: Discrete Systems with Python

State-space ModelοΏ½Μ‡οΏ½" = π‘₯<οΏ½Μ‡οΏ½< =

"M 𝐹 βˆ’ 𝑐π‘₯< βˆ’ π‘˜π‘₯"

οΏ½Μ‡οΏ½" = π‘₯<οΏ½Μ‡οΏ½< =βˆ’

7M π‘₯" βˆ’

NM π‘₯<+ "

M𝐹

οΏ½Μ‡οΏ½ = 𝐴π‘₯ + 𝐡𝑒

𝐴 =0 1

βˆ’π‘˜π‘š

βˆ’π‘π‘š

𝐡 =01π‘š

π‘₯ =π‘₯#π‘₯%

οΏ½Μ‡οΏ½"οΏ½Μ‡οΏ½'

=0 1

βˆ’π‘˜π‘š

βˆ’π‘π‘š

π‘₯"π‘₯' +

01π‘š

𝐹

Page 48: Discrete Systems with Python

Python Codeimport numpy as npimport matplotlib.pyplot as pltimport control

# Parameters defining the systemc = 4 # Damping constantk = 2 # Stiffness of the springm = 20 # MassF = 5 # Force

# Simulation Parameterststart = 0tstop = 60increment = 0.1t = np.arange(tstart,tstop+1,increment)

# System matricesA = [[0, 1], [-k/m, -c/m]]B = [[0], [1/m]]C = [[1, 0]]sys = control.ss(A, B, C, 0)

# Step response for the systemt, y, x = control.forced_response(sys, t, F)plt.plot(t, y)plt.title('Simulation of Mass-Spring-Damper System')plt.xlabel('t')plt.ylabel('x(t)')plt.grid()plt.show()

State-space Model

οΏ½Μ‡οΏ½"οΏ½Μ‡οΏ½'

=0 1

βˆ’π‘˜π‘š βˆ’

π‘π‘š

π‘₯"π‘₯' +

01π‘š

𝐹

𝑦 = 1 0π‘₯"π‘₯'

Page 49: Discrete Systems with Python

Python Codeimport numpy as npimport matplotlib.pyplot as pltimport control

# Parameters defining the systemc = 4 # Damping constantk = 2 # Stiffness of the springm = 20 # MassF = 5 # Force

# Simulation Parameterststart = 0tstop = 60increment = 0.1t = np.arange(tstart,tstop+1,increment)

# System matricesA = [[0, 1], [-k/m, -c/m]]B = [[0], [1/m]]C = [[1, 0]]sys = control.ss(A, B, C, 0)

# Step response for the systemt, y, x = control.forced_response(sys, t, F)x1 = x[0 ,:]x2 = x[1 ,:]

plt.plot(t, x1, t, x2)plt.title('Simulation of Mass-Spring-Damper System')plt.xlabel('t')plt.ylabel('x(t)')plt.grid()plt.show()

State-space Model

οΏ½Μ‡οΏ½"οΏ½Μ‡οΏ½'

=0 1

βˆ’π‘˜π‘š βˆ’

π‘π‘š

π‘₯"π‘₯' +

01π‘š

𝐹

𝑦 = 1 0π‘₯"π‘₯'

Page 50: Discrete Systems with Python

DiscretizationGiven:

οΏ½Μ‡οΏ½! = π‘₯"οΏ½Μ‡οΏ½" =

!#𝐹 βˆ’ 𝑐π‘₯" βˆ’ π‘˜π‘₯!

Using Euler:

οΏ½Μ‡οΏ½ β‰ˆπ‘₯ π‘˜ + 1 βˆ’ π‘₯(π‘˜)

𝑇$

Then we get:π‘₯! π‘˜ + 1 βˆ’ π‘₯! π‘˜

𝑇$= π‘₯" π‘˜

π‘₯" π‘˜ + 1 βˆ’ π‘₯" π‘˜π‘‡$

=1π‘š

𝐹(π‘˜) βˆ’ 𝑐π‘₯" π‘˜ βˆ’ π‘˜π‘₯! π‘˜

This gives:π‘₯! π‘˜ + 1 = π‘₯! π‘˜ + 𝑇$π‘₯" π‘˜

π‘₯" π‘˜ + 1 = π‘₯" π‘˜ + 𝑇$1π‘š

𝐹(π‘˜) βˆ’ 𝑐π‘₯" π‘˜ βˆ’ π‘˜π‘₯! π‘˜

Then we get:π‘₯! π‘˜ + 1 = π‘₯! π‘˜ + 𝑇$π‘₯" π‘˜π‘₯" π‘˜ + 1 = βˆ’π‘‡$

%#π‘₯! π‘˜ + π‘₯" π‘˜ βˆ’ 𝑇$

&#π‘₯" π‘˜ + 𝑇$

!#𝐹(π‘˜)

Finally:π‘₯! π‘˜ + 1 = π‘₯! π‘˜ + 𝑇$π‘₯" π‘˜π‘₯" π‘˜ + 1 = βˆ’π‘‡$

%#π‘₯! π‘˜ + (1 βˆ’ 𝑇$

&#)π‘₯" π‘˜ + 𝑇$

!#𝐹(π‘˜)

Page 51: Discrete Systems with Python

π‘₯" π‘˜ + 1 = π‘₯" π‘˜ + 𝑇$π‘₯' π‘˜π‘₯' π‘˜ + 1 = βˆ’π‘‡$

%/π‘₯" π‘˜ + (1 βˆ’ 𝑇$

0/)π‘₯' π‘˜ + 𝑇$

"/𝐹

π‘₯" π‘˜ + 1π‘₯' π‘˜ + 1

=1 𝑇$

βˆ’π‘‡$π‘˜π‘š 1 βˆ’ 𝑇$

π‘π‘š

π‘₯" π‘˜π‘₯' π‘˜

+0

𝑇$1π‘š

𝐹

Discrete State-space ModelDiscrete System:

π‘₯(π‘˜ + 1) = 𝐴(π‘₯(π‘˜) + 𝐡(𝑒(π‘˜)

𝐴 =1 𝑇$

βˆ’π‘‡$π‘˜π‘š

1 βˆ’ 𝑇$π‘π‘š

𝐡 =0

𝑇$1π‘š

π‘₯(π‘˜) = π‘₯# π‘˜π‘₯% π‘˜

We can set it on Discrete state space form:

This gives:

Page 52: Discrete Systems with Python

Python Code# Simulation of Mass-Spring-Damper Systemimport numpy as npimport matplotlib.pyplot as plt

# Model Parametersc = 4 # Damping constantk = 2 # Stiffness of the springm = 20 # MassF = 5 # Force

# Simulation ParametersTs = 0.1Tstart = 0Tstop = 60N = int((Tstop-Tstart)/Ts) # Simulation lengthx1 = np.zeros(N+2)x2 = np.zeros(N+2)x1[0] = 0 # Initial Positionx2[0] = 0 # Initial Speed

a11 = 1a12 = Tsa21 = -(Ts*k)/ma22 = 1 - (Ts*c)/m

b1 = 0b2 = Ts/m

# Simulationfor k in range(N+1):

x1[k+1] = a11 * x1[k] + a12 * x2[k] + b1 * Fx2[k+1] = a21 * x1[k] + a22 * x2[k] + b2 * F

# Plot the Simulation Resultst = np.arange(Tstart,Tstop+2*Ts,Ts)

#plt.plot(t, x1, t, x2)plt.plot(t,x1)plt.plot(t,x2)plt.title('Simulation of Mass-Spring-Damper System')plt.xlabel('t [s]')plt.ylabel('x(t)')plt.grid()plt.legend(["x1", "x2"])plt.show()

π‘₯!= Positionπ‘₯"= Velocity/Speed

Discrete System

π‘₯" π‘˜ + 1 = π‘₯" π‘˜ + 𝑇$π‘₯' π‘˜π‘₯' π‘˜ + 1 = βˆ’π‘‡$

%/π‘₯" π‘˜ + (1 βˆ’ 𝑇$

0/)π‘₯' π‘˜ + 𝑇$

"/𝐹

Page 53: Discrete Systems with Python

Additional Python Resources

https://www.halvorsen.blog/documents/programming/python/

Page 54: Discrete Systems with Python

Hans-Petter Halvorsen

University of South-Eastern Norwaywww.usn.no

E-mail: [email protected]: https://www.halvorsen.blog