% Sheet 6 / Ex C
clf, clear, close all

% you need to play around with the parameters (enough starting nodes,
% refinements etc)

p = 70; % parameter
%p = -70;

n_nodes = 10;    % number of nodes on the coarse mesh
nodes = linspace(0,1,n_nodes);
f = @(x) 0;
lambda = @(x) 1+0*x;

% h-adaptivity
it_h = 10;   % number of refinements with h-adaptivity
for it = 1:it_h
    [K,f_vec] = assembling(nodes,lambda,f);
    % need to add the term for phi'*phi (convection term)
    conv_loc = p/2*[-1,-1;1,1];
    for k=1:length(nodes)-1
        K(k:k+1,k:k+1) = K(k:k+1,k:k+1) + conv_loc;
    end
    
    % adaption for dirichlet boundary
    K(1,1) = K(1,1)*(1 + 1e6);
    f_vec(end) = K(end,end)*1e6;
    K(end,end) = K(end,end)*(1 + 1e6);
    
    % solving the system
    u = K\f_vec;
    
    % adapting the mesh
    if it < it_h
        nodes = adapt_h(nodes,u,lambda);
    end
end

figure(1)
hold on
plot(nodes,u,'-o')
title(['h-adapt: u_h after ' num2str(it_h) ' refinements, nstart=' num2str(n_nodes) ', nend=' num2str(length(nodes))]);
xlabel('x values');
ylabel('u');
grid on;
hold off
file_name_1 = ['ex_6_C_h-adap_ref' num2str(it_h) '_n_nodes' num2str(n_nodes) '.jpg'];
saveas(figure(1), file_name_1);


% r-adaptivity
n_nodes_r = 20;    % number of nodes on the coarse mesh
nodes_r = linspace(0,1,n_nodes_r);
it_r = 3;   % number of refinements with r-adaptivity
for it = 1:it_r
    [K,f_vec] = assembling(nodes_r,lambda,f);
    % need to add the term for phi'*phi (convection term)
    conv_loc = p/2*[-1,-1;1,1];
    for k=1:length(nodes_r)-1
        K(k:k+1,k:k+1) = K(k:k+1,k:k+1) + conv_loc;
    end
    
    % adaption for dirichlet boundary
    K(1,1) = K(1,1)*(1 + 1e6);
    f_vec(end) = K(end,end)*1e6;
    K(end,end) = K(end,end)*(1 + 1e6);
    
    % solving the system
    u_r = K\f_vec;
    
    % adapting the mesh
    if it < it_r
        nodes_r = adapt_r(nodes_r,u_r,lambda);
    end
end

figure(2)
hold on
plot(nodes_r,u_r,'-o')
title(['r-adapt: u_h after ' num2str(it_r) ' refinements and n=' num2str(n_nodes_r)]);
xlabel('x values');
ylabel('u');
grid on;
hold off
file_name_2 = ['ex_6_C_r-adap_ref' num2str(it_r) '_n_nodes' num2str(n_nodes_r) '.jpg'];
saveas(figure(2), file_name_2);