Transcription
https://www.halvorsen.blogDifferential Equationsin PythonHans-Petter Halvorsen
Free Textbook with lots of Practical amming/python/
Additional Python ramming/python/
Contents Differential EquationsSimulationODE SolversDiscrete SystemsTo benefit from the tutorial, you shouldExamplesalready know about differential equations
Python Editors Python IDLESpyder (Anaconda distribution)PyCharmVisual Studio CodeVisual StudioJupyter Notebook
Spyder (Anaconda distribution)Run Program buttonVariable Explorer windowCode Editor windowConsole windowhttps://www.anaconda.com
https://www.halvorsen.blogDifferential EquationsHans-Petter Halvorsen
Differential EquationsDifferential Equation on general form:ππ¦ π π‘, π¦ ,ππ‘Different notation is used:π¦ π‘! π¦!Example:ππ¦ π¦ ! π¦Μππ‘ODE β Ordinary Differential EquationsInitial conditionππ¦ 3y 2,ππ‘π¦ π‘! 0
Differential EquationsExample: %Note that π₯Μ &Where π₯! π₯ 0 π₯(π‘! ) is the initial conditionπ₯Μ ππ₯"Where π #, where π is denoted as the time constant of the systemThe solution for the differential equation is found to be (learnedin basic Math courses):π₯ π‘ π !" π₯#Where π₯! π₯ 0 π₯(π‘! ) is the initial condition
Python Codeπ₯ π‘ π -& π₯.In our system we can set π 5 andthe initial condition π₯! π₯(0) 1import math as mtimport numpy as npimport matplotlib.pyplot as plt# ParametersT 5a -1/Tx0 1t 0tstart 0tstop 25increment 1x []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 d()plt.axis([0, 25, 0, 1])
Alt. Solutionπ₯ π‘ π -& π₯.In our system we can set π 5 andthe initial condition π₯! π₯(0) 1In this alternative solution noFor Loop has been usedimport numpy as npimport matplotlib.pyplot as plt# ParametersT 5a -1/Tx0 1t 0tstart 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 d()plt.axis([0, 25, 0, 1])plt.show()
Comments to Example Solving differential equations like shown in theseexamples works fine But the problem is that we first have to manually (byβpen and paperβ) find the solution to the differentialequation. An alternative is to use solvers for Ordinary DifferentialEquations (ODE) in Python, so-called ODE Solvers The next approach is to find the discrete version andthen implement and simulate the discrete system
ODE Solvers in Python The scipy.integrate library has two powerful powerfulfunctions; ode() and odeint(), for numerically solving firstorder ordinary differential equations (ODEs). The ode() is more flexible, while odeint() (ODE integrator)has a simpler Python interface and works fine for mostproblems. For details, see the SciPy documentation: ed/scipy.integrate.odeint.html enerated/scipy.integrate.ode.html
Python CodeHere we use an ODE solver in SciPyπ₯Μ ππ₯In our system we can set π 5 andthe initial condition π₯! π₯(0) 1import 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 d()plt.axis([0, 25, 0, 1])plt.show()
Passing Argumentπ₯Μ ππ₯!We set π 5, π " and π₯# π₯(0) 1In the modified example we have theparameters used in the differential equation(in this case a) as an input argument.By doing this, it is very easy to changevalues for the parameters used in thedifferential equation without changing thecode for the differential equation.The differential equation can even be in aseparate file.import numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt# InitializationT 5a -1/Ttstart 0tstop 25increment 1x0 1t np.arange(tstart,tstop 1,increment)# Function that returns dx/dtdef mydiff(x, t, a):dxdt a * xreturn dxdt# Solve ODEx odeint(mydiff, x0, t, args (a,))print(x)# Plot the Resultsplt.plot(t,x)plt.title('Plotting Differential Equation d()plt.axis([0, 25, 0, 1])plt.show()
Passing ArgumentsPython CommentsYou can also easily run multiplesimulations like this:Then you can run multiplesimulations for different values of a.a -0.2x odeint(mydiff, x0, t, args (a,))a -0.1x odeint(mydiff, x0, t, args (a,)).To write a tuple containing a single value you have toinclude a comma, even though there is only one valueargs (a,)
Diff. Eq. in Separate .py Fileβdifferential equations.pyβ:def mydiff1(x, t, a):dxdt a * xreturn dxdtβtest mydiffq.pyβ:from differential equations import mydiff1import numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt# InitializationT 5a -1/Ttstart 0tstop 25increment 1x0 1t np.arange(tstart,tstop 1,increment)# Solve ODEx odeint(mydiff1, x0, t, args (a,))print(x)# Plot the Resultsplt.plot(t,x)plt.title('Plotting Differential Equation d()plt.axis([0, 25, 0, 1])plt.show()
Diff. Eq. in For Loopπ₯Μ ππ₯βdifferential equations.pyβ:"Where π , where def mydiff1(x, t, a):#dxdt a * xπ is denoted as thereturn dxdttime constant of thesystemfrom differential equations import mydiff1import numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt# InitializationTsimulations [2, 5, 10, 20]tstart 0tstop 25increment 1x0 1t np.arange(tstart,tstop 1,increment)for T in Tsimulations:a -1/T# Solve ODEx odeint(mydiff1, x0, t, args (a,))print(x)# Plot the Resultsplt.plot(t,x)βtest mydiffq.pyβ:plt.title('Plotting dxdt d()plt.axis([0, 25, 0, 1])plt.legend(["T 2", "T 5", "T 10", "T 20"])plt.show()
r Halvorsen
DiscretizationThe differential equation of the system is:π₯Μ ππ₯Next:π₯ %" π₯ π& ππ₯ We need to find the discrete version:Next:We use the Euler forward method:π₯"# π₯"π₯Μ π%π₯56" π₯5 π7 ππ₯5This gives:π₯ %" π₯ ππ₯ π&This gives the following discrete version:π₯56" (1 ππ7 ) π₯5
Python CodeDifferential Equation: πΜ ππSimulation of Discrete System:ππ%π (π ππ»π )ππimport numpy as npimport matplotlib.pyplot as plt# Model ParametersT 5a -1/T# Simulation ParametersTs 0.01Tstop 25N 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 Seriesplt.plot(t,x)plt.title('Plotting Differential Equation d()plt.axis([0, 25, 0, 1])plt.show()
Discretization Discretization are covered more in detail inanother Tutorial/Video You find also more aboutDiscretization in my TextbookβPython for Science nts/programming/python/
https://www.halvorsen.blogMore ExamplesHans-Petter Halvorsen
Bacteria SimulationIn this example we will simulate a simple model of a bacteria population in a jar.The model is as follows:Birth rate: ππ₯Death rate: ππ₯ *Then the total rate of change of bacteria population is:π₯Μ ππ₯ ππ₯ ?Where x is the number of bacteria in the jarNote that π₯Μ ,We will simulate the number of bacteriain the jar after 1 hour, assuming thatinitially there are 100 bacteria present. -In the simulations we can set b 1/hour and p 0.5 bacteria-hour
Python CodeDifferential Equation: π₯Μ ππ₯ ππ₯ &import numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt# Initializationtstart 0tstop 1increment 0.01x0 100t np.arange(tstart,tstop increment,increment)# Function that returns dx/dtdef bacteriadiff(x, t):b 1p 0.5dxdt b * x - p * x**2return dxdt# Solve ODEx odeint(bacteriadiff, x0, t)#print(x)# Plot the Resultsplt.plot(t,x)plt.title('Bacteria rid()plt.axis([0, 1, 0, 100])plt.show()
Simulation with 2 variablesGiven the following system:ππ₯" π₯?ππ‘ππ₯? π₯"ππ‘Let's simulate the system in Python. The equations will besolved in the time span [ 1 1] with initial values [1, 1].
Python CodeSystem:ππ₯" π₯*ππ‘ππ₯* π₯"ππ‘import numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt# Initializationtstart -1tstop 1increment 0.1x0 [1,1]t np.arange(tstart,tstop 1,increment)# Function that returns dx/dtdef mydiff(x, t):dx1dt -x[1]dx2dt x[0]dxdt [dx1dt,dx2dt]return dxdt# Solve ODEx odeint(mydiff, x0, t)print(x)x1 x[:,0]x2 x[:,1]# Plot the lation with 2 id()plt.axis([-1, 1, -1.5, 1.5])plt.legend(["x1", "x2"])plt.show()
https://www.halvorsen.blogSimulation of1.order SystemHans-Petter Halvorsen
1.order Dynamic SystemAssume the following general Differential Equation:Input Signalπ¦Μ ππ¦ ππ’π’(π‘)orπ¦Μ 1( π¦ πΎπ’)πWhere π "#and π DynamicSystemOutput Signalπ¦(π‘).#Where πΎ is the Gain and π is the Time constantThis differential equation represents a 1. order dynamic systemAssume π’(π‘) is a step (π), then we can find that the solution to the differential equation is:π¦ π‘ πΎπ(1 π/#)
Step ResponseπΎπ100%63%π¦Μ 1( π¦ πΎπ’)ππ¦ π‘ πΎπ(1 π/#)π‘π
1.order Dynamic System1( π¦ πΎπ’)πLet's find the mathematical expression for the step responseπΎWe use Laplace:π¦π π’(π )Note π¦Μ π π¦(π )ππ 10We apply a step in the input signal π’(π ): π’ π 1&π π¦(π ) ( π¦(π ) πΎπ’(π ))πΎπππ¦ π HNext, we use Inverse Laplaceππ 1 π 1πΎπ π¦ π π¦(π ) π’(π )We use the following Laplace Transformation pairπππin order to find π¦(π‘):/# π(1 π )ππ π¦ π π¦(π ) πΎπ’(π )ππ 1 π This gives the following step response:(ππ 1)π¦ π πΎπ’(π )/#π¦ π‘ πΎπ(1 π )Given the differential equation: π¦Μ
Python CodeWe start by plotting the following:π¦ π‘ &J#πΎπ(1 π )In the Python code we can set:π 1πΎ 3π 4import numpy as npimport matplotlib.pyplot as pltK 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()
Python Code1π¦Μ ( π¦ πΎπ’)πIn the Python code we can set:πΎ 3π 4import numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt# InitializationK 3T 4u 1tstart 0tstop 25increment 1y0 0t np.arange(tstart,tstop 1,increment)# Function that returns dx/dtdef system1order(y, t, K, T, u):dydt (1/T) * (-y K*u)return dydt# Solve ODEx odeint(system1order, y0, t, args (K, T, u))print(x)# Plot the Resultsplt.plot(t,x)plt.title('1.order System dydt (1/T)*(-y lt.show()
Additional Python ramming/python/
Hans-Petter HalvorsenUniversity of South-Eastern Norwaywww.usn.noE-mail: hans.p.halvorsen@usn.noWeb: https://www.halvorsen.blog
Python Code import numpyas np import matplotlib.pyplotas plt K 3 T 4 start 0 stop 30 increment 0.1 t 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() "# 67(1 *J & #) We start by plotting the following: In the Python code we .