%% This shell aims to calculate the H-Kappa
% Written by Hyy on 2025/5/22
clear;clc;close all
%%
sacdir = "D:\YB\yunnan2\F0_6.0_waterlevel_0.01\3_selected_stationset_v2";
dirlist = string(ls(fullfile(sacdir, 'NK*')));
fig_savedir = "D:\YB\yunnan2\F0_6.0_waterlevel_0.01\HKAPPA_ANALYSIS";
if ~exist(fig_savedir, 'dir')
    mkdir(fig_savedir);
end

np = 1000;
mod = 'ak135'; thmax = 15;
em = refinemodel(set_vmodel_v2(mod), thmax);

labelsize = 28;
tickfontsize = 24;
labelsize2 = 24;
tickfontsize2 = 20;
textsize = 16;
color = [0,0,0;0.7451,0.7451,0.7451];% black and grey
color_moveout = [1,0,0;0.7451,0.7451,0.7451];%red and grey
color_stack = [0,0,1;0.7451,0.7451,0.7451];
amp_scale = 1;

timewin = [-30 60];
delta = 0.1;
time = (timewin(1):delta:timewin(2))';
t0 = -timewin(1);
rayp0 = 0.07;
fl = 0.02;
fh = 1;
order = 2;

dH = 0.1;
dk = 0.01;
H = 30:dH:60;
k = 1.5:dk:2.0;
vp = 6.3;
ref_k = 1.73;
weight = [3/5 1/5 1/5];

% bootstrap
B = 500; % bootstrap times,要做 500 次重采样来估计s0的波动 


% ind_4 = find(time == 4);
% ind_8 = find(time == 8);
% ind_16 = find(time == 16);
% ind_20 = find(time == 20);
% ind_22 = find(time == 22);
% ind_26 = find(time == 26);

% flag_H = 1;
% H_results_savepath = fullfile(fig_savedir, "mohodepth.txt"); 
% if ~exist(H_results_savepath, 'file')
%     flag_H = 0;
%     fid1 = fopen(H_results_savepath, 'w');
%     fprintf(fid1, '# Longitude Latitude MohoDepth \n');
% end
% flag_k = 1;
% k_results_savepath = fullfile(fig_savedir, "kappa.txt");
% if ~exist(k_results_savepath, 'file')
%     flag_k = 0;
%     fid2 = fopen(k_results_savepath, 'w');
%     fprintf(fid2, '# Longitude Latitude Kappa \n');
% end
% flag_stloc = 1;
% station_loc_savepath = "D:\YB\YB-geospatial\china-geospatial-data-GB2312\YB_station.txt";
% if ~exist(station_loc_savepath, 'file')
%     flag_stloc = 0;
%     fid3 = fopen(station_loc_savepath, 'w');
%     fprintf(fid3, '# Longitude Latitude \n');
% end

% H_uncertainty_savepath = fullfile(fig_savedir, "H_uncertainty.txt"); 
% fid4 = fopen(H_uncertainty_savepath, 'w');
% fprintf(fid4, '# Longitude Latitude H_uncertainty \n');
% 
% K_uncertainty_savepath = fullfile(fig_savedir, "K_uncertainty.txt"); 
% fid5 = fopen(K_uncertainty_savepath, 'w');
% fprintf(fid5, '# Longitude Latitude K_uncertainty \n');

for i = 27%:length(dirlist)
    clear RF rayp RF_moveout distance
%     tempfile = dir(fullfile(sacdir, dirlist(i)));
%     if length(tempfile) <= 2
%         continue
%     end
%      sacfiles = string(ls(fullfile(inputdir, stdir(profile_NO(i)), '*R.sac.PF.Decon')));
     fid = fopen(fullfile(sacdir, dirlist(i), 'list_r_Decon_PF.txt'), 'r');
     if fid == -1
         continue
     end
     list_r_Decon_PF = textscan(fid, '%s %f %f %f %f %s %s %f %f %f %f %f %f %f %f %f %f %f %f \n', ...
         'Commentstyle', 'shell', 'HeaderLines', 1); 
     fclose(fid);
     if isempty(list_r_Decon_PF{1})
         continue
     end
     sacfiles = list_r_Decon_PF{1};
     rayp = list_r_Decon_PF{8};
     distance = list_r_Decon_PF{15};
    for j = 1:length(sacfiles)
        [hdr, data] = irdsac(fullfile(sacdir, dirlist(i), sacfiles(j)));
        RF(:,j) = filtering(data, hdr.delta, fl, fh, order);
        RF(:,j) = RF(:,j)/max(abs(RF(:,j)));
        header{j} = hdr;
