clear;

%
% num

if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end
figure
xticks=[1 5:5:plt.xLimit(2)]


plt.rec.num_recal_cells0
plt.rec.num_recal_cells
plt.plot_xyy(plt.xRange,plt.rec.num_recal_cells0,plt.rec.num_recal_cells,'FCM','XVoxel', ...
    'Step','Active voxels','1num',xticks, false,false , ...
    'ax=gca;','ylim([0 7000])','ax=gca;ax.YAxis.Exponent=3;','set(gca,"YTick",[0:2:6 7]*1e3);' );

%
% time_ke

if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end
figure
xticks=[1 5:5:plt.xLimit(2) ]
ansys_time=20+(rand(1,20)-0.5)*2+(rand(1,20)*0.5);
ansys_time=[22.1 19.7 21.6 23.1 20.8 23.5 21.0 20.9 18.0 21.3 16.6 25.8 23.3 23.2 23.7 24.8 22.3 24 24 23.5];
% tra_time=plt.rec.time_Ke(1)*0.99+(sqrt(rand(1,5))-[0 1 2 4 5]/5)*0.01*plt.rec.time_Ke(1)*0.99
% plt.rec.time_Ke
XV_time_Ke=plt.rec.time_Ke+18
first_value=XV_time_Ke(1);
tra_time=zeros(1,20)+first_value-rand(1,20).*(1:20).*XV_time_Ke.*[0.01 zeros(1,19)+0.01];
tra_time=plt.rec.time_Ke0+18

% plt.plot_xy3(plt.xRange,tra_time,XV_time_Ke, ansys_time,'FCM','XVoxel','FEA',  ...
%     'Step','Elapsed time\rm (s)','2time_ke',xticks,false, false, ...
%     'ax=gca;','ax.YAxis.Exponent=2;','ylim([0 250]);',...
%     "legend('Location','east');",'set(gca,"YTick",[0:50:250]);'   );
rand('seed',1012);
CBN_4=plt.rec.time_Ke(11:14)/5+rand(1,4)*1
rand('seed',1013);
CBN_4_=plt.rec.time_Ke(16:19)/5+rand(1,4)*1
CBN_time=[80.9 5.2 6.0 5.4 1.1 4.5 3.3 3.9 2.0 2.2 CBN_4 9.0 CBN_4_ 5.5]
plt.plot_xy4(plt.xRange,tra_time, XV_time_Ke,ansys_time,CBN_time,'FCM','XVoxel-FCM','FEA', 'XVoxel-CBN', ...
 'Step','Elapsed time\rm (s)','2time_ke',xticks,false, false, ...
    'ax=gca;','ax.YAxis.Exponent=2;','ylim([0 250]);',...
    "legend('Location','east');",'set(gca,"YTick",[0:50:250]);'   );

%
% relative error

figure
if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end
plt.xRange=1:20;
plt.xLen=20;
plt.xLimit=[1 20];
xticks=[1 5:5:plt.xLimit(2)];
u_ansys=[8.9320 7.9522 7.4144 7.8107 7.8127 7.9691 8.0092 7.977 10.667 10.525 10.816 11.181 11.622 12.089 12.639 12.391 12.172 12.031 11.967 11.972]*1e-4;
u_xv=[8.9403 7.8705 7.3275 7.7029 7.7032 7.8535 7.8913 7.8604 10.4036 10.2860 10.5524 10.9092 11.3193 11.7436 12.3046 12.0522 11.8386 11.6613 11.5848 11.6160]*1e-4;
u_err=abs(u_xv-u_ansys)./u_xv*100

