%% Laboratory notes: Introduction to Simulink®
% Riccardo Antonello (riccardo.antonello@unipd.it) and Giulia Michieletto (giulia.michieletto@unipd.it)
% March 10, 2024
% Dept. of Management and Engineering, University of Padova, Italy
%
%
% This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.
%
%% Contents
% Introduction: what is Simulink ?
% Creation of a new model in Simulink
% Simulation of a linear model in Simulink
%
%% 1.  Introduction: what is Simulink ?
% Simulink is a graphical environment that allows to model, simulate and analyze dynamical systems represented in block-diagram form.
% A dynamical system is modeled as an oriented connection of oriented blocks, i.e. a (oriented) block diagram (indeed, "Simulink" stands for "simulation + link", to point out that the model used for simulation consists of several linked blocks).
% The causality assignment, namely the selection of what is input and what is output in every block, is implicitly performed during the construction of the model. Note that there are other simulation software tools, e.g. Spice for electrical circuit simulations, but also Modelica and other tools, where it is not necessary to perfrom a causality assignment before implementing the model.
% Block diagram modeling, as used in Simulink, is particularly suited for control systems since they are signal-oriented systems (i.e. causality is implicitly considered in the model definition) rather than energy-oriented systems (where energy exchanges are usually "not oriented"): this explain the widespread use of Simulink as a tool for modeling, simulation, analysis and validation of control systems.
%
% A block diagram is inserted in Simulink by using a graphical user interface. A rich library of built-in blocks is provided in Simulink; additional blocks can be created by the user.
% Block diagrams can be simulated by using the integration methods provided by Simulink. In practice, the block diagram is internally converted into a set of ODEs that are numerically integrated using the Matlab ODE solvers. Model analysis tools include linearization and trimming tools.
% Because of the strict integration between MATLAB and Simulink, it is possible to simulate, analyze, and revise a model in both environments at any moment.
%
%
%% 2.  Creation of a new model in Simulink
% Invoke Simulink
% run simulink from the Matlab command window: the Simulink Start Page opens. Note: run slLibraryBrowser to directly access to the Simulink Library Browser window (by skipping the Simulink Start Page).

slLibraryBrowser

%
% Create a new model
% select File\rightarrowNew/Model in the Simulink Library Browser window menu, or press the button New in the toolbar of the Library Browser. A new window (Model window) opens, inside which a block diagram can be created.
%
% Build a block diagram (Simulink model)
% drag and drop the Simulink blocks from the Simulink Library Browser to the Model Window.
% connect blocks with connection lines. Place the mouse over the output port of a block: the pointer changes to a cross. By holding the left mouse button pressed, move the pointer over the input terminal of another block and release the button. Alternatively, select a block by left clicking over it; then, by left clicking over another block while pressing the Ctrl button, a connection between the two blocks is created.
%
% Save a model (file with .slx or .mdl extension):
% use the menu option File\rightarrowSave As... in the Model window menu (or the equivalent button in the Simulink model window).
%
% Mouse usage to operate with blocks
% Left button: select a block.
% Drag and drop with the left button: move the block.
% Click and Hold and Release with the left button: select a group of blocks.
% Right button over a block: open a pop-up menu from which it is possible to select different operations to be performed on the block.
% Drag and drop with the right button: create a copy of the selected block.
% Double click with the left button over a block: open the Block Parameters window associated with the block.
%
% Mouse usage to operate with connections
% Left button: select a line.
% Drag and drop with the left button: drag the connection line (or one of its corners, if selected).
% Click and Hold and Release with the left button, starting from a corner of the connection line: create a derivation point in a connection line.
% Right button over a connection line: open a pop-up menu from which it is possible to select different operations to be performed on the line.
% Click and Hold and Release with the right button: create a derivation point in a connection line.
% Double click with the left button over a connection line: assign a label to the connection.
%
% Others
% To delete a block, select it and press the Canc button; alternatively, use the option Clear in the pop-up menu associated to the block.
% Blocks can be duplicated by cut and paste (Ctrl+C, Ctrl+V, Ctrl+X or by using the menu options).
% For inserting a block along a connection, drag the block over the connection and then release it.
% For disconnecting a block from a connection, drag it while holding Shift button pressed.
%
%% 3.  Simulation of a linear model in Simulink
% Consider the following simplified model of a DC motor, with input the armature voltage u_a and output the motor speed \omega_m:
% (1)    P(s) = \frac{\Omega_m(s)}{U_a(s)} = \frac{k}{T\,s+1}\,, \qquad k = 8.3, \quad T = 0.028
% Consider a 6\,V step input applied at t = 1\,s: determine the time-evolution of the rotor shaft speed in the time interval [0\,\mathrm{s}, 5\,\mathrm{s}].
%
% Prepare the Simulink model

