Module : 5 Python for Control Systems (7hours) Simulation of Control Systems: Using Python for system
simulation. Libraries for Control Systems: Introduction to libraries such as SciPy for control system
analysis.
System Simulation
A simulation is a representation of a real-world system. One can use mathematical or
computational models of this system to study how it works, or what happens when parts of it are
changed. Simulations are used in airports, restaurants, mechanics, government agencies, and many
other systems where poor resource allocation can lead to congestion, customer dissatisfaction, and
critical transportation delays.
A system can be any environment where things happen. Examples of real-world systems include
car washes, banks, manufacturing plants, airports, post offices, call centers, and more. These
systems have agents that undergo processes within them. For instance:
· A car wash will have cars go through the washing process.
· An airport will have passengers go through the security check process.
· A call center will have customers go through the process of speaking with a telemarketer.
How Simulation Works
In Python, you can use the simpy framework for event simulation. First, take a quick look at how
a simulated process would run in Python. Below is a code snippet from a simulation of a security
checkpoint system. The following three lines of code set up the environment, pass all necessary
functions, and run the simulation:
# Set up the environment
env = [Link]()
# Assume you've defined checkpoint_run() beforehand
[Link](checkpoint_run(env, num_booths, check_time, passenger_arrival))
# Let's go!
[Link](until=10)
The first line of code above establishes the environment. You’ll do this by
assigning [Link]() to the desired variable Here, it’s simply named env. This
tells simpy to create an environment object named env that will manage the simulation time and
move the simulation through each subsequent time step.
Once you have your environment established, you’ll pass in all of the variables that will act as
your parameters. These are the things you can vary to see how the system will react to changes.
For this security checkpoint system, you’re using the following parameters:
1. env: the environment object to schedule and process events
2. num_booths: the number of ID check booths
3. check_time: the length of time it takes to check a passenger’s ID
4. passenger_arrival: the rate at which passengers arrive at the queue
Then, it’s time to run the simulation! You can do this by calling [Link]() and specifying how long
you want the simulation to run for. The simulation runs in minutes, so this sample code will run
the simulation for 10 real-time minutes.
here are the three steps to running a simulation in Python:
1. Establish the environment.
2. Pass in the parameters.
3. Run the simulation.
But there’s a lot more going on underneath the hood! You’ll need to understand how to choose
those parameters, and you’ll have to define all the functions that will be called when the simulation
is run
SimPy is a powerful, open-source Python library for discrete-event simulation (DES). It is
primarily used for modeling systems where changes happen at specific, distinct moments in time,
rather than for continuous control systems.
What is SimPy?
SimPy provides a framework to simulate active components (like customers, vehicles, or
messages) as parallel processes using Python's generator functions.
Key features include:
· Process-based modeling: System components are modeled as processes that interact with
their environment and each other via events.
· Event-driven time management: SimPy's environment manages a simulation clock,
intelligently jumping from one event to the next, rather than simulating every moment of
real time.
· Resource management: It offers built-in resource types (Resource, Container, Store) to
model limited-capacity congestion points (e.g., a server, a machine, or a queue).
· Interruption handling: Processes can be interrupted by other processes, allowing for the
modeling of complex interactions and prioritization logic.
How it is used in a control system?
SimPy is generally not used for modeling continuous control systems (like those involving
feedback loops with differential equations, which are typically handled by tools like MATLAB's
Simulink); it has no built-in features to support continuous simulations.
Instead, its primary use in the context of systems, which may involve some form of control or
optimization, is in modeling the logic and performance of a system's operational or architectural
control, usually at a high level of abstraction, before implementing the actual control
logic. Specific uses include SimPy provides a framework to simulate active components (like
customers, vehicles, or messages) as parallel processes using Python's generator functions.
Key features include:
· Process-based modeling: System components are modeled as processes that interact
with their environment and each other via events.
· Event-driven time management: SimPy's environment manages a simulation clock,
intelligently jumping from one event to the next, rather than simulating every moment of
real time.
· Resource management: It offers built-in resource types (Resource, Container, Store) to
model limited-capacity congestion points (e.g., a server, a machine, or a queue).
· Interruption handling: Processes can be interrupted by other processes, allowing for the
modeling of complex interactions and prioritization logic.
How it is used in a control system context
SimPy is generally not used for modeling continuous control systems (like those involving
feedback loops with differential equations, which are typically handled by tools like MATLAB's
Simulink); it has no built-in features to support continuous simulations.
Instead, its primary use in the context of systems, which may involve some form of control or
optimization, is in modeling the logic and performance of a system's operational or
architectural control, usually at a high level of abstraction, before implementing the actual
control logic.
Specific uses include:
· Performance modeling and optimization: Engineers use SimPy to test and evaluate
different control strategies in a risk-free virtual environment. For example, simulating
different supply chain management strategies (e.g., "just-in-time" vs. "bulk purchasing")
to find the most efficient approach.
· Resource allocation: It is used to design and optimize systems where limited resources
need to be managed effectively. This could involve determining the optimal number of
servers in a data center or staff at a service desk to meet performance goals (e.g., average
wait time).
· System architecture validation: In fields like chip design, SimPy is used to model
complex on-chip interconnects and system-on-chip (SoC) architectures to identify
potential issues like deadlocks or bottlenecks before committing to expensive hardware
development.
· Testing decision-making logic: By modeling agents and their interactions, developers
can test the effectiveness of various decision-making algorithms (routing logic,
scheduling policies) and measure key performance metrics to inform real-world control
systems
Uses of SimPy:
SimPy is widely used to simulate real-world processes in a variety of domains, including:
· Manufacturing and supply chain management
· Traffic and Transportation
· Healthcare and medical systems
· Computer systems and networks
· Finance and economics
SimPy can help in optimizing and improving these processes by allowing analysts and engineers
to test and evaluate different scenarios in a risk-free virtual environment. SimPy can also be used
to predict the behaviour of complex systems, which can be useful in making informed decisions.
Prerequisites:
To use SimPy, you need to have a good understanding of Python programming language and basic
knowledge of probability theory. Knowledge of statistics and queueing theory is also helpful.
SimPy Code Example:
Let’s look at an example of using SimPy to simulate a simple queuing system. In this system,
customers arrive at a service centre and wait in line to be served by a single server. The simulation
will generate random inter-arrival times and service times to simulate a real-world process.
import simpy
import random
# Define the service center
class ServiceCenter:
def __init__(self, env):
[Link] = [Link](env, capacity=1)
def serve_customer(self, customer):
service_time = [Link](0.5)
yield [Link](service_time)
# Define the customer
def customer(env, name, service_center):
print(f'{name} arrived at {[Link]}')
with service_center.[Link]() as request:
yield request
print(f'{name} started being served at {[Link]}')
yield [Link](service_center.serve_customer(name))
print(f'{name} finished being served at {[Link]}')
# Define the simulation
def simulation(env, service_center):
i=0
while True:
i += 1
[Link](customer(env, f'Customer {i}', service_center))
inter_arrival_time = [Link](0.2)
yield [Link](inter_arrival_time)
# Run the simulation
env = [Link]()
service_center = ServiceCenter(env)
[Link](simulation(env, service_center))
[Link](until=20)
Output:
Customer 1 arrived at 0
Customer 1 started being served at 0
Customer 1 finished being served at 0.7177599203882269
Customer 2 arrived at 1.080941720826772
Customer 2 started being served at 1.080941720826772
Customer 2 finished being served at 1.3288283392409
Customer 3 arrived at 6.3360360795964255
Customer 3 started being served at 6.3360360795964255
Customer 3 finished being served at 7.317214535559814
Customer 4 arrived at 14.449912929380302
Customer 4 started being served at 14.449912929380302
Customer 4 finished being served at 15.254367767875237
SciPY
SciPy provides foundational numerical algorithms that are essential for control systems
engineering, but the specialized functions for control analysis and design are found in the
dedicated Python Control Systems Library (often imported as control or ct) which builds
heavily on SciPy and NumPy.
SciPy's Role in Control Systems
SciPy offers several sub-packages that are indirectly used in control systems analysis and design:
· [Link]: Used for solving ordinary differential equations (ODEs), which is
fundamental to simulating the time response of dynamic systems (e.g.,
using solve_ivp or odeint).
· [Link]: Provides highly optimized linear algebra routines (e.g., eigenvalue problems,
matrix decompositions) crucial for state-space analysis, stability analysis, and controller
design methods like the Linear Quadratic Regulator (LQR).
· [Link]: Algorithms for optimization are used in optimal control problems and
system identification (e.g., minimizing error functions or finding optimal parameters).
· [Link]: Offers filtering and Fourier transform functions (fft, convolve, filter design tools
like butter for Butterworth filters), useful for signal processing aspects of control systems,
such as analyzing frequency content or filtering sensor data.
The Python Control Systems Library
For direct control systems functionality, the external Python Control Systems Library is the
standard tool in the Python ecosystem. This library specifically implements control-oriented
operations, leveraging SciPy's underlying numerical power.
Key capabilities of the python-control library include:
· System Representation: Handling linear input/output systems in both state-space and
frequency domains.
· Time Response: Computing and visualizing step, impulse, and forced responses.
· Frequency Response: Generating Bode, Nyquist, and Nichols plots.
· Analysis: Tools for stability analysis, root locus plots, and calculating stability margins.
· Design: Functions for eigenvalue placement, LQR design.
Major Sub-packages and Modules
Module Description Common Functions
[Link] Optimization and root finding. minimize(),curve_fit(), root().
[Link] Numerical integration and quad() (single integral),
ODE solvers. solve_ivp() (ODEs).
[Link] Advanced linear algebra inv(), det(), eig()
routines. (eigenvalues).
[Link] Statistical distributions and norm, ttest_ind(), describe().
tests.
[Link] Signal processing tools. butter() (filters), convolve(),
find_peaks()
[Link] Data interpolation and splines. interp1d(), UnivariateSpline()
[Link] Fast Fourier Transform fft(), ifft().
algorithms.
[Link] Sparse matrices and related csr_matrix(), csc_matrix().
routines.
Basic Functions:
Interaction with NumPy:
SciPy builds on NumPy and therefore you can make use of NumPy functions itself to handle
arrays. To know in-depth about these functions, you can simply make use of help(), info() or
source() functions.
help():
To get information about any function, you can make use of the help() function. There are two
ways in which this function can be used:
· without any parameters
· using parameters
from scipy import cluster
help(cluster) #with parameter
help() #without parameter
When you execute the above code, the first help() returns the information about
the cluster submodule. The second help() asks the user to enter the name of any module, keyword,
etc for which the user desires to seek information. To stop the execution of this function, simply
type ‘quit’ and hit enter.
info():
This function returns information about the desired functions, modules, etc.
[Link](cluster)
source():
[Link](cluster)
The source code is returned only for objects written in Python. This function does not return useful
information in case the methods or objects are written in any other language such as C. However
in case you want to make use of this function, you can do it as follows:
Special Functions:
SciPy provides a number of special functions that are used in mathematical physics such as elliptic,
convenience functions, gamma, beta, etc. To look for all the functions, you can make use of help()
function as described earlier.
[Link](cluster)
Exponential and Trigonometric Functions:
SciPy’s Special Function package provides a number of functions through which you can find
exponents and solve trigonometric problems.
Consider the following example:
EXAMPLE:
from scipy import special
a = special.exp10(3)
print(a)
b = special.exp2(3)
print(b)
c = [Link](90)
print(c)
d = [Link](45)
print(d)
OUTPUT:
1000.0
8.0
1.0
0.7071067811865475
There are many other functions present in the special functions package of SciPy that you can try
for yourself.
Integration Functions:
SciPy provides a number of functions to solve integrals. Ranging from ordinary differential
integrator to using trapezoidal rules to compute integrals, SciPy is a storehouse of functions to
solve all types of integrals problems.
General Integration:
SiPy provides a function named quad to calculate the integral of a function which has one variable.
The limits can be ±∞ (± inf) to indicate infinite limits. The syntax of the quad() function is as
follows:
SYNTAX:
quad(func, a, b, args=(), full_output=0, epsabs=1.49e-08, epsrel=1.49e-08, limit=50,
points=None, weight=None, wvar=None, wopts=None, maxp1=50, limlst=50)
Here, the function will be integrated between the limits a and b (can also be infinite).
EXAMPLE:
from scipy import special
from scipy import integrate
a= lambda x:special.exp10(x)
b = [Link](a, 0, 1)
print(b)
In the above example, the function ‘a’ is evaluated between the limits 0, 1. When this code is
executed, you will see the following output.
OUTPUT:
(3.9086503371292665, 4.3394735994897923e-14)