ATLAS Offline Software
OverlayMetadata.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
2 
3 import re
4 
5 from AthenaCommon.Logging import logging
6 from PyUtils.MetaReader import read_metadata
7 
8 logger = logging.getLogger("OverlayMetadataConfig")
9 
10 # Module level cache of file-metadata:
11 _fileMetadata = dict()
12 
13 def _getFileMD(filenames):
14  if type(filenames) is list:
15  filename = filenames[0]
16  else:
17  filename = filenames
18 
19  if filename not in _fileMetadata:
20  logger.info("Obtaining full metadata of %s", filename)
21 
22  thisFileMD = read_metadata(filename, None, 'full')
23  _fileMetadata.update(thisFileMD)
24 
25  return _fileMetadata[filename]
26 
27 
28 def validateGeometryTag(logger, target, value):
29  """Validate geometry tag so it is the same as target"""
30  target_layout = target.split('-')
31  value_layout = value.split('-')
32  if len(target_layout) != len(value_layout):
33  return False
34 
35  for p, s in zip(target_layout[:-1], value_layout[:-1]):
36  if not re.match(p, s):
37  return False
38 
39  if not re.match(target_layout[-1], value_layout[-1]):
40  logger.warning("Simulation geometry tag mismatch! %s vs %s", target, value)
41 
42  return True
43 
44 
45 def overlayInputMetadataCheck(flags, simDict, tagInfoDict):
46  """Check the metadata for signal HITS or presampled pileup RDO file"""
47  logger.info("Checking Overlay configuration against Signal or presampled pileup RDO metadata...")
48 
49  simKeys = simDict.keys()
50  tagInfoKeys = tagInfoDict.keys()
51 
52  # Check the PhysicsList set agrees with that used in the simulation
53  if "PhysicsList" in simKeys:
54  if re.match(simDict["PhysicsList"], flags.Sim.PhysicsList):
55  logger.debug("Overlay configuration matches Signal Simulation metadata. [Sim.PhysicsList = %s]", flags.Sim.PhysicsList)
56  else:
57  flags.Sim.PhysicsList = simDict["PhysicsList"]
58  logger.warning("Overlay Sim.PhysicsList does not match the PhysicsList used in the Signal Simulation step! Assume the value from the Signal Simulation step is correct!")
59  logger.warning("Set Sim.PhysicsList = %s", flags.Sim.PhysicsList)
60  else:
61  logger.error("'PhysicsList' key not found in Signal Simulation metadata!")
62  raise AssertionError("Signal Simulation metadata key not found")
63 
64  # Check the DetDescrVersion set agrees with that used in the simulation
65  if "SimLayout" in simKeys:
66  if validateGeometryTag(logger, simDict["SimLayout"], flags.GeoModel.AtlasVersion):
67  logger.debug("Overlay configuration matches Signal Simulation metadata. [Geomodel.AtlasVersion = %s]",
68  flags.GeoModel.AtlasVersion)
69  else:
70  flags.GeoModel.AtlasVersion = simDict["SimLayout"]
71  logger.warning("Overlay Geomodel.AtlasVersion does not match the value used in the Signal Simulation step! Assume the value from the Signal Simulation step is correct!")
72  logger.warning("Set Geomodel.AtlasVersion = %s", flags.GeoModel.AtlasVersion)
73  else:
74  logger.error("'SimLayout' key not found in Signal Simulation metadata!")
75  raise AssertionError("Signal Simulation metadata key not found")
76 
77  # Check the Conditions Tag set against that used in the simulation
78  if "IOVDbGlobalTag" in tagInfoKeys:
79  if not re.match(tagInfoDict["IOVDbGlobalTag"], flags.IOVDb.GlobalTag):
80  logger.debug("Overlay configuration: [IOVDb.GlobalTag = %s], Signal Simulation metadata: [IOVDb.GlobalTag = %s]",
81  flags.IOVDb.GlobalTag, tagInfoDict['IOVDbGlobalTag'])
82  else:
83  logger.error("'IOVDbGlobalTag' key not found in Signal Simulation metadata!")
84  raise AssertionError("Signal Simulation metadata key not found")
85 
86  # Set the TRTRangeCut digitizationFlag based on what was used during the simulation.
87  if "TRTRangeCut" in simKeys:
88  if not re.match(simDict["TRTRangeCut"], str(flags.Sim.TRTRangeCut)):
89  flags.Sim.TRTRangeCut = simDict["TRTRangeCut"]
90  logger.warning("Overlay Sim.TRTRangeCut does not match the value used in the Signal Simulation step! Assume the value from the Signal Simulation step is correct!")
91  logger.warning("Set Sim.TRTRangeCut = %s", flags.Sim.TRTRangeCut)
92  else:
93  logger.warning("'TRTRangeCut' key not found in Signal Simulation metadata!")
94 
95  # Check which sub-detectors were simulated
96  # TODO: needed?
97 
98  logger.info("Completed checks of Overlay configuration against Signal Simulation metadata.")
99 
100 
101 def simulationMetadataCheck(sigdict, pudict):
102  """Check the simulation metadata for presampled pileup RDO file"""
103  sigkeys = sigdict.keys()
104  pukeys = pudict.keys()
105 
106  # Loop over metadata keys which must have matching values
107  warningKeys = ['G4Version']
108  sigKeysToCheck = ['PhysicsList', 'SimLayout', 'MagneticField', 'hitFileMagicNumber'] + warningKeys
109  for o in sigKeysToCheck:
110  try:
111  assert o in pukeys
112  except AssertionError:
113  logger.error("%s key missing from Presampled pile-up Simulation metadata!", o)
114  raise AssertionError("Presampled pile-up Simulation metadata key not found")
115  try:
116  assert o in sigkeys
117  except AssertionError:
118  logger.error("%s key missing from Signal Simulation metadata!", o)
119  raise AssertionError("Signal Simulation metadata key not found")
120  try:
121  if o == "SimLayout": # allow last part of the simulation tag to differ
122  assert validateGeometryTag(logger, sigdict[o], pudict[o])
123  elif not isinstance(pudict[o], type(sigdict[o])):
124  assert re.match(str(pudict[o]), str(sigdict[o]))
125  else:
126  if isinstance(pudict[o], str):
127  assert re.match(pudict[o], sigdict[o])
128  elif isinstance(pudict[o], int):
129  assert (pudict[o] == sigdict[o])
130  else:
131  assert re.match(str(pudict[o]), str(sigdict[o]))
132  except AssertionError:
133  if o in warningKeys:
134  logger.warning("Simulation metadata mismatch! Presampled pile-up: [%s = %s] Signal: [%s = %s]", o, pudict[o], o, sigdict[o])
135  else:
136  logger.error("Simulation metadata mismatch! Presampled pile-up: [%s = %s] Signal: [%s = %s]", o, pudict[o], o, sigdict[o])
137  raise AssertionError("Simulation metadata mismatch")
138 
139 
140 def tagInfoMetadataCheck(sigdict, pudict):
141  """Check the tag info metadata for presampled pileup RDO File"""
142  sigkeys = sigdict.keys()
143  pukeys = pudict.keys()
144 
145  logger.debug("Signal /TagInfo ", sigdict)
146  logger.debug("Pileup /TagInfo ", pudict)
147 
148  sigOnlyDict = dict()
149  sigOnlyKeySet = set(sigkeys).difference(set(pukeys))
150  logger.debug("The following keys only appear in Signal /TagInfo metadata:")
151  logger.debug(sigOnlyKeySet)
152  for key in sigOnlyKeySet:
153  sigOnlyDict[key] = sigdict[key]
154  logger.debug(" key: ", key, "value: ", sigdict[key])
155  pass
156  # TODO: extra
157  keysToCompareSet = set(sigkeys).intersection(set(pukeys))
158  logger.debug("The following keys appear in Signal and Presampled pile-up /TagInfo metadata:")
159  logger.debug(keysToCompareSet)
160 
161  # Loop over metadata keys which must have matching values
162  warningKeys = ['IOVDbGlobalTag']
163  sigKeysToCheck = warningKeys
164  for o in sigKeysToCheck:
165  try:
166  assert o in pukeys
167  except AssertionError:
168  logger.error("%s key missing from Presampled pile-up Simulation metadata!", o)
169  raise AssertionError("Presampled pile-up Simulation metadata key not found")
170  try:
171  assert o in sigkeys
172  except AssertionError:
173  logger.error("%s key missing from Signal Simulation metadata!", o)
174  raise AssertionError("Signal Simulation metadata key not found")
175  try:
176  if not isinstance(pudict[o], type(sigdict[o])):
177  assert re.match(str(pudict[o]), str(sigdict[o]))
178  else:
179  if isinstance(pudict[o], str):
180  assert re.match(pudict[o], sigdict[o])
181  elif isinstance(pudict[o], int):
182  assert (pudict[o] == sigdict[o])
183  else:
184  assert re.match(str(pudict[o]), str(sigdict[o]))
185  except AssertionError:
186  if o in warningKeys:
187  logger.warning("Simulation metadata mismatch! Presampled pile-up: [%s = %s] Signal: [%s = %s]", o, pudict[o], o, sigdict[o])
188  else:
189  logger.error("Simulation metadata mismatch! Presampled pile-up: [%s = %s] Signal: [%s = %s]", o, pudict[o], o, sigdict[o])
190  raise AssertionError("Simulation metadata mismatch")
191 
192 
194  """Check overlay metadata"""
195  if flags.Overlay.DataOverlay:
196  files = flags.Input.Files
197  filesPileup = flags.Input.SecondaryFiles
198  else:
199  files = flags.Input.SecondaryFiles
200  filesPileup = flags.Input.Files
201 
202  if files:
203  signalMetadata = _getFileMD(files)
204  signalSimulationMetadata = signalMetadata["/Simulation/Parameters"]
205  signalTagInfoMetadata = signalMetadata["/TagInfo"]
206  # signal check
207  overlayInputMetadataCheck(flags, signalSimulationMetadata, signalTagInfoMetadata)
208  else:
209  # This can be the case for the FastChain with overlay
210  # It is not an error.
211  logger.info("Simulation metadata check not done due to no inputs")
212 
213  # pile-up check
214  if not flags.Overlay.DataOverlay and filesPileup:
215  pileupMetaDataCheck = _getFileMD(filesPileup)
216  pileupDigitizationMetadata = pileupMetaDataCheck["/Digitization/Parameters"]
217  pileupSimulationMetadata = pileupMetaDataCheck["/Simulation/Parameters"]
218  pileupTagInfoMetadata = pileupMetaDataCheck["/TagInfo"]
219 
220  logger.info("Checking Presampled pile-up metadata against Signal Simulation metadata...")
221  simulationMetadataCheck(signalSimulationMetadata, pileupSimulationMetadata)
222  tagInfoMetadataCheck(signalTagInfoMetadata, pileupTagInfoMetadata)
223  logger.info("Completed all checks against Presampled pile-up Simulation metadata.")
224 
225  if pileupDigitizationMetadata:
226  writeOverlayDigitizationMetadata(flags,pileupDigitizationMetadata)
227 
228 
230  """Check fastchain overlay metadata"""
231  if flags.Overlay.DataOverlay:
232  filesPileup = flags.Input.SecondaryFiles
233  else:
234  filesPileup = flags.Input.Files
235 
236  # pile-up check
237  if not flags.Overlay.DataOverlay and filesPileup:
238  pileupMetaDataCheck = _getFileMD(filesPileup)
239  pileupDigitizationMetadata = pileupMetaDataCheck["/Digitization/Parameters"]
240  pileupSimulationMetadata = pileupMetaDataCheck["/Simulation/Parameters"]
241  pileupTagInfoMetadata = pileupMetaDataCheck["/TagInfo"]
242 
243  logger.info("Checking Presampled pile-up metadata against configuration of jobs (i.e. flags)...")
244  overlayInputMetadataCheck(flags, pileupSimulationMetadata, pileupTagInfoMetadata)
245  logger.info("Completed all checks against Presampled pile-up Simulation metadata.")
246 
247  if pileupDigitizationMetadata:
248  writeOverlayDigitizationMetadata(flags,pileupDigitizationMetadata)
249 
250 
251 def writeOverlayDigitizationMetadata(flags,pileupDict):
252  from IOVDbMetaDataTools import ParameterDbFiller
254  runNumber = flags.Input.RunNumbers[0]
255  runNumberEnd = flags.Input.RunNumbers[-1]
256  if runNumberEnd == runNumber:
257  runNumberEnd += 1
258  logger.debug('ParameterDbFiller BeginRun = %s', str(runNumber) )
259  dbFiller.setBeginRun(runNumber)
260  logger.debug('ParameterDbFiller EndRun = %s', str(runNumberEnd) )
261  dbFiller.setEndRun(runNumberEnd)
262 
263  logger.info('Filling Digitization MetaData')
264 
265  # Copy over pileup dictionary
266  for key in pileupDict:
267  value = str(pileupDict[key])
268  logger.info('DigitizationMetaData: setting "%s" to be %s', key, value)
269  if key in ["BeamIntensityPattern"]:
270  dbFiller.addDigitParam64(key, value)
271  else:
272  dbFiller.addDigitParam(key, value)
273 
274  # Make the MetaData Db
275  dbFiller.genDigitDb()
python.ParameterDbFiller.ParameterDbFiller
Definition: ParameterDbFiller.py:26
python.MetaReader.read_metadata
def read_metadata(filenames, file_type=None, mode='lite', promote=None, meta_key_filter=None, unique_tag_info_values=True, ignoreNonExistingLocalFiles=False)
Definition: MetaReader.py:52
python.OverlayMetadata.overlayMetadataCheck
def overlayMetadataCheck(flags)
Definition: OverlayMetadata.py:193
python.OverlayMetadata.validateGeometryTag
def validateGeometryTag(logger, target, value)
Definition: OverlayMetadata.py:28
intersection
std::vector< std::string > intersection(std::vector< std::string > &v1, std::vector< std::string > &v2)
Definition: compareFlatTrees.cxx:25
python.OverlayMetadata.simulationMetadataCheck
def simulationMetadataCheck(sigdict, pudict)
Definition: OverlayMetadata.py:101
python.OverlayMetadata.fastChainOverlayMetadataCheck
def fastChainOverlayMetadataCheck(flags)
Definition: OverlayMetadata.py:229
python.OverlayMetadata._getFileMD
def _getFileMD(filenames)
Definition: OverlayMetadata.py:13
CxxUtils::set
constexpr std::enable_if_t< is_bitmask_v< E >, E & > set(E &lhs, E rhs)
Convenience function to set bits in a class enum bitmask.
Definition: bitmask.h:232
python.OverlayMetadata.tagInfoMetadataCheck
def tagInfoMetadataCheck(sigdict, pudict)
Definition: OverlayMetadata.py:140
python.OverlayMetadata.writeOverlayDigitizationMetadata
def writeOverlayDigitizationMetadata(flags, pileupDict)
Definition: OverlayMetadata.py:251
python.CaloScaleNoiseConfig.type
type
Definition: CaloScaleNoiseConfig.py:78
python.OverlayMetadata.overlayInputMetadataCheck
def overlayInputMetadataCheck(flags, simDict, tagInfoDict)
Definition: OverlayMetadata.py:45
str
Definition: BTagTrackIpAccessor.cxx:11