#!/usr/bin/env python3
#
'''
.. module:: event_surface_spectrum
   :synopsis: plot a spectrum of the pulse surfaces as function of event energy 
.. moduleauthor:: Cor de Vries <c.p.de.vries@sron.nl>

'''

from tesfdmtools.utils.readevents import readevents
from tesfdmtools.utils.widgets.filechooser import getfile
from tesfdmtools.utils.tesfdm_defaults import Tesfdm_Defaults

import matplotlib
if __name__ == "__main__":
   matplotlib.use('GTK3Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

import numpy

#=====================================================================
if __name__ == "__main__":

   defs=Tesfdm_Defaults()

   print("Select processed event file to obtain energy calibration")
   plist=getfile(path=defs.get_filepath('lst'),pattern='eventlist_*.lst')
   defs.set_filepath(plist)
   
   phead,pdata=readevents(plist)   # read processed events to obtain energy calibration
   
   surf=-pdata['event-surface']
   
   ic=numpy.polyfit(pdata['energy(eV)'],surf,5)   # energy calibration of surface as function of energy
   
   iax=numpy.linspace(0,pdata['energy(eV)'].max(),500) 
   intscale=numpy.polyval(ic,iax)
   
  
   f,ax=plt.subplots(1)
   
   ax.plot(pdata['energy(eV)'],surf,'b.')
   ax.plot(iax,intscale,'r-')
   ax.set_xlabel('Energy(eV)')
   ax.set_ylabel('Pulse surface')
   ax.set_title('Energy calibration')
   
   plt.show()
   plt.close()
   
   print("Select raw event file to get pulse surfaces")
   rlist=getfile(path=defs.get_filepath('lst'),pattern='raweventlist_*.lst')
   ehead,edata=readevents(rlist)
   energies=numpy.interp(-edata['pulse-surface'],intscale,iax)
   
   f,ax=plt.subplots(1)
   
   ax.hist(energies,bins=2000)
   ax.set_xlabel('(approx.) Energy(eV)')
   ax.set_ylabel('Counts')
   ax.set_title('Pulse-surface spectrum')
   
   plt.show()
   plt.close()
   
      
  
   
   
