% gen Channel grid

% % written by 2020_0324

dist_t = @(x) 1/(grid_t*x)*(2*rand-1);
dist_rh = @(x) 1/(grid_rh*x)*(2*rand-1);
dist_rv = @(x) 1/(grid_rv*x)*(2*rand-1);
dis_ratio = 2;
%% gen_hr_G
kd = 2*pi; M = M_h*M_v; 
path_G = 3;
path_R = 3;
K_Factor = 13.2;

%% attention
A_ula_t = @(x) sqrt(1/Nt)*exp( (0:Nt-1)'*1j*kd*(x));
A_ula_r = @(x) sqrt(1/M)*exp( (0:M-1)'*1j*kd*(x));
A_ura_M = @(x) sqrt(1/M)* (  kron(exp(1j*kd*(0:M_h-1)'*x(1)),exp(1j*kd*(0:M_v-1)'*(x(2))) ) ) ; % UPA

% BS- IRS channel
% 
AR_G_irs = zeros(M,path_G); % IRS
AT_G_bs = zeros(Nt,path_G); % transmitter
gain_G_domi = sqrt(1/2)*(randn(1,1)+1j*randn(1,1));
gain_G_ndom = sqrt(10^(-0.1*K_Factor)/2)*(randn(path_G-1,1)+1j*randn(path_G-1,1));

gain_G_path = sqrt(Nt*M/path_G)*[gain_G_domi;gain_G_ndom]; 


AoD_G = zeros(1,path_G);
AoA_G = zeros(2,path_G);
for i = 1:path_G
%     aod = unifrnd(-pi/2,pi/2,1);
%     aoa = unifrnd(-pi/2,pi/2,2,1);
    
    aod = x_t(randperm(grid_t,1)) + dist_t(dis_ratio);
    aoa = zeros(2,1);
    t_abs = 1;
    while t_abs >= 1
        aoa(1) = x_ry(randperm(grid_rv,1)) + dist_rv(dis_ratio);
        aoa(2) = x_ry(randperm(grid_rh,1)) + dist_rh(dis_ratio);
        phi = acos(aoa(2));
        s_theta = aoa(1)/(sin(phi));
        t_abs = abs(s_theta);
    end
    
    AoD_G(i) = aod;
    AoA_G(:,i) = aoa;
    AT_G_bs(:,i) = A_ula_t(aod);
    AR_G_irs(:,i) = A_ura_M(aoa);
end
G = AR_G_irs*diag(gain_G_path)*AT_G_bs';

% IRS-User channel **********************************************
% path_R = 5;
AT_R_irs = zeros(M,path_R); % IRS
% AR_R_re = zeros(Nr,path_R); % user
gain_R_domi = sqrt(1/2)*(randn(1,1)+1j*randn(1,1));
gain_R_ndom = sqrt(10^(-0.1*K_Factor)/2)*(randn(path_R-1,1)+1j*randn(path_R-1,1));

gain_R_path = sqrt(M/path_R)*[gain_R_domi;gain_R_ndom]; 

AoA_R = zeros(2,path_R);

for i = 1:path_R
%     aod = unifrnd(-pi/2,pi/2,1);
    aoa = unifrnd(-pi/2,pi/2,2,1);
    aoa = zeros(2,1);
    t_abs = 1;
    while t_abs >= 1
        aoa(1) = x_ry(randperm(grid_rv,1)) + dist_rv(dis_ratio);
        aoa(2) = x_ry(randperm(grid_rh,1)) + dist_rh(dis_ratio);
        phi = acos(aoa(2));
        s_theta = aoa(1)/(sin(phi));
        t_abs = abs(s_theta);
    end
    AoA_R(:,i) = aoa;
    AT_R_irs(:,i) = A_ura_M(aoa);
end

hr = AT_R_irs*gain_R_path;

H_cas = diag(hr')*G;

