%% Quasi-Resonant Buck 
% State plane solution to Qsw buck with minimum negative current necessary
% for soft switching (J4=0)
%% Circuit definition
Vg = 48;
V = 5;

C = 10e-6; %Not used due to small ripple assumption
L = 1e-6;
Csw = 10e-9;



%% Solve all I1 operating points
% Note, because M<1/2, ZVS is assured in interval (2), so can start from
% I1=0
I1 = linspace(0,50,100);
t1 = I1*L/(Vg-V);

%% State Plane Analysis
% Normalization
Ro = sqrt(L/Csw);
wo = 1/sqrt(L*Csw);
Vbase = Vg;
Ibase = Vg/Ro;

M = V/Vbase;

% Interval 4
J3 = sqrt(1-2*M); %At ZVS Boundary
I3 = -J3*Ibase;
delta = pi-atan(J3/M);
r4 = (1-M);

% Interval 1
% theta1 is set to get I1 as specified
theta1 = t1*wo;
J1 = theta1*(1-M);

% Interval 2
r2 = sqrt(J1.^2+(1-M)^2);
J2 = sqrt(r2.^2-(M)^2);
beta = pi-atan(J1/(1-M))-atan(J2/M);

% Interval 3
theta3 = (J2+J3)/M;

% Averaging
F = 2*pi./(theta1+theta3+beta+delta);
Jout = F/2/pi.*(theta1/2.*J1+theta3/2.*(J2-J3));




%% Denormalize
tbeta = beta/wo;
tdelta = delta/wo;
t1 = theta1/wo;
t3 = theta3/wo;
I1 = J1*Ibase;
I2 = J2*Ibase;
I3 = J3*Ibase;
Iout = Jout*Ibase;
fs = F*wo/2/pi;
Ts = 1./fs;

%% Additional parameters of interest
Ipk = r2*Ibase;

%% Plot overall operation
subplot(2,1,1)
hold off;
plot(t1*1e6, Iout*V, 'LineWidth', 3);
hold on;
plot(t1*1e6, Iout, 'LineWidth', 3);
plot(t1*1e6, Ipk, 'LineWidth', 3);

legend('P_{out} [W]', 'I_{out} [A]', 'I_{pk} [A]');
xlabel('t_1 [{\mu}sec]');

subplot(2,1,2)
hold off;
plot(Iout*V,fs/1e6, 'LineWidth', 3);
hold on;
plot(Iout*V, t1./t3, 'LineWidth', 3);
plot(Iout*V, V/Vg*ones(size(t1)), ':k', 'LineWidth', 3)
plot(Iout*V, Iout./Ipk, 'LineWidth', 3)

legend('f_s [MHz]', 't_1 / t_3', 'D_{ideal}', 'I_{out} / I_{pk}');
xlabel('P_{out} [W]');