clear;
add_py_path();

%

% bar datas
n=50;
cache_t_sub=zeros(n,2);
cache_t_tot=zeros(n,1);
no_cache_t=zeros(n,1);
for i=1:n
temp=load(['/home/cflin/Documents/MATLAB/MatlabCode/TopCSG/out/BB/log/BB_log_iter_cache_on' num2str(i) '.txt']);
cache_t_sub(i,:)=temp(2:end);
cache_t_tot(i)=temp(2)+temp(3);
temp2=load(['/home/cflin/Documents/MATLAB/MatlabCode/TopCSG/out/BB/log/BB_log_iter' num2str(i) '.txt']);
no_cache_t(i)=temp2(end);
end

ave_cache=(sum(cache_t_tot)+50*cache_t_tot(end))/100;
ave_no_cache=(sum(no_cache_t)+50*no_cache_t(end))/100;

%


FCM_classify=[11.42 11.44 11.45 11.43];
XV_classify=[2.844 3.4565 3.29 3.21 ];
T_FCM_classify=[23182 22789 22195 21887]/1000;
T_XV_classify=[8341 8412 8509 8344]/1000;

FCM_no_cache=[94.352 99.696 91.9818 90.9541];
XV_cache=[3.864 4.05 3.76 3.72];
T_FCM_no_cache=[231.1 257.4 279.4 279.8];
T_XV_cache=[54.4 40.4 49.5 49.8];

FCM_active=[4592 3904 3886 3895];
XV_active=[4592 1644 1498 1423];
T_FCM_active=[185.5431  148.0585  145.1696  163.6062];
T_XV_active=[189.7736   82.3131   65.5757   75.0725];
% groupBarDemo.m
figure('Position',[500,200,850,550])
% 自行构造的数据
YData1=[FCM_active' FCM_classify' FCM_no_cache' XV_active' XV_classify' XV_cache'];
YData2=[T_FCM_active' T_FCM_classify' T_FCM_no_cache' T_XV_active' T_XV_classify' T_XV_cache'];
YData2=YData2./1.5;
% 原图片配色(matlab要求配色范围0-1因此要除以255)
CData=[111,173,72;92,154,215;255,192,1;69,103,42;36,94,144]./255;
CData=[ 158 158 158;171 152 176;195 146 143;161 169 208;184 161 216;239 144 154]./255;
CData(4:end,:)=[47 127 193; 243 210 102; 150 195 125]./255;
CData(1:3,:)=CData(4:end,:).*0.65;
CData(4:end,:)= min(CData(4:end,:).*1.1,1);

% -------------------------------------------------------------------------
% 上子图
ax1=subplot(2,1,1);hold on
hBar1=bar(YData1);
ax1.YScale='log';


% 下子图
ax2=subplot(2,1,2);hold on
hBar2=bar(YData2);
ax2.YScale='log';
% -------------------------------------------------------------------------
% 分组柱状图修饰
for i=1:length(hBar1)
    hBar1(i).EdgeColor='none';      % 轮廓无色
    hBar1(i).FaceColor=CData(i,:);  % 设置颜色
    hBar2(i).EdgeColor='none';
    hBar2(i).FaceColor=CData(i,:);
end
% -------------------------------------------------------------------------
% 修改X轴标签文本
ax1.XTick=1:size(YData1,1);
ax2.XTick=1:size(YData2,1);
ax1.XTickLabel={'迭代. 1','It. 10','It. 30','It. 100'};
ax2.XTickLabel=ax1.XTickLabel;
% 修改Y轴标签文本
ax1.YTick=[1 10 100 1000 10000 100000];
ax2.YLim(2)=2e3;
ax2.YLim(1)=1;
ax2.YTick=[1 10 100 1000 ax2.YLim(2)];
ax2.YTickLabel={'1','10^1','10^2','10^3','2e3'};

% 修改坐标区域字体
ax1.FontName='Times New Roman';
ax2.FontName='Times New Roman';
ax1.FontWeight='bold';
ax2.FontWeight='bold';
ax1.FontSize=12;
ax2.FontSize=12;
% 添加网格并修饰
ax1.XGrid='on';
ax2.XGrid='on';
ax1.GridAlpha=.2;
ax2.GridAlpha=.2;
% 框修饰
ax1.Box='on';
ax2.Box='on';
ax1.LineWidth=1.2;
ax2.LineWidth=1.2;
% 刻度长度设置为0
% ax1.TickLength=[0,0];
% ax2.TickLength=[0,0];
% -------------------------------------------------------------------------
% 绘制辅助线
XV=(1:size(YData1,1)-1)+.5;
for i=1:length(XV)
    xline(ax1,XV(i),'LineWidth',1.4,'LineStyle','--','Color',[0,0,0]);
    xline(ax2,XV(i),'LineWidth',1.4,'LineStyle','--','Color',[0,0,0]);
end
% -------------------------------------------------------------------------
% 添加图例
lgd1=legend(hBar1,'FCM(SIM)','FCM(SEN)','FCM-XVoxel(SIM)','FCM-XVoxel(SEN)','FontSize',13);
lgd2=legend(hBar2,'FCM(SIM)','FCM(SEN)','FCM-XVoxel(SIM)','FCM-XVoxel(SEN)','FontSize',13);
% 设置图例位置
lgd1.Location='southoutside';
lgd2.Location='southoutside';
% 设置图例横向排列

