% Tune SRC for xB. First use V and then use L



%% Symbolic variables that will be used to tune SRC

% 1= V
% 2= L
syms alpha1 alpha2 Kc dv1 dv2

% alpha: the slopes in the SR block
% Kc: common proportional gain
% dv: range of the internal variable for each MV

% internal signal
vmax=1;
vmin=0;

% Ranges for the MVs
Vmax = 4;
Lmax = 3.1575;  %At F=1.4 and pV=0.02. Actual max is 10

% Tunings
%Kc_VxB  
%Kc_LTxB 

% This is commented to make the scrip faster

eq1     = alpha1*Kc-Kc_VxB;
eq2     = alpha2*Kc-Kc_LTxB;
eq3     = alpha1-Vmax/dv1;
eq4     = alpha2-Lmax/dv2;
eq5     = abs(dv1)+abs(dv2)-vmax;

eq      = [eq1;eq2;eq3;eq4;eq5];
var     = [alpha1;alpha2;Kc;dv1;dv2];

%S=solve(eq,var,'PrincipalValue',true);
S       = solve(eq,var);

alpha   = double([S.alpha1; S.alpha2]); % slopes
Kc_SRC  = double(S.Kc);                    % controller gain
dv      = double([abs(S.dv1); abs(S.dv2)]); % delta v


alpha_V         = abs(alpha(1)); % -8.2548; 
alpha_L         = -abs(alpha(2)); % 6.1259;
Kc_SRC          = abs(Kc_SRC); %    -1.1080 ;  %The actual result is negative
dv_V            = dv(1); % 0.4846;
dv_L            = dv(2); % 0.5154;

%% Common integrator
tauI_SRC        = (tauI_VxB+tauI_LTxB)/2;% min(tauI_VxB, tauI_LTxB);
KI_SRC          = Kc_SRC/tauI_SRC;

%%  Calculation of bias
% Moving the origin to the nominal operating point. 

% For V
biasV = VB0; 

% For LT
% delta v within the range of V, from nominal operating point to saturation
% of V
deltav  = (Vmax-VB0)/alpha_V; 
% And then how much would the line for L would go into the range of V
% (until nominal operating point)
biasL   = 3.2; % 3.1575+abs(alpha_L)*deltav;