LSST Applications g044012fb7c+6976b5ec80,g04a91732dc+88a5fc122b,g07dc498a13+7e3c5f68a2,g114c6a66ad+09472d7a76,g1409bbee79+7e3c5f68a2,g1a7e361dbc+7e3c5f68a2,g1fd858c14a+3a43eabc0e,g35bb328faa+fcb1d3bbc8,g3bd4b5ce2c+2647bb081c,g4e0f332c67+5d362be553,g53246c7159+fcb1d3bbc8,g5477a8d5ce+b19c77c7ae,g58d0cdf3ff+4a2e102ff8,g60b5630c4e+09472d7a76,g623d845a50+09472d7a76,g6f0c2978f1+fcf1c0bcd6,g71fabbc107+09472d7a76,g75b6c65c88+d0b1dc44cc,g78460c75b0+2f9a1b4bcd,g786e29fd12+cf7ec2a62a,g7b71ed6315+fcb1d3bbc8,g8852436030+349c7e81d4,g89139ef638+7e3c5f68a2,g9125e01d80+fcb1d3bbc8,g95236ca021+f7a31438ed,g989de1cb63+7e3c5f68a2,g9f33ca652e+f17d666fbc,gaaedd4e678+7e3c5f68a2,gabe3b4be73+1e0a283bba,gb1101e3267+f870f33517,gb58c049af0+f03b321e39,gc99c83e5f0+76d20ab76d,gcf25f946ba+349c7e81d4,gd0fa69b896+f3a65fa83c,gd6cbbdb0b4+c8606af20c,gde0f65d7ad+5bd27d919f,ge278dab8ac+932305ba37,gfba249425e+fcb1d3bbc8,w.2025.07
LSST Data Management Base Package
Loading...
Searching...
No Matches
lsst.meas.base.diaCalculationPlugins.MinMaxDiaPsfFluxConfig Class Reference
Inheritance diagram for lsst.meas.base.diaCalculationPlugins.MinMaxDiaPsfFluxConfig:
lsst.meas.base.diaCalculation.DiaObjectCalculationPluginConfig lsst.meas.base.catalogCalculation.CatalogCalculationPluginConfig lsst.meas.base.pluginsBase.BasePluginConfig lsst.pex.config.config.Config lsst.pex.config.config.ConfigMeta

Public Member Functions

 __iter__ (self)
 
 keys (self)
 
 values (self)
 
 items (self)
 
 __contains__ (self, name)
 
 __new__ (cls, *args, **kw)
 
 __reduce__ (self)
 
 setDefaults (self)
 
 update (self, **kw)
 
 load (self, filename, root="config")
 
 loadFromStream (self, stream, root="config", filename=None, extraLocals=None)
 
 loadFromString (self, code, root="config", filename=None, extraLocals=None)
 
 save (self, filename, root="config")
 
 saveToString (self, skipImports=False)
 
 saveToStream (self, outfile, root="config", skipImports=False)
 
 freeze (self)
 
 toDict (self)
 
 names (self)
 
 validate (self)
 
 formatHistory (self, name, **kwargs)
 
 __setattr__ (self, attr, value, at=None, label="assignment")
 
 __delattr__ (self, attr, at=None, label="deletion")
 
 __eq__ (self, other)
 
 __ne__ (self, other)
 
 __str__ (self)
 
 __repr__ (self)
 
 compare (self, other, shortcut=True, rtol=1e-8, atol=1e-8, output=None)
 
 __init_subclass__ (cls, **kwargs)
 

Protected Member Functions

 _save (self, outfile)
 
 _collectImports (self)
 
 _rename (self, name)
 
 _fromPython (cls, config_py)
 

Protected Attributes

bool _frozen = True
 
 _name = name
 
dict _fields = {}
 
 _source = getStackFrame()
 

Static Protected Attributes

dict _storage [str, Any]
 
dict _history [str, list[Any]]
 
set _imports [Any]
 

Properties

 history = property(lambda x: x._history)
 

Detailed Description

Definition at line 950 of file diaCalculationPlugins.py.

Member Function Documentation

◆ __contains__()

lsst.pex.config.config.Config.__contains__ ( self,
name )
inherited
Return `True` if the specified field exists in this config.

Parameters
----------
name : `str`
    Field name to test for.

Returns
-------
in : `bool`
    `True` if the specified field exists in the config.

Definition at line 1010 of file config.py.

1010 def __contains__(self, name):
1011 """Return `True` if the specified field exists in this config.
1012
1013 Parameters
1014 ----------
1015 name : `str`
1016 Field name to test for.
1017
1018 Returns
1019 -------
1020 in : `bool`
1021 `True` if the specified field exists in the config.
1022 """
1023 return self._storage.__contains__(name)
1024

◆ __delattr__()

lsst.pex.config.config.Config.__delattr__ ( self,
attr,
at = None,
label = "deletion" )
inherited

Definition at line 1585 of file config.py.

1585 def __delattr__(self, attr, at=None, label="deletion"):
1586 if attr in self._fields:
1587 if at is None:
1588 at = getCallStack()
1589 self._fields[attr].__delete__(self, at=at, label=label)
1590 else:
1591 object.__delattr__(self, attr)
1592

◆ __eq__()

lsst.pex.config.config.Config.__eq__ ( self,
other )
inherited

Definition at line 1593 of file config.py.

1593 def __eq__(self, other):
1594 if type(other) is type(self):
1595 for name in self._fields:
1596 thisValue = getattr(self, name)
1597 otherValue = getattr(other, name)
1598 if isinstance(thisValue, float) and math.isnan(thisValue):
1599 if not math.isnan(otherValue):
1600 return False
1601 elif thisValue != otherValue:
1602 return False
1603 return True
1604 return False
1605

◆ __init_subclass__()

