import numpy as np
import matplotlib.pyplot as plt

def FWHM(X,Y):
    half_max = max(Y) / 2.
    #find when function crosses line half_max (when sign of diff flips)
    #take the 'derivative' of signum(half_max - Y[])
    d = np.sign(half_max - np.array(Y[0:-1])) - np.sign(half_max - np.array(Y[1:]))
    #plot(X[0:len(d)],d) #if you are interested
    #find the left and right most indexes
    left_idx = np.where(d > 0)[0][0]
    print(X[left_idx])
    right_idx = np.where(d < 0)[-1][-1]
    print(X[right_idx])
    return X[right_idx] - X[left_idx] #return the difference (full width)

x,y = np.loadtxt('jitter_clocksync_apd.txt',skiprows=5,delimiter=',').T

plt.figure()
plt.plot(x,y)

mask = x<np.mean(x)
fwhm = FWHM(x[mask],y[mask])*1e9*1e3 #psec
stdev = fwhm/(2*np.sqrt(2*np.log(2)))
conv_stdev = stdev * np.sqrt(2)
conv_fwhm = stdev * np.sqrt(2) * (2*np.sqrt(2*np.log(2))) 
stderr = conv_stdev/np.sqrt(165*2)
print('fwhm = {:.2f} psec'.format(fwhm))
print('expected standard deviation of the offset distribution = {} psec'.format(stdev))
print('convolved stdev = {} (fwhm = {})'.format(conv_stdev,conv_fwhm))
print('stderr = {}'.format(stderr))
# plt.show()