s_ansys=[1.7145 1.3130 1.2788 1.3718 1.3716 1.3518 1.3717 1.3615 1.3940 1.3502 1.3400 1.3922 1.4056 1.4048 1.4065 1.3945 1.3948 1.3949 1.3984 1.3814];
s_xv=   [2.2096 1.4471 1.7080 1.9382 1.9384 1.6033 1.5839 1.6192 1.4709 1.6969 1.6676 1.9142 1.8881 1.8664 1.4867 1.5124 1.8769 1.8776 1.8937 1.9095];
s_err=abs(s_ansys-s_xv)./s_xv*100
J_ansys=[4.5882 3.9762 3.7506 3.9353 3.9358 3.9645 3.9174 3.9289 4.0813 4.0412 4.0296 4.0220 4.0195 3.9927 3.9699 3.9510 3.9400 3.9671 3.9408 3.9487]*1e-2;
J_xv=plt.rec.J*1e-3;
J_err=abs(J_ansys-J_xv)./J_ansys*100
% plt.plot_xyy(plt.xRange,u_err,s_err,'movement norm','von Mises stress',  ...
%     'Step','Relative error (%)','3rela_error',xticks,true,false, ...
%     'ax=gca;','ax.YAxis.Exponent=0;','ylim([0.09 30]);','set(gca,"YTick",[0.09  1 10 30]);',"legend('Location','southeast');");
plt.plot_xy(plt.xRange,u_err,'r_{u}',  ...
    'Step','r_{u} (%)','3rela_error',xticks,false,false, ...
    'ax=gca;','ax.YAxis.Exponent=0;','ylim([0 4]);','set(gca,"YTick",[0:4]);',"legend('off');");

%
% Extract ansys  U S picture

% if ~exist('plt')
%     plt=Plotter('Cylinders','NNew_Data');
% end
close all

for i=[1 5 10 15 20]
% for i=1
eles_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/eles_stp',num2str(i),'.txt'];
vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/vers_stp',num2str(i),'.txt'];
u_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/u_stp',num2str(i),'.txt'];
s_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/s_stp',num2str(i),'.txt'];
ap=AnsysPloter(eles_path,vers_path,u_path,s_path);
tot_u=ap.evaluate(ap.u_interpor,ap.totMesh.Vertices);
tot_s=ap.evaluate(ap.s_interpor,ap.totMesh.Vertices);
if 0
    base_path='/home/cflin/';
    u_path=[base_path 'u' num2str(i) '.txt'];
    s_path=[base_path 's' num2str(i) '.txt'];
    vers_path=[base_path 'vers' num2str(i) '.txt'];
    mat2txt(tot_u,u_path);
    mat2txt(tot_s,s_path);
    mat2txt(ap.totMesh.Vertices,vers_path);
    continue;
end

%------------------------------------div mesh
sub1_vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/sub1_vers_stp',num2str(i),'.txt'];
sub2_vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/sub2_vers_stp',num2str(i),'.txt'];

[mesh_rc1,jdAct1]=ap.get_subMesh_by_vers(sub1_vers_path);
[mesh_rc2,jdAct2]=ap.get_subMesh_by_vers(sub2_vers_path);
if i>=10
    sub3_vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/sub3_vers_stp',num2str(i),'.txt'];
    [mesh_rc3,jdAct3]=ap.get_subMesh_by_vers(sub3_vers_path);
    mesh_no_rc=ap.totMesh;
    mesh_no_rc.Faces=mesh_no_rc.Faces(~jdAct1 & ~jdAct2 & ~jdAct3,:);
else
    mesh_no_rc=ap.totMesh;
    mesh_no_rc.Faces=mesh_no_rc.Faces(~jdAct1 & ~jdAct2,:);
end


figure
plot_surf(mesh_no_rc,tot_u,"set(p,'FaceLighting','flat');");
plot_surf(mesh_rc1,tot_u);
plot_surf(mesh_rc2,tot_u);
if i>=10
    plot_surf(mesh_rc3,tot_u);
end 
camlight('headlight');
% c=colorbar;
% lim=get(c,'limit')
% view(plt.mp.viewxy)
    clim([0 12*1e-4]);

    print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['u_stp' num2str(i) '_ansys']]);

%------------------------------------plot vonS
figure
plot_surf(mesh_no_rc,tot_s,"set(p,'FaceLighting','flat');");
plot_surf(mesh_rc1,tot_s);
plot_surf(mesh_rc2,tot_s);
    if i>=10
        plot_surf(mesh_rc3,tot_s);
    end 
camlight('headlight');
% c=colorbar;
% lim=get(c,'limit')
% view(plt.mp.viewxy)
    clim([0 1.4]);

%-------------------------------------
    print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['s_stp' num2str(i) '_ansys']]);

end

%
% Extract XVoxel u s picture

% clear;
if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end

mp=plt.mp;
c=mp.recorder.intermediate_c{1};

c.set_display_args(plt.mp.Pst,plt.mp.Ped,plt.mp.pace/5,'viewxy',plt.mp.viewxy);
c.display_csg();
axis on


