clear all;
clc

q=1.6e-19;
T=300;
kb=1.38e-23;
e0 = 8.85e-12;
eSi = 11.7*e0;

FF = 0.8;
Apd = (1.5e-6)^2*FF;
xdep = 2e-6;
Cg = 0.2e-15;
Cdep = Apd*eSi/xdep;
VDD = 6;
Qmax = (Cg+Cdep)*VDD;
tint = 10e-3;
iph = logspace(-17,-11,10000);
id = 0.2e-15;

for i = 1:length(iph)
    if (iph(i)+id)*tint>Qmax
        iph(i) = NaN;
    end
end

% shot noise photon
S_shotph = q*iph*tint;
e_shotph = sqrt(S_shotph)/q;

% shot noise dark
S_shotd = q*id*tint;
e_shotd = sqrt(S_shotd)/q*ones(1,length(e_shotph));

% kTC noise
S_kTC = kb*T*(Cg+Cdep);
e_kTC = sqrt(S_kTC)/q*ones(1,length(e_shotph));

% DSNU
DSNUperc = 5;
S_DSNU = (id*tint*DSNUperc/100).^2;
e_DSNU = sqrt(S_DSNU)/q*ones(1,length(e_shotph));

% PRNU
PRNUperc = 1.5;
S_PRNU = (iph*tint*PRNUperc/100).^2;
e_PRNU = sqrt(S_PRNU)/q;

% total noise
sigma = sqrt(S_shotph + S_shotd + S_kTC + S_DSNU + S_PRNU);
e = sigma/q;

figure(13);
ax=axes;
ax.XScale='log';
ax.YScale='log';
ax.FontSize = 24;
hold all; grid on; box on;
plot(iph*tint/q, e_shotd, '-.', 'LineWidth', 2);
plot(iph*tint/q, e_shotph, '-.', 'LineWidth', 2);
plot(iph*tint/q, e_kTC, '-.', 'LineWidth', 2);
plot(iph*tint/q, e_DSNU, '-.', 'LineWidth', 2);
plot(iph*tint/q, e_PRNU, '-.', 'LineWidth', 2);
plot(iph*tint/q, e, 'LineWidth', 6);
legend('dark shot noise', 'photon shot noise', 'kTC noise', 'DSNU noise', 'PRNU noise', 'overall noise', 'Location','NorthWest');
xlabel('Signal [electrons]');
ylabel('Noise [electrons_r_m_s] ');

% DR calculation
diff = abs(iph*tint/q-e);
index = find(diff==min(diff));
min_signal = iph(index);
max_signal = max(max(iph),Qmax/tint);
DR = 20*log10(max_signal/min_signal)
