for subdir, dirs, files in os.walk(path): for file in files: if file.find("tree.root") >= 0: the_file = os.path.join(subdir, file) if useChunk == False and the_file.find("Chunk") >= 0: continue Trees.append(the_file) #################### # check the trees #################### out_file = open("diagnostic.txt", "w") out_file.write("The tree list with event issue found :\n") for tree in Trees: print "check tree " + str(Trees.index(tree) + 1) + "/" + str(len(Trees)) rf = TFile(tree) t = rf.Get("events") numberOfEntries = t.GetEntries() bad_status = False show_every = 5 count = 1 for entry in xrange(numberOfEntries): ratio = 100. * float(entry) / float(numberOfEntries) if ratio > show_every * count: print "Done " + str(int(ratio)) + "% (" + str(entry) + "/" + str( numberOfEntries) + ")" count += 1 bad_event_status = t.GetEntry(entry) if bad_event_status == -1: bad_status = True break if bad_status == True: out_file.write(tree + "\n")
reader.AddVariable("m_Wj1Wj2", m_Wj1Wj2) reader.AddVariable("nllKinFit", nllKinFit) reader.AddVariable("pT_Wj2", pT_Wj2) reader.AddVariable("pT_bWj1Wj2", pT_bWj1Wj2) reader.AddVariable("qg_Wj2", qg_Wj2) #reader.BookMVA("testmva", "Results/TMVABDT_hadTopTagger_maxDepth3_9Var_ttH.xml") reader.BookMVA( "testmva", "Results_10Oct2017/TMVABDT_hadTopTagger_maxDepth3_9Var_ps75.xml") if process == "signal": file = TFile( "/scratch/arun/mvaTraining/22Sep2017/histograms_harvested_stage1_hadTopTagger_ttHToNonbb_fastsim.root" ) tree = file.Get("analyze_hadTopTagger/evtntuple/signal/evtTree") elif process == "TT": file = TFile( "/scratch/arun/mvaTraining/22Sep2017/histograms_harvested_stage1_hadTopTagger_TTToSemilepton_fastsim.root" ) tree = file.Get("analyze_hadTopTagger/evtntuple/TT/evtTree") elif process == "TTV": file1 = TFile( "/hdfs/local/veelken/ttHAnalysis/2016/2017Aug31/histograms/hadTopTagger/histograms_harvested_stage1_hadTopTagger_TTWJetsToLNu_fastsim.root" ) tree_ttw = file1.Get("analyze_hadTopTagger/evtntuple/TTW/evtTree") file2 = TFile( "/hdfs/local/veelken/ttHAnalysis/2016/2017Aug31/histograms/hadTopTagger/histograms_harvested_stage1_hadTopTagger_TTZToLLNuNu_fastsim.root" ) tree_ttz = file2.Get("analyze_hadTopTagger/evtntuple/TTZ/evtTree") list = TList()
pileupCut = 0.1 # script arguments if (len(sys.argv) > 1): fileNum = int(sys.argv[1]) if (len(sys.argv) > 2): dataDir = str(sys.argv[2]) if (len(sys.argv) > 3): fileList = str(sys.argv[3]) inarray = np.loadtxt(fileList, dtype=float) fileNum = int(inarray[fileNum]) layers = int(sys.argv[4]) fname = "hist_" + str(fileNum) + ".root" print "File " + dataDir + fname fin = TFile(dataDir + fname, 'read') fakeTree = fin.Get('fakeTree') realTree = fin.Get('realTree') pileupTree = fin.Get('pileupTree') print("Fake Tree Events: " + str(fakeTree.GetEntries())) print("Real Tree Events: " + str(realTree.GetEntries())) print("Pileup Tree Events: " + str(pileupTree.GetEntries())) def pileupMatching(track): min_dz = 10e6 for vertex in event.pileupZPosition: dZ = abs(track.vz - vertex) if dZ < min_dz: min_dz = dZ print("DZ Matched: ", min_dz) return min_dz
def test_PyROOT(): f = TFile(load('single1.root')) tree = f.Get('tree') rnp.tree2array(tree)
from ROOT import TFile import sys import array as arr import configparser ####################################### CONFIGURATION START ####################################### config = configparser.ConfigParser() config.read(sys.argv[1]) input_file = TFile(config['Head']['InputFile']) object_list = input_file.Get(config['Head']['ListName']) particle_name = config['Head']['Particle'] trig_pt_low = float(config['Pt']['TrigPtLow']) trig_pt_high = float(config['Pt']['TrigPtHigh']) assoc_pt_low = float(config['Pt']['AssocPtLow']) assoc_pt_high = float(config['Pt']['AssocPtHigh']) cent_low = float(config['Cent']['CentLow']) cent_high = float(config['Cent']['CentHigh']) peak_low = float(config['MassRegions']['PeakLow']) peak_high = float(config['MassRegions']['PeakHigh']) rsb_low = float(config['MassRegions']['RightSidebandLow']) rsb_high = float(config['MassRegions']['RightSidebandHigh']) lsb_low = float(config['MassRegions']['LeftSidebandLow']) lsb_high = float(config['MassRegions']['LeftSidebandHigh']) ####################################### CONFIGURATION END ####################################### def reset_ranges(hist, dim): #can we just talk about how stupid it is that TH1,2,3D's don't have a GetAxis attr if dim == 1: hist.GetXaxis().SetRangeUser(0, 0)
color=kAzure + 4, markerstyle=kOpenSquare, markersize=1.5, linewidh=2, linestyle=7) if args.ptweights: infileWeigts = TFile.Open(args.ptweights[0]) hPtWeights = infileWeigts.Get(args.ptweights[1]) hRecoPrompt, hRecoFD, hGenPrompt, hGenFD = ([] for iHisto in range(4)) infile = TFile(args.inFileName) for iPt, (ptMin, ptMax) in enumerate(zip(ptMins, ptMaxs)): hRecoPrompt.append( infile.Get('hPromptPt_%0.f_%0.f' % (ptMin * 10, ptMax * 10))) hRecoFD.append(infile.Get('hFDPt_%0.f_%0.f' % (ptMin * 10, ptMax * 10))) hGenPrompt.append( infile.Get('hPromptGenPt_%0.f_%0.f' % (ptMin * 10, ptMax * 10))) hGenFD.append(infile.Get('hFDGenPt_%0.f_%0.f' % (ptMin * 10, ptMax * 10))) # get unweighted yields (for uncertainty) nRecoPrompt = hRecoPrompt[iPt].Integral() nGenPrompt = hGenPrompt[iPt].Integral() nRecoFD = hRecoFD[iPt].Integral() nGenFD = hGenFD[iPt].Integral() # get weighted yields nRecoPromptWeighted, nGenPromptWeighted, nRecoFDWeighted, nGenFDWeighted = ( 0 for iVal in range(4)) for iBin in range(hRecoPrompt[iPt].GetNbinsX()):
def main(): parser = ArgumentParser() parser.add_argument('--indir', default="FILLMEPLEASE", help='directory name of input files') parser.add_argument('--infiles', default="*", help='name of input files') parser.add_argument('--tag', default=time.strftime("%a%d%b%Y_%Hh%Mm%Ss"), help='name of output directory') parser.add_argument( '--nevents', type=int, default=-1, help='maximum number of events for each dataset to process') parser.add_argument( '--nmaxevtsperjob', type=int, default=200000, help='maximum number of events per job (otherwise split)') parser.add_argument('--ncpu', type=int, default=-1, help='number of CPU to use in parallel') parser.add_argument('--topmatchingdir', default="FILLME", help='name of training directory') parser.add_argument('--tthfselectordir', default="FILLME", help='name of training directory') parser.add_argument('--reweightingdir', default="FILLME", help='name of training directory') parser.add_argument('--cTagSFFile', default="FILLME", help='PATH to file containing c-tagger SFs') args = parser.parse_args() workingdir = os.getcwd() if not os.path.isdir(workingdir + "/SELECTED_" + args.tag): os.mkdir(workingdir + "/SELECTED_" + args.tag) # Search for the input directory indir = os.path.abspath(args.indir) + "/" if not os.path.isdir(indir): print "Error: could not find directory '%s'" % indir sys.exit(1) # Take only files defined by args.infiles if not args.infiles == "*": filelist = [] tags = args.infiles.split("*") for f in [f for f in os.listdir(indir)]: for t in tags: if t == "": continue if t in f: filelist.append(f) else: filelist = [ f for f in os.listdir(indir) if not "ttH" in f and not "TTZ" in f ] # and not "31Mar" in f] # Count number of events in each file nevts_dict = {} print "Counting number of events in each file" for f in filelist: tfile = TFile(indir + f, workingdir + "/SELECTED_" + args.tag + "/" + f) tree_ = tfile.Get("tree") nevts = tree_.GetEntries() if nevts > args.nevents and args.nevents > 0: nevts = args.nevents nevts_dict[f] = nevts for _f, _n in nevts_dict.iteritems(): print "**** %s: %i events ****" % (_f, _n) #sys.exit(1) # Create batch temp tmpdirname = "BATCH_TMP_" + args.tag if not os.path.isdir(workingdir + "/" + tmpdirname): os.mkdir(workingdir + "/" + tmpdirname) ff_ = open(workingdir + "/" + tmpdirname + "/bigsub.txt", 'w') split_jobs_dict = {} for f in filelist: split_jobs_dict[f] = False # See if jobs need to be split if args.nmaxevtsperjob > 0 and nevts_dict[f] > args.nmaxevtsperjob: split_jobs_dict[f] = True eventsList = [] startEvent = 0 while (startEvent < nevts_dict[f]): eventsList.append(startEvent) startEvent += args.nmaxevtsperjob eventsList.append(nevts_dict[f]) print "Dataset %s was splitted in %i jobs" % (f, len(eventsList) - 1) for i in range(len(eventsList) - 1): if not os.path.isdir(workingdir + "/" + tmpdirname + "/" + f.split(".root")[0] + "_events_" + str(eventsList[i]) + "_" + str(eventsList[i + 1] - 1)): os.mkdir(workingdir + "/" + tmpdirname + "/" + f.split(".root")[0] + "_events_" + str(eventsList[i]) + "_" + str(eventsList[i + 1] - 1)) flaunch_ = open( workingdir + "/" + tmpdirname + "/" + f.split(".root")[0] + "_events_" + str(eventsList[i]) + "_" + str(eventsList[i + 1] - 1) + "/launch.sh", 'w') flaunch_.write("#!/bin/bash \n") flaunch_.write("source /user/smoortga/sklearn_setenv.sh \n") flaunch_.write( "cdir=/user/smoortga/Analysis/2017/ttcc_Analysis/CMSSW_8_0_25/src/ttcc/ \n" ) flaunch_.write( "export LD_LIBRARY_PATH=${cdir}:${cdir}/selection:$LD_LIBRARY_PATH \n" ) flaunch_.write( "cd /user/smoortga/Analysis/2017/ttcc_Analysis/CMSSW_8_0_25/src/ttcc/setup \n" ) flaunch_.write("root -l setup.C \n") flaunch_.write( "cd /user/smoortga/Analysis/2017/ttcc_Analysis/CMSSW_8_0_25/src/ttcc/analyse \n" ) flaunch_.write( "python Analyze.py --infile=%s --outfile=%s --topmatchingdir=%s --tthfselectordir=%s --reweightingdir=%s --cTagSFFile=%s --firstEvt=%i --lastEvt=%i --splitted=1 \n" % (indir + f, workingdir + "/SELECTED_" + args.tag + "/" + f, args.topmatchingdir, args.tthfselectordir, args.reweightingdir, args.cTagSFFile, eventsList[i], eventsList[i + 1])) flaunch_.close() ff_.write( "qsub -q localgrid -o %s/script.stdout -e %s/script.stderr -l walltime=04:59:59 %s/launch.sh \n" % (workingdir + "/" + tmpdirname + "/" + f.split(".root")[0] + "_events_" + str(eventsList[i]) + "_" + str(eventsList[i + 1] - 1), workingdir + "/" + tmpdirname + "/" + f.split(".root")[0] + "_events_" + str(eventsList[i]) + "_" + str(eventsList[i + 1] - 1), workingdir + "/" + tmpdirname + "/" + f.split(".root")[0] + "_events_" + str(eventsList[i]) + "_" + str(eventsList[i + 1] - 1))) #res = p.apply_async(Analyze, args = (indir+f,workingdir+"/SELECTED_"+args.tag+"/"+f, args.topmatchingdir,eventsList[i], eventsList[i+1],True,)) else: if not os.path.isdir(workingdir + "/" + tmpdirname + "/" + f.split(".root")[0]): os.mkdir(workingdir + "/" + tmpdirname + "/" + f.split(".root")[0]) flaunch_ = open( workingdir + "/" + tmpdirname + "/" + f.split(".root")[0] + "/launch.sh", 'w') flaunch_.write("#!/bin/bash \n") flaunch_.write("source /user/smoortga/sklearn_setenv.sh \n") flaunch_.write( "cdir=/user/smoortga/Analysis/2017/ttcc_Analysis/CMSSW_8_0_25/src/ttcc/ \n" ) flaunch_.write( "export LD_LIBRARY_PATH=${cdir}:${cdir}/selection:$LD_LIBRARY_PATH \n" ) flaunch_.write( "cd /user/smoortga/Analysis/2017/ttcc_Analysis/CMSSW_8_0_25/src/ttcc/setup \n" ) flaunch_.write("root -l setup.C \n") flaunch_.write( "cd /user/smoortga/Analysis/2017/ttcc_Analysis/CMSSW_8_0_25/src/ttcc/analyse \n" ) flaunch_.write( "python Analyze.py --infile=%s --outfile=%s --topmatchingdir=%s --tthfselectordir=%s --reweightingdir=%s --cTagSFFile=%s --firstEvt=0 --lastEvt=%i --splitted=0 \n" % (indir + f, workingdir + "/SELECTED_" + args.tag + "/" + f, args.topmatchingdir, args.tthfselectordir, args.reweightingdir, args.cTagSFFile, nevts_dict[f])) flaunch_.close() ff_.write( "qsub -q localgrid -o %s/script.stdout -e %s/script.stderr -l walltime=04:59:59 %s/launch.sh \n" % (workingdir + "/" + tmpdirname + "/" + f.split(".root")[0], workingdir + "/" + tmpdirname + "/" + f.split(".root")[0], workingdir + "/" + tmpdirname + "/" + f.split(".root")[0])) #res = p.apply_async(Analyze, args = (indir+f,workingdir+"/SELECTED_"+args.tag+"/"+f, args.topmatchingdir,0,nevts_dict[f],False,)) ff_.close()
h_TopMatch = TH1F("h_TopMatch", "", nbins, edges) h_Wmatch = TH1F("h_Wmatch", "", nbins, edges) h_unmatch = TH1F("h_unmatch", "", nbins, edges) h_ttFailed = TH1F("h_ttFailed", "", nbins, edges) h_ttPassed = TH1F("h_ttPassed", "", nbins, edges) h_ttPassed_Match = TH1F("h_ttPassed_Match", "", nbins, edges) h_ttPassed_Wmatch = TH1F("h_ttPassed_Wmatch", "", nbins, edges) h_ttPassed_unmatch = TH1F("h_ttPassed_unmatch", "", nbins, edges) h_pfMC = TH1F("h_pfMC", "", 2, 0, 2) h_pfMCpassf = TH1F("h_pfMCpassf", "", 2, 0, 2) h_pfMCpassp = TH1F("h_pfMCpassp", "", 2, 0, 2) h_pfMCfailf = TH1F("h_pfMCfailf", "", 2, 0, 2) h_pfMCfailp = TH1F("h_pfMCfailp", "", 2, 0, 2) openTop = TFile(Top_path, "read") h_total_mcweight_Top = openTop.Get("h_total_mcweight") totalEventsTop = h_total_mcweight_Top.Integral() treeTop = openTop.Get("monoHbb_Tope_boosted") EventsTop = treeTop.GetEntries() for i in range(EventsTop): treeTop.GetEntry(i) st_TopMatching = getattr(treeTop, 'st_TopMatching') CSV_Top = getattr(treeTop, 'FJetCSV') SD_Top = getattr(treeTop, 'FJetMass') dPhi_Top = getattr(treeTop, 'min_dPhi') if (st_TopMatching == 2) and (SD_Top > 100.0) and (SD_Top < 150.0) and ( dPhi_Top > 0.4): h_TopMatch.Fill(CSV_Top) if (st_TopMatching == 3) and (SD_Top > 100.0) and (SD_Top < 150.0) and ( dPhi_Top > 0.4):
import ROOT from ROOT import TFile, TTree, TCanvas, TGraph, TMultiGraph, TGraphErrors, TLegend file10p = TFile("10p/upper_limits.root") file50p = TFile("50p/upper_limits.root") file100p = TFile("100p/upper_limits.root") file300p = TFile("300p/upper_limits.root") g10p = file10p.Get("Graph") g50p = file50p.Get("Graph") g100p = file100p.Get("Graph") g300p = file300p.Get("Graph") g50p.SetLineColor(2) g100p.SetLineColor(3) g300p.SetLineColor(4) W = 800 H = 600 T = 0.08*H B = 0.12*H L = 0.12*W R = 0.04*W c = TCanvas("c","c",100,100,W,H) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin( L/W ) c.SetRightMargin( R/W )
#---------------------------------# p = argparse.ArgumentParser(description='Specify whether the MVA was performed on the muon or the electron sample') p.add_argument('isMuon_option', help='Type <<muon>> or <<electron>>') args = p.parse_args() # Switch from muon to electron channel if args.isMuon_option == "muon": isMuon = True if args.isMuon_option == "electron": isMuon = False #---------------------------------# # Get input trees (MC) if isMuon: fIn_bkg = TFile("/eos/user/j/jdioquin/www/MVA_studies/TreeFiles_31718/Tree_MC_Background_mu.root") tbkg_in = fIn_bkg.Get("minitree_background_mu") fIn_sig = TFile("/eos/user/j/jdioquin/www/MVA_studies/TreeFiles_31718/Tree_MC_Signal_mu.root") tsig_in = fIn_sig.Get("minitree_signal_mu") fOut = TFile("/eos/user/j/jdioquin/www/MVA_studies/BDTeval2818/BDTeval_mu.root","RECREATE") else: fIn_bkg = TFile("/eos/user/j/jdioquin/www/MVA_studies/TreeFiles_31718/Tree_MC_Background_ele.root") tbkg_in = fIn_bkg.Get("minitree_background_ele") fIn_sig = TFile("/eos/user/j/jdioquin/www/MVA_studies/TreeFiles_31718/Tree_MC_Signal_ele.root") tsig_in = fIn_sig.Get("minitree_signal_ele") fOut = TFile("/eos/user/j/jdioquin/www/MVA_studies/BDTeval2818/BDTeval_ele.root","RECREATE") # Create arrays for the reader
from ROOT import TFile, TH2F, TCanvas, TH3F from HistEfficiency2D import HistEfficiency2D from style import papas_style, cms_style papas_file = TFile('./rootfiles/papassampletuned.root') cms_file = TFile('./rootfiles/cmssamplejetted.root') papas_tree = papas_file.Get('events') cms_tree = cms_file.Get('events') #histo = TH2F('2D_eff1', 'PAPAS efficiency : P_{T} : eta', 50, 0, 10, 50, -4, 4) #papas_tree.Project('2D_eff1', 'jet1_eta:jet1_pt', 'jet1_pt>0') #can1 = TCanvas() #histo.Draw('LEGO') #histo2 = TH2F('2D_eff2', 'PAPAS efficiency : P_{T} : eta', 50, 0, 10, 50, -4, 4) #papas_tree.Project('2D_eff2', 'jet1_eta:jet1_pt', # 'jet1_pt>0 && jet1_rec_211_num==1') #can2 = TCanvas() #histo2.Draw('LEGO') #div_histo = histo2.Clone('2D_eff') #div_histo.Divide(histo) #can3 = TCanvas() #div_histo.Draw('LEGO')
from ROOT import TFile, TH2D, TDirectory, TCanvas, TList, gPad, gStyle, TLegend, TVector2, TMath import math Data = TFile('user.luadamek.20219352._000196.hist-output.root') Monte = TFile('user.luadamek.20219380._000083.hist-output.root') histTreeData = Data.Get( 'LA_EoverP_InDetTrackParticlesSortedLooseIsolatedVertexAssociated_tree') histTreeMonte = Monte.Get( 'LA_EoverP_InDetTrackParticlesSortedLooseIsolatedVertexAssociated_tree') entriesdata = histTreeData.GetEntriesFast() for jentry in xrange(entriesdata): nb = histTreeData.GetEntry(jentry) if nb <= 0: continue etacal = 0 ntrt = histTreeData.trk_nTRT E = histTreeData.trk_nclusters_EM_200 + histTreeData.trk_nclusters_HAD_200 if (ntrt > 20 and E > 0): print("Fill histogram here") entriesmonte = histTreeMonte.GetEntriesFast() for jentry in xrange(entriesmonte): nb = histTreeMonte.GetEntry(jentry) if nb <= 0: continue
InSyncRuns = list() OutOfSyncRuns = list() for Run in range(StartRun,StopRun+1,1): IsInSync = False inputfile = "/eos/uscms/store/user/cmstestbeam/2019_04_April_CMSTiming/KeySightScope/RecoData/TimingDAQRECO/RecoWithTracks/v6/run_scope"+str(Run)+"_converted.root" if not os.path.exists(inputfile): print "input file "+inputfile+" does not exist" continue file = TFile(inputfile) tree = file.Get("pulse") c = TCanvas("cv","cv",800,800) num = TH2F("num",";x;y",25,0,50,25,0,50) den = TH2F("den",";x;y",25,0,50,25,0,50) tree.Draw("y_dut[0]:x_dut[0]>>den","ntracks==1 && y_dut[0] > 0 ","colz") tree.Draw("y_dut[0]:x_dut[0]>>num","ntracks==1 && y_dut[0] > 0 && amp[1] > 200 ","colz") num.Divide(den) effInside = num.GetBinContent(num.GetXaxis().FindFixBin(18.0),num.GetYaxis().FindFixBin(25.0)) effOutside = num.GetBinContent(num.GetXaxis().FindFixBin(18.0),num.GetYaxis().FindFixBin(18.0)) print num.GetXaxis().FindFixBin(18.0), " ", num.GetYaxis().FindFixBin(25.0), " ", effInside print num.GetXaxis().FindFixBin(18.0), " ", num.GetYaxis().FindFixBin(18.0), " ", effOutside
inFile3 = TFile(filename3) inFile4 = TFile(filename4) inFile5 = TFile(filename5) inFile6 = TFile(filename6) zFile1 = TFile( "/home/mrsolt/hps/Vertexing/L0/1pt05/ap/upperlimit/golden_massbin.root") zFile2 = TFile("/home/mrsolt/hps/Vertexing/L0/1pt05/ap/L1L2/golden.root") zFile3 = TFile("/home/mrsolt/hps/Vertexing/L0/1pt05/ap/L2L2/golden.root") zFile4 = TFile("/home/mrsolt/hps/Vertexing/L0/1pt05/ap/L2L3/golden.root") zFile5 = TFile("/home/mrsolt/hps/Vertexing/L0/1pt05/ap/L3L3/golden.root") zFile6 = "" c = TCanvas("c", "c", 800, 600) XaxisTitle = inFile1.Get(histoTitle).GetXaxis().GetTitle() YaxisTitle = inFile1.Get(histoTitle).GetYaxis().GetTitle() Histo1 = inFile1.Get(histoTitle) Histo2 = inFile2.Get("eff_all_unscaled") Histo3 = inFile3.Get(histoTitle) Histo4 = inFile4.Get(histoTitle) Histo5 = inFile5.Get(histoTitle) Histo6 = inFile6.Get("eff_all_unscaled") normHisto = inFile1.Get("eff_all_unscaled").GetFunction("exppol4").Eval(-5) print normHisto Histo2.Scale(1. / normHisto) Histo6.Scale(1. / normHisto) func1 = inFile1.Get(histoTitle).GetFunction("exppol4")
print( "Plotting of the enrgy distribution can be performed only for one energy value" ) exit() energy = calo_init.energy(0) canv = prepare_single_canvas('energyDistribution_' + str(energy) + 'GeV', 'Energy distribution for ' + str(energy) + 'GeV') canv.cd() energy = calo_init.energy(0) resolution_list = [] mean_list = [] # files represent different types for the same particle energy: for ifile, filename in enumerate(calo_init.filenamesIn): f = TFile(filename, "READ") hEn = f.Get(histogramNames[ifile]) hEn.Sumw2() if hEn.GetEntries() > 0: hEn.Scale(1. / hEn.GetEntries()) hEn.Rebin(4) hEn.SetTitle('') if calo_init.args.axisMax: hEn.GetYaxis().SetRangeUser(0, calo_init.args.axisMax) fitPre = TF1("fitPre", "gaus", hEn.GetMean() - 1. * hEn.GetRMS(), hEn.GetMean() + 1. * hEn.GetRMS()) resultPre = hEn.Fit(fitPre, "SQRN") fit = TF1("fit", "gaus", resultPre.Get().Parameter(1) - 2. * resultPre.Get().Parameter(2), resultPre.Get().Parameter(1) + 2. * resultPre.Get().Parameter(2)) fit.SetLineColor(coloursFit[ifile])
from ROOT import TFile, TH2F, TCanvas, TF1 from papas_analysis_gael.tools.style import papas_style, cms_style, cms_style2, papas_style2 from papas_analysis_gael.tools.HistComparator import HistComparator from cpyroot.tools.fitter2d import Fitter2D fil = TFile('./rootfiles/photon_test_tree.root') tree = fil.Get('events') eres = TF1('eres', 'sqrt(([0]/sqrt(x))**2+([1]/x)**2+[2]**2)') comp = HistComparator(tree, style1 = cms_style, style2 = papas_style, nbin = 200, xmin = 0.5, xmax = 1.5, xvar = 'E_{rec}/E_{gen}', var1 = 'cmsjet_e/gen_jet_e', cut = 'gen_jet_pt>1 && gen_jet_pt<10 && abs(gen_jet_eta)<1.479 && simtrack_len==3', var2 = 'papasjet_e/gen_jet_e') comp2 = HistComparator(tree, style1 = cms_style, style2 = papas_style, nbin = 200, xmin = 0.4, xmax = 1.6, xvar = 'E_{rec}/E_{gen}', var1 = 'cmsjet_e/gen_jet_e', cut = 'gen_jet_pt>1 && gen_jet_pt<10 && abs(gen_jet_eta)>1.479 && abs(gen_jet_eta)<3 && simtrack_len==3', var2 = 'papasjet_e/gen_jet_e') fitter = Fitter2D('histo2d','E_{rec}/E_{gen}vsE_{gen} endcap', 198, 1, 100, 200, 0, 2) tree.Project('histo2d','cmsjet_e/gen_jet_e:gen_jet_e','gen_jet_pt>1 && abs(gen_jet_eta)>1.479 && abs(gen_jet_eta)<3 && simtrack_len==3 && cmsjet_e>0') fitter.fit_slices(selection=3) can3 = TCanvas() fitter.h2d.Draw() can = TCanvas() fitter.hmean.SetTitle('Fitted value of mean endcap') fitter.hmean.Draw() fitter.hsigma.SetTitle('Fitted value of Sigma endcap')
from ROOT import TFile, TH1F, TCanvas, TF1, gStyle, gROOT, gPad, TLegend, TH2F from numpy import arctan gROOT.SetBatch() gStyle.SetOptStat(0) fontsize = 0.045 gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) gStyle.SetTitleOffset(1.5) f = TFile("../data.root") tree = f.Get("drift_4000V") th = 0.02 cut = "Chn1_Height>{0}&&Chn3_Height>{0}&&Chn7_Height>{0}&&Chn8_Height>{0}".format( th) theta_max = arctan(100 / 290.) print("Maximum angle [rad]: {}".format(theta_max)) print("Number of total events: {}".format(tree.GetEntries())) print("Number of events after applying threshold: {}".format( tree.GetEntries(cut))) print("Number of events after removing bad fits: {}".format( tree.GetEntries(cut + "&&X0Err<6&&ThetaErr<0.04"))) print("Number of events after removing bad fits (x0 only): {}".format(
isBlinded = True ROOT.TH1.SetDefaultSumw2(True) ########################## # get data tree ########################## treeName = "TauCheck" if channel == "mt": fdata = TFile(indirData + "/" + "SingleMuon_Run2016BCD.root", "read") if channel == "et": fdata = TFile(indirData + "/" + "SingleElectron_Run2016BCD.root", "read") tdata = fdata.Get(treeName) #redefine tree name for MC treeName = "TauCheck" + systName ########################## # define file lists ########################## lvv = { "ST_t-channel_top_4f_leptonDecays": { "xsec": 136.95 * 3 * 0.108, "isBinned": False, "binVar": "", "files": ["ST_t-channel_top_4f_leptonDecays"] },
# filename='/nfs/dust/cms/user/albrechs/CMSSW_8_1_0/src/DijetCombineLimitCode/plots/fitDiagnosticsZZ_T7_m21p00'+postfix+'0_invMass_combined.root' filename = '/nfs/dust/cms/user/albrechs/CMSSW_8_1_0/src/DijetCombineLimitCode/plots/fitDiagnosticsZZ_T7_m15p40' + postfix + '0_invMass_combined.root' # filename='/nfs/dust/cms/user/albrechs/CMSSW_8_1_0/src/DijetCombineLimitCode/plots/fitDiagnosticsZZ_T0_m1p080_invMass_combined.root' # filename='/nfs/dust/cms/user/albrechs/CMSSW_8_1_0/src/DijetCombineLimitCode/plots/fitDiagnosticsZZ_M0_105p000_invMass_combined_1GeV.root' # filename='/nfs/dust/cms/user/albrechs/CMSSW_8_1_0/src/DijetCombineLimitCode/plots/fitDiagnosticsZZ_M0_105p000_invMass_combined_1GeV.root' File = TFile(filename, 'READ') pointname = filename.split('/')[-1].split('_') canvTitle = pointname[1] + ' ' + pointname[2] + ' ' + pointname[3][:-1] pointname = pointname[1] + '_' + pointname[2] + '_' + pointname[3][:-1] for channel in ['ch1', 'ch2']: if channel == 'ch1': name = 'VV' if channel == 'ch2': name = 'VBF' signal = File.Get('shapes_fit_s/' + channel + '/total_signal') background = File.Get('shapes_fit_s/' + channel + '/total_background') data = File.Get('shapes_fit_s/' + channel + '/data') # signal.Scale(10) # TH1 h; // the histogram (you should set the number of bins, the title etc) # auto nPoints = graph.GetN(); // number of points in your TGraph # for(int i=0; i < nPoints; ++i) { # double x,y; # graph.GetPoint(i, x, y); # h->Fill(x,y); // ? # } N = 0 datahist = TH1F('data', 'data', 3451, 1050, 4500)
fin_ZB = TFile('../../toHist/data/ptH_%s/mc_ptH_%s_ptV%d.hist_ZB.root'%(ptH,ptH,i)) fin_JP0 = TFile('../../toHist/data/ptH_%s/mc_ptH_%s_ptV%d.hist_JP0.root'%(ptH,ptH,i)) fin_JP1 = TFile('../../toHist/data/ptH_%s/mc_ptH_%s_ptV%d.hist_JP1.root'%(ptH,ptH,i)) fin_JP2 = TFile('../../toHist/data/ptH_%s/mc_ptH_%s_ptV%d.hist_JP2.root'%(ptH,ptH,i)) fin_AJP = TFile('../../toHist/data/ptH_%s/mc_ptH_%s_ptV%d.hist_AJP.root'%(ptH,ptH,i)) for j in reckind_List: print j for m in xrange(0,2): print m for k in particle_List: tc=TCanvas('c','c',700,500) print k h_ZB=fin_ZB.Get('h_%s_pid_parent_%s_J%d_PT%d'%(j,k,m,i-1)) h_JP0=fin_JP0.Get('h_%s_pid_parent_%s_J%d_PT%d'%(j,k,m,i-1)) h_JP1=fin_JP1.Get('h_%s_pid_parent_%s_J%d_PT%d'%(j,k,m,i-1)) h_JP2=fin_JP2.Get('h_%s_pid_parent_%s_J%d_PT%d'%(j,k,m,i-1)) h_AJP=fin_AJP.Get('h_%s_pid_parent_%s_J%d_PT%d'%(j,k,m,i-1)) h_ZB.Scale(1.0000/(h_ZB.Integral())) h_JP0.Scale(1.0000/(h_JP0.Integral())) h_JP1.Scale(1.0000/(h_JP1.Integral())) h_JP2.Scale(1.0000/(h_JP2.Integral())) h_AJP.Scale(1.0000/(h_AJP.Integral())) ''' h_ZB.GetXaxis().SetDecimals(1) h_JP0.GetXaxis().SetDecimals(1) h_JP1.GetXaxis().SetDecimals(1)
if not isxgbs: for vkey, ivar in vardir.items(): if vkey.find('xgbs') != -1: vardir.pop(vkey) print '-' * 80 for vkey, ivar in vardir.items(): print '->', vkey.ljust(20), ivar print '-' * 80 for type, ivar in ddir.items(): file = TFile(ivar['file']) tree = file.Get('tree') print ivar['file'], 'is read ...' var_tuples, hists = returnTuples(type, vardir) cut = '(' + ivar['acut'] + ')*' + ivar['weight'] print(type, cut) tree.MultiDraw(var_tuples, cut) multihists.update(copy.deepcopy(hists)) writes = {} for vkey, ivar in vardir.items():
def main(argv): parser = argparse.ArgumentParser( description='Makes training data set for various vertex/decay ID') parser.add_argument('-c', '--config', help="JSON with script configuration", default='config.json') parser.add_argument('-t', '--type', help="Input file format") parser.add_argument('-i', '--input', help="Input directory") parser.add_argument('-o', '--output', help="Output directory") parser.add_argument('-v', '--view', help="view") args = parser.parse_args() config = read_config(args.config) print '#' * 50, '\nPrepare data for CNN' INPUT_TYPE = config['prepare_data_vtx_id']['input_type'] INPUT_DIR = config['prepare_data_vtx_id']['input_dir'] OUTPUT_DIR = config['prepare_data_vtx_id']['output_dir'] PATCH_SIZE_W = config['prepare_data_vtx_id']['patch_size_w'] PATCH_SIZE_D = config['prepare_data_vtx_id']['patch_size_d'] print 'Using %s as input dir, and %s as output dir' % (INPUT_DIR, OUTPUT_DIR) print '#' * 50 rootModule = config['prepare_data_vtx_id'][ 'module_name'] # larsoft module name used for data dumps in ROOT format selected_view_idx = config['prepare_data_vtx_id'][ 'selected_view_idx'] # set the view id nearby_empty = config['prepare_data_vtx_id'][ 'nearby_empty'] # number of patches near each vtx, but with empty area in the central pixel nearby_on_track = config['prepare_data_vtx_id'][ 'nearby_on_track'] # number of patches on tracks or showers, somewhere close to each vtx crop_event = config['prepare_data_vtx_id'][ 'crop_event'] # use true only if no crop on LArSoft level and not a noise dump print 'Using', nearby_empty, 'empty and', nearby_on_track, 'on track patches per each verex in view', selected_view_idx max_capacity = 300000 db = np.zeros((max_capacity, PATCH_SIZE_W, PATCH_SIZE_D), dtype=np.float32) db_y = np.zeros((max_capacity, 5), dtype=np.int32) kHadr = 0x1 # hadronic inelastic scattering kPi0 = 0x2 # pi0 produced in this vertex kDecay = 0x4 # point of particle decay (except pi0 decays) kConv = 0x8 # gamma conversion cnt_ind = 0 cnt_vtx = 0 cnt_decay = 0 cnt_gamma = 0 cnt_nu = 0 cnt_trk = 0 cnt_void = 0 fcount = 0 event_list = [] if INPUT_TYPE == "root": fnames = [f for f in os.listdir(INPUT_DIR) if '.root' in f] for n in fnames: rootFile = TFile(INPUT_DIR + '/' + n) keys = [ rootModule + '/' + k.GetName()[:-4] for k in rootFile.Get(rootModule).GetListOfKeys() if '_raw' in k.GetName() ] event_list.append((rootFile, keys)) else: keys = [f[:-4] for f in os.listdir(INPUT_DIR) if '.raw' in f ] # only main part of file name, without extension event_list.append( (INPUT_DIR, keys)) # single entry in the list of txt files for entry in event_list: folder = entry[0] event_names = entry[1] for evname in event_names: finfo = evname.split('_') evt_no = finfo[2] tpc_idx = int(finfo[8]) view_idx = int(finfo[10]) if view_idx != selected_view_idx: continue fcount += 1 print 'Process event', fcount, evname, 'NO.', evt_no # get clipped data, margin depends on patch size in drift direction raw, deposit, pdg, tracks, showers = get_data( folder, evname, PATCH_SIZE_D / 2 + 2, crop_event) if raw is None: print 'Skip empty event...' continue vtx = get_vertices(pdg) nuvtx = get_nu_vertices(pdg) print 'Found', vtx.shape[ 0], 'hadronic vertices/decay', nuvtx.shape[ 0], 'neutrino vertices' for v in range(vtx.shape[0]): flags = 0 if vtx.shape[0] > 0: flags = vtx[v, 2] nuflags = 0 if nuvtx.shape[0] > 0: nuflags = nuvtx[v, 2] if (flags & kHadr) > 0 or (flags & kDecay) > 0 or ( (flags & kPi0) > 0 and (flags & kConv) > 0): wire = vtx[v, 0] drif = vtx[v, 1] x_start = np.max([0, wire - PATCH_SIZE_W / 2]) x_stop = np.min([raw.shape[0], x_start + PATCH_SIZE_W]) y_start = np.max([0, drif - PATCH_SIZE_D / 2]) y_stop = np.min([raw.shape[1], y_start + PATCH_SIZE_D]) if x_stop - x_start != PATCH_SIZE_W or y_stop - y_start != PATCH_SIZE_D: continue target = np.zeros( 5, dtype=np.int32 ) # [decay, hadronic_vtx, g_conversion, nu_primary, not_vtx] if nuflags > 0: target[3] = 1 cnt_nu += 1 elif (flags & kDecay) > 0: target[0] = 1 cnt_decay += 1 elif (flags & kHadr) > 0: target[1] = 1 cnt_vtx += 1 elif (flags & kConv) > 0: target[2] = 1 cnt_gamma += 1 patch = get_patch(raw, wire, drif, PATCH_SIZE_W, PATCH_SIZE_D) if cnt_ind < max_capacity: db[cnt_ind] = patch db_y[cnt_ind] = target cnt_ind += 1 else: break n_empty = 0 n_trials = 0 while n_empty < nearby_empty and n_trials < 500: wi = np.random.randint(x_start + 1, x_stop - 1) di = np.random.randint(y_start + 1, y_stop - 1) if (wi < wire - 1 or wi > wire + 1) and (di < drif - 2 or di > drif + 2): if tracks[wi, di] == 0 and showers[wi, di] == 0: if cnt_ind < max_capacity: patch = get_patch(raw, wi, di, PATCH_SIZE_W, PATCH_SIZE_D) target = np.zeros(5, dtype=np.int32) target[4] = 1 db[cnt_ind] = patch db_y[cnt_ind] = target cnt_void += 1 cnt_ind += 1 n_empty += 1 else: break n_trials += 1 n_track = 0 n_trials = 0 while n_track < nearby_on_track and n_trials < 500: wi = np.random.randint(x_start + 1, x_stop - 1) di = np.random.randint(y_start + 1, y_stop - 1) if (wi < wire - 1 or wi > wire + 1) and (di < drif - 2 or di > drif + 2): if tracks[wi, di] == 1 or showers[wi, di] == 1: if cnt_ind < max_capacity: patch = get_patch(raw, wi, di, PATCH_SIZE_W, PATCH_SIZE_D) target = np.zeros(5, dtype=np.int32) target[4] = 1 db[cnt_ind] = patch db_y[cnt_ind] = target cnt_trk += 1 cnt_ind += 1 n_track += 1 else: break n_trials += 1 print 'Total size', cnt_ind, ':: hadronic:', cnt_vtx, 'decays:', cnt_decay, 'nu-primary:', cnt_nu, 'g-conv:', cnt_gamma, 'empty:', cnt_void, 'on-track:', cnt_trk np.save(OUTPUT_DIR + '/db_view_' + str(selected_view_idx) + '_x', db[:cnt_ind]) np.save(OUTPUT_DIR + '/db_view_' + str(selected_view_idx) + '_y', db_y[:cnt_ind])
def setPUHistogram(l): # https://raw.githubusercontent.com/cms-sw/cmssw/CMSSW_7_4_X/SimGeneral/MixingModule/python/mix_2015_25ns_Startup_PoissonOOTPU_cfi.py probValue = [ 4.8551E-07, 1.74806E-06, 3.30868E-06, 1.62972E-05, 4.95667E-05, 0.000606966, 0.003307249, 0.010340741, 0.022852296, 0.041948781, 0.058609363, 0.067475755, 0.072817826, 0.075931405, 0.076782504, 0.076202319, 0.074502547, 0.072355135, 0.069642102, 0.064920999, 0.05725576, 0.047289348, 0.036528446, 0.026376131, 0.017806872, 0.011249422, 0.006643385, 0.003662904, 0.001899681, 0.00095614, 0.00050028, 0.000297353, 0.000208717, 0.000165856, 0.000139974, 0.000120481, 0.000103826, 8.88868E-05, 7.53323E-05, 6.30863E-05, 5.21356E-05, 4.24754E-05, 3.40876E-05, 2.69282E-05, 2.09267E-05, 1.5989E-05, 4.8551E-06, 2.42755E-06, 4.8551E-07, 2.42755E-07, 1.21378E-07, 4.8551E-08 ] mc = TH1F("mc", "nPV distribution", 50, 0, 50) mc.Sumw2() for i in range(50): mc.SetBinContent(i + 1, probValue[i]) mc.SetLineWidth(3) mc.SetLineColor(1) mc.SetLineStyle(2) mc.Scale(1. / mc.Integral()) puFile = TFile("./PU/PU_%s_69000.root" % l, "READ") data = puFile.Get("pileup") data.SetLineWidth(3) data.SetLineColor(1) data.Scale(1. / data.Integral()) puUpFile = TFile("./PU/PU_%s_72450.root" % l, "READ") dataUp = puUpFile.Get("pileup") dataUp.SetLineWidth(3) dataUp.SetLineColor(634) dataUp.Scale(1. / dataUp.Integral()) puDownFile = TFile("./PU/PU_%s_65550.root" % l, "READ") dataDown = puDownFile.Get("pileup") dataDown.SetLineWidth(3) dataDown.SetLineColor(598) dataDown.Scale(1. / dataDown.Integral()) ratio = data.Clone("ratio") ratioUp = dataUp.Clone("ratioUp") ratioDown = dataDown.Clone("ratioDown") ratio.Divide(mc) ratioUp.Divide(mc) ratioDown.Divide(mc) outFile = TFile("./PU/PU_%s.root" % l, "RECREATE") outFile.cd() mc.Write() data.Write() dataUp.Write() dataDown.Write() ratio.Write() ratioUp.Write() ratioDown.Write() outFile.Close() print "Histograms written to ./PU/PU_%s.root file" % l leg = TLegend(0.65, 0.7, 0.98, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("pile-up reweighting") leg.AddEntry(dataUp, "Up", "pl") leg.AddEntry(data, "Central", "pl") leg.AddEntry(dataDown, "Down", "pl") leg.AddEntry(mc, "MC 25ns", "pl") c1 = TCanvas("c1", "PileUp reweighting", 800, 800) c1.cd() c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetTicks(1, 1) dataDown.SetTitle(";number of true interactions") dataDown.GetXaxis().SetRangeUser(0., 30) dataDown.Draw("HIST") dataUp.Draw("SAME, HIST") data.Draw("SAME, HIST") mc.Draw("SAME, L") leg.Draw() c1.Print("PU/PU_%s.pdf" % l) c1.Print("PU/PU_%s.png" % l)
from ROOT import TFile, TGraph, TMarker, TLine, TLegend, TCanvas f_hmssm = TFile('data/hMSSM_13TeV.root') h_width_A = f_hmssm.Get('width_A') h_br_A_tt = f_hmssm.Get('br_A_tt') # to calculate partial width mass = 600. bin_mass = h_width_A.FindBin(mass) h_width = h_width_A.ProjectionY('h_width', bin_mass, bin_mass) h_br = h_br_A_tt.ProjectionY('h_br', bin_mass, bin_mass) h_coupling = h_width.Clone('h_coupling') for i in xrange(1, h_coupling.GetNbinsX() + 1): h_coupling.SetBinContent(i, 1. / h_coupling.GetXaxis().GetBinCenter(i)**2) n_points = h_width.GetNbinsX() g_width = TGraph(n_points) g_partial_width = TGraph(n_points) for i in xrange(n_points): g_width.SetPoint(i, h_coupling.GetBinContent(i + 1), h_width.GetBinContent(i + 1)) g_partial_width.SetPoint( i, h_coupling.GetBinContent(i + 1), h_width.GetBinContent(i + 1) * h_br.GetBinContent(i + 1)) # Points/lines for simulated samples
file_100TeV = TFile( "minBias_100TeV_particleDistributions/MinBiasDistribution_100TeV.root") file_13TeV = TFile( "minBias_13TeV_particleDistributions/MinBiasDistribution_13TeV.root") file_13TeV_DelphesCMS = TFile( "minBias_13TeV_DelphesCMS_particleDistributions/MinBiasDistribution_13TeV_DelphesCMS.root" ) file_13TeV_DelphesFCC_CMSJets = TFile( "minBias_13TeV_DelphesFCC_CMSJets_particleDistributions/MinBiasDistribution_13TeV_DelphesFCC_CMSJets.root" ) file_100TeV_DelphesFCC_CMSJets = TFile( "minBias_100TeV_DelphesFCC_CMSJets_particleDistributions/MinBiasDistribution_100TeV_DelphesFCC_CMSJets.root" ) # Retrieving plots jetRecoPtDistribution_TH1I_100TeV = file_100TeV.Get("jetRecoPtDistribution") jetRecoPtDistribution_TH1I_13TeV = file_13TeV.Get("jetRecoPtDistribution") jetRecoPtDistribution_TH1I_13TeV_DelphesCMS = file_13TeV_DelphesCMS.Get( "jetRecoPtDistribution") jetRecoPtDistribution_TH1I_13TeV_DelphesFCC_CMSJets = file_13TeV_DelphesFCC_CMSJets.Get( "jetRecoPtDistribution") jetRecoPtDistribution_TH1I_100TeV_DelphesFCC_CMSJets = file_100TeV_DelphesFCC_CMSJets.Get( "jetRecoPtDistribution") # Converting to float histogram jetRecoPtDistribution_TH1F_100TeV = TH1F() jetRecoPtDistribution_TH1F_13TeV = TH1F() jetRecoPtDistribution_TH1F_13TeV_DelphesCMS = TH1F() jetRecoPtDistribution_TH1F_13TeV_DelphesFCC_CMSJets = TH1F() jetRecoPtDistribution_TH1F_100TeV_DelphesFCC_CMSJets = TH1F() jetRecoPtDistribution_TH1F_100TeV.Add(jetRecoPtDistribution_TH1I_100TeV)
parser.add_argument("input_file", nargs=1, metavar='FILE', type=lambda x: is_valid_file(parser, x)) parser.add_argument("-t", "--tree-name", dest='tree_name', default="MatchChi2Algo/match_chi2") arguments = parser.parse_args() from ROOT import TFile, TCanvas from ROOT import TTree, gDirectory input_file = TFile(arguments.input_file[0]) tree = input_file.Get(arguments.tree_name) if not tree: print 'Could not find tree %s in %s' % (arguments.tree_name, arguments.input_file[0]) sys.exit(-1) chi2_bkg = [] chi2_sig = [] for entry in tree: if entry.true_muon == 1 and entry.muon_overlap > 0.9: chi2_sig.append(entry.chi2DoF) else: chi2_bkg.append(entry.chi2DoF) chi2_bkg = sorted(chi2_bkg)
gROOT.SetBatch() input_files = args.input_files out_histo = None for filename in input_files: if not isfile(filename): logging.info("missing: " + filename) continue logging.debug(filename) tfile = TFile(filename) thisto = tfile.Get(args.histo_name) if not out_histo: out_histo = thisto.Clone() out_histo.Clone() out_histo.SetDirectory(0) else: out_histo.Add(thisto) tfile.Close() fout = TFile(args.output, "RECREATE") fout.Write() out_histo.Write()
line = "Integral of " + hist + " in " + inputFile.GetName( ) + " from " + str(xlo) + " to " + str(xhi) + ": " + str( integral) + " +- " + str(intError) # print line return integral outputFile = os.environ[ 'CMSSW_BASE'] + "/src/DisappTrks/StandardAnalysis/data/systematic_values__" + systematic_name + ".txt" if not makeRewtdPlot: fout = open(outputFile, "w") # get rewt histogram fileWithWtHist = TFile(str(ratioHistFile)) hwts = fileWithWtHist.Get(ratioHistName) print "Debug: using hwts hist=", ratioHistName, ", ratioHistFile=", ratioHistFile for sample in datasets: numEvents = getIntegral(sample, central_condor_dir, channel, "numEvents", 0, 10, 0) central_yield = getIntegral(sample, central_condor_dir, channel, histRewtName, histMin, histMax, 0) plus_yield = getIntegral(sample, central_condor_dir, channel, histRewtName, histMin, histMax, hwts) central_gen_yield = getIntegral(sample, central_gen_condor_dir, channelNoCuts, histRewtName, histMin, histMax, 0) plus_gen_yield = getIntegral(sample, central_gen_condor_dir, channelNoCuts, histRewtName, histMin, histMax, hwts)
def skim_c(name, newFileName): #-------------------------------- Jet_old_dict = {} for j in range(num_of_jets): #if 'ctauS' in name: Jet_old_dict[j + 1] = JetType() #if 'ctauS' in name: if NJT == 1: Jet_old_dict[j + 1] = JetTypeSgn() #-------------------------------- print 'filename:', name oldFile = TFile(name, "READ") oldTree = oldFile.Get("reconstruction/tree") #locate and register the Jet branches of the old ttree #oldTree.SetBranchAddress("Jet1", AddressOf(Jet1o, 'pt') ); for j in range(num_of_jets): if 'QCD' in name: oldTree.SetBranchAddress('Jet' + str(j + 1), AddressOf(Jet_old_dict[j + 1], 'pt')) elif 'ctauS' in name: oldTree.SetBranchAddress('MatchedJet' + str(j + 1), AddressOf(Jet_old_dict[j + 1], 'pt')) print 'skimming file', oldFile.GetName(), '\tevents =', oldTree.GetEntries( ), '\tweight =', oldTree.GetWeight() newFile = TFile('Skim/' + newFileName, "RECREATE") newFile.cd() newTree = TTree("tree44", "tree44") newTree.Branch( 'Jet1s', Jets1, 'pt/F:eta/F:chf/F:nhf/F:phf/F:elf/F:muf/F:chm/I:cm/I:nm/I:dR_q1/F:dR_q2/F:dR_q3/F:dR_q4/F' ) #newTree.Branch( 'Jet2s', Jets2, 'pt/F:eta/F:chf/F:nhf/F:phf/F:elf/F:muf/F:chm/I:cm/I:nm/I:dR_q1/F:dR_q2/F:dR_q3/F:dR_q4/F' ) # this attribute list must exactly match (the order of) the features in the header file!!!! ti = 80000 #theweight = oldTree.GetWeight() for i in range(0, oldTree.GetEntries()): # why -1? if i == 0: start = timer() elif i % ti == 2: start = timer() oldTree.GetEntry(i) # selections # Trigger """ if Jet1o.pt>15 \ and \ (Jet1o.eta>-2.4 or Jet1o.eta<2.4) \ and \ ( \ (Jet1o.dR_q1<0.4 and Jet1o.dR_q2>0.4 and Jet1o.dR_q3>0.4 and Jet1o.dR_q4>0.4) \ or \ (Jet1o.dR_q2<0.4 and Jet1o.dR_q1>0.4 and Jet1o.dR_q3>0.4 and Jet1o.dR_q4>0.4) \ or \ (Jet1o.dR_q3<0.4 and Jet1o.dR_q2>0.4 and Jet1o.dR_q1>0.4 and Jet1o.dR_q4>0.4) \ or \ (Jet1o.dR_q4<0.4 and Jet1o.dR_q2>0.4 and Jet1o.dR_q3>0.4 and Jet1o.dR_q1>0.4) \ ) \ : # set new leaf values to old ones # this attribute list must exactly match (the order of) the features in the header file!!!! Jets1.pt = Jet1o.pt Jets1.eta = Jet1o.eta Jets1.phi = Jet1o.phi Jets1.chf = Jet1o.chf Jets1.nhf = Jet1o.nhf Jets1.phf = Jet1o.phf Jets1.elf = Jet1o.elf Jets1.muf = Jet1o.muf Jets1.chm = Jet1o.chm Jets1.cm = Jet1o.cm Jets1.nm = Jet1o.nm Jets1.dR_q1 = Jet1o.dR_q1 Jets1.dR_q2 = Jet1o.dR_q2 Jets1.dR_q3 = Jet1o.dR_q3 Jets1.dR_q4 = Jet1o.dR_q4 newTree.Fill() """ for j in range(num_of_jets): if cut_on == 0: condition_str_dict[j + 1] = '1' if eval(condition_str_dict[j + 1]): Jets1.pt = Jet_old_dict[j + 1].pt Jets1.eta = Jet_old_dict[j + 1].eta Jets1.phi = Jet_old_dict[j + 1].phi Jets1.chf = Jet_old_dict[j + 1].chf Jets1.nhf = Jet_old_dict[j + 1].nhf Jets1.phf = Jet_old_dict[j + 1].phf Jets1.elf = Jet_old_dict[j + 1].elf Jets1.muf = Jet_old_dict[j + 1].muf Jets1.chm = Jet_old_dict[j + 1].chm Jets1.cm = Jet_old_dict[j + 1].cm Jets1.nm = Jet_old_dict[j + 1].nm Jets1.dR_q1 = Jet_old_dict[j + 1].dR_q1 Jets1.dR_q2 = Jet_old_dict[j + 1].dR_q2 Jets1.dR_q3 = Jet_old_dict[j + 1].dR_q3 Jets1.dR_q4 = Jet_old_dict[j + 1].dR_q4 newTree.Fill() ######################################################### if i % 2 == 0: ss = '.' elif i % 2 == 1: ss = 'o' if i % ti == 1 and i > ti: end = timer() dt = end - start tl = int(((oldTree.GetEntries() - i) / ti) * dt) if tl > 60: sys.stdout.write("\r" + 'time left: ' + str(tl / 60) + 'min' + ss) sys.stdout.flush() else: sys.stdout.write("\r" + 'time left: ' + str(tl / 60) + 's') sys.stdout.flush() ######################################################### print 'produced skimmed file', newFile.GetName( ), '\tevents =', newTree.GetEntries(), '\tweight =', newTree.GetWeight() newFile.cd() newFile.Write() newFile.Close() oldFile.Close()
def plot(path, pt_title, ecms, arrow_left, arrow_bottom, arrow_right, arrow_top, D_sample): try: f_incMC = TFile(path[0]) f_sigMC = TFile(path[1]) t_incMC = f_incMC.Get('save') t_sigMC = f_sigMC.Get('save') entries_incMC = t_incMC.GetEntries() entries_sigMC = t_sigMC.GetEntries() logging.info('inclusive MC entries :' + str(entries_incMC)) logging.info('D2(2460) MC entries :' + str(entries_sigMC)) except: logging.error('Files are invalid!') sys.exit() mbc = TCanvas('mbc', 'mbc', 800, 600) set_canvas_style(mbc) xbins = 100 M_D = 0. step = 0. if D_sample == 'Dplus': M_D = 1.86965 step = (1.89555 - M_D) / xbins if D_sample == 'D0': M_D = 1.86483 step = (1.95 - M_D) / xbins h_FOM, ientry, arrow_top = cal_significance(t_incMC, t_sigMC, xbins, step, ecms, M_D, D_sample) h_FOM.Draw() arrow_bottom = 0. arrow = TArrow(arrow_left, arrow_bottom, arrow_right, arrow_top, 0.01, '>') set_arrow(arrow) arrow.Draw() pt = TPaveText(0.6, 0.8, 0.85, 0.85, "BRNDC") set_pavetext(pt) pt.Draw() pt.AddText(pt_title) mass_low = 0. mass_up = 0. window = 0. if D_sample == 'Dplus' or D_sample == 'D0': mass_low = str(M_D - arrow_left) mass_up = str(M_D + arrow_left) window = str(2 * arrow_left) range = 'Mass window of rawm_D : [' + mass_low + ', ' + mass_up + '] GeV/c2' + ' with mass window width: ' + window + ' GeV/c2' print range if not os.path.exists('./txts/'): os.makedirs('./txts/') path_out = './txts/window_rawm_D_' + str(ecms) + '_' + D_sample + '.txt' f_out = open(path_out, 'w') f_out.write(range) f_out.close() if not os.path.exists('./figs/'): os.makedirs('./figs/') mbc.Update() mbc.SaveAs('./figs/opt_rawm_D_' + str(ecms) + '_' + D_sample + '.pdf') raw_input('Enter anything to end...')