Python For Control Engineering - Halvorsen.blog

Transcription

https://www.halvorsen.blogPython for ControlEngineeringHans-Petter Halvorsen

Free Textbook with lots of Practical amming/python/

Additional Python ramming/python/

Contents Introduction to Control Engineering Python Libraries useful in ControlEngineering Applications– NumPy, Matplotlib– SciPy (especially scipy.signal)– Python Control Systems Library (control) Python Examples Additional Tutorials/Videos/Topics

Additional Tutorials/Videos/TopicsThis Tutorial is only the beginning. Some Examples of Tutorials that goes more in depth: Transfer Functions with Python State-space Models with PythonVideos available Frequency Response with Pythonon YouTube PID Control with Python Stability Analysis with Python Frequency Response Stability Analysis with Python Logging Measurement Data to File with Python Control System with Python– Exemplified using Small-scale Industrial Processes and Simulators DAQ ogramming/python/

https://www.halvorsen.blogPython LibrariesHans-Petter Halvorsen

NumPy, Matplotlib In addition to Python itself, thePython libraries NumPy, Matplotlib istypically needed in all kind ofapplication If you have installed Python using theAnaconda distribution, these arealready installed

SciPy.signal An alternative to The Python Control Systems Library isSciPy.signal, i.e. the Signal Module in the SciPy Library htmlWith SciPy.signal you cancreate Transfer Functions,State-space Models, you cansimulate dynamic systems, doFrequency Response Analysis,including Bode plot, etc.

Python Control Systems Library The Python Control Systems Library (control) is aPython package that implements basic operationsfor analysis and design of feedback control systems. Existing MATLAB user? The functions and thefeatures are very similar to the MATLAB ControlSystems Toolbox. Python Control Systems Library Homepage:https://pypi.org/project/control Python Control Systems Library o

https://www.halvorsen.blogControl EngineeringHans-Petter Halvorsen

Control SystemNoise/Disturbanceπ‘Ÿπ‘’ 𝑣The Controller istypically a PID sors

Control System π‘Ÿ – Reference Value, SP (Set-point), SV (Set Value) 𝑦 – Measurement Value (MV), Process Value (PV) 𝑒 – Error between the reference value and themeasurement value (𝑒 π‘Ÿ – 𝑦) 𝑣 – Disturbance, makes it more complicated to controlthe process 𝑒 - Control Signal from the Controller

The PID Algorithm&𝐾#( π‘’π‘‘πœ 𝐾# 𝑇' 𝑒̇𝑒 𝑑 𝐾# 𝑒 𝑇 %Where 𝑒 is the controller output and 𝑒 is thecontrol error:𝑒 𝑑 π‘Ÿ 𝑑 𝑦(𝑑)π‘Ÿ is the Reference Signal or Set-point𝑦 is the Process value, i.e., the Measured valueTuning Parameters:𝐾!𝑇"𝑇#Proportional GainIntegral Time [sec. ]Derivative Time [sec. ]

The PID Algorithm&𝐾#𝑒 𝑑 𝐾# 𝑒 ( π‘’π‘‘πœ 𝐾# 𝑇' 𝑒̇𝑇 %PProportional GainTuning Parameters:𝐾%IIntegral Time𝑇&DDerivative Time𝑇'

https://www.halvorsen.blogPython ExamplesHans-Petter Halvorsen

https://www.halvorsen.blogDynamic Systems andDifferential EquationsHans-Petter Halvorsen

Dynamic Systems and Models The purpose with a Control System is to Control a DynamicSystem, e.g., an industrial process, an airplane, a self-drivencar, etc. (a Control System is β€œeverywhereβ€œ). Typically, we start with a Mathematical model of such asDynamic System The mathematical model of such a system can be– A Differential Equation– A Transfer Function– A State-space Model We use the Mathematical model to create a Simulator ofthe system

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 𝑒 %")(we use Laplace)

