def limit(effErr): f=str(eff)+'_'+str(effErr) res={} keys = ['exp','1ms','2ms','1ps','2ps','obs'] for key in keys: res[key]=None print b,o if eff>0: os.mkdir(f) os.chdir(f) limit = r.LimitResult() r.roostats_cl95(lumi[0],lumi[1],eff,eff*effErr/100.,rnd(b[0],3),rnd(b[1],2),int(o[0]),False,0,'cls','',random.randint(0,1e7),limit) #limit=r.roostats_clm(lumi[0],lumi[1],rnd(eff,3),rnd(effErr*eff/100.,2),rnd(b[0],3),rnd(b[1],2),int(o[0]),False,1,'cls','',random.randint(0,1e7),limit) res['obs'] = limit.GetObservedLimit() res['exp'] = limit.GetExpectedLimit() res['1ms'] = limit.GetOneSigmaLowRange() res['2ms'] = limit.GetTwoSigmaLowRange() res['1ps'] = limit.GetOneSigmaHighRange() res['2ps'] = limit.GetTwoSigmaHighRange() os.system('rm ws.root') os.chdir('../') os.rmdir(f) pickle.dump(res,open(limDir+f,'w'))
def __init__(self,file): stream = open(file,'r') self._file = file self._weight = None self._mods = [] self._cutMods = [] for line in stream: if len(line.strip()) == 0 or line.strip()[0] == '#': continue while line.strip()[-1] == "\\": line = line.strip()[:-1] + stream.next() fields = [x.strip() for x in line.split(":")] if fields[0] == "weight": if self._weight is not None: raise RuntimeError, "Duplicate weight definition in fake rate file "+file self._weight = fields[1] elif fields[0] == "change": self._mods.append( SimpleCorrection(fields[1],fields[2]) ) elif fields[0] == "cut-change": self._cutMods.append( SimpleCorrection(fields[1],fields[2],onlyForCuts=True) ) elif fields[0] == "load-histo": data = "%s/src/CMGTools/TTHAnalysis/data/" % os.environ['CMSSW_BASE']; ROOT.loadFRHisto(fields[1],fields[2].replace("$DATA",data),fields[3] if len(fields) >= 4 else fields[1]) else: raise RuntimeError, "Unknown directive "+fields[0] if self._weight is None: raise RuntimeError, "Missing weight definition in fake rate file "+file if len(self._cutMods) == 0 is None: print "WARNING: no directives to change cuts in fake rate file "+file
def readPDGtable(self): """ Returns R data from PDG in a easy to use format """ ecm=r.vector('double')() ratio=r.vector('double')() """ecm,ratio = [],[]""" with open(os.path.expandvars('$FAIRSHIP/input/rpp2012-hadronicrpp_page1001.dat'),'r') as f: for line in f: line = line.split() try: numEcm = float(line[0]) numR = float(line[3]) strType = line[7] strBis = line[8] #if numEcm<2: # print numEcm,numR,strType if (('EXCLSUM' in strType) or ('EDWARDS' in strType) or ('BLINOV' in strType)): ecm.push_back(numEcm) ratio.push_back(numR) #print numEcm,numR,strType if 'BAI' in strType and '01' in strBis: ecm.push_back(numEcm) ratio.push_back(numR) #print numEcm,numR,strType except: continue return ecm,ratio
def compare(f1_name, f2_name, f3_name): f1 = ROOT.TFile.Open(f1_name, "read") f2 = ROOT.TFile.Open(f2_name, "read") f3 = ROOT.TFile.Open(f3_name, "read") bkg_f1 = f1.Get("hist_bkg_inclusive_13TeV__obs_x_channel") bkg_f2 = f2.Get("hist_bkg_inclusive_13TeV__obs_x_channel") bkg_f3 = f3.Get("bkg_total_gg_full") bkg_f3.Rebin(5) canvas = ROOT.TCanvas("canvas", "canvas", 600, 600) canvas.SetLogy() bkg_f1.SetLineColor(2) bkg_f2.SetLineColor(8) bkg_f3.SetLineColor(4) bkg_f1.SetMarkerSize(0) bkg_f2.SetMarkerSize(0) bkg_f3.SetMarkerSize(0) h_bkgs = ROOT.TList() h_bkgs.Add(bkg_f1) h_bkgs.Add(bkg_f2) c1 = ROOT.add_ratio_pad(bkg_f3, bkg_f2) c1.SetLogy() bkg_f2.Draw("") bkg_f3.Draw("same") legend = ROOT.myLegend(0.7, 0.8, 0.9, 0.9) #legend.AddEntry( bkg_f1, "nominal v4", "L") legend.AddEntry( bkg_f2, "nominal v5", "L") legend.AddEntry( bkg_f3, "nominal LIN", "L") legend.Draw() canvas.SaveAs("test.pdf")
def compare_ws_hist(f1_name, f2_name): f1 = ROOT.TFile.Open(f1_name, "read") ## workspace f2 = ROOT.TFile.Open(f2_name, "read") if not f1 or not f2: return None bkg_f2 = f2.Get("bkg_total_gg_full") #bkg_f2.Rebin(5) ws = f1.Get("combined") pdf = ws.obj("channel_model") obs = ws.var("obs_x_channel") obs.setRange(200, 5000) nbins = 960 bkg_f1 = pdf.createHistogram("bkg_f1", obs, ROOT.RooFit.Binning(nbins)) print bkg_f1.Integral(), bkg_f2.Integral() bkg_f1.Scale(bkg_f2.Integral()/bkg_f1.Integral()) bkg_f1.SetLineColor(2) bkg_f2.SetLineColor(4) bkg_f1.SetMarkerSize(0) bkg_f2.SetMarkerSize(0) canvas = ROOT.TCanvas("canvas", "canvas", 600, 600) #canvas.SetLogy() c1 = ROOT.add_ratio_pad(bkg_f2, bkg_f1) c1.SetLogy() bkg_f1.Draw() bkg_f2.Draw("same") legend = ROOT.myLegend(0.7, 0.8, 0.9, 0.9) legend.AddEntry( bkg_f1, "workspace", "L") legend.AddEntry( bkg_f2, "input hist", "L") legend.Draw() canvas.SaveAs(f1_name.replace("root", "pdf"))
def compare_hists(f1_name, f2_name, hist_name): f1 = ROOT.TFile.Open(f1_name, "read") # Data f2 = ROOT.TFile.Open(f2_name, "read") # MC h1 = f1.Get(hist_name) #if "v7" in f1_name: #h2.Rebin(5) if "solation" in f2_name: if "_extend" in f2_name: h2 = f2.Get("h_isoshape") else: h2 = f2.Get("up") elif "irreducible" in hist_name: h2 = f2.Get("hreluncert_irreducible") else: h2 = f2.Get(hist_name) print "binning: ", h1.GetNbinsX(), h2.GetNbinsX() print h2.GetName() sys_name = hist_name.split('_')[1] factor = 1.0 is_log = False if "bkg_total_gg_full" in hist_name: is_log = True factor = h1.Integral()/h2.Integral() print "intergral: ", h1.Integral(), h2.Integral(), factor h2.Scale(factor) h1.SetMarkerSize(0) h2.SetMarkerSize(0) ROOT.compare_two_hists(h1, h2, #"Isolation [GeV]", "m_{#gamma#gamma} [GeV]", sys_name+" from ws", sys_name+" from original input", is_log) f1.Close() f2.Close()
def hit2wire(self, ahit): wl = ShipGeo.straw.length detname = self.vols[ ahit.GetDetectorID() - 1 ].GetName() # don't know why -1 is needed, should not, but ... TR 31.5.2014 nd = self.layerType[detname] nrwire = int((ahit.GetX() - self.detinfo[nd]["firstWire"]) / self.detinfo[nd]["pitch"] + 0.5) xwire = nrwire * self.detinfo[nd]["pitch"] + self.detinfo[nd]["firstWire"] # rotate top/bot of wire in xy plane around true hit over angle.. xt, yt = self.dorot(xwire, wl, ahit.GetX(), ahit.GetY(), self.detinfo[nd]["stereoAngle"]) xb, yb = self.dorot(xwire, -wl, ahit.GetX(), ahit.GetY(), self.detinfo[nd]["stereoAngle"]) # distance to wire, and smear it. dw = ROOT.fabs(ahit.GetX() - xwire) smear = ROOT.fabs(self.random.Gaus(dw, self.detinfo[nd]["resol"])) smearedHit = { "mcHit": ahit, "xtop": xt, "ytop": yt, "z": ahit.GetZ(), "xbot": xb, "ybot": yb, "z": ahit.GetZ(), "dist": smear, } return smearedHit
def __init__(self, folder, decaymode, plotsdir, g1=1, g2=0, g4=0, g1L1=0, nbins=80, mPOLE=750., useTaus=False): self.files = [os.path.join(folder, file) for file in os.listdir(folder)] self.decaymode = decaymode assert self.decaymode in self.validdecaymodes self.plotsdir = plotsdir if os.path.exists(plotsdir) and os.listdir(plotsdir): return mkdir_p(plotsdir) open(os.path.join(plotsdir, "index.php"), "w") self.g1 = g1 self.g2 = g2 self.g4 = g4 self.g1L1 = g1L1 self.nbins = nbins self.mPOLE = mPOLE self.useTaus = useTaus # def __enter__(self): self.tmpdir = tempfile.mkdtemp() self.cinput = os.path.join(self.tmpdir, "{}.root".format(decaymode)) os.symlink(os.path.abspath(self.files[0]), self.cinput) os.symlink(os.path.abspath(plotsdir), os.path.join(self.tmpdir, "Validation")) self.morecinputs = ROOT.std.vector(ROOT.std.string)() for f in self.files[1:]: self.morecinputs.push_back(f) self.args = self.cinput, self.g1.real, self.g2.real, self.g4.real, self.g1L1.real, self.g2.imag, self.g4.imag, self.g1L1.imag, self.nbins, self.mPOLE, self.useTaus, self.morecinputs self.incontextmanager = True # def __call__(self): # if not self.incontextmanager: # raise RuntimeError("Can only call AngularDistributions within context manager!") ROOT.angularDistributions_spin0_ggH(*self.args)
def check_type_conversion(self): s = ROOT.TString(self.test_str) # Works with TString... self.assertEqual(ROOT.myfun(s), self.test_str) # ... and Python string self.assertEqual(ROOT.myfun(self.test_str), self.test_str)
def _createFWLiteEvent (self): """(Internal) Creates an FWLite Event""" self._veryFirstTime = False self._toBegin = True if isinstance (self._filenames[0], ROOT.TFile): self._event = ROOT.fwlite.Event (self._filenames[0]) self._mode = 'single' return self._mode if len (self._filenames) == 1 and self._forceEvent: self._tfile = ROOT.TFile.Open (self._filenames[0]) self._event = ROOT.fwlite.Event (self._tfile) self._mode = 'single' return self._mode filenamesSVec = ROOT.vector("string") () for name in self._filenames: filenamesSVec.push_back (name) if self._secondaryFilenames: secondarySVec = ROOT.vector("string") () for name in self._secondaryFilenames: secondarySVec.push_back (name) self._event = ROOT.fwlite.MultiChainEvent (filenamesSVec, secondarySVec) self._mode = 'multi' else: self._event = ROOT.fwlite.ChainEvent (filenamesSVec) self._mode = 'chain' return self._mode
def plotROCEtaEABins(self,name,radius,rhovar,eaname,selsig,selbkg,etabins): ROOT.loadEAHisto("EA_el","%s/EA.root" % self.options.printDir,eaname+"_el") ROOT.loadEAHisto("EA_mu","%s/EA.root" % self.options.printDir,eaname+"_mu") hsig1d = ROOT.TH1D("hsig","hsig",2000,0,10) hbkg1d = ROOT.TH1D("hbkg","hbkg",2000,0,10) hist1d = ROOT.TH1D("frame","frame;Eff(background);Eff(signal)",100,0.,0.319) hist1d.GetYaxis().SetRangeUser(0.4,1.019) for i in xrange(1,len(etabins)): etamin, etamax = etabins[i-1], etabins[i] myname = "%s_eta_%.3f_%.3f" % (name, etamin, etamax) mysig = "(%s) && %f <= abs(LepGood_eta) && abs(LepGood_eta) < %f" % (selsig,etamin,etamax) mybkg = "(%s) && %f <= abs(LepGood_eta) && abs(LepGood_eta) < %f" % (selbkg,etamin,etamax) isoc="(LepGood_chargedHadRelIso{R}+eaCorr(LepGood_absRawNeutralIso{R},LepGood_pdgId,LepGood_eta,{rho})/LepGood_pt)".format(R=radius,rho=rhovar) isou="(LepGood_chargedHadRelIso{R}+LepGood_absRawNeutralIso{R}/LepGood_pt)".format(R=radius) isod="(LepGood_chargedHadRelIso{R}+max(LepGood_absRawNeutralIso{R}-0.5*LepGood_puIso{R},0)/LepGood_pt)".format(R=radius) self.tree.Draw("%s>>hsig" % isoc, mysig, "goff") self.tree.Draw("%s>>hbkg" % isoc, mybkg, "goff") rocc = hist2ROC1d(hsig1d,hbkg1d) self.tree.Draw("%s>>hsig" % isou, mysig, "goff") self.tree.Draw("%s>>hbkg" % isou, mybkg, "goff") rocu = hist2ROC1d(hsig1d,hbkg1d) self.tree.Draw("%s>>hsig" % isod, mysig, "goff") self.tree.Draw("%s>>hbkg" % isod, mybkg, "goff") rocd = hist2ROC1d(hsig1d,hbkg1d) hist1d.Draw() rocd.SetLineWidth(3) rocu.SetLineWidth(3) rocc.SetLineWidth(3) rocd.SetLineColor(ROOT.kRed-4); rocu.SetLineColor(ROOT.kGray+1); rocc.SetLineColor(ROOT.kBlue+1); rocu.Draw("L SAME"); rocd.Draw("L SAME"); rocc.Draw("L SAME"); self.c1.Print("%s/%s.png" % (self.options.printDir, myname) );
def getMorphedShape(name, node0, node1, val): # use a linear interpolation NIM A 425 (1999) 357-360 # for 2D distributions do this for each projection in Y if node0[1].InheritsFrom("TH2"): h = node0[1].Clone(name) maxbins = ROOT.TMath.Min(node0[1].GetYaxis().GetNbins(), node1[1].GetYaxis().GetNbins()) + 1 for ybin in xrange(1, maxbins): px0 = node0[1].ProjectionX("px0", ybin, ybin) px1 = node1[1].ProjectionX("px1", ybin, ybin) newNorm = linearYieldExtrapolation((node0[0], px0), (node1[0], px1), val) if newNorm > 0: pxint = ROOT.th1fmorph("pxint", "pxint", px0, px1, node0[0], node1[0], val, newNorm) for xbin in xrange(1, pxint.GetXaxis().GetNbins() + 1): h.SetBinContent(xbin, ybin, pxint.GetBinContent(xbin)) h.SetBinError(xbin, ybin, pxint.GetBinError(xbin)) pxint.Delete() px0.Delete() px1.Delete() else: newNorm = linearYieldExtrapolation(node0, node1, val) h = ROOT.th1fmorph(name, name, node0[1], node1[1], node0[0], node1[0], val, newNorm) h.SetDirectory(0) # all done return h
def reportCache(self) : r.gROOT.ProcessLine(".L %s/cpp/tdrstyle.C"%whereami()) r.setTDRStyle() r.gStyle.SetPalette(1) hists = self.setup() if not hists : print '%s.setup() failed'%self.name return fileName = '/'.join(self.outputFileName.split('/')[:-1]+[self.name]) + '.pdf' c = r.TCanvas() c.Print(fileName +'[') for h in hists.values() + [self.LR]: h.UseCurrentStyle() h.SetTitle(';'+self.label) h.SetLineWidth(2) hists['correct'].SetLineColor(r.kRed) hists['correct'].Draw('hist') hists['incorrect'].Draw('hist same') c.Print(fileName) self.LR.SetTitle(";%s;Likelihood Ratio, Correct:Incorrect"%self.label) self.LR.SetMinimum(0) self.LR.Draw('hist') c.Print(fileName) c.Print(fileName +']') print 'Wrote : %s'%fileName
def reportCache(self) : optstat = r.gStyle.GetOptStat() r.gStyle.SetOptStat(0) r.gROOT.ProcessLine(".L %s/cpp/tdrstyle.C"%whereami()) r.setTDRStyle() r.tdrStyle.SetPadRightMargin(0.2) r.gStyle.SetPalette(1) self.setup() fileName = '/'.join(self.outputFileName.split('/')[:-1]+[self.name]) sigmas = r.TH2D("sigmas","Contours of Integer Sigma, Gaussian Approximation;%s;%s"%self.labelsXY, *(self.binningX+self.binningY)) for iX in range(1,1+sigmas.GetNbinsX()) : for iY in range(1,1+sigmas.GetNbinsY()) : xy = (sigmas.GetXaxis().GetBinCenter(iX), sigmas.GetYaxis().GetBinCenter(iY), 1) sigmas.SetBinContent(iX, iY, math.sqrt( np.dot(xy, np.dot(self.matrix, xy) ) ) ) sigmas.SetContour(6, np.array([0.1]+range(1,6),'d')) c = r.TCanvas() c.Print(fileName+'.pdf[') sigmas.Draw("cont3") c.Print(fileName+'.pdf') if self.xy : self.xy.UseCurrentStyle() self.xy.Draw('colzsame') sigmas.Draw('cont3same') c.Print(fileName+'.pdf') if hasattr(self,'xySup') : self.xySup.UseCurrentStyle() self.xySup.Draw('colz') sigmas.Draw('cont3same') c.Print(fileName+'.pdf') c.Print(fileName+'.pdf]') print 'Wrote : %s.pdf'%fileName r.gStyle.SetOptStat(optstat)
def beginLoop(self, setup): super(TriggerBitAnalyzer,self).beginLoop(setup) self.triggerBitCheckers = [] if self.unrollbits : self.allPaths = set() self.triggerBitCheckersSingleBits = [] for T, TL in self.cfg_ana.triggerBits.iteritems(): trigVec = ROOT.vector(ROOT.string)() for TP in TL: trigVec.push_back(TP) if self.unrollbits : if TP not in self.allPaths : self.allPaths.update([TP]) trigVecBit = ROOT.vector(ROOT.string)() trigVecBit.push_back(TP) outname="%s_BIT_%s"%(self.outprefix,TP) if not hasattr(setup ,"globalVariables") : setup.globalVariables = [] if outname[-1] == '*' : outname=outname[0:-1] setup.globalVariables.append( NTupleVariable(outname, eval("lambda ev: ev.%s" % outname), int, help="Trigger bit %s"%TP) ) if self.saveIsUnprescaled or self.force1prescale: setup.globalVariables.append( NTupleVariable(outname+'_isUnprescaled', eval("lambda ev: ev.%s_isUnprescaled" % outname), int, help="Trigger bit %s isUnprescaled flag"%TP) ) if self.saveIsUnprescaled or self.force1prescale: setup.globalVariables.append( NTupleVariable(outname+'_Prescale', eval("lambda ev: ev.%s_Prescale" % outname), int, help="get prescale %s "%TP) ) self.triggerBitCheckersSingleBits.append( (TP, ROOT.heppy.TriggerBitChecker(trigVecBit)) ) outname="%s_%s"%(self.outprefix,T) if not hasattr(setup ,"globalVariables") : setup.globalVariables = [] setup.globalVariables.append( NTupleVariable(outname, eval("lambda ev: ev.%s" % outname), int, help="OR of %s"%TL) ) if self.saveIsUnprescaled or self.force1prescale: setup.globalVariables.append( NTupleVariable(outname+'_isUnprescaled', eval("lambda ev: ev.%s_isUnprescaled" % outname), int, help="OR of %s is Unprescaled flag"%TL) ) self.triggerBitCheckers.append( (T, ROOT.heppy.TriggerBitChecker(trigVec)) )
def read_ntuple(filename="test.root", treename="Events"): stream = itreestream(filename, treename) stream.ls() # declare variables to receive data # note variable length arrays are mapped to STL vectors and # note that here the type differs (float) from that stored # in the ntuple (double) HT = c_double() ET = rt.vector("float")(20) comment = rt.string(80*' ') # select which variables (branches) to # read and where to copy their data. stream.select("jetEt", ET) stream.select("comment", comment) stream.select("HT", HT) entries = stream.entries() step = 200 for entry in range(entries): # read event into memory stream.read(entry) if entry % step == 0: print "%5d%5d%10.2f (%s)" % (entry, ET.size(), HT.value, comment) stream.close()
def setupTdrStyle() : r.gROOT.ProcessLine(".L cpp/tdrstyle.C") r.setTDRStyle() #tweaks r.tdrStyle.SetPadRightMargin(0.06) r.tdrStyle.SetErrorX(r.TStyle().GetErrorX()) r.gStyle.SetPalette(1)
def style(filename): if os.path.lexists(filename): ROOT.gROOT.ProcessLine(".L {0}".format(filename)) ROOT.setTDRStyle() print("Loaded ROOT style from: " + filename) else: print("ROOT style is not available: " + filename, file = sys.stderr)
def s_inv_m(chain): pt0 = getValue(chain, "top_m0_pt") pz0 = getValue(chain, "top_m0_pz") pt1 = getValue(chain, "top_m1_pt") pz1 = getValue(chain, "top_m1_pz") xa = ROOT.sqrt(pt0 * pt0 + pz0 * pz0) / 3500 xb = ROOT.sqrt(pt1 * pt1 + pz1 * pz1) / 3500 return xa * xb * 7000 ** 2
def compare_ws_ws(f1_name, f2_name): f1 = ROOT.TFile.Open(f1_name, "read") ## workspace f2 = ROOT.TFile.Open(f2_name, "read") ## mine if not f1 or not f2: return None #f3_name = "Bkg_Total_allcat_TOPO_PTDEP_8.0_lead50_sublead50_norm17_62_linear.root" f3_name = "BkgEstimation_Lin/BkgEstimation_NONE_TOPO_PTDEP_HKHI_Lin.root" f3 = ROOT.TFile.Open(f3_name, "read") bkg_f3_org = f3.Get("bkg_total_gg_full").Rebin(5) bkg_f3 = new_sys.truncate_hist(bkg_f3_org, "bkg_f3") f4_name = "ruggero_template/BkgEstimation_NONE_NONE_TOPO_PTDEP_HKHI_Lin.root" f4 = ROOT.TFile.Open(f4_name, "read") bkg_f4 = f4.Get("bkg_total_gg_full") ws1 = f1.Get("combined") ws2 = f2.Get("combined") bkg_f1 = create_hist_from_ws(ws1, "channel", "bkg_f1") #bkg_f2 = create_hist_from_ws(ws2, "chan_8TeV", "bkg_f2") bkg_f2 = create_hist_from_ws(ws2, "chan_HKHI_13TeV", "bkg_f2") bkg_f1.Scale(bkg_f2.Integral()/bkg_f1.Integral()) bkg_f3.Scale(bkg_f2.Integral()/bkg_f3.Integral()) bkg_f4.Scale(bkg_f2.Integral()/bkg_f4.Integral()) bkg_f1.SetLineColor(2) bkg_f2.SetLineColor(4) bkg_f4.SetLineColor(8) bkg_f1.SetMarkerSize(0) bkg_f2.SetMarkerSize(0) bkg_f3.SetMarkerSize(0) bkg_f4.SetMarkerSize(0) print bkg_f1.GetNbinsX(),bkg_f2.GetNbinsX(),bkg_f3.GetNbinsX(),bkg_f4.GetNbinsX() canvas = ROOT.TCanvas("canvas", "canvas", 600, 600) #canvas.SetLogy() h_bkgs = ROOT.TList() h_bkgs.Add(bkg_f1) h_bkgs.Add(bkg_f2) h_bkgs.Add(bkg_f4) c1 = ROOT.add_ratio_pad(bkg_f3, h_bkgs) c1.SetLogy() bkg_f1.Draw() bkg_f2.Draw("same") bkg_f3.Draw("same") bkg_f4.Draw("same") legend = ROOT.myLegend(0.7, 0.8, 0.9, 0.9) legend.AddEntry( bkg_f1, "Rugero", "L") legend.AddEntry( bkg_f2, "XY", "L") legend.AddEntry( bkg_f3, "input hist", "L") legend.AddEntry( bkg_f4, "new hist", "L") legend.Draw() canvas.SaveAs(f1_name.replace("root", "pdf"))
def run_egammaMVACalibMulti(outputfile, inputTree, inputPath, useTMVA, method, particleType, calibrationType, nEvents, branchName, copyBranches='input', shift=0, fudge=False, debug=False, etaBinDef = '', energyBinDef = '', particleTypeVar='', filePattern='', ignoreSpectators=True, interact=False, friend = False, defs=None): """run_egammaMVACalibMulti(outputfile, inputTree, inputPath, useTMVA, method, particleType, calibrationType, nEvents, branchName, copyBranches='input', shift=0, fudge=False, debug=False, etaBinDef = '', energyBinDef = '', particleTypeVar='', filePattern='', ignoreSpectators=True, interact=False, friend = False, defs=None)""" print "Running egammaMVACalibMulti" # Convert all the inputs to lists and make sure all the lists have the same size # (lists that have size 1 are multiplied by N, the maximum size) iter_options = map(make_list, (inputPath, useTMVA, method, calibrationType, shift, defs)) N = max(len(i) for i in iter_options) if any(len(i) not in (1, N) for i in iter_options): raise ValueError("Invalid input: %s" % iter_options) iter_options = (make_list(i[0], N) if len(i) == 1 else i for i in iter_options) loop = zip(*iter_options) # print loop if len(loop) != len(branchName): raise ValueError("Multiple options passed, branchName must have %s values, got %s" % \ (len(loop), len(branchName)) ) if len(set(branchName)) != len(branchName): raise ValueError("Repeated values for branchName: %s" % branchName) import ROOT loadLibs() M = ROOT.egammaMVACalibMulti(particleType, inputTree, copyBranches) for i,j in enumerate(loop): inputPath, useTMVA, method, calibrationType, shift, defs = j if fudge is None: print ROOT.gSystem.WorkingDirectory() params = particleType, not useTMVA, inputPath, method, calibrationType, debug, \ etaBinDef, energyBinDef, particleTypeVar, filePattern, ignoreSpectators if fudge is None: m = ROOT.egammaMVACalib(*params) else: m = ROOT.egammaMVACalibFudge(fudge, *params) setDefinitions(m, defs) M.Add(m, branchName[i]) if shift is not None and shift >= 0: M.GetInstance().setPeakCorrection(shift) if interact: doInteract(**locals()) return fout = ROOT.TFile(outputfile, 'update') mvaTree = M.Run(nEvents) mvaTree.Print() if friend: mvaTree.AddFriend(inputTree) mvaTree.Write('', ROOT.TObject.kOverwrite) fout.Close()
def plotLimit(self,options,coup,tfile): ## TGraphAsymmErrors *theBand(TFile *file, int doSyst, int whichChannel, BandType type, double width=0.68) { if options.asimov_expected: ROOT.use_precomputed_quantiles = True bandType = ROOT.Median else: bandType = ROOT.Median expected68 = ROOT.theBand( tfile, 1, 0, bandType, 0.68 ) expected95 = ROOT.theBand( tfile, 1, 0, bandType, 0.95 ) observed = ROOT.theBand( tfile, 1, 0, ROOT.Observed, 0.95 ) unit = "fb" if options.use_fb else "pb" basicStyle = [["SetMarkerSize",0.6],["SetLineWidth",3], ["SetTitle",";m_{G} (GeV);95%% C.L. limit #sigma(pp#rightarrow G#rightarrow#gamma#gamma) (%s)" % unit]] commonStyle = [[self.scaleByXsec,coup],"Sort"]+basicStyle ## expectedStyle = commonStyle+[["SetMarkerStyle",ROOT.kOpenCircle]] expectedStyle = commonStyle+[["SetMarkerSize",0]] observedStyle = commonStyle+[["SetMarkerStyle",ROOT.kFullCircle]] style_utils.apply( expected68, [["colors",ROOT.kYellow],["SetName","expected68_%s"%coup]]+expectedStyle ) style_utils.apply( expected95, [["colors",ROOT.kGreen],["SetName","expected95_%s"%coup]]+expectedStyle ) expected = ROOT.TGraph(expected68) style_utils.apply( expected, [["colors",ROOT.kBlack],["SetLineStyle",7],["SetName","expected_%s"%coup]]) style_utils.apply(observed,[["SetName","observed_%s"%coup]]+observedStyle) canv = ROOT.TCanvas("limits_k%s"%coup,"limits_k%s"%coup) canv.SetLogx() legend = ROOT.TLegend(0.6,0.6,0.9,0.9) expected95.Draw("AE3") expected95.GetXaxis().SetRangeUser(450,5500) expected95.GetXaxis().SetMoreLogLabels() expected68.Draw("E3L") expected.Draw("L") kappa = "0."+coup[1:] legend.AddEntry(None,"#tilde{#kappa} = %s" % kappa,"") legend.AddEntry(expected,"Expected limit","l") legend.AddEntry(expected68," \pm 1 \sigma","f") legend.AddEntry(expected95," \pm 2 \sigma","f") if options.unblind: observed.Draw("PL") ## observed.Draw("L") legend.AddEntry(observed,"Observed limit","l") if coup in self.xsections_: grav = self.xsections_[coup] style_utils.apply( grav, basicStyle+[["SetLineStyle",9],["colors",ROOT.myColorB2]] ) grav.Draw("L") legend.AddEntry(grav,"G_{RS}#rightarrow#gamma#gamma (LO)","l").SetLineStyle(0) self.keep(legend,True) legend.Draw() self.graphs.extend([observed,expected,expected68,expected95]) self.keep( [canv,observed,expected,expected68,expected95] ) self.format(canv,options.postproc)
def reportCache(self) : optStat = r.gStyle.GetOptStat() r.gStyle.SetOptStat(0) r.gROOT.ProcessLine(".L %s/cpp/tdrstyle.C"%whereami()) r.setTDRStyle() r.tdrStyle.SetPadRightMargin(0.06) self.setup(None) if not self.hists : print '%s.setup() failed'%self.name r.gStyle.SetOptStat(optStat) return fileName = '/'.join(self.outputFileName.split('/')[:-1]+[self.name]) + '.pdf' c = r.TCanvas() c.Print(fileName +'[') stamp = r.TText() ssize = stamp.GetTextSize() for f in 'BQN' : leg = r.TLegend(0.31,0.65,0.9,0.95) #leg.SetHeader("#eta range") leg.SetFillColor(r.kWhite) leg.SetBorderSize(0) leg.SetTextFont(42) for i,(color,style) in enumerate(zip([r.kBlack,r.kRed,r.kBlue],[1,7,8])) : h = self.hists[f+str(i)] label = h.GetTitle().split(',')[1].replace("0.000<","").replace("<"," < ") letter = h.GetTitle().split(',')[0] h.SetTitle(';#lower[0.2]{p_{#lower[-0.25]{T}}^{meas} (GeV)};#lower[-0.15]{Median log(E^{#lower[0.4]{gen}}/E^{#lower[0.4]{meas}})}') h.SetLineColor(color) h.SetLineStyle(style) h.SetLineWidth(3 if style!=1 else 2) h.SetMaximum(0.2) h.SetMinimum(-0.2) h.Draw("histsame" if i else "hist") stamp.SetTextFont(42) stamp.SetTextSize(ssize) stamp.DrawTextNDC(0.2,0.2, {'B':'Jets from b quark hadronization', 'Q':'Jets from W boson decay', 'N':'Other jets'}[letter]) leg.AddEntry(h,label,'l') leg.Draw() r.gPad.RedrawAxis() stamp.SetTextFont(62) stamp.SetTextSize(ssize) stamp.DrawTextNDC(0.16 ,0.96,"CMS") stamp.SetTextFont(52) stamp.SetTextSize(0.8 * ssize) stamp.DrawTextNDC(0.27, 0.96, "Simulation") stamp.SetTextFont(42) stamp.SetTextSize(ssize) stamp.DrawTextNDC(0.8, 0.96, "(8 TeV)") c.Print(fileName) c.Print(fileName +']') print 'Wrote : %s'%fileName r.gStyle.SetOptStat(optStat)
def set_style(self, plotData): super(PlotRoot, self).set_style(plotData) # load TDR Style cwd = os.getcwd() ROOT.gROOT.LoadMacro(os.path.expandvars("$ARTUSPATH/HarryPlotter/python/utility/tdrstyle.C")) # +"+") # compilation currently does not work ROOT.setTDRStyle() # load custom painter (fixes for horizontal histograms) ROOT.gROOT.LoadMacro(os.path.expandvars("$ARTUSPATH/HarryPlotter/python/utility/customhistogrampainter.C+"))
def scan_confidence_value_space_for_model(self, model, model_amplitude, variables, number_of_events, number_iterations, cl): print_level = -1 if self.debug: print_level = 1 confidence_value = ROOT.TMath.ChisquareQuantile(cl, 1) # Save the values of the parameters to reset at the end var_cache = ROOT.ostringstream() model.getVariables().writeToStream(var_cache, False) # Generate the data, use Extended flag # because the number_of_events is just # an expected number. # Generate the full set here, because we want to # make sure it's with the correct model distribution ROOT.RooTrace.active(True) # Perform the fit and find the limits list_of_values = [] iter = 1 for iter in range(number_iterations): if self.debug: self.logging("Iteration: %i of %i" % (iter+1, number_iterations)) data_model = model.generate(variables, ROOT.RooFit.NumEvents(number_of_events), ROOT.RooFit.Extended(), ROOT.RooFit.Name("Data_" + str(iter))) get_val = self.find_confidence_value_for_model( model, data_model, model_amplitude, confidence_value/2, print_level) model.getVariables().readFromStream(ROOT.istringstream(var_cache.str()), False) data_model.IsA().Destructor(data_model) if get_val is None: # There was an error somewhere downstream # or an interrupt was signalled # Get out break # Store the results list_of_values.append(get_val) # Reset the variables return list_of_values
def reportCache(self) : optStat = r.gStyle.GetOptStat() r.gStyle.SetOptStat(0) r.gROOT.ProcessLine(".L %s/cpp/tdrstyle.C"%whereami()) r.setTDRStyle() self.setup(None) for hist in filter(None,self.histsBQN) : hist.Scale(1./hist.Integral(0,hist.GetNbinsX()+1)) if None in self.histsBQN : print '%s.setup() failed'%self.name r.gStyle.SetOptStat(optStat) return fileName = '/'.join(self.outputFileName.split('/')[:-1]+[self.name]) + '.pdf' c = r.TCanvas() c.Print(fileName +'[') leg = r.TLegend(0.18,0.45,0.95,0.75) #leg.SetHeader("jet flavor") leg.SetFillColor(r.kWhite) leg.SetBorderSize(0) leg.SetTextFont(42) for h in self.histsBQN : h.Fill(h.GetBinCenter(1), h.GetBinContent(0)) h.SetBinContent(0,0) height = 1.1 * max(h.GetMaximum() for h in self.histsBQN) for i,(f,color,style) in enumerate(zip('BQN',[r.kBlack,r.kRed,r.kBlue],[1,7,8])) : h = self.histsBQN[i] h.UseCurrentStyle() h.SetTitle(";%s;Probability / %.2f"%(h.GetXaxis().GetTitle().split()[0].replace('jet',''),(self.binning[2]-self.binning[1]) / self.binning[0])) h.SetLineColor(color) h.SetLineWidth(2 if style==1 else 3) h.SetLineStyle(style) h.SetMaximum(height) h.SetMinimum(0) h.Draw("hist" + ("same" if i else "")) leg.AddEntry(h,{"B":"Jets from b quark hadronization","Q":"Jets from W boson decay","N":"Other jets"}[f],'l') leg.Draw() r.gPad.RedrawAxis() stamp = r.TText() ssize = stamp.GetTextSize() stamp.SetTextFont(62) stamp.SetTextSize(ssize) stamp.DrawTextNDC(0.20 ,0.88,"CMS") stamp.SetTextFont(52) stamp.SetTextSize(0.8 * ssize) stamp.DrawTextNDC(0.20, 0.83, "Simulation") stamp.SetTextFont(42) stamp.SetTextSize(ssize) stamp.DrawTextNDC(0.84, 0.96, "(8 TeV)") c.Print(fileName) c.Print(fileName +']') print 'Wrote : %s'%fileName r.gStyle.SetOptStat(optStat)
def make_graphs(infile, det, mva_branch, eregions, blockSize): """Fills, fits and visualizes distributions of Etrue/Erec. Results are cached into file. """ # return cached results, if any fname = os.path.basename(infile).replace('.root', '') fmt = 'output/cache/draw_results_{0}_{1}_{2}_{3}.pkl' cachefile = fmt.format(fname, det, mva_branch, blockSize) if os.access(cachefile, os.R_OK): with open(cachefile, 'rb') as f: return pickle.load(f) # fill necessary arrays of points in C++ friend = 'output/friend_{0}.root'.format(fname) ROOT.fill_arrays(infile, friend, mva_branch, True if det == 'EE' else False) # resolution vs mcE title = 'mcE_{0}_{1}_{2}'.format(fname, det, mva_branch) ROOT.fit_slices(0, blockSize, title, 'E^{gen}') grMeanE = ROOT.grMean.Clone() grSigmaE = ROOT.grSigma.Clone() # resolution vs mcPt title = 'mcPt_{0}_{1}_{2}'.format(fname, det, mva_branch) ROOT.fit_slices(1, blockSize, title, 'p_{T}^{gen}') grMeanPt = ROOT.grMean.Clone() grSigmaPt = ROOT.grSigma.Clone() # resolution vs mcEta in energy ranges grMeanEta = [] grSigmaEta = [] for (e1, e2) in eregions: title = 'mcEta_{0}_{1}_{2}_E{3}-{4}'.format(fname, det, mva_branch, e1, e2) ROOT.fit_slices(2, blockSize, title, '#eta^{gen}', e1, e2) grMeanEta.append(ROOT.grMean.Clone()) grSigmaEta.append(ROOT.grSigma.Clone()) # resolution vs nVtx in energy ranges grMeanVtx = [] grSigmaVtx = [] for (e1, e2) in eregions: title = 'nVtx_{0}_{1}_{2}_E{3}-{4}'.format(fname, det, mva_branch, e1, e2) ROOT.fit_slices(3, blockSize, title, 'nVtx', e1, e2) grMeanVtx.append(ROOT.grMean.Clone()) grSigmaVtx.append(ROOT.grSigma.Clone()) result = (grMeanE, grSigmaE, grMeanPt, grSigmaPt, grMeanEta, grSigmaEta, grMeanVtx, grSigmaVtx) # save cache with open(cachefile, 'wb') as f: pickle.dump(result, f) return result
def run_egammaMVACalib(outputfile, inputTree, inputPath='egammaMVACalib/offline/v3', useTMVA='', particleType=0, method='BDTG', calibrationType=1, nEvents=-1, debug=False, printBranches=False, branchName="", copyBranches="input", shift=0, fudge=None, etaBinDef='', energyBinDef='', particleTypeVar= '', filePattern="", ignoreSpectators = True, interact=False, first_event=0, friend=False, defs=None): """run_egammaMVACalib(outputfile, inputTree, inputPath='egammaMVACalib/offline/v3', useTMVA='', particleType=0, method='BDTG', calibrationType=1, nEvents=-1, debug=False, printBranches=False, branchName="", copyBranches="input", shift=0, fudge=None, etaBinDef='', energyBinDef='', particleTypeVar= '', filePattern="", ignoreSpectators = True, interact=False, first_event=0, friend=False, defs=None)""" iter_options = inputPath, useTMVA, method, calibrationType, shift, branchName, defs if any(isinstance(i, (list,tuple)) and len(i) > 1 for i in iter_options): inputPath, useTMVA, method, calibrationType, shift, branchName, defs = iter_options return run_egammaMVACalibMulti(outputfile, inputTree, inputPath, useTMVA, method, particleType, calibrationType, nEvents, branchName, copyBranches, shift, fudge, debug, etaBinDef, energyBinDef, particleTypeVar, filePattern, ignoreSpectators, first_event, friend, defs) # FIXME else: # Make sure we do not have lists inputPath, useTMVA, method, calibrationType, shift, branchName, defs = \ (i[0] if isinstance(i, (list,tuple)) else i for i in iter_options) import ROOT loadLibs() params = particleType, not useTMVA, inputPath, method, calibrationType, debug, \ etaBinDef, energyBinDef, particleTypeVar, filePattern, ignoreSpectators if fudge is None: m = ROOT.egammaMVACalib(*params) else: m = ROOT.egammaMVACalibFudge(fudge, *params) if shift is not None and shift >= 0: m.setPeakCorrection(shift) setDefinitions(m, defs) if printBranches: m.InitTree(inputTree) for i in m.getListOfBranches(): print i.GetName() return elif interact: doInteract(**locals()) return fout = ROOT.TFile(outputfile, 'update') mvaTree = m.getMVAResponseTree(inputTree, nEvents, branchName, copyBranches, first_event) mvaTree.Print() if friend: mvaTree.AddFriend(inputTree) mvaTree.Write('', ROOT.TObject.kOverwrite) fout.Close()
def setup_root(): """Setup ROOT ready to do the fitting""" r.gSystem.Load("libRooFit") r.gROOT.ProcessLine(".L RooW.cxx+") r.gSystem.Load("RooW_cxx.so") r.gROOT.ProcessLine(".L tdrstyle.C") r.gROOT.SetBatch(r.kTRUE) r.setTDRStyle() r.tdrStyle.SetPadRightMargin(0.06) # tweak # r.RooRandom.randomGenerator().SetSeed(random.randint(0, 10000)) r.RooRandom.randomGenerator().SetSeed(4192)
def __init__(self,globalTag,jetFlavour,doResidualJECs,jecPath,upToLevel=3, calculateSeparateCorrections=False, calculateType1METCorrection=False, type1METParams={'jetPtThreshold':15., 'skipEMfractionThreshold':0.9, 'skipMuons':True} ): """Create a corrector object that reads the payloads from the text dumps of a global tag under CMGTools/RootTools/data/jec (see the getJec.py there to make the dumps). It will apply the L1,L2,L3 and possibly the residual corrections to the jets. If configured to do so, it will also compute the type1 MET corrections.""" self.globalTag = globalTag self.jetFlavour = jetFlavour self.doResidualJECs = doResidualJECs self.jecPath = jecPath self.upToLevel = upToLevel self.calculateType1METCorr = calculateType1METCorrection self.type1METParams = type1METParams # Make base corrections path = os.path.expandvars(jecPath) #"%s/src/CMGTools/RootTools/data/jec" % os.environ['CMSSW_BASE']; self.L1JetPar = ROOT.JetCorrectorParameters("%s/%s_L1FastJet_%s.txt" % (path,globalTag,jetFlavour),""); self.L2JetPar = ROOT.JetCorrectorParameters("%s/%s_L2Relative_%s.txt" % (path,globalTag,jetFlavour),""); self.L3JetPar = ROOT.JetCorrectorParameters("%s/%s_L3Absolute_%s.txt" % (path,globalTag,jetFlavour),""); self.vPar = ROOT.vector(ROOT.JetCorrectorParameters)() self.vPar.push_back(self.L1JetPar); if upToLevel >= 2: self.vPar.push_back(self.L2JetPar); if upToLevel >= 3: self.vPar.push_back(self.L3JetPar); # Add residuals if needed if doResidualJECs : self.ResJetPar = ROOT.JetCorrectorParameters("%s/%s_L2L3Residual_%s.txt" % (path,globalTag,jetFlavour)) self.vPar.push_back(self.ResJetPar); #Step3 (Construct a FactorizedJetCorrector object) self.JetCorrector = ROOT.FactorizedJetCorrector(self.vPar) if os.path.exists("%s/%s_Uncertainty_%s.txt" % (path,globalTag,jetFlavour)): self.JetUncertainty = ROOT.JetCorrectionUncertainty("%s/%s_Uncertainty_%s.txt" % (path,globalTag,jetFlavour)); elif os.path.exists("%s/Uncertainty_FAKE.txt" % path): self.JetUncertainty = ROOT.JetCorrectionUncertainty("%s/Uncertainty_FAKE.txt" % path); else: print 'Missing JEC uncertainty file "%s/%s_Uncertainty_%s.txt", so jet energy uncertainties will not be available' % (path,globalTag,jetFlavour) self.JetUncertainty = None self.separateJetCorrectors = {} if calculateSeparateCorrections or calculateType1METCorrection: self.vParL1 = ROOT.vector(ROOT.JetCorrectorParameters)() self.vParL1.push_back(self.L1JetPar) self.separateJetCorrectors["L1"] = ROOT.FactorizedJetCorrector(self.vParL1) if upToLevel >= 2 and calculateSeparateCorrections: self.vParL2 = ROOT.vector(ROOT.JetCorrectorParameters)() for i in [self.L1JetPar,self.L2JetPar]: self.vParL2.push_back(i) self.separateJetCorrectors["L1L2"] = ROOT.FactorizedJetCorrector(self.vParL2) if upToLevel >= 3 and calculateSeparateCorrections: self.vParL3 = ROOT.vector(ROOT.JetCorrectorParameters)() for i in [self.L1JetPar,self.L2JetPar,self.L3JetPar]: self.vParL3.push_back(i) self.separateJetCorrectors["L1L2L3"] = ROOT.FactorizedJetCorrector(self.vParL3) if doResidualJECs and calculateSeparateCorrections: self.vParL3Res = ROOT.vector(ROOT.JetCorrectorParameters)() for i in [self.L1JetPar,self.L2JetPar,self.L3JetPar,self.ResJetPar]: self.vParL3Res.push_back(i) self.separateJetCorrectors["L1L2L3Res"] = ROOT.FactorizedJetCorrector(self.vParL3Res)
def runAll(cls, treeName, outFile, sampleList = None, \ maxFilesMC=None, maxFilesData=None, maxNevents = -1, \ slaveParameters = None, nWorkers=None, usePickle=False, useProofOFile = False, verbosity=1): if slaveParameters == None: # When default param is used reset contents on every call to runAll slaveParameters = {} cwd = os.getcwd() + "/" treeFilesAndNormalizations = getTreeFilesAndNormalizations( maxFilesMC=maxFilesMC, maxFilesData=maxFilesData, samplesToProcess=sampleList, usePickle=usePickle) if sampleList == None: todo = treeFilesAndNormalizations.keys() # run them all else: todo = sampleList slaveParameters["useProofOFile"] = useProofOFile if not useProofOFile: of = ROOT.TFile(outFile, "RECREATE") if not of: print "Cannot create outfile:", outFile sys.exit() of.Close() # so we dont mess with file opens during proof ana slaveParameters["outFile"] = outFile if maxNevents == None: maxNevents = -1 # extra security, run on all events skipped = [] sampleListFullInfo = CommonFSQFramework.Core.Util.getAnaDefinition( "sam") sampleCnt = 0 for t in todo: sampleCnt += 1 print "#" * 60 print "Next sample:", t, "(" + str(sampleCnt) + "/" + str( len(todo)) + ")" print "#" * 60 if len(treeFilesAndNormalizations[t]["files"]) == 0: print "Skipping, empty filelist for", t skipped.append(t) continue dataset = ROOT.TDSet( 'TTree', 'data', treeName ) # the last name is the directory name inside the root file for file in treeFilesAndNormalizations[t]["files"]: dataset.Add(file) slaveParameters["datasetName"] = t slaveParameters["isData"] = sampleListFullInfo[t]["isData"] slaveParameters[ "normalizationFactor"] = treeFilesAndNormalizations[t][ "normFactor"] ROOT.TProof.AddEnvVar( "PATH2", ROOT.gSystem.Getenv("PYTHONPATH") + ":" + os.getcwd()) #ROOT.gSystem.Setenv("TMFDatasetName", t) supportedTypes = set(["int", "str", "float", "bool"]) variablesToFetch = "" coma = "" variablesToSetInProof = {} for p in slaveParameters: encodedName = cls.encodeEnvString(p) # Check if parameter is supported. Adding another type is easy - see # getVariables method paramType = slaveParameters[p].__class__.__name__ if paramType not in supportedTypes: raise Exception("Parameter of type "+paramType \ + " is not of currently supported types: " + ", ".join(supportedTypes) ) ROOT.gSystem.Setenv( encodedName, str(slaveParameters[p]) + ";;;" + paramType) variablesToSetInProof[encodedName] = str( slaveParameters[p]) + ";;;" + paramType variablesToFetch += coma + p coma = "," ROOT.gSystem.Setenv(cls.encodeEnvString("VariablesToFetch"), variablesToFetch) variablesToSetInProof[cls.encodeEnvString( "VariablesToFetch")] = variablesToFetch proofConnectionString = None if "proofConnectionString" in os.environ: proofConnectionString = os.environ["proofConnectionString"] print "Found proof environment. Will try to connect to", proofConnectionString if not proofConnectionString: if nWorkers == None: proof = ROOT.TProof.Open('') else: proof = ROOT.TProof.Open('workers=' + str(nWorkers)) else: proof = ROOT.TProof.Open(proofConnectionString) proof.Exec( 'gSystem->Setenv("PYTHONPATH",gSystem->Getenv("PATH2"));' ) # for some reason cannot use method below for python path proof.Exec('gSystem->Setenv("PATH", "' + ROOT.gSystem.Getenv("PATH") + '");') for v in variablesToSetInProof: # if you get better implemenation (GetParameter?) mail me proof.Exec('gSystem->Setenv("' + v + '","' + variablesToSetInProof[v] + '");') print dataset.Process( 'TPySelector', cls.__name__, maxNevents) # with parameter to limit on number of events try: print "Logs saved to:" logs = proof.GetManager().GetSessionLogs().GetListOfLogs() for l in logs: print l.GetTitle() if len(logs) > 1: with open(logs[1].GetTitle(), "r") as f: if verbosity > 1: print "Printing output of first worker node:" for l in f: if "error" in l.lower( ) or "exception" in l.lower(): print bcolors.ERROR + l.rstrip( '\n') + bcolors.ENDC elif "warn" in l.lower(): print bcolors.WARNING + l.rstrip( '\n') + bcolors.ENDC else: print l, elif verbosity == 1: if any([("error" in l.lower()) or ("exception" in l.lower()) or ("warning" in l.lower()) for l in f]): print "Error/Warning found in log file. Printing first log of worker node:" f.seek(0) for l in f: if "error" in l.lower( ) or "exception" in l.lower(): print bcolors.ERROR + l.rstrip( '\n') + bcolors.ENDC elif "warn" in l.lower(): print bcolors.WARNING + l.rstrip( '\n') + bcolors.ENDC else: print l, else: #logs has not enough entries print "Cannot print log file of first worker node. Only" + len( logs) + "log(s) available" except: print "Cannot get lognames" curPath = ROOT.gDirectory.GetPath() if useProofOFile: bigFileName = outFile.replace(".root", "") + "_" + t + ".root" of = ROOT.TFile(bigFileName, "UPDATE") else: of = ROOT.TFile(outFile, "UPDATE") # Write norm value and other info saveDir = of.Get(t) if not saveDir: print "Cannot get directory from plot file" continue saveDir.cd() norm = treeFilesAndNormalizations[t]["normFactor"] hist = ROOT.TH1D("norm", "norm", 1, 0, 1) hist.SetBinContent(1, norm) #saveDir.WriteObject(hist, hist.GetName()) hist.Write(hist.GetName()) of.Close() ROOT.gDirectory.cd(curPath) # clean environment for v in variablesToSetInProof: #command = 'gSystem->Unsetenv("'+v+'");' #print command proof.Exec('gSystem->Unsetenv("' + v + '");') if len(skipped) > 0: print "Note: following samples were skipped:" for sk in skipped: print " ", sk print "Analyzed:" done = set(todo) - set(skipped) for t in done: print t if useProofOFile: ''' partFiles = [] for t in done: partFiles.append(outFile.replace(".root","")+"_"+t+".root") print "Running hadd" os.system("hadd -f " + outFile + " " + " ".join(partFiles)) ''' # // note: calling hadd directly is problematic, when there are RooUnfold objects inside # this way RooUnfold library is allready loaded, so objects get merged properly merger = ROOT.TFileMerger(False, False) merger.OutputFile(outFile, True, 1) for t in done: merger.AddFile( outFile.replace(".root", "") + "_" + t + ".root") status = merger.Merge() print "Merge status: ", status
#!/usr/bin/env python from sys import argv from os import getenv which = argv[1] argv = [] import ROOT as root from PandaCore.Tools.Load import * from PandaCore.Tools.Misc import * Load('Tools', 'BranchAdder') ba = root.BranchAdder() ba.formula = 'max(0,min(40,npv))' ba.newBranchName = 'sf_pu2016_fixed' fin = root.TFile(which, 'UPDATE') tin = fin.Get('events') fpu = root.TFile('/data/t3home000/bmaier/flat_v9/cr_dimuon/puWeight.root') hpu = fpu.Get('hPU') ba.AddBranchFromHistogram(tin, hpu) fin.WriteTObject(tin, 'events', 'Overwrite') fin.Close()
parser.add_argument('cuts_file_name', help='Cuts file to process.') parser.add_argument('tree_file_name', help='ROOT file with tree to dump.') parser.add_argument( '--no_lists', action='store_true', help= 'Do not make a list of run:lumi:event:... information for events passing each cut. (Speeds up yield-table making.)' ) if not os.path.exists('event_dumps'): os.makedirs('event_dumps') args = parser.parse_args() config = ConfigParser() config.read(args.cuts_file_name) tree_file = ROOT.TFile(args.tree_file_name) labels_and_cut_strings = config['cuts'].items() yields = OrderedDict() tree = tree_file.Get('summaryTree') all_cuts = ROOT.TCut() for (cut_label, cut_string) in labels_and_cut_strings: print "Evaluating yields for cut: %s..." % cut_label all_cuts += ROOT.TCut(cut_string) tree.Draw(">>event_list_%s" % cut_label, all_cuts.GetTitle()) event_list = ROOT.gDirectory.Get("event_list_%s" % cut_label) yields[cut_label] = int(event_list.GetN()) output_file_name = "event_dumps/event_list_%s.txt" % cut_label tree.SetEventList(event_list) if not args.no_lists: with open(output_file_name, 'w') as output_file:
def makeRatioCanvas(width=600, height=600, dataset='combination', wide_labels=None, nvert=1, make_yaxes=False, legend_inside=True, prelim=True): canvas = ROOT.TCanvas('c1', 'c1', width, height) canvas.cmsLabel = makeCMS(prelim=prelim) canvas.lumiLabel = makeLumi(lumis[dataset]) if legend_inside: canvas.hlegend = 0. canvas.ydmax = 1. else: canvas.hlegend = 0.08 # height of the area where the CMS and legend go canvas.ydmax = 0.97 canvas.yrmin = 0. canvas.ydmin = 0.31 canvas.yrmax = 0.3 canvas.xaxis = ROOT.TGaxis(xmin, ymin, xmax, ymin, 0., 1., 404, 'S') canvas.xaxis.SetTitleOffset(ROOT.gStyle.GetTitleOffset('X') * 0.8) canvas.xaxis.SetLabelFont(42) canvas.xaxis.SetTitleFont(42) canvas.xaxis.SetTitleSize(0.048) canvas.xaxis.SetLabelSize(0.875 * 0.048) canvas.xaxis.SetTickLength(0.02) canvas.xaxis.SetGridLength(0.) def change_label(self, *args): self._ChangeLabel(*args) self._label_mods.append(args) canvas.xaxis._ChangeLabel = canvas.xaxis.ChangeLabel canvas.xaxis._label_mods = [] canvas.xaxis.ChangeLabel = types.MethodType(change_label, canvas.xaxis) if wide_labels is not None: if type(wide_labels[0]) is not list: wide_labels = [wide_labels] * nvert canvas.wide_labels = wide_labels canvas.nvert = nvert hvert = (ymax - ymin - canvas.hlegend) / nvert canvas.yaxes = [] canvas.raxes = [] for iv in range(nvert): yoffset = iv * hvert + ymin if make_yaxes: yaxis = ROOT.TGaxis(xmin, yoffset + hvert * canvas.ydmin, xmin, yoffset + hvert * canvas.ydmax, 0., 1., 110, 'S') yaxis.SetTitleFont(42) yaxis.SetTitleOffset(ROOT.gStyle.GetTitleOffset('Y') * 0.85) yaxis.SetTitleSize(0.048 / nvert) yaxis.SetLabelFont(42) yaxis.SetLabelSize(0.875 * 0.048 / nvert) yaxis.SetTickLength(0.03) yaxis.SetGridLength(0.) yaxis.SetNoExponent(True) canvas.yaxes.append(yaxis) raxis = ROOT.TGaxis(xmin, yoffset + hvert * canvas.yrmin, xmin, yoffset + hvert * (canvas.yrmin + (canvas.yrmax - canvas.yrmin) * 0.95), 0., 1., 204, 'S') raxis.SetTitleFont(42) raxis.SetTitleOffset(ROOT.gStyle.GetTitleOffset('Y') * 0.85) raxis.SetTitleSize(0.048 / nvert) raxis.SetLabelFont(42) raxis.SetLabelSize(0.875 * 0.048 / nvert) raxis.SetTickLength(0.1) raxis.SetGridLength(0.) canvas.raxes.append(raxis) def finalize(self): self.cd() for iv in range(self.nvert): distpad = self.GetPad(iv * 2 + 1) ratiopad = self.GetPad(iv * 2 + 2) distpad.Update() frame = distpad.GetListOfPrimitives().At(1) rframe = ratiopad.GetListOfPrimitives().At(1) if not frame or not rframe: continue xaxis = frame.GetXaxis() uxmin = xaxis.GetXmin() disty1 = distpad.GetYlowNDC() if self.wide_labels is not None: dataset_divider = ROOT.TLine(0., 0., 0., 0.) dataset_divider.SetLineStyle(ROOT.kDotted) dataset_divider.SetLineWidth(1) dataset_divider.SetLineColor(ROOT.kBlack) dataset_label = ROOT.TLatex(0., 0., '') dataset_label.SetTextFont(42) dataset_label.SetTextAlign(11) dataset_label.SetTextSize(0.05 * self.nvert) uxmax = xaxis.GetBinUpEdge(xaxis.GetNbins() / len(self.wide_labels[iv])) xwidth = uxmax - uxmin x1 = distpad.GetXlowNDC() xlen = distpad.GetWNDC() / len(self.wide_labels[iv]) for il, label in enumerate(self.wide_labels[iv]): xdiv = xaxis.GetBinUpEdge(xaxis.GetNbins() / len(self.wide_labels[iv]) * il) distpad.cd() dataset_label.DrawLatex(xdiv + 0.05 * xwidth, frame.GetMaximum() * 0.85, label) if il != 0: dataset_divider.DrawLine(xdiv, frame.GetMinimum(), xdiv, frame.GetMaximum()) ratiopad.cd() dataset_divider.DrawLine(xdiv, rframe.GetMinimum(), xdiv, rframe.GetMaximum()) self.cd() # dist pad self.xaxis.DrawAxis(x1, disty1, x1 + xlen, disty1, uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) newaxis = self.GetListOfPrimitives().Last() newaxis.SetLabelSize(0.) newaxis.SetTitle('') # ratio pad self.xaxis.DrawAxis(x1, self.raxes[iv].GetY1(), x1 + xlen, self.raxes[iv].GetY1(), uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) newaxis = self.GetListOfPrimitives().Last() if iv != 0: newaxis.SetLabelSize(0.) else: newaxis.SetBit(ROOT.TAxis.kCenterLabels, self.xaxis.TestBit(ROOT.TAxis.kCenterLabels)) for args in self.xaxis._label_mods: newaxis.ChangeLabel(*args) if iv != 0 or il != len(self.wide_labels[iv]) - 1: newaxis.SetTitle('') x1 += xlen else: uxmax = xaxis.GetBinUpEdge(xaxis.GetNbins() / len(self.wide_labels[iv])) # dist pad self.xaxis.DrawAxis(self.xaxis.GetX1(), disty1, self.xaxis.GetX2(), disty1, uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) newaxis = self.GetListOfPrimitives().Last() newaxis.SetLabelSize(0.) newaxis.SetTitle('') # ratio pad self.xaxis.DrawAxis(x1, self.raxes[iv].GetY1(), x1 + xlen, self.raxes[iv].GetY1(), uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) if iv != 0: newaxis.SetLabelSize(0.) else: newaxis.SetBit(ROOT.TAxis.kCenterLabels, self.xaxis.TestBit(ROOT.TAxis.kCenterLabels)) if iv != 0 or il != len(self.wide_labels[iv]) - 1: newaxis.SetTitle('') self.cd() uymin = distpad.GetUymin() uymax = distpad.GetUymax() if len(self.yaxes) != 0: self.yaxes[iv].SetWmin(uymin) self.yaxes[iv].SetWmax(uymax) self.yaxes[iv].Draw() urmin = ratiopad.GetUymin() urmax = ratiopad.GetUymax() self.raxes[iv].SetWmin(urmin) self.raxes[iv].SetWmax(urmin + (urmax - urmin) * 0.95) self.raxes[iv].Draw() distpad.RedrawAxis() ratiopad.RedrawAxis() self.cd() self.cmsLabel.Draw() self.lumiLabel.Draw() self.Update() def printout(self, path, out_file=None): self.finalize() if out_file is None: try: os.makedirs(os.path.dirname(path)) except OSError: pass self.Print(path) else: out_file.cd() self.Write(path) def clear(self): self.Clear() self.Divide(1, 2 * self.nvert) hvert = (ymax - ymin - self.hlegend) / self.nvert for iv in range(self.nvert): yoffset = iv * hvert + ymin distpad = self.GetPad(iv * 2 + 1) if len(self.yaxes) == 0: distpad.SetPad(0., yoffset + hvert * self.ydmin, 1., yoffset + hvert * self.ydmax) distpad.SetMargin(xmin, 1. - xmax, 0., 0.) else: distpad.SetPad(xmin, yoffset + hvert * self.ydmin, xmax, yoffset + hvert * self.ydmax) distpad.SetMargin(0., 0., 0., 0.) ratiopad = self.GetPad(iv * 2 + 2) ratiopad.SetPad(xmin, yoffset + hvert * self.yrmin, xmax, yoffset + hvert * self.yrmax) ratiopad.SetMargin(0., 0., 0., 0.) if self.hlegend != 0.: self.cd() self.legendborder = ROOT.TBox(xmin, ymax - self.hlegend, xmax, ymax) self.legendborder.SetLineStyle(ROOT.kSolid) self.legendborder.SetLineColor(ROOT.kBlack) self.legendborder.SetLineWidth(1) self.legendborder.Draw() canvas.finalize = types.MethodType(finalize, canvas) canvas.printout = types.MethodType(printout, canvas) canvas.clear = types.MethodType(clear, canvas) canvas.clear() return canvas
def main(): plotNames = [ "GamEmTB-eSum", "GamEmTB-pairMass", "GamEmTB-p1Mom", "GamEmTB-p2Mom", "GamEmTB-p1ClusterSlope", "GamEmTB-p2slope", "GamEmTB-p2d0", "GamEmTB-p2phi0", "EpEmTB-eSum", "EpEmTB-pairMass", "EpEmTB-p1Mom", "EpEmTB-p2Mom", "EpEmTB-p1slope", "EpEmTB-p2slope", "EpEmTB-p1d0", "EpEmTB-p1phi0", "EpEmTB-p2d0", "EpEmTB-p2phi0" ] ROOT.gStyle.SetOptTitle(0) makeRatioPlot = True normToArea = False addMCHistos = True iLumi5772 = 42.366 * 1000.0 # ub^-1 run 5772 full run iLumi = 1.4 * 1000.0 # ub^-1 run 5754 #wabv3AF_200MeV_5mrad # wabXS=770.3*1000.0 #ub...this is the lower peak wabXS = 944.2 * 1000.0 #ub...this is the upper peak wabNGen = 10000 * 1000 * 10 # v6 detector #tritrig with ESum>0.5 GeV and 5mrad tritrigMG5XS = 2.777 * 1000.0 #ub tritrigMG5NGen = 10000.0 * 10 * 10 # v6 detector ###### RAD MG5 (no xchange) 5mrad radMG5XS = 0.1074 * 1000.0 #ub radMG5NGen = 10000 * 10 * 10 #v6 detector ############ #wab-beam-tri Luminosity wabBeamTriMG5Lumi = 0.0861 * 1000 #ub^-1 ROOT.gROOT.SetBatch(True) dataPath = "OutputHistograms/Data/" datapass = "******" # label="NoESumCut_WeighInEclVsY_ElePosSame_MattsBase_TrkChiSq" # label="NoESumCut_WeighInEclVsY_ElePosSame_MattsBase_OmarsBase" # label="NoESumCut_WeighInEclVsY_ElePosSame_MattsBase_V0ChiSq" # label="NoESumCut_WeighInEclVsY_ElePosSame_OmarsBase_WABCuts_SuperFiducial" # label="WeighInEclVsY_ElePosSame_OmarsBase_WABCuts_SuperFiducial" # label="NoESumCut_WeighInEclVsY_ElePosSame_OmarsBase" # label="NoESumCut_WeighInEclVsY_ElePosSame_MattsBase" # label="WeighInEclVsY_ElePosSame_OmarsBase_WABCuts" # label="WeighInEclVsY_ElePosSame_OmarsBase" # label="WeighInEclVsY_ElePosSame_MattsBase" # label="NoESumCut_WeighInEclVsY_ElePosSame_OmarsBase_WABCuts" # label="NoESumCut_WeighInEclVsY_KillL1Hits_ElePosSame_OmarsBase_WABCuts" # label="WeighInEclVsY_KillL1Hits_ElePosSame_OmarsBase_WABCuts" # label="WeighInEclVsY_KillL1Hits_ElePosSame_OmarsBase" # label="NoESumCut_WeighInEclVsY_KillL1Hits_ElePosSame_OmarsBase" mcTag = "" # plotFilePostFix="" # plotFilePostFix="_RescaleWAB_1pt5" # plotFilePostFix="_ScaleWABBy0pt87_NoRatios" mcpass = "******" mcPath = "OutputHistograms/MC/" # mcLabel="_HPS-EngRun2015-Nominal-v6-0"+mcpass+lable prefix = "fromscratch_" run = "hps_005772.1" dataNorm = [1 / iLumi5772 * (471. / 111.0) ] #only running through a fraction of the DSTs for speed. # run="hps_005772.11" # dataNorm=[1/iLumi5772 * (471./11.0)] #only running through a fraction of the DSTs for speed. print 'Scaling RAD-MG5 sample by ' + str(radMG5XS / radMG5NGen) mcSamples = ["wab-beam", "tritrig-beam"] mcNorm = [ wabXS / wabNGen, tritrigMG5XS / tritrigMG5NGen, radMG5XS / radMG5NGen, 1 / wabBeamTriMG5Lumi ] mcLegends = ["WAB+beam", "TriTrig+beam", "Rad+beam", "Wab-Beam-Tri"] # mcLegends=["Wab-Beam-Tri"] # mcScale=[1000/989.,10./96.,1,1,1,1] #correct for number of files # mcScale=[1000/989.*0.87,10./96.,1,1,1,1]# correct WABs by 13% # mcScale=[1000/989.*0.87*1.10,10./96.*0.87*0.983,1*0.87*0.95,1*0.87,1*0.87,1*0.87]# correct ALL components by 13%, but then move WABs up by 10% and tridents down by ~2% to compensate total (radiative cut XS) # mcScale=[1000/989.*0.87*1.25,10./96.*0.87*0.942,1*0.87*0.95,1*0.87,1*0.87,1*0.87]# correct ALL components by 13%, but then move WABs up by 25% and tridents down by ~6% to compensate total (radiative cut XS) # mcScale=[1000/989.*0.87*2.0,10./96.*0.87*0.738,1*0.87*0.95,1*0.87,1*0.87,1*0.87]# correct ALL components by 13%, but then move WABs up by x2 and tridents down by ~27% to compensate total (radiative cut XS) # mcScale=[1000/989.*0.87*1.0,10./96.*0.87*1.0,1*0.87*0.95,1*0.87,1*0.87,1*0.87]# correct ALL components by 13%, but then move WABs up by x1! and tridents down by 1.0! to compensate total (radiative cut XS) ############# below is for without WABCuts! Different ~5% normalization #omars cuts w/o WABCuts...already scaled by 0.87 #data = 32.8; wab=10.5; tri=20.7 # relative scale data/MC=1.05 # so then, wab=11.0; tri=21.7 # mcScale=[1000/989.*0.87*1.05*2.0,10./96.*0.87*1.05*0.5]# move WABs up by x2 and tridents down by 0.5 to compensate total (radiative cut XS) # mcScale=[1000/989.*0.87*1.05*1.0,10./96.*0.87*1.05*1.0]# move WABs up by x1 and tridents down by 1.0 to compensate total (radiative cut XS) # mcScale=[1000/989.*0.87*1.05*1.5,10./96.*0.87*1.05*0.823]# move WABs up by x1.5 and tridents down by 0.82.0 to compensate total (radiative cut XS) # mcScale=[1000/989.*0.87*1.05*1.2,10./96.*0.87*1.05*0.90]# move WABs up by x1.2 and tridents down by 0.90 to compensate total (radiative cut XS) postMCProcess = "WeighInEclVsY_KillL1Hits_ElePosSame_" radLabels = ["", "NoESumCut_"] cutLabels = [ "OmarsBase", "OmarsBase_WABCuts", "OmarsBase_WABCuts_SuperFiducial" ] # label="NoESumCut_WeighInEclVsY_KillL1Hits_ElePosSame_OmarsBase" mcScale = [ 1000 / 989. * 0.87, 10. / 96. * 0.87, 1 * 0.87, 1 * 0.87, 1 * 0.87, 1 * 0.87 ] # correct ALL components by 13% plotFilePostFix = "_ScaleAllBy0pt87" for radLabel in radLabels: for cutLabel in cutLabels: label = radLabel + postMCProcess + cutLabel datalabel = datapass + "" + label mcLabel = "_HPS-EngRun2015-Nominal-v5-0" + mcpass + label print datalabel dataFile = ROOT.TFile(dataPath + prefix + run + datalabel + ".root") dataFile.cd() mcFile = [] for sample in mcSamples: print 'loading ' + mcPath + prefix + sample + mcLabel + mcTag + ".root" mcFile.append( ROOT.TFile(mcPath + prefix + sample + mcLabel + mcTag + ".root")) # mcFile.append(ROOT.TFile(mcPath+prefix+sample+mcLabel+label+".root")) if normToArea: mcTag = mcTag + "_normToArea" #loop through all of the histograms # for key in allKeys : for hname in plotNames: canvas = ROOT.TCanvas("Dumb Canvas") h = dataFile.Get(hname) if not h.GetEntries() > 0: continue is2D = False if type(h) is ROOT.TH2D: is2D = True if is2D: canvas.Divide(2, 2) canvas.cd(1) totalCrossSection = h.Integral() * dataNorm[0] h.Sumw2(True) print hname + ' ' + str(len(mcFile)) print "data cross-section = " + str( totalCrossSection) + " ub " + str( h.GetEntries()) + " entries" plotFileName = "PlotsForNote/" + hname + datalabel + mcTag + plotFilePostFix + ".pdf" if normToArea: h.Scale(10000.0 / h.Integral()) else: h.Scale(dataNorm[0]) max = h.GetMaximum() if normToArea: makePretty(h, getAxisTitle(h.GetTitle()), "Arbitrary") else: makePretty(h, getAxisTitle(h.GetTitle()), "#sigma (#mub)") mchList = [] mchLabList = [] mchScaleList = [] addCnt = 0 for ii in range(len(mcFile)): mcf = mcFile[ii] mch = mcf.Get(hname) if not mch: print hname + ' ' + str(ii) + ' does not exist!' continue mch.Sumw2(True) mcCrossSection = mch.Integral() * mcNorm[ii] * mcScale[ii] print mcSamples[ii] + " MC cross-section = " + str( mcCrossSection) + " ub using " + str(mch.GetEntries( )) + " entries and integral = " + str(mch.Integral()) if normToArea: mch.Scale(10000.0 / mch.Integral()) else: print 'normalizing by ' + str( (mcNorm[ii] * mcScale[ii])) mch.Scale(mcNorm[ii] * mcScale[ii]) mchList.append(mch) mchLabList.append(mcLegends[ii]) mchScaleList.append(mcScale[ii]) makePretty(mch, "foo", "bar", ii + 2) tm = mch.GetMaximum() if tm > max: max = tm if addMCHistos and mch is not None: if addCnt == 0: mchAdd = mch.Clone() mchAdd.SetDirectory(0) elif ii < 2: mchAdd.Add(mch.Clone()) addCnt += 1 if addMCHistos and mchAdd is not None: makePretty(mchAdd, "foo", "bar", 9) mchList.append(mchAdd) mchLabList.append("Tridents+WABs") mchScaleList.append("") if mchAdd.GetMaximum() > max: max = mchAdd.GetMaximum() #do something to them... leg = ROOT.TLegend(0.1, 0.9, 0.3, 0.73) leg.SetTextSize(0.032) leg.AddEntry(h, "Run 5772", "l") if not is2D and makeRatioPlot: # Upper plot will be in pad1 pad1 = ROOT.TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetTitle("") pad1.SetBottomMargin(0) pad1.SetGridx() pad1.Draw() pad1.cd() h.SetMaximum(1.2 * max) if "Missing" in hname: h.SetMinimum(0.01) h.SetMaximum(10 * max) if is2D: h.SetTitle(h.GetTitle() + ' Data') h.Draw("colz") else: h.SetStats(0) h.SetMaximum(1.2 * max) h.GetYaxis().SetTitleSize(0.05) h.GetYaxis().SetLabelSize(0.05) h.Draw("ehist") for i in range(0, len(mchList)): mch = mchList[i] if is2D: canvas.cd(i + 2) mch.SetTitle(mch.GetTitle() + ' ' + mchLabList[i] + ' x' + str(mchScaleList[i])) mch.Draw("colz") else: if "Missing" in hname: mch.SetMinimum(h.GetMinimum()) mch.Draw("esame") leg.AddEntry(mch, mchLabList[i], "l") i += 1 if not is2D: print 'drawing legend!' leg.Draw() if not is2D and makeRatioPlot: #...this is for monkeying with axis labels # h1->GetYaxis()->SetLabelSize(0.); # axis =ROOT.TGaxis( -5, 20, -5, 220, 20,220,510,""); # axis.SetLabelFont(43); # axis.SetLabelSize(15); # axis.Draw(); canvas.cd() pad2 = ROOT.TPad("pad2", "pad2", 0, 0.0, 1, 0.3) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.3) pad2.SetGridx() pad2.Draw() pad2.cd() ratio = h.Clone() # take the ratio with the last mchList histogram... ratio.SetLineColor(1) ratio.SetMinimum(0.5) ratio.SetMaximum(1.5) ratio.Sumw2() ratio.SetStats(0) ratio.Divide(mchList[-1]) ratio.SetMarkerStyle(21) ratio.SetTitle("") ratio.GetYaxis().SetTitle("ratio data/MC ") ratio.GetYaxis().SetNdivisions(505) ratio.GetYaxis().SetTitleSize(20) ratio.GetYaxis().SetTitleFont(43) # ratio.GetYaxis().SetTitleOffset(1.55) ratio.GetYaxis().SetLabelFont(43) ratio.GetYaxis().SetLabelSize(15) ratio.GetXaxis().SetTitleSize(20) ratio.GetXaxis().SetTitleFont(43) ratio.GetXaxis().SetTitleOffset(3.) ratio.GetXaxis().SetLabelFont(43) ratio.GetXaxis().SetLabelSize(15) ratio.Draw("ep") xmin = ratio.GetXaxis().GetXmin() xmax = ratio.GetXaxis().GetXmax() tl = ROOT.TLine(xmin, 1, xmax, 1) tl.Draw() if "Missing" in hname: canvas.SetLogy(True) else: canvas.SetLogy(False) # else : canvas.Print(plotFileName)
def DrawDataVsMC(histogram_dict, LegendLabels={}, MCKeys=[""], DataKey="", doLogy=True, doLogx=False, ratio_min=0.0, ratio_max=2.0, extra_description=None, extra_desx=0.40, extra_desy=0.85, scale_factor=1000, xTicksNumber=None, yTicksNumber=505, rebin=None, ylabel=None, xAxis_range=None, xlabel=None, marker_size=None, ratio_label=None, invert_ratio=False, bigger_legend=False, skip_data=False, skip_ratio=False, skip_atlas_label=False, skip_legend=False, more_logx_labels=True): ''' This function returns a canvas with a data and MC histogram drawn acoording to configurable settings. inputs ----------------------------------------------------------------------------------------------------- histogram_dict: a dictionary of string channel name to TH1 or TProfile LegendLabels: a dictionary of string channel name to string description of channel to be used in the legend. MCKey: A string corresponding to the key for the MC histogram DataKey: a string correponding to the key for the data histogram doLogy: Bool. When true, the y axis is drawn with logarithmic scale doLogx: Bool. When true, the x axis is drawn with logarithmic scale ratio_min: the minimum value of the range of the y-axis in the data/MC ratio plot ratio_max: the maximum value of the range of the y-axis in the data/MC ratio plot extra_desction: list of strings corresponding to be drawn on the plot. These are used to describe what is being plotted. extra_desx: the x co-ordinate of the extra descriptions in NDC coordinates extra_desy: the y co-ordinate of the extra descriptions in NDC coordinates scale_dactor: the maximual value of the y-axis is set to scale_factor * (largest bin entry) xTicksNumber: change the number of ticks on the x-axis yTicksNumber: set the number of ticks on the y-axis ----------------------------------------------------------------------------------------------------- ''' text_size = 0.05 if not skip_ratio: text_size *= 1.3 global CANVAS_COUNTER #This is to make sure that no two canvases ever get the same name. Otherwise root complains... canvas_name = "Canvas" + "".join(MCKeys) + DataKey + str(CANVAS_COUNTER) CANVAS_COUNTER = CANVAS_COUNTER + 1 canvas = ROOT.TCanvas(canvas_name, canvas_name, 1300, 800) canvas.cd() MCHists_keys = [(histogram_dict[MCKey], MCKey) for MCKey in MCKeys] MCHists = [MCHists_key[0] for MCHists_key in MCHists_keys] MCKeys = [MCHists_key[1] for MCHists_key in MCHists_keys] DataHist = histogram_dict[DataKey] if marker_size != None: DataHist.SetMarkerSize(marker_size) MCHists = [cleanUpHistograms(MCHist) for MCHist in MCHists] [MCHist.SetTickLength(0.06) for MCHist in MCHists] DataHist.SetTickLength(0.06) title_offset = 0.9 if not skip_ratio: [ MCHist.GetXaxis().SetLabelSize( float(MCHist.GetXaxis().GetLabelSize() * 1.2)) for MCHist in MCHists ] [ MCHist.GetYaxis().SetLabelSize( float(MCHist.GetYaxis().GetLabelSize() * 1.2)) for MCHist in MCHists ] DataHist.GetYaxis().SetLabelSize( float(MCHists[0].GetYaxis().GetLabelSize() * 1.2)) DataHist.GetXaxis().SetLabelSize( float(MCHists[0].GetXaxis().GetLabelSize() * 1.2)) [ MCHist.GetXaxis().SetTitleSize( float(MCHist.GetXaxis().GetTitleSize() * 1.7)) for MCHist in MCHists ] [ MCHist.GetYaxis().SetTitleSize( float(MCHist.GetYaxis().GetTitleSize() * 1.7)) for MCHist in MCHists ] DataHist.GetYaxis().SetTitleSize( float(MCHists[0].GetYaxis().GetTitleSize() * 1.7)) DataHist.GetXaxis().SetTitleSize( float(MCHists[0].GetXaxis().GetTitleSize() * 1.7)) [MCHist.GetXaxis().SetTitleOffset(title_offset) for MCHist in MCHists] [MCHist.GetYaxis().SetTitleOffset(title_offset) for MCHist in MCHists] DataHist.GetYaxis().SetTitleOffset(title_offset) #title_offset = DataHist.GetYaxis().GetTitleOffset() #title_offset = MCHists[0].GetYaxis().GetTitleOffset() [ MCHist.SetLineColor(COLOURS[MCKey]) for MCKey, MCHist in zip(MCKeys, MCHists) ] if xlabel: [MCHist.GetXaxis().SetTitle(xlabel) for MCHist in MCHists] if ylabel: [MCHist.GetYaxis().SetTitle(ylabel) for MCHist in MCHists] DataHist.SetLineColor(DataColor) if rebin != None: [MCHist.Rebin(rebin) for MCHist in MCHists] DataHist.Rebin(rebin) if xAxis_range != None: #find the bin to use to set the range x_low = None x_high = None for MCHist in MCHists: for bin in range(0, MCHist.GetNbinsX() + 1): cent = MCHist.GetBinCenter(bin) if cent >= xAxis_range[0] and x_low == None: x_low = bin elif cent > xAxis_range[1] and x_high == None: x_high = bin - 1 [MCHist.GetXaxis().SetRange(x_low, x_high) for MCHist in MCHists] DataHist.GetXaxis().SetRange(x_low, x_high) if not bigger_legend: legend = ROOT.TLegend(0.58, 0.65, 0.94, 0.89) else: legend = ROOT.TLegend(0.58, 0.65, 0.94, 0.89) legend.SetNColumns(2) legend.SetTextSize(text_size) if skip_ratio: legend.SetTextSize(text_size * 0.7) legend.SetBorderSize(0) toGlobalScope(legend) if not skip_ratio: top_pad = ROOT.TPad("toppad" + str(CANVAS_COUNTER), "toppad" + str(CANVAS_COUNTER), 0, 0.3, 1, 1.0) else: top_pad = ROOT.TPad("toppad" + str(CANVAS_COUNTER), "toppad" + str(CANVAS_COUNTER), 0, 0.0, 1, 1.0) canvas.cd() top_pad.Draw() top_pad.cd() if not skip_ratio: top_pad.SetBottomMargin(0) else: top_pad.SetBottomMargin(0.2) filename = MCHists[0].GetTitle() + "histogram" if (type(extra_description) == list and len(extra_description) > 3): scale_factor *= 10.0 maximum_bin = 0.0 minimum_bin = 10000000000000000.0 for MCHist in MCHists: for bin in range(1, MCHist.GetNbinsX() + 1): content = MCHist.GetBinContent(bin) if content > maximum_bin: maximum_bin = content if content < minimum_bin and content > 0.0: minimum_bin = content if not skip_data: for bin in range(1, DataHist.GetNbinsX() + 1): content = DataHist.GetBinContent(bin) if content > maximum_bin: maximum_bin = content if content < minimum_bin and content > 0.0: minimum_bin = content if doLogy: filename += "logy" if doLogy: if minimum_bin <= 0.0: minimum_bin = 1 for MCHist in MCHists: MCHist.SetMaximum(maximum_bin * scale_factor) MCHist.SetMinimum(minimum_bin * 0.5) DataHist.SetMaximum(maximum_bin * scale_factor) DataHist.SetMinimum(minimum_bin * 0.5) else: for MCHist in MCHists: MCHist.SetMaximum(maximum_bin * 1.5) MCHist.SetMinimum(minimum_bin * 0.5) DataHist.SetMaximum(maximum_bin * 1.5) DataHist.SetMinimum(minimum_bin * 0.5) if ylabel: [MCHist.GetYaxis().SetTitle(ylabel) for MCHist in MCHists] MCHists[0].Draw("][ HIST E") MCHists[0].Draw("][ HIST SAME") for MCHist in MCHists[1:]: MCHist.Draw("SAME ][ HIST E") MCHist.Draw("SAME ][ HIST") if not skip_data: DataHist.Draw("SAME") hist_description = [] for MCHist in MCHists: fit = MCHist.GetListOfFunctions().Last() if not fit: continue fit.SetLineColor(MCHist.GetLineColor()) fit.Draw("SAME") chisq = fit.GetChisquare() ndf = fit.GetNDF() prob = fit.GetProb() string = "#chi^2/ndf = {:1.3f}/{} Prob = {:1.3f}".format( chisq, ndf, prob) DrawText(0.60, 0.5, string, color=fit.GetLineColor(), size=text_size) fit = DataHist.GetListOfFunctions().Last() if fit: fit.Draw("SAME") fit.SetLineColor(DataHist.GetMarkerColor()) chisq = fit.GetChisquare() ndf = fit.GetNDF() prob = fit.GetProb() string = "#chi^2/ndf = {:1.3f}/{} Prob = {:1.3f}".format( chisq, ndf, prob) DrawText(0.6, 0.6, string, color=fit.GetLineColor(), size=text_size) #legend.SetTextSize(0.04) for MCHist, MCKey in zip(MCHists, MCKeys): legend.AddEntry(MCHist, LegendLabels[MCKey]) legend.AddEntry(DataHist, LegendLabels[DataKey]) if not skip_legend: legend.Draw() if skip_atlas_label: extra_desx -= 0.15 if extra_description: if not type(extra_description) == list: DrawText(extra_desx, extra_desy, extra_description, size=text_size) else: top = extra_desy for descr in extra_description: DrawText(extra_desx, top, descr, size=text_size) if not skip_ratio: top -= 0.10 else: top -= 0.07 if doLogy: top_pad.SetLogy() if doLogx: top_pad.SetLogx() ROOT.gROOT.SetStyle("ATLAS") if foundAtlasPlots: x = 0.2 y = 0.85 if not skip_atlas_label: ATLASLabel(x, y, "Internal", size=text_size) top_pad.Modified() top_pad.Update() toGlobalScope(top_pad) canvas.cd() bottom_pad = ROOT.TPad("botpad" + str(CANVAS_COUNTER), "botpad" + str(CANVAS_COUNTER), 0, 0.01, 1, 0.3) if not skip_ratio: canvas.cd() if doLogx: bottom_pad.SetLogx() #bottom_pad.SetRightMargin(0.15) bottom_pad.Draw() bottom_pad.cd() toGlobalScope(bottom_pad) counter = 0 for MCHist, MCKey in zip(MCHists, MCKeys): counter += 1 if not invert_ratio: data_ratio = DataHist.Clone("data_histogram" + str(counter)) data_ratio.Divide(MCHist) else: data_ratio = MCHist.Clone("data_histogram" + str(counter)) data_ratio.Divide(DataHist) data_ratio = cleanUpHistograms(data_ratio) data_ratio.SetLineColor(COLOURS[MCKey]) if doLogx and more_logx_labels: data_ratio.GetXaxis().SetMoreLogLabels(True) if counter == 1: data_ratio.Draw("][ HIST E") data_ratio.Draw("][ HIST SAME") else: data_ratio.Draw("][ HIST SAME E") data_ratio.Draw("][ HIST SAME") MCHist_label_size = MCHist.GetXaxis().GetLabelSize() MCHist_xtitle_size = MCHist.GetXaxis().GetTitleSize() MCHist_ytitle_size = MCHist.GetYaxis().GetTitleSize() variableLabel = MCHist.GetXaxis().GetTitle() data_ratio.GetYaxis().SetNdivisions(yTicksNumber) if ratio_label == None: data_ratio.GetYaxis().SetTitle("Data/MC") else: data_ratio.GetYaxis().SetTitle(ratio_label) scale_ratio = (top_pad.GetWh() * top_pad.GetAbsHNDC()) / ( bottom_pad.GetWh() * bottom_pad.GetAbsHNDC()) data_ratio.GetXaxis().SetLabelSize(MCHist_label_size * (scale_ratio)) data_ratio.GetYaxis().SetLabelSize(MCHist_label_size * (scale_ratio)) data_ratio.GetXaxis().SetTitle(variableLabel) data_ratio.GetXaxis().SetTitleOffset(title_offset) data_ratio.SetMaximum(ratio_max - 0.0001) data_ratio.SetMinimum(ratio_min + 0.0001) data_ratio.GetXaxis().SetTitleSize(MCHist_xtitle_size * scale_ratio) data_ratio.GetYaxis().SetTitleSize(MCHist_ytitle_size * scale_ratio) data_ratio.GetYaxis().SetTitleOffset(title_offset / scale_ratio) data_ratio.SetMaximum(ratio_max - 0.0001) data_ratio.SetMinimum(ratio_min + 0.0001) if counter == 1: data_ratio.Draw("][ HIST E") data_ratio.Draw("][ HIST SAME") else: data_ratio.Draw("SAME ][ HIST E") data_ratio.Draw("SAME ][ HIST SAME") toGlobalScope(data_ratio) if xTicksNumber != None: data_ratio.GetXaxis().SetNdivisions(xTicksNumber) ##Draw a set of solid and dotted lines on the ratio plot to guide the reader's eyes straight_line = ROOT.TF1("line1", str(1.0), -10e6, +10e6) straight_line.SetLineWidth(2) straight_line.Draw("Same") toGlobalScope(straight_line) straight_line_up = ROOT.TF1("line2", str(1.0 + (2.0 * (ratio_max - 1.0) / 4)), -10e6, +10e6) straight_line_up.SetLineWidth(1) straight_line_up.SetLineStyle(1) straight_line_up.Draw("Same") toGlobalScope(straight_line_up) straight_line_up2 = ROOT.TF1("line3", str(1.0 + (1.0 * (ratio_max - 1.0) / 4)), -10e6, +10e6) straight_line_up2.SetLineWidth(1) straight_line_up2.SetLineStyle(3) straight_line_up2.Draw("Same") toGlobalScope(straight_line_up2) straight_line_up3 = ROOT.TF1("line4", str(1.0 + (3.0 * (ratio_max - 1.0) / 4)), -10e6, +10e6) straight_line_up3.SetLineWidth(1) straight_line_up3.SetLineStyle(3) straight_line_up3.Draw("Same") toGlobalScope(straight_line_up3) straight_line_down3 = ROOT.TF1( "line5", str(1.0 - (3.0 * (ratio_max - 1.0) / 4)), -10e6, +10e6) straight_line_down3.SetLineWidth(1) straight_line_down3.SetLineStyle(3) straight_line_down3.Draw("Same") toGlobalScope(straight_line_down3) straight_line_down = ROOT.TF1("line6", str(1.0 - (2.0 * (ratio_max - 1.0) / 4)), -10e6, +10e6) straight_line_down.SetLineWidth(1) straight_line_down.SetLineStyle(1) straight_line_down.Draw("Same") toGlobalScope(straight_line_down) straight_line_down2 = ROOT.TF1( "line7", str(1.0 - (1.0 * (ratio_max - 1.0) / 4)), -10e6, +10e6) straight_line_down2.SetLineWidth(1) straight_line_down2.SetLineStyle(3) straight_line_down2.Draw("Same") toGlobalScope(straight_line_down2) canvas.cd() bottom_pad.Modified() bottom_pad.Update() bottom_pad.Draw() bottom_pad.cd() bottom_pad.SetTopMargin(0) bottom_pad.SetBottomMargin(0.45) bottom_pad.Modified() bottom_pad.Update() top_pad.Modified() top_pad.Update() canvas.SetRightMargin(0.15) canvas.Modified() canvas.Update() return canvas, top_pad, bottom_pad
#! /usr/bin/env python import ROOT import sys from DataFormats.FWLite import Events, Handle #ROOT.gROOT.Macro("~/rootlogon.C") #ROOT.gROOT.SetBatch() #HISTOGRAMS outputFile = ROOT.TFile('testJTB.root', "RECREATE") hJetsPt = ROOT.TH1F("hJetsPt", ";jet pt (GeV)", 100, 0, 1000) hJetsTrimmedMass = ROOT.TH1F("hJetsTrimmedMass", ";jet Trimmed mass (GeV)", 30, 0, 300) hJetsPrunedMass = ROOT.TH1F("hJetsPrunedMass", ";jet Pruned mass (GeV)", 30, 0, 300) hJetsSoftDropMass = ROOT.TH1F("hJetsSoftDropMass", ";jet SoftDrop mass (GeV)", 30, 0, 300) hJetsCSV = ROOT.TH1F("hJetsCSV", ";CSV value", 100, 0, 1) hJetsCHF = ROOT.TH1F("hJetsCHF", ";Charged Hadron Fraction", 100, 0, 1) hJet1Pt = ROOT.TH1F("hJet1Pt", ";jet pt (GeV)", 100, 0, 1000) hJet1TrimmedMass = ROOT.TH1F("hJet1TrimmedMass", ";jet Trimmed mass (GeV)", 30, 0, 300) hJet1PrunedMass = ROOT.TH1F("hJet1PrunedMass", ";jet Pruned mass (GeV)", 30, 0, 300) hJet1SoftDropMass = ROOT.TH1F("hJet1SoftDropMass", ";jet SoftDrop mass (GeV)", 30, 0, 300) hJet1CHF = ROOT.TH1F("hJet1CHF", ";Charged Hadron Fraction", 100, 0, 1) #EVENT LOOP events = Events('jettoolbox.root')
def plot(MillePedeUser, alignables, config): logger = logging.getLogger("mpsvalidate") # more space for labels ROOT.gStyle.SetPadBottomMargin(0.25) ROOT.gStyle.SetOptStat("emrs") for mode in ["xyz", "rot"]: big = mpsv_classes.PlotData(mode) # count number of needed bins and max shift for line in MillePedeUser: if (line.ObjId != 1): for i in range(3): if (abs(line.Par[big.data[i]]) != 999999): if (mode == "xyz"): line.Par[big.data[i]] *= 10000 big.numberOfBins[i] += 1 if (abs(line.Par[big.data[i]]) > abs(big.maxShift[i])): big.maxShift[i] = line.Par[big.data[i]] # initialize histograms for i in range(3): big.histo.append( ROOT.TH1F("Big Structure {0} {1}".format(big.xyz[i], mode), "", big.numberOfBins[i], 0, big.numberOfBins[i])) if (big.unit != ""): big.histo[i].SetYTitle("#Delta" + big.xyz[i] + " [" + big.unit + "]") else: big.histo[i].SetYTitle("#Delta" + big.xyz[i]) big.histo[i].SetStats(0) big.histo[i].SetMarkerStyle(21) big.histoAxis.append(big.histo[i].GetXaxis()) # bigger labels for the text big.histoAxis[i].SetLabelSize(0.06) big.histo[i].GetYaxis().SetTitleOffset(1.6) # add labels big.title = ROOT.TPaveLabel(0.1, 0.8, 0.9, 0.9, "High Level Structures {0}".format(mode)) big.text = ROOT.TPaveText(0.05, 0.1, 0.95, 0.75) big.text.SetTextAlign(12) # error if shift is bigger than limit limit = config.limit[mode] for i in range(3): if (big.unit != ""): big.text.AddText("max. shift {0}: {1:.2} {2}".format( big.xyz[i], float(big.maxShift[i]), big.unit)) if (abs(big.maxShift[i]) > limit): big.text.AddText("! {0} shift bigger than {1} {2}".format( big.xyz[i], limit, big.unit)) else: big.text.AddText("max. shift {0}: {1:.2}".format( big.xyz[i], float(big.maxShift[i]))) if (abs(big.maxShift[i]) > limit): big.text.AddText("! {0} shift bigger than {1}".format( big.xyz[i], limit)) # fill histograms with value and name for line in MillePedeUser: if (line.ObjId != 1): for i in range(3): if (abs(line.Par[big.data[i]]) != 999999): # set name of the structure big.histoAxis[i].SetBinLabel( big.binPosition[i], str(line.Name) if len(line.Name) <= 13 else str(line.Name)[:12] + ".") # fill with data, big.data[i] xyz or rot data # transform xyz data from cm to #mu m if (mode == "xyz"): big.histo[i].SetBinContent( big.binPosition[i], 10000 * line.Par[big.data[i]]) else: big.histo[i].SetBinContent(big.binPosition[i], line.Par[big.data[i]]) big.binPosition[i] += 1 # rotate labels for i in range(3): big.histoAxis[i].LabelsOption("v") # reset y range # two types of ranges # 1. show all if (config.rangemodeHL == "all"): for i in range(3): big.usedRange[i] = big.maxShift[i] # 2. use given values if (config.rangemodeHL == "given"): # loop over coordinates for i in range(3): if (mode == "xyz"): valuelist = config.rangexyzHL if (mode == "rot"): valuelist = config.rangerotHL # loop over given values # without last value for value in valuelist: # maximum smaller than given value if (abs(big.maxShift[i]) < value): big.usedRange[i] = value break # if not possible, force highest if (abs(big.maxShift[i]) > valuelist[-1]): big.usedRange[i] = valuelist[-1] # all the same range if (config.samerangeHL == 1): # apply new range for i in range(3): big.usedRange[i] = max(map(abs, big.usedRange)) # count outlieres if (config.rangemodeHL == "given"): for i in range(3): for binNumber in range(1, big.numberOfBins[i] + 1): if (abs(big.histo[i].GetBinContent(binNumber)) > big.usedRange[i]): big.hiddenEntries[i] += 1 # add number of outlieres to text for i in range(3): if (big.hiddenEntries[i] != 0): big.text.AddText("! {0}: {1} outlier !".format( big.xyz[i], int(big.hiddenEntries[i]))) # create canvas cBig = ROOT.TCanvas("canvasBigStrucutres_{0}".format(mode), "Parameter", 300, 0, 800, 600) cBig.Divide(2, 2) # draw histograms cBig.cd(1) big.title.Draw() big.text.Draw() # draw identification ident = mpsv_style.identification(config) ident.Draw() # TGraph copy to hide outlier copy = 3 * [None] # loop over coordinates for i in range(3): cBig.cd(i + 2) # option "AXIS" to only draw the axis big.histo[i].SetLineColor(0) big.histo[i].Draw("AXIS") # set new range big.histo[i].GetYaxis().SetRangeUser(-1.1 * abs(big.usedRange[i]), 1.1 * abs(big.usedRange[i])) # TGraph object to hide outlier copy[i] = ROOT.TGraph(big.histo[i]) # set the new range copy[i].SetMaximum(1.1 * abs(big.usedRange[i])) copy[i].SetMinimum(-1.1 * abs(big.usedRange[i])) # draw the data copy[i].Draw("PSAME") cBig.Update() # save as pdf cBig.Print("{0}/plots/pdf/structures_{1}.pdf".format( config.outputPath, mode)) # export as png image = ROOT.TImage.Create() image.FromPad(cBig) image.WriteImage("{0}/plots/png/structures_{1}.png".format( config.outputPath, mode)) # add to output list output = mpsv_classes.OutputData( plottype="big", parameter=mode, filename="structures_{0}".format(mode)) config.outputList.append(output) # reset BottomMargin ROOT.gStyle.SetPadBottomMargin(0.1)
from BsToPhiMuMuFitter.varCollection import Bmass, CosThetaL, CosThetaK from v2Fitter.Fitter.ToyGenerator import ToyGenerator from v2Fitter.Fitter.FitterCore import FitterCore from BsToPhiMuMuFitter.FitDBPlayer import FitDBPlayer from BsToPhiMuMuFitter.fitCollection import setupSigAFitter import ROOT from BsToPhiMuMuFitter.StdProcess import p import BsToPhiMuMuFitter.pdfCollection as pdfCollection CFG = deepcopy(ToyGenerator.templateConfig()) CFG.update({ 'db': "{0}/input/selected/fitResults_{{binLabel}}.db".format(modulePath), 'argset': ROOT.RooArgSet(Bmass, CosThetaL, CosThetaK), 'argAliasInDB': {}, 'generateOpt': [], 'mixWith': "ToyGenerator.mixedToy", 'scale': 1, }) def decorator_initParameters(func): @functools.wraps(func) def wrapped_f(self): self.pdf = self.process.sourcemanager.get(self.cfg['pdf']) self.argset = self.cfg['argset'] self.params = self.pdf.getParameters(self.argset) FitDBPlayer.initFromDB(self.cfg['db'].format(binLabel=q2bins[self.process.cfg['binKey']]['label']), self.params, self.cfg.get('argAliasInDB', [])) func(self)
##array ref 175 #label = "ArrayRef" #data =[ "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000022_LastRun000039_BAR001752.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000202_LastRun000219_BAR001752.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000361_LastRun000378_BAR001752.root"] ##array pre irr label = "ArrayPreIRR" data =[ "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000361_LastRun000378_BAR001752.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000253_LastRun000270_BAR001892.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000235_LastRun000252_BAR001862.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000379_LastRun000396_BAR001902.root", "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000397_LastRun000414_BAR001872.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000289_LastRun000306_BAR001852.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000325_LastRun000342_BAR001882.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000307_LastRun000324_BAR001922.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000343_LastRun000360_BAR001912.root" ] ##array post irr #label = "ArrayPostIRR" #data = ["/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000040_LastRun000057_BAR001762.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000058_LastRun000075_BAR001822.root", "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000076_LastRun000093_BAR001792.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000094_LastRun000111_BAR001772.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000112_LastRun000129_BAR001802.root", "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000130_LastRun000147_BAR001782.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000148_LastRun000165_BAR001812.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000166_LastRun000183_BAR001832.root" , "/media/cmsdaq/ext/data/LYSOBARSINARRAY/RESULTS/tree_FirstRun000184_LastRun000201_BAR001842.root"] ##--------------------- c1=R.TCanvas("c1","c1",800,800) g_time_vs_th1 = [] gCorr=R.TGraphErrors(len(data)) slopeByProd=R.TGraphErrors(len(data)) timeOffsetByProd=R.TGraphErrors(len(data)) for ip,prod in enumerate(data): print ip, prod firstRun = int(prod.split("/")[-1].split("_")[1].strip("FirstRun").lstrip("0")) print firstRun thisFile = R.TFile(prod) thisFile.Print()
import ROOT from palettable import colorbrewer from itertools import cycle import os f = ROOT.TFile( 'hist-user.cylin.L1CaloSimu.MinimumBias.tag-00-00-17_OUTPUT.root') for objType, objName in [('offline', 'AntiKt4'), ('offline', 'AntiKt10'), ('offline', 'AntiKt10Trimmed'), ('offline', 'CamKt12')]: for kinematic, xaxis_label in zip(['deltaPhi'], ['#Delta#phi']): tex = [] colors = cycle(colorbrewer.qualitative.Set1_9.colors) c = ROOT.TCanvas() leg = ROOT.TLegend(0.8, 0.8, 0.9, 0.9) for selection, drawstyle in zip(['presel', 'postsel'], ['hist', 'hist same']): color = ROOT.TColor.GetColor(*next(colors)) hist = f.Get(os.path.join(selection, objType, objName, kinematic)) hist.SetStats(0) leg.AddEntry(hist, selection, "lf") hist.SetTitle('{0:s}/{1:s}'.format(objType, objName.replace('_', ' '))) hist.GetXaxis().SetTitle( 'leading object {0:s}'.format(xaxis_label)) hist.GetYaxis().SetTitle('Events') hist.GetXaxis().SetTitleOffset(1.3) hist.GetYaxis().SetTitleOffset(1.3) hist.Draw(drawstyle) hist.SetLineColor(color)
def __init_histos(self): #pylint: disable=R0201, R0914 """ Initialise ROOT to display histograms. @param self Object reference. """ # white canvas self.cnv = ROOT.gROOT.SetStyle("Plain") #turn off stat box self.style = ROOT.gStyle.SetOptStat(0) #sensible colour palette self.style = ROOT.gStyle.SetPalette(1) self.eff_plot = ROOT.TH1D("SP_Type", "Space Point Type Across All Stations", 3, 1, 4) self.sp_tr_up = ROOT.TH1D("Tr1pStSp", "Space Points in TkU per Station", 7, 0, 6) #upstream tracker self.sp_tr_up.GetXaxis().SetTitle("Station Number ") self.sp_tr_up.GetXaxis().CenterTitle() self.sp_tr_dn = ROOT.TH1D("Tr2pStSp", "Space Points in TkD per Station", 7, 0, 6) #downstream tracker self.sp_tr_dn.GetXaxis().SetTitle("Station Number ") self.sp_tr_dn.GetXaxis().CenterTitle() self.track1_2Clus = ROOT.TH1D( "Tr1pStSp", "Space Points (2 Clusters) in Tracker1 per Station", 7, 0, 6) self.track1_2Clus.GetXaxis().SetTitle("Station Number ") self.track1_2Clus.GetXaxis().CenterTitle() self.track2_2Clus = ROOT.TH1D( "Tr2pStSp", "Space Points (2 Clusters) in Tracker2 per Station", 7, 0, 6) self.track2_2Clus.GetXaxis().SetTitle("Station Number ") self.track2_2Clus.GetXaxis().CenterTitle() self.track1_3Clus = ROOT.TH1D( "Tr1pStSp", "Space Points (3 Clusters) in Tracker1 per Station", 7, 0, 6) self.track1_3Clus.GetXaxis().SetTitle("Station Number ") self.track1_3Clus.GetXaxis().CenterTitle() self.track2_3Clus = ROOT.TH1D( "Tr2pStSp", "Space Points (3 Clusters) in Tracker2 per Stacdtion", 7, 0, 6) self.track2_3Clus.GetXaxis().SetTitle("Station Number ") self.track2_3Clus.GetXaxis().CenterTitle() for tr in range(0, 2): self.dig_hist[tr] = {} self.spt_hist[tr] = {} self.spd_hist[tr] = {} self.eff_hist[tr] = {} if tr == 0: trs = "U" if tr == 1: trs = "D" sum_name = "Ch_Sum%s" % (trs) sum_titl = "Digit Channel Sum Tk%s" % (trs) self.sum_hist[tr] = ROOT.TH1F(sum_name, sum_titl, 670, -5, 642) self.sum_hist[tr].GetXaxis().SetTitle("Channel Number") self.sum_hist[tr].GetXaxis().CenterTitle() self.sum_hist[tr].SetStats(1) spa_name = "SP_Tk%s" % (trs) spa_titl = "Space Points per Station Tk%s" % (trs) self.spa_hist[tr] = ROOT.TH1D(spa_name, spa_titl, 7, 0, 6) self.spa_hist[tr].GetXaxis().SetTitle("Station Number") self.spa_hist[tr].GetXaxis().CenterTitle() for st in range(1, 6): #within each tracker create 5 stations self.dig_hist[tr][st] = {} eff_name = "Ef_Tk%s%d" % (trs, st) eff_titl = "Space Point Type Tk%s S%d" % (trs, st) self.eff_hist[tr][st] = ROOT.TH1D(eff_name, eff_titl, 3, 1, 4) spt_name = "SP_Pos%s%d" % (trs, st) spt_titl = "Space Point Triplets Tk%s S%d" % (trs, st) self.spt_hist[tr][st] = ROOT.TH2D(spt_name, spt_titl, 50, -200, 200, 50, -200, 200) self.spt_hist[tr][st].GetYaxis().SetTitle("y Position (mm)") self.spt_hist[tr][st].GetXaxis().SetTitle("x Position (mm)") self.spt_hist[tr][st].GetYaxis().CenterTitle() self.spt_hist[tr][st].GetXaxis().CenterTitle() spt_name = "SP_Pos%s%d" % (trs, st) spt_titl = "Space Point Doublets Tk%s S%d" % (trs, st) self.spd_hist[tr][st] = ROOT.TH2D(spt_name, spt_titl, 50, -200, 200, 50, -200, 200) self.spd_hist[tr][st].GetYaxis().SetTitle("y Position (mm)") self.spd_hist[tr][st].GetXaxis().SetTitle("x Position (mm)") self.spd_hist[tr][st].GetYaxis().CenterTitle() self.spd_hist[tr][st].GetXaxis().CenterTitle() for pl in range( 0, 3 ): #create 3 planes in each stations, draw histogram for each of them dig_name = "DC_Tk%s%d%d" % (trs, st, pl) dig_titl = "Digits in Channel Tk%s S%d P%d" % (trs, st, pl) self.dig_hist[tr][st][pl] = ROOT.TH1D( dig_name, dig_titl, 215, 0, 215) self.dig_hist[tr][st][pl].GetXaxis().SetTitle( "Channel Number") self.dig_hist[tr][st][pl].GetXaxis().CenterTitle() # Create canvases # Draw() of histos has to be done only once # for updating the histograms, just Modified() and Update() on canvases # the update/refresh is done in update_histos() self.canvas_SciFiDigitUS = ROOT.TCanvas("Digit_in_Channel_US", "Digit_in_Channel_US", 900, 900) self.canvas_SciFiDigitUS.Divide(3, 5) self.canvas_SciFiDigitUS.cd(1) self.dig_hist[0][1][0].Draw() self.canvas_SciFiDigitUS.cd(2) self.dig_hist[0][1][1].Draw() self.canvas_SciFiDigitUS.cd(3) self.dig_hist[0][1][2].Draw() self.canvas_SciFiDigitUS.cd(4) self.dig_hist[0][2][0].Draw() self.canvas_SciFiDigitUS.cd(5) self.dig_hist[0][2][1].Draw() self.canvas_SciFiDigitUS.cd(6) self.dig_hist[0][2][2].Draw() self.canvas_SciFiDigitUS.cd(7) self.dig_hist[0][3][0].Draw() self.canvas_SciFiDigitUS.cd(8) self.dig_hist[0][3][1].Draw() self.canvas_SciFiDigitUS.cd(9) self.dig_hist[0][3][2].Draw() self.canvas_SciFiDigitUS.cd(10) self.dig_hist[0][4][0].Draw() self.canvas_SciFiDigitUS.cd(11) self.dig_hist[0][4][1].Draw() self.canvas_SciFiDigitUS.cd(12) self.dig_hist[0][4][2].Draw() self.canvas_SciFiDigitUS.cd(13) self.dig_hist[0][5][0].Draw() self.canvas_SciFiDigitUS.cd(14) self.dig_hist[0][5][1].Draw() self.canvas_SciFiDigitUS.cd(15) self.dig_hist[0][5][2].Draw() self.canvas_SciFiDigitDS = ROOT.TCanvas("Digit_in_Channel_DS", "Digit_in_Channel_DS", 900, 900) self.canvas_SciFiDigitDS.Divide(3, 5) self.canvas_SciFiDigitDS.cd(1) self.dig_hist[1][1][0].Draw() self.canvas_SciFiDigitDS.cd(2) self.dig_hist[1][1][1].Draw() self.canvas_SciFiDigitDS.cd(3) self.dig_hist[1][1][2].Draw() self.canvas_SciFiDigitDS.cd(4) self.dig_hist[1][2][0].Draw() self.canvas_SciFiDigitDS.cd(5) self.dig_hist[1][2][1].Draw() self.canvas_SciFiDigitDS.cd(6) self.dig_hist[1][2][2].Draw() self.canvas_SciFiDigitDS.cd(7) self.dig_hist[1][3][0].Draw() self.canvas_SciFiDigitDS.cd(8) self.dig_hist[1][3][1].Draw() self.canvas_SciFiDigitDS.cd(9) self.dig_hist[1][3][2].Draw() self.canvas_SciFiDigitDS.cd(10) self.dig_hist[1][4][0].Draw() self.canvas_SciFiDigitDS.cd(11) self.dig_hist[1][4][1].Draw() self.canvas_SciFiDigitDS.cd(12) self.dig_hist[1][4][2].Draw() self.canvas_SciFiDigitDS.cd(13) self.dig_hist[1][5][0].Draw() self.canvas_SciFiDigitDS.cd(14) self.dig_hist[1][5][1].Draw() self.canvas_SciFiDigitDS.cd(15) self.dig_hist[1][5][2].Draw() self.canvas_SciFiSpacepoints = ROOT.TCanvas( "Spacepoint_Types_in_Stations", "Spacepoint_Types_in_Stations", 800, 600) self.canvas_SciFiSpacepoints.Divide(3, 2) self.canvas_SciFiSpacepoints.cd(1) self.eff_plot.Draw() self.canvas_SciFiSpacepoints.cd(2) self.track1_3Clus.Draw() self.canvas_SciFiSpacepoints.cd(3) self.track2_3Clus.Draw() self.canvas_SciFiSpacepoints.cd(4) self.track1_2Clus.Draw() self.canvas_SciFiSpacepoints.cd(5) self.track2_2Clus.Draw() self.canvas_US_trip = ROOT.TCanvas("Spacepoint_Triplets_Up", "Spacepoint_Triplets_Up", 900, 600) self.canvas_US_trip.Divide(3, 2) self.canvas_US_trip.cd(1) self.spt_hist[0][1].Draw("COL") self.canvas_US_trip.cd(2) self.spt_hist[0][2].Draw("COL") self.canvas_US_trip.cd(3) self.spt_hist[0][3].Draw("COL") self.canvas_US_trip.cd(4) self.spt_hist[0][4].Draw("COL") self.canvas_US_trip.cd(5) self.spt_hist[0][5].Draw("COL") self.canvas_US_doub = ROOT.TCanvas("Spacepoint_Triplets_Down", "Spacepoint_Triplets_Down", 900, 600) self.canvas_US_doub.Divide(3, 2) self.canvas_US_doub.cd(1) self.spt_hist[1][1].Draw("COL") self.canvas_US_doub.cd(2) self.spt_hist[1][2].Draw("COL") self.canvas_US_doub.cd(3) self.spt_hist[1][3].Draw("COL") self.canvas_US_doub.cd(4) self.spt_hist[1][4].Draw("COL") self.canvas_US_doub.cd(5) self.spt_hist[1][5].Draw("COL") self.canvas_DS_trip = ROOT.TCanvas("Spacepoint_Doublets_Up", "Spacepoint_Doublets_Up", 900, 600) self.canvas_DS_trip.Divide(3, 2) self.canvas_DS_trip.cd(1) self.spd_hist[0][1].Draw("COL") self.canvas_DS_trip.cd(2) self.spd_hist[0][2].Draw("COL") self.canvas_DS_trip.cd(3) self.spd_hist[0][3].Draw("COL") self.canvas_DS_trip.cd(4) self.spd_hist[0][4].Draw("COL") self.canvas_DS_trip.cd(5) self.spd_hist[0][5].Draw("COL") self.canvas_DS_doub = ROOT.TCanvas("Spacepoint_Doublets_Down", "Spacepoint_Doublets_Down", 900, 600) self.canvas_DS_doub.Divide(3, 2) self.canvas_DS_doub.cd(1) self.spd_hist[1][1].Draw("COL") self.canvas_DS_doub.cd(2) self.spd_hist[1][2].Draw("COL") self.canvas_DS_doub.cd(3) self.spd_hist[1][3].Draw("COL") self.canvas_DS_doub.cd(4) self.spd_hist[1][4].Draw("COL") self.canvas_DS_doub.cd(5) self.spd_hist[1][5].Draw("COL") self.KunoCanv = ROOT.TCanvas("Kuno Plots", "Kuno Plots", 800, 600) self.KunoCanv.Divide(2, 1) self.KunoCanv.cd(1) self.sum_hist[0].Draw() self.KunoCanv.cd(2) self.sum_hist[1].Draw() return True
def setTree(self, tree, fm): self._fclass = ROOT.TTreeFormula(self.name, self.formula, tree) fm.Add(self._fclass)
def __init__(self, fileToLoad=None, lFilesToLoad=None, degreeSetting=None, cathodeSetting=None, anodeSetting=None): if fileToLoad == None and lFilesToLoad == None: print 'Need to use a file or list of files!' sys.exit() elif fileToLoad == None and lFilesToLoad != None: print 'Given list of files - creating TChain' print 'Note: degree, cathode, and anode setting are fixed' print 'Note: can only use files from the same run' elif fileToLoad != None and lFilesToLoad == None: print 'Given single file - creating TTree' else: print 'Can only give filename OR list of files. Cannot give both!' sys.exit() PARAMETERS_INDEX = neriX_datasets.PARAMETERS_INDEX ANODE_INDEX = neriX_datasets.ANODE_INDEX CATHODE_INDEX = neriX_datasets.CATHODE_INDEX DEGREE_INDEX = neriX_datasets.DEGREE_INDEX dRunFiles = neriX_datasets.run_files lRuns = neriX_datasets.runsInUse lParameters = None if fileToLoad != None: # check neriX_datasets for file and parameters if fileToLoad[-5:] != '.root': fileToLoad += '.root' self.filename = fileToLoad[-22:] # just grab neriX portion for run in lRuns: try: lParameters = dRunFiles[run][self.filename] currentRun = run break except KeyError: continue if not lParameters: print 'File does not appear in neriX_datasets.py' print 'Please check if the file exists and that your spelling is correct' sys.exit() self.runNumber = currentRun if fileToLoad[0] == 'n' or fileToLoad[0] == 'c': pathToFile = neriX_config.pathToData + 'run_' + str( self.runNumber) + '/' + str(fileToLoad) else: pathToFile = fileToLoad self.rootFile = File(pathToFile, 'read') if self.rootFile.keys() == []: print 'Problem opening file - please check name entered' print 'Entered: ' + pathToFile sys.exit(1) self.anodeSetting = dRunFiles[self.runNumber][ self.filename][ANODE_INDEX] self.cathodeSetting = dRunFiles[self.runNumber][ self.filename][CATHODE_INDEX] self.degreeSetting = dRunFiles[self.runNumber][ self.filename][DEGREE_INDEX] # load trees self.T1 = self.rootFile.T1 self.T2 = self.rootFile.T2 self.T3 = self.rootFile.T3 try: self.T4 = self.rootFile.T4 except AttributeError: self.T4 = None self.T1.SetName('T1_' + self.filename) self.T2.SetName('T2_' + self.filename) self.T3.SetName('T3_' + self.filename) if self.T4: self.T4.SetName('T4_' + self.filename) self.T1.create_buffer() self.T2.create_buffer() self.T3.create_buffer() if self.T4: self.T4.create_buffer() self.T1.AddFriend('T2_' + self.filename) self.T2.AddFriend('T1_' + self.filename) self.T1.AddFriend('T3_' + self.filename) if self.T4: self.T1.AddFriend('T4_' + self.filename) if lFilesToLoad != None: # check neriX_datasets for file and parameters for currentFile in lFilesToLoad: if currentFile[-5:] != '.root': currentFile += '.root' # sort files lFilesToLoad.sort() lRootFiles = [] # check run number and set it for run in lRuns: try: # check run of first file lParameters = dRunFiles[run][lFilesToLoad[0][-22:]] currentRun = run break except KeyError: continue if not lParameters: print 'Current file does not appear in neriX_datasets.py' print 'Please check if the file exists and that your spelling is correct' sys.exit() self.runNumber = currentRun # loop through files and add ones that match settings given to init for currentFile in lFilesToLoad: try: lParameters = dRunFiles[self.runNumber][currentFile[-22:]] # check if settings match if lParameters[ DEGREE_INDEX] == degreeSetting and lParameters[ ANODE_INDEX] == anodeSetting and lParameters[ CATHODE_INDEX] == cathodeSetting: # settings match so add proper filename with proper path if currentFile[0] == 'n' or currentFile[0] == 'c': pathToFile = neriX_config.pathToData + 'run_' + str( self.runNumber) + '/' + str(currentFile) else: pathToFile = currentFile lRootFiles.append(pathToFile) print 'Added ' + pathToFile[-22:] + ' to chain.' else: print currentFile[ -22:] + ' does not have proper settings - skipping...' except KeyError: print currentFile[-22:] + ' cannot be found in run ' + str( self.runNumber) # open first file to check if it has T4 branch rootFile = File(lRootFiles[0], 'read') #print TreeChain('T1', lRootFiles[0]).__dict__ self.T1 = TreeChain('T1', lRootFiles) self.T2 = TreeChain('T2', lRootFiles) self.T3 = TreeChain('T3', lRootFiles) try: rootFile.T4 self.T4 = TreeChain('T4', lRootFiles) except: self.T4 = None # erase test file del rootFile self.T1.create_buffer() self.T2.create_buffer() self.T3.create_buffer() if self.T4: self.T4.create_buffer() self.T1.AddFriend('T2') self.T1.AddFriend('T3') if self.T4: self.T1.AddFriend('T4') self.T1.SetName('T1_' + str(degreeSetting) + '_' + str(cathodeSetting) + '_' + str(anodeSetting)) self.T2.SetName('T2_' + str(degreeSetting) + '_' + str(cathodeSetting) + '_' + str(anodeSetting)) self.T3.SetName('T3_' + str(degreeSetting) + '_' + str(cathodeSetting) + '_' + str(anodeSetting)) if self.T4: self.T4.SetName('T4_' + str(degreeSetting) + '_' + str(cathodeSetting) + '_' + str(anodeSetting)) self.anodeSetting = anodeSetting self.cathodeSetting = cathodeSetting self.degreeSetting = degreeSetting # even though not the filename need it for later use self.filename = str(degreeSetting) + '_' + str( cathodeSetting) + '_' + str(anodeSetting) #define helpful aliases self.T1.SetAlias('dt', '(S2sPeak[0]-S1sPeak[0])/100.') self.T1.SetAlias('X', 'S2sPosFann[0][0]') self.T1.SetAlias('Y', 'S2sPosFann[0][1]') if self.T4: self.T1.SetAlias('R', 'sqrt(pow(ctNNPos[0],2)+pow(ctNNPos[1],2))') else: self.T1.SetAlias( 'R', 'sqrt(pow(S2sPosFann[0][0],2)+pow(S2sPosFann[0][1],2))') self.T1.SetAlias('czS1sTotBottom', '(S1sTotBottom[0]/(0.863098 + (-0.00977873)*Z))') self.T1.SetAlias('ctS1sTotBottom', 'czS1sTotBottom') self.T1.SetAlias('s1asym', '(S1sTotTop[0]-S1sTotBottom[0])/S1sTot[0]') self.T1.SetAlias('s2asym', '(S2sTotTop[0]-S2sTotBottom[0])/S2sTot[0]') if self.cathodeSetting == 0.345: self.T1.SetAlias('Z', '-1.511*(S2sPeak[0]-S1sPeak[0])/100') elif self.cathodeSetting == 1.054: self.T1.SetAlias('Z', '-1.717*(S2sPeak[0]-S1sPeak[0])/100') elif self.cathodeSetting == 2.356: self.T1.SetAlias('Z', '-1.958*(S2sPeak[0]-S1sPeak[0])/100') elif self.cathodeSetting == 5.500: self.T1.SetAlias('Z', '-2.208*(S2sPeak[0]-S1sPeak[0])/100') else: print 'Incorrect field entered - cannot correct Z' #will need to change these constants depending on Ge Calibratio self.T1.SetAlias( 'GeEnergy', self.__GERMANIUM_SLOPE + '*GeHeight[0] + ' + self.__GERMANIUM_INTERCEPT) self.T1.SetAlias('eDep', '661.657 - GeEnergy') self.Xrun = '(EventId != -1)' #add a cut so that add statements work # create event list self.eList = root.TEventList('eList_' + self.filename) root.SetOwnership(self.eList, True)
def checkTree(self, tree): fclass = ROOT.TTreeFormula(self.name, self.formula, tree) if fclass.GetNdim() == 1: return True print "Failed to make variable %s for %r" % (self.name, tree) return False
def DrawErrorBand(graph): isErrorBand = graph.GetErrorYhigh(0) != -1 and graph.GetErrorYlow(0) != -1 npoints = graph.GetN() if not isErrorBand: graph.Draw("l same") return # Declare individual TGraph objects used in drawing error band central, min, max = ROOT.TGraph(), ROOT.TGraph(), ROOT.TGraph() shapes = [] for i in range((npoints-1)*4): shapes.append(ROOT.TGraph()) # Set ownership of TGraph objects ROOT.SetOwnership(central, False) ROOT.SetOwnership( min, False) ROOT.SetOwnership( max, False) for shape in shapes: ROOT.SetOwnership(shape, False) # Get data points from TGraphAsymmErrors x, y, ymin, ymax = [], [], [], [] for i in range(npoints): tmpX, tmpY = ROOT.Double(0), ROOT.Double(0) graph.GetPoint(i, tmpX, tmpY) x.append(tmpX) y.append(tmpY) ymin.append(tmpY - graph.GetErrorYlow(i)) ymax.append(tmpY + graph.GetErrorYhigh(i)) # Fill central, min and max graphs for i in range(npoints): central.SetPoint(i, x[i], y[i]) min.SetPoint(i, x[i], ymin[i]) max.SetPoint(i, x[i], ymax[i]) # Fill shapes which will be shaded to create the error band for i in range(npoints-1): for version in range(4): shapes[i+(npoints-1)*version].SetPoint((version+0)%4, x[i], ymax[i]) shapes[i+(npoints-1)*version].SetPoint((version+1)%4, x[i+1], ymax[i+1]) shapes[i+(npoints-1)*version].SetPoint((version+2)%4, x[i+1], ymin[i+1]) shapes[i+(npoints-1)*version].SetPoint((version+3)%4, x[i], ymin[i]) # Set attributes to those of input graph central.SetLineColor(graph.GetLineColor()) central.SetLineStyle(graph.GetLineStyle()) central.SetLineWidth(graph.GetLineWidth()) min.SetLineColor(graph.GetLineColor()) min.SetLineStyle(graph.GetLineStyle()) max.SetLineColor(graph.GetLineColor()) max.SetLineStyle(graph.GetLineStyle()) for shape in shapes: shape.SetFillColor(graph.GetFillColor()) shape.SetFillStyle(graph.GetFillStyle()) # Draw for shape in shapes: shape.Draw("f same") min.Draw("l same") max.Draw("l same") #central.Draw("l same") #min.Draw("same") #max.Draw("same") #central.Draw("same") ROOT.gPad.RedrawAxis()
def loadBackgroundShape(ws,useShapeUncert=False): bkg_a = RooRealVar('bkg_a_dimuon_2017_BB','bkg_a_dimuon_2017_BB', 20.08967958) bkg_b = RooRealVar('bkg_b_dimuon_2017_BB','bkg_b_dimuon_2017_BB',-0.000726469552191) bkg_c = RooRealVar('bkg_c_dimuon_2017_BB','bkg_c_dimuon_2017_BB',-5.30536993745e-08) bkg_d = RooRealVar('bkg_d_dimuon_2017_BB','bkg_d_dimuon_2017_BB',-4.87301932e-12) bkg_e = RooRealVar('bkg_e_dimuon_2017_BB','bkg_e_dimuon_2017_BB',-4.04060321483) bkg_a2 = RooRealVar('bkg_a2_dimuon_2017_BB','bkg_a2_dimuon_2017_BB', 8.74986890797) bkg_b2 = RooRealVar('bkg_b2_dimuon_2017_BB','bkg_b2_dimuon_2017_BB',-0.0146386650943) bkg_c2 = RooRealVar('bkg_c2_dimuon_2017_BB','bkg_c2_dimuon_2017_BB', 8.66470108875e-06) bkg_e2 = RooRealVar('bkg_e2_dimuon_2017_BB','bkg_e2_dimuon_2017_BB',-1.43336705959) bkg_a.setConstant() bkg_b.setConstant() bkg_c.setConstant() bkg_d.setConstant() bkg_e.setConstant() bkg_a2.setConstant() bkg_b2.setConstant() bkg_c2.setConstant() bkg_e2.setConstant() getattr(ws,'import')(bkg_a,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_b,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_c,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_d,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_e,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_a2,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_b2,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_c2,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_e2,ROOT.RooCmdArg()) # background systematics bkg_syst_a = RooRealVar('bkg_syst_a','bkg_syst_a',1.0) bkg_syst_b = RooRealVar('bkg_syst_b','bkg_syst_b',0.0) #bkg_syst_b = RooRealVar('bkg_syst_b','bkg_syst_b',-0.00016666666666) bkg_syst_a.setConstant() bkg_syst_b.setConstant() getattr(ws,'import')(bkg_syst_a,ROOT.RooCmdArg()) getattr(ws,'import')(bkg_syst_b,ROOT.RooCmdArg()) # background shape if useShapeUncert: bkgParamsUncert = provideUncertainties(1000)["bkgParams"] for uncert in bkgParamsUncert: addBkgUncertPrior(ws,uncert,"dimuon_2017_BB",bkgParamsUncert[uncert] ) #addBkgUncertPrior(ws,uncert,"dimuon_2017_BB",0.1 ) ws.factory("ZPrimeMuonBkgPdf2::bkgpdf_dimuon_2017_BB(mass_dimuon_2017_BB, bkg_a_dimuon_2017_BB_forUse, bkg_b_dimuon_2017_BB_forUse, bkg_c_dimuon_2017_BB_forUse,bkg_d_dimuon_2017_BB_forUse,bkg_e_dimuon_2017_BB_forUse,bkg_a2_dimuon_2017_BB_forUse, bkg_b2_dimuon_2017_BB_forUse, bkg_c2_dimuon_2017_BB_forUse,bkg_e2_dimuon_2017_BB_forUse,bkg_syst_a,bkg_syst_b)") ws.factory("ZPrimeMuonBkgPdf2::bkgpdf_fullRange(massFullRange, bkg_a_dimuon_2017_BB_forUse, bkg_b_dimuon_2017_BB_forUse, bkg_c_dimuon_2017_BB_forUse,bkg_d_dimuon_2017_BB_forUse,bkg_e_dimuon_2017_BB_forUse, bkg_a2_dimuon_2017_BB_forUse, bkg_b2_dimuon_2017_BB_forUse, bkg_c2_dimuon_2017_BB_forUse,bkg_e2_dimuon_2017_BB,bkg_syst_a,bkg_syst_b)") else: ws.factory("ZPrimeMuonBkgPdf2::bkgpdf_dimuon_2017_BB(mass_dimuon_2017_BB, bkg_a_dimuon_2017_BB, bkg_b_dimuon_2017_BB, bkg_c_dimuon_2017_BB,bkg_d_dimuon_2017_BB,bkg_e_dimuon_2017_BB,bkg_a2_dimuon_2017_BB, bkg_b2_dimuon_2017_BB, bkg_c2_dimuon_2017_BB,bkg_e2_dimuon_2017_BB,bkg_syst_a,bkg_syst_b)") ws.factory("ZPrimeMuonBkgPdf2::bkgpdf_fullRange(massFullRange, bkg_a_dimuon_2017_BB, bkg_b_dimuon_2017_BB, bkg_c_dimuon_2017_BB,bkg_d_dimuon_2017_BB,bkg_e_dimuon_2017_BB, bkg_a2_dimuon_2017_BB, bkg_b2_dimuon_2017_BB, bkg_c2_dimuon_2017_BB,bkg_e2_dimuon_2017_BB,bkg_syst_a,bkg_syst_b)") return ws
elif 360 - iphi < off: diff = off - (360 - iphi) img_crop = np.concatenate( (imgECAL[:, ieta - off:ieta + off + 1, iphi - off:], imgECAL[:, ieta - off:ieta + off + 1, :diff + 1]), axis=-1) # Nominal case else: img_crop = imgECAL[:, ieta - off:ieta + off + 1, iphi - off:iphi + off + 1] return img_crop rhTreeStr = args.infile rhTree = ROOT.TChain("fevt/RHTree") rhTree.Add(rhTreeStr) nEvts = rhTree.GetEntries() assert nEvts > 0 print " >> Input file:", rhTreeStr print " >> nEvts:", nEvts outStr = '%s/%s.parquet.%d' % (args.outdir, args.decay, args.idx) print " >> Output file:", outStr ##### MAIN ##### # Event range to process iEvtStart = 0 #iEvtEnd = 10 iEvtEnd = nEvts assert iEvtEnd <= nEvts
from sys import argv, stdout, stderr import getopt import ROOT import sys import math import array import numpy ROOT.gROOT.LoadMacro("tdrstyle.C") ROOT.setTDRStyle() ROOT.gROOT.SetStyle("Plain") ROOT.gROOT.SetBatch(True) ROOT.gStyle.SetOptStat(0) fileFit = ROOT.TFile("ForAaron_fakes_tJetPt.root") ntupleFit = fileFit.Get("datacorHisto_Ratio").Clone() fit = ntupleFit.Fit("pol1","","",30.0,230.0) canvas = ROOT.TCanvas("canvas","canvas",800,800) ntupleFit.GetYaxis().SetTitle("Fake Rate Factor") ntupleFit.GetYaxis().SetTitleOffset(0.9) ntupleFit.GetYaxis().SetLabelSize(0.035) ntupleFit.GetYaxis().SetTitleSize(0.05) ntupleFit.GetXaxis().SetTitleOffset(0.9) ntupleFit.GetXaxis().SetLabelSize(0.035) ntupleFit.GetXaxis().SetTitleSize(0.05) ntupleFit.GetXaxis().SetTitle("Tau Jet Pt") ntupleFit.Draw() canvas.SaveAs("FakeFitLine.png")
def drawHist(hist,name,width=500,height=500, drawoptions=""): customROOTstyle() c = ROOT.TCanvas("c","c",width,height) #hist.SetLineWidth(2) hist.Draw(drawoptions) c.SaveAs(name)
def finalize(self): self.cd() for iv in range(self.nvert): distpad = self.GetPad(iv * 2 + 1) ratiopad = self.GetPad(iv * 2 + 2) distpad.Update() frame = distpad.GetListOfPrimitives().At(1) rframe = ratiopad.GetListOfPrimitives().At(1) if not frame or not rframe: continue xaxis = frame.GetXaxis() uxmin = xaxis.GetXmin() disty1 = distpad.GetYlowNDC() if self.wide_labels is not None: dataset_divider = ROOT.TLine(0., 0., 0., 0.) dataset_divider.SetLineStyle(ROOT.kDotted) dataset_divider.SetLineWidth(1) dataset_divider.SetLineColor(ROOT.kBlack) dataset_label = ROOT.TLatex(0., 0., '') dataset_label.SetTextFont(42) dataset_label.SetTextAlign(11) dataset_label.SetTextSize(0.05 * self.nvert) uxmax = xaxis.GetBinUpEdge(xaxis.GetNbins() / len(self.wide_labels[iv])) xwidth = uxmax - uxmin x1 = distpad.GetXlowNDC() xlen = distpad.GetWNDC() / len(self.wide_labels[iv]) for il, label in enumerate(self.wide_labels[iv]): xdiv = xaxis.GetBinUpEdge(xaxis.GetNbins() / len(self.wide_labels[iv]) * il) distpad.cd() dataset_label.DrawLatex(xdiv + 0.05 * xwidth, frame.GetMaximum() * 0.85, label) if il != 0: dataset_divider.DrawLine(xdiv, frame.GetMinimum(), xdiv, frame.GetMaximum()) ratiopad.cd() dataset_divider.DrawLine(xdiv, rframe.GetMinimum(), xdiv, rframe.GetMaximum()) self.cd() # dist pad self.xaxis.DrawAxis(x1, disty1, x1 + xlen, disty1, uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) newaxis = self.GetListOfPrimitives().Last() newaxis.SetLabelSize(0.) newaxis.SetTitle('') # ratio pad self.xaxis.DrawAxis(x1, self.raxes[iv].GetY1(), x1 + xlen, self.raxes[iv].GetY1(), uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) newaxis = self.GetListOfPrimitives().Last() if iv != 0: newaxis.SetLabelSize(0.) else: newaxis.SetBit(ROOT.TAxis.kCenterLabels, self.xaxis.TestBit(ROOT.TAxis.kCenterLabels)) for args in self.xaxis._label_mods: newaxis.ChangeLabel(*args) if iv != 0 or il != len(self.wide_labels[iv]) - 1: newaxis.SetTitle('') x1 += xlen else: uxmax = xaxis.GetBinUpEdge(xaxis.GetNbins() / len(self.wide_labels[iv])) # dist pad self.xaxis.DrawAxis(self.xaxis.GetX1(), disty1, self.xaxis.GetX2(), disty1, uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) newaxis = self.GetListOfPrimitives().Last() newaxis.SetLabelSize(0.) newaxis.SetTitle('') # ratio pad self.xaxis.DrawAxis(x1, self.raxes[iv].GetY1(), x1 + xlen, self.raxes[iv].GetY1(), uxmin, uxmax, self.xaxis.GetNdiv(), self.xaxis.GetOption(), self.xaxis.GetGridLength()) if iv != 0: newaxis.SetLabelSize(0.) else: newaxis.SetBit(ROOT.TAxis.kCenterLabels, self.xaxis.TestBit(ROOT.TAxis.kCenterLabels)) if iv != 0 or il != len(self.wide_labels[iv]) - 1: newaxis.SetTitle('') self.cd() uymin = distpad.GetUymin() uymax = distpad.GetUymax() if len(self.yaxes) != 0: self.yaxes[iv].SetWmin(uymin) self.yaxes[iv].SetWmax(uymax) self.yaxes[iv].Draw() urmin = ratiopad.GetUymin() urmax = ratiopad.GetUymax() self.raxes[iv].SetWmin(urmin) self.raxes[iv].SetWmax(urmin + (urmax - urmin) * 0.95) self.raxes[iv].Draw() distpad.RedrawAxis() ratiopad.RedrawAxis() self.cd() self.cmsLabel.Draw() self.lumiLabel.Draw() self.Update()
def doULPlot(suffix): xbins = array('d', []) xbins_env = array('d', []) ybins_exp = array('d', []) ybins_obs = array('d', []) ybins_1s = array('d', []) ybins_2s = array('d', []) ybins_th = array('d', []) for i in range(len(mass)): curFile = "higgsCombine_lim_%s%03d%s.Asymptotic.mH%03d.root" % ( options.signalmodel, mass[i], suffix, mass[i]) print "curFile: %s" % curFile if options.lvqqBR: sf = table_signalscale[mass[i]] * xsDict_lvj[mass[i]] #*0.1057*0.577; # BR(W->munu)*BR(H->bb) else: sf = table_signalscale[mass[i]] * xsDict[mass[i]] curAsymLimits = getAsymLimits(curFile) #print mass[i] #print curAsymLimits #raw_input("zixu") xbins.append(mass[i] / 1000.) #GeV->TeV xbins_env.append(mass[i] / 1000.) ybins_exp.append(curAsymLimits[3] * sf) ybins_obs.append(curAsymLimits[0] * sf) ybins_2s.append(curAsymLimits[1] * sf) ybins_1s.append(curAsymLimits[2] * sf) #ybins_th.append(sf);#/20.); #*0.25); if options.lvqqBR: ybins_th.append(xsDict_lvj[mass[i]]) #/20.); #*0.25); else: ybins_th.append(xsDict[mass[i]]) #/20.); #*0.25); for i in range(len(mass) - 1, -1, -1): curFile = "higgsCombine_lim_%s%03d%s.Asymptotic.mH%03d.root" % ( options.signalmodel, mass[i], suffix, mass[i]) print "curFile: %s" % curFile if options.lvqqBR: sf = table_signalscale[mass[i]] * xsDict_lvj[mass[i]] #*0.1057*0.577; # BR(W->munu)*BR(H->bb) else: sf = table_signalscale[mass[i]] * xsDict[mass[i]] curAsymLimits = getAsymLimits(curFile) xbins_env.append(mass[i] / 1000.) ybins_2s.append(curAsymLimits[5] * sf) ybins_1s.append(curAsymLimits[4] * sf) nPoints = len(mass) curGraph_exp = ROOT.TGraphAsymmErrors(nPoints, xbins, ybins_exp) curGraph_obs = ROOT.TGraphAsymmErrors(nPoints, xbins, ybins_obs) curGraph_th = ROOT.TGraph(nPoints, xbins, ybins_th) curGraph_1s = ROOT.TGraphAsymmErrors(nPoints * 2, xbins_env, ybins_1s) curGraph_2s = ROOT.TGraphAsymmErrors(nPoints * 2, xbins_env, ybins_2s) curGraph_obs.SetMarkerStyle(20) curGraph_obs.SetLineWidth(3) curGraph_obs.SetLineStyle(1) curGraph_obs.SetMarkerSize(1.6) curGraph_exp.SetMarkerSize(1.3) curGraph_exp.SetMarkerColor(ROOT.kBlack) curGraph_exp.SetLineStyle(2) curGraph_exp.SetLineWidth(3) curGraph_exp.SetMarkerSize(2) curGraph_exp.SetMarkerStyle(24) curGraph_exp.SetMarkerColor(ROOT.kBlack) #curGraph_th.SetLineStyle(ROOT.kDashed); curGraph_th.SetFillStyle(3344) curGraph_th.SetLineWidth(2) curGraph_th.SetMarkerSize(2) curGraph_th.SetLineColor(ROOT.kRed) curGraph_1s.SetFillColor(ROOT.kGreen) curGraph_1s.SetFillStyle(1001) curGraph_1s.SetLineStyle(ROOT.kDashed) curGraph_1s.SetLineWidth(3) curGraph_2s.SetFillColor(ROOT.kYellow) curGraph_2s.SetFillStyle(1001) curGraph_2s.SetLineStyle(ROOT.kDashed) curGraph_2s.SetLineWidth(3) oneLine = ROOT.TF1("oneLine", "1", 799, 1001) oneLine.SetLineColor(ROOT.kRed) oneLine.SetLineWidth(3) setStyle() can_SM = ROOT.TCanvas("can_SM", "can_SM", 630, 600) hrl_SM = can_SM.DrawFrame(mass[0] / 1000. - 0.01, 1e-4, mass[nPoints - 1] / 1000. + 0.01, 1e2) if options.signalmodel == "BulkGravWW": if options.lvqqBR: hrl_SM.GetYaxis().SetTitle( "#sigma_{95%} (pp #rightarrow G_{Bulk} #rightarrow WW #rightarrow l#nuqq') (pb)" ) else: hrl_SM.GetYaxis().SetTitle( "#sigma_{95%} (pp #rightarrow G_{Bulk} #rightarrow WW) (pb)") elif options.signalmodel == "WprimeWZ": if options.lvqqBR: hrl_SM.GetYaxis().SetTitle( "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ #rightarrow l#nuqq') (pb)" ) else: hrl_SM.GetYaxis().SetTitle( "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ) (pb)") elif options.signalmodel == "WprimeWZ-HVT-A": if options.lvqqBR: hrl_SM.GetYaxis().SetTitle( "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ #rightarrow l#nuqq') (pb)" ) else: hrl_SM.GetYaxis().SetTitle( "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ) (pb)") hrl_SM.GetYaxis().SetTitleOffset(1.35) hrl_SM.GetYaxis().SetTitleSize(0.045) hrl_SM.GetYaxis().SetTitleFont(42) if options.signalmodel == "BulkGravWW": hrl_SM.GetXaxis().SetTitle("M_{G_{Bulk}} (TeV)") elif options.signalmodel == "WprimeWZ": hrl_SM.GetXaxis().SetTitle("M_{W'} (TeV)") elif options.signalmodel == "WprimeWZ-HVT-A": hrl_SM.GetXaxis().SetTitle("M_{W'} (TeV)") hrl_SM.GetXaxis().SetTitleSize(0.045) hrl_SM.GetXaxis().SetTitleFont(42) hrl_SM.GetXaxis().SetNdivisions(510) hrl_SM.GetYaxis().SetNdivisions(505) can_SM.SetGridx(1) can_SM.SetGridy(1) curGraph_2s.Draw("F") curGraph_1s.Draw("Fsame") if options.keepblind == 0: curGraph_obs.Draw("PLsame") curGraph_exp.Draw("Lsame") curGraph_th.Draw("Csame") leg2 = ROOT.TLegend(0.32, 0.67, 0.9, 0.92) leg2.SetFillColor(0) leg2.SetShadowColor(0) leg2.SetTextFont(42) leg2.SetTextSize(0.035) leg2.AddEntry(curGraph_1s, "Asympt. CL_{S} Expected #pm 1 s.d.", "LF") leg2.AddEntry(curGraph_2s, "Asympt. CL_{S} Expected #pm 2 s.d.", "LF") if options.signalmodel == "BulkGravWW": if options.lvqqBR: leg2.AddEntry( curGraph_th, "#sigma_{TH} #times BR(G_{Bulk}#rightarrow WW#rightarrow l#nuqq'), #tilde{k}=0.5", "L") else: leg2.AddEntry( curGraph_th, "#sigma_{TH} #times BR(G_{Bulk}#rightarrow WW), #tilde{k}=0.5", "L") elif options.signalmodel == "WprimeWZ": if options.lvqqBR: leg2.AddEntry( curGraph_th, "#sigma_{TH} #times BR(W'_{HVT B}#rightarrow WZ#rightarrow l#nuqq')", "L") else: leg2.AddEntry(curGraph_th, "#sigma_{TH} #times BR(W'_{HVT B}#rightarrow WZ)", "L") elif options.signalmodel == "WprimeWZ-HVT-A": if options.lvqqBR: leg2.AddEntry( curGraph_th, "#sigma_{TH} #times BR(W'_{HVT A}#rightarrow WZ#rightarrow l#nuqq')", "L") else: leg2.AddEntry(curGraph_th, "#sigma_{TH} #times BR(W'_{HVT A}#rightarrow WZ)", "L") leg2.AddEntry(curGraph_obs, "Asympt. CL_{S} Observed", "LP") #ROOT.gPad.SetLogx(); #hrl_SM.GetXaxis().SetMoreLogLabels() #hrl_SM.GetXaxis().SetNoExponent() ROOT.gPad.SetLogy() can_SM.Update() can_SM.RedrawAxis() can_SM.RedrawAxis("g") can_SM.Update() leg2.Draw() line = TLine(1.1, 1e-4, 1.1, 1e0) line.SetLineWidth(2) line.SetLineColor(kBlack) line.SetLineStyle(9) line.Draw() banner = TLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % (Lumi)) banner.SetNDC() banner.SetTextSize(0.038) banner.SetTextFont(42) banner.SetTextAlign(31) banner.SetLineWidth(2) banner.Draw() CMStext = TLatex(0.15, 0.96, "CMS") CMStext.SetNDC() CMStext.SetTextSize(0.041) CMStext.SetTextFont(61) CMStext.SetTextAlign(11) CMStext.SetLineWidth(2) CMStext.Draw() if suffix == "_el_HP": Extratext = TLatex(0.241, 0.96, "Preliminary W#rightarrow e#nu") Extratext.SetNDC() Extratext.SetTextSize(0.032) Extratext.SetTextFont(52) Extratext.SetTextAlign(11) Extratext.SetLineWidth(2) Extratext.Draw() elif suffix == "_mu_HP": Extratext = TLatex(0.241, 0.96, "Preliminary W#rightarrow #mu#nu") Extratext.SetNDC() Extratext.SetTextSize(0.032) Extratext.SetTextFont(52) Extratext.SetTextAlign(11) Extratext.SetLineWidth(2) Extratext.Draw() elif suffix == "_em_HP": Extratext = TLatex(0.241, 0.96, "Preliminary W#rightarrow l#nu") Extratext.SetNDC() Extratext.SetTextSize(0.032) Extratext.SetTextFont(52) Extratext.SetTextAlign(11) Extratext.SetLineWidth(2) Extratext.Draw() #CMS_lumi.lumi_13TeV = "%s fb^{-1}"%(Lumi) #CMS_lumi.writeExtraText = 1 #CMS_lumi.extraText = "Preliminary" #iPos = 11 #if(iPos == 0): # CMS_lumi.relPosX = 0.15 #CMS_lumi.CMS_lumi(can_SM, 4, 11) os.system("mkdir -p %s/LimitResult/" % (os.getcwd())) os.system("mkdir -p %s/LimitResult/Limit_%s_sys%s/" % (os.getcwd(), options.signalmodel, options.Sys)) can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s.png" % (options.signalmodel, options.Sys, suffix)) can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s.pdf" % (options.signalmodel, options.Sys, suffix)) #can_SM.SaveAs("./LimitResult/Limit_sys%s/Lim%s.root"%(options.Sys, suffix)); can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s.C" % (options.signalmodel, options.Sys, suffix)) ROOT.gPad.SetLogx() hrl_SM.GetXaxis().SetMoreLogLabels() hrl_SM.GetXaxis().SetNoExponent() can_SM.Update() can_SM.RedrawAxis() can_SM.RedrawAxis("g") leg2.Draw() can_SM.Update() can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s_Logx.png" % (options.signalmodel, options.Sys, suffix)) can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s_Logx.pdf" % (options.signalmodel, options.Sys, suffix)) can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s_Logx.C" % (options.signalmodel, options.Sys, suffix))
_h.SetBinError(_bin, h.GetBinError(_bin)) _h.GetXaxis().SetTitle(h.GetXaxis().GetTitle()) _h.GetYaxis().SetTitle(h.GetYaxis().GetTitle()) return _h if __name__ == "__main__": gROOT.ProcessLine('.L ' + GALAPAGOPATH + 'include/tdrstyle.C') gROOT.SetBatch(1) print('WORKPATH: ' + WORKPATH) r.setTDRStyle() ########################### #### Parser object #### ########################### parser = optparse.OptionParser(usage='usage: %prog [opts] FilenameWithSamples', version='%prog 1.0') parser.add_option('-t', '--tag', action='store', type=str, dest='tag', default='', help='Output tag') (opts, args) = parser.parse_args() ############################## #### Some definitions #### ############################## ptbin = np.concatenate((np.arange(0, 90, 5, float), np.arange(90, 130, 10), np.arange(130, 190, 15), np.arange(190, 260, 40), np.array([300]))) ######################## #### Histograms ####
#!/usr/bin/env python import ROOT as r import sys sys.path.append("../") import Plotter as p writePath ='~/Documents/Presentations/2018/181202-CCStatus/' r.gSystem.Load('../../lib/LUTClasses_cpp') r.gSystem.Load('../../lib/PatternFinderHelperFunctions_cpp') r.gSystem.Load('../../lib/PatternFinderClasses_cpp') lut = r.LUT("test", "../../dat/linearFits.lut"); #lut.printPython() lut.makeFinal() slopes_h = r.TH1F("slopes",";Slope [strips/layer]; Comparator Codes", 50, -1.6,1.6) for [key, entry] in lut: #print entry.slope() if(entry._layers < 3): continue slopes_h.Fill(entry.slope()) can = p.Canvas(lumi='') slopes = p.Plot(slopes_h,legType= 'l',legName='#splitline{#bf{Entries}: %i}{#bf{UFlow}: %i #bf{OFlow}: %i}'\ %(slopes_h.GetEntries(), slopes_h.GetBinContent(0), slopes_h.GetBinContent(slopes_h.GetNbinsX()+1)), option='hist') can.addMainPlot(slopes)
# main_hist = tmp_file.Get("shapes_fit_s/CAT%d/total"%cat) # main_hist.SetBit(ROOT.TH1F.kIsAverage) # violin_hist = ROOT.TH2F("violin_CAT%d"%cat,"violin_CAT%d"%cat,10,80,200,10,0,10000) # all_hists.append(main_hist) len=0 for num,file in enumerate(files): tmp_file = ROOT.TFile.Open(file) if tmp_file.cd("shapes_fit_b")==False : continue tmp_hist = tmp_file.Get("shapes_fit_b/CAT%d/total"%cat) for i in range(0,tmp_hist.GetNbinsX()): tmp_hist.SetBinContent(i+1,tmp_hist.GetBinContent(i+1)*tmp_hist.GetBinWidth(i+1)) all_hists.append(tmp_hist) data_gr = tmp_file.Get("shapes_fit_b/CAT%d/data"%cat) data_hist = ROOT.TH1F("data_hist_CAT%d"%cat,"data_hist_CAT%d"%cat,1200,80,200) for bin in range(0,1200): tmp_x=ROOT.Double(0) tmp_y=ROOT.Double(0) data_gr.GetPoint(bin,tmp_x,tmp_y) data_hist.SetBinContent(bin+1,tmp_y) data_hist.SetBinError(bin+1,data_gr.GetErrorYhigh(bin)) #print tmp_x, tmp_y, data_hist.GetBinCenter(bin+1),data_hist.GetBinContent(bin+1) for i in range(0,data_hist.GetNbinsX()): data_hist.SetBinContent(i+1,data_hist.GetBinContent(i+1)*data_hist.GetBinWidth(i+1)) data_hist.SetBinError(i+1,data_hist.GetBinError(i+1)*data_hist.GetBinWidth(i+1)) all_toys_data.append(data_hist) len=len+1
def MakePullPlot(name='pulls', title='title', xtitle='xtitle', xlow=0, xhigh=3, names=[], values=(), colors=(), addvalues=True, valuesasint=True): # creates a plot with horizontal bars n = len(values) # set all colors to gray if not given while len(colors) < len(values): colors.append(root.kGray) # set name to integers if not given par = len(names) + 1 while len(names) < len(values): names.append('parameter %i' % par) par += 1 c = MakePullTCanvas(name, title, n) c.Draw() if max(values) > xhigh: xhigh = max(values) * 1.05 histname = name + "hist" th1d_frame = MakeTH1D(histname, histname, 1000, xlow, xhigh, xtitle, "", 0) # th1d_frame.GetYaxis().SetRangeUser(0., float(n)) th1d_frame.GetYaxis().SetLabelOffset(999) #//"remove" y-axis label th1d_frame.GetYaxis().SetLabelSize(0) # //"remove" y-axis label th1d_frame.GetYaxis().SetTickLength(0) # //"remove" y-axis ticks th1d_frame.GetXaxis().CenterTitle() th1d_frame.Draw("AXIS") th1d_frame.GetXaxis().SetNdivisions(505) root.gPad.Update() # //need NDC coordinates... b = c.GetBottomMargin() t = c.GetTopMargin() r = c.GetRightMargin() l = c.GetLeftMargin() diff = (1. - t) - b # //"histogram" height step = diff / (float(n)) #//height per entry boxes = [] texts = [] textvalues = [] for i in range(n): # //add text, one per value, use same values for the boxes x1 = 0. y1 = b + i * step + step / 4. x2 = l - 0.015 y2 = b + i * step + step / 4. + step / 2. box = AddVerticalBox(min(0, values[i]), max(0, values[i]), 0.25 + i, 0.75 + i, colors[i], 1.0, 1001, names[i]) box.SetLineStyle(1) box.SetLineColor(root.kBlack) box.SetLineWidth(2) boxes.append(box) box.Draw('LF') tp = root.TPaveText(x1, y1, x2, y2, "NDC") tp.SetBorderSize(0) tp.SetMargin(0) tp.SetTextAlign(32) tp.SetTextColor(root.kBlack) tp.AddText(0.0, 0.0, names[i]) tp.SetFillColor(0) tp.SetFillStyle(0) tp.SetTextSize(root.gStyle.GetTitleSize("X") * 0.8) texts.append(tp) tp.Draw() x1 = 1. - r + 0.015 x2 = 1. if addvalues: tpv = root.TPaveText(x1, y1, x2, y2, "NDC") tpv.SetBorderSize(0) tpv.SetMargin(0) tpv.SetTextAlign(12) tpv.SetTextColor(root.kBlack) if valuesasint: tpv.AddText(0.0, 0.0, ' %i' % int(values[i])) else: tpv.AddText(0.0, 0.0, ' %3.3f' % values[i]) textvalues.append(tpv) tpv.SetFillColor(0) tpv.SetFillStyle(0) tpv.SetTextSize(root.gStyle.GetTitleSize("X") * 0.8) tpv.AppendPad() return c, th1d_frame, boxes, texts, textvalues
def scalePtHardHistos(referenceFile): PtHardBins = 20 ptHardLo = [ 5, 7, 9, 12, 16, 21, 28, 36, 45, 57, 70, 85, 99, 115, 132, 150, 169, 190, 212, 235 ] ptHardHi = [ 7, 9, 12, 16, 21, 28, 36, 45, 57, 70, 85, 99, 115, 132, 150, 169, 190, 212, 235, -1 ] # Option to remove outliers from specified histograms (see below) bRemoveOutliers = False #bRemoveOutliers = True outlierLimit=2 outlierNBinsThreshold=4 # Get a list of all the output list names, in order to scale all of them f = ROOT.TFile("1/AnalysisResultsPtHard1.root", "READ") qaListKeys = f.GetListOfKeys() qaListNames = [] eventList = "" for key in qaListKeys: name = key.GetName() # Get all relevant lists for which scaling should be done if referenceFile: if "PWGJEQA" in name or "Jet" in name or "Emcal" in name: # For the case of using reference scale factors, we want essentially all user tasks qaListNames.append(name) else: print("Nothing added to qaListNames from reference file") print(name) else: if "PWGJEQA" in name: # For the case of computing the scale factors, we want only the PWGJEQA task qaListNames.append(name) else: print("Nothing added to qaListNames") print(name) # Get a list that has the event histograms if "PWGJEQA" in name or "JetPerformance" in name: eventList = name # Note: In the case of embedding, we assume that we only need the number of accepted events, and that internal event selection # is activated, in which case the event count can be read from any task that has the internal event selection applied print("Using " + eventList + " for event list.") f.Close() print("......... Get the Number of events .........") # Create histogram of NEvents accepted and NEvents acc+rej, as a function of pT-hard bin hNEventsAcc = ROOT.TH1F("hNEventsAcc", "hNEventsAccepted", PtHardBins+1, 0, PtHardBins+1) hNEventsTot = ROOT.TH1F("hNEventsTot", "hNEventsTotal", PtHardBins+1, 0, PtHardBins+1) nEventsAccSum = 0 nEventsTotSum=0 for bin in range(0,PtHardBins): hNEventsAcc.GetXaxis().SetBinLabel(bin+1, "%d-%d" % (ptHardLo[bin],ptHardHi[bin])) hNEventsTot.GetXaxis().SetBinLabel(bin+1, "%d-%d" % (ptHardLo[bin],ptHardHi[bin])) for bin in range(0,PtHardBins): nNEventsTot= GetNEvents(eventList, bin, hNEventsTot, bAcceptedEventsOnly=False) nEventsAcc = GetNEvents(eventList, bin, hNEventsAcc, bAcceptedEventsOnly=True) nEventsAccSum += nEventsAcc nEventsTotSum += nNEventsTot nEventsAccAvg = nEventsAccSum/PtHardBins nNEventsTotAvg= nEventsTotSum/PtHardBins print("......... Start the scaling .........") # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If a reference file is provided, get the scale factors from there, and scale histos # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if referenceFile: print("ooo Get Scale Factors from merged Reference") print("ooo file: " + referenceFile) controlFile = open('ControlTable.txt', 'w') # This is a measure to check the factors used for the single bins controlFile.write('| *Bin* | *pT-hard range (!GeV)* | *Factor From File* | *Factor Applied (xEvtFactor)* |\n') for bin in range(0,PtHardBins): # Open ref file and get scale factor for given bin refFile = ROOT.TFile(referenceFile, "READ") scaleFactorHist = refFile.Get("hScaleFactor") scaleFactor = scaleFactorHist.GetBinContent(bin+1) refFile.Close() # Open input file and get relevant lists inputFile = "{0}/AnalysisResultsPtHard{0}.root".format(bin+1) print("................................................................") print("ooo Scaling Pt-hard bin %d" % (bin+1)) f = ROOT.TFile(inputFile, "UPDATE") # Scale further to account for a different number of events in each pT-hard bin hNEventsAccepted = f.Get("hNEventsAcc") # Get NEvents histos from file, since we undo the entry after writing it nEventsAcc = hNEventsAccepted.GetBinContent(bin+1) eventScaleFactorAcc = nEventsAccAvg/nEventsAcc print("ooo nEventsAcc: {0}".format(nEventsAcc)) print("ooo scaleFactor: {0}".format(scaleFactor)) print("ooo eventScaleFactor: {0}".format(eventScaleFactorAcc)) print("ooo combined ScaleFactor: {0}".format(eventScaleFactorAcc*scaleFactor)) print("| *{0}* | {1} - {2} | {3} | {4} |".format((bin+1), ptHardLo[bin], ptHardHi[bin], scaleFactor, scaleFactor*eventScaleFactorAcc),file=controlFile) for qaListName in qaListNames: qaList = f.Get(qaListName) # Now, scale all the histograms print("Scaling list: " + qaList.GetName()) RadiusName="" for obj in qaList: name = obj.GetName() ScaleAllHistograms(obj, scaleFactor * eventScaleFactorAcc, f, bRemoveOutliers,outlierLimit, outlierNBinsThreshold, bin, name) # Write the histograms to file qaList.Write("%sScaled" % qaListName, ROOT.TObject.kSingleKey) f.Close() print("ooo Save control table for current run") controlFile.close() # you can omit in most cases as the destructor will call it # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # If no reference file is provided, compute the scale factors and write them, and scale the histos # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - else: print("ooo Determine Scale Factors from single pT Hard Bins") # Prepare histograms hXSecPerEvent = ROOT.TH1F("hXSecPerEvent", "hXSecPerEvent", PtHardBins+1, 0, PtHardBins+1) hNTrialsPerEvent = ROOT.TH1F("hNTrialsPerEvent", "hNTrialsPerEvent", PtHardBins+1, 0, PtHardBins+1) hScaleFactor = ROOT.TH1F("hScaleFactor", "hScaleFactor", PtHardBins+1, 0, PtHardBins+1) twikifile = open('twikiTableoutput.txt', 'w') # This is to be added to https://twiki.cern.ch/twiki/bin/viewauth/ALICE/JetMCProductionsCrossSections twikifile.write('This is to be added to https://twiki.cern.ch/twiki/bin/viewauth/ALICE/JetMCProductionsCrossSections \n') # python will convert \n to os.linesep twikifile.write('| *Bin* | *pT-hard range (!GeV)* | *Factor xSec* | *Event Scale Factor (Acc)* | *Event Scale Factor (Tot)* |\n') for bin in range(0,PtHardBins): # Label histograms hXSecPerEvent.GetXaxis().SetBinLabel(bin+1, "%d-%d" % (ptHardLo[bin],ptHardHi[bin])) hNTrialsPerEvent.GetXaxis().SetBinLabel(bin+1, "%d-%d" % (ptHardLo[bin],ptHardHi[bin])) hScaleFactor.GetXaxis().SetBinLabel(bin+1, "%d-%d" % (ptHardLo[bin],ptHardHi[bin])) # Extract cross sections from pT Hard bins for bin in range(0,PtHardBins): # Open input file and get relevant lists inputFile = "{0}/AnalysisResultsPtHard{0}.root".format(bin+1) print("ooo Scaling Pt-hard bin %d" % (bin+1)) f = ROOT.TFile(inputFile, "UPDATE") qaList = f.Get(qaListNames[0]) print("ooo Computing scaling factors with list: " + qaList.GetName()) hXsecPtHard = qaList.FindObject("hXsec") hTrialsPtHard = qaList.FindObject("hNtrials") hNEventsTotal = f.Get("hNEventsTot") # Get NEvents histos from file, since we undo the entry after writing it hNEventsAccepted = f.Get("hNEventsAcc") # Compute: scale factor = xsec per event / trials per event nEventsTot = hNEventsTotal.GetBinContent(bin+1) nEventsAcc = hNEventsAccepted.GetBinContent(bin+1) xsec = hXsecPtHard.GetBinContent(1) / hXsecPtHard.GetEntries() #entries in this case are number of files that were merged together #print("ooo Test entries: {0}".format(hXsecPtHard.GetEntries())) trials = 1.*hTrialsPtHard.GetBinContent(1) / nEventsTot scaleFactor = xsec/trials eventScaleFactorAcc = nEventsAccAvg/nEventsAcc # also scale to account that there are different number of events in each Pt-hard bin eventScaleFactorTot = nNEventsTotAvg/nEventsTot print("ooo nEventsAcc: {0}".format(nEventsAcc)) print("ooo nEventsTot: {0}".format(nEventsTot)) print("ooo nTrials: {0}".format(trials)) print("ooo scaleFactor: {0}".format(scaleFactor)) print("ooo eventScaleFactor Acc: {0}".format(eventScaleFactorAcc)) print("ooo eventScaleFactor All: {0}".format(eventScaleFactorTot)) print("ooo combined ScaleFactor: {0}".format(eventScaleFactorAcc*scaleFactor)) print("| *{0}* | {1} - {2} | {3} | {4} | {5} |".format((bin+1), ptHardLo[bin], ptHardHi[bin], scaleFactor, eventScaleFactorAcc, eventScaleFactorTot ),file=twikifile) hXSecPerEvent.Fill(bin+0.5, xsec) hNTrialsPerEvent.Fill(bin+0.5, trials) hScaleFactor.Fill(bin+0.5, scaleFactor) # Now, scale all the histograms print("ooo Scaling list: " + qaList.GetName()) RadiusName="" for obj in qaList: name = obj.GetName() ScaleAllHistograms(obj, scaleFactor * eventScaleFactorAcc, f, bRemoveOutliers, outlierLimit, outlierNBinsThreshold,bin, name) # Write the histograms to file hXSecPerEvent.Write() hXSecPerEvent.Reset() hNTrialsPerEvent.Write() hNTrialsPerEvent.Reset() hScaleFactor.Write() hScaleFactor.Reset() qaList.Write("%sScaled" % qaListNames[0], ROOT.TObject.kSingleKey) f.Close() twikifile.close() # you can omit in most cases as the destructor will call it
def main(): f = open("baseline.result", "r") baselines = f.readlines() f.close() baselines = [line.split(",") for line in baselines] (nvar, tauc_avg, tauc_error) = zip(*baselines) nvar = [int(i) for i in nvar] tauc_avg = [float(i) for i in tauc_avg] tauc_error = [float(i) for i in tauc_error] max_n_var = len(nvar) leg = ROOT.TLegend(0.5, 0.2, 0.8, 0.35) leg.SetBorderSize(0) leg.SetFillColor(0) leg.SetTextSize(0.025) leg.SetTextFont(42) x = array.array('f', range(1, max_n_var + 1)) y = array.array('f', tauc_avg) ye = array.array('f', tauc_error) xe = array.array('f', [0] * max_n_var) gr = ROOT.TGraphErrors(max_n_var, x, y, xe, ye) gr.SetMarkerColor(38) gr.SetLineColor(38) gr.SetMarkerStyle(20) gr.SetTitle("ROC Integral vs No. of Variables") gr.GetXaxis().SetTitle("No. of Training Variables") gr.GetYaxis().SetTitle("Relative Performance (AUROC)") leg.AddEntry( gr, "#splitline{Reference Baseline}{(Randomly selected variable sets as basis of comparison)}", "p") f = open("roc-tmva.result", "r") lines = f.readlines() f.close() blabel = [float((l.split(",")[0]).split("-")[-1]) for l in lines] bdata = [float((l.split(",")[-1])) for l in lines] x2 = array.array('f', blabel) y2 = array.array('f', bdata) d = dict() gr4 = plot_file("roc-tmva.result", 813, 813) gr9 = plot_file("itrRm.result", 905, 905) c1 = ROOT.TCanvas( "c1", "Relative Performance (AUROC) vs No. of Training Variables", 950, 600) gr.Draw("APL") gr4.Draw("PL") leg.AddEntry( gr4, "#splitline{TMVA out-of-the-box Ranking}{(Performance of top N vars as ranked by TMVA)}", "p") leg.AddEntry( gr9, "#splitline{Iterative Removal - vSearch}{(Removing var with least impact on performance iteratively)}", "p") leg.Draw() print "press enter to continue\n" raw_input()
l = lhood[0] elif m > binsLow[-1]: l = lhood[-1] else: l = lhood[m >= binsLow][-1] return np.float32(l) for j,decay in enumerate(decays): if j == 0: pass #continue tfile_str = '%s/%s_FEVTDEBUG_IMG.root'%(eosDir,decay) #tfile_str = '%s/%s_FEVTDEBUG_nXXX_IMG.root'%(eosDir,decay) tfile = ROOT.TFile(tfile_str) tree = tfile.Get('fevt/RHTree') nevts = tree.GetEntries() neff = (nevts//1000)*1000 #neff = 256000 #neff = 250 print " >> Doing decay:", decay print " >> Input file:", tfile_str print " >> Total events:", nevts print " >> Effective events:", neff # EB readouts = [170,360] branches = ["EB_energy"] X = da.concatenate([\ da.from_delayed(\
return Area*pT*pow( (1 + (Q-1)*((mk**2 + pT**2)**(0.5) - mk)/Temper) , (-1/(Q-1)) ) #------------------------------------------------------------------------------------------------------1 def FCNchi1(npar, gin, f, par, iflag): global valFCN1 yTheor = np.array([Tsallis(i, par) for i in x]) indPos = y1 > 0 arrayFCN = ( (y1[indPos] - yTheor[indPos])/ey1[indPos] )**2 valFCN1 = np.sum(arrayFCN) f.value = valFCN1 ''' #MIUNIT ''' minuit1 = ROOT.TMinuit(5) minuit1.SetPrintLevel(1) minuit1.SetFCN(FCNchi1) errordef = 1. # Chi square start parameters minuit1.DefineParameter(0, 'Area', 10.2, 1e-4, 0., 0.) minuit1.DefineParameter(1, 'Temper', 0.65, 1e-4, 0., 0.) minuit1.DefineParameter(2, 'Q', 1.14, 1e-3, 0., 0.) ierflg = ctypes.c_int(0) minuit1.mncomd("SET ERR " + str(1), ierflg) minuit1.mncomd("SET STR 1", ierflg) minuit1.mncomd("MIGRAD 100000 1e-8", ierflg)