clear;

% electrical
Vdc = 200;

% mechanical (shaft) speed
Wm = 1.0*2*pi*1000/60; % radians per second

% PWM and sampling
fpwm = 10000;
fs = fpwm;
Tpwm = 1/fpwm;
Tdt = 0.01*Tpwm; % deadtime
Ts = 1/fs;

Tcs = 1/(2*pi*100000); % current sensor bandwidth

% "R" Parameters
Mot.Rs = 0.387;
Mot.Ld = 0.4775/424.26;
Mot.Lq = 0.58/426.26478;
Mot.Lss = 8*10e-6;
Mot.P = 2*2;
Mot.Psir  = 0.115045845623418;
Mot.Id0 = 0;
Mot.Iq0 = 0;

Mot.thm0 = 0;
% assumes initial position is zero!!!
Mot.is0 = [Mot.Id0 (-0.5*Mot.Id0 + sqrt(3)/2* Mot.Iq0)];

% equivalent small time-constant (used for current regulator tuning)
Tcalc = 0.5/fs;
Ta = 0.5/fpwm;
Tsh = 0.5/fs;
Tp = Tcalc + Ta + Tsh + Tcs;

% current regulator tuning
Ra = 0.0;
R = Mot.Rs+Ra;

Tii = 2/R*Tp;
Tni_D = Mot.Ld/R;
Tni_Q = Mot.Lq/R;

Ki = 1/Tii;
Kpd = Tni_D/Tii;
Kpq = Tni_Q/Tii;

% current regulator
IReg.Ra = Ra;

IReg.Tcalc = Tcalc;
IReg.Ts = Ts;
IReg.Tn_D = Tni_D;
IReg.Tn_Q = Tni_Q;
IReg.Ti = Tii;
IReg.Kp = [Kpd Kpq];
IReg.Ki = [Ki Ki];

IReg.V0 = [0 (Wm*Mot.P/2*(Mot.Psir+Mot.Ld*Mot.Id0))];

%%%% Look-up Table-based model

load('ID.mat')
load('IQ.mat');
load('lambda_d.mat');
load('lambda_q.mat');

%%%% Analytical Fit-based model:

%% q-axis:
Analytical.Lmq0 = 1/50;   %  unsaturated inductance
Analytical.Lmq_sat = 1/1500;   % saturated inductance
Analytical.PsiT_q = 0.2;   % flux level at transition from unsaturated to saturated
Analytical.fT_q = 20;   % tightness of transition

%% d-axis:
Analytical.Lmd0 = 1/50;   %  unsaturated inductance
Analytical.Lmd_sat = 1/950;   % saturated inductance
Analytical.PsiT_d = 0.125;   % flux level at transition from unsaturated to saturated
Analytical.fT_d = 30;   % tightness of transition