##PURPOSE:
## To plot the linearity of H2RG_001 with and without reference pixel corrections.
##
from Return_Linearity import *
execfile('/afs/slac/u/ki/lances/python/python_HxRG/HxRG_Setup.py')
execfile('/afs/slac/u/ki/lances/python/SPIEPlotSettings.py')
PlotDir = '/nfs/slac/g/ki/ki04/lances/LSST/KPNO/Latex/Thesis/Linearity/Figures/'

FitsFileName  = '/nfs/slac/g/ki/ki04/lances/H2RG-32-147/LEACH/Test_Images/H2RG_Test_Ifilter_5usec_pixel_Shift_1.fits'
FitsFileName  = '/nfs/slac/g/ki/ki04/lances/H2RG-32-147/LEACH/Test_Images/H2RG_Test_Ifilter_Increased_Vpullup_0.fits'
#FitsFileName  = '/nfs/slac/g/ki/ki04/lances/H2RG-32-147/LEACH/Test_Images/H2RG_Test_Ifilter_Increased_Vpullup_1.fits'
SlopeFileName = '/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/Reduced/07Dec13/Flat/Flat_G_H2RG_SIPIN_15_Reads_Dec13_2007_21_35_50_G_Slope.fits' 

YStart=1200 
YStop=1600 
XStart=100 
XStop=500 
TvFlag=0 
Mode=2 
UseRef=1 
CFac  = 1.10
CGain = 4.00
MedADU_RP, DeltasMed_RP, DeltasMean_RP, DeltasCumMed_RP, DeltasCumMean_RP = \
  ReturnLinearity(FitsFileName, SlopeFileName, YStart=YStart, YStop=YStop, XStart=XStart, \
                  XStop=XStop, Mode=Mode, UseRef=UseRef, CFac=CFac)

UseRef=0
MedADU_NRP, DeltasMed_NRP, DeltasMean_NRP, DeltasCumMed_NRP, DeltasCumMean_NRP = \
  ReturnLinearity(FitsFileName, SlopeFileName, YStart=YStart, YStop=YStop, XStart=XStart, \
                  XStop=XStop, Mode=Mode, UseRef=UseRef, CFac=CFac)

mplot.figure(0)
mplot.clf()
mplot.plot(CGain*MedADU_NRP[0:-1], DeltasCumMed_NRP/(DeltasCumMed_NRP[0]), 'r', \
           label=r'\textbf{No Reference Pixels Applied}')
mplot.plot(CGain*MedADU_RP[0:-1],  DeltasCumMed_RP/(DeltasCumMed_RP[0:3].mean()), 'b',\
           label=r'\textbf{Reference Pixels Applied}')
mplot.legend(loc=3)
mplot.plot(CGain*MedADU_RP[0:-1],  DeltasCumMed_RP/(DeltasCumMed_RP[0:3].mean()), 'bo')
mplot.plot(CGain*MedADU_NRP[0:-1], DeltasCumMed_NRP/(DeltasCumMed_NRP[0]), 'ro')
ylim(.8,1.1)
mplot.xlabel(r'\textbf{Mean Signal ($e^{-}$ in well)}')
mplot.ylabel(r'\textbf{Fractional Countrate}')

mplot.figtext(.185,.340,(r'\textbf{Region: [' +
                        str(int(XStart)) + ':' + str(int(XStop)) + ',' +
                        str(int(YStart)) + ':' + str(int(YStop)) + ']}'),size=13, \
              backgroundcolor='w')
mplot.figtext(.185,.300,r'\textbf{Detector   : H2RG-32-147}' , color='k', size=13, \
              backgroundcolor='w')
mplot.figtext(.185,.260,r'\textbf{Electronics: LEACH}'       , color='k', size=13,  \
              backgroundcolor='w')

mplot.savefig(PlotDir+'LinearityOf_H2RG_32_147_FromFlat.png')
mplot.savefig(PlotDir+'LinearityOf_H2RG_32_147_FromFlat.eps')
