%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% .m script of web demo 'Multiuser Capacity' 
% Written for Matlab
% 
% INSTITUTE OF TELECOMMUNICATIONS  
% University of Stuttgart 
% www.inue-uni-stuttgart.de 
% author: Wei Wang, Jintong JU   
% date: 01.05.2021 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% This example script just prints the values of the given parameters.
% Make sure that the function prototype matches the prototype defined
% in the XML config file. (Parameter names are arbitrary but should be the same
% for better readability)
function [] = demo_5_function(p,h_1,h_2,webdemo_en,filename)

% Create an invisible figure.
if (webdemo_en)
    fig = figure(2); set(fig, 'visible', 'off');
else
    fig = figure(2); set(fig, 'visible', 'on');
end

% set default Fontsize and name
set(gca, 'defaultlinelinewidth', 2);
set(gca, 'fontname','Helvetica');
set(gca, 'fontsize', 15);


p = 10.^(p/10);
N_0=1;

% NOMA
R_1_NOMA=[];
R_2_NOMA=[];
beta = 0:0.01:1;
for i=1:length(beta)
    r_1_noma=log2(1+(p*beta(i)*h_1)/(p*(1-beta(i))*h_1+N_0));
    r_2_noma=log2(1+(p*(1-beta(i))*h_2)/N_0);
    R_1_NOMA=cat(1,R_1_NOMA,r_1_noma);
    R_2_NOMA=cat(1,R_2_NOMA,r_2_noma);
end

% OMA
alpha = 0:0.001:1;
beta = 0:0.001:1;
k=1;
for n=1:length(beta)
    for m=1:length(alpha)
        r_1_OMA(k)=alpha(m)*log2(1+p*beta(n)*h_1/(alpha(m)*N_0));
        r_2_OMA(k)=(1-alpha(m))*log2(1+p*(1-beta(n))*h_2/((1-alpha(m))*N_0));
        k=k+1;
    end
end
r_1_OMA=roundn(r_1_OMA,-2);
k=1;
for r1 = rmmissing(unique(r_1_OMA))
    r2(k)=max(r_2_OMA(r_1_OMA==r1));
    k=k+1;
end
r1=rmmissing(unique(r_1_OMA));
% Prepare plot
xlabel('R_1 in bits/s/Hz');
ylabel('R_2 in bits/s/Hz');
grid on;
box on;
hold on;
% Plot into the figure
h1 = plot(R_1_NOMA,R_2_NOMA,'color','k','DisplayName','NOMA');
h2 = plot(r1,r2,'color','r','linestyle','--','DisplayName','OMA');
legend;

if (webdemo_en)
    print(filename, "-dpng", '-r83');% generate the picture results
end

end