lsst.pex.config.config.Config.__init_subclass__ ( cls,
** kwargs )
inherited
Run initialization for every subclass.

Specifically registers the subclass with a YAML representer
and YAML constructor (if pyyaml is available)

Definition at line 1662 of file config.py.

1662 def __init_subclass__(cls, **kwargs):
1663 """Run initialization for every subclass.
1664
1665 Specifically registers the subclass with a YAML representer
1666 and YAML constructor (if pyyaml is available)
1667 """
1668 super().__init_subclass__(**kwargs)
1669
1670 if not yaml:
1671 return
1672
1673 yaml.add_representer(cls, _yaml_config_representer)
1674

◆ __iter__()

lsst.pex.config.config.Config.__iter__ ( self)
inherited
Iterate over fields.

Definition at line 973 of file config.py.

973 def __iter__(self):
974 """Iterate over fields."""
975 return self._fields.__iter__()
976

◆ __ne__()

lsst.pex.config.config.Config.__ne__ ( self,
other )
inherited

Definition at line 1606 of file config.py.

1606 def __ne__(self, other):
1607 return not self.__eq__(other)
1608

◆ __new__()

lsst.pex.config.config.Config.__new__ ( cls,
* args,
** kw )
inherited
Allocate a new `lsst.pex.config.Config` object.

In order to ensure that all Config object are always in a proper state
when handed to users or to derived `~lsst.pex.config.Config` classes,
some attributes are handled at allocation time rather than at
initialization.

This ensures that even if a derived `~lsst.pex.config.Config` class
implements ``__init__``, its author does not need to be concerned about
when or even the base ``Config.__init__`` should be called.

Definition at line 1025 of file config.py.

1025 def __new__(cls, *args, **kw):
1026 """Allocate a new `lsst.pex.config.Config` object.
1027
1028 In order to ensure that all Config object are always in a proper state
1029 when handed to users or to derived `~lsst.pex.config.Config` classes,
1030 some attributes are handled at allocation time rather than at
1031 initialization.
1032
1033 This ensures that even if a derived `~lsst.pex.config.Config` class
1034 implements ``__init__``, its author does not need to be concerned about
1035 when or even the base ``Config.__init__`` should be called.
1036 """
1037 name = kw.pop("__name", None)
1038 at = kw.pop("__at", getCallStack())
1039 # remove __label and ignore it
1040 kw.pop("__label", "default")
1041
1042 instance = object.__new__(cls)
1043 instance._frozen = False
1044 instance._name = name
1045 instance._storage = {}
1046 instance._history = {}
1047 instance._imports = set()
1048 # load up defaults
1049 for field in instance._fields.values():
1050 instance._history[field.name] = []
1051 field.__set__(instance, field.default, at=at + [field.source], label="default")
1052 # set custom default-overrides
1053 instance.setDefaults()
1054 # set constructor overrides
1055 instance.update(__at=at, **kw)
1056 return instance
1057

◆ __reduce__()

lsst.pex.config.config.Config.__reduce__ ( self)
inherited
Reduction for pickling (function with arguments to reproduce).

We need to condense and reconstitute the `~lsst.pex.config.Config`,
since it may contain lambdas (as the ``check`` elements) that cannot
be pickled.

Definition at line 1058 of file config.py.

1058 def __reduce__(self):
1059 """Reduction for pickling (function with arguments to reproduce).
1060
1061 We need to condense and reconstitute the `~lsst.pex.config.Config`,
1062 since it may contain lambdas (as the ``check`` elements) that cannot
1063 be pickled.
1064 """
1065 # The stream must be in characters to match the API but pickle
1066 # requires bytes
1067 stream = io.StringIO()
1068 self.saveToStream(stream)
1069 return (unreduceConfig, (self.__class__, stream.getvalue().encode()))
1070

◆ __repr__()

lsst.pex.config.config.Config.__repr__ ( self)
inherited

Definition at line 1612 of file config.py.

1612 def __repr__(self):
1613 return "{}({})".format(
1614 _typeStr(self),
1615 ", ".join(f"{k}={v!r}" for k, v in self.toDict().items() if v is not None),
1616 )
1617

◆ __setattr__()

