line = line.strip('\n')
        chamberAndScanDatePair = line.rsplit('\t')  #chamber name, scandate
        if len(chamberAndScanDatePair) != 2:
            print "Input format incorrect"
            print "I was expecting a tab-delimited file with each line having 2 entries"
            print "But I received:"
            print "\t%s" % (line)
            print "Exiting"
            exit(os.EX_USAGE)
        tupleChamberAndScanDate = (chamberAndScanDatePair[0],
                                   chamberAndScanDatePair[1])

        # 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])

        # Get the Plot and Reset it's Name
        dictPlots[tupleChamberAndScanDate] = overlay_scurve(
            vfat=options.vfat,
            vfatCH=options.strip,
            fit_filename=filename,
            vfatChNotROBstr=options.channels)

        # Rename the image of the canvas
def arbitraryPlotter(anaType,
                     listDataPtTuples,
                     rootFileName,
                     treeName,
                     branchName,
                     vfat,
                     vfatCH=None,
                     strip=None,
                     ztrim=4):
    """
    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
    """

    from 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)
            print 'Please cross-check, exiting!'
            exit(os.EX_DATAERR)
        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, 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

        # 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_NOTFOUND) #Weird, not found but described in: https://docs.python.org/2/library/os.html#process-management
                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
Esempio n. 3
0
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 anautilities import filePathExists, 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
def arbitraryPlotter2D(anaType,
                       listDataPtTuples,
                       rootFileName,
                       treeName,
                       branchName,
                       vfat,
                       ROBstr=True,
                       ztrim=4):
    """
    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
    """

    from 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)
            print 'Please cross-check, exiting!'
            exit(os.EX_DATAERR)
        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, 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

        # 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_NOTFOUND) #Weird, not found but described in: https://docs.python.org/2/library/os.html#process-management
                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