ATLAS Offline Software
Public Member Functions | Private Member Functions | Private Attributes | List of all members
python.ConfigText.TextConfig Class Reference
Inheritance diagram for python.ConfigText.TextConfig:
Collaboration diagram for python.ConfigText.TextConfig:

Public Member Functions

def __init__ (self, yamlPath=None, *config=None, addDefaultBlocks=True)
 
def setConfig (self, config)
 
def preprocessConfig (self, config, algs)
 
def cleanupPlaceholders (self, config)
 
def loadConfig (self, yamlPath=None, *configDict=None)
 
def printConfig (self, sort=False, jsonFormat=False)
 
def saveYaml (self, filePath='config.yaml', default_flow_style=False, **kwargs)
 
def addBlock (self, name, **kwargs)
 
def setOptions (self, **kwargs)
 
def configure (self)
 

Private Member Functions

def _addNewConfigBlocks (self, modulePath, functionName, algName, defaults=None, pos=None, superBlocks=None)
 
def _configureAlg (self, block, blockConfig, configSeq=None, containerName=None, extraOptions=None)
 

Private Attributes

 _config
 
 __loadedYaml
 
 _last
 

Detailed Description

Definition at line 35 of file ConfigText.py.

Constructor & Destructor Documentation

◆ __init__()

def python.ConfigText.TextConfig.__init__ (   self,
  yamlPath = None,
config = None,
  addDefaultBlocks = True 
)

Definition at line 36 of file ConfigText.py.

36  def __init__(self, yamlPath=None, *, config=None, addDefaultBlocks=True):
37  super().__init__(addDefaultBlocks=False)
38 
39  if yamlPath and config:
40  raise ValueError("Cannot specify both yamlPath and config. Use one or the other.")
41 
42  # Block to add new blocks to this object
43  self.addAlgConfigBlock(algName="AddConfigBlocks", alg=self._addNewConfigBlocks,
44  defaults={'self': self})
45  # add default blocks
46  if addDefaultBlocks:
47  self.addDefaultAlgs()
48  # load yaml
49  self._config = {}
50  # do not allow for loading multiple yaml files
51  self.__loadedYaml = False
52  if yamlPath is not None or config is not None:
53  self.loadConfig(yamlPath, configDict=config)
54  # last is used for setOptionValue when using addBlock
55  self._last = None
56 
57 

Member Function Documentation

◆ _addNewConfigBlocks()

def python.ConfigText.TextConfig._addNewConfigBlocks (   self,
  modulePath,
  functionName,
  algName,
  defaults = None,
  pos = None,
  superBlocks = None 
)
private
Load <functionName> from <modulePath>

Definition at line 237 of file ConfigText.py.

237  def _addNewConfigBlocks(self, modulePath, functionName,
238  algName, defaults=None, pos=None, superBlocks=None):
239  """
240  Load <functionName> from <modulePath>
241  """
242  try:
243  module = importlib.import_module(modulePath)
244  fxn = getattr(module, functionName)
245  except ModuleNotFoundError as e:
246  raise ModuleNotFoundError(f"{e}\nFailed to load {functionName} from {modulePath}")
247  else:
248  sys.modules[functionName] = fxn
249  # add new algorithm to available algorithms
250  self.addAlgConfigBlock(algName=algName, alg=fxn,
251  defaults=defaults,
252  superBlocks=superBlocks,
253  pos=pos)
254  return
255 
256 

◆ _configureAlg()

def python.ConfigText.TextConfig._configureAlg (   self,
  block,
  blockConfig,
  configSeq = None,
  containerName = None,
  extraOptions = None 
)
private

Definition at line 257 of file ConfigText.py.

