Example #1
0
def get_pos(event):  # start position of each particle

    a = TNtuple(
        "a", "a",
        "x:y:z:x2:y2:z2")  # creates ntuple to store the values of x y z

    mcpart = event.getCollection("MCParticle")
    for ding in mcpart:
        ptype = ding.getPDG()
        if ptype != 11 and ptype != -11:

            pos = ding.getVertex()
            end = ding.getEndpoint()

            x = pos[0]
            y = pos[1]
            z = pos[2]

            x2 = end[0]
            y2 = end[1]
            z2 = end[2]

            print x, "\t", y, "\t", z

            a.Fill(x, y, z, x2, y2, z2)

    return a
Example #2
0
def get_pos(event):  # start position of each particle

    # get a hit collection
    BCAL = event.getCollection("BeamCalHits")

    # get the cell ID encoding string from the collection parameters
    cellIdEncoding = BCAL.getParameters().getStringVal(
        EVENT.LCIO.CellIDEncoding)

    # define a cell ID decoder for the collection
    idDecoder = UTIL.BitField64(cellIdEncoding)
    for calhit in BCAL:

        # combine the two 32 bit cell IDs of the hit into one 64 bit integer
        cellID = long(calhit.getCellID0()
                      & 0xffffffff) | (long(calhit.getCellID1()) << 32)

        # set up the ID decoder for this cell ID
    idDecoder.setValue(cellID)

    # access the field information using a valid field from the cell ID encoding string
    print 'x:', idDecoder['x'].value()
    print 'y:', idDecoder['y'].value()
    # can put 'barrel' , 'layer' instead of 'x' and 'y' to get those values

    a = TNtuple("a", "cell", "layer")
Example #3
0
def make_graph(a, output):

    c1 = TCanvas("c1", "c1", 1000,
                 1000)  # Creates the canvas to draw the bar chart to.
    c1.SetGrid()  # Adds grid lines to canvas.

    leg = TLegend(0.7, 0.6, 0.95, 0.95)
    leg.AddEntry(a, "Start", "P")

    n0 = TNtuple("n0", "n0",
                 "x:y:z")  # creates ntuple to store the values of x y z
    n0.SetMarkerColor(0)
    n0.Fill(-4500, -4500, -5700)
    n0.Fill(4500, 4500, 5700)
    n0.Draw("x:y:z")

    #a.SetMarkerColor(1)
    #a.SetMarkerStyle(6)
    #a.Draw("x:y:z","","same") 				# Draws the histogram to the canvas.

    a.SetMarkerColor(2)
    a.SetMarkerStyle(6)
    a.Draw("x2:y2:z2", "", "same")  # Draws the histogram to the canvas.

    #leg.Draw()

    c1.Update()  # Makes the canvas show the histogram.

    img = ROOT.TImage.Create()  # creates image
    img.FromPad(c1)  # takes it from canvas
    img.WriteImage(
        output)  # Saves it to png file with this name in input file directory.

    return c1
Example #4
0
def make_ntup(file_name, tree_name, branches, outfile, n_events,
              new_tree_name):
    if new_tree_name == "":
        new_tree_name = tree_name

    print file_name

    # Get the event tree
    tree = TChain(tree_name)
    tree.Add(file_name)
    if not tree:
        print "Error: No tree named %s in %s" % (tree_name, file_name)
        sys.exit()

    # Check branches exist
    branches_avail = [x.GetName() for x in tree.GetListOfBranches()]
    for b in branches:
        if not b in branches_avail:
            print "Error branch '%s' not a branch in input tree" % (b)
            print "Branches available are: \n"
            print "\t".join(branches_avail)
            sys.exit()

    # output
    out_file = TFile(outfile, "RECREATE")
    nt = TNtuple(new_tree_name, "", ":".join(branches))

    if (n_events < 0):
        n_events = tree.GetEntries()

    # loop over events and fill the branches of new ntuple
    for index, entry in enumerate(tree):
        if index > n_events:
            break
        vals = array('f', [entry.__getattr__(b) for b in branches])
        nt.Fill(vals)

        if (index % 100000 == 0):
            print index, "/", n_events
    # Save
    out_file.cd()
    nt.Write()
    out_file.Close()

    print "Written %i entries of branch(es) '%s' \nto tree %s  \nin file %s" % (
        n_events, ":".join(branches), new_tree_name, outfile)
Example #5
0
def FillNTuple(tupname, data, names) : 
  """
    Create and fill ROOT NTuple with the data sample. 
      tupname : name of the NTuple
      data : data sample
      names : names of the NTuple variables
  """
  variables = ""
  for n in names : variables += "%s:" % n
  variables = variables[:-1]
  values = len(names)*[ 0. ]
  avalues = array.array('f', values)
  nt = TNtuple(tupname, "", variables)
  for d in data : 
    for i in range(len(names)) : avalues[i] = d[i]
    nt.Fill(avalues)
  nt.Write()
Example #6
0
def get_mom(event): # Each detector is a 'collection', the No. of Elements are the hits.

	k=0
	n = TNtuple("n", "n", "x:y:z") # creates ntuple to store the values of x y z
	mcpart = event.getCollection("MCParticle") # opens the collection
	nbin = mcpart.getNumberOfElements() # gets the number of hits on the beamcal
	for ding in mcpart: # for each hit in the beamcal

		pos = ding.getMomentum() # gets position in 3 vector array
		ptype = ding.getPDG()
		if ptype != 11 and ptype != -11:
			x = pos[0] # sets value from 3 vector array to single variables
			y = pos[1]
			z = pos[2]
			k+=1
			n.Fill(x,y,z) # fills the ntuple
	print k
	return n