%         [RAYP, taup, Xp]= y_get_p_P_Pdiff (hdr.evdp, np, em);
%         dd = Xp*180/pi;
%         dist = hdr.gcarc;
%         rayp_i = interp1db(dist, dd, RAYP);
%         rayp_i = rayp_i/6371; % slowness unit: s/km
%         rayp(j) = rayp_i;
%         distance(j) = dist;
    end
    [S, xi] = y_Hkappa_modified_v2( RF, time, rayp, H, k, vp, weight );
    [ind_k, ind_H] = find(S == max(max(S)));
    theo_k = sum(k(ind_k))/length(k(ind_k));
    theo_H = sum(H(ind_H))/length(H(ind_H));
    [X, Y] = meshgrid(H, k);
    [X_new, Y_new] = meshgrid(linspace(H(1), H(end), 2001), linspace(k(1), k(end), 251));
    Hk_new = interp2(X,Y,S, X_new,Y_new, 'linear');
    
    %% calculate uncertainty
    B = 300;                 % bootstrap次数
    dH = 0.1; dK = 0.01;     % 你的网格步长（按你实际的）
    Hgrid = (theo_H-3):dH:(theo_H+3);      % 只在最优点±3 km内重搜
    Kgrid = (theo_k-0.08):dK:(theo_k+0.08);% 只在最优点±0.08内重搜
    Ne = size(RF,2);
    Hbest = nan(B,1);
    Kbest = nan(B,1);
    for b = 1:B
        idx = randi(Ne, Ne, 1);        % 有放回抽样事件
        RFb = RF(:,idx);
        pb  = rayp(idx);
        % 计算这一轮的能量面 Sb
        Sb = y_Hkappa_modified_v2( RFb, time, pb, Hgrid, Kgrid, vp, weight );
        % 找最大值
        [~, idm] = max(Sb(:));
        [iK, iH] = ind2sub(size(Sb), idm);
        Hbest(b) = Hgrid(iH);
        Kbest(b) = Kgrid(iK);
    end

    % 1-sigma（标准差）
    sigmaH = std(Hbest, 'omitnan');
    sigmaK = std(Kbest, 'omitnan');
    fprintf('Bootstrap param std: sigmaH=%.2f km, sigmaK=%.3f\n', sigmaH, sigmaK);
%     fprintf(fid4, '%0.4f %0.4f %0.1f \n', hdr.stlo, hdr.stla, sigmaH);
%     fprintf(fid5, '%0.4f %0.4f %0.2f \n', hdr.stlo, hdr.stla, sigmaK);
    

    
%     if flag_H == 0
%     fprintf(fid1, '%0.4f %0.4f %0.1f \n', hdr.stlo, hdr.stla, theo_H);
%     else
%         fid_temple_1_r = fopen(H_results_savepath, 'r');
%         H_result = textscan(fid_temple_1_r, '%f %f %f \n', 'CommentStyle', 'shell', 'HeaderLines', 1);
%         H_result_lo = H_result{1};
%         H_result_la = H_result{2};
%         H_result_H  = H_result{3};
%         H_result_H(i) = theo_H;
%         fid_temple_1_w = fopen(H_results_savepath, 'w');
%         fprintf(fid_temple_1_w, '# Longitude Latitude MohoDepth \n');
%         for i_result = 1:length(H_result_H)
%             fprintf(fid_temple_1_w, '%f %f %f \n', H_result_lo(i_result), H_result_la(i_result), H_result_H(i_result));
%         end
%         fclose(fid_temple_1_r);
%         fclose(fid_temple_1_w);
%     end
%     if flag_k == 0
%         fprintf(fid2, '%0.4f %0.4f %0.2f \n', hdr.stlo, hdr.stla, theo_k);
%     else
%         fid_temple_2_r = fopen(k_results_savepath, 'r');
%         k_result = textscan(fid_temple_2_r, '%f %f %f \n', 'CommentStyle', 'shell', 'HeaderLines', 1);
%         k_result_lo = k_result{1};
%         k_result_la = k_result{2};
%         k_result_k  = k_result{3};
%         k_result_k(i) = theo_k;
%         fid_temple_2_w = fopen(k_results_savepath, 'w');
%         fprintf(fid_temple_2_w, '# Longitude Latitude Kappa \n');
%         for i_result = 1:length(k_result_k)
%             fprintf(fid_temple_2_w, '%f %f %f \n', k_result_lo(i_result), k_result_la(i_result), k_result_k(i_result));
%         end
%         fclose(fid_temple_2_r);
%         fclose(fid_temple_2_w);
%     end
%     if flag_stloc == 0
%         fprintf(fid3, '%0.4f %0.4f \n', hdr.stlo, hdr.stla);
%     end



    %% H-k figure
    figure(1)
    pcolor(X_new, Y_new, Hk_new);
    colormap('parula')  
    shading interp
    colorbar
