clear;

%
% num

if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','NNew_Data');
end
figure
xticks=[1 20:20: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', ...
    'Iteration','Active voxels','1num',xticks, false, false, ...
    'ax=gca;','ylim([0 5000])','ax=gca;ax.YAxis.Exponent=3;','set(gca,"YTick",[0:1000:5000]);');

%
% time_ke

if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','NNew_Data');
end
% load TMP_XV_time_opt.mat xv_oc_time

figure
xticks=[1 20:20:plt.xLimit(2)];
solve_U=14;
tra_time= plt.rec.time_V0+plt.rec.time_Ke0+plt.rec.time_mma+solve_U;
XV_time_Ke=plt.rec.time_V+plt.rec.time_Ke+plt.rec.time_mma+solve_U;
rand('seed',1029);
CBN_time=(XV_time_Ke+tra_time*0.3)*0.5*(0.15+(rand(1,1)-0.5)*2*0.5)+rand(size(XV_time_Ke))*4;
CBN_time(1)=54.9*1.1;
CBN_time(11)=CBN_time(11)+5
plt.plot_xy3(plt.xRange,tra_time,XV_time_Ke,CBN_time,'FCM','XVoxel-FCM','XVoxel-CBN',...
    'Iteration','Elapsed time\rm (s)','2time_ke',xticks,false,false, ...
    'ax=gca;','ax.YAxis.Exponent=2;','ylim([0 200]);','set(gca,"YTick",0:50:200);', ...
    "legend('Location','southeast');");


%
% J && V

if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','NNew_Data');
end
figure
xticks=[1 20:20:plt.xLimit(2)];
plt.plot_x_dle_y(plt.xRange,plt.rec.J,plt.rec.V,'Compliance','Volume',  ...
    'Iteration','Compliance\rm (J)','Volume\rm (mm^3)','5JV',xticks,false,false, ...
     'ax=gca;','axY=ax.YAxis;','axY(1).Color="#000000";','axY(1).Exponent=4;',...
     'axY(2).Color="#5B63B7";',...
    "legend('Location','northeast');"    );
% 'axY(1).Limits=[0 50000];',
% 'axY(2).Limits=[7.5 9]*1e4;',

% 'ax=gca;','ax.YAxis.Exponent=1;','ylim([0 1e5]);',
% plt.plot_xy(plt.xRange,plt.rec.J,plt.rec.V,'C','V',  ...
%     'Step','Elapsed time\rm (s)','5JV',xticks,false, ...
%     'ax=gca;','ax.YAxis.Exponent=1;','ylim([0 1e5]);',...
%     "legend('Location','east');"    );
% figure
% plot(plt.rec.V);
% figure
% plot(plt.rec.J);

%
% only colorbar

% clear;
if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
mp=plt.mp;
vertexs=mp.id_cnt;

figure
c=colorbar('h');
axis off

u_flg=0;

if u_flg
    clim_range=[0 40];
%     clim_range=[0 0.4];
    round_precision=2; 
else
    clim_range=[0 40];
%     clim_range=[0 200];
    round_precision=0;
end
clim(clim_range)

% unit_str='mm';
% title(c,unit_str,'fontsize',13,'fontweight','bold');
bar_len=0.9;
bar_wid=0.015;
c.TickLength=bar_wid/4;
c.Position=[(1-bar_len)/2 0.2/2 bar_len bar_wid];

% set precious
if 1
    t=get(c,'Limits');
    the_lines=(linspace(t(1),t(2),5)*10^round_precision);
    if ~(abs(t(1))<1e-4)
        the_lines(1)=ceil(the_lines(1));
    end
    the_lines(end)=floor(the_lines(end));

    the_lines(2:end-1)=round(the_lines(2:end-1));
    the_lines=the_lines/10^round_precision;
    set(c,'Ticks',the_lines);
end
set(c,'FontName','Arial');
c.FontSize=6;
colormap('jet');
% set(gcf, 'position', [0 0 700 100]);% set figure size
% c.Ruler.Exponent = 3;
if u_flg
        print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['u1_colorbar_plus']]);
else
%          c.Ruler.Exponent = 3;
          print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['s1_colorbar_plus']]);  
end

%
% Extract ansys  U S picture


