22 __all__ = [
"ConfigChoiceField"]
25 import collections.abc
27 from .config
import Config, Field, FieldValidationError, _typeStr, _joinNamePath
28 from .comparison
import getComparisonName, compareScalars, compareConfigs
29 from .callStack
import getCallStack, getStackFrame
33 """A mutable set class that tracks the selection of multi-select 34 `~lsst.pex.config.ConfigChoiceField` objects. 38 dict_ : `ConfigInstanceDict` 39 The dictionary of instantiated configs. 42 at : `lsst.pex.config.callStack.StackFrame`, optional 43 The call stack when the selection was made. 44 label : `str`, optional 45 Label for history tracking. 46 setHistory : `bool`, optional 47 Add this even to the history, if `True`. 51 This class allows a user of a multi-select 52 `~lsst.pex.config.ConfigChoiceField` to add or discard items from the set 53 of active configs. Each change to the selection is tracked in the field's 57 def __init__(self, dict_, value, at=None, label="assignment", setHistory=True):
67 if v
not in self.
_dict:
69 self.
_dict.__getitem__(v, at=at)
71 msg =
"Value %s is of incorrect type %s. Sequence type expected"(value, _typeStr(value))
73 self.
_set = set(value)
78 self.
__history.append((
"Set selection to %s" % self, at, label))
80 def add(self, value, at=None):
81 """Add a value to the selected set. 85 "Cannot modify a frozen Config")
90 if value
not in self.
_dict:
92 self.
_dict.__getitem__(value, at=at)
94 self.
__history.append((
"added %s to selection" % value, at,
"selection"))
98 """Discard a value from the selected set. 102 "Cannot modify a frozen Config")
104 if value
not in self.
_dict:
110 self.
__history.append((
"removed %s from selection" % value, at,
"selection"))
114 return len(self.
_set)
117 return iter(self.
_set)
120 return value
in self.
_set 123 return repr(list(self.
_set))
126 return str(list(self.
_set))
130 """Dictionary of instantiated configs, used to populate a 131 `~lsst.pex.config.ConfigChoiceField`. 135 config : `lsst.pex.config.Config` 136 A configuration instance. 137 field : `lsst.pex.config.Field`-type 138 A configuration field. Note that the `lsst.pex.config.Field.fieldmap` 139 attribute must provide key-based access to configuration classes, 140 (that is, ``typemap[name]``). 143 collections.abc.Mapping.__init__(self)
148 self.
_history = config._history.setdefault(field.name, [])
151 types = property(
lambda x: x._field.typemap)
154 return k
in self.
_field.typemap
157 return len(self.
_field.typemap)
160 return iter(self.
_field.typemap)
162 def _setSelection(self, value, at=None, label="assignment"):
174 if value
not in self.
_dict:
177 self.
_history.append((value, at, label))
182 "Single-selection field has no attribute 'names'")
185 def _setNames(self, value):
188 "Single-selection field has no attribute 'names'")
194 "Single-selection field has no attribute 'names'")
200 "Multi-selection field has no attribute 'name'")
203 def _setName(self, value):
206 "Multi-selection field has no attribute 'name'")
212 "Multi-selection field has no attribute 'name'")
215 names = property(_getNames, _setNames, _delNames)
216 """List of names of active items in a multi-selection 217 ``ConfigInstanceDict``. Disabled in a single-selection ``_Registry``; use 218 the `name` attribute instead. 221 name = property(_getName, _setName, _delName)
222 """Name of the active item in a single-selection ``ConfigInstanceDict``. 223 Disabled in a multi-selection ``_Registry``; use the ``names`` attribute 227 def _getActive(self):
236 active = property(_getActive)
237 """The selected items. 239 For multi-selection, this is equivalent to: ``[self[name] for name in 240 self.names]``. For single-selection, this is equivalent to: ``self[name]``. 245 value = self.
_dict[k]
248 dtype = self.
_field.typemap[k]
251 "Unknown key %r in Registry/ConfigChoiceField" % k)
252 name = _joinNamePath(self.
_config._name, self.
_field.name, k)
255 at.insert(0, dtype._source)
256 value = self.
_dict.setdefault(k, dtype(__name=name, __at=at, __label=label))
264 dtype = self.
_field.typemap[k]
268 if value != dtype
and type(value) != dtype:
269 msg =
"Value %s at key %k is of incorrect type %s. Expected type %s" % \
270 (value, k, _typeStr(value), _typeStr(dtype))
275 name = _joinNamePath(self.
_config._name, self.
_field.name, k)
276 oldValue = self.
_dict.get(k,
None)
279 self.
_dict[k] = value(__name=name, __at=at, __label=label)
281 self.
_dict[k] = dtype(__name=name, __at=at, __label=label, **value._storage)
285 oldValue.update(__at=at, __label=label, **value._storage)
287 def _rename(self, fullname):
288 for k, v
in self.
_dict.items():
289 v._rename(_joinNamePath(name=fullname, index=k))
292 if hasattr(getattr(self.__class__, attr,
None),
'__set__'):
294 object.__setattr__(self, attr, value)
295 elif attr
in self.__dict__
or attr
in [
"_history",
"_field",
"_config",
"_dict",
296 "_selection",
"__doc__"]:
298 object.__setattr__(self, attr, value)
301 msg =
"%s has no attribute %s" % (_typeStr(self.
_field), attr)
306 """A configuration field (`~lsst.pex.config.Field` subclass) that allows a 307 user to choose from a set of `~lsst.pex.config.Config` types. 312 Documentation string for the field. 313 typemap : `dict`-like 314 A mapping between keys and `~lsst.pex.config.Config`-types as values. 315 See *Examples* for details. 316 default : `str`, optional 317 The default configuration name. 318 optional : `bool`, optional 319 When `False`, `lsst.pex.config.Config.validate` will fail if the 320 field's value is `None`. 321 multi : `bool`, optional 322 If `True`, the field allows multiple selections. In this case, set the 323 selections by assigning a sequence to the ``names`` attribute of the 326 If `False`, the field allows only a single selection. In this case, 327 set the active config by assigning the config's key from the 328 ``typemap`` to the field's ``name`` attribute (see *Examples*). 329 deprecated : None or `str`, optional 330 A description of why this Field is deprecated, including removal date. 331 If not None, the string is appended to the docstring for this Field. 347 ``ConfigChoiceField`` instances can allow either single selections or 348 multiple selections, depending on the ``multi`` parameter. For 349 single-selection fields, set the selection with the ``name`` attribute. 350 For multi-selection fields, set the selection though the ``names`` 353 This field is validated only against the active selection. If the 354 ``active`` attribute is `None` and the field is not optional, validation 357 When saving a configuration with a ``ConfigChoiceField``, the entire set is 358 saved, as well as the active selection. 362 While the ``typemap`` is shared by all instances of the field, each 363 instance of the field has its own instance of a particular sub-config type. 365 For example, ``AaaConfig`` is a config object 367 >>> from lsst.pex.config import Config, ConfigChoiceField, Field 368 >>> class AaaConfig(Config): 369 ... somefield = Field("doc", int) 372 The ``MyConfig`` config has a ``ConfigChoiceField`` field called ``choice`` 373 that maps the ``AaaConfig`` type to the ``"AAA"`` key: 375 >>> TYPEMAP = {"AAA", AaaConfig} 376 >>> class MyConfig(Config): 377 ... choice = ConfigChoiceField("doc for choice", TYPEMAP) 380 Creating an instance of ``MyConfig``: 382 >>> instance = MyConfig() 384 Setting value of the field ``somefield`` on the "AAA" key of the ``choice`` 387 >>> instance.choice['AAA'].somefield = 5 389 **Selecting the active configuration** 391 Make the ``"AAA"`` key the active configuration value for the ``choice`` 394 >>> instance.choice = "AAA" 396 Alternatively, the last line can be written: 398 >>> instance.choice.name = "AAA" 400 (If the config instance allows multiple selections, you'd assign a sequence 401 to the ``names`` attribute instead.) 403 ``ConfigChoiceField`` instances also allow multiple values of the same type: 405 >>> TYPEMAP["CCC"] = AaaConfig 406 >>> TYPEMAP["BBB"] = AaaConfig 409 instanceDictClass = ConfigInstanceDict
411 def __init__(self, doc, typemap, default=None, optional=False, multi=False, deprecated=None):
414 source=source, deprecated=deprecated)
418 def _getOrMake(self, instance, label="default"):
419 instanceDict = instance._storage.get(self.name)
420 if instanceDict
is None:
422 instanceDict = self.
dtype(instance, self)
423 instanceDict.__doc__ = self.
doc 424 instance._storage[self.name] = instanceDict
425 history = instance._history.setdefault(self.name, [])
426 history.append((
"Initialized from defaults", at, label))
431 if instance
is None or not isinstance(instance, Config):
436 def __set__(self, instance, value, at=None, label="assignment"):
443 for k, v
in value.items():
444 instanceDict.__setitem__(k, v, at=at, label=label)
445 instanceDict._setSelection(value._selection, at=at, label=label)
448 instanceDict._setSelection(value, at=at, label=label)
451 instanceDict = self.
__get__(instance)
452 fullname = _joinNamePath(instance._name, self.name)
453 instanceDict._rename(fullname)
456 instanceDict = self.
__get__(instance)
457 if instanceDict.active
is None and not self.
optional:
458 msg =
"Required field cannot be None" 460 elif instanceDict.active
is not None:
462 for a
in instanceDict.active:
465 instanceDict.active.validate()
468 instanceDict = self.
__get__(instance)
472 dict_[
"names"] = instanceDict.names
474 dict_[
"name"] = instanceDict.name
477 for k, v
in instanceDict.items():
478 values[k] = v.toDict()
479 dict_[
"values"] = values
488 instanceDict = self.
__get__(instance)
489 for v
in instanceDict.values():
492 def _collectImports(self, instance, imports):
493 instanceDict = self.
__get__(instance)
494 for config
in instanceDict.values():
495 config._collectImports()
496 imports |= config._imports
498 def save(self, outfile, instance):
499 instanceDict = self.
__get__(instance)
500 fullname = _joinNamePath(instance._name, self.name)
501 for v
in instanceDict.values():
504 outfile.write(
u"{}.names={!r}\n".
format(fullname, instanceDict.names))
506 outfile.write(
u"{}.name={!r}\n".
format(fullname, instanceDict.name))
509 """Customize deep-copying, because we always want a reference to the 512 WARNING: this must be overridden by subclasses if they change the 513 constructor signature! 515 other = type(self)(doc=self.
doc, typemap=self.
typemap, default=copy.deepcopy(self.
default),
517 other.source = self.
source 520 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
521 """Compare two fields for equality. 523 Used by `lsst.pex.ConfigChoiceField.compare`. 527 instance1 : `lsst.pex.config.Config` 528 Left-hand side config instance to compare. 529 instance2 : `lsst.pex.config.Config` 530 Right-hand side config instance to compare. 532 If `True`, this function returns as soon as an inequality if found. 534 Relative tolerance for floating point comparisons. 536 Absolute tolerance for floating point comparisons. 538 A callable that takes a string, used (possibly repeatedly) to 544 `True` if the fields are equal, `False` otherwise. 548 Only the selected configurations are compared, as the parameters of any 549 others do not matter. 551 Floating point comparisons are performed by `numpy.allclose`. 553 d1 = getattr(instance1, self.name)
554 d2 = getattr(instance2, self.name)
556 _joinNamePath(instance1._name, self.name),
557 _joinNamePath(instance2._name, self.name)
559 if not compareScalars(
"selection for %s" % name, d1._selection, d2._selection, output=output):
561 if d1._selection
is None:
564 nested = [(k, d1[k], d2[k])
for k
in d1._selection]
566 nested = [(d1._selection, d1[d1._selection], d2[d1._selection])]
568 for k, c1, c2
in nested:
569 result =
compareConfigs(
"%s[%r]" % (name, k), c1, c2, shortcut=shortcut,
570 rtol=rtol, atol=atol, output=output)
571 if not result
and shortcut:
573 equal = equal
and result
def __getitem__(self, k, at=None, label="default")
def __init__(self, doc, typemap, default=None, optional=False, multi=False, deprecated=None)
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
def save(self, outfile, instance)
def __init__(self, dict_, value, at=None, label="assignment", setHistory=True)
def __setattr__(self, attr, value, at=None, label="assignment")
def compareConfigs(name, c1, c2, shortcut=True, rtol=1E-8, atol=1E-8, output=None)
def validate(self, instance)
def add(self, value, at=None)
def _setSelection(self, value, at=None, label="assignment")
def __get__(self, instance, owner=None)
def freeze(self, instance)
def __deepcopy__(self, memo)
def getStackFrame(relative=0)
def __contains__(self, value)
def discard(self, value, at=None)
def __get__(self, instance, owner=None, at=None, label="default")
def __setitem__(self, k, value, at=None, label="assignment")
def toDict(self, instance)
def __init__(self, config, field)
def rename(self, instance)
def __contains__(self, k)
def getComparisonName(name1, name2)
def compareScalars(name, v1, v2, output, rtol=1E-8, atol=1E-8, dtype=None)
def _getOrMake(self, instance, label="default")
def __set__(self, instance, value, at=None, label="assignment")
def _setup(self, doc, dtype, default, check, optional, source, deprecated)