%% Identify Model and Tune Controller
% This script lets you tune a PID controller for a plant when all you have is the measured plant response to a known input signal. The script contains the Estimate State-Space Model Live Editor Task, which generates code for estimating a state-space model that represents the plant. It contains another Live Editor Task, Tune PID Controller to generate code for achieving a closed-loop response that balances disturbance rejection and reference tracking performance.
%
%% Load Plant Data
% Load measured input-output data. The data in icEngine.mat consists of the response of an engine to a chirp input. The input u is a vector containing the input signal sampled every 0.04 seconds. The output vector y contains the corresponding meaured response.

load icEngine.mat u y
t = 0.04*(0:length(u)-1);
plot(t,u,t,y)

%
%% Estimate State-Space Model
% To estimate a state-space model from this data, use the Estimate State-Space Model Live Editor Task.Experiment with different plant order values and observe the fit result, displayed in the output plot legend.
%

% Create object for time-series data
estimationData3 = iddata(y,u,0.04);

% Estimate state-space model
sys = ssest(estimationData3,4);

% Visualize results
compareplot(estimationData3,sys);
clear estimationData3;
title('Estimation');

%
%% Tune PID Controller for Estimated Plant
% The estimated model sys is a state-space model that you can use to design a PID controller. To do, use the Tune PID Controller Live Editor Task.
%

% Convert Response Time to Bandwidth
% Bandwidth is equivalent to 2 divided by the Response Time
wc = 2/17.702;

% PID tuning algorithm for linear plant model
[C,pidInfo] = pidtune(sys,'PIDF',wc);

% Clear Temporary Variables
clear wc

% Get desired loop response
Response = getPIDLoopResponse(C,sys,'closed loop');

% Plot the result
stepplot(Response)
grid on

% Display system response characteristics
disp(stepinfo(Response))

% Clear Temporary Variables
clear Response

%
%% Compute Further Responses
% Tune PID Controller generates a controller, C, which you can use to examine other responses of the closed-loop system with the identified model sys. For instance, compute the response to a disturbance at the plant output, using this controller.

CLdist = getPIDLoopResponse(C,sys,"Output Disturbance");
step(CLdist)
grid on
disp(stepinfo(CLdist))

%