clc;clear;close all

% hdlsetuptoolpath('ToolName','Xilinx Vivado','ToolPath','D:\SoftWare\Xilinx\Vivado\2019.2\bin\vivado.bat');	
%%配置参数
fs_L = 0.75e9;    %硬件频率
fs_H = 12e9;      %以高频近似理想信号
TargetFrequency = 3e9;
G = 1;
DownSample = 2;
simulink_time = 20e-6;  %1.5*16e-6;1.5e-3
intp_mode = 3;     %0不内插，1内插2倍，2内插4倍,3内插8倍
dac_mode_sel = 0;  %选择DAC模式，0出八路，1邻近插值，2邻近插值
route_num = 5;  %线路个数
env_num = 7;    %包络个数

Ideal2Low = fs_H/(fs_L/2);
Ideal2Target = fs_H/TargetFrequency;
%% 添加路径、产生包络、配置S21参数、使用脚本计算
%%添加路径
% addpath(genpath('D:\Work\EnvData'));	
% addpath(genpath('D:\Work\EnvData\data-v2'));	
% addpath(genpath('D:\Work\TailCorr_20241008_NoGit'));	
% addpath('D:\Work\TailCorr\script_m');
cd("D:\Work\EnvData\acz");
obj1 = py.importlib.import_module('acz');
py.importlib.reload(obj1);
cd("D:\Work\TailCorr_20241008_NoGit");
obj2 = py.importlib.import_module('wave_calculation');
py.importlib.reload(obj2);
cd("D:\Work\TailCorr");    
%%产生包络
%按点数产生理想方波
% amp_rect = 1.5e4;
% %单位是ns front是到达时间，flat是持续时间，lagging是后边还有多少个0，会影响脚本的修正时间
% [front(1), flat(1), lagging(1)] = deal(50,100,7400);% 50,100,7400;100ns方波     
% [front(2), flat(2), lagging(2)] = deal(50,4000,11500);% 50,4000,11500；4us方波     
% 
% for i = 1:2
%     front_H(i) = front(i)*fs_H/1e9; flat_H(i) = flat(i)*fs_H/1e9; lagging_H(i) = lagging(i)*fs_H/1e9;
%     wave_pre{i} = amp_rect*cat(2,zeros(1,front_H(i)),ones(1,flat_H(i)),zeros(1,lagging_H(i)));%脚本的单位是点数
% end

%flattop波
A = 1.5e4;
[edge(1), length_flattop(1)] = deal(2,30);%ns，在fsn_L取1时是参数里的length
[edge(2), length_flattop(2)] = deal(4,30);
[edge(3), length_flattop(3)] = deal(4,50);
[edge(4), length_flattop(4)] = deal(4,1000);
[edge(5), length_flattop(5)] = deal(100,10000);
for i = 1:5
    [edge_H(i), length_H(i)] = deal(edge(i)*fs_H/1e9,length_flattop(i)*fs_H/1e9);
    wave_pre{i} = flattop(A, edge_H(i), length_H(i), 1);
end

%acz波
amplitude = 1.5e4;

carrierFreq = 0.000000;
carrierPhase = 0.000000;
dragAlpha = 0.000000;
thf = 0.864;
thi = 0.05;
lam2 = -0.18;
lam3 = 0.04;

length_acz(1) = 30;
length_acz(2) = 50;

for i = 1:2
    length_acz_H(i) = int32(length_acz(i)*fs_H/1e9);
    wave_pre{i+5} = real(double(py.acz.aczwave(amplitude, length_acz_H(i), carrierFreq,carrierPhase, dragAlpha,thf, thi, lam2, lam3)));
end

for i = 1:7
    wave_pre{i} = cat(2,wave_pre{i},zeros(1,floor(simulink_time*fs_H)));    %校正前的高频信号
    wave_preL{i} = wave_pre{i}(1:Ideal2Low:end);    %校正前的低频信号
end

%%S21参数
amp_real{1}= [0.025 0.015 0.0002 0.2 0 0];
amp_imag{1}= [0 0 0 0 0 0];
time_real{1} = [-1/250, -1/650, -1/1600 -1/20 0 0];
time_imag{1} = [0 0 0 0 0 0];

