Ejemplo n.º 1
0
def copy_directory(newdir, olddir, condition=None):
    """Reads all objects from olddir and writes them to newdir.

    newdir, olddir: Directories (inheriting from TDirectory).
    condition: Function that takes key name and returns whether the file should
        be kept or not (optional).
    """
    for key in olddir.GetListOfKeys():
        if condition is not None and (not condition(key) or
                                      key.GetName().startswith('ProcessID')):
            continue
        cl = gROOT.GetClass(key.GetClassName())
        if not cl:
            continue
        if cl.InheritsFrom(TDirectory.Class()):
            newsub = newdir.mkdir(key.GetName())
            oldsub = olddir.GetDirectory(key.GetName())
            copy_directory(newsub, oldsub)
        elif cl.InheritsFrom(TTree.Class()):
            oldtree = olddir.Get(key.GetName())
            newdir.cd()
            newtree = oldtree.CloneTree(-1, 'fast')
            newtree.Write()
        else:
            olddir.cd()
            obj = key.ReadObj()
            newdir.cd()
            obj.Write(key.GetName())
            del obj
Ejemplo n.º 2
0
    def default_constructor(self):
        """
        Check status of gDirectory with default constructor.
        """
        filename = "TContextContextManager_test_default_constructor.root"
        self.assertEqual(ROOT.gDirectory, ROOT.gROOT)

        with TDirectory.TContext():
            # Create a file to change gDirectory
            testfile = ROOT.TFile(filename, "recreate")
            self.assertEqual(ROOT.gDirectory, testfile)
            testfile.Close()

        self.assertEqual(ROOT.gDirectory, ROOT.gROOT)
        os.remove(filename)
Ejemplo n.º 3
0
    def constructor_onearg(self):
        """
        Check status of gDirectory with constructor taking a new directory.
        """
        filenames = ["TContextContextManager_test_constructor_onearg_{}.root".format(i) for i in range(2)]

        file0 = ROOT.TFile(filenames[0], "recreate")
        file1 = ROOT.TFile(filenames[1], "recreate")
        self.assertEqual(ROOT.gDirectory, file1)

        with TDirectory.TContext(file0):
            self.assertEqual(ROOT.gDirectory, file0)

        self.assertEqual(ROOT.gDirectory, file1)
        file0.Close()
        file1.Close()
        for filename in filenames:
            os.remove(filename)
Ejemplo n.º 4
0
    def constructor_twoargs(self):
        """
        Check status of gDirectory with constructor taking the previous directory and a new one.
        """
        filenames = ["TContextContextManager_test_constructor_onearg_{}.root".format(i) for i in range(3)]

        file0 = ROOT.TFile(filenames[0], "recreate")
        file1 = ROOT.TFile(filenames[1], "recreate")
        file2 = ROOT.TFile(filenames[2], "recreate")
        self.assertEqual(ROOT.gDirectory, file2)

        with TDirectory.TContext(file0, file1):
            self.assertEqual(ROOT.gDirectory, file1)

        self.assertEqual(ROOT.gDirectory, file0)
        file0.Close()
        file1.Close()
        file2.Close()
        for filename in filenames:
            os.remove(filename)
Ejemplo n.º 5
0
def printDirectory(directory, prefix, args):
    for key in directory.GetListOfKeys():
        classname = key.GetClassName()
        cl = gROOT.GetClass(classname)
        if (not cl):
            continue
        if (cl.InheritsFrom(TDirectory.Class())):
            print prefix, key.GetName()
            printDirectory(key.ReadObj(), prefix + "   ", args)
        elif (cl.InheritsFrom(TH1.Class())):
            hist = key.ReadObj()
            if args.systematics or hist.GetName(
            ) == "nominal" or hist.GetTitle() == "nominal":
                if args.full:
                    print prefix, hist.GetName(), hist.GetSumOfWeights()
                    for i in range(0, hist.GetNbinsX() + 2):
                        print prefix, "   ", hist.GetBinContent(
                            i), " +/- ", hist.GetBinError(i)
                else:
                    print prefix, key.GetName(), hist.GetSumOfWeights()
        else:
            print "Unknown", key.GetName()
Ejemplo n.º 6
0
reference_frame = [
    "colinsoper_phi", "collinsoper_theta", "helicity_phi", "helicity_theta"
]

master_canvas = []
# print vars()

histograms = []

nframe = 0
print "reference frame length must be 4 and it is : ", len(reference_frame)

