ATLAS Offline Software
SortedCollectionCreator.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
2 
3 __author__ = "Marcin Nowak"
4 __doc__ = """
5 Create a sorted collection of Event references from a set of Athnea files containing EventInfoTags
6 (or from other compatible APR Event collections)
7 """
8 
9 from CollectionUtilities.GetCollectionType import getCollectionType
10 
11 
13  """Creates a sorted (APR) collection of event references from input files"""
14 
15  def __init__(self, name="sortEvents"):
16  from AthenaCommon import Logging
17  Logging.log.name = name
18  self.name = name
19  self.info = Logging.log.info
20  self.debug = Logging.log.debug
21  self.verbose = Logging.log.verbose
22  self.collDescription = None
23  self.collSvc = None
24 
25  def loadRoot(self):
26  """import ROOT, create CollectionSvc"""
27  import ROOT
28  self.pool = ROOT.pool
29  self.collSvc = self.pool.CollectionService()
30 
31  def readCollectionDescription(self, collection):
32  """read Collection Description and remember it"""
33  desc = collection.description()
34  self.debug("Reading Collection Description from {}".format(desc.name()))
35  # read attributes' names and types from the description and remember them
36  for an in range(0, desc.numberOfAttributeColumns()):
37  attr = desc.attributeColumn(an)
38  name = attr.name()
39  self.attrNames.append(name)
40  self.attrTypes[name] = attr.type()
41  self.tokenName = desc.eventReferenceColumnName()
42  # make a local copy of the description
43  self.collDescription = self.pool.CollectionDescription( desc )
44  # prevent overwriting input by accident
45  self.collDescription.setName("")
46 
47 
48  def readInputCollections(self, inputCollections):
49  """read all input collections into memore"""
50  self.collDescription = None
51  self.allRows = []
52  self.attrNames = []
53  self.attrTypes = {}
54  self.tokenName = None
55  for inFileName in inputCollections:
56  self.debug("Opening {}".format(inFileName))
57  iColl = self.collSvc.open( "PFN:"+inFileName, getCollectionType(inFileName))
58  self.debug("{} opened".format(inFileName))
59  if self.collDescription is None:
60  self.readCollectionDescription(iColl)
61  self.info("Reading Events from {}".format(inFileName))
62 
63  query = iColl.newQuery()
64  query.selectAll()
65  cursor = query.execute()
66 
67  while cursor.next():
68  row = cursor.currentRow()
69  # put the token first in the attribute list, for convenience
70  t = [ row.tokenList()[self.tokenName].toString() ]
71  for nam in self.attrNames:
72  t.append( row.attributeList()[nam].data[ self.attrTypes[nam] ]() )
73  self.allRows.append(t)
74 
75  iColl.close()
76 
77  for t in self.allRows:
78  self.verbose( (t[1:], t[0]) )
79  self.verbose('='*80)
80  self.info("Finished reading input collections, total events read: {}".format(len(self.allRows)) )
81 
82  def sortEvents(self, sortAttrName, sortReverse=False):
83  """sort the events based on an attribute name"""
84  self.info("Sorting on attribute {}, sort order {}".format(sortAttrName, ("Descending" if sortReverse else "Ascending") ))
85  # add 1 to offsets because the Ref is first
86  attrPos = self.attrNames.index(sortAttrName)+1
87  self.allRows.sort( key=lambda t: t[attrPos], reverse=sortReverse )
88 
89  for t in self.allRows:
90  self.verbose( (t[1:], t[0]) )
91  self.verbose('='*80)
92 
93  def writeCollection(self, outputCollection, outputCollectionType):
94  """write sorted collection into a Collection file"""
95  self.info("Writing Event collection {}".format(outputCollection))
96  self.collDescription.setName(outputCollection)
97  self.collDescription.setType(outputCollectionType)
98  # create the output collection (file)
99  dstColl = self.collSvc.create(self.collDescription)
100  row = self.pool.CollectionRowBuffer()
101  dstColl.initNewRow( row )
102  for t in self.allRows:
103  row.tokenList()[0].fromString( t[0] )
104  for idx,nam in enumerate(self.attrNames):
105  type = self.attrTypes[nam]
106  row.attributeList()[nam].setValue[type]( t[idx+1] )
107  dstColl.insertRow( row )
108 
109  dstColl.commit()
110  dstColl.close()
111 
112  def execute(self, inputCollections, outputCollection="PFN:collection.root", sortAttribute="LumiBlockN",
113  sortOrder="Ascending", outputCollectionType="RootCollection"):
114  sort_opts = ("Ascending", "Descending")
115  self.info("Executing SortedCollectionCreator, inputs={}, output='{}' ({}), sort by: {}, order: {}"
116  .format(inputCollections, outputCollection, outputCollectionType, sortAttribute, sortOrder))
117  if isinstance(inputCollections, str):
118  inputs = [inputCollections]
119  else:
120  inputs = inputCollections
121  if sortOrder.lower() not in [opt.lower() for opt in sort_opts]:
122  raise Exception(self.name + ": Accepted sortOrder values are: " + str(sort_opts))
123  sortReverse = ( sortOrder.lower()[0] == "d" )
124  self.loadRoot()
125  self.readInputCollections(inputs)
126  self.sortEvents(sortAttribute, sortReverse)
127  self.writeCollection(outputCollection, outputCollectionType)
128 
129 
python.SortedCollectionCreator.SortedCollectionCreator.readCollectionDescription
def readCollectionDescription(self, collection)
Definition: SortedCollectionCreator.py:31
vtune_athena.format
format
Definition: vtune_athena.py:14
python.SortedCollectionCreator.SortedCollectionCreator.__init__
def __init__(self, name="sortEvents")
Definition: SortedCollectionCreator.py:15
python.SortedCollectionCreator.SortedCollectionCreator.attrTypes
attrTypes
Definition: SortedCollectionCreator.py:53
index
Definition: index.py:1
python.SortedCollectionCreator.SortedCollectionCreator.tokenName
tokenName
Definition: SortedCollectionCreator.py:41
python.SortedCollectionCreator.SortedCollectionCreator.readInputCollections
def readInputCollections(self, inputCollections)
Definition: SortedCollectionCreator.py:48
python.SortedCollectionCreator.SortedCollectionCreator.execute
def execute(self, inputCollections, outputCollection="PFN:collection.root", sortAttribute="LumiBlockN", sortOrder="Ascending", outputCollectionType="RootCollection")
Definition: SortedCollectionCreator.py:112
python.SortedCollectionCreator.SortedCollectionCreator.verbose
verbose
Definition: SortedCollectionCreator.py:21
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:91
python.SortedCollectionCreator.SortedCollectionCreator
Definition: SortedCollectionCreator.py:12
Amg::toString
std::string toString(const Translation3D &translation, int precision=4)
GeoPrimitvesToStringConverter.
Definition: GeoPrimitivesToStringConverter.h:40
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:194
python.GetCollectionType.getCollectionType
def getCollectionType(fileName)
Definition: GetCollectionType.py:9
python.SortedCollectionCreator.SortedCollectionCreator.debug
debug
Definition: SortedCollectionCreator.py:20
PixelConditionsData::fromString
T fromString(const std::string &s)
Definition: PixelConditionsDataStringUtils.h:14
python.SortedCollectionCreator.SortedCollectionCreator.info
info
Definition: SortedCollectionCreator.py:19
python.SortedCollectionCreator.SortedCollectionCreator.sortEvents
def sortEvents(self, sortAttrName, sortReverse=False)
Definition: SortedCollectionCreator.py:82
python.SortedCollectionCreator.SortedCollectionCreator.loadRoot
def loadRoot(self)
Definition: SortedCollectionCreator.py:25
python.SortedCollectionCreator.SortedCollectionCreator.writeCollection
def writeCollection(self, outputCollection, outputCollectionType)
Definition: SortedCollectionCreator.py:93
python.SortedCollectionCreator.SortedCollectionCreator.collDescription
collDescription
Definition: SortedCollectionCreator.py:22
Trk::open
@ open
Definition: BinningType.h:40
python.SortedCollectionCreator.SortedCollectionCreator.allRows
allRows
Definition: SortedCollectionCreator.py:51
python.SortedCollectionCreator.SortedCollectionCreator.name
name
Definition: SortedCollectionCreator.py:18
str
Definition: BTagTrackIpAccessor.cxx:11
python.SortedCollectionCreator.SortedCollectionCreator.attrNames
attrNames
Definition: SortedCollectionCreator.py:52
python.SortedCollectionCreator.SortedCollectionCreator.pool
pool
Definition: SortedCollectionCreator.py:28
python.SortedCollectionCreator.SortedCollectionCreator.collSvc
collSvc
Definition: SortedCollectionCreator.py:23