import numpy as np
import matplotlib.pyplot as plt

from scipy import constants as const
from scipy import signal as sig

I0 = 1e-3 # average sum photocurrent
Ix = 0.1e-3 # average X photocurrent
T = 32 # measurement time
dt = 1/2**19 # sampling time
fs = 1/dt
t = np.arange(0, T, dt)
N = int(T/dt)
print('Measurement time: {} s'.format(T))
print('Sampling rate: {} Hz'.format(fs))
fclk = 10013.42131 # Hz
clk = np.ceil(np.sin(2*np.pi*fclk*t)) # clock signal, 0 or 1
I = np.random.normal(Ix, np.sqrt(2*const.e*I0*fs/2), size=N) # non-modulated (steady) photocurrent, with shot noise added
Imod = I*clk # modulated photocurrent
Ihp = Imod-np.mean(Imod) # high-passed modulated photocurrent
Idemod = Ihp*2*(clk-0.5)
#plt.plot(t[:1000], I[:1000], t[:1000], Imod[:1000], t[:1000], Ihp[:1000], t[:1000], Idemod[:1000])
fxx, Pxx = sig.welch(I, fs=1/dt, nperseg=2**19, window='flattop')
fxx, Pxx_demod = sig.welch(Idemod, fs=1/dt, nperseg=2**19, window='flattop')
fxx, Pxx_mod = sig.welch(Imod, fs=1/dt, nperseg=2**19, window='flattop')

def current_plot(ax):
    ax.loglog(
        fxx,
        np.sqrt(Pxx),
        label='No modulation',
    )
    ax.loglog(fxx, np.sqrt(Pxx_mod), label='Modulation')
    ax.loglog(fxx, np.sqrt(Pxx_demod), label='Demodulated')
    ax.loglog(
        fxx,
        np.ones_like(fxx) * np.sqrt(2 * const.e * I0),
        ls=(0, (6, 2,)),
        color='xkcd:gray',
        label='Shot noise [{:g} mA]'.format(I0*1e3),
    )
    ax.set_xlabel('Frequency [Hz]')
    ax.set_ylabel('Current noise [A/Hz$^{1/2}$]')
    ax.legend(loc='upper left')

fig_a, ax_a = plt.subplots()
current_plot(ax_a)
ax_a.set_xlim([1, fs/2])
fig_b, ax_b = plt.subplots()
current_plot(ax_b)
ax_b.set_xscale('linear')
ax_b.set_xlim([9600, 10400])
fig_a.tight_layout()
fig_b.tight_layout()
fig_a.savefig('current_noise_all.pdf')
fig_b.savefig('current_noise_zoom.pdf')
