### Control Systems in Python - Part 1 - Bode and Step Response

I hate matlab with passion, yet sadly, nearly everyone uses it.  I'm a fan of Python and open source stuff so here's a simple article on how to do some common control systems stuff in Python.

### First we need to make sure the environment is setup.

1. Install IPython (or you can use any other python shell, but a unicode supported shell is preferred)
2. Install python-control (numpy, scipy)
3. Install sympy

These should do if your on Ubuntu/debian:

sudo apt-get install python-sympy python-numpy python-scipy python-matplotlib ipython

Then you need to install python control, see How to download and install python-control

## Intro to using Sympy

Open ipython and run the following:

import sympy
from sympy import *
sympy.init_printing()
s = Symbol('s')

Now we can do things like define transfer functions using the symbolic variable s.

We can expand the bottom using the .simplify() method

and we can do something more complex like...
which is really nice because it does all the multiplication for us... and it’s much prettier than matlab.

An example of a system in feedback form:

Note: Use floats (number including a decimal )for all values you insert!

Doing Step Response Plots:
Okay cool, now let’s do something useful, add the following imports:

from control import matlab
import matplotlib.pyplot as plt

Copy or save and import this helper function (use %paste in iPython to enter it)

def stepResponse(Ts,*args,**kwargs):
num = Poly(Ts.as_numer_denom()[0],s).all_coeffs()
den = Poly(Ts.as_numer_denom()[1],s).all_coeffs()
tf = matlab.tf(map(float,num),map(float,den))
y,t = matlab.step([tf],*args,**kwargs)
plt.plot(t,y)
plt.title("Step Response")
plt.grid()
plt.xlabel("time (s)")
plt.ylabel("y(t)")
info ="OS: %f%s"%(round((y.max()/y[-1]-1)*100,2),'%')
try:
i10 = next(i for i in range(0,len(y)-1) if y[i]>=y[-1]*.10)
Tr = round(t[next(i for i in range(i10,len(y)-1) if y[i]>=y[-1]*.90)]-t[i10],2)
except StopIteration:
Tr = "unknown"
try:
Ts = round(t[next(len(y)-i for i in range(2,len(y)-1) if abs(y[-i]/y[-1])>1.02)]-t[0],2)
except StopIteration:
Ts = "unknown"

info += "\nTr: %s"%(Tr)
info +="\nTs: %s"%(Ts)
print info
plt.legend([info],loc=4)
plt.show()

Then run stepResponse(G), where Ts is the transfer function of the system

# Doing Bode, Magnitude / Phase plots:

def freqResponse(Ts,*args,**kwargs):
num = Poly(Ts.as_numer_denom()[0],s).all_coeffs()
den = Poly(Ts.as_numer_denom()[1],s).all_coeffs()
tf = matlab.tf(map(float,num),map(float,den))
matlab.bode([tf],*args,**kwargs)
plt.show()

Then you just call freqResponse(ts) like:
You can also pass in arguments to the matlab.bode and matplotlib semilogx methods like:
which plots using dB and Hz scales.  You might notice this is pretty sketch looking, it actually missed a significant part of the magnitude plot, to smooth it out pass in your own omega values, like:
which looks much better.

There’s lot more things you can do with the python-control library that isn’t implemented in the functions given here (such as plotting for various K values):

Anyways that’s enough for now...

Good luck and have fun!

1. Hi Jairus,

Thanks for these posts with control systems + Python. I've been looking for an alternative to MATLAB to help confirm homework answers and this looks like it'll do well.

I had an issue initially with your stepResponse function - it seems the following line is invalid:

--
y,t = matlab.step([tf],*args,**kwargs)
--

I've removed the list for the tf argument and I'm now able to use the function. With the list matlab.step() doesn't return the expected yout/time lists with version 0.6.

Perhaps this is due to differing versions or something of that nature.

Bryon

2. This comment has been removed by the author.

3. OVERSHOOT, round(..., 2) but why show more digits in the legend?

4. yout, t = matlab.step(tf, *args, **kwargs) #should have no [ ] or?

5. Same I have tried with tf without [ ] and *args and **kwargs

6. Thanks for this post...and the others. !!!!!! Cheers

7. My code have it errors when i copy and paste. Would like to have a direct chat with you cos I'm trying to figure this out with my Lecturer and it will be great to finally get a solution

### Kivy vs React-Native for building cross platform mobile apps

I've built three apps now using Kivy and one with React-Native, just wanted to share my thoughts on both. Just a warning, I am strongly biased towards python and this is all based on opinion and experience and is thus worth what you pay for it. I don't claim to be an expert in either of these, just have worked with each for several months.  If something is incorrect I'd love to hear advice. Kivy Demo of one of the apps Pros: Nice to be able to run natively on the desktop WITHOUT a simulator Python is easy to work with Use (almost) any python library Very easy to create custom widgets Kivy properties and data binding just work. Way nicer than React's "state" / flux / redux whatever you want to call it (stupid?).  Native interfaces (pyjnius) and (pyobjc) Runs and feels pretty smooth Cons: Default widget toolkit looks like Android 4.4. Requiring you use your own widgets or a theming kit like KivyMD  if styling bothers you Creating dy

### Control Systems in Python - Part 2 - Routh Hurwitz

In my last post Control Systems in Python Part 1 , i described how to setup and use Python for doing some basic plotting of transfer functions. One of the biggest benefits of using sympy vs numeric packages like matlab/numpy/scipy is the fact that you can use symbolic variables. This post includes a function for computing the Routh Hurwitz table (Note: It does not work for row's of zeros). Lets do my control systems design homework problem together :) (Warning: I have not verified if this answer is right so please correct me if it’s not!) The Problem The problem is DP 9.11 from Dorf & Bishop’s Modern Control Systems. ISBN 0136024580. Basically we have to design a controller to compensate for a system with a time delay. The controller is: And the system is: First we approximate the exponential term with a 2nd order polynomial using pade(0.4,2) such that: Thus the approximated system is: Using frequency response methods, design the controller so that th