def limit(signal_n, background_n, bkg_uncert): signal = TH1F("signal" + str(random.randrange(1e6)), "signal", 1, 0, 1) background = TH1F("background" + str(random.randrange(1e6)), "background", 1, 0, 1) data = TH1F("data" + str(random.randrange(1e6)), "data", 1, 0, 1) signal.Sumw2() signal.SetBinContent(1, signal_n) signal.SetBinError(1, sqrt(signal_n)) background.Sumw2() background.SetBinContent(1, background_n) background.SetBinError(1, sqrt(background_n)) errorsignal = TVectorD(1) errorbackground = TVectorD(1) errorsignal[0] = 0.20 # hardcoded to 2015 approximate value errorbackground[0] = bkg_uncert names = TObjArray() name1 = TObjString("bkg uncertainty") name2 = TObjString("sig uncertainty") names.AddLast(name1) names.AddLast(name2) datasource = TLimitDataSource() datasource = TLimitDataSource(signal, background, data, errorsignal, errorbackground, names) confidence = TConfidenceLevel(TLimit.ComputeLimit(datasource, 5000)) return 1 - confidence.GetExpectedCLs_b()
def compareEEC( filename="sjm91_all.root", datafilename="../EECMC/share/OPAL/data.dat" ): f= TFile( filename ) ao= createAnalysisObservable( f, "EEC" ) tokens= datafilename.split( "/" ) exp= tokens[3] plotoptions= { "xmin": 0.0, "xmax": 3.14159, "ymin": 0.05, "ymax": 5.0, "markerStyle": 20, "markerSize": 0.5, "drawas": "3", "fillcolor": 6, "title": "EEC "+exp, "xlabel": "\chi\ [rad.]", "ylabel": "1/\sigma d\Sigma/d\chi", "logy": 1 } tgest, tgesy= ao.plot( plotoptions ) lines= [ line.rstrip( '\n' ) for line in open( datafilename ) ] n= len( lines ) points= TVectorD( n ) values= TVectorD( n ) errors= TVectorD( n ) perrs= TVectorD(n) grad2rad= 3.14159/180.0 for i in range( n ): line= (lines[i]).split() points[i]= float(line[0])*grad2rad values[i]= float(line[3]) errors[i]= float(line[4]) perrs[i]= 0.0 datatge= TGraphErrors( points, values, perrs, errors ) datatge.SetMarkerStyle( 20 ) datatge.SetMarkerSize( 0.5 ) datatge.Draw( "psame" ) legend= TLegend( 0.2, 0.7, 0.5, 0.85 ) datatge.SetName( "datatge" ); tgesy.SetName( "tgesy" ) legend.AddEntry( "datatge", exp+" data", "pe" ) legend.AddEntry( "tgesy", "OPAL "+filename, "f" ) legend.Draw() return
def makeMETs(self, event): event.met = self.handles['met'].product()[0] event.metNoPU = self.handles['nopumet'].product()[0] if hasattr(event, 'deltaMetFromJetSmearing'): import ROOT px, py = event.met.px() + event.deltaMetFromJetSmearing[ 0], event.met.py() + event.deltaMetFromJetSmearing[1] event.met.setP4( ROOT.reco.Particle.LorentzVector(px, py, 0, hypot(px, py))) px, py = event.metNoPU.px() + event.deltaMetFromJetSmearing[ 0], event.metNoPU.py() + event.deltaMetFromJetSmearing[1] event.metNoPU.setP4( ROOT.reco.Particle.LorentzVector(px, py, 0, hypot(px, py))) metMatrix = self.handles['metSignificance'].product().significance() metMatrix.Invert() import array metVector = TVectorD( 2, array.array('d', [event.met.px(), event.met.py()])) event.metSignificance = metMatrix.Similarity(metVector) event.projMetAll1S = self.jetProjectedMET(event.met, event.jets, True) event.projMetAll2S = self.jetProjectedMET(event.met, event.jets, False) event.projMetJets1S = self.jetProjectedMET(event.met, event.cleanJets, True) event.projMetJets2S = self.jetProjectedMET(event.met, event.cleanJets, False)
def makeMETs(self, event): event.met = self.handles['met'].product()[0] event.metNoPU = self.handles['nopumet'].product()[0] if hasattr(event, 'deltaMetFromJetSmearing'): import ROOT px, py = event.met.px() + event.deltaMetFromJetSmearing[ 0], event.met.py() + event.deltaMetFromJetSmearing[1] event.met.setP4( ROOT.reco.Particle.LorentzVector(px, py, 0, hypot(px, py))) px, py = event.metNoPU.px() + event.deltaMetFromJetSmearing[ 0], event.metNoPU.py() + event.deltaMetFromJetSmearing[1] event.metNoPU.setP4( ROOT.reco.Particle.LorentzVector(px, py, 0, hypot(px, py))) if hasattr( event, 'deltaMetFromJEC' ) and event.deltaMetFromJEC[0] != 0 and event.deltaMetFromJEC[1] != 0: import ROOT px, py = event.met.px() + event.deltaMetFromJEC[0], event.met.py( ) + event.deltaMetFromJEC[1] event.met.setP4( ROOT.reco.Particle.LorentzVector(px, py, 0, hypot(px, py))) px, py = event.metNoPU.px() + event.deltaMetFromJEC[ 0], event.metNoPU.py() + event.deltaMetFromJEC[1] event.metNoPU.setP4( ROOT.reco.Particle.LorentzVector(px, py, 0, hypot(px, py))) metMatrix = self.handles['metSignificance'].product().significance() metMatrix.Invert() import array metVector = TVectorD( 2, array.array('d', [event.met.px(), event.met.py()])) event.metSignificance = metMatrix.Similarity(metVector)
def makeMT2W(self, event): # print '==> INSIDE THE PRINT MT2' # print 'MET=',event.met.pt() import array import numpy ## ===> hadronic MT2w (as used in the SUS-13-011) below just a placeHolder to be coded properly if not self.cfg_ana.doOnlyDefault: if len(event.selectedLeptons) >= 1: metVector = TVectorD( 3, array.array('d', [0., event.met.px(), event.met.py()])) lVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) #placeholder for visaVector and visbVector need to get the jets visaVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) visbVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) metVector = numpy.asarray(metVector, dtype='double') lVector = numpy.asarray(lVector, dtype='double') visaVector = numpy.asarray(visaVector, dtype='double') visbVector = numpy.asarray(visbVector, dtype='double') mt2wSNT.set_momenta(lVector, visaVector, visbVector, metVector) event.mt2w = mt2wSNT.get_mt2w()
def computeMT2(self, visaVec, visbVec, metVec): import array import numpy metVector = TVectorD(3, array.array( 'd', [0., metVec.px(), metVec.py()])) visaVector = TVectorD( 3, array.array('d', [0., visaVec.px(), visaVec.py()])) visbVector = TVectorD( 3, array.array('d', [0., visbVec.px(), visbVec.py()])) metVector = numpy.asarray(metVector, dtype='double') visaVector = numpy.asarray(visaVector, dtype='double') visbVector = numpy.asarray(visbVector, dtype='double') davismt2.set_momenta(visaVector, visbVector, metVector) davismt2.set_mn(0) return davismt2.get_mt2()
float(s_expected[m][int(len(s_expected[m]) * .975)])) exp95L[i] = abs( float(s_expected[m][len(s_expected[m]) / 2]) - float(s_expected[m][int(len(s_expected[m]) * .025)])) i = i + 1 #print "mass",mass #print "exp", exp #print "obs", obs #print "68H", exp68H #print "68L", exp68L #print "95H", exp95H #print "95L", exp95L massv = TVectorD(len(mass), mass) expv = TVectorD(len(mass), exp) obsv = TVectorD(len(mass), obs) exp68Hv = TVectorD(len(mass), exp68H) exp68Lv = TVectorD(len(mass), exp68L) exp95Hv = TVectorD(len(mass), exp95H) exp95Lv = TVectorD(len(mass), exp95L) masserrv = TVectorD(len(mass), masserr) obserrv = TVectorD(len(mass), obserr) experrv = TVectorD(len(mass), experr) theory_a = array("d", [ 1.5e-02, 5.2e-03, 1.8e-03, 7.04e-04, 2.79e-04, 1.14e-04, 4.68e-05, 1.19e-05, 7.7e-06 ])
hRecoDn = unfoldDn.Hreco() # unfolded & measured (vectors) vReco = unfold.Vreco() vMeas = unfold.Vmeasured() vRecoUp = unfoldUp.Vreco() vRecoDn = unfoldDn.Vreco() vMeasUp = unfoldUp.Vmeasured() vMeasDn = unfoldDn.Vmeasured() # response matrix as matrix instead of 2D histogram: (row,column)=(measured,truth) mResponse = response.Mresponse() # refolded (vector) vRefold = TVectorD(vReco) vRefold *= mResponse vRefoldUp = TVectorD(vRecoUp) vRefoldDn = TVectorD(vRecoDn) vRefoldUp *= mResponse vRefoldDn *= mResponse hRefold = TH1D("hRefold", "refolded", nbinsMeas, 0, nbinsMeas) hMeasCheck = TH1D("hMeasCheck", "measured check", nbinsMeas, 0, nbinsMeas) hRefoldUp = TH1D("hRefoldUp", "refoldedUp", nbinsMeas, 0, nbinsMeas) hRefoldDn = TH1D("hRefoldDn", "refoldedDn", nbinsMeas, 0, nbinsMeas) hMeasCheckUp = TH1D("hMeasCheckUp", "measured check up", nbinsMeas, 0, nbinsMeas) hMeasCheckDn = TH1D("hMeasCheckDn", "measured check down", nbinsMeas, 0,
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option("-i", "--inputfile", dest="inputfile") parser.add_option("-o", "--ouputfile", dest="outputfile") parser.add_option("-b", "--batch", action="store_true",\ dest="isBatch", default=False) parser.add_option("--normalization", nargs=2,\ type="float", dest="norm_range") parser.add_option("--fit", nargs=2,\ type="float", dest="fit_range") (options, args) = parser.parse_args() isSaveOutput = options.outputfile is not None if not (options.inputfile): parser.error("Please specify inputfiles.") import configurations as config if options.fit_range: fit_range = options.fit_range norm_range = (fit_range[1] - 200., fit_range[1]) else: fit_range = config.fit_range norm_range = config.norm_range # Override normalization range from input if options.norm_range: norm_range = options.norm_range from Styles import formatST, formatTemplate, formatUncertainty from ROOT import TFile, TF1, TH1D, TMath, TCanvas, TLegend,\ TGraphAsymmErrors, TVectorD, gStyle gStyle.SetPadTopMargin(0.05) gStyle.SetPadRightMargin(0.05) #gStyle.SetOptFit(1111111) #input file name infile = TFile(options.inputfile, "READ") from HistoStore import HistoStore store = HistoStore() canvas = HistoStore() print "Fit range: %d - %d GeV" % fit_range print "Normalization range: %d - %d GeV" % norm_range # Fit for N in config.exclusive_multiplicities: hST = infile.Get("plots%dJets/ST" % N) if not options.isBatch: c = TCanvas("TemplateN%d" % N, "TemplateN%d" % N, 500, 500) canvas.book(c) formatST(hST) hST.Draw("e") hST.GetXaxis().SetRangeUser(fit_range[0], config.maxST) hST.GetYaxis().SetRangeUser(1e-2, 2e4) hST.GetYaxis().SetTitleOffset(1.2) c.SetLogy(1) for i, formula in enumerate(config.templates): if N == 2: f = TF1("templateN%d_%d" % (N, i), formula, 0, 10000) elif N == 3: f = store.get("templateN2_%d" % i).Clone("templateN%d_%d" % (N, i)) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) hST.Fit(f, "QN0", "", fit_range[0], fit_range[1]) if i == 0: hST.Fit(f, "Q0", "", fit_range[0], fit_range[1]) formatTemplate(f, N, i) store.book(f) if not options.isBatch: f.Draw("same") hTemplate = hST.Clone("histoTemplateN%d_%d" % (N, i)) hTemplate.Reset() hTemplate.Eval(f) formatTemplate(hTemplate, N, i) store.book(hTemplate) if i == 0: hRef = hTemplate.Clone("ReferenceTemplateN%d_0" % N) store.book(hRef) # Print Chi-squre/Ndof print "N = %d, Chi^2/Ndof = %0.2f/%d" %\ (N, f.GetChisquare(), f.GetNDF()) if not options.isBatch: c.Update() # Calculate scale/error from OptimizationTools import OptimizeScale for histoN, templateN in [[2, 3]]: hST = store.get("ReferenceTemplateN%d_0" % histoN) hTemplate = store.get("ReferenceTemplateN%d_0" % templateN) hlnL, scale, err = OptimizeScale(hST, hTemplate, norm_range) hlnL.SetName("LogLikelihood_%dto%d" % (templateN, histoN)) store.book(hlnL) for i in range(len(config.templates)): hTemplate = store.get("histoTemplateN%d_%d" % (templateN, i)) hTemplate_ = hTemplate.Clone("histoTemplateN%d_%d__RescaledToN%d" % (templateN, i, histoN)) hTemplate_.Scale(scale) store.book(hTemplate_) # Shape Uncertainty hBkgTemplate = store.get("histoTemplateN2_0") hBkgTemplate.Rebin(config.rebin) nbins = hBkgTemplate.GetNbinsX() vST = TVectorD(nbins) vBkg = TVectorD(nbins) vexl = TVectorD(nbins) vexh = TVectorD(nbins) shape_el = TVectorD(nbins) shape_eh = TVectorD(nbins) rel_shape_el = TVectorD(nbins) rel_shape_eh = TVectorD(nbins) for i in range(nbins): vST[i] = hBkgTemplate.GetBinCenter(i + 1) if (vST[i] < config.com): vBkg[i] = hBkgTemplate.GetBinContent(i + 1) else: vBkg[i] = 0.0 vexl[i] = 0.0 vexh[i] = 0.0 shape_el[i] = 0.0 shape_eh[i] = 0.0 rel_shape_el[i] = 0.0 rel_shape_eh[i] = 0.0 for i in range(len(config.templates)): for label in [ "histoTemplateN2_%d", "histoTemplateN3_%d__RescaledToN2" ]: if label % i == "histoTemplateN2_0": continue h = store.get(label % i) h.Rebin(config.rebin) for ibin in range(nbins): diff = h.GetBinContent(ibin + 1) - vBkg[ibin] if diff > 0 and diff > shape_eh[ibin]: shape_eh[ibin] = diff elif diff < 0 and abs(diff) > shape_el[ibin]: shape_el[ibin] = abs(diff) # Relative Shape Uncertaincy for i in range(nbins): if vBkg[i] > 0: #rel_shape_el[i] = rel_shape_el[i] / vBkg[i] #hape_eh[i] = rel_shape_eh[i] / vBkg[i] max_err = max(shape_el[i], shape_eh[i]) shape_el[i] = max_err shape_eh[i] = max_err rel_shape_el[i] = max_err / vBkg[i] rel_shape_eh[i] = max_err / vBkg[i] else: rel_shape_el[i] = 0.0 rel_shape_eh[i] = 0.0 #print vST[i], vBkg[i], rel_shape_el[i], rel_shape_eh[i] gShapeUncertainty = TGraphAsymmErrors(vST, vBkg, vexl, vexh, shape_el, shape_eh) gShapeUncertainty.SetName("Shape_Uncertainty") formatUncertainty(gShapeUncertainty) store.book(gShapeUncertainty) gRelShapeUncertainty = TGraphAsymmErrors(vST, vexl, vexl, vexh, rel_shape_el, rel_shape_eh) gRelShapeUncertainty.SetName("Relative_Shape_Uncertainty") formatUncertainty(gRelShapeUncertainty) store.book(gRelShapeUncertainty) # Generate Backgrouds for N in config.label_for_data: hST = infile.Get("plotsN%s/ST" % N) rel_scale_err2 = 0.0 scale_factor = 1.0 for Nref in config.label_for_ref: if N == Nref: continue template = store.get("ReferenceTemplateN%s_0" % Nref) hlnL, scale, err = OptimizeScale(hST, template, norm_range) hlnL.SetName("LogLikelihood_%sto%s" % (Nref, N)) store.book(hlnL) if Nref == "2": scale_factor = scale rel_scale_err2 += err / scale * err / scale print "%s/%s %.3f +/- %.3f" % (N, Nref, scale, err) vy = TVectorD(nbins) veyh = TVectorD(nbins) veyl = TVectorD(nbins) for i in range(nbins): vy[i] = vBkg[i] * scale_factor veyh[i] = vy[i] * TMath.Sqrt(rel_scale_err2 + rel_shape_eh[i] * rel_shape_eh[i]) veyl[i] = vy[i] * TMath.Sqrt(rel_scale_err2 + rel_shape_el[i] * rel_shape_el[i]) print "Scaling uncertainty (%s): %.2f" %\ (N, TMath.sqrt(rel_scale_err2) * 100.0) gBkg = TGraphAsymmErrors(vST, vy, vexl, vexh, veyl, veyh) gBkg.SetName("BackgroundGraph_N%s" % N) formatUncertainty(gBkg) store.book(gBkg) hST.Rebin(config.rebin) hST.SetName("Data_N%s" % N) formatST(hST) store.book(hST) hBkg = hST.Clone("Background_N%s" % N) hBkg.Reset() store.book(hBkg) for i in range(nbins): ibin = hBkg.FindBin(vST[i]) hBkg.SetBinContent(ibin, vy[i]) hBkg.SetBinError(ibin, max(veyh[i], vexl[i])) from OptimizationTools import Integral hIntBkg = hBkg.Clone("IntegralBackground_N%s" % N) Integral(hIntBkg) store.book(hIntBkg) hIntData = hST.Clone("IntegralData_N%s" % N) Integral(hIntData) store.book(hIntData) # Plot Shape Uncertainty if not options.isBatch: legend_shape = TLegend(0.5544355, 0.5741525, 0.9395968, 0.9152542) legend_shape.SetTextFont(42) legend_shape.SetFillColor(0) legend_shape.SetLineColor(0) c = TCanvas("ShapeUncertaintyN2", "ShapeUncertaintyN2", 500, 500) canvas.book(c) gShapeUncertainty.Draw("AC3") gShapeUncertainty.GetXaxis().SetRangeUser(fit_range[0], config.maxST) gShapeUncertainty.GetYaxis().SetRangeUser(5e-2, 1.2e6) legend_shape.AddEntry(store.get("Data_N2"), "Data (N = 2)", "p") legend_shape.AddEntry(gShapeUncertainty, "Shape Uncertainty", "f") for i in range(len(config.templates)): for label in [ "histoTemplateN2_%d", "histoTemplateN3_%d__RescaledToN2" ]: h = store.get(label % i) h.GetXaxis().SetRangeUser(fit_range[0], config.maxST) h.Draw("histcsame") if label == "histoTemplateN2_%d": N = 2 else: N = 3 legend_shape.AddEntry(h, "Parametrization %d (N = %d)" % (i, N), "l") store.get("Data_N2").Draw("esame") c.SetLogy(1) legend_shape.Draw("plain") c.Update() if isSaveOutput: store.saveAs(options.outputfile) if not options.isBatch: raw_input("Press Enter to continue...")
def makeMT2(self, event): # print '==> INSIDE THE PRINT MT2' # print 'MET=',event.met.pt() ## ===> hadronic MT2 (as used in the SUS-13-019) objects40jc = [ j for j in event.cleanJets if j.pt() > 40 and abs(j.eta()) < 2.5 ] if len(objects40jc) >= 2: pxvec = ROOT.std.vector(float)() pyvec = ROOT.std.vector(float)() pzvec = ROOT.std.vector(float)() Evec = ROOT.std.vector(float)() grouping = ROOT.std.vector(int)() groupingViaKt = ROOT.std.vector(ROOT.std.vector(float))() for jet in objects40jc: pxvec.push_back(jet.px()) pyvec.push_back(jet.py()) pzvec.push_back(jet.pz()) Evec.push_back(jet.energy()) #### get hemispheres via AntiKT -1 antikt, 1 kt, 0 CA hemisphereViaAKt = HemisphereViaKt(pxvec, pyvec, pzvec, Evec, -1.) groupingViaAKt = hemisphereViaAKt.getGrouping() pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(groupingViaAKt[0])): if (index == 0): pseudoJet1px = groupingViaAKt[0][index] pseudoJet1py = groupingViaAKt[1][index] pseudoJet1pz = groupingViaAKt[2][index] pseudoJet1energy = groupingViaAKt[3][index] if (index == 1): pseudoJet2px = groupingViaAKt[0][index] pseudoJet2py = groupingViaAKt[1][index] pseudoJet2pz = groupingViaAKt[2][index] pseudoJet2energy = groupingViaAKt[3][index] event.pseudoViaAKtJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoViaAKtJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.mt2ViaAKt = self.computeMT2(event.pseudoViaAKtJet1, event.pseudoViaAKtJet2, event.met) #### get hemispheres via AntiKT -1 antikt, 1 kt, 0 CA hemisphereViaKt = HemisphereViaKt(pxvec, pyvec, pzvec, Evec, 1.) groupingViaKt = hemisphereViaKt.getGrouping() pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(groupingViaKt[0])): if (index == 0): pseudoJet1px = groupingViaKt[0][index] pseudoJet1py = groupingViaKt[1][index] pseudoJet1pz = groupingViaKt[2][index] pseudoJet1energy = groupingViaKt[3][index] if (index == 1): pseudoJet2px = groupingViaKt[0][index] pseudoJet2py = groupingViaKt[1][index] pseudoJet2pz = groupingViaKt[2][index] pseudoJet2energy = groupingViaKt[3][index] event.pseudoViaKtJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoViaKtJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.mt2ViaKt = self.computeMT2(event.pseudoViaKtJet1, event.pseudoViaKtJet2, event.met) #### get hemispheres (seed 2: max inv mass, association method: default 3 = minimal lund distance) hemisphere = Hemisphere(pxvec, pyvec, pzvec, Evec, 2, 3) grouping = hemisphere.getGrouping() pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(pxvec)): if (grouping[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] event.multPseudoJet1 += 1 if (grouping[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] event.multPseudoJet2 += 1 event.pseudoJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.mt2 = self.computeMT2(event.pseudoJet1, event.pseudoJet2, event.met) #### get hemispheres alternatice: 3: two objects who give maximal transverse mass 2: minimal mass squared sum of the hemispheres hemisphere32 = Hemisphere(pxvec, pyvec, pzvec, Evec, 3, 2) grouping32 = hemisphere32.getGrouping() pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(pxvec)): if (grouping32[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] if (grouping32[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] event.pseudoJet1minmass = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoJet2minmass = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.mt2minmass = self.computeMT2(event.pseudoJet1minmass, event.pseudoJet2minmass, event.met) #### do same things for GEN ## allGenJets = map( Jet, event.genJetsself.handles['genJets'].product() ) objects40jc_Gen = [ j for j in event.genJets if j.pt() > 40 and abs(j.eta()) < 2.5 ] if len(objects40jc_Gen) >= 2: pxvec = ROOT.std.vector(float)() pyvec = ROOT.std.vector(float)() pzvec = ROOT.std.vector(float)() Evec = ROOT.std.vector(float)() grouping = ROOT.std.vector(int)() for jet in objects40jc_Gen: pxvec.push_back(jet.px()) pyvec.push_back(jet.py()) pzvec.push_back(jet.pz()) Evec.push_back(jet.energy()) #### get hemispheres (seed 2: max inv mass, association method: default 3 = minimal lund distance) hemisphere = Hemisphere(pxvec, pyvec, pzvec, Evec, 2, 3) grouping = hemisphere.getGrouping() ## print 'grouping ',len(grouping) pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(pxvec)): if (grouping[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] if (grouping[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] pseudoGenJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) pseudoGenJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.mt2_gen = self.computeMT2(pseudoGenJet1, pseudoGenJet2, event.met.genMET()) #### do the mt2 with one or two b jets (medium CSV) if len(event.bjetsMedium) >= 2: event.mt2bb = self.computeMT2(event.bjetsMedium[0], event.bjetsMedium[1], event.met) # print 'MT2bb(2b)',event.mt2bb if len(event.bjetsMedium) == 1: objects40jcCSV = [ j for j in event.cleanJets if j.pt() > 40 and abs(j.eta()) < 2.5 and j.p4() != event.bjetsMedium[0].p4() ] objects40jcCSV.sort( key=lambda l: l.btag('combinedSecondaryVertexBJetTags'), reverse=True) if len(objects40jcCSV) > 0: # for index in range(0, len(objects40jcCSV)): # print 'CSV ',objects40jcCSV[index].btag('combinedSecondaryVertexBJetTags') event.mt2bb = self.computeMT2(event.bjetsMedium[0], objects40jcCSV[0], event.met) ## print 'MT2bb(1b)',event.mt2bb ## ===> leptonic MT2 (as used in the SUS-13-025 ) if len(event.selectedLeptons) >= 2: event.mt2lep = self.computeMT2(event.selectedLeptons[0], event.selectedLeptons[1], event.met) ## ===> hadronic MT2w (as used in the SUS-13-011) below just a placeHolder to be coded properly if len(event.selectedLeptons) >= 1: import array import numpy metVector = TVectorD( 3, array.array( 'd', [0., event.met.px(), event.met.py()])) lVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) #placeholder for visaVector and visbVector need to get the jets visaVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) visbVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) metVector = numpy.asarray(metVector, dtype='double') lVector = numpy.asarray(lVector, dtype='double') visaVector = numpy.asarray(visaVector, dtype='double') visbVector = numpy.asarray(visbVector, dtype='double') mt2wSNT.set_momenta(lVector, visaVector, visbVector, metVector) event.mt2w = mt2wSNT.get_mt2w()
model = ModelParser(row) models.append(model) from ROOT import TFile, TVectorD, TGraph from Styles import formatXsecCL from HistoStore import HistoStore store = HistoStore() group = ModelGroup(models) for generator, group_generator in group.items(): texfile = open("table_content-%s.tex" % generator, "w") for n, group_n in group_generator.items(): for icolor, (MD, models) in enumerate(group_n.items()): vsize = len(models) vx = TVectorD(vsize) vxsec = TVectorD(vsize) vcl95 = TVectorD(vsize) vcla = TVectorD(vsize) for i, m in enumerate(models): vx[i] = m.M vxsec[i] = m.xsec vcl95[i] = m.cl95 vcla[i] = m.cla bkg_str = "" if m.NbkgErr > m.Nbkg: bkg_str = "$%.2f ^{+%.2f}_{-%.2f}$" % (m.Nbkg, m.NbkgErr, m.Nbkg) else:
#create canvas cv[thegraph[ikey].name] = TCanvas(thegraph[ikey].name,thegraph[ikey].title,700,700) #legend aleg = TLegend(0.6,0.4,0.8,0.6) SetOwnership( aleg, 0 ) aleg.SetMargin(0.12) aleg.SetTextSize(0.035) aleg.SetFillColor(10) aleg.SetBorderSize(0) isFirst = 1 ii = 0 stacklist[thegraph[ikey].name] = THStack("astack"+thegraph[ikey].name,thegraph[ikey].title) astack = stacklist[thegraph[ikey].name] xVal_val = TVectorD() yVal_val = TVectorD() yBin_val = std.vector(int)() xErr_val = TVectorD() yErr_val = TVectorD() zVal_val = TVectorD() zErr_val = TVectorD() nVal_val = 0 xVal_ref = TVectorD() yVal_ref = TVectorD() yBin_ref = std.vector(int)() xErr_ref = TVectorD() yErr_ref = TVectorD() zVal_ref = TVectorD() zErr_ref = TVectorD()
def plotPValues(labels, masses0, **kwargs): print color("plotPValues()", color="magenta", prepend=">>>\n>>> ") # SIGNAL strength & mass bins = kwargs.get('bins', []) ymin = 0.00005 # LOOP over LABELS for label in labels: print color("plotPValues - %s" % (label), color="grey", prepend="\n>>> ") masses = array('d', []) zeros = array('d', []) limitObs = array('d', []) limitExps = [] up2s = [] for i, mass in enumerate(masses0): bin = -1 if bins: bin = bins[i] filename = getOutputFilename(label, mass, method="ProfileLikelihood", bin=bin, extralabel=".SignifObs") limitObs.append(getLimits(filename, brazilian=False)) masses.append(mass) zeros.append(0.0) v_masses = TVectorD(len(masses), masses) v_zeros = TVectorD(len(zeros), zeros) v_limitObs = TVectorD(len(limitObs), limitObs) v_limitExps = [] for limitExp in limitExps: v_limitExps.append(TVectorD(len(limitExp), limitExp)) W = 800 H = 600 T = 0.08 * H B = 0.12 * H L = 0.12 * W R = 0.04 * W canvas = TCanvas("canvas", "canvas", 100, 100, W, H) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin(L / W) canvas.SetRightMargin(R / W) canvas.SetTopMargin(T / H) canvas.SetBottomMargin(B / H) canvas.SetTickx(0) canvas.SetTicky(0) canvas.SetGrid() canvas.SetLogy() # log canvas.cd() frame = canvas.DrawFrame(1.4, 0.001, 4.1, 10) frame.GetYaxis().CenterTitle() frame.GetYaxis().SetTitleSize(0.05) frame.GetXaxis().SetTitleSize(0.05) frame.GetXaxis().SetLabelSize(0.04) frame.GetYaxis().SetLabelSize(0.04) frame.GetYaxis().SetTitleOffset(1.14) frame.GetXaxis().SetNdivisions(508) frame.GetYaxis().CenterTitle(False) frame.GetYaxis().SetTitle("local p-value") #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}") frame.GetXaxis().SetTitle("X#rightarrow#tau#tau mass [GeV]") frame.SetMinimum(ymin) frame.SetMaximum(1.5) frame.GetXaxis().SetLimits(min(masses), max(masses)) latex = TLatex() latex.SetTextSize(0.4 * canvas.GetTopMargin()) latex.SetTextColor(2) f1 = TF1("f1", "0.15866", min(masses), max(masses)) f1.SetLineColor(2) f1.SetLineWidth(2) f1.Draw("lsame") latex.DrawLatex(min(masses) + 1, 0.15866 * 1.1, "1#sigma") f2 = TF1("f2", "0.02275", min(masses), max(masses)) f2.SetLineColor(2) f2.SetLineWidth(2) f2.Draw("lsame") latex.DrawLatex(min(masses) + 1, 0.02275 * 1.1, "2#sigma") f3 = TF1("f3", "0.0013499", min(masses), max(masses)) f3.SetLineColor(2) f3.SetLineWidth(2) f3.Draw("lsame") latex.DrawLatex(min(masses) + 1, 0.0013499 * 1.1, "3#sigma") graph_limitExps = [] colors = [4, 2, 3, 6, 7, 8] for i, v_limitExp in enumerate(v_limitExps): graph_limitExps.append( TGraphAsymmErrors(v_masses, v_limitExp, v_zeros, v_zeros, v_zeros, v_zeros)) graph_limitExps[-1].SetLineColor(colors[i]) graph_limitExps[-1].SetLineWidth(2) graph_limitExps[-1].SetLineStyle(2) graph_limitExps[-1].Draw("Lsame") graph_limitObs = TGraphAsymmErrors(v_masses, v_limitObs, v_zeros, v_zeros, v_zeros, v_zeros) graph_limitObs.SetLineColor(1) graph_limitObs.SetLineWidth(2) graph_limitObs.Draw("Csame") CMS_lumi.CMS_lumi(canvas, 13, 0) gPad.SetTicks(1, 1) frame.Draw('sameaxis') x1 = 0.62 x2 = x1 + 0.24 y1 = 0.15 y2 = y1 + 0.20 legend = TLegend(x1, y1, x2, y2) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextSize(0.041) legend.SetTextFont(42) legend.SetHeader("%s" % (label_dict[label])) legend.AddEntry(graph_limitObs, "observed", 'L') #p-value legend.Draw("same") gPad.RedrawAxis() print " " canvas.SaveAs("%s/p-value-local-%s.png" % (PLOTS_DIR, label)) canvas.SaveAs("%s/p-value-local-%s.pdf" % (PLOTS_DIR, label)) canvas.Close()
def makeMT2(self, event): # print '==> INSIDE THE PRINT MT2' # print 'MET=',event.met.pt() import array import numpy ## ===> hadronic MT2 (as used in the SUS-13-019) objects40jc = [ j for j in event.cleanJets if j.pt() > 40 and abs(j.eta()) < 2.5 ] #### get hemispheres via AntiKT -1 antikt, 1 kt, 0 CA if len(objects40jc) >= 2: objects = ROOT.std.vector(ROOT.reco.Particle.LorentzVector)() for jet in objects40jc: objects.push_back(jet.p4()) hemisphereViaKt = ReclusterJets(objects, 1., 50.0) groupingViaKt = hemisphereViaKt.getGroupingExclusive(2) if len(groupingViaKt) >= 2: event.pseudoViaKtJet1_had = ROOT.reco.Particle.LorentzVector( groupingViaKt[0]) event.pseudoViaKtJet2_had = ROOT.reco.Particle.LorentzVector( groupingViaKt[1]) event.mt2ViaKt_had = self.computeMT2(event.pseudoViaKtJet1_had, event.pseudoViaKtJet2_had, event.met) if not self.cfg_ana.doOnlyDefault: hemisphereViaAKt = ReclusterJets(objects, -1., 50.0) groupingViaAKt = hemisphereViaAKt.getGroupingExclusive(2) if len(groupingViaAKt) >= 2: event.pseudoViaKtJet1_had = ROOT.reco.Particle.LorentzVector( groupingViaAKt[0]) event.pseudoViaKtJet2_had = ROOT.reco.Particle.LorentzVector( groupingViaAKt[1]) event.mt2ViaAKt_had = self.computeMT2( event.pseudoViaAKtJet1_had, event.pseudoViaAKtJet2_had, event.met) #### get hemispheres (seed 2: max inv mass, association method: default 3 = minimal lund distance) if len(objects40jc) >= 2: pxvec = ROOT.std.vector(float)() pyvec = ROOT.std.vector(float)() pzvec = ROOT.std.vector(float)() Evec = ROOT.std.vector(float)() grouping = ROOT.std.vector(int)() for jet in objects40jc: pxvec.push_back(jet.px()) pyvec.push_back(jet.py()) pzvec.push_back(jet.pz()) Evec.push_back(jet.energy()) hemisphere = Hemisphere(pxvec, pyvec, pzvec, Evec, 2, 3) grouping = hemisphere.getGrouping() ## print 'grouping ',len(grouping) pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 multPSJ1 = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 multPSJ2 = 0 for index in range(0, len(pxvec)): if (grouping[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] multPSJ1 += 1 if (grouping[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] multPSJ2 += 1 pseudoJet1pt2 = pseudoJet1px * pseudoJet1px + pseudoJet1py * pseudoJet1py pseudoJet2pt2 = pseudoJet2px * pseudoJet2px + pseudoJet2py * pseudoJet2py if pseudoJet1pt2 >= pseudoJet2pt2: event.pseudoJet1_had = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoJet2_had = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.multPseudoJet1_had = multPSJ1 event.multPseudoJet2_had = multPSJ2 else: event.pseudoJet2_had = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoJet1_had = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.multPseudoJet1_had = multPSJ2 event.multPseudoJet2_had = multPSJ1 event.mt2_had = self.computeMT2(event.pseudoJet1_had, event.pseudoJet2_had, event.met) #### do same things for GEN allGenJets = [x for x in self.handles['genJets'].product()] objects40jc_Gen = [ j for j in allGenJets if j.pt() > 40 and abs(j.eta()) < 2.5 ] if len(objects40jc_Gen) >= 2: pxvec = ROOT.std.vector(float)() pyvec = ROOT.std.vector(float)() pzvec = ROOT.std.vector(float)() Evec = ROOT.std.vector(float)() grouping = ROOT.std.vector(int)() for jet in objects40jc_Gen: pxvec.push_back(jet.px()) pyvec.push_back(jet.py()) pzvec.push_back(jet.pz()) Evec.push_back(jet.energy()) #### get hemispheres (seed 2: max inv mass, association method: default 3 = minimal lund distance) hemisphere = Hemisphere(pxvec, pyvec, pzvec, Evec, 2, 3) grouping = hemisphere.getGrouping() ## print 'grouping ',len(grouping) pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(pxvec)): if (grouping[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] if (grouping[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] pseudoGenJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) pseudoGenJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.mt2_gen = self.computeMT2(pseudoGenJet1, pseudoGenJet2, event.met.genMET()) ## ===> full MT2 (jets + leptons) objects10lc = [ l for l in event.selectedLeptons if l.pt() > 10 and abs(l.eta()) < 2.5 ] if hasattr(event, 'selectedIsoCleanTrack'): objects10lc = [ l for l in event.selectedLeptons if l.pt() > 10 and abs(l.eta()) < 2.5 ] + [t for t in event.selectedIsoCleanTrack] objects40j10lc = objects40jc + objects10lc objects40j10lc.sort(key=lambda obj: obj.pt(), reverse=True) if len(objects40j10lc) >= 2: pxvec = ROOT.std.vector(float)() pyvec = ROOT.std.vector(float)() pzvec = ROOT.std.vector(float)() Evec = ROOT.std.vector(float)() grouping = ROOT.std.vector(int)() for obj in objects40j10lc: pxvec.push_back(obj.px()) pyvec.push_back(obj.py()) pzvec.push_back(obj.pz()) Evec.push_back(obj.energy()) #for obj in objects_fullmt2: # print "pt: ", obj.pt(), ", eta: ", obj.eta(), ", phi: ", obj.phi(), ", mass: ", obj.mass() #### get hemispheres (seed 2: max inv mass, association method: default 3 = minimal lund distance) hemisphere = Hemisphere(pxvec, pyvec, pzvec, Evec, 2, 3) grouping = hemisphere.getGrouping() ## print 'grouping ',len(grouping) pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(pxvec)): if (grouping[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] if (grouping[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] pseudoJet1pt2 = pseudoJet1px * pseudoJet1px + pseudoJet1py * pseudoJet1py pseudoJet2pt2 = pseudoJet2px * pseudoJet2px + pseudoJet2py * pseudoJet2py if pseudoJet1pt2 >= pseudoJet2pt2: event.pseudoJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) else: event.pseudoJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.pseudoJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) ### event.mt2 = self.computeMT2(event.pseudoJet1, event.pseudoJet2, event.met) ## ===> full gamma_MT2 gamma_objects40jc = [ j for j in event.gamma_cleanJets if j.pt() > 40 and abs(j.eta()) < 2.5 ] gamma_objects40j10lc = gamma_objects40jc + objects10lc gamma_objects40j10lc.sort(key=lambda obj: obj.pt(), reverse=True) ## if len(gamma_objects40j10lc)>=2: if len(gamma_objects40jc) >= 2: pxvec = ROOT.std.vector(float)() pyvec = ROOT.std.vector(float)() pzvec = ROOT.std.vector(float)() Evec = ROOT.std.vector(float)() grouping = ROOT.std.vector(int)() ## for obj in objects40j10lc: for obj in gamma_objects40jc: pxvec.push_back(obj.px()) pyvec.push_back(obj.py()) pzvec.push_back(obj.pz()) Evec.push_back(obj.energy()) #### get hemispheres (seed 2: max inv mass, association method: default 3 = minimal lund distance) hemisphere = Hemisphere(pxvec, pyvec, pzvec, Evec, 2, 3) grouping = hemisphere.getGrouping() ## print 'grouping ',len(grouping) pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(pxvec)): if (grouping[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] if (grouping[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] event.gamma_pseudoJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) event.gamma_pseudoJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.gamma_mt2 = self.computeMT2(event.gamma_pseudoJet1, event.gamma_pseudoJet2, event.gamma_met) ## ===> zll_MT2 csLeptons = [ l for l in event.selectedLeptons if l.pt() > 10 and abs(l.eta()) < 2.5 ] if len(csLeptons) == 2 and len(objects40jc) >= 2: pxvec = ROOT.std.vector(float)() pyvec = ROOT.std.vector(float)() pzvec = ROOT.std.vector(float)() Evec = ROOT.std.vector(float)() grouping = ROOT.std.vector(int)() for obj in objects40jc: pxvec.push_back(obj.px()) pyvec.push_back(obj.py()) pzvec.push_back(obj.pz()) Evec.push_back(obj.energy()) #### get hemispheres (seed 2: max inv mass, association method: default 3 = minimal lund distance) hemisphere = Hemisphere(pxvec, pyvec, pzvec, Evec, 2, 3) grouping = hemisphere.getGrouping() ## print 'grouping ',len(grouping) pseudoJet1px = 0 pseudoJet1py = 0 pseudoJet1pz = 0 pseudoJet1energy = 0 pseudoJet2px = 0 pseudoJet2py = 0 pseudoJet2pz = 0 pseudoJet2energy = 0 for index in range(0, len(pxvec)): if (grouping[index] == 1): pseudoJet1px += pxvec[index] pseudoJet1py += pyvec[index] pseudoJet1pz += pzvec[index] pseudoJet1energy += Evec[index] if (grouping[index] == 2): pseudoJet2px += pxvec[index] pseudoJet2py += pyvec[index] pseudoJet2pz += pzvec[index] pseudoJet2energy += Evec[index] zll_pseudoJet1 = ROOT.reco.Particle.LorentzVector( pseudoJet1px, pseudoJet1py, pseudoJet1pz, pseudoJet1energy) zll_pseudoJet2 = ROOT.reco.Particle.LorentzVector( pseudoJet2px, pseudoJet2py, pseudoJet2pz, pseudoJet2energy) event.zll_mt2 = self.computeMT2(zll_pseudoJet1, zll_pseudoJet2, event.zll_met) #### do the mt2 with one or two b jets (medium CSV) if len(event.bjetsMedium) >= 2: event.mt2bb = self.computeMT2(event.bjetsMedium[0], event.bjetsMedium[1], event.met) # print 'MT2bb(2b)',event.mt2bb if len(event.bjetsMedium) == 1: objects40jcCSV = [ j for j in event.cleanJets if j.pt() > 40 and abs(j.eta()) < 2.5 and j.p4() != event.bjetsMedium[0].p4() ] objects40jcCSV.sort(key=lambda l: l.btag( 'combinedInclusiveSecondaryVertexV2BJetTags'), reverse=True) if len(objects40jcCSV) > 0: event.mt2bb = self.computeMT2(event.bjetsMedium[0], objects40jcCSV[0], event.met) ## print 'MT2bb(1b)',event.mt2bb ## ===> leptonic MT2 (as used in the SUS-13-025 ) if not self.cfg_ana.doOnlyDefault: if len(event.selectedLeptons) >= 2: event.mt2lep = self.computeMT2(event.selectedLeptons[0], event.selectedLeptons[1], event.met) ## ===> hadronic MT2w (as used in the SUS-13-011) below just a placeHolder to be coded properly if not self.cfg_ana.doOnlyDefault: if len(event.selectedLeptons) >= 1: metVector = TVectorD( 3, array.array('d', [0., event.met.px(), event.met.py()])) lVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) #placeholder for visaVector and visbVector need to get the jets visaVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) visbVector = TVectorD( 3, array.array('d', [ 0., event.selectedLeptons[0].px(), event.selectedLeptons[0].py() ])) metVector = numpy.asarray(metVector, dtype='double') lVector = numpy.asarray(lVector, dtype='double') visaVector = numpy.asarray(visaVector, dtype='double') visbVector = numpy.asarray(visbVector, dtype='double') mt2wSNT.set_momenta(lVector, visaVector, visbVector, metVector) event.mt2w = mt2wSNT.get_mt2w()
def PlotLimits(Type): theory_x = array('d', [ 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1900, 2100, 2300, 2500 ]) if Type == 'Right': theory_y = array('d', [ 1.2 * 1.6997, 1.2 * 0.97609, 1.2 * 0.58782, 1.2 * 0.36266, 1.2 * 0.22815, 1.2 * 0.14584, 1.2 * 0.09445, 1.2 * 0.06195, 1.2 * 0.04102, 1.2 * 0.027453, 1.2 * 0.012585, 1.2 * 0.005984, 1.2 * 0.0029719, 1.2 * 0.0015585 ]) theory_xv = TVectorD(len(theory_x), theory_x) theory_yv = TVectorD(len(theory_y), theory_y) theory = TGraph(theory_xv, theory_yv) theory.SetLineColor(2) theory.SetLineWidth(2) Nentries = Trees[Type].GetEntriesFast() mass = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) exp = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) obs = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) exp68H = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) exp68L = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) exp95H = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) exp95L = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) masserr = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) obserr = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) experr = array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) m = 0 for entry in xrange(Nentries): Trees[Type].GetEntry(entry) thismass = Trees[Type].mh thisquantile = Trees[Type].quantileExpected thislimit = Trees[Type].limit thislimiterr = Trees[Type].limitErr if thismass == 800.0: i = 0 elif thismass == 900.0: i = 1 elif thismass == 1000.0: i = 2 elif thismass == 1100.0: i = 3 elif thismass == 1200.0: i = 4 elif thismass == 1300.0: i = 5 elif thismass == 1400.0: i = 6 elif thismass == 1500.0: i = 7 elif thismass == 1600.0: i = 8 elif thismass == 1700.0: i = 9 elif thismass == 1900.0: i = 10 elif thismass == 2100.0: i = 11 elif thismass == 2300.0: i = 12 elif thismass == 2500.0: i = 13 #if thismass < 1000: continue if (abs(thisquantile + 1.000) < 0.01): mass[i] = thismass obs[i] = thislimit obserr[i] = 0 masserr[i] = 0 elif (abs(thisquantile - 0.025) < 0.01): exp95L[i] = thislimit print '95L ', thislimit elif (abs(thisquantile - 0.160) < 0.01): exp68L[i] = thislimit elif (abs(thisquantile - 0.500) < 0.01): exp[i] = thislimit experr[i] = thislimiterr elif (abs(thisquantile - 0.840) < 0.01): exp68H[i] = thislimit elif (abs(thisquantile - 0.975) < 0.01): exp95H[i] = thislimit print str(thismass) + ' ' + str(thisquantile) + ' ' + str(thislimit) print 'exp95L', exp95L print 'exp95H', exp95H print 'exp68L', exp68L print 'exp68H', exp68H massv = TVectorD(len(mass), mass) expv = TVectorD(len(mass), exp) obsv = TVectorD(len(mass), obs) exp68Hv = TVectorD(len(mass), exp68H) exp68Lv = TVectorD(len(mass), exp68L) exp95Hv = TVectorD(len(mass), exp95H) exp95Lv = TVectorD(len(mass), exp95L) #exp95Lv = TVectorD(len(mass),exp68L) masserrv = TVectorD(len(mass), masserr) obserrv = TVectorD(len(mass), obserr) experrv = TVectorD(len(mass), experr) observed = TGraphAsymmErrors(massv, obsv, masserrv, masserrv, obserrv, obserrv) observed.SetLineColor(ROOT.kBlack) observed.SetLineWidth(2) observed.SetMarkerStyle(20) expected = TGraphAsymmErrors(massv, expv, masserrv, masserrv, experrv, experrv) expected.SetLineColor(ROOT.kBlack) expected.SetLineWidth(2) expected.SetLineStyle(2) ## I'm confused, somehow this is the way that works expected68 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp95Lv, exp68Hv) #expected68 = TGraphAsymmErrors(massv,expv,masserrv,masserrv,exp68Lv,exp68Hv) expected68.SetFillColor(ROOT.kGreen) expected95 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp68Lv, exp95Hv) #expected95 = TGraphAsymmErrors(massv,expv,masserrv,masserrv,exp95Lv,exp95Hv) expected95.SetFillColor(ROOT.kYellow) c4 = TCanvas("c4", "W' tb Limits", 1000, 800) c4.SetBottomMargin(0.15) c4.SetRightMargin(0.06) expected95.Draw("a3") expected95.GetXaxis().SetTitle("W'_{" + Type + "} mass [GeV/c^{2}]") expected95.GetYaxis().SetTitle("#sigma(pp#rightarrowW/W'_{" + str(Type) + "}#rightarrowtb) [pb]") expected68.Draw("3same") expected.Draw("csame") observed.Draw("cpsame") theory.Draw("csame") latex = TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.SetTextAlign(31) # align right latex.DrawLatex(0.45, 0.95, "CMS Preliminary") latex2 = TLatex() latex2.SetNDC() latex2.SetTextSize(0.04) latex2.SetTextAlign(31) # align right latex2.DrawLatex(0.87, 0.95, str(lumiPlot) + " fb^{-1} at #sqrt{s} = 7 TeV") latex4 = TLatex() latex4.SetNDC() latex4.SetTextSize(0.04) latex4.SetTextAlign(31) # align right latex4.DrawLatex(0.80, 0.87, "e+jets N_{b tags} #geq 1 ") legend = TLegend(.566, .684, .84, .84) legend.AddEntry(observed, '95% C.L. Observed', "lp") legend.AddEntry(expected, '95% C.L. Expected', "l") legend.AddEntry(expected68, '#pm 1#sigma Expected', "f") legend.AddEntry(expected95, '#pm 2#sigma Expected', "f") legend.SetShadowColor(0) legend.SetFillColor(0) legend.SetLineColor(0) legend.Draw() c4.SaveAs('Wprime_' + Type + '_Limits.root') c4.SaveAs('Wprime_' + Type + '_Limits.png')
def graphProducer(plot, histos, tagFlav="B", mistagFlav=["C", "DUSG"], isVal=True): if histos is None: return if isVal: sample = "Val" else: sample = "Ref" #define graphs g = {} g_out = [] if tagFlav not in listFlavors: return if plot.tagFlavor and plot.mistagFlavor: tagFlav = plot.tagFlavor mistagFlav = plot.mistagFlavor for f in listFlavors: #compute errors, in case not already done histos[f].Sumw2() #efficiency lists Eff = {} EffErr = {} for f in listFlavors: Eff[f] = [] EffErr[f] = [] #define mapping points for the histos maxnpoints = histos[tagFlav].GetNbinsX() for f in listFlavors: Eff[f].append(histos[f].GetBinContent(1)) EffErr[f].append(histos[f].GetBinError(1)) for bin in range(2, maxnpoints + 1): #check if we add the point to the graph for Val sample if len(Eff[tagFlav]) > 0: delta = Eff[tagFlav][-1] - histos[tagFlav].GetBinContent(bin) if delta > max(0.005, EffErr[tagFlav][-1]): #get efficiencies for f in listFlavors: Eff[f].append(histos[f].GetBinContent(bin)) EffErr[f].append(histos[f].GetBinError(bin)) #create TVector len_ = len(Eff[tagFlav]) TVec_Eff = {} TVec_EffErr = {} for f in listFlavors: TVec_Eff[f] = TVectorD(len_) TVec_EffErr[f] = TVectorD(len_) #Fill the vector for j in range(0, len_): for f in listFlavors: TVec_Eff[f][j] = Eff[f][j] TVec_EffErr[f][j] = EffErr[f][j] #fill TGraph for mis in mistagFlav: g[tagFlav + mis] = TGraphErrors(TVec_Eff[tagFlav], TVec_Eff[mis], TVec_EffErr[tagFlav], TVec_EffErr[mis]) #style for f in listFlavors: if f not in mistagFlav: continue g[tagFlav + f].SetLineColor(mapColor[f]) g[tagFlav + f].SetMarkerStyle(mapMarker[sample]) g[tagFlav + f].SetMarkerColor(mapColor[f]) g_out.append(g[tagFlav + f]) index = -1 for g_i in g_out: index += 1 if g_i is not None: break #Axis g_out[index].GetXaxis().SetRangeUser(0, 1) g_out[index].GetYaxis().SetRangeUser(0.0001, 1) if plot.Xlabel: g_out[index].GetXaxis().SetTitle(plot.Xlabel) if plot.Ylabel: g_out[index].GetYaxis().SetTitle(plot.Ylabel) #add in the list None for element in listFlavors for which no TGraph is computed for index, f in enumerate(listFlavors): if f not in mistagFlav: g_out.insert(index, None) return g_out
store = HistoStore() models = [] with open("xsec_tmp2.txt", "rb") as f: reader = csv.reader(f, delimiter=" ", skipinitialspace=True) for row in reader: model = XsecParser(row) models.append(model) group = ModelGroup(models) for generator, group_generator in group.items(): for n, group_n in group_generator.items(): for icolor, (MD, models) in enumerate(group_n.items()): vsize = len(models) vx = TVectorD(vsize) vxsec = TVectorD(vsize) vex = TVectorD(vsize) vey = TVectorD(vsize) for i, m in enumerate(models): vx[i] = m.M vex[i] = 0.0 vxsec[i] = m.xsec vey[i] = m.xsecErr g = TGraphErrors(vx, vxsec, vex, vey) g.SetName("%s-MD%.1f_n%d-xsec" % (generator, MD, n)) store.book(g) store.saveAs("xsec_tmp2.root")
exp68H[i] = abs( float(s_expected[m][len(s_expected[m]) / 2]) - float(s_expected[m][int(len(s_expected[m]) * .84)])) exp68L[i] = abs( float(s_expected[m][len(s_expected[m]) / 2]) - float(s_expected[m][int(len(s_expected[m]) * .16)])) exp95H[i] = abs( float(s_expected[m][len(s_expected[m]) / 2]) - float(s_expected[m][int(len(s_expected[m]) * .975)])) exp95L[i] = abs( float(s_expected[m][len(s_expected[m]) / 2]) - float(s_expected[m][int(len(s_expected[m]) * .025)])) i = i + 1 massv = TVectorD(len(mass), mass) massv_ob = TVectorD(len(mass_ob), mass_ob) expv = TVectorD(len(mass), exp) obsv = TVectorD(len(mass_ob), obs) exp68Hv = TVectorD(len(mass), exp68H) exp68Lv = TVectorD(len(mass), exp68L) exp95Hv = TVectorD(len(mass), exp95H) exp95Lv = TVectorD(len(mass), exp95L) masserrv = TVectorD(len(mass), masserr) masserrv_ob = TVectorD(len(mass_ob), masserr_ob) obserrv = TVectorD(len(mass_ob), obserr) experrv = TVectorD(len(mass), experr)