%% INPUT -----------------------------------------------------------------+
a = 0; % left time interval limit
b = 10; %20; % right time interval limit
mu = 10; %3; % parameter
f = @(t,x) [x(2);-x(1)-mu*(x(1)^2-1)*x(2)]; % function f
x0 = [-2.5;2.5];
%% SOLVER RKF45 ----------------------------------------------------------+

N = 10; % number of points
tol = 10.^[-12 -11 -10 -8 -7 -6 -5]; % tolerance 10.^(-12:1:-5);
smpl = length(tol);
CPUtimeRKF45 = zeros(1,smpl);
URKF45 = zeros(1,smpl);
pointsRKF45 = zeros(1,smpl);

for ii = 1:smpl
    tic;
    [~,x,~] = RKF45(a,b,x0,N,tol(ii),f); % Runge-Kutta-Fehlberg 4th order adaptative scheme
    CPUtimeRKF45(ii) = toc;
    URKF45(ii) = x(1,end);
    pointsRKF45(ii) = size(x,2);
end
errRKF45 = abs(URKF45(1:smpl-1)-URKF45(2:smpl))./abs(URKF45(1:smpl-1));
%% SOLVER RK4 ------------------------------------------------------------+

N = [10^3 3*10^3 10^4 3*10^4 10^5 3*10^5 10^6]; % number of points
smpl2 = length(N);
CPUtimeRK4 = zeros(1,smpl2);
URK4 = zeros(1,smpl2);
pointsRK4 = zeros(1,smpl2);

for ii = 1:smpl2
    tic;
    [x,~] = RK4(a,b,x0,N(ii),f);
    CPUtimeRK4(ii) = toc;
    URK4(ii) = x(1,end);
    pointsRK4(ii) = size(x,2);
end
errRK4 = abs(URK4(1:smpl2-1)-URK4(2:smpl2))./abs(URK4(2:smpl2));

%% OUTPUT
figure('Position',[500 500 800 400]);

subplot(1,3,1);
loglog(errRKF45,CPUtimeRKF45(1:smpl-1),'-*','LineWidth',2); hold on;
loglog(errRK4,CPUtimeRK4(1:smpl2-1),'-*','LineWidth',2);

subplot(1,3,2:3);
loglog(errRKF45,pointsRKF45(1:smpl-1),'-*','LineWidth',2); hold on;
loglog(errRK4,pointsRK4(1:smpl2-1),'-*','LineWidth',2);
%% FORMAT OUTPUT ---------------------------------------------------------+
subplot(1,3,1);
title('(a)','interpreter','latex');

axis([1e-15 1e-5 1e-3 1e1]);
ax = gca;
ax.XTick = [1e-15 1e-10 1e-5];
ax.YTick = [1e-3 1e-2 1e-1 1 1e1];
set(ax,'TickLabelInterpreter','latex');
ax.TickLength = [0.02 0.02];

set(gca,'fontsize',16)
str='$\epsilon$';
xlabel(str,'interpreter','latex','FontSize',20);
str='Tempo de computa\c{c}\~{a}o [s]';
ylabel(str,'interpreter','latex','FontSize',20);

subplot(1,3,2:3);
title('(b)','interpreter','latex');

axis([1e-15 1e-5 1e2 1e6]);
ax = gca;
ax.XTick = [1e-15 1e-10 1e-5];
ax.YTick = [1e2 1e3 1e4 1e5 1e6];
set(ax,'TickLabelInterpreter','latex');
ax.TickLength = [0.02 0.02];

set(gca,'fontsize',16)
str='$\epsilon$';
xlabel(str,'interpreter','latex','FontSize',20);
str='pontos na discretiza\c{c}\~{a}o';
ylabel(str,'interpreter','latex','FontSize',20);

h = legend('RKF4(5)','RK4');
set(h,'Interpreter','latex','FontSize',16,'Location','northeast')

tightfig;