% motor params
k = 8.3;    %  static gain
T = 0.028;  %  time constant

% voltage input params
ts = 1;     %  step time
As = 6;     %  step amplitude   

% open simulink model
open_system('sim_DC_mot.slx');

%
%
% Set the simulation parameters
% In the Model window menu, select Simulation \rightarrow Model Configuration Parameters (or press the equivalent button in the model window toolbar); a dialog box opens.
% In the dialog box, set Stop time to 5\,\mathrm{s} and ode45 with Variable step as the integration method for the simulation.
% Alternative: use the set_param routine.

set_param('sim_DC_mot', ...
    'SolverType', 'Variable-step', ...
    'Solver', 'ode45', ...
    'StopTime', '5');

%
% Some notes on the integration methods
% Let \dot{\mathbf{x}}(t) = \mathbf{f}(t,\mathbf{x}(t))represent the set of ordinary differential equations (ODE) associated with the model (1), from which the Simulink model reported above is derived.
% Given the initial condition \mathbf{x}(t_0) = \mathbf{x}_0 and the simulation time span t \in [t_0,t_1], the set of ODE is numerically solved by computing \mathbf{x}(t) in a certain amount of time instants t_i within the time interval [t_0,t_1].
% At the instant t_{i+1}, the solution x(t) is evaluated as:
% \mathbf{x}(t_{i+1}) \;=\; \mathbf{x}(t_i) + \Delta_i\,\mathbf{g}\left(t_i,\, \mathbf{x}(t_i),\, \mathbf{f}, \Delta_i\right)
% where \Delta_i=t_{i+1}-t_i is the integration step and \mathbf{g} is a suitable function that depends on the integration method.
%
% There are two main classes of integration methods:
% fixed-step methods: the integration step is decided by the user or it is determined before starting the simulation. It does not change during simulation.
% variable-step methods: the integration step is automatically changed during the simulation in order to fulfill the required simulation accuracy.
%
% There are solvers for continuous-time and discrete-time models:
% even for discrete-time solvers it is possible to select between fixed-step methods (the step will be equal to the sampling period, or a integer submultiple) and variable step methods (the step will be equal to one or more sampling periods, depending on whether the system is single or multi rate).
% it is possible to simulate a discrete-time (or "hybrid-time", such as sample-data systems) model with a continuous-time solver, but the reverse is not allowed.
%
% Solver choice criteria:
% ode45 with variable-step can be applied in many situations, and for this reason it is the default solver in Simulink. It might be not so effective in simulating stiff models, i.e. models in which some components with very fast and slow modes (i.e. components with large and small dominant time constants) coexist.
% ode1s with variable-step is the first method to try when the model is suspected to be stiff.
% discrete is the solver to use for discrete-time models with no continuous states.
%
% For variable step solvers, the following parameters (to set in the Simulation Parameter dialog box) control the simulation accuracy:
% Max step size and min step size control the maximum and minimum size of the integration step.
% Relative tolerance defines the number of significant digits in the solution; Absolute tolerance defines the threshold below which the solution is considered negligible (i.e. equal to zero).
%
% Run the simulation
% In the Model window menu, select Simulation \rightarrowRun (or use the equivalent button in the model window toolbar).
% Alternative: use the sim routine.

%   run simulation
sim('sim_DC_mot');

%
% Display the simulation results
% During a simulation, the trace of a scope can be visualized by double-clicking over the scope (a window opens, showing the scope trace).
% A Sinks \rightarrowTo Workspace block can be used to export a certain Simulink signal (obtained by running a simulation) to the Matlab workspace. Alternatively, all the traces logged by a scope can be exported to the Matlab workspace by enabling the "Log data to workspace" option under the "Logging" tab of the scope Configuration Properties window.
% If the option Save format: Structure with Time is selected to export Simulink data to the Matlab workspace, then every Simulink signal is saved as a structure with a time field and a data field.

% list vars in workspace
whos

% Plot the simulation results, after extracting all the relevat data from the "Structure with time" data structures (ua, wm, thm):

%   extract simulation results from data structs
tu = u.time;                  %   time vector [s]
u = u.signals.values(:,1);    %   voltage input [V]

ty = y.time;                  %   time vector [s]
y = y.signals.values(:,1);    %   speed output [rad/s]  
y = y * (60/2/pi);            %   convert from [rad/s] to [rpm] units

% plot simulation results
figure;
subplot(2, 1, 1);
plot(ty, y, 'b-');
ylabel('Speed [rpm]');
grid on;

subplot(2, 1, 2);
plot(tu, u, 'b-');
ylabel('Voltage [V]')
xlabel('Time [s]');
ylim([0, 10]);
grid on;