LSST Applications g0265f82a02+0e5473021a,g02d81e74bb+bd2ed33bd6,g1470d8bcf6+de7501a2e0,g14a832a312+ff425fae3c,g2079a07aa2+86d27d4dc4,g2305ad1205+91a32aca49,g295015adf3+762506a1ad,g2bbee38e9b+0e5473021a,g337abbeb29+0e5473021a,g3ddfee87b4+c34e8be1fa,g487adcacf7+5fae3daba8,g50ff169b8f+96c6868917,g52b1c1532d+585e252eca,g591dd9f2cf+ea1711114f,g5a732f18d5+53520f316c,g64a986408d+bd2ed33bd6,g858d7b2824+bd2ed33bd6,g8a8a8dda67+585e252eca,g99cad8db69+016a06b37a,g9ddcbc5298+9a081db1e4,ga1e77700b3+15fc3df1f7,ga8c6da7877+ef4e3a5875,gb0e22166c9+60f28cb32d,gb6a65358fc+0e5473021a,gba4ed39666+c2a2e4ac27,gbb8dafda3b+09e12c87ab,gc120e1dc64+bc2e06c061,gc28159a63d+0e5473021a,gcf0d15dbbd+c34e8be1fa,gdaeeff99f8+f9a426f77a,ge6526c86ff+508d0e0a30,ge79ae78c31+0e5473021a,gee10cc3b42+585e252eca,gf18bd8381d+8d59551888,gf1cff7945b+bd2ed33bd6,w.2024.16
LSST Data Management Base Package
Loading...
Searching...
No Matches
Public Member Functions | Public Attributes | Protected Member Functions | Static Protected Member Functions | List of all members
lsst.pex.config.configurableField.ConfigurableField Class Reference
Inheritance diagram for lsst.pex.config.configurableField.ConfigurableField:
lsst.pex.config.config.Field lsst.pex.config.configurableField.ConfigurableInstance

Public Member Functions

 validateTarget (self, target, ConfigClass)
 
 __init__ (self, doc, target, ConfigClass=None, default=None, check=None, deprecated=None)
 
ConfigurableField __get__ (self, None instance, Any owner=None, Any at=None, str label="default")
 
ConfigurableInstance[FieldTypeVar] __get__ (self, Config instance, Any owner=None, Any at=None, str label="default")
 
 __get__ (self, instance, owner=None, at=None, label="default")
 
 __set__ (self, instance, value, at=None, label="assignment")
 
 rename (self, instance)
 
 save (self, outfile, instance)
 
 freeze (self, instance)
 
 toDict (self, instance)
 
 validate (self, instance)
 
 __deepcopy__ (self, memo)
 

Public Attributes

 target
 
 ConfigClass
 
 name
 

Protected Member Functions

 _collectImports (self, instance, imports)
 
 _compare (self, instance1, instance2, shortcut, rtol, atol, output)
 

Static Protected Member Functions

Mapping[str, Any] _parseTypingArgs (tuple[type,...]|tuple[str,...] params, Mapping[str, Any] kwds)
 

Detailed Description

A configuration field (`~lsst.pex.config.Field` subclass) that can be
can be retargeted towards a different configurable (often a
`lsst.pipe.base.Task` subclass).

The ``ConfigurableField`` is often used to configure subtasks, which are
tasks (`~lsst.pipe.base.Task`) called by a parent task.

Parameters
----------
doc : `str`
    A description of the configuration field.
target : configurable class
    The configurable target. Configurables have a ``ConfigClass``
    attribute. Within the task framework, configurables are
    `lsst.pipe.base.Task` subclasses).
ConfigClass : `lsst.pex.config.Config`-type, optional
    The subclass of `lsst.pex.config.Config` expected as the configuration
    class of the ``target``. If ``ConfigClass`` is unset then
    ``target.ConfigClass`` is used.
default : ``ConfigClass``-type, optional
    The default configuration class. Normally this parameter is not set,
    and defaults to ``ConfigClass`` (or ``target.ConfigClass``).
check : callable, optional
    Callable that takes the field's value (the ``target``) as its only
    positional argument, and returns `True` if the ``target`` is valid (and
    `False` otherwise).
deprecated : None or `str`, optional
    A description of why this Field is deprecated, including removal date.
    If not None, the string is appended to the docstring for this Field.

