5 import copy, string, types, os
7 from inspect
import isclass
10 VERBOSE, DEBUG, INFO, WARNING, ERROR, FATAL
17 ControlFlowLeaf, ControlFlowNode,
21 __all__ = [
'Configurable',
22 'ConfigurableAlgorithm',
23 'ConfigurableAlgTool',
24 'ConfigurableAuditor',
25 'ConfigurableService',
27 'VERBOSE',
'DEBUG',
'INFO',
'WARNING',
'ERROR',
'FATAL',
28 'appendPostConfigAction',
'removePostConfigAction' ]
32 log = logging.getLogger(
'Configurable' )
36 Expand environment variables "data". 37 Data can be string, list, tuple and dictionary. For collection, all the 38 contained strings will be manipulated (recursively). 43 return os.path.expandvars(data)
44 elif typ
in [list, tuple]:
58 Error occurred in the configuration process. 63 class PropertyReference(object):
67 return "@%s"%self.
name 71 refname, refprop = self.name.rsplit(
'.',1)
72 if refname
in Configurable.allConfigurables:
73 conf = Configurable.allConfigurables[refname]
74 retval = getattr(conf,refprop)
75 if hasattr(retval,
"getFullName"):
76 retval = retval.getFullName()
78 raise NameError(
"name '%s' not found resolving '%s'"%(refname,self))
81 """This function allow transparent integration with 82 Configurable.getValuedProperties. 89 except AttributeError:
95 """Base class for Gaudi components that implement the IProperty interface. 96 Provides most of the boilerplate code, but the actual useful classes 97 are its derived ConfigurableAlgorithm, ConfigurableService, and 98 ConfigurableAlgTool.""" 104 propertyNoValue =
'<no value>' 120 allConfigurables = {}
121 configurableServices = {}
124 _configurationLocked =
False 127 """To Gaudi, any object with the same type/name is the same object. Hence, 128 this is mimicked in the configuration: instantiating a new Configurable 129 of a type with the same name will return the same instance.""" 135 name = kwargs[
'name' ]
136 elif 'name' in cls.__init__.func_code.co_varnames:
138 index = list(cls.__init__.func_code.co_varnames).index(
'name' )
141 name = args[ index - 1 ]
144 name = cls.__init__.func_defaults[ index - (len(args)+1) ]
149 except (IndexError,TypeError):
150 raise TypeError(
'no "name" argument while instantiating "%s"' % cls.__name__ )
154 if hasattr(cls,
'DefaultedName' ) :
155 name = cls.DefaultedName
158 elif not name
or type(name) != str:
160 raise TypeError(
'could not retrieve name from %s.__init__ arguments' % cls.__name__ )
164 if issubclass( cls, ConfigurableAlgTool)
and '.' not in name :
165 name =
'ToolSvc.' + name
175 if name
in cls.configurables:
176 conf = cls.configurables[ name ]
178 cls.configurables[ conf.getType() ] = conf
180 for n,v
in kwargs.items():
183 if not cls.
_configurationLocked and not "_enabled" in kwargs
and isinstance(conf, ConfigurableUser):
186 setattr(conf,
"_enabled",
True)
190 spos = name.find(
'/' )
193 ti_name =
"%s/%s" % (name,name)
194 if ti_name
in cls.configurables:
196 return cls.configurables[ ti_name ]
201 if i_name == name[spos+1:]
and i_name
in cls.configurables:
203 return cls.configurables[ i_name ]
206 conf = cls.allConfigurables.get( name,
None )
or\
207 (spos < 0
and cls.allConfigurables.get( ti_name,
None ))
or\
208 (spos > 0
and i_name == name[spos+1:]
and cls.allConfigurables.get( i_name,
None ))
210 if conf.__class__
is ConfigurableGeneric :
214 newconf = object.__new__( cls )
215 cls.
__init__( newconf, *args, **kwargs )
220 for n
in newconf.__slots__:
222 for n
in conf._properties:
223 if names[n.lower()] != n:
224 log.warning(
"Option '%s' was used for %s, but the correct spelling is '%s'"%(n,name,names[n.lower()]) )
225 setattr(newconf, names[n.lower()], getattr( conf, n ) )
226 for n,v
in kwargs.items():
227 setattr(newconf, n, v)
228 cls.configurables[ name ] = newconf
233 log.error(
'attempt to redefine type of "%s" (was: %s, new: %s)%s',
234 name, conf.__class__.__name__, cls.__name__, error_explanation )
239 for n,v
in kwargs.items():
244 conf = object.__new__(cls)
245 cls.
__init__( conf, *args, **kwargs )
248 cls.configurables[ name ] = conf
250 for base
in cls.__bases__:
251 if base.__name__ ==
'ConfigurableService':
263 klass = self.__class__
266 if klass == Configurable:
267 raise TypeError,
"%s is an ABC and can not be instantiated" % str(Configurable)
271 meths = {
'getDlls' : 1,
276 for meth, nArgs
in meths.items():
278 f = getattr( klass, meth ).im_func
279 except AttributeError:
280 raise NotImplementedError,
"%s is missing in class %s" % (meth,str(klass))
283 nargcount = f.func_code.co_argcount
284 ndefaults = f.func_defaults
and len(f.func_defaults)
or 0
285 if not nargcount - ndefaults <= nArgs <= nargcount:
286 raise TypeError,
"%s.%s requires exactly %d arguments" % (klass,meth,nArgs)
294 if hasattr(self.__class__,
'DefaultedName' ) :
295 self.
_name = self.__class__.DefaultedName
313 for name, proxy
in self._properties.items():
315 dict[ name ] = proxy.__get__( self )
316 except AttributeError:
319 dict[
'_Configurable__children' ] = self.
__children 320 dict[
'_Configurable__tools' ] = self.
__tools 321 dict[
'_name' ] = self.
_name 329 for n, v
in dict.items():
342 newconf = object.__new__( self.__class__ )
343 self.__class__.__init__( newconf, self.
getName() )
345 for proxy
in self._properties.values():
347 proxy.__set__( newconf, proxy.__get__( self ) )
348 except AttributeError:
358 if not type(configs)
in (list,tuple):
359 configs = ( configs, )
365 if not isinstance( cfg, Configurable ):
366 raise TypeError(
"'%s' is not a Configurable" % str(cfg) )
371 ccjo = cc.getJobOptName()
373 if c.getJobOptName() == ccjo:
374 log.error(
'attempt to add a duplicate ... dupe ignored%s', error_explanation )
377 self.__children.append( cc )
381 descr.__set__( self, cc )
383 setattr( self, cc.getName(), cc )
384 except AttributeError:
393 if attr
in self._properties:
394 if isinstance(self._properties[attr].__get__( self ), DataObjectHandleBase):
395 return self._properties[attr].__get__( self )
398 if c.getName() == attr:
401 raise AttributeError(
"'%s' object has no attribute '%s'" % (self.__class__,attr) )
405 raise RuntimeError(
"%s: Configuration cannot be modified after the ApplicationMgr has been started."%self.
name())
407 super( Configurable, self ).
__setattr__( name, value )
408 except AttributeError:
409 raise AttributeError(
"Configurable '%s' does not have property '%s'." 410 % ( self.__class__.__name__, name) )
416 prop = self._properties[ attr ]
417 prop.__delete__( self )
418 prop.__set__( self, prop.default )
428 if c.getName() == attr:
429 self.__children.remove( c )
433 del self.__dict__[ attr ]
434 except (AttributeError,KeyError):
442 if type(items) != list
and type(items) != tuple:
452 return copy.deepcopy( child )
466 if hasattr( cc,
'setParent' )
and parent:
468 cc.setParent( parent )
469 except RuntimeError, e:
471 log.error( str(e) +
'%s', error_explanation )
472 ccbd = cc.configurables[ cc.getJobOptName() ]
475 for proxy
in self._properties.values():
476 if proxy.history.has_key( cc ):
477 proxy.__set__( ccbd, proxy.__get__( cc ) )
487 return self.__tools.values()
490 log.error(
"children() is deprecated, use getChildren() instead for consistency" )
491 log.error(
"getChildren() returns a copy; to add a child, use 'parent += child'%s",
496 """Get all (private) configurable children, both explicit ones (added with +=) 497 and the ones in the private GaudiHandle properties""" 500 for proxy
in self._properties.values():
502 c = proxy.__get__( self )
503 except AttributeError:
506 if isinstance(c,Configurable)
and not c.isPublic():
508 elif isinstance(c,GaudiHandle):
510 conf = c.configurable
511 except AttributeError:
514 if not conf.isPublic():
516 elif isinstance(c,GaudiHandleArray):
520 if isinstance(ci,Configurable):
524 conf = ci.configurable
525 except AttributeError:
537 elems.append( c.getFullName() )
542 if not hasattr(self,
'_initok')
or not self.
_initok:
545 "Configurable.__init__ not called in %s override" % self.__class__.__name__
559 handle = self.getHandle()
561 log.debug(
'no handle for %s: not transporting properties', self.
_name )
565 for name
in self._properties.keys():
566 if hasattr( self, name ):
567 setattr( handle, name, getattr(self,name) )
574 for name, proxy
in self._properties.items():
576 props[ name ] = proxy.__get__( self )
577 except AttributeError:
578 props[ name ] = Configurable.propertyNoValue
583 """Get all properties with their description string as { name : (value, desc) }.""" 585 for name, proxy
in self._properties.items():
587 props[ name ] = ( proxy.__get__( self ), proxy.__doc__)
588 except AttributeError:
589 props[ name ] = ( Configurable.propertyNoValue, proxy.__doc__)
594 for name, proxy
in self._properties.items():
596 value = proxy.__get__( self )
597 if hasattr(value,
'getFullName') :
598 value = value.getFullName()
599 elif type(value)
in [list, tuple]:
602 if hasattr(i,
'getFullName'):
603 new_value.append(i.getFullName())
606 value =
type(value)(new_value)
607 elif type(value)
is dict:
610 if hasattr(value[i],
'getFullName'):
613 new_value[i] = value[i]
615 props[ name ] = value
632 for k,v
in cls._properties.items():
633 if not k
in c.__dict__
and hasattr( v,
'default' ):
634 c.__dict__[ k ] = v.default
647 if name
in c.__dict__:
648 return c.__dict__[ name ]
652 v = cls._properties[name]
653 if hasattr( v,
'default' ):
661 """Returns the value of the given property. 663 if hasattr(self, name):
664 return getattr(self, name)
669 """Set the value of a given property 671 return setattr(self, name, value)
674 """Tell if the property 'name' has been set or not. 676 Because of a problem with list and dictionary properties, in those cases 677 if the value is equal to the default, the property is considered as not 680 if not hasattr(self, name):
683 if isinstance(default, (list, dict, DataObjectHandleBase)):
684 value = getattr(self, name)
685 return value != default
705 log.error(
"jobOptName() is deprecated, use getJobOptName() instead for consistency%s",
719 if log.isEnabledFor( logging.DEBUG ):
727 def clone( self, name = None, **kwargs ) :
729 if hasattr(self,
'DefaultedName' ) : name = self.DefaultedName
730 else : name = self.getType()
732 newconf = Configurable.__new__( self.__class__, name )
733 self.__class__.__init__( newconf, name )
735 for proxy
in self._properties.values():
737 value = proxy.__get__( self )
738 if type(value)
in [ str, list, dict, tuple ]:
740 value =
type(value)(value)
741 proxy.__set__( newconf, value )
742 except AttributeError:
745 for c
in self.__children:
748 for n , t
in self.__tools.items():
749 newconf.addTool(t, n)
751 for name, value
in kwargs.items():
752 setattr(newconf, name, value)
758 dot = fullname.find(
'.')
760 parentname = fullname[:dot]
761 longname = fullname[dot+1:]
765 dot = longname.find(
'.')
767 name = longname[:dot]
770 return parentname, name, longname
773 if isclass(tool)
and issubclass(tool, ConfigurableAlgTool):
776 priv_tool = tool( self.
getName()+
'.' + name )
777 elif isinstance(tool, ConfigurableAlgTool):
779 name = tool.splitName()[1]
780 priv_tool = tool.clone( self.
getName()+
'.' + name )
783 classname = tool.__name__
785 classname =
type(tool).__name__
786 raise TypeError,
"addTool requires AlgTool configurable. Got %s type" % classname
790 setattr(self,name,self.
__tools[name])
805 handle = __main__.Service( svc )
810 if hasattr( self,
'configure' + svc ):
811 eval(
'self.configure' + svc +
'( handle )' )
814 dlls = self.getDlls()
817 elif type(dlls) == types.StringType:
820 from __main__
import theApp
821 dlls = filter(
lambda d: d
not in theApp.Dlls, dlls )
822 if dlls: theApp.Dlls += dlls
833 preLen = Configurable.printHeaderPre
834 postLen = Configurable.printHeaderWidth - preLen - 3 - len(title)
835 postLen = max(preLen,postLen)
836 return indentStr +
'/%s %s %s' % (preLen*
'*',title,postLen*
'*')
840 preLen = Configurable.printHeaderPre
841 postLen = Configurable.printHeaderWidth - preLen - 12 - len(title)
842 postLen = max(preLen,postLen)
843 return indentStr +
'\\%s (End of %s) %s' % (preLen*
'-',title,postLen*
'-')
845 def __str__( self, indent = 0, headerLastIndentUnit=indentUnit ):
847 indentStr = indent*Configurable.indentUnit
852 headerIndent = (indent-1)*Configurable.indentUnit + headerLastIndentUnit
855 rep = Configurable._printHeader( headerIndent, title )
861 rep += indentStr +
'|-<no properties>' + os.linesep
865 for p
in props.keys():
866 nameWidth=max(nameWidth,len(p))
867 for p, v
in props.items():
869 prefix = indentStr +
'|-%-*s' % (nameWidth,p)
871 if log.isEnabledFor( logging.DEBUG ):
872 if v != Configurable.propertyNoValue:
873 address =
' @%11s' %
hex(id(v))
878 default = defs.get(p)
879 if v == Configurable.propertyNoValue:
881 strVal = repr(default)
885 if hasattr(v,
"getGaudiHandle"):
886 vv = v.getGaudiHandle()
889 if isinstance(vv,GaudiHandle)
or isinstance(vv,GaudiHandleArray):
891 if hasattr(default,
"toStringProperty"):
892 strDef = repr(default.toStringProperty())
894 strDef = repr(default)
895 if strDef == repr(vv.toStringProperty()):
899 strDef = repr(default)
901 line = prefix +
' = ' + strVal
903 if strDef
is not None:
905 if len(line) + len(strDef) > Configurable.printHeaderWidth:
906 line += os.linesep + indentStr +
'| ' + (len(prefix)-len(indentStr)-3)*
' ' 907 line +=
' (default: %s)' % (strDef,)
909 rep += line + os.linesep
921 rep += cfg.__str__( indent + 1,
'|=' ) + os.linesep
924 rep += Configurable._printFooter( indentStr, title )
929 Return True is the instance can be "applied". 930 Always False for plain Configurable instances 931 (i.e. not ConfigurableUser). 941 return getattr( obj, self.
__name__ )
944 object.__setattr__( obj, self.
__name__, value )
949 def __init__( self, name = Configurable.DefaultName ):
950 Configurable.__init__( self, name )
958 def getDlls( self ) :
pass 964 super( ConfigurableGeneric, self ).
__setattr__( name, value )
968 if isinstance( value, Configurable ):
969 self.__dict__[ name ] = value
981 class ConfigurableAlgorithm( Configurable ):
982 __slots__ = {
'_jobOptName' : 0,
'OutputLevel' : 0, \
983 'Enable' : 1,
'ErrorMax' : 1,
'ErrorCount' : 0,
'AuditAlgorithms' : 0, \
984 'AuditInitialize' : 0,
'AuditReinitialize' : 0,
'AuditExecute' : 0, \
985 'AuditFinalize' : 0,
'AuditBeginRun' : 0,
'AuditEndRun' : 0 }
987 def __init__( self, name = Configurable.DefaultName ):
988 super( ConfigurableAlgorithm, self ).
__init__( name )
1011 elif rhs
is CFFalse:
1013 return AndNode(self, rhs)
1020 return OrNode(self, rhs)
1023 return InvertNode(self)
1026 return OrderedNode(self, rhs)
1037 return (repr(self) == repr(other))
1041 __slots__ = {
'OutputLevel' : 0, \
1042 'AuditServices' : 0,
'AuditInitialize' : 0,
'AuditFinalize' : 0 }
1051 return iService( self.
_name )
1065 __slots__ = {
'_jobOptName' :
'',
'OutputLevel' : 0, \
1066 'AuditTools' : 0,
'AuditInitialize' : 0,
'AuditFinalize' : 0 }
1069 super( ConfigurableAlgTool, self ).
__init__( name )
1070 if '.' not in self.
_name:
1074 name = name[ name.find(
'/')+1 : ]
1095 return pop + Configurable.getPrintTitle(self)
1104 if isinstance(c,ConfigurableAlgTool): c.setParent( parentName )
1108 name = name[name.rfind(
'.')+1:]
1112 dot = self._jobOptName.rfind(
'.')
1119 return self._jobOptName.startswith( parent +
'.' )
1128 return self._jobOptName.startswith(
'ToolSvc.')
1139 name = name[name.rfind(
'.')+1:]
1140 return str( self.
getType() +
'/' + name )
1147 __slots__ = {
'_jobOptName' : 0,
'OutputLevel' : 0, \
1151 super( ConfigurableAuditor, self ).
__init__( name )
1153 name = name[ name.find(
'/')+1 : ]
1171 __slots__ = {
"__users__": [],
1172 "__used_instances__": [],
1183 __used_configurables__ = []
1186 __queried_configurables__ = []
1187 def __init__( self, name = Configurable.DefaultName, _enabled = True, **kwargs ):
1188 super( ConfigurableUser, self ).
__init__( name )
1189 for n, v
in kwargs.items():
1207 if type(used)
is tuple:
1208 used, used_name = used
1212 if type(used)
is str:
1213 used_class = confDbGetConfigurable(used)
1218 inst = used_class(name = used_name, _enabled =
False)
1219 except AttributeError:
1223 inst = used_class(name = used_name)
1227 if type(queried)
is str:
1228 queried = confDbGetConfigurable(used)
1229 inst = queried(_enabled =
False)
1230 except AttributeError:
1235 Declare that we are going to modify the Configurable 'other' in our 1236 __apply_configuration__. 1238 self.__used_instances__.append(other)
1239 if hasattr(other,
"__users__"):
1240 other.__users__.append(self)
1243 Declare that we are going to retrieve property values from the 1244 ConfigurableUser 'other' in our __apply_configuration__. 1246 if not isinstance(other, ConfigurableUser):
1247 raise Error(
"'%s': Cannot make passive use of '%s', it is not a ConfigurableUser" % (self.
name(), other.name()))
1248 other.__addActiveUseOf(self)
1258 Remove this ConfigurableUser instance from the users list of the used 1262 if hasattr(used,
"__users__"):
1263 used.__users__.remove(self)
1267 Propagate the property 'name' (if set) to other configurables (if possible). 1270 propagate to all the entries in __used_configurables__ 1271 a configurable instance: 1272 propagate only to it 1273 list of configurable instances: 1274 propagate to all of them. 1278 - if the local property is set, the other property will be overwritten 1279 - local property not set and other set => keep other 1280 - local property not set and other not set => overwrite the default for 1281 ConfigurableUser instances and set the property for Configurables 1286 elif type(others)
not in [ list, tuple ] :
1292 for other
in [ o
for o
in others
if name
in o.__slots__ ]:
1295 if other.isPropertySet(name):
1296 log.warning(
"Property '%(prop)s' is set in both '%(self)s' and '%(other)s', using '%(self)s.%(prop)s'"%
1297 {
"self": self.
name(),
1298 "other": other.name(),
1300 other.setProp(name, value)
1302 elif not other.isPropertySet(name):
1303 if isinstance(other,ConfigurableUser):
1304 otherType =
type(other._properties[name].getDefault())
1305 other._properties[name].setDefault(value)
1306 if otherType
in [list, dict]:
1309 other.setProp(name, otherType(value))
1311 other.setProp(name, value)
1316 Call propagateProperty for each property listed in 'names'. 1317 If 'names' is None, all the properties are propagated. 1321 names = [ p
for p
in self.
__slots__ if not p.startswith(
"_") ]
1327 Function to be overridden to convert the high level configuration into a 1329 The default implementation calls applyConf, which is the method defined 1330 in some ConfigurableUser implementations. 1336 Function to be overridden to convert the high level configuration into a 1343 Function used to define the name of the private instance of a given class 1345 This method is used when the __used_configurables_property__ declares the 1346 need of a private used configurable without specifying the name. 1348 if type(cls)
is str:
1351 clName = cls.__name__
1352 return "%s_%s" % (self.name(), clName)
1356 Return the used instance with a given name. 1359 if i.name() == name:
1360 if hasattr(i,
"_enabled"):
1365 raise KeyError(name)
1369 Return True is the instance can be "applied". 1375 postConfigActions = []
1378 Add a new callable ('function') to the list of post-configuration actions. 1379 If the callable is already in the list, it is moved to the end of the list. 1380 The list is directly accessible as 'GaudiKernel.Configurable.postConfigActions'. 1383 postConfigActions.remove(function)
1386 postConfigActions.append(function)
1389 Remove a callable from the list of post-config actions. 1390 The list is directly accessible as 'GaudiKernel.Configurable.postConfigActions'. 1392 postConfigActions.remove(function)
1394 _appliedConfigurableUsers_ =
False 1397 Call the apply method of all the ConfigurableUser instances respecting the 1398 dependencies. First the C.U.s that are not used by anybody, then the used 1399 ones, when they are not used anymore. 1402 global _appliedConfigurableUsers_, postConfigActions
1403 if _appliedConfigurableUsers_:
1405 _appliedConfigurableUsers_ =
True 1407 def applicableConfUsers():
1409 Generator returning all the configurables that can be applied in the 1410 order in which they can be applied. 1422 yield (c
for c
in Configurable.allConfigurables.values()
1423 if c.isApplicable()).next()
1425 debugApplyOrder =
'GAUDI_DUBUG_CONF_USER' in os.environ
1426 for c
in applicableConfUsers():
1428 log.info(
"applying configuration of %s", c.name())
1430 sys.stderr.write(
'applying %r' % c)
1431 c.__apply_configuration__()
1434 log.info(
"skipping configuration of %s", c.name())
1436 if hasattr(c,
"__detach_used__"):
1441 leftConfUsers = [c
for c
in Configurable.allConfigurables.values()
1442 if hasattr(c,
'__apply_configuration__')
and 1443 c._enabled
and not c._applied]
1446 raise Error(
"Detected loop in the ConfigurableUser" 1447 " dependencies: %r" % [ c.name()
1448 for c
in leftConfUsers ])
1451 unknown = set(Configurable.allConfigurables)
1455 log.debug(
'new configurable created automatically: %s', k)
1457 Configurable.allConfigurables[k].
properties()
1461 for action
in postConfigActions:
1466 Obsolete (buggy) implementation of applyConfigurableUsers(), kept to provide 1467 backward compatibility for configurations that where relying (implicitly) on 1468 bug #103803, or on a specific (non guaranteed) order of execution. 1470 @see applyConfigurableUsers() 1473 global _appliedConfigurableUsers_, postConfigActions
1474 if _appliedConfigurableUsers_:
1476 _appliedConfigurableUsers_ =
True 1478 debugApplyOrder =
'GAUDI_DUBUG_CONF_USER' in os.environ
1480 for c
in Configurable.allConfigurables.values()
1481 if hasattr(c,
"__apply_configuration__") ]
1483 while applied
and confUsers:
1487 if hasattr(c,
"__users__")
and c.__users__:
1488 newConfUsers.append(c)
1493 enabled = (
not hasattr(c,
"_enabled"))
or c._enabled
1495 log.info(
"applying configuration of %s", c.name())
1497 sys.stderr.write(
'applying %r' % c)
1498 c.__apply_configuration__()
1501 log.info(
"skipping configuration of %s", c.name())
1502 if hasattr(c,
"__detach_used__"):
1505 confUsers = newConfUsers
1508 raise Error(
"Detected loop in the ConfigurableUser " 1509 " dependencies: %r" % [ c.name()
1510 for c
in confUsers ])
1513 unknown = set(Configurable.allConfigurables)
1517 log.debug(
'new configurable created automatically: %s', k)
1519 Configurable.allConfigurables[k].
properties()
1523 for action
in postConfigActions:
1528 Function to select all and only the configurables that have to be used in 1529 GaudiPython.AppMgr constructor. 1530 This is needed because in Athena the implementation have to be different (the 1531 configuration is used in a different moment). 1534 for k, v
in Configurable.allConfigurables.items()
1535 if v.getGaudiType() !=
"User" ]
1539 Clean up all configurations and configurables. 1541 for c
in Configurable.allConfigurables.values():
1542 c.__class__.configurables.clear()
1543 Configurable.allConfigurables.clear()
1546 ConfigurableGeneric.configurables.clear()
1547 from ProcessJobOptions
import _included_files
1549 for file
in _included_files:
1550 dirname, basname = os.path.split(file)
1551 basname, ext = os.path.splitext(basname)
1552 if basname
in sys.modules:
1553 del sys.modules[basname]
1554 _included_files.clear()
1563 return self.
stack[-1]
1571 name = prefix + str(cnt)
1572 while name
in allConfigurables:
1574 name = prefix + str(cnt)
1578 from Configurables
import GaudiSequencer
1584 if visitee
in (CFTrue, CFFalse):
1585 stack.append(self.
_newSeq(Invert=visitee
is CFFalse))
1586 elif isinstance(visitee, (ControlFlowLeaf, ConfigurableAlgorithm)):
1587 stack.append(visitee)
1588 elif isinstance(visitee, (OrNode, AndNode, OrderedNode)):
1591 seq = self.
_newSeq(Members=[a, b],
1592 ModeOR=isinstance(visitee, OrNode),
1593 ShortCircuit=
not isinstance(visitee, OrderedNode),
1596 elif isinstance(visitee, ignore):
1597 if hasattr(stack[-1],
'IgnoreFilterPassed'):
1598 stack[-1].IgnoreFilterPassed =
True 1600 stack.append(self.
_newSeq(Members=[stack.pop()],
1601 IgnoreFilterPassed=
True))
1602 elif isinstance(visitee, InvertNode):
1603 if hasattr(stack[-1],
'Invert'):
1604 stack[-1].Invert =
True 1606 stack.append(self.
_newSeq(Members=[stack.pop()],
1611 Convert a control flow expression to nested GaudiSequencers. 1613 if not isinstance(expression, ControlFlowNode):
1614 raise ValueError(
'ControlFlowNode instance expected, got %s' %
1615 type(expression).__name__)
1617 expression.visitNode(visitor)
1618 return visitor.sequence
1623 Helper class to use a ControlFlowNode as an algorithm configurable 1629 if name
in Configurable.allConfigurables:
1630 instance = Configurable.allConfigurables[name]
1631 assert type(instance)
is cls, \
1632 (
'trying to reuse {0!r} as name of a {1} instance while it''s ' 1633 'already used for an instance of {2}').
format(
1636 type(instance).__name__)
1639 instance = super(SuperAlgorithm, cls).
__new__(cls, name, **kwargs)
1640 Configurable.allConfigurables[name] = instance
1647 setattr(self, key, kwargs[key])
1671 Instantiate and algorithm of type 'typ' with a name suitable for use 1672 inside a SuperAlgorithm. 1674 name =
'{0}_{1}'.
format(self.
name, kwargs.pop(
'name', typ.getType()))
1675 return typ(name, **kwargs)
1678 raise NotImplementedError()
1685 self.graph.visitNode(visitor)
1688 super(SuperAlgorithm, self).
__setattr__(name, value)
1689 if name
in (
'_name',
'graph'):
1693 class PropSetter(object):
1694 def enter(self, node):
1696 setattr(node, name, value)
1697 except (ValueError, AttributeError):
1700 def leave(self, node):
1703 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__
list of ConfigurableUser classes this one is going to query in the apply_configuration method ...
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__
list of ConfigurableUser classes this one is going to modify in the apply_configuration method...
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()
iAlgorithm
The basic module.
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)
classes for generic Gaudi component ===========
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)
if isinstance(v,Configurable) and not v.isPublic(): rep += v.__str__( indent + 1 ) + os...
def visitNode(self, visitor)
for detecting the default name