def test04NamespacedTemplateIdentity( self ): """Identity of templated classes with and w/o std:: should match""" gInterpreter.Declare( 'namespace PR_HepMC { class GenParticle {}; }' ) gInterpreter.Declare( 'namespace PR_LoKi { template< typename T, typename S > class Functor {}; }' ) PR_LoKi = ROOT.PR_LoKi f1 = PR_LoKi.Functor( "vector<const PR_HepMC::GenParticle*>", "vector<double>" ) f2 = PR_LoKi.Functor( "std::vector<const PR_HepMC::GenParticle*>", "std::vector<double>" ) self.assert_( f1 is f2 ) self.assertEqual( f1, f2 )
def load_fastjet(fastjet_dir=None): if hasattr(ROOT, "fastjet"): print("'fastjet' was already loaded.") return None lib_dir = gSystem.ConcatFileName(fastjet_dir, "lib") include_dir = gSystem.ConcatFileName(fastjet_dir, "include") libfastjet_so = gSystem.ConcatFileName(lib_dir, "libfastjet.so") libfastjettools_so = gSystem.ConcatFileName(lib_dir, "libfastjettools.so") gInterpreter.AddIncludePath(include_dir) gSystem.Load(libfastjet_so) gSystem.Load(libfastjettools_so) gInterpreter.Declare('#include "fastjet/PseudoJet.hh"') gInterpreter.Declare('#include "fastjet/ClusterSequence.hh"') gInterpreter.Declare('#include "fastjet/Selector.hh"')
def test4ClassAndTypedefEquality( self ): """Typedefs of the same class must point to the same python class""" gInterpreter.Declare( """namespace PyABC { struct SomeStruct {}; struct SomeOtherStruct { typedef std::vector<const PyABC::SomeStruct*> StructContainer; }; }""" ) import cppyy PyABC = cppyy.gbl.PyABC self.assert_( PyABC.SomeOtherStruct.StructContainer is cppyy.gbl.std.vector('const PyABC::SomeStruct*') )
def load_delphes(delphes_dir): if hasattr(ROOT, "Delphes"): print("'delphes' was already loaded.") return None classes_dir = gSystem.ConcatFileName(delphes_dir, "classes") external_dir = gSystem.ConcatFileName(delphes_dir, "external") exrootanalysis_dir = gSystem.ConcatFileName(external_dir, "ExRootAnalysis") so_file = gSystem.ConcatFileName(delphes_dir, "libDelphes.so") gInterpreter.AddIncludePath(delphes_dir) gInterpreter.AddIncludePath(classes_dir) gInterpreter.AddIncludePath(external_dir) gInterpreter.AddIncludePath(exrootanalysis_dir) gSystem.Load(so_file) gInterpreter.Declare('#include "classes/DelphesClasses.h"')
def load_histo(year, polarity, particle, histo_name, histo_dim, histos, loaded_histos): histo_lbl = '_'.join([year, polarity, particle])+'_'+histo_name if histo_lbl in loaded_histos: return loaded_histos[histo_lbl] try: ntp_filename = find_histo(histos, year, polarity, particle) except IndexError: raise(ValueError('Histo {} cannot be loaded! Abort!'.format(histo_lbl))) print(' Loading histo {} from ntuple {}'.format(histo_name, ntp_filename)) gInterpreter.Declare('auto ntp_{} = TFile("{}", "read");'.format( histo_lbl, ntp_filename)) # NOTE: Don't use dynamic_cast here, as sometimes the cast will fail and a # nullptr is returned instead. Use static_cast to force a type gInterpreter.Declare(''' auto histo_{lbl} = static_cast<TH{dim}D*>(ntp_{lbl}.Get("{name}")); '''.format(lbl=histo_lbl, dim=histo_dim, name=histo_name) ) loaded_histos[histo_lbl] = 'histo_' + histo_lbl return loaded_histos[histo_lbl]
def _LoadFunctions(): gInterpreter.Declare(CPPIOFunctions)
def _LoadClass(): gInterpreter.Declare(CPPIOClass)
import argparse import numpy from os import path try: from common import run_cmd, warning_msg, bcolors except: raise FileNotFoundError( "Cannot find common.py in path, you can download it via:" "wget https://raw.githubusercontent.com/AliceO2Group/DelphesO2/master/examples/scripts/common.py" ) import multiprocessing # Function to create indices for each particle gInterpreter.Declare(""" int part_index = 0; int index_maker(Int_t ev) { return part_index++; } """) # Function to check if it is physical primary gInterpreter.Declare(""" enum MCParticleFlags : uint8_t { ProducedByTransport = 0x1, FromBackgroundEvent = 0x2, // Particle from background event (may have been used several times) PhysicalPrimary = 0x4 // Particle is a physical primary according to ALICE definition }; bool physPrim(UChar_t flag) { return (flag & PhysicalPrimary) == PhysicalPrimary; uint8_t f = static_cast<uint8_t>(flag); //Printf("%i %c", f, flag); return (f & PhysicalPrimary) == PhysicalPrimary; }
def check_corresponding(file_list, origin="AODRun5", friend="delphes", verbose=False, show=False): """ Function to check that the delphes and AODs are consistent """ print("Checking correspondance between O2 tables and delphes output") for i in file_list: def get_frame(tree_name, file_name): frame = RDataFrame(tree_name, file_name) if verbose: colNames = frame.GetColumnNames() for j in colNames: print(j) return frame df = get_frame("TF_0/O2mcparticle", i) df = df.Define("fP", "TMath::Sqrt(fPx*fPx + fPy*fPy + fPz*fPz)") df = df.Define("fEta", "-0.5*TMath::Log((fP+fPz)/(fP-fPz))") # df_reco = get_frame("TF_0/O2track", i) df_reco = df_reco.Define( "fEta", "-1.f * TMath::Log(TMath::Tan(0.25f * TMath::Pi() - 0.5f * TMath::ATan(fTgl)))" ) df_reco = df_reco.Define("fPt", "1./TMath::Abs(fSigned1Pt)") # df_delphes = get_frame("Delphes", i.replace(origin, friend)) gInterpreter.Declare(""" auto p(ROOT::VecOps::RVec<Float_t> px, ROOT::VecOps::RVec<Float_t> py, ROOT::VecOps::RVec<Float_t> pz) { std::vector<Float_t> v; int counter = 0; for(auto i : px){ v.push_back(TMath::Sqrt(px[counter]*px[counter] + py[counter]*py[counter] + pz[counter]*pz[counter])); counter++; } return v; } """) gInterpreter.Declare(""" auto eta(ROOT::VecOps::RVec<Float_t> p, ROOT::VecOps::RVec<Float_t> pz) { std::vector<Float_t> v; int counter = 0; for(auto i : p){ v.push_back(0.5*TMath::Log((p[counter]+pz[counter])/(p[counter]-pz[counter]))); counter++; } return v; } """) gInterpreter.Declare(""" auto recomc(ROOT::VecOps::RVec<Float_t> mc, ROOT::VecOps::RVec<Int_t> mclabel, ROOT::VecOps::RVec<TRef> recolabel) { std::vector<Float_t> v; int counter = 0; for(auto i : mc){ for(auto j : recolabel){ if (mclabel[counter] == j.GetUniqueID()) {v.push_back(i);} } counter++; } return v; } """) gInterpreter.Declare(""" auto diff(ROOT::VecOps::RVec<Float_t> a, ROOT::VecOps::RVec<Float_t> b) { std::vector<Float_t> v; int counter = 0; for(auto i : a){ v.push_back(i-b[counter]); counter++; } return v; } """) df_delphes = df_delphes.Define( "P", "p(Particle.Px, Particle.Py, Particle.Pz)") df_delphes = df_delphes.Define("Eta", "eta(P, Particle.Pz)") df_delphes = df_delphes.Define( "RecoEta", "recomc(Eta, Particle.fUniqueID, Track.Particle)") df_delphes = df_delphes.Define("EtaDiff", "diff(RecoEta, Particle.Eta)") df_delphes = df_delphes.Define( "RecoPhi", "recomc(Particle.Phi, Particle.fUniqueID, Track.Particle)") df_delphes = df_delphes.Define("PhiDiff", "diff(RecoPhi, Track.Phi)") canvas_list = [] def canvas(name, diff=False): can = TCanvas(name, name, 800, 1280) can.Divide(1, 2) canvas_list.append(can) return can def check(var, nbins, low, up, friend_var="Particle.{}", frame=df): h = f"{origin} {var}" h = frame.Histo1D(RDF.TH1DModel(h, h, nbins, low, up), f"f{var}") friend_var = friend_var.format(var) h2 = f"{friend} {friend_var}" h2 = df_delphes.Histo1D(RDF.TH1DModel(h2, h2, nbins, low, up), friend_var) h2.SetLineColor(2) h2.SetLineStyle(3) can = canvas(var, diff=True) can.cd(1) h.SetDirectory(0) h2.SetDirectory(0) hdrawn = [h.DrawCopy(), h2.DrawCopy("same")] for i in hdrawn: i.SetDirectory(0) leg = TLegend(.7, .5, .9, .75) leg.AddEntry(h.GetValue()) leg.AddEntry(h2.GetValue()) leg.Draw() gPad.Update() can.cd(2) hdiff = h.DrawCopy() hdiff.SetDirectory(0) hdiff.SetName("hdiff") hdiff.SetTitle("diff") hdiff.Add(h2.GetValue(), -1) hdiff.GetYaxis().SetRangeUser(-1, 1) gPad.Update() for i in range(1, hdiff.GetNbinsX() + 1): diff = hdiff.GetBinContent(i) if diff != 0: return False return True def correlate(frame, x, y): hn = f"{x[0]}_vs_{y[0]}" ht = f";{x[0]};{y[0]}" h = frame.Histo2D( RDF.TH2DModel(hn, ht, x[1], x[2], x[3], y[1], y[2], y[3]), x[0], y[0]) can = canvas(hn) can.SetLeftMargin(0.15) h.Draw("COLZ") can.Update() def plot(frame, x): hn = f"{x[0]}" ht = f";{x[0]}" h = frame.Histo1D(RDF.TH1DModel(hn, ht, x[1], x[2], x[3]), x[0]) can = canvas(hn) can.SetLeftMargin(0.15) h.Draw("COLZ") can.Update() # Comparison of Delphes Particles and O2 Particles variables = { "Px": [1000, -100, 100], "Py": [1000, -100, 100], "Pz": [1000, -100, 100], "P": [1000, 0, 100], "Vx": [1000, -100, 100, "Particle.X"], "Vy": [1000, -100, 100, "Particle.Y"], "Vz": [1000, -100, 100, "Particle.Z"], "Eta": [1000, -10, 10], "E": [1000, 0, 1000] } for i in variables: x = variables[i] if not check(i, *x): print("Something is wrong for", i) # Comparison of Delphes Tracks and O2 Tracks check("Eta", 1000, -10, 10, frame=df_reco, friend_var="Track.{}") check("Pt", 1000, 0, 30, frame=df_reco, friend_var="Track.PT") # check("Pt", 1000, 0, 30, frame=df_reco, friend_var="Particle.PT") # Correlation of Delphes variables correlate(df_delphes, ["Eta", 1000, -10, 10], ["Particle.Eta", 1000, -10, 10]) correlate(df_delphes, ["P", 1000, -1, 10], ["Particle.P", 1000, -1, 10]) correlate(df_delphes, ["Track.Eta", 1000, -10, 10], ["EtaDiff", 1000, -10, 10]) # Plot of Delphes variables plot(df_delphes, ["EtaDiff", 1000, -2, 2]) plot(df_delphes, ["PhiDiff", 1000, -2, 2]) if show: input("Press enter to continue") fout = TFile("table_check.root", "RECREATE") fout.cd() canvas_list[0].SaveAs("table_check.pdf[") for i in canvas_list: i.SaveAs("table_check.pdf") i.Write() canvas_list[0].SaveAs("table_check.pdf]") fout.Close()
import os import sys import ROOT from DAZSLE.PhiBBPlusJet.analysis_base import AnalysisBase from math import ceil, sqrt from ROOT import gInterpreter, gSystem, gROOT, gStyle, Root, TCanvas, TLegend, TH1F, TFile, TGraphErrors gInterpreter.Declare("#include \"MyTools/RootUtils/interface/SeabornInterface.h\"") gInterpreter.Declare("#include \"MyTools/RootUtils/interface/HistogramManager.h\"") gSystem.Load("/uscms/home/dryu/DAZSLE/CMSSW_8_0_20/lib/slc6_amd64_gcc530/libMyToolsRootUtils.so") gInterpreter.Declare("#include \"MyTools/AnalysisTools/interface/EventSelector.h\"") gSystem.Load("/uscms/home/dryu/DAZSLE/CMSSW_8_0_20/lib/slc6_amd64_gcc530/libMyToolsAnalysisTools.so") gROOT.SetBatch(ROOT.kTRUE); gStyle.SetOptStat(0) gStyle.SetOptTitle(0) seaborn = Root.SeabornInterface() seaborn.Initialize() class SignalCutflow(AnalysisBase): def __init__(self, tree_name="Events"): super(SignalCutflow, self).__init__(tree_name=tree_name) self._output_path = "" def set_output_path(self, output_path): self._output_path = output_path def start(self): self._processed_events = 0 # Histograms self._histograms = ROOT.Root.HistogramManager()
print('Cannot find layout {}, please choose one of {}'.format(args.channels, list(layout))) exit(-1) # recover paths for attr in ['root_file', 'out_dir']: setattr(args, attr, os.path.join(owd, getattr(args, attr))) os.makedirs(args.out_dir, exist_ok=True) # batch mode gROOT.SetBatch(True) # root macros gROOT.Macro('rootlogon.C') # declare root graph code func_code = open(os.path.join(script_dir, '..', 'decoder', 'WfRootGraph.h')).read() gInterpreter.Declare(func_code) # style my_style.cd() # root file f = ROOT.TFile(args.root_file, 'r') tree = f.EvTree channels = layout[args.channels] # define analyzer analyzer = ROOT.fdec.Analyzer(args.res, args.thres, args.npeds, args.flat) events = [] for ev in args.events.split(','): try:
HEADER = "\033[95m" OKBLUE = "\033[94m" BOKBLUE = BOLD + OKBLUE OKGREEN = "\033[92m" BOKGREEN = BOLD + OKGREEN WARNING = "\033[93m" BWARNING = BOLD + WARNING FAIL = "\033[91m" BFAIL = BOLD + FAIL ENDC = "\033[0m" # Function to create indices for each particle gInterpreter.Declare(""" int part_index = 0; auto index_maker(Int_t ev) { return part_index++; } """) def main(filename, verbose=True, pdg_of_interest=[421], event_filters=None, summary=True): def get_frame(tree_name, file_name): """ Getter of the frame from the file """ frame = RDataFrame(tree_name, file_name) if verbose:
gInterpreter.Declare(''' #include <cmath> #include <TMath.h> using namespace std; Double_t P(Double_t px, Double_t py, Double_t pz) { return TMath::Sqrt(px*px + py*py + pz*pz); } Double_t ETA(Double_t p, Double_t pz) { return 0.5 * TMath::Log((p + pz) / (p - pz)); } Double_t ETA(Double_t px, Double_t py, Double_t pz) { auto p = P(px, py, pz); return ETA(p, pz); } Double_t GUARD(Double_t val, Double_t low, Double_t high, Double_t offset=0.01) { if (val <= low) return low + offset; if (val >= high) return high - offset; return val; } Int_t GET_BIN(Double_t x, TH1D* histo) { return histo->FindFixBin(x); } Int_t GET_BIN(Double_t x, Double_t y, TH2D* histo) { return histo->FindFixBin(x, y); } Int_t GET_BIN(Double_t x, Double_t y, Double_t z, TH3D* histo) { return histo->FindFixBin(x, y, z); } Double_t GET_WEIGHT(Double_t x, TH1D* histo) { auto bin_idx = GET_BIN(x, histo); Double_t wt = histo->GetBinContent(bin_idx); if (isnan(wt) || wt < 0) return 0.0; return wt; } Double_t GET_WEIGHT(Double_t x, Double_t y, TH2D* histo) { auto bin_idx = GET_BIN(x, y, histo); Double_t wt = histo->GetBinContent(bin_idx); if (isnan(wt) || wt < 0) return 0.0; return wt; } Double_t GET_WEIGHT(Double_t x, Double_t y, Double_t z, TH3D* histo) { if (histo == nullptr) { cout << "Histo is a nullptr!"; exit(1); } auto bin_idx = GET_BIN(x, y, z, histo); Double_t wt = histo->GetBinContent(bin_idx); if (isnan(wt) || wt < 0) return 0.0; return wt; } ''')
ub=train + validation), 'test': '{lb} <= {br} && {br} <= {ub}'.format(br=br, lb=train + validation, ub=100) } ######## # Main # ######## if __name__ == '__main__': args = parse_input() gInterpreter.Declare('auto rand_gen = TRandom3({});'.format(args.seed)) init_frame = RDataFrame(args.tree, args.ntp) rand_frame = init_frame.Define('rand_split', 'rand_gen.Uniform(0, 100)') if args.debug: print('loaded {} with {} entries'.format( args.ntp, rand_frame.Count().GetValue())) cuts = get_cuts(args.train_ratio, args.validation_ratio) for sample, cut in cuts.items(): subsample_frame = rand_frame.Filter(cut) output_ntp = join(args.output_dir, '{}_{}.root'.format(get_filename(args.ntp), sample)) subsample_frame.Snapshot(args.tree, output_ntp)
mcNtpN = '../../ntuples/0.9.6-2016_production/JpsiK-mc-step2/JpsiK--22_03_10--mc--12143001--2016--md.root' mcTreeN = 'tree' histoNtpN = '../../run2-JpsiK/reweight/JpsiK/root-run2-JpsiK_oldcut/run2-JpsiK-2016-md-B-ndof_ntracks__pt_eta.root' histoN = 'h_occupancy' ################# # Histo w/ ROOT # ################# gInterpreter.Declare(''' Int_t getBin(Double_t x, Double_t y, TH2D* histo) { return histo->FindFixBin(x, y); } auto getWeight(Double_t x, Double_t y, TH2D* histo) { auto binIdx = getBin(x, y, histo); return histo->GetBinContent(binIdx); } ''') gInterpreter.Declare(f'auto histoNtp = new TFile("{histoNtpN}", "read");') gInterpreter.Declare(f'auto histo = dynamic_cast<TH2D*>(histoNtp->Get("{histoN}"));') dfInit = RDataFrame(mcTreeN, mcNtpN) df = dfInit.Define('wjk_alt', 'getWeight(b_ownpv_ndof, ntracks, histo)').Define('wt', 'wpid*wtrk*wjk_alt') # NOTE: This comes from the existing ntuple mcRootBrs = df.AsNumpy(columns=['wjk_occ', 'wjk_alt']) wtJkOccRoot = mcRootBrs['wjk_occ'] wtJkOccAltRoot = mcRootBrs['wjk_alt']