257  def _configureAlg(self, block, blockConfig, configSeq=None, containerName=None,
258  extraOptions=None):
259  if not isinstance(blockConfig, list):
260  blockConfig = [blockConfig]
261 
262  for options in blockConfig:
263  # Special case: propogate containerName down to subAlgs
264  if 'containerName' in options:
265  containerName = options['containerName']
266  elif containerName is not None and 'containerName' not in options:
267  options['containerName'] = containerName
268  # will check which options are associated alg and not options
269  logCPAlgTextCfg.info(f"Configuring {block.algName}")
270  seq, funcOpts = block.makeConfig(options)
271  if not seq._blocks:
272  continue
273  algOpts = seq.setOptions(options)
274  # If containerName was not set explicitly, we can now retrieve
275  # its default value
276  if containerName is None:
277  for opt in algOpts:
278  if 'name' in opt and opt['name'] == 'containerName':
279  containerName = opt.get('value', None)
280  break # Exit the loop as we've found the key
281 
282  if configSeq is not None:
283  configSeq += seq
284 
285  # propagate special extra options to subalgs
286  if extraOptions is None:
287  extraOptionsList = ["skipOnData", "skipOnMC", "onlyForDSIDs"]
288  for i in algOpts:
289  if i['name'] in extraOptionsList and i['defaultValue'] != i['value']:
290  if extraOptions is None:
291  extraOptions = {}
292  extraOptions[i['name']] = i['value']
293  else:
294  algOpts = seq.setOptions(extraOptions.copy())
295 
296  # check to see if there are unused parameters
297  algOpts = [i['name'] for i in algOpts]
298  expectedOptions = set(funcOpts)
299  expectedOptions |= set(algOpts)
300  expectedOptions |= set(block.subAlgs)
301 
302  difference = set(options.keys()) - expectedOptions
303  difference.discard('__placeholder__')
304  if difference:
305  difference = "\n".join(difference)
306  raise ValueError(f"There are options set that are not used for "
307  f"{block.algName}:\n{difference}\n"
308  "Please check your configuration.")
309 
310  # check for sub-blocks and call this function recursively
311  for alg in self._order.get(block.algName, []):
312  if alg in options:
313  subAlg = block.subAlgs[alg]
314  self._configureAlg(subAlg, options[alg], configSeq, containerName, extraOptions)
315  return configSeq
316 
317 

◆ addBlock()

def python.ConfigText.TextConfig.addBlock (   self,
  name,
**  kwargs 
)
Create entry into dictionary representing the text configuration

Definition at line 174 of file ConfigText.py.

174  def addBlock(self, name, **kwargs):
175  """
176  Create entry into dictionary representing the text configuration
177  """
178  def setEntry(name, config, opts):
179  if '.' not in name:
180  if name not in config:
181  config[name] = opts
182  elif isinstance(config[name], list):
183  config[name].append(opts)
184  else:
185  config[name] = [config[name], opts]
186  # set last added block for setOptionValue
187  self._last = opts
188  else:
189  name, rest = name[:name.index('.')], name[name.index('.') + 1:]
190  config = config[name]
191  if isinstance(config, list):
192  config = config[-1]
193  setEntry(rest, config, opts)
194  return
195  setEntry(name, self._config, dict(kwargs))
196  return
197 
198 

◆ cleanupPlaceholders()

def python.ConfigText.TextConfig.cleanupPlaceholders (   self,
  config 
)
Remove placeholder markers after initialization.

Definition at line 90 of file ConfigText.py.

90  def cleanupPlaceholders(self, config):
91  """
92  Remove placeholder markers after initialization.
93  """
94  if not isinstance(config, dict):
95  return
96  if "__placeholder__" in config:
97  del config["__placeholder__"]
98  for key, value in config.items():
99  self.cleanupPlaceholders(value)
100 

◆ configure()

def python.ConfigText.TextConfig.configure (   self)
Process YAML configuration file and confgure added algorithms.

Definition at line 210 of file ConfigText.py.

