def __init__(self, files, tree_name, options=None): from DataFormats.FWLite import Events as FWLiteEvents #TODO not sure we still need the stuff below from ROOT import gROOT, gSystem, AutoLibraryLoader print "Loading FW Lite" gSystem.Load("libFWCoreFWLite") gROOT.ProcessLine('FWLiteEnabler::enable();') gSystem.Load("libFWCoreFWLite") gSystem.Load("libDataFormatsPatCandidates") from ROOT import gInterpreter gInterpreter.ProcessLine("using namespace reco;") gInterpreter.ProcessLine("using edm::refhelper::FindUsingAdvance;") if options is not None: if not hasattr(options, "inputFiles"): options.inputFiles = files if not hasattr(options, "maxEvents"): options.maxEvents = 0 if not hasattr(options, "secondaryInputFiles"): options.secondaryInputFiles = [] self.events = FWLiteEvents(options=options) else: self.events = FWLiteEvents(files)
def _LoadHeaders(): gInterpreter.ProcessLine("#include<TRint.h>") gInterpreter.ProcessLine("#include<TApplication.h>") gInterpreter.ProcessLine("#include<TException.h>") gInterpreter.ProcessLine("#include<TInterpreter.h>") gInterpreter.ProcessLine("#include <TROOT.h>") gInterpreter.ProcessLine("#include<string>") gInterpreter.ProcessLine("#include<sstream>") gInterpreter.ProcessLine("#include<iostream>") gInterpreter.ProcessLine("#include<fstream>") gInterpreter.ProcessLine(CHeaders)
def load_libs(): print 'loading FWLite.' #load the libaries needed gSystem.Load("libFWCoreFWLite") gROOT.ProcessLine('FWLiteEnabler::enable();') gSystem.Load("libDataFormatsFWLite") gSystem.Load("libDataFormatsParticleFlowReco") #now the RootTools stuff # gSystem.Load("libPhysicsToolsHeppy") from ROOT import gInterpreter gInterpreter.ProcessLine("using namespace reco;") gInterpreter.ProcessLine("using edm::refhelper::FindUsingAdvance;")
def main(file_name): headers = """ #include "lutCovm.hh" #include <iostream> #include <fstream> """ gInterpreter.ProcessLine(headers) gInterpreter.ProcessLine(f"const char* filename = \"{file_name}\";") printer = """ ifstream lutFile(filename, std::ofstream::binary); lutHeader_t lutHeader; lutFile.read(reinterpret_cast<char*>(&lutHeader), sizeof(lutHeader)); lutHeader.print(); """ gInterpreter.ProcessLine(printer)
def get_approximator(path_to_file, approximator_name): """ Get approximator_test from file. :param path_to_file: path to file with serialized LHCOpticsApproximator object :param approximator_name: name of approximator_test in ROOT file :return: approximator_test object """ root_initializer.initialise() global approximators_counter root_pointer_name = "apr" + str(approximators_counter) approximators_counter += 1 gInterpreter.ProcessLine('f=TFile::Open("' + path_to_file + '");') gInterpreter.ProcessLine( 'std::auto_ptr<LHCOpticsApproximator> ' + root_pointer_name + ' = std::auto_ptr<LHCOpticsApproximator>((LHCOpticsApproximator*) f->Get("' + approximator_name + '"));') gInterpreter.ProcessLine("f->Close()") approximator = getattr(ROOT, root_pointer_name) return approximator
def compileAClick(dictionary, g4=True): from ROOT import gInterpreter, gSystem import os.path dd4hep = os.environ['DD4hepINSTALL'] inc = ' -I' + os.environ['ROOTSYS'] + '/include -I' + dd4hep + '/include ' lib = ' -L' + dd4hep + '/lib -lDDCore -lDDG4 -lDDSegmentation ' if g4: geant4 = os.environ['G4INSTALL'] inc = inc + ' -I' + geant4 + '/include/Geant4 -Wno-shadow -g -O0 ' lib = lib + ' -L' + geant4 + '/lib -L' + geant4 + '/lib64 -lG4event -lG4tracking -lG4particles ' gSystem.AddIncludePath(inc) gSystem.AddLinkedLibs(lib) logger.info('Loading AClick %s', dictionary) package = imp.find_module('DDG4') dic = os.path.dirname(package[1]) + os.sep + dictionary gInterpreter.ProcessLine('.L ' + dic + '+') from ROOT import dd4hep as module return module
def compileAClick(dictionary,g4=True): from ROOT import gInterpreter, gSystem import sys, imp, exceptions import os.path dd4hep = os.environ['DD4hepINSTALL'] inc = ' -I'+os.environ['ROOTSYS']+'/include -I'+dd4hep+'/include ' lib = ' -L'+dd4hep+'/lib -lDDCore -lDDG4 -lDDSegmentation ' if g4: geant4 = os.environ['G4INSTALL'] inc = inc + ' -I'+geant4+'/include/Geant4 -Wno-shadow -g -O0 ' lib = lib + ' -L'+geant4+'/lib -L'+geant4+'/lib64 -lG4event -lG4tracking -lG4particles ' gSystem.AddIncludePath(inc) gSystem.AddLinkedLibs(lib) #####print "Includes: ",gSystem.GetIncludePath(),"\n","Linked libs:",gSystem.GetLinkedLibs() print 'Loading AClick ',dictionary package = imp.find_module('DDG4') dic = os.path.dirname(package[1])+os.sep+dictionary ###print dic gInterpreter.ProcessLine('.L '+dic+'+') #####gInterpreter.Load('DDG4Dict_C.so') from ROOT import DD4hep as module return module
def initialise(): # This lines should be invoked only once during program run # It initialize ROOT variables using in train and transport global was_initialised if not was_initialised: # Transport gInterpreter.ProcessLine("double input[5];") gInterpreter.ProcessLine("double output[5];") # Train gInterpreter.ProcessLine("double x_in[5];") gInterpreter.ProcessLine("Int_t mPowers[5];") gInterpreter.ProcessLine('char option[] = "k";') gInterpreter.ProcessLine('std::string dummy_name = "approximator";') library_name = "LHCOpticsApproximator.so" gSystem.Load(library_name) # Read in approximator gInterpreter.ProcessLine('TFile *f;') was_initialised = True
from ROOT import * from ROOT import gInterpreter, gSystem import math, os #gInterpreter.ProcessLine('#include "RooCruijff.h"') gInterpreter.ProcessLine('.L RooVoigtian.cxx++') #gSystem.Load('RooCruijff.cxx++') f1 = "/home/taylor/Research/root/78nbcutmfdtokpi.root" tree = "dsprecontree" f = TFile(f1, "READ") t = f.Get(tree) deltam = RooRealVar("deltam", "deltam", 0.138, 0.18) lb = deltam.getMin() rb = deltam.getMax() nBins = 42 binWidth = (rb - lb) / nBins binWidthMEV = binWidth * 1000 vars = RooArgSet(deltam) data = RooDataSet("data", "raw data", t, vars) #Function Variables #Voigtian voigmean = RooRealVar("<>_{signal}", "<>_{signal}", 0.145, 0, 0.5) voigwidth = RooRealVar("width_{signal}", "#width_{signal}", 0.0005, 0, 0.1) voigsigma = RooRealVar("#sigma_{signal}", "#sigma_{signal}", 0.0005, 0, 0.1)
import os import ROOT from ROOT import gInterpreter, gSystem fw_path = os.environ['FRAMEWORK_PATH'] gInterpreter.ProcessLine(' #include "%s/lib/EventInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/JetInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/JetPairInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/MetInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/MuPairInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/MuonInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/VertexInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/EleInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/MhtInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/GenParentInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/GenMuonInfo.h"' % fw_path) gInterpreter.ProcessLine(' #include "%s/lib/GenMuPairInfo.h"' % fw_path)
from __future__ import print_function from DataFormats.FWLite import Events as FWLiteEvents from ROOT import gROOT, gSystem, AutoLibraryLoader print("Loading FW Lite") gSystem.Load("libFWCoreFWLite") gROOT.ProcessLine('FWLiteEnabler::enable();') gSystem.Load("libFWCoreFWLite") gSystem.Load("libDataFormatsPatCandidates") from ROOT import gInterpreter gInterpreter.ProcessLine("using namespace reco;") gInterpreter.ProcessLine("using edm::refhelper::FindUsingAdvance;") class Events(object): def __init__(self, files, tree_name, options=None): if options is not None: if not hasattr(options, "inputFiles"): options.inputFiles = files if not hasattr(options, "maxEvents"): options.maxEvents = 0 if not hasattr(options, "secondaryInputFiles"): options.secondaryInputFiles = [] self.events = FWLiteEvents(options=options) else: self.events = FWLiteEvents(files) def __len__(self):
Get waveform from AraSim events with Python Author: Jorge Torres Date: Jul 28, 2020. """ from ROOT import TCanvas, TGraph from ROOT import gROOT import ROOT import os import pandas as pd import matplotlib.pyplot as plt import numpy as np from ROOT import gInterpreter, gSystem #add headers from AraSim. Not sure if all of them are needed, and I'm lazy to check that. MAK SURE to change the location of the headers gInterpreter.ProcessLine('#include "/users/PCON0003/cond0068/ARA/AraSim/Position.h"') gInterpreter.ProcessLine('#include "/users/PCON0003/cond0068/ARA/AraSim/Report.h"') gInterpreter.ProcessLine('#include "/users/PCON0003/cond0068/ARA/AraSim/Detector.h"') gInterpreter.ProcessLine('#include "/users/PCON0003/cond0068/ARA/AraSim/Settings.h"') gSystem.Load('libAra.so') #load the simulation event library. You might get an error asking for the eventSim dictionry. To solve that, go to where you compiled AraSim, find that file, and copy it to where you set LD_LIBRARY_PATH. test = ROOT.TFile.Open("/fs/scratch/PAS0654/jorge/sim_results/default/AraOut.default_A2_c1_E610.txt.run9.root")#directory where the simulation files are reportPtr = ROOT.Report()#report pointer eventTree = test.Get("eventTree")#eventTree, from AraSim output files SimTree = test.Get("AraTree2") #AraTree2, from AraSim output files rawEvent = ROOT.UsefulAtriStationEvent() eventTree.SetBranchAddress("UsefulAtriStationEvent",ROOT.AddressOf(rawEvent)) SimTree.SetBranchAddress("report",ROOT.AddressOf(reportPtr))
import ROOT import os import pandas as pd import matplotlib.pyplot as plt import numpy as np from ROOT import gInterpreter, gSystem from ROOT import TChain, TSelector, TTree import scipy import sys import deDisperse_util as util import pyrex import warnings warnings.filterwarnings("ignore") #add headers from AraSim. Not sure if all of them are needed, and I'm lazy to check that. MAK SURE to change the location of the headers gInterpreter.ProcessLine('#include "/users/PAS0654/osu8354/AraSim/Position.h"') gInterpreter.ProcessLine('#include "/users/PAS0654/osu8354/AraSim/Report.h"') gInterpreter.ProcessLine('#include "/users/PAS0654/osu8354/AraSim/Detector.h"') gInterpreter.ProcessLine('#include "/users/PAS0654/osu8354/AraSim/Settings.h"') gSystem.Load( '/users/PAS0654/osu8354/AraSim/libAra.so' ) #load the simulation event library. You might get an error asking for the eventSim dictionry. To solve that, go to where you compiled AraSim, find that file, and copy it to where you set LD_LIBRARY_PATH. file_list = [] #Define an empty list for filename in os.listdir("/fs/scratch/PAS0654/jorge/sim_results/1E18FixedNnu" ): #Loop over desired directory if filename.startswith("AraOut.fixed_A2_1E19.txt.run%s.root" % (sys.argv[1])): #extension, .root in this case file_list.append( os.path.join("/fs/scratch/PAS0654/jorge/sim_results/1E18FixedNnu",
gr = ROOT.FFTtools.padWaveToLength(gr,2048) wfLength = gr.GetN() t = [] v = [] for kk in range(0,wfLength): t.append(gr.GetX()[kk]) v.append(gr.GetY()[kk]) del gr return np.array(t), np.array(v) def calculateSNR(t, v): peak = np.max(abs(v)) RMS = v.std() return peak/RMS gInterpreter.ProcessLine('#include "/users/PAS0654/osu8354/ARA_cvmfs/build/include/FFTtools.h"') gSystem.Load('libAraEvent.so') #load the simulation event library. You might get an error asking for the eventSim dictionry. To solve that, go to where you compiled AraSim, find that file, and copy it to where you set LD_LIBRARY_PATH. gSystem.Load("/users/PAS0654/osu8354/ARA_cvmfs/build/lib/libRootFftwWrapper.so") test = ROOT.TFile.Open("/fs/scratch/PAS0654/brian/L1/ARA02/1224/run_012559/event012559.root")#directory where the files are calibrator = ROOT.AraEventCalibrator.Instance() eventTree = test.Get("eventTree") rawEvent = ROOT.RawAtriStationEvent() eventTree.SetBranchAddress("event",ROOT.AddressOf(rawEvent)) totalEvents = eventTree.GetEntries() print('total events:', totalEvents) evt_num = [] fftArray = []
import os from tqdm import tqdm import ROOT from ROOT import gSystem, gInterpreter thispath = os.path.abspath(os.path.dirname(__file__)) gInterpreter.ProcessLine('#include "{0}/Ranger.h"'.format(thispath)) gInterpreter.ProcessLine('#include "{0}/LeafBuffer.h"'.format(thispath)) gSystem.Load(os.path.join(thispath, 'ranger.so')) class Ranger: def __init__(self, file): self.__ranger = ROOT.Ranger(file) def copy_tree(self, treename, dest='', branches='*', cut=''): """Copies a TTree to a new file using a branch selection and an optional cut""" self.__ranger.TreeCopy(treename, self.__construct_regex(branches), self.__parse_cut(cut), dest) def flatten_tree(self, treename, flat_branches, branches='*', cut='', dest=''): """Uses the leaf counter variable associated with the branches in flat_branches to reduce the dimensionality of these leaves. If multiple different leaf counters are used, they need to have the same contents.""" self.__ranger.FlattenTree(treename, self.__construct_regex(branches), self.__construct_regex(flat_branches),
import ROOT from ROOT import TGraph from ROOT import gInterpreter, gSystem import numpy as np import os, sys from matplotlib import pyplot as plt # custom lib import SNR_def as snr_def ROOT.gSystem.Load(os.environ.get('ARA_UTIL_INSTALL_DIR')+"/lib/libAraEvent.so") gInterpreter.ProcessLine('#include "'+os.environ.get('ARA_UTIL_INSTALL_DIR')+'/../misc_build/include/FFTtools.h"') #load data wf = np.loadtxt('example_interpolated_wf_A2_R1449_E452_Ch7.txt') # shape info # wf[:,0] -> time(ns) # wf[:,1] -> volt(mV) # 1 SNR from FFTtools # make Tgraph for uising ROOT.FFTtools.getWaveformSNR() ex_gr = TGraph(len(wf[:,0]), np.array(wf[:,0]), np.array(wf[:,1])) # test ROOT.FFTtools.getWaveformSNR() snr_ffttools = ROOT.FFTtools.getWaveformSNR(ex_gr) print('SNR from FFTtools:',snr_ffttools) # 2 SNR from python version of FFTtools(double check)
import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from src.classifier import Framework from samples import * import ROOT from ROOT import gInterpreter, gSystem gInterpreter.ProcessLine('#include "interface/JetInfo.h"') gInterpreter.ProcessLine('#include "interface/EventInfo.h"') gInterpreter.ProcessLine('#include "interface/VertexInfo.h"') gInterpreter.ProcessLine('#include "interface/JetPairInfo.h"') gInterpreter.ProcessLine('#include "interface/MuonInfo.h"') gInterpreter.ProcessLine('#include "interface/MuPairInfo.h"') gInterpreter.ProcessLine('#include "interface/EleInfo.h"') gInterpreter.ProcessLine('#include "interface/MetInfo.h"') gInterpreter.ProcessLine('#include "interface/MhtInfo.h"') gInterpreter.ProcessLine('#include "interface/GenParentInfo.h"') gInterpreter.ProcessLine('#include "interface/GenMuonInfo.h"') gInterpreter.ProcessLine('#include "interface/GenMuPairInfo.h"') gInterpreter.ProcessLine('#include "interface/GenJetInfo.h"') c = Framework() treePath = 'dimuons/tree' c.add_data_to_evaluate(SingleMu2017B.name, SingleMu2017B.path) c.add_data_to_evaluate(SingleMu2017C.name, SingleMu2017C.path) c.add_data_to_evaluate(SingleMu2017D.name, SingleMu2017D.path) c.add_data_to_evaluate(SingleMu2017E.name, SingleMu2017E.path) c.add_data_to_evaluate(SingleMu2017F.name, SingleMu2017F.path)
#!/usr/bin/env python # Ref: https://root-forum.cern.ch/t/wrapping-root-classes-for-python/21845/2 # Load the library and include the header file from ROOT import gInterpreter, gSystem gInterpreter.ProcessLine('#include "../include/classes.h"') gSystem.Load('../lib/libBabyMINDUnpack') # Try loading an existing file import ROOT infpn = '/cshare/vol2/users/shihkai/sample_code/siva/data_file/1September_16_MCR0_muons_2Gev_0pt2T_4trigg_0deg___NewStructure.root' tinf = ROOT.TFile.Open(infpn) tr_all = tinf.AllEvents # AllEvents is the tree name. # tr_all.Draw('fdEdz') # Then I can draw histograms of variables. for entry in tr_all: # Or loop through variables. # Regarding how to iterate a tree, the method is from here: https://root-forum.cern.ch/t/reading-a-ttree-branch-using-pyroot/29019 # print(entry.Event.GetNHits()) for hit in entry.Event.GetHits(): print(hit.GetView(), hit.GetRE(), hit.GetX(), hit.GetY(), hit.GetZ()) break # input('Press enter to continue.') # In python 3 raw_input is renamed to input.