lsst.pex.config.config.Config.__setattr__ ( self,
attr,
value,
at = None,
label = "assignment" )
inherited
Set an attribute (such as a field's value).

Notes
-----
Unlike normal Python objects, `~lsst.pex.config.Config` objects are
locked such that no additional attributes nor properties may be added
to them dynamically.

Although this is not the standard Python behavior, it helps to protect
users from accidentally mispelling a field name, or trying to set a
non-existent field.

Definition at line 1550 of file config.py.

1550 def __setattr__(self, attr, value, at=None, label="assignment"):
1551 """Set an attribute (such as a field's value).
1552
1553 Notes
1554 -----
1555 Unlike normal Python objects, `~lsst.pex.config.Config` objects are
1556 locked such that no additional attributes nor properties may be added
1557 to them dynamically.
1558
1559 Although this is not the standard Python behavior, it helps to protect
1560 users from accidentally mispelling a field name, or trying to set a
1561 non-existent field.
1562 """
1563 if attr in self._fields:
1564 if self._fields[attr].deprecated is not None:
1565 fullname = _joinNamePath(self._name, self._fields[attr].name)
1566 warnings.warn(
1567 f"Config field {fullname} is deprecated: {self._fields[attr].deprecated}",
1568 FutureWarning,
1569 stacklevel=2,
1570 )
1571 if at is None:
1572 at = getCallStack()
1573 # This allows Field descriptors to work.
1574 self._fields[attr].__set__(self, value, at=at, label=label)
1575 elif hasattr(getattr(self.__class__, attr, None), "__set__"):
1576 # This allows properties and other non-Field descriptors to work.
1577 return object.__setattr__(self, attr, value)
1578 elif attr in self.__dict__ or attr in ("_name", "_history", "_storage", "_frozen", "_imports"):
1579 # This allows specific private attributes to work.
1580 self.__dict__[attr] = value
1581 else:
1582 # We throw everything else.
1583 raise AttributeError(f"{_typeStr(self)} has no attribute {attr}")
1584

◆ __str__()

lsst.pex.config.config.Config.__str__ ( self)
inherited

Definition at line 1609 of file config.py.

1609 def __str__(self):
1610 return str(self.toDict())
1611

◆ _collectImports()

lsst.pex.config.config.Config._collectImports ( self)
protectedinherited
Add module containing self to the list of things to import and
then loops over all the fields in the config calling a corresponding
collect method.

The field method will call _collectImports on any
configs it may own and return the set of things to import. This
returned set will be merged with the set of imports for this config
class.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField.

Definition at line 1406 of file config.py.

1406 def _collectImports(self):
1407 """Add module containing self to the list of things to import and
1408 then loops over all the fields in the config calling a corresponding
1409 collect method.
1410
1411 The field method will call _collectImports on any
1412 configs it may own and return the set of things to import. This
1413 returned set will be merged with the set of imports for this config
1414 class.
1415 """
1416 self._imports.add(self.__module__)
1417 for field in self._fields.values():
1418 field._collectImports(self, self._imports)
1419

◆ _fromPython()

lsst.pex.config.config.Config._fromPython ( cls,
config_py )
protectedinherited
Instantiate a `Config`-subclass from serialized Python form.

Parameters
----------
config_py : `str`
    A serialized form of the Config as created by
    `Config.saveToStream`.

Returns
-------
config : `Config`
    Reconstructed `Config` instant.

Definition at line 1676 of file config.py.

1676 def _fromPython(cls, config_py):
1677 """Instantiate a `Config`-subclass from serialized Python form.
1678
1679 Parameters
1680 ----------
1681 config_py : `str`
1682 A serialized form of the Config as created by
1683 `Config.saveToStream`.
1684
1685 Returns
1686 -------
1687 config : `Config`
1688 Reconstructed `Config` instant.
1689 """
1690 cls = _classFromPython(config_py)
1691 return unreduceConfig(cls, config_py)
1692
1693

◆ _rename()

lsst.pex.config.config.Config._rename ( self,
name )
protectedinherited
Rename this config object in its parent `~lsst.pex.config.Config`.

Parameters
----------
name : `str`
    New name for this config in its parent `~lsst.pex.config.Config`.

Notes
-----
This method uses the `~lsst.pex.config.Field.rename` method of
individual `lsst.pex.config.Field` instances.
`lsst.pex.config.Field` subclasses may need to implement a ``rename``
method for *this* method to work.

See Also
--------
lsst.pex.config.Field.rename

Reimplemented in lsst.pex.config.configChoiceField.ConfigInstanceDict.

Definition at line 1474 of file config.py.

1474 def _rename(self, name):
1475 """Rename this config object in its parent `~lsst.pex.config.Config`.
1476
1477 Parameters
1478 ----------
1479 name : `str`
1480 New name for this config in its parent `~lsst.pex.config.Config`.
1481
1482 Notes
1483 -----
1484 This method uses the `~lsst.pex.config.Field.rename` method of
1485 individual `lsst.pex.config.Field` instances.
1486 `lsst.pex.config.Field` subclasses may need to implement a ``rename``
1487 method for *this* method to work.
1488
1489 See Also
1490 --------
1491 lsst.pex.config.Field.rename
1492 """
1493 self._name = name
1494 for field in self._fields.values():
1495 field.rename(self)
1496

◆ _save()

lsst.pex.config.config.Config._save ( self,
outfile )
protectedinherited
Save this config to an open stream object.

Parameters
----------
outfile : file-like object
    Destination file object write the config into. Accepts strings not
    bytes.

Definition at line 1394 of file config.py.

1394 def _save(self, outfile):
1395 """Save this config to an open stream object.
1396
1397 Parameters
1398 ----------
1399 outfile : file-like object
1400 Destination file object write the config into. Accepts strings not
1401 bytes.
1402 """
1403 for field in self._fields.values():
1404 field.save(outfile, self)
1405

◆ compare()

lsst.pex.config.config.Config.compare ( self,
other,
shortcut = True,
rtol = 1e-8,
atol = 1e-8,
output = None )
inherited
Compare this configuration to another `~lsst.pex.config.Config` for
equality.

Parameters
----------
other : `lsst.pex.config.Config`
    Other `~lsst.pex.config.Config` object to compare against this
    config.
shortcut : `bool`, optional
    If `True`, return as soon as an inequality is found. Default is
    `True`.
rtol : `float`, optional
    Relative tolerance for floating point comparisons.
atol : `float`, optional
    Absolute tolerance for floating point comparisons.
output : callable, optional
    A callable that takes a string, used (possibly repeatedly) to
    report inequalities.

Returns
-------
isEqual : `bool`
    `True` when the two `lsst.pex.config.Config` instances are equal.
    `False` if there is an inequality.

See Also
--------
lsst.pex.config.compareConfigs

Notes
-----
Unselected targets of `~lsst.pex.config.RegistryField` fields and
unselected choices of `~lsst.pex.config.ConfigChoiceField` fields
are not considered by this method.

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

Definition at line 1618 of file config.py.

1618 def compare(self, other, shortcut=True, rtol=1e-8, atol=1e-8, output=None):
1619 """Compare this configuration to another `~lsst.pex.config.Config` for
1620 equality.
1621
1622 Parameters
1623 ----------
1624 other : `lsst.pex.config.Config`
1625 Other `~lsst.pex.config.Config` object to compare against this
1626 config.
1627 shortcut : `bool`, optional
1628 If `True`, return as soon as an inequality is found. Default is
1629 `True`.
1630 rtol : `float`, optional
1631 Relative tolerance for floating point comparisons.
1632 atol : `float`, optional
1633 Absolute tolerance for floating point comparisons.
1634 output : callable, optional
1635 A callable that takes a string, used (possibly repeatedly) to
1636 report inequalities.
1637
1638 Returns
1639 -------
1640 isEqual : `bool`
1641 `True` when the two `lsst.pex.config.Config` instances are equal.
1642 `False` if there is an inequality.
1643
1644 See Also
1645 --------
1646 lsst.pex.config.compareConfigs
1647
1648 Notes
1649 -----
1650 Unselected targets of `~lsst.pex.config.RegistryField` fields and
1651 unselected choices of `~lsst.pex.config.ConfigChoiceField` fields
1652 are not considered by this method.
1653
1654 Floating point comparisons are performed by `numpy.allclose`.
1655 """
1656 name1 = self._name if self._name is not None else "config"
1657 name2 = other._name if other._name is not None else "config"
1658 name = getComparisonName(name1, name2)
1659 return compareConfigs(name, self, other, shortcut=shortcut, rtol=rtol, atol=atol, output=output)
1660

◆ formatHistory()

lsst.pex.config.config.Config.formatHistory ( self,
name,
** kwargs )
inherited
Format a configuration field's history to a human-readable format.

Parameters
----------
name : `str`
    Name of a `~lsst.pex.config.Field` in this config.
**kwargs
    Keyword arguments passed to `lsst.pex.config.history.format`.

Returns
-------
history : `str`
    A string containing the formatted history.

See Also
--------
lsst.pex.config.history.format

Definition at line 1523 of file config.py.

1523 def formatHistory(self, name, **kwargs):
1524 """Format a configuration field's history to a human-readable format.
1525
1526 Parameters
1527 ----------
1528 name : `str`
1529 Name of a `~lsst.pex.config.Field` in this config.
1530 **kwargs
1531 Keyword arguments passed to `lsst.pex.config.history.format`.
1532
1533 Returns
1534 -------
1535 history : `str`
1536 A string containing the formatted history.
1537
1538 See Also
1539 --------
1540 lsst.pex.config.history.format
1541 """
1542 import lsst.pex.config.history as pexHist
1543
1544 return pexHist.format(self, name, **kwargs)
1545

◆ freeze()

lsst.pex.config.config.Config.freeze ( self)
inherited
Make this config, and all subconfigs, read-only.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField, and lsst.pex.config.configChoiceField.ConfigInstanceDict.

Definition at line 1388 of file config.py.

1388 def freeze(self):
1389 """Make this config, and all subconfigs, read-only."""
1390 self._frozen = True
1391 for field in self._fields.values():
1392 field.freeze(self)
1393

◆ items()

lsst.pex.config.config.Config.items ( self)
inherited
Get configurations as ``(field name, field value)`` pairs.

Returns
-------
items : `~collections.abc.ItemsView`
    Iterator of tuples for each configuration. Tuple items are:

    0. Field name.
    1. Field value.

Definition at line 997 of file config.py.

997 def items(self):
998 """Get configurations as ``(field name, field value)`` pairs.
999
1000 Returns
1001 -------
1002 items : `~collections.abc.ItemsView`
1003 Iterator of tuples for each configuration. Tuple items are:
1004
1005 0. Field name.
1006 1. Field value.
1007 """
1008 return self._storage.items()
1009

◆ keys()

lsst.pex.config.config.Config.keys ( self)
inherited
Get field names.

Returns
-------
names : `~collections.abc.KeysView`
    List of `lsst.pex.config.Field` names.

Definition at line 977 of file config.py.

977 def keys(self):
978 """Get field names.
979
980 Returns
981 -------
982 names : `~collections.abc.KeysView`
983 List of `lsst.pex.config.Field` names.
984 """
985 return self._storage.keys()
986

◆ load()

lsst.pex.config.config.Config.load ( self,
filename,
root = "config" )
inherited
Modify this config in place by executing the Python code in a
configuration file.

Parameters
----------
filename : `str`
    Name of the configuration file. A configuration file is Python
    module.
root : `str`, optional
    Name of the variable in file that refers to the config being
    overridden.

    For example, the value of root is ``"config"`` and the file
    contains::

        config.myField = 5

    Then this config's field ``myField`` is set to ``5``.

See Also
--------
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.loadFromString
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.saveToString

Definition at line 1142 of file config.py.

1142 def load(self, filename, root="config"):
1143 """Modify this config in place by executing the Python code in a
1144 configuration file.
1145
1146 Parameters
1147 ----------
1148 filename : `str`
1149 Name of the configuration file. A configuration file is Python
1150 module.
1151 root : `str`, optional
1152 Name of the variable in file that refers to the config being
1153 overridden.
1154
1155 For example, the value of root is ``"config"`` and the file
1156 contains::
1157
1158 config.myField = 5
1159
1160 Then this config's field ``myField`` is set to ``5``.
1161
1162 See Also
1163 --------
1164 lsst.pex.config.Config.loadFromStream
1165 lsst.pex.config.Config.loadFromString
1166 lsst.pex.config.Config.save
1167 lsst.pex.config.Config.saveToStream
1168 lsst.pex.config.Config.saveToString
1169 """
1170 with open(filename) as f:
1171 code = compile(f.read(), filename=filename, mode="exec")
1172 self.loadFromString(code, root=root, filename=filename)
1173

◆ loadFromStream()

lsst.pex.config.config.Config.loadFromStream ( self,
stream,
root = "config",
filename = None,
extraLocals = None )
inherited
Modify this Config in place by executing the Python code in the
provided stream.

Parameters
----------
stream : file-like object, `str`, `bytes`, or `~types.CodeType`
    Stream containing configuration override code.  If this is a
    code object, it should be compiled with ``mode="exec"``.
root : `str`, optional
    Name of the variable in file that refers to the config being
    overridden.

    For example, the value of root is ``"config"`` and the file
    contains::

        config.myField = 5

    Then this config's field ``myField`` is set to ``5``.
filename : `str`, optional
    Name of the configuration file, or `None` if unknown or contained
    in the stream. Used for error reporting.
extraLocals : `dict` of `str` to `object`, optional
    Any extra variables to include in local scope when loading.

Notes
-----
For backwards compatibility reasons, this method accepts strings, bytes
and code objects as well as file-like objects.  New code should use
`loadFromString` instead for most of these types.

See Also
--------
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromString
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.saveToString

Definition at line 1174 of file config.py.

1174 def loadFromStream(self, stream, root="config", filename=None, extraLocals=None):
1175 """Modify this Config in place by executing the Python code in the
1176 provided stream.
1177
1178 Parameters
1179 ----------
1180 stream : file-like object, `str`, `bytes`, or `~types.CodeType`
1181 Stream containing configuration override code. If this is a
1182 code object, it should be compiled with ``mode="exec"``.
1183 root : `str`, optional
1184 Name of the variable in file that refers to the config being
1185 overridden.
1186
1187 For example, the value of root is ``"config"`` and the file
1188 contains::
1189
1190 config.myField = 5
1191
1192 Then this config's field ``myField`` is set to ``5``.
1193 filename : `str`, optional
1194 Name of the configuration file, or `None` if unknown or contained
1195 in the stream. Used for error reporting.
1196 extraLocals : `dict` of `str` to `object`, optional
1197 Any extra variables to include in local scope when loading.
1198
1199 Notes
1200 -----
1201 For backwards compatibility reasons, this method accepts strings, bytes
1202 and code objects as well as file-like objects. New code should use
1203 `loadFromString` instead for most of these types.
1204
1205 See Also
1206 --------
1207 lsst.pex.config.Config.load
1208 lsst.pex.config.Config.loadFromString
1209 lsst.pex.config.Config.save
1210 lsst.pex.config.Config.saveToStream
1211 lsst.pex.config.Config.saveToString
1212 """
1213 if hasattr(stream, "read"):
1214 if filename is None:
1215 filename = getattr(stream, "name", "?")
1216 code = compile(stream.read(), filename=filename, mode="exec")
1217 else:
1218 code = stream
1219 self.loadFromString(code, root=root, filename=filename, extraLocals=extraLocals)
1220

◆ loadFromString()

lsst.pex.config.config.Config.loadFromString ( self,
code,
root = "config",
filename = None,
extraLocals = None )
inherited
Modify this Config in place by executing the Python code in the
provided string.

Parameters
----------
code : `str`, `bytes`, or `~types.CodeType`
    Stream containing configuration override code.
root : `str`, optional
    Name of the variable in file that refers to the config being
    overridden.

    For example, the value of root is ``"config"`` and the file
    contains::

        config.myField = 5

    Then this config's field ``myField`` is set to ``5``.
filename : `str`, optional
    Name of the configuration file, or `None` if unknown or contained
    in the stream. Used for error reporting.
extraLocals : `dict` of `str` to `object`, optional
    Any extra variables to include in local scope when loading.

Raises
------
ValueError
    Raised if a key in extraLocals is the same value as the value of
    the root argument.

See Also
--------
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.saveToString

Definition at line 1221 of file config.py.

1221 def loadFromString(self, code, root="config", filename=None, extraLocals=None):
1222 """Modify this Config in place by executing the Python code in the
1223 provided string.
1224
1225 Parameters
1226 ----------
1227 code : `str`, `bytes`, or `~types.CodeType`
1228 Stream containing configuration override code.
1229 root : `str`, optional
1230 Name of the variable in file that refers to the config being
1231 overridden.
1232
1233 For example, the value of root is ``"config"`` and the file
1234 contains::
1235
1236 config.myField = 5
1237
1238 Then this config's field ``myField`` is set to ``5``.
1239 filename : `str`, optional
1240 Name of the configuration file, or `None` if unknown or contained
1241 in the stream. Used for error reporting.
1242 extraLocals : `dict` of `str` to `object`, optional
1243 Any extra variables to include in local scope when loading.
1244
1245 Raises
1246 ------
1247 ValueError
1248 Raised if a key in extraLocals is the same value as the value of
1249 the root argument.
1250
1251 See Also
1252 --------
1253 lsst.pex.config.Config.load
1254 lsst.pex.config.Config.loadFromStream
1255 lsst.pex.config.Config.save
1256 lsst.pex.config.Config.saveToStream
1257 lsst.pex.config.Config.saveToString
1258 """
1259 if filename is None:
1260 # try to determine the file name; a compiled string
1261 # has attribute "co_filename",
1262 filename = getattr(code, "co_filename", "?")
1263 with RecordingImporter() as importer:
1264 globals = {"__file__": filename}
1265 local = {root: self}
1266 if extraLocals is not None:
1267 # verify the value of root was not passed as extra local args
1268 if root in extraLocals:
1269 raise ValueError(
1270 f"{root} is reserved and cannot be used as a variable name in extraLocals"
1271 )
1272 local.update(extraLocals)
1273 exec(code, globals, local)
1274
1275 self._imports.update(importer.getModules())
1276

◆ names()

lsst.pex.config.config.Config.names ( self)
inherited
Get all the field names in the config, recursively.

Returns
-------
names : `list` of `str`
    Field names.

Definition at line 1444 of file config.py.

1444 def names(self):
1445 """Get all the field names in the config, recursively.
1446
1447 Returns
1448 -------
1449 names : `list` of `str`
1450 Field names.
1451 """
1452 #
1453 # Rather than sort out the recursion all over again use the
1454 # pre-existing saveToStream()
1455 #
1456 with io.StringIO() as strFd:
1457 self.saveToStream(strFd, "config")
1458 contents = strFd.getvalue()
1459 strFd.close()
1460 #
1461 # Pull the names out of the dumped config
1462 #
1463 keys = []
1464 for line in contents.split("\n"):
1465 if re.search(r"^((assert|import)\s+|\s*$|#)", line):
1466 continue
1467
1468 mat = re.search(r"^(?:config\.)?([^=]+)\s*=\s*.*", line)
1469 if mat:
1470 keys.append(mat.group(1))
1471
1472 return keys
1473

◆ save()

lsst.pex.config.config.Config.save ( self,
filename,
root = "config" )
inherited
Save a Python script to the named file, which, when loaded,
reproduces this config.

Parameters
----------
filename : `str`
    Desination filename of this configuration.
root : `str`, optional
    Name to use for the root config variable. The same value must be
    used when loading (see `lsst.pex.config.Config.load`).

See Also
--------
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.saveToString
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.loadFromString

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField.

Definition at line 1277 of file config.py.

1277 def save(self, filename, root="config"):
1278 """Save a Python script to the named file, which, when loaded,
1279 reproduces this config.
1280
1281 Parameters
1282 ----------
1283 filename : `str`
1284 Desination filename of this configuration.
1285 root : `str`, optional
1286 Name to use for the root config variable. The same value must be
1287 used when loading (see `lsst.pex.config.Config.load`).
1288
1289 See Also
1290 --------
1291 lsst.pex.config.Config.saveToStream
1292 lsst.pex.config.Config.saveToString
1293 lsst.pex.config.Config.load
1294 lsst.pex.config.Config.loadFromStream
1295 lsst.pex.config.Config.loadFromString
1296 """
1297 d = os.path.dirname(filename)
1298 with tempfile.NamedTemporaryFile(mode="w", delete=False, dir=d) as outfile:
1299 self.saveToStream(outfile, root)
1300 # tempfile is hardcoded to create files with mode '0600'
1301 # for an explantion of these antics see:
1302 # https://stackoverflow.com/questions/10291131/how-to-use-os-umask-in-python
1303 umask = os.umask(0o077)
1304 os.umask(umask)
1305 os.chmod(outfile.name, (~umask & 0o666))
1306 # chmod before the move so we get quasi-atomic behavior if the
1307 # source and dest. are on the same filesystem.
1308 # os.rename may not work across filesystems
1309 shutil.move(outfile.name, filename)
1310

◆ saveToStream()

lsst.pex.config.config.Config.saveToStream ( self,
outfile,
root = "config",
skipImports = False )
inherited
Save a configuration file to a stream, which, when loaded,
reproduces this config.

Parameters
----------
outfile : file-like object
    Destination file object write the config into. Accepts strings not
    bytes.
root : `str`, optional
    Name to use for the root config variable. The same value must be
    used when loading (see `lsst.pex.config.Config.load`).
skipImports : `bool`, optional
    If `True` then do not include ``import`` statements in output,
    this is to support human-oriented output from ``pipetask`` where
    additional clutter is not useful.

See Also
--------
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToString
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.loadFromString

Definition at line 1339 of file config.py.

1339 def saveToStream(self, outfile, root="config", skipImports=False):
1340 """Save a configuration file to a stream, which, when loaded,
1341 reproduces this config.
1342
1343 Parameters
1344 ----------
1345 outfile : file-like object
1346 Destination file object write the config into. Accepts strings not
1347 bytes.
1348 root : `str`, optional
1349 Name to use for the root config variable. The same value must be
1350 used when loading (see `lsst.pex.config.Config.load`).
1351 skipImports : `bool`, optional
1352 If `True` then do not include ``import`` statements in output,
1353 this is to support human-oriented output from ``pipetask`` where
1354 additional clutter is not useful.
1355
1356 See Also
1357 --------
1358 lsst.pex.config.Config.save
1359 lsst.pex.config.Config.saveToString
1360 lsst.pex.config.Config.load
1361 lsst.pex.config.Config.loadFromStream
1362 lsst.pex.config.Config.loadFromString
1363 """
1364 tmp = self._name
1365 self._rename(root)
1366 try:
1367 if not skipImports:
1368 self._collectImports()
1369 # Remove self from the set, as it is handled explicitly below
1370 self._imports.remove(self.__module__)
1371 configType = type(self)
1372 typeString = _typeStr(configType)
1373 outfile.write(f"import {configType.__module__}\n")
1374 # We are required to write this on a single line because
1375 # of later regex matching, rather than adopting black style
1376 # formatting.
1377 outfile.write(
1378 f'assert type({root}) is {typeString}, f"config is of type '
1379 f'{{type({root}).__module__}}.{{type({root}).__name__}} instead of {typeString}"\n\n'
1380 )
1381 for imp in sorted(self._imports):
1382 if imp in sys.modules and sys.modules[imp] is not None:
1383 outfile.write(f"import {imp}\n")
1384 self._save(outfile)
1385 finally:
1386 self._rename(tmp)
1387

◆ saveToString()

lsst.pex.config.config.Config.saveToString ( self,
skipImports = False )
inherited
Return the Python script form of this configuration as an executable
string.

Parameters
----------
skipImports : `bool`, optional
    If `True` then do not include ``import`` statements in output,
    this is to support human-oriented output from ``pipetask`` where
    additional clutter is not useful.

Returns
-------
code : `str`
    A code string readable by `loadFromString`.

See Also
--------
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.loadFromString

Definition at line 1311 of file config.py.

1311 def saveToString(self, skipImports=False):
1312 """Return the Python script form of this configuration as an executable
1313 string.
1314
1315 Parameters
1316 ----------
1317 skipImports : `bool`, optional
1318 If `True` then do not include ``import`` statements in output,
1319 this is to support human-oriented output from ``pipetask`` where
1320 additional clutter is not useful.
1321
1322 Returns
1323 -------
1324 code : `str`
1325 A code string readable by `loadFromString`.
1326
1327 See Also
1328 --------
1329 lsst.pex.config.Config.save
1330 lsst.pex.config.Config.saveToStream
1331 lsst.pex.config.Config.load
1332 lsst.pex.config.Config.loadFromStream
1333 lsst.pex.config.Config.loadFromString
1334 """
1335 buffer = io.StringIO()
1336 self.saveToStream(buffer, skipImports=skipImports)
1337 return buffer.getvalue()
1338

◆ setDefaults()

lsst.pex.config.config.Config.setDefaults ( self)
inherited
Subclass hook for computing defaults.

Notes
-----
Derived `~lsst.pex.config.Config` classes that must compute defaults
rather than using the `~lsst.pex.config.Field` instances's defaults
should do so here. To correctly use inherited defaults,
implementations of ``setDefaults`` must call their base class's
``setDefaults``.

Reimplemented in lsst.pipe.tasks.background.MaskObjectsConfig, lsst.pipe.tasks.dataFrameActions._actions.NanoJansky, lsst.ip.diffim.dipoleMeasurement.DipoleMeasurementConfig, lsst.ip.diffim.subtractImages.AlardLuptonSubtractBaseConfig, lsst.ip.isr.ampOffset.AmpOffsetConfig, lsst.meas.algorithms.computeExPsf.ComputeExPsfConfig, lsst.meas.algorithms.measureApCorr.MeasureApCorrConfig, lsst.meas.algorithms.noise_covariance.ComputeNoiseCorrelationConfig, lsst.meas.algorithms.normalizedCalibrationFlux.NormalizedCalibrationFluxConfig, lsst.meas.algorithms.scaleVariance.ScaleVarianceConfig, lsst.meas.base.forcedMeasurement.ForcedMeasurementConfig, lsst.meas.modelfit.cmodel.cmodelContinued.CModelForcedConfig, lsst.meas.modelfit.cmodel.cmodelContinued.CModelSingleFrameConfig, lsst.meas.modelfit.psf.psfContinued.GeneralShapeletPsfApproxForcedConfig, and lsst.meas.modelfit.psf.psfContinued.GeneralShapeletPsfApproxSingleFrameConfig.

Definition at line 1071 of file config.py.

1071 def setDefaults(self):
1072 """Subclass hook for computing defaults.
1073
1074 Notes
1075 -----
1076 Derived `~lsst.pex.config.Config` classes that must compute defaults
1077 rather than using the `~lsst.pex.config.Field` instances's defaults
1078 should do so here. To correctly use inherited defaults,
1079 implementations of ``setDefaults`` must call their base class's
1080 ``setDefaults``.
1081 """
1082 pass
1083

◆ toDict()

lsst.pex.config.config.Config.toDict ( self)
inherited
Make a dictionary of field names and their values.

Returns
-------
dict_ : `dict`
    Dictionary with keys that are `~lsst.pex.config.Field` names.
    Values are `~lsst.pex.config.Field` values.

See Also
--------
lsst.pex.config.Field.toDict

Notes
-----
This method uses the `~lsst.pex.config.Field.toDict` method of
individual fields. Subclasses of `~lsst.pex.config.Field` may need to
implement a ``toDict`` method for *this* method to work.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField.

Definition at line 1420 of file config.py.

1420 def toDict(self):
1421 """Make a dictionary of field names and their values.
1422
1423 Returns
1424 -------
1425 dict_ : `dict`
1426 Dictionary with keys that are `~lsst.pex.config.Field` names.
1427 Values are `~lsst.pex.config.Field` values.
1428
1429 See Also
1430 --------
1431 lsst.pex.config.Field.toDict
1432
1433 Notes
1434 -----
1435 This method uses the `~lsst.pex.config.Field.toDict` method of
1436 individual fields. Subclasses of `~lsst.pex.config.Field` may need to
1437 implement a ``toDict`` method for *this* method to work.
1438 """
1439 dict_ = {}
1440 for name, field in self._fields.items():
1441 dict_[name] = field.toDict(self)
1442 return dict_
1443

◆ update()

lsst.pex.config.config.Config.update ( self,
** kw )
inherited
Update values of fields specified by the keyword arguments.

Parameters
----------
**kw
    Keywords are configuration field names. Values are configuration
    field values.

Notes
-----
The ``__at`` and ``__label`` keyword arguments are special internal
keywords. They are used to strip out any internal steps from the
history tracebacks of the config. Do not modify these keywords to
subvert a `~lsst.pex.config.Config` instance's history.

Examples
--------
This is a config with three fields:

>>> from lsst.pex.config import Config, Field
>>> class DemoConfig(Config):
...     fieldA = Field(doc="Field A", dtype=int, default=42)
...     fieldB = Field(doc="Field B", dtype=bool, default=True)
...     fieldC = Field(doc="Field C", dtype=str, default="Hello world")
>>> config = DemoConfig()

These are the default values of each field:

>>> for name, value in config.iteritems():
...     print(f"{name}: {value}")
fieldA: 42
fieldB: True
fieldC: 'Hello world'

Using this method to update ``fieldA`` and ``fieldC``:

>>> config.update(fieldA=13, fieldC="Updated!")

Now the values of each field are:

>>> for name, value in config.iteritems():
...     print(f"{name}: {value}")
fieldA: 13
fieldB: True
fieldC: 'Updated!'

Definition at line 1084 of file config.py.

1084 def update(self, **kw):
1085 """Update values of fields specified by the keyword arguments.
1086
1087 Parameters
1088 ----------
1089 **kw
1090 Keywords are configuration field names. Values are configuration
1091 field values.
1092
1093 Notes
1094 -----
1095 The ``__at`` and ``__label`` keyword arguments are special internal
1096 keywords. They are used to strip out any internal steps from the
1097 history tracebacks of the config. Do not modify these keywords to
1098 subvert a `~lsst.pex.config.Config` instance's history.
1099
1100 Examples
1101 --------
1102 This is a config with three fields:
1103
1104 >>> from lsst.pex.config import Config, Field
1105 >>> class DemoConfig(Config):
1106 ... fieldA = Field(doc="Field A", dtype=int, default=42)
1107 ... fieldB = Field(doc="Field B", dtype=bool, default=True)
1108 ... fieldC = Field(doc="Field C", dtype=str, default="Hello world")
1109 >>> config = DemoConfig()
1110
1111 These are the default values of each field:
1112
1113 >>> for name, value in config.iteritems():
1114 ... print(f"{name}: {value}")
1115 fieldA: 42
1116 fieldB: True
1117 fieldC: 'Hello world'
1118
1119 Using this method to update ``fieldA`` and ``fieldC``:
1120
1121 >>> config.update(fieldA=13, fieldC="Updated!")
1122
1123 Now the values of each field are:
1124
1125 >>> for name, value in config.iteritems():
1126 ... print(f"{name}: {value}")
1127 fieldA: 13
1128 fieldB: True
1129 fieldC: 'Updated!'
1130 """
1131 at = kw.pop("__at", getCallStack())
1132 label = kw.pop("__label", "update")
1133
1134 for name, value in kw.items():
1135 try:
1136 field = self._fields[name]
1137 field.__set__(self, value, at=at, label=label)
1138 except KeyError as e:
1139 e.add_note(f"No field of name {name} exists in config type {_typeStr(self)}")
1140 raise
1141

◆ validate()

lsst.pex.config.config.Config.validate ( self)
inherited
Validate the Config, raising an exception if invalid.

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

Notes
-----
The base class implementation performs type checks on all fields by
calling their `~lsst.pex.config.Field.validate` methods.

Complex single-field validation can be defined by deriving new Field
types. For convenience, some derived `lsst.pex.config.Field`-types
(`~lsst.pex.config.ConfigField` and
`~lsst.pex.config.ConfigChoiceField`) are defined in
``lsst.pex.config`` that handle recursing into subconfigs.

Inter-field relationships should only be checked in derived
`~lsst.pex.config.Config` classes after calling this method, and base
validation is complete.

Reimplemented in lsst.fgcmcal.sedterms.Sedterm, lsst.pex.config.configChoiceField.ConfigChoiceField, lsst.pex.config.configurableActions.tests.ActionTest1, lsst.pex.config.configurableActions.tests.ActionTest2, lsst.pex.config.configurableActions.tests.ActionTest3, lsst.pex.config.configurableActions.tests.TestDivideAction, lsst.pipe.tasks.background.MaskObjectsConfig, lsst.pipe.tasks.measurementDriver.MeasurementDriverBaseConfig, lsst.afw.geom.transformConfig.RadialTransformConfig, lsst.meas.algorithms.gaussianPsfFactory.GaussianPsfFactory, lsst.meas.algorithms.measureApCorr.MeasureApCorrConfig, lsst.meas.algorithms.treecorrUtils.TreecorrConfig, lsst.meas.base.baseMeasurement.BaseMeasurementConfig, and lsst.meas.base.compensatedGaussian._compensatedTophat.SingleFrameCompensatedTophatFluxConfig.

Definition at line 1497 of file config.py.

1497 def validate(self):
1498 """Validate the Config, raising an exception if invalid.
1499
1500 Raises
1501 ------
1502 lsst.pex.config.FieldValidationError
1503 Raised if verification fails.
1504
1505 Notes
1506 -----
1507 The base class implementation performs type checks on all fields by
1508 calling their `~lsst.pex.config.Field.validate` methods.
1509
1510 Complex single-field validation can be defined by deriving new Field
1511 types. For convenience, some derived `lsst.pex.config.Field`-types
1512 (`~lsst.pex.config.ConfigField` and
1513 `~lsst.pex.config.ConfigChoiceField`) are defined in
1514 ``lsst.pex.config`` that handle recursing into subconfigs.
1515
1516 Inter-field relationships should only be checked in derived
1517 `~lsst.pex.config.Config` classes after calling this method, and base
1518 validation is complete.
1519 """
1520 for field in self._fields.values():
1521 field.validate(self)
1522

◆ values()

lsst.pex.config.config.Config.values ( self)
inherited
Get field values.

Returns
-------
values : `~collections.abc.ValuesView`
    Iterator of field values.

Definition at line 987 of file config.py.

987 def values(self):
988 """Get field values.
989
990 Returns
991 -------
992 values : `~collections.abc.ValuesView`
993 Iterator of field values.
994 """
995 return self._storage.values()
996

Member Data Documentation

◆ _fields

dict lsst.pex.config.config.ConfigMeta._fields = {}
protectedinherited

Definition at line 228 of file config.py.

◆ _frozen

bool lsst.pex.config.config.Config._frozen = True
protectedinherited

Definition at line 1390 of file config.py.

◆ _history

dict lsst.pex.config.config.Config._history [str, list[Any]]
staticprotectedinherited

Definition at line 970 of file config.py.

◆ _imports

lsst.pex.config.config.Config._imports [Any]
staticprotectedinherited

Definition at line 971 of file config.py.

◆ _name

lsst.pex.config.config.Config._name = name
protectedinherited

Definition at line 1493 of file config.py.

◆ _source

lsst.pex.config.config.ConfigMeta._source = getStackFrame()
protectedinherited

Definition at line 229 of file config.py.

◆ _storage

dict lsst.pex.config.config.Config._storage [str, Any]
staticprotectedinherited

Definition at line 968 of file config.py.

Property Documentation

◆ history

lsst.pex.config.config.Config.history = property(lambda x: x._history)
staticinherited

Definition at line 1546 of file config.py.


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