Example #7
0
def get_pos(
    event
):  # Each detector is a 'collection', the No. of Elements are the hits.

    xcoord1 = []  # a list for each x coordinate
    ycoord1 = []
    zcoord1 = []

    n = TNtuple("n", "n",
                "x:y:z")  # creates ntuple to store the values of x y z
    BCAL = event.getCollection("BeamCalHits")  # opens the collection
    nbin = BCAL.getNumberOfElements()  # gets the number of hits on the beamcal
    for ding in BCAL:  # for each hit in the beamcal
        pos = ding.getPosition()  # gets position in 3 vector array
        x = pos[0]  # sets value from 3 vector array to single variables
        y = pos[1]
        z = pos[2]
        n.Fill(x, y, z)  # fills the ntuple

    return n
Example #8
0
def make_graph(n, output):
	

	c1 = TCanvas() # Creates the canvas to draw the bar chart to.
	c1.SetGrid() # Adds grid lines to canvas.

	n0 = TNtuple("n0", "n0", "x:y:z")
	n0.Fill(-0.1, -0.1, -1)
	n0.Fill(0.1, 0.1, 1)
	n0.Draw("x:y:z")

	n.SetMarkerColor(2)
	n.SetMarkerStyle(6)
	n.Draw("x:y:z","","same") 				# Draws the histogram to the canvas.
	c1.Update()					# Makes the canvas show the histogram.
    
	img = ROOT.TImage.Create()				# creates image
	img.FromPad(c1)							# takes it from canvas
	img.WriteImage(output)	# Saves it to png file with this name in input file directory.

	return c1
Example #9
0
def get_pos(
    event
):  # Each detector is a 'collection', the No. of Elements are the hits.
    xcoord1 = []
    ycoord1 = []
    zcoord1 = []
    nparts = 0  # counter for number of interesting particles

    n = TNtuple("n", "n", "x:y:z")  # makes the ntuple to be filled
    mcpart = event.getCollection("MCParticle")
    for ding in mcpart:
        if ding.getPDG() != 11 and ding.getPDG() != -11:  # id not e+ or e-
            pos = ding.getVertex()  # gets the start position as 3 vector array
            x = pos[0]  # assigns value from array to single variables
            y = pos[1]
            z = pos[2]
            n.Fill(x, y, z)  # fills the ntuple
            nparts += 1  # counts up for each particle
    print nparts

    return n
    def beginLoop(self):
        super(SimpleJetNTupler, self).beginLoop()
        self.file = TFile('/'.join([self.looperName, 'testJetsNT.root']),
                          'recreate')
        if self.cfg_ana.applyPFLooseId:
            from ROOT import PFJetIDSelectionFunctor
            self.isPFLooseFunc = PFJetIDSelectionFunctor(
                0, PFJetIDSelectionFunctor.LOOSE)
            ## Workaround: for some reason PyROOT does not bind nor PFJetIDSelectionFunctor(Jet)PFJetIDSelectionFunctor.getBitsTemplates
            from ROOT import pat
            self.isPFLooseFunc.bits = pat.strbitset()
            for i in "CHF", "NHF", "CEF", "NEF", "NCH", "nConstituents":
                self.isPFLooseFunc.bits.push_back(i)
            ## /Workaround
            self.isPFLoose = lambda x: self.isPFLooseFunc(
                x, self.isPFLooseFunc.bits)
        else:
            self.isPFLoose = lambda x: True

        self.myntuple = TNtuple(
            self.cfg_ana.ntupleName, self.cfg_ana.ntupleName,
            'genPt:recoPt:genEta:recoEta:genPhi:recoPhi:nvtx')
Paul Eugenio
PHZ4151C
Florida State University
April 2, 2019

"""

from __future__ import division, print_function
import numpy as np
from ROOT import TLorentzVector, TNtuple, TCanvas, TFile

rootFile = TFile("ntp.root", "RECREATE")


def f(x):
    return x**2


squares = TNtuple("sqntuple", "Squares", "x:x2")
sqCanvas = TCanvas("cc", "squares", 10, 10, 800, 600)
sqCanvas.Divide(1, 2)

for k in range(1, 10, 1):
    squares.Fill(k, f(k))

squares.Draw("x")
sqCanvas.cd(2)
squares.Draw("x2")

rootFile.Write()
from ROOT import TCanvas, TFile, TProfile, TNtuple, TH1F, TH2F from ROOT import gROOT, gBenchmark, gRandom, gSystem, Double
# Create a new canvas, and customize it.
c1 = TCanvas( 'c1', 'Dynamic Filling Example', 200, 10, 700, 500 ) c1.SetFillColor( 42 ) c1.GetFrame().SetFillColor( 21 ) 
c1.GetFrame().SetBorderSize( 6 ) c1.GetFrame().SetBorderMode( -1 )
# Create a new ROOT binary machine independent file. Note that this file may contain any kind of ROOT objects, histograms, 
# pictures, graphics objects, detector geometries, tracks, events, etc.. This file is now becoming the current directory.
hfile = gROOT.FindObject( 'py-hsimple.root' ) if hfile:
   hfile.Close() hfile = TFile( 'py-hsimple.root', 'RECREATE', 'Demo ROOT file with histograms' )
# Create some histograms, a profile histogram and an ntuple
hpx = TH1F( 'hpx', 'This is the px distribution', 100, -4, 4 ) hpxpy = TH2F( 'hpxpy', 'py vs px', 40, -4, 4, 40, -4, 4 ) hprof = 
TProfile( 'hprof', 'Profile of pz versus px', 100, -4, 4, 0, 20 ) ntuple = TNtuple( 'ntuple', 'Demo ntuple', 'px:py:pz:random:i' )
# Set canvas/frame attributes.
hpx.SetFillColor( 48 ) gBenchmark.Start( 'hsimple' )
# Initialize random number generator.
gRandom.SetSeed() rannor, rndm = gRandom.Rannor, gRandom.Rndm
# For speed, bind and cache the Fill member functions,
histos = [ 'hpx', 'hpxpy', 'hprof', 'ntuple' ] for name in histos:
   exec('%sFill = %s.Fill' % (name,name))
# Fill histograms randomly.
px, py = Double(), Double() kUPDATE = 1000 for i in range( 25000 ):
 # Generate random values.
   rannor( px, py )
   pz = px*px + py*py
   random = rndm(1)
 # Fill histograms.
   hpx.Fill( px )
   hpxpy.Fill( px, py )
   hprof.Fill( px, pz )
   ntuple.Fill( px, py, pz, random, i )
 # Update display every kUPDATE events.
   if i and i%kUPDATE == 0:
Example #13
0
def get_pos(
    event
):  # Each detector is a 'collection', the No. of Elements are the hits.
    a = TNtuple("a", "a",
                "x:y:z")  # creates ntuple to store the values of x y z
    b = TNtuple("b", "b",
                "x:y:z")  # creates ntuple to store the values of x y z
    c = TNtuple("c", "c",
                "x:y:z")  # creates ntuple to store the values of x y z
    d = TNtuple("d", "d",
                "x:y:z")  # creates ntuple to store the values of x y z
    e = TNtuple("e", "e",
                "x:y:z")  # creates ntuple to store the values of x y z
    f = TNtuple("f", "f",
                "x:y:z")  # creates ntuple to store the values of x y z
    g = TNtuple("g", "g",
                "x:y:z")  # creates ntuple to store the values of x y z
    h = TNtuple("h", "h",
                "x:y:z")  # creates ntuple to store the values of x y z
    i = TNtuple("i", "i",
                "x:y:z")  # creates ntuple to store the values of x y z
    j = TNtuple("j", "j",
                "x:y:z")  # creates ntuple to store the values of x y z
    k = TNtuple("k", "k",
                "x:y:z")  # creates ntuple to store the values of x y z
    l = TNtuple("l", "l",
                "x:y:z")  # creates ntuple to store the values of x y z

    ECALB = event.getCollection("EcalBarrelHits")
    for ding in ECALB:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        a.Fill(x, y, z)

    ECALE = event.getCollection("EcalEndcapHits")
    for ding in ECALE:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        b.Fill(x, y, z)

    HCALB = event.getCollection("HcalBarrelHits")
    for ding in HCALB:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        c.Fill(x, y, z)

    HCALE = event.getCollection("HcalEndcapHits")
    for ding in HCALE:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        d.Fill(x, y, z)

    LUMICAL = event.getCollection("LumiCalHits")
    for ding in LUMICAL:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        e.Fill(x, y, z)

    MUONB = event.getCollection("MuonBarrelHits")
    for ding in MUONB:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        f.Fill(x, y, z)

    MUONE = event.getCollection("MuonEndcapHits")
    for ding in MUONE:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        g.Fill(x, y, z)

    SITB = event.getCollection("SiTrackerBarrelHits")
    for ding in SITB:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        h.Fill(x, y, z)

    SITE = event.getCollection("SiTrackerEndcapHits")
    for ding in SITE:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        i.Fill(x, y, z)

    SITF = event.getCollection("SiTrackerForwardHits")
    for ding in SITF:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        j.Fill(x, y, z)

    SIVB = event.getCollection("SiVertexBarrelHits")
    for ding in SIVB:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        k.Fill(x, y, z)

    SIVE = event.getCollection("SiVertexEndcapHits")
    for ding in SIVE:
        pos = ding.getPosition()
        x = pos[0]
        y = pos[1]
        z = pos[2]
        l.Fill(x, y, z)

    return a, b, c, d, e, f, g, h, i, j, k, l
Example #14
0
Exercise 10 Part 3
"""

from __future__ import division, print_function
import numpy as np
from ROOT import TLorentzVector, TNtuple, TCanvas, TFile, TBrowser
#
Beam = TLorentzVector()
PiPlus = [TLorentzVector(), TLorentzVector()]
PiMinus = TLorentzVector()
Target = TLorentzVector(0, 0, 0, 0.938)
nEvents = 0
nPiPlus = 0

IMspectra = TNtuple(
    "imntuple", "Invariant Mass Spectra",
    "npip1pip2pim:pip1pip2pim:pip1pim:pip2pim:pip1pip2:npip1:npip2:npim")

with open("n3pi.dat", "r") as dataFile:
    # open file and read in ascii events line-by-line
    # the line will contain either the number of particles which indicates start of an event
    # or the line contains particle information: id charge Px Py Pz E
    #

    rootFile = TFile("imNtp.root", "RECREATE")

    for line in dataFile:
        word = line.split()  # split line into a list of words
        value = int(word[0])
        if value == 4:
            nPiPlus = 0
estNames = {
    'Signif': 'expected significance',
    'SoverB': 'S/B',
    'S': 'expected signal',
    'B': 'expected background',
    'EffAccPrompt': '(Acc#times#font[152]{e})_{prompt}',
    'EffAccFD': '(Acc#times#font[152]{e})_{FD}',
    'fPrompt': '#it{f}_{ prompt}^{ fc}',
    'fFD': '#it{f}_{ FD}^{ fc}'
}

varsName4Tuple = (
    ':'.join(cutVars) +
    ':PtMin:PtMax:ParCutMin:ParCutMax:EffAccPromptError:EffAccFDError:SError:BError'
    ':SignifError:SoverBError:' + ':'.join(estNames.keys()))
tSignif = TNtuple('tSignif', 'tSignif', varsName4Tuple)

totSets = [1 for _ in enumerate(ptMaxs)]

for iPt, _ in enumerate(ptMaxs):
    for cutRange in cutRanges[iPt]:
        totSets[iPt] *= len(cutRange)
print(f'Total number of sets per pT bin: {totSets}')

SetGlobalStyle(padleftmargin=0.12,
               padrightmargin=0.2,
               padbottommargin=0.15,
               padtopmargin=0.075,
               titleoffset=1.,
               palette=kRainBow,
               titlesize=0.06,
Example #16
0
jsonfile=sys.argv[1]
wdir = "lumis"

cmd=['lumiCalc.py -n 0.0429 -c frontier://LumiProd/CMS_LUMI_PROD -r ',' -o ','.csvt lumibyls']

a={}        
with open(jsonfile) as f:
    a = json.load(f)
    f.close()

if not os.path.isdir(wdir):
    os.system('mkdir '+wdir)

f = TFile(wdir+'/lumis.root','recreate')
ntuple = TNtuple('ntuple','data from ascii file','run:ls:lumiDelivered:lumiReported')

for run, lumis in a.iteritems():
    fullcmd=cmd[0]+run+cmd[1]+wdir+'/'+run+cmd[2]
    print 'Get luminosity information for run '+run
    os.system(fullcmd)
    rf=open(wdir+'/'+run+'.csvt','r')
    crf=csv.reader(rf)
    crf.next()
    for row in crf:
        ntuple.Fill(int(row[0]),int(row[1]),float(row[2]),float(row[3]))
    rf.close()
    os.system('rm '+wdir+'/'+run+'.csvt')

f.Write()
f.Close()
    def CreateTuple(self):

        return TNtuple(
            self.name, self.name,
            "{0}_MM:{0}_PT:{0}_Y:{0}_Z:{0}_DV:{0}_dZ:{0}_tZ:nVeloClusters:runNumber"
            .format(self.mother_leaf))
Example #18
0
import zmq
import signal
import time

from ROOT import TCanvas, TH1F, TSlider, THttpServer, TFile, TNtuple

###
title = "LTC2983 - channel 2 - rejection 50 Hz - 5 cm cable - ground floor"
channel = "CH2"
###

timestr = time.strftime("%Y%m%d-%H%M%S")
filename = str("LTC2983-" + channel + "-" + timestr + ".root")

f = TFile(filename, "recreate")
ntuple = TNtuple("nt", "samples", 's')
#c1 = TCanvas("c1","LTC2983 canvas",200,10,700,500)

#ch2plot = TH1F(channel, title, 20, -5, 5)
ch2plot = TH1F(channel, title, 1600, -400, 400)
ch2plot.GetXaxis().SetTitle("uV")
ch2plot.SetOption("B")
ch2plot.SetFillColor(46)


def terminate(signum, frame):
    print("Bye !")
    f.Write()
    sys.exit(0)

Example #19
0
def main(argv=None):
    start = time.time()

    # ROOT batch mode
    ROOT.gROOT.SetBatch(1)
    '''
    # ============================================================
    # ArgumentParser
    # ============================================================
    parser = argparse.ArgumentParser(description='Cosmic Tracks')
    parser.add_argument("config_file")
    parser.add_argument("data_file",        nargs="+")
    parser.add_argument("-o", "--out_path")
    parser.add_argument("-i", "--uid",      type=int,            default=0,              help="Unique identifier used in output files.")
    parser.add_argument("-n", "--max_evts", type=int,            default=0, metavar="N", help="Stop after %(metavar)s events.")
    parser.add_argument("-n",               type=int,            default=0, metavar="N", help="Stop after %(metavar)s spills.")
    parser.add_argument("-s", "--seed",     type=int,                                    help="Set the RNG seed.")
    parser.add_argument("-m", "--measure",  action="store_true",                         help="Measure rho, phi and doca for each gamma and fill into histogram.")
    parser.add_argument("-a", "--analyse",  action="store_true",                         help="Run analysis.")
    parser.add_argument("-d", "--display",  action="store_true",                         help="Save event display CSVs.")
    parser.add_argument("-D", "--debug",    action="store_true",                         help="Only one event per spill, fixed vertex position.")
    args = parser.parse_args(argv)
    '''

    # ============================================================
    # Set paths
    # ============================================================
    datapath = '/data/SingleModule_Nov2020/LArPix/dataRuns/rootTrees/combined_with_light'
    print(' datapath:   ', datapath)

    outputpath = '/home/lhep/PACMAN/larpix-analysis/lightCharge_anticorrelation'
    print(' outputpath: ', outputpath)

    files = sorted(
        [os.path.basename(path) for path in glob.glob(datapath + '/*.root')])
    print(' datafiles:  ')
    for f in files:
        print('              ', f)

    # ============================================================
    # Define voxelisation
    # ============================================================
    n_voxels_x = 70
    n_voxels_y = 70
    n_voxels_z = 70
    pitch_x = 4.434
    pitch_y = 4.434
    pitch_z = 4.434
    x_min = -pitch_x * n_voxels_x / 2.  #155.19
    x_max = pitch_x * n_voxels_x / 2.  #155.19
    y_min = -pitch_y * n_voxels_y / 2.  #155.19
    y_max = pitch_y * n_voxels_y / 2.  #155.19
    #z_min = - pitch_z * n_voxels_z/2. #155.19
    #z_max =   pitch_z * n_voxels_z/2. #155.19
    #y_min = -155.19
    #y_max = 155.19
    z_min = 0
    z_max = 400

    # ============================================================
    # Input tree
    # ============================================================
    #inputFileName = (str(args.data_file)[34:])[:-7]   # excludes ending .root
    for file_number in range(len(files)):

        # Only process specific file(s)
        #if files[file_number] != 'datalog_2020_11_29_12_22_02_CET_evd.h5':
        #    continue

        #if not (file_number >= 0 and file_number < 10):
        #    continue

        inputFileName = files[file_number]

        print(' -------------------------------------- ')
        print(' Processing file', inputFileName)
        outFileName = inputFileName[:-7] + '.root'

        input_tree = ROOT.TChain("t_out", "t_out")
        #for root_file in config["data_files"]:
        #    input_tree.Add(root_file)
        #input_tree.Add( "/path/to.root" )
        input_tree.Add(datapath + '/' + inputFileName)

        #not_used_files = [13,32,50,61,66,77,81,86,89,92,94,97,99]
        #print " Do not use files with numbers in {:} " .format(not_used_files)

        # Define if plots are made or not
        make_plots = True
        if make_plots:
            plot_folder = inputFileName[16:-5]
            os.system('rm -rf plots/' + str(plot_folder))
            os.system('mkdir plots/' + str(plot_folder))

        # Turn on all branches
        input_tree.SetBranchStatus("*", 1)

    # Define Histograms / NTuples
    # ---------------------------------------------------------
    makePlots = True
    h1_trLength = TH1F('h1_trLength', ' ; Track length [mm] ; Entries [-]',
                       150, 0, 500)
    h2_trLength_vs_nHits = TH2F(
        'h2_trLength_vs_nHits',
        ' ; Track Length [mm] ; Number of Hits [-] ; Entries [-]', 100, 0, 500,
        100, 0, 500)
    h3_event_hits = TH3F('h3_event_hits', ' ; x ; y; z', 70, -155, 155, 70,
                         -155, 155, 100, -300, 3000)
    ntuple = TNtuple('ntuple', 'data from ascii file', 'x:y:z:cont')
    plot4d = TH3F('h3_ev_hits', ' ; x ; y; z', 70, -155.19, 155.19, 70,
                  -155.19, 155.19, 200, -500, 1500)

    # Make track selection
    # ---------------------------------------------------------
    # TODO: Make 3D histogram to test selection goodness
    # Event with only 1 track (right?)

    # Analyse input tree
    # ---------------------------------------------------------
    n_tracks = input_tree.GetEntries()
    print(' n_tracks: ', n_tracks)

    x_min = 100
    x_max = -100
    y_min = 100
    y_max = -100
    z_min = 100
    z_max = -100

    # Loop over all tracks in input_tree
    for track_id in range(n_tracks):
        input_tree.GetEntry(track_id)

        print(' Processing track', track_id, 'of', n_tracks, '...')

        if track_id > 5:
            break

        #print(' t_eventID:     ', input_tree.t_eventID)
        #print(' t_trackID:     ', input_tree.t_trackID)
        #print(' t_event_q:     ', input_tree.t_event_q)
        #print(' t_track_q:     ', input_tree.t_track_q)
        #print(' t_event_nhits: ', input_tree.t_event_nhits)
        #print(' t_track_nhits: ', input_tree.t_track_nhits)

        h1_trLength.Fill(input_tree.t_track_length)
        h2_trLength_vs_nHits.Fill(input_tree.t_track_length,
                                  input_tree.t_track_nhits)

        # Get all hits in the event
        voxels = np.zeros((n_voxels_x, n_voxels_y, n_voxels_z))

        for hit in range(10):  #input_tree.t_event_nhits):
            if input_tree.t_event_hits_x[hit] < x_min:
                x_min = input_tree.t_event_hits_x[hit]
            if input_tree.t_event_hits_x[hit] > x_max:
                x_max = input_tree.t_event_hits_x[hit]
            if input_tree.t_event_hits_y[hit] < y_min:
                y_min = input_tree.t_event_hits_y[hit]
            if input_tree.t_event_hits_y[hit] > y_max:
                y_max = input_tree.t_event_hits_y[hit]
            if input_tree.t_event_hits_z[hit] < z_min:
                z_min = input_tree.t_event_hits_z[hit]
            if input_tree.t_event_hits_z[hit] > z_max:
                z_max = input_tree.t_event_hits_z[hit]

            #print(' hit: ', hit, ' \t x: ', input_tree.t_event_hits_x[hit], '\t y: ', input_tree.t_event_hits_y[hit], ' \t z: ', input_tree.t_event_hits_z[hit])

            voxel_x = math.floor((input_tree.t_event_hits_x[hit] +
                                  (pitch_x * (n_voxels_x) / 2.)) / pitch_x)
            voxel_y = math.floor((input_tree.t_event_hits_y[hit] +
                                  (pitch_y * (n_voxels_y) / 2.)) / pitch_y)
            voxel_z = math.floor((input_tree.t_event_hits_z[hit] +
                                  (pitch_z * (n_voxels_z) / 2.)) / pitch_z)

            #print(' voxel_x: ', voxel_x, ' \t voxel_y: ', voxel_y, ' \t voxel_z: ', voxel_z)
            if voxel_x < n_voxels_x and voxel_y < n_voxels_y and voxel_z < n_voxels_z:
                voxels[voxel_x][voxel_y][voxel_z] += input_tree.t_event_hits_q[
                    hit]
            # TODO: make under- and overflow voxel for every coordinate

            h3_event_hits.Fill(input_tree.t_event_hits_x[hit],
                               input_tree.t_event_hits_y[hit],
                               input_tree.t_event_hits_z[hit],
                               input_tree.t_event_hits_q[hit])

        for vox_x in range(n_voxels_x):
            vox_x_middle = x_min + (vox_x + 0.5) * pitch_x
            for vox_y in range(n_voxels_y):
                vox_y_middle = y_min + (vox_y + 0.5) * pitch_y
                for vox_z in range(n_voxels_z):
                    vox_z_middle = z_min + (vox_z + 0.5) * pitch_z
                    if voxels[vox_x][vox_y][vox_z] > 0:
                        ntuple.Fill(vox_x_middle, vox_y_middle, vox_z_middle,
                                    voxels[vox_x][vox_y][vox_z])
                        #h3_event_hits.Fill(vox_x_middle,vox_y_middle,vox_z_middle,voxels[vox_x][vox_y][vox_z])

        if (track_id % 2 == 0):
            now = time.time()
            print(' Processed', math.floor(track_id * 100 / n_tracks), 'of',
                  n_tracks, 'tracks. \t Elapsed time:', (now - start),
                  ' seconds ... \r')

    print(' x_min: ', x_min)
    print(' x_max: ', x_max)
    print(' y_min: ', y_min)
    print(' y_max: ', y_max)
    print(' z_min: ', z_min)
    print(' z_max: ', z_max)

    c0 = ROOT.TCanvas()
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetOptTitle(0)
    ntuple.Draw('x:y:z:cont>>plot4d', '', 'COLZ')
    #plot4d.SetLabelSize(0.5)
    #plot4d.SetMarkerSize(300)
    #ntuple.SetMarkerSize(300)
    #ntuple.SetMarkerColor(2)
    #ntuple.SetFillColor(38)
    #h3_event_hits.Draw("COLZ")
    c0.Print('test.png')

    # Make plots
    # ---------------------------------------------------------
    if makePlots:
        plot_h1_trLength(h1_trLength, 'h1_trLength', plot_folder)
        plot_h2_trLength_vs_nHits(h2_trLength_vs_nHits, 'h2_trLength_vs_nHits',
                                  plot_folder)
        plot_h3_event_hits(h3_event_hits, 'h3_event_hits', plot_folder)
Example #20
0
"""
   Build ROOT Ntuple from other source.   
   This program reads the `aptuple.txt' file row by row, then creates
   the Ntuple by adding row by row.
"""

import sys, string
from ROOT import TFile, TNtuple

ifn = 'aptuple.txt'
ofn = 'aptuple.root'

print 'opening file', ifn, '...'
infile = open('aptuple.txt', 'r')
lines = infile.readlines()
title = lines[0]
labels = string.split(lines[1])

print 'writing file', ofn, '...'
outfile = TFile(ofn, 'RECREATE', 'ROOT file with an NTuple')
ntuple = TNtuple('ntuple', title, string.join(labels, ':'))

for line in lines[2:]:
    words = string.split(line)
    row = map(float, words)
    apply(ntuple.Fill, row)

outfile.Write()

print 'done'
Example #21
0
#!/usr/bin/env python
# Example taken from https://root.cern.ch/how/how-write-ttree-python
# and modified to run...
"""
Creates a simple ROOT file with a tree containing a branch with a large array.

"""
from ROOT import TFile, TNtuple
from array import array

f = TFile('TNtuple.root', 'recreate')
t = TNtuple('n1', 'ntuple with 3 columes', "x:y:z")

x = array('i', [0])
y = array('f', [0])
z = array('d', [0])

for i in range(100):
    x[0] = i
    y[0] = i + i / 13
    z[0] = i + i / 17
    t.Fill(x[0], y[0], z[0])
f.Write()
f.Close()
Example #22
0
        if opt=='-h':
            print_usage()
            sys.exit(0)

if len(remainder)!=2:
    print_usage()
    sys.exit(0)

outfile = remainder[0]
inputfile = remainder[1]

gROOT.Reset()

rootfile = TFile(outfile + ".root","RECREATE")

eleBeamNtuple = TNtuple("eleBeamNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")
ApNtuple = TNtuple("ApNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")
RhoNtuple = TNtuple("RhoNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")
eleRecoilNtuple = TNtuple("eleRecoilNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")
WRecoilNtuple = TNtuple("WRecoilNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")
posDecayNtuple = TNtuple("posDecayNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")
eleDecayNtuple = TNtuple("eleDecayNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")
PionNtuple = TNtuple("PionNtuple","data from lhefile file","PID:Px:Py:Pz:E:m")

LHEfile = open(inputfile,"r")
lines = LHEfile.readlines()
readEvent = False
nPart = 0
nEvents = 0
for line in lines:
    if(line == "<mgrwt>\n"): readEvent = False
Example #23
0
    def CreateTuple(self):

        return TNtuple(
            self.name, self.name, "MM:PT:Y:Z:DV:dZ:tZ"
            ":plusPIDmu:minusPIDmu:plusPIDK:minusPIDK"
            ":Hcal:Ecal:nVeloClusters")
def main():
    """
    Creates a simple summary of the ROI for fast calibration.
    """
    fIn = TFile.Open(FLAGS.noPUFile, 'READ')
    fOut = TFile(FLAGS.outpath, 'RECREATE')

    varnames  = ['genen', 'geneta', 'genphi']
    for i in range(1,NREG+1):
        varnames += ['en_sr{}_ROI'.format(i), 
                     'noise_sr{}_ROI'.format(i)]
        for idet in range(1,NSUBDETS+1):
            varnames += ['en_sr{}_det{}'.format(i,idet), 
                         'noise_sr{}_det{}'.format(i,idet)]
        for il in range(1,NLAYERS+1):
            varnames += ['en_sr{}_layer{}'.format(i,il), 
                         'noise_sr{}_layer{}'.format(i,il)]
    output_tuples = TNtuple('summary','summary',':'.join(varnames))
        
    tree = fIn.Get('an_mask/CEE_HEF_HEB')
    for t in tree:
        #define the ROIs
        roiList={}
        for ir in range(0,t.ROIs.size()):
            if t.ROIs[ir].pdgid() < 0 and t.ROIs[ir].pdgid() != -211: 
                continue
            roiList[ir] = ROISummary(t.ROIs[ir].p4(), Nlayers=NLAYERS, PartType='Pion')

        for h in t.Hits:
            roiIdx  = h.associatedROI()
            rid     = t.ROIs[roiIdx].pdgid()
            roiKey  = roiIdx if rid>0 or rid==-211 else abs(rid)-1
            mipflag = True
            en      = h.en(mipflag)
            subdet  = h.subdet()
            layer   = int(h.layerId()) #originally it is long
            isNoise = True if rid<0 and rid!=-211 else False
            regIdx  = h.signalRegion()
            roiList[roiKey].AddHit(en=en, layer=layer, subdet=subdet, isNoise=isNoise, regIdx=regIdx)

        for r in roiList:
            varvals = []
            genP4 = roiList[r].genP4
            varvals += [genP4.E(),genP4.Eta(),genP4.Phi()]

            for ireg in range(1,NREG+1):
                recP4 = roiList[r].RecoP4(ireg)
                assert(np.isclose(recP4.E(), ( roiList[r].SubdetEnergyDeposited(ireg, 1) + 
                                               roiList[r].SubdetEnergyDeposited(ireg, 2) + 
                                               roiList[r].SubdetEnergyDeposited(ireg, 3) ) ))
                noiseROI = roiList[r].NoiseInROI(ireg)
                varvals += [recP4.E(),noiseROI]
                for idet in range(1,NSUBDETS+1):
                    recEnSubdet = roiList[r].SubdetEnergyDeposited(ireg, idet)
                    noiseSubdet = roiList[r].SubdetNoiseDeposited(ireg, idet)
                    varvals += [recEnSubdet, noiseSubdet]
                for il in range(1,NLAYERS+1):
                    recEn = roiList[r].RecoEnergyDeposited(ireg, il)
                    noiseLayer = roiList[r].NoiseInLayer(ireg, il)
                    varvals += [recEn, noiseLayer]

            output_tuples.Fill(array.array("f", varvals))
    fOut.cd()
    fOut.Write()
    fOut.Close()
Example #25
0
def LeCroy2Root(directory, outputRootFile):
    masterFile = TFile(outputRootFile, "recreate")

    print("listing files...")
    filesPerChannel = listFilesPerChannel(directory)
    ## se rellena el ultimo canal en 0:
    print len(filesPerChannel)
    nMC = len(
        filesPerChannel[0])  # number of available measurement per channel

    for i in range(4 - len(filesPerChannel)):
        filesPerChannel.append([0] * nMC)

    #### Get time from CHANNEL n #######################
    TimeNch = 1
    ########################################

    nMC = len(
        filesPerChannel[0])  # number of available measurement per channel

    # formar la tupla con las columnas necesarias:
    # measuresLabels = "event:time:C1:C2:C3:C4"
    measuresLabels = "event:time:C1:C2:C3"

    tup = TNtuple("osc", "LeCroy Readings", measuresLabels)

    readingGroup = []

    print("loading data..." + str(nMC))

    # para cada frame
    for i in range(nMC):
        # obtener cada canal
        for j in range(len(filesPerChannel)):
            if (filesPerChannel[j][i] == 0):
                readingGroup.append([])
#               print "channel: " + str(j) + " empty"
            else:
                #               print "channel: " + str(j) + " ok"
                #               print directory+filesPerChannel[j][i]
                readingGroup.append(readTrc(directory + filesPerChannel[j][i]))

        largos = []
        for j in range(len(readingGroup)):
            if (not (len(readingGroup[j]) in largos)):
                if (len(readingGroup[j]) != 0):
                    largos.append(len(readingGroup[j][0]))
        n_data = max(largos)
        for j in range(len(readingGroup)):
            if (len(readingGroup[j]) == 0):
                x_data = [0] * n_data
                y_data = [0] * n_data
                d_data = [0] * n_data
                readingGroup[j] = [x_data, y_data, d_data]

        # luego, generar listas a cargar a la tupla
        event = i
        for [time, c1, c2,
             c3] in zip(readingGroup[TimeNch - 1][0], readingGroup[0][1],
                        readingGroup[1][1], readingGroup[2][1]):
            tup.Fill(event, time, c1, c2, c3)


#        for [time,c1,c2,c3,c4] in zip(readingGroup[TimeNch-1][0], readingGroup[0][1], readingGroup[1][1], readingGroup[2][1], readingGroup[3][1]):	tup.Fill(event,time,c1,c2,c3,c4)

#        for [time,c1] in zip(readingGroup[0][0], readingGroup[0][1]):
#            tup.Fill(event,time,c1)

#        for [time,c2,c3] in zip(readingGroup[0][0], readingGroup[0][1], ):
#            tup.Fill(event,time,c2,c3)

        readingGroup = []
        if (int((float(i * 100) / nMC) * 100) % 100 == 0):
            sys.stdout.write(str(float(i * 100) / nMC) + "%" + "\r")
            sys.stdout.flush()

    tup.Write("", tup.kOverwrite)
    masterFile.Close()
    sys.stdout.write("\n")
	def initNtuple(self, labels):
		self.ntuple  = TNtuple( 'ntuple', ' nuStorm source', ':'.join( labels ) )
		if self.__Validated__: print ("ntuple is ", self.ntuple)
		return
Example #27
0
def make_graph(a, b, c, d, e, f, g, h, i, j, k, l, output):

    c1 = TCanvas("c1", "c1", 800,
                 800)  # Creates the canvas to draw the bar chart to.
    c1.SetGrid()  # Adds grid lines to canvas.

    leg = TLegend(0.7, 0.6, 0.95, 0.95)
    leg.AddEntry(a, "EcalBarrelHits", "P")
    leg.AddEntry(b, "EcalEndcapHits", "P")
    leg.AddEntry(c, "HcalBarrelHits", "P")
    leg.AddEntry(d, "HcalEndcapHits", "P")
    leg.AddEntry(e, "LumiCalHits", "P")
    leg.AddEntry(f, "MuonBarrelHits", "P")
    leg.AddEntry(g, "MuonEndcapHits", "P")
    leg.AddEntry(h, "SiTrackerBarrelHits", "P")
    leg.AddEntry(i, "SiTrackerEndcapHits", "P")
    leg.AddEntry(j, "SiTrackerForwardHits", "P")
    leg.AddEntry(k, "SiVertexBarrelHits", "P")
    leg.AddEntry(l, "SiVertexEndcapHits", "P")

    n0 = TNtuple("n0", "n0",
                 "x:y:z")  # creates ntuple to store the values of x y z
    n0.SetMarkerColor(0)
    n0.Fill(-4500, -4500, -5700)
    n0.Fill(4500, 4500, 5700)
    n0.Draw("x:y:z")

    a.SetMarkerColor(1)
    a.SetMarkerStyle(6)
    a.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    b.SetMarkerColor(2)
    b.SetMarkerStyle(6)
    b.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    c.SetMarkerColor(3)
    c.SetMarkerStyle(6)
    c.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    d.SetMarkerColor(4)
    d.SetMarkerStyle(6)
    d.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    e.SetMarkerColor(5)
    e.SetMarkerStyle(6)
    e.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    f.SetMarkerColor(6)
    f.SetMarkerStyle(6)
    f.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    g.SetMarkerColor(7)
    g.SetMarkerStyle(6)
    g.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    h.SetMarkerColor(8)
    h.SetMarkerStyle(6)
    h.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    i.SetMarkerColor(9)
    i.SetMarkerStyle(6)
    i.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    j.SetMarkerColor(30)
    j.SetMarkerStyle(6)
    j.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    k.SetMarkerColor(40)
    k.SetMarkerStyle(6)
    k.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    l.SetMarkerColor(28)
    l.SetMarkerStyle(6)
    l.Draw("x:y:z", "", "same")  # Draws the histogram to the canvas.

    leg.Draw()

    c1.Update()  # Makes the canvas show the histogram.

    img = ROOT.TImage.Create()  # creates image
    img.FromPad(c1)  # takes it from canvas
    img.WriteImage(
        output)  # Saves it to png file with this name in input file directory.

    return c1
Example #28
0
 def BookNTuple(self, title, vals):
     "Book a TNtuple."
     self.ntuple = TNtuple(title, title, ':'.join(vals))
     return
Example #29
0
# Create a new ROOT binary machine independent file.
# Note that this file may contain any kind of ROOT objects, histograms,
# pictures, graphics objects, detector geometries, tracks, events, etc..
# This file is now becoming the current directory.

hfile = gROOT.FindObject('hsimple.root')
if hfile:
    hfile.Close()
hfile = TFile('hsimple.root', 'RECREATE', 'Demo ROOT file with histograms')

# Create some histograms, a profile histogram and an ntuple
hpx = TH1F('hpx', 'This is the px distribution', 100, -4, 4)
hpxpy = TH2F('hpxpy', 'py vs px', 40, -4, 4, 40, -4, 4)
hprof = TProfile('hprof', 'Profile of pz versus px', 100, -4, 4, 0, 20)
ntuple = TNtuple('ntuple', 'Demo ntuple', 'px:py:pz:random:i')

# Set canvas/frame attributes.
hpx.SetFillColor(48)

gBenchmark.Start('hsimple')

# Initialize random number generator.
gRandom.SetSeed()
gauss, rndm = gRandom.Gaus, gRandom.Rndm

# For speed, bind and cache the Fill member functions,
histos = ['hpx', 'hpxpy', 'hprof', 'ntuple']
for name in histos:
    exec '%sFill = %s.Fill' % (name, name)
Example #30
0
##
## \macro_output
## \macro_code
##
## \author Wim Lavrijsen

import sys, os
from ROOT import TFile, TNtuple, TROOT

ifn = os.path.join(str(TROOT.GetTutorialDir()), 'pyroot', 'aptuple.txt')
ofn = 'aptuple.root'

print('opening file %s ...' % ifn)
infile = open(ifn, 'r')
lines = infile.readlines()
title = lines[0]
labels = lines[1].split()

print('writing file %s ...' % ofn)
outfile = TFile(ofn, 'RECREATE', 'ROOT file with an NTuple')
ntuple = TNtuple('ntuple', title, ':'.join(labels))

for line in lines[2:]:
    words = line.split()
    row = map(float, words)
    ntuple.Fill(*row)

outfile.Write()

print('done')