while nframe < len(reference_frame):
    folder = reference_frame[nframe]

    vars()[folder] = TDirectory()

    #folder = TDirectory()

    folder = file2.mkdir(reference_frame[nframe])

    folder.cd()
    costheta_binmax = 0.6
    costheta_binmin = -0.6
    costheta_bin1 = 100
    costheta_bin2 = 17
    # histogram = TH1F(hist,"",n_bin,xmin,xmax)
    hist_costheta = TH1F("hist_costheta", "", costheta_bin1, costheta_binmax,
                         costheta_binmin)

    hist_costheta2 = TH1F("hist_costheta2", "purityHv3", costheta_bin2,
Ejemplo n.º 7
0
inFileName = sys.argv[1]
outFileName = sys.argv[2]
outFileType = sys.argv[3]

print("Input           " + inFileName)
print("Output          " + outFileName)
print("Ouput File Type " + outFileType)

cscRootName = "MUON_CSC_PED"
overviewName = "Overview"

inFile = TFile(inFileName)

cnv = TCanvas("c1", "c1")

rootDir = TDirectory()
overDir = TDirectory()

rootDir = inFile.FindObjectAny(cscRootName)
overDir = rootDir.FindObjectAny(overviewName)

hist = TH1D()

#Page 1
hist = overDir.Get("h_csc_calib_numSignificant")
hist.Draw()
cnv.Print(outFileName + "(", outFileType)

#Page 2
cnv.Clear()
cnv.Divide(2, 2)
Ejemplo n.º 8
0
##
## \date March 2022
## \author Vincenzo Eduardo Padulano CERN/UPV
import os

import ROOT
from ROOT import TDirectory, TFile

# Sometimes it is useful to have multiple open files at once. In such cases,
# the current directory will always be the file that was open last.
file_1 = TFile("pyroot006_file_1.root", "recreate")
file_2 = TFile("pyroot006_file_2.root", "recreate")
print("Current directory: '{}'.\n".format(ROOT.gDirectory.GetName()))
# Changing directory into another file can be safely done through a TContext
# context manager.
with TDirectory.TContext(file_1):
    # Inside the statement, the current directory is file_1
    print("Current directory: '{}'.\n".format(ROOT.gDirectory.GetName()))
    histo_1 = ROOT.TH1F("histo_1", "histo_1", 10, 0, 10)
    file_1.WriteObject(histo_1, "my_histogram")

# After the context, the current directory is restored back to file_2. Also, the
# two files are kept open. This means that objects read, written or modified
# inside the context are still available afterwards.
print("Current directory: '{}'.\n".format(ROOT.gDirectory.GetName()))
if file_1.IsOpen() and file_2.IsOpen():
    print("'{}' and '{}' are open.\n".format(file_1.GetName(),
                                             file_2.GetName()))

# TContext and TFile context managers can also be used in conjunction, allowing
# for safely:
Ejemplo n.º 9
0
def merge_root_file(target, source_list):
    """
    Merge next file from the source list with the target file.
    Function called recursively for each element of the list.

    :param TFile target: the result ROOT file
    :param TList source_list: list of input files to merge
    """
    logger = get_logger()
    raw_path = target.GetPath()
    path = raw_path[raw_path.find(":") + 1:]

    first_source = source_list.First()
    first_source.cd(path)
    current_source_dir = gDirectory
    # gain time, do not add the objects in the list in memory
    status = TH1.AddDirectoryStatus()
    TH1.AddDirectory(False)

    # loop over all keys in this directory
    #global_chain = TChain()
    next_key = TIter(current_source_dir.GetListOfKeys())
    #key = TKey()
    #TKey old_key = None
    key = next_key()
    while key:
        # keep only the highest cycle number for each key
        #if old_key and not old_key.GetName() == key.GetName():
        #    continue
        # read object from first source file
        first_source.cd(path)
        obj = key.ReadObj()

        if obj.IsA().InheritsFrom(TH1.Class()):
            # descendant of TH1 -> merge it
            logger.info("Merging histogram %s", obj.GetName())
            h1 = TH1(obj)

            # loop over all source files and add the content of the
            # correspondant histogram to the one pointed to by "h1"
            next_source = source_list.After(first_source)
            while next_source:
                # make sure we are at the correct directory level by cd'ing to path
                next_source.cd(path)
                key2 = gDirectory.GetListOfKeys().FindObject(h1.GetName())
                if key2:
                    h2 = TH1(key2.ReadObj())
                    h1.Add(h2)
                    #del h2
                next_source = source_list.After(next_source)

        elif obj.IsA().InheritsFrom(TTree.Class()):
            logger.info("Merging tree %s", obj.GetName())
            # loop over all source files and create a chain of Trees "global_chain"
            obj_name = obj.GetName()
            global_chain = TChain(obj_name)
            global_chain.Add(first_source.GetName())
            next_source = source_list.After(first_source)
            while next_source:
                global_chain.Add(next_source.GetName())
                next_source = source_list.After(next_source)

        elif obj.IsA().InheritsFrom(TDirectory.Class()):
            logger.info("Found subdirectory %s", obj.GetName())
            # create a new subdir of same name and title in the target file
            target.cd()
            new_dir = target.mkdir(obj.GetName(), obj.GetTitle())
            # newdir is now the starting point of another round of merging
            # newdir still knows its depth within the target file via
            # GetPath(), so we can still figure out where we are in the recursion
            merge_root_file(new_dir, source_list)

        else:
            logger.info("Unknown object type, name: %s, title: %s",
                        obj.GetName(), obj.GetTitle())

        # now write the merged histogram (which is "in" obj) to the target file
        # note that this will just store obj in the current directory level,
        # which is not persistent until the complete directory itself is stored
        # by "target.Write()" below
        if obj is not None:
            target.cd()
            # if the object is a tree, it is stored in global_chain...
            if obj.IsA().InheritsFrom(TTree.Class()):
                global_chain.Merge(target.GetFile(), 0, "keep")
            else:
                obj.Write(key.GetName())

        # move to the next element
        key = next_key()

    # save modifications to target file
    target.SaveSelf(True)
    TH1.AddDirectory(status)
    target.Write()
Ejemplo n.º 10
0
 def save_histograms(self, directory: ROOT.TDirectory):
     directory.cd()
     for hist in self.get_histogram_dict().keys():
         self.get_histogram_dict()[hist].Write()
Ejemplo n.º 11
0
def ApplyAddCuts(InputFolder, OutputFolder, Campaign):

    ChannelList = ChannelList_MC16a

    if Campaign == "MC16d":
        ChannelList = ChannelList_MC16d
    if Campaign == "MC16e":
        ChannelList = ChannelList_MC16e

    TreeList = ["nominal"]

    if "SYSLJ" in InputFolder:
        TreeList = SystTreeList

    InputFiles = glob.glob(InputFolder + "/*root*")

    for InputFile in InputFiles:

        OutputFile = InputFile.replace(InputFolder, OutputFolder)

        if os.path.exists(OutputFile):
            continue

        fF = TFile(InputFile, "READ")

        fF_out = TFile(OutputFile, "RECREATE")

        # save sumWeights tree to new file
        fT_weight = fF.Get("sumWeights")
        fT_weight_out = fT_weight.CloneTree()

        fT_weight_out.Write()

        # save all bookkeeping histograms to new file
        for Channel in ChannelList:

            DIR = TDirectory()
            fF.GetObject(Channel, DIR)
            DIR.ReadAll()
            fF_out.mkdir(Channel)
            fF_out.cd(Channel)
            DIR_new = TDirectory()
            DIR.GetList().Write()
            DIR_new.Write()

            fF_out.cd()

        for TreeName in TreeList:

            print(
                "---------------------------------------------------------------------------> Running over tree = ",
                TreeName)

            if TreeName == "nominal_SYST":
                continue

            fT = fF.Get(TreeName)
            entries = fT.GetEntries()
            reader1 = TMVA.Reader()
            reader2 = TMVA.Reader()

            var_LL_1 = array('f', [0])
            reader1.AddVariable("klfitter_logLikelihood[0]", var_LL_1)
            var_EvtProb_1 = array('f', [0])
            reader1.AddVariable("klfitter_eventProbability[0]", var_EvtProb_1)
            var_WhadPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_Whad_pt", var_WhadPt_1)
            var_WlepPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_Wlep_pt", var_WlepPt_1)
            var_ThadPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_tophad_pt", var_ThadPt_1)
            var_TlepPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_toplep_pt", var_TlepPt_1)
            var_j_n_1 = array('f', [0])
            reader1.AddVariable("tma_njets", var_j_n_1)
            var_met_1 = array('f', [0])
            reader1.AddVariable("tma_met", var_met_1)
            var_TTbarPt_1 = array('f', [0])
            reader1.AddVariable("klf_orig_ttbar_pt", var_TTbarPt_1)
            var_mwt_1 = array('f', [0])
            reader1.AddVariable("tma_mtw", var_mwt_1)
            var_DRwjets_1 = array('f', [0])
            reader1.AddVariable("klf_orig_dR_qq_W", var_DRwjets_1)
            var_DRbjets_1 = array('f', [0])
            reader1.AddVariable("klf_orig_dR_bb", var_DRbjets_1)

            var_LL_2 = array('f', [0])
            reader2.AddVariable("klfitter_logLikelihood[0]", var_LL_2)
            var_EvtProb_2 = array('f', [0])
            reader2.AddVariable("klfitter_eventProbability[0]", var_EvtProb_2)
            var_WhadPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_Whad_pt", var_WhadPt_2)
            var_WlepPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_Wlep_pt", var_WlepPt_2)
            var_ThadPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_tophad_pt", var_ThadPt_2)
            var_TlepPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_toplep_pt", var_TlepPt_2)
            var_j_n_2 = array('f', [0])
            reader2.AddVariable("tma_njets", var_j_n_2)
            var_met_2 = array('f', [0])
            reader2.AddVariable("tma_met", var_met_2)
            var_TTbarPt_2 = array('f', [0])
            reader2.AddVariable("klf_orig_ttbar_pt", var_TTbarPt_2)
            var_mwt_2 = array('f', [0])
            reader2.AddVariable("tma_mtw", var_mwt_2)
            var_DRwjets_2 = array('f', [0])
            reader2.AddVariable("klf_orig_dR_qq_W", var_DRwjets_2)
            var_DRbjets_2 = array('f', [0])
            reader2.AddVariable("klf_orig_dR_bb", var_DRbjets_2)

            reader1.BookMVA(
                "BDT",
                "TrainingSteffenChristmas/weights_noWindowCuts/MassTraining_BDT.weights.xml"
            )
            reader2.BookMVA(
                "BDT",
                "TrainingSteffenChristmas/weights_withWindowCuts/MassTraining_BDT.weights.xml"
            )

            fT_out = fT.CloneTree(0)
            d_noWC = array('f', [0.])
            d_withWC = array('f', [0.])

            fT_out.Branch("bdtOutput_8TeVlike_noWC", d_noWC,
                          'bdtOutput_8TeVlike_noWC/F')
            fT_out.Branch("bdtOutput_8TeVlike_withWC", d_withWC,
                          'bdtOutput_8TeVlike_withWC/F')

            for i in range(0, entries):
                fT.GetEntry(i)

                var_LL_1[0] = fT.klfitter_logLikelihood[0]
                var_EvtProb_1[0] = fT.klfitter_eventProbability[0]
                var_WhadPt_1[0] = fT.klf_orig_Whad_pt
                var_WlepPt_1[0] = fT.klf_orig_Wlep_pt
                var_ThadPt_1[0] = fT.klf_orig_tophad_pt
                var_TlepPt_1[0] = fT.klf_orig_toplep_pt
                var_j_n_1[0] = fT.tma_njets
                var_met_1[0] = fT.tma_met
                var_TTbarPt_1[0] = fT.klf_orig_ttbar_pt
                var_mwt_1[0] = fT.tma_mtw
                var_DRwjets_1[0] = fT.klf_orig_dR_qq_W
                var_DRbjets_1[0] = fT.klf_orig_dR_bb

                var_LL_2[0] = fT.klfitter_logLikelihood[0]
                var_EvtProb_2[0] = fT.klfitter_eventProbability[0]
                var_WhadPt_2[0] = fT.klf_orig_Whad_pt
                var_WlepPt_2[0] = fT.klf_orig_Wlep_pt
                var_ThadPt_2[0] = fT.klf_orig_tophad_pt
                var_TlepPt_2[0] = fT.klf_orig_toplep_pt
                var_j_n_2[0] = fT.tma_njets
                var_met_2[0] = fT.tma_met
                var_TTbarPt_2[0] = fT.klf_orig_ttbar_pt
                var_mwt_2[0] = fT.tma_mtw
                var_DRwjets_2[0] = fT.klf_orig_dR_qq_W
                var_DRbjets_2[0] = fT.klf_orig_dR_bb

                d_noWC[0] = reader1.EvaluateMVA("BDT")
                d_withWC[0] = reader2.EvaluateMVA("BDT")

                #print d_noWC[0],"     ",d_withWC[0]

                fT_out.Fill()

            fT_out.Write()

        fF_out.Close()