Controlling a Simulink Model by a Python Controller
MATLAB’s Simulink is unparalleled in terms of the ability to simulate complex non-linear systems. It provides a no-frills experience to design dynamical models as is often the case with Robotics and Control Systems Design.
Simulink, however, lags behind in the ability to provide extensive support to Deep Learning Frameworks and thus leads to complications when designing Intelligent controllers for Simulink Models.
Python is unmatched in terms of support for Deep Learning Frameworks and Numerical Computation tools but fails to model complex non-linear systems.
Can't we use both Python and Simulink in sync to utilize the benefits of each of these tools to mitigate the challenges raised by the other?
In this article, we will take a look at establishing communication between MATLAB and Python and thus design a simple PI Controller in Python for a Model in Simulink.
Prerequisites
- MATLAB v2013 or higher (Author used 2018b)
- Python v3.6
Installation
Follow the instructions on the link https://in.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html to install Matlab Engine API for Python for your operating system. That’s it.
The Simulink Model
In Simulink, create the desired model of choice in Simulink and place a constant block in each place you want to enforce a control action from Python. In this case, a constant named ‘u’ with an initial value of 0 was added as a control action to the model. The variables that are needed to be seen by Python must be sent to Workspace through a ‘To Workspace’ Block.
The Workspace variable must be set to the format of ‘2D-Array’.
The Python Code
Importing the Necessary Libraries
import matlab.engine
import matplotlib.pyplot as plt
The matlab.engine library will establish communication with MATLAB and matplotlib will be used to plot the data obtained.
The Simulink Connection Class
This class sets up the connection between MATLAB and Python and develops a control loop to control the plant at each timestep.
The Controller Class
This class acts as the control strategy to provide control actions at each timestep.
Putting it all Together
The output of the code can be seen as follows-
Success !
Now one can easily modify the Controller class to incorporate better control strategies. Possibilities are endless.