%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Application Note AN005   
% Parameters for 'Back-to-back converter with grid-tied LCL filter' 
% Copyright imperix ltd, 2025
% dev@imperix.ch
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Created: August 2025
% Designer: Adeel Jamal

clear all;

% To generate the correct variant
variant_generation = Simulink.Variant('SIMULINK_MODE==1');
variant_simulation = Simulink.Variant('SIMULINK_MODE==0');
SIMULINK_MODE = true;

%% SYSTEM PARAMETERS
Control_Freq = 50e3;            % Switching/Control frequency [Hz]
ControlPeriod = 1/Control_Freq; % Switching period [s]
Ts = 1*ControlPeriod;           % Sampling period [s]
fs = Control_Freq;              % Sampling frequency [Hz]
SamplingPhase = 0.5;            % Sampling phase [-]

Vdc0 = 580;                     % Initial DC voltage [V]
Vg = 230;                       % RMS Grid voltage [V]
Freq = 50;                      % Grid frequency [Hz]                  
Cdc = 1.5e-3*2;                 % DC bus capacitance [F] (2 TPIs in parallel)

Lload = 2.5e-3;                 % Load inductance [H]
Rload = 27;                     % Load resistance [Ohm]
LoadFreq = 60;                  % Frequency of the load currents [Hz]

%% MODEL PARAMETERS
L1 = 1.05e-3;                    % TPI main inductor value [H]
Rf1 = 54e-3;                     % Series equivalent resistance of L1 [ohm]
L2 = 650e-6;                     % Grid-side choke of LCL filter [H]
Rf2 = 100e-3;                    % Internal resistor of L2 [ohm]
Cf = 8.2e-6;                     % Capacitor of LCL filter [F]
Rc = 10;                         % Series resitor of Cf [ohm]
Lg = 1e-6;                       % Grid inductor [H]

%% Load side control
tr_load = 2e-3;                 % Response time of load current controller [s]
ksi_load = 1;                   % Damping of load controller
w0_Il = 4.744/tr_load;          % Controller bandwidth [rad/s]
KiIl = w0_Il^2*Lload;           % Integral gain
KpIl = 2*ksi_load/w0_Il*KiIl;   % Proportional gain

%% GRID CURRENT CONTROLLER PARAMETERS (alpha beta)
% DC bus voltage control
tr_Vdc = 15e-3;                 % Response time of the DC bus controller [s]
ksi_Vdc = 1;                    % Damping of DC bus controller
w0_Vdc = 4.744/tr_Vdc;          % Controller bandwidth [rad/s]
KiVdc = w0_Vdc^2*Cdc;           % Integral gain
KpVdc = 2*ksi_Vdc/w0_Vdc*KiVdc; % Proportional gain

% Grid current control
KpIg = 5; % proportional resonant gain
KrIg = 100;  % intergral gain

wc = 2*pi*2.5; % Resonant cutoff freq
wo = 2*pi*50; % Resonant frequency

%% ACTIVE DAMPING LOOP TUNING
w_ad_Ig = 0.06*2*pi/Ts;                   % Active damping pulsation
Kad_Ig = 0.15*w_ad_Ig*(L2+Lg);            % Active damping gain

% Resonant Frequency of LCL Filter 
w_res = sqrt((L1+(L2+Lg))/(L1*(L2+Lg)*Cf));
f_res = 1/(2*pi)*w_res;