See Also
--------
ChoiceField
ConfigChoiceField
ConfigDictField
ConfigField
DictField
Field
ListField
RangeField
RegistryField

Notes
-----
You can use the `ConfigurableInstance.apply` method to construct a
fully-configured configurable.

Definition at line 228 of file configurableField.py.

Constructor & Destructor Documentation

◆ __init__()

lsst.pex.config.configurableField.ConfigurableField.__init__ ( self,
doc,
target,
ConfigClass = None,
default = None,
check = None,
deprecated = None )

Reimplemented from lsst.pex.config.config.Field.

Definition at line 322 of file configurableField.py.

322 def __init__(self, doc, target, ConfigClass=None, default=None, check=None, deprecated=None):
323 ConfigClass = self.validateTarget(target, ConfigClass)
324
325 if default is None:
326 default = ConfigClass
327 if default != ConfigClass and type(default) is not ConfigClass:
328 raise TypeError(
329 f"'default' is of incorrect type {_typeStr(default)}. Expected {_typeStr(ConfigClass)}"
330 )
331
332 source = getStackFrame()
333 self._setup(
334 doc=doc,
335 dtype=ConfigurableInstance,
336 default=default,
337 check=check,
338 optional=False,
339 source=source,
340 deprecated=deprecated,
341 )
342 self.target = target
343 self.ConfigClass = ConfigClass
344

Member Function Documentation

◆ __deepcopy__()

lsst.pex.config.configurableField.ConfigurableField.__deepcopy__ ( self,
memo )
Customize deep-copying, because we always want a reference to the
original typemap.

WARNING: this must be overridden by subclasses if they change the
constructor signature!

Definition at line 446 of file configurableField.py.

446 def __deepcopy__(self, memo):
447 """Customize deep-copying, because we always want a reference to the
448 original typemap.
449
450 WARNING: this must be overridden by subclasses if they change the
451 constructor signature!
452 """
453 return type(self)(
454 doc=self.doc,
455 target=self.target,
456 ConfigClass=self.ConfigClass,
457 default=copy.deepcopy(self.default),
458 )
459

◆ __get__() [1/3]

ConfigurableInstance[FieldTypeVar] lsst.pex.config.configurableField.ConfigurableField.__get__ ( self,
Config instance,
Any owner = None,
Any at = None,
str label = "default" )

Reimplemented from lsst.pex.config.config.Field.

Definition at line 367 of file configurableField.py.

369 ) -> ConfigurableInstance[FieldTypeVar]:
370 ...
371

◆ __get__() [2/3]

lsst.pex.config.configurableField.ConfigurableField.__get__ ( self,
instance,
owner = None,
at = None,
label = "default" )

Reimplemented from lsst.pex.config.config.Field.

Definition at line 372 of file configurableField.py.

372 def __get__(self, instance, owner=None, at=None, label="default"):
373 if instance is None or not isinstance(instance, Config):
374 return self
375 else:
376 return self.__getOrMake(instance, at=at, label=label)
377

◆ __get__() [3/3]

ConfigurableField lsst.pex.config.configurableField.ConfigurableField.__get__ ( self,
None instance,
Any owner = None,
Any at = None,
str label = "default" )

Reimplemented from lsst.pex.config.config.Field.

Definition at line 361 of file configurableField.py.

363 ) -> ConfigurableField:
364 ...
365

◆ __set__()

lsst.pex.config.configurableField.ConfigurableField.__set__ ( self,
instance,
value,
at = None,
label = "assignment" )
Set an attribute on the config instance.

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.
value : obj
    Value to set on this field.
at : `list` of `~lsst.pex.config.callStack.StackFrame` or `None`,\
        optional
    The call stack (created by
    `lsst.pex.config.callStack.getCallStack`).
label : `str`, optional
    Event label for the history.

Notes
-----
This method is invoked by the owning `lsst.pex.config.Config` object
and should not be called directly.

Derived `~lsst.pex.config.Field` classes may need to override the
behavior. When overriding ``__set__``, `~lsst.pex.config.Field` authors
should follow the following rules:

- Do not allow modification of frozen configs.
- Validate the new value **before** modifying the field. Except if the
  new value is `None`. `None` is special and no attempt should be made
  to validate it until `lsst.pex.config.Config.validate` is called.
