execfile('/afs/slac/u/ki/lances/python/python_HxRG/HxRG_Setup.py')
from ForwardBias_Extract_Database import *
from FitDecay import *
execfile('/afs/slac/u/ki/lances/python/ThesisPlotSettings.py')
PlotDir='/nfs/slac/g/ki/ki04/lances/LSST/KPNO/Latex/Thesis/ForwardAndChangeBias/Figures/'
##############This has an abnormal behavior for some reason
T_o     = 0.0
T_f     = 1400.0
TvFlag  = 1
SaveImg = 1
AttFit  = 2
Gain    = 5.4

##Arrays for Averages
Tau1s = []
Tau2s = []
N1s   = []
N2s   = []

QueryStr='WHERE SEQUENCE = 1'
FileNums, ReadNums, Times, RawADUs, RawSlopes, BiasADUs, RawADU_RPs, RawSlope_RPs, BiasADU_RPs \
  = ForwardBias_Extract_Database('H1RG-018','LEACH',33,0,1,QueryStr=QueryStr)
RawSlope_RPs = Gain*RawSlope_RPs
mplot.figure(0)
mplot.clf()
mplot.plot(Times, RawSlope_RPs,'ro', label=r'\textbf{10 Resets, 40 Reads}')
mplot.plot(Times, RawSlopes,'bo', label=r'\textbf{10 Resets, 40 Reads}')
GoodTimes = (where((Times < T_f) & (ReadNums > 3)))[0]
if AttFit == 0:
  N1, Tau1, Off = FitDecay(Times[GoodTimes], RawSlope_RPs[GoodTimes], TvFlag=TvFlag, AttFit=AttFit)
else:
  N1, Tau1, N2, Tau2, Off = FitDecay(Times[GoodTimes], RawSlope_RPs[GoodTimes], TvFlag=TvFlag, AttFit=AttFit)
Tau1s.append(Tau1); Tau2s.append(Tau2); N1s.append(N1); N2s.append(N2)

##Print the means
FirstTau = 1
LastTau  = 5
Tau1Mean = mean(Tau1s[FirstTau:LastTau])
Tau2Mean = mean(Tau2s[FirstTau:LastTau])
N1Mean   = mean(N1s[FirstTau:LastTau])
N2Mean   = mean(N2s[FirstTau:LastTau])
print 'Mean Tau1: ' + str(Tau1Mean)
print 'Mean Tau2: ' + str(Tau2Mean)
print 'Mean N1:   ' + str(N1Mean)
print 'Mean N2:   ' + str(N2Mean)

##NOW PLOT THE FIT
N1   = 244.
N2   = 121.00
Tau1 = 13.13
Tau2 = 91.1
Off  = 11.5
mplot.figure(0)
mplot.plot(Times1, N1*exp(-Times1/Tau1)+N2*exp(-Times1/Tau2)+Off, 'k-', linewidth=3, label=r'\textbf{Fit}')
mplot.xlim(100,400)
mplot.ylim(0,Gain*10)
mplot.xlabel(r'\textbf{Time (s)}')
mplot.ylabel(r'\textbf{Dark Current \ (e$^{-}$/sec/pix)}')
if SaveImg==1:
  mplot.savefig(PlotDir+'FowardBiasExperiment_LongTimeScale_08Jun28.png')
  mplot.savefig(PlotDir+'FowardBiasExperiment_LongTimeScale_08Jun28.eps')

mplot.xlim(0,100)
mplot.ylim(0,Gain*80)
mplot.legend(numpoints=1)
if SaveImg==1:
  mplot.savefig(PlotDir+'FowardBiasExperiment_ShortTimeScale_08Jun28.png')
  mplot.savefig(PlotDir+'FowardBiasExperiment_ShortTimeScale_08Jun28.eps')


