function [rate_trj] = rate_convex_trajectory_M_2(Q,A,Qr,P,N,K,M,sigma2,rho,H,w,eta_trj,dmin,S)
%UNTITLED11 Summary of this function goes here
%calculates the approximate rate underestimator for optimizing the
%trajectory
my_log2_for_cvx = @(x) log(x)/log(2); 

if M ==1
    for k = 1:K
        for n = 1:N
            if isnumeric(Q)
                rate_trj(k,n) = 0 ;
            else
                rate_trj(k,n) = cvx(0) ;
            end
            
            A_const = (((P(n)*rho)/(H^2 + norm(Qr(n,:)-w(k,:),2)^2)^2) * log2(exp(1))) / ...
                (((P(n)*rho)/(H^2 + norm(Qr(n,:)-w(k,:),2)^2)) + sigma2) ;
            B_const = log2( ((P(n)*rho)/(H^2 + (norm(Qr(n,:)-w(k,:),2))^2)) + sigma2) ;
            R_hat = -A_const * (sum_square(Q(n,:)-w(k,:))-(norm(Qr(n,:)-w(k,:),2))^2) + B_const ;
            rate_trj(k) = rate_trj(k) + (1/N)*A(n,k,1) *  (R_hat - my_log2_for_cvx(sigma2)) ;
        end
    end
else
    for k = 1:K
        if isnumeric(Q)
            rate_trj(k) = 0 ;
        else
            rate_trj(k) = cvx(0) ;
        end
        for n = 1:N 
            D = (((P(n,1)*rho)/(H^2 + norm(Qr(n,:,1)-w(k,:),2)^2)) + ... 
                 ((P(n,2)*rho)/(H^2 + norm(Qr(n,:,2)-w(k,:),2)^2)) + ...
                   sigma2) ;
            A_const_1 = (((P(n,1)*rho)/(H^2 + norm(Qr(n,:,1)-w(k,:),2)^2)^2) * log2(exp(1))) / D;
            A_const_2 = (((P(n,2)*rho)/(H^2 + norm(Qr(n,:,2)-w(k,:),2)^2)^2) * log2(exp(1))) / D;   
            B_const = log2(D) ; 
            
            R_hat_1 =  -A_const_1 * (pow_pos(norm(Q(n,:,1)-w(k,:)),2)-(norm(Qr(n,:,1)-w(k,:),2))^2) + B_const ;
            
            R_hat_2 =  -A_const_2 * (pow_pos(norm(Q(n,:,2)-w(k,:)),2)-(norm(Qr(n,:,2)-w(k,:),2))^2) + B_const ; 
            
            R_hat = R_hat_1 + R_hat_2;
            
            rate_trj(k) = rate_trj(k) + (1/N) * A(n,k,1) * (R_hat -my_log2_for_cvx(sigma2 + ((P(n,2)*rho)*inv_pos(H^2 + S(n,k,2)))) )  ...
                                      + (1/N) * A(n,k,2) * (R_hat -my_log2_for_cvx(sigma2 + ((P(n,1)*rho)*inv_pos(H^2 + S(n,k,1)))) ); 

%             rate_trj(k) = rate_trj(k) + (1/N) * A(n,k,1) * (R_hat -my_log2_for_cvx(sigma2 + ((P(n,2)*rho)*inv_pos(H^2 + S(n,k,2)))) )  ...
%                                       + (1/N) * A(n,k,2) * (R_hat -my_log2_for_cvx(sigma2 + ((P(n,1)*rho)*inv_pos(H^2 + S(n,k,1)))) );

%             rate_trj(k) = rate_trj(k) + (1/N) * A(n,k,1)*(R_hat-log(sigma2 *(H^2 + S(n,k,2))+ P(n,2)*rho) + rel_entr(1,H^2+S(n,k,2)) ) ... 
%                                       + (1/N) * A(n,k,2)*(R_hat-log(sigma2 *(H^2 + S(n,k,1))+ P(n,1)*rho) +rel_entr(1,H^2+S(n,k,1)) );            
%             rate_trj(k) = rate_trj(k) + (1/N) * A(n,k,1)*(R_hat-  rel_entr(1,H^2+S(n,k,2)) + log2(exp(1))*log(sigma2*H + P(n,2)*rho) ) ... 
%                                       + (1/N) * A(n,k,2)*(R_hat-  rel_entr(1,H^2+S(n,k,1)) + log2(exp(1))*log(sigma2*H + P(n,1)*rho) ); 
        
        end
    end
    
    
end


end