- Do not modify the `~lsst.pex.config.Config` instance to contain
  invalid values.
- If the field is modified, update the history of the
  `lsst.pex.config.field.Field` to reflect the changes.

In order to decrease the need to implement this method in derived
`~lsst.pex.config.Field` types, value validation is performed in the
`lsst.pex.config.Field._validateValue`. If only the validation step
differs in the derived `~lsst.pex.config.Field`, it is simpler to
implement `lsst.pex.config.Field._validateValue` than to reimplement
``__set__``. More complicated behavior, however, may require
reimplementation.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 378 of file configurableField.py.

378 def __set__(self, instance, value, at=None, label="assignment"):
379 if instance._frozen:
380 raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
381 if at is None:
382 at = getCallStack()
383 oldValue = self.__getOrMake(instance, at=at)
384
385 if isinstance(value, ConfigurableInstance):
386 oldValue.retarget(value.target, value.ConfigClass, at, label)
387 oldValue.update(__at=at, __label=label, **value._storage)
388 elif type(value) is oldValue._ConfigClass:
389 oldValue.update(__at=at, __label=label, **value._storage)
390 elif value == oldValue.ConfigClass:
391 value = oldValue.ConfigClass()
392 oldValue.update(__at=at, __label=label, **value._storage)
393 else:
394 msg = "Value {} is of incorrect type {}. Expected {}".format(
395 value,
396 _typeStr(value),
397 _typeStr(oldValue.ConfigClass),
398 )
399 raise FieldValidationError(self, instance, msg)
400

◆ _collectImports()

lsst.pex.config.configurableField.ConfigurableField._collectImports ( self,
instance,
imports )
protected
Call the _collectImports method on all config
objects the field may own, and union them with the supplied imports
set.

Parameters
----------
instance : instance or subclass of `lsst.pex.config.Config`
    A config object that has this field defined on it
imports : `set`
    Set of python modules that need imported after persistence

Reimplemented from lsst.pex.config.config.Field.

Definition at line 406 of file configurableField.py.

406 def _collectImports(self, instance, imports):
407 value = self.__get__(instance)
408 target = value.target
409 imports.add(target.__module__)
410 value.value._collectImports()
411 imports |= value.value._imports
412

◆ _compare()

lsst.pex.config.configurableField.ConfigurableField._compare ( self,
instance1,
instance2,
shortcut,
rtol,
atol,
output )
protected
Compare two fields for equality.

Used by `lsst.pex.ConfigDictField.compare`.

Parameters
----------
instance1 : `lsst.pex.config.Config`
    Left-hand side config instance to compare.
instance2 : `lsst.pex.config.Config`
    Right-hand side config instance to compare.
shortcut : `bool`
    If `True`, this function returns as soon as an inequality if found.
rtol : `float`
    Relative tolerance for floating point comparisons.
atol : `float`
    Absolute tolerance for floating point comparisons.
output : callable
    A callable that takes a string, used (possibly repeatedly) to
    report inequalities. For example: `print`.

Returns
-------
isEqual : bool
    `True` if the fields are equal, `False` otherwise.

Notes
-----
Floating point comparisons are performed by `numpy.allclose`.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 460 of file configurableField.py.

460 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
461 """Compare two fields for equality.
462
463 Used by `lsst.pex.ConfigDictField.compare`.
464
465 Parameters
466 ----------
467 instance1 : `lsst.pex.config.Config`
468 Left-hand side config instance to compare.
469 instance2 : `lsst.pex.config.Config`
470 Right-hand side config instance to compare.
471 shortcut : `bool`
472 If `True`, this function returns as soon as an inequality if found.
473 rtol : `float`
474 Relative tolerance for floating point comparisons.
475 atol : `float`
476 Absolute tolerance for floating point comparisons.
477 output : callable
478 A callable that takes a string, used (possibly repeatedly) to
479 report inequalities. For example: `print`.
480
481 Returns
482 -------
483 isEqual : bool
484 `True` if the fields are equal, `False` otherwise.
485
486 Notes
487 -----
488 Floating point comparisons are performed by `numpy.allclose`.
489 """
490 c1 = getattr(instance1, self.name)._value
491 c2 = getattr(instance2, self.name)._value
492 name = getComparisonName(
493 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
494 )
495 return compareConfigs(name, c1, c2, shortcut=shortcut, rtol=rtol, atol=atol, output=output)

