function mcb_getControlAnalysis(pmsm,inverter,PU_System,PI_params,Ts,Ts_speed)
% mcb_getControlAnalysis  Control Analysis for PMSM FOC Current Control
% 
%   mcb_getControlAnalysis computes frequency domain analysis for computed
%   gains of PI controllers used in Field Oriented Control of Motor control systems. 
% 
%   mcb_getControlAnalysis(pmsm,inverter,PU_System,PI_params,Ts,Ts_speed)
%   performs the following functionalities for Current Control Loop:
%   - Transfer Function for Closed loop current control system
%   - Root Locus
%   - Bode Diagram
%   - Stability Margins (PM & GM)
%   - Step Response
%   - PZ Map
%   The respective figures are plotted on the screen.  
% 
%   See HELP for additional information for this utility.

% Function      :   mcb_getControlAnalysis
% Description   :   Control Analysis for PMSM FOC
% File name     :   mcb_getControlAnalysis.m
% Inputs        :   pmsm object, inverter object, PU system params, T_pwm, Ts, Ts_speed
% Authors       :   Darshan Pandit

% Copyright 2020 The MathWorks, Inc.

%% Analysis for uncompensated system

% TF for uncompensated system
% Assumed: Ts = T_pwm & SPMSM Plant

K = 1;
Ta_q    = pmsm.Lq/pmsm.Rs;                % Electrical time constant for Q-axis

G_pmsm      = tf([0 (K/pmsm.Rs)],[Ta_q 1]);
G_control    = tf([0 1/PU_System.I_base],[0.5*Ts 1]); 
G_pwm       = tf([0 PU_System.V_base],[0.5*Ts 1]);  % Assumed: Ts = T_pwm; Replace if T_pwm is different

sys_uncompensated = G_pmsm*G_control*G_pwm;

%% TF for compensated system
Kp = PI_params.Kp_i;

num_comp = (PI_params.Kp_i)*[PI_params.Ti_i 1];
den_comp = [PI_params.Ti_i 0];

tf_comp = tf(num_comp,den_comp);

sys_compensated = tf_comp*sys_uncompensated

%% Root locus for Uncompensated System

figure(2);
subplot(2,2,1);
rlocus(sys_uncompensated);
grid;

%% Bode Diagram for the system

f_min = 0.01; %Hz
f_max = 100e3; %Hz

w_min = 2*pi*f_min;
w_max = 2*pi*f_max;
w = logspace(-3,5,1000);

subplot(2,2,2);
title('Bode Plot of Iq closed loop');
f = bodeplot(sys_uncompensated,'g:',sys_compensated,w);
grid;

%% Checking stability margins
[Gm_uc,Pm_uc,Wcp_uc,Wcg_uc] = margin(sys_uncompensated);
GmdB_uc = 20*log10(Gm_uc);
Pm_uc;
Wcp_uc;
Wcg_uc;

[Gm,Pm,Wcp,Wcg] = margin(sys_compensated);
GmdB = 20*log10(Gm);
[GmdB Pm Wcp Wcg];
Gain_Margin = GmdB
Phase_Margin = Pm
Wcp
Wcg

%% Plotting step response for the closed loop systems

sys_closed_loop_compensated = feedback(sys_compensated,1);

subplot(2,2,3);
t = [0:Ts:0.1];
step(sys_closed_loop_compensated,t,'b');
title('Unit-Step Response of Current Loop');
xlabel('t Sec');
ylabel('Outputs');
grid;
v = [0 2e-3 0 1.4]; 
axis(v);

%% Plotting PZmap for closed loop system
subplot(2,2,4);
pzmap(sys_closed_loop_compensated)
grid;
axis([-6e4 0 -1.5e4 1.5e4]);

end