210  def configure(self):
211  """Process YAML configuration file and confgure added algorithms."""
212  # make sure all blocks in yaml file are added (otherwise they would be ignored)
213  for blockName in self._config:
214  if blockName not in self._order[self.ROOTNAME]:
215  if not blockName:
216  blockName = list(self._config[blockName].keys())[0]
217  raise ValueError(f"Unkown block {blockName} in yaml file")
218 
219  # configure blocks
220  configSeq = ConfigSequence()
221  for blockName in self._order[self.ROOTNAME]:
222  if blockName == "AddConfigBlocks":
223  continue
224 
225  assert blockName in self._algs
226 
227  # order only applies to root blocks
228  if blockName in self._config:
229  blockConfig = self._config[blockName]
230  alg = self._algs[blockName]
231  self._configureAlg(alg, blockConfig, configSeq)
232  else:
233  continue
234  return configSeq
235 
236 

◆ loadConfig()

def python.ConfigText.TextConfig.loadConfig (   self,
  yamlPath = None,
configDict = None 
)
read a YAML file. Will combine with any config blocks added using python

Definition at line 101 of file ConfigText.py.

101  def loadConfig(self, yamlPath=None, *, configDict=None):
102  """
103  read a YAML file. Will combine with any config blocks added using python
104  """
105  if self.__loadedYaml or isinstance(yamlPath, list):
106  raise NotImplementedError("Mering multiple yaml files is not implemented.")
107  self.__loadedYaml = True
108 
109  def merge(config, algs, path=''):
110  """Add to config block-by-block"""
111  if not isinstance(config, list):
112  config = [config]
113  # loop over list of blocks with same block name
114  for blocks in config:
115  # deal with case where empty dict is config
116  if blocks == {} and path:
117  self.addBlock(path)
118  return
119  # remove any subBlocks from block config
120  subBlocks = {}
121  for blockName in algs:
122  if blockName in blocks:
123  subBlocks[blockName] = blocks.pop(blockName)
124  # anything left should be a block and it's configuration
125  if blocks:
126  self.addBlock(path, **blocks)
127  # add in any subBlocks
128  for subName, subBlock in subBlocks.items():
129  newPath = f'{path}.{subName}' if path else subName
130  merge(subBlock, algs[subName].subAlgs, newPath)
131  return
132 
133  logCPAlgTextCfg.info(f'loading {yamlPath}')
134  if configDict is not None:
135  # if configDict is provided, use it directly
136  config = configDict
137  else:
138  config = readYaml(yamlPath)
139  # check if blocks are defined in yaml file
140  if "AddConfigBlocks" in config:
141  self._configureAlg(self._algs["AddConfigBlocks"], config["AddConfigBlocks"])
142 
143  # Preprocess the configuration dictionary (see !76767)
144  self.preprocessConfig(config, self._algs)
145 
146  merge(config, self._algs)
147 
148  # Cleanup placeholders (see !76767)
149  self.cleanupPlaceholders(config)
150 
151  return
152 
153 

◆ preprocessConfig()

def python.ConfigText.TextConfig.preprocessConfig (   self,
  config,
  algs 
)
Preprocess the configuration dictionary.
Ensure blocks with only sub-blocks are initialized with an empty dictionary.

Definition at line 66 of file ConfigText.py.

66  def preprocessConfig(self, config, algs):
67  """
68  Preprocess the configuration dictionary.
69  Ensure blocks with only sub-blocks are initialized with an empty dictionary.
70  """
71  def processNode(node, algs):
72  if not isinstance(node, dict):
73  return # Base case: not a dictionary
74  for blockName, blockContent in list(node.items()):
75  # If the block name is recognized in algs
76  if blockName in algs:
77  # If the block only defines sub-blocks, initialize it
78  if isinstance(blockContent, dict) and not any(
79  key in algs[blockName].options for key in blockContent
80  ):
81  # Ensure parent block is initialized as an empty dictionary
82  node[blockName] = {'__placeholder__': True, **blockContent}
83  # Recurse into sub-blocks
84  processNode(node[blockName], algs[blockName].subAlgs)
85 
86  # Start processing from the root of the configuration
87  processNode(config, algs)
88 

◆ printConfig()

def python.ConfigText.TextConfig.printConfig (   self,
  sort = False,
  jsonFormat = False 
)
Print YAML configuration file.

Definition at line 154 of file ConfigText.py.

