def computeFluxMap(self, eltId, eltData, parentId, parentData): groupList = self.getChildrenId(eltId) self.c = [] fluxMapList = [] for gElt in groupList: groupNumber = self.GetItemText(gElt) gData = self.getChildData(gElt, 'FLUX-INTG') fluxMapList.append(gData.content) gNb = 0 nx = 60 ny = 60 nz = 29 # for each energy group for fluxMap in fluxMapList: gNb += 1 groupNumber = '%d' % gNb gROOT.Reset() c = TCanvas( groupNumber, '2D Histograms of group ' + groupNumber + ' (FLUX-INTG)', 0, 0, 700, 600) histFlux = TH2F(groupNumber, 'Flux of group ' + groupNumber, nx, -nx / 2, nx / 2, ny, -ny / 2, ny / 2) histFlux.GetXaxis().SetTitle("X axis title") histFlux.GetXaxis().SetDecimals(ROOT.kTRUE) histFlux.GetYaxis().SetTitle("Y axis title") for n in range(nx * ny): x = n / nx - (nx + 1) / 2 y = n % ny - (ny + 1) / 2 z = float(fluxMap[(nz - 1) * nx * ny + n]) histFlux.Fill(int(x), int(y), z) histFlux.DrawCopy('LEGO2') ROOT.gStyle.SetPalette(1) c.Update() self.c.append(c) # for group 1 over group 2 gROOT.Reset() c = TCanvas('ratio', '2D Histograms of group 1 over group 2 ratio (FLUX-INTG)', 0, 0, 700, 600) histFlux = TH2F('ratio', 'Flux ratio', nx, -nx / 2, nx / 2, ny, -ny / 2, ny / 2) histFlux.GetXaxis().SetTitle("X axis title") histFlux.GetYaxis().SetTitle("Y axis title") for n in range(nx * ny): x = n / nx - (nx + 1) / 2 y = n % ny - (ny + 1) / 2 z = float(fluxMapList[0][(nz - 1) * nx * ny + n]) / float( fluxMapList[1][(nz - 1) * nx * ny + n]) histFlux.Fill(x, y, z) histFlux.DrawCopy('LEGO2') ROOT.gStyle.SetPalette(1) c.Update() self.c.append(c)
def main(): gROOT.Reset() outputFilename = 'Theory_MCFM.root' histoBase = '_MCFM_scale' massScales = ['172','345','690'] kinVar_histobases = ['pttop','pttt','Mtt'] kinVar_newhistobases = ['toppT_MCFM_','pTtt_MCFM_','Mtt_MCFM_'] newMassScales = ['mtop','2mtop','4mtop'] fileLocation = 'root://eosatlas//eos/atlas/user/c/childers/September_4' filenameBase = 'Theory_MCFM_' kinVar_filenames = ['pTt','pTtt','Mtt'] filenamePostfix = '.root' outputFile = TFile(outputFilename,'UPDATE') for i in range(len(kinVar_histobases)): filename = fileLocation + '/' + filenameBase + kinVar_filenames[i] + filenamePostfix file = openEosFile(filename) if not file: print 'error opening file',filename return histobase = kinVar_histobases[i] + histoBase newHistobase = kinVar_newhistobases[i] for j in range(len(massScales)): histogram = file.Get(histobase + massScales[j]) histogram.SetName(newHistobase + newMassScales[j]) outputFile.cd() histogram.Write(histogram.GetName(),TObject.kOverwrite)
def SetStyle(styleName="MyStyle"): ## MyStyle or tdrStyle from ROOT import gROOT, gStyle gROOT.Reset() gROOT.ProcessLine(".x ~/rootmacros/myStyle.cc") gROOT.ProcessLine(".x ~/rootmacros/setTDRStyle.C") # gROOT.SetStyle("tdrStyle"); # gROOT.SetStyle("MyStyle"); gROOT.SetStyle(styleName) gStyle.SetOptLogy(0) gStyle.SetPalette(1) gStyle.SetOptTitle(0) gStyle.SetOptStat(0) gStyle.SetPadTopMargin(0.02) gStyle.SetPadTickX(1) gStyle.SetLabelSize(0.045, "XYZ") gStyle.SetLabelSize(0.04, "Y") gStyle.SetTitleSize(0.045, "XYZ") gROOT.ForceStyle() return
def SetPalette(self, optstat=1111111): """Sets default plot settings.""" gROOT.Reset() gROOT.SetStyle('Plain') gStyle.SetOptStat(optstat) gStyle.SetPalette(1) gStyle.SetLineColor(4) return
def Configure(self): self.evtbuf = {} self.filename = self.GetParameter('Filename') # create a root file and my result tree gROOT.Reset() self.rootf = TFile(self.filename, 'recreate') self.tree = TTree('tree', 'My tree') self.branched = False
def _initDefaultStyle(self): gROOT.Reset() gROOT.SetStyle("Plain") gStyle.SetOptStat(0) gStyle.SetOptFit(1111) gStyle.SetPadLeftMargin(0.12) gStyle.SetPadBottomMargin(0.12) gStyle.SetMarkerSize(1.) gStyle.SetHistLineWidth(1)
def plot_historoot(self): """ Plots the imported ROOT histogram. """ from ROOT import gROOT, TCanvas gROOT.Reset() c1 = TCanvas('c1', 'Imported ROOT histogram', 200, 10, 700, 500) self.HistoRoot.Draw() c1.SetGrid() c1.Update() return c1
def tearDown(self): super(TestHistoToolsBase, self).tearDown() if os.path.exists("test"): shutil.rmtree("test") del self.test_wrp diskio.drop_io_refs() gROOT.Reset()
def tearDown(self): super(TestHistoToolsBase, self).tearDown() del self.test_wrp diskio.close_open_root_files() gROOT.Reset() if os.path.exists(self.test_dir): os.system('rm -r %s' % self.test_dir)
def buildArraysFromROOT(tree, allowedFeatures, cut, skipEvents, maxEvents, name): dataContainer = {} featureNames = [] eventCounter = -1 gROOT.Reset() # Get branch names for item in tree.GetListOfBranches(): featureName = item.GetName() if featureName in allowedFeatures: featureNames.append(featureName) dataContainer[featureName] = [] # Build the event list tcut = TCut(cut) tree.Draw(">>eventList", tcut) eventList = TEventList() eventList = gDirectory.Get("eventList") nSelectedEvents = eventList.GetN() # Event loop for i in range(0, nSelectedEvents): if (i < skipEvents): continue if (i % 100 == 0): sys.stdout.write("Reading %s: %d%% \r" % (tree.GetName(), 100 * i / (maxEvents + skipEvents))) sys.stdout.flush() if i >= (maxEvents + skipEvents): break selectedEvNum = eventList.GetEntry(i) tree.GetEntry(selectedEvNum) for feature in featureNames: dataContainer[feature].append(tree.__getattr__(feature)) sys.stdout.write("\n") # Make the numpy arrays outputArray = np.array([]) for feature in allowedFeatures: column = dataContainer[feature] feature_vector = np.asarray(column) feature_vector = feature_vector.reshape(feature_vector.size, 1) if outputArray.shape[0] == 0: outputArray = feature_vector else: outputArray = np.concatenate((outputArray, feature_vector), axis=1) imp = Imputer(missing_values=-999, strategy='mean', axis=0) imp.fit(outputArray) outputArray = imp.transform(outputArray) print name print "Events: ", outputArray.shape[0] print "Features: ", outputArray.shape[1] return outputArray
def set_root_style(stat=1110, grid=0, PadTopMargin=0.08, PadLeftMargin=0.10, TitleOffsetY=1.2): # must be used in the beginning from ROOT import gROOT, gStyle gROOT.SetBatch(1) gROOT.Reset() gStyle.SetOptTitle(1) gStyle.SetTitleFillColor(0) gStyle.SetTitleBorderSize(0) # gStyle.SetTitleFont(22) # gStyle.SetStatFont(22) # gStyle.SetStatColor(1) # gStyle.SetLabelFont(22,"X") # gStyle.SetLabelFont(22,"Y") gStyle.SetCanvasBorderMode(0) gStyle.SetCanvasColor(0) gStyle.SetCanvasDefX(0) gStyle.SetCanvasDefY(0) gStyle.SetFrameBorderMode(0) gStyle.SetFrameBorderSize(1) gStyle.SetFrameFillColor(0) gStyle.SetFrameFillStyle(0) gStyle.SetFrameLineColor(1) gStyle.SetFrameLineStyle(1) gStyle.SetFrameLineWidth(1) gStyle.SetPadTopMargin(PadTopMargin) gStyle.SetPadLeftMargin(PadLeftMargin) gStyle.SetPadRightMargin(0.05) gStyle.SetLabelSize(0.03, "XYZ") gStyle.SetTitleSize(0.04, "XYZ") gStyle.SetTitleOffset(TitleOffsetY, "Y") gStyle.SetPadBorderMode(0) gStyle.SetPadColor(0) gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) gStyle.SetPadGridX(grid) gStyle.SetPadGridY(grid) gStyle.SetOptStat(stat) gStyle.SetStatColor(0) gStyle.SetStatBorderSize(1)
def set_root_env(): from ROOT import gStyle, gROOT gROOT.Reset() gROOT.SetStyle('Plain') gStyle.SetCanvasColor(10) gStyle.SetStatBorderSize(1) gStyle.SetFillColor(10) gStyle.SetOptStat(1) gStyle.SetStatX(0.46) gStyle.SetStatY(0.9) gStyle.SetTitleYOffset(1.4) gStyle.SetPalette(45) gStyle.SetMarkerSize(0.8) gStyle.SetLineColor(1) gStyle.SetLineWidth(1)
def _initDefaultStyle(self): gROOT.Reset() gROOT.SetStyle("Plain") #gStyle.SetOptStat(0) gStyle.SetOptFit(1111) gStyle.SetPadLeftMargin(0.1) gStyle.SetPadBottomMargin(0.1) gStyle.SetMarkerSize(1.5) gStyle.SetHistLineWidth(1) gStyle.SetStatFontSize(0.025) gStyle.SetTitleFontSize(0.05) gStyle.SetTitle( 'CMS Preliminary tH, H#to#tau#tau, 19.7 fb^{-1} at 8 TeV') gStyle.SetTitleSize(0.06, "XYZ") gStyle.SetLabelSize(0.05, "XYZ") gStyle.SetNdivisions(510, "XYZ")
def setStyle(): gROOT.Reset() icol = 0 # WHITE font = 42 # Helvetica tsize = 0.05 gStyle.SetFrameBorderMode(icol) gStyle.SetFrameFillColor(icol) gStyle.SetCanvasBorderMode(icol) gStyle.SetCanvasColor(icol) gStyle.SetPadBorderMode(icol) gStyle.SetPadColor(icol) gStyle.SetStatColor(icol) gStyle.SetPaperSize(20, 26) gStyle.SetPadTopMargin(0.05) gStyle.SetPadRightMargin(0.08) gStyle.SetPadBottomMargin(0.15) gStyle.SetPadLeftMargin(0.12) gStyle.SetTitleXOffset(1.05) gStyle.SetTitleYOffset(0.95) gStyle.SetTextFont(font) gStyle.SetTextSize(tsize) gStyle.SetLabelFont(font, "x") gStyle.SetTitleFont(font, "x") gStyle.SetLabelFont(font, "y") gStyle.SetTitleFont(font, "y") gStyle.SetLabelFont(font, "z") gStyle.SetTitleFont(font, "z") gStyle.SetLabelSize(tsize * 0.85, "x") gStyle.SetTitleSize(tsize * 1.10, "x") gStyle.SetLabelSize(tsize * 0.85, "y") gStyle.SetTitleSize(tsize * 1.10, "y") gStyle.SetLabelSize(tsize * 0.85, "z") gStyle.SetTitleSize(tsize * 1.10, "z") gStyle.SetMarkerStyle(20) gStyle.SetMarkerSize(1.) gStyle.SetHistLineWidth(2) gStyle.SetLineStyleString(2, "[12 12]") # postscript dashes gStyle.SetEndErrorSize(0.) # gStyle.SetOptTitle(0); gStyle.SetOptStat(0) gStyle.SetOptFit(0) gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) gStyle.SetPaintTextFormat("4.1f")
def main(options, args): gROOT.Reset() #load our super special Polarization PDF gROOT.ProcessLine('.L RooPolarizationPdf.cxx+') gROOT.ProcessLine('.L RooPolarizationConstraint.cxx+') #setup integration intConf = ROOT.RooAbsReal.defaultIntegratorConfig() #intConf.Print('v') # intConf.method1D().setLabel('RooAdaptiveGaussKronrodIntegrator1D') intConf.setEpsAbs(1e-13) intConf.setEpsRel(1e-13) print intConf.epsAbs() print intConf.epsRel() # intConf.method2D().setLabel('RooMCIntegrator') # intConf.methodND().setLabel('RooMCIntegrator') output = TFile.Open(options.workspaceName + '.root', 'RECREATE') theWS = RooWorkspace(options.workspaceName, 1) #save the polarization PDF code in the RooWorkspace theWS.importClassCode('RooPolarization*', True) buildDataAndCategories(theWS, options, args) buildMassAndLifetimePDF(theWS) # if options.fitFrame is not None: # buildPolarizationPDF(theWS,options) #root is stupid output.cd() theWS.Print('v') ROOT.RooMsgService.instance().Print() doFit(theWS, options) theWS.Write() output.Close()
def IRFContext(fname, dZe, Fnorm, index, E0, nsb=250): irf_MC = r.VInstrumentResponseFunctionReader() irf_Rec = r.VInstrumentResponseFunctionReader() loaded_MC = irf_MC.fillData(fname, dZe, 0.5, 16, index, nsb, "A_MC") loaded_Rec = irf_Rec.fillData(fname, dZe, 0.5, 16, index, nsb, "A_Rec") if (not (loaded_MC or loaded_Rec)): raise Exception( "IRF not loaded! File: {}; Ze: {}; index: {}; nsb: {}".format( fname, dZe, index, nsb)) h_Migration_Original = irf_MC.getMigrationMatrix() EA_ori = irf_Rec.gEffArea_Rec h_FA = r.getConvolvedHist(h_Migration_Original, EA_ori, Fnorm, index, E0) yield h_FA h_Migration_Original.Delete() EA_ori.Delete() h_FA.Delete() irf_MC.Delete() irf_Rec.Delete() gROOT.Reset() gROOT.CloseFiles()
def plot_histosvc(self): """ Plots the histogram at the HistogramDataSvc as a ROOT TGraph. """ from ROOT import gROOT, TCanvas, TGraph from array import array n = len(self.HistoSvcEntry.contents()) x, y = array('f'), array('f') for i in range(len(self.HistoSvcEntry.contents())): x.append(self.HistoSvcEntry.binMean(i + 1)) y.append(self.HistoSvcEntry.binHeight(i + 1)) self.HistoSvc2Root = TGraph(n, x, y) gROOT.Reset() c2 = TCanvas('c2', 'Histogram at HistogramDataSvc', 200, 10, 700, 500) self.HistoSvc2Root.SetTitle('Histo at HistogramDataSvc as TGraph') self.HistoSvc2Root.GetXaxis().SetTitle('x axis') self.HistoSvc2Root.GetYaxis().SetTitle('y axis') self.HistoSvc2Root.Draw('ACP') c2.SetGrid() c2.Update() return c2
def PrintToTextFile(inputRootFile, txtfilename, mode): from ROOT import TTree, TFile, gROOT import re, array from array import array gROOT.Reset() f = TFile(inputRootFile,"read") tree = f.Get("WJet") entries = tree.GetEntriesFast() txtfile = file(txtfilename,"w") # loop over events for jentry in xrange( entries ): # get the next tree in the chain ientry = tree.LoadTree(jentry) if ientry < 0: break # copy next entry into memory and verify nb = tree.GetEntry(jentry) if nb<=0: continue if not (tree.gdevtt==1): continue if jentry%50000 == 0: print "Processing entry = "+str(jentry) if mode==0: line = '%i' %(tree.event_runNo) + " "+ '%i' %(tree.event_lumi) + " "+ '%i' %(tree.event_evtNo) + " "+ '%10.5f' %(tree.W_muon_pt)+" "+ '%10.5f' %(tree.W_muon_eta) + ' ' + '%10.5f' %(tree.W_muon_phi) + ' ' + '%10.5f' %(tree.event_met_pfmet) + ' ' + '%10.5f' %(tree.event_met_pfmetPhi) + ' ' + '%10.5f' %(tree.JetPFCor_Pt[0]) + ' ' + '%10.5f' %(tree.JetPFCor_Eta[0]) + ' ' + '%10.5f' %(tree.JetPFCor_Phi[0]) + ' ' + '%10.5f' %(tree.JetPFCor_Pt[1]) + ' ' + '%10.5f' %(tree.JetPFCor_Eta[1]) + ' ' + '%10.5f' %(tree.JetPFCor_Phi[1]) + '\n' else: line = '%i' %(tree.event_runNo) + " "+ '%i' %(tree.event_lumi) + " "+ '%i' %(tree.event_evtNo) + " "+ '%10.5f' %(tree.W_electron_pt)+" "+ '%10.5f' %(tree.W_electron_eta) + ' ' + '%10.5f' %(tree.W_electron_phi) + ' ' + '%10.5f' %(tree.event_met_pfmet) + ' ' + '%10.5f' %(tree.event_met_pfmetPhi) + ' ' + '%10.5f' %(tree.JetPFCor_Pt[0]) + ' ' + '%10.5f' %(tree.JetPFCor_Eta[0]) + ' ' + '%10.5f' %(tree.JetPFCor_Phi[0]) + ' ' + '%10.5f' %(tree.JetPFCor_Pt[1]) + ' ' + '%10.5f' %(tree.JetPFCor_Eta[1]) + ' ' + '%10.5f' %(tree.JetPFCor_Phi[1]) + '\n' txtfile.write(line) print "flat file "+txtfilename +" has been written." f.Close()
def drawlik(input, gr = TGraph(), color = 8, second = False, Folder = "") : print ("reading " + Folder+"/"+input) tf2 = TFile.Open(Folder+"/"+input, "READ") tree2 = tf2.Get("limit") bu = "P" if second : bu = "P same" tree2.Draw("2*deltaNLL:kappa_t>>hist(50,-3,3)","2*deltaNLL<50", bu) canv.Update(); canv.Modified(); gr = gROOT.FindObject("Graph").Clone() gr.Sort() tf2.Close() gROOT.Reset() #hist = gDirectory.Get("hist") gr.GetXaxis().SetTitleFont(43) gr.GetYaxis().SetTitleFont(43) gr.GetXaxis().SetTitleSize(28) gr.GetYaxis().SetTitleSize(28) gr.GetXaxis().SetTitleOffset(0.8) gr.GetYaxis().SetTitleOffset(0.7) gr.GetXaxis().SetTitle("#kappa_t") gr.GetYaxis().SetTitle("-2#Delta lnL") #gr2.SetMarkerStyle(34) return gr
def PrintToTextFile(inputRootFile, txtfilename): from ROOT import TTree, TFile, gROOT import re, array from array import array gROOT.Reset() f = TFile(inputRootFile, "read") tree = f.Get("WJet") entries = tree.GetEntriesFast() txtfile = file(txtfilename, "w") # loop over events for jentry in xrange(entries): # get the next tree in the chain ientry = tree.LoadTree(jentry) ## if ientry < 0 or ientry>(0.5*entries): ## break # copy next entry into memory and verify nb = tree.GetEntry(jentry) if nb <= 0: continue ## if not (tree.W_muon_pt>25.0 and (tree.W_muon_trackiso+tree.W_muon_ecaliso+tree.W_muon_hcaliso-tree.event_RhoForLeptonIsolation*3.141592653589*0.09)/tree.W_muon_pt < 0.1 and tree.W_muon_d0bsp<0.02 and tree.W_muon_d0bsp>-0.02 and tree.event_met_pfmet>30.0 and tree.W_mt>40.0 and tree.JetPFCor_Pt[0]>30.0 and tree.JetPFCor_Pt[1]>30.0): ## continue if not (tree.gdevtt == 1): continue if jentry % 50000 == 0: print "Processing entry = " + str(jentry) line = '%10.5f' % (-15) + " " + '%10.5f' % ( tree.W_muon_pt ) + " " + '%10.5f' % (tree.W_muon_eta) + ' ' + '%10.5f' % ( tree.W_muon_phi ) + ' ' + '%10.5f' % 0 + ' ' + '%10.5f' % 0 + ' ' + '%10.5f' % 0 + '\n' txtfile.write(line) line = '%10.5f' % (-5) + " " + '%10.5f' % ( tree.event_met_pfmet) + ' ' + '%10.5f' % ( tree.event_met_pfmetPhi) + ' ' + '%10.5f' % ( tree.event_met_pfmetsignificance) + ' ' + '%10.5f' % ( tree.event_met_pfsumet) + ' ' + '%10.5f' % ( tree.event_nPV) + ' ' + '%10.5f' % 0 + '\n' txtfile.write(line) numJets = 2 if (tree.JetPFCor_Pt[2] > 25.0 and tree.JetPFCor_Pt[3] < 25.0): numJets = 3 if (tree.JetPFCor_Pt[3] > 25.0 and tree.JetPFCor_Pt[4] < 25.0): numJets = 4 if (tree.JetPFCor_Pt[4] > 25.0 and tree.JetPFCor_Pt[5] > 25.0): numJets = 5 if (tree.JetPFCor_Pt[5] > 25.0): numJets = 6 for iijet in xrange(numJets): line = '%10.5f' % (tree.JetPFCor_E[iijet]) + ' ' + '%10.5f' % ( tree.JetPFCor_Pt[iijet]) + '' + '%10.5f' % ( tree.JetPFCor_Eta[iijet]) + ' ' + '%10.5f' % ( tree.JetPFCor_Phi[iijet]) + ' ' + '%10.5f' % ( tree.JetPFCor_bDiscriminator[iijet] ) + ' ' + '%10.5f' % 0 + ' ' + '%10.5f' % 0 txtfile.write(line + '\n') print "flat file " + txtfilename + " has been written." f.Close()
def main(options,args): gROOT.Reset() #define trigger unprescaled periods jpsi_Trig_unP = {#'HLT_Mu0_Track0_Jpsi' :[133446,141882], #'HLT_Mu0_TkMu0_Jpsi' :[140116,144114], #'HLT_Mu0_TkMu0_OST_Jpsi' :[146428,148058], #'HLT_Mu0_TkMu0_OST_Jpsi_Tight_v2':[148819,149182], #'HLT_Mu0_TkMu0_OST_Jpsi_Tight_v3':[149291,149442]} 'HLT_DoubleMu0' :[133446,147116], 'HLT_DoubleMu0_Quarkonium_v1' :[147196,149442]} #load calcPol routine gROOT.ProcessLine('.L calcPol.C+') inputs = TChain(options.treeName) for arg in args: print 'Adding: ',arg inputs.Add(arg) out = TFile.Open(options.output,'RECREATE') outTree = inputs.CloneTree(0) # polarization stuff gROOT.ProcessLine('struct theBranches { TLorentzVector* JpsiP; TLorentzVector* muPosP; TLorentzVector* muNegP; Double_t JpsiMass; Double_t JpsiPt; Double_t JpsiRap; Double_t muPosPt; Double_t muPosEta; Double_t muPosPhi; Double_t muNegPt; Double_t muNegEta; Double_t muNegPhi; Double_t costh_CS; Double_t phi_CS; Double_t costh_HX; Double_t phi_HX; Double_t costh_PHX; Double_t phi_PHX; Double_t costh_sGJ; Double_t phi_sGJ; Double_t costh_GJ1; Double_t phi_GJ1; Double_t costh_GJ2; Double_t phi_GJ2; }') # trigger stuff gROOT.ProcessLine('struct triggers { Int_t runNb; Int_t HLT_Mu0_Track0_Jpsi; Int_t HLT_Mu0_TkMu0_Jpsi; Int_t HLT_Mu0_TkMu0_OST_Jpsi; Int_t HLT_Mu0_TkMu0_OST_Jpsi_Tight_v2; Int_t HLT_Mu0_TkMu0_OST_Jpsi_Tight_v3; Int_t HLT_DoubleMu0; Int_t HLT_DoubleMu0_Quarkonium_v1; }') branches = ROOT.theBranches() thetriggers = ROOT.triggers() inputs.SetBranchAddress('runNb',AddressOf(thetriggers,'runNb')) inputs.SetBranchAddress('HLT_Mu0_Track0_Jpsi',AddressOf(thetriggers,'HLT_Mu0_Track0_Jpsi')) inputs.SetBranchAddress('HLT_Mu0_TkMu0_Jpsi',AddressOf(thetriggers,'HLT_Mu0_TkMu0_Jpsi')) inputs.SetBranchAddress('HLT_Mu0_TkMu0_OST_Jpsi',AddressOf(thetriggers,'HLT_Mu0_TkMu0_OST_Jpsi')) inputs.SetBranchAddress('HLT_Mu0_TkMu0_OST_Jpsi_Tight_v2',AddressOf(thetriggers,'HLT_Mu0_TkMu0_OST_Jpsi_Tight_v2')) inputs.SetBranchAddress('HLT_Mu0_TkMu0_OST_Jpsi_Tight_v3',AddressOf(thetriggers,'HLT_Mu0_TkMu0_OST_Jpsi_Tight_v3')) inputs.SetBranchAddress('HLT_DoubleMu0',AddressOf(thetriggers,'HLT_DoubleMu0')) inputs.SetBranchAddress('HLT_DoubleMu0_Quarkonium_v1',AddressOf(thetriggers,'HLT_DoubleMu0_Quarkonium_v1')) outTree.SetBranchAddress('runNb',AddressOf(thetriggers,'runNb')) outTree.SetBranchAddress('HLT_Mu0_Track0_Jpsi',AddressOf(thetriggers,'HLT_Mu0_Track0_Jpsi')) outTree.SetBranchAddress('HLT_Mu0_TkMu0_Jpsi',AddressOf(thetriggers,'HLT_Mu0_TkMu0_Jpsi')) outTree.SetBranchAddress('HLT_Mu0_TkMu0_OST_Jpsi',AddressOf(thetriggers,'HLT_Mu0_TkMu0_OST_Jpsi')) outTree.SetBranchAddress('HLT_Mu0_TkMu0_OST_Jpsi_Tight_v2',AddressOf(thetriggers,'HLT_Mu0_TkMu0_OST_Jpsi_Tight_v2')) outTree.SetBranchAddress('HLT_Mu0_TkMu0_OST_Jpsi_Tight_v3',AddressOf(thetriggers,'HLT_Mu0_TkMu0_OST_Jpsi_Tight_v3')) outTree.SetBranchAddress('HLT_DoubleMu0',AddressOf(thetriggers,'HLT_DoubleMu0')) outTree.SetBranchAddress('HLT_DoubleMu0_Quarkonium_v1',AddressOf(thetriggers,'HLT_DoubleMu0_Quarkonium_v1')) inputs.SetBranchAddress('JpsiP',AddressOf(branches,'JpsiP')) inputs.SetBranchAddress('muPosP',AddressOf(branches,'muPosP')) inputs.SetBranchAddress('muNegP',AddressOf(branches,'muNegP')) phiFolded = [0,0,0,0,0,0] thetaAdjusted = [0,0,0,0,0,0] outTree.Branch("JpsiMass",AddressOf(branches,'JpsiMass'),"JpsiMass/D"); outTree.Branch("JpsiPt",AddressOf(branches,'JpsiPt'),"JpsiPt/D"); outTree.Branch("JpsiRap",AddressOf(branches,'JpsiRap'),"JpsiRap/D"); outTree.Branch("muPosPt",AddressOf(branches,'muPosPt'),"muPosPt/D"); outTree.Branch("muPosEta",AddressOf(branches,'muPosEta'),"muPosEta/D"); outTree.Branch("muPosPhi",AddressOf(branches,'muPosPhi'),"muPosPhi/D"); outTree.Branch("muNegPt",AddressOf(branches,'muNegPt'),"muNegPt/D"); outTree.Branch("muNegEta",AddressOf(branches,'muNegEta'),"muNegEta/D"); outTree.Branch("muNegPhi",AddressOf(branches,'muNegPhi'),"muNegPhi/D"); outTree.Branch("costh_CS",AddressOf(branches,'costh_CS'),"costh_CS/D"); outTree.Branch("phi_CS",AddressOf(branches,'phi_CS'),"phi_CS/D"); outTree.Branch("costh_HX",AddressOf(branches,'costh_HX'),"costh_HX/D"); outTree.Branch("phi_HX",AddressOf(branches,'phi_HX'),"phi_HX/D"); outTree.Branch("costh_PHX",AddressOf(branches,'costh_PHX'),"costh_PHX/D"); outTree.Branch("phi_PHX",AddressOf(branches,'phi_PHX'),"phi_PHX/D"); outTree.Branch("costh_sGJ",AddressOf(branches,'costh_sGJ'),"costh_sGJ/D"); outTree.Branch("phi_sGJ",AddressOf(branches,'phi_sGJ'),"phi_sGJ/D"); outTree.Branch("costh_GJ1",AddressOf(branches,'costh_GJ1'),"costh_GJ1/D"); outTree.Branch("phi_GJ1",AddressOf(branches,'phi_GJ1'),"phi_GJ1/D"); outTree.Branch("costh_GJ2",AddressOf(branches,'costh_GJ2'),"costh_GJ2/D"); outTree.Branch("phi_GJ2",AddressOf(branches,'phi_GJ2'),"phi_GJ2/D"); nEvents=inputs.GetEntries() print 'There are ',nEvents,' events to process!' FiducialCutCountPos = 0 FiducialCutCountNeg = 0 for j in range(0,nEvents): nb = inputs.GetEntry(j) if branches.muPosP.Pt() == branches.muNegP.Pt(): continue passesTrigger = True if not options.isMC: passesTrigger=False for trig in jpsi_Trig_unP.keys(): if thetriggers.runNb >= jpsi_Trig_unP[trig][0] and thetriggers.runNb <= jpsi_Trig_unP[trig][-1] and getattr(thetriggers,trig) == 1: passesTrigger = True if not passesTrigger: continue branches.muPosPt = branches.muPosP.Pt() branches.muPosEta = branches.muPosP.Eta() branches.muPosPhi = branches.muPosP.Phi() branches.muNegPt = branches.muNegP.Pt() branches.muNegEta = branches.muNegP.Eta() branches.muNegPhi = branches.muNegP.Phi() #(a) on the positive muon if((abs(branches.muPosEta) < jpsi.etaPS[0] and branches.muPosPt < jpsi.pTMuMin[0]) or (abs(branches.muPosEta) > jpsi.etaPS[0] and abs(branches.muPosEta) < jpsi.etaPS[1] and branches.muPosP.P() < jpsi.pMuMin[1]) or (abs(branches.muPosEta) > jpsi.etaPS[1] and abs(branches.muPosEta) < jpsi.etaPS[2] and branches.muPosPt < jpsi.pTMuMin[2])): FiducialCutCountPos += 1 continue #(b) on the negative muon if((abs(branches.muNegEta) < jpsi.etaPS[0] and branches.muNegPt < jpsi.pTMuMin[0]) or (abs(branches.muNegEta) > jpsi.etaPS[0] and abs(branches.muNegEta) < jpsi.etaPS[1] and branches.muNegP.P() < jpsi.pMuMin[1]) or (abs(branches.muNegEta) > jpsi.etaPS[1] and abs(branches.muNegEta) < jpsi.etaPS[2] and branches.muNegPt < jpsi.pTMuMin[2])): FiducialCutCountNeg += 1 continue ROOT.calcPol(branches.muPosP,branches.muNegP) #set up KLUDGE to make DoubleMu0 and DoubleMu0_Quarkonium to be the same as they have the same acceptance map if thetriggers.HLT_DoubleMu0_Quarkonium_v1 == 1: thetriggers.HLT_DoubleMu0 = 1 if options.isFolded: for frame in range(len(jpsi.frameLabel)): phiFolded[frame] = ROOT.thisPhi[frame] thetaAdjusted[frame] = ROOT.thisCosTh[frame] if ROOT.thisPhi[frame] >= -90 and ROOT.thisPhi[frame] < 0.: phiFolded[frame] *= -1 elif ROOT.thisPhi[frame] > 90 and ROOT.thisPhi[frame] < 180: phiFolded[frame] = 180 - ROOT.thisPhi[frame] thetaAdjusted[frame] *= -1 elif ROOT.thisPhi[frame] > -180 and ROOT.thisPhi[frame] < -90: phiFolded[frame] = 180 + ROOT.thisPhi[frame] thetaAdjusted[frame] *= -1 branches.costh_CS = thetaAdjusted[0] branches.phi_CS = phiFolded[0] branches.costh_HX = thetaAdjusted[1] branches.phi_HX = phiFolded[1] branches.costh_PHX = thetaAdjusted[2] branches.phi_PHX = phiFolded[2] branches.costh_sGJ = thetaAdjusted[3] branches.phi_sGJ = phiFolded[3] branches.costh_GJ1 = thetaAdjusted[4] branches.phi_GJ1 = phiFolded[4] branches.costh_GJ2 = thetaAdjusted[5] branches.phi_GJ2 = phiFolded[5] else: branches.costh_CS = ROOT.thisCosTh[0] branches.phi_CS = ROOT.thisPhi[0] branches.costh_HX = ROOT.thisCosTh[1] branches.phi_HX = ROOT.thisPhi[1] branches.costh_PHX = ROOT.thisCosTh[2] branches.phi_PHX = ROOT.thisPhi[2] branches.costh_sGJ = ROOT.thisCosTh[3] branches.phi_sGJ = ROOT.thisPhi[3] branches.costh_GJ1 = ROOT.thisCosTh[4] branches.phi_GJ1 = ROOT.thisPhi[4] branches.costh_GJ2 = ROOT.thisCosTh[5] branches.phi_GJ2 = ROOT.thisPhi[5] branches.JpsiMass = branches.JpsiP.M() branches.JpsiPt = branches.JpsiP.Pt() branches.JpsiRap = branches.JpsiP.Rapidity() outTree.Fill() out.Write() out.Close()
def setupROOT(): """sets up ROOT """ gROOT.Reset() gROOT.SetStyle('Plain') gStyle.SetPadTickY(1) gStyle.SetPadTickX(1)
def setAtlasDefaults(webDisplay): print 'Applying ATLAS style settings...\n' gROOT.Reset() atlasStyle = AtlasStyle() gROOT.SetStyle('ATLAS') gROOT.ForceStyle()
def main(options, args): from ROOT import gSystem, gROOT, gStyle gROOT.SetBatch() gSystem.Load("libRooFitCore") if options.doWebPage: from lip.Tools.rootutils import loadToolsLib, apply_modifs loadToolsLib() from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList from ROOT import kWhite, kBlue, kOpenSquare if options.doWebPage: from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot rootglobestyle.setTDRStyle() gStyle.SetMarkerSize(1.5) gStyle.SetTitleYOffset(1.5) gStyle.SetPadLeftMargin(0.16) gStyle.SetPadRightMargin(0.05) gStyle.SetPadTopMargin(0.05) gStyle.SetPadBottomMargin(0.13) gStyle.SetLabelFont(42, "XYZ") gStyle.SetLabelOffset(0.007, "XYZ") gStyle.SetLabelSize(0.05, "XYZ") gStyle.SetTitleSize(0.06, "XYZ") gStyle.SetTitleXOffset(0.9) gStyle.SetTitleYOffset(1.24) gStyle.SetTitleFont(42, "XYZ") ## ## Read files ## options.outdir = "%s_m%1.0f" % (options.outdir, options.mH) if options.fp: options.outdir += "_fp" ncat = options.ncat cats = options.cats if cats is "": categories = ["_cat%d" % i for i in range(0, ncat)] else: categories = ["_cat%s" % i for i in cats.split(",")] if options.mva: clables = { "_cat0": ("MVA > 0.89", ""), "_cat1": ("0.74 #leq MVA", "MVA < 0.89"), "_cat2": ("0.545 #leq MVA", "MVA < 0.74"), "_cat3": ("0.05 #leq MVA", "MVA < 0.545"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } else: clables = { "_cat0": ("max(|#eta|<1.5", "min(R_{9})>0.94"), "_cat1": ("max(|#eta|<1.5", "min(R_{9})<0.94"), "_cat2": ("max(|#eta|>1.5", "min(R_{9})>0.94"), "_cat3": ("max(|#eta|>1.5", "min(R_{9})<0.94"), "_cat4": ("Di-jet", "Tagged"), "_cat5": ("Di-jet", "Tagged"), "_combcat": ("All Classes", "Combined") } helper = Helper() fin = TFile.Open(options.infile) helper.files.append(fin) ws = fin.Get("cms_hgg_workspace") mass = ws.var("CMS_hgg_mass") mass.SetTitle("m_{#gamma#gamma}") mass.setUnit("GeV") mass.setRange(100., 150.) mass.setBins(100, "plot") mass.setBins(5000) print ws aset = RooArgSet(mass) helper.objs.append(mass) helper.objs.append(aset) fitopt = (RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False), RooFit.SumW2Error(False), RooFit.NumCPU(8)) if not options.binned and not options.refit: finpdf = TFile.Open(options.infilepdf) helper.files.append(finpdf) wspdf = finpdf.Get("wsig") else: wspdf = ws for c in categories: processes = ["ggh", "vbf", "wzh"] if options.fp: processes = ["vbf", "wzh"] ### elif clables[c][0] == "Di-jet": ### processes = [ "vbf", "ggh" ] dsname = "sig_mass_m%1.0f%s" % (options.mH, c) print dsname print ws ds = ws.data("sig_%s_mass_m%1.0f%s" % (processes[0], options.mH, c)).Clone(dsname) for proc in processes[1:]: ds.append(ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c))) helper.dsets.append(ds) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, ds) pdf = RooKeysPdf("pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname, mass, ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: if options.refit: if options.refitall and clables[c][0] != "Di-jet": rpdfs = [] for proc in processes: for ngaus in range(1, 4): pp = build_pdf(ws, "%s_%s" % (c, proc), ngaus, ngaus == 3) pp.fitTo( ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c)), RooFit.Strategy(0), *fitopt) rpdfs.append(pp) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*tuple(rpdfs))) else: if options.refitall and clables[c][0] == "Di-jet": for ngaus in range(1, 5): pdf = build_pdf(ws, c, ngaus, ngaus == 5) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: for ngaus in range(1, 4): pdf = build_pdf(ws, c, ngaus, ngaus == 3) pdf.fitTo(ds, RooFit.Strategy(0), *fitopt) else: pdfs = (wspdf.pdf("hggpdfrel%s_%s" % (c, p)) for p in processes) pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c, RooArgList(*pdfs)) helper.add(pdf, pdf.GetName()) plot_pdf = pdf.Clone("pdf_%s" % dsname) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(ds) cdf = pdf.createCdf(aset) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) ### hmin, hmax, hm = get_FWHM( points ) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma%s" % c) helper.add((hmin, hmax, hm), "FWHM%s" % c) helper.add(ds.sumEntries(), "sumEntries%s" % c) # signal model integral # data integral for PAS tables data = ws.data("data_mass%s" % c) helper.add( data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f" % (options.mH - 10., options.mH + 10.)), "data_sumEntries%s" % c) del cdf del pdf dsname = "sig_mass_m%1.0f_combcat" % options.mH print dsname combined_ds = helper.dsets[0].Clone(dsname) for d in helper.dsets[1:]: combined_ds.append(d) if options.binned: binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname, aset, combined_ds) pdf = RooKeysPdf("pdf_%s" % (dsname), "pdf_%s" % dsname, mass, combined_ds) plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset, plot_ds) helper.add(binned_ds, binned_ds.GetName()) else: #### pdf = build_pdf(ws,"_combcat") #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt ) #### plot_pdf = pdf.Clone( "pdf_%s" % dsname ) pdf = RooAddPdf( "pdf_%s" % dsname, "pdf_%s" % dsname, RooArgList(*(helper.histos["hggpdfrel%s" % c] for c in categories))) plot_pdf = pdf cdf = pdf.createCdf(aset) plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot") plot_ds.add(combined_ds) wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10., options.mH + 10.) hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10., options.mH + 10.) helper.add(plot_ds, plot_ds.GetName()) helper.add(plot_pdf, plot_pdf.GetName()) helper.add((wmin, wmax), "eff_sigma_combcat") helper.add((hmin, hmax, hm), "FWHM_combcat") helper.add(plot_ds.sumEntries(), "sumEntries_combcat") mass.setRange("higgsrange", options.mH - 25., options.mH + 15.) del cdf del pdf del helper.dsets ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}") label = TLatex(0.7, 0.86, "#scale[0.65]{#splitline{CMS preliminary}{Simulation}}") label.SetNDC(1) ## ## Make web page with plots ## if options.doWebPage: hth = HtmlHelper(options.outdir) hth.navbar().cell(HtmlTag("a")).firstChild().txt("..").set( "href", "../?C=M;O=D") hth.navbar().cell(HtmlTag("a")).firstChild().txt("home").set( "href", "./") tab = hth.body().add(HtmlTable()) ip = 0 for c in ["_combcat"] + categories: ### for c in categories: if options.doWebPage and ip % 4 == 0: row = tab.row() ip = ip + 1 dsname = "sig_mass_m%1.0f%s" % (options.mH, c) canv = TCanvas(dsname, dsname, 600, 600) helper.objs.append(canv) ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322) leg = TLegend(0.2, 0.96, 0.5, 0.55) #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] ) hplotcompint = mass.frame(RooFit.Bins(250), RooFit.Range("higgsrange")) helper.objs.append(hplotcompint) helper.objs.append(leg) plot_ds = helper.histos["plot_%s" % dsname] plot_pdf = helper.histos["pdf_%s" % dsname] wmin, wmax = helper.histos["eff_sigma%s" % c] hmin, hmax, hm = helper.histos["FWHM%s" % c] print hmin, hmax, hm style = (RooFit.LineColor(kBlue), RooFit.LineWidth(2), RooFit.FillStyle(0)) style_seff = ( RooFit.LineWidth(2), RooFit.FillStyle(1001), RooFit.VLines(), RooFit.LineColor(15), ) style_ds = (RooFit.MarkerStyle(kOpenSquare), ) plot_ds.plotOn(hplotcompint, RooFit.Invisible()) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.FillColor(19), RooFit.DrawOption("F"), *style_seff) seffleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range(wmin, wmax), RooFit.LineColor(15), *style_seff) plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"), RooFit.Range("higgsrange"), *style) pdfleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) plot_ds.plotOn(hplotcompint, *style_ds) pointsleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1)) iob = int(hplotcompint.numItems() - 1) leg.AddEntry(pointsleg, "Simulation", "pe") leg.AddEntry(pdfleg, "Parametric model", "l") leg.AddEntry(seffleg, "#sigma_{eff} = %1.2f GeV " % (0.5 * (wmax - wmin)), "fl") clabel = TLatex(0.74, 0.65, "#scale[0.65]{#splitline{%s}{%s}}" % clables[c]) clabel.SetNDC(1) helper.objs.append(clabel) hm = hplotcompint.GetMaximum() * 0.5 * 0.9 ### hm = pdfleg.GetMaximum()*0.5 fwhmarrow = TArrow(hmin, hm, hmax, hm) fwhmarrow.SetArrowSize(0.03) helper.objs.append(fwhmarrow) fwhmlabel = TPaveText(0.20, 0.58, 0.56, 0.48, "brNDC") fwhmlabel.SetFillStyle(0) fwhmlabel.SetLineColor(kWhite) reducedFWHM = (hmax - hmin) / 2.3548200 fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM) helper.objs.append(fwhmlabel) hplotcompint.SetTitle("") hplotcompint.GetXaxis().SetNoExponent(True) hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)") hplotcompint.GetXaxis().SetNdivisions(509) ## hplotcompint.GetYaxis().SetTitle("A.U."); ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4); hplotcompint.Draw() leg.Draw("same") label.Draw("same") clabel.Draw("same") fwhmarrow.Draw("<>") fwhmlabel.Draw("same") plot_ds.sumEntries() if options.doWebPage: hpl = HtmlPlot(canv, False, "", True, True, True) hpl.caption("<i>%s</i>" % canv.GetTitle()) row.cell(hpl) else: if os.path.isdir(options.outdir) is False: os.mkdir(options.outdir) for ext in "C", "png", "pdf": canv.SaveAs( os.path.join(options.outdir, "%s.%s" % (canv.GetName(), ext))) if "comb" in c: ip = 0 if options.doWebPage: print "Creating pages..." hth.dump() for f in helper.files: f.Close() gROOT.Reset() from pprint import pprint pprint(helper) print 'Summary statistics per event class' print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35' % options.mH sigTotal = 0. dataTotal = 0. for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] sigTotal += sigVal dataTotal += datVal for c in categories: sigVal = helper.histos["sumEntries%s" % c] datVal = helper.histos["data_sumEntries%s" % c] effSig = 0.5 * (helper.histos["eff_sigma%s" % c][1] - helper.histos["eff_sigma%s" % c][0]) fwhm = (helper.histos["FWHM%s" % c][1] - helper.histos["FWHM%s" % c][0]) / 2.3548200 print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f' % ( sigVal, 100. * sigVal / sigTotal, datVal / (10. + 10.), 100. * datVal / dataTotal, effSig, fwhm) print "Done."
def drawPlots(plots, plotopts, rootopts, output, optzero, optmean, opth, optw): from ROOT import TPostScript, TCanvas, TLegend from ROOT import gROOT, gStyle, gPad gROOT.Reset() gROOT.SetStyle("Plain") gStyle.SetOptStat(0) gStyle.SetPalette(1) leg = TLegend(0.54, 0.71, 0.9, 0.9) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetBorderSize(0) if output != "DISPLAY": ps = TPostScript(output, 111) ps.NewPage() canv = TCanvas('c1', "Validation Plot Viewer", 600, 800) canv.Divide(opth, optw) maxperlist = opth * optw #current pad num = 0 #for stupid drawing system legends = [] #drawing hists for plotopt in plotopts: print "Drawing", plotopt.display_name num += 1 if (num > maxperlist and output != "DISPLAY"): #end of a current PS page ps.NewPage() print "new page" num = 1 canv.cd(num) gPad.SetLogy(plotopt.logy) leg.Clear() entries = {} valuemax = -999999.9 valuemin = 999999.9 entryZ = 0 for rootopt in rootopts: #get the max entries entries[rootopt] = plots[plotopt][rootopt].GetEntries() if (plots[plotopt][rootopt].GetEntries() > entryZ): entryZ = plots[plotopt][rootopt].GetEntries() for rootopt in rootopts: #get the max entries plot = plots[plotopt][rootopt] if (plotopt.profile): print rootopt.legendname, "is a profile: no need to scale" else: if not (entries[rootopt] == 0): print "scaling", rootopt.legendname, "to", entryZ / entries[ rootopt] plot.Scale(entryZ / entries[rootopt]) else: print rootopt.legendname, "is an empty hist, no scale" for rootopt in rootopts: #get the highest peak if (plots[plotopt][rootopt].GetMaximum() > valuemax): valuemax = plots[plotopt][rootopt].GetMaximum() entryZ = plots[plotopt][rootopt].GetEntries() sameDrawOpt = "" #now we plot all fillers, as otherwise they will render invisible everything behind them for rootopt in rootopts: if (rootopt.markerstyle > 0): #not filler continue plot = plots[plotopt][rootopt] print "Drawing filler from", rootopt.legendname if optzero: if (plotopt.logy == 1): plot.SetMinimum(1.0) else: plot.SetMinimum(0.0) plot.SetMaximum(valuemax * 1.1) plot.GetXaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[0].lstrip("+")]) if len(plotopt.vars_to_draw) > 1: plot.GetYaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[1].lstrip("+")]) if (plotopt.i2d): plot.Draw("CONT4Z " + sameDrawOpt) else: plot.Draw(rootopt.drawopt + sameDrawOpt) sameDrawOpt = " SAME" #plot the rest & fill the legend in the normal order for rootopt in rootopts: plot = plots[plotopt][rootopt] prname = rootopt.legendname if optmean and (not plotopt.profile): prname += " (mean: " + ("%.4f" % plot.GetMean()) + ")" leg.AddEntry(plot, prname, "L") if (rootopt.markerstyle == 0): #filler continue #fillers are already drawn print "Drawing plot from", rootopt.legendname if optzero: if (plotopt.logy == 1): plot.SetMinimum(1.0) else: plot.SetMinimum(0.0) plot.SetMaximum(valuemax * 1.1) plot.GetXaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[0].lstrip("+")]) if len(plotopt.vars_to_draw) > 1: plot.GetYaxis().SetTitle( plotopt.axis_captions[plotopt.vars_to_draw[1].lstrip("+")]) if (plotopt.i2d): plot.Draw("CONT4Z " + sameDrawOpt) else: plot.Draw(rootopt.drawopt + sameDrawOpt) sameDrawOpt = " SAME" if not plotopt.i2d: legends.append(leg.Clone()) legends[len(legends) - 1].Draw() canv.Update() if output != "DISPLAY": canv.Close() ps.Close() return canv, legends
def initialization(batch=True, font=default_font): '''-- ROOT initialization --''' print "Initializing ROOT ..." # general gROOT.Reset() gROOT.SetBatch(batch) gROOT.SetStyle("Plain") # gStyle gStyle.SetFillColor(0) gStyle.SetCanvasColor(10) gStyle.SetLineWidth(1) gStyle.SetPalette(8) gStyle.SetTextFont(font) #gStyle.SetTextSize(30) # Frame gStyle.SetFrameBorderMode(0) gStyle.SetFrameFillColor(0) # Pad gStyle.SetPadBorderMode(0) gStyle.SetPadColor(0) gStyle.SetPadBottomMargin(0.1) gStyle.SetPadTopMargin(0.01) gStyle.SetPadLeftMargin(0.1) gStyle.SetPadRightMargin(0.01) gStyle.SetPadTickX(1) # make ticks be on all 4 sides. gStyle.SetPadTickY(1) gStyle.SetPadGridX(0) gStyle.SetPadGridY(0) # histogram gStyle.SetHistFillStyle(0) gStyle.SetOptTitle(0) gStyle.SetTitleSize(0.22) gStyle.SetTitleFontSize(10) gStyle.SetTitleFont(font) gStyle.SetTitleFont(font, "xyz") gStyle.SetTitleYOffset(1.0) gStyle.SetTitleXOffset(1.0) gStyle.SetTitleXSize(0.04) gStyle.SetTitleYSize(0.04) gStyle.SetTitleX(.15) gStyle.SetTitleY(.98) gStyle.SetTitleW(.70) gStyle.SetTitleH(.05) # statistics box gStyle.SetOptStat(0) gStyle.SetStatFont(font) gStyle.SetStatFontSize(10) gStyle.SetStatX(.91) gStyle.SetStatY(.90) gStyle.SetStatW(.15) gStyle.SetStatH(.15) # axis labels gStyle.SetLabelFont(font) gStyle.SetLabelFont(font, "xyz") gStyle.SetLabelSize(10, "xyz") # gStyle.SetGridColor(1) gStyle.SetLegendBorderSize(1)
def plotInputComparison(files, runs, processes, path): #clear memory gROOT.Reset() #make canvas to save plots to c1 = TCanvas('c1') i = 0 Tfiles = [] while i < len(files): print "Adding file: %s to list of files to run with Run Number: %s and Process Name: %s" % ( files[i], runs[i], processes[i]) Tfiles.append(TFile(files[i])) i += 1 j = 0 Thists = [] while j < len(Tfiles): dirname = "DQMData/Run %s/HLT/Run summary/TimerService/Running 1 processes/process %s/Paths/%s_exclusive" % ( runs[j], processes[j], path) print dirname hist = Tfiles[j].Get(dirname) Thists.append(hist) j += 1 k = 0 leg = TLegend(0.4, 0.6, 0.9, 0.9, "") leg.SetFillStyle(0) leg.SetBorderSize(0) while k < len(Thists): if k == 0: Thists[k].Scale(1.0 / Thists[k].Integral()) Thists[k].GetYaxis().SetRangeUser(0.000008, 0.2) print "lower bound of bin 100: %i" % Thists[k].GetBinCenter(100) print "percentage of events running particle flow: %i " % Thists[ k].Integral(100, 500) Thists[k].SetLineWidth(2) Thists[k].SetLineColor(k + 1) if args.ext: Thists[k].GetXaxis().SetRangeUser(0, 2000) else: Thists[k].GetXaxis().SetRangeUser(0, 400) Thists[k].Draw() else: Thists[k].Scale(1.0 / Thists[k].Integral()) Thists[k].SetLineWidth(2) Thists[k].SetLineColor(k + 1) Thists[k].Draw("same") #write name in full name = files[k] if args.ext: Thists[k].GetXaxis().SetRangeUser(0, 2000) else: Thists[k].GetXaxis().SetRangeUser(0, 400) leg.AddEntry(Thists[k], name, "l") k += 1 leg.Draw("same") filename = 'PathExclusive_%s.pdf' % path c1.Print(filename)
def plotInputComparison(files, runs, processes, path): #clear memory gROOT.Reset() #make canvas to save plots to c1 = TCanvas('c1') i = 0 Tfiles = [] while i < len(files): print "Adding file: %s to list of files to run with Run Number: %s and Process Name: %s" % ( files[i], runs[i], processes[i]) Tfiles.append(TFile(files[i])) i += 1 j = 0 Thists = [] while j < len(Tfiles): dirname = "DQMData/Run %s/HLT/Run summary/TimerService/Running %s processes/process %s/Paths/%s_exclusive" % ( runs[j], nthreads[0], processes[j], path) print dirname hist = Tfiles[j].Get(dirname) Thists.append(hist) j += 1 k = 0 leg = TLegend(0.4, 0.6, 0.9, 0.9, "") leg.SetFillStyle(0) leg.SetBorderSize(0) while k < len(Thists): if k == 0: print "Overflow: %i" % Thists[k].GetBinContent( Thists[k].GetNbinsX() + 1) Thists[k].Scale(1.0 / Thists[k].Integral()) Thists[k].GetYaxis().SetRangeUser(0.000008, 0.2) Thists[k].SetLineWidth(2) Thists[k].SetLineColor(k + 1) Thists[k].Draw() else: print "Overflow: %i" % Thists[k].GetBinContent( Thists[k].GetNbinsX() + 1) Thists[k].Scale(1.0 / Thists[k].Integral()) Thists[k].SetLineWidth(2) Thists[k].SetLineColor(k + 1) Thists[k].Draw("same") #write name in full name = "Mean: %f" % Thists[k].GetMean() leg.AddEntry(Thists[k], name, "l") k += 1 leg.Draw("same") filename = 'PathExclusive_%s' % path if args.log: filename += '_log' c1.SetLogy(1) c1.Print(outdir + filename + '.png')
from ROOT import gBenchmark from ROOT import gROOT from ROOT import gRandom from ROOT import gSystem from ctypes import * import ROOT as r import re from array import array ##### Get Jet to Tau FR from Step1_JetToMuFR_Data import Make_Mu_FakeRate from Step1_JetToMuFR_Data import * from Step5_TT_W_ScaleFactor import * ##### Get Jet to Tau FR gROOT.Reset() import os ROOT.gROOT.SetBatch(True) #SubRootDir = 'OutFiles_FullSelection/' #SubRootDir = 'OutFiles_FullSelection_MT_LQMET/' #SubRootDir = 'OutFiles_FullSelection_MuEta2/' #SubRootDir = 'OutFiles_FinalSelection_SampleLQ1/' #SubRootDir = 'OutFiles_FullSelection_Jet50/' #SubRootDir = 'NewOutFiles_FinalSelection_SingleMu/' #SubRootDir = 'NewOutFiles_FinalSelection_/' #SubRootDir = 'NewOutFiles_FinalSelection_newTk50Trg/' #SubRootDir = 'NewOutFiles_FinalSelection_NoBRemove/' #SubRootDir = 'NewOutFiles_FinalSelection_FinalFixBug/' #SubRootDir = 'NewOutFiles_FinalSelection_FinalFixBugNoBVetoREmove/' #SubRootDir = 'NewOutFiles_FinalSelection_Approval_v1/'
def execute(run, sfile, lb_max): db = [] gROOT.Reset(); file = TFile(sfile) shmu = "Global/Luminosity/AnyTrigger/actualMu_vs_LB" hmu = file.Get(shmu) shits = [] shits.append("InnerDetector/Pixel/PIXIBL/Hits/AvgOcc_active_per_lumi_IBL") shits.append("InnerDetector/Pixel/PIX0/Hits/AvgOcc_active_per_lumi_B0") shits.append("InnerDetector/Pixel/PIX1/Hits/AvgOcc_active_per_lumi_B1") shits.append("InnerDetector/Pixel/PIX2/Hits/AvgOcc_active_per_lumi_B2") shits.append("InnerDetector/Pixel/PIXECA/Hits/AvgOcc_active_per_lumi_ECA") shits.append("InnerDetector/Pixel/PIXECC/Hits/AvgOcc_active_per_lumi_ECC") sdisabled = [] sdisabled.append("InnerDetector/Pixel/PIXIBL/_Experts/DisableAndErrorsLB/DisabledAndSyncErrorsModules_per_lumi_IBL2D_byPostProcess") sdisabled.append("InnerDetector/Pixel/PIX0/DisableAndErrorsLB/DisabledAndSyncErrorsModules_per_lumi_B0_byPostProcess") sdisabled.append("InnerDetector/Pixel/PIX1/DisableAndErrorsLB/DisabledAndSyncErrorsModules_per_lumi_B1_byPostProcess") sdisabled.append("InnerDetector/Pixel/PIX2/DisableAndErrorsLB/DisabledAndSyncErrorsModules_per_lumi_B2_byPostProcess") sdisabled.append("InnerDetector/Pixel/PIXECA/DisableAndErrorsLB/DisabledAndSyncErrorsModules_per_lumi_ECA_byPostProcess") sdisabled.append("InnerDetector/Pixel/PIXECC/DisableAndErrorsLB/DisabledAndSyncErrorsModules_per_lumi_ECC_byPostProcess") nlayer = 6 hhits = [] hdisabled = [] for i in range(0, nlayer): hhits.append(file.Get(shits[i])) hdisabled.append(file.Get(sdisabled[i])) standby_lb = [] find_standby(nlayer, hhits, lb_max, standby_lb) notready5to7pct_lb = [] notready7to10pct_lb = [] notready10to20pct_lb = [] notready20to30pct_lb = [] notready_gt30pct_lb = [] find_notready(nlayer, hdisabled, 0.05, 0.07, notready5to7pct_lb) find_notready(nlayer, hdisabled, 0.07, 0.1, notready7to10pct_lb) find_notready(nlayer, hdisabled, 0.1, 0.2, notready10to20pct_lb) find_notready(nlayer, hdisabled, 0.2, 0.3, notready20to30pct_lb) find_notready(nlayer, hdisabled, 0.3, 1., notready_gt30pct_lb) #print_def("standby", standby_lb) #user = "******" #assign_defect(db, "STANDBY", run, standby_lb) if 0: print_def("5to7pct", notready5to7pct_lb) print_def("7to10pct", notready7to10pct_lb) print_def("10to20pct", notready10to20pct_lb) print_def("20to30pct", notready20to30pct_lb) print_def("gt30pct", notready_gt30pct_lb) if 1: assign_defect(db, "5to7pct_NOTREADY", run, notready5to7pct_lb) assign_defect(db, "7to10pct_NOTREADY", run, notready7to10pct_lb) assign_defect(db, "10to20pct_NOTREADY", run, notready10to20pct_lb) assign_defect(db, "20to30pct_NOTREADY", run, notready20to30pct_lb) assign_defect(db, "GT30pct_NOTREADY", run, notready_gt30pct_lb) #nevent = hmu.GetEntries() #if nevent < 100000: #assign_lowstat(db, run, "assign lowstat") return db