Python For Control Engineering
Python For Control Engineering
Python For Control Engineering
Engineering
Hans-Petter Halvorsen
https://www.halvorsen.blog
Python for Control Engineering
Python for Control Engineering
Hans-Petter Halvorsen
2020
Python for Control Engineering
Hans-Petter
c Halvorsen
1
Preface
Python is a popular programming language, and it is one of the most used pro-
gramming languages today.
Python works on all the main platforms and operating systems used today, such
Windows, macOS, and Linux.
Here you find lots of technical resources about Technology, Programming, Soft-
ware Engineering, Automation and Control, Industrial IT, etc.
https://www.halvorsen.blog/documents/programming/python/
These resources are a supplement to this textbook. Here you can download the
software, download code examples, etc.
LATEXis a document preparation system used for the communication and publi-
cation of scientific documents.
2
For more information about LATEX:
https://www.latex-project.org
Python Books
You find other Python textbooks within different domains on my Python Web
page:
https://www.halvorsen.blog/documents/programming/python/
Python Books:
3
Video Resources
In addition to the textbooks mentioned, lots of videos explaining and comple-
ments the different Python topics and examples within the textbook have been
made. These are both available on my website and on YouTube.
Blog:
https://www.halvorsen.blog
Python Resources:
https://www.halvorsen.blog/documents/programming/python/
Programming
The way we create software today has changed dramatically the last 30 years,
from the childhood of personal computers in the early 80s to today’s powerful
devices such as Smartphones, Tablets and PCs.
The Internet has also changed the way we use devices and software. We still
have traditional desktop applications, but Web Sites, Web Applications and so-
called Apps for Smartphones, etc. are dominating the software market today.
We need to find and learn Programming Languages that are suitable for the
New Age of Programming.
4
in today’s software market.
Software Engineering
Software Engineering is the discipline for creating software applications. A
systematic approach to the design, development, testing, and maintenance of
software.
• Planning
• Requirements Analysis
• Design
• Implementation
• Testing
5
6
Contents
2 What is Python? 21
2.1 Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.1 Interpreted vs. Compiled . . . . . . . . . . . . . . . . . . 22
2.2 Python Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2.1 Python Packages for Science and Numerical Computations 24
2.3 Anaconda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.4.1 Python IDLE . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.4.2 Visual Studio Code . . . . . . . . . . . . . . . . . . . . . . 26
2.4.3 Thonny . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4.4 Spyder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4.5 Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4.6 PyCharm . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.4.7 Wing Python IDE . . . . . . . . . . . . . . . . . . . . . . 27
2.4.8 Jupyter Notebook . . . . . . . . . . . . . . . . . . . . . . 27
2.5 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.6 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.6.1 Python Windows 10 Store App . . . . . . . . . . . . . . . 28
2.6.2 Installing Anaconda . . . . . . . . . . . . . . . . . . . . . 29
2.6.3 Installing Visual Studio Code . . . . . . . . . . . . . . . . 29
7
3.5.3 Run Python Scripts from the Command Prompt in Win-
dows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.5.4 Run Python Scripts from Spyder . . . . . . . . . . . . . . 37
II Python Programming 54
5 Python Programming 55
5.1 If ... Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.2 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.3 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.3.1 Nested For Loops . . . . . . . . . . . . . . . . . . . . . . . 61
5.4 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
8
10 Error Handling in Python 83
10.1 Introduction to Error Handling . . . . . . . . . . . . . . . . . . . 83
10.1.1 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . 83
10.1.2 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 83
10.2 Exceptions Handling . . . . . . . . . . . . . . . . . . . . . . . . . 84
11 Debugging in Python 86
14 Anaconda 92
14.1 Anaconda Navigator . . . . . . . . . . . . . . . . . . . . . . . . . 92
14.2 Anaconda Prompt . . . . . . . . . . . . . . . . . . . . . . . . . . 92
IV Python Editors 95
15 Python Editors 96
16 Spyder 98
16.1 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
9
19 Linear Algebra in Python 118
19.1 Introduction to Linear Algebra . . . . . . . . . . . . . . . . . . . 118
19.2 Linear Algebra with Python . . . . . . . . . . . . . . . . . . . . . 119
19.2.1 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
19.2.2 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
19.2.3 Linear Algebra (numpy.linalg) . . . . . . . . . . . . . . . . 121
19.2.4 Matrix Addition . . . . . . . . . . . . . . . . . . . . . . . 121
19.2.5 Matrix Subtraction . . . . . . . . . . . . . . . . . . . . . . 122
19.2.6 Matrix Multiplication . . . . . . . . . . . . . . . . . . . . 124
19.2.7 Transpose of a Matrix . . . . . . . . . . . . . . . . . . . . 126
19.2.8 Determinant . . . . . . . . . . . . . . . . . . . . . . . . . 127
19.2.9 Inverse Matrix . . . . . . . . . . . . . . . . . . . . . . . . 128
19.3 Solving Linear Equations . . . . . . . . . . . . . . . . . . . . . . 129
19.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
22 Optimization 153
10
27.2 Introduction to Real-Time Plotting . . . . . . . . . . . . . . . . . 184
27.3 Real-Time Plotting with Animation . . . . . . . . . . . . . . . . 186
27.3.1 Speeding Up the Plot Animation . . . . . . . . . . . . . . 188
11
32 Frequency Response 239
32.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
32.1.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
32.2 Bode Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
XI Resources 263
38 Python for MATLAB Users 264
38.1 Use Python inside MATLAB . . . . . . . . . . . . . . . . . . . . 265
38.2 Calling MATLAB from Python . . . . . . . . . . . . . . . . . . . 266
12
39 Python Resources 268
39.1 Python Distributions . . . . . . . . . . . . . . . . . . . . . . . . . 268
39.2 Python Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
39.3 Python Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
39.4 Python Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
39.5 Python in Visual Studio . . . . . . . . . . . . . . . . . . . . . . . 269
13
Part I
14
Chapter 1
Introduction
With this textbook you will learn basic Python programming. The textbook
contains lots of examples and self-paced tasks that the users should go through
and solve in their own pace.
The Internet has also changed the way we use devices and software. We still
have traditional desktop applications, but Web Sites, Web Applications and so-
called Apps for Smartphones, etc. are dominating the software market today.
We need to find and learn Programming Languages that are suitable for the
New Age of Programming.
15
Figure 1.1: Web Site - Python
Python has during the last 10 years become more and more popular. Today,
Python has become one of the most popular Programming Languages.
There are many different rankings regarding which programming language which
is most popular. In most of these ranking, Python is in top 10.
One of these rankings is the IEEE Spectrum’s ranking of the top programming
languages [3].
From this ranking we see that Python is the most popular Programming Lan-
guage in 2018. See Figure 1.2
As we see in Figure 1.2 they categorize the different Programming Languages
into the following categories:
• Web
16
Figure 1.2: The Most Popular Programming Languages
• Mobile
• Enterprise
• Embedded
According to Figure 1.2 we see that Python can be used to program Web Ap-
plications, Enterprise Applications and Embedded Applications.
So far Python is not used or not optimized for creating Mobile Applications. We
have today 2 major Mobile platforms; iOS Applications are mainly programmed
with the Swift Programming language, while Android Applications are mainly
programmed with either Java or Kotlin.
Another survey is the ”Stack Overflow Developer Survey 2018” [4]. See Figure
1.3.
As we can see from [5] and Figure 1.4, Python becomes more and more popular
year by year.
Based on Figure 1.4, the source [5] try to predict the future of Python, see
Figure 1.5.
Based on the surveys and statistics mention above, obviously Python is a pro-
gramming language that you should learn.
Lets summarize:
• Python is fun to learn and use and it is also named after the British
comedy group called Monty Python.
• Python has a simple and flexible code structure and the code is easy to
read.
17
Figure 1.3: The Top Programming Languages - Stack Overflow Survey
18
Figure 1.4: The Incredible Growth of Python
• Databases (such as SQL Server and MySQL) and using the Structured
Query Language (SQL) or the upcoming NoSQL databases
• App Development for the 2 main platforms iOS (XCode using the Swift
Programming Language) and Android (Android Studio using the Java
Programming Language or Kotlin Programming language)
If you have skills in most of the tools, programming languages and frameworks
mention above, you are well suited for working as a full-time programmer or
software engineer.
1.2 MATLAB
If you are looking for MATLAB, please see the following:
https://www.halvorsen.blog/documents/programming/matlab/
19
Figure 1.5: The Future of Python
20
Chapter 2
What is Python?
But this is just the Python core, i.e. the interpreter a very basic editor, and the
minimum needed to create basic Python programs.
Typically you will need more features for solving your tasks. Then you can in-
stall and use separate Python packages created by third parties. These packages
need to be downloaded and installed separately (typically you use something
called PIP), or you choose to use, e.g., a distribution package like Anaconda.
21
Figure 2.1: IDLE - Basic Python Editor
you write Python (.py) files in a text editor and then put those files into the
python interpreter to be executed. Depending on the Editor you are using, this
is either done automatically, or you need to do it manually.
22
With interpreted languages, the code is saved in the same format that you en-
tered. Compiled programs generally run faster than interpreted ones because
interpreted programs must be reduced to machine instructions at run-time. It
is usually easier to develop applications in an interpreted environment because
you don’t have to recompile your application each time you want to test a small
section.
Compiled languages are all translated by running the source code through a
compiler. This results in very efficient code that can be executed any number of
times. The overhead for the translation is incurred just once, when the source
is compiled; thereafter, it need only be loaded and executed.
During the design of an application, you might need to decide whether to use a
compiled language or an interpreted language for the application source code.
Thus, an interpreted language is generally more suited for doing ”ad hoc” cal-
culations or simulations, while compiled languages are better for permanent
applications where speed is in focus.
This is also typical approach for open source software, because everybody can
create their own Python packages and distribute them. In that way you also
find Python packages for almost everything, from Scientific Computing to Web
Development.
23
These packages need to be downloaded and installed separately, or you choose
to use, e.g., a distribution package like Anaconda, where you typically get the
packages you need for scientific computing. With Anaconda you typically get
the same features as with MATLAB.
Lots of Python packages exists, depending on what you are going to solve.
We have Python packages for Desktop GUI Development, Database Develop-
ment, Web Development, Software Development, etc.
Here you can search for, download and install many hundreds Python Packages
within different topics and applications. You can also make your own Python
Packages and distribute them here.
2.3 Anaconda
Anaconda is a distribution package, where you get Python compiler, Python
packages and the Spyder editor, all in one package.
Anaconda includes Python, the Jupyter Notebook, and other commonly used
packages for scientific computing and data science.
24
They offer a free version (Anaconda Distribution) and a paid version (Enter-
prise) Anaconda is available for Windows, macOS, and Linux
Web:
https://www.anaconda.com
Wikipedia:
https://en.wikipedia.org/wiki/Anaconda( P ythond istribution)
Spyder and the Python packages (NumPy, SciPy, Matplotlib, ...) mention above
+++ are included in the Anaconda Distribution.
Which editor you should use depends on your background, what kind of code
editors you have used previously, your programming skills, what your are going
to develop in Python, etc.
25
Web:
https://www.python.org
Web:
https://code.visualstudio.com
2.4.3 Thonny
Thonny is a Python IDE for beginners. Thonny is a very simple and ba-
sic Python editor which is highly recommended for new Python users. With
Thonny you can easily install Python Libraries/Packages using a Graphical
User Interface without the need of using more cryptic PIP commands in the
Command window/Terminal.
Web: https://thonny.org
Wikipedia: https://en.wikipedia.org/wiki/Thonny
2.4.4 Spyder
Spyder is an open source cross-platform integrated development environment
(IDE) for scientific programming in the Python language.
Web:
https://www.spyder-ide.org
Wikipedia:
https://en.wikipedia.org/wiki/Spyder( sof tware)
26
Visual Studio (from 2017), has integrated support for Python, it is called
”Python Support in Visual Studio”.
Web:
https://visualstudio.microsoft.com
Wikipedia:
https://en.wikipedia.org/wiki/MicrosoftV isualS tudio
2.4.6 PyCharm
PyCharm is cross-platform, with Windows, macOS and Linux versions. The
Community Edition is free to use, while the Professional Edition (paid version)
has some extra features.
Web:
https://www.jetbrains.com/pycharm/
• Wing 101 – a very simplified free version, for teaching beginning pro-
grammers
• Wing Personal – free version that omits some features, for students and
hobbyists
• Wing Pro – a full-featured commercial (paid) version, for professional
programmers
Web:
http://jupyter.org
Wikipedia:
https://en.wikipedia.org/wiki/ProjectJ upyter
27
2.5 Resources
Here are some useful Python resources:
• The official Python Tutorial
- https://docs.python.org/3.7/tutorial/index.html
https://www.python.org
Here you can download the basic Python features in one package, which includes
the Python programming language interpreter, and a basic code editor, or an
integrated development environment, called IDLE. See Figure 2.1
For more advanced Python Programming you typically need a better Code Ed-
itor and additional Packages.
For the basic Python examples in the beginning, the basic Python software
from:
https://www.python.org is good enough.
I suggest you start with the basic Python software in order to learn the basics,
then you can upgrade to a better Editor, install addition Python packages (either
manually or or install Anaconda where ”everything” is included).
The Microsoft Store version of Python 3.7 is a simplified installer for running
scripts and packages.
Microsoft Store version of Python 3.7 is very basic but it’s good enough to run
the simple scripts.
Python 3.7 Microsoft Store edition will receive all updates automatically when
they are released and no manual action is required from your end.
28
In order to install the Microsoft Store version of Python just open Microsoft
Store in Windows 10 and search for Python.
29
Chapter 3
Other Python Editors will be discussed more in detail later. For now you can
use the basic Python IDE (IDLE) or Spyder if you have installed the Anaconda
distribution package.
30
Example 3.2.1. Plotting in Python
Lets open your Python Editor and type the following:
1 p r i n t ( ” H e l l o World ! ” )
Listing 3.1: Hello World Python Example
[End of Example]
You can use Python in different ways, either in ”interactive” mode or in ”Script-
ing” mode.
The python program that you have installed will by default act as something
called an interpreter. An interpreter takes text commands and runs them as
you enter them - very handy for trying things out.
Yo can run Python interactively in different ways either using the Console which
is part of the operating system or the Python IDLE and the Python Shell which
is part of the basic Python installation from https://www.python.org.
Here you type one and one command at a time after the ”>>>” sign in the
Python Shell.
1 >>> p r i n t ( ” H e l l o World ! ” )
The python program that you have installed will by default act as something
called an interpreter. An interpreter takes text commands and runs them as
you enter them - very handy for trying things out.
Below we see how we can run Python from the Console which is part of the OS.
31
3.4.1 Opening the Console on macOS
The standard console on macOS is a program called Terminal. Open Terminal
by navigating to Applications, then Utilities, then double-click the Terminal pro-
gram. You can also easily search for it in the system search tool in the top right.
The command line Terminal is a tool for interacting with your computer. A
window will open with a command line prompt message, something like this:
L a s t l o g i n : Tue Dec 11 0 8 : 3 3 : 5 1 on c o n s o l e
computername : ˜ username
Just type python at your console, hit Enter, and you should enter Python’s
Interpreter.
1 L a s t l o g i n : Tue Dec 11 1 2 : 3 4 : 1 6 on t t y s 0 0 0
2 Hans−P e t t e r −Work−MacBook−A i r : ˜ hansha$ python
3 Python 3 . 6 . 5 | Anaconda , I n c . | ( d e f a u l t , Apr 26 2 0 1 8 , 0 8 : 4 2 : 3 7 )
4 [GCC 4 . 2 . 1 Compatible Clang 4 . 0 . 1 ( t a g s /RELEASE 401/ f i n a l ) ] on
darwin
5 Type ” h e l p ” , ” c o p y r i g h t ” , ” c r e d i t s ” o r ” l i c e n s e ” f o r more
information .
6 >>>
The prompt >>> on the last line indicates that you are now in an interactive
Python interpeter session, also called the “Python shell”. This is different from
the normal terminal command prompt!
You can now enter some code for python to run. Try:
>>> p r i n t ( ” H e l l o World ” )
32
3.4.2 Opening the Console on Windows
Window’s console is called the Command Prompt, named cmd. An easy way to
get to it is by using the key combination Windows+R (Windows meaning the
windows logo button), which should open a Run dialog. Then type cmd and
hit Enter or click Ok.
Just type python in the Command Prompt, hit Enter, and you should enter
Python’s Interpreter. See Figure 3.3.
Note! This is also an option during the setup. While installing you can se-
lect ”Add Python.exe to path”. This option is by default set to ”Off”. To get
that option you need to select ”Customize”, not using the ”Default” installation.
In the window that appears, click Environment Variables. . . near the bottom
right. See Figure 3.4.
33
Figure 3.4: Windows System Properties
In the next window, find and select the user variable named Path and click
Edit. . . to change its value. See Figure 3.5.
Select ”New” and add the path where ”python.exe” is located. See Figure 3.6.
Click Save and open the Command Prompt once more and enter ”python” to
verify it works. See Figure 3.3.
34
Figure 3.5: Windows System Properties
In Figure 3.7 we see how this is done. As you see we can enter many Python
commands that together makes a Python program or Python script.
From the Python Shell you select Run → Run Module or hit F5 in order to run
or execute the Python Script. See Figure 3.8.
35
Figure 3.6: Windows System Properties
The IDLE editor is very basic, for more complicated tasks you typically may
prefer to use another editor like Spyder, Visual Studio Code, etc.
1 $ cd / U s e r s / username / Downloads
2 $ python h e l l o w o r l d . py
Note! Make sure you are at your system command prompt, which will have $
or > at the end, not in Python mode (which has >>> instead)!
1 Hello
2 World
3 How a r e you ?
36
Figure 3.7: Python Script
1 > cd /
2 > cd Temp
3 > python h e l l o w o r l d . py
Note! Make sure you are at your system command prompt, which will have >
at the end, not in Python mode (which has >>> instead)!
1 Hello
2 World
3 How a r e you ?
In the Spyder editor we have the Script Editor to the left and the interactive
Python Shell or the Console window to the right. See See 3.11.
37
Figure 3.8: Running a Python Script
38
Figure 3.11: Running a Python Script in Spyder
39
Chapter 4
1 p r i n t ( ” H e l l o World ! ” )
Listing 4.1: Hello World Python Example
[End of Example]
Press q to close the help window and return to the Python prompt.
4.2 Variables
Variables are defined with the assignment operator, “=”. Python is dynamically
typed, meaning that variables can be assigned without declaring their type, and
that their type can change. Values can come from constants, from computation
involving values of other variables, or from the output of a function.
40
Example 4.2.1. Creating and using Variables in Python
We use the basic IDLE (or another Python Editor) and type the following:
1 >>> x = 3
2 >>> x
3 3
Listing 4.2: Using Variables in Python
Here we define a variable and sets the value equal to 3 and then print the result
to the screen.
[End of Example]
You can write one command by time in the IDLE. If you quit IDLE the variables
and data are lost. Therefore, if you want to write a somewhat longer program,
you are better off using a text editor to prepare the input for the interpreter
and running it with that file as input instead. This is known as creating a script.
Python scripts or programs are save as a text file with the extension .py
As seen in the examples, you can use the print() command in order to show the
values on the screen.
[End of Example]
41
A variable can have a short name (like x and y) or a more descriptive name
(sum, amount, etc).
You don need to define the variables before you use them (like you need to to
in, e.g., C/C++/C).
Figure 4.1 show these examples using the basic IDLE editor.
4.2.1 Numbers
There are three numeric types in Python:
• int
• float
• complex
42
Variables of numeric types are created when you assign a value to them, so in
normal coding you don’t need to bother.
1 x = 1 # int
2 y = 2.8 # float
3 z = 3 + 2j # complex
Listing 4.5: Numeric Types in Python
This means you just assign values to a variable without worrying about what
kind of data type it is.
1 p r i n t ( type ( x ) )
2 p r i n t ( type ( y ) )
3 p r i n t ( type ( z ) )
Listing 4.6: Check Data Types in Python
If you use the Spyder Editor, you can see the data types that a variable has
using the Variable Explorer (Figure 4.2):
[End of Example]
4.2.2 Strings
Strings in Python are surrounded by either single quotation marks, or double
quotation marks. ’Hello’ is the same as ”Hello”.
Strings can be output to screen using the print function. For example: print(”Hello”).
1 a = ” H e l l o World ! ”
2
3 print (a)
4
5 print (a [ 1 ] )
6 print (a [ 2 : 5 ] )
7 print ( len (a) )
8 print ( a . lower () )
43
9 p r i n t ( a . upper ( ) )
10 p r i n t ( a . r e p l a c e ( ”H” , ”J” ) )
11 print (a . s p l i t (” ”) )
Listing 4.7: Strings in Python
As you see in the example, there are many built-in functions form manipulating
strings in Python. The Example shows only a few of them.
Strings in Python are arrays of bytes, and we can use index to get a specific
character within the string as shown in the example code.
[End of Example]
[End of Example]
In another chapter we will learn to create our own functions from scratch.
44
4.4 Python Standard Library
Python allows you to split your program into modules that can be reused in
other Python programs. It comes with a large collection of standard modules
that you can use as the basis of your programs.
The Python Standard Library consists of different modules for handling file
I/O, basic mathematics, etc. You don’t need to install these separately, but you
need to important them when you want to use some of these modules or some
of the functions within these modules.
The math module has all the basic math functions you need, such as: Trigono-
metric functions: sin(x), cos(x), etc. Logarithmic functions: log(), log10(), etc.
Constants like pi, e, inf, nan, etc.
45
We can also write it like this:
1 im po rt math a s mt
2
3 x = 3.14
4 y = mt . s i n ( x )
5
6 print (y)
[End of Example]
There are advantages and disadvantages with the different approaches. In your
program you may need to use functions from many different modules or pack-
ages. If you import the whole module instead of just the function(s) you need
you use more of the computer memory.
Very often we also need to import and use multiple libraries where the different
libraries have some functions with the same name but different use.
Other useful modules in the Python Standard Library are statistics (where
you have functions like mean(), stdev(), etc.)
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/index.html
46
Lots of other packages exists, depending on what you are going to solve.
You will learn the basics features in all these libraries. We will use all of the in
different examples and exercises throughout this textbook.
Example 4.5.1. Using libraries
In this example we use the NumPy library:
1 im po rt numpy a s np
2
3 x = 3
4
5 y = np . s i n ( x )
6
7 print (y)
In this example we use both the math module in the Python Standard Library
and the NumPy library:
1 im po rt math a s mt
2 im po rt numpy a s np
3
4 x = 3
5
6 y = mt . s i n ( x )
7
8 print (y)
9
10
11 y = np . s i n ( x )
12
13 print (y)
Note! As seen in this example we use a function called sin() which exists both
in the math module in the Python Standard Library and the NumPy library.
In this case they give the same results. In this case the following code is not
recommended:
1 from math im por t ∗
2 from numpy imp ort ∗
3
4 x = 3
5
47
6 y = sin (x)
7
8 print (y)
9
10
11 y = sin (x)
12
13 print (y)
In this case it works, but assume you have 2 different functions with the same
name that have different meaning in 2 different libraries.
[End of Example]
Anaconda:
https://www.anaconda.com/distribution/
If you are familiar with MATLAB and basic plotting in MATLAB, using the
Matplotlib is very similar.
The main difference from MATLAB is that you need to import the library,
either the whole library or one or more functions.
For simplicity we import the whole library like this:
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
48
Plotting functions that you will use a lot:
• plot()
• title()
• xlabel()
• ylabel()
• axis()
• grid()
• subplot()
• legend()
• show()
Lets create some basic plotting examples using the Matplotlib library:
This makes the code simpler to read. one problem with this approach appears
assuming we import and use multiple libraries and the different libraries have
some functions with the same name but different use.
49
Figure 4.3: Plotting in Python
[End of Example]
• plot()
• xlabel()
• ylabel()
• show()
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 x = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7]
5
6 y = np . s i n ( x )
7
8 plt . plot (x , y)
9 plt . xlabel ( ’x ’ )
10 plt . ylabel ( ’y ’ )
11 plt . show ( )
50
Figure 4.4: Plotting a Sine function in Python
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt numpy a s np
3
4 xstart = 0
5 x s t o p = 2∗ np . p i
6 increment = 0.1
7
8 x = np . a r a n g e ( x s t a r t , xstop , i n c r e m e n t )
9
10 y = np . s i n ( x )
11
12 plt . plot (x , y)
13 plt . xlabel ( ’x ’ )
14 plt . ylabel ( ’y ’ )
15 plt . show ( )
[End of Example]
4.6.1 Subplots
The subplot command enables you to display multiple plots in the same window.
Typing ”subplot(m,n,p)” partitions the figure window into an m-by-n matrix
of small subplots and selects the subplot for the current plot. The plots are
numbered along the first row of the figure window, then the second row, and so
on. See Figure 4.6.
51
Figure 4.5: Plotting a Sine function in Python - Better Implementation
[End of Example]
52
Figure 4.6: Creating Subplots in Python
4.6.2 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
You should use all the Plotting functions listed below in your code:
• plot()
• title()
• xlabel()
• ylabel()
• axis()
• grid()
• legend()
• show()
[End of Exercise]
53
Part II
Python Programming
54
Chapter 5
Python Programming
We have been through the basics in Python, such as variables, using some basic
built-in functions, basic plotting, etc.
You may come far only using these thins, but to create real applications, you
need to know about and use features like:
• If ... Else
• For Loops
• While Loops
• Arrays ...
If you are familiar with one or more other programming language, these fea-
tures should be familiar and known to you. All programming languages have
these features built-in, but the syntax is slightly different from one language to
another.
55
11 p r i n t ( ” a i s e q u a l t o b” )
Listing 5.1: If
Using If - Else:
1 a = 5
2 b = 8
3
4 if a > b:
5 p r i n t ( ” a i s g r e a t e r than b” )
6 else :
7 p r i n t ( ”b i s g r e a t e r than a o r a and b a r e e q u a l ” )
Listing 5.2: If - Else
Using Elif :
1 a = 5
2 b = 8
3
4 if a > b:
5 p r i n t ( ” a i s g r e a t e r than b” )
6 elif b > a:
7 p r i n t ( ”b i s g r e a t e r than a ” )
8 e l i f a == b :
9 p r i n t ( ” a i s e q u a l t o b” )
Listing 5.3: Elif
Note! Python uses ”elif” not ”elseif” like many other programming languages
do.
[End of Example]
5.2 Arrays
An array is a special variable, which can hold more than one value at a time.
Here are some Examples how you can create and use Arrays in Python:
Example 5.2.1. Arrays in Python
1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
2
3 N = l e n ( data )
4
5 p r i n t (N)
6
7 p r i n t ( data [ 2 ] )
8
9 data [ 2 ] = 7 . 3
10
11 p r i n t ( data [ 2 ] )
56
12
13
14 f o r x i n data :
15 print (x)
16
17
18 data . append ( 1 1 . 4 )
19
20
21 N = l e n ( data )
22
23 p r i n t (N)
24
25
26 f o r x i n data :
27 print (x)
Listing 5.4: Using Arrays in Python
You can return the number of elements in the array like this:
1 N = l e n ( data )
You can get a specific value inside the array like this:
1 index = 2
2 x = cars [ index ]
[End of Example]
You have many built in methods you can use in combination with arrays, like
sort(), clear(), copy(), count(), insert(), remove(), etc.
57
5.3 For Loops
A For loop is used for iterating over a sequence. I guess all your programs will
use one or more For loops. So if you have not used For loops before, make sure
to learn it now.
Below you see a basic example how you can use a For loop in Python:
1 f o r i in range (1 , 10) :
2 print ( i )
The For loop is probably one of the most useful feature in Python (or in any
kind of programming language). Below you will see different examples how you
can use a For loop in Python.
1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
2
3 f o r x i n data :
4 print (x)
5
6
7 c a r l i s t = [ ” Volvo ” , ” T e s l a ” , ” Ford ” ]
8
9 for car in c a r l i s t :
10 print ( car )
Listing 5.5: Using For Loops in Python
Finally, you can also use the range() function like this:
1 start = 4
2 s t o p = 12 #but not i n c l u d i n g
3 step = 2
4
5 f o r x i n r a n g e ( s t a r t , s top , s t e p ) :
6 print (x)
58
You should try all these examples in order to learn the basic structure of a For
loop.
[End of Example]
[End of Example]
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent
number is the sum of the previous two.
Some sources omit the initial 0, instead beginning the sequence with two 1s.
59
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the
recurrence relation
f0 = 0, f1 = 1
We will write a Python script that calculates the N first Fibonacci numbers.
The Python Script becomes like this:
1 N = 10
2
3 fib1 = 0
4 fib2 = 1
5
6 print ( fib1 )
7 print ( fib2 )
8
9 f o r k i n r a n g e (N−2) :
10 f i b n e x t = f i b 2 +f i b 1
11 fib1 = fib2
12 fib2 = fib next
13 print ( fib next )
Listing 5.6: Fibonacci Numbers Using a For Loop in Python
Alternative solution:
1 N = 10
2
3 fib = [0 , 1]
4
5
6 f o r k i n r a n g e (N−2) :
7 f i b n e x t = f i b [ k +1] +f i b [ k ]
8 f i b . append ( f i b n e x t )
9
10 print ( fib )
Listing 5.7: Fibonacci Numbers Using a For Loop in Python - Alt2
60
11 f o r k i n r a n g e (N−2) :
12 f i b [ k +2] = f i b [ k +1] +f i b [ k ]
13
14
15 print ( fib )
Listing 5.8: Fibonacci Numbers Using a For Loop in Python - Alt3
[End of Example]
Simple example:
1 f o r i in range (1 , 10) :
2 f o r k in range (1 , 10) :
3 print ( i , k)
61
By definition a prime number has both 1 and itself as a divisor. If it has any
other divisor, it cannot be prime.
Create a Python Script where you find all prime numbers between 1 and 200.
Tip! I guess this can be done in many different ways, but one way is to use 2
nested For Loops.
[End of Exercise]
1 m = 8
2
3 while m > 2:
4 p r i n t (m)
5 m = m− 1
Listing 5.10: Using While Loops in Python
[End of Example]
5.5 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
62
where T is the time constant.
Create a Script in Python (.py file) where you plot the solution x(t) in the time
interval:
0 ≤ t ≤ 25
Add Grid, and proper Title and Axis Labels to the plot.
[End of Exercise]
63
Chapter 6
Creating Functions in
Python
6.1 Introduction
A function is a block of code which only runs when it is called. You can pass
data, known as parameters, into a function. A function can return data as a
result.
If you are familiar with one or more other programming language, creating and
using functions should be familiar and known to you. All programming lan-
guages has the possibility to create functions, but the syntax is slightly different
from one language to another.
Scripts:
• A collection of commands that you would execute in the Editor
• Used for automating repetitive tasks
Functions:
• Operate on information (inputs) fed into them and return outputs
• Have a separate workspace and internal variables that is only valid inside
the function
64
• Your own user-defined functions work the same way as the built-in func-
tions you use all the time, such as plot(), rand(), mean(), std(), etc.
Python have lots of built-in functions, but very often we need to create our own
functions (we could refer to these functions as user-defined functions)
In Python a function is defined using the def keyword:
1 d e f FunctionName :
2 <s t a t e m e n t −1>
3 .
4 .
5 <s t a t e m e n t −N>
6 return . . .
The function adds 2 numbers. The name of the function is add, and it returns
the answer using the return statement.
Note that you need to use a colon ”:” at the end of line where you define the
function.
1 d e f add ( x , y ) :
65
[End of Example]
Next, we create a new Python File (e.g., testaverage.py) where we use the
function we created:
1 from m y f u n c t i o n s im po rt a v e r a g e
2
3 a = 2
4 b = 3
5
6 c = average (a , b)
7
8 print ( c )
Listing 6.4: Test of Average function
[End of Example]
66
21 data = [ 1 , 5 , 6 , 3 , 1 2 , 3 ]
22
23
24 t o t a l s u m , mean = s t a t ( data )
25
26 p r i n t ( t o t a l s u m , mean )
Listing 6.5: Function with multiple return values
[End of Example]
6.3 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
[End of Exercise]
Exercise 6.3.2. Create Python functions for converting between radians and
degrees
Since most of the trigonometric functions require that the angle is expressed in
radians, we will create our own functions in order to convert between radians
and degrees.
We have that:
67
[End of Exercise]
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent
number is the sum of the previous two.
Some sources omit the initial 0, instead beginning the sequence with two 1s.
f0 = 0, f1 = 1
[End of Exercise]
By definition a prime number has both 1 and itself as a divisor. If it has any
other divisor, it cannot be prime.
Tip! I guess this can be implemented in many different ways, but one way is to
use 2 nested For Loops.
68
Create a Python function where you check if a given number is a prime number
or not.
You can check the function in the Command Window like this:
1 number = 4
2 c h e c k i f p r i m e ( number )
[End of Exercise]
69
Chapter 7
7.1 Introduction
Python is an object oriented programming (OOP) language. Almost everything
in Python is an object, with its properties and methods.
The foundation for all object oriented programming (OOP) languages are Classes.
1 c l a s s ClassName :
2 <s t a t e m e n t −1>
3 .
4 .
5 .
6 <s t a t e m e n t −N>
1 c l a s s Car :
2 model = ” Volvo ”
3 c o l o r = ” Blue ”
4
5
6 c a r = Car ( )
7
8
9 p r i n t ( c a r . model )
10 print ( car . color )
Listing 7.1: Simple Python Class
70
This example don’t illustrate the good things with classes so we will create some
more examples.
[End of Example]
[End of Example]
71
12 c a r 2 = Car ( ” Volvo ” , ” Blue ” )
13
14 p r i n t ( c a r 2 . model )
15 print ( car2 . c o l o r )
Listing 7.3: Python Class Constructor Example
As you see from the code we have now defined a Class ”Car” that has 2 Class
variables called ”model” and ”color”, and in addition we have defined a Func-
tion (or Method) called ”displayCar()”.
Its normal to use the term ”Method” for Functions that are defined within a
Class.
You declare class methods like normal functions with the exception that the
first argument to each method is self.
To create instances of a class, you call the class using class name and pass in
whatever arguments its init () method accepts.
For example:
72
1 c a r 1 = Car ( ” T e s l a ” , ”Red” )
Listing 7.5: Import Class
[End of Example]
Then we create a Python Script (testCar.py) where we are using the Class:
1 # I m p o r t i n g t h e Car C l a s s
2 from Car im por t Car
3
4 # Lets s t a r t using the Class
5
6 c a r 1 = Car ( ” T e s l a ” , ”Red” )
7
8 car1 . displayCar ()
9
10
11 c a r 2 = Car ( ” Ford ” , ” Green ” )
12
13 p r i n t ( c a r 2 . model )
14 print ( car2 . c o l o r )
15
16
17 c a r 3 = Car ( ” Volvo ” , ” Blue ” )
18
19 p r i n t ( c a r 3 . model )
20 print ( car3 . c o l o r )
21
22 c a r 3 . c o l o r=” Black ”
23
24 car3 . displayCar ()
Listing 7.7: Script that is using the Class
[language=Python]
[End of Example]
73
7.3 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
[End of Exercise]
74
Chapter 8
As your program gets longer, you may want to split it into several files for easier
maintenance. You may also want to use a handy function that you have written
in several programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them
in a script or in an interactive instance of the interpreter (the Python Console
window).
Python allows you to split your program into modules that can be reused in
other Python programs. It comes with a large collection of standard modules
that you can use as the basis of your programs as we have seen examples of in
previous chapters. Not it is time to make your own modules from scratch.
Previously you have been using different modules, libraries or packages created
by the Python organization or by others. Here you will create your own modules
from scratch.
75
The formula for converting from Fahrenheit to Celsius is:
8.2 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
Exercise 8.2.1. Create Python Module for converting between radians and
degrees
Since most of the trigonometric functions require that the angle is expressed in
radians, we will create our own functions in order to convert between radians
76
and degrees.
Create two functions that convert from radians to degrees (r2d(x)) and from
degrees to radians (d2r(x)) respectively.
Test the functions to make sure that they work as expected. You can choose to
make a new .py file to test these functions or you can use the Console window.
[End of Exercise]
77
Chapter 9
9.1 Introduction
Python has several functions for creating, reading, updating, and deleting files.
The key function for working with files in Python is the open() function.
• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”r” - Read - Default value. Opens a file for reading, error if the file does
not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
In addition you can specify if the file should be handled as binary or text mode
• ”x” - Create - Creates the specified file, returns an error if the file exists
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
78
To write to an Existing file, you must add a parameter to the open() function:
• ”w” - Write - Opens a file for writing, creates the file if it does not exist
• ”a” - Append - Opens a file for appending, creates the file if it does not
exist
1 f = open ( ” m y f i l e . t x t ” , ”x” )
2
3 data = ” H e l l o World”
4
5 f . w r i t e ( data )
6
7 f . close ()
Listing 9.1: Write Data to a File
[End of Example]
• ”r” - Read - Default value. Opens a file for reading, error if the file does
not exist
1 f = open ( ” m y f i l e . t x t ” , ” r ” )
2
3 data = f . r e a d ( )
4
5 p r i n t ( data )
6
7 f . close ()
Listing 9.2: Read Data from a File
[End of Example]
79
1 data = [ 1 . 6 , 3 . 4 , 5 . 5 , 9 . 4 ]
2
3 f = open ( ” m y f i l e . t x t ” , ”x” )
4
5 f o r v a l u e i n data :
6 record = s t r ( value )
7 f . write ( record )
8 f . w r i t e ( ” \n” )
9
10 f . close ()
Listing 9.3: Logging Data to File
[End of Example]
1 f = open ( ” m y f i l e . t x t ” , ” r ” )
2
3 for record in f :
4 r e c o r d = r e c o r d . r e p l a c e ( ” \n” , ” ” )
5 print ( record )
6
7 f . close ()
Listing 9.4: Read Logged Data from File
[End of Example]
9.6 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
80
[End of Exercise]
You can use the Random Generator in Python. An example of how to use the
Random Generator is shown below:
1 im po rt random
2 f o r x in range (10) :
3 data = random . r a n d i n t ( 1 , 3 1 )
4 p r i n t ( data )
Listing 9.5: Read Data from a File
Make sure to log both the time and the temperature value
You should also plot the data you read from the File.
[End of Exercise]
81
Table 9.1: Logged Data
Time Value
1 22
2 25
3 28
... ...
82
Chapter 10
10.1.2 Exceptions
Even if a statement or expression is syntactically correct, it may cause an error
when an attempt is made to execute it. Errors detected during execution are
called exceptions and are not unconditionally fatal: you will soon learn how to
handle them in Python programs. Most exceptions are not handled by programs,
however, and result in error messages as shown here:
1 >>> 10 ∗ ( 1 / 0 )
2 Traceback ( most r e c e n t c a l l last ) :
3
4 F i l e ”<ipython −i n p u t −2−0b 2 8 0 f 3 6 8 3 5 c >” , l i n e 1 , i n <module>
5 10 ∗ ( 1 / 0 )
6
7 Z e r o D i v i s i o n E r r o r : d i v i s i o n by z e r o
or:
1 >>> ’ 2 ’ + 2
2 Traceback ( most r e c e n t c a l l last ) :
3
83
4 F i l e ”<ipython −i n p u t −3−d2b23a1db757>” , l i n e 1 , i n <module>
5 ’2 ’ + 2
6
7 TypeError : must be s t r , not i n t
• The try block lets you test a block of code for errors.
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
1 try :
2 10 ∗ ( 1 / 0 )
3 except :
4 p r i n t ( ”The c a l c u l a t i o n f a i l e d ” )
or:
1 try :
2 print (x)
3 except :
4 p r i n t ( ”x i s not d e f i n e d ” )
The finally block, if specified, will be executed regardless if the try block raises
an error or not.
Example:
84
1 x=2
2
3 try :
4 print (x)
5 e x c e p t NameError :
6 p r i n t ( ”x i s not d e f i n e d ” )
7 except :
8 p r i n t ( ” Something i s wrong ” )
9 finally :
10 p r i n t ( ”The Program i s f i n i s h e d ” )
In general you should use try - except - finally when you try to open a File, read
or write to Files, connect to a Database, etc.
Example:
1 try :
2 f = open ( ” m y f i l e . t x t ” )
3 f . w r i t e ( ”Lorum Ipsum ” )
4 except :
5 p r i n t ( ” Something went wrong when w r i t i n g t o t h e f i l e ” )
6 finally :
7 f . close ()
85
Chapter 11
Debugging in Python
Debuggers are software tools which enable the programmer to monitor the ex-
ecution of a program, stop it, restart it, set breakpoints, and change values in
memory. The term debugger can also refer to the person who is doing the de-
bugging.
As a programmer, one of the first things that you need for serious program
development is a debugger.
Python has a built-in debugger that can be used if you are coding Python with
a basic text editor and running your Python programs from the command line.
A better option is to use the Debugging features integrated in your Python Ed-
itor. Debugging is typically integrated with the Python Editor you are using.
86
Chapter 12
A package contains all the files you need for a module. Modules are Python
code libraries you can include in your project.
Since Python is open source you can find thousands of Python Packages that
you can install and use in your Python programs.
You can use a Python Distribution like Anaconda Distribution (or similar
Python Distributions) to download and install many common Python Pack-
ages as mentioned previously.
If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/
PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).
1 p i p i n s t a l l packagename
Some Python Editors also have a graphical way of installing Python Packages,
like, e.g., Visual Studio.
87
Part III
88
Chapter 13
Introduction to Python
Environments and
Distributions
Python is open source and everybody can bundle and distribute Python and
different Python Packages.
A Python environment is a context in which you run Python code and includes
Python Packages.
• Anaconda
• Enthought Canopy
• WinPython
• etc.
89
But you can also install the core Python from:
https://www.python.org
Then install the additional Python Packages you need by using PIP.
https://pypi.org/project/pip/
13.1.1 PIP
Web:
https://pypi.org
PIP is typically used from the Command Prompt (Windows) or Terminal win-
dow (macOS).
1 p i p i n s t a l l packagename
13.1.2 Conda
Conda is an open source package management system and environment man-
agement system that runs on Windows, macOS and Linux. Conda installs, runs
and updates packages and their dependencies.
The Conda package and environment manager is included in all versions of Ana-
conda.
Conda was created for Python programs, but it can package and distribute soft-
ware for any language.
Conda allows you to to also create separate environments containing files, pack-
ages and their dependencies that will not interact with other environments.
90
Web:
https://conda.io/
Web:
https://www.anaconda.com
Python Virtual Environments have their own installation directories and they
don’t share libraries with other virtual environments.
Python ”Virtual Environments” is handy when you have different Python appli-
cations that needs different versions of Python or different version of the Python
Packages you are using.
91
Chapter 14
Anaconda
Web:
https://www.anaconda.com
Wikipedia:
https://en.wikipedia.org/wiki/Anaconda( P ythond istribution)
Let say you want to install the Python Control Systems Library package. Just
enter the following in the Anaconda Prompt:
pip i n s t a l l c o n t r o l
92
Figure 14.1: Anaconda Navigator
Python Package Index, or just pip, is a tool used to handle and install Python
packages.
For for information about pip and different packages you can install, see the
following:
https://pypi.org
Figure 14.2 shows where you can find the Anaconda Prompt. Windows: Search
for Anaconda Prompt in the Search field in the start menu.
93
Figure 14.2: Anaconda Navigator
94
Part IV
Python Editors
95
Chapter 15
Python Editors
An Editor is a program where you create your code (and where you can run
and test it). Most Editors have also features for Debugging and IntelliSense.
In theory, you can use Windows Notepad for creating Python programs, but
in practice it is impossible to create programs without having an editor with
Debugging, IntelliSense, color formatting, etc.
For simple Python programs you can use the IDLE Editor, but for more ad-
vanced programs a better editor is recommended.
• Spyder
• Visual Studio Code
• Thonny
• Visual Studio
• PyCharm
• Wing
• JupyterNotebook
I guess hundreds of different editors can be used for Python Programming, ei-
ther out of the box or if you install an additional Extension that makes sure
you can use Python in that editor.
If you already have a favorite Code Editor, it is a good change you can use that
one for Python programming.
Which editor you should use depends on your background, what kind of code
editors you have used previously, your programming skills, what your are going
96
to develop in Python, etc.
If you are familiar with MATLAB, Spyder is recommended. Also, if you want
to use Python for numerical calculations and computations, Spyder is a good
choice.
For Internet of Things Applications, simple editors like Visual Studio Code or
Thonny may be good choices. Thonny is also the default editor on the Rasp-
berry Pi OS, which is popular Internet of Things platform.
97
Chapter 16
Spyder
98
• Variable Explorer
• etc.
Web:
https://www.spyder-ide.org
If you have used MATLAB previously or want to use Python for scientific use,
Spyder is a good choice. it is easy to install using the Anaconda Distribution.
Web:
https://www.anaconda.com
16.1 Configuration
Typically you want to show figures and plots in separate windows.
99
Figure 16.3: Python Preferences window
100
Chapter 17
Web:
https://code.visualstudio.com
Wikipedia:
https://en.wikipedia.org/wiki/VisualS tudioC ode
101
17.2 Python in Visual Studio Code
In addition to Visual Studio Code you need to install the Python extension for
Visual Studio Code.
You must install a Python interpreter yourself separately from the extension.
For a quick install, use Python from python.org.
https://www.python.org
Python is an interpreted language, and in order to run Python code and get
Python IntelliSense within Visual Studio Code, you must tell Visual Studio
Code which interpreter to use.
Web:
https://code.visualstudio.com/docs/languages/python
102
Part V
103
Chapter 18
Mathematics in Python
If you are looking for similar using MATLAB, please take a look at these re-
sources:
https://www.halvorsen.blog/documents/programming/matlab/
In this chapter we will focus on the math module that is part of the Python
Standard Library.
The math module has all the basic math functions you need, such as: Trigono-
metric functions: sin(x), cos(x), etc. Logarithmic functions: log(), log10(), etc.
Constants like pi, e, inf, nan, etc. etc.
104
1 from math im por t s i n , c o s
2
3 x = 3.14
4 y = sin (x)
5 print (y)
6
7 y = cos (x)
8 print (y)
[End of Example]
There are advantages and disadvantages with the different approaches. In your
program you may need to use functions from many different modules or pack-
ages. If you import the whole module instead of just the function(s) you need
you use more of the computer memory.
Very often we also need to import and use multiple libraries where the different
libraries have some functions with the same name but different use.
Other useful modules in the Python Standard Library are statistics (where
you have functions like mean(), stdev(), etc.)
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/
105
18.1.1 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
[End of Exercise]
ln (ax2 + bx + c) − sin(ax2 + bx + c)
f (x) = (18.2)
4πx2 + cos(x − 2)(ax2 + bx + c)
Tip! You should split the expressions into different parts, such as:
poly = ax2 + bx + c
num = . . .
den = . . .
f = ...
This makes the expression simpler to read and understand, and you minimize
the risk of making an error while typing the expression in Python.
When you got the correct answer try to change to, e.g., a = 2, b = 8, c = 6
Find f (9)
[End of Exercise]
106
Figure 18.1: Right-angled triangle
c2 = a2 + b2 (18.3)
1 def pythagoras (a , b)
2 ...
3 ...
4 return c
[End of Exercise]
E = mc2 (18.4)
Calculate how much of the mass on the sun is used to create this energy per day.
How many years will it take to convert all the mass of the sun completely? Do
we need to worry if the sun will be used up in our generation or the next? justify
the answer.
107
[End of Exercise]
[End of Exercise]
18.2 Statistics
18.2.1 Introduction to Statistics
Mean or average:
The mean is the sum of the data divided by the number of data points. It is
commonly called ”the average”.
Mean:
N
1 X 2.2 + 4.5 + 6.2 + 3.6 + 2.6 19.1
x̄ = xi = = = 3.82 (18.6)
N i=1 5 5
108
[End of Example]
Variance:
N
1 X
var(x) = (xi − x̄)2 (18.7)
N i=1
Standard deviation:
The standard deviation is a measure of the spread of the values in a dataset
or the value of a random variable. It is defined as the square root of the variance.
v
u N
√ u1 X
std(x) = σ = var = t (xi − x̄)2 (18.8)
N i=1
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/
1 im po rt s t a t i s t i c s a s s t
2
3 data = [ − 1 . 0 , 2 . 5 , 3 . 2 5 , 5 . 7 5 ]
4
5 #Mean o r Average
6 m = s t . mean ( data )
7 p r i n t (m)
8
9 # Standard D e v i a t i o n
10 s t d e v = s t . s t d e v ( data )
109
11 print ( st dev )
12
13 # Median
14 med = s t . median ( data )
15 p r i n t ( med )
16
17 # Variance
18 v a r = s t . v a r i a n c e ( data )
19 p r i n t ( var )
Listing 18.1: Statistics functions in Python
[End of Example]
IMPORTANT: Do not name your file ”statistics.py” since the import will be
confused and throw the errors of the library not existing and the mean function
not existing.
You can also use the NumPy Library. NumPy is the fundamental package for
scientific computing with Python.
Below you find some examples how to use some of the statistics functions in
NumPy:
1 im po rt numpy a s np
2
3 data = [ − 1 . 0 , 2 . 5 , 3 . 2 5 , 5 . 7 5 ]
4
5 #Mean o r Average
6 m = np . mean ( data )
7 p r i n t (m)
8
9 # Standard D e v i a t i o n
10 s t d e v = np . s t d ( data )
11 print ( st dev )
12
13 # Median
14 med = np . median ( data )
15 p r i n t ( med )
16
17 # Minimum Value
18 minv = np . min ( data )
19 p r i n t ( minv )
20
21 # Maxumum Value
22 maxv = np . max( data )
23 p r i n t ( maxv )
Listing 18.2: Statistics using the NumPy Library
110
[End of Example]
Create your own Statistics Module in Python (e.g., ”mystatistics.py) and then
create a Python Script (e.g., ”testmystatistics.py) where you test these func-
tions.
You should at least implement functions for mean, variance, standard deviation,
minimum and maximum.
[End of Exercise]
Note! Most of the trigonometric functions require that the angle is expressed in
radians.
Example 18.3.1. Trigonometric Functions in Math module
1 im po rt math a s mt
2
3 x = 2∗mt . p i
4
5 y = mt . s i n ( x )
6 print (y)
7
8 y = mt . c o s ( x )
9 print (y)
10
11 y = mt . tan ( x )
12 print (y)
Listing 18.3: Trigonometric Functions in Math module
Here we have used the Math module in the Python Standard Library.
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/index.html
111
[End of Example]
1 im po rt math a s mt
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 xdata = [ ]
5 ydata = [ ]
6
7 f o r x in range (0 , 10) :
8 xdata . append ( x )
9 y = mt . s i n ( x )
10 ydata . append ( y )
11
12 p l t . p l o t ( xdata , ydata )
13 p l t . show ( )
Listing 18.4: Plotting Trigonometric Functions
In the example we have plotted sin(x), we can easily extend the program to plot
cos(x), etc.
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/index.html
[End of Example]
We will use the NumPy library instead because they handle arrays, in addition
to all the handy functionality in the NumPy library.
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 xstart = 0
5 x s t o p = 2∗ np . p i
6 increment = 0.1
7
8 x = np . a r a n g e ( x s t a r t , xstop , i n c r e m e n t )
9
10 y = np . s i n ( x )
112
11 plt . plot (x , y)
12 plt . t i t l e ( ’ y=s i n ( x ) ’ )
13 plt . xlabel ( ’x ’ )
14 plt . ylabel ( ’y ’ )
15 plt . grid ()
16 plt . a x i s ( [ 0 , 2∗ np . pi , −1, 1 ] )
17 plt . show ( )
18
19 y = np . c o s ( x )
20 plt . plot (x , y)
21 p l t . t i t l e ( ’ y=c o s ( x ) ’ )
22 plt . xlabel ( ’x ’ )
23 plt . ylabel ( ’y ’ )
24 plt . grid ()
25 p l t . a x i s ( [ 0 , 2∗ np . pi , −1, 1 ] )
26 p l t . show ( )
27
28 y = np . tan ( x )
29 plt . plot (x , y)
30 p l t . t i t l e ( ’ y=tan ( x ) ’ )
31 plt . xlabel ( ’x ’ )
32 plt . ylabel ( ’y ’ )
33 plt . grid ()
34 p l t . a x i s ( [ 0 , 2∗ np . pi , −1, 1 ] )
35 p l t . show ( )
Listing 18.5: Trigonometric Functions using NumPy
[End of Example]
We have that:
113
These functions should be saved in one Python file .py.
[End of Exercise]
Create a function that finds the angle A (in degrees) based on input arguments
(a,c), (b,c) and (a,b) respectively.
Use, e.g., a third input “type” to define the different types above.
Use you previous function r2d() to make sure the output of your function is in
degrees and not in radians.
a a
sin(A) = → A = arcsin( ) (18.12)
c c
b b
cos(A) = → A = arccos( ) (18.13)
c c
a a
tan(A) = → A = arctan( ) (18.14)
b b
c2 = a2 + b2 (18.15)
1 >>> a=5
2 >>> b=8
3 >>> c = s q r t ( a ∗∗2 + b ∗ ∗ 2 )
4
5 >>> A = r i g h t t r i a n g l e ( a , c , ’ s i n ’ )
6 A =
7 32.0054
8
9 >>> A = r i g h t t r i a n g l e ( b , c , ’ c o s ’ )
10 A =
11 32.0054
12 >>> A = r i g h t t r i a n g l e ( a , b , ’ tan ’ )
13 A =
14 32.0054
We also see that the answer in this case is the same, which is expected.
114
[End of Exercise]
[End of Exercise]
Plot sin(θ) and cos(θ) for 0 ≤ θ ≤ 2π in the same plot (both in the same plot
and in 2 different subplots).
Make sure to add labels and a legend and use different line styles and colors for
the plots.
[End of Exercise]
18.4 Polynomials
A polynomial is expressed as:
Web:
https://numpy.org/doc/stable/reference/routines.polynomials.polynomial.html
Other Resources:
115
116
117
Chapter 19
Matrix is a special case of two dimensional array where each data element is of
strictly same size.
Matrices are very important data structures for many mathematical and scien-
tific calculations.
Example of a 3 x 3 matrix:
1 5 3
A= 4 6 6 (19.2)
3 8 9
Example of a 3 x 4 matrix:
1 5 3 4
A= 4 5 7 8 (19.3)
7 8 9 3
Example of a 4 x 2 matrix:
118
1 5
4 5
A=
3
(19.4)
2
7 8
Python doesn’t have a built-in type for matrices. However, we can create list of
a list as a matrix.
So we can define vectors and matrices with standard Python, but standard
Python has no support for manipulation and calculation of them.
But fortunately we can use the NumPy package for creating matrices and for
matrix manipulation.
[End of Example]
119
Below you see how we can use NumPy for creating vectors and matrices and
manipulate them using NumPy:
1 im po rt numpy a s np
2
3 a = np . a r r a y ( [ 1 , 3 , 7 , 2 ] )
4
5 p r i n t ( ” a =” , a )
6
7
8
9 A = np . a r r a y ( [ [ 1 , 3 , 7 , 2 ] ,
10 [ 5 , 8 , −9, 0 ] ,
11 [ 6 , −7, 1 1 , 1 2 ] ] )
12
13
14 p r i n t ( ”A =” , A)
15
16
17
18
19 A = np . a r r a y ( [ [ 0 , 1 ] ,
20 [ −2 , − 3 ] ] )
21
22 B = np . a r r a y ( [ [ 1 , 0 ] ,
23 [ 3 , −2]])
24
25 C = A + B
26 p r i n t (C)
27
28
29 C = A. dot (B)
30 p r i n t (C)
31
32 C = A. t r a n s p o s e ( )
33 p r i n t (C)
Listing 19.2: Matrix manipulation using NumPy
[End of Example]
19.2.1 Vectors
Use np.array() when you define vectors:
1 im po rt numpy a s np
2
3 a = np . a r r a y ( [ 1 , 3 , 7 , 2 ] )
4
5 p r i n t ( ” a =” , a )
Listing 19.3: Matrix manipulation using NumPy
120
19.2.2 Matrices
You can use np.array() when defining matrices also, but you may also use
np.matrix().
The numpy matrix object is a subclass of the numpy array object and it is
tailor-made for matrices. The numpy matrices are strictly 2-dimensional, while
numpy arrays can be of any dimension.
Example:
1 im po rt numpy a s np
2
3 A = np . m a t r i x ( [ [ 0 , 1 ] ,
4 [ −2 , − 3 ] ] )
5
6 p r i n t ( ”A =” , A)
It is no longer recommended to use this class, even for linear algebra. Instead
use regular arrays. The class may be removed in the future.
https://numpy.org/doc/stable/reference/generated/numpy.matrix.html
A ∈ Rnxm
and
B ∈ Rnxm
Then
C = A + B ∈ Rnxm
Example:
121
0 1
A= (19.5)
−2 −3
1 0
B= (19.6)
3 −2
Then we get:
0 1 1 0 0+1 1+0 1 1
A+B = = = (19.7)
−2 −3 3 −2 −2 + 3 −3 − 2 1 −5
1 im po rt numpy a s np
2
3 A = np . m a t r i x ( [ [ 0 , 1 ] ,
4 [ −2 , − 3 ] ] )
5
6 B = np . m a t r i x ( [ [ 1 , 0 ] ,
7 [ 3 , −2]])
8
9 C = A + B
10 p r i n t (C)
Listing 19.4: Matrix Addition in Python
We get:
1 [ [ 1 1]
2 [ 1 −5]]
[End of Example]
A ∈ Rnxm
and
B ∈ Rnxm
Then
122
C = A − B ∈ Rnxm
Example:
0 1
A= (19.8)
−2 −3
1 0
B= (19.9)
3 −2
Then we get:
0 1 1 0 0−1 1−0 −1 1
A−B = = =
−2 −3 3 −2 −2 − 3 −3 − (−2) −5 −1
(19.10)
1 im po rt numpy a s np
2
3 A = np . m a t r i x ( [ [ 0 , 1 ] ,
4 [ −2 , − 3 ] ] )
5
6 B = np . m a t r i x ( [ [ 1 , 0 ] ,
7 [ 3 , −2]])
8
9 C = A − B
10 p r i n t (C)
Listing 19.5: Matrix Subraction in Python
We get:
1 [[ − 1 1]
2 [ −5 − 1 ] ]
[End of Example]
123
19.2.6 Matrix Multiplication
Given the matrices:
A ∈ Rnxm
and
B ∈ Rmxp
Then
C = AB ∈ Rnxp
Where
n
X
cjk = ajl blk
l=1
Example:
0 1
A= (19.11)
−2 −3
1 0
B= (19.12)
3 −2
Then we get:
10 1 0
AB =
−2
−3 3 −2
0·1+1·3 0 · 0 + 1 · (−2) 3 −2
= = (19.13)
−2 · 1 − 3 · 3 −2 · 0 − 3 · (−2) −11 6
1 im po rt numpy a s np
2
3 A = np . m a t r i x ( [ [ 0 , 1 ] ,
4 [ −2 , − 3 ] ] )
5
6 B = np . m a t r i x ( [ [ 1 , 0 ] ,
7 [ 3 , −2]])
8
9 C = A ∗ B
10 p r i n t (C)
Listing 19.6: Matrix Multiplication in Python
124
This gives:
1 [[ 3 −2]
2 [ −11 6]]
As shown in the example you can use different syntax. The 3 alternatives in the
example give the same result. Try it.
[End of Example]
In matrix multiplication the matrices don’t need to be quadratic, but the inner
dimensions need to be the same. The size of the resulting matrix will be the
outer dimensions. See Figure 19.1.
AB 6= BA (19.14)
125
(A + B)C = AC + BC (19.16)
C(A + B) = CA + CB (19.17)
[End of Exercise]
a11 a21 ... an1
T
a12 a22 .. an2
A = ∈ Rmxn (19.19)
... ... ... ...
a1m a2m ... anm
The transform of a matrix is formed by turning all the rows of a given matrix
into columns and vice-versa.
Example 19.2.5. Transpose of a Matrix in Python
1 im po rt numpy a s np
2
3 A = np . m a t r i x ( [ [ 0 , 1 ] ,
4 [ −2 , − 3 ] ] )
5
6 At = np . t r a n s p o s e (A)
7 p r i n t ( At )
8
9
10 B = np . m a t r i x ( [ [ 1 , 0 , 4 ] ,
11 [ 3 , −2, 8 ] ] )
12
13 Bt = np . t r a n s p o s e (B)
14 p r i n t ( Bt )
126
15
16
17
18 C = np . m a t r i x ( [ [ 1 , 4 , ] ,
19 [ 2 , −3 ,] ,
20 [ −6 , − 2 ] ] )
21
22 Ct = np . t r a n s p o s e (C)
23 p r i n t ( Ct )
Listing 19.8: Transpose of a Matrix
1 [ [ 0 −2]
2 [ 1 −3]]
3
4 [ [ 1 3]
5 [ 0 −2]
6 [ 4 8]]
7
8 [ [ 1 2 −6]
9 [ 4 −3 − 2 ] ]
[End of Example]
19.2.8 Determinant
Given a matrix A the Determinant is given by:
det(A) = |A|
We have:
Example:
1 2
A= (19.22)
3 4
We get:
127
Example 19.2.6. Determinant
Python Example:
1 im po rt numpy a s np
2 im po rt numpy . l i n a l g a s l a
3
4 A = np . m a t r i x ( [ [ 1 , 2 ] ,
5 [3 , 4]])
6
7 Adet = l a . d e t (A)
8
9 p r i n t ( Adet )
Listing 19.9: Determinant
This gives:
1 −2.0000000000000004
Listing 19.10: Determinant
[End of Example]
A−1
We have that:
128
Python Example:
1 im po rt numpy a s np
2 im po rt numpy . l i n a l g a s l a
3
4 A = np . m a t r i x ( [ [ 1 , 2 ] ,
5 [3 , 4]])
6
7 Ainv = l a . i n v (A)
8
9 p r i n t ( Ainv )
Listing 19.11: Inverse Matrix
[End of Example]
x1 + 2x2 = 5 (19.27)
Ax = b (19.29)
Then we can solve the equations, i.e., find x1 and x2 using Python.
x = A−1 b (19.30)
We get:
129
1 2
A= (19.31)
3 4
5
b= (19.32)
6
x1
x= (19.33)
x2
Python Script:
1 im po rt numpy a s np
2 im po rt numpy . l i n a l g a s l a
3
4 A = np . a r r a y ( [ [ 1 , 2 ] ,
5 [3 , 4]])
6
7 b = np . a r r a y ( [ [ 5 ] ,
8 [6]])
9
10 Ainv = l a . i n v (A)
11
12 x = Ainv . dot ( b )
13
14 print (x)
Python Script:
1 im po rt numpy a s np
2
3 A = np . a r r a y ( [ [ 1 , 2 ] ,
4 [3 , 4]])
5
6 b = np . a r r a y ( [ [ 5 ] ,
7 [6]])
8
9 x = np . l i n a l g . s o l v e (A, b )
10 print (x)
Note! The A matrix must be square and of full-rank, i.e. the inverse matrix
needs to exists.
130
[End of Example]
In many cases we cannot find the inverse matrix, e.g., when the matrix is not
quadratic. Finding the inverse matrix for large matrices is also time-consuming.
Python Script:
1 im po rt numpy a s np
2
3 A = np . a r r a y ( [ [ 1 , 2 ] ,
4 [3 , 4] ,
5 [7 , 8]])
6
7 b = np . a r r a y ( [ [ 5 ] ,
8 [6] ,
9 [9]])
10
11 #x = np . l i n a l g . s o l v e (A, b ) #Not working b e c a u s e i n v e r s e (A) d o e s not
exists
12
13
14 x = np . l i n a l g . l s t s q (A, b , rcond=None ) [ 0 ]
15
16 print (x)
[End of Example]
19.4 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
131
Given the following equations:
x1 + 2x2 = 5 (19.34)
[End of Exercise]
You should test your function by do the calculations by hand and by using the
the numpy functionality. Compare the results and make sure you get the same
answers.
[End of Exercise]
132
Chapter 20
Complex Numbers in
Python
z = a + jb (20.1)
√
Where the imaginary unit j is defined as i = −1
Where a is called the real part of z and b is called the imaginary part of z, i.e.:
Re(z) = a, Im(z) = b
z∗ = a − jb (20.2)
z = rejθ (20.3)
133
Where:
p
r = |z| = a2 + b2 (20.4)
and
b
θ = arctan (20.5)
a
To add or subtract two complex numbers, we simply add (or subtract) their real
parts and their imaginary parts.
z1 = r1 ejθ1 (20.6)
z2 = r2 ejθ2 (20.7)
Multiplication:
134
Figure 20.2: Complex Numbers - Polar form
Division:
z1 r1 ejθ1 r1
z3 = = = ej(θ1 −θ2 ) (20.9)
z2 r2 ejθ2 r2
https://docs.python.org/3/library/cmath.html
For more information about the functions in the Python Standard Library,
see:
https://docs.python.org/3/library/
a = 5 + 3j (20.10)
135
b = 1 − 1j (20.11)
In Python we can define the complex numbers and perform basic operations (+,
-, *, /) like this:
1 a = 5 + 3j
2 b = 1 − 1j
3
4 c = a + b
5 print ( c )
6
7 d = a − b
8 print (d)
9
10 e = a ∗ b
11 print ( e )
12
13 f = a / b
14 print ( f )
Listing 20.1: Basic Complex Numbers in Python
[End of Example]
1 im po rt cmath
2
3 x = 2
4 y = −3
5
6 # c o n v e r t i n g x and y i n t o complex number u s i n g complex ( )
7 z = complex ( x , y )
8 print ( z . real )
9 p r i n t ( z . imag )
10
11 print ( z . conjugate () )
12
13 # c o n v e r t i n g complex number i n t o p o l a r u s i n g p o l a r ( )
14 w = cmath . p o l a r ( z )
15 p r i n t (w)
16
17
18 # c o n v e r t i n g complex number i n t o r e c t a n g u l a r u s i n g r e c t ( )
19 w = cmath . r e c t ( 2 , 3 )
20 p r i n t (w)
Listing 20.2: Complex Number Functions in Python
[End of Example]
136
Chapter 21
Differential Equations
ẋ = −ax + bu (21.2)
dx
Note! ẋ is the same as dt
137
[End of Example]
With Python have we can solve these differential equations in many different
ways.
We can use so-called ODE solvers or we can make discrete version of the differ-
ential equations using discretization methods like Euler, etc.
With ODE solvers Python can solve these equations numerically. Higher order
differential equations must be reformulated into a system of first order differen-
tial equations.
In chapter 25 we will simulate (solve and plot the results) such differential equa-
tions numerically using Euler discretization.
ẋ = ax (21.3)
Where a = − T1 , where T is defined as the time constant of the system.
dx
Note! ẋ is the same as dt
138
22
23
24 # D e f i n e t h e Equation
25 f o r k in range ( tstop ) :
26 x [ k ] = mt . exp ( a ∗ t [ k ] ) ∗ x0
27
28
29 # Plot the Results
30 plt . plot (t , x)
31 p l t . t i t l e ( ’ P l o t t i n g D i f f e r e n t i a l Equation S o l u t i o n ’ )
32 plt . xlabel ( ’ t ’ )
33 plt . ylabel ( ’x( t ) ’ )
34 plt . grid ()
35 p l t . a x i s ( [ 0 , 25 , 0 , 1 ] )
36 p l t . show ( )
Listing 21.1: Differential Equation
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4
5 # P ar a m e t e r s
6 T = 5
139
7 a = −1/T
8
9 x0 = 1
10 t = 0
11
12 tstart = 0
13 t s t o p = 25
14 increment = 1
15 N = 25
16
17 #t = np . a r a n g e ( t s t a r t , t s t o p +1 , i n c r e m e n t ) #A l t e r n a t i v e Approach
18 t = np . l i n s p a c e ( t s t a r t , t s t o p , N)
19
20 x = np . exp ( a ∗ t ) ∗ x0
21
22
23 # Plot the Results
24 plt . plot (t , x)
25 p l t . t i t l e ( ’ P l o t t i n g D i f f e r e n t i a l Equation S o l u t i o n ’ )
26 plt . xlabel ( ’ t ’ )
27 plt . ylabel ( ’x( t ) ’ )
28 plt . grid ()
29 p l t . a x i s ( [ 0 , 25 , 0 , 1 ] )
30 p l t . show ( )
Listing 21.2: Differential Equation
This alternative Python code gives the same plot as shown in Figure 21.1.
Solving differential equations like shown in this example works fine, but the
problem is that we first have to manually (by pen and paper) find the solution
to the differential equation.
In the examples and tasks below we will learn how we can use these built-in
ODE solvers.
Another approach is to solve such equations from ”scratch” by making a dis-
crete version of the differential equation. This approach is presented later in
this textbook (chapter 25).
[End of Example]
140
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
ẋ = ax (21.5)
Where a = − T1 , where T is defined as the time constant of the system.
dx
Note! ẋ is the same as dt
Where we have:
functioname: Function that returns derivative values at requested x and t values
as dxdt = model(x,t)
141
18
19 dxdt = a ∗ x
20
21 r e t u r n dxdt
22
23
24 # S o l v e ODE
25 x = o d e i n t ( m y d i f f , x0 , t )
26 print (x)
27
28
29 # Plot the Results
30 plt . plot (t , x)
31 p l t . t i t l e ( ’ P l o t t i n g D i f f e r e n t i a l Equation S o l u t i o n ’ )
32 plt . xlabel ( ’ t ’ )
33 plt . ylabel ( ’x( t ) ’ )
34 plt . grid ()
35 p l t . a x i s ( [ 0 , 25 , 0 , 1 ] )
36 p l t . show ( )
Listing 21.3: Using ODE Solver in Python
142
36 p l t . show ( )
Listing 21.4: Using ODE Solver in Python
In the modified example we have the parameters used in the differential equation
(in htis case a) as an input argument. By doing this, it is very easy to changes
values for the parameters used in the differential equation without changing the
code for the differential equation.
[End of Example]
Python code:
143
1 im po rt numpy a s np
2 from s c i p y . i n t e g r a t e i mpo rt o d e i n t
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Initialization
6 t s t a r t = −1
7 tstop = 1
8 increment = 0.1
9
10 # I n i t i a l condition
11 z0 = [ 1 , 1 ]
12
13
14 t = np . a r a n g e ( t s t a r t , t s t o p +1 , i n c r e m e n t )
15
16
17 # F u n c t i o n t h a t r e t u r n s dx/ dt
18 def mydiff ( z , t ) :
19 dxdt = −z [ 1 ]
20 dydt = z [ 0 ]
21
22 dzdt = [ dxdt , dydt ]
23 r e t u r n dzdt
24
25
26 # S o l v e ODE
27 z = o d e i n t ( m y d i f f , z0 , t )
28 print ( z )
29
30 x = z [: ,0]
31 y = z [: ,1]
32
33
34 # Plot the Results
35 plt . plot (t , x)
36 plt . plot (t , y)
37 p l t . t i t l e ( ’ P l o t t i n g D i f f e r e n t i a l Equations So lut ion ’ )
38 plt . xlabel ( ’ t ’ )
39 plt . ylabel ( ’z( t ) ’ )
40 plt . grid ()
41 p l t . a x i s ( [ − 1 , 1 , −1.5 , 1 . 5 ] )
42 p l t . show ( )
Listing 21.5: xxx
We can also rewrite the differential equations like this (to make it easier to
understand?):
dx1
= −x2 (21.8)
dt
dx2
= x1 (21.9)
dt
144
Figure 21.2: Figure Name
1 im po rt numpy a s np
2 from s c i p y . i n t e g r a t e i mpo rt o d e i n t
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Initialization
6 t s t a r t = −1
7 tstop = 1
8 increment = 0.1
9
10 # I n i t i a l condition
11 x init = [1 ,1]
12
13
14 t = np . a r a n g e ( t s t a r t , t s t o p +1 , i n c r e m e n t )
15
16
17 # F u n c t i o n t h a t r e t u r n s dx/ dt
18 def mydiff (x , t ) :
19 dx1dt = −x [ 1 ]
20 dx2dt = x [ 0 ]
21
22 dxdt = [ dx1dt , dx2dt ]
23 r e t u r n dxdt
24
25
26 # S o l v e ODE
27 x = odeint ( mydiff , x i n i t , t )
28 print (x)
29
30 x1 = x [ : , 0 ]
145
31 x2 = x [ : , 1 ]
32
33
34 # Plot the Results
35 p l t . p l o t ( t , x1 )
36 p l t . p l o t ( t , x2 )
37 p l t . t i t l e ( ’ P l o t t i n g D i f f e r e n t i a l Equations So lut ion ’ )
38 plt . xlabel ( ’ t ’ )
39 plt . ylabel ( ’x( t ) ’ )
40 plt . grid ()
41 p l t . a x i s ( [ − 1 , 1 , −1.5 , 1 . 5 ] )
42 p l t . show ( )
Listing 21.6: xxx
[End of Example]
Note! Don’t be confused that in this example w is used and not x or y. All
these are just parameters or variable names.
dw d2 w
Note! ẇ = dt and ẅ = dt2
First, we should rewrite the equation in order to get the highest derivative alone
on the left side of the equation:
2 − 2tẇ − 3w
ẅ = (21.11)
1 + t2
146
w = x1 (21.12)
ẇ = x2 (21.13)
This gives a set of 1.order differential equations:
ẋ1 = x2 (21.14)
2 − 2tx2 − 3x1
ẋ2 = (21.15)
1 + t2
Python code:
1 im po rt numpy a s np
2 from s c i p y . i n t e g r a t e i mpo rt o d e i n t
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Initialization
6 tstart = 0
7 tstop = 5
8 increment = 0.1
9
10 # I n i t i a l condition
11 x init = [0 ,1]
12
13
14 t = np . a r a n g e ( t s t a r t , t s t o p +1 , i n c r e m e n t )
15
16
17 # F u n c t i o n t h a t r e t u r n s dx/ dt
18 def mydiff (x , t ) :
19 dx1dt = x [ 1 ]
20 dx2dt = ( 2 − t ∗x [ 1 ] − 3∗ x [ 0 ] ) / ( 1 + t ∗ ∗ 2 )
21
22 dxdt = [ dx1dt , dx2dt ]
23 r e t u r n dxdt
24
25
26 # S o l v e ODE
27 x = odeint ( mydiff , x i n i t , t )
28 print (x)
29
30 x1 = x [ : , 0 ]
31 x2 = x [ : , 1 ]
32
33
34 # Plot the Results
35 p l t . p l o t ( t , x1 )
36 p l t . p l o t ( t , x2 )
37 p l t . t i t l e ( ’ P l o t t i n g D i f f e r e n t i a l Equations So lut ion ’ )
38 plt . xlabel ( ’ t ’ )
39 plt . ylabel ( ’x( t ) ’ )
147
40 plt . grid ()
41 p l t . a x i s ( [ 0 , 5 , −1, 2 ] )
42 p l t . show ( )
Listing 21.7: xxx
21.5 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
148
death rate = px2 (21.17)
ẋ = bx − px2 (21.18)
dx
Note! ẋ is the same as dt
We will simulate the number of bacteria in the jar after 1 hour, assuming that
initially there are 100 bacteria present.
[End of Exercise]
ẋ = ax + b (21.19)
Where a = − T1 , where T is defined as the time constant of the system. We can
set b = 1.
dx
Note! ẋ is the same as dt
[End of Exercise]
ẋ = −ax + bu (21.20)
dx
Note! ẋ is the same as dt
149
• u - Input variable, e.g., Control Signal from the Controller
• a, b - Constants
Start by setting a = 0.25, b = 2 and u = 1. Plot the simulation results. Use one
of the ODE solvers in Python.
[End of Exercise]
Where t is the simulation time, F(t) is an external force applied to the system, c
is the damping constant of the spring, k is the stiffness of the spring, m is a mass.
150
ẋ(t) is the first derivative of the position, which equals the velocity of the object
(m).
ẍ(t) is the second derivative of the position, which equals the acceleration of the
object (m).
Use your skills learned from the previous examples in order to simulate this
system. Use one of the ODE solvers in Python.
[End of Exercise]
1
3w0 + w = cos(t) (21.22)
1 + t2
Where the initial conditions are t0 = 0, tf = 5, w(t0 ) = 1
[End of Exercise]
ẋ1 = x2 (21.23)
g b
ẋ2 = − x1 − x2 (21.24)
r mr2
In the model, x1 is the distance from the starting point (which is when the
pendulum hangs straight down) and x2 is the velocity.
151
Figure 21.5: Pendulum
You may use the following values: m = 8, r = 5 and b = 10 (units are not so
important in this case). You may also explore with other values as well.
Assume you, e.g., take the pendulum away from the starting point and then drop
it, what happens then? You may, e.g., use the initial conditions x1 (0) = 0.5 and
x2 (0) = 0.
Explain the simulation results and see it in relation with the real world. Does
the simulation results make sense?
[End of Exercise]
152
Chapter 22
Optimization
f (x) = x2 + 2x + 1 (22.1)
We start by plotting the function:
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 xmin = −5
5 xmax = 5
6 dx = 0 . 1
7
8 N = i n t ( ( xmax − xmin ) /dx )
9
10 x = np . l i n s p a c e ( xmin , xmax , N+1)
11 #x = np . a r a n g e ( xmin , xmax+dx , dx ) #A l t e r n a t i v e i m p l e m e n t a t i o n
12
13 y = x ∗∗2 + 2∗ x + 1 ;
14
15
16 plt . plot (x , y)
17 p l t . x l i m ( [ xmin , xmax ] )
Listing 22.1: Optimization in Python
Python code:
1 from s c i p y i mpo rt o p t i m i z e
2
153
Figure 22.1: Optimization Example
3 xmin = −5
4 xmax = 5
5
6
7 def y(x) :
8 r e t u r n x ∗∗2 + 2∗ x + 1
9
10
11 x min = o p t i m i z e . fminbound ( y , xmin , xmax )
12
13 p r i n t ( x min )
Listing 22.2: xxx
xmin = -1.0
We see that this is the correct answer based on our plot in Figure 22.1.
[End of Example]
f (x) = x2 + 2x + 1 (22.2)
154
Implement a basic minimization function from scratch using either a For loop
or a While loop.
Make sure to test the function and see if you get the same answer as in the
example above.
[End of Exercise]
scipy.optimize.fmin
scipy.optimize.minimize scalar
scipy.optimize.minimize
f (x) = x2 + 2x + 1 (22.3)
scipy.optimize.fmin
scipy.optimize.minimize scalar
scipy.optimize.minimize
[End of Exercise]
f (x) = x3 − 4x (22.4)
scipyoptimize.fminbound
155
scipy.optimize.fmin
scipy.optimize.minimize scalar
scipy.optimize.minimize
[End of Exercise]
[End of Exercise]
[End of Exercise]
156
Part VI
157
Chapter 23
Introduction to Simulations
158
Chapter 24
Differential Equations
ẋ = −ax + bu (24.2)
dx
Note! ẋ is the same as dt
159
[End of Example]
With Python have we can solve these differential equations in many different
ways.
We can use so-called ODE solvers or we can make discrete version of the differ-
ential equations using discretization methods like Euler, etc.
With ODE solvers Python can solve these equations numerically. Higher order
differential equations must be reformulated into a system of first order differen-
tial equations.
In chapter 25 we will simulate (solve and plot the results) such differential
equations numerically using Euler discretization.
160
Chapter 25
Discrete Systems
25.1 Discretization
Sometimes we want to or need to discretize a continuous system and then sim-
ulate it in Python. When dealing with computer simulation, we need to create
a discrete version of our system. This means we need to make a discrete version
of our continuous differential equations. Interpolation, Curve Fitting, etc. is
also based on a set of discrete values (data points or measurements). The same
with Numerical Differentiation and Numerical Integration, etc.
Below we see a continuous signal vs the discrete signal for a given system with
discrete time interval T s = 0.1s.
x(k + 1) − x(k)
ẋ = (25.1)
Ts
161
Ts is the Sampling Time
ẋ = −ax + bu (25.2)
dx
Note! ẋ is the same as dt
• a, b - Constants
We start with finding the discrete differential equation.
xk+1 − xk
ẋ ≈ (25.3)
Ts
Ts - Sampling Interval
Then we get:
xk+1 − xk
= −axk + buk (25.4)
Ts
162
This gives the following discrete differential equation:
We set a=0.25, b=2 and u=1 (You can explore with other values on your own)
We start creating the Python Script for the simulation of this system:
1 # S i m u l a t i o n o f d i s c r e t e model
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 a = 0.25
7 b = 2
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 Tstop = 30
12 uk = 1 # Step Response
13 xk = 0
14 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
15 data = [ ]
16 data . append ( xk )
17
18
19 # Simulation
20 f o r k i n r a n g e (N) :
21 xk1 = ( 1 − a ∗Ts ) ∗ xk + Ts ∗ b ∗ uk
22 xk = xk1
23 data . append ( xk1 )
24
25
26 # Plot the Simulation Results
27 t = np . a r a n g e ( 0 , Tstop+Ts , Ts )
28
29 p l t . p l o t ( t , data )
30
31 # Formatting t h e a p p e a r a n c e o f t h e P l o t
32 p l t . t i t l e ( ’ S i m u l a t i o n o f dxdt = −ax + bu ’ )
33 plt . xlabel ( ’ t [ s ] ’ )
34 plt . ylabel ( ’x ’ )
35 plt . grid ()
36 p l t . a x i s ( [ 0 , 30 , 0 , 8 ] )
37 p l t . show ( )
Listing 25.1: Simulation of Discrete Dynamic System in Python
Lets also take a look at the Variable Explorer as shown in Figure 25.4.
163
Figure 25.3: Simulation of Discrete System using Python
1 # S i m u l a t i o n o f d i s c r e t e model
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 a = 0.25
7 b = 2
8
9 # Simulation Parameters
10 Ts = 0 . 1 # Sampling Time
11 Tstop = 30 # End o f S i m u l a t i o n Time
12 uk = 1 # Step Response
13 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
14 x = np . z e r o s (N+2) # I n i t i a l i z a t i o n t h e x v e c t o r
15 x[0] = 0
16
17
18 # Simulation
19 f o r k i n r a n g e (N+1) :
20 x [ k +1] = ( 1 − a ∗Ts ) ∗ x [ k ] + Ts ∗ b ∗ uk
21
22
23 # Plot the Simulation Results
24 t = np . a r a n g e ( 0 , Tstop+2∗Ts , Ts ) #C r e a t e t h e Time S e r i e s
25
26 plt . plot (t , x)
27
28 # Formatting t h e a p p e a r a n c e o f t h e P l o t
29 p l t . t i t l e ( ’ S i m u l a t i o n o f dxdt = −ax + bu ’ )
30 plt . xlabel ( ’ t [ s ] ’ )
31 plt . ylabel ( ’x ’ )
164
Figure 25.4: Variable Explorer for Discrete Simulation Example
32 plt . grid ()
33 p l t . a x i s ( [ 0 , 30 , 0 , 8 ] )
34 p l t . show ( )
Listing 25.2: Simulation of Discrete Dynamic System in Python
This gives of course the same results and the same plot.
You should try both examples, and then decide which one you prefer. I guess
there are also many other ways to do it.
[End of Example]
25.2 Exercises
Below you find different self-paced Exercises that you should go through and
solve on your own. The only way to learn Python is to do lots of Exercises!
165
ẋ = bx − px2 (25.8)
We will simulate the number of bacteria in the jar after 1 hour, assuming that
initially there are 100 bacteria present.
Find the discrete model using the Euler Forward method by hand and implement
and simulate the system in Python using a For Loop.
[End of Example]
dx1
= −x2 (25.9)
dt
dx2
= x1 (25.10)
dt
Find the discrete system and simulate the discrete system in MATLAB. Solve
the equations, e.g., in the time span [-1 1] with initial values [1, 1].
[End of Exercise]
166
Chapter 26
Real-Time Simulations
26.1 Introduction
Typically in a simulation, you run the simulation in a for loop. When you are
finished with the simulation you plot the data.
We repeat a basic simulation example from chapter 25.
We set a=0.25, b=2 and u=1 (You can explore with other values on your own)
We start creating the Python Script for the simulation of this system:
1 # S i m u l a t i o n o f d i s c r e t e model
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 a = 0.25
7 b = 2
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 Tstop = 30
12 uk = 1 # Step Response
13 xk = 0
14 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
15 data = [ ]
16 data . append ( xk )
17
18
19 # Simulation
20 f o r k i n r a n g e (N) :
21 xk1 = ( 1 − a ∗Ts ) ∗ xk + Ts ∗ b ∗ uk
167
22 xk = xk1
23 data . append ( xk1 )
24
25
26 # Plot the Simulation Results
27 t = np . a r a n g e ( 0 , Tstop+Ts , Ts )
28
29 p l t . p l o t ( t , data )
30
31 # Formatting t h e a p p e a r a n c e o f t h e P l o t
32 p l t . t i t l e ( ’ S i m u l a t i o n o f dxdt = −ax + bu ’ )
33 plt . xlabel ( ’ t [ s ] ’ )
34 plt . ylabel ( ’x ’ )
35 plt . grid ()
36 p l t . a x i s ( [ 0 , 30 , 0 , 8 ] )
37 p l t . show ( )
Listing 26.1: Simulation of Discrete Dynamic System in Python
As you can see from the code and when running the code, the simulation results
are plotted all in one operation after the simulation is finished, i.e, after the for
loop.
[End of Example]
Sometimes we want to plot one value at the time inside the loop, so-called
”Real-Time simulations”. That is also the case if we want to plot data from a
sensor or a real process.
168
26.2 Introduction to Real-Time Plotting
You can also use the matplotlib for real-time plotting.
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 p l t . a x i s ( [ 0 , 10 , 0 , 1 ] )
5
6 d e l a y = 1 #Se co n ds
7
8 f o r i in range (10) :
9 y = np . random . random ( )
10 plt . scatter ( i , y)
11 p l t . pause ( d e l a y )
12
13 p l t . show ( )
Listing 26.2: Real-Time Plotting in Python
You cannot see the the actual behavior of the plot by watching Figure 27.1, so
169
you need to run the Python program yourself.
If you run the code you see the plot is updated with a new value every second
as specified in the code.
[End of Example]
Note! If you use Anaconda and Spider, you typically need to change the the
settings for how graphics are are displayed in Spyder.
Select Preferences from the menu, then IPython console in the list of categories
on the left, then the tab Graphics at the top, and change the Graphics back-end
from Inline to e.g. Automatic or Qt. See Figure 27.2.
Figure 26.3: Change how Graphics are displayed in the Spyder Editor
170
13 xk = 0
14 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
15 data = [ ]
16 data . append ( xk )
17
18 p l t . a x i s ( [ 0 , N, 0 , 1 0 ] )
19
20 f o r k i n r a n g e (N) :
21 xk1 = ( 1 − a ∗Ts ) ∗ xk + Ts ∗ b ∗ uk
22 xk = xk1
23 data . append ( xk1 )
24
25 p l t . s c a t t e r ( k , xk1 )
26 p l t . pause ( Ts )
27
28 p l t . show ( )
Listing 26.3: Real-Time Simulation of Discrete Dynamic System in Python
You cannot see the the actual behavior of the plot by watching Figure 26.4, so
you need to run the Python program yourself.
If you run the code you see the plot is updated with a new value every second
as specified in the code.
In this example we have locked the scaling using the axis method. If we remove
or comment out the line ”plt.axis([0, N, 0, 10])”, we get a plot the automatically
scales the x axis and the y axis. Whats best depends on if you know the
simulation length from the beginning and know the minimum and maximum
value of the simulation results.
171
Figure 26.5 shows the Real-Time Plot with Auto-scaling after 30 iterations for
this example. You cannot see the the actual behavior of the plot by watching
Figure 26.5, so you need to run the Python program yourself.
The examples shown shows the discrete time step k on the x-axis. Typically we
want to display the continuous time t instead. Some small adjustment to the
examples make this possible. See the code below:
1 # Real−Time S i m u l a t i o n o f D i s c r e t e System
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 a = 0.25
7 b = 2
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 Tstop = 30
12 uk = 1 # Step Response
13 xk = 0
14 y s c a l e m a x = 10
15 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
16 data = [ ]
17 data . append ( xk )
172
18
19 p l t . a x i s ( [ 0 , N∗Ts , 0 , y s c a l e m a x ] )
20
21 f o r k i n r a n g e (N) :
22 xk1 = ( 1 − a ∗Ts ) ∗ xk + Ts ∗ b ∗ uk
23 xk = xk1
24 data . append ( xk1 )
25
26 t = Ts∗k
27
28 p l t . s c a t t e r ( t , xk1 )
29 p l t . pause ( Ts )
30
31 p l t . show ( )
Listing 26.4: Real-Time Simulation of Discrete Dynamic System in Python
Figure 26.6 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 26.6, so you need to run the Python
program yourself.
We can also add some formatting regarding the appearance of the plot (xlabel,
ylabel, title, etc.). The final code example is shown below.
173
1 # Real−Time S i m u l a t i o n o f D i s c r e t e System
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 a = 0.25
7 b = 2
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 Tstop = 30
12 uk = 1 # Step Response
13 xk = 0
14 y s c a l e m a x = 10
15 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
16 data = [ ]
17 data . append ( xk )
18
19
20 # Formatting t h e a p p e a r a n c e o f t h e P l o t
21 p l t . t i t l e ( ’ S i m u l a t i o n o f dxdt = −ax + bu ’ )
22 plt . xlabel ( ’ t [ s ] ’ )
23 plt . ylabel ( ’x ’ )
24 plt . grid ()
25
26 p l t . a x i s ( [ 0 , N∗Ts , 0 , y s c a l e m a x ] )
27
28 f o r k i n r a n g e (N) :
29 xk1 = ( 1 − a ∗Ts ) ∗ xk + Ts ∗ b ∗ uk
30 xk = xk1
31 data . append ( xk1 )
32
33 t = Ts∗k
34
35 p l t . s c a t t e r ( t , xk1 )
36 p l t . pause ( Ts )
37
38 p l t . show ( )
Listing 26.5: Real-Time Simulation of Discrete Dynamic System in Python
[End of Example]
174
1 a n i = a n i m a t i o n . FuncAnimation ( f i g , animate , f a r g s =(xs , ys ) ,
i n t e r v a l =1000)
Still in the FuncAnimation() parameters, we set fargs, which are the arguments
we want to pass to our animate function (since we are not calling animate()
directly from within our own code). Then, we set interval, which is how long
we should wait between calls to animate() (in milliseconds).
In the example we update the plot every seconds by setting the interval=1000ms
as an input argument to the FuncAnaimation function.
1 im po rt d a t e t i m e a s dt
2 im po rt numpy a s np
3 im po rt matplotlib . pyplot as p l t
4 im po rt m at pl ot l ib . animation as animation
5
6 # Create f i g u r e f o r p l o t t i n g
7 fig = plt . figure ()
8 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
9 xs = [ ]
10 ys = [ ]
11
12
13 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
14 d e f animate ( i , xs , ys ) :
15
16 temp c = round ( np . random . random ( ) , 2 )
17
18 # Add x and y t o l i s t s
19 xs . append ( dt . d a t e t i m e . now ( ) . s t r f t i m e ( ’%H:%M:%S.% f ’ ) )
20 ys . append ( temp c )
21
22 # L i m i t x and y l i s t s t o 20 i t e m s
23 xs = xs [ − 2 0 : ]
24 ys = ys [ − 2 0 : ]
25
26 # Draw x and y l i s t s
27 ax . c l e a r ( )
28 ax . p l o t ( xs , ys )
175
29
30 # Format p l o t
31 p l t . x t i c k s ( r o t a t i o n =45 , ha= ’ r i g h t ’ )
32 p l t . s u b p l o t s a d j u s t ( bottom =0 .3 0)
33 p l t . t i t l e ( ’ Temperature Data ’ )
34 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
35
36 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
37 a n i = a n i m a t i o n . FuncAnimation ( f i g , animate , f a r g s =(xs , ys ) ,
i n t e r v a l =1000)
38 p l t . show ( )
Listing 26.6: Real-Time Plotting with Animation
Figure 27.3 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 27.3, so you need to run the Python
program yourself.
[End of Example]
Python Code:
176
1 im po rt d a t e t i m e a s dt
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4 im po rt m a t p l o t l i b . a n i m a t i o n a s a n i m a t i o n
5 # Create f i g u r e f o r p l o t t i n g
6 fig = plt . figure ()
7 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
8 xs = [ ]
9 ys = [ ]
10
11 xk = 0 # I n i t i a l Value f o r x
12
13 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
14 d e f s i m u l a t i o n ( i , xs , ys ) :
15
16 # Model P a r a m e t e r s
17 a = 0.25
18 b = 2
19
20 # Simulation Parameters
21 Ts = 0 . 1 # Sampling Time
22 uk = 1 # Step Response
23 g l o b a l xk # S i n c e we change x i n s i d e a f u n c t i o n we d e f i n e i t a s
a gobal v a r i a b l e
24
25 # Model o f D i s c r e t e System
26 xk1 = ( 1 − a ∗Ts ) ∗ xk + Ts ∗ b ∗ uk
27 xk = xk1
28
29 # Add x and y t o l i s t s
30 xs . append ( dt . d a t e t i m e . now ( ) . s t r f t i m e ( ’%H:%M:%S.% f ’ ) )
31 ys . append ( xk1 )
32
33 N = 60 # L i m i t x and y l i s t s t o N i t e m s
34 xs = xs [−N : ]
35 ys = ys [−N : ]
36
37 # Draw x and y l i s t s
38 ax . c l e a r ( )
39 ax . p l o t ( xs , ys )
40
41 # Format p l o t
42 p l t . x t i c k s ( r o t a t i o n =45 , ha= ’ r i g h t ’ )
43 p l t . s u b p l o t s a d j u s t ( bottom =0 .3 0)
44 p l t . t i t l e ( ’ S i m u l a t i o n o f dxdt = −ax + bu ’ )
45 plt . xlabel ( ’ t [ s ] ’ )
46 plt . ylabel ( ’x ’ )
47 plt . grid ()
48
49 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
50 a n i = a n i m a t i o n . FuncAnimation ( f i g , s i m u l a t i o n , f a r g s =(xs , ys ) ,
i n t e r v a l =100)
51 p l t . show ( )
Listing 26.7: Real-Time Simulation of Discrete Dynamic System with Animation
Figure 26.8 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 26.8, so you need to run the Python
program yourself.
177
Figure 26.8: Real-Time Simulation of Discrete Dynamic System with Animation
[End of Example]
Python Code:
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt m a t p l o t l i b . a n i m a t i o n a s a n i m a t i o n
4
5 # P ar a m e t e r s
6 x l e n = 200 # Number o f p o i n t s t o d i s p l a y
178
7 y range = [0 , 20] # Range o f p o s s i b l e Y v a l u e s t o d i s p l a y
8
9 # Create f i g u r e f o r p l o t t i n g
10 fig = plt . figure ()
11 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
12 xs = l i s t ( r a n g e ( 0 , 2 0 0 ) )
13 ys = [ 0 ] ∗ x l e n
14 ax . s e t y l i m ( y r a n g e )
15
16
17 # C r e a t e a b l a n k l i n e . We w i l l update t h e l i n e i n animate
18 l i n e , = ax . p l o t ( xs , ys )
19
20 # Add l a b e l s
21 p l t . t i t l e ( ’ Temperature Data ’ )
22 p l t . x l a b e l ( ’ Samples ’ )
23 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
24
25 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
26 d e f animate ( i , ys ) :
27
28 r a n d v a l = np . random . random ( ) ∗20 #G e n e r a t e Random V a l u e s
between 0 and 20
29
30 temp c = round ( r a n d v a l , 2 )
31
32 #p r i n t ( temp c )
33
34 # Add y t o l i s t
35 ys . append ( temp c )
36
37 # L i m i t y l i s t t o s e t number o f i t e m s
38 ys = ys [− x l e n : ]
39
40 # Update l i n e with new Y v a l u e s
41 l i n e . s e t y d a t a ( ys )
42
43 return line ,
44
45 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
46 a n i = a n i m a t i o n . FuncAnimation ( f i g ,
47 animate ,
48 f a r g s =(ys , ) ,
49 i n t e r v a l =100 ,
50 b l i t=True )
51 p l t . show ( )
Listing 26.8: Real-Time Plotting with Animation
Figure 27.4 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 27.4, so you need to run the Python
program yourself.
[End of Example]
179
Figure 26.9: Real-Time Plotting with Animation
Python Code:
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt m a t p l o t l i b . a n i m a t i o n a s a n i m a t i o n
4
5 # P ar a m e t e r s
6 N = 200
7 x len = N # Number o f p o i n t s t o d i s p l a y
8 y r a n g e = [ 0 , 1 0 ] # Range o f p o s s i b l e Y v a l u e s t o d i s p l a y
9
10 # Create f i g u r e f o r p l o t t i n g
11 fig = plt . figure ()
12 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
13 xs = l i s t ( r a n g e ( 0 , N) )
14 ys = [ 0 ] ∗ x l e n
15 ax . s e t y l i m ( y r a n g e )
16
17 xk = 0 # I n i t i a l Value f o r x
18
19 # C r e a t e a b l a n k l i n e . We w i l l update t h e l i n e i n animate
20 l i n e , = ax . p l o t ( xs , ys )
21
22 # Add l a b e l s
23 p l t . t i t l e ( ’ S i m u l a t i o n o f dxdt = −ax + bu ’ )
24 p l t . x l a b e l ( ’ Samples ’ )
25 plt . ylabel ( ’x ’ )
26
27 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
28 d e f s i m u l a t i o n ( i , ys ) :
29
30 # Model P a r a m e t e r s
31 a = 0.25
32 b = 2
33
34 # Simulation Parameters
35 Ts = 0 . 1 # Sampling Time
36 uk = 1 # Step Response
180
37 g l o b a l xk # S i n c e we change x i n s i d e a f u n c t i o n we d e f i n e i t a s
a gobal v a r i a b l e
38
39 # Model o f D i s c r e t e System
40 xk1 = ( 1 − a ∗Ts ) ∗ xk + Ts ∗ b ∗ uk
41 xk = xk1
42
43 # Add y t o l i s t
44 ys . append ( xk1 )
45
46 # L i m i t y l i s t t o s e t number o f i t e m s
47 ys = ys [− x l e n : ]
48
49 # Update l i n e with new Y v a l u e s
50 l i n e . s e t y d a t a ( ys )
51
52 return line ,
53
54 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
55 a n i = a n i m a t i o n . FuncAnimation ( f i g ,
56 simulation ,
57 f a r g s =(ys , ) ,
58 i n t e r v a l =100 ,
59 b l i t=True )
60 p l t . show ( )
Listing 26.9: Real-Time Simulation of Discrete Dynamic System with Animation
and increased Speed
Figure 26.10 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 26.10, so you need to run the Python
program yourself.
[End of Example]
https://scipy-cookbook.readthedocs.io/items/MatplotlibA nimations.html
Other resources:
https://learn.sparkfun.com/tutorials/graph-sensor-data-with-python-and-matplotlib/allplot-
sensor-data
https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-
loop-using-matplotlib
181
Figure 26.10: Real-Time Plotting with Animation
182
Part VII
183
Chapter 27
27.1 Introduction
Typically we want to plot the data from the sensor. We can plot save the data
in an array and then plot the data at the end of the program, but more likely
we want to plot one value at the time inside the loop, so-called ”Real-Time
plotting”.
In this chapter we only show how you can plot the data from any given sensor
using this general approach. Instead of the actual sensor data we just use the
random generator in Python.
To read the actual sensor data you typically need a DAQ (Data Acquisition)
device connected to you PC or, e.g, a Raspberry Pi device. In all cases you
will typically need to install a driver from the vendor of the DAQ device or the
sensor you are using.
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 p l t . a x i s ( [ 0 , 10 , 0 , 1 ] )
5
6 d e l a y = 1 #Se co n ds
7
8 f o r i in range (10) :
9 y = np . random . random ( )
10 plt . scatter ( i , y)
11 p l t . pause ( d e l a y )
184
12
13 p l t . show ( )
Listing 27.1: Real-Time Plotting in Python
You cannot see the the actual behavior of the plot by watching Figure 27.1, so
you need to run the Python program yourself.
If you run the code you see the plot is updated with a new value every second
as specified in the code.
[End of Example]
Note! If you use Anaconda and Spyder, you typically need to change the the
settings for how graphics are are displayed in Spyder.
Select Preferences from the menu, then IPython console in the list of categories
on the left, then the tab Graphics at the top, and change the Graphics back-end
from Inline to e.g. Automatic or Qt. See Figure 27.2.
185
Figure 27.2: Change how Graphics are displayed in the Spyder Editor
Still in the FuncAnimation() parameters, we set fargs, which are the arguments
we want to pass to our animate function (since we are not calling animate()
directly from within our own code). Then, we set interval, which is how long
we should wait between calls to animate() (in milliseconds).
186
Example 27.3.1. Real-Time Plotting with Animation
Below you find the Python Code for a basic example where we use the anima-
tion module in matplotlib.
In the example we update the plot every seconds by setting the interval=1000ms
as an input argument to the FuncAnaimation function.
1 im po rt d a t e t i m e a s dt
2 im po rt numpy a s np
3 im po rt matplotlib . pyplot as p l t
4 im po rt m at pl ot l ib . animation as animation
5
6 # Create f i g u r e f o r p l o t t i n g
7 fig = plt . figure ()
8 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
9 xs = [ ]
10 ys = [ ]
11
12
13 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
14 d e f animate ( i , xs , ys ) :
15
16 temp c = round ( np . random . random ( ) , 2 )
17
18 # Add x and y t o l i s t s
19 xs . append ( dt . d a t e t i m e . now ( ) . s t r f t i m e ( ’%H:%M:%S.% f ’ ) )
20 ys . append ( temp c )
21
22 # L i m i t x and y l i s t s t o 20 i t e m s
23 xs = xs [ − 2 0 : ]
24 ys = ys [ − 2 0 : ]
25
26 # Draw x and y l i s t s
27 ax . c l e a r ( )
28 ax . p l o t ( xs , ys )
29
30 # Format p l o t
31 p l t . x t i c k s ( r o t a t i o n =45 , ha= ’ r i g h t ’ )
32 p l t . s u b p l o t s a d j u s t ( bottom =0 .3 0)
33 p l t . t i t l e ( ’ Temperature Data ’ )
34 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
35
36 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
37 a n i = a n i m a t i o n . FuncAnimation ( f i g , animate , f a r g s =(xs , ys ) ,
i n t e r v a l =1000)
38 p l t . show ( )
Listing 27.2: Real-Time Plotting with Animation
Figure 27.3 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 27.3, so you need to run the Python
program yourself.
[End of Example]
187
Figure 27.3: Real-Time Plotting with Animation
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt m a t p l o t l i b . a n i m a t i o n a s a n i m a t i o n
4
5 # P ar a m e t e r s
6 x l e n = 200 # Number o f p o i n t s t o d i s p l a y
7 y range = [0 , 20] # Range o f p o s s i b l e Y v a l u e s t o d i s p l a y
8
188
9 # Create f i g u r e f o r p l o t t i n g
10 fig = plt . figure ()
11 ax = f i g . a d d s u b p l o t ( 1 , 1 , 1 )
12 xs = l i s t ( r a n g e ( 0 , 2 0 0 ) )
13 ys = [ 0 ] ∗ x l e n
14 ax . s e t y l i m ( y r a n g e )
15
16
17 # C r e a t e a b l a n k l i n e . We w i l l update t h e l i n e i n animate
18 l i n e , = ax . p l o t ( xs , ys )
19
20 # Add l a b e l s
21 p l t . t i t l e ( ’ Temperature Data ’ )
22 p l t . x l a b e l ( ’ Samples ’ )
23 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
24
25 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
26 d e f animate ( i , ys ) :
27
28 r a n d v a l = np . random . random ( ) ∗20 #G e n e r a t e Random V a l u e s
between 0 and 20
29
30 temp c = round ( r a n d v a l , 2 )
31
32 #p r i n t ( temp c )
33
34 # Add y t o l i s t
35 ys . append ( temp c )
36
37 # L i m i t y l i s t t o s e t number o f i t e m s
38 ys = ys [− x l e n : ]
39
40 # Update l i n e with new Y v a l u e s
41 l i n e . s e t y d a t a ( ys )
42
43 return line ,
44
45 # S e t up p l o t t o c a l l animate ( ) f u n c t i o n p e r i o d i c a l l y
46 a n i = a n i m a t i o n . FuncAnimation ( f i g ,
47 animate ,
48 f a r g s =(ys , ) ,
49 i n t e r v a l =100 ,
50 b l i t=True )
51 p l t . show ( )
Listing 27.3: Real-Time Plotting with Animation
Figure 27.4 shows the final plot for this example. You cannot see the the actual
behavior of the plot by watching Figure 27.4, so you need to run the Python
program yourself.
[End of Example]
https://scipy-cookbook.readthedocs.io/items/MatplotlibA nimations.html
189
Figure 27.4: Real-Time Plotting with Animation
Other resources:
https://learn.sparkfun.com/tutorials/graph-sensor-data-with-python-and-matplotlib/allplot-
sensor-data
https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-
loop-using-matplotlib
190
Chapter 28
Here you find more information, resources, videos and examples regarding DAQ:
https://www.halvorsen.blog/documents/technology/daq/
191
Figure 28.1: Data Acquisition (DAQ) System
Web:
http://www.ni.com/
DAQ hardware: WE will use a NI-USB-600x DAQ device from National Instru-
ments, such as:
• NI-USB-6001
• NI-USB-6008
• NI-USB-6009
They are almost identical and the prices is not so bad either.
USB-6008:
http://www.ni.com/en-no/support/model.usb-6008.html
The best way to do this is to use the NI-DAQmx Python API provided by Na-
tional Instruments (nidaqmx). The NI-DAQmx Python API is hosted on
GitHub.
The nidaqmx Python package is a wrapper around the NI-DAQmx C API us-
ing the ctypes Python library, and only supports the Windows operating system.
192
Figure 28.2: USB-6008
For more information about Python Resources for NI Hardware and Software:
ni.com/python
Web:
https://pypi.org/project/PyDAQmx/
https://pythonhosted.org/PyDAQmx/
28.2.1 NI-DAQmx
NI-DAQmx is the software you use to communicate with and control your NI
data acquisition (DAQ) device.
193
https://www.ni.com/download
With MAX you can make sure your DAQ device works as expected before you
start using it in your Python program. You can use the Test Panels to test your
analog and digital inputs and outputs channels.
You can also change name of the unit, which you need to use in your Python
code.
194
The nidaqmx Python package is a wrapper around the NI-DAQmx C API us-
ing the ctypes Python library, and only supports the Windows operating system.
Other resources:
Control NI DAQ Device with Python and NI DAQmx:
https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z0000019Pf1SAE
You can easily extend this examples to make them suit your needs. Typically
you need to include a while loop where you write and/or read from the DAQ
device inside the loop, e.g. read values from one or more sensors that are con-
nected to the DAQ device, you may want to create a control system reading
the process value and then later write the calculated control signal (e.g. using
a PID controller) back to the DAQ device and the process.
Note! The USB-6008 can only output a voltage signal between 0 and 5V.
[End of Example]
195
28.3.2 Analog Read
Example 28.3.2. Analog Read using NI DAQ Device
Python code:
1 im po rt nidaqmx
2
3 with nidaqmx . Task ( ) a s t a s k :
4 t a s k . a i c h a n n e l s . a d d a i v o l t a g e c h a n ( ”Dev1/ a i 1 ” )
5
6 value = task . read ( )
7 print ( value )
8 task . stop
Listing 28.2: Analog Read using NI DAQ Device
[End of Example]
[End of Example]
[End of Example]
196
28.3.3 Digital Write
Example 28.3.5. Digital Write using NI DAQ Device
Python code:
1 im po rt nidaqmx
2
3 with nidaqmx . Task ( ) a s t a s k :
4 t a s k . d o c h a n n e l s . a d d d o c h a n ( ”Dev1/ p o r t 0 / l i n e 0 ” )
5
6 v a l u e = True
7 task . s t a r t
8 task . write ( value )
9 task . stop
Listing 28.5: Digital Write using NI DAQ Device
[End of Example]
[End of Example]
You should use the ”nidaqmx.stream readers” and nidaqmx.stream writers classes
to increase the performance of your application, which accept pre-allocated
NumPy arrays.
https://nidaqmx-python.readthedocs.io/en/latest/stream readers.html#module-
nidaqmx.stream readers
https://nidaqmx-python.readthedocs.io/en/latest/stream writers.html#module-
nidaqmx.stream writers
197
28.4 Controlling LEDs
In this section we will see how we can control a LED from Python.
Figure 28.6 shows how you wire the LED and connect it to the DAQ device.
198
Figure 28.5: How to wire a LED on a Breadboard
Figure 28.6: Wire the LED and connect to the DAQ device
Below you see an example where we turn the LED on and off inside a loop.
Python code:
1 im po rt nidaqmx
2 im po rt time
3
4
5 with nidaqmx . Task ( ) a s t a s k :
6 t a s k . d o c h a n n e l s . a d d d o c h a n ( ”Dev1/ p o r t 0 / l i n e 0 ” )
7
8 v a l u e = True
9 task . s t a r t
10
11 i = 1
12 while i < 10:
13
199
14 task . write ( value )
15 time . s l e e p ( 1 )
16 v a l u e = not v a l u e
17 task . write ( value )
18 i = i +1
19
20 task . stop
Listing 28.8: Controlling a LED using Python
[End of Example]
• PC with Python
• DAQ device
• Breadboard
We connect the TMP36 to LabVIEW using a USB DAQ Device from National
Instruments, e.g., USB-6001, USB-6008 or similar. I have used a breadboard
for the wiring.
Figure 28.8 show how we can wire the TMP36 together with the USB-6008 DAQ
device.
200
Figure 28.7: TMP36 Temperature Sensor
From the Datasheet (Figure 28.9) we see that there is a linear relationship
between Voltage and degrees Celsius (28.3):
y = ax + b (28.3)
We can find a and b using the following known formula (28.4):
y2 − y1
y − y1 = (x − x1 ) (28.4)
x2 − x1
By putting (28.1) and (28.2) into (28.4) we get:
50 − 25
y − 25 = (x − 0.75) (28.5)
1 − 0.75
Then we get the following formula we can implement in our Python program:
y = 100x − 50 (28.6)
Python code:
201
Figure 28.8: TMP36 tmp36 Wiring
1 im po rt nidaqmx
2 im po rt time
3
4 from nidaqmx . c o n s t a n t s im por t (
5 TerminalConfiguration )
6
7
8 with nidaqmx . Task ( ) a s t a s k :
9 t a s k . a i c h a n n e l s . a d d a i v o l t a g e c h a n ( ”Dev1/ a i 0 ” ,
t e r m i n a l c o n f i g=T e r m i n a l C o n f i g u r a t i o n . RSE)
10
11 i = 0
12 while i < 10:
13
14 v o l t a ge = task . read ( )
15
16 d e g r e e s C = 100∗ v o l t a g e − 50
17
18 p r i n t ( ” Sample : ” , i )
19 p r i n t ( ” V o l t a g e Value : ” , round ( v o l t a g e , 2 ) )
20 p r i n t ( ” C e l s i u s Value : ” , round ( degreesC , 1 ) )
21 p r i n t ( ” \n” )
22 time . s l e e p ( 1 )
23 i = i +1
24
25 task . stop
Listing 28.9: Read TMP36 Temperature Data
In the example an ordinary while loop in combination with the sleep() function
have been used to read one new value each second.
[End of Example]
202
Figure 28.9: TMP3x Datasheet
In this example we will plot the data from the sensor using the Real-time plot-
ting examples shown in Chapter 27.
203
21 task . s t a r t
22
23
24 # This f u n c t i o n i s c a l l e d p e r i o d i c a l l y from FuncAnimation
25 d e f readdaq ( i , xs , ys ) :
26
27 #Read Value from DAQ d e v i c e
28 v o l t a g e = task . read ( )
29
30 #Convert V o l t a g e t o d e g r e e s C e l s i u s
31 d e g r e e s C = 100∗ v o l t a g e − 50
32 temp c = round ( degreesC , 1 )
33 p r i n t ( ” C e l s i u s Value : ” , temp c )
34
35 # Add x and y t o l i s t s
36 xs . append ( dt . d a t e t i m e . now ( ) . s t r f t i m e ( ’%H:%M:%S.% f ’ ) )
37 ys . append ( temp c )
38
39 # L i m i t x and y l i s t s t o 20 i t e m s
40 xs = xs [ − 2 0 : ]
41 ys = ys [ − 2 0 : ]
42
43 # Draw x and y l i s t s
44 ax . c l e a r ( )
45 ax . p l o t ( xs , ys )
46
47 # Format p l o t
48 p l t . x t i c k s ( r o t a t i o n =45 , ha= ’ r i g h t ’ )
49 p l t . s u b p l o t s a d j u s t ( bottom =0 .3 0)
50 p l t . t i t l e ( ’ Temperature Data ’ )
51 p l t . y l a b e l ( ’ Temperature ( deg C) ’ )
52
53
54 # S e t up p l o t t o c a l l readdaq ( ) f u n c t i o n p e r i o d i c a l l y
55 a n i = a n i m a t i o n . FuncAnimation ( f i g , readdaq , f a r g s =(xs , ys ) ,
i n t e r v a l =1000)
56 p l t . show ( )
57 task . stop
Listing 28.10: Real-Time Plotting of Temperature Data
[End of Example]
• PC with Python
• DAQ device
204
• Breadboard
• 10kohm Thermistor
• 10kohm Resistor
• Wires for connecting the components and create the circuit
1
= A + B ln(R) + C(ln(R))3 (28.7)
TK
where A, B and C are constants with the following values: A = 0.001129148, B =
0.000234125, C = 8.76741E − 08
TC = TK − 273.15 (28.9)
Wiring...
Figure 28.10 shows how we wire the components together.
205
Figure 28.11: Voltage Divider
206
where Rt is our 10kohm Thermistor and R0 is an ordinary 10kohm Resistor.
Vin in our case will be +5V which we get from the USB-6008 DAQ device as
shown in the wiring diagram.
1. We wire the circuit on the Breadboard and connect it to the DAQ device
2. We measure Vout using the DAQ
3. We calculate Rt using the Voltage Divider equation
Vout R0
Rt = Vin −Vout
207
24 # Steinhart constants
25 A = 0.001129148
26 B = 0.000234125
27 C = 0.0000000876741
28
29 # S t e i n h a r t −Hart Equation
30 TempK = 1 / (A + (B ∗ np . l o g ( Rt ) ) + (C ∗ pow ( np . l o g ( Rt ) , 3 ) )
)
31
32 # Convert from K e l v i n t o C e l s i u s
33 TempC = TempK − 2 7 3 . 1 5
34
35 p r i n t ( ” Sample : ” , i )
36 p r i n t ( ” V o l t a g e Value : ” , round ( Vout , 2 ) )
37 p r i n t ( ” C e l s i u s Value : ” , round (TempC, 1 ) )
38 p r i n t ( ” \n” )
39 time . s l e e p ( 1 )
40 i = i +1
41
42 task . stop
Listing 28.11: Read Thermistor Temperature Data
[End of Example]
[End of Example]
Here some examples will be shown using a preset temperature sensor from Na-
tional Instruments called NI USB-TC01. This is a USB based temperature
without need for any kind of wiring, you just plug it in and make your Python
program. Since the NI USB-TC01 is compatible with NI-DAQmx, you can pro-
gram it in the same way as other DAQ devices from NI.
208
Figure 28.13: TC-01 Thermocouple Device
1 im po rt nidaqmx
2
3 t a s k = nidaqmx . Task ( )
4
5 t a s k . a i c h a n n e l s . a d d a i t h r m c p l c h a n ( ”TC01/ a i 0 ” )
6
7 task . s t a r t ()
8
9 value = task . read ( )
10 p r i n t ( round ( v a l u e , 1 ) )
11
12 task . stop ()
13 task . c l o s e ()
Listing 28.13: TC-01 Thermocouple Python Example
This is just a basic example, which you can easily extend using a while loop or
using some kind of plotting, etc..
[End of Example]
209
Part VIII
Control Systems
210
Chapter 29
https://pypi.org/project/control
https://python-control.readthedocs.io
pip i n s t a l l c o n t r o l
211
Functions for Model Creation and Manipulation:
There are lots of other functions. They are documented in the Python Control
Systems Library Documentation:
https://python-control.readthedocs.io
212
29.1.2 MATLAB compatibility module
The control.matlab module contains a number of functions that emulate some
of the functionality of MATLAB. The intent of these functions is to provide
a simple interface to the python control systems library (python-control) for
people who are familiar with the MATLAB Control Systems Toolbox.
1 im po rt m a t p l o t l i b . p y p l o t a s p l t # MATLAB p l o t t i n g f u n c t i o n s
2 from c o n t r o l . matlab im po rt ∗ # MATLAB−l i k e f u n c t i o n s
3
4 # P ar a m e t e r s d e f i n i n g t h e system
5 m = 250.0 # system mass
6 k = 40.0 # spring constant
7 b = 60.0 # damping c o n s t a n t
8
9 # System m a t r i c e s
10 A = [ [ 0 , 1 . ] , [−k/m, −b/m ] ]
11 B = [ [ 0 ] , [ 1 /m ] ]
12 C = [[1. , 0]]
13 s y s = s s (A, B, C, 0 )
14
15 # Step r e s p o n s e f o r t h e system
16 plt . figure (1)
17 yout , T = s t e p ( s y s )
18 p l t . p l o t (T . T, yout . T)
19
20 # Bode p l o t f o r t h e system
21 plt . figure (2)
22 mag , phase , om = bode ( s y s )
Listing 29.1: MATLAB compatibility module Example
[End of Example]
• Transfer Functions
• State-space Models
213
Figure 29.1: MATLAB compatibility module Example
• PID Control
• Frequency Response
y(s)
H(s) = (29.1)
u(s)
214
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 num = np . a r r a y ( [ 3 ] )
5 den = np . a r r a y ( [ 4 , 1 ] )
6
7 H = c o n t r o l . t f (num , den )
8
9 p r i n t ( ’H( s ) = ’ , H)
Listing 29.2: Basic Transfer Function in Python
[End of Example]
A general linear State-space model can then be written on this compact form:
ẋ = Ax + Bu (29.3)
y = Cx + Du (29.4)
x˙1 = x2 (29.5)
x˙1 0 1 x1 0 0 u1
= + (29.8)
x˙2 −1 −3 x2 2 4 u2
215
x1 u1
y= 5 6 7 0 (29.9)
x2 u2
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt c o n t r o l
3
4 # System m a t r i c e s
5 A = [ [ 0 , 1 ] , [ −1 , − 3 ] ]
6 B = [[0 , 0] , [2 , 4]]
7 C = [[5 , 6]]
8 D = [[7 , 0]]
9 s s m o d e l = c o n t r o l . s s (A, B, C, D)
Listing 29.3: State space model
[End of Example]
Z t
Kp
u(t) = Kp e + edτ + Kp Td ė (29.10)
Ti 0
216
Where u is the controller output and e is the control error:
Where
r is the Reference Signal or Set-point
y is the Process value, i.e., the Measured value
The transfer function for the PID controller is (we use Laplace on 29.10):
u(s) Kp
Hpid (s) = = Kp + + Kp Td s (29.12)
e(s) Ti s
Or like this:
u(s) Kp (Td Ti s2 + Ti s + 1)
Hpid (s) = = (29.13)
e(s) Ti s
29.3.1 PI Control
Very often we only need to use the PI Algorithm (29.14):
Z t
Kp
u(t) = Kp e + edτ (29.14)
Ti 0
u(s) Kp (Ti s + 1)
Hpi (s) = = (29.15)
e(s) Ti s
217
Chapter 30
Transfer Functions
Transfer functions are a model form based on the Laplace transform. Transfer
functions are very useful in analysis and design of linear dynamic systems.
y(s)
H(s) = (30.1)
u(s)
Where y is the output and u is the input. A general transfer function can be
written on the following general form:
numerator(s)
H(s) = (30.2)
denominator(s)
or to be more specific:
Below we will learn more about some important special cases of this general
form, namely the 1.order transfer function and the 2.order transfer function.
We will use the Python Control Systems Library. The Python Control Systems
Library (python-control) is a Python package that implements basic operations
for analysis and design of feedback control systems.
https://python-control.readthedocs.io
218
Given the following transfer function:
3
H(s) = (30.4)
4s + 1
The Python code becomes:
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 num = np . a r r a y ( [ 3 ] )
5 den = np . a r r a y ( [ 4 , 1 ] )
6
7 H = c o n t r o l . t f (num , den )
8
9 p r i n t ( ’H( s ) = ’ , H)
Listing 30.1: Create Transfer Function in Python
[End of Example]
3s + 3
H(s) = (30.5)
4s2 + 5s + 6
The Python code becomes:
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 num = np . a r r a y ( [ 3 , 2 ] )
5 den = np . a r r a y ( [ 4 , 5 , 6 ] )
6
7 H = c o n t r o l . t f (num , den )
8
9 p r i n t ( ’H( s ) = ’ , H)
Listing 30.2: Create Transfer Function in Python
[End of Example]
x(s) K
H(s) = = (30.6)
u(s) Ts + 1
219
Where K is the Gain and T is the Time constant. u is the input signal, while x
is the output signal.
In the time domain we get the following differential equation (using Inverse
Laplace):
1
ẋ = (−x + Ku) (30.7)
T
dx
Note that ẋ is the same as dt .
We can draw the following block diagram of the system as shown in Figure 30.1.
Poles: A 1.order system has a pole p = − T1 . In Python you may use the pole()
function in order to find the poles. You can also use the pzmap() function.
Step Response: In Python you may use the step response() function in order
to find the step response.
3
H(s) = (30.8)
4s + 1
The Python code becomes:
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 K = 3
5 T = 4
6
7 num = np . a r r a y ( [K] )
8 den = np . a r r a y ( [ T , 1 ] )
220
9
10 H = c o n t r o l . t f (num , den )
11
12 p r i n t ( ’H( s ) = ’ , H)
Listing 30.3: Basic Transfer Function in Python
[End of Example]
y(s) K
H(s) = = (30.9)
u(s) Ts + 1
Here we will start by finding the mathematical expression for the step response
(y(t)):
1
⇔1 (30.10)
s
221
Or more general:
U
⇔U (30.11)
s
Where
U
u(s) = (30.13)
s
This gives:
U K U
y(s) = H(s) = (30.14)
s Ts + 1 s
In Python we can use the step response function from the Python Control Sys-
tems Library.
Python code:
1 >>> t , y = s t e p r e s p o n s e ( s y s , t , x0 )
222
Where sys is either a transfer function or a state-space model, x0 is the start/ini-
tial condition and t is the time vector. Note that t is auto-computed if not given.
3
H(s) = (30.17)
4s + 1
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt c o n t r o l
4
5 K = 3
6 T = 4
7
8 num = np . a r r a y ( [K] )
9 den = np . a r r a y ( [ T , 1 ] )
10
11 H = c o n t r o l . t f (num , den )
12 p r i n t ( ’H( s ) = ’ , H)
13
14 t , y = c o n t r o l . s t e p r e s p o n s e (H)
15 plt . plot (t , y)
Listing 30.4: Basic Step Response Example
You should of course use different functions for creating grid, axis, title, xlabel,
ylabel, etc. These are exemplified in other chapters.
[End of Example]
3
H(s) = (30.18)
4s + 1
Here we will use the TransferFunction class to define the Laplace operator s
as a constant. This can then be used to create variables that allow algebraic
creation of transfer functions
The Python code for defining the transfer function in an alternative way and
plotting the step response:
223
Figure 30.3: Step Response Example
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt c o n t r o l
3
4 s = control . TransferFunction . s
5
6 H = (3) /(4∗ s + 1)
7
8 p r i n t ( ’H( s ) = ’ , H)
9
10 t , y = c o n t r o l . s t e p r e s p o n s e (H)
11
12 plt . plot (t , y)
Listing 30.5: Alternative definition of the Transfer Function
[End of Example]
224
K
H(s) = e−τ s (30.19)
Ts + 1
In the time domain we get the following differential equation (using Inverse
Laplace):
1
ẋ = (−x + Ku(t − τ )) (30.20)
T
Step response for a 1.order process with time delay, see Figure 30.5.
Example 30.2.1. 1.order Transfer Function with Time Delay using Pade Ap-
proximation
225
Given the following transfer function with time delay:
3
H(s) = e−2s (30.21)
4s + 1
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt c o n t r o l
4
5 K = 3
6 T = 4
7
8 num = np . a r r a y ( [K] )
9 den = np . a r r a y ( [ T , 1 ] )
10
11 H1 = c o n t r o l . t f (num , den )
12 p r i n t ( ’H1( s ) = ’ , H1)
13
14
15 Tau = 2
16 N = 10 # Order o f t h e Approximation
17
18
19 [ num pade , den pade ] = c o n t r o l . pade ( Tau ,N)
20 Hpade = c o n t r o l . t f ( num pade , den pade )
21 p r i n t ( ’ Hpade ( s ) = ’ , Hpade )
22
23 H = c o n t r o l . s e r i e s (H1 , Hpade )
24 p r i n t ( ’H( s ) = ’ , H)
25
26 t , y = c o n t r o l . s t e p r e s p o n s e (H)
27
28 plt . plot (t , y)
Listing 30.6: Basic Step Response Example
You should try to change the variable N in the code, which is the order of the
Pade approximation.
You should of course also use different functions for creating grid, axis, title,
xlabel, ylabel, etc. These are exemplified in other chapters.
[End of Example]
226
Figure 30.6: Step Response 1.order with Time Delay using Pade
y(s) K
H(s) = = (30.22)
u(s) s
Poles: The Integrator has a pole in origo: p=0. In Python you may use the
pole() function in order to find the poles. You can also use the pzmap() func-
tion.
Step Response: In Python you may use the step response() function in order
to find the step response.
Here we will start by finding the mathematical expression for the step response
(y(t)):
1
⇔1 (30.23)
s
227
KU 1
y(s) = H(s)u(s) = = KU 2 (30.24)
s s s
y(t) = KU t (30.26)
y(s) K
H(s) = = (30.27)
u(s) s
We will find poles, perform step response, etc. in Python for this system.
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt c o n t r o l
4
5 K = 3
6 num = np . a r r a y ( [K] )
7 den = np . a r r a y ( [ 1 , 0 ] )
8 H = c o n t r o l . t f (num , den )
9 p r i n t ( ’H( s ) = ’ , H)
10
11 p = c o n t r o l . p o l e (H)
12
13
14 t , y = c o n t r o l . s t e p r e s p o n s e (H)
15 plt . plot (t , y)
16 p l t . t i t l e ( ’ Step Response ’ )
17 plt . xlabel ( ’ t [ s ] ’ )
18 plt . ylabel ( ’y( t ) ’ )
19 plt . grid ()
20 plt . axis ([0 , 7 , 0 , 22])
21 p l t . show ( )
228
22
23 c o n t r o l . pzmap (H)
24 p l t . show ( )
Listing 30.7: Integrator
In the simulation we have set K = 3. You should explore with other values as
well and observe the results.
Instead of using the step response() function, we can implement and plot (30.26):
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3
4 #Model P a r a m e t e r s
5 K = 3
6
7 # Simulation Parameters
8 U = 1 # A s t e p i n t h e c o n t r o l s i g n a l a t t=0
9 t = 0
10
11 tstart = 0
12 t s t o p = 10
13
14 increment = 1
15
16 y = []
17 y = np . z e r o s ( t s t o p )
18
19 t = np . a r a n g e ( t s t a r t , t s t o p , i n c r e m e n t )
20
21
22 # Define the Function
23 f o r k in range ( tstop ) :
24 y[k] = K ∗ U ∗ t [k]
25
26
27 # Plot the Simulation Results
28 plt . plot (t , y)
29 p l t . t i t l e ( ’ Step Response ’ )
30 plt . xlabel ( ’ t [ s ] ’ )
31 plt . ylabel ( ’y( t ) ’ )
32 p l t . show ( )
Listing 30.8: Integrator from scratch
[End of Example]
229
K
H(s) = (30.28)
as2 + bs + c
K
H(s) = (30.29)
( ωs0 )2 + 2ζ ωs0 + 1
Where
K is the gain
ζ is the relative damping factor
ω0 [rad/s] is the undamped resonance frequency
K
H(s) = (30.30)
(T1 s + 1)(T2 s + 1)
We see that this system can be considered as two 1.order systems in series:
K 1 K
H(s) = = (30.31)
(T1 s + 1) (T2 s + 1) (T1 s + 1)(T2 s + 1)
3
H(s) = (30.32)
4s + 1
230
Figure 30.7: Serial Block Diagram
5
H(s) = (30.33)
2s + 1
Python code:
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt c o n t r o l
4
5 K = 3
6 T = 4
7 num = np . a r r a y ( [K] )
8 den = np . a r r a y ( [ T , 1 ] )
9 H1 = c o n t r o l . t f (num , den )
10
11 K = 5
12 T = 2
13 num = np . a r r a y ( [K] )
14 den = np . a r r a y ( [ T , 1 ] )
15 H2 = c o n t r o l . t f (num , den )
16
17 H = c o n t r o l . s e r i e s (H1 , H2)
18
19 p r i n t ( ’H( s ) = ’ , H)
20
21 t , y = c o n t r o l . s t e p r e s p o n s e (H)
22 plt . plot (t , y)
Listing 30.9: Serial Block Diagram Example
[End of Example]
231
Figure 30.8: Parallel Block Diagram
3
H(s) = (30.34)
4s + 1
5
H(s) = (30.35)
2s + 1
Python code:
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt c o n t r o l
4
5 K = 3
6 T = 4
7 num = np . a r r a y ( [K] )
8 den = np . a r r a y ( [ T , 1 ] )
9 H1 = c o n t r o l . t f (num , den )
10
11 K = 5
12 T = 2
13 num = np . a r r a y ( [K] )
14 den = np . a r r a y ( [ T , 1 ] )
15 H2 = c o n t r o l . t f (num , den )
16
17 H = c o n t r o l . p a r a l l e l (H1 , H2)
18
19 p r i n t ( ’H( s ) = ’ , H)
20
21 t , y = c o n t r o l . s t e p r e s p o n s e (H)
22 plt . plot (t , y)
Listing 30.10: Parallel Block Diagram Example
[End of Example]
232
30.5.3 Feedback Block Diagrams
Feedback:
3
H(s) = (30.36)
4s + 1
5
H(s) = (30.37)
2s + 1
Python code:
1 im po rt numpy a s np
2 im po rt m a t p l o t l i b . p y p l o t a s p l t
3 im po rt c o n t r o l
4
5 K = 3
6 T = 4
7 num = np . a r r a y ( [K] )
8 den = np . a r r a y ( [ T , 1 ] )
9 H1 = c o n t r o l . t f (num , den )
10
11 K = 5
12 T = 2
13 num = np . a r r a y ( [K] )
14 den = np . a r r a y ( [ T , 1 ] )
15 H2 = c o n t r o l . t f (num , den )
16
17 H = c o n t r o l . f e e d b a c k (H1 , H2)
18
19 p r i n t ( ’H( s ) = ’ , H)
20
21 t , y = c o n t r o l . s t e p r e s p o n s e (H)
233
22 plt . plot (t , y)
Listing 30.11: Feedback Block Diagram Example
[End of Example]
234
Chapter 31
31.1 Introduction
A state-space model is a structured form or representation of a set of differen-
tial equations. State-space models are very useful in Control theory and design.
The differential equations are converted in matrices and vectors.
...
ẋn = a1 mx1 + a2 mx2 + +an mxn + b1 mu1 + b2 mu2 + +bn 1un
ẋ = Ax + Bu (31.1)
y = Cx + Du (31.2)
dx
Note that ẋ is the same as dt .
x˙1 = x2 (31.3)
235
2x˙1 = −2x1 − 6x2 + 4u1 + 8u2 (31.4)
x˙1 1 0 x1 0 0 u1
= + (31.6)
x˙2 −3−1 x2 2 4 u2
x1 u1
y= 5 6 7 0 (31.7)
x2 u2
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt c o n t r o l
3
4 # System m a t r i c e s
5 A = [ [ 0 , 1 ] , [ −1 , − 3 ] ]
6 B = [[0 , 0] , [2 , 4]]
7 C = [[5 , 6]]
8 D = [[7 , 0]]
9 s s m o d e l = c o n t r o l . s s (A, B, C, D)
Listing 31.1: State space model
[End of Example]
Where t is the simulation time, F(t) is an external force applied to the system, c
is the damping constant of the spring, k is the stiffness of the spring, m is a mass.
ẋ(t) is the first derivative of the position, which equals the velocity of the object
(m).
236
Figure 31.1: Mass-Spring-Damper System
ẍ(t) is the second derivative of the position, which equals the acceleration of the
object (m).
x˙1 0 1 x1 0
= k c + 1 u (31.9)
x˙2 −m −m x2 m
x1
y= 1 0 (31.10)
x2
Python code:
1 im po rt m a t p l o t l i b . p y p l o t a s p l t
2 im po rt c o n t r o l
3
4 # P ar a m e t e r s d e f i n i n g t h e system
5 m = 250.0 # system mass
6 k = 40.0 # spring constant
7 c = 60.0 # damping c o n s t a n t
8
9 # System m a t r i c e s
10 A = [ [ 0 , 1 . ] , [−k/m, −c /m ] ]
11 B = [ [ 0 ] , [ 1 /m ] ]
12 C = [[1. , 0]]
13 s y s = c o n t r o l . s s (A, B, C, 0 )
14
237
15 # Step r e s p o n s e f o r t h e system
16 t , y = control . step response ( sys )
17 plt . plot (t , y)
Listing 31.2: Mass Spring Damper System
[End of Example]
238
Chapter 32
Frequency Response
32.1 Introduction
The frequency response of a system is a frequency dependent function which
expresses how a sinusoidal signal of a given frequency on the system input is
transferred through the system. Each frequency component is a sinusoidal sig-
nal having certain amplitude and a certain frequency.
The frequency response is an important tool for analysis and design of signal
filters and for analysis and design of control systems.The frequency response
can be found experimentally or from a transfer function model.
https://python-control.readthedocs.io
32.1.1 Theory
The frequency response of a system is defined as the steady-state response of
the system to a sinusoidal input signal. When the system is in steady-state, it
differs from the input signal only in amplitude/gain (A) and phase lag (φ).
239
Figure 32.1: Frequency Response Definition
Where A = YU is the ratio between the amplitudes of the output signal and the
input signal (in steady-state).
y(s)
H(S) = (32.3)
u(s)
We have that:
6 H(jω)
H(jω) = |H(jω)|ej (32.4)
Where H(jω) is the frequency response of the system, i.e., we may find the
frequency response by setting s = jω in the transfer function.
240
diagram, φ(ω).
You can find the Bode diagram from experiments on the physical process or
from the transfer function (the model of the system).
With Python you can easily create Bode diagram from the Transfer function
model using the bode() function in the Python Control Systems Library.
241
The A(ω) axis is in decibel (dB), where the decibel value of x is calculated as:
3
H(s) = (32.8)
4s + 1
The Python code becomes:
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 num = np . a r r a y ( [ 3 ] )
5 den = np . a r r a y ( [ 4 , 1 ] )
6
7 H = c o n t r o l . t f (num , den )
8 p r i n t ( ’H( s ) = ’ , H)
9
10 c o n t r o l . bode (H, dB=True )
Listing 32.1: Frequency Response - 1.order
Instead of Plotting the Bode Diagram we can also use the bode function for
calculation and showing the data as well. We can also specify which frequencies
we want to include.
Python Code:
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 num = np . a r r a y ( [ 3 ] )
5 den = np . a r r a y ( [ 4 , 1 ] )
6
7 H = c o n t r o l . t f (num , den )
8 p r i n t ( ’H( s ) = ’ , H)
9
10 w l i s t = [ 0 . 0 1 , 0 . 1 , 1 , 2 ,3 ,5 ,10 , 100]
11 [ mag , phase , w ] = c o n t r o l . bode (H, w l i s t , dB=True )
12
13 # Convert t o D e c i b e l
14 magdb = 20 ∗ np . l o g 1 0 ( mag )
15 #magdb = c o n t r o l . mag2db ( mag ) A l t e r n a t i v e s o l u t i o n : This i s a
premade f u n c t i o n implmenting t h e f o r m u l a above
16 p r i n t ( magdb )
242
Figure 32.3: Frequency Response 1.order
17
18 # Convert t o D e g r e e s
19 p h a s e d e g = phase ∗ 180/ np . p i ;
20 p r i n t ( phasedeg )
Listing 32.2: Frequency Response - 1.order
[End of Example]
3
H(s) = (32.9)
4s2 + 5s + 6
The Python code becomes:
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 num = np . a r r a y ( [ 3 ] )
5 den = np . a r r a y ( [ 4 , 5 , 6 ] )
6
7 H = c o n t r o l . t f (num , den )
8 p r i n t ( ’H( s ) = ’ , H)
243
9
10 c o n t r o l . bode (H, dB=True )
Listing 32.3: Frequency Response - 2.order
[End of Example]
3s + 3
H(s) = (32.10)
4s2 + 5s + 6
The Python code becomes:
1 im po rt numpy a s np
2 im po rt c o n t r o l
3
4 num = np . a r r a y ( [ 3 , 2 ] )
5 den = np . a r r a y ( [ 4 , 5 , 6 ] )
6
7 H = c o n t r o l . t f (num , den )
8 p r i n t ( ’H( s ) = ’ , H)
244
9
10 c o n t r o l . bode (H, dB=True )
Listing 32.4: Frequency Response Example
[End of Example]
245
Part IX
Python Database
Development
246
Chapter 33
Here we will learn how we can use Python for communication with a Database
system such as SQL Server or MySQL. We will learn how we connect to a
database, how we can insert data into the database and retrieve data from the
database.
Here you can learn more about Database Systems, download examples and get
additional resources, see videos, etc.:
https://www.halvorsen.blog/documents/technology/database/
247
Figure 33.1: ER Diagram Example
system, like insert data into the database and retrieve data from the database.
Here you can learn more about SQL, download examples and get additional
resources, see videos, etc.:
https://www.halvorsen.blog/documents/technology/database/
33.3 MySQL
Here we will see how we can communicate with a MySQL database from Python.
33.4 MongoDB
Here we will see how we can communicate with a MongoDB database from
Python.
248
Chapter 34
pyodbc is an open source Python module that can be used to accessing ODBC
databases.
34.3 pyodbc
pyODBC uses the Microsoft ODBC driver for SQL Server.
249
Note that the ”SQL Server Native Client ...” and earlier drivers are deprecated
and should not be used for new development.
The connection string can be written like this:
1 im po rt pyodbc
2
3 s e r v e r = ”NUCHPH\\SQLEXPRESS”
4 d a t a b a s e = ”BOOKS”
5 username = ” s a ”
6 password = ” xxx ”
7 conn = pyodbc . c o n n e c t ( ”DRIVER={ODBC D r i v e r 17 f o r SQL S e r v e r } ;
SERVER=” + s e r v e r + ” ;DATABASE=” + d a t a b a s e + ” ; UID=” +
username + ” ;PWD=” + password )
8
9 c u r s o r = conn . c u r s o r ( )
10
11 c u r s o r . e x e c u t e ( ”SELECT @@version ; ” )
12 row = c u r s o r . f e t c h o n e ( )
13 w h i l e row :
14 p r i n t ( row [ 0 ] )
15 row = c u r s o r . f e t c h o n e ( )
Listing 34.1: Basic SQL Server Example
Below you find a basic example where data are retrieved from the SQL Server.
1 im po rt pyodbc
2
3 s e r v e r = ”NUCHPH\\SQLEXPRESS”
4 d a t a b a s e = ”BOOKS”
5 username = ” s a ”
6 password = ” xxx ”
7 conn = pyodbc . c o n n e c t ( ”DRIVER={ODBC D r i v e r 17 f o r SQL S e r v e r } ;
SERVER=” + s e r v e r + ” ;DATABASE=” + d a t a b a s e + ” ; UID=” +
username + ” ;PWD=” + password )
8
250
9 c u r s o r = conn . c u r s o r ( )
10
11
12 f o r row i n c u r s o r . e x e c u t e ( ” s e l e c t BookId , T i t l e , I s b n from BOOK” ) :
13 p r i n t ( row . BookId , row . T i t l e , row . I s b n )
Listing 34.2: Getting Data from SQL Server
[End of Example]
34.7 pymssql
Resources:
https://pypi.org/project/pymssql/
http://www.pymssql.org/
34.8 Resources
https://docs.microsoft.com/en-us/sql/connect/python/python-driver-for-sql-server
251
Part X
Python Application
Development
252
Chapter 35
OPC allows “plug-and-play”, gives benefits as reduces installation time and the
opportunity to choose products from different manufactures.
253
We have different OPC standards: “Real-time” data (OPC DA), Historical data
(OPC HDA), Alarm Event data (OPC AE), etc.
We can divide the OPC in 2 categories: OPC Classic and OPC UA, which is
the next generation OPC.
In Figure 35.3 we get an overview of the main differences between OPC Classic
and OPC UA.
Here you find more information, resources, videos and examples regarding OPC:
https://www.halvorsen.blog/documents/technology/opc/
254
Figure 35.3: Typical OPC Scenario
These OPC specification are based on the OLE, COM, and DCOM technologies
developed by Microsoft for the Microsoft Windows operating system family.
This makes it complicated to make it work in a modern Network! Typically
you need a Tunneller Software in order to share the OPC data in a network
(between OPC Servers and Clients)
35.3 OPC UA
OPC UA (Unified Architecture).
• Cross-platform
• No dedicated OPC Server is no longer necessary because the server can
run on an embedded system
255
Figure 35.4: OPC Firewall Challenges
In Figure 35.4 we get an overview of the main differences between OPC Classic
and OPC UA regarding communication over a network.
256
Chapter 36
https://www.halvorsen.blog/documents/programming/labview/
Her you find information about LabVIEW, you find lots of resources like training
material, videos, code examples, etc.
Web:
https://zone.ni.com/reference/en-XX/help/371361R-01/glang/pythonp al/
Use the Python functions to call Python code from LabVIEW. See Figure 36.1
Note! LabVIEW supports calling Python version 2.7 and 3.6. Although un-
supported versions might work with the LabVIEW Python functions, NI rec-
ommends using supported versions of Python only.
Ensure that the bitness of Python corresponds to the bitness of LabVIEW in-
stalled on the machine. This means if you have LabVIEW 32 bit, you should
use Python 32 bit and if you have LabVIEW 64 bit, you should use Python 64
257
bit.
To run the Python code, LabVIEW requires the Python shared libraries (DLLs)
in the system path.
For Windows: If you install Python 3.6, add the directory containing python36.dll
to the system path. If you install Python 2.7, add the directory containing
python27.dll to the system path.
For detailed instructions regarding Installing Python for Calling Python Code:
http://www.ni.com/product-documentation/54295/en/
LabVIEW functions for dealing with Python: Open Python Session Python
Node Close Python Session
Here I will present some examples how we can integrate an existing Python
script or Python function.
Example 36.2.1. Python Integration in LabVIEW
We want to use Python to covert between Ceslius and Fahrenheit (and vice
versa).
258
3 Tf = ( Tc ∗ 9 / 5 ) + 32
4 r e t u r n Tf
5
6
7 d e f f 2 c ( Tf ) :
8
9 Tc = ( Tf − 3 2 ) ∗ ( 5 / 9 )
10 r e t u r n Tc
Listing 36.1: Python Functions
Then, we create a Python script for testing the functions (test fahrenheit.py):
1 from f a h r e n h e i t i mp ort c 2 f , f 2 c
2
3 Tc = 0
4
5 Tf = c 2 f ( Tc )
6
7 p r i n t ( ” F a h r e n h e i t : ” + s t r ( Tf ) )
8
9
10 Tf = 32
11
12 Tc = f 2 c ( Tf )
13
14 p r i n t ( ” C e l s i u s : ” + s t r ( Tc ) )
Listing 36.2: Testing the Functions
Lets make the LabVIEW program that call these Python functions:
In Figure 36.4 we see LabVIEW Code for calling both Python functions (c2f
and f2c) from LabVIEW.
[End of Example]
259
Figure 36.2: Python Integration in LabVIEW
260
Figure 36.4: Python Integration in LabVIEW
261
Chapter 37
https://www.halvorsen.blog/documents/technology/iot/raspberry pi.php
Other Resources:
https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-
with-the-raspberry-pi/programming-in-python
First, before you start programming Python on a Raspberry Pi device, you need
to install an operating system like Raspbian. Raspbian is a Linux distribution
tailor made for Raspberry Pi.
https://www.raspberrypi.org/downloads/raspbian/
262
Part XI
Resources
263
Chapter 38
If you are familiar with MATLAB, you can relatively easily switch to Python.
Most of the functionality and the functions in different toolboxes have similar
functions in Python.
If you are looking for MATLAB resources, please see the following:
https://www.halvorsen.blog/documents/programming/matlab/
• Introduction to MATLAB
• Modelling, Simulation and Control in MATLAB
264
38.1 Use Python inside MATLAB
To call Python libraries from MATLAB, you need to install the reference im-
plementation for Python (CPython).
For more information, see the following:
https://se.mathworks.com/help/matlab/getting-started-with-python.html
MATLAB and Python must also be the same architecture/bit version. If you
have MATLAB 64 bits version, you need Python 64 bits. If you have MATLAB
32 bits version, you need Python 32 bits.
If MATLAB and Python don’t the same architecture/bit version, you need to
either install the proper version of either MATLAB or Python. You may also
need to ”Add Python to Path” as described in Chapter 3.
Earlier we have created a Python module with 2 functions. The first function
should convert from Celsius to Fahrenheit and the other function should convert
from Fahrenheit to Celsius.
265
1 d e f c 2 f ( Tc ) :
2
3 Tf = ( Tc ∗ 9 / 5 ) + 32
4 r e t u r n Tf
5
6
7 d e f f 2 c ( Tf ) :
8
9 Tc = ( Tf − 3 2 ) ∗ ( 5 / 9 )
10 r e t u r n Tc
Listing 38.1: Fahrenheit Functions
1 clc
2 Tc = 0
3 Tf = py . f a h r e n h e i t . c 2 f ( Tc )
4 Tc = py . f a h r e n h e i t . f 2 c ( Tf )
Listing 38.3: Calling Python Library and Functions from MATLAB
[End of Example]
266
For more information, see the following:
https://se.mathworks.com/help/matlab/matlab-engine-for-python.html
267
Chapter 39
Python Resources
SciPy Library:
https://www.scipy.org
Matplotlib Library:
https://matplotlib.org
268
Visual studio Code:
https://code.visualstudio.com
Visual Studio:
https://visualstudio.microsoft.com
PyCharm:
https://www.jetbrains.com/pycharm/
Wing:
https://wingware.com
Jupyter Notebook:
http://jupyter.org
269
Bibliography
270
Part XII
Solutions to Exercises
271
Start using Python
Create a Script in Python (.py file) where you plot the solution x(t) in the time
interval:
0 ≤ t ≤ 25
Add Grid, and proper Title and Axis Labels to the plot.
Python Script:
1 im po rt math a s mt
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5
6 # Model P a r a m e t e r s
7 T = 5
8 a = −1/T
9
10 # Simulation Parameters
11 x0 = 1
12 t = 0
13
14 tstart = 0
272
15 t s t o p = 25
16
17 increment = 1
18
19 x = []
20 x = np . z e r o s ( t s t o p +1)
21
22 t = np . a r a n g e ( t s t a r t , t s t o p +1 , i n c r e m e n t )
23
24
25 # Define the Function
26 f o r k in range ( tstop ) :
27 x [ k ] = mt . exp ( a ∗ t [ k ] ) ∗ x0
28
29
30 # Plot the Simulation Results
31 plt . plot (t , x)
32 p l t . t i t l e ( ’ S i m u l a t i o n o f Dynamic System ’ )
33 plt . xlabel ( ’ t ’ )
34 plt . ylabel ( ’x ’ )
35 plt . grid ()
36 p l t . a x i s ( [ 0 , 25 , 0 , 1 ] )
37 p l t . show ( )
[End of Exercise]
273
Mathematics in Python
[End of Solution]
ln (ax2 + bx + c) − sin(ax2 + bx + c)
f (x) = (4)
4πx2 + cos(x − 2)(ax2 + bx + c)
274
Given a = 1, b = 3, c = 5 Find f (9)
(The answer should be f (9) = 0.0044)
Tip! You should split the expressions into different parts, such as:
poly = ax2 + bx + c
num = . . .
den = . . .
f = ...
This makes the expression simpler to read and understand, and you minimize
the risk of making an error while typing the expression in Python.
When you got the correct answer try to change to, e.g., a = 2, b = 8, c = 6
Find f (9)
Python Script:
1 ...
[End of Solution]
275
Discrete Systems
Bacteria Population
In this task we will simulate a simple model of a bacteria population in a jar.
ẋ = bx − px2 (7)
We will simulate the number of bacteria in the jar after 1 hour, assuming that
initially there are 100 bacteria present.
Find the discrete model using the Euler Forward method by hand and imple-
ment and simulate the system in Python using a For Loop.
xk+1 − xk
ẋ ≈ (8)
Ts
Ts - Sampling Interval
Then we get:
276
xk+1 − xk
= bxk − px2k (9)
Ts
Python Script:
1 # Simulation of Bacteria Population
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 b = 1
7 p = 0.5
8
9 # Simulation Parameters
10 Ts = 0 . 0 1
11 Tstop = 1
12 xk = 100
13 N = i n t ( Tstop /Ts ) # S i m u l a t i o n l e n g t h
14 data = [ ]
15 data . append ( xk )
16
17
18 # Simulation
19 f o r k i n r a n g e (N) :
20 xk1 = xk + Ts∗ ( b ∗ xk − p ∗ xk ∗ ∗ 2 ) ;
21 xk = xk1
22 data . append ( xk1 )
23
24 # Plot the Simulation Results
25 t = np . a r a n g e ( 0 , Tstop+Ts , Ts )
26
27 plt . p l o t ( t , data )
28 plt . t i t l e ( ’ Simulation of Bacteria Population ’ )
29 plt . xlabel ( ’ t [ s ] ’ )
30 plt . ylabel ( ’x ’ )
31 plt . grid ()
32 plt . axis ([0 , 1 , 0 , 100])
33 plt . show ( )
[End of Solution]
277
Figure 2: Simulation of Bacteria Population
dx1
= −x2 (11)
dt
dx2
= x1 (12)
dt
Find the discrete system and simulate the discrete system in Python. Solve the
equations, e.g., in the time span [-1 1] with initial values [1, 1].
Python Script:
1 # S i m u l a t i o n with 2 V a r i a b l e s
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
6 b = 1
7 p = 0.5
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 T s t a r t = −1
12 Tstop = 1
13 x1k = 1
14 x2k = 1
15 N = i n t ( ( Tstop−T s t a r t ) /Ts ) # S i m u l a t i o n l e n g t h
16 datax1 = [ ]
278
17 datax2 = [ ]
18 datax1 . append ( x1k )
19 datax2 . append ( x2k )
20
21
22 # Simulation
23 f o r k i n r a n g e (N) :
24 x1k1 = x1k − Ts ∗ x2k
25 x2k1 = x2k + Ts ∗ x1k
26
27 x1k = x1k1
28 x2k = x2k1
29 datax1 . append ( x1k1 )
30 datax2 . append ( x2k1 )
31
32 # Plot the Simulation Results
33 t = np . a r a n g e ( T s t a r t , Tstop+Ts , Ts )
34
35 plt . p l o t ( t , datax1 , t , datax2 )
36 plt . t i t l e ( ’ S i m u l a t i o n with 2 V a r i a b l e s ’ )
37 plt . xlabel ( ’ t [ s ] ’ )
38 plt . ylabel ( ’x ’ )
39 plt . grid ()
40 plt . a x i s ( [ − 1 , 1 , −1.5 , 1 . 5 ] )
41 plt . show ( )
Alternative Solution:
1 # S i m u l a t i o n with 2 V a r i a b l e s
2 im po rt numpy a s np
3 im po rt m a t p l o t l i b . p y p l o t a s p l t
4
5 # Model P a r a m e t e r s
279
6 b = 1
7 p = 0.5
8
9 # Simulation Parameters
10 Ts = 0 . 1
11 T s t a r t = −1
12 Tstop = 1
13 N = i n t ( ( Tstop−T s t a r t ) /Ts ) # S i m u l a t i o n l e n g t h
14 x1 = np . z e r o s (N+2)
15 x2 = np . z e r o s (N+2)
16 x1 [ 0 ] = 1
17 x2 [ 0 ] = 1
18
19
20 # Simulation
21 f o r k i n r a n g e (N+1) :
22 x1 [ k +1] = x1 [ k ] − Ts ∗ x2 [ k ]
23 x2 [ k +1] = x2 [ k ] + Ts ∗ x1 [ k ]
24
25
26 # Plot the Simulation Results
27 t = np . a r a n g e ( T s t a r t , Tstop+2∗Ts , Ts )
28
29 plt . p l o t ( t , x1 , t , x2 )
30 plt . t i t l e ( ’ S i m u l a t i o n with 2 V a r i a b l e s ’ )
31 plt . xlabel ( ’ t [ s ] ’ )
32 plt . ylabel ( ’x ’ )
33 plt . grid ()
34 plt . a x i s ( [ − 1 , 1 , −1.5 , 1 . 5 ] )
35 plt . show ( )
Choose the approach that fits you. You should also check the time that the
simulation take. For larger simulations, this second alternative may be better.
[End of Solution]
280
Python for Control Engineering