28 __all__ = [
"ConfigChoiceField"]
31 import collections.abc
33 from .config
import Config, Field, FieldValidationError, _typeStr, _joinNamePath
34 from .comparison
import getComparisonName, compareScalars, compareConfigs
35 from .callStack
import getCallStack, getStackFrame
39 """A mutable set class that tracks the selection of multi-select 40 `~lsst.pex.config.ConfigChoiceField` objects. 44 dict_ : `ConfigInstanceDict` 45 The dictionary of instantiated configs. 48 at : `lsst.pex.config.callStack.StackFrame`, optional 49 The call stack when the selection was made. 50 label : `str`, optional 51 Label for history tracking. 52 setHistory : `bool`, optional 53 Add this even to the history, if `True`. 57 This class allows a user of a multi-select 58 `~lsst.pex.config.ConfigChoiceField` to add or discard items from the set 59 of active configs. Each change to the selection is tracked in the field's 63 def __init__(self, dict_, value, at=None, label="assignment", setHistory=True):
73 if v
not in self.
_dict:
75 self.
_dict.__getitem__(v, at=at)
77 msg =
"Value %s is of incorrect type %s. Sequence type expected" % (value, _typeStr(value))
86 def add(self, value, at=None):
87 """Add a value to the selected set. 91 "Cannot modify a frozen Config")
96 if value
not in self.
_dict:
98 self.
_dict.__getitem__(value, at=at)
100 self.
__history.
append((
"added %s to selection" % value, at,
"selection"))
104 """Discard a value from the selected set. 108 "Cannot modify a frozen Config")
110 if value
not in self.
_dict:
116 self.
__history.
append((
"removed %s from selection" % value, at,
"selection"))
120 return len(self.
_set)
126 return value
in self.
_set 136 """Dictionary of instantiated configs, used to populate a 137 `~lsst.pex.config.ConfigChoiceField`. 141 config : `lsst.pex.config.Config` 142 A configuration instance. 143 field : `lsst.pex.config.Field`-type 144 A configuration field. Note that the `lsst.pex.config.Field.fieldmap` 145 attribute must provide key-based access to configuration classes, 146 (that is, ``typemap[name]``). 149 collections.abc.Mapping.__init__(self)
154 self.
_history = config._history.setdefault(field.name, [])
157 types = property(
lambda x: x._field.typemap)
160 return k
in self.
_field.typemap
163 return len(self.
_field.typemap)
168 def _setSelection(self, value, at=None, label="assignment"):
180 if value
not in self.
_dict:
188 "Single-selection field has no attribute 'names'")
191 def _setNames(self, value):
194 "Single-selection field has no attribute 'names'")
200 "Single-selection field has no attribute 'names'")
206 "Multi-selection field has no attribute 'name'")
209 def _setName(self, value):
212 "Multi-selection field has no attribute 'name'")
218 "Multi-selection field has no attribute 'name'")
221 names = property(_getNames, _setNames, _delNames)
222 """List of names of active items in a multi-selection 223 ``ConfigInstanceDict``. Disabled in a single-selection ``_Registry``; use 224 the `name` attribute instead. 227 name = property(_getName, _setName, _delName)
228 """Name of the active item in a single-selection ``ConfigInstanceDict``. 229 Disabled in a multi-selection ``_Registry``; use the ``names`` attribute 233 def _getActive(self):
242 active = property(_getActive)
243 """The selected items. 245 For multi-selection, this is equivalent to: ``[self[name] for name in 246 self.names]``. For single-selection, this is equivalent to: ``self[name]``. 251 value = self.
_dict[k]
254 dtype = self.
_field.typemap[k]
257 "Unknown key %r in Registry/ConfigChoiceField" % k)
258 name = _joinNamePath(self.
_config._name, self.
_field.name, k)
261 at.insert(0, dtype._source)
262 value = self.
_dict.setdefault(k, dtype(__name=name, __at=at, __label=label))
270 dtype = self.
_field.typemap[k]
274 if value != dtype
and type(value) != dtype:
275 msg =
"Value %s at key %k is of incorrect type %s. Expected type %s" % \
276 (value, k, _typeStr(value), _typeStr(dtype))
281 name = _joinNamePath(self.
_config._name, self.
_field.name, k)
282 oldValue = self.
_dict.get(k,
None)
285 self.
_dict[k] = value(__name=name, __at=at, __label=label)
287 self.
_dict[k] = dtype(__name=name, __at=at, __label=label, **value._storage)
291 oldValue.update(__at=at, __label=label, **value._storage)
293 def _rename(self, fullname):
295 v._rename(_joinNamePath(name=fullname, index=k))
298 if hasattr(getattr(self.__class__, attr,
None),
'__set__'):
300 object.__setattr__(self, attr, value)
301 elif attr
in self.__dict__
or attr
in [
"_history",
"_field",
"_config",
"_dict",
302 "_selection",
"__doc__"]:
304 object.__setattr__(self, attr, value)
307 msg =
"%s has no attribute %s" % (_typeStr(self.
_field), attr)
312 """A configuration field (`~lsst.pex.config.Field` subclass) that allows a 313 user to choose from a set of `~lsst.pex.config.Config` types. 318 Documentation string for the field. 319 typemap : `dict`-like 320 A mapping between keys and `~lsst.pex.config.Config`-types as values. 321 See *Examples* for details. 322 default : `str`, optional 323 The default configuration name. 324 optional : `bool`, optional 325 When `False`, `lsst.pex.config.Config.validate` will fail if the 326 field's value is `None`. 327 multi : `bool`, optional 328 If `True`, the field allows multiple selections. In this case, set the 329 selections by assigning a sequence to the ``names`` attribute of the 332 If `False`, the field allows only a single selection. In this case, 333 set the active config by assigning the config's key from the 334 ``typemap`` to the field's ``name`` attribute (see *Examples*). 335 deprecated : None or `str`, optional 336 A description of why this Field is deprecated, including removal date. 337 If not None, the string is appended to the docstring for this Field. 353 ``ConfigChoiceField`` instances can allow either single selections or 354 multiple selections, depending on the ``multi`` parameter. For 355 single-selection fields, set the selection with the ``name`` attribute. 356 For multi-selection fields, set the selection though the ``names`` 359 This field is validated only against the active selection. If the 360 ``active`` attribute is `None` and the field is not optional, validation 363 When saving a configuration with a ``ConfigChoiceField``, the entire set is 364 saved, as well as the active selection. 368 While the ``typemap`` is shared by all instances of the field, each 369 instance of the field has its own instance of a particular sub-config type. 371 For example, ``AaaConfig`` is a config object 373 >>> from lsst.pex.config import Config, ConfigChoiceField, Field 374 >>> class AaaConfig(Config): 375 ... somefield = Field("doc", int) 378 The ``MyConfig`` config has a ``ConfigChoiceField`` field called ``choice`` 379 that maps the ``AaaConfig`` type to the ``"AAA"`` key: 381 >>> TYPEMAP = {"AAA", AaaConfig} 382 >>> class MyConfig(Config): 383 ... choice = ConfigChoiceField("doc for choice", TYPEMAP) 386 Creating an instance of ``MyConfig``: 388 >>> instance = MyConfig() 390 Setting value of the field ``somefield`` on the "AAA" key of the ``choice`` 393 >>> instance.choice['AAA'].somefield = 5 395 **Selecting the active configuration** 397 Make the ``"AAA"`` key the active configuration value for the ``choice`` 400 >>> instance.choice = "AAA" 402 Alternatively, the last line can be written: 404 >>> instance.choice.name = "AAA" 406 (If the config instance allows multiple selections, you'd assign a sequence 407 to the ``names`` attribute instead.) 409 ``ConfigChoiceField`` instances also allow multiple values of the same 412 >>> TYPEMAP["CCC"] = AaaConfig 413 >>> TYPEMAP["BBB"] = AaaConfig 416 instanceDictClass = ConfigInstanceDict
418 def __init__(self, doc, typemap, default=None, optional=False, multi=False, deprecated=None):
421 source=source, deprecated=deprecated)
425 def _getOrMake(self, instance, label="default"):
426 instanceDict = instance._storage.get(self.name)
427 if instanceDict
is None:
429 instanceDict = self.
dtype(instance, self)
430 instanceDict.__doc__ = self.
doc 431 instance._storage[self.name] = instanceDict
432 history = instance._history.setdefault(self.name, [])
433 history.append((
"Initialized from defaults", at, label))
438 if instance
is None or not isinstance(instance, Config):
443 def __set__(self, instance, value, at=None, label="assignment"):
450 for k, v
in value.items():
451 instanceDict.__setitem__(k, v, at=at, label=label)
452 instanceDict._setSelection(value._selection, at=at, label=label)
455 instanceDict._setSelection(value, at=at, label=label)
458 instanceDict = self.
__get__(instance)
459 fullname = _joinNamePath(instance._name, self.name)
460 instanceDict._rename(fullname)
463 instanceDict = self.
__get__(instance)
464 if instanceDict.active
is None and not self.
optional:
465 msg =
"Required field cannot be None" 467 elif instanceDict.active
is not None:
469 for a
in instanceDict.active:
472 instanceDict.active.validate()
475 instanceDict = self.
__get__(instance)
479 dict_[
"names"] = instanceDict.names
481 dict_[
"name"] = instanceDict.name
484 for k, v
in instanceDict.items():
485 values[k] = v.toDict()
486 dict_[
"values"] = values
495 instanceDict = self.
__get__(instance)
496 for v
in instanceDict.values():
499 def _collectImports(self, instance, imports):
500 instanceDict = self.
__get__(instance)
501 for config
in instanceDict.values():
502 config._collectImports()
503 imports |= config._imports
505 def save(self, outfile, instance):
506 instanceDict = self.
__get__(instance)
507 fullname = _joinNamePath(instance._name, self.name)
508 for v
in instanceDict.values():
511 outfile.write(
u"{}.names={!r}\n".
format(fullname, instanceDict.names))
513 outfile.write(
u"{}.name={!r}\n".
format(fullname, instanceDict.name))
516 """Customize deep-copying, because we always want a reference to the 519 WARNING: this must be overridden by subclasses if they change the 520 constructor signature! 524 other.source = self.
source 527 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
528 """Compare two fields for equality. 530 Used by `lsst.pex.ConfigChoiceField.compare`. 534 instance1 : `lsst.pex.config.Config` 535 Left-hand side config instance to compare. 536 instance2 : `lsst.pex.config.Config` 537 Right-hand side config instance to compare. 539 If `True`, this function returns as soon as an inequality if found. 541 Relative tolerance for floating point comparisons. 543 Absolute tolerance for floating point comparisons. 545 A callable that takes a string, used (possibly repeatedly) to 551 `True` if the fields are equal, `False` otherwise. 555 Only the selected configurations are compared, as the parameters of any 556 others do not matter. 558 Floating point comparisons are performed by `numpy.allclose`. 560 d1 = getattr(instance1, self.name)
561 d2 = getattr(instance2, self.name)
563 _joinNamePath(instance1._name, self.name),
564 _joinNamePath(instance2._name, self.name)
566 if not compareScalars(
"selection for %s" % name, d1._selection, d2._selection, output=output):
568 if d1._selection
is None:
571 nested = [(k, d1[k], d2[k])
for k
in d1._selection]
573 nested = [(d1._selection, d1[d1._selection], d2[d1._selection])]
575 for k, c1, c2
in nested:
576 result =
compareConfigs(
"%s[%r]" % (name, k), c1, c2, shortcut=shortcut,
577 rtol=rtol, atol=atol, output=output)
578 if not result
and shortcut:
580 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)
std::vector< SchemaItem< Flag > > * items
std::shared_ptr< FrameSet > append(FrameSet const &first, FrameSet const &second)
Construct a FrameSet that performs two transformations in series.
def add(self, value, at=None)
daf::base::PropertySet * set
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)
daf::base::PropertyList * list
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)