PythonWe start by plotting the following:𝑦 𝑑 0/1πΎπ‘ˆ(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()

CommentsWe have many different options when it comes to simulation a DynamicSystem: We can solve the differential Equation(s) and then implement the thealgebraic solution and plot it.– This solution may work for simple systems. For more complicatedsystems it may be difficult to solve the differential equation(s) byhand We can use one of the β€œbuilt-in” ODE solvers in Python We can make a Discrete version of the system We can convert the differential equation(s) to Transfer Function(s) etc.We will demonstrate and show examples of all these approaches

PythonDifferential Equation:Using ODE Solver1𝑦̇ ( 𝑦 𝐾𝑒)𝑇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()

DiscretizationWe start with the differential equation:𝑦̇ π‘Žπ‘¦ 𝑏𝑒We can use the Euler forward method:𝑦456 𝑦4𝑦̇ 𝑇7This gives:8!"# /8!1 π‘Žπ‘¦4 𝑏𝑒4Further we get:𝑦456 𝑦4 𝑇7 π‘Žπ‘¦4 𝑏𝑒4𝑦456 𝑦4 𝑇7 π‘Žπ‘¦4 𝑇7 𝑏𝑒4This gives the following discrete differentialequation:𝑦 %& (1 𝑇' π‘Ž)𝑦 𝑇' 𝑏𝑒

PythonLet's simulate the discrete system:𝑦()* (1 𝑇 π‘Ž)𝑦( 𝑇 𝑏𝑒(Where π‘Ž !"and 𝑏 #"In the Python code we can set:𝐾 3𝑇 4import numpy as npimport matplotlib.pyplot as plt# Model ParametersK 3T 4a -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) * ykyk yk1data.append(yk1) Ts * b * uk# 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()

https://www.halvorsen.blogTransfer FunctionsHans-Petter Halvorsen

Transfer Functions Transfer functions are a model formbased on the Laplace transform. Transfer functions are very useful inanalysis and design of linear dynamicsystems. You can create Transfer Functions bothwith SciPy.signal and the Python ControlSystems Library

1.order Transfer FunctionsA 1.order transfer function is given by:𝑦(𝑠)𝐾𝐻 𝑠 𝑒(𝑠) 𝑇𝑠 1Where 𝐾 is the Gain and 𝑇 is the Time constantIn the time domain we get the followingequation (using Inverse Laplace):𝑦 𝑑 πΎπ‘ˆ(1 )(𝑒 *)(After a Step π‘ˆ for the unput signal 𝑒(𝑠))Output SignalInput Signal𝑒(𝑠)DifferentialEquation𝐻 𝑠𝑦(𝑠)1𝑦̇ ( 𝑦 𝐾𝑒)𝑇We ca find the Transfer function fromthe Differential Equation using Laplace

1.order – Step Response100%𝑦(𝑑)πΎπ‘ˆπ‘¦ 𝑑 63%0/1πΎπ‘ˆ(1 𝑒 )𝑦(𝑠)𝐾𝐻 𝑠 𝑒(𝑠) 𝑇𝑠 1𝑑𝑇

PythonTransfer Function:3𝐻(𝑠) 4𝑠 1import controlimport numpy as npimport matplotlib.pyplot as pltK T numden34 np.array([K]) np.array([T , 1])H control.tf(num , den)print ('H(s) ', H)t, y control.step response(H)plt.plot(t,y)plt.title("Step Response")

https://www.halvorsen.blogState-space ModelsHans-Petter Halvorsen

State-space ModelsSystemA general State-space Model is given by:π‘₯Μ‡ 𝐴π‘₯ 𝐡𝑒𝑦 𝐢π‘₯ 𝐷𝑒Note that π‘₯Μ‡ is the same as!"!#𝑒InputInternalStatesπ‘₯Output𝑦𝐴, 𝐡, 𝐢 and 𝐷 are matricesπ‘₯, π‘₯,Μ‡ 𝑒, 𝑦 are vectors A state-space model is a structured form or representation of a set of differentialequations. State-space models are very useful in Control theory and design. Thedifferential equations are converted in matrices and vectors. You can create State.space Models both with SciPy.signal and the Python Control SystemsLibrary

Basic ExampleGiven the following System: We want to put the equations on the following form:π‘₯Μ‡ & π‘₯ π‘₯Μ‡ π‘₯ 𝑒𝑦 π‘₯&This gives the following State-space Model:π‘₯Μ‡ *0 1 π‘₯*0 𝑒π‘₯π‘₯Μ‡ ,0 1 ,1π‘₯*𝑦 1 0 π‘₯,π‘₯Μ‡ 𝐴π‘₯ 𝐡𝑒𝑦 𝐢π‘₯ 𝐷𝑒Where:0𝐴 01 1𝐢 10π‘₯Μ‡ π‘₯Μ‡ !π‘₯Μ‡ &𝐡 01𝐷 0π‘₯!π‘₯ π‘₯&

PythonWe have the differential equations:1π‘₯Μ‡ ! π‘₯! 𝐾𝑒𝑇π‘₯Μ‡ & 0𝑦 π‘₯!The State-space Model becomes:1𝐾π‘₯π‘₯Μ‡ !! 𝑇 0 π‘₯ 𝑇 𝑒π‘₯Μ‡ &&0 00𝑦 1π‘₯!0 π‘₯&Here we use the following function:t, y sig.step(sys, x0, t)import scipy.signal as sigimport matplotlib.pyplot as pltimport numpy as np#Simulation Parametersx0 [0,0]start 0stop 30step 1t np.arange(start,stop,step)K 3T 4# State-space ModelA [[-1/T, 0],[0, 0]]B [[K/T],[0]]C [[1, 0]]D 0sys sig.StateSpace(A, B, C, D)# Step Responset, y sig.step(sys, x0, t)# Plottingplt.plot(t, y)plt.title("Step plt.show()

PythonState-space Model:1π‘₯Μ‡ ! 𝑇π‘₯Μ‡ "0𝑦 1𝐾0 π‘₯! 𝑇 𝑒π‘₯"00π‘₯!0 π‘₯"We want to find the Transfer Function:𝑦(𝑠)𝐻 𝑠 𝑒(𝑠)TransferFunctionContinuous(array([0.75, 0. ]),array([1. , 0.25, 0. ]),dt: None)Python give us the following:0.75𝐻(𝑠) 𝑠 0.253𝐻(𝑠) 4𝑠 1Which is the same asimport scipy.signal as sigimport matplotlib.pyplot as pltimport numpy as np#Simulation Parametersx0 [0,0]start 0; stop 30; step 1t np.arange(start,stop,step)K 3; T 4# State-space ModelA [[-1/T, 0],[0, 0]]B [[K/T],[0]]C [[1, 0]]D 0sys sig.StateSpace(A, B, C, D)H sys.to tf()print(H)# Step Responset, y sig.step(H, x0, t)# Plottingplt.plot(t, y)plt.title("Step Response")plt.xlabel("t"); plt.ylabel("y")plt.grid()plt.show()

https://www.halvorsen.blogFrequency ResponseHans-Petter Halvorsen

Frequency Response The Frequency Response is an important tool forAnalysis and Design of signal filters and foranalysis and design of Control Systems The frequency response can be found from atransfer function model The Bode diagram gives a simple Graphicaloverview of the Frequency Response for a givensystem The Bode Diagram is tool for Analyzing theStability properties of the Control System.

PythonTransfer Function Example:import numpy as npimport scipy.signal as signalimport matplotlib.pyplot as pltSciPy.signal3(2𝑠 1)𝐻 𝑠 (3𝑠 1)(5𝑠 1)# Define Transfer Functionnum1 np.array([3])num2 np.array([2, 1])num np.convolve(num1, num2)den1 np.array([3, 1])den2 np.array([5, 1])den np.convolve(den1, den2)H signal.TransferFunction(num, den)print ('H(s) ', H)# Frequenciesw start 0.01w stop 10step 0.01N int ((w stop-w start )/step) 1w np.linspace (w start , w stop , N)# Bode Plotw, mag, phase signal.bode(H, w)plt.figure()plt.subplot (2, 1, 1)plt.semilogx(w, mag)# Bode Magnitude Plotplt.title("Bode Plot")plt.grid(b None, which 'major', axis 'both')plt.grid(b None, which 'minor', axis 'both')plt.ylabel("Magnitude (dB)")plt.subplot (2, 1, 2)plt.semilogx(w, phase) # Bode Phase plotplt.grid(b None, which 'major', axis 'both')plt.grid(b None, which 'minor', axis 'both')plt.ylabel("Phase (deg)")plt.xlabel("Frequency (rad/sec)")plt.show()

PythonTransfer Function Example:3(2𝑠 1)𝐻 𝑠 (3𝑠 1)(5𝑠 1)Python Control Systems Libraryimport numpy as npimport control# Define Transfer Functionnum1 np.array([3])num2 np.array([2, 1])num np.convolve(num1, num2)den1 np.array([3, 1])den2 np.array([5, 1])den np.convolve(den1, den2)H control.tf(num, den)print ('H(s) ', H)# Bode Plotcontrol.bode(H, dB True)

https://www.halvorsen.blogPID ControlHans-Petter Halvorsen

Control SystemThe purpose with a Control System is to Control a Dynamic System, e.g., an industrialprocess, an airplane, a self-driven car, etc. (a Control System is β€œeverywhereβ€œ).PID ControllerReferenceValueπ‘Ÿπ‘’ 𝑦Controller𝑒ControlSignalProcess𝑦

PID The PID Controller is the most usedcontroller today It is easy to understand andimplement There are few Tuning Parameters

The PID Algorithm&𝐾#( π‘’π‘‘πœ 𝐾# 𝑇' 𝑒̇𝑒 𝑑 𝐾# 𝑒 𝑇 %Where 𝑒 is the controller output and 𝑒 is thecontrol error:𝑒 𝑑 π‘Ÿ 𝑑 𝑦(𝑑)π‘Ÿ is the Reference Signal or Set-point𝑦 is the Process value, i.e., the Measured valueTuning Parameters:𝐾!𝑇"𝑇#Proportional GainIntegral Time [sec. ]Derivative Time [sec. ]

Discrete PI ControllerWe start with the continuous PI Controller:𝐾! 𝑒 𝑑 𝐾! 𝑒 π‘’π‘‘πœπ‘‡" #We derive both sides in order to removethe Integral:𝑒̇ 𝐾( 𝑒̇ 𝐾(𝑒𝑇)We can use the Euler Backward Discretization method:π‘₯Μ‡ π‘₯ π‘˜ π‘₯ π‘˜ 1𝑇%Where 𝑇' is the Sampling TimeThen we get:𝑒& 𝑒&'(𝑒& 𝑒&'( 𝐾! 𝐾! 𝑒𝑇%𝑇%𝑇" &Finally, we get:𝑒4 𝑒4/6 𝐾C 𝑒4 𝑒4/6Where 𝑒* π‘Ÿ* 𝑦*𝐾C 𝑇7 𝑒4𝑇D

Control System SimulationsPI Controller:Discrete Version (Ready to implement in Python):𝐾, /( π‘’π‘‘πœπ‘’ 𝑑 𝐾, 𝑒 𝑇- .𝑒4 π‘Ÿ4 𝑦4𝑒4 𝑒4/6 𝐾C 𝑒4 𝑒4/6𝐾C 𝑇7 𝑒4𝑇DProcess (1.order system):𝑦̇ π‘Žπ‘¦ 𝑏𝑒Where π‘Ž !"and 𝑏 #Discrete Version (Ready to implement in Python):𝑦()* (1 𝑇 π‘Ž)𝑦( 𝑇 𝑏𝑒("In the Python code we can set 𝐾 3 and 𝑇 4

import numpy as npimport matplotlib.pyplot as plt#KTabModel Parameters 3 4 -(1/T) K/T# Simulation ParametersTs 0.1 # Sampling TimeTstop 20 # End of Simulation TimeN int(Tstop/Ts) # Simulation lengthy np.zeros(N 2) # Initialization the Tout vectory[0] 0 # Initial Vaue# PI Controller SettingsKp 0.5Ti 5r 5 # Reference valuee np.zeros(N 2) # Initializationu np.zeros(N 2) # Initialization# Simulationfor k in range(N 1):e[k] r - y[k]u[k] u[k-1] Kp*(e[k] - e[k-1]) (Kp/Ti)*Ts*e[k]y[k 1] (1 Ts*a)*y[k] Ts*b*u[k]# Plot the Simulation Resultst np.arange(0,Tstop 2*Ts,Ts) #Create the Time SeriesPython# Plot Process Valueplt.figure(1)plt.plot(t,y)# Formatting the appearance of the Plotplt.title('Control of Dynamic System')plt.xlabel('t [s]')plt.ylabel('y')plt.grid()xmin 0xmax Tstopymin 0ymax 8plt.axis([xmin, xmax, ymin, ymax])plt.show()# Plot Control Signalplt.figure(2)plt.plot(t,u)# Formatting the appearance of the Plotplt.title('Control Signal')plt.xlabel('t [s]')plt.ylabel('u [V]')plt.grid()

Python

https://www.halvorsen.blogStability AnalysisHans-Petter Halvorsen

Stability AnalysisPoles:Unstable SystemImMarginally Stable SystemImAsymptotically Stable SystemImReReReStep Response:𝑑lim 𝑦 𝑑 π‘˜ *Frequency Response:πœ” πœ”(,#𝑑0 lim 𝑦 𝑑 *πœ” πœ”(,#𝑑lim 𝑦 𝑑 *πœ” πœ”(,#

Stability Analysis Exampleπ‘ŸπΎ! (𝑇" 𝑠 1)𝐻 𝑠 𝑇" 𝑠𝑒 𝑦FControllerFilter𝐻. 𝑠 𝑒3𝐻! 𝑠 4𝑠 11𝑇. 𝑠 1Processπ‘₯Sensor𝐻-1𝑠 𝑇- 𝑠 1In Stability Analysis we use the following Transfer Functions:Loop Transfer Function: 𝐿 𝑠 𝐻 (𝑠)𝐻! (𝑠)𝐻- (𝑠)𝐻. (𝑠)Tracking Transfer Function: 𝑇(𝑠) /(%)2(%) 3(%)(43(%)

import numpy as npimport matplotlib.pyplot as pltimport control# Tracking transfer functionT control.feedback(L,1)print ('T(s) ', T)# Transfer Function ProcessK 3; T 4num p np.array ([K])den p np.array ([T , 1])Hp control.tf(num p , den p)print ('Hp(s) ', Hp)# Step Response Feedback System (Tracking System)t, y control.step ep Response Feedback System T(s)")plt.grid()# Transfer Function PI ControllerKp 0.4Ti 2num c np.array ([Kp*Ti, Kp])den c np.array ([Ti , 0])Hc control.tf(num c, den c)print ('Hc(s) ', Hc)# Bode Diagram with Stability Marginsplt.figure(2)control.bode(L, dB True, deg True, margins True)# Transfer Function MeasurementTm 1num m np.array ([1])den m np.array ([Tm , 1])Hm control.tf(num m , den m)print ('Hm(s) ', Hm)# Transfer Function Lowpass FilterTf 1num f np.array ([1])den f np.array ([Tf , 1])Hf control.tf(num f , den f)print ('Hf(s) ', Hf)# The Loop Transfer functionL control.series(Hc, Hp, Hf, Hm)print ('L(s) ', L)# Poles and Zeroscontrol.pzmap(T)p control.pole(T)z control.zero(T)print("poles ", p)# Calculating stability margins and crossover frequenciesgm , pm , w180 , wc control.margin(L)# Convert gm to Decibelgmdb 20 * np.log10(gm)print("wc ", f'{wc:.2f}', "rad/s")print("w180 ", f'{w180:.2f}', "rad/s")print("GM ", f'{gm:.2f}')print("GM ", f'{gmdb:.2f}', "dB")print("PM ", f'{pm:.2f}', "deg")# Find when Sysem is Marginally Stable (Kritical Gain Kc Kp*gmprint("Kc ", f'{Kc:.2f}')Kc)

𝐾( 0.4𝑇) 2𝑠ResultsFrequency ResponseGain Margin (GM): Δ𝐾 11. 𝑑𝐡Phase Margin (PM): Ο† 30 This means that we can increase𝐾# a bit without problemPolesStep ResponseAs you see we have an Asymptotically Stable SystemThe Critical Gain is 𝐾 𝐾( Δ𝐾 1.43

ConclusionsWe have an Asymptotically Stable System when 𝐾! 𝐾 We have Poles in the left half plane lim 𝑦 𝑑 1 (Good Tracking) * πœ” πœ”(,#We have a Marginally Stable System when 𝐾! 𝐾 We have Poles on the Imaginary Axis 0 lim 𝑦 𝑑 * πœ” πœ”(,#We have an Unstable System when 𝐾! 𝐾 We have Poles in the right half plane lim 𝑦 𝑑 * πœ” πœ”(,#

Additional Tutorials/Videos/TopicsWant to learn more? Some Examples: Transfer Functions with Python State-space Models with PythonVideos available Frequency Response with Pythonon YouTube PID Control with Python Stability Analysis with Python Frequency Response Stability Analysis with Python Logging Measurement Data to File with Python Control System with Python – Exemplified using Small-scaleIndustrial Processes and Simulators DAQ Systems ng/python/

Additional Python ramming/python/

Hans-Petter HalvorsenUniversity of South-Eastern Norwaywww.usn.noE-mail: hans.p.halvorsen@usn.noWeb: https://www.halvorsen.blog

Introduction to Control Engineering Python Libraries useful in Control Engineering Applications –NumPy, Matplotlib . The Python Control Systems Library (control) is a Python package that implements basic operations for analysis