def make2Dresponse(responses, jetPt, meas, true, misses=None, fakes=None): print("++++++++ Create Response from 3D histograms ++++++++") response2D = RooUnfoldResponse(meas, true) for r, pT, i in zip(responses, jetPt, range(len(responses))): nx = r.GetNbinsX() ny = r.GetNbinsY() nz = r.GetNbinsZ() pttrue = (pT[0] + pT[1]) / 2.0 print("{:.0f}%".format(100.0 * i / len(jetPt))) for ix in range(0, nx): for iy in range(0, ny): for iz in range(1, nz): ib = r.GetBin(ix, iy, iz) c = r.GetBinContent(ib) jttrue = r.GetZaxis().GetBinCenter(iz) # if iy == 0 and ix == 0: # response2D.Miss(jttrue,pttrue,c) if ix > 0 and iy > 0: jtobs = r.GetXaxis().GetBinCenter(ix) jtobs_meas = meas.GetXaxis().GetBinCenter(ix) ptobs_meas = meas.GetYaxis().GetBinCenter(iy) if TMath.Abs(jtobs - jtobs_meas) > 0.01: print("jtobs: {}, jtobs_meas: {}".format( jtobs, jtobs_meas)) raise ValueError( "Incorrect binning in make2Dresponse") ptobs = r.GetYaxis().GetBinCenter(iy) if TMath.Abs(ptobs - ptobs_meas) > 0.01: print("ptobs: {}, ptobs_meas: {}".format( ptobs, ptobs_meas)) raise ValueError( "Incorrect binning in make2Dresponse") jttrue = r.GetZaxis().GetBinCenter(iz) response2D.Fill(jtobs, ptobs, jttrue, pttrue, c) print("{:.0f}%".format(100)) if misses != None: nx = misses.GetNbinsX() ny = misses.GetNbinsY() for ix in range(1, nx): for iy in range(1, ny): ib = misses.GetBin(ix, iy) c = misses.GetBinContent(ib) jttrue = misses.GetXaxis().GetBinCenter(ix) pttrue = misses.GetYaxis().GetBinCenter(iy) # print("jtTrue: {}, ptTrue: {}, Misses: {}".format(jttrue,pttrue,c)) response2D.Miss(jttrue, pttrue, c) if fakes != None: nx = fakes.GetNbinsX() ny = fakes.GetNbinsY() for ix in range(1, nx): for iy in range(1, ny): ib = fakes.GetBin(ix, iy) c = fakes.GetBinContent(ib) jtobs = fakes.GetXaxis().GetBinCenter(ix) ptobs = fakes.GetYaxis().GetBinCenter(iy) # print("jtObs: {}, ptObs: {}, Fakes: {}".format(jtobs,ptobs,c)) response2D.Fake(jtobs, ptobs, c) return response2D
def SelectKfromDevents(TrueID, TrueMID): if mt.Abs(TrueID) in Kcodes: if mt.Abs(TrueMID) in Dcodes: return 1 else: return 0 else: return 0
def AddDiffNuisances(nuisances, up, dn, norm): nbins = up.GetNbinsX() for ibin in range(1, nbins + 1): if norm[ibin] == 0: continue up[ibin] = norm[ibin] * TMath.Sqrt( sum((nuisance.up[ibin] / norm[ibin])**2 for nuisance in nuisances)) dn[ibin] = norm[ibin] * TMath.Sqrt( sum((nuisance.dn[ibin] / norm[ibin])**2 for nuisance in nuisances))
def __call__(self, x, par): x1 = par[0] * TMath.Power(x[0] - 60, -par[1]) # x2=TMath.Exp(-1.0*(TMath.Power(par[2]*(x[0]-60),2))) # x2=TMath.Exp(-par[2]*(x[0]-60))*TMath.Exp(-1.0*(TMath.Power(par[3]*(x[0]-60),2))) x2 = TMath.Exp(-1.0 * (TMath.Power(par[2] * (x[0] - 60), 2))) # x2=TMath.Exp(-par[2]*(x[0]-60)) return x1 * x2
def __call__(self, x, par): x1 = par[0] * TMath.Power(x[0], -par[1]) x2 = TMath.Exp(-par[2] * x[0]) x3 = TMath.Exp(-par[3] * x[0] * x[0]) # x3=TMath.Power(x[0]*x[0],-par[1]) # x3=TMath.Exp(-par[3]*TMath.Sqrt(x[0])) # x3=par[3]*TMath.Gaus(x[0],par[4],par[5]) return x1 * x2 * x3
def run_zbi_stat(self): n_on = self.observation() mu_b_hat = self.background sigma_b = self.fullunc() tau = mu_b_hat / (sigma_b * sigma_b) n_off = tau * mu_b_hat P_Bi = TMath.BetaIncomplete(1. / (1. + tau), n_on, n_off + 1) Z_Bi = math.sqrt(2.) * TMath.ErfInverse(1 - 2. * P_Bi) return str(round(Z_Bi, 4))
def GetYaxisRanges(can, check_all=False, ignorezeros=False, ignoreErrors=False): # # check_all is if you want to check the maximum extent of all the histograms you plotted. # from ROOT import TGraph, TH1, THStack, TMath, TEfficiency ymin = 999999999 ymax = -999999999 for i in can.GetListOfPrimitives(): if issubclass(type(i), TGraph): ymin = min(ymin, TMath.MinElement(i.GetN(), i.GetY())) ymax = max(ymax, TMath.MaxElement(i.GetN(), i.GetY())) if not check_all: return ymin, ymax elif issubclass(type(i), TH1): ysum = 0 for bin in range(i.GetNbinsX()): ysum = ysum + i.GetBinContent(bin + 1) if ysum == 0: ignorezeros = 0 for bin in range(i.GetNbinsX()): y = i.GetBinContent(bin + 1) if ignoreErrors: ye = 0 else: ye = i.GetBinError(bin + 1) if ignorezeros and y == 0: continue ymin = min(ymin, y - ye) ymax = max(ymax, y + ye) if not check_all: return ymin, ymax elif issubclass(type(i), TEfficiency): ysum = 0 for bin in range(i.GetTotalHistogram().GetNbinsX()): ysum = ysum + i.GetTotalHistogram().GetBinContent(bin + 1) if ysum == 0: ignorezeros = 0 for bin in range(i.GetTotalHistogram().GetNbinsX()): y = i.GetTotalHistogram().GetBinContent(bin + 1) if ignoreErrors: ye = 0 else: ye = i.GetTotalHistogram().GetBinError(bin + 1) if ignorezeros and y == 0: continue ymin = min(ymin, y - ye) ymax = max(ymax, y + ye) if not check_all: return ymin, ymax elif issubclass(type(i), THStack): ymin = i.GetMinimum() ymax = i.GetMaximum() return ymin, ymax
def addPhi(phi1, phi2): sumphi = phi1 + phi2 while sumphi >= TMath.Pi(): sumphi -= 2 * TMath.Pi() while sumphi < -TMath.Pi(): sumphi += 2 * TMath.Pi() return sumphi
def deltaPhi(phi1, phi2): dphi = phi1 - phi2 while dphi >= TMath.Pi(): dphi -= 2 * TMath.Pi() while dphi < -TMath.Pi(): dphi += 2 * TMath.Pi() return dphi
def get_lifetime_weight(tree, ctau, ctau_MC): if len(tree.Rhadron_properdecaytime) != 2: #print('vector size of Rhadron_properdecaytime is not 2. return weight=0.') return 0 dt1 = tree.Rhadron_properdecaytime[0] * 1e-9 # [ns]->[s] dt2 = tree.Rhadron_properdecaytime[1] * 1e-9 # [ns]->[s] tau = ctau / TMath.C() tau_MC = ctau_MC / TMath.C() weight_rhad1 = tau_MC / tau * TMath.Exp(dt1 / tau_MC - dt1 / tau) weight_rhad2 = tau_MC / tau * TMath.Exp(dt2 / tau_MC - dt2 / tau) return weight_rhad1 * weight_rhad2
def read(self, iev): #read a given event if iev >= self.nev: return False self.tree.GetEntry(iev) #initialize event variables self.epos = 0. self.eneg = 0. self.npos = 0 self.nneg = 0 self.is_XnXn = False self.is_Cen = True vec = TLorentzVector() #particle loop for imc in xrange(self.particles.GetEntriesFast()): part = self.particles.At(imc) #central electron and positron if TMath.Abs(part.GetPdgCode()) == 11: if TMath.Abs(part.Eta()) > self.aeta_max: self.is_Cen = False #if part.P() < self.p_min: self.is_Cen = False pv = TLorentzVector() part.Momentum(pv) vec += pv #select the neutrons if part.GetPdgCode() != 2112: continue #energy at positive and negative rapidity if part.Eta() > 0: self.epos += part.Energy() self.npos += 1 else: self.eneg += part.Energy() self.nneg += 1 #particle loop #flag for XnXn event if self.npos > 0 and self.nneg > 0: self.is_XnXn = True #J/psi kinematics self.pT = vec.Pt() self.y = vec.Rapidity() self.m = vec.M() return True
def TH1pvalueAndChi2(h1, h2, ndf=None): try: chi2 = TH1ChiSquare(h1, h2) except: raise pvalue = 0 if ndf is not None: pvalue = TMath.Prob(chi2, ndf) else: pvalue = TMath.Prob(chi2, h1.GetNbinsX()) return pvalue, chi2
def get_pos( event ): # Each detector is a 'collection', the No. of Elements are the hits. n = TH1F("n", "Zenith Angles", 100, 0, 2) # first histogram to be filled with particles below the cut m = TH1F("m", "Zenith Angles", 100, 0, 2) # second for above k = 0 # counter for the number of particles below mcpart = event.getCollection( "MCParticle") # essentially 'opens up' the collection for ding in mcpart: # for every entry in the collection - can be called whatever mom = ding.getMomentum( ) # gets the momentum in a 3 vector fro mthe slcio file collection if ding.getPDG() == 11 or ding.getPDG() == -11 and mom[ 2] != 0: # condition that only allows electrons or positrons (their pdg id) also, the momenta cant be 0 x = mom[0] # assign a vales from the 3 vector to a variable y = mom[1] z = mom[2] if z == 0: print "weird angle..." # was to show me how many zeros I was getting t = TMath.Sqrt( (x * x) + (y * y)) # calculates transverse momentum using Pythatgoras if t < 0.0075: # this is the cut value of 7.5 GeV k += 1 try: # try statement allows to get around division by 0 theta = TMath.ATan(t / TMath.Abs(z)) # calculate the angle except ZeroDivisionError: theta = 90 # if the z momentum is 0, the angle is 90. n.Fill( theta, 1 ) # fills up the histogram so the value of theta gets 1 extra weight per cycle else: # if the transverse momentum is above try: theta = TMath.ATan(t / TMath.Abs(z)) except ZeroDivisionError: theta = 90 m.Fill(theta, 1) # fills the other histogram print "number of particles with transverse momenta < 7.5 MeV: ", k return n, m # returns the two histograms
def AssignMassIsoParticle_wTrueID(TrueID): m = m_pi isK = 0 if mt.Abs(TrueID) in Kcodes: m = m_K isK = 1 else: if mt.Abs(TrueID) == 2212: m = m_p else: m = m_pi return m, isK
def acc_el_en_theta_tag(): #Tagger acceptance in energy and theta #bins in theta tbin = 4e-4 tmin = TMath.Pi() - 2.1e-2 tmax = TMath.Pi() + 0.5e-2 #bins in energy ebin = 0.3 emin = 0 emax = 21 sel = "lowQ2s1_IsHit==1" #sel = "lowQ2s2_IsHit==1" #sel = "lowQ2s1_IsHit==1 || lowQ2s2_IsHit==1" can = ut.box_canvas() hEnThetaTag = ut.prepare_TH2D("hEnThetaTag", tbin, tmin, tmax, ebin, emin, emax) hEnThetaAll = ut.prepare_TH2D("hEnThetaAll", tbin, tmin, tmax, ebin, emin, emax) form = "true_el_E:true_el_theta" tree.Draw(form + " >> hEnThetaTag", sel) tree.Draw(form + " >> hEnThetaAll") hEnThetaTag.Divide(hEnThetaAll) ytit = "Electron energy #it{E} (GeV)" xtit = "Electron polar angle #theta (rad)" ut.put_yx_tit(hEnThetaTag, ytit, xtit, 1.4, 1.3) hEnThetaTag.SetTitleOffset(1.5, "Z") hEnThetaTag.SetZTitle("Acceptance") ut.set_margin_lbtr(gPad, 0.1, 0.1, 0.015, 0.15) #gPad.SetLogz() gPad.SetGrid() hEnThetaTag.SetMinimum(0) hEnThetaTag.SetMaximum(1) hEnThetaTag.SetContour(300) hEnThetaTag.Draw("colz") ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def getProb(yields): NTot = yields["NTot"] NTotErr = yields["NTotErr"] NPass = yields["NPass"] NPassErr = yields["NPassErr"] P = NPass / NTot PErr = NPassErr / NTot PErrUp = -1 PErrDn = -1 NLimit68Raw = -1 # Handle the case in which there are a small number of raw events corresponding to NPass. if "NTotRaw" in yields: NTotRaw = yields["NTotRaw"] else: NTotRaw = getRawEvts(NTot, NTotErr) NPassRaw = getRawEvts(NPass, NPassErr) if NPassRaw < 10: # Crude estimate of when Poisson approximates a binomial, see https://en.wikipedia.org/wiki/Poisson_distribution # print "Debug: NTotRaw = ", NTotRaw NPassRawErr = NPassRaw * (NPassErr / NPass) if NPass else 0 alpha = 0.84 # choose alpha such that 68% of distribution is within +/-1 sigma NPassErrUpRaw = math.fabs( 0.5 * TMath.ChisquareQuantile(alpha, 2 * (NPassRaw + 1)) - NPassRaw) NPassErrDnRaw = math.fabs( 0.5 * TMath.ChisquareQuantile(1.0 - alpha, 2 * (NPassRaw)) - NPassRaw) P = NPassRaw / NTotRaw PErrUp = NPassErrUpRaw / NTotRaw PErrDn = NPassErrDnRaw / NTotRaw PErr = PErrUp # Arbitrary choice; usually PErrUp is larger than PErrDn # For the case of NPassRaw, use a one-sided 68% confidence interval if NPassRaw == 0: NLimit68Raw = 0.5 * TMath.ChisquareQuantile( 0.68, 2 * (NPassRaw + 1) ) # 68% CL upper limit, see https://github.com/OSU-CMS/OSUT3Analysis/blob/master/AnaTools/bin/cutFlowLimits.cpp PErrUp = NLimit68Raw / NTotRaw PErrDn = 0 PErr = PErrUp # Arbitrary choice; usually PErrUp is larger than PErrDn prob = {} prob["P"] = P prob["PErr"] = PErr prob["PErrUp"] = PErrUp prob["PErrDn"] = PErrDn prob["NLimit68Raw"] = NLimit68Raw return prob
def acc_theta_s12(): #acceptance in electron polar angle for tagger 1 and tagger 2 inp = "/home/jaroslav/sim/lmon/data/taggers/tag1a/hits_tag.root" #inp = "/home/jaroslav/sim/lmon/data/taggers/tag1ax1/hits_tag.root" infile = TFile.Open(inp) tree = infile.Get("event") tmin = TMath.Pi() - 1.1e-2 tmax = TMath.Pi() + 1e-3 #amax = 0.25 amax = 0.4 as1 = rt.acc_Q2_kine(tree, "true_el_theta", "s1_IsHit") as1.prec = 0.1 as1.bmin = 2e-4 #as1.nev = int(1e5) gs1 = as1.get() as2 = rt.acc_Q2_kine(tree, "true_el_theta", "s2_IsHit") as2.prec = 0.1 as2.bmin = 2e-4 #as2.nev = int(1e5) gs2 = as2.get() can = ut.box_canvas() frame = gPad.DrawFrame(tmin, 0, tmax, amax) ut.put_yx_tit(frame, "Tagger acceptance", "Electron polar angle #it{#theta} (rad)", 1.6, 1.3) frame.Draw() ut.set_margin_lbtr(gPad, 0.11, 0.1, 0.03, 0.02) ut.set_graph(gs1, rt.kRed) gs1.Draw("psame") ut.set_graph(gs2, rt.kBlue) gs2.Draw("psame") gPad.SetGrid() leg = ut.prepare_leg(0.15, 0.82, 0.24, 0.12, 0.035) # x, y, dx, dy, tsiz leg.AddEntry(gs1, "Tagger 1", "lp") leg.AddEntry(gs2, "Tagger 2", "lp") leg.Draw("same") ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def PhiHE(p1, charge1, p2): # Phi decay angle (top (Q=+2/3)) in the Helicity frame pTop1Lab = TLorentzVector(0,0,-1,1) # In the lab. frame pTop2Lab = TLorentzVector(0,0,-1,1) # In the lab. frame pProjLab = TLorentzVector(0,0,-1,1) # In the lab. frame pTargLab = TLorentzVector(0,0,-1,1) # In the lab. frame pDitopLab = TLorentzVector(0,0,-1,1) # In the lab. frame pTop1Ditop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame pTop2Ditop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame pProjDitop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame pTargDitop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame beta = TVector3(0,0,0) xaxis = TVector3(0,0,0) yaxis = TVector3(0,0,0) zaxis = TVector3(0,0,0) mp = 0.93827231 ep = 6500. # Get the muons parameters in the LAB frame pTop1Lab.SetPxPyPzE(p1.Px(),p1.Py(),p1.Pz(),p1.E()) pTop2Lab.SetPxPyPzE(p2.Px(),p2.Py(),p2.Pz(),p2.E()) # Obtain the Ditop parameters in the LAB frame pDitopLab=pTop1Lab+pTop2Lab zaxis=(pDitopLab.Vect()).Unit() # Translate the muon parameters in the Ditop rest frame beta=(-1./pDitopLab.E())*pDitopLab.Vect() if(beta.Mag()>=1.): return 666. pProjLab.SetPxPyPzE(0.,0.,-ep,TMath.Sqrt(ep*ep+mp*mp)) pTargLab.SetPxPyPzE(0.,0.,+ep,TMath.Sqrt(ep*ep+mp*mp)) pProjDitop=pProjLab pTargDitop=pTargLab pProjDitop.Boost(beta) pTargDitop.Boost(beta) yaxis=((pProjDitop.Vect()).Cross(pTargDitop.Vect())).Unit() xaxis=(yaxis.Cross(zaxis)).Unit() pTop1Ditop=pTop1Lab pTop2Ditop=pTop2Lab pTop1Ditop.Boost(beta) pTop2Ditop.Boost(beta) phi = -999. if(charge1>0.): phi = TMath.ATan2((pTop1Ditop.Vect()).Dot(yaxis),(pTop1Ditop.Vect()).Dot(xaxis)) else: phi = TMath.ATan2((pTop2Ditop.Vect()).Dot(yaxis),(pTop2Ditop.Vect()).Dot(xaxis)) return phi
def __call__(self, x, par): out = 0.0 gaus1 = 0.0 gaus2 = 0.0 gaus1 = par[0] * TMath.Exp( (-0.5) * (x[0] - par[1]) * (x[0] - par[1]) / (par[2] * par[2])) gaus2 = par[4] * TMath.Exp( (-0.5) * (x[0] - par[1]) * (x[0] - par[1]) / (par[3] * par[3])) cc = par[2] * par[3] if cc > 0: out = gaus1 + gaus2 return out
def __call__(self, x, par): out = 0 t = (x[0] - par[1]) / par[2] if (par[0] < 0): t = -t absAlpha = TMath.Abs(par[3]) if (t >= -absAlpha): out = par[0] * TMath.Exp(-0.5 * t * t) else: a = TMath.Power(par[4] / absAlpha, par[4]) * TMath.Exp( -0.5 * absAlpha * absAlpha) b = par[4] / absAlpha - absAlpha out = par[0] * (a / TMath.Power(b - t, par[4])) return out
def get_pos( event ): # Each detector is a 'collection', the No. of Elements are the hits. i = 0 # left particle counter j = 0 # not left particle counter m = TH1F( "m", "Transverse Momenta", 100, 0, 2 ) # creates the histogram with ("name,"description", nbins, x low, x high) n = TH1F( "n", "Transverse Momenta", 100, 0, 2 ) # creates the histogram with ("name,"description", nbins, x low, x high) mcpart = event.getCollection("MCParticle") # opens up the collection for ding in mcpart: # for every entry in the collection - can be named anything mom = ding.getMomentum( ) # gets the momentum of th eparticle in a 3 vector array left = ding.hasLeftDetector() # checks if the particle has left if (ding.getPDG() == 11 or ding.getPDG() == -11) and mom[ 2] != 0 and left: # condition for being e+ e-, not zero z momentum and has left i += 1 x = mom[0] # assigns value from array to variable y = mom[1] z = mom[2] if z == 0: print "weird angle..." # see how many weird 0 z momentums there are t = TMath.Sqrt( (x * x) + (y * y)) # calculates transverse momentum using Pythagoras m.Fill(t, 1) # fills the histogram if (ding.getPDG() == 11 or ding.getPDG() == -11) and mom[ 2] != 0 and left == False: # condition for being e+ e-, not zero z momentum and has not left j += 1 x = mom[0] # assigns value from array to variable y = mom[1] z = mom[2] if z == 0: print "weird angle..." # see how many weird 0 z momentums there are t = TMath.Sqrt( (x * x) + (y * y)) # calculates transverse momentum using Pythagoras n.Fill(t, 1) # fills the histogram print "number of particles left: ", i, "\nnumber of particles didn't leave: ", j return m, n
def acc_phi_s2(): #Tagger 2 phi pmin = -TMath.Pi() - 0.3 pmax = TMath.Pi() + 0.3 amax = 0.3 acc_qr = rt.acc_Q2_kine(tree_qr, "true_el_phi", "lowQ2s2_IsHit") acc_qr.prec = 0.01 #acc_qr.bmin = 2e-4 #acc_qr.nev = int(1e5) gPhiQr = acc_qr.get() #gprint(gPtQr) acc_py = rt.acc_Q2_kine(tree_py, "true_el_phi", "lowQ2s2_IsHit") acc_py.prec = 0.01 #acc_py.bmin = 2e-4 #acc_py.nev = int(1e4) gPhiPy = acc_py.get() can = ut.box_canvas() frame = gPad.DrawFrame(pmin, 0, pmax, amax) #ytit = "Acceptance / {0:.1f} %".format(acc_qr.prec*100) ut.put_yx_tit(frame, "Acceptance", "Electron azimuthal angle #phi (rad)", 1.6, 1.3) frame.Draw() ut.set_margin_lbtr(gPad, 0.11, 0.1, 0.03, 0.02) ut.set_graph(gPhiQr, rt.kRed) gPhiQr.Draw("psame") ut.set_graph(gPhiPy, rt.kBlue) gPhiPy.Draw("psame") gPad.SetGrid() leg = ut.prepare_leg(0.72, 0.78, 0.24, 0.16, 0.035) # x, y, dx, dy, tsiz leg.AddEntry(None, "Tagger 2", "") leg.AddEntry(gPhiPy, "Pythia6", "l") leg.AddEntry(gPhiQr, "QR", "l") leg.Draw("same") #ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def el_phi_beff(): #electron azimuthal angle phi xbin = 3e-2 xmin = -TMath.Pi() - 0.3 xmax = TMath.Pi() + 0.3 qrpy = 0 if qrpy == 0: tree = tree_qr lab_data = "QR" col = rt.kBlue else: tree = tree_py lab_data = "Pythia6" col = rt.kRed can = ut.box_canvas() hP = ut.prepare_TH1D("hP", xbin, xmin, xmax) hB = ut.prepare_TH1D("hB", xbin, xmin, xmax) tree.Draw("true_el_phi >> hP") tree.Draw("el_phi >> hB") ut.line_h1(hP, col) ut.line_h1(hB, rt.kViolet) vmax = hP.GetMaximum() + 0.5 * hP.GetMaximum() frame = gPad.DrawFrame(xmin, 0.5, xmax, vmax) ut.put_yx_tit(frame, "Counts", "Electron #phi (rad)", 1.6, 1.3) frame.Draw() ut.set_margin_lbtr(gPad, 0.11, 0.1, 0.05, 0.02) gPad.SetGrid() #gPad.SetLogy() hB.Draw("same") hP.Draw("same") leg = ut.prepare_leg(0.55, 0.8, 0.24, 0.12, 0.035) # x, y, dx, dy, tsiz leg.AddEntry(hP, lab_data + ", no divergence", "l") leg.AddEntry(hB, "Divergence included", "l") leg.Draw("same") #ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def get_s(self, Ee, Ep): #calculate the CMS squared s #proton mass mp = TDatabasePDG.Instance().GetParticle(2212).Mass() #CMS energy squared s, GeV^2 s = 2.*Ee*Ep + self.me**2 + mp**2 s += 2*TMath.Sqrt(Ee**2 - self.me**2) * TMath.Sqrt(Ep**2 - mp**2) #print "sqrt(s):", TMath.Sqrt(s) return s
def GetTestStatistics( h_mass_data, h_temp_bgd, h_temp_sig ): # Compute likelihood Loglik_bgr = 0. Loglik_sb = 0. for i in range(1,h_mass_data.GetNbinsX()+1): # \mu = 0 (no signal) Loglik_bgr += TMath.Log( TMath.Poisson( h_mass_data.GetBinContent(i),h_temp_bgd.GetBinContent(i) ) ) # \mu = 1 (signal + background) Loglik_sb += TMath.Log( TMath.Poisson( h_mass_data.GetBinContent(i),h_temp_sig.GetBinContent(i)+h_temp_bgd.GetBinContent(i) ) ) # Get likelihood ratio X = 2*( Loglik_bgr-Loglik_sb ) return X
def _ExpoPowIntegralNorm(self, x, par): ''' Exponential times power law function normalized to its integral for D* background. Parameters ---------- - x: function variable - par: function parameters par[0]: normalisation (integral of background) par[1]: expo slope ''' return par[0] * TMath.Sqrt(x[0] - self.mPi) * TMath.Exp( -1. * par[1] * (x[0] - self.mPi))
def CostCS(p1, charge1, p2): #Cosine of the theta decay angle (top (Q=+2/3)) in the Collins-Soper frame pTop1CM = TLorentzVector(0,0,-1,1) # In the CM. frame pTop2CM = TLorentzVector(0,0,-1,1) # In the CM. frame pProjCM = TLorentzVector(0,0,-1,1) # In the CM. frame pTargCM = TLorentzVector(0,0,-1,1) # In the CM. frame pDitopCM = TLorentzVector(0,0,-1,1) # In the CM. frame pTop1Ditop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame pTop2Ditop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame pProjDitop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame pTargDitop = TLorentzVector(0,0,-1,1) # In the Ditop rest frame beta = TVector3(0,0,0) zaxisCS = TVector3(0,0,0) mp = 0.93827231 ep = 6500. # Fill the Lorentz vector for projectile and target in the CM frame pProjCM.SetPxPyPzE(0.,0.,-ep,TMath.Sqrt(ep*ep+mp*mp)) pTargCM.SetPxPyPzE(0.,0.,+ep,TMath.Sqrt(ep*ep+mp*mp)) # Get the Topons parameters in the CM frame pTop1CM.SetPxPyPzE(p1.Px(),p1.Py(),p1.Pz(),p1.E()) pTop2CM.SetPxPyPzE(p2.Px(),p2.Py(),p2.Pz(),p2.E()) # Obtain the Ditop parameters in the CM frame pDitopCM=pTop1CM+pTop2CM # Translate the Ditop parameters in the Ditop rest frame beta=(-1./pDitopCM.E())*pDitopCM.Vect() if(beta.Mag()>=1): return 666. pTop1Ditop=pTop1CM pTop2Ditop=pTop2CM pProjDitop=pProjCM pTargDitop=pTargCM pTop1Ditop.Boost(beta) pTop2Ditop.Boost(beta) pProjDitop.Boost(beta) pTargDitop.Boost(beta) # Determine the z axis for the CS angle zaxisCS=(((pProjDitop.Vect()).Unit())-((pTargDitop.Vect()).Unit())).Unit(); # Determine the CS angle (angle between Top+ and the z axis defined above) cost = -999 if(charge1>0): cost = zaxisCS.Dot((pTop1Ditop.Vect()).Unit()) else: cost = zaxisCS.Dot((pTop2Ditop.Vect()).Unit()) return cost
def acc_theta_s1(): tmin = TMath.Pi() - 2.1e-2 tmax = TMath.Pi() + 0.5e-2 amax = 0.08 acc_qr = rt.acc_Q2_kine(tree_qr, "true_el_theta", "lowQ2s1_IsHit") acc_qr.prec = 0.05 acc_qr.bmin = 2e-4 #acc_qr.nev = int(1e5) gThetaQr = acc_qr.get() #gprint(gPtQr) acc_py = rt.acc_Q2_kine(tree_py, "true_el_theta", "lowQ2s1_IsHit") acc_py.prec = 0.05 acc_py.bmin = 2e-4 #acc_py.nev = int(1e4) gThetaPy = acc_py.get() can = ut.box_canvas() frame = gPad.DrawFrame(tmin, 0, tmax, amax) #ytit = "Acceptance / {0:.1f} %".format(acc_qr.prec*100) ut.put_yx_tit(frame, "Acceptance", "Electron polar angle #theta (rad)", 1.6, 1.3) frame.Draw() ut.set_margin_lbtr(gPad, 0.11, 0.1, 0.03, 0.02) ut.set_graph(gThetaQr, rt.kRed) gThetaQr.Draw("psame") ut.set_graph(gThetaPy, rt.kBlue) gThetaPy.Draw("psame") gPad.SetGrid() leg = ut.prepare_leg(0.15, 0.78, 0.24, 0.16, 0.035) # x, y, dx, dy, tsiz leg.AddEntry(None, "Tagger 1", "") leg.AddEntry(gThetaPy, "Pythia6", "l") leg.AddEntry(gThetaQr, "QR", "l") leg.Draw("same") ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def conv_phi(): #conversion probablity as a function of azimuthal angle phi pbin = 0.4 pmin = -TMath.Pi() - 0.3 pmax = TMath.Pi() + 0.3 prec = 0.01 delt = 1e-6 gROOT.LoadMacro("get_ew_conv.C") #hEffV1 = rt.get_ew_conv(tree_v1, "phot_phi", "ew_conv", prec, delt) hEffV2 = rt.get_ew_conv(tree_v2, "phot_phi", "ew_conv", prec, delt) #hEffV1 = get_eff(tree_v1, "phot_phi", "ew_conv", pbin, pmin, pmax) #hEffV2 = get_eff(tree_v2, "phot_phi", "ew_conv", pbin, pmin, pmax) #ut.set_graph(hEffV1, rt.kBlue) #ut.set_graph(hEffV2, rt.kRed, rt.kFullTriangleUp) #hEffV2.SetMarkerSize(1.5) ut.set_graph(hEffV2) #plot the probability can = ut.box_canvas() #frame = gPad.DrawFrame(pmin, 0.075, pmax, 0.087) frame = gPad.DrawFrame(pmin, 0.065, pmax, 0.095) frame.SetXTitle("Generated #phi (rad)") frame.SetYTitle("Conversion probability") frame.SetTitleOffset(2.1, "Y") frame.SetTitleOffset(1.2, "X") ut.set_margin_lbtr(gPad, 0.14, 0.09, 0.02, 0.01) frame.Draw() #hEffV1.Draw("psame") hEffV2.Draw("psame") leg = ut.prepare_leg(0.2, 0.84, 0.2, 0.1, 0.035) #leg.AddEntry(hEffV1, "Tilted plane", "lp") leg.AddEntry(hEffV2, "Half-cylinder", "lp") #leg.Draw("same") #ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
def _ExpoIntegralNorm(self, x, par): ''' Exponential function normalized to its integral. See AliHFInvMassFitter::FitFunction4Bkg for more information. Parameters ---------- - x: function variable - par: function parameters par[0]: normalisation (integral of background) par[1]: expo slope ''' norm = par[0] * par[1] / (TMath.Exp(par[1] * self.maxMass) - TMath.Exp(par[1] * self.minMass)) return norm * TMath.Exp(par[1] * x[0])
def afterFirstMagnet(lz=12.): # assume there is a gap between First and second magnet, like in ..Zpl # exciting C1orC2 zEndOfAbsorb = z0+2*0.25+2*1.50 sz = str(int(lz)) hk = 'afterFirstMagnet_XY'+sz u.bookHist(h,hk,'afterFirstMagnet XY at z='+sz+'m' ,100,-2.,2.,100,-2.,2.) volDict = {} for x in dictVol: volDict[dictVol[x]]=x t = h['T'] t.SetEventList(0) ntotal = h['T'].GetEntries() previous = -999 f = open('afterFirstMagnet.txt','w') for i in range( ntotal ): t.GetEntry(i) for m in range(t.Nmeas): if (previous == volDict['MagC1'] or previous == volDict['MagC2']) and t.volid[m]==volDict['Snoopy']: line = '%3i %9.5F %9.5F %9.5F %9.5F %9.5F %9.5F %9.5F %9.5F\n'%( t.id, TMath.sqrt(t.px[m]**2+t.py[m]**2+t.pz[m]**2),t.px[m],t.py[m],t.pz[m],t.x[m],t.y[m],t.z[m],t.w) f.write(line) Xf,Yf = extrapXY(zEndOfAbsorb+lz,t.x[m],t.y[m],t.z[m],t.px[m],t.py[m],t.pz[m]) h[hk].Fill(Xf,Yf,t.w) previous = t.volid[m] f.close()
def originOfMuon(t,fl=None): leaves = t.GetListOfLeaves() nmax = t.GetEntries() evnrs = [] leaves = h['T'].GetListOfLeaves() names = u.setAttributes(pyl,leaves) for n in range(nmax): rc = t.GetEntry(n) if not pyl.id : names = u.setAttributes(pyl,leaves) if abs(pyl.id.GetValue())!=13:continue z = pyl.z.GetValue() y = pyl.y.GetValue() x = pyl.x.GetValue() pz = pyl.pz.GetValue() py = pyl.py.GetValue() px = pyl.px.GetValue() E = pyl.Ezero.GetValue() if z > 39.9 and z<40.1 and abs(pz)>0.1 and abs(x)<2 and abs(y)<2: evnrs.append(pyl.iev.GetValue()) print 'strange muon, original direction:',pyl.iev.GetValue(),n,px,py,pz,E,TMath.sqrt(px*px+py*py)/pz print ' ',x,y,z if fl!= None: for n in range(nmax): rc = t.GetEntry(n) ie = pyl.iev.GetValue() if ie in evnrs: z = pyl.z.GetValue() y = pyl.y.GetValue() x = pyl.x.GetValue() pz = pyl.pz.GetValue() py = pyl.py.GetValue() px = pyl.px.GetValue() E = pyl.Ezero.GetValue() if z<-50 : er,ex,ey,ep = extrap(-50+3.5,pyl) print 'pos at 3.5m',ex,ey,er er,ex,ey,ep = extrap(-50+40,pyl) print 'pos at 40m',ex,ey,er else: print ' ',pyl.iev.GetValue(),pyl.id.GetValue(),px,py,pz,E,TMath.sqrt(px*px+py*py)/pz print ' ',x,y,z er,ex,ey,ep = extrap(10.5,pyl) print 'pos at 60m',ex,ey,er return evnrs
def originOfMuon(t,fl=None): leaves = t.GetListOfLeaves() nmax = t.GetEntries() evnrs = [] for n in range(nmax): rc = t.GetEntry(n) if abs(leaves[1].GetValue())!=13:continue z = leaves[7].GetValue() y = leaves[6].GetValue() x = leaves[5].GetValue() pz = leaves[4].GetValue() py = leaves[3].GetValue() px = leaves[2].GetValue() p = math.sqrt(px**2+py**2+pz**2) if z > 39.9 and z<40.1 and abs(pz)>0.1 and abs(x)<2 and abs(y)<2: evnrs.append(leaves[0].GetValue()) print 'strange muon, original direction:',leaves[0].GetValue(),n,px,py,pz,p,TMath.sqrt(px*px+py*py)/pz print ' ',x,y,z if fl!= None: for n in range(nmax): rc = t.GetEntry(n) ie = leaves[0].GetValue() if ie in evnrs: z = leaves[7].GetValue() y = leaves[6].GetValue() x = leaves[5].GetValue() pz = leaves[4].GetValue() py = leaves[3].GetValue() px = leaves[2].GetValue() p = math.sqrt(px**2+py**2+pz**2) if z<-50 : er,ex,ey,ep = extrap(-50+3.5,leaves) print 'pos at 3.5m',ex,ey,er er,ex,ey,ep = extrap(-50+40,leaves) print 'pos at 40m',ex,ey,er else: print ' ',leaves[0].GetValue(),leaves[1].GetValue(),px,py,pz,p,TMath.sqrt(px*px+py*py)/pz print ' ',x,y,z er,ex,ey,ep = extrap(10.5,leaves) print 'pos at 60m',ex,ey,er return evnrs
def getISRerr(sig): errisr = 0. if "slepton" in sig: mgl = int(sig.split('_')[4]) mlsp = int(sig.split('_')[7]) else: mgl = int(sig.split('_')[3]) mlsp = int(sig.split('_')[4]) mdiff = mgl - mlsp # these are the max. showering parameter variations we found # (variations recommended for pythia 2011 tunes) norm = TMath.sqrt(0.25 ** 2 + 0.10 ** 2) if mgl < 300: norm += (1.0 - (mgl - 200) / 100.0) * 0.25 if mdiff < 300: # the uncertainty grows towards the mass diagonal, # and when mgl gets smaller. errisr = (1.0 - (mdiff / 300.0)) * norm return errisr
def logLikelihood(self, nParameters, gin, f, par, iflag): lnL = 0.0 data_vector = self.vectors[self.data_label] vector_entry = 0 for data in data_vector: x_i = 0 param_index = 0 for sample in self.samples: x_i += par[param_index] * self.vectors[sample][vector_entry] self.param_indices[sample] = param_index param_index += 1 data_i = self.normalisation[self.data_label] * data if not data == 0 and not x_i == 0: L = TMath.Poisson(data_i, x_i) lnL += TMath.log(L) vector_entry += 1 f[0] = -2.0 * lnL # Adding the QCD and V+jets constraints if self.constraint_type == "normalisation": f[0] += self.get_fit_normalisation_constraints(par)
if (mbb < mllbb) and (mllbb > 126.0): combine_cmd = "combine -M ProfileLikelihood --signif -m "+str(int(mbb))+" "+yield_path+" --toysFreq" #combine_cmd = "combine -M ProfileLikelihood --significance --pvalue -m "+str(int(mbb))+" "+yield_path try: file_path = MH_dir+"/higgsCombineTest.ProfileLikelihood.mA"+str(int(mbb))+".root" if run_combine == 1: os.system(str(combine_cmd)) cp_cmd = "cp higgsCombineTest.ProfileLikelihood.mH"+str(int(mbb))+".root "+file_path os.system(str(cp_cmd)) fList = TFile(str(file_path)) mytree = fList.Get("limit") for entry in mytree: print "p-value(",(i-1)*numDirs+(j-1) , ", " , int(mbb) , ", " , int(mllbb),") = ", mytree.limit n+=1 myTGraph.SetPoint(n, mbb, mllbb, mytree.limit) nSigma = tmath.sqrt(2)*tmath.ErfInverse(1-2*mytree.limit) print mbb, mllbb, mytree.limit, nSigma myTGraph_sigma.SetPoint(n, mbb, mllbb, nSigma) except: print 'no background events' mbb+=step_mbb print '##############################################' print 'mbb:', mbb, 'myTGraph size', myTGraph.GetN() print '##############################################' mllbb+=step_mllbb '''
def getHists(contained_only = False): # Define the desired energy ranges ERanges = [(0.3,0.5), (0.5,0.7), (0.7,0.9), (0.9,1.1), (1.1,1.3), (1.3,1.5), (1.5,1.7), (1.7,1.9), (1.9,2.1)] # Creating empty histograms hist_dictionary = {} for myE in ERanges: myName = "h_min%s_max%s" % (myE[0], myE[1]) if contained_only: myName = "cont_h_min%s_max%s" % (myE[0], myE[1]) myTitle = "Energies from %0.1f to %0.1f;(True p - Reco p) / True p;Entries" % (myE[0], myE[1]) if contained_only: myTitle = "Contained Tracks: Energies from %0.1f to %0.1f;(True p - Reco p) / True p;Entries" % (myE[0], myE[1]) hist_dictionary[myE] = TH1D(myName, myTitle, 100, -4, 4) # Loop over energy ranges to create graphs of type (2) for myE in ERanges: myPlot = "(true_mom - mcs_reco_mom) / true_mom >> h_min%0.1f_max%0.1f" % (myE[0], myE[1]) if contained_only: myPlot = "(true_mom - mcs_reco_mom) / true_mom >> cont_h_min%0.1f_max%0.1f" % (myE[0], myE[1]) myCut = "mcs_reco_mom > 0 && true_mom > %f && true_mom < %f" % (myE[0], myE[1]) if contained_only: myCut += " && mu_contained == 1" f.ana_tree.Draw(myPlot, myCut) # Create lists for graphs (3), (4) that will be filled in the next loop xpoints = [] filMeanVals, filSqrtHistEntries = [], [] filStdVals, filStdErrs = [], [] for myE in ERanges: # Filter out energy ranges with 0 entries if hist_dictionary[myE].GetEntries() != 0: xpoints.append(myE[0] + ( myE[1] - myE[0] ) / 2.) filMeanVals.append(hist_dictionary[myE].GetMean()) filSqrtHistEntries.append(TMath.sqrt(hist_dictionary[myE].GetEntries())) filStdVals.append(hist_dictionary[myE].GetRMS()) filStdErrs.append(hist_dictionary[myE].GetRMSError()) # Calculate error bars for graph (3): (stdDev / sqrt(entries)) yerrs = map(truediv, filStdVals, filSqrtHistEntries) # Define a constant width (x-error bar) for each marker xerrs = [( myE[1] - myE[0] ) / 2. for myE in ERanges] # Graph (3) and (4) setup meanGraph = TGraphErrors() stdGraph = TGraphErrors() meanGraphTitle = "Mean vs. Energy;True Muon Energy (GeV);#left[p_{MC}-p_{MCS} / p_{MC}#right]" if contained_only: meanGraphTitle = "Contained Tracks: Mean vs. Energy;True Muon Energy (GeV);#left[p_{MC}-p_{MCS} / p_{MC}#right]" stdGraphTitle = "Standard Deviation vs. Energy;True Muon Energy (GeV);Fractional Momentum Resolution" if contained_only: stdGraphTitle = "Contained Tracks: Standard Deviation vs. Energy;True Muon Energy (GeV);Fractional Momentum Resolution" meanGraph.SetTitle(meanGraphTitle) stdGraph.SetTitle(stdGraphTitle) # Fill in data for graph (3) for i in xrange(len(xpoints)): meanGraph.SetPoint(i, xpoints[i], filMeanVals[i]) meanGraph.SetPointError(i, xerrs[i], yerrs[i]) meanGraph.Draw("ALP") # Fill in data for graph (4) for i in xrange(len(xpoints)): stdGraph.SetPoint(i, xpoints[i], filStdVals[i]) stdGraph.SetPointError(i, xerrs[i], filStdErrs[i]) stdGraph.Draw("ALP") return hist_dictionary, meanGraph, stdGraph
from ROOT import TMath as tmath from ROOT import * #pvalue=1-0.682689492137086 pvalue = 0.003 sigma = tmath.sqrt(2)*tmath.ErfInverse(1-2*pvalue) print sigma
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 integrated_luminosity = config.integrated_luminosity 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(2222222) #gStyle.SetStatX(0.95) #gStyle.SetStatY(0.95) gStyle.SetOptStat(0000000) gStyle.SetOptFit(0000000) from ROOT import TFile, TCanvas, TMultiGraph, TLegend, TPaveText #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 print "Integrated luminosity: %d inv. pb" % integrated_luminosity # Fit for N in config.exclusive_multiplicities: hST = infile.Get("plots%dJets/ST" % N) hST.GetXaxis().SetNdivisions(510) if not options.isBatch: c = TCanvas("TemplateN%d" % N, "TemplateN%d" % N, 500, 500) canvas.book(c) formatST(hST) hST.SetTitle("") hST.Draw("e") hST.GetXaxis().SetRangeUser(fit_range[0], config.maxST) hST.GetYaxis().SetRangeUser(1e-2, 2e4) hST.GetYaxis().SetTitleOffset(1.25) hST.GetYaxis().SetTitleSize(0.04) hST.GetYaxis().SetLabelSize(0.04) hST.GetXaxis().SetTitleSize(0.04) hST.GetXaxis().SetLabelSize(0.04) c.SetLogy(1) for i,formula in enumerate(config.templates): print "formula %d" % (i) 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)) if i < 3: hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "QN0", "", 1800, 2800) hST.Fit(f, "N0", "", 1800, 2800) elif i == 0: hST.Fit(f, "Q0", "", fit_range[0], fit_range[1]) elif i > 2: 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]) 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() c.Print("TemplateN%d.pdf" % N) c.Print("TemplateN%d.png" % N) # 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 $\pm$ %.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.4244355,0.4241525,0.9395968,0.8652542) legend_shape.SetTextFont(42) legend_shape.SetFillColor(0) legend_shape.SetLineColor(0) legend_shape.SetTextSize(0.036) c = TCanvas("ShapeUncertaintyN2", "ShapeUncertaintyN2", 500, 500) canvas.book(c) gShapeUncertainty.Draw("AC3") gShapeUncertainty.GetXaxis().SetNdivisions(510) gShapeUncertainty.GetXaxis().SetRangeUser(fit_range[0], config.maxST) gShapeUncertainty.GetYaxis().SetRangeUser(5e-2, 5e6) 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") h.GetXaxis().SetNdivisions(510) if label == "histoTemplateN2_%d": N = 2 else: N = 3 legend_shape.AddEntry(h, "Parameterization %d (N = %d)" % (i, N), "l") store.get("Data_N2").Draw("esame") cmslabel = TPaveText(0.45,0.90,0.60,0.93,"brNDC") cmslabel.AddText(config.cmsTitle) #cmslabel.AddText(config.cmsSubtitle) cmslabel.SetFillColor(0) cmslabel.SetTextSize(0.041) cmslabel.Draw("plain") c.SetLogy(1) legend_shape.Draw("plain") c.Update() c.Print("ShapeUncertaintyN2.pdf") c.Print("ShapeUncertaintyN2.png") if isSaveOutput: store.saveAs(options.outputfile) if not options.isBatch: raw_input("Press Enter to continue...")
gen_type2 = TH1F("Generated_by_Type_2_Function","Generated_by_Type_2_Function", N, mass_low, mass_high) gen_type2.Sumw2() #Generate by type 1 for i in range(0,N): progress = 100.0*i/(1.0*N) k = TMath.FloorNint(progress) update_progress(k) r = TRandom1() mjj_y = func_type1.Integral(mass_low+i, mass_low+i+1) gen_type1.SetBinContent(i+1, r.Poisson(mjj_y)) gen_type1.SetBinError(i+1, TMath.Sqrt(gen_type1.GetBinContent(i+1))) print mjj_y, gen_type1.GetBinLowEdge(i+1), gen_type1.GetBinContent(i+1) mjj_y = func_type2.Integral(mass_low+i, mass_low+i+1) gen_type2.SetBinContent(i+1, r.Poisson(mjj_y)) gen_type2.SetBinError(i+1, TMath.sqrt(gen_type2.GetBinContent(i+1))) Canvas0 = TCanvas("Canvas0","Canvas0") gen_type1.Draw("E") func_type1.Draw("SAME") gen_type1.GetXaxis().SetRangeUser(mass_low-100, mass_high+100) gen_type1.GetXaxis().SetMoreLogLabels() gen_type1.GetXaxis().SetNoExponent() gPad.SetLogx() gPad.SetLogy() Canvas1 = TCanvas("Canvas1","Canvas1") gen_type2.Draw("E") func_type2.Draw("SAME") gen_type2.GetXaxis().SetRangeUser(mass_low-100, mass_high+100) gen_type2.GetXaxis().SetMoreLogLabels()