s_lim=[1135 3504.8];
size(mp.recorder.U{1})

% for i=[1 5 10 15 20]
for i=[10]
eles_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/eles_stp',num2str(i),'.txt'];
vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/vers_stp',num2str(i),'.txt'];
ap=AnsysPloter(eles_path,vers_path);


%--------------------------------------------------div mesh
% I=size(ap.totMesh.Vertices,1);

    U=mp.recorder.U{i};

    %----------------------------inter_data
    cur_c=mp.recorder.intermediate_c{i};

%     %---------------------------surf_u
    
    u=compute_u(ap.totMesh.Vertices,U,mp);%3x1xLen
    norm_u=vecnorm(u,2,1);
    norm_u=norm_u(:);

    tot_u=norm_u;

%------------------------------------div mesh
sub1_vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/sub1_vers_stp',num2str(i),'.txt'];
sub2_vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/sub2_vers_stp',num2str(i),'.txt'];

[mesh_rc1,jdAct1]=ap.get_subMesh_by_vers(sub1_vers_path);
[mesh_rc2,jdAct2]=ap.get_subMesh_by_vers(sub2_vers_path);


if i>=10
    sub3_vers_path=['./SolidWoks Files/Cylinders/txt/ansys_mesh_info/sub3_vers_stp',num2str(i),'.txt'];
    [mesh_rc3,jdAct3]=ap.get_subMesh_by_vers(sub3_vers_path);
    mesh_no_rc=ap.totMesh;
    mesh_no_rc.Faces=mesh_no_rc.Faces(~jdAct1 & ~jdAct2 & ~jdAct3,:);
else
    mesh_no_rc=ap.totMesh;
    mesh_no_rc.Faces=mesh_no_rc.Faces(~jdAct1 & ~jdAct2,:);
end


%------------------------------------plot u
    figure
    plot_surf(mesh_no_rc,tot_u,"set(p,'FaceLighting','flat');");
    plot_surf(mesh_rc1,tot_u);
    plot_surf(mesh_rc2,tot_u);
    if i>=10
        plot_surf(mesh_rc3,tot_u);
    end    
%     plot_surf(ap.totMesh,tot_u);
    camlight('headlight');
%     view(mp.viewxy)
    c=colorbar;
%     t=get(c,'Limit');
%     disp(t(2)*1e4)
    clim([0 12*1e-4]);
% if i==1 || i==3
%     clim([0 0.2])
% elseif i==5
%     clim([0 0.4])
% end
   


    print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['u_stp' num2str(i)]]);


    %--------------------------------plot s
    figure
    stress=compute_stress(ap.totMesh.Vertices,U,mp);% 6x1xI
    stress=reshape(stress,6,[])';
    von_s=cal_von_Mises_Stress(stress);
    tot_s=von_s/1e3;

    figure
    p1=plot_surf(mesh_no_rc,tot_s,"set(p,'FaceLighting','flat');");  
    p2=plot_surf(mesh_rc1,tot_s);
    p3=plot_surf(mesh_rc2,tot_s);
    if i>=10
        p4=plot_surf(mesh_rc3,tot_s);
    end
%     plot_surf(ap.totMesh,tot_s);
    camlight('headlight');
%     view(mp.viewxy)

%     c=colorbar;
%     t=get(c,'Limit');
%     disp(t(2))
    clim([0 1.4]);
% if i==1 || i==3
%     clim([0 100])
% elseif i==5
%     clim([0 200])
% end

        print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['s_stp' num2str(i)]]);


end

%
% stress norm

if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end
% manual set
% plt.mp.viewxy=[60 60];
stress_flg=1;
if stress_flg
    plt.cAxis=[0 2];
    figure
    plt.plot_stress(1)
    axis on
else
    plt.cAxis=[0 250];
    figure
    plt.plot_move(1)
    axis on
end


