Cicada  v1.2.1
Project 8 Processed-Data File Format Library
ReadKTOutputFile.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 '''
4 Name: ReadKTOutputFile
5 Author: MG
6 Date: 2018/05/10
7 Purpose:
8  Example of how to open and read a Katydid output file.
9  Can read
10 '''
11 
12 import CicadaPy
14 
15 from ROOT import TFile, TTreeReader, TTreeReaderValue
16 import sys
17 
18 def ReadKTOutputFile(filename,var,katydid=False,objectType="TMultiTrackEventData",name="multiTrackEvents:Event"):
19  '''
20  Read a ROOT file and returns specified content.
21  filename (str): name of the ROOT file
22  var (str/list): Variable to extract from the object
23  katydid (bool): Katydid (true) or Cicada (false) namespace
24  objectType (str): class name of the object to read
25  name (str:str): names of the tree and of the object to read, separated by a ":"
26  '''
27  # Open the ROOT file
28  file = TFile.Open(filename)
29  if not file:
30  raise FileNotFoundError("File {} does not exist".format(filename))
31  # Extract tree and object names
32  # names[0]: name of the tree
33  # names[1]: name of the object in the tree
34  names = name.split(":")
35  # Extract tree from file
36  tree = file.Get(str(names[0]))
37  # Create TTreeReader
38  treeReader = TTreeReader(tree)
39  # Create object TMultiTrackEventData to "point" to the object "Event" in the tree
40  if katydid:
41  import ROOT.Katydid as KT
42  else:
43  import ROOT.Cicada as KT
44  if hasattr(KT,objectType):
45  multiTrackEvents = TTreeReaderValue(getattr(KT,objectType))(treeReader, names[1])
46  else:
47  print("Couldn't find type <{}> in module; exiting!".format(objectType))
48  sys.exit(1)
49 
50  result = {}
51  if isinstance(var,list):
52  for key in var:
53  result.update({key:[]})
54  elif isinstance(var,str):
55  result.update({var: []})
56  else:
57  print("{} not a list or a string; exiting!".format(var))
58 
59  for var,_ in result.items():
60  # Analyze var to see if we are looking for a subTree
61  subArg = var.split(".")
62 
63  n=0
64  # Go through the events
65  if len(subArg)==1:
66  while treeReader.Next():
67  function = getattr(multiTrackEvents,"Get{}".format(subArg[0]))
68  result[var].append(function())
69  n+=1
70  else:
71  while treeReader.Next():
72  function = getattr(multiTrackEvents,"Get{}".format(subArg[0]))
73  obj = function()
74  subList = []
75  for i in range(multiTrackEvents.GetTracks().GetEntries()):
76  function = getattr(getattr(obj,"At")(i),"Get{}".format(subArg[1]))
77  subList.append(function())
78  result[var].append(subList)
79  n+=1
80  treeReader.Restart()
81  if n==0:
82  print("Error: no data found; wrong branch? or wrong namespace (Cicada/Katydid) -- maybe, try '-k'/add True as last argument?")
83  if len(result.keys())==1:
84  return result[list(result.keys())[0]]
85  return result
86 
87 if __name__ =="__main__":
88  print('\n P8 Katydid output file reader example\n')
89  import argparse
90  p = argparse.ArgumentParser(description='''
91  Katydid output file reader script
92  ''')
93  p.add_argument('-i','--input',
94  help='ROOT input file',
95  type=str)
96  p.add_argument('-b','--branch',
97  help='Branch to read in the TMultiTrackEventData object',
98  nargs='+',
99  default="StartTimeInAcq")
100  p.add_argument('-k','--katydid',
101  help='Flag stating Katydid namespace should be used instead of Cicada',
102  action='store_true',
103  required=False,
104  default=False)
105  p.add_argument('-t','--type',
106  help='Object Type to be read',
107  type=str,
108  required=False,
109  default="TMultiTrackEventData")
110  p.add_argument('-n','--name',
111  help='Object and Tree Name to be read, separated by a ":" (ex: multiTrackEvents:Event)',
112  type=str,
113  required=False,
114  default="multiTrackEvents:Event")
115  args = p.parse_args()
116 
117  result = ReadKTOutputFile(args.input, args.branch, katydid=args.katydid, objectType=args.type, name=args.name)
118  if isinstance(result,dict):
119  nElements=len(result[list(result.keys())[0]])
120  else:
121  nElements = len(result)
122  print("Found {} elements for {}".format(nElements,args.branch))
def loadLibraries(silence=False)
Definition: CicadaPy.py:30
def ReadKTOutputFile(filename, var, katydid=False, objectType="TMultiTrackEventData", name="multiTrackEvents:Event")