amp_real{2}= [0.025 0.015 0.0002 0.2 0 0];
amp_imag{2}= [0 0 0 0 0 0];
time_real{2} = [-1/250, -1/650, -1/1600 -1/20 0 0];
time_imag{2} = [0 -1/300 -1/500 0 0 0];

amp_real{3}= [0.025 0.009 0.0002 0.2 0 0];
amp_imag{3}= [0 0.012 0 0 0 0];
time_real{3} = [-1/250, -1/650, -1/1600 -1/20 0 0];
time_imag{3} = [0 -1/300 -1/500 0 0 0];

amp_real{4}= [0.025 0.015 0.0002 0.2 0 0];
amp_imag{4}= [0 0 0 0 0 0];
time_real{4} = [-1/250, -1/2000, -1/1600 -1/20 0 0];
time_imag{4} = [0 -1/15 -1/50 0 0 0];

amp_real{5}= [0.025 0.009 0.0002 0.2 0 0];
amp_imag{5}= [0 0.012 0 0 0 0];
time_real{5} = [-1/250, -1/2000, -1/1600 -1/20 0 0];
time_imag{5} = [0 -1/15 -1/50 0 0 0];

for i = 1:5
    amp_routing{i}  = amp_real{1,i} + 1j*amp_imag{1,i};
    time_routing{i} = time_real{1,i} + 1j*time_imag{1,i};
    tau{i} = -1./time_routing{i};
end

%%python脚本校正结果

convolve_bound = int8(3);
calibration_time = int32(20e3);
cal_method = int8(1);
sampling_rateL = int64(fs_L/2);
sampling_rate = int64(fs_H);

%校正后的高频信号
for m = 1:route_num
    for n = 1:env_num
        wave_cal = cell(py.wave_calculation.wave_cal(wave_pre{1,n}, amp_real{1,m}, amp_imag{1,m}, time_real{1,m}, time_imag{1,m}, convolve_bound, calibration_time, cal_method, sampling_rate));
        wave_revised{m,n} = double(wave_cal{1,1});
        wave_calL = cell(py.wave_calculation.wave_cal(wave_preL{1,n}, amp_real{1,m}, amp_imag{1,m}, time_real{1,m}, time_imag{1,m}, convolve_bound, calibration_time, cal_method, sampling_rateL));
        wave_revisedL{m,n} = double(wave_calL{1,1});        
    end
    alpha{m} = double(wave_calL{1,2});
    beta{m} =  double(wave_calL{1,3});   
end
% signalAnalyzer(wave_pre{1,1},'SampleRate',fs_H);

%校正后的低频信号

alpha_wideth=32; 
beta_width=32;
%定点化系数
for i = 1:route_num
    alphaFixRe{i} = ceil((2^(alpha_wideth-1))*real(alpha{i}));
    alphaFixIm{i} = ceil((2^(alpha_wideth-1))*imag(alpha{i}));
    betaFixRe{i}  = ceil((2^(beta_width-1))*real(beta{i}));
    betaFixIm{i}  = ceil((2^(beta_width-1))*imag(beta{i}));
end
%% 仿真
for m = 1:route_num
    for n = 1:env_num
        optnons=simset('SrcWorkspace','current');
        sim('z_dsp_FIL',[0,simulink_time]);
        sim2m = @(x)reshape(logsout.get(x).Values.Data,[],1);
        dout0{m,n} = sim2m("dout0");
        dout1{m,n} = sim2m("dout1");
        dout2{m,n} = sim2m("dout2");
        dout3{m,n} = sim2m("dout3");
    
        N = length(dout0{m,n});
        cs_wave{m,n} = zeros(4*N,1);            
        
        cs_wave{m,n}(1:4:4*N) = dout0{m,n};
        cs_wave{m,n}(2:4:4*N) = dout1{m,n};
        cs_wave{m,n}(3:4:4*N) = dout2{m,n};
        cs_wave{m,n}(4:4:4*N) = dout3{m,n};
    
        HardwareMeanIntpData{m,n} = cs_wave{m,n};%硬件校正后内插
        DownsamplingBy12GData{m,n} = wave_revised{m,n}(1:Ideal2Target:end);
        [DownsamplingBy12GDataAlign{m,n},HardwareMeanIntpDataAlign{m,n},Delay(m,n)] = ...
        alignsignals(DownsamplingBy12GData{m,n}(1:round(TargetFrequency*20e-6)),HardwareMeanIntpData{m,n}(1:round(TargetFrequency*20e-6)),"Method","xcorr");
    end
