def drawGraph(self, g): ''' output graph to file ''' title = g.GetTitle() name = g.GetName() pdf = self.figDir + name + '.pdf' xsize, ysize = 1100, 850 # landscape style noPopUp = True if noPopUp: gROOT.ProcessLine("gROOT->SetBatch()") canvas = TCanvas(pdf, title, xsize, ysize) g.Draw() canvas.Draw() canvas.SetGrid(1) canvas.SetTicks(1) canvas.cd() canvas.Modified() canvas.Update() canvas.Print(pdf, 'pdf') return
def getLBDataStruct(self): # # Define LBDATA tree # Time is in ms structStr = "struct LBDataStruct {\ ULong64_t fStartTime;\ ULong64_t fEndTime;\ UInt_t fRun;\ UInt_t fLB;\ UInt_t fStable;\ Float_t fAvgBeam1;\ Float_t fAvgBeam2;\ Float_t fPmtA;\ Float_t fPmtC;\ Float_t fFibA;\ Float_t fFibC;\ };" # Replace sizes if needed gROOT.ProcessLine(structStr) from ROOT import LBDataStruct return LBDataStruct()
def waitRootCmdX(defaultSaveName='test', saveDirectly=False, updateFirst=True, pad=gPad): if not pad: print("pad is None. Will do nothing.") else: if updateFirst: pad.Update() if saveDirectly: return savePad(defaultSaveName, pad) print('defaultSaveName:', defaultSaveName) ### code records if the figure is saved. code = 0 while True: x = input('root: ').rstrip() if x.lower() == 'e' or x.lower() == 'end' or x.lower( ) == 'q' or x.lower() == 'quit' or x.lower() == '.q': sys.exit() elif x == '' or x.lower() == 'n' or x.lower() == 'next': break args = x.split() if args[0] == 's' or args[0] == 'save': if pad is None: print("pad is None. Can not save!!!!") if len(args) < 2: args.append(defaultSaveName) savePad(args[1:], pad) code |= (1 << 1) continue elif args[0] == 'p' or args[0] == 'pass': return args[1:] try: print('root processing "' + x + '"') gROOT.ProcessLine(x) except: print('command not recognized') continue return code
def __init__(self, logfile=""): ## initialize DB self.db = datamon_db() self.BASE_ONLINEMON_DIR = "/work/halld/online_monitoring" self.PROCESSED_RUN_LIST_FILE = "processedrun.lst.online" self.ONLINE_ROOT_DIR = self.BASE_ONLINEMON_DIR + '/root' self.ONLINE_CONDITION_DIR = self.BASE_ONLINEMON_DIR + '/conditions' self.MIN_RUN_NUMBER = 30001 #self.MAX_RUN_NUMBER = 9000 self.MAX_RUN_NUMBER = 1000000 self.VERSION_NUMBER = 88 ## hardcode default - need to change this self.MONITORING_OUTPUT_DIR = "/work/halld2/data_monitoring" self.RUN_PERIOD = "RunPeriod-2017-01" self.MAKE_PLOTS = True self.MAKE_DB_SUMMARY = True #self.MAKE_PLOTS = False #self.MAKE_DB_SUMMARY = False #self.MAKE_RUN_CONDITIONS = False self.MAKE_RUN_CONDITIONS = True self.NEWDIR_MODE = "775" self.VERBOSE = 1 self.FORCE_PROCESSING = False # limit ROOT output gROOT.ProcessLine("gErrorIgnoreLevel = 2001;") # only output at least "Error" level messages # optionally log the output to a file # use separate log files for ROOT and all other output # append by default self.LOGFILE = logfile if self.LOGFILE is not "": logging.basicConfig(filename=self.LOGFILE) gSystem.RedirectOutput(self.LOGFILE)
def waitRootCmdMore(padlist, saveDirectly=False): if saveDirectly: for p, c in padlist.iteritems(): savePad(p, c) while True: x = raw_input('root: ') if x.lower() == 'e' or x.lower() == 'end' or x.lower( ) == 'q' or x.lower() == 'quit' or x.lower() == '.q': sys.exit() elif x == '' or x.lower() == 'n' or x.lower() == 'next': break args = x.split() if args[0] == 's' or args[0] == 'save': if len(args) < 2: for p, c in padlist.iteritems(): savePad(p, c) else: savePad(args[1:], gPad) continue try: gROOT.ProcessLine(x) except: print 'command not recognized' continue
def SavePlots(sum_hists, sum_dir, hists_to_plot, macros_to_run): global WEB_OUTPUT # plot individual histograms if(len(sum_hists) > 0): for (hnamepath,h) in sum_hists.items(): #if not match_hnamepaths(hists_to_plot, hnamepath): if (h.GetName() not in hists_to_plot) and (hnamepath not in hists_to_plot): continue if(isinstance(h,TH2)): plot_2dhist(h) else: plot_hist(h) # Output canvas #print_canvas_pdf() if(WEB_OUTPUT): print_canvas_png("_"+hnamepath) ## name hack for backward compatability # plot RootSpy macros if(len(macros_to_run) > 0): for macro_file in macros_to_run: if os.path.isfile(macro_file): if VERBOSE: print "running macro = " + macro_file # run the macro ClearPad(c1) sum_dir.cd() gROOT.ProcessLine(".x " + macro_file) # save the canvas - the name depends just on the file name img_fname = macro_file.split('/')[-1] #print "SPLIT = " + img_fname[0:-2] + " / " + img_fname[-2:] if img_fname[-2:] == ".C": img_fname = img_fname[0:-2] print_canvas_png(img_fname) else: print "could not find macro = " + macro_file + " !"
def __init__(self): # ROOT gROOT.LoadMacro("tdrstyle.C") gROOT.LoadMacro("../interface/HelperMath.h") gROOT.LoadMacro("../../AMSimulationIO/src/AMSimulationIOLinkDef.h") gROOT.ProcessLine("setTDRStyle()") gStyle.SetEndErrorSize(2) gStyle.SetPadRightMargin(0.05) gStyle.SetTitleOffset(1.1, "Y") gStyle.SetLabelSize(0.04, "Y") gStyle.SetLabelSize(0.04, "Z") gStyle.SetNdivisions(505, "XY") gStyle.SetPalette(55) # rainbow color map gStyle.SetNumberContours(100) gStyle.SetOptStat(111110) gStyle.SetStatX(0.94) gStyle.SetStatY(0.93) gStyle.SetStatH(0.30) gStyle.SetStatW(0.28) TH1.SetDefaultSumw2()
def setup_analysis(filename='analysis.root'): from ROOT import gROOT, TFile, AliAnalysisManager tfile = TFile.Open(str(filename), "RECREATE") mgr = AliAnalysisManager("mgr") gROOT.Macro("$ALICE_ROOT/ANALYSIS/macros/train/AddAODHandler.C") gROOT.Macro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C") gROOT.Macro( "$ALICE_PHYSICS/OADB/COMMON/MULTIPLICITY/macros/AddTaskMultSelection.C" ) gROOT.LoadMacro("$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/AddTaskFemto.C") macro_config_path = (Path(__file__).parent / "ConfigFemtoAnalysis.C").absolute() gROOT.ProcessLine(f'AddTaskFemto("{macro_config_path}")') # gROOT.LoadMacro("$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto/AddNuTaskPionPionRoot6.C") # gROOT.ProcessLine("""AddNuTaskPionPionRoot6( # "container1", # "", # "{30:40:50}; (0.2:0.3:0.4:0.5:0.6:0.7:0.8:1.0);" # "~do_kt_ylm_cf=true; ~do_kt_qinv_cf=true; ~do_kt_pqq3d_cf=true;" # "~do_sharequality_cf=true; ~do_avg_sep_cf=true; ~do_detadphistar_cf=true;" # "~q3d_bin_count=47; ~q3d_maxq = 0.141;" # "@enable_pair_monitors=false;" # "@num_events_to_mix=3;" # "$pion_1_min_tpc_chi_ndof=0.33; $pion_1_max_its_chi_ndof=1.8;" # "$pion_1_max_tpc_chi_ndof=1.8;" # )""") mgr.Write() tfile.Close()
def main(): gROOT.ProcessLine( "gErrorIgnoreLevel = kError;" ) # Surpress info messages below Error or Fatal levels (IE info or warning) args = input_arguments() if (args.freq == '160') or (args.freq == '160MHz'): freq = '160MHz' # Ensures consistent formatting elif (args.freq == '120') or (args.freq == '120MHz'): freq = '120MHz' # IE does the user enter '120', or '120MHz'? if (args.temp == '18') or (args.temp == '18deg'): temp = '18deg' # Resolve it either way elif (args.temp == '9') or (args.temp == '9deg'): temp = '9deg' # blahblah licht mehr licht if not args.directory.endswith('/'): args.directory += '/' # For consistency, makes sure '/directory/path/ends/with/' <-- a '/' name_base = "ECAL_H4_Oct2018_" + freq + "_" + temp + "_" # Get position and energy info on all files in the directory, and sort them into the mastertable (dict) for filei in os.listdir( args.directory): # Iterate over all files in the given directory if filei.endswith(".root"): # Only includes .root files print "Found file:", filei, "\t\t", tfile = TFile(args.directory + filei) infotree = tfile.Get("info") try: infotree.GetEntry(1) except AtributeError: print "file " + filei + "is missing info!" Energy = int(infotree.Energy) Position = str(infotree.Positions) print "Position: {0:9} \t Energy: {1}".format(Position, Energy) print
def __init__(self, year=2017, dozpt=True): """Load correction tool.""" assert year in [ 2016, 2017, 2018 ], "RecoilCorrectionTool: You must choose a year from: 2016, 2017, or 2018." if year == 2016: filename = rcpath + "TypeI-PFMet_Run2016BtoH.root" #"TypeI-PFMet_Run2016_legacy.root" elif year == 2017: filename = rcpath + "Type1_PFMET_2017.root" else: filename = rcpath + "TypeI-PFMet_Run2018.root" print "Loading RecoilCorrectionTool for %s..." % filename CMSSW_BASE = os.environ.get("CMSSW_BASE", None) recoil_h = "%s/src/HTT-utilities/RecoilCorrections/interface/RecoilCorrector.h" % ( CMSSW_BASE) assert CMSSW_BASE, "RecoilCorrectionTool: Did not find $CMSSW_BASE" assert os.path.isfile( recoil_h ), "RecoilCorrectionTool: Did not find RecoilCorrection header: %s" % recoil_h gROOT.ProcessLine('#include "%s"' % recoil_h) gSystem.Load("libHTT-utilitiesRecoilCorrections.so") corrector = ROOT.RecoilCorrector(filename) self.corrector = corrector self.filename = filename
def makeNameSpaceSingleFakes(self): # import sfr_hist f = TFile('modules/DDE_singlefake.root') sfr_hist = f.Get('ptCone_eta').GetPrimitive("pt_eta_T_012") #prepare a .h file to implement the fakerates into the ROOT namespace sfr_namespace_dir = "/home/dehuazhu/HNL/CMSSW_9_4_6_patch1/src/PlotFactory/DataBkgPlots/modules/DDE_singlefake.h" with open(sfr_namespace_dir, "w") as sfr_namespace: sfr_namespace.write("// This namespace prepares the singlefakerate measured via DDE.py to be implementable in dataframe for the main plotting tool.\n") sfr_namespace.write("namespace sfr_namespace {\n") sfr_namespace.write("\tdouble getSingleFakeRate(double ptCone, double eta){\n") for xbin_i in np.arange(sfr_hist.GetNbinsX()): for ybin_i in np.arange(sfr_hist.GetNbinsY()): xbin_low = sfr_hist.GetXaxis().GetXbins()[xbin_i] xbin_up = sfr_hist.GetXaxis().GetXbins()[xbin_i+1] ybin_low = sfr_hist.GetYaxis().GetXbins()[ybin_i] ybin_up = sfr_hist.GetYaxis().GetXbins()[ybin_i+1] result = sfr_hist.GetBinContent(xbin_i+1, ybin_i+1) sfr_namespace.write("\t\tif (ptCone >= %f && ptCone < %f && eta >= %f && eta < %f) return %f;\n"%(xbin_low,xbin_up,ybin_low,ybin_up,result)) sfr_namespace.write("\t\treturn 0.;\n") sfr_namespace.write("\t}\n") sfr_namespace.write("}\n") print ('FakeRateNamespace saved in "%s"'%(sfr_namespace_dir)) gROOT.ProcessLine(".L modules/DDE_singlefake.h+")
def initBunchData(self): # # Define BUNCHDATA tree gROOT.ProcessLine("struct BunchDataStruct {\ UInt_t fValidBPTX;\ Float_t fB1BunchAverageBPTX;\ Float_t fB2BunchAverageBPTX;\ Int_t fB1BunchesBPTX;\ Int_t fB2BunchesBPTX;\ Float_t fB1BunchIntensitiesBPTX[3564];\ Int_t fB1BCIDsBPTX[3564];\ Float_t fB2BunchIntensitiesBPTX[3564];\ Int_t fB2BCIDsBPTX[3564];\ UInt_t fValidBCT;\ Float_t fB1BunchAverageBCT;\ Float_t fB2BunchAverageBCT;\ Int_t fB1BunchesBCT;\ Int_t fB2BunchesBCT;\ Int_t fB1BCIDsBCT[3564];\ Float_t fB1BunchIntensitiesBCT[3564];\ Int_t fB2BCIDsBCT[3564];\ Float_t fB2BunchIntensitiesBCT[3564];\ };") from ROOT import BunchDataStruct self.bunchDataStruct = BunchDataStruct() # Not sure why this is necessary self.bunchDataStruct.fB1BunchesBPTX = 0 self.bunchDataStruct.fB2BunchesBPTX = 0 self.bunchDataStruct.fB1BunchesBCT = 0 self.bunchDataStruct.fB2BunchesBCT = 0 self.tree.Branch( 'BCT_BUNCHDATA', AddressOf(self.bunchDataStruct, 'fValidBCT'), 'BCT_Valid/i:BCT_B1BunchAverage/F:BCT_B2BunchAverage/F:BCT_B1Bunches/I:BCT_B2Bunches/I' ) self.tree.Branch('BCT_B1BCID', AddressOf(self.bunchDataStruct, 'fB1BCIDsBCT'), 'BCT_B1BCID[BCT_B1Bunches]/I') self.tree.Branch('BCT_B2BCID', AddressOf(self.bunchDataStruct, 'fB2BCIDsBCT'), 'BCT_B2BCID[BCT_B2Bunches]/I') self.tree.Branch( 'BCT_B1BunchIntensity', AddressOf(self.bunchDataStruct, 'fB1BunchIntensitiesBCT'), 'BCT_B1BunchIntensity[BCT_B1Bunches]/F') self.tree.Branch( 'BCT_B2BunchIntensity', AddressOf(self.bunchDataStruct, 'fB2BunchIntensitiesBCT'), 'BCT_B2BunchIntensity[BCT_B2Bunches]/F') self.tree.Branch( 'BPTX_BUNCHDATA', AddressOf(self.bunchDataStruct, 'fValidBPTX'), 'BPTX_Valid/i:BPTX_B1BunchAverage/F:BPTX_B2BunchAverage/F:BPTX_B1Bunches/I:BPTX_B2Bunches/I' ) self.tree.Branch('BPTX_B1BCID', AddressOf(self.bunchDataStruct, 'fB1BCIDsBPTX'), 'BPTX_B1BCID[BPTX_B1Bunches]/I') self.tree.Branch('BPTX_B2BCID', AddressOf(self.bunchDataStruct, 'fB2BCIDsBPTX'), 'BPTX_B2BCID[BPTX_B2Bunches]/I') self.tree.Branch( 'BPTX_B1BunchIntensity', AddressOf(self.bunchDataStruct, 'fB1BunchIntensitiesBPTX'), 'BPTX_B1BunchIntensity[BPTX_B1Bunches]/F') self.tree.Branch( 'BPTX_B2BunchIntensity', AddressOf(self.bunchDataStruct, 'fB2BunchIntensitiesBPTX'), 'BPTX_B2BunchIntensity[BPTX_B2Bunches]/F')
def plotter(plotdir, plot, xTitle, logY, channels=['VV'], includeData=False, scaleSignal=0, UserRange=[None, None, None, None], initPath=''): # channelTex={'WPWP':'W^{+}W^{+}', 'WPWM':'W^{+}W^{-}','WMWM':'W^{-}W^{-}','WPZ':'W^{+}Z','WMZ':'W^{-}Z','ZZ':'ZZ'} channelTex = {'ZZ': 'ZZ'} # plotstyle=[(1,1),(1,2),(2,1),(2,2),(4,1),(4,2)] plotstyle = [(1, 1)] # 0 1 2 3 4 5 6 # Backgrounds=['QCD', 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'TT', 'WW', 'WZ', 'ZZ'] # BGColors= [rt.kAzure+7, rt.kRed-4, rt.kOrange-2, rt.kGreen+2, rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] # BGTeX= ['QCD', 'W+JetsToQQ', 'Z+JetsToQQ', 'TTbar'], 'WW', 'WZ', 'ZZ'] #stackOrder= [4,5,6,2,1,3,0] Backgrounds = [ 'QCD' ] # 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'ZZ'] 'TT', 'WW', 'WZ', 'ZZ'] BGColors = [ rt.kAzure + 7 ] #, rt.kOrange-2, rt.kGreen+2], rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] BGTeX = ['QCD'] # stackOrder = [0] PreSelection = [ 'nocuts', 'common', 'corrections', 'cleaner', 'softdropmassCorr', 'AK4pfidfilter', 'AK8pfidfilter', 'invMAk8sel', 'detaAk8sel', 'AK8N2sel' ] Selection = [ 'preselection', 'softdropAK8sel', 'tau21sel', 'deltaR48', 'VVRegion', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0', 'Kin_AK8' ] cutnames = [ 'cleaner', 'AK8N2sel', 'invMAk8sel', 'detaAk8sel', 'softdropAK8sel', 'tau21sel', 'AK4cleaner', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0' ] cuts = { 'cleaner': '#splitline{p_{T-AK8} > 200 GeV, |#eta_{AK8}| < 2.5}{p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0}', 'AK8N2sel': 'N_{AK8} #geq 2', 'invMAk8sel': 'M_{jj-AK8} > 1050 GeV', 'detaAk8sel': '|#Delta#eta_{jj-AK8}|<1.3', 'softdropAK8sel': '65 GeV <M_{SD}< 105 GeV', 'tau21sel': '0 #leq #tau_{2}/#tau_{1}<0.45', # 'AK4cleaner':'p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0', 'AK4cleaner': '', 'AK4N2sel': 'N_{AK4} #geq 2', 'OpSignsel': '#eta_{1-AK4} #eta_{2-AK4} < 0', 'detaAk4sel': '|#Delta#eta_{jj-AK4}| > 3.0', 'invMAk4sel_1p0': 'M_{jj-AK4} > 1.0 TeV' } VV = ('VV' in channels) seperate = (not VV) if VV: #channels=["WPWP","WPWM","WMWM","WPZ","WMZ","ZZ"] channels = ["ZZ"] plottitle = plotdir + '_' + plot lumi = 36.814 xLabelSize = 18. yLabelSize = 18. xTitleSize = 20. yTitleSize = 22. xTitleOffset = 4. yTitleOffset = 1.3 printout = False Portrait = True cutname = False ratio = includeData if ('highbin' in plot): binning = 'dijetbinning' else: binning = 'default' if (Portrait): canvX = 600 canvY = 600 else: canvX = 900 canvY = 675 if (plotdir in PreSelection): region = 'PreSelection' initPath = '' referenceHistPath = 'detaAk8sel/N_pv' if (PreSelection.index(plotdir) < 4 and ('softdrop' in plot)): return 'SofdropMass not filled yet!' else: region = 'SignalRegion' referenceHistPath = 'tau21sel/N_pv' referenceHistPath = plotdir + '/' + plot if (initPath == ''): path = '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/%s' % region else: path = initPath outputPath = path.replace( '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/SignalRegion', 'plots/') if (plotdir in PreSelection): CutNumber = PreSelection.index(plotdir) else: CutNumber = Selection.index(plotdir) outputPath = outputPath + '/%02i_%s' % (CutNumber, plotdir) + '/' if (printout): print('InputPath:', path) print('OutputPath:', outputPath) #check if OutputPath exists - and if not create it! if not os.path.exists(outputPath): os.makedirs(outputPath) # path='/home/albrec/Master/signal/' scaleVV = (scaleSignal != 0) VVScale = scaleSignal if (UserRange[2] == None or UserRange[3] == None): YRangeUser = False Ymin = UserRange[2] Ymax = UserRange[3] else: YRangeUser = True Ymin = UserRange[2] Ymax = UserRange[3] if (UserRange[0] == None or UserRange[1] == None): XRangeUser = False Xmin = UserRange[0] Xmax = UserRange[1] else: XRangeUser = True Xmin = UserRange[0] Xmax = UserRange[1] # YRangeUser=False # Ymin=0.11 # Ymax=9*10**3 # XRangeUser=False # Xmin=0 # Xmax=6000. gROOT.ProcessLine("gErrorIgnoreLevel = 2001;") SFiles = [] for i in range(len(channels)): SFiles.append( TFile( path + "/uhh2.AnalysisModuleRunner.MC.MC_aQGC_%sjj_hadronic_2016v3.root" % channels[i])) #uhh2.AnalysisModuleRunner.MC.MC_aQGC_ZZjj_hadronic_2016v3.root ##Open Files to get BackgroundHist: BFiles = [] for i in range(len(Backgrounds)): BFiles.append( TFile(path + "/uhh2.AnalysisModuleRunner.MC.MC_%s.root" % Backgrounds[i])) #Open File to get DataHist: # DataFile = TFile(path+"/uhh2.AnalysisModuleRunner.Data.DATA.root") #gROOT.ProcessLine( "gErrorIgnoreLevel = 0;") if (includeData == True): #calculate QCDscale with Integrals from the following Histogram: # referenceHistPath = 'tau21sel/N_AK4' # referenceHistPath = 'detaAk8sel/N_pv' # referenceHistPath = 'tau21sel/met_pt_over_sumptAK8_2' QCDscale = float(DataFile.Get(referenceHistPath).Integral()) QCDNorm = 1 for i in range(len(BFiles)): if ('QCD' in BFiles[i].GetName()): QCDNorm = float(BFiles[i].Get(referenceHistPath).Integral()) else: QCDscale -= float(BFiles[i].Get(referenceHistPath).Integral()) QCDscale /= QCDNorm else: QCDscale = 1.0 if (printout): print('using QCDscale:', QCDscale) SHists = [] for i in range(len(channels)): SHists.append(SFiles[i].Get(plotdir + '/' + plot)) BHists = [] for i in range(len(BFiles)): BHists.append(BFiles[i].Get(plotdir + '/' + plot)) if ('QCD' in BFiles[i].GetName()): BHists[-1].Scale(QCDscale) #if(includeData): # DataHist=DataFile.Get(plotdir+'/'+plot) if (binning == 'dijetbinning'): fitbinning = array('d') binwidth = 200 NBins = (14000 / binwidth) - ((1040 / binwidth) + 1) NBins = int(NBins) for i in range(NBins + 1): fitbinning.append(1050 + i * binwidth) for i in range(len(channels)): SHists[i] = SHists[i].Rebin(NBins, "new binning", fitbinning) for i in range(len(Backgrounds)): BHists[i] = BHists[i].Rebin(NBins, "new binning", fitbinning) if (includeData): DataHist = DataHist.Rebin(NBins, "new binning", fitbinning) canv = TCanvas(plottitle, plottitle, canvX, canvY) yplot = 0.7 yratio = 0.3 ymax = 1.0 xmax = 1.0 xmin = 0.0 if (ratio): plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot, xmax, ymax) ratiopad = TPad("ratiopad", "Ratio", xmin, ymax - yplot - yratio, xmax, ymax - yplot) else: plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot - yratio, xmax, ymax) plotpad.SetTopMargin(0.08) plotpad.SetLeftMargin(0.1) plotpad.SetRightMargin(0.05) plotpad.SetTicks() plotpad.Draw() if (ratio): plotpad.SetBottomMargin(0.016) ratiopad.SetTopMargin(0.016) ratiopad.SetBottomMargin(0.35) ratiopad.SetLeftMargin(0.1) ratiopad.SetRightMargin(0.05) ratiopad.SetTicks() ratiopad.Draw() else: plotpad.SetBottomMargin(0.1) if (logY): plotpad.SetLogy() canv.SetLogy() if ('-logX' in xTitle): plotpad.SetLogx() if (ratio): ratiopad.SetLogx() canv.SetLogx() drawOptions = "HE" stack = THStack(plottitle, plottitle) BHist = THStack(plottitle, plottitle) # for i in range(len(Backgrounds)): for i in stackOrder: # BHists[i].SetFillColor(BGColors[i]) BHists[i].SetLineColor(BGColors[i]) BHist.Add(BHists[i], 'Hist') BHist.SetTitle(plottitle) BHistErr = BHists[0].Clone() for i in range(1, len(Backgrounds)): BHistErr.Add(BHists[i]) BHistErr.SetFillStyle(3204) BHistErr.SetFillColor(rt.kGray + 2) BHistErr.SetLineColor(1) BGMax = BHist.GetMaximum() SIGMax = 0 #if(VV): #new # SIGMax=VVsum.GetMaximum() #else: for i in range(len(channels)): tmpmax = SHists[i].GetMaximum() if (tmpmax > SIGMax): SIGMax = tmpmax if (scaleVV): SIGMax = SIGMax * VVScale if (logY): MAX = 0.9 * float(10**(magnitude(max(BGMax, SIGMax)) + 1)) MIN = float(10**(magnitude(max(BGMax, SIGMax)) - 5)) MIN += float(10**(magnitude(MIN))) legendMIN = math.log(max(BGMax, SIGMax)) / math.log(MAX) else: MAX = (1.0 / 0.8) * max(BGMax, SIGMax) legendMIN = 0.7 MIN = 0. legendMIN = (legendMIN * 0.7) + 0.3 - 0.016 legend = TLegend(0.5, 0.75, 0.85, 0.89) legend.SetFillStyle(0) legend.SetTextSize(0.02) legend.SetMargin(0.4) legend.SetNColumns(2) legend.SetColumnSeparation(0.3) if (includeData): DataHist.SetMarkerStyle(8) DataHist.SetLineColor(1) DataHist.SetTitle(plottitle) if VV: for i in range(len(channels)): if (i == 0): VVsum = SHists[i].Clone() else: VVsum.Add(SHists[i]) legentry = 'VVjj' if (scaleVV): VVsum.Scale(VVScale) legentry += ' *%0.f' % VVScale VVsum.SetLineColor(1) VVsum.SetLineStyle(plotstyle[0][1]) VVsum.SetLineWidth(2) legend.AddEntry(VVsum, legentry) else: for i in range(len(channels)): SHists[i].SetLineColor(plotstyle[i][0]) SHists[i].SetLineStyle(plotstyle[i][1]) SHists[i].SetLineWidth(2) legentry = "%sjj" % channelTex[channels[i]] if (scaleVV): SHists[i].Scale(VVScale) legentry += ' *%.2E' % VVScale legend.AddEntry(SHists[i], legentry) for i in stackOrder: legend.AddEntry(BHists[i], BGTeX[i], "f") legend.AddEntry(BHistErr, "stat. Uncertainty", "f") if (includeData): legend.AddEntry(DataHist, "Data", "lep") canv.SetTitle(plottitle) BHistErr.GetYaxis().SetTitle('Events') BHistErr.GetYaxis().SetRangeUser(MIN, MAX) BHistErr.GetYaxis().SetTitleFont(43) BHistErr.GetYaxis().SetTitleSize(yTitleSize) BHistErr.GetYaxis().SetTitleOffset(yTitleOffset) BHistErr.GetYaxis().SetLabelFont(43) BHistErr.GetYaxis().SetLabelSize(yLabelSize) if (ratio): BHistErr.GetXaxis().SetTitleSize(0.0) BHistErr.GetXaxis().SetLabelSize(0.0) else: BHistErr.GetXaxis().SetTitle(xTitle) BHistErr.GetXaxis().SetTitleFont(43) BHistErr.GetXaxis().SetTitleSize(xTitleSize) # BHistErr.GetXaxis().SetTitleOffset(xTitleOffset) BHistErr.GetXaxis().SetTitleOffset(1.2) BHistErr.GetXaxis().SetLabelFont(43) BHistErr.GetXaxis().SetLabelSize(xLabelSize) # BHistErr.GetXaxis().SetTickLength(0.08) # BHistErr.GetXaxis().SetNdivisions(506) if (YRangeUser): BHistErr.GetYaxis().SetRangeUser(Ymin, Ymax) if (XRangeUser): BHistErr.GetXaxis().SetRangeUser(Xmin, Xmax) plotpad.cd() BHistErr.Draw("E2") BHist.Draw("HistSAME") BHistErr.Draw("E2SAME") if (VV): VVsum.Draw("SAME" + drawOptions) elif ('-noSig' not in xTitle): for i in range(len(channels)): SHists[i].Draw("SAME" + drawOptions) if (includeData): DataHist.Draw("APE1SAME") plotpad.RedrawAxis() if (ratio): ratiopad.cd() if (includeData): ratioHist = DataHist.Clone() else: ratioHist = BHistErr.Clone() ratioHist.SetLineColor(rt.kBlack) # ratioHist.Sumw2() ratioHist.SetStats(0) ratioHist.Divide(BHistErr) ratioHist.SetMarkerStyle(21) ratioHist.SetMarkerSize(0.7) #Yaxis ratioHist.GetYaxis().SetRangeUser(0.3, 1.7) ratioHist.GetYaxis().SetTitle("Data/BG") ratioHist.GetYaxis().CenterTitle() ratioHist.GetYaxis().SetTitleFont(43) ratioHist.GetYaxis().SetTitleSize(yTitleSize) ratioHist.GetYaxis().SetTitleOffset(yTitleOffset) ratioHist.GetYaxis().SetLabelFont(43) ratioHist.GetYaxis().SetLabelSize(yLabelSize) ratioHist.GetYaxis().SetNdivisions(506) #Xaxis ratioHist.GetXaxis().SetTitle(xTitle) ratioHist.GetXaxis().SetTitleFont(43) ratioHist.GetXaxis().SetTitleSize(xTitleSize) ratioHist.GetXaxis().SetTitleOffset(xTitleOffset) ratioHist.GetXaxis().SetLabelFont(43) ratioHist.GetXaxis().SetLabelSize(xLabelSize) ratioHist.GetXaxis().SetTickLength(0.08) ratioHist.GetXaxis().SetNdivisions(506) # if(YRangeUser): # ratioHist.GetYaxis().SetRangeUser(Ymin,Ymax) if (XRangeUser): ratioHist.GetXaxis().SetRangeUser(Xmin, Xmax) ratioXMin = Xmin ratioXMax = Xmax else: ratioXMin = ratioHist.GetXaxis().GetXmin() ratioXMax = ratioHist.GetXaxis().GetXmax() ratioHist.Draw("ep") zeropercent = TLine(ratioXMin, 1, ratioXMax, 1) zeropercent.Draw() plus10percent = TLine(ratioXMin, 1.1, ratioXMax, 1.1) plus10percent.SetLineStyle(rt.kDashed) plus10percent.Draw() minus10percent = TLine(ratioXMin, 0.9, ratioXMax, 0.9) minus10percent.SetLineStyle(rt.kDashed) minus10percent.Draw() canv.cd() gPad.RedrawAxis() legend.Draw() latex = TLatex() latex.SetNDC(kTRUE) latex.SetTextSize(20) latex.DrawLatex(0.69, 0.953, "%.2f fb^{-1} (13 TeV)" % lumi) latex.DrawLatex(0.1, 0.953, "private work") lastcut = 'nocuts' for cut in cutnames: if cut in plotdir: lastcut = cut if (not (lastcut == 'nocuts') and cutname): # latex.SetTextSize(0.03) latex.SetTextSize(15) for l in range(cutnames.index(lastcut) + 1): latex.DrawLatex(0.12, 0.8 - l * 0.04, cuts[cutnames[l]]) canv.Update() canv.Print(outputPath + '/%s_%s.pdf' % (plotdir, plot)) #prevents memory leak in Canvas Creation/Deletion #see: https://root.cern.ch/root/roottalk/roottalk04/2484.html gSystem.ProcessEvents() if (ratio): del ratiopad del plotpad, canv # gc.collect() return 'done!'
def saveToFile(correctionFactors, analysisType, bjetbin): stringForFile = '' fileName = fileTemplate % (analysisType, bjetbin) stringForFile += str(correctionFactors) + '\n' import json stringForFile = json.dumps(correctionFactors, sort_keys=True, indent=4) outputFile = open(fileName, 'w') outputFile.write(stringForFile) outputFile.close() if __name__ == "__main__": from optparse import OptionParser gROOT.SetBatch(True) gROOT.ProcessLine('gErrorIgnoreLevel = 1001;') parser = OptionParser() parser.add_option("-b", "--bjetbin", dest="bjetbin", default='2m', help="set b-jet multiplicity for analysis. Options: exclusive: 0-3, inclusive (N or more): 0m, 1m, 2m, 3m, 4m") parser.add_option("-a", "--analysisType", dest="analysisType", default='EPlusJets', help="set analysis type: EPlusJets or MuPlusJets") parser.add_option("-t", "--test", action="store_true", dest="test", default=False, help="Run test") translateOptions = { '0':'0btag', '1':'1btag', '2':'2btags', '3':'3btags',
def main(): ##Both conservative and not conservative will give same efficiency shapes for SM get_tot_eff() #get_tot_eff_alternate_model(scenario, model_indx, conservative) if __name__ == '__main__': scenario = sys.argv[1] model_indx = sys.argv[2] variation_range = sys.argv[3] conservative = None if variation_range == 'large': conservative = True elif variation_range == 'one_sigma': conservative = False else: raise Exception( "The value of variation_range not recognised, only 'large' or 'one_sigma' allowed!" ) print(scenario, model_indx, variation_range, conservative) scenarios = ['CVR', 'CSR', 'CSL', 'CT', 'SM'] if scenario not in scenarios: raise Exception('Scenario not in Scenarios') gROOT.ProcessLine(".x lhcbStyle2D.C") gStyle.SetPaintTextFormat("1.3f") main()
def write_root(self, path): gROOT.ProcessLine('struct TreeStruct {\ int runNo;\ int layer;\ int gemroc;\ int tiger;\ int channel;\ int tac;\ float tcoarse;\ float tcoarse_10b;\ float ecoarse;\ float tfine;\ float efine;\ float charge_SH;\ int count;\ int count_ori;\ int count_new;\ int timestamp;\ int l1ts_min_tcoarse;\ int lasttigerframenum;\ int local_l1_count;\ int count_mismatch;\ float delta_coarse;\ int count_missing_trailer;\ int subRunNo;\ int l1_framenum;\ int trailer_tiger;\ };') from ROOT import TreeStruct rname = path.replace(".dat", ".root") # subRunNo = int(path.split("_")[7]) subRunNo = self.SUBRUN # run = int(path.split("_")[6].split("/")[0]) # print run rootFile = ROOT.TFile(rname, 'recreate') tree = ROOT.TTree('tree', '') mystruct = TreeStruct() for key in TreeStruct.__dict__.keys(): if '__' not in key: formstring = '/F' if isinstance(mystruct.__getattribute__(key), int): formstring = '/I' tree.Branch(key, AddressOf(mystruct, key), key + formstring) statinfo = os.stat(path) packet_header = -1 packet_tailer = -1 packet_udp = -1 l1count = -1 l1count_new = [] lschannel = [] lstac = [] lstcoarse = [] lstcoarse_10b = [] lsecoarse = [] lstfine = [] lsefine = [] lscharge_SH = [] lstigerid = [] lsl1ts_min_tcoarse = [] lslasttigerframenum = [] lscount_mismatch = [] lsdelta_coarse = [] l1timestamp = -1 gemroc = -1 l1framenum = -1 trailer_tiger = -1 pre_timestamp = 0 pre_pretimestamp = 0 tiger_framenum = -1 prev_tiger_framenum = -1 prev2_tiger_framenum = -1 prev3_tiger_framenum = -1 count_missing_trailer = 0 hitcounter = 0 max_hitcount = 1000000000 flag_swap1 = False flag_swap2 = False firstPacket = True firstData = False print_debug = False with open(path, 'rb') as f: for i in range(0, statinfo.st_size // 8): data = f.read(8) # hexdata = binascii.hexlify(data) if sys.version_info[0] == 2: hexdata = str(binascii.hexlify(data)) else: hexdata = str(binascii.hexlify(data), 'ascii') string = "{:064b}".format(int(hexdata, 16)) inverted = [] for i in range(8, 0, -1): inverted.append(string[(i - 1) * 8:i * 8]) string_inv = "".join(inverted) int_x = int(string_inv, 2) # for x in range(0, len(hexdata) - 1, 16): # int_x = 0 # for b in range(7, 0, -1): # hex_to_int = (int(str(hexdata[x + b * 2]), 16)) * 16 + int(str(hexdata[x + b * 2 + 1]), 16) # int_x = (int_x + hex_to_int) << 8 # # hex_to_int = (int(str(hexdata[x]), 16)) * 16 + int(str(hexdata[x + 1]), 16) # acr 2017-11-17 this should fix the problem # int_x = (int_x + hex_to_int) ############################################################################################## ## ## ## TRIGGER-LESS DECODE ## ## ## ############################################################################################## if (((int_x & 0xFF00000000000000) >> 59) == 0x00 and self.MODE == 0): mystruct.runNo = self.RUN mystruct.gemroc = self.GEMROC_ID mystruct.tiger = (int_x >> 56) & 0x7 mystruct.channel = (int_x >> 48) & 0x3F mystruct.tac = (int_x >> 46) & 0x3 mystruct.tcoarse = (int_x >> 30) & 0xFFFF mystruct.ecoarse = (int_x >> 20) & 0x3FF mystruct.tfine = (int_x >> 10) & 0x3FF mystruct.efine = int_x & 0x3FF mystruct.tcoarse_10b = (int_x >> 30) & 0x3FF if (((int_x >> 20) & 0x3FF) - ((int_x >> 30) & 0x3FF)) > 0: mystruct.delta_coarse = (((int_x >> 20) & 0x3FF) - ((int_x >> 30) & 0x3FF)) else: mystruct.delta_coarse = (((int_x >> 20) & 0x3FF) - ( (int_x >> 30) & 0x3FF)) + 1024 temp_ecoarse = mystruct.ecoarse mystruct.charge_SH = int_x & 0x3FF if (self.GEMROC_ID < 4): mystruct.layer = 1 elif (self.GEMROC_ID > 3): mystruct.layer = 2 if (self.GEMROC_ID > 11): mystruct.layer = 0 tree.Fill() ############################################################################################## ############################################################################################## ############################################################################################## ############################################################################################## ############################################################################################## ## ## ## TRIGGER-MATCH DECODE ## ## ## ############################################################################################## if (self.MODE == 1): if (((int_x & 0xE000000000000000) >> 61) == 0x6): # print "enter header" packet_header = 1 LOCAL_L1_COUNT_31_6 = int_x >> 32 & 0x3FFFFFF LOCAL_L1_COUNT_5_0 = int_x >> 24 & 0x3F LOCAL_L1_COUNT = ( LOCAL_L1_COUNT_31_6 << 6) + LOCAL_L1_COUNT_5_0 LOCAL_L1_TIMESTAMP = int_x & 0xFFFF # print("local l1 count {}".format(LOCAL_L1_COUNT)) pre_pretimestamp = pre_timestamp pre_timestamp = l1timestamp # pre_l1count = l1count l1count = LOCAL_L1_COUNT l1timestamp = LOCAL_L1_TIMESTAMP if firstData: if print_debug: print( "WARNING: not able to record last tiger frame number of previous packet: no hits from TIGER 0-3 (L1_count={})!!!!!!!!!!!!!!!" .format(LOCAL_L1_COUNT)) firstData = True ## Header flags that next line will be first data word of the packet if len(lschannel) > 0: lschannel = [] lstac = [] lstcoarse = [] lsecoarse = [] lstfine = [] lsefine = [] lstcoarse_10b = [] lscharge_SH = [] lstigerid = [] lsl1ts_min_tcoarse = [] lslasttigerframenum = [] lscount_mismatch = [] l1count_new = [] lsdelta_coarse = [] if (((int_x & 0xC000000000000000) >> 62) == 0x0 and packet_header == 1 and packet_udp != 1): ## DATA word LOCAL_L1_TS_minus_TIGER_COARSE_TS = LOCAL_L1_TIMESTAMP - ( (int_x >> 32) & 0xFFFF) # print "enter DATA" lstigerid.append((int_x >> 59) & 0x7) lschannel.append((int_x >> 50) & 0x3F) lstac.append((int_x >> 48) & 0x3) lsecoarse.append((int_x >> 20) & 0x3FF) lstfine.append((int_x >> 10) & 0x3FF) lsefine.append(int_x & 0x3FF) lslasttigerframenum.append((int_x >> 56) & 0x7) lscharge_SH.append(int_x & 0x3FF) temp_ecoarse = (int_x >> 20) & 0x3FF lstcoarse_10b.append(((int_x >> 32) & 0x3FF)) temp_tcoarse = ((int_x >> 32) & 0x3FF) tcoarse = (int_x >> 32) & 0xFFFF ecoarse = (int_x >> 20) & 0x3FF if (((int_x >> 20) & 0x3FF) - ((int_x >> 32) & 0x3FF)) > 0: lsdelta_coarse.append(((int_x >> 20) & 0x3FF) - ((int_x >> 32) & 0x3FF)) else: lsdelta_coarse.append(((int_x >> 20) & 0x3FF) - ((int_x >> 32) & 0x3FF) + 1024) lstcoarse.append(tcoarse) count_mismatch = 0 lsl1ts_min_tcoarse_to_append = LOCAL_L1_TIMESTAMP - tcoarse l1count_new_to_append = l1count if int_x == 0: print( "WARNING: DATA with all zeros (subRun = {}, L1_count = {})" .format(subRunNo, LOCAL_L1_COUNT)) else: tiger_framenum = (int_x >> 56) & 0x7 if firstData: prev3_tiger_framenum = prev2_tiger_framenum prev2_tiger_framenum = prev_tiger_framenum if ( int_x >> 59 ) & 0x7 < 4: ## store 2 previous tiger frame number (only from TIGER 0-3) prev_tiger_framenum = tiger_framenum else: if print_debug: print( "WARNING: not able to record last tiger frame number of this packet: no hits from TIGER 0-3 (L1_count={})!!!!!!!!!!!!!!!" .format(LOCAL_L1_COUNT)) firstData = False ######################################## ## PACKETS MATCHING ## ######################################## ## Start from alignment of previous packet if ((int_x >> 59) & 0x7 > 3): if flag_swap1: temp_diff = pre_timestamp - tcoarse elif flag_swap2: temp_diff = pre_pretimestamp - tcoarse else: temp_diff = LOCAL_L1_TIMESTAMP - tcoarse else: temp_diff = lsl1ts_min_tcoarse_to_append ## TIGER 0-3 always take the current l1ts ## Find correct packet ## performed only when lsl1ts_min_tcoarse is not inside the trigger window (roll-over taken into account) if (not ( (temp_diff > 1299 and temp_diff < 1567) or (temp_diff < -63960 and temp_diff > -64240))): if firstPacket: ## avoid packets correction for first packet pass ## wrong entries in first packet should be discarded since they cannot be corrected else: # print("Try SWAP 0") ## try swap packets by 0 temp_diff = LOCAL_L1_TIMESTAMP - tcoarse if ((temp_diff > 1299 and temp_diff < 1567) or (temp_diff < -63960 and temp_diff > -64240)): if flag_swap1 == True or flag_swap2 == True: print( "SWAP 0 activated (L1_count={})" .format(LOCAL_L1_COUNT)) flag_swap1 = False flag_swap2 = False else: # print("Try SWAP 1") ## try swap packets by 1 temp_diff = pre_timestamp - tcoarse if ((temp_diff > 1299 and temp_diff < 1567) or (temp_diff < -63960 and temp_diff > -64240)): if flag_swap1 == False: print( "SWAP 1 activated (L1_count={})" .format(LOCAL_L1_COUNT)) flag_swap1 = True flag_swap2 = False else: # print("Try SWAP 2") ## try swap packets by 2 temp_diff = pre_pretimestamp - tcoarse if ((temp_diff > 1299 and temp_diff < 1567) or (temp_diff < -63960 and temp_diff > -64240)): if flag_swap2 == False: print( "SWAP 2 activated (L1_count={})" .format( LOCAL_L1_COUNT)) flag_swap1 = False flag_swap2 = True else: if self.warning_print_MAX != 0: print( "WARNING: not able to correct packet (L1_count={}) !!!!!!!!!!!!!!!" .format( LOCAL_L1_COUNT)) self.warning_print_MAX = self.warning_print_MAX - 1 ## Apply packet correction to data of TIGER 4-7 if ((int_x >> 59) & 0x7 > 3 ): ## correct packet for data of TIGER 4-7 if not (flag_swap1 or flag_swap2): ## apply SWAP by 0 packet lsl1ts_min_tcoarse_to_append = LOCAL_L1_TIMESTAMP - tcoarse ## use l1ts of current packet l1count_new_to_append = l1count ## use l1count of current packet count_mismatch = 0 elif flag_swap1: ## apply SWAP by 1 packet lsl1ts_min_tcoarse_to_append = pre_timestamp - tcoarse ## use l1ts of previous packet l1count_new_to_append = l1count - 1 ## use l1count of previous packet count_mismatch = 1 if tiger_framenum != prev2_tiger_framenum: if print_debug: print( "TIGER framecount not matched (SWAP1: L1_count={}: {} vs {}) !!!!!!!!!!!!!!!" .format( LOCAL_L1_COUNT, tiger_framenum, prev2_tiger_framenum)) elif flag_swap2: ## apply SWAP by 2 packets lsl1ts_min_tcoarse_to_append = pre_pretimestamp - tcoarse ## use l1ts of 2 previous packet l1count_new_to_append = l1count - 2 ## use l1count of 2 previous packet count_mismatch = 2 if tiger_framenum != prev3_tiger_framenum: if print_debug: print( "TIGER framecount not matched (SWAP2: L1_count={}: {} vs {}) !!!!!!!!!!!!!!!" .format( LOCAL_L1_COUNT, tiger_framenum, prev3_tiger_framenum)) else: print( "Swap ERROR: a problem occurred in swap logic (subRun={}, L1_count={}) !!!!!!!!!!!!!!!" .format(subRunNo, LOCAL_L1_COUNT)) ## Correct counters roll-over if (lsl1ts_min_tcoarse_to_append < 0): if ((int_x >> 59) & 0x7 > 3): if flag_swap1: lsl1ts_min_tcoarse_to_append = pre_timestamp - tcoarse + 2**16 if flag_swap2: lsl1ts_min_tcoarse_to_append = pre_pretimestamp - tcoarse + 2**16 if not (flag_swap1 or flag_swap2): lsl1ts_min_tcoarse_to_append = LOCAL_L1_TIMESTAMP - tcoarse + 2**16 else: lsl1ts_min_tcoarse_to_append = LOCAL_L1_TIMESTAMP - tcoarse + 2**16 ##################################################################################################################### ##################################################################################################################### ##################################################################################################################### lsl1ts_min_tcoarse.append(lsl1ts_min_tcoarse_to_append) l1count_new.append(l1count_new_to_append) lscount_mismatch.append(count_mismatch) if ( ((int_x & 0xE000000000000000) >> 61) == 0x7 ): ## TRAILER WORD --> sometimes is missing --> DO NOT USE # print "enter trailer" packet_tailer = 1 l1framenum = (int_x >> 37) & 0xFFFFFF trailer_tiger = (int_x >> 27) & 0x7 gemroc = (int_x >> 32) & 0x1F if (((int_x & 0xF000000000000000) >> 60 ) == 0x4): ## UDP WORD --> used to flag end of packet # print "enter UDP" if packet_tailer == 0: count_missing_trailer = count_missing_trailer + 1 print( "WARNING: missing trailer word (subRun = {}, L1 count = {})!!!!!!!!!!!!!!!" .format(subRunNo, LOCAL_L1_COUNT)) packet_udp = 1 # pre_udp_packet = udp_packet # udp_packet = (((int_x >> 32)&0xFFFFF) + ((int_x >> 0) & 0xFFFFFFF)) if (packet_header == 1 and packet_udp == 1): ## Fill ROOT file for x in range(len(lstac)): mystruct.channel = lschannel.pop() mystruct.tac = lstac.pop() mystruct.tcoarse = lstcoarse.pop() mystruct.ecoarse = lsecoarse.pop() mystruct.tfine = lstfine.pop() mystruct.efine = lsefine.pop() mystruct.tcoarse_10b = lstcoarse_10b.pop() mystruct.charge_SH = lscharge_SH.pop() mystruct.tiger = lstigerid.pop() mystruct.l1ts_min_tcoarse = lsl1ts_min_tcoarse.pop( ) mystruct.lasttigerframenum = lslasttigerframenum.pop( ) mystruct.count_mismatch = lscount_mismatch.pop() mystruct.count_new = l1count_new.pop() mystruct.delta_coarse = lsdelta_coarse.pop() mystruct.count_missing_trailer = count_missing_trailer mystruct.local_l1_count = LOCAL_L1_COUNT mystruct.count_ori = l1count mystruct.count = mystruct.count_new mystruct.timestamp = l1timestamp mystruct.gemroc = self.GEMROC_ID # previously was gemroc value from trailer word mystruct.runNo = self.RUN mystruct.subRunNo = subRunNo mystruct.l1_framenum = l1framenum mystruct.trailer_tiger = trailer_tiger """ if(gemrocid<4): mystruct.layer_id = 1 elif(gemrocid>3): mystruct.layer_id = 2 if(gemrocid>11): mystruct.layer_id = 0 """ if (self.GEMROC_ID < 4): mystruct.layer = 1 elif (self.GEMROC_ID > 3): mystruct.layer = 2 if (self.GEMROC_ID > 11): mystruct.layer = 0 hitcounter = hitcounter + 1 if (hitcounter > max_hitcount): sys.stderr.write("Increase max hit counter \n") continue # print "PRE FILL" tree.Fill() # print "POST FILL" packet_header = 0 packet_tailer = 0 packet_udp = 0 firstPacket = False # print("Writing to ROOT file...") rootFile.Write() rootFile.Close()
import sys, os from ROOT import gROOT gROOT.ProcessLine(".x " + os.environ['MYSW_DIR'] + "/Utils/rootlogon.C") from ROOT import Main maker = Main.Maker() # BNBComisc maker.SetInputFile( "/Users/deltutto/RealWork/CCInclusiveEventSelection/Files/Input/ubxsec_output_mc_bnbcosmic_mcc8.9_500k.root" ) maker.SetOutputFile( "/Users/deltutto/RealWork/CCInclusiveEventSelection/Files/Output/ubxsecana_output_bnbcosmic_mcc8.9_500k.root" ) maker.SetEntries(50000) maker.SetInitialEntry(0) maker.SetBeamSpillStart(3.2) maker.SetBeamSpillEnd(4.8) maker.SetFlashShift(0.) maker.SetGainCalibration(198) maker.SetCalculatePOT(True) maker.SetIsData(False) maker.SetExtraWeight(1.028) # Flux correction maker.SetTargetFluxSystematic("total")
def test1NestedNamespace(self): """Test nested namespace lookup""" gROOT.ProcessLine('#include "NestedNamespace.h"') self.assert_(ROOT.ABCDEFG.ABCD.Nested)
'--timerequest', help='Time request for running a job at HTCondor', required=False) parser.add_argument('-memory', '--memoryrequest', help='Memory request for running a job at HTCondor', required=False) memoryrequest = "" timerequest = "" ### Getting changes for requests in memory and time than default ones and other options stated beforehand args = parser.parse_args() ### Switch off recovery mode in ROOT, if file is corrupted we don't want to keep even its ashes. gROOT.ProcessLine("gEnv->SetValue(\"TFile.Recover\", 0);") ###### Method for creating HTCondor submission script ########################################################### def CreateSubmissionScript(Pathtodirectory, DirectoryName, CMSSW_BASE, cmsRunCommand, FileName, CreateEndOfSubmissionScript): '''Create job submission file for HTCondor in sample subdirectory''' file = open(DirectoryName + "/" + FileName + ".submit", "w") file.write("universe = vanilla\n \n") file.write( "transfer_executable = True \nshould_transfer_files = IF_NEEDED \nwhen_to_transfer_output = ON_EXIT\n" ) file.write("requirements = OpSysAndVer == \"SL6\"\ngetenv = true \n") file.write("batch_name = " + FileName + "\n")
def loadFWLite(): gSystem.Load("libFWCoreFWLite") gROOT.ProcessLine('AutoLibraryLoader::enable();') gSystem.Load("libFWCoreFWLite")
def main(argv): print "========================================" print "LAT2 started:", time.strftime('%X %x %Z') startT = time.clock() gROOT.ProcessLine( "gErrorIgnoreLevel = 3001;") # suppress ROOT error messages dsNum, subNum, runNum = None, None, None fCal, fUpd, fBat, fFor, fPlt, fRaw, fCalPath = 0, 0, 0, 0, 0, 0, 0 fPaths = [".", "."] if len(argv) == 0: return for i, opt in enumerate(argv): if opt == "-cal": fCal = True print "Calibration mode." if opt == "-upd": fUpd = True print "File update mode." if opt == "-p": fPlt = True print "Writing plots mode." if opt == "-debug": debugFiles() stopT = time.clock() print "Stopped:", time.strftime( '%X %x %Z'), "\nProcess time (min):", (stopT - startT) / 60 exit() if opt == "-fitRN": fitDBRiseNoise() # stopT = time.clock() # print "Stopped:",time.strftime('%X %x %Z'),"\nProcess time (min):",(stopT - startT)/60 exit() if opt == "-force": fFor = True print "Force DB update mode." if opt == "-raw": fRaw = True print "Printing raw peakfinder plots." if opt == "-d": dsNum = int(argv[i + 1]) print "Scanning DS-%d" % (dsNum) if opt == "-c": fCalPath = True print "pointing to cal path" if opt == "-f": print "Scanning DS-%d, run %d" % (dsNum, runNum) if opt == "-s": dsNum, subNum = int(argv[i + 1]), int(argv[i + 2]) print "Scanning DS-%d sub-range %d" % (dsNum, subNum) if opt == "-p": fPaths = [argv[i + 1], argv[i + 2]] print "Manual I/O paths set." if opt == "-test": testDB() if opt == "-b": fBat = True import matplotlib if os.environ.get('DISPLAY', '') == '': print "No display found. Using non-interactive Agg backend" matplotlib.use('Agg') print "Batch mode selected." global plt import matplotlib.pyplot as plt if fCal: rec = calibrateRuns(dsNum, subNum, fPaths, fBat, fPlt, fRaw) ds.setDBRecord(rec, fFor) if fUpd: updateFile(dsNum, fCalPath) stopT = time.clock() print "Stopped:", time.strftime( '%X %x %Z'), "\nProcess time (min):", (stopT - startT) / 60
def setupROOT(): gSystem.Load("libFWCoreFWLite") gROOT.ProcessLine('FWLiteEnabler::enable();')
def ProcessCommandline(self, args, options, db): """ Set configuration variables based on command line options """ # these three arguments are required to be set for every invocation self.REVISION = args[1] self.INPUT_DIRECTORY = args[2] self.INPUT_SMALLFILE_DIRECTORY = args[3] self.OUTPUT_DIRECTORY = args[4] # fix directories used in MC production if self.REVISION == "mc": self.ROOTFILE_DIR = "hd_root" self.COPY_REST_FILES = False # sanity check # set up output logging if options.logfile: logging.basicConfig(filename=options.logfile, level=logging.INFO) gSystem.RedirectOutput(options.logfile) else: logging.basicConfig(level=logging.INFO) # limit ROOT output gROOT.ProcessLine("gErrorIgnoreLevel = 2001;" ) # only output at least "Error" level messages # see if we should disable any processing steps if (options.disable_plotting): self.MAKE_PLOTS = False if (options.disable_db_summary): self.MAKE_DB_SUMMARY = False #if(options.process_run_conditions): # MAKE_RUN_CONDITIONS = True if (options.disable_hadd): self.MAKE_SUMMED_ROOTFILE = False if (options.force): self.FORCE_PROCESSING = True if (options.save_rest): self.COPY_REST_FILES = True if (options.merge_increment): self.MERGE_INCREMENT = True if (options.batch_tempdir): self.BATCH_TEMP_DIR = True # should we process only one run? if (options.run_number): try: self.RUN_NUMBER = int(options.run_number) except ValueError: logging.error("Invalid run number = " + options.run_number) sys.exit(0) if self.RUN_NUMBER <= 0: logging.error("Invalid run number = " + options.run_number) sys.exit(0) # set which data version in the DB this processing run corresponds to if (options.version_string): try: revision = -1 (run_period, revision_str) = options.version_string.split(",") try: revision = int(revision_str) except ValueError: logging.error("Invalid revision = " + revision) sys.exit(0) self.VERSION_NUMBER = db.GetVersionIDRunPeriod( run_period, revision) if (self.VERSION_NUMBER < 0): logging.error("version not found in DB = " + options.version_string) sys.exit(0) except: logging.error("Invalid version specification = " + options.version_string) raise sys.exit(0) logging.info( "Configured RunPeriod = %s Revision = %d -> VersionID = %d" % (run_period, revision, self.VERSION_NUMBER)) if (options.version_number): try: self.VERSION_NUMBER = int(options.version_number) except ValueError: logging.error("Invalid version number = " + options.version_number) sys.exit(0) if self.VERSION_NUMBER <= 0: logging.error("Invalid version number = " + options.version_number) sys.exit(0) # process a range of runs? if options.min_run: self.MIN_RUN = int(options.min_run) logging.info("Minimum run = %d" % self.MIN_RUN) if options.max_run: self.MAX_RUN = int(options.max_run) logging.info("Maximum run = %d" % self.MAX_RUN) if options.nthreads: self.NTHREADS = options.nthreads if options.noendofjob_processing: self.EOR_PROCESSING = False if options.root_output_dir: self.MERGED_ROOTFILE_OUTPUT_DIRECTORY = options.root_output_dir if options.root_trees_to_merge: self.ROOT_TREES_TO_MERGE = options.root_trees_to_merge.split(",") if options.evio_skims_to_merge: self.EVIO_SKIMS_TO_MERGE = options.evio_skims_to_merge.split(",") if options.hddm_files_to_merge: self.HDDM_FILES_TO_MERGE = options.hddm_files_to_merge.split(",")
def GeneralSettings(paintformat="4.2f"): gROOT.SetBatch(True) gStyle.SetOptStat(0) tdr.setTDRStyle() gStyle.SetPaintTextFormat(paintformat) gROOT.ProcessLine("gErrorIgnoreLevel = 1001;")
liczba2=generator.Gaus(300,60)/1; liczba2=int(liczba2) if liczba2>liczba: self.stworzDane([bool(0)],i,liczba2) self.stworzDane([bool(1)],i,liczba) else: self.stworzDane([bool(0)],i,liczba) self.stworzDane([bool(1)],i,liczba2) struktura="struct DaneZKanalow {" for i in range(52): struktura=struktura+"Bool_t kanal"+str(i)+"op[32]; " struktura=struktura+"Bool_t kanal"+str(i)+"nar[32]; " struktura=struktura+"};" gROOT.ProcessLine(struktura) from ROOT import DaneZKanalow czas=time.strftime("%d.%m.%Y %H:%M:%S") plik=TFile('daneGener ['+czas+'].root', 'RECREATE') gener=TRandom3(0) drzewo=TTree("Zestawy","Drzewo z wygenerowanymi zestawami.") kanaly=DaneZKanalow() struktura="kanal0op[32]/B:kanal0nar[32]" for i in range(51): struktura=struktura+":kanal"+str(i+1)+"op[32]" struktura=struktura+":kanal"+str(i+1)+"nar[32]" galaz=drzewo.Branch("Zestaw",kanaly,struktura) galaz.SetBasketSize(240)
# # create dictionary with ratio of smoothed / raw efficiencies # argument: dictionary with raw efficiencies # from optparse import OptionParser parser = OptionParser() parser.add_option("--m3Ratio", dest="m3Ratio", default=-1., type="float", action="store", help="ratio for intermediate mass in SMS models") parser.add_option("-f", dest="force", default=False, action="store_true", help="replace output file") (options, args) = parser.parse_args() filename = args[0] mydic = pickle.load(file(filename)) from ROOT import gROOT gROOT.ProcessLine(".L SmoothingUtils.C+") # output dictionary newdic = {} m0s = [ ] m12s = [ ] labels = [ ] # loop over all ht and met values # in input dictionary model = None suffix = None for btag in mydic: for ht in mydic[btag]: for met in mydic[btag][ht]: # create lists of M0 and M12 values and
label='Ratio', xlog=False, outputDir=WORKPATH + 'SymmetryResults/', maxYnumbers=maxY) print('>>>>>>>>>> KOLMOGOROV test for ' + labela) print('>>>>>>>>>> ' + str(histo1.KolmogorovTest(histo2))) print('>>>>>>>>>> Chi2 test for ' + labela) print('>>>>>>>>>> ' + str(histo1.Chi2Test(histo2, "WWP"))) return 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='',
import os import ROOT from ROOT import gSystem, gROOT from CMGTools.H2TauTau.proto.plotter.PlotConfigs import SampleCfg from CMGTools.H2TauTau.proto.plotter.HistCreator import setSumWeights from CMGTools.H2TauTau.proto.samples.spring16.sms_xsec import get_xsec from CMGTools.H2TauTau.proto.samples.spring16.htt_common import TT_pow_ext, DYJetsToLL_M50_LO, DYNJets, WJetsToLNu, WNJets, WWTo2L2Nu, T_tWch, TBar_tWch, VVTo2L2Nu, ZZTo4L, WZTo1L3Nu, WWTo1L1Nu2Q, ZZTo2L2Q, WZTo2L2Q, WZTo1L1Nu2Q, TBarToLeptons_tch_powheg, TToLeptons_tch_powheg, mssm_signals, dy_weight_dict, w_weight_dict # WJetsToLNu_LO, TToLeptons_tch_amcatnlo, WZTo3LNu_amcatnlo, , WJetsToLNu_HT100to200, WJetsToLNu_HT200to400, WJetsToLNu_HT400to600, WJetsToLNu_HT600toInf, QCD_Mu15, DYJetsToTauTau_M150_LO, DYJetsToLL_M10to50_ext1 if "/sDYReweighting_cc.so" not in gSystem.GetLibraries(): gROOT.ProcessLine(".L %s/src/CMGTools/H2TauTau/python/proto/plotter/DYReweighting.cc+" % os.environ['CMSSW_BASE']); from ROOT import getDYWeight splitDY = False useDYWeight = False # data2016G = True if useDYWeight: dy_exps = [] for njet in xrange(0, 5): weight = dy_weight_dict[(njet, 0)] dy_exps.append('(geninfo_nup == {njet})*{weight}'.format(njet=njet, weight=weight)) # dy_exps.append('(geninfo_nup == {njet} && (geninfo_invmass<150. || !(l2_gen_match==5 || l1_gen_lepfromtau)))*{weight}'.format(njet=njet, weight=weight)) # weight = dy_weight_dict[(njet, 150)] # dy_exps.append('(geninfo_nup == {njet} && (geninfo_invmass>=150. && (l2_gen_match==5 || l1_gen_lepfromtau)))*{weight}'.format(njet=njet, weight=weight)) dy_exp = '*({})'.format(' + '.join(dy_exps))
def getCommonInfo(rootfile): commoninfo = {} gROOT.ProcessLine('gSystem->Load("libRootEventData.so");') gROOT.ProcessLine('TFile file("%s");' % rootfile) gROOT.ProcessLine('TTree* tree =(TTree*)file.Get("JobInfoTree");') gROOT.ProcessLine('TTree* tree1 =(TTree*)file.Get("Event");') gROOT.ProcessLine('TBranch* branch =(TBranch*)tree->GetBranch("JobInfo");') gROOT.ProcessLine( 'TBranch* branch1 =(TBranch*)tree1->GetBranch("TEvtHeader");') gROOT.ProcessLine('TJobInfo* jobInfo = new TJobInfo();') gROOT.ProcessLine('TEvtHeader* evtHeader = new TEvtHeader();') gROOT.ProcessLine('branch->SetAddress(&jobInfo);') gROOT.ProcessLine('branch1->SetAddress(&evtHeader);') gROOT.ProcessLine('branch->GetEntry(0);') gROOT.ProcessLine('branch1->GetEntry(0);') gROOT.ProcessLine('Int_t num=tree1.GetEntries()') #get Boss Version commoninfo["bossVer"] = ROOT.jobInfo.getBossVer() #get RunId commoninfo["runId"] = abs(ROOT.evtHeader.getRunId()) #get all entries commoninfo["eventNum"] = ROOT.num #get TotEvtNo #commoninfo["TotEvtNo"] = list(i for i in ROOT.jobInfo.getTotEvtNo()) #get JobOption commoninfo["jobOptions"] = list(i for i in ROOT.jobInfo.getJobOptions()) #set DataType commoninfo["dataType"] = 'dst' return commoninfo
print "Setup complete \nOpened file " + str( sys.argv[1] ) + " \nConverting to .root format and outputing to " + output_file_name # Setup output branches PID_v = r.vector('Int_t')() P_X_v = r.vector('Double_t')() P_Y_v = r.vector('Double_t')() P_Z_v = r.vector('Double_t')() E_v = r.vector('Double_t')() M_v = r.vector('Double_t')() P4_v = r.vector('ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float>>')() Wgt_v = r.vector('Double_t')() # Create a struct which acts as the TBranch for non-vectors gROOT.ProcessLine("struct MyStruct{ Int_t n_particles; };") gROOT.ProcessLine("struct MyFloat{ Float_t weight; };") from ROOT import MyStruct from ROOT import MyFloat # Assign the variables to the struct s = MyStruct() event_wgt = MyFloat() output_tree.Branch('n_particles', AddressOf(s, 'n_particles'), 'n_particles/I') output_tree.Branch("PID", PID_v) output_tree.Branch("P_X", P_X_v) output_tree.Branch("P_Y", P_Y_v) output_tree.Branch("P_Z", P_Z_v) output_tree.Branch("E", E_v) output_tree.Branch("M", M_v) output_tree.Branch("P4", P4_v)