
%% Main script for generating trade-off curves
% version v.BareBone-Lund
% written by: Chriss Grimholt 2015

s = tf('s'); % defining the Laplace variable

% specify the problem (make changes here)
% =======================================

G = 1/(1*s+1)*exp(-s); % The process model
K = @(p) p(1) + p(2)/s;  % PI controller, p = [kp, ki]


dK = @(p) [tf(1); 1/s]; % The derivative of the PI controller

% specift the robustness constraint
problem.ms_eqcon = 1.2;
problem.mt_eqcon = problem.ms_eqcon;

% specify the initial guess
problem.x0 = [.85 .2];

% Parameters for the step simulation and the gridding of the frequncy domain
problem.time_gridding = linspace(0,25, 1e4);
problem.freqency_gridding = logspace(-2,2,1e4);

problem.opt = optimset('Algorithm','active-set','GradConstr','on','GradObj','on','DerivativeCheck','off','Display','off');



%% Solving the problem
%  ===================

current_date = clock;
fprintf('\n')
fprintf('Date: %i/%i-%i, Time: %i:%i',current_date(3),current_date(2),current_date(1),current_date(4:5))
fprintf('\n')
fprintf('Finding Optimal Controller\n')
fprintf('***************************\n')
fprintf('\n')
fprintf('cost  \t Ms \t Mt \t eFlag \t iter \t time \t\topt_param   \n')
fprintf('----------------------------------------------------------------------------------\n')
%%  
% Create the transfer functions
% The Gang of Four
S  = @(p) 1/(1+G*K(p));
GS = @(p) G*S(p);
KS = @(p) K(p)*S(p);

% The gradient of the error
de_di = @(p) -GS(p)*GS(p)*dK(p);

% Adding transfer functions to problem
problem.G  = G;
problem.K  = K;
problem.KS = KS;
problem.dK = dK;
problem.S  = S;
problem.GS = GS;
problem.de_di = de_di;

% take the time
tic

% optimize and find the optimal solution (sending the struct problem to
% function opt_problem.

res = opt_problem(problem);

% find how long it took to solve the problem
res.calc_time = toc;

% find how many iteration it required
res.iter = res.output.iterations;


% print the current results
fprintf('%0.2f \t %.2f \t %.2f \t %i \t\t %i \t\t %.2fs\t\t', res.cost, res.ms, res.mt, res.exitflag, res.iter, res.calc_time)
for i = 1:length(res.tuning(:))
    fprintf('%.2f  ', res.tuning(i))
end
fprintf('\n')

