def divideEtaTH1Ds(etaHist, numCat, sourceFileName=None, categoryList=None, drawHist=False): # etaHist - the TH1D to split into categories # numCat - number of tagging categories # categoryList - list of tagging category names # drawHist - whether or not to display each category-split histogram # sourceFileName - name of etaHist root file #normalize etaHist etaHist.Scale(1.0 / etaHist.Integral()) #create default category names if none are given if categoryList == None: categoryList = [] for i in range(numCat): categoryList += ["Cat" + str(i)] histSum = etaHist.Integral() #get list of limits limList = [-1] for i in range(1, numCat): start = limList[i - 1] + 1 targetVal = histSum / numCat left = start right = etaHist.GetNbinsX() #print "\n\n\n",etaHist.Integral(start,start+1),"\n\n\n\n"; while abs(left - right) > 1: if etaHist.Integral(start, int((left + right) / 2)) > targetVal: right = (left + right) / 2 else: left = (left + right) / 2 #print start, left, right, etaHist.Integral(start,int((left+right)/2)),targetVal,",", if abs(etaHist.Integral(start, left) - targetVal) > abs(etaHist.Integral(start, right) - targetVal): limList += [right] else: limList += [left] limList[0] = 0 limList += [etaHist.GetNbinsX()] print limList #rangeFit is a 4-element TList containing: # - the sourceFileName as element 0 # - a RooThresholdCategory as element 2, and its RooRealVar as element 1 # - a tList of tFitResult as element 3 rangeFit = TList() rangeFit.AddLast(TObjString(sourceFileName)) rangeFit.AddLast(RooRealVar('x', 'x', 0.0, 1.0)) rangeFit.AddLast( RooThresholdCategory("tageffRegion", "region of tageff", rangeFit.At(1), "Cat" + str(numCat))) rangeFit.AddLast(TList()) #plot each category-split histogram, if necessary if drawHist == True: ROOT.gStyle.SetPalette(ROOT.kOcean) #create stack to contain the category TH1Ds etaHistStack = THStack("etaHistStack", "Stack of TH1Ds") #create category-masking function for TH1D clones histCutterFunc = TF1("histCutterFunc", "((x>=[0])?((x<[1])?1.0:0.0):0.0)", 0.0, 1.0) for i in range(len(limList) - 1): etaHistClone = etaHist.Clone() histCutterFunc.SetParameter( 0, etaHist.GetXaxis().GetBinCenter(limList[i])) histCutterFunc.SetParameter( 1, etaHist.GetXaxis().GetBinCenter(limList[i + 1])) #histCutterFunc.Draw(); #raw_input("Press Enter to continue to next hisCutterFunc"); etaHistClone.Multiply(histCutterFunc) etaHistClone.SetFillColor(38 + i) etaHistStack.Add(etaHistClone) etaHistClone = etaHist.Clone() etaHistClone.SetFillColor(38 + len(limList)) #etaHistStack.Add(etaHistClone); import time os.chdir(os.environ['B2DXFITTERSROOT'] + '/tutorial') if (not (os.path.isdir('fits'))): os.mkdir('fits') os.chdir('fits') histCanvas = TCanvas() etaHistStack.Draw("hist PFC") #etaHistClone.Draw("hist PFC"); #histCanvas.SaveAs('tagRegionFitList_%f.pdf' % time.time()); #create thresholds and fitting functions (all linear, but with different ranges corresponding to the categories) currentRangeTF1List = TList() for i in range(1, numCat + 1): if (i <= numCat): rangeFit.At(2).addThreshold( etaHist.GetXaxis().GetBinCenter(limList[i]), categoryList[i - 1]) currentRangeTF1List.AddLast( TF1( "fitFuncEtaset", "[0]+[1]*(x-" + str( etaHist.Integral(limList[i - 1], limList[i]) / (limList[i] - limList[i - 1])) + ")", etaHist.GetXaxis().GetBinCenter(limList[i - 1]), etaHist.GetXaxis().GetBinCenter(limList[i]))) #currentRangeTF1 = TF1("fitFuncEtaset","[0]+[1]*x",etaHist.GetXaxis().GetBinCenter(limList[i-1]),etaHist.GetXaxis().GetBinCenter(limList[i])); rangeFit.Last().AddLast( etaHist.Fit(currentRangeTF1List.Last(), "R0S").Get().Clone()) if (drawHist == True): currentRangeTF1List.Last().DrawCopy('same') #raw_input('Press Enter to continue to next fit function'); #currentRangeTF1.IsA().Destructor(currentRangeTF1); #print "P0, P1 = ",rangeFit.Last().Last().Parameter(0), rangeFit.Last().Last().Parameter(1); histCanvas.SaveAs('tagRegionFitList_%f.pdf' % time.time()) currentRangeTF1List.Delete() #for i in range(1,numCat+1): #currentRangeTF1List.Last().IsA().Destructor(currentRangeTF1List.Last()); #s = raw_input("Press Enter to continue..."); return rangeFit
def fhadd(self, prefix="", force=False, verbose=False, slow=True): """ taken from https://root.cern.ch/phpBB3/viewtopic.php?t=14881 This function will merge objects from a list of root files and write them to a target root file. The target file is newly created and must not exist, or if -f ("force") is given, must not be one of the source files. IMPORTANT: It is required that all files have the same content! Fast but memory hungry alternative to ROOT's hadd. Arguments: target -- name of the target root file sources -- list of source root files classname -- restrict merging to objects inheriting from classname force -- overwrite target file if exists """ target = prefix + self.Name + ".root" sources = [j.Output for j in self.Jobs] TH1.AddDirectory(False) # check if target file exists and exit if it does and not in force mode if not force and os.path.exists(target): raise RuntimeError("target file %s exists" % target) # open the target file print "fhadd Target file:", target outfile = TFile(target, "RECREATE") # open the seed file - contents is looked up from here seedfilename = sources[0] print "fhadd Source file 1", seedfilename seedfile = TFile(seedfilename) # get contents of seed file print "looping over seed file" contents = self.loop(seedfile) print "done %d objects are ready to be merged" % len(contents) if (verbose): for c in contents: print c # open remaining files otherfiles = [] for n, f in enumerate(sources[1:]): print "fhadd Source file %d: %s" % (n + 2, f) otherfiles.append(TFile(f)) # loop over contents and merge objects from other files to seed file objects for n, (path, hname) in enumerate(contents): print "fhadd Target object: %s" % os.path.join(path, hname) obj_path = os.path.join(path, hname) obj_ = seedfile.Get(obj_path[1:]) outfile.cd('/') # create target directory structure for d in path.split('/')[1:]: directory = gDirectory.GetDirectory(d) if not directory: gDirectory.mkdir(d).cd() else: gDirectory.cd(d) obj = None if obj_.InheritsFrom("TTree"): obj = obj_.CloneTree() else: obj = obj_.Clone() # merge objects l = TList() for o in [of.Get(obj_path[1:]) for of in otherfiles]: l.Add(o) obj.Merge(l) # delete objects if in slow mode if slow: print "Deleting %d object(s)", l.GetEntries() l.Delete() # write object to target obj.Write(obj.GetName(), TObject.kOverwrite) print "Writing and closing file" # let ROOT forget about open files - prevents deletion of TKeys for f in [outfile, seedfile] + otherfiles: gROOT.GetListOfFiles().Remove(f) outfile.Write() outfile.Close() for f in [seedfile] + otherfiles: f.Close()