◆ _parseTypingArgs()

Mapping[str, Any] lsst.pex.config.configurableField.ConfigurableField._parseTypingArgs ( tuple[type, ...] | tuple[str, ...] params,
Mapping[str, Any] kwds )
staticprotected
Parse type annotations into keyword constructor arguments.

This is a special private method that interprets type arguments (i.e.
Field[str]) into keyword arguments to be passed on to the constructor.

Subclasses of Field can implement this method to customize how they
handle turning type parameters into keyword arguments (see DictField
for an example)

Parameters
----------
params : `tuple` of `type` or `tuple` of str
    Parameters passed to the type annotation. These will either be
    types or strings. Strings are to interpreted as forward references
    and will be treated as such.
kwds : `MutableMapping` with keys of `str` and values of `Any`
    These are the user supplied keywords that are to be passed to the
    Field constructor.

Returns
-------
kwds : `MutableMapping` with keys of `str` and values of `Any`
    The mapping of keywords that will be passed onto the constructor
    of the Field. Should be filled in with any information gleaned
    from the input parameters.

Raises
------
ValueError
    Raised if params is of incorrect length.
    Raised if a forward reference could not be resolved
    Raised if there is a conflict between params and values in kwds

Reimplemented from lsst.pex.config.config.Field.

Definition at line 346 of file configurableField.py.

348 ) -> Mapping[str, Any]:
349 return kwds
350

◆ freeze()

lsst.pex.config.configurableField.ConfigurableField.freeze ( self,
instance )
Make this field read-only (for internal use only).

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Notes
-----
Freezing is only relevant for fields that hold subconfigs. Fields which
hold subconfigs should freeze each subconfig.

**Subclasses should implement this method.**

Reimplemented from lsst.pex.config.config.Field.

Definition at line 430 of file configurableField.py.

430 def freeze(self, instance):
431 value = self.__getOrMake(instance)
432 value.freeze()
433

◆ rename()

lsst.pex.config.configurableField.ConfigurableField.rename ( self,
instance )
Rename the field in a `~lsst.pex.config.Config` (for internal use
only).

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Notes
-----
This method is invoked by the `lsst.pex.config.Config` object that
contains this field and should not be called directly.

Renaming is only relevant for `~lsst.pex.config.Field` instances that
hold subconfigs. `~lsst.pex.config.Field`\s that hold subconfigs should
rename each subconfig with the full field name as generated by
`lsst.pex.config.config._joinNamePath`.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 401 of file configurableField.py.

401 def rename(self, instance):
402 fullname = _joinNamePath(instance._name, self.name)
403 value = self.__getOrMake(instance)
404 value._rename(fullname)
405

◆ save()

lsst.pex.config.configurableField.ConfigurableField.save ( self,
outfile,
instance )
Save this field to a file (for internal use only).

Parameters
----------
outfile : file-like object
    A writeable field handle.
instance : `~lsst.pex.config.Config`
    The `~lsst.pex.config.Config` instance that contains this field.

Notes
-----
This method is invoked by the `~lsst.pex.config.Config` object that
contains this field and should not be called directly.

The output consists of the documentation string
(`lsst.pex.config.Field.doc`) formatted as a Python comment. The second
line is formatted as an assignment: ``{fullname}={value}``.

This output can be executed with Python.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 413 of file configurableField.py.

413 def save(self, outfile, instance):
414 fullname = _joinNamePath(instance._name, self.name)
415 value = self.__getOrMake(instance)
416 target = value.target
417
418 if target != self.target:
419 # not targeting the field-default target.
420 # save target information
421 ConfigClass = value.ConfigClass
422 outfile.write(
423 "{}.retarget(target={}, ConfigClass={})\n\n".format(
424 fullname, _typeStr(target), _typeStr(ConfigClass)
425 )
426 )
427 # save field values
428 value._save(outfile)
429

◆ toDict()

lsst.pex.config.configurableField.ConfigurableField.toDict ( self,
instance )
Convert the field value so that it can be set as the value of an
item in a `dict` (for internal use only).

Parameters
----------
instance : `~lsst.pex.config.Config`
    The `~lsst.pex.config.Config` that contains this field.

Returns
-------
value : object
    The field's value. See *Notes*.

