"""
evaluate the offset for the various gains
"""

from struct import*
import ctypes
import array
import numpy as np
import matplotlib.pyplot as plt
import time
from scipy import stats

ADC = np.load("tmp.npy")
V = np.linspace(0,990,1000)
slope = np.zeros(7)

for g in range(1,8):
    k=0
    while ADC[g-1,k]<10:
        k+=1
    start = k
    while (k<1000 and ADC[g-1,k]<4000):
        k+=1
    stop = k
    slope[g-1], intercept,t_value,p_value,std_err = stats.linregress(V[start:stop],ADC[g-1,start:stop])
    plt.plot(V[start:stop],ADC[g-1,start:stop])
    plt.plot(V,slope[g-1]*V+intercept,':',color='black')
    print(slope[g-1])
    print(intercept)
    
plt.ylim(-10,4100)
plt.xlim(-1,810)
plt.xlabel("Voffset")
plt.ylabel("ADC")
plt.title("Gain from 2 to 128")
plt.grid()
plt.show()

G = [1.63/0.62,3.044/1.63,4.66/3.044,6.15/4.66,7.24/6.15,7.926/7.24]
Gth = [3,7.0/3,15.0/7,31.0/15,63/31,127/63]
B=slope

for g in range(2,8):
    G[g-2] = slope[g-1]/slope[g-2]

for g in range(1,8):
    B[g-1]=slope[g-1]/(2**g-1)

plt.plot(G)
plt.plot(Gth)
plt.show()

plt.plot(B)
plt.xlabel("Gain G from 2 to 128")
plt.ylabel("B")
#plt.title("Gain from 2 to 128")
plt.grid()

plt.show()