%     caxis([max(max(Hk_new))/2  max(max(Hk_new))])
    hold on
    plot([H(1), H(end)], [theo_k, theo_k], 'k-', 'LineWidth', 2);
    hold on 
    plot([theo_H, theo_H], [k(1), k(end)], 'k-', 'LineWidth', 2);
    set(gca, 'FontSize', tickfontsize)
    xlabel('H (km)','FontSize', labelsize)
    ylabel('Vp/Vs', 'FontSize', labelsize)
    plus_minus = char(177); 
    title(sprintf('%s: H = %0.1f %c %0.1f, Vp/Vs = %0.2f %c %0.2f ', dirlist(i), theo_H, plus_minus, sigmaH, theo_k, plus_minus, sigmaK), 'FontSize', labelsize+4);
    size_fig1 = [-1642          46        1141        1035];
    set(gcf, 'OuterPosition', size_fig1)
    fig_name_Hk = strcat('HKappa_', deblank(dirlist(i)),'.png');
%     saveas(gcf,fullfile(fig_savedir, fig_name_Hk)); 
    exportgraphics(gcf,fullfile(fig_savedir, fig_name_Hk), 'BackgroundColor', 'white', 'Resolution',600);
    [rayp_ascend, ind] = sort(rayp);
    
    %% RFs' waveform figure and moveout figure
    figure(2)
    vs = vp/theo_k; 
    rayp1 = sum(rayp)/length(rayp);
    % theoretical arrival time
    partP = sqrt(vp^(-2) - rayp1^2);
    partS = sqrt(vs^(-2) - rayp1^2);
    tPs = theo_H*(partS-partP);
    tPpPs = theo_H*(partP+partS);
    tPpSs = 2*theo_H*partS;
    for ii = 1:size(RF,2)
%         phase = 'PpPs';
%         data_moveout = h_moveout_phases(RF(:,ind(ii)), header{ind(ii)}, rayp(ind(ii)), rayp0, vp, vp/ref_k, phase);
        i_RF = RF(:,ind(ii));
%         Ps_NMO = h_moveout_phases(i_RF, header{ind(ii)}, rayp(ind(ii)), rayp0, vp, ref_k, 'Ps')';
%         PpPs_NMO = h_moveout_phases(i_RF, header{ind(ii)}, rayp(ind(ii)), rayp0, vp, ref_k, 'PpPs')';
%         PsPs_NMO = h_moveout_phases(i_RF, header{ind(ii)}, rayp(ind(ii)), rayp0, vp, ref_k, 'PsPs')';
%         NMO_RF = [i_RF(1:ind_4); Ps_NMO(ind_4+1:ind_8); i_RF(ind_8+1:ind_16); PpPs_NMO(ind_16+1:ind_20); i_RF(ind_20+1:ind_22); PsPs_NMO(ind_22+1:ind_26); i_RF(ind_26+1:end)];
%         single_wig7(time, NMO_RF, ii, color_moveout(1,:), color_moveout(2,:), 'yes', 'yes'); 
%         hold on   
        single_wig7(time, RF(:,ind(ii)), ii, color(1,:), color(2,:), 'yes', 'yes');
        hold on
    end
    plot([0 0], [0.5 ii+1.5]*amp_scale, 'r', 'LineWidth', 2)
    hold on
    plot([tPs tPs], [0.5 ii+1.5]*amp_scale, 'r', 'LineWidth', 2)
    hold on
    plot([tPpPs tPpPs], [0.5 ii+1.5]*amp_scale, 'r', 'LineWidth', 2)
    hold on
    plot([tPpSs tPpSs], [0.5 ii+1.5]*amp_scale, 'r', 'LineWidth', 2)
    hold on
    text(0.5, (ii+1.5)*amp_scale, 'P','FontSize', textsize, 'Color', 'r')
    hold on
    text(tPs+0.5, (ii+1.5)*amp_scale, 'Ps','FontSize', textsize, 'Color', 'r')
    hold on
    text(tPpPs+0.5, (ii+1.5)*amp_scale, 'PpPs','FontSize', textsize, 'Color', 'r')
    hold on
    text(tPpSs+0.5, (ii+1.5)*amp_scale, 'PsPs+PpSs','FontSize', textsize, 'Color', 'r')
    ytick = 1:2:ii;
    yticklabel = string(ytick);
    set(gca, 'YTick', ytick);
    set(gca, 'YTickLabel',yticklabel);
    set(gca, 'FontSize', tickfontsize2)
    xlabel('Time after P (s)', 'FontSize', labelsize2)
    ylabel('Trace', 'FontSize', labelsize2)
    title(sprintf('%s: T_{Ps}=%0.1f,T_{PpPs}=%0.1f,T_{PsPs}=%0.1f', char(dirlist(i)), tPs, tPpPs, tPpSs), 'FontSize', labelsize2)
    axis auto
    box on
    xlim([-2 30])
    ylim([0 ii+2])
    size_fig = [-1136         132         821         898]; 
    set(gcf, 'OuterPosition', size_fig)
    fig_name_RF_moveout = strcat('RFs_', deblank(dirlist(i)), '.png');
    exportgraphics(gcf,fullfile(fig_savedir, fig_name_RF_moveout), 'BackgroundColor', 'white', 'Resolution',600);    
    close all
end
% fclose(fid1);
% fclose(fid2);
% fclose(fid3);