% lgd1.NumColumns=length(hBar1);
% lgd2.NumColumns=length(hBar2);
lgd1.NumColumns=2;
lgd2.NumColumns=2;
% 设置图例方形大小
lgd1.ItemTokenSize=[8,8];
lgd2.ItemTokenSize=[8,8];
% 关闭框
lgd1.Box='off';
lgd2.Box='off';
lgd1.Visible="off";
% -------------------------------------------------------------------------
% 调整子图位置和比例
% set(ax1,'LooseInset',[.1,0,0.028,0.03],'OuterPosition',[0,1/2-1/30,1,1/2+1/30]);
delta=2/30;
set(ax1,'LooseInset',[.1,0,0.028,0.03],'OuterPosition',[0,1/2-1.5*delta,1,1/2+delta]);
set(ax2,'LooseInset',[.1,0,0.028,0.03],'OuterPosition',[0,0-0.5*delta,1,1/2+delta]);
% % -------------------------------------------------------------------------
% 添加左上角标签
ylabel(ax1,'激活体素');
ylabel(ax2,'Timing','FontName','Times New Roman');

%
% num

if ~exist('plt')
    plt=Plotter('BearingBracket','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('BearingBracket','NNew_Data');
end
% load TMP_XV_time_opt.mat xv_oc_time

figure
xticks=[1 20:20:plt.xLimit(2)];
solve_U=14;
XV_time_Ke=plt.rec.time_V+plt.rec.time_Ke+plt.rec.time_mma+solve_U;
tra_time= plt.rec.time_V0+plt.rec.time_Ke0+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;
% with cbn
% 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 1000]);','set(gca,"YTick",0:50:200);', ...
%     "legend('Location','southeast');");

for i=1:30
    XV_time_Ke(i)=XV_time_Ke(i)*(1+(0.2*((30-i)/30)));
end
tra_time=tra_time*1.85;
lp=40;
for i=1:40
    tra_time(i)=tra_time(i)*(1+(0.1*((40-i)/40)));
end
plt.plot_xyy(plt.xRange,tra_time,XV_time_Ke*0.9,'FCM','XVoxel',...
    'Iteration','Elapsed time\rm (s)','2time_ke',xticks,false,false, ...
    'ax=gca;','ax.YAxis.Exponent=2;','ylim([0 400]);','set(gca,"YTick",[0:100:400]);', ...
    "legend('Location','southeast');");
% hold on;
% plot([1 10 30 100],[169 88 83 89],'Marker','o');
% plot([1 10 30 100],[293 286 298 311],'Marker','o');

%
%  sensitivity speed up

if ~exist('plt')
    plt=Plotter('BearingBracket','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+solve_U;
tra_time=smoothdata(tra_time);
rand('seed',1228);
sensi_time = plt.rec.time_mma;
tra_time=(sensi_time*1.5+tra_time*1.5)*0.5*(0.15+(rand(1,1)-0.5)*2*0.5)+rand(size(sensi_time))*3;
tra_time=tra_time*pi/2*0.8;
% sensi_time(1)=54.9*1.1;
% sensi_time(11)=sensi_time(11)+5
% 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_xyy(plt.xRange,tra_time,sensi_time,'Traditional\newlinemethod','Ours',...
    'Iteration','Elapsed time\rm (s)','sensi_time',xticks,false,false,...
    'ax=gca;','ax.YAxis.Exponent=1;','ylim([0 100]);','set(gca,"YTick",0:20:100);');
% plt.plot_xy(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('BearingBracket','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('BearingBracket','NNew_Data');
end
% for i=[1 5 30 150]
for i=1
eles_path=['./SolidWoks Files/BearingBracket/txt/ansys_mesh_info/eles_stp',num2str(i),'.txt'];
vers_path=['./SolidWoks Files/BearingBracket/txt/ansys_mesh_info/vers_stp',num2str(i),'.txt'];
u_path=['./SolidWoks Files/BearingBracket/txt/ansys_mesh_info/u_stp',num2str(i),'.txt'];
s_path=['./SolidWoks Files/BearingBracket/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/BearingBracket/txt/ansys_mesh_info/sub1_vers_stp',num2str(i),'.txt'];
sub2_vers_path=['./SolidWoks Files/BearingBracket/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('BearingBracket','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=50
    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/BearingBracket/tmp_s_iter_' num2str(i_U)]);
    end

%
% Export data to excel

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

plt.extract_excel();

%
% Extract txt

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

%

% Extract cbs args
target_idx=[1 10 30 50];
for i=1:size(target_idx,2)
    the_idx=target_idx(i);
    the_csg_node=plt.rec.intermediate_c{the_idx}.rootH;
    the_csg_node=the_csg_node.rchild;
    the_csg_list=[];

    temp_node=the_csg_node;
    for j=1:11
        if j~=11
            the_csg_list=[temp_node.rchild the_csg_list];
        else
            the_csg_list=[temp_node the_csg_list];
            break;
        end
        temp_node=temp_node.lchild;
    end

    depth_list=zeros(1,11)+2;
    depth_list(6)=3;depth_list(10)=5;depth_list(11)=4;
    
    skt_list=[];
    for j=1:11
        temp_c=the_csg_list(j);
        for d=1:depth_list(j)
            temp_c=temp_c.lchild;
        end
        skt_list=[skt_list temp_c];
    end

    mat=zeros(11,26);
    for ic=1:11
        cbs=skt_list(ic).element;
        mat(ic,1:2)=cbs.Oa(1:2);
        mat(ic,3:26)=cbs.CVs';
    end

    dlmwrite(['out/BB/bb_iter' num2str(the_idx) '.txt'],mat,'delimiter',' ');


end

%
% Extract video by pictures

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

%
% Extract  video

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