def fitSourcePeaksInEnergy(self,srcRunPeriod=1, PMTbyPMT=False, Simulation=False, overwrite=True):
        filename = "Source_Calibration_Run_Period_%i.dat"%srcRunPeriod
        infile = open(self.runListPath+filename,'r')
        runs = []
        for line in infile:       
            #checking if peaks have already been fit
            filepath = self.srcPeakPath +"source_peaks_EvisPMTbyPMT_%i.dat"%int(line)
            if not PMTbyPMT:
                filepath = self.srcPeakPath +"source_peaks_EnergyPeak_%i.dat"%int(line)
            
            print filepath
            if not MButils.fileExistsAndNotEmpty(filepath) or overwrite:
                runs.append(int(line))

        for run in runs:
            if PMTbyPMT:
                if Simulation:
                     os.system("cd ../source_peaks; ./sim_source_peaks_EvisPMTbyPMT.exe %i"%run)
                     os.system("root -b -q '../source_peaks/plot_sim_source_peaks_Evis.C(\"%i\")'"%run)
                else:   
                    os.system("cd ../source_peaks; ./source_peaks_EvisPMTbyPMT.exe %i"%run)
                    os.system("root -b -q '../source_peaks/plot_source_peaks_Evis.C(\"%i\")'"%run)
            else:
                if Simulation:
                    os.system("cd ../source_peaks; ./sim_source_peaks_EnergyPeak.exe %i"%run)
                    #os.system("root -b -q '../source_peaks/plot_source_peaks_Energy.C(\"%i\")'"%run)
                else:
                    os.system("cd ../source_peaks; ./source_peaks_EnergyPeak.exe %i"%run)
                    os.system("root -b -q '../source_peaks/plot_source_peaks_Energy.C(\"%i\")'"%run)
            print "Ran plot_source_peaks.C on run %i"%run
    def makeSourceCalibrationFile(self,CalibrationPeriod=1):
        #This utilizes the omittedRuns and removes them from the calibration. Any time you make a change
        # to the runs which are to be omitted, you shoud rerun this!

        outputFile = "../residuals/source_runs_RunPeriod_%i.dat"%(CalibrationPeriod)
        runList = []

        with open("../run_lists/Source_Calibration_Run_Period_%i.dat"%CalibrationPeriod) as runlist:
            for run in runlist:
                if os.path.isfile(self.srcListPath+"source_list_%i.dat"%int(run)):
                    srcList = open(self.srcListPath+"source_list_%i.dat"%int(run))
                    lines = []
                    for line in srcList:
                        lines.append(line)
                    if int(lines[0])>0:
                        runList.append(int(run))

        #print runList

        outfile = open(outputFile,'w')

        for run in runList:
            src_file = self.srcPeakPath + "source_peaks_%i.dat"%run
            if MButils.fileExistsAndNotEmpty(src_file) and run not in omittedRuns:
                infile = open(src_file,'r')
                for line in infile:
                    outfile.write(line)
                infile.close()

        outfile.close()
        print "Made combined source peak file for Calibration Period %i"%CalibrationPeriod
 def calculateResiduals(self, CalibrationPeriod=1):
     filename = "../residuals/source_runs_RunPeriod_%i.dat"%CalibrationPeriod
     if MButils.fileExistsAndNotEmpty(filename):
         os.system("root -l -b -q 'MB_calc_residuals.C (%i)'"%CalibrationPeriod)
         print "Calculated residuals for Calibration Period %i"%CalibrationPeriod
     else:
         print "No peak file to calculate residuals"
         sys.exit
    def fitSourcePositions(self,srcRunPeriod=1, overwrite=False):
        filename = "Source_Calibration_Run_Period_%i.dat"%srcRunPeriod
        infile = open(self.runListPath + filename,'r')
        runs = []
        for line in infile:
        #checking if positions have already been fit
            filepath = self.srcPositionsPath + "source_positions_%i.dat"%int(line)
            print filepath
            if not MButils.fileExistsAndNotEmpty(filepath) or overwrite:
                runs.append(int(line))

        for run in runs:
            os.system("root -b -q '../source_positions/fit_source_positions.C(\"%i\")'"%run)
            print "Running fit_source_positions.C on run %i"%run
    def plotErrorEnvelope(self, calPeriodLow=2, calPeriodHigh=10, PMT=0, InEnergy=False):
        ## This runs code which calculates the mean and RMS of the global residual file
        ## from Calibration run periods CalPeriodLow to CalPeriodHigh. It prints out the mean and RMS
        ## for each source. Later this will be input into code which actually plots the error envelope.
        
        filenameEast = None
        filenameWest = None

        if calPeriodLow!=calPeriodHigh and not PMT:
            filenameEast = "../residuals/residuals_global_East_periods_%i-%i.dat"%(calPeriodLow, calPeriodHigh)
            filenameWest = "../residuals/residuals_global_West_periods_%i-%i.dat"%(calPeriodLow, calPeriodHigh)
        elif calPeriodLow==calPeriodHigh and not PMT:
            filenameEast = "../residuals/residuals_East_runPeriod_%i.dat"%calPeriodLow
            filenameWest = "../residuals/residuals_West_runPeriod_%i.dat"%calPeriodLow
        elif calPeriodLow!=calPeriodHigh and PMT:
            filenameEast = "../residuals/residuals_global_East_periods_%i-%i_PMTE%i.dat"%(calPeriodLow, calPeriodHigh, PMT)
            filenameWest = "../residuals/residuals_global_West_periods_%i-%i_PMTW%i.dat"%(calPeriodLow, calPeriodHigh, PMT)
        elif calPeriodLow==calPeriodHigh and PMT:
            filenameEast = "../residuals/residuals_East_runPeriod_%i_PMTE%i.dat"%(calPeriodLow,PMT)
            filenameWest = "../residuals/residuals_West_runPeriod_%i_PMTW%i.dat"%(calPeriodLow,PMT)
        
        if MButils.fileExistsAndNotEmpty(filenameEast) and MButils.fileExistsAndNotEmpty(filenameWest):
            print "Making Error Envelope for Run Periods %i to %i"%(calPeriodLow,calPeriodHigh)
            os.system("root -l -b -q 'MB_errorEnvelope.C (%i,%i,%i)'"%(calPeriodLow,calPeriodHigh,PMT))
    def fitSourcePeaks(self,srcRunPeriod=1, overwrite=True):
        filename = "Source_Calibration_Run_Period_%i.dat"%srcRunPeriod
        infile = open(self.runListPath+filename,'r')
        runs = []
        for line in infile:       
            #checking if peaks have already been fit
            filepath = self.srcPeakPath +"source_peaks_%i.dat"%int(line)
            print filepath
            if not MButils.fileExistsAndNotEmpty(filepath) or overwrite:
                #if int(line)>18734 and int(line)<18756: #TAKE THIS OUT AFTER DOING COMPARISON W/ BRADS ENVELOPE
                runs.append(int(line))

        for run in runs:
            os.system("cd ../source_peaks; ./source_peaks.exe %i"%run)
            os.system("root -b -q '../source_peaks/plot_source_peaks.C(\"%i\")'"%run)
            print "Ran fit_source_peaks.C on run %i"%run
    def runReverseCalibration(self, srcRunPeriod=1, sourceORxenon="source"):
        print "Running reverse calibration for %s run period %i"%(sourceORxenon,srcRunPeriod)
        filename=None
        if sourceORxenon=="source":
            filename = "Source_Calibration_Run_Period_%i.dat"%srcRunPeriod
        elif sourceORxenon=="xenon":
            filename = "Xenon_Calibration_Run_Period_%i.dat"%srcRunPeriod
        else:
            print "Not a valid source type!! Options: source or xenon"
            exit();
        infile = open(self.runListPath+filename,'r')
        runs = []
        for line in infile:      
            runs.append(int(line))

        for run in runs:
            filename = self.srcListPath+"source_list_%i.dat"%run
            if not MButils.fileExistsAndNotEmpty(filename):
                continue
            srcFile = open(filename)
            srcFileInput = []
            for line in srcFile:
                srcFileInput.append(line)
            for src in range(1,int(srcFileInput[0])+1):
                source = srcFileInput[src][0:2]
                if source=="Ce":
                    source = source+"139"
                elif source=='Sn':
                    source = source + "113"
                elif source=="Bi":
                    source = source + "207"
                elif source == "In":
                    source = source + "114"
                elif source == "Cd":
                    source = source + "109"
                elif source == "Cs":
                    source = source+"137"

                os.system("./../simulation_comparison/revCalSim.exe %i %s"%(run, source))
                #print "./../simulation_comparison/revCalSim.exe %i %s"%(run, source)

        print "Finished reverse calibration for " + sourceORxenon + "run period %i"%srcRunPeriod