154  def printConfig(self, sort=False, jsonFormat=False):
155  """Print YAML configuration file."""
156  if self._config is None:
157  raise ValueError("No configuration has been loaded.")
158  printYaml(self._config, sort, jsonFormat)
159  return
160 
161 

◆ saveYaml()

def python.ConfigText.TextConfig.saveYaml (   self,
  filePath = 'config.yaml',
  default_flow_style = False,
**  kwargs 
)
Convert dictionary representation to yaml and save

Definition at line 162 of file ConfigText.py.

162  def saveYaml(self, filePath='config.yaml', default_flow_style=False,
163  **kwargs):
164  """
165  Convert dictionary representation to yaml and save
166  """
167  logCPAlgTextCfg.info(f"Saving configuration to {filePath}")
168  config = self._config
169  with open(filePath, 'w') as outfile:
170  yaml.dump(config, outfile, default_flow_style=False, **kwargs)
171  return
172 
173 

◆ setConfig()

def python.ConfigText.TextConfig.setConfig (   self,
  config 
)
Print YAML configuration file.

Definition at line 58 of file ConfigText.py.

58  def setConfig(self, config):
59  """Print YAML configuration file."""
60  if self._config:
61  raise ValueError("Configuration has already been loaded.")
62  self._config = config
63  return
64 

◆ setOptions()

def python.ConfigText.TextConfig.setOptions (   self,
**  kwargs 
)
Set option(s) for the lsat block that was added. If an option
was added previously, will update value

Definition at line 199 of file ConfigText.py.

199  def setOptions(self, **kwargs):
200  """
201  Set option(s) for the lsat block that was added. If an option
202  was added previously, will update value
203  """
204  if self._last is None:
205  raise TypeError("Cannot set options before adding a block")
206  # points to dict with opts for last added block
207  self._last.update(**kwargs)
208 
209 

Member Data Documentation

◆ __loadedYaml

python.ConfigText.TextConfig.__loadedYaml
private

Definition at line 51 of file ConfigText.py.

◆ _config

python.ConfigText.TextConfig._config
private

Definition at line 49 of file ConfigText.py.

◆ _last

python.ConfigText.TextConfig._last
private

Definition at line 55 of file ConfigText.py.


The documentation for this class was generated from the following file:
configure
bool configure(asg::AnaToolHandle< ITrigGlobalEfficiencyCorrectionTool > &tool, ToolHandleArray< IAsgElectronEfficiencyCorrectionTool > &electronEffToolsHandles, ToolHandleArray< IAsgElectronEfficiencyCorrectionTool > &electronSFToolsHandles, ToolHandleArray< CP::IMuonTriggerScaleFactors > &muonToolsHandles, ToolHandleArray< IAsgPhotonEfficiencyCorrectionTool > &photonEffToolsHandles, ToolHandleArray< IAsgPhotonEfficiencyCorrectionTool > &photonSFToolsHandles, const std::string &triggers, const std::map< std::string, std::string > &legsPerTool, unsigned long nToys, bool debug)
Definition: TrigGlobEffCorrValidation.cxx:514
dumpHVPathFromNtuple.append
bool append
Definition: dumpHVPathFromNtuple.py:91
python.ConfigText.readYaml
def readYaml(yamlPath)
Definition: ConfigText.py:21
python.ConfigText.printYaml
def printYaml(d, sort=False, jsonFormat=False)
Definition: ConfigText.py:30
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
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
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
python.processes.powheg.ZZ.ZZ.__init__
def __init__(self, base_directory, **kwargs)
Constructor: all process options are set here.
Definition: ZZ.py:18
Trk::open
@ open
Definition: BinningType.h:40
get
T * get(TKey *tobj)
get a TObject* from a TKey* (why can't a TObject be a TKey?)
Definition: hcg.cxx:127
python.utility.LHE.merge
def merge(input_file_pattern, output_file)
Merge many input LHE files into a single output file.
Definition: LHE.py:29
python.Bindings.keys
keys
Definition: Control/AthenaPython/python/Bindings.py:801
merge
Definition: merge.py:1