end
% signalAnalyzer(wave_revised,'SampleRate',3e9);
%% 绘图并保存
close all;

Amp = 1.5e4;
FallingEdge = [
%    150e-9,4050e-9,...%矩形波
    30e-9,30e-9,50e-9,1000e-9,10000e-9,...%flattop
    30e-9,50e-9%acz
    ];

name = [
    "第一组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后10ns",...    
    "第一组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后10ns",...
    "第一组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后10ns",...
    "第一组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后10ns",...
    "第一组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后10ns",...
    "第一组S21参数_acz_持续时间30ns_下降沿后10ns",...
    "第一组S21参数_acz_持续时间50ns_下降沿后10ns";
    "第二组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后10ns",...    
    "第二组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后10ns",...
    "第二组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后10ns",...
    "第二组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后10ns",...
    "第二组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后10ns",...
    "第二组S21参数_acz_持续时间30ns_下降沿后10ns",...
    "第二组S21参数_acz_持续时间50ns_下降沿后10ns";
    "第三组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后10ns",...    
    "第三组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后10ns",...
    "第三组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后10ns",...
    "第三组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后10ns",...
    "第三组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后10ns",...
    "第三组S21参数_acz_持续时间30ns_下降沿后10ns",...
    "第三组S21参数_acz_持续时间50ns_下降沿后10ns";
    "第四组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后10ns",...    
    "第四组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后10ns",...
    "第四组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后10ns",...
    "第四组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后10ns",...
    "第四组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后10ns",...
    "第四组S21参数_acz_持续时间30ns_下降沿后10ns",...
    "第四组S21参数_acz_持续时间50ns_下降沿后10ns";
    "第五组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后10ns",...    
    "第五组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后10ns",...
    "第五组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后10ns",...
    "第五组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后10ns",...
    "第五组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后10ns",...
    "第五组S21参数_acz_持续时间30ns_下降沿后10ns",...
    "第五组S21参数_acz_持续时间50ns_下降沿后10ns";
    "第一组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后1us",...    
    "第一组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后1us",...
    "第一组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后1us",...
    "第一组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后1us",...
    "第一组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后1us",...
    "第一组S21参数_acz_持续时间30ns_下降沿后1us",...
    "第一组S21参数_acz_持续时间50ns_下降沿后1us";
    "第二组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后1us",...    
    "第二组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后1us",...
    "第二组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后1us",...
    "第二组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后1us",...
    "第二组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后1us",...
    "第二组S21参数_acz_持续时间30ns_下降沿后1us",...
    "第二组S21参数_acz_持续时间50ns_下降沿后1us";
    "第三组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后1us",...    
    "第三组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后1us",...
    "第三组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后1us",...
    "第三组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后1us",...
    "第三组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后1us",...
    "第三组S21参数_acz_持续时间30ns_下降沿后1us",...
    "第三组S21参数_acz_持续时间50ns_下降沿后1us";
    "第四组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后1us",...    
    "第四组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后1us",...
    "第四组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后1us",...
    "第四组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后1us",...
    "第四组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后1us",...
    "第四组S21参数_acz_持续时间30ns_下降沿后1us",...
    "第四组S21参数_acz_持续时间50ns_下降沿后1us";
    "第五组S21参数_flattop_上升沿2ns_持续时间30ns_下降沿后1us",...    
    "第五组S21参数_flattop_上升沿4ns_持续时间30ns_下降沿后1us",...
    "第五组S21参数_flattop_上升沿4ns_持续时间50ns_下降沿后1us",...
    "第五组S21参数_flattop_上升沿4ns_持续时间1000ns_下降沿后1us",...
    "第五组S21参数_flattop_上升沿100ns_持续时间10000ns_下降沿后1us",...
    "第五组S21参数_acz_持续时间30ns_下降沿后1us",...
    "第五组S21参数_acz_持续时间50ns_下降沿后1us";
];

Delay_mode = mode(Delay,'all');
fileID = fopen('20241226_output.txt', 'w');
if fileID == -1
    disp('文件打开失败');
else

end

for m = 1:route_num
    for n = 1:env_num
        start_time(n) = abs(Delay_mode)/(TargetFrequency/1e9)*1e-9;%由于相位修正后会有偏移的点数，所以需要考虑上这个偏移的时间，采样率为3GHz，3个点对应1ns
        edge_Align(n) = FallingEdge(n) + start_time(n);
        tmp(n) = edge_Align(n) + 10e-9;
        a{n} = [start_time(n)-5e-9 tmp(n)];%[1/fs_H 50e-9];[50e-9 1.5e-6],[500e-9+10e-9 tmp-20e-9]
        b{n} = [tmp(n) 20e-6];
        fig1 = figure('Units','normalized','Position',[0.000390625,0.517361111111111,0.49921875,0.422916666666667]);
        diff_plot_py(TargetFrequency,HardwareMeanIntpDataAlign{m,n}', DownsamplingBy12GDataAlign{m,n}(1:floor(TargetFrequency*20e-6)),'HardwareRevised','ScriptRevised',a{n},Amp,edge_Align(n),fileID);
        title(name(m,n),Interpreter="none");
        savefig(name(m,n));
        fig2 = figure('Units','normalized','Position',[0.000390625,0.034027777777778,0.49921875,0.422916666666667]);
        diff_plot_py(TargetFrequency,HardwareMeanIntpDataAlign{m,n}', DownsamplingBy12GDataAlign{m,n}(1:floor(TargetFrequency*20e-6)),'HardwareRevised','ScriptRevised',b{n},Amp,edge_Align(n),fileID);
        title(name(m,n),Interpreter="none");
        savefig(name(m+5,n));
    end
end
fclose(fileID);
%% 可视化S21参数
t = 0:1/(1e2):10000;
for m = 1:route_num
    for n = 1:1:length(amp_routing{1,m})
        S21_time{m}(:,n) = amp_routing{1,m}(n)*exp(time_routing{1,m}(n)*t);
    end
    figure
    plot(t*1e-9,real(sum(S21_time{m},2)));
    grid on
    title("s(t)");
end

% savefig("S21参数");

% signalAnalyzer(real(sum(S21_time,2)),'SampleRate',1e11);%时间是1ns，还得加上采样率

% rmpath(genpath('D:\Work\EnvData'));
% rmpath(genpath('D:\Work\EnvData\data-v2'));
% rmpath(genpath('D:\Work\TailCorr_20241008_NoGit'));
%% 查看图像
for m = 1:35
    figure(2*m-1)
    figure(2*m)
    pause(0.2);
end
%% 读图像并查看
% cd("D:\Work\TailCorr\仿真结果\20241101_125M八倍内插至1G_第1组S21参数");
close all
for n = 1:route_num
    for m = 1:env_num
    open(strcat(name(n,m),'.fig'));
    open(strcat(name(n+5,m),'.fig'));
    pause();
    end
end
%%
close all
fid = fopen('20241226_output.txt','r');
data = textscan(fid,'Falling edge of 20ns~40ns mean :%s	 std :%s	Falling edge of 1us~1.1us mean :%s	 std :%s	The mean and std stably less than 1e-4 is :%s s');
fclose(fid);
data{1} = cellfun(@str2num,data{1});
data{2} = cellfun(@str2num,data{2});
data{3} = cellfun(@str2num,data{3});
data{4} = cellfun(@str2num,data{4});
data{5} = cellfun(@str2num,data{5});
title_name = ["下降沿后20ns~40ns误差的平均值","下降沿后20ns~40ns误差的标准差","下降沿后1us~1.1us误差的平均值","下降沿后1us~1.1us误差的标准差","加窗参数"];
err_threshold = [1e-3 1e-3 1e-4 3e-4 5e-5];
figure()
tiledlayout('flow','TileSpacing','tight')
colors = lines(route_num);

for m = 1:5
    nexttile
    hold on
    for i = 1:(route_num)
        idx = (i-1)*(length(falling20_mean)/route_num) + 1 : i*(length(falling20_mean)/route_num);
        plot(idx,abs(data{m}(idx)),'-o','Color', colors(i, :));
    end
    yline(err_threshold(m),'--r');
    title(title_name(m));
    set(gca,'YScale','log');
end

%%
figure()
semilogy(abs(falling20_mean),'-o');
