function mcb_getCharacteristics(pmsm,inverter)
% mcb_getCharacteristics Computes the torque-speed characteristics for PMSM
% 
%   mcb_getCharacteristics calculates the torque and speed characteristics 
%   of the motor. This is helpful in control algorithm development for the motor. 
% 
%   mcb_getCharacteristics(pmsm,inverter) returns the following
%   characteristics the given PMSM:
%   - Torque vs Speed
%   - Power vs Speed 
%   - Iq vs Speed
%   - Id vs Speed
%   
%   The function accepts a pmsm object and an inverter object as inputs. 
%   pmsm        = obj1;
%   inverter    = obj2;
%   I_max       = obj3;
% 
%   See HELP for additional information for this utility.
%   Copyright 2020 The MathWorks, Inc.

% Function      :   mcb_getCharacteristics
% Description   :   Compute Torque-Speed & Other curves for PMSM
% File name     :   mcb_getCharacteristics.m
% Inputs        :   pmsm object & inverter object
% Authors       :   Darshan Pandit

%% Get Torque & Speed Characteristics
P_max = 2*pi*pmsm.N_base*pmsm.T_rated/60;
I_max = pmsm.I_rated;

N = 1:2*pmsm.N_base;
T_max  = P_max./((2*pi/60).*N);
T_max(1:pmsm.N_base) = pmsm.T_rated*ones(1,pmsm.N_base);
P =  2*pi.*N.*T_max/60;

subplot(2,2,1);
plot(N,T_max,'b')
title(['Torque-Speed Characteristics for ' pmsm.model]);
xlabel('Speed (rpm)');
ylabel('Torque (Nm)');
grid on;

%% Get Power & Speed Characteristics

subplot(2,2,2)
plot(N,P,'g')
title(['Power-Speed Characteristics for ' pmsm.model]);
xlabel('Speed (rpm)');
ylabel('Power (Watts)');
grid on;

%% Get Id & Iq Characteristics

% Get Id & Iq Values
Omega_e     = pmsm.p*2*pi*N/60;
Omega_e_base= pmsm.p*2*pi*pmsm.N_base/60;

Id          = zeros(1,2*pmsm.N_base);
Iq          = ones(1,2*pmsm.N_base);

% Get Id for FWC
Id          = (((Omega_e_base - Omega_e).*pmsm.FluxPM)./(Omega_e.*pmsm.Ld));
Id(1:pmsm.N_base) = zeros(1,pmsm.N_base);

% Get Iq for FWC
index       = length(find(abs(Id) <= I_max));

max_speed_I	= N(index);
Iq          = sqrt(I_max^2 - Id.^2);
Iq_limits   = T_max./((3/2)*pmsm.p*pmsm.FluxPM);

Rs          = pmsm.Rs;

Vd          = Id(1:index).*Rs - Omega_e(1:index).*pmsm.Lq.*Iq(1:index);
Vq          = Iq(1:index).*Rs + Omega_e(1:index).*pmsm.Ld.*Id(1:index) + Omega_e(1:index)*pmsm.FluxPM;

V_max       = sqrt(Vd.^2 + Vq.^2);
Vpu         = V_max/(inverter.V_dc/sqrt(3));
idx         = find(Vpu<=1);
max_speed_V	= N(length(idx));

subplot(2,2,4)
plot(N(1:index),Id(1:index),'g')
title('Id Vs Speed');
xlabel('Speed (rpm)');
ylabel('Id (Amps)');
grid on;

subplot(2,2,3)
plot(N(1:index),Iq(1:index),'b',N(1:index),Iq_limits(1:index),'g')
title('Iq Vs Speed');
xlabel('Speed (rpm)');
ylabel('Iq (Amps)');
legend('Iq@I_{max}','Iq@T_{max}')
grid on;

% Return the computed values
% Id_ref = Id(1:index);
% Iq_ref = Iq(1:index);
% Speed_ref = N(1:index);

end