Notes
-----
This method invoked by the owning `~lsst.pex.config.Config` object and
should not be called directly.

Simple values are passed through. Complex data structures must be
manipulated. For example, a `~lsst.pex.config.Field` holding a
subconfig should, instead of the subconfig object, return a `dict`
where the keys are the field names in the subconfig, and the values are
the field values in the subconfig.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 434 of file configurableField.py.

434 def toDict(self, instance):
435 value = self.__get__(instance)
436 return value.toDict()
437

◆ validate()

lsst.pex.config.configurableField.ConfigurableField.validate ( self,
instance )
Validate the field (for internal use only).

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Raises
------
lsst.pex.config.FieldValidationError
    Raised if verification fails.

Notes
-----
This method provides basic validation:

- Ensures that the value is not `None` if the field is not optional.
- Ensures type correctness.
- Ensures that the user-provided ``check`` function is valid.

Most `~lsst.pex.config.Field` subclasses should call
`lsst.pex.config.Field.validate` if they re-implement
`~lsst.pex.config.Field.validate`.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 438 of file configurableField.py.

438 def validate(self, instance):
439 value = self.__get__(instance)
440 value.validate()
441
442 if self.check is not None and not self.check(value):
443 msg = "%s is not a valid value" % str(value)
444 raise FieldValidationError(self, instance, msg)
445

◆ validateTarget()

lsst.pex.config.configurableField.ConfigurableField.validateTarget ( self,
target,
ConfigClass )
Validate the target and configuration class.

Parameters
----------
target : configurable class
    The configurable being verified.
ConfigClass : `lsst.pex.config.Config`-type or `None`
    The configuration class associated with the ``target``. This can
    be `None` if ``target`` has a ``ConfigClass`` attribute.

Raises
------
AttributeError
    Raised if ``ConfigClass`` is `None` and ``target`` does not have a
    ``ConfigClass`` attribute.
TypeError
    Raised if ``ConfigClass`` is not a `~lsst.pex.config.Config`
    subclass.
ValueError
    Raised if:

    - ``target`` is not callable (callables have a ``__call__``
      method).
    - ``target`` is not startically defined (does not have
      ``__module__`` or ``__name__`` attributes).

Definition at line 277 of file configurableField.py.

277 def validateTarget(self, target, ConfigClass):
278 """Validate the target and configuration class.
279
280 Parameters
281 ----------
282 target : configurable class
283 The configurable being verified.
284 ConfigClass : `lsst.pex.config.Config`-type or `None`
285 The configuration class associated with the ``target``. This can
286 be `None` if ``target`` has a ``ConfigClass`` attribute.
287
288 Raises
289 ------
290 AttributeError
291 Raised if ``ConfigClass`` is `None` and ``target`` does not have a
292 ``ConfigClass`` attribute.
293 TypeError
294 Raised if ``ConfigClass`` is not a `~lsst.pex.config.Config`
295 subclass.
296 ValueError
297 Raised if:
298
299 - ``target`` is not callable (callables have a ``__call__``
300 method).
301 - ``target`` is not startically defined (does not have
302 ``__module__`` or ``__name__`` attributes).
303 """
304 if ConfigClass is None:
305 try:
306 ConfigClass = target.ConfigClass
307 except Exception:
308 raise AttributeError("'target' must define attribute 'ConfigClass'")
309 if not issubclass(ConfigClass, Config):
310 raise TypeError(
311 "'ConfigClass' is of incorrect type %s.'ConfigClass' must be a subclass of Config"
312 % _typeStr(ConfigClass)
313 )
314 if not hasattr(target, "__call__"):
315 raise ValueError("'target' must be callable")
316 if not hasattr(target, "__module__") or not hasattr(target, "__name__"):
317 raise ValueError(
318 "'target' must be statically defined (must have '__module__' and '__name__' attributes)"
319 )
320 return ConfigClass
321

Member Data Documentation

◆ ConfigClass

lsst.pex.config.configurableField.ConfigurableField.ConfigClass

Definition at line 343 of file configurableField.py.

◆ name

lsst.pex.config.configurableField.ConfigurableField.name

Definition at line 493 of file configurableField.py.

◆ target

lsst.pex.config.configurableField.ConfigurableField.target

Definition at line 342 of file configurableField.py.


The documentation for this class was generated from the following file: