% Calculando espectro de Lyapunov do sistema de Lorenz
% Espectro = (1.50, 0, -22.46) (base e)

sigma = 16;
rho = 45.92;
beta = 4;

%sigma = 10;
%beta = 8/3;
%rho = 28;

F = @(t,x) Lorenz(t,x,sigma,rho,beta);
linF = @(t,x) LorenzLin(t,x,sigma,rho,beta);

% Initial conditions and solver parameters

x0 = 0.5.*[1,1,1];
Gamma0 = diag([1,1,1],0);

t0 = 0;
dt = 0.01;
tf = 200;

t = (t0:dt:tf)' ;

x = zeros(length(t),length(x0));
SV = x;
x(1,:) = x0;

Gamma = cell(length(t),1);
Gamma{1} = Gamma0;
cont_normalize = 0;

for i = 2:length(t)
    
    [t(i), x(i,:), Gamma{i}] = RK4Lin(t0,dt,x(i-1,:),Gamma{i-1},F,linF);
%     
%     norm_col2 = norm(Gamma{i}(:,2));
%     norm_col3 = norm(Gamma{i}(:,3));
%     Gamma{i}(:,2) = Gamma{i}(:,2) - (Gamma{i}(:,2)'*Gamma{i}(:,1))/(Gamma{i}(:,1)'*Gamma{i}(:,1)).*Gamma{i}(:,1);
%     Gamma{i}(:,2) = norm_col2/norm(Gamma{i}(:,2)).*Gamma{i}(:,2);
%     
%     Gamma{i}(:,3) = Gamma{i}(:,3) - (Gamma{i}(:,3)'*Gamma{i}(:,1))/(Gamma{i}(:,1)'*Gamma{i}(:,1)).*Gamma{i}(:,1) ...
%                                   - (Gamma{i}(:,3)'*Gamma{i}(:,2))/(Gamma{i}(:,2)'*Gamma{i}(:,2)).*Gamma{i}(:,2);
%     Gamma{i}(:,3) = norm_col3/norm(Gamma{i}(:,3)).*Gamma{i}(:,3);
    SV(i,:) = svd(Gamma{i}');
    
%     cont_normalize = cont_normalize + 1;
%     if cont_normalize == 1
%         cont_normalize = 0;
%         Gamma{i}(:,1) = Gamma{i}(:,1)./norm(Gamma{i}(:,1));
%         Gamma{i}(:,2) = Gamma{i}(:,2)./norm(Gamma{i}(:,2));
%         Gamma{i}(:,3) = Gamma{i}(:,3)./norm(Gamma{i}(:,3));
%     end
end

figure; plot3(x(:,1),x(:,2),x(:,3))
xlabel('x'); ylabel('y'); zlabel('z');

figure; 
plot(log(SV(:,1))/t)
