%-----------------------------PdeFEA
pfea=PdeFEA('/home/cflin/Downloads/plate_05.STL');
pfea.set_view_point([-50 30]);
pfea.set_mesh(0.095);


pfea.set_DBC(3,[1 0 0]);
pfea.set_DBC(5,[0 1 0]);
pfea.set_DBC(7,[0 0 1]);
pfea.set_NBC(1,[1e-3 0 0]);
%--------------------------solve
tic
pfea.solve();
toc
%--------------------------plot
pfea.plot_displacement_norm();
pfea.plot_von_Mises_stress();
%--------------------------post_process
%------------cut line:A to B of pFEA

    CutLine=get_cutline();

norm_U_CL_pFEA=pfea.query_norm_U(CutLine);
von_S_CL_pFEA=pfea.query_von_S(CutLine);
save US_CL_pFEA_05.mat norm_U_CL_pFEA von_S_CL_pFEA

%

if ~exist("norm_U_CL_pFEA_05",'var')
    %----------cut line of pFEA
    load US_CL_pFEA_05.mat norm_U_CL_pFEA von_S_CL_pFEA
end

if ~exist('CutLine','var')
    CutLine=get_cutline();
end

% extract fcm data

use_mat=1;
if use_mat
    if ~exist('plt')
        plt=Plotter('Cube_tmp','NNew_Data');
    end
    cur_order=plt.mp.order;
    cur_deep=plt.mp.maxdeep;
    cur_c=plt.mp.recorder.intermediate_c{1};
    %------------cut line:A to B of FCM
    Q_U_CL_XV=compute_u(CutLine,plt.mp.recorder.U{1},plt.mp);
    Q_U_CL_XV=reshape(Q_U_CL_XV,3,[])';% lenx3
    Q_S_CL_XV=squeeze(compute_stress(CutLine,plt.mp.recorder.U{1},plt.mp))';
    norm_U_CL_FCM=vecnorm(Q_U_CL_XV,2,2);
    von_S_CL_FCM=cal_von_Mises_Stress(Q_S_CL_XV);
else
    load plate_05_p3d5.mat
    cur_order=3;
    cur_deep=5;
    norm_U_CL_FCM=norm_U3;
    von_S_CL_FCM=von_S3;
end

%-------------plot movement contrast
plot(CutLine(:,1).*sqrt(2),norm_U_CL_pFEA);
hold on
plot(CutLine(:,1).*sqrt(2),norm_U_CL_FCM,'b');
legend({'pFEA','FCM, p=5'},'Location',"best");
xlabel('cut line A-B: r')
ylabel('movement norm')
%-------------plot von Mises stress contrast
figure
plot(CutLine(:,1).*sqrt(2),von_S_CL_pFEA);
hold on
plot(CutLine(:,1).*sqrt(2),von_S_CL_FCM);
legend({'pFEA','FCM, p=5'},'Location',"best");
xlabel('cut line A-B: r')
ylabel('von Mises stress')

%-------------plot relative error contrast
figure
rela_U=sqrt(abs(norm_U_CL_pFEA-norm_U_CL_FCM)./norm_U_CL_pFEA)*100;
max(rela_U)
plot(CutLine(:,1).*sqrt(2),rela_U);
xlabel('cut line A-B: r')
ylabel('relative error in movement norm (%)')
%-------------plot relative error contrast
figure
rela_S=sqrt(abs(von_S_CL_pFEA-von_S_CL_FCM)./von_S_CL_pFEA)*100;
max(rela_S)

% semilogy(CutLine(:,1).*sqrt(2),rela_S);ylim([1e-3 1e2]);

% plot(CutLine(:,1).*sqrt(2),rela_S);
semilogy(CutLine(:,1).*sqrt(2),rela_S);

xlabel('cut line A-B: r')
ylabel('relative error in von Mises stress (%)')

%%-------------save data
eval(['norm_U' num2str(cur_order) '=norm_U_CL_FCM;']);
eval(['von_S' num2str(cur_order) '=von_S_CL_FCM;']);
eval(['rela_U' num2str(cur_order) '=rela_U;']);
eval(['rela_S' num2str(cur_order) '=rela_S;']);
eval(['save plate_05_p' num2str(cur_order) 'd' num2str(cur_deep) '.mat ' ...
    'norm_U' num2str(cur_order) ' von_S' num2str(cur_order) ' rela_U' num2str(cur_order) ' rela_S' num2str(cur_order)]);