#!/usr/bin/python

#Runs source peak fitting routine. Set the overwrite var to False if you
# do not want to overwrite previously fitted peaks

import os
import MButils


overwrite = True ### whether to overwrite previous source peak data files
src_peak_path = os.environ["SOURCE_PEAKS"]
runlist_path = "../run_lists/"

for p in range(1,12,1):
    filename = "Source_Calibration_Run_Period_%i.dat"%p
    infile = open(runlist_path+filename,'r')
    runs = []
    for line in infile:
        
        #checking if peaks have already been fit
        filepath = src_peak_path +"source_peaks_%i.dat"%int(line)
        print filepath
        if not MButils.fileExistsAndNotEmpty(filepath) or overwrite:
            #if int(line)>17949 and int(line)<20000: #TAKE THIS OUT AFTER DOING COMPARISON W/ BRADS ENVELOPE
                runs.append(int(line))

    for run in runs:
        #os.system("cd ../source_peaks; ./source_peaks.exe %i"%run)
        os.system("root -b -q '../source_peaks/plot_source_peaks.C(\"%i\")'"%run)
        print "Running fit_source_peaks.C on run %i"%run
src_peak_path = os.getenv("SOURCE_PEAKS")

for CalibrationPeriod in CalibrationPeriods:
    outputFile = "../residuals/source_runs_RunPeriod_%i.dat"%(CalibrationPeriod)
    runList = []

    with open("../run_lists/Source_Calibration_Run_Period_%i.dat"%CalibrationPeriod) as runlist:
        for run in runlist:
            if os.path.isfile(src_list_path+"source_list_%i.dat"%int(run)):
                srcList = open(src_list_path+"source_list_%i.dat"%int(run))
                lines = []
                for line in srcList:
                    lines.append(line)
                if int(lines[0])>0:
                    runList.append(int(run))

    print runList

    outfile = open(outputFile,'w')

    for run in runList:
        src_file = src_peak_path + "source_peaks_%i.dat"%run
        if MButils.fileExistsAndNotEmpty(src_file) and run not in omittedRuns:
            infile = open(src_file,'r')
            for line in infile:
                outfile.write(line)
            infile.close()

    outfile.close()
    
src_list_path = os.getenv("SOURCE_LIST")
src_peak_path = os.getenv("SOURCE_PEAKS")

for CalibrationPeriod in CalibrationPeriods:
    outputFile = "../residuals/source_runs_RunPeriod_%i.dat" % (CalibrationPeriod)
    runList = []

    with open("../run_lists/Source_Calibration_Run_Period_%i.dat" % CalibrationPeriod) as runlist:
        for run in runlist:
            if os.path.isfile(src_list_path + "source_list_%i.dat" % int(run)):
                srcList = open(src_list_path + "source_list_%i.dat" % int(run))
                lines = []
                for line in srcList:
                    lines.append(line)
                if int(lines[0]) > 0:
                    runList.append(int(run))

    print runList

    outfile = open(outputFile, "w")

    for run in runList:
        src_file = src_peak_path + "source_peaks_%i.dat" % run
        if MButils.fileExistsAndNotEmpty(src_file) and run not in omittedRuns:
            infile = open(src_file, "r")
            for line in infile:
                outfile.write(line)
            infile.close()

    outfile.close()