ATLAS Offline Software
EventPicking.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 # Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration
4 
5 '''
6 @file EventPicking.py
7 @author Alaettin Serhan Mete
8 @brief A basic script for picking events from POOL files
9 '''
10 
11 from AthenaPython.PyAthena import Alg, py_svc, StatusCode
12 
13 # A basic filtering algorithm
14 class PyEvtFilter(Alg):
15 
16  # Constructor
17  def __init__(self, name='PyEvtFilter', **kwargs):
18  kwargs['name'] = name
19  super().__init__(**kwargs)
20  self.evtList = kwargs.get('evtList', None)
21  self.isMC = kwargs.get('isMC', False)
22 
23  # Initialize the algorithm
24  def initialize(self):
25  self.sg = py_svc('StoreGateSvc')
26  return StatusCode.Success
27 
28  # Execute the algorithm
29  def execute(self):
30 
31  # Read the run/event number from xAOD::EventInfo
32  if self.sg.contains('xAOD::EventInfo', 'EventInfo'):
33  ei = self.sg.retrieve('xAOD::EventInfo', 'EventInfo')
34  if not self.isMC:
35  runNumber = ei.runNumber()
36  else:
37  runNumber = ei.mcChannelNumber()
38  eventNumber = ei.eventNumber()
39 
40  # Check to see if we should accept or reject the event
41  if (runNumber, eventNumber) in self.evtList:
42  self.setFilterPassed(True)
43  else:
44  self.setFilterPassed(False)
45 
46  # Let's happily move to the next event
47  return StatusCode.Success
48 
49  # If we made it thus far something went wrong
50  return StatusCode.Failure
51 
52 # Main executable
53 if __name__ == "__main__":
54 
55  # Parse user input
56  import argparse
57  parser = argparse.ArgumentParser(description='Select events identified by run number (mc channel number'
58  ' in case of Monte Carlo), event number from the input POOL file(s)')
59  parser.add_argument('--inputFiles', required=True,
60  help='Input POOL file(s) separated with commas')
61  parser.add_argument('--outputFile', required=True,
62  help='Output POOL file')
63  parser.add_argument('--eventList', required=True,
64  help='Text file containing <run number> <event number> [<guid>] record(s) (one per line)')
65  args, _ = parser.parse_known_args()
66 
67  # Setup configuration logging
68  from AthenaCommon.Logging import logging
69  log = logging.getLogger('EventPicking')
70  log.info('== Picking events from POOL files w/ the CA Configuration')
71 
72  # Parse input file that contains run_number, event_number[, guid] combinations
73  evtList = []
74  with open(args.eventList) as f:
75  for line in f:
76  run, evt, *guid = line.rstrip().split()
77  evtList.append((int(run), int(evt)))
78 
79  # Set the configuration flags
80  log.info('== Setting ConfigFlags')
81  from AthenaConfiguration.AllConfigFlags import initConfigFlags
82  flags = initConfigFlags()
83  flags.Input.Files = args.inputFiles.split(',')
84 
85  try:
86  streamToOutput = flags.Input.ProcessingTags[0].removeprefix('Stream')
87  except Exception as e:
88  raise RuntimeError('Could not determine the stream type') from e
89 
90  for name, value in ((f'Output.{streamToOutput}FileName', args.outputFile),
91  (f'Output.doWrite{streamToOutput}', True)):
92  if flags.hasFlag(name):
93  setattr(flags, name, value)
94  else:
95  flags.addFlag(name, value)
96  if 'DAOD' in streamToOutput:
97  flags.Output.doWriteDAOD = True
98 
99  # Lock and dump the configuration flags
100  flags.lock()
101  log.info('== ConfigFlags Locked')
102 
103  # Setup the main services
104  log.info('== Configuring Main Services')
105  from AthenaConfiguration.MainServicesConfig import MainServicesCfg
106  cfg = MainServicesCfg(flags)
107 
108  # Setup the input reading
109  log.info('== Configuring Input Reading')
110  from AthenaPoolCnvSvc.PoolReadConfig import PoolReadCfg
111  cfg.merge(PoolReadCfg(flags))
112 
113  # Setup event picking
114  cfg.addEventAlgo(PyEvtFilter('EventFilterAlg', evtList=evtList, isMC=flags.Input.isMC), sequenceName='AthAlgSeq')
115 
116  # Configure the output stream
117  log.info(f'== Configuring Output Stream {streamToOutput!r}')
118  from OutputStreamAthenaPool.OutputStreamConfig import OutputStreamCfg, outputStreamName
119  cfg.merge(OutputStreamCfg(flags, streamToOutput, takeItemsFromInput=True, extendProvenanceRecord=False))
120 
121  # Configure metadata
122  log.info('== Configuring metadata for the output stream')
123  from xAODMetaDataCnv.InfileMetaDataConfig import SetupMetaDataForStreamCfg
124  from AthenaConfiguration.Enums import MetadataCategory
125 
126  cfg.merge(SetupMetaDataForStreamCfg(flags, streamToOutput,
127  createMetadata=[MetadataCategory.IOVMetaData]))
128 
129  # Setup the output stream algorithm
130  Stream = cfg.getEventAlgo(outputStreamName(streamToOutput))
131  Stream.ForceRead = True
132  Stream.AcceptAlgs += ['EventFilterAlg']
133 
134  log.info(f'== Configured {streamToOutput!r} writing')
135 
136  for item in flags.Input.TypedCollections:
137  ctype, cname = item.split('#')
138  if ctype.startswith('Trk') or ctype.startswith('InDet'):
139  from TrkEventCnvTools.TrkEventCnvToolsConfig import TrkEventCnvSuperToolCfg
140  cfg.merge(TrkEventCnvSuperToolCfg(flags))
141  if ctype.startswith('Calo') or ctype.startswith('LAr'):
142  from LArGeoAlgsNV.LArGMConfig import LArGMCfg
143  cfg.merge(LArGMCfg(flags))
144  if ctype.startswith('Calo') or ctype.startswith('Tile'):
145  from TileGeoModel.TileGMConfig import TileGMCfg
146  cfg.merge(TileGMCfg(flags))
147  if ctype.startswith('Muon'):
148  from MuonConfig.MuonGeometryConfig import MuonGeoModelCfg
149  cfg.merge(MuonGeoModelCfg(flags))
150 
151  # Needed for merging in MT
152  if 'ESD' in streamToOutput:
153  Stream.ExtraInputs.add(
154  ( 'MuonGM::MuonDetectorManager',
155  'ConditionStore+MuonDetectorManager' ) )
156  Stream.ExtraInputs.add(
157  ( 'InDetDD::SiDetectorElementCollection',
158  'ConditionStore+PixelDetectorElementCollection' ) )
159  Stream.ExtraInputs.add(
160  ( 'InDetDD::SiDetectorElementCollection',
161  'ConditionStore+SCT_DetectorElementCollection' ) )
162  Stream.ExtraInputs.add(
163  ( 'InDetDD::TRT_DetElementContainer',
164  'ConditionStore+TRT_DetElementContainer' ) )
165 
166  # Setup PerfMon
167  log.info('== Configuring PerfMon')
168  from PerfMonComps.PerfMonCompsConfig import PerfMonMTSvcCfg
169  cfg.merge(PerfMonMTSvcCfg(flags))
170 
171  # Now run the job
172  log.info('== Running...')
173  sc = cfg.run()
174 
175  # Exit accordingly
176  import sys
177  sys.exit(not sc.isSuccess())
python.PyKernel.retrieve
def retrieve(aClass, aKey=None)
Definition: PyKernel.py:110
python.OutputStreamConfig.OutputStreamCfg
def OutputStreamCfg(flags, streamName, ItemList=None, MetadataItemList=None, disableEventTag=False, trigNavThinningSvc=None, takeItemsFromInput=False, extendProvenanceRecord=True, keepProvenanceTagsRegEx=None, AcceptAlgs=None, HelperTools=None)
Definition: OutputStreamConfig.py:13
AthenaPoolExample_WriteCond.outputStreamName
string outputStreamName
Definition: AthenaPoolExample_WriteCond.py:21
EventPicking.PyEvtFilter.execute
def execute(self)
Definition: EventPicking.py:29
python.PerfMonCompsConfig.PerfMonMTSvcCfg
def PerfMonMTSvcCfg(flags, **kwargs)
A minimal new-style configuration for PerfMonMTSvc.
Definition: PerfMonCompsConfig.py:10
EventPicking.PyEvtFilter
Definition: EventPicking.py:14
EventPicking.PyEvtFilter.evtList
evtList
Definition: EventPicking.py:20
python.TrkEventCnvToolsConfig.TrkEventCnvSuperToolCfg
def TrkEventCnvSuperToolCfg(flags, name='EventCnvSuperTool', **kwargs)
Definition: TrkEventCnvToolsConfig.py:51
python.Bindings.py_svc
def py_svc(svcName, createIf=True, iface=None)
Definition: Control/AthenaPython/python/Bindings.py:98
MuonGeometryConfig.MuonGeoModelCfg
def MuonGeoModelCfg(flags)
Definition: MuonGeometryConfig.py:28
contains
bool contains(const std::string &s, const std::string &regx)
does a string contain the substring
Definition: hcg.cxx:111
python.MainServicesConfig.MainServicesCfg
def MainServicesCfg(flags, LoopMgr='AthenaEventLoopMgr')
Definition: MainServicesConfig.py:310
EventPicking.PyEvtFilter.initialize
def initialize(self)
Definition: EventPicking.py:24
LArGMConfig.LArGMCfg
def LArGMCfg(flags)
Definition: LArGMConfig.py:8
EventPicking.PyEvtFilter.sg
sg
Definition: EventPicking.py:25
Trk::open
@ open
Definition: BinningType.h:40
python.CaloAddPedShiftConfig.int
int
Definition: CaloAddPedShiftConfig.py:45
python.AllConfigFlags.initConfigFlags
def initConfigFlags()
Definition: AllConfigFlags.py:19
EventPicking.PyEvtFilter.__init__
def __init__(self, name='PyEvtFilter', **kwargs)
Definition: EventPicking.py:17
InfileMetaDataConfig.SetupMetaDataForStreamCfg
def SetupMetaDataForStreamCfg(flags, streamName="", AcceptAlgs=None, createMetadata=None, propagateMetadataFromInput=True, *args, **kwargs)
Definition: InfileMetaDataConfig.py:222
python.PoolReadConfig.PoolReadCfg
def PoolReadCfg(flags)
Definition: PoolReadConfig.py:71
EventPicking.PyEvtFilter.isMC
isMC
Definition: EventPicking.py:21
Trk::split
@ split
Definition: LayerMaterialProperties.h:38
TileGMConfig.TileGMCfg
def TileGMCfg(flags)
Definition: TileGMConfig.py:7