3from AnalysisAlgorithmsConfig.ConfigBlock
import ConfigBlock
4from AnaAlgorithm.Logging
import logging
5logCPAlgCfgSeq = logging.getLogger(
'CPAlgCfgSeq')
7from functools
import wraps
8from random
import randrange
13 Decorates a configSequence or function with 'seq' as a
16 Sets groupName to the name of the decorated funtion or
17 calss plus and integer for each ConfigBlock in the configSequence.
19 Blocks with the same groupName can be configured together.
22 def wrapper(**kwargs):
24 groupName = f
"{func.__name__}_{randrange(10**8):08}"
25 for block
in kwargs[
'seq']:
26 block.setOptionValue(
'groupName', groupName)
30 """a sequence of ConfigBlock objects
32 This could in principle just be a simple python list, and maybe we
33 change it to that at some point (10 Mar 22). Having it as its own
34 class allows to implement some helper functions.
36 This implements an interface similar to ConfigBlock, but it
37 doesn't derive from it, as ConfigBlock will likely gain
38 functionality in the future that wouldn't work for a sequence (or
39 wouldn't work in the same way).
48 """append a configuration block to the sequence"""
53 """call makeAlgs() on all blocks
55 This will create the actual algorithm configurables based on
56 how the blocks are configured right now.
59 if not block.isUsedForConfig(config):
61 config.setAlgPostfix(block.instanceName())
62 block.checkExpertSettings (config)
63 block.makeAlgs (config)
64 config.setAlgPostfix(
'')
65 ConfigBlock.instance_counts.clear()
70 Apply any properties that were set in the block's
71 'propertyOverrides' option.
74 if not block.isUsedForConfig(config):
76 config.setAlgPostfix(block.instanceName())
77 block.applyConfigOverrides(config)
78 config.setAlgPostfix(
'')
82 Check for blocks with dependencies.
84 If a block required another block that is not present, will
85 throw an error; Otherwise, will move block immediately after
86 required block. If dependency is not required, will move
87 after other block, if it is present.
89 Note: this implementation can only move blocks forward.
91 def moveBlock(blocks):
92 for i, block
in enumerate(blocks):
94 ignore = block.getOptionValue(
'ignoreDependencies')
95 if block.hasDependencies():
97 for dep
in block.getDependencies():
102 lastIdx =
max(index
for index,value
in enumerate(blocks)
if value == dep.blockName)
106 raise ValueError(f
"{dep} block is required"
107 f
" for {block} but was not found.")
110 logCPAlgCfgSeq.info(f
"Moving {block} after {blocks[depIdx]}")
112 blocks.insert(depIdx, blocks.pop(i))
117 for _
in range(MAXTRIES):
122 raise Exception(
"Could not order blocks based on dependencies"
123 f
" in {MAXTRIES} moves.")
127 """do the full configuration on this sequence
129 This sequence needs to be the only sequence, i.e. it needs to
130 contain all the blocks that will be configured, as it will
131 perform all configuration steps at once.
134 if re.compile (
'^[_a-zA-Z0-9]*$').match (block.instanceName())
is None :
135 raise ValueError (f
'invalid block instance name: {block.instanceName()} for {block.factoryName()}')
145 """set the given option on the sequence
147 The name should generally be of the form
148 "groupName.optionName" to identify what group the option
151 For simplicity I also allow a ".optionName" here, which will
152 then set the property in the last group added. That makes it
153 fairly straightforward to add new blocks, set options on them,
154 and then move on to the next blocks. Please note that this
155 mechanism ought to be viewed as strictly as a temporary
156 convenience, and this short cut may go away once better
157 alternatives are available.
159 WARNING: The backend to option handling is slated to be
160 replaced at some point. This particular function may change
161 behavior, interface or be removed/replaced entirely.
163 names = name.split(
'.')
165 optionName = names.pop(-1)
168 groupName = names.pop(0)
if names
else ''
170 raise ValueError(f
'Option name can be either <groupName>.<optionName>'
171 f
' or <optionName> not {name}')
175 groupName = blocks[-1].getOptionValue(
'groupName')
180 if ( block.getOptionValue(
'groupName') == groupName
181 and block.hasOption(optionName) ):
182 block.setOptionValue (optionName, value, **kwargs)
185 raise ValueError(f
'{optionName} not found in blocks with '
186 f
'group name {groupName}')
189 blocks[-1].setOptionValue (optionName, value, **kwargs)
194 Prints options and their values for each config block in a config sequence
197 logCPAlgCfgSeq.info(config.__class__.__name__)
198 config.printOptions(verbose=verbose)
202 """get information on options for last block in sequence"""
204 groupName = self.
_blocks[-1].getOptionValue(
'groupName')
208 for block
in self.
_blocks[:-1]:
209 if block.getOptionValue(
'groupName') == groupName:
214 for name, o
in block.getOptions().items():
215 val = getattr(block, name)
216 valDefault = o.default
218 valRequired = o.required
219 noneAction = o.noneAction
220 options.append({
'name': name,
'defaultValue': valDefault,
221 'type': valType,
'required': valRequired,
222 'noneAction': noneAction,
'value': val})
227 """Set options for a ConfigBlock"""
229 for opt
in algOptions:
233 logCPAlgCfgSeq.debug(f
" {name}: {options[name]}")
236 raise ValueError(f
'{name} is required but not included in config')
238 defaultVal = opt[
'value']
if opt[
'value']
else opt[
'defaultValue']
240 if name !=
'groupName':
241 options[name] = defaultVal
242 logCPAlgCfgSeq.debug(f
" {name}: {defaultVal}")
249 Assigns all blocks in configSequence groupName. If no name is
250 provided, the name is set to group_ plus an integer.
252 Blocks with the same groupName can be configured together.
255 groupName = f
"group_{randrange(10**8):08}"
257 block.setOptionValue(
'groupName', groupName)
262 Set the factory name for all blocks in the sequence.
264 This is used to set a common factory name for all blocks, which
265 can be useful for debugging or logging purposes.
271 for index, block
in enumerate(self.
_blocks):
272 block.setFactoryName(f
"{factoryName}[{index}:{block.__class__.__name__}]")
275 """Add another sequence to this one
277 This function is used to add another sequence to this sequence
278 using the '+=' operator.
281 if not isinstance( sequence, ConfigSequence ):
282 raise TypeError(
'The received object is not of type ConfigSequence' )
284 for block
in sequence._blocks :
292 """Create an iterator over all the configurations in this sequence
294 This is to allow for a Python-like iteration over all
295 configuration blocks that are part of the sequence.
groupBlocks(self, groupName='')
setOptionValue(self, name, value, **kwargs)
__iadd__(self, sequence, index=None)
fullConfigure(self, config)
setFactoryName(self, factoryName)
setOptions(self, options)
printOptions(self, verbose=False)
applyConfigOverrides(self, config)