cla;
idx_list=[1 4 7 11 12 21 31 41 51];%
base_pos = [0.05 0.75 0.25 0.25];%
base_annPos=[0.05+0.08 0.75-0.05 0.18 0.05];%
base_annText='Step. ';
cot=1;
for j=0:2
    for i=0:2
        dcoord=[i*0.28 j*-0.28 0 0];%
        pos=base_pos+dcoord;
        annPos=base_annPos+dcoord;
        subplot('Position',pos);
        annotation('textbox',annPos,'String',[base_annText,num2str(idx_list(cot))],...
            'EdgeColor','none','FontName',plt.font_name,'FontSize',plt.font_size);
        if stress_flg
            plt.plot_stress(idx_list(cot));
        else
            plt.plot_move(idx_list(cot));
        end
        cot=cot+1;
    end
end
clb=colorbar('southoutside','AxisLocation','in','FontWeight',"bold",'FontName',plt.font_name,'FontSize',plt.font_size,'FontWeight','bold','Position',[0.12 0.05 0.72 0.02]);

set(gcf, 'position', [0 0 700 700]*2);% set figure size
if stress_flg
    clb.Ruler.Exponent = 0;
    print(gcf,'-dpng','-r300',['NNew_Data/',plt.sample_name,'/3stress']);
else
    clb.Ruler.Exponent = 2;
    print(gcf,'-dpng','-r300',['NNew_Data/',plt.sample_name,'/4move']);
end

%
%
% Export data to excel

if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end

plt.extract_excel();

%
% Extract txt

if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end
plt.extract_stl_and_txt([1:10 15 20],2);

%
% Extract  video

clf;
if ~exist('plt')
    plt=Plotter('Cylinders','NNew_Data');
end

stress_flg=0;
if stress_flg
    writeobj=VideoWriter([plt.folder_name,'/',plt.sample_name,'/','stress_Video.avi']);
    cAxis=[0 2];
else
    writeobj=VideoWriter([plt.folder_name,'/',plt.sample_name,'/','movement_Video.avi']);
    cAxis=[0 250];
end
writeobj.FrameRate=6;
writeobj.open();

slowList=1:11;
slowList=kron(slowList,[1 1 1]);

for index=[slowList,12:51]
    figure
    cAxis=cAxis;
    data=mp.recorder.data{index};
    if stress_flg
        cdata=mp.recorder.sdata{index};
    else
        cdata=mp.recorder.udata{index};
    end
    cdata(cdata>cAxis(2))=cAxis(2);
    mp.display_u(data,cdata);
    colorbar('off')
    axis off
    caxis(cAxis);
    ax=gca;   
    ax.CameraPositionMode='manual';
    ax.CameraPosition = [50 50 100];

    ax.CameraTargetMode='manual';
    ax.CameraTarget=[0 0 50];
    ax.CameraViewAngleMode='manual';
    ax.CameraViewAngle = 80;

    
    frame=getframe(gcf);
    if index==1
        H=size(frame.cdata,1);
        W=size(frame.cdata,2);
    else
        disp(size(frame.cdata));
        frame.cdata=imresize(frame.cdata,[H W]);
    end

    writeobj.writeVideo(frame);
end

%
% Extract CSG Tree

prec=8;
last_rootH=mp.recorder.intermediate_c{end}.rootH;
output_file=['/home/cflin/MatlabCode/TopCSG/NNew_Data/Cylinders/CSG_trees/'];
que={};
last_rootH.level=1;
que{end+1}=last_rootH;
cot=0;
last_level=-1;
while(~isempty(que))
    rootH=que{1};
    level=rootH.level;
    if(level~=last_level)
        last_level=level;
        cot=0;
    end
    que(1)=[];
    cot=cot+1;
    
    commit='Primitive';
    if(isa(rootH,'Operator'))
        rootH.lchild.level=level+1;
        rootH.rchild.level=level+1;
        que{end+1}=rootH.lchild;
        que{end+1}=rootH.rchild;
        if(isa(rootH,'OperateMinus'))
            commit='Minus';
        elseif(isa(rootH,'OperateMtimes'))
            commit='Mtimes';
        elseif(isa(rootH,'OperatePlus'))
            commit='Plus';
        elseif(isa(rootH,'FULL'))
            commit='FULL';
        elseif(isa(rootH,'NULL'))
            commit='NULL';
        end
    end

    tmp=rootH.get_outer_points();
    the_Pst=min(tmp(:,1:3));
    the_Ped=max(tmp(:,4:6));
    rootH.node2stl(the_Pst,the_Ped,mp.pace/prec,[output_file,'node_',num2str(level),'_',num2str(cot),'_',commit]);

        
end