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, *addDefaultBlocks=True)
 
def setConfig (self, config)
 
def loadConfig (self, yamlPath)
 
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)
 

Private Attributes

 _config
 
 __loadedYaml
 
 _last
 

Detailed Description

Definition at line 33 of file ConfigText.py.

Constructor & Destructor Documentation

◆ __init__()

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

Definition at line 34 of file ConfigText.py.

34  def __init__(self, yamlPath=None, *, addDefaultBlocks=True):
35  super().__init__(addDefaultBlocks=False)
36 
37  # Block to add new blocks to this object
38  self.addAlgConfigBlock(algName="AddConfigBlocks", alg=self._addNewConfigBlocks,
39  defaults={'self': self})
40  # add default blocks
41  if addDefaultBlocks:
42  self.addDefaultAlgs()
43  # load yaml
44  self._config = {}
45  # do not allow for loading multiple yaml files
46  self.__loadedYaml = False
47  if yamlPath is not None:
48  self.loadConfig(yamlPath)
49  # last is used for setOptionValue when using addBlock
50  self._last = None
51 
52 

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 183 of file ConfigText.py.

183  def _addNewConfigBlocks(self, modulePath, functionName,
184  algName, defaults=None, pos=None, superBlocks=None):
185  """
186  Load <functionName> from <modulePath>
187  """
188  try:
189  module = importlib.import_module(modulePath)
190  fxn = getattr(module, functionName)
191  except ModuleNotFoundError as e:
192  raise ModuleNotFoundError(f"{e}\nFailed to load {functionName} from {modulePath}")
193  else:
194  sys.modules[functionName] = fxn
195  # add new algorithm to available algorithms
196  self.addAlgConfigBlock(algName=algName, alg=fxn,
197  defaults=defaults,
198  superBlocks=superBlocks,
199  pos=pos)
200  return
201 
202 

◆ _configureAlg()

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

Definition at line 203 of file ConfigText.py.

203  def _configureAlg(self, block, blockConfig, configSeq=None, containerName=None):
204  if not isinstance(blockConfig, list):
205  blockConfig = [blockConfig]
206 
207  for options in blockConfig:
208  # Special case: propogate containerName down to subAlgs
209  if 'containerName' in options:
210  containerName = options['containerName']
211  elif containerName is not None and 'containerName' not in options:
212  options['containerName'] = containerName
213  # will check which options are associated alg and not options
214  logCPAlgTextCfg.info(f"Configuring {block.algName}")
215  seq, funcOpts = block.makeConfig(options)
216  if not seq._blocks:
217  continue
218  algOpts = seq.setOptions(options)
219  if configSeq is not None:
220  configSeq += seq
221 
222  # check to see if there are unused parameters
223  algOpts = [i['name'] for i in algOpts]
224  expectedOptions = set(funcOpts)
225  expectedOptions |= set(algOpts)
226  expectedOptions |= set(block.subAlgs)
227 
228  difference = set(options.keys()) - expectedOptions
229  if difference:
230  difference = "\n".join(difference)
231  raise ValueError(f"There are options set that are not used for "
232  f"{block.algName}:\n{difference}\n"
233  "Please check your configuration.")
234 
235  # check for sub-blocks and call this function recursively
236  for alg in self._order.get(block.algName, []):
237  if alg in options:
238  subAlg = block.subAlgs[alg]
239  self._configureAlg(subAlg, options[alg], configSeq, containerName)
240  return configSeq
241 
242 

◆ addBlock()

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

Definition at line 122 of file ConfigText.py.

122  def addBlock(self, name, **kwargs):
123  """
124  Create entry into dictionary representing the text configuration
125  """
126  def setEntry(name, config, opts):
127  if '.' not in name:
128  if name not in config:
129  config[name] = opts
130  elif isinstance(config[name], list):
131  config[name].append(opts)
132  else:
133  config[name] = [config[name], opts]
134  # set last added block for setOptionValue
135  self._last = opts
136  else:
137  name, rest = name[:name.index('.')], name[name.index('.') + 1:]
138  config = config[name]
139  if isinstance(config, list):
140  config = config[-1]
141  setEntry(rest, config, opts)
142  return
143  setEntry(name, self._config, dict(kwargs))
144  return
145 
146 

◆ configure()

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

Definition at line 158 of file ConfigText.py.

