0% found this document useful (0 votes)
253 views

2 The Python Control Systems Library

The Python Control Systems Library (python-control) is an open source Python package that implements common operations for analyzing and designing feedback control systems. It provides support for standard linear time-invariant control systems as well as nonlinear input/output systems. The library takes advantage of popular Python packages like NumPy, Matplotlib, and Jupyter Notebooks. It has grown in popularity in recent years as Python has become a widely used language for science and engineering applications.

Uploaded by

Azt Rib
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
253 views

2 The Python Control Systems Library

The Python Control Systems Library (python-control) is an open source Python package that implements common operations for analyzing and designing feedback control systems. It provides support for standard linear time-invariant control systems as well as nonlinear input/output systems. The library takes advantage of popular Python packages like NumPy, Matplotlib, and Jupyter Notebooks. It has grown in popularity in recent years as Python has become a widely used language for science and engineering applications.

Uploaded by

Azt Rib
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

The Python Control Systems Library (python-control)

Sawyer Fuller, Ben Greiner, Jason Moore, Richard Murray, René van Paassen, Rory Yorke
https://python-control.org

Abstract— The Python Control Systems Library (python- a rich, graphical interface. JuliaControl [4] is an emerging
control) is an open source set of Python classes and functions open source effort that builds on the numerically robust Julia
that implement common operations for the analysis and design language. The primary difference between these libraries is
of feedback control systems. In addition to support for standard
LTI control systems (including time and frequency response, the underlying programming language. Several other Python-
block diagram algebra, stability and robustness analysis, and based packages were under development around the same
control system synthesis), the package provides support for time as python-control was started, including packages by
nonlinear input/output systems, including system interconnec- Roberto Bucher [2] and Ryan Krauss [5], both of whom have
tion, simulation, and describing function analysis. A MATLAB contributed ideas and code to the python-control library.
compatibility layer provides an many of the common functions
corresponding to commands available in the MATLAB Control An early decision in developing the package was to make
Systems Toolbox. The library takes advantage of the Python use of the SLICOT library of functions [8], which provides a
“scientific stack” of Numpy, Matplotlib, and Jupyter Notebooks set of FORTRAN subroutines for carrying out control com-
and offers easy interoperation with other category-leading putations. The use of SLICOT was enabled by the existence
software systems in data science, machine learning, and robotics of the slycot library created by Enrico Avventi [9], which
that have largely been built on Python.
provided a set of Python wrappers around the FORTRAN
I. INTRODUCTION code. By making use of slycot, it was possible to implement
many standard control functions quickly and easily. SLICOT
The Python Control Systems Library (python-control) is a was designed to be highly efficient, numerically stable, and
Python package that implements basic operations for analysis accurate, allowing many python-control functions to inherit
and design of feedback control systems. The package was these properties. As of 2019, slycot is available on Windows,
created in 2009, shortly after the publication of Feedback Mac, and Linux in binary form through the Anaconda soft-
Systems (FBS) by Åström and Murray [1]. The initial goal of ware distribution system and conda-forge [10]. This removes
the project was to implement the operations needed to carry the need to install and run a FORTRAN compiler, broadening
out all the examples in FBS. A primary motivation for the accessibility by simplifying the installation process for most
creation of the python-control library was the need for open- users.
source control design software built on the Python general- We are encouraged by growing usage numbers and world-
purpose programming language. The “scientific stack” of wide adoption. According to pypistats.org, downloads
NumPy, SciPy, and Matplotlib provide fast and efficient array using pip were 47,302/month in May 2021. The condastats
operations, linear algebra and other numerical functions, tool provides historical download numbers for Anaconda;
and plotting capabilities to Python users. Python-control they were 3686, 1969, 987, 315, and 71 for python-control
has benefited from this foundation, using, e.g., optimization during the month of June the past five years, indicating
routines from SciPy in its optimal control methods, and a download rate that is approximately doubling each year.
Matplotlib for Bode diagrams. This growth is partially attributable to being open source,
The scientific stack is fast-moving, however, and the which makes python-control accessible to people in industry,
python-control package has had to keep up with changes. hobbyists, and educators who may not want to pay for propri-
One example is Matplotlib moving away from a 1990s etary software. Users are also freely able to modify the code
MATLAB-like plotting paradigm, characterized by global to suit specific “long-tail” uses. But perhaps more important
state (e.g., the current figure) to one in which Matplotlib to its success is that python-control is written in Python,
library users are encouraged to more directly manage the a general-purpose language that has become a de facto
figures, axes, etc., currently in use. Another example is the language for science. Leading libraries in machine learning
“soft” deprecation of NumPy’s matrix class, which was used and data science, e.g. Pandas, TensorFlow, and PyTorch, and
in python-control’s linear-algebra-heavy code. in robotics, e.g. Robot Operating System and the Robotics
The Python Control Systems Library is one of many open Toolkit, are written in Python. This is complemented by wide
source tools that are available on different platforms. The availability of purpose-built libraries for graphics and user
GNU Octave application [3] is mainly compatible with MAT- interfaces, to name a few. This facilitates easy migration
LAB’s command line interface, allowing rapid conversion of and interoperation between libraries and domains if desired.
code from MATLAB to an open source alternative. Scilab [7] Integration with Jupyter notebooks leverages elements of
is a free and open source software for engineers and scien- the broader open source software community to allow for
tists, also mainly compatible with MATLAB and provides a simple and intuitive design environment.
The remainder of this article provides a brief overview the planar vertical takeoff and landing (PVTOL) example
of the python-control package. While we indicate the calling in FBS [1]. A slightly different version of this example is
structure of the code and include a few simple examples, our available in the python-control GitHub repository.
intent here is not to provide a complete guide or tutorial to We begin by initializing the Python environment with the
using python-control, but rather to give a high level overview packages that we will use in the example:
that provides a flavor of what is available and documents # pvtol-nested.py - inner/outer design for
some of our design decisions. More detailed documentation # vectored thrust aircraft
is available at http://python-control.org. # RMM, 5 Sep 2009 (updated 11 May 2021)
II. PACKAGE STRUCTURE AND BASIC #
FUNCTIONALITY # This file works through a control design and
The python-control package implements an inheritance # analysis for the planar vertical takeoff and
hierarchy of dynamical system objects. For the most part, # landing (PVTOL) aircraft in Astrom and Murray.
when two systems are combined in some way through a
mathematical operation, one will be promoted to the type import control as ct
that is the highest of the two. Arranged in order from most import matplotlib.pyplot as plt
to least general, they are: import numpy as np
• InputOutputSystem: Input/output system that may be We next define the system that we plan to control (see [1]
nonlinear and time-varying for a more complete description of these dynamics):
– InterconnectedSystem: Interconnected I/O system
# System parameters
consisting of multiple subsystems
m = 4 # mass of aircraft
– NonlinearIOSystem: Nonlinear I/O system
J = 0.0475 # inertia around pitch axis
– LinearICSystem: Linear interconnected I/O sys-
r = 0.25 # distance to center of force
tems
g = 9.8 # gravitational constant
– LinearIOSystem: Linear I/O system
c = 0.05 # damping factor (estimated)
• LTI: Linear, time-invariant system
– FrequencyResponseData: Frequency response data # Transfer functions for dynamics
systems Pi = ct.tf([r], [J, 0, 0]) # inner loop (roll)
– StateSpace: State space systems Po = ct.tf([1], [m, c, 0]) # outer loop (posn)
– TransferFunction: Transfer functions
Each can be either discrete-time, that is, x(k + 1) = The control design is performed by using a lead compen-
f (x(k), u(k)); y(k) = g(x(k), u(k)) or continuous time, that sator to control the inner loop (roll axis):
is, ẋ = f (x, u); y = g(x, u). A discrete-time system is created # Inner loop control design
by specifying a nonzero ‘timebase’ dt when the system is #
constructed: # Controller for the pitch dynamics: the goal is
• dt = 0: continuous time system (default) # to have a fast response so that we can use this
• dt > 0: discrete time system with sampling period dt # as a simplified process for the lateral dynamics
• dt = True: discrete time with unspecified sampling
period # Design a simple lead controller for the system
• dt = None: no timebase specified k_i, a_i, b_i = 200, 2, 50
Linear, time-invariant systems can be interconnected using Ci = k_i * ct.tf([1, a_i], [1, b_i])
mathematical operations +, -, *, and /, as well as the domain- Li = Pi * Ci
specific functions feedback, parallel (+), and series (*). We can now analyze the results by plotting the frequency
Some important functions for LTI systems and their descrip- response as well as the Gang of 4:
tions are given in Table I. Other categories of tools that are
available include model simplification and reduction tools, # Loop transfer function Bode plot, with margins
matrix computations (Lyapunov and Ricatti equations), and plt.figure(); ct.bode_plot(Li, margins=True)
a variety of system creation, interconnection and conversion plt.savefig(’pvtol-inner-ltf.pdf’)
tools. A MATLAB compatibility layer is provided that has
functions and calling conventions that are equivalent to # Make sure inner loop specification is met
their MATLAB counterparts, e.g. tf, ss, step, impulse, plt.figure(); ct.gangof4_plot(Pi, Ci)
bode, margin, nyquist and so on. A complete list is avail- plt.savefig(’pvtol-gangof4.pdf’)
able at http://python-control.org. Figures 1a and b show the outputs from these commands.
III. EXAMPLE The outer loop (lateral position) is designed using a second
lead compensator, using the roll angle as the input:
To illustrate the use of the package, we present an example
of the design of an inner/outer loop control architecture for # Design lateral control system (lead compensator)
TABLE I: Sample functions available in the python-control package.
Frequency domain analysis:
sys(x[, squeeze]) Evaluate frequency response of an LTI system at complex frequenc(ies) x
sys.frequency_response(omega[, squeeze]) Evaluate frequency response of an LTI system at real angular frequenc(ies) omega
stability_margins(sysdata[, returnall, ...]) Calculate stability margins and associated crossover frequencies
phase_crossover_frequencies(sys) Compute frequencies and gains at intersections with the real axis in a Nyquist plot
bode_plot(syslist[, omega, plot, ...]) Bode plot for a system
nyquist_plot(syslist[, omega, plot, ...]) Nyquist plot for a system
gangof4_plot(P, C[, omega]) Plot the “Gang of 4” transfer functions for a system
nichols_plot(sys_list[, omega, grid]) Nichols plot for a system
Time domain analysis:
forced_response(sys[, T, U, X0, transpose, ...]) Simulated response of a linear system to a general input
impulse_response(sys[, T, X0, input, ...]) Compute the impulse response for a linear system
initial_response(sys[, T, X0, input, ...]) Initial condition response of a linear system
step_response(sys[, T, X0, input, output, ...]) Compute the step response for a linear system
step_info(sys[, T, X0, input, output, ...]) Compute step response characteristics
phase_plot(odefun[, X, Y, scale, X0, T, ...]) Phase plot for 2D dynamical systems
Other analysis functions and methods:
sys.dcgain() Return the zero-frequency (or DC) gain of an LTI system
sys.pole() Compute poles of an LTI system
sys.zero() Compute zeros of an LTI system
sys.damp() Compute natural frequency and damping ratio of LTI system poles
pzmap(sys[, plot, grid, title]) Plot a pole/zero map for a linear system
root_locus(sys[, kvect, xlim, ylim, ...]) Root locus plot
sisotool(sys[, kvect, xlim_rlocus, ...]) Sisotool style collection of plots inspired by MATLAB
Synthesis tools:
acker(A, B, poles) Pole placement using the Ackermann method
h2syn(P, nmeas, ncon) H2 control synthesis for plant P
hinfsyn(P, nmeas, ncon) H∞ control synthesis for plant P
lqr(A, B, Q, R[, N]) Linear quadratic regulator design
lqe(A, G, C, QN, RN, [, N]) Linear quadratic estimator design (Kalman filter) for continuous-time systems
mixsyn(g[, w1, w2, w3]) Mixed-sensitivity H-infinity synthesis
place(A, B, p) Place closed-loop poles

