def recursiveMerge(target, infile, path='', cache={'TOTALLUMI': 0}, cutflow=True): l = infile.GetDirectory(path) keys = l.GetListOfKeys() cycles = {} for entry in range(keys.GetEntries()): name = keys.At(entry).GetName() + ";" + str(keys.At(entry).GetCycle()) if path: cachename = path + "/" + name else: cachename = name obj = l.Get(name) if type(obj) == TDirectoryFile: #print obj, "DIRECTORY" targetpath = keys.At(entry).GetName() if not target.Get(targetpath): target.mkdir(targetpath) recursiveMerge(target, infile, path + "/" + obj.GetName(), cache) elif type(obj) == TTree: # print obj, cachename, "TTree" cyclename, cyclenumber = cachename.split(';') if cyclename in cycles: continue # print cachename, "Used!" cycles[cyclename] = cyclenumber if not cyclename in cache: target.cd(path) cache[cyclename] = obj.CloneTree() else: objcached = cache[cyclename] col = TObjArray() col.Add(obj) objcached.Merge(col) elif issubclass(obj.__class__, TH1): #print obj, "TH1" if not cutflow and keys.At(entry).GetName() == "CutFlow": continue if not cachename in cache: target.cd(path) cache[cachename] = obj.Clone() else: objcached = cache[cachename] col = TObjArray() col.Add(obj) objcached.Merge(col) elif type(obj) == TObjString: #print type(obj), name, "TObjString" if obj: target.cd(path) objnew = TObjString(obj.GetString().Data()) objnew.Write(keys.At(entry).GetName()) cache['TOTALLUMI'] += 1 else: print "UNKNOWN OBJECT", name, "OF TYPE", type(obj)
def getCutFlowFromHistogram(inputdir): try: from ROOT import AnalysisFramework except: compileMinimal() from ROOT import AnalysisFramework CutFlowHist = AnalysisFramework.CutFlows.CutFlowHist inputpath = listifyInputFiles(inputdir) htemp = CutFlowHist("CutFlow", "CutFlow output of AnalysisFramework", 400000, 0, 1) for d in inputpath: f = TFile.Open(d) heach = f.Get("CutFlow") #for i in range(heach.GetNbinsX()): # if not heach.GetBinLabel(i+1): # break # print i+1, heach.GetBinLabel(i+1) col = TObjArray() col.Add(heach) htemp.Merge(col) f.Close() #xaxis = htemp.GetXaxis() temp = {} for i in range(htemp.GetNbinsX()): label = htemp.GetBinLabel(i + 1) if not label: continue flownum = int(label.split('/')[0]) isweighted = label.split('/')[1] == 'W' flowname = label.split('/')[2] streamlet = label.split('/')[3] if isweighted: raw = 0. weighted = htemp.GetBinContent(i + 1) else: raw = htemp.GetBinContent(i + 1) weighted = 0. if not flownum in temp: temp[flownum] = (flowname, {}) flownametemp, numberstemp = temp[flownum] if not streamlet in numberstemp: numberstemp[streamlet] = (raw, weighted) else: rawtemp, weightedtemp = numberstemp[streamlet] numberstemp[streamlet] = (raw + rawtemp, weighted + weightedtemp) cutflow = [] totalEvents = getTotalEventsHistogram(inputdir) if totalEvents: cutflow.append(('OriginalTotalEvents', { 'All': (totalEvents.GetBinContent(1), totalEvents.GetBinContent(2)) })) for i in sorted(temp.keys()): cutflow.append(temp[i]) return cutflow
def makeTObjArray(theList): """Turn a python iterable into a ROOT TObjArray""" # Make PyROOT give up ownership of the things that are being placed in the # TObjArary. They get deleted because of result.SetOwner() result = TObjArray() result.SetOwner() for item in theList: SetOwnership(item, False) result.Add(item) return result
def test11WriteTObjArray(self): """Test writing of a TObjArray""" f = TFile(self.fname, 'RECREATE') t = TTree(self.tname, self.ttitle) o = TObjArray() t.Branch('mydata', o) nameds = [TNamed(name, name) for name in self.testnames] for name in nameds: o.Add(name) self.assertEqual(len(o), len(self.testnames)) t.Fill() f.Write() f.Close()
f1.ls() hDen = gDirectory.Get(Deno) hNum = gDirectory.Get(Numer) i1 = 0 i2 = 800 hNum.GetXaxis().SetRangeUser(i1, i2) hDen.GetXaxis().SetRangeUser(i1, i2) hDen.SetLineColor(ROOT.kRed) hRat = hNum.Clone() hRat.SetName("Ratio") hRat.Divide(hNum, hDen, 1., 1., "B") Hlist = TObjArray() Hlist.Add(hRat) cname = "pT" c1 = prepPlot("c1", cname, 700, 20, 500, 500) c1.SetLogy(1) hDen.Draw() hNum.Draw("same") cname = "Ratio" c2 = prepPlot("c2", cname, 150, 120, 500, 500) c2.SetLogy(0) min = 0.65 max = 1.04
def recursiveMerge(target, infile, path='', cache={'TOTALLUMI': 0}, cutflow=True): l = infile.GetDirectory(path) keys = l.GetListOfKeys() cycles = {} #print("keys in input file: \n\n{0}\n\n".format(keys.ls())) for entry in range(keys.GetEntries()): name = keys.At(entry).GetName() + ";" + str(keys.At(entry).GetCycle()) if path: cachename = path + "/" + name else: cachename = name obj = l.Get(name) if type(obj) == TDirectoryFile: #print("TDirectory obj name: {0}".format(obj.GetName())) targetpath = keys.At(entry).GetName() if not target.Get(targetpath): target.mkdir(targetpath) recursiveMerge(target, infile, path + "/" + obj.GetName(), cache) elif type(obj) == TTree: #print("TTree obj name: {0} - cachename: {1} ".format(obj.GetName(), cachename)) cyclename, cyclenumber = cachename.split(';') if cyclename in cycles: continue #print("cyclename: {0} - cyclenumber: {1}".format(cyclename, cyclenumber)) cycles[cyclename] = cyclenumber if not cyclename in cache: #print("adding cyclename {0} to cache (via TTree::CloneTree())".format(cyclename)) target.cd(path) cache[cyclename] = obj.CloneTree() else: objcached = cache[cyclename] col = TObjArray() col.Add(obj) #print("merging TTree obj to cached object") objcached.Merge(col) elif issubclass(obj.__class__, TH1): #print("TH1 obj name: {0}".format(obj.GetName())) if not cutflow and keys.At(entry).GetName() == "CutFlow": continue if not cachename in cache: target.cd(path) cache[cachename] = obj.Clone() else: objcached = cache[cachename] col = TObjArray() col.Add(obj) objcached.Merge(col) elif type(obj) == TObjString: #print("TObjString obj name: {0}".format(obj.GetName())) if obj: target.cd(path) objnew = TObjString(obj.GetString().Data()) objnew.Write(keys.At(entry).GetName()) cache['TOTALLUMI'] += 1 elif issubclass(obj.__class__, TList): #print("TList obj name: {0}".format(obj.GetName())) if obj: target.cd(path) objnew = TList(obj) objnew.Write(keys.At(entry).GetName()) # not working... else: print "UNKNOWN OBJECT", name, "OF TYPE", type(obj)
def FitAndPlot(self, fitpattern): #####Prepare the Histogram to the TFractionFitter#################### print "We are Fitting the variable: " + self.variable_ print "We are using the cut: " + self.cutname_ print "We are using the weight: " + self.weightname_ ttbarregionsignal = "" for tmpfiletype in self.filedict_.keys(): tmpcutname = self.cutname_ self.tmpplot.SetBinMinMax(self.bin_, self.min_, self.max_) self.tmpplot.SetCutWeightName(tmpcutname, self.weightname_) if (tmpfiletype != "data" and tmpfiletype != "QCD" and tmpfiletype != "WJets"): self.tmpplot.DrawTrees( self.filedict_[tmpfiletype], self.treename_, self.variable_, 0, self.xtitle_, self.ytitle_, "%s:%s" % (self.scalefactortxtfilename_, tmpfiletype), self.lumi_, tmpfiletype, self.histograms_, self.multiplicitylabel_, ttbarregionsignal) elif (tmpfiletype == "WJets"): self.tmpplot.SetCutWeightName( tmpcutname, self.weightname_ + "*W_nParton_weight") self.tmpplot.DrawTrees( self.filedict_[tmpfiletype], self.treename_, self.variable_, 0, self.xtitle_, self.ytitle_, "%s:%s" % (self.scalefactortxtfilename_, tmpfiletype), self.lumi_, tmpfiletype, self.histograms_, self.multiplicitylabel_, ttbarregionsignal) elif (tmpfiletype == "data"): self.tmpplot.DrawTrees(self.filedict_[tmpfiletype], self.treename_, self.variable_, 0, self.xtitle_, self.ytitle_, 1.0, 1.0, tmpfiletype, self.histograms_, self.multiplicitylabel_, ttbarregionsignal) elif (tmpfiletype == "QCD"): self.tmpplot.SetCutWeightName( tmpcutname + "&&((EWK_W_2jets_l_tagjet2_deltaR<EWK_W_2jets_l_tagjet1_deltaR?EWK_W_2jets_l_tagjet2_deltaR:EWK_W_2jets_l_tagjet1_deltaR)>1.0)", self.weightname_) self.tmpplot.DrawTrees(self.filedict_[tmpfiletype], self.treename_, self.variable_, 0, self.xtitle_, self.ytitle_, 1.0, 1.0, tmpfiletype, self.histograms_, self.multiplicitylabel_, ttbarregionsignal) if fitpattern == "QCDfraction": wjet1D = TH1D("wjet1D", "wjet1D", self.bin_, self.min_, self.max_) firstbin = 1 lastbin = self.histograms_["data"].GetNbinsX() dataentries = self.histograms_["data"].Integral(firstbin, lastbin) print "data Entries: " + str(dataentries) self.histograms_["QCD"].Scale( dataentries / self.histograms_["QCD"].Integral(firstbin, lastbin + 1)) wjet1D = self.histograms_["WJets"] + self.histograms_[ "W1Jets"] + self.histograms_["W2Jets"] + self.histograms_[ "W3Jets"] + self.histograms_["W4Jets"] wjet1D.Scale(dataentries / wjet1D.Integral(firstbin, lastbin + 1)) constrainfaction = 0. tconstrain1D = TH1D("tconstrain", "tconstrain", self.bin_, self.min_, self.max_) if len(self.constrains_) > 0: for icons in self.constrains_: tconstrain1D.Add(self.histograms_[icons]) #tconstrain1D.Scale(dataentries/tconstrain1D.Integral(firstbin,lastbin)) constrainfaction = tconstrain1D.Integral(firstbin, lastbin) / dataentries print "TTbar constrainfaction: " + str(constrainfaction) tconstrain1D.Scale( dataentries / tconstrain1D.Integral(firstbin, lastbin + 1)) mc = TObjArray() mc.Add(self.histograms_["QCD"]) mc.Add(wjet1D) if len(self.constrains_) > 0: mc.Add(tconstrain1D) self.fit_ = TFractionFitter(self.histograms_["data"], mc) self.fit_.Constrain(1, 0.0, 1.0) self.fit_.Constrain(2, 0.0, 1.0) if len(self.constrains_) > 0: #self.fit_.Constrain(3,constrainfaction - 0.0001*constrainfaction,constrainfaction + 0.0001*constrainfaction) self.fit_.Constrain(3, 0.0, 1.0) self.fit_.SetRangeX(firstbin, lastbin) status = self.fit_.Fit() print "fit status: " + str(status) self.SetUpPlotEnviroment() if (self.batch_): gROOT.SetBatch() canvas = TCanvas("c1", "c1", 10, 10, 700, 700) lgnd = TLegend(0.6, 0.6, 0.90, 0.9) lgnd.SetFillColor(kWhite) result = self.fit_.GetPlot() result.SetFillColor(kYellow) self.histograms_["data"].SetMinimum(0) self.histograms_["data"].Draw("Ep") result.Draw("histsame") frac_value = array('d', [0.]) frac_error = array('d', [0.]) self.fit_.GetResult(0, frac_value, frac_error) integralanalysisbin = self.histograms_["data"].FindBin( self.metcut_) dataentriesanalysisbin = self.histograms_["data"].Integral( integralanalysisbin, lastbin) qcdintegralanalysisbin = self.histograms_["QCD"].Integral( integralanalysisbin, lastbin) wjetsintegralanalysisbin = wjet1D.Integral(integralanalysisbin, lastbin) qcdfrac_valuemetcut = frac_value[ 0] * qcdintegralanalysisbin / dataentriesanalysisbin print "QCD: frac_value= " + str(qcdfrac_valuemetcut) + "+/-" + str( frac_error[0]) + " NEvts=" + str( dataentries * qcdfrac_valuemetcut) + "+/-" + str( dataentries * frac_error[0]) self.qcdfraction_ = qcdfrac_valuemetcut #self.qcdfraction_ = frac_value[0] self.qcdfractionerror_ = frac_error[0] self.histograms_["QCD"].Scale(frac_value[0]) self.histograms_["QCD"].SetLineWidth(2) self.histograms_["QCD"].SetLineColor(kBlue) self.histograms_["QCD"].Draw("histesame") self.fit_.GetResult(1, frac_value, frac_error) wjetsfrac_valuemetcut = frac_value[ 0] * wjetsintegralanalysisbin / dataentriesanalysisbin print "WJets: frac_value= " + str( wjetsfrac_valuemetcut) + "+/-" + str( frac_error[0]) + " NEvts=" + str( dataentries * wjetsfrac_valuemetcut) + "+/-" + str( dataentries * frac_error[0]) #self.histograms_["WJets"].Scale(frac_value[0]) #self.histograms_["WJets"].SetLineWidth(2) #self.histograms_["WJets"].SetLineColor(kRed) #self.histograms_["WJets"].Draw("histesame") wjet1D.Scale(frac_value[0]) wjet1D.SetLineWidth(2) wjet1D.SetLineColor(kRed) wjet1D.Draw("histesame") if len(self.constrains_) > 0: self.fit_.GetResult(2, frac_value, frac_error) tconstrain1D.Scale(frac_value[0]) #tconstrain1D.Scale(frac_value[0]*dataentries/tconstrain1D.Integral(firstbin,lastbin+1)) tconstrain1D.SetLineWidth(2) tconstrain1D.SetLineColor(kGreen) tconstrain1D.Draw("histsame") lgnd.AddEntry(result, "TemplatePrediction", "f") lgnd.AddEntry(self.histograms_["data"], "data", "p") lgnd.AddEntry(self.histograms_["QCD"], "QCD", "l") #lgnd.AddEntry(self.histograms_["WJets"], "WJetsMC","l") lgnd.AddEntry(wjet1D, "WJetsMC", "l") if len(self.constrains_) > 0: #lgnd.AddEntry(tconstrain1D, "Fixed Processes", "l") lgnd.AddEntry(tconstrain1D, "Other Processes", "l") chi2ndof = -999.0 if len(self.constrains_) > 0: print "FitChiSquare/ndof= " + str(self.fit_.GetChisquare() / (self.bin_ - 3)) chi2ndof = self.fit_.GetChisquare() / (self.bin_ - 3) else: print "FitChiSquare/ndof= " + str(self.fit_.GetChisquare() / (self.bin_ - 2)) chi2ndof = self.fit_.GetChisquare() / (self.bin_ - 2) print "FitProbatility= " + str(self.fit_.GetProb()) latex = TLatex(0.60, 0.50, "#chi2/ndof=%s" % (round(chi2ndof, 2))) latex.SetNDC() latex.SetTextSize(0.035) self.histograms_["data"].SetMarkerStyle(20) self.histograms_["data"].SetMarkerSize(1) self.histograms_["data"].Draw("Esame") lgnd.Draw() latex.Draw() if len(self.constrains_) > 0: self.channel_ = self.channel_ + "constrainotherprocess" self.variable_ = self.variable_.replace(".", "_") self.savelabel_ = self.savelabel_.replace(".", "_") canvas.SaveAs("QCDFractionFit/" + self.channel_ + "_" + self.variable_ + self.savelabel_ + "_qcdfraction.png") canvas.SaveAs("QCDFractionFit/" + self.channel_ + "_" + self.variable_ + self.savelabel_ + "_qcdfraction.pdf") canvas.SaveAs("QCDFractionFit/" + self.channel_ + "_" + self.variable_ + self.savelabel_ + "_qcdfraction.eps")
def cal_fraction(year, outputdir, eORb, pt_down, pt_up, fit_type, fdata, ftrue, ffake): sieie_cut = 0 if eORb == "barrel": sieie_cut = 0.01015 if eORb == "endcap": sieie_cut = 0.0272 lumi = 0 if year == "2016": lumi = 35.92 if year == "2017": lumi = 41.50 if year == "2018": lumi = 59.74 histname = "hist_" + eORb + "_" + str(pt_down) + "to" + str(pt_up) hdata = fdata.Get(histname) htrue = ftrue.Get(histname) hfake = ffake.Get(histname) c1 = TCanvas(histname, histname, 1000, 700) htrue.Scale(lumi) if fit_type == 'closureTEST': hdata.Scale(lumi) hfake.Scale(lumi) for i in range(hdata.GetNbinsX() + 2): if hdata.GetBinContent(i) < 0: hdata.SetBinContent(i, 0) if htrue.GetBinContent(i) < 0: htrue.SetBinContent(i, 0) if hfake.GetBinContent(i) < 0: hfake.SetBinContent(i, 0) mc = TObjArray(2) mc.Add(htrue) mc.Add(hfake) fit = TFractionFitter(hdata, mc) fit.Constrain(1, 0.0, 1.0) status = fit.Fit() val0, err0, val1, err1 = ROOT.Double(0), ROOT.Double(0), ROOT.Double( 0), ROOT.Double(0) n_data_total = hdata.Integral() fit.GetResult(0, val0, err0) fit.GetResult(1, val1, err1) # get fake rate nbin = hdata.FindFixBin(sieie_cut) - 1 nbins = hdata.GetNbinsX() fake_err_in_window, fake_err_total, data_err_in_window, data_err_total = ROOT.Double( 0), ROOT.Double(0), ROOT.Double(0), ROOT.Double(0) n_hfake_in_window = hfake.IntegralAndError(1, nbin, fake_err_in_window) n_hfake_total = hfake.IntegralAndError(1, nbins, fake_err_total) sector1 = n_hfake_in_window / n_hfake_total n_hdata_in_window = hdata.IntegralAndError(1, nbin, data_err_in_window) n_hdata_total = hdata.IntegralAndError(1, nbins, data_err_total) sector2 = n_hdata_in_window / n_hdata_total fakerate = val1 * sector1 / sector2 err_sector1 = sqrt( (sector1)**2 * ((fake_err_in_window / n_hfake_in_window)**2 + (fake_err_total / n_hfake_total)**2)) err_sector2 = sqrt( (sector2)**2 * ((data_err_in_window / n_hdata_in_window)**2 + (data_err_total / n_hdata_total)**2)) tmp = val1 * sector1 tmp_err = sqrt( (val1 * sector1)**2 * ((err_sector1 / sector1)**2 + (err1 / val1)**2)) fakerate_err = sqrt( (tmp / sector2)**2 * ((tmp_err / tmp)**2 + (err_sector2 / sector2)**2)) result = fit.GetPlot() hdata.Draw("p e") hdata.GetYaxis().SetTitle("Events/bin") hdata.GetYaxis().SetTitleOffset(1.45) hdata.GetXaxis().SetTitle("#sigma_{i#etai#eta}") hdata.SetStats(0) hdata.SetLineColor(1) hdata.SetMarkerStyle(20) result.Draw("HIST same") result.SetLineColor(8) result.SetLineWidth(2) result.SetStats(0) htrue.SetLineColor(2) htrue.SetLineWidth(2) htrue.SetStats(0) htrue.DrawNormalized("HIST e same", val0 * n_data_total) hfake.SetLineColor(4) hfake.SetLineWidth(2) hfake.SetStats(0) hfake.DrawNormalized("HIST e same", val1 * n_data_total) maximum = 1.3 * hdata.GetMaximum() hdata.SetMaximum(maximum) leg = TLegend(0.53, 0.48, 0.88, 0.88, "brNDC") leg.SetFillStyle(0) leg.SetLineColor(0) leg.SetFillColor(10) leg.SetBorderSize(0) leg.SetHeader( str(pt_down) + "GeV<p_{T}^{#gamma}<" + str(pt_up) + "GeV", "c") leg.AddEntry(hdata, "Data", "LPE") leg.AddEntry(result, "Template prediction", "LPE") leg.AddEntry(htrue, "True template from W#gamma", "LPE") leg.AddEntry(hfake, "Fake template from Data", "LPE") leg.Draw("same") statusStr = "fit status: " + str(int(status)) chi2 = fit.GetChisquare() ndf = fit.GetNDF() chi2ToNDF = chi2 / ndf chiInt = (100 * chi2ToNDF) strChi = "#chi^{2}/ndf = " + str(round( chiInt / 100, 3)) #+ '.' + str(round(chiInt % 100,3)) FRInt = (10000 * fakerate) FRErrInt = (10000 * fakerate_err) strFR = "fake rate = (" + str(round(FRInt / 100, 3)) + '#pm' + str( round(FRErrInt / 100, 3)) + '%)' latex = TLatex() latex.SetNDC() latex.SetTextSize(0.03) latex.SetLineWidth(1) latex.DrawLatex(0.75, 0.90, eORb) latex.DrawLatex(0.55, 0.44, statusStr) latex.DrawLatex(0.55, 0.38, strChi) latex.DrawLatex(0.55, 0.34, strFR) PNG_name = outputdir + '/' + str(year) + '_' + histname + '.png' c1.SaveAs(PNG_name) return fakerate, fakerate_err
from ROOT import gROOT, gStyle, TGraph, TFile, TObjArray gROOT.Reset(); rootFileName = fileName + ".root" f0 = TFile(rootFileName, "RECREATE") gList = TObjArray() for j in range(0, reactionNum): gr = TGraph() gr.Clear() gr.SetName(saveFileFirstLine[j+1]) for i in range(0, Size): gr.SetPoint(i, angle[i], dataMatrix[j][i]) name = "gr" + str(j) gList.Add(gr); gList.Write("gList", 1); f0.Write() #========= Calculate total Xsec print("======================") Xsec = [] deg2rad = 3.141592654 / 180. dTheta = angleStep * deg2rad phi = 6.283185307 for j in range(0, reactionNum): xsecTemp = 0 for i in range(0, Size):
def TemplateFit(filename, data, mc_q, mc_g, w_q=None, w_g=None, pull_widths=[1, 1], doPlots=True): n_mc = 2 # Define MC samples mc = TObjArray(n_mc) mc.Add(mc_q) mc.Add(mc_g) # Names mc_type = [] mc_type.append('Quarks') mc_type.append('Gluons') # Perform Fit fit = TFractionFitter(data, mc, "q") if w_q and w_g: fit.SetWeight(0, w_q) fit.SetWeight(1, w_g) fit.Constrain(0, 0.0, 1.0) #quarks fit.Constrain(1, 0.0, 1.0) #gluons fit.Fit() # Printing results val_q = ROOT.Double() err_q = ROOT.Double() val_g = ROOT.Double() err_g = ROOT.Double() fit.GetResult(0, val_q, err_q) fit.GetResult(1, val_g, err_g) err_q = err_q * pull_widths[ 0] # correcting the error for the width of the pull plot err_g = err_g * pull_widths[ 1] # correcting the error for the width of the pull plot for i in range(n_mc): val = ROOT.Double() err = ROOT.Double() fit.GetResult(i, val, err) out_file.write("fit result {}: {}, {}\n".format(mc_type[i], val, err)) out_file.write("X2 = {}\n".format(fit.GetChisquare())) out_file.write("NDF = {}\n".format(fit.GetNDF())) red_chi = fit.GetChisquare() / fit.GetNDF() out_file.write("red. X2 = {}\n".format(red_chi)) out_file.write("\n") if doPlots: print "storing plot as {}".format(filename) # Preparing Histograms h_fit = fit.GetPlot() h_q = fit.GetMCPrediction(0) h_g = fit.GetMCPrediction(1) h_fit.SetTitle("Fit") h_q.SetTitle("Quarks") h_g.SetTitle("Gluons") h_fit.SetLineColor(kGreen) h_q.SetLineColor(kRed) h_g.SetLineColor(kBlue) h_q.SetMarkerColor(kRed) h_g.SetMarkerColor(kBlue) # Scaling to the fit result int_fit = h_fit.Integral() int_q = h_q.Integral() int_g = h_g.Integral() h_q.Sumw2() h_g.Sumw2() h_q.Scale(val_q * int_fit / int_q) h_g.Scale(val_g * int_fit / int_g) # Checking fit vs. templates h_check = h_fit.Clone('Fit - Templates Check') h_check.Add(h_q, -1) h_check.Add(h_g, -1) check_maxBin = h_check.GetMaximumBin() out_file.write( "Maximal bin of fit minus templates divided by content of that bin in fit: {} / {}\n\n" .format(h_fit.GetBinContent(check_maxBin), h_check.GetBinContent(check_maxBin))) # Plotting results bp = BasicPlot(filename, var_tau0_width) bp.addHistogram(h_q, 'E', copy=True) bp.addHistogram(h_g, 'E', copy=True) bp.addHistogram(h_fit, 'HIST', copy=True) bp.addHistogram(data, 'E', copy=True) bp.titles.append( 'Quarks: {:.3} #pm {:.2}, Gluons: {:.3} #pm {:.2}'.format( val_q, err_q, val_g, err_g)) bp.titles.append( '#sqrt{{s}} = 13 TeV, #scale[0.5]{{#int}}Ldt = {0:.2f} fb^{{-1}}'. format(lumi / 1000.)) bp.titles.append('#chi^{{2}}/ndf: {:.3}'.format(red_chi)) bp.yVariable = Variable("Events") bp.legendDecorator.textSize = 0.045 bp.normalizeByBinWidth = False bp.showBinWidthY = False bp.normalized = False bp.logY = False bp.yVariable.binning.low = 0 # start y-axis at 0 bp.draw() bp.saveAsAll(os.path.join(outFolder, bp.title)) return fit
ix, bkghist.GetBinError(ix)**2 / bkghist.GetBinContent(ix)) sighistcounts.SetBinContent( ix, sighist.GetBinContent(ix)**2 / sighist.GetBinError(ix)**2) sighistweights.SetBinContent( ix, sighist.GetBinError(ix)**2 / sighist.GetBinContent(ix)) #bkghistnorm.Draw() #c.Print(outfilename+".pdf"); #sighistnorm.Draw() #c.Print(outfilename+".pdf"); fitcomponents = TObjArray(2) fitcomponents.Add(sighistcounts) fitcomponents.Add(bkghistcounts) #c.Print(outfilename+".pdf]") #sys.exit(0) for iy in range(1, nbinsY + 1): dataslice = hist.ProjectionX("rawdataslice" + str(iy), iy, iy) fracfitter = TFractionFitter(dataslice, fitcomponents, "Q") fracfitter.UnConstrain(0) fracfitter.UnConstrain(1) fracfitter.SetRangeX(firstbin, lastbin) fracfitter.SetWeight(0, sighistweights) fracfitter.SetWeight(1, bkghistweights) #fracfitter.SetData(dataslice) fitstatus = fracfitter.Fit()