ATLAS Offline Software
Loading...
Searching...
No Matches
ConfigBlock.py
Go to the documentation of this file.
1# Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
2
3import textwrap
4import inspect
5from functools import wraps
6import warnings
7
8from AnaAlgorithm.Logging import logging
9logCPAlgCfgBlock = logging.getLogger('CPAlgCfgBlock')
10
11from AnalysisAlgorithmsConfig.ConfigAccumulator import DataType, ExpertModeWarning
12import re
13
14def filter_dsids (filterList, config) :
15 """check whether the sample being run passes a"""
16 """possible DSID filter on the block"""
17 if len(filterList) == 0:
18 return True
19 for dsid_filter in filterList:
20 # Check if the pattern is enclosed in regex delimiters (e.g., starts with '^' or contains regex metacharacters)
21 if any(char in str(dsid_filter) for char in "^$*+?.()|[]{}\\"):
22 pattern = re.compile(dsid_filter)
23 if pattern.match(str(config.dsid())):
24 return True
25 else:
26 # Otherwise it's an exact DSID (but could be int or string)
27 if str(dsid_filter) == str(config.dsid()):
28 return True
29 return False
30
32 """this wrapper ensures that the 'instanceName' of the various """
33 """config blocks is cleaned up of any non-alphanumeric characters """
34 """that may arise from using 'selectionName' in the naming."""
35 @wraps(func)
36 def wrapper(*args, **kwargs):
37 # Get the string returned by the 'instanceName()' method of a config block
38 orig_name = func(*args, **kwargs)
39
40 if orig_name is None:
41 return ""
42
43 # Allowed replacements - anything else is likely a mistake on the user-side
44 result = orig_name.replace("||", "OR").replace("&&", "AND").replace("(","LB").replace(")","RB").replace(" ","")
45
46 return result
47 return wrapper
48
50 """this meta class enforces the application of 'alphanumeric_block_names()' """
51 """to 'instanceName()' and will be used in the main ConfigBlock class in order """
52 """to propagate this rule also to all derived classes (the individual config blocks."""
53 def __new__(cls, name, bases, dct):
54 # Automatically apply alphanumeric-only decorator to 'instanceName()' method
55 if 'instanceName' in dct and callable(dct['instanceName']):
56 dct['instanceName'] = alphanumeric_block_name(dct['instanceName'])
57 return super().__new__(cls, name, bases, dct)
58
60 """the information for a single option on a configuration block"""
61
62 def __init__ (self, type=None, info='', noneAction='ignore', required=False,
63 default=None) :
64 self.type = type
65 self.info = info
66 self.required = required
67 self.noneAction = noneAction
68 self.default = default
69
70
71
73 """Class encoding a blocks dependence on other blocks."""
74
75 def __init__(self, blockName, required=True):
76 self.blockName = blockName
77 self.required = required
78
79
80 def __eq__(self, name):
81 return self.blockName == name
82
83
84 def __str__(self):
85 return self.blockName
86
87
88 def __repr__(self):
89 return f'ConfigBlockDependency(blockName="{self.blockName}", required={self.required})'
90
91
92class ConfigBlock(metaclass=BlockNameProcessorMeta):
93 """the base class for classes implementing individual blocks of
94 configuration
95
96 A configuration block is a sequence of one or more algorithms that
97 should always be scheduled together, e.g. the muon four momentum
98 corrections could be a single block, muon selection could then be
99 another block. The blocks themselves generally have their own
100 configuration options/properties specific to the block, and will
101 perform a dynamic configuration based on those options as well as
102 the overall job.
103
104 The actual configuration of the algorithms in the block will
105 depend on what other blocks are scheduled before and afterwards,
106 most importantly some algorithms will introduce shallow copies
107 that subsequent algorithms will need to run on, and some
108 algorithms will add selection decorations that subquent algorithms
109 should use as preselections.
110
111 The algorithms get created in a multi-step process (that may be
112 extended in the future): As a first step each block retrieves
113 references to the containers it uses (essentially marking its spot
114 in the processing chain) and also registering any shallow copies
115 that will be made. In the second/last step each block then
116 creates the fully configured algorithms.
117
118 One goal is that when the algorithms get created they will have
119 their final configuration and there needs to be no
120 meta-configuration data attached to the algorithms, essentially an
121 inversion of the approach in AnaAlgSequence in which the
122 algorithms got created first with associated meta-configuration
123 and then get modified in susequent configuration steps.
124
125 For now this is mostly an empty base class, but another goal of
126 this approach is to make it easier to build another configuration
127 layer on top of this one, and this class will likely be extended
128 and get data members at that point.
129
130 The child class needs to implement the method `makeAlgs` which is
131 given a single `ConfigAccumulator` type argument. This is meant to
132 create the sequence of algorithms that this block configures. This
133 is currently (28 Jul 2025) called twice and should do the same thing
134 during both calls, but the plan is to change that to a single call.
135
136 The child class should also implement the method `getInstanceName`
137 which should return a string that is used to distinguish between
138 multiple instances of the same block. This is used to append the
139 instance name to the names of all algorithms created by this block,
140 and may in the future also be used to distinguish between multiple
141 instances of the block.
142 """
143
144 # Class-level dictionary to keep track of instance counts for each derived class
145 instance_counts = {}
146
147 def __init__ (self) :
148 self._blockName = ''
149 self._factoryName = None
151 self._options = {} # used with block configuration to set arbitrary option
152 self._expertModeSettings = {} # dictionary to track expert mode requirements for each option
153 self.addOption('groupName', '', type=str,
154 info=('Used to specify this block when setting an'
155 ' option at an arbitrary location.'))
156 self.addOption('skipOnData', False, type=bool,
157 info=('User option to prevent the block from running'
158 ' on data. This only affects blocks that are'
159 ' intended to run on data.'))
160 self.addOption('skipOnMC', False, type=bool,
161 info=('User option to prevent the block from running'
162 ' on MC. This only affects blocks that are'
163 ' intended to run on MC.'))
164 self.addOption('skipWithSystematics', False, type=bool,
165 info=('User option to prevent the block from running with systematics.'))
166 self.addOption('onlyForDSIDs', [], type=list,
167 info=('Used to specify which MC DSIDs to allow this'
168 ' block to run on. Each element of the list'
169 ' can be a full DSID (e.g. 410470), or a regex'
170 ' (e.g. 410.* to select all 410xxx DSIDs, or'
171 ' ^(?!410) to veto them). An empty list means no'
172 ' DSID restriction.'))
173 self.addOption('propertyOverrides', {}, type=dict,
174 info=('EXPERT USE ONLY: A dictionary of properties to'
175 ' override at the end of configuration. This should'
176 ' take the form'
177 ' {"algName.toolName.propertyName": value, ...},'
178 ' without any automatically applied postfixes for'
179 ' the algorithm name. THIS IS MEANT TO BE EXPERT'
180 ' USAGE ONLY. Properties that need to be set by'
181 ' the user should be declared as options on the'
182 ' block itself. EXPERT USE ONLY!'),
183 expertMode=True)
184 # Increment the instance count for the current class
185 cls = type(self) # Get the actual class of the instance (also derived!)
186 if cls not in ConfigBlock.instance_counts:
187 ConfigBlock.instance_counts[cls] = 0
188 # Note: we do need to check in the call stack that we are
189 # in a real makeConfig situation, and not e.g. printAlgs
190 stack = inspect.stack()
191 for frame_info in stack:
192 # Get the class name (if any) from the frame
193 parent_cls = frame_info.frame.f_locals.get('self', None)
194 if parent_cls is None or not isinstance(parent_cls, ConfigBlock):
195 # If the frame does not belong to an instance of ConfigBlock, it's an external caller
196 if frame_info.function == "makeConfig":
197 ConfigBlock.instance_counts[cls] += 1
198 break
199
200
201 def setBlockName(self, name):
202 """Set blockName"""
203 self._blockName = name
204
205 def getBlockName(self):
206 """Get blockName"""
207 return self._blockName
208
209 def factoryName(self):
210 """get the factory name for this block
211
212 This is mostly to give a reliable means of identifying the type
213 of block we have in error messages. This is meant to be
214 automatically set by the factory based on the requested block
215 name, but there are a number of fallbacks. It is best not to
216 assume a specific format, this is mostly meant to be used as an
217 identifier in output messages.
218 """
219 if self._factoryName is not None and self._factoryName != '':
220 return self._factoryName
221 # If no factory name is set and the block has a name, use that
222 if self._blockName is not None and self._blockName != '':
223 return self._blockName
224 # Use the class name as a fallback
225 return self.__class__.__name__
226
227 def setFactoryName(self, name):
228 """set the factory name for this block
229
230 This is meant to be called automatically by the factory based on
231 the requested block name. If you are creating a block without a factory,
232 you can call this method to set the factory name manually.
233 """
234 self._factoryName = name
235
236 def instanceName(self):
237 """Get the name of the instance
238
239 The name of the instance is used to distinguish between multiple
240 instances of the same block. Most importantly, this will be
241 appended to the names of all algorithms created by this block.
242 This defaults to an empty string, but block implementations
243 should override it with an appropriate name based on identifying
244 options set on this instance. A typical example would be the
245 name of the (main) container, plus potentially the selection or
246 working point.
247
248 Ideally all blocks should override this method, but for backward
249 compatibility (28 Jul 25) it defaults to an empty string.
250 """
251 return ''
252
253 def isUsedForConfig(self, config):
254 """
255 whether this block should be used for the given configuration
256
257 This is used by `ConfigSequence` to determine whether this block
258 should be included in the configuration.
259 """
260 if self.skipWithSystematics and not config.noSystematics():
261 return False
262 if self.skipOnData and config.dataType() is DataType.Data:
263 return False
264 if self.skipOnMC and config.dataType() is not DataType.Data:
265 return False
266 if not filter_dsids(self.onlyForDSIDs, config):
267 return False
268 return True
269
270 def applyConfigOverrides(self, config):
271 """
272 Apply any configuration overrides specified in the block's
273 `propertyOverrides` option. This is meant to be called at the
274 end of the configuration process, after all algorithms have been
275 created and configured.
276 """
277 for key, value in self.propertyOverrides.items():
278 # Split the key into algorithm name, tool name, and property name
279 parts = key.split('.')
280 if len(parts) < 2:
281 raise Exception(f"Invalid override key format: {key}")
282 alg = config.getAlgorithm(parts[0])
283 if alg is None:
284 raise Exception(f"Algorithm {parts[0]} not found in config for override: {key}")
285 for name in parts[1:-1]:
286 # Navigate through tools if necessary
287 if hasattr(alg, name):
288 alg = getattr(alg, name)
289 else:
290 raise Exception(f"Tool {name} not found for override: {key}")
291 # Set the property on the algorithm/tool. This is probably a
292 # horrible hack, but `setattr` didn't work for me.
293 alg.__setattr__(parts[-1], value)
294
295 def addDependency(self, dependencyName, required=True):
296 """
297 Add a dependency for the block. Dependency is corresponds to the
298 blockName of another block. If required is True, will throw an
299 error if dependency is not present; otherwise will move this
300 block after the required block. If required is False, will do
301 nothing if required block is not present; otherwise, it will
302 move block after required block.
303 """
304 if not self.hasDependencies():
305 # add option to block ignore dependencies
306 self.addOption('ignoreDependencies', [], type=list,
307 info='List of dependencies defined in the ConfigBlock to ignore.')
308 self._dependencies.append(ConfigBlockDependency(dependencyName, required))
309
311 """Return True if there is a dependency."""
312 return bool(self._dependencies)
313
315 """Return the list of dependencies. """
316 return self._dependencies
317
318 def addOption (self, name, defaultValue, *,
319 type, info='', noneAction='ignore', required=False, expertMode=None) :
320 """declare the given option on the configuration block
321
322 This should only be called in the constructor of the
323 configuration block.
324
325 NOTE: The backend to option handling is slated to be replaced
326 at some point. This particular function should essentially
327 stay the same, but some behavior may change.
328 """
329 if name in self._options :
330 raise KeyError (f'duplicate option: {name}')
331 if type not in [str, bool, int, float, list, dict, None] :
332 raise TypeError (f'unknown option type: {type}')
333 noneActions = ['error', 'set', 'ignore']
334 if noneAction not in noneActions :
335 raise ValueError (f'invalid noneAction: {noneAction} [allowed values: {noneActions}]')
336
337 # Store expert mode settings if provided
338 if expertMode is not None:
339 if expertMode is True:
340 # in this case we will just check against the default value
341 self._expertModeSettings[name] = True
342 elif not isinstance(expertMode, list):
343 raise TypeError (f'expertMode must be a list, got {type(expertMode)}')
344 else:
345 # here we will check against a list of custom values
346 self._expertModeSettings[name] = expertMode
347
348 setattr (self, name, defaultValue)
349 self._options[name] = ConfigBlockOption(type=type, info=info,
350 noneAction=noneAction, required=required, default=defaultValue)
351
352
353 def setOptionValue (self, name, value) :
354 """set the given option on the configuration block
355
356 NOTE: The backend to option handling is slated to be replaced
357 at some point. This particular function should essentially
358 stay the same, but some behavior may change.
359 """
360
361 if name not in self._options :
362 raise KeyError (f'unknown option "{name}" in block "{self.__class__.__name__}"')
363 noneAction = self._options[name].noneAction
364 if value is not None or noneAction == 'set' :
365 # check type if specified
366 optType = self._options[name].type
367 # convert int to float to prevent crash
368 if optType is float and type(value) is int:
369 value = float(value)
370 if optType is not None and optType != type(value):
371 raise ValueError(f'{name} for block {self.__class__.__name__} should '
372 f'be of type {optType} not {type(value)}')
373 setattr (self, name, value)
374 elif noneAction == 'ignore' :
375 pass
376 elif noneAction == 'error' :
377 raise ValueError (f'passed None for setting option {name} with noneAction=error')
378
379
380 def getOptionValue(self, name):
381 """Returns config option value, if present; otherwise return None"""
382 if name in self._options:
383 return getattr(self, name)
384
385
386 def getOptions(self):
387 """Return a copy of the options associated with the block"""
388 return self._options.copy()
389
390
391 def printOptions(self, verbose=False, width=60, indent=" "):
392 """
393 Prints options and their values
394 """
395 def printWrap(text, width=60, indent=" "):
396 wrapper = textwrap.TextWrapper(width=width, initial_indent=indent,
397 subsequent_indent=indent)
398 for line in wrapper.wrap(text=text):
399 logCPAlgCfgBlock.info(line)
400
401 for opt, vals in self.getOptions().items():
402 if verbose:
403 logCPAlgCfgBlock.info(indent + f"\033[4m{opt}\033[0m: {self.getOptionValue(opt)}")
404 logCPAlgCfgBlock.info(indent*2 + f"\033[4mtype\033[0m: {vals.type}")
405 logCPAlgCfgBlock.info(indent*2 + f"\033[4mdefault\033[0m: {vals.default}")
406 logCPAlgCfgBlock.info(indent*2 + f"\033[4mrequired\033[0m: {vals.required}")
407 logCPAlgCfgBlock.info(indent*2 + f"\033[4mnoneAction\033[0m: {vals.noneAction}")
408 printWrap(f"\033[4minfo\033[0m: {vals.info}", indent=indent*2)
409 else:
410 logCPAlgCfgBlock.info(indent + f"{ opt}: {self.getOptionValue(opt)}")
411
412
413 def hasOption (self, name) :
414 """whether the configuration block has the given option
415
416 WARNING: The backend to option handling is slated to be
417 replaced at some point. This particular function may change
418 behavior, interface or be removed/replaced entirely.
419 """
420 return name in self._options
421
422
423 def __eq__(self, blockName):
424 """
425 Implementation of == operator. Used for seaching configSeque.
426 E.g. if blockName in configSeq:
427 """
428 return self._blockName == blockName
429
430
431 def __str__(self):
432 return self._blockName if self._blockName else self.factoryName()
433
434
435 @classmethod
437 # Access the current count for this class
438 return ConfigBlock.instance_counts.get(cls, 0)
439
440 def _is_expert_value(self, rule, value):
441 """
442 Check whether value matches an expert mode rule.
443 Rule can be:
444 - A literal (compared with ==)
445 - A callable predicate (called with value)
446 - A special marker string (common callable)
447 """
448 if callable(rule):
449 return rule(value)
450
451 if isinstance(rule, str):
452 if rule == "nonemptystring":
453 return isinstance(value, str) and value != ""
454 if rule == "nonemptylist":
455 return isinstance(value, list) and value != []
456 if rule == "positiveint":
457 return isinstance(value, int) and value > 0
458
459 # Fallback: direct value comparison
460 return value == rule
461
462 def checkExpertSettings(self, config):
463 """
464 Check if any settings require expert mode and validate accordingly.
465 If any setting is set to a value that requires expert mode but we're
466 not in expert mode, raise an error.
467 """
468 for option_name, expert_rule in self._expertModeSettings.items():
469 current_value = self.getOptionValue(option_name)
470 default_value = self._options[option_name].default
471
472 if expert_rule is True:
473 # Any deviation from the default requires expert mode
474 if current_value != default_value:
475 warnings.warn(
476 f"Block '{self.factoryName()}' option '{option_name}' "
477 f"set to '{current_value}' (default '{default_value}'), "
478 f"requires expert mode.",
479 ExpertModeWarning, stacklevel=2
480 )
481
482 else: # it's a list of expert values/markers/predicates
483 for ev in expert_rule:
484 if self._is_expert_value(ev, current_value):
485 warnings.warn(
486 f"Block '{self.factoryName()}' option '{option_name}' "
487 f"set to expert-only value '{current_value}'. "
488 f"Requires expert mode.",
489 ExpertModeWarning, stacklevel=2
490 )
491 # All checks passed
492 return
__init__(self, blockName, required=True)
__init__(self, type=None, info='', noneAction='ignore', required=False, default=None)
_is_expert_value(self, rule, value)
printOptions(self, verbose=False, width=60, indent=" ")
setOptionValue(self, name, value)
addDependency(self, dependencyName, required=True)
addOption(self, name, defaultValue, *, type, info='', noneAction='ignore', required=False, expertMode=None)
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition hcg.cxx:312
alphanumeric_block_name(func)
filter_dsids(filterList, config)