10 from inspect
import isclass
13 VERBOSE, DEBUG, INFO, WARNING, ERROR, FATAL
20 ControlFlowLeaf, ControlFlowNode,
24 __all__ = [
'Configurable',
25 'ConfigurableAlgorithm',
26 'ConfigurableAlgTool',
27 'ConfigurableAuditor',
28 'ConfigurableService',
30 'VERBOSE',
'DEBUG',
'INFO',
'WARNING',
'ERROR',
'FATAL',
31 'appendPostConfigAction',
'removePostConfigAction']
35 log = logging.getLogger(
'Configurable')
40 Expand environment variables "data". 41 Data can be string, list, tuple and dictionary. For collection, all the 42 contained strings will be manipulated (recursively). 47 return os.path.expandvars(data)
48 elif typ
in [list, tuple]:
63 Error occurred in the configuration process. 70 class PropertyReference(object):
75 return "@%s" % self.
name 80 refname, refprop = self.name.rsplit(
'.', 1)
81 if refname
in Configurable.allConfigurables:
82 conf = Configurable.allConfigurables[refname]
83 retval = getattr(conf, refprop)
84 if hasattr(retval,
"getFullName"):
85 retval = retval.getFullName()
87 raise NameError(
"name '%s' not found resolving '%s'" %
92 """This function allow transparent integration with 93 Configurable.getValuedProperties. 100 except AttributeError:
108 """Base class for Gaudi components that implement the IProperty interface. 109 Provides most of the boilerplate code, but the actual useful classes 110 are its derived ConfigurableAlgorithm, ConfigurableService, and 111 ConfigurableAlgTool.""" 117 propertyNoValue =
'<no value>' 119 printHeaderWidth = 100
134 allConfigurables = {}
135 configurableServices = {}
138 _configurationLocked =
False 141 """To Gaudi, any object with the same type/name is the same object. Hence, 142 this is mimicked in the configuration: instantiating a new Configurable 143 of a type with the same name will return the same instance.""" 149 name = kwargs[
'name']
150 elif 'name' in cls.__init__.func_code.co_varnames:
152 index = list(cls.__init__.func_code.co_varnames).index(
'name')
155 name = args[index - 1]
158 name = cls.__init__.func_defaults[index - (len(args) + 1)]
163 except (IndexError, TypeError):
165 'no "name" argument while instantiating "%s"' % cls.__name__)
169 if hasattr(cls,
'DefaultedName'):
170 name = cls.DefaultedName
173 elif not name
or type(name) != str:
176 'could not retrieve name from %s.__init__ arguments' % cls.__name__)
180 if issubclass(cls, ConfigurableAlgTool)
and '.' not in name:
181 name =
'ToolSvc.' + name
191 if name
in cls.configurables:
192 conf = cls.configurables[name]
194 cls.configurables[conf.getType()] = conf
196 for n, v
in kwargs.items():
199 if not cls.
_configurationLocked and not "_enabled" in kwargs
and isinstance(conf, ConfigurableUser):
202 setattr(conf,
"_enabled",
True)
206 spos = name.find(
'/')
209 ti_name =
"%s/%s" % (name, name)
210 if ti_name
in cls.configurables:
212 return cls.configurables[ti_name]
217 if i_name == name[spos + 1:]
and i_name
in cls.configurables:
219 return cls.configurables[i_name]
222 conf = cls.allConfigurables.get(name,
None)
or\
223 (spos < 0
and cls.allConfigurables.get(ti_name,
None))
or\
224 (spos > 0
and i_name == name[spos + 1:]
225 and cls.allConfigurables.get(i_name,
None))
227 if conf.__class__
is ConfigurableGeneric:
231 newconf = object.__new__(cls)
232 cls.
__init__(newconf, *args, **kwargs)
237 for n
in newconf.__slots__:
239 for n
in conf._properties:
240 if names[n.lower()] != n:
241 log.warning(
"Option '%s' was used for %s, but the correct spelling is '%s'" % (
242 n, name, names[n.lower()]))
243 setattr(newconf, names[n.lower()], getattr(conf, n))
244 for n, v
in kwargs.items():
245 setattr(newconf, n, v)
246 cls.configurables[name] = newconf
251 log.error(
'attempt to redefine type of "%s" (was: %s, new: %s)%s',
252 name, conf.__class__.__name__, cls.__name__, error_explanation)
257 for n, v
in kwargs.items():
262 conf = object.__new__(cls)
266 cls.configurables[name] = conf
268 for base
in cls.__bases__:
269 if base.__name__ ==
'ConfigurableService':
281 klass = self.__class__
284 if klass == Configurable:
285 raise TypeError,
"%s is an ABC and can not be instantiated" % str(
290 meths = {
'getDlls': 1,
295 for meth, nArgs
in meths.items():
297 f = getattr(klass, meth).im_func
298 except AttributeError:
299 raise NotImplementedError,
"%s is missing in class %s" % (
303 nargcount = f.func_code.co_argcount
304 ndefaults = f.func_defaults
and len(f.func_defaults)
or 0
305 if not nargcount - ndefaults <= nArgs <= nargcount:
306 raise TypeError,
"%s.%s requires exactly %d arguments" % (
315 if hasattr(self.__class__,
'DefaultedName'):
316 self.
_name = self.__class__.DefaultedName
337 for name, proxy
in self._properties.items():
339 dict[name] = proxy.__get__(self)
340 except AttributeError:
343 dict[
'_Configurable__children'] = self.
__children 344 dict[
'_Configurable__tools'] = self.
__tools 345 dict[
'_name'] = self.
_name 353 from contextlib
import contextmanager
363 for n, v
in dict.items():
375 newconf = object.__new__(self.__class__)
376 self.__class__.__init__(newconf, self.
getName())
378 for proxy
in self._properties.values():
380 proxy.__set__(newconf, proxy.__get__(self))
381 except AttributeError:
391 if not type(configs)
in (list, tuple):
392 configs = (configs, )
398 if not isinstance(cfg, Configurable):
399 raise TypeError(
"'%s' is not a Configurable" % str(cfg))
404 ccjo = cc.getJobOptName()
406 if c.getJobOptName() == ccjo:
408 'attempt to add a duplicate ... dupe ignored%s', error_explanation)
411 self.__children.append(cc)
415 descr.__set__(self, cc)
417 setattr(self, cc.getName(), cc)
418 except AttributeError:
428 if attr
in self._properties:
429 if isinstance(self._properties[attr].__get__(self), DataObjectHandleBase):
430 return self._properties[attr].__get__(self)
433 if c.getName() == attr:
436 raise AttributeError(
437 "'%s' object has no attribute '%s'" % (self.__class__, attr))
442 "%s: Configuration cannot be modified after the ApplicationMgr has been started." % self.
name())
445 except AttributeError:
446 raise AttributeError(
"Configurable '%s' does not have property '%s'." 447 % (self.__class__.__name__, name))
453 prop = self._properties[attr]
454 prop.__delete__(self)
455 prop.__set__(self, prop.default)
465 if c.getName() == attr:
466 self.__children.remove(c)
470 del self.__dict__[attr]
471 except (AttributeError, KeyError):
478 if type(items) != list
and type(items) != tuple:
488 return copy.deepcopy(child)
502 if hasattr(cc,
'setParent')
and parent:
505 except RuntimeError, e:
507 log.error(str(e) +
'%s', error_explanation)
508 ccbd = cc.configurables[cc.getJobOptName()]
511 for proxy
in self._properties.values():
512 if proxy.history.has_key(cc):
513 proxy.__set__(ccbd, proxy.__get__(cc))
523 return self.__tools.values()
527 "children() is deprecated, use getChildren() instead for consistency")
528 log.error(
"getChildren() returns a copy; to add a child, use 'parent += child'%s",
533 """Get all (private) configurable children, both explicit ones (added with +=) 534 and the ones in the private GaudiHandle properties""" 537 for proxy
in self._properties.values():
539 c = proxy.__get__(self)
540 except AttributeError:
543 if isinstance(c, Configurable)
and not c.isPublic():
545 elif isinstance(c, GaudiHandle):
547 conf = c.configurable
548 except AttributeError:
551 if not conf.isPublic():
553 elif isinstance(c, GaudiHandleArray):
557 if isinstance(ci, Configurable):
561 conf = ci.configurable
562 except AttributeError:
574 elems.append(c.getFullName())
579 if not hasattr(self,
'_initok')
or not self.
_initok:
582 "Configurable.__init__ not called in %s override" % self.__class__.__name__
596 handle = self.getHandle()
598 log.debug(
'no handle for %s: not transporting properties', self.
_name)
602 for name
in self._properties.keys():
603 if hasattr(self, name):
604 setattr(handle, name, getattr(self, name))
611 for name, proxy
in self._properties.items():
613 props[name] = proxy.__get__(self)
614 except AttributeError:
615 props[name] = Configurable.propertyNoValue
620 """Get all properties with their description string as { name : (value, desc) }.""" 622 for name, proxy
in self._properties.items():
624 props[name] = (proxy.__get__(self), proxy.__doc__)
625 except AttributeError:
626 props[name] = (Configurable.propertyNoValue, proxy.__doc__)
631 for name, proxy
in self._properties.items():
633 value = proxy.__get__(self)
634 if hasattr(value,
'getFullName'):
635 value = value.getFullName()
636 elif type(value)
in [list, tuple]:
639 if hasattr(i,
'getFullName'):
640 new_value.append(i.getFullName())
643 value =
type(value)(new_value)
644 elif type(value)
is dict:
647 if hasattr(value[i],
'getFullName'):
650 new_value[i] = value[i]
669 for k, v
in cls._properties.items():
670 if not k
in c.__dict__
and hasattr(v,
'default'):
671 c.__dict__[k] = v.default
684 if name
in c.__dict__:
685 return c.__dict__[name]
689 v = cls._properties[name]
690 if hasattr(v,
'default'):
698 """Returns the value of the given property. 700 if hasattr(self, name):
701 return getattr(self, name)
706 """Set the value of a given property 708 return setattr(self, name, value)
711 """Tell if the property 'name' has been set or not. 713 Because of a problem with list and dictionary properties, in those cases 714 if the value is equal to the default, the property is considered as not 717 if not hasattr(self, name):
720 if isinstance(default, (list, dict, DataObjectHandleBase)):
721 value = getattr(self, name)
722 return value != default
742 log.error(
"jobOptName() is deprecated, use getJobOptName() instead for consistency%s",
756 if log.isEnabledFor(logging.DEBUG):
764 def clone(self, name=None, **kwargs):
766 if hasattr(self,
'DefaultedName'):
767 name = self.DefaultedName
769 name = self.getType()
771 newconf = Configurable.__new__(self.__class__, name)
772 self.__class__.__init__(newconf, name)
774 for proxy
in self._properties.values():
776 value = proxy.__get__(self)
777 if type(value)
in [str, list, dict, tuple]:
779 value =
type(value)(value)
780 proxy.__set__(newconf, value)
781 except AttributeError:
784 for c
in self.__children:
787 for n, t
in self.__tools.items():
788 newconf.addTool(t, n)
790 for name, value
in kwargs.items():
791 setattr(newconf, name, value)
797 dot = fullname.find(
'.')
799 parentname = fullname[:dot]
800 longname = fullname[dot + 1:]
804 dot = longname.find(
'.')
806 name = longname[:dot]
809 return parentname, name, longname
812 if isclass(tool)
and issubclass(tool, ConfigurableAlgTool):
815 priv_tool = tool(self.
getName() +
'.' + name)
816 elif isinstance(tool, ConfigurableAlgTool):
818 name = tool.splitName()[1]
819 priv_tool = tool.clone(self.
getName() +
'.' + name)
822 classname = tool.__name__
824 classname =
type(tool).__name__
825 raise TypeError,
"addTool requires AlgTool configurable. Got %s type" % classname
829 setattr(self, name, self.
__tools[name])
844 handle = __main__.Service(svc)
849 if hasattr(self,
'configure' + svc):
850 eval(
'self.configure' + svc +
'( handle )')
853 dlls = self.getDlls()
856 elif type(dlls) == types.StringType:
859 from __main__
import theApp
860 dlls = filter(
lambda d: d
not in theApp.Dlls, dlls)
873 preLen = Configurable.printHeaderPre
874 postLen = Configurable.printHeaderWidth - \
875 preLen - 3 - len(title)
876 postLen = max(preLen, postLen)
877 return indentStr +
'/%s %s %s' % (preLen *
'*', title, postLen *
'*')
881 preLen = Configurable.printHeaderPre
882 postLen = Configurable.printHeaderWidth - \
883 preLen - 12 - len(title)
884 postLen = max(preLen, postLen)
885 return indentStr +
'\\%s (End of %s) %s' % (preLen *
'-', title, postLen *
'-')
888 return '{0}({1!r})'.
format(self.__class__.__name__, self.
name())
890 def __str__(self, indent=0, headerLastIndentUnit=indentUnit):
892 indentStr = indent * Configurable.indentUnit
897 headerIndent = (indent - 1) * \
898 Configurable.indentUnit + headerLastIndentUnit
901 rep = Configurable._printHeader(headerIndent, title)
907 rep += indentStr +
'|-<no properties>' + os.linesep
911 for p
in props.keys():
912 nameWidth = max(nameWidth, len(p))
913 for p, v
in props.items():
915 prefix = indentStr +
'|-%-*s' % (nameWidth, p)
917 if log.isEnabledFor(logging.DEBUG):
918 if v != Configurable.propertyNoValue:
919 address =
' @%11s' %
hex(id(v))
924 default = defs.get(p)
925 if v == Configurable.propertyNoValue:
927 strVal = repr(default)
931 if hasattr(v,
"getGaudiHandle"):
932 vv = v.getGaudiHandle()
935 if isinstance(vv, GaudiHandle)
or isinstance(vv, GaudiHandleArray):
938 if hasattr(default,
"toStringProperty"):
939 strDef = repr(default.toStringProperty())
941 strDef = repr(default)
942 if strDef == repr(vv.toStringProperty()):
946 strDef = repr(default)
948 line = prefix +
' = ' + strVal
950 if strDef
is not None:
952 if len(line) + len(strDef) > Configurable.printHeaderWidth:
953 line += os.linesep + indentStr +
'| ' + \
954 (len(prefix) - len(indentStr) - 3) *
' ' 955 line +=
' (default: %s)' % (strDef,)
957 rep += line + os.linesep
969 rep += cfg.__str__(indent + 1,
'|=') + os.linesep
972 rep += Configurable._printFooter(indentStr, title)
977 Return True is the instance can be "applied". 978 Always False for plain Configurable instances 979 (i.e. not ConfigurableUser). 994 object.__setattr__(obj, self.
__name__, value)
1001 Configurable.__init__(self, name)
1010 def getDlls(self):
pass 1017 super(ConfigurableGeneric, self).
__setattr__(name, value)
1021 if isinstance(value, Configurable):
1022 self.__dict__[name] = value
1034 class ConfigurableAlgorithm(Configurable):
1035 __slots__ = {
'_jobOptName': 0,
'OutputLevel': 0,
1036 'Enable': 1,
'ErrorMax': 1,
'ErrorCount': 0,
'AuditAlgorithms': 0,
1037 'AuditInitialize': 0,
'AuditReinitialize': 0,
'AuditExecute': 0,
1038 'AuditFinalize': 0,
'AuditBeginRun': 0,
'AuditEndRun': 0}
1041 super(ConfigurableAlgorithm, self).
__init__(name)
1061 elif rhs
is CFFalse:
1063 return AndNode(self, rhs)
1070 return OrNode(self, rhs)
1073 return InvertNode(self)
1076 return OrderedNode(self, rhs)
1087 return (repr(self) == repr(other))
1091 __slots__ = {
'OutputLevel': 0,
1092 'AuditServices': 0,
'AuditInitialize': 0,
'AuditFinalize': 0}
1101 return iService(self.
_name)
1115 __slots__ = {
'_jobOptName':
'',
'OutputLevel': 0,
1116 'AuditTools': 0,
'AuditInitialize': 0,
'AuditFinalize': 0}
1119 super(ConfigurableAlgTool, self).
__init__(name)
1120 if '.' not in self.
_name:
1124 name = name[name.find(
'/') + 1:]
1145 return pop + Configurable.getPrintTitle(self)
1154 if isinstance(c, ConfigurableAlgTool):
1155 c.setParent(parentName)
1159 name = name[name.rfind(
'.') + 1:]
1163 dot = self._jobOptName.rfind(
'.')
1170 return self._jobOptName.startswith(parent +
'.')
1179 return self._jobOptName.startswith(
'ToolSvc.')
1190 name = name[name.rfind(
'.') + 1:]
1191 return str(self.
getType() +
'/' + name)
1198 __slots__ = {
'_jobOptName': 0,
'OutputLevel': 0,
1202 super(ConfigurableAuditor, self).
__init__(name)
1204 name = name[name.find(
'/') + 1:]
1223 __slots__ = {
"__users__": [],
1224 "__used_instances__": [],
1235 __used_configurables__ = []
1238 __queried_configurables__ = []
1240 def __init__(self, name=Configurable.DefaultName, _enabled=True, **kwargs):
1241 super(ConfigurableUser, self).
__init__(name)
1242 for n, v
in kwargs.items():
1260 if type(used)
is tuple:
1261 used, used_name = used
1265 if type(used)
is str:
1266 used_class = confDbGetConfigurable(used)
1271 inst = used_class(name=used_name, _enabled=
False)
1272 except AttributeError:
1276 inst = used_class(name=used_name)
1280 if type(queried)
is str:
1281 queried = confDbGetConfigurable(used)
1282 inst = queried(_enabled=
False)
1283 except AttributeError:
1289 Declare that we are going to modify the Configurable 'other' in our 1290 __apply_configuration__. 1292 self.__used_instances__.append(other)
1293 if hasattr(other,
"__users__"):
1294 other.__users__.append(self)
1298 Declare that we are going to retrieve property values from the 1299 ConfigurableUser 'other' in our __apply_configuration__. 1301 if not isinstance(other, ConfigurableUser):
1302 raise Error(
"'%s': Cannot make passive use of '%s', it is not a ConfigurableUser" % (
1303 self.
name(), other.name()))
1304 other.__addActiveUseOf(self)
1317 Remove this ConfigurableUser instance from the users list of the used 1321 if hasattr(used,
"__users__"):
1322 used.__users__.remove(self)
1326 Propagate the property 'name' (if set) to other configurables (if possible). 1329 propagate to all the entries in __used_configurables__ 1330 a configurable instance: 1331 propagate only to it 1332 list of configurable instances: 1333 propagate to all of them. 1337 - if the local property is set, the other property will be overwritten 1338 - local property not set and other set => keep other 1339 - local property not set and other not set => overwrite the default for 1340 ConfigurableUser instances and set the property for Configurables 1345 elif type(others)
not in [list, tuple]:
1351 for other
in [o
for o
in others
if name
in o.__slots__]:
1354 if other.isPropertySet(name):
1355 log.warning(
"Property '%(prop)s' is set in both '%(self)s' and '%(other)s', using '%(self)s.%(prop)s'" %
1356 {
"self": self.
name(),
1357 "other": other.name(),
1359 other.setProp(name, value)
1361 elif not other.isPropertySet(name):
1362 if isinstance(other, ConfigurableUser):
1363 otherType =
type(other._properties[name].getDefault())
1364 other._properties[name].setDefault(value)
1365 if otherType
in [list, dict]:
1368 other.setProp(name, otherType(value))
1370 other.setProp(name, value)
1375 Call propagateProperty for each property listed in 'names'. 1376 If 'names' is None, all the properties are propagated. 1380 names = [p
for p
in self.
__slots__ if not p.startswith(
"_")]
1386 Function to be overridden to convert the high level configuration into a 1388 The default implementation calls applyConf, which is the method defined 1389 in some ConfigurableUser implementations. 1395 Function to be overridden to convert the high level configuration into a 1402 Function used to define the name of the private instance of a given class 1404 This method is used when the __used_configurables_property__ declares the 1405 need of a private used configurable without specifying the name. 1407 if type(cls)
is str:
1410 clName = cls.__name__
1411 return "%s_%s" % (self.name(), clName)
1415 Return the used instance with a given name. 1418 if i.name() == name:
1419 if hasattr(i,
"_enabled"):
1424 raise KeyError(name)
1428 Return True is the instance can be "applied". 1434 postConfigActions = []
1439 Add a new callable ('function') to the list of post-configuration actions. 1440 If the callable is already in the list, it is moved to the end of the list. 1441 The list is directly accessible as 'GaudiKernel.Configurable.postConfigActions'. 1444 postConfigActions.remove(function)
1447 postConfigActions.append(function)
1452 Remove a callable from the list of post-config actions. 1453 The list is directly accessible as 'GaudiKernel.Configurable.postConfigActions'. 1455 postConfigActions.remove(function)
1458 _appliedConfigurableUsers_ =
False 1463 Call the apply method of all the ConfigurableUser instances respecting the 1464 dependencies. First the C.U.s that are not used by anybody, then the used 1465 ones, when they are not used anymore. 1468 global _appliedConfigurableUsers_, postConfigActions
1469 if _appliedConfigurableUsers_:
1471 _appliedConfigurableUsers_ =
True 1473 def applicableConfUsers():
1475 Generator returning all the configurables that can be applied in the 1476 order in which they can be applied. 1488 yield (c
for c
in Configurable.allConfigurables.values()
1489 if c.isApplicable()).next()
1491 debugApplyOrder =
'GAUDI_DUBUG_CONF_USER' in os.environ
1492 for c
in applicableConfUsers():
1494 log.info(
"applying configuration of %s", c.name())
1496 sys.stderr.write(
'applying %r' % c)
1497 c.__apply_configuration__()
1500 log.info(
"skipping configuration of %s", c.name())
1502 if hasattr(c,
"__detach_used__"):
1507 leftConfUsers = [c
for c
in Configurable.allConfigurables.values()
1508 if hasattr(c,
'__apply_configuration__')
and 1509 c._enabled
and not c._applied]
1512 raise Error(
"Detected loop in the ConfigurableUser" 1513 " dependencies: %r" % [c.name()
1514 for c
in leftConfUsers])
1517 unknown = set(Configurable.allConfigurables)
1521 log.debug(
'new configurable created automatically: %s', k)
1523 Configurable.allConfigurables[k].
properties()
1527 for action
in postConfigActions:
1533 Obsolete (buggy) implementation of applyConfigurableUsers(), kept to provide 1534 backward compatibility for configurations that where relying (implicitly) on 1535 bug #103803, or on a specific (non guaranteed) order of execution. 1537 @see applyConfigurableUsers() 1540 global _appliedConfigurableUsers_, postConfigActions
1541 if _appliedConfigurableUsers_:
1543 _appliedConfigurableUsers_ =
True 1545 debugApplyOrder =
'GAUDI_DUBUG_CONF_USER' in os.environ
1547 for c
in Configurable.allConfigurables.values()
1548 if hasattr(c,
"__apply_configuration__")]
1550 while applied
and confUsers:
1554 if hasattr(c,
"__users__")
and c.__users__:
1555 newConfUsers.append(c)
1560 enabled = (
not hasattr(c,
"_enabled"))
or c._enabled
1562 log.info(
"applying configuration of %s", c.name())
1564 sys.stderr.write(
'applying %r' % c)
1565 c.__apply_configuration__()
1568 log.info(
"skipping configuration of %s", c.name())
1569 if hasattr(c,
"__detach_used__"):
1572 confUsers = newConfUsers
1575 raise Error(
"Detected loop in the ConfigurableUser " 1576 " dependencies: %r" % [c.name()
1577 for c
in confUsers])
1580 unknown = set(Configurable.allConfigurables)
1584 log.debug(
'new configurable created automatically: %s', k)
1586 Configurable.allConfigurables[k].
properties()
1590 for action
in postConfigActions:
1596 Function to select all and only the configurables that have to be used in 1597 GaudiPython.AppMgr constructor. 1598 This is needed because in Athena the implementation have to be different (the 1599 configuration is used in a different moment). 1602 for k, v
in Configurable.allConfigurables.items()
1603 if v.getGaudiType() !=
"User"]
1608 Clean up all configurations and configurables. 1610 for c
in Configurable.allConfigurables.values():
1611 c.__class__.configurables.clear()
1612 Configurable.allConfigurables.clear()
1615 ConfigurableGeneric.configurables.clear()
1616 from ProcessJobOptions
import _included_files
1619 for file
in _included_files:
1620 dirname, basname = os.path.split(file)
1621 basname, ext = os.path.splitext(basname)
1622 if basname
in sys.modules:
1623 del sys.modules[basname]
1624 _included_files.clear()
1633 return self.
stack[-1]
1641 name = prefix + str(cnt)
1642 while name
in allConfigurables:
1644 name = prefix + str(cnt)
1648 from Configurables
import GaudiSequencer
1654 if visitee
in (CFTrue, CFFalse):
1655 stack.append(self.
_newSeq(Invert=visitee
is CFFalse))
1656 elif isinstance(visitee, (ControlFlowLeaf, ConfigurableAlgorithm)):
1657 stack.append(visitee)
1658 elif isinstance(visitee, (OrNode, AndNode, OrderedNode)):
1661 seq = self.
_newSeq(Members=[a, b],
1662 ModeOR=isinstance(visitee, OrNode),
1663 ShortCircuit=
not isinstance(
1664 visitee, OrderedNode),
1667 elif isinstance(visitee, ignore):
1668 if hasattr(stack[-1],
'IgnoreFilterPassed'):
1669 stack[-1].IgnoreFilterPassed =
True 1671 stack.append(self.
_newSeq(Members=[stack.pop()],
1672 IgnoreFilterPassed=
True))
1673 elif isinstance(visitee, InvertNode):
1674 if hasattr(stack[-1],
'Invert'):
1675 stack[-1].Invert =
True 1677 stack.append(self.
_newSeq(Members=[stack.pop()],
1683 Convert a control flow expression to nested GaudiSequencers. 1685 if not isinstance(expression, ControlFlowNode):
1686 raise ValueError(
'ControlFlowNode instance expected, got %s' %
1687 type(expression).__name__)
1689 expression.visitNode(visitor)
1690 return visitor.sequence
1695 Helper class to use a ControlFlowNode as an algorithm configurable 1701 if name
in Configurable.allConfigurables:
1702 instance = Configurable.allConfigurables[name]
1703 assert type(instance)
is cls, \
1704 (
'trying to reuse {0!r} as name of a {1} instance while it''s ' 1705 'already used for an instance of {2}').
format(
1708 type(instance).__name__)
1711 instance = super(SuperAlgorithm, cls).
__new__(cls, name, **kwargs)
1712 Configurable.allConfigurables[name] = instance
1719 setattr(self, key, kwargs[key])
1743 Instantiate and algorithm of type 'typ' with a name suitable for use 1744 inside a SuperAlgorithm. 1746 name =
'{0}_{1}'.
format(self.
name, kwargs.pop(
'name', typ.getType()))
1747 return typ(name, **kwargs)
1750 raise NotImplementedError()
1757 self.graph.visitNode(visitor)
1760 super(SuperAlgorithm, self).
__setattr__(name, value)
1761 if name
in (
'_name',
'graph'):
1765 class PropSetter(object):
1766 def enter(self, node):
1768 setattr(node, name, value)
1769 except (ValueError, AttributeError):
1773 def leave(self, node):
1776 self._visitSubNodes(PropSetter())
def getNeededConfigurables()
def __deepcopy__(self, memo)
def propagateProperty(self, name, others=None, force=True)
def setParent(self, parentName)
def __apply_configuration__(self)
dictionary allConfigurables
def _newSeq(self, prefix='seq_', kwargs)
def __deepcopy__(self, memo)
def __detach_used__(self)
def __setstate__(self, dict)
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
list __queried_configurables__
def _printHeader(indentStr, title)
def _getUniqueName(self, prefix)
def __init__(self, name=Configurable.DefaultName, _enabled=True, kwargs)
dictionary configurableServices
def __addPassiveUseOf(self, other)
def __new__(cls, args, kwargs)
def hasParent(self, parent)
def __init__(self, name=None, kwargs)
def appendPostConfigAction(function)
Sequencer for executing several algorithms, stopping when one is faulty.
def __init__(self, name=DefaultName)
def getPropertiesWithDescription(self)
def addTool(self, tool, name=None)
def __setupDefaults(self)
def makeSequences(expression)
def _printFooter(indentStr, title)
def _makeAlg(self, typ, kwargs)
def _visitSubNodes(self, visitor)
def applyConfigurableUsers()
def clone(self, name=None, kwargs)
def _instanceName(self, cls)
def setProp(self, name, value)
list __used_configurables__
def __deepcopy__(self, memo)
MsgStream & hex(MsgStream &log)
def __init__(self, name=Configurable.DefaultName)
def __getattr__(self, attr)
def __init__(self, name=Configurable.DefaultName)
def __init__(self, propname)
def __deepcopy__(self, memo)
def copyChildAndSetParent(self, cfg, parent)
def __setattr__(self, name, value)
def __addActiveUseOf(self, other)
def setDefaults(cls, handle)
def __iadd__(self, configs, descr=None)
def isPropertySet(self, name)
def toStringProperty(self)
def __new__(cls, name=None, kwargs)
def getDefaultProperties(cls)
def __rshift__(self, rhs)
def __delattr__(self, attr)
def getUsedInstance(self, name)
def copyChild(self, child)
def applyConfigurableUsers_old()
def __setattr__(self, name, value)
def getFullJobOptName(self)
def __set__(self, obj, value)
def removePostConfigAction(function)
def __str__(self, indent=0, headerLastIndentUnit=indentUnit)
bool _configurationLocked
def __setupServices(self)
def _isInSetDefaults(self)
def __init__(self, name=Configurable.DefaultName)
def getDefaultProperty(cls, name)
def toStringProperty(self)
def propagateProperties(self, names=None, others=None, force=True)
def __get__(self, obj, type=None)
def _visitSubNodes(self, visitor)
def copyChild(self, child)
def getValuedProperties(self)
def __setattr__(self, name, value)
def isApplicable(self)
rep += v.__str__( indent + 1 ) + os.linesep elif isinstance(v,GaudiHandleArray): for vi in v: if isin...
def visitNode(self, visitor)