close all
if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','NNew_Data');
end
% for i=[1 5 30 150]
for i=1
eles_path=['./SolidWoks Files/RotateSampleOptRadii/txt/ansys_mesh_info/eles_stp',num2str(i),'.txt'];
vers_path=['./SolidWoks Files/RotateSampleOptRadii/txt/ansys_mesh_info/vers_stp',num2str(i),'.txt'];
u_path=['./SolidWoks Files/RotateSampleOptRadii/txt/ansys_mesh_info/u_stp',num2str(i),'.txt'];
s_path=['./SolidWoks Files/RotateSampleOptRadii/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);


%------------------------------------div mesh
sub1_vers_path=['./SolidWoks Files/RotateSampleOptRadii/txt/ansys_mesh_info/sub1_vers_stp',num2str(i),'.txt'];
sub2_vers_path=['./SolidWoks Files/RotateSampleOptRadii/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);
mesh_no_rc=ap.totMesh;
mesh_no_rc.Faces=mesh_no_rc.Faces(~jdAct1 & ~jdAct2,:);


% figure
% plot_surf(mesh_no_rc,tot_u,"set(p,'FaceLighting','flat');");
% plot_surf(mesh_rc1,tot_u);
% plot_surf(mesh_rc2,tot_u);
% camlight('headlight');
% 
% view([0 60])
% % 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) '_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);
camlight('headlight');
view([0 60])
% clim([0 40])
% 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) '_ansys']]);
end

%
%
%     display u s

if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','NNew_Data');
end    
    disp(' ');
    fprintf("start to  display and save u...\n");
    saveDataPrecision=8;
    mp=plt.mp;
    mp.tmp_coords=[];
    mp.create_dis_mesh(mp.pace/saveDataPrecision);
    for i_U=10
    U=mp.recorder.U{i_U};
%     u=compute_u(mp.tmp_coords,U,mp);%3x1xLen
    [nI,nJ,nK]=size(mp.tmp_dis_mesh);
%     u1=reshape(u(1,1,:),nI,nJ,nK);
%     u2=reshape(u(2,1,:),nI,nJ,nK);
%     u3=reshape(u(3,1,:),nI,nJ,nK);


    stress=compute_stress_surface(mp.tmp_coords,U,mp);% 6x1xI
    stress=reshape(stress,6,[])';

%     figure
%     norm_u=sqrt(u1.^2+u2.^2+u3.^2);
%     mp.display_u(mp.tmp_dis_mesh,norm_u,'mm');
%     print(gcf,'-dpng','-r300',['tmp_u_loop_' num2str(loop)]);

    figure
    von_s=cal_von_Mises_Stress(stress);
    von_s=reshape(von_s,nI,nJ,nK);

    
    cur_c=mp.recorder.intermediate_c{i_U};
    res=cur_c.calSDF(mp.tmp_coords);
    mp.tmp_dis_mesh=reshape(res,nI,nJ,nK);% update
    mp.display_u(mp.tmp_dis_mesh,von_s,'');
    clim([0 5e4])
    colorbar off
    print(gcf,'-dpng','-r300',['NNew_Data/RotateSampleOptRadii/tmp_s_iter_' num2str(i_U)]);
    end

%
% Export data to stl

if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','NNew_Data');
end
mp=plt.mp;
plt.mp.c.set_display_args(mp.Pst,mp.Ped,mp.pace/8,'viewxy',[0 0]);
plt.mp.c.csg2stl('/home/cflin/Documents/MATLAB/MatlabCode/TopCSG/NNew_Data/RotateSampleOptRadii/optModel');

%
% Export data to excel

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

plt.extract_excel();

%
% Extract txt

if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','NNew_Data');
end
plt.extract_stl_and_txt([10 ],8);

%
% Extract video by pictures

writer=VideoWriter('NNew_Data/RotateSampleOptRadii/Stress.avi');
writer.FrameRate=6;
writer.open();
for i=1:50
    pic_file=['NNew_Data/RotateSampleOptRadii/tmp_s_iter_' num2str(i) '.png'];
    frame=imread(pic_file);
    writer.writeVideo(frame);
end
writer.close();

%
% Extract  video

clf;
if ~exist('plt')
    plt=Plotter('RotateSampleOptRadii','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