def arbitraryPlotter2D(anaType, listDataPtTuples, rootFileName, treeName, branchName, vfat, ROBstr=True, ztrim=4, skipBad=False): """ Provides a list of tuples for 2D data where each element is of the ``(x,y,z)`` form: ``(indepVarVal, vfatCHOrROBstr, depVarVal)`` Args: anaType (string): type of analysis to perform, helps build the file path to the input file(s), from the keys of :any:`utils.anaInfo.ana_config` listDataPtTuples: list of tuples where each element is of the form: ``(cName, scandate, indepVar)``, note ``indepVar`` is expected to be numeric rootFileName (string): name of the ``TFile`` that will be found in the data path corresponding to ``anaType`` treeName (string): name of the ``TTree`` inside ``rootFileName`` branchName (string): name of a branch inside ``treeName`` that the dependent variable will be extracted from vfat (int): vfat number that plots should be made for skipBad (bool): if a file fails to open or the ``TTree`` cannot be found, the input is skipped and the processing continues rather than exiting """ from gempython.gemplotting.utils.anautilities import filePathExists, getDirByAnaType import numpy as np import os import root_numpy as rp # Make branches to load listNames = ["vfatN"] strChanName = "" #Name of channel TBranch, either 'ROBstr' or 'vfatCH' if ROBstr: listNames.append("ROBstr") strChanName = "ROBstr" else: listNames.append("vfatCH") strChanName = "vfatCH" listNames.append(branchName) # Load data listData = [] for dataPt in listDataPtTuples: # Get human readable info cName = dataPt[0] scandate = dataPt[1] indepVarVal = dataPt[2] # Setup Paths dirPath = getDirByAnaType(anaType.strip("Ana"), cName, ztrim) if not filePathExists(dirPath, scandate): print('Filepath {0}/{1} does not exist!'.format(dirPath, scandate)) if skipBad: print('Skipping') continue else: print('Please cross-check, exiting!') exit(os.EX_DATAERR) pass filename = "{0}/{1}/{2}".format(dirPath, scandate, rootFileName) # Get TTree try: dataFile = r.TFile(filename, "READ") dataTree = dataFile.Get(treeName) knownBranches = dataTree.GetListOfBranches() except AttributeError as e: print('{0} may not exist in {1}'.format(treeName, filename)) print(e) if skipBad: print('Skipping') continue else: print('Please cross-check, exiting!') exit(os.EX_DATAERR) pass pass # Check to make sure listNames are present in dataTree for testBranch in listNames: if testBranch not in knownBranches: print("Branch {0} not in TTree {1} of file {2}".format( branchName, treeName, filename)) print("Existing Branches are:") for realBranch in knownBranches: print(realBranch) print("Please try again using one of the existing branches") exit(os.EX_DATAERR) # Get dependent variable value - VFAT Level arrayVFATData = rp.tree2array(dataTree, listNames) dataThisVFAT = arrayVFATData[arrayVFATData['vfatN'] == vfat] #VFAT Level # Close the TFile dataFile.Close() # Get the data for each strip and store it as a tuple in the list to be returned for chan in range(0, 128): dataThisChan = dataThisVFAT[dataThisVFAT[strChanName] == chan] #Channel Level depVarVal = np.asscalar(np.mean(dataThisChan[branchName])) listData.append((indepVarVal, chan, depVarVal)) pass # Return Data return listData
linkByChamber = dict( (value, key) for key, value in chamber_config.iteritems()) ## Only in python 2.7 and up # linkByChamber = { value:key for key,value in chamber_config.iteritems() } # Make and launch a job for each file import time for idx, chamberAndScanDatePair in enumerate(listChamberAndScanDate): # Setup the path dirPath = getDirByAnaType(options.anaType, chamberAndScanDatePair[0], options.ztrim) dirPath = "%s/%s" % (dirPath, chamberAndScanDatePair[1]) # Check if file exists, if it does not write to output as commented line but skip to next input if not filePathExists(dirPath, tree_names[options.anaType][0]): outputScanDatesFile.write( '#%s\t%s\n' % (chamberAndScanDatePair[0], chamberAndScanDatePair[1])) continue outputScanDatesFile.write( '%s\t%s\n' % (chamberAndScanDatePair[0], chamberAndScanDatePair[1])) # Input file jobInputFile = "%s/%s" % (dirPath, tree_names[options.anaType][0]) # stdout jobStdOut = "%s/stdout" % dirPath runCommand(["mkdir", "-p", jobStdOut]) if len(os.listdir(jobStdOut)) > 0:
def compareSBitThreshResults(args): # Suppress all pop-ups from ROOT import ROOT as r r.gROOT.SetBatch(True) # Check Paths import os, sys from gempython.utils.wrappers import envCheck envCheck('DATA_PATH') envCheck('ELOG_PATH') elogPath = os.getenv('ELOG_PATH') # Get info from input file from gempython.gemplotting.utils.anautilities import getCyclicColor, getDirByAnaType, filePathExists, getSummaryCanvas, parseArmDacCalFile, parseListOfScanDatesFile parsedTuple = parseListOfScanDatesFile(args.filename, alphaLabels=args.alphaLabels) listChamberAndScanDate = parsedTuple[0] chamberName = listChamberAndScanDate[0][0] thrDacName = parsedTuple[1] gemType = "ge11" from gempython.tools.hw_constants import vfatsPerGemVariant # Parse calibration file if present arrayCalInfo = None if args.calFileARM is not None: arrayCalInfo = parseArmDacCalFile( args.calFileARM, gemType=gemType) # arrayCalInfo[i][vfatN] for coef of x^(4-i) legPlot = r.TLegend(0.5, 0.5, 0.9, 0.9) from gempython.utils.nesteddict import nesteddict as ndict dict_Histos = ndict() dict_Graphs = ndict() dict_MultiGraphs = {} for idx, infoTuple in enumerate(listChamberAndScanDate): # Setup the path dirPath = getDirByAnaType("sbitRateor", infoTuple[0]) if not filePathExists(dirPath, infoTuple[1]): print('Filepath {:s}/{:s} does not exist!'.format( dirPath, infoTuple[1])) print('Please cross-check, exiting!') sys.exit(os.EX_NOINPUT) filename = "{:s}/{:s}/SBitRatePlots.root".format(dirPath, infoTuple[1]) # Load the file r.TH1.AddDirectory(False) scanFile = r.TFile(filename, "READ") if scanFile.IsZombie(): print("{0} is a zombie!!!".format(filename)) print( "Please double check your input list of scandates: {0}".format( args.filename)) print("And then call this script again") raise IOError ################### # Get individual distributions ################### for vfat in range(vfatsPerGemVariant[gemType]): dict_Histos[infoTuple[2]][vfat] = scanFile.Get( "VFAT{0}/THR_ARM_DAC/g1D_rate_vs_THR-ARM-DAC_vfat{0}".format( vfat)) dict_Graphs[infoTuple[2]][vfat] = r.TGraph( dict_Histos[infoTuple[2]][vfat]) # Do we convert x-axis to charge units? if arrayCalInfo is not None: for pt in range(dict_Graphs[infoTuple[2]][vfat].GetN()): valX = r.Double() valY = r.Double() dict_Graphs[infoTuple[2]][vfat].GetPoint(pt, valX, valY) valX_Q = 0 for coef in range(0, 5): valX_Q += arrayCalInfo[coef][vfat] * pow( valX, 4 - coef) dict_Graphs[infoTuple[2]][vfat].SetPoint(pt, valX_Q, valY) pass pass # Make the TMultiGraph Objects suffix = "VFAT{0}".format(vfat) if idx == 0: dict_MultiGraphs[vfat] = r.TMultiGraph( "mGraph_RateVsThrDac_vfat{0}".format(suffix), suffix) # Set Style of TGraph dict_Graphs[infoTuple[2]][vfat].SetLineColor(getCyclicColor(idx)) dict_Graphs[infoTuple[2]][vfat].SetMarkerColor(getCyclicColor(idx)) dict_Graphs[infoTuple[2]][vfat].SetMarkerStyle(20 + idx) dict_Graphs[infoTuple[2]][vfat].SetMarkerSize(0.8) # Add to the MultiGraph dict_MultiGraphs[vfat].Add(dict_Graphs[infoTuple[2]][vfat]) ################### # Make an entry in the TLegend ################### if vfat == 0: legPlot.AddEntry(dict_Graphs[infoTuple[2]][vfat], "{0} = {1}".format(thrDacName, infoTuple[2]), "LPE") pass pass ################### # Make output ROOT file ################### outFileName = "{0}/compSbitThresh_{1}.root".format(elogPath, chamberName) outFile = r.TFile(outFileName, "RECREATE") # Plot Containers dict_canv = {} ################### # Now Make plots ################### for vfat in range(vfatsPerGemVariant[gemType]): # Make Output Canvas dict_canv[vfat] = r.TCanvas("canvSBitRate_VFAT{0}".format(vfat), "SBIT Rate by THR DAC", 700, 700) dict_canv[vfat].cd() dict_canv[vfat].cd().SetLogy() dict_MultiGraphs[vfat].Draw("APE1") dict_MultiGraphs[vfat].GetYaxis().SetTitle("Rate #left(Hz#right)") dict_MultiGraphs[vfat].GetYaxis().SetRangeUser(1e-1, 5e8) # max is 40 MHz if arrayCalInfo is not None: dict_MultiGraphs[vfat].GetXaxis().SetTitle( "Threshold #left(fC#right)") dict_MultiGraphs[vfat].GetXaxis().SetRangeUser(0, 20) else: dict_MultiGraphs[vfat].GetXaxis().SetTitle( "CFG_THR_ARM_DAC #left(DAC#right)") dict_MultiGraphs[vfat].GetXaxis().SetRangeUser(0, 125) pass dict_MultiGraphs[vfat].Draw("APE1") # Draw Legend? if not args.noLeg: legPlot.Draw("same") pass # Make output image? if args.savePlots: dict_canv[vfat].SaveAs("{0}/{1}.png".format( elogPath, dict_canv[vfat].GetName())) pass # Store Output thisDirectory = outFile.mkdir("VFAT{0}".format(vfat)) thisDirectory.cd() dict_MultiGraphs[vfat].Write() dict_canv[vfat].Write() pass # Make summary canvases, always save these canvSBitRate_Summary = getSummaryCanvas( dict_MultiGraphs.values()[0:vfatsPerGemVariant[gemType]], name="canvSBitRate_Summary", drawOpt="APE1", gemType=gemType) for vfatCanv in range(1, vfatsPerGemVariant[gemType] + 1): canvSBitRate_Summary.cd(vfatCanv).SetLogy() # Draw Legend? if not args.noLeg: canvSBitRate_Summary.cd(1) legPlot.Draw("same") pass # Save summary canvases (always) print("\nSaving Summary TCanvas Objects") canvSBitRate_Summary.SaveAs("{0}/{1}.png".format( elogPath, canvSBitRate_Summary.GetName())) # Close output files outFile.Close() print("You can find all ROOT objects in:") print("\n\t{0}/compSbitThresh_{1}.root\n".format(elogPath, chamberName)) print("You can find all plots in:") print("\n\t{0}\n".format(elogPath)) print("Done") return
def arbitraryPlotter(anaType, listDataPtTuples, rootFileName, treeName, branchName, vfat, vfatCH=None, strip=None, ztrim=4, skipBad=False): """ Provides a list of tuples for 1D data where each element is of the form: ``(indepVarVal, depVarVal, depVarValErr)`` Args: anaType (string): type of analysis to perform, helps build the file path to the input file(s), from the keys of :any:`utils.anaInfo.ana_config` listDataPtTuples: list of tuples where each element is of the form ``(cName, scandate, indepVar)``, note ``indepVar`` is expected to be numeric rootFileName (string): name of the ``TFile`` that will be found in the data path corresponding to ``anaType`` treeName (string): name of the ``TTree`` inside ``rootFileName`` branchName (string): name of a branch inside ``treeName`` that the dependent variable will be extracted from vfat (int): vfat number that plots should be made for vfatCH (int): channel of the vfat that should be used, if ``None`` an average is performed w/stdev for error bar, mutually exclusive w/ ``strip`` strip (int): strip of the detector that should be used, if ``None`` an average is performed w/stdev for error bar, mutually exclusive w/ ``vfatCH`` skipBad (bool): if a file fails to open or the ``TTree`` cannot be found, the input is skipped and the processing continues rather than exiting """ from gempython.gemplotting.utils.anautilities import filePathExists, getDirByAnaType import numpy as np import os import root_numpy as rp # Make branches to load listNames = ["vfatN"] if vfatCH is not None and strip is None: listNames.append("vfatCH") elif strip is not None and vfatCH is None: listNames.append("ROBstr") listNames.append(branchName) # Load data listData = [] for dataPt in listDataPtTuples: # Get human readable info cName = dataPt[0] scandate = dataPt[1] indepVarVal = dataPt[2] # Setup Paths dirPath = getDirByAnaType(anaType.strip("Ana"), cName, ztrim) if not filePathExists(dirPath, scandate): print('Filepath {0}/{1} does not exist!'.format(dirPath, scandate)) if skipBad: print('Skipping') continue else: print('Please cross-check, exiting!') exit(os.EX_DATAERR) pass filename = "{0}/{1}/{2}".format(dirPath, scandate, rootFileName) # Get TTree try: dataFile = r.TFile(filename, "READ") dataTree = dataFile.Get(treeName) knownBranches = dataTree.GetListOfBranches() except AttributeError as e: print('{0} may not exist in {1}'.format(treeName, filename)) print(e) if skipBad: print('Skipping') continue else: print('Please cross-check, exiting!') exit(os.EX_DATAERR) pass pass # Check to make sure listNames are present in dataTree for testBranch in listNames: if testBranch not in knownBranches: print("Branch {0} not in TTree {1} of file {2}".format( branchName, treeName, filename)) print("Existing Branches are:") for realBranch in knownBranches: print(realBranch) print("Please try again using one of the existing branches") exit(os.EX_DATAERR) # Get dependent variable value arrayVFATData = rp.tree2array(dataTree, listNames) dataThisVFAT = arrayVFATData[arrayVFATData['vfatN'] == vfat] #VFAT Level # Close the TFile dataFile.Close() if vfatCH is not None and strip is None: dataThisVFAT = dataThisVFAT[dataThisVFAT['vfatCH'] == vfatCH] #VFAT Channel Level elif strip is not None and vfatCH is None: dataThisVFAT = dataThisVFAT[dataThisVFAT['ROBstr'] == strip] #Readout Board Strip Level depVarVal = np.asscalar( np.mean(dataThisVFAT[branchName]) ) #If a vfatCH/ROBstr obs & chan/strip not give will be avg over all, else a number depVarValErr = np.asscalar( np.std(dataThisVFAT[branchName]) ) #If a vfatCH/ROBstr obs & chan/strip not given will be stdev over all, or zero #Record this dataPt listData.append((indepVarVal, depVarVal, depVarValErr)) # Return Data return listData
def getPlotFromTree(filename, treeName, expression, selection=""): """ Returns the type of TObject returned by TTree::Draw(expression, selection, drawOpt) filename - string, physical filename of the input TFile treeName - string, name of the TTree found in filename See https://root.cern.ch/doc/master/classTTree.html#a73450649dc6e54b5b94516c468523e45 for TTree::Draw() documentation expression - string, the "varexp" argument passed to TTree::Draw() selection - string, the "selection" argument passed to TTree::Draw() """ from gempython.gemplotting.utils.anautilities import filePathExists, getStringNoSpecials, getDirByAnaType import os import ROOT as r # Check input file if not filePathExists(filename): print 'getPlotFromTree() - Filepath %s does not exist!' % (filename) print 'getPlotFromTree() - Please cross-check, exiting!' exit(os.EX_DATAERR) # Get TTree try: dataFile = r.TFile(filename, "READ") dataTree = dataFile.Get(treeName) knownBranches = dataTree.GetListOfBranches() except Exception as e: print 'getPlotFromTree() - %s may not exist in %s, please cross check' % ( treeName, filename) print e #exit(os.EX_NOTFOUND) #Weird, not found but described in: https://docs.python.org/2/library/os.html#process-management exit(os.EX_DATAERR) pass # Make the name for the plot listParsedExpress = expression.split(":") if len(listParsedExpress) > 2: print( "getPlotFromTree() - Sorry right now I cannot handle N_Dimensions > 2" ) print("\tYou'll need to make your plot by hand") print("\tExiting") exit(os.EX_USAGE) dictPrefix = {1: "h", 2: "g", 3: "poly3D"} strPlotName = dictPrefix[len(listParsedExpress)] for idx in range(len(listParsedExpress) - 1, -1, -1): strPlotName = "%s_%s" % (strPlotName, getStringNoSpecials(listParsedExpress[idx])) if idx > 0: strPlotName = "%s_vs" % (strPlotName) # Draw the PLot try: dataTree.Draw(expression, selection) except Exception as e: print( "getPlotFromTree() - An Exception has occurred, TTree::Draw() was not successful" ) print("\texpression = %s" % expression) print("\tselection = %s" % selection) print("\tdrawOpt = %s" % drawOpt) print("") print("\tMaybe you mispelled the TBranch names?") print("\tExisting Branches are:") for realBranch in knownBranches: print("\t", realBranch) print("") print("getPlotFromTree() - Please cross check and try again") print("") print(e) #exit(os.EX_NOTFOUND) #Weird, not found but described in: https://docs.python.org/2/library/os.html#process-management exit(os.EX_DATAERR) # Get the plot and return it to the user if len(listParsedExpress) == 1: #thisPlot = r.gPad.GetPrimitive("htemp").Clone(strPlotName) #For some reason if trying this I get a null pointer later :-/ thisPlot = r.TGraph(r.gPad.GetPrimitive("htemp")) thisPlot.SetName(strPlotName.replace('h_', 'g_')) return thisPlot elif len(listParsedExpress) == 2: thisPlot = r.gPad.GetPrimitive("Graph").Clone(strPlotName) return thisPlot
strRootName = "%s_%s" % (strRootName, getStringNoSpecials(listParsedExpress[idx])) if idx > 0: strRootName = "%s_vs" % (strRootName) strRootName = elogPath + "/gemTreeDrawWrapper%s.root" % (strRootName) r.gROOT.SetBatch(True) outF = r.TFile(strRootName, options.rootOpt) # Loop Over inputs listPlots = [] for chamberAndScanDatePair in listChamberAndScanDate: # Setup the path dirPath = getDirByAnaType(options.anaType.strip("Ana"), chamberAndScanDatePair[0], options.ztrim) if not filePathExists(dirPath, chamberAndScanDatePair[1]): print 'Filepath %s/%s does not exist!' % (dirPath, scandate) print 'Please cross-check, exiting!' outF.Close() exit(os.EX_DATAERR) filename = "%s/%s/%s" % (dirPath, chamberAndScanDatePair[1], tree_names[options.anaType][0]) treeName = tree_names[options.anaType][1] # Get the Plot and Reset it's Name thisPlot = getPlotFromTree(filename, treeName, options.treeExpress, options.treeSel) strPlotName = thisPlot.GetName() strPlotName = "%s_%s_%s" % (strPlotName, chamberAndScanDatePair[0], chamberAndScanDatePair[1]) thisPlot.SetName(strPlotName)
def arbitraryPlotter(anaType, listDataPtTuples, rootFileName, treeName, branchName, vfat, vfatCH=None, strip=None, ztrim=4, skipBad=False): """ Provides a list of tuples for 1D data where each element is of the form: (indepVarVal, depVarVal, depVarValErr) anaType - type of analysis to perform, helps build the file path to the input file(s), from set ana_config.keys() listDataPtTuples - list of tuples where each element is of the form: (cName, scandate, indepVar), note indepVar is expected to be numeric rootFileName - name of the TFile that will be found in the data path corresponding to anaType treeName - name of the TTree inside rootFileName branchName - name of a branch inside treeName that the dependent variable will be extracted from vfat - vfat number that plots should be made for vfatCH - channel of the vfat that should be used, if None an average is performed w/stdev for error bar, mutually exclusive w/strip strip - strip of the detector that should be used, if None an average is performed w/stdev for error bar, mutually exclusive w/vfatCH skipBad - if a file fails to open or the TTree cannot be found, the input is skipped and the processing continues rather than exiting """ from gempython.gemplotting.utils.anautilities import filePathExists, getDirByAnaType import numpy as np import os import root_numpy as rp # Make branches to load listNames = ["vfatN"] if vfatCH is not None and strip is None: listNames.append("vfatCH") elif strip is not None and vfatCH is None: listNames.append("ROBstr") listNames.append(branchName) # Load data listData = [] for dataPt in listDataPtTuples: # Get human readable info cName = dataPt[0] scandate = dataPt[1] indepVarVal = dataPt[2] # Setup Paths dirPath = getDirByAnaType(anaType.strip("Ana"), cName, ztrim) if not filePathExists(dirPath, scandate): print 'Filepath %s/%s does not exist!' % (dirPath, scandate) if skipBad: print 'Skipping' continue else: print 'Please cross-check, exiting!' exit(os.EX_DATAERR) pass filename = "%s/%s/%s" % (dirPath, scandate, rootFileName) # Get TTree try: dataFile = r.TFile(filename, "READ") dataTree = dataFile.Get(treeName) knownBranches = dataTree.GetListOfBranches() except Exception as e: print '%s may not exist in %s' % (treeName, filename) print e if skipBad: print 'Skipping' continue else: print 'Please cross-check, exiting!' exit(os.EX_DATAERR) pass pass # Check to make sure listNames are present in dataTree for testBranch in listNames: if testBranch not in knownBranches: print "Branch %s not in TTree %s of file %s" % ( branchName, treeName, filename) print "Existing Branches are:" for realBranch in knownBranches: print realBranch print "Please try again using one of the existing branches" exit(os.EX_DATAERR) # Get dependent variable value arrayVFATData = rp.tree2array(dataTree, listNames) dataThisVFAT = arrayVFATData[arrayVFATData['vfatN'] == vfat] #VFAT Level # Close the TFile dataFile.Close() if vfatCH is not None and strip is None: dataThisVFAT = dataThisVFAT[dataThisVFAT['vfatCH'] == vfatCH] #VFAT Channel Level elif strip is not None and vfatCH is None: dataThisVFAT = dataThisVFAT[dataThisVFAT['ROBstr'] == strip] #Readout Board Strip Level depVarVal = np.asscalar( np.mean(dataThisVFAT[branchName]) ) #If a vfatCH/ROBstr obs & chan/strip not give will be avg over all, else a number depVarValErr = np.asscalar( np.std(dataThisVFAT[branchName]) ) #If a vfatCH/ROBstr obs & chan/strip not given will be stdev over all, or zero #Record this dataPt listData.append((indepVarVal, depVarVal, depVarValErr)) # Return Data return listData
def arbitraryPlotter2D(anaType, listDataPtTuples, rootFileName, treeName, branchName, vfat, ROBstr=True, ztrim=4, skipBad=False): """ Provides a list of tuples for 2D data where each element is of the (x,y,z) form: (indepVarVal, vfatCHOrROBstr, depVarVal) anaType - type of analysis to perform, helps build the file path to the input file(s), from set ana_config.keys() listDataPtTuples - list of tuples where each element is of the form: (cName, scandate, indepVar), note indepVar is expected to be numeric rootFileName - name of the TFile that will be found in the data path corresponding to anaType treeName - name of the TTree inside rootFileName branchName - name of a branch inside treeName that the dependent variable will be extracted from vfat - vfat number that plots should be made for skipBad - if a file fails to open or the TTree cannot be found, the input is skipped and the processing continues rather than exiting """ from gempython.gemplotting.utils.anautilities import filePathExists, getDirByAnaType import numpy as np import os import root_numpy as rp # Make branches to load listNames = ["vfatN"] strChanName = "" #Name of channel TBranch, either 'ROBstr' or 'vfatCH' if ROBstr: listNames.append("ROBstr") strChanName = "ROBstr" else: listNames.append("vfatCH") strChanName = "vfatCH" listNames.append(branchName) # Load data listData = [] for dataPt in listDataPtTuples: # Get human readable info cName = dataPt[0] scandate = dataPt[1] indepVarVal = dataPt[2] # Setup Paths dirPath = getDirByAnaType(anaType.strip("Ana"), cName, ztrim) if not filePathExists(dirPath, scandate): print 'Filepath %s/%s does not exist!' % (dirPath, scandate) if skipBad: print 'Skipping' continue else: print 'Please cross-check, exiting!' exit(os.EX_DATAERR) pass filename = "%s/%s/%s" % (dirPath, scandate, rootFileName) # Get TTree try: dataFile = r.TFile(filename, "READ") dataTree = dataFile.Get(treeName) knownBranches = dataTree.GetListOfBranches() except Exception as e: print '%s may not exist in %s' % (treeName, filename) print e if skipBad: print 'Skipping' continue else: print 'Please cross-check, exiting!' exit(os.EX_DATAERR) pass pass # Check to make sure listNames are present in dataTree for testBranch in listNames: if testBranch not in knownBranches: print "Branch %s not in TTree %s of file %s" % ( branchName, treeName, filename) print "Existing Branches are:" for realBranch in knownBranches: print realBranch print "Please try again using one of the existing branches" exit(os.EX_DATAERR) # Get dependent variable value - VFAT Level arrayVFATData = rp.tree2array(dataTree, listNames) dataThisVFAT = arrayVFATData[arrayVFATData['vfatN'] == vfat] #VFAT Level # Close the TFile dataFile.Close() # Get the data for each strip and store it as a tuple in the list to be returned for chan in range(0, 128): dataThisChan = dataThisVFAT[dataThisVFAT[strChanName] == chan] #Channel Level depVarVal = np.asscalar(np.mean(dataThisChan[branchName])) listData.append((indepVarVal, chan, depVarVal)) pass # Return Data return listData
def compareLatResults(args): # Suppress all pop-ups from ROOT import ROOT as r r.gROOT.SetBatch(True) # Check Paths import os, sys from gempython.utils.wrappers import envCheck envCheck('DATA_PATH') envCheck('ELOG_PATH') elogPath = os.getenv('ELOG_PATH') # Get info from input file from gempython.gemplotting.utils.anautilities import getCyclicColor, getDirByAnaType, filePathExists, make3x8Canvas, parseListOfScanDatesFile parsedTuple = parseListOfScanDatesFile(args.filename,alphaLabels=args.alphaLabels) listChamberAndScanDate = parsedTuple[0] chamberName = listChamberAndScanDate[0][0] legPlot = r.TLegend(0.5,0.5,0.9,0.9) from gempython.utils.nesteddict import nesteddict as ndict dict_Histos = ndict() dict_Graphs = ndict() dict_MultiGraphs = {} print("Loading data from input list of scandates file") from gempython.gemplotting.utils.anaInfo import tree_names for idx,infoTuple in enumerate(listChamberAndScanDate): # Setup the path dirPath = getDirByAnaType("latency", infoTuple[0]) if not filePathExists(dirPath, infoTuple[1]): print('Filepath {:s}/{:s} does not exist!'.format(dirPath, infoTuple[1])) print('Please cross-check, exiting!') sys.exit(os.EX_NOINPUT) filename = "{:s}/{:s}/{:s}".format(dirPath, infoTuple[1], tree_names["latencyAna"][0]) if not os.path.isfile(filename): print('File {:s} does not exist!'.format(filename)) print('Please cross-check, exiting!') sys.exit(os.EX_NOINPUT) # Load the file r.TH1.AddDirectory(False) scanFile = r.TFile(filename,"READ") if scanFile.IsZombie(): print("{:s} is a zombie!!!".format(filename)) print("Please double check your input list of scandates: {:s}".format(args.filename)) print("And then call this script again") raise IOError ################### # Get individual distributions ################### for vfat in range(24): baseDir = "VFAT_Plots/VFAT{0:d}".format(vfat) dict_Histos[infoTuple[2]][vfat] = scanFile.Get("{:s}/vfat{:d}HitsVsLat".format(baseDir,vfat)) dict_Graphs[infoTuple[2]][vfat] = scanFile.Get("{:s}/g_N_vs_Lat_VFAT{:d}".format(baseDir,vfat)) # Make the TMultiGraph Objects suffix = "VFAT{:d}".format(vfat) if idx == 0: dict_MultiGraphs[vfat] = r.TMultiGraph("mGraph_RateVsThrDac_vfat{:s}".format(suffix),suffix) # Set Style of TGraph dict_Graphs[infoTuple[2]][vfat].SetLineColor(getCyclicColor(idx)) dict_Graphs[infoTuple[2]][vfat].SetMarkerColor(getCyclicColor(idx)) dict_Graphs[infoTuple[2]][vfat].SetMarkerStyle(20+idx) dict_Graphs[infoTuple[2]][vfat].SetMarkerSize(0.8) # Add to the MultiGraph dict_MultiGraphs[vfat].Add(dict_Graphs[infoTuple[2]][vfat]) ################### # Make an entry in the TLegend ################### if vfat == 0: print("infoTuple[2] = ", infoTuple[2]) legPlot.AddEntry( dict_Graphs[infoTuple[2]][vfat], "{0}".format(infoTuple[2]), "LPE") pass pass ################### # Make output ROOT file ################### outFileName = "{0}/compLatResults_{1}.root".format(elogPath,chamberName) outFile = r.TFile(outFileName,"RECREATE") ################### # Now Make plots ################### print("Making output plots") dict_canv = {} for vfat in range(24): # Make Output Canvas dict_canv[vfat] = r.TCanvas("canvLatResults_VFAT{0}".format(vfat),"Hits vs. CFG_LATENCY Value",700,700) dict_canv[vfat].cd() dict_MultiGraphs[vfat].Draw("APE1") dict_MultiGraphs[vfat].GetYaxis().SetTitle("Hits #left(A.U.#right)") dict_MultiGraphs[vfat].GetYaxis().SetRangeUser(0,args.eventsPerLat) # max is 40 MHz dict_MultiGraphs[vfat].GetXaxis().SetTitle("CFG_LATENCY #left(BX#right)") dict_MultiGraphs[vfat].Draw("APE1") # Draw Legend? if not args.noLeg: legPlot.Draw("same") pass # Make output image? if args.savePlots: dict_canv[vfat].SaveAs("{0}/{1}.png".format(elogPath,dict_canv[vfat].GetName())) pass # Store Output thisDirectory = outFile.mkdir("VFAT{0}".format(vfat)) thisDirectory.cd() dict_MultiGraphs[vfat].Write() dict_canv[vfat].Write() pass # Make summary canvases, always save these canvLatResults_Summary = make3x8Canvas("canvLatResults_Summary",dict_MultiGraphs.values()[0:24],"APE1") # Draw Legend? if not args.noLeg: canvLatResults_Summary.cd(1) legPlot.Draw("same") pass # Save summary canvases (always) print("\nSaving Summary TCanvas Objects") #canvLatResults_Summary.SaveAs("{0}/{1}.png".format(elogPath,canvLatResults_Summary.GetName())) # Close output files outFile.Close() print("You can find all ROOT objects in:") print("\n\t{0}//compLatResults_{1}.root\n".format(elogPath,chamberName)) print("You can find all plots in:") print("\n\t{0}\n".format(elogPath)) print("Done") return