158  def configure(self):
159  """Process YAML configuration file and confgure added algorithms."""
160  # make sure all blocks in yaml file are added (otherwise they would be ignored)
161  for blockName in self._config:
162  if blockName not in self._order[self.ROOTNAME]:
163  raise ValueError(f"Unkown block {blockName} in yaml file")
164 
165  # configure blocks
166  configSeq = ConfigSequence()
167  for blockName in self._order[self.ROOTNAME]:
168  if blockName == "AddConfigBlocks":
169  continue
170 
171  assert blockName in self._algs
172 
173  # order only applies to root blocks
174  if blockName in self._config:
175  blockConfig = self._config[blockName]
176  alg = self._algs[blockName]
177  self._configureAlg(alg, blockConfig, configSeq)
178  else:
179  continue
180  return configSeq
181 
182 

◆ loadConfig()

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

Definition at line 61 of file ConfigText.py.

61  def loadConfig(self, yamlPath):
62  """
63  read a YAML file. Will combine with any config blocks added using python
64  """
65  if self.__loadedYaml or isinstance(yamlPath, list):
66  raise NotImplementedError("Mering multiple yaml files is not implemented.")
67  self.__loadedYaml = True
68 
69  def merge(config, algs, path=''):
70  """Add to config block-by-block"""
71  if not isinstance(config, list):
72  config = [config]
73  # loop over list of blocks with same block name
74  for blocks in config:
75  # deal with case where empty dict is config
76  if blocks == {} and path:
77  self.addBlock(path)
78  return
79  # remove any subBlocks from block config
80  subBlocks = {}
81  for blockName in algs:
82  if blockName in blocks:
83  subBlocks[blockName] = blocks.pop(blockName)
84  # anything left should be a block and it's configuration
85  if blocks:
86  self.addBlock(path, **blocks)
87  # add in any subBlocks
88  for subName, subBlock in subBlocks.items():
89  newPath = f'{path}.{subName}' if path else subName
90  merge(subBlock, algs[subName].subAlgs, newPath)
91  return
92 
93  logCPAlgTextCfg.info(f'loading {yamlPath}')
94  config = readYaml(yamlPath)
95  # check if blocks are defined in yaml file
96  if "AddConfigBlocks" in config:
97  self._configureAlg(self._algs["AddConfigBlocks"], config["AddConfigBlocks"])
98  merge(config, self._algs)
99  return
100 
101 

◆ printConfig()

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

Definition at line 102 of file ConfigText.py.

102  def printConfig(self, sort=False, jsonFormat=False):
103  """Print YAML configuration file."""
104  if self._config is None:
105  raise ValueError("No configuration has been loaded.")
106  printYaml(self._config, sort, jsonFormat)
107  return
108 
109 

◆ 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 110 of file ConfigText.py.

110  def saveYaml(self, filePath='config.yaml', default_flow_style=False,
111  **kwargs):
112  """
113  Convert dictionary representation to yaml and save
114  """
115  logCPAlgTextCfg.info(f"Saving configuration to {filePath}")
116  config = self._config
117  with open(filePath, 'w') as outfile:
118  yaml.dump(config, outfile, default_flow_style=False, **kwargs)
119  return
120 
121 

◆ setConfig()

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

Definition at line 53 of file ConfigText.py.

53  def setConfig(self, config):
54  """Print YAML configuration file."""
55  if self._config:
56  raise ValueError("Configuration has already been loaded.")
57  self._config = config
58  return
59 
60 

◆ 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 147 of file ConfigText.py.

147  def setOptions(self, **kwargs):
148  """
149  Set option(s) for the lsat block that was added. If an option
150  was added previously, will update value
151  """
152  if self._last is None:
153  raise TypeError("Cannot set options before adding a block")
154  # points to dict with opts for last added block
155  self._last.update(**kwargs)
156 
157 

Member Data Documentation

◆ __loadedYaml

python.ConfigText.TextConfig.__loadedYaml
private

Definition at line 46 of file ConfigText.py.

◆ _config

python.ConfigText.TextConfig._config
private

Definition at line 44 of file ConfigText.py.

◆ _last

python.ConfigText.TextConfig._last
private

Definition at line 50 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:19
python.ConfigText.printYaml
def printYaml(d, sort=False, jsonFormat=False)
Definition: ConfigText.py:28
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:224
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
dqt_zlumi_pandas.update
update
Definition: dqt_zlumi_pandas.py:42
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:17
merge
Definition: merge.py:1