ATLAS Offline Software
Loading...
Searching...
No Matches
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
11from AthenaPython.PyAthena import Alg, py_svc, StatusCode
12
13# A basic filtering algorithm
14class 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
53if __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())
__init__(self, name='PyEvtFilter', **kwargs)
bool contains(const std::string &s, const std::string &regx)
does a string contain the substring
Definition hcg.cxx:114
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:177
void initialize()