%% Figure S4 generator

clear all
close all


%% settings
% colormap
cjet=jet;
cmap1=cjet([1 50 80 95],:);%線

%cmap2=cjet([180 215 256],:);%交点
cmap2=cjet([180:256],:);

%border
a0=[12 7 3 1];
b0=[20 18 12 5];

%外周内判定線分
p=(20-12)/(9-3);%a-b平面内の傾き
q=8;%a-b平面内の切片

%intersection
x_int = (b0(2:end)-b0(1:end-1))./(a0(2:end)-a0(1:end-1));
y_int = -a0(1:end-1).*(b0(2:end)-b0(1:end-1))./(a0(2:end)-a0(1:end-1))+b0(1:end-1);

x_start = 0;
x_end = 10;

%% linear piecewise function and objective function
figure(1)
hold on
for ii=1:length(a0)%境界線   
    switch ii
        case 1     
            x=[x_start x_int(ii)];            
        case {2,3}                
            x=x_int(ii-1:ii);            
        case 4            
            x=[x_int(ii-1) x_end];            
    end
    
    plot(x,-a0(ii)*x+b0(ii),'-','Color',cmap1(ii,:),'LineWidth',2);    
end 

% for ii=1:length(a0)%交点
%     if ii>1
%         plot(x_int(ii-1), y_int(ii-1),'s','MarkerFaceColor',cmap2(ii-1,:),'MarkerEdgeColor',cmap2(ii-1,:),'MarkerSize',14);
%     end
% end
colormap(cmap2)
ss=scatter(x_int',y_int',100,x_int','s','filled');


%目的関数例
x=[0 4];
a = 5;
b = 15;
plot(x,b-a*x,'k--');


% figure label
box on
grid on
set(gca,'FontSize',16)
xlabel('$$ x_g $$','fontsize',24,'Interpreter','latex');
ylabel('$$ x_s $$','fontsize',24,'Interpreter','latex');
xlim([0 6]);
ylim([0 25]);

set(gcf,'Color',[1 1 1]);

%% Cg,Cs and optimal solution
smalln=0.0001;

Cg = 0.01:0.01:10;
Cs_plus = Cg'*(a0.^-1)+smalln;
Cs_minus = Cg'*(a0.^-1)-smalln;
Cs=sort([Cs_plus(:);Cs_minus(:)],'ascend');
[Cg_m, Cs_m]=meshgrid(Cg,Cs);

temp_L = Cg_m(:)*x_int + Cs_m(:)*y_int;
[~,j_min]=min(temp_L,[],2);
ij_min = reshape(j_min,length(Cs),length(Cg));%temp_Lが最小となるx_intのj番号
ij_outrange = Cg_m./Cs_m >= a0(1) | Cg_m./Cs_m <= a0(end);%a0の範囲外＝１
xg_opt=x_int(ij_min);
xs_opt=y_int(ij_min);
xg_opt(ij_outrange)=NaN;
xs_opt(ij_outrange)=NaN;

figure()
colormap(cmap2)
contourf(Cg_m,Cs_m,xg_opt)

set(gca,'FontSize',16)
xlabel('$$ c_g $$','fontsize',24,'Interpreter','latex');
ylabel('$$ c_s $$','fontsize',24,'Interpreter','latex');
xlim([0 max(Cg)]);
ylim([0 max(Cs)]);
grid on
set(gcf,'Color',[1 1 1]);