a_o, b_o, k_o = 0.3, 10, 2 IV. SPECIALIZED FUNCTIONALITY


Co = -k_o * ct.tf([1, a_o], [1, b_o]) In addition to basic control functions and MATLAB com-
Lo = -m * g * Po * Co patibility, the Python Control Systems Library has some spe-
cialized functions that allow analysis of nonlinear feedback
# Compute real outer-loop loop transfer function control systems.
L = Co * Hi * Po
A. Input/output systems
We can analyze the results using Bode plots, Nyquist plots
Python-control supports the notion of an input/output sys-
and time domain simulations:
tem in a manner that is similar to the MATLAB “S-function”
# Compute stability margins
implementation. Input/output systems can be combined using
gm, pm, wgc, wpc = ct.margin(L)
standard block diagram manipulation functions (including
overloaded operators), simulated to obtain input/output and
# Check to make sure that the specification is met
initial condition responses, and linearized about an oper-
plt.figure(); ct.gangof4_plot(-m * g * Po, Co)
ating point to obtain a new linear system that is both an
input/output and an LTI system.
# Nyquist plot for complete design
An input/output system is defined as a dynamical system
plt.figure(); ct.nyquist_plot(L)
that has a system state as well as inputs and outputs (either
plt.savefig(’pvtol-nyquist.pdf’)
inputs or states can be empty). The dynamics of the system
can be in continuous or discrete time. To simulate an
# Step response
input/output system, the input_output_response() function
t, y = ct.step_response(T, np.linspace(0, 20))
is used:
plt.figure(); plt.plot(t, y) t, y = input_output_response(io_sys, T, U,
plt.savefig(’pvtol-step.pdf’) X0, params)

Figures 1c and d show the outputs from the nyquist_plot Here, the variable T is an array of times and the variable
and step_response commands (note that the step_response U is the corresponding inputs at those times. The output
command only computes the response, unlike MATLAB). will be evaluated at those times, though the NumPy interp
V. DISCUSSION better. Compiled languages like C can execute as much as
The python-control package provides a variety of opera- 100 times faster than Python. Currently, however, the flexi-
tions for the analysis and design of feedback control systems. bility and fast iteration afforded by an interpreted language
In this section we discuss some of the issues, uses, and future provide distinct advantages. Many control design tasks, such
directions for the library. as PID design, can be simulated in less than a second
and therefore are more limited by the speed of the user
A. Experience using python-control in education interface than computation time. In fact, the task of executing
In 2013, the Aerospace Engineering department at the Python itself and the python-control is also completed within
Delft University of Technology transitioned to teaching that second. This short period, which is characteristic of
Python in the first bachelor year. The second-year course interpreted languages, facilitates rapid, exploratory cross-
in control theory, taught by Dr. René van Paassen, had domain investigations that are the cornerstone of design.
been using MATLAB for control system design. To provide No compilation also greatly aids development of the library
students with an opportunity to continue their use of Python, itself. Furthermore, execution speed is faster than a 100-fold
provisions were made to accommodate the python-control reduction because most numerical computation is performed
package in the course. The primary difficulty at the time was in low-level compiled libraries such as Numpy. Further
installation of python-control and Slycot, which was needed speedups are possible by compiling heavily-executed sec-
for introducing state space systems. This was initially solved tions using Cython or Numba. Julia is an emerging numerical
by creating and providing a Windows package to students language that includes a just-in-time (JIT) compiler. This
using Windows, and build and installation instructions for requires compiling at startup, requiring 10–30 seconds to
students who wished to use other operating systems. Students plot a system step response in ControlSystems.jl [4], after
had, and still have, the option to choose between using which execution runs at the speed of a compiled language. As
MATLAB and Python; initial adoption of Python and python- compilation time reduces and functionality expands in Julia,
control was in the order of 25%. However, in later years, with this tradeoff may become more advantageous, especially for
an increasing number of other courses and assignments in the compute-heavy nonlinear control (Section IV).
Bachelor program also transitioning to Python from a variety C. Future plans
of programming options (such as spreadsheets and Visual
Desired future functionality includes support for time
Basic), and the increased ease of installation by integration
delays and a SIMULINK-like graphical user environment
of python-control and slycot in the conda-forge ecosystem,
(building on pysimCoder [6]) available on platforms other
has led to Python and python-control becoming the de facto
than Linux. There is also a nascent effort to build a symbolic
choice for most students.
version of the library that will work with SymPy.
In 2021, Python-control’s support for discrete-time sys-
tems became sufficient to offer it as an alternative to Acknowledgements. The following individuals have con-
MATLAB in the University of Washington’s Digital Control tributed to the python-control package (individuals with 10
Systems Design course taught by Dr. Sawyer B. Fuller. Of 29 or more commits to the repository, ordered by the number
enrolled students, 11 responded to an anonymous survey at of commits): Richard Murray, Ben Greiner, Sawyer Fuller,
the middle of the quarter. Six of the respondents (55%) opted Clancy Rowley, René van Paassen, Rory Yorke, David de
to use Python-control rather than MATLAB where possible. Jong, Anthony De Bortoli, [gonmolina], Mikhail Pak, James
Student satisfaction with the software was encouraging: of Goppert, Arnold Braker, and Scott Livingston.
the six Python-control users, five indicated they would either R EFERENCES
“definitely” or “probably” use it for their next control design [1] K. J. Åström and R. M. Murray. Feedback Systems: An Introduction for
project if the option was available. Reasons given by these Scientists and Engineers. Princeton University Press, 2008. Available
students for using Python-control included that “Python is at http://fbsbook.org.
[2] R. Bucher. Practical experiences with Python and Linux RT at the
more versatile and free,” and “python can be used more easily SUPSI laboratory. IFAC-PapersOnLine, 52(9):133–138, 2019.
with [the Robot Operating System], which is used in most [3] J. W. Eaton, D. Bateman, S. Hauberg, and R. Wehbring. GNU Octave
things I am interested in.” One student was positive about version 6.2.0 manual: a high-level interactive language for numerical
computations, 2021.
the package’s usability: “The error messages for python were [4] Controlsystems.jl. http://juliacontrol.github.io/
more helpful and well-explained than I thought they would ControlSystems.jl/latest/. Accessed: 2021-05-14.
be.” A key limiting factor for Python-control was the lack [5] R. W. Krauss and W. J. Book. A Python module for modeling
and control design of flexible robots. Computing in Science and
of an alternative to Simulink for simulating interconnected Engineering, 9(3):41–45, 2007.
systems. PysimCoder [6], introduced in 2019, is one open- [6] PysimCoder – SIMULINK like editor for Python. http://
source graphical interface that may satisfy this deficiency. robertobucher.dti.supsi.ch/python/pysimcoder. Accessed: 2021-
05-14.
B. Python versus compiled languages for control design [7] Scilab. https://www.scilab.org. Accessed: 2021-05-13.
[8] SLICOT – A subroutine library in control and systems theory. http:
The interpreted nature of Python has facilitated the sci- //slicot.org. Accessed: 2021-05-14.
[9] Slycot – Python wrapper for SLICOT.
entific Python stack (NumPy, SciPy, Matplotlib, and Jupyter python-control/Slycot. Accessed: 2021-05-14.
https://github.com/

Notebooks), which are well-suited to a control design library. [10] Slycot conda-forge distribution. https://anaconda.org/
It is natural to ask whether a compiled language could be conda-forge/slycot. Accessed: 2021-05-14.

You might also like