firecrown.updatable =================== .. py:module:: firecrown.updatable .. autoapi-nested-parse:: Parameters that can be updated, and collections of them. Abstract class :class:`Updatable` is the base class from which any class in Firecrown that supports updating from a :class:`ParamsMap` should inherit. Such classes are expected to change state only in through their implementation of :meth:`_update` (including any other private methods used to implement :meth:`_update`). Other functions should not change the data of :class:`Updatable` objects. :class:`UpdatableCollection` is a subclass of the built-in list. It implements the :class:`Updatable` interface by calling :meth:`update()` on each element it contains. The :meth:`append()` method is overridden to make sure that only objects which are of a type that implements :class:`Updatable` can be appended to the list. Exceptions ---------- .. autoapisummary:: firecrown.updatable.MissingSamplerParameterError Classes ------- .. autoapisummary:: firecrown.updatable.Updatable firecrown.updatable.UpdatableUsageRecord firecrown.updatable.UpdatableProtocol firecrown.updatable.UpdatableCollection firecrown.updatable.DerivedParameter firecrown.updatable.DerivedParameterCollection firecrown.updatable.ParamsMap firecrown.updatable.RequiredParameters firecrown.updatable.InternalParameter firecrown.updatable.SamplerParameter Functions --------- .. autoapisummary:: firecrown.updatable.get_default_params firecrown.updatable.get_default_params_map firecrown.updatable.assert_updatable_interface firecrown.updatable.handle_unused_params firecrown.updatable.parameter_get_full_name firecrown.updatable.register_new_updatable_parameter Package Contents ---------------- .. py:exception:: MissingSamplerParameterError(parameter) Bases: :py:obj:`RuntimeError` .. autoapi-inheritance-diagram:: firecrown.updatable.MissingSamplerParameterError :parts: 1 Error for when a required parameter is missing. Raised when an Updatable fails to be updated because the ParamsMap supplied for the update is missing a parameter that should have been provided by the sampler. .. py:attribute:: parameter .. py:class:: Updatable(parameter_prefix = None) Bases: :py:obj:`abc.ABC` .. autoapi-inheritance-diagram:: firecrown.updatable.Updatable :parts: 1 Abstract class Updatable is the base class for Updatable objects in Firecrown. Any class in Firecrown that supports updating from a ParamsMap should inherit from :class:`Updatable`. Such classes are expected to change state only in through their implementation of _update (including any other private methods used to implement _update). Other functions should not change the data of Updatable objects. .. py:attribute:: parameter_prefix :type: None | str :value: None .. py:method:: __setattr__(key, value) Set the attribute named :attr:`key` to the supplied `value`. There is special handling for two types: :class:`SamplerParameter` and :class:`InternalParameter`. We also keep track of all :class:`Updatable` instance variables added, appending a reference to each to :attr:`self._updatables` as well as storing the attribute directly. :param key: name of the attribute :param value: value for the attribute .. py:method:: set_parameter(key, value) Sets the parameter to the given value. Assure this InternalParameter or SamplerParameter has not already been set, and then set it. :param key: name of the attribute :param value: value for the attribute .. py:method:: set_internal_parameter(key, value) Assure this InternalParameter has not already been set, and then set it. :param key: name of the attribute :param value: value for the attribute .. py:method:: set_sampler_parameter(value) Assure this SamplerParameter has not already been set, and then set it. :param value: value for the attribute .. py:method:: update(params, updated_record = None) Update self by calling to prepare for the next MCMC sample. We first update the values of sampler parameters from the values in `params`. An error will be raised if any of self's sampler parameters can not be found in `params` or if any internal parameters are provided in `params`. We then use the `params` to update each contained :class:`Updatable` or :class:`UpdatableCollection` object. The method :meth:`_update` is called to give subclasses an opportunity to do any other preparation for the next MCMC sample. :param params: new parameter values .. py:method:: is_updated() Determine if the object has been updated. A default-constructed Updatable has not been updated. After `update`, but before `reset`, has been called the object is updated. After `reset` has been called, the object is not currently updated. :return: True if the object is currently updated, and False if not. .. py:method:: reset() Reset the updatable. Clean up self by clearing the _updated status and resetting all internals. We call the abstract method _reset to allow derived classes to clean up any additional internals. Each MCMC framework connector should call this after handling an MCMC sample. .. py:method:: required_parameters() Returns all information about parameters required by this object. This object returned contains the information for all parameters defined in the implementing class, and any additional parameters. :return: a RequiredParameters object containing all relevant parameters .. py:method:: get_params_names() Return the names of the parameters required by this object. The order of the returned names is arbitrary. :return: a list of parameter names .. py:method:: get_derived_parameters() Returns a collection of derived parameters. This occurs once per iteration of the statistical analysis. First call returns the DerivedParameterCollection, further calls return None. :return: a collection of derived parameters, or None .. py:class:: UpdatableUsageRecord Dataclass to record the usage of parameters by an Updatable object. .. py:attribute:: cls :type: str .. py:attribute:: prefix :type: str | None .. py:attribute:: obj_id :type: int .. py:attribute:: sampler_params :type: list[str] .. py:attribute:: internal_params :type: list[str] .. py:attribute:: child_records :type: list[UpdatableUsageRecord] .. py:attribute:: already_updated :type: bool :value: False .. py:property:: is_empty :type: bool Check if the record is empty. Return True if the record has no sampler parameters, internal parameters, or child records. .. py:property:: is_empty_parent :type: bool Check if the record is an empty parent. Return True if the record has no sampler or internal parameters and exactly one child record. .. py:method:: get_log_lines(level = 0, parent = None, print_empty = False) Print the usage record. .. py:class:: UpdatableProtocol Bases: :py:obj:`Protocol` .. autoapi-inheritance-diagram:: firecrown.updatable.UpdatableProtocol :parts: 1 Protocol defining the interface for updatable objects. Both Updatable and UpdatableCollection implement this interface. The @runtime_checkable decorator allows isinstance() checks. .. py:method:: update(params, updated_record = None) Update the object with new parameters. .. py:method:: reset() Reset the object to its initial state. .. py:method:: is_updated() Check if the object has been updated. .. py:method:: required_parameters() Return the required parameters for this object. .. py:method:: get_derived_parameters() Get the derived parameters for this object. .. py:class:: UpdatableCollection(iterable = None) Bases: :py:obj:`collections.UserList`\ [\ :py:obj:`T`\ ], :py:obj:`Generic`\ [\ :py:obj:`T`\ ] .. autoapi-inheritance-diagram:: firecrown.updatable.UpdatableCollection :parts: 1 Class that represents a collection of updatable objects. UpdatableCollection is a list of Updatable objects and is itself supports :meth:`update` and :meth:`reset` (although it does not inherit from :class:`Updatable`). Every item in an UpdatableCollection must itself be :class:`Updatable`. Calling :meth:`update` on the collection results in every item in the collection being updated. .. py:method:: update(params, updated_record = None) Update self by calling update() on each contained item. :param params: new parameter values for each contained item .. py:method:: is_updated() Returns whether this updatable has been updated. Return True if the object is currently updated, and False if not. A default-constructed Updatable has not been updated. After `update`, but before `reset`, has been called the object is updated. After `reset` has been called, the object is not currently updated. .. py:method:: reset() Resets self by calling reset() on each contained item. .. py:method:: required_parameters() Return a RequiredParameters object. The RequiredParameters object is formed by concatenating the RequiredParameters of each contained item. .. py:method:: get_derived_parameters() Get all derived parameters if any. .. py:method:: append(item) Append the given item to self. If the item is not Updatable a TypeError is raised. :param item: new item to be appended to the list .. py:method:: __setitem__(key, value) Set self[key] to value; raise TypeError if Value is not Updatable. .. py:function:: get_default_params(*args) Get a ParamsMap with the default values of all parameters in the updatables. :param args: updatables to get the default parameters from :return: a ParamsMap with the default values of all parameters .. py:function:: get_default_params_map(*args) Get a ParamsMap with the default values of all parameters in the updatables. :param args: updatables to get the default parameters from :return: a ParamsMap with the default values of all parameters .. py:function:: assert_updatable_interface(obj, recursive = True, raise_on_override = False) Asserts that all final methods were not overridden. The methods: - :func:`update` - :func:`reset` - :func:`is_updated` - :func:`required_parameters` - :func:`get_derived_parameters` Are final and should not be overridden. If any of these methods are overridden a TypeError is raised. .. py:class:: DerivedParameter(section, name, val) Represents a derived scalar parameter generated by an Updatable object. This class provide the type that encapsulate a derived scalar quantity (represented by a float) computed by an Updatable object during a statistical analysis. .. py:attribute:: section :type: str .. py:attribute:: name :type: str .. py:attribute:: val :type: float .. py:method:: get_val() Return the value of this parameter. .. py:method:: __eq__(other) Compare two DerivedParameter objects for equality. This implementation raises a NotImplemented exception unless both objects are DerivedParameter objects. Two DerivedParameter objects are equal if they have the same section, name and value. .. py:method:: get_full_name() Constructs the full name using section--name. .. py:class:: DerivedParameterCollection(derived_parameters) Represents a list of DerivedParameter objects. .. py:attribute:: derived_parameters :type: dict[str, DerivedParameter] .. py:method:: __len__() Return the number of parameters contained. .. py:method:: __add__(other) Add two DerivedParameterCollection objects. Return a new DerivedParameterCollection with the lists of DerivedParameter objects. If other is none return self. Otherwise, constructs a new object representing the addition. Note that this function returns a new object that does not share state with either argument to the addition operator. .. py:method:: __eq__(other) Compare two DerivedParameterCollection objects for equality. This implementation raises a NotImplemented exception unless both objects are DerivedParameterCollection objects. Two DerivedParameterCollection objects are equal if they contain the same DerivedParameter objects. .. py:method:: __iter__() Implementation of lazy iteration through the collection. .. py:method:: add_required_parameter(derived_parameter) Adds derived_parameter to the collection. We raises an ValueError if a required parameter with the same name is already present in the collection. .. py:method:: get_derived_list() Implement lazy iteration through the contained parameter names. .. py:class:: ParamsMap(*args, **kwargs) A dict-like object in which all keys are strings and values are floats. The recommended access method is get_from_prefix_param, rather than indexing with square brackets like x[]. .. py:attribute:: params :type: dict[str, float] .. py:attribute:: lower_case :type: bool :value: False .. py:attribute:: used_keys :type: set[str] .. py:method:: __getitem__(key) Return the value for the given key. If the key has not been used, add it to the set of used keys. :param key: key :return: value .. py:method:: __setitem__(key, value) Set the value for the given key. :param key: key :param value: value .. py:method:: __contains__(key) Return True if the key is in the map, False otherwise. :param key: key :return: True if the key is in the map, False otherwise .. py:method:: copy() Return a shallow copy of the ParamsMap. .. py:method:: items() Return an iterator over the items in the dictionary. :return: an iterator over the items in the dictionary .. py:method:: union(other) Return a new ParamsMap that is the union of self and other. If the same key is used in both self and other, the values in both self and other must be equal. :param other: other ParamsMap :return: a new ParamsMap that is the union of self and other .. py:method:: update(d) Update self with the values from d. This will raise an error if any of the keys in d are already in self. :param d: dictionary .. py:method:: use_lower_case_keys(enable) Control whether keys will be translated into lower case. If `enable` is True, such translation will be done. This can help make sure code works with CosmoSIS, because such translation is done inside CosmoSIS itself. :param enable: whether to enable or disable this option .. py:method:: get(key, default = None) Return the value for the given key, or default if the key is not found. :param key: key :param default: default value, used if the key is not found :return: value .. py:method:: get_from_full_name(full_name) Return the parameter identified by the full name. Raises a KeyError if the parameter is not found. .. py:method:: get_from_prefix_param(prefix, param) Return the parameter identified by the optional prefix and parameter name. See parameter_get_full_name for rules on the forming of prefix and name. Raises a KeyError if the parameter is not found. .. py:method:: get_unused_keys() Return the set of keys that have not been used. This is the set of keys that are not in self.used_keys. .. py:method:: keys() Return the set of keys in the map. :return: set of keys .. py:function:: handle_unused_params(params, updated_records, raise_on_unused = False) Check for unused keys in the parameters map. .. py:function:: parameter_get_full_name(prefix, param) Form a full parameter name from the given (optional) prefix and name. Parameter names, as stored in SACC, for example, contain an optional prefix; if a prefix is present, it will be separated from the name by an underscore. Prefixes and names should avoid containing embedded underscores. This is currently not enforced in the code. The parameter name can not be empty, even if accompanied by a prefix; this is enforced in the code. :param prefix: optional prefix :param param: name :return: full name :raises ValueError: if the parameter name is empty .. py:class:: RequiredParameters(params) Represents a sequence of parameter names. This class provides some type safety to distinguish between an arbitrary list of strings, and one intended to be a list of required parameter names. An instance can be created from a list of strings. Instances can be concatenated using `+`, and compared for equality using `==`. To iterate through the names (which are strings), use `get+params_names`, which implements lazy evaluation. .. py:attribute:: params_set :type: set[firecrown.updatable._parameters_types.SamplerParameter] .. py:method:: __len__() Return the number of parameters contained. .. py:method:: __add__(other) Return a new RequiredParameters with the concatenated names. Note that this function returns a new object that does not share state with either argument to the addition operator. .. py:method:: __sub__(other) Return a new RequiredParameters with the names in self but not in other. Note that this function returns a new object that does not share state with either argument to the subtraction operator. .. py:method:: __eq__(other) Compare two RequiredParameters objects for equality. This implementation raises a NotImplemented exception unless both objects are RequireParameters objects. Two RequireParameters objects are equal if their contained names are equal (including appearing in the same order). .. py:method:: get_params_names() Implement lazy iteration through the contained parameter names. .. py:method:: get_default_values() Return a dictionary with the default values of the parameters. .. py:class:: InternalParameter(value) Class to represent an internally defined parameter. .. py:attribute:: value .. py:method:: set_value(value) Set the value of this parameter. :param value: new value .. py:method:: get_value() Return the current value of this parameter. .. py:class:: SamplerParameter(*, default_value, name = None, prefix = None, shared = False) Class to represent a sampler defined parameter. .. py:attribute:: default_value .. py:method:: get_default_value() Get the default value of this parameter. .. py:method:: set_fullname(prefix, name) Set the prefix and name of this parameter. If the parameter is shared (shared=True), the prefix will be ignored and the parameter will have the same name across all instances. :param prefix: new prefix (ignored if shared=True) :param name: the name of the parameter .. py:property:: shared :type: bool Get whether this parameter is shared across instances. .. py:property:: prefix :type: str | None Get the prefix of this parameter. .. py:property:: name :type: str Get the name of this parameter. .. py:property:: fullname :type: str Get the full name of this parameter. .. py:method:: __hash__() Return the hash of the full name of this parameter. .. py:method:: __eq__(other) Return whether this parameter is equal to another. Two SamplerParameter objects are equal if they have the same full name. .. py:function:: register_new_updatable_parameter(value = None, *, default_value, shared = False) Create a new parameter, either a SamplerParameter or an InternalParameter. If `value` is `None`, the result will be a `SamplerParameter`; Firecrown will expect this value to be supplied by the sampling framework. If `value` is a `float` quantity, then Firecrown will expect this parameter to *not* be supplied by the sampling framework, and instead the provided value will be used for every sample. Only `None` or a `float` value is allowed. :param value: the value of the parameter :param default_value: the default value of the parameter to be used if `value` is `None` :param shared: if True, the parameter will not receive a prefix, making it shared across all instances (only applies when value is None) :return: a `SamplerParameter` if `value` is `None`, otherwise an `InternalParameter` :raises TypeError: if `value` is not `None` and not a `float`