CMS 3D CMS Logo

extractBaryCentre.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 from argparse import ArgumentParser
4 import logging
5 import ROOT
6 
8  def __init__(self, *args):
9  self.tfile = ROOT.TFile(*args)
10  def __enter__(self):
11  return self.tfile
12  def __exit__(self, type, value, traceback):
13  self.tfile.Close()
14 
15 def display_results(t_data, style='twiki'):
16  before = after = None
17  if (style == 'twiki'):
18  header_fmt = ' | '.join( ['{:^6s}'] + ['{:^9s}' ] * (len(t_data.keys())-1) )
19  row_fmt = ' | '.join( ['{:6d}' ] + ['{:9.6f}'] * (len(t_data.keys())-1) )
20  header_fmt = '| '+header_fmt+' |'
21  row_fmt = '| '+row_fmt +' |'
22  elif(style == 'latex'):
23  before = '\\begin{tabular}{' + 'c'*len(t_data.keys()) + '}'
24  after = '\\end{tabular}'
25  header_fmt = ' & '.join( ['{:^6s}'] + ['{:^9s}' ] * (len(t_data.keys())-1) ) + ' \\\\\n\\hline'
26  row_fmt = ' & '.join( ['{:6d}' ] + ['{:9.6f}'] * (len(t_data.keys())-1) ) + ' \\\\'
27  elif(style == 'csv'):
28  header_fmt = ', '.join( ['{:s}' ] * len(t_data.keys()) )
29  row_fmt = ', '.join( ['{:d}' ] + ['{:f}' ] * (len(t_data.keys())-1) )
30  else:
31  raise RuntimeError('Unknown style "%s" for table'%(style))
32 
33  if(before is not None): print(before)
34  print( header_fmt.format(*t_data.keys()) )
35  for i, run in enumerate(t_data['run']):
36  print(row_fmt.format(run, *[t_data[k][i] for k in t_data.keys() if not k == 'run']))
37  if(after is not None): print(after)
38 
39 
40 def main():
41  parser = ArgumentParser()
42  parser.add_argument('fname' , metavar='FILE')
43  parser.add_argument('-p', '--partition', default='BPIX', help='Tracker partition (e.g. BPIX, FPIX, BPIXLYR1, etc.). Default: %(default)s')
44  parser.add_argument('-l', '--list-content' , action='store_true', dest='list_content', help='List the contents of file and exit')
45  parser.add_argument( '--list-branches', action='store_true', help='List the branches of the tree and exit')
46  parser.add_argument('-t', '--type' , default='barycentre', choices=('barycentre', 'beamspot'), type=str.lower, help='Default: %(default)s')
47  parser.add_argument( '--label' , default=None, help='Additional label that is appended to the folder name (i.e. PixelBaryCentreAnalyzer by default)')
48  parser.add_argument( '--quality' , action='store_true', help='Read results with the WithPixelQuality flag (default: %(default)s)')
49  parser.add_argument('-s', '--style' , default='twiki', choices=('twiki', 'latex', 'csv'), type=str.lower, help='Table style for the output (default: %(default)s)')
50  parser.add_argument( '--loglevel' , metavar='LEVEL', default='WARNING', help='Level for the python logging module. Can be either a mnemonic string like DEBUG, INFO or WARNING or an integer (lower means more verbose).')
51 
52  args = parser.parse_args()
53  loglevel = args.loglevel.upper() if not args.loglevel.isdigit() else int(args.loglevel)
54  logging.basicConfig(format='%(levelname)s:%(module)s:%(funcName)s: %(message)s', level=loglevel)
55  logging.debug('args: %s', args)
56 
57 
58  folder = 'PixelBaryCentreAnalyzer' if not args.quality else 'PixelBaryCentreAnalyzerWithPixelQuality'
59  tree_name = 'PixelBarycentre' if args.type == 'barycentre' else 'BeamSpot'
60  if(args.label is not None):
61  tree_name += '_'+args.label
62  columns = ['run'] + [(args.partition if args.type=='barycentre' else 'BS')+'.'+coord for coord in ('x', 'y', 'z')]
63 
64  with TFileContext(args.fname) as tfile:
65  if(args.list_content):
66  list_content(tfile)
67  return 0
68 
69  tfolder = tfile.Get(folder)
70  if(not tfolder):
71  raise KeyError('Folder "%s" not found in "%s"' %(folder, args.fname))
72 
73  logging.debug('Opened folder "%s"', folder)
74  tree = tfolder.Get(tree_name)
75  if(not tree):
76  logging.error('Tree "%s" not found; content of file "%s":', tree_name, args.fname)
77  list_content(args.fname)
78  raise KeyError(tree_name)
79 
80  if(args.list_branches):
81  list_branches(tree, folder=folder)
82  return 0
83 
84  rdf = ROOT.RDataFrame(tree)
85  logging.info('Reading "%s"', tree_name)
86  results = rdf.AsNumpy(columns)
87 
88  display_results(results, style=args.style)
89 
90  return 0
91 
92 
93 def list_content(tfile):
94  for tfolder in tfile.GetListOfKeys():
95  for key in tfolder.ReadObj().GetListOfKeys():
96  obj = key.ReadObj()
97  print('%s\t%s/%s\t%d branches, %d entries' %(obj.ClassName(), tfolder.GetName(), key.GetName(), len(obj.GetListOfBranches()), obj.GetEntries()))
98 
99 
100 def list_branches(tree, folder_name=''):
101  branches = [b.GetName() for b in tree.GetListOfBranches()]
102  logging.info('Branches (%s/%s): %d', (folder_name, tree.GetName(), len(branches)))
103  print('\n'.join(branches))
104 
105 
106 if __name__ == '__main__':
107  exit(main())
def list_branches(tree, folder_name='')
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
static std::string join(char **cmd)
Definition: RemoteFile.cc:21
Definition: main.py:1
def __exit__(self, type, value, traceback)
if(threadIdxLocalY==0 &&threadIdxLocalX==0)
def display_results(t_data, style='twiki')
def exit(msg="")