Skip to content

Commit

Permalink
Update docstrings (#425)
Browse files Browse the repository at this point in the history
* Add test of Likelihood.get_parameters()
* Ignore files generated by building the tutorial
* Simplify example; remove needless dictionaries
* Cleanup of docstrings
  • Loading branch information
marcpaterno authored Jun 11, 2024
1 parent ec5008f commit a0ee415
Show file tree
Hide file tree
Showing 11 changed files with 141 additions and 86 deletions.
47 changes: 21 additions & 26 deletions examples/des_y1_3x2pt/des_y1_3x2pt_PT.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,6 @@ def build_likelihood(_) -> tuple[Likelihood, ModelingTools]:
# Load sacc file
sacc_data = sacc.Sacc.load_fits(saccfile)

# Define sources
sources: dict[str, wl.WeakLensing | nc.NumberCounts] = {}

# Define the intrinsic alignment systematic. This will be added to the
# lensing sources later
ia_systematic = wl.TattAlignmentSystematic()
Expand All @@ -97,14 +94,12 @@ def build_likelihood(_) -> tuple[Likelihood, ModelingTools]:

# Create the weak lensing source, specifying the name of the tracer in the
# sacc file and a list of systematics
sources["src0"] = wl.WeakLensing(
sacc_tracer="src0", systematics=[src_pzshift, ia_systematic]
)
src0 = wl.WeakLensing(sacc_tracer="src0", systematics=[src_pzshift, ia_systematic])

lens_pzshift = nc.PhotoZShift(sacc_tracer="lens0")
magnification = nc.ConstantMagnificationBiasSystematic(sacc_tracer="lens0")
nl_bias = nc.PTNonLinearBiasSystematic(sacc_tracer="lens0")
sources["lens0"] = nc.NumberCounts(
lens0 = nc.NumberCounts(
sacc_tracer="lens0",
has_rsd=True,
systematics=[lens_pzshift, magnification, nl_bias],
Expand All @@ -114,27 +109,22 @@ def build_likelihood(_) -> tuple[Likelihood, ModelingTools]:
# The only place the dict 'stats' gets used, other than setting values in
# it, is to call 'values' on it. Thus we don't need a dict, we need a list
# of the values. The keys assigned to the dict are never used.
stats = {}
for stat, sacc_stat in [
("xip", "galaxy_shear_xi_plus"),
("xim", "galaxy_shear_xi_minus"),
]:
# Define two-point statistics, given two sources (from above) and
# the type of statistic.
stats[f"{stat}_src0_src0"] = TwoPoint(
source0=sources["src0"],
source1=sources["src0"],
sacc_data_type=sacc_stat,
)
stats["gammat_lens0_src0"] = TwoPoint(
source0=sources["lens0"],
source1=sources["src0"],
xip_src0_src0 = TwoPoint(
source0=src0, source1=src0, sacc_data_type="galaxy_shear_xi_plus"
)
xim_src0_src0 = TwoPoint(
source0=src0, source1=src0, sacc_data_type="galaxy_shear_xi_minus"
)

gammat_lens0_src0 = TwoPoint(
source0=lens0,
source1=src0,
sacc_data_type="galaxy_shearDensity_xi_t",
)

stats["wtheta_lens0_lens0"] = TwoPoint(
source0=sources["lens0"],
source1=sources["lens0"],
wtheta_lens0_lens0 = TwoPoint(
source0=lens0,
source1=lens0,
sacc_data_type="galaxy_density_xi",
)

Expand All @@ -148,7 +138,12 @@ def build_likelihood(_) -> tuple[Likelihood, ModelingTools]:
)

modeling_tools = ModelingTools(pt_calculator=pt_calculator)
likelihood = ConstGaussian(statistics=list(stats.values()))
# Note that the ordering of the statistics is relevant, because the data
# vector, theory vector, and covariance matrix will be organized to
# follow the order used here.
likelihood = ConstGaussian(
statistics=[xip_src0_src0, xim_src0_src0, gammat_lens0_src0, wtheta_lens0_lens0]
)

# Read the two-point data from the sacc file
likelihood.read(sacc_data)
Expand Down
6 changes: 1 addition & 5 deletions firecrown/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
"""
A package for creation of DESC likelihoods.
"""A package for the creation of DESC likelihoods.
"""

from firecrown.version import __version__
Expand Down
48 changes: 35 additions & 13 deletions firecrown/connector/cobaya/ccl.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ class CCLConnector(Theory):
input_style: str | None = None

def initialize(self):
"""Required by Cobaya.
"""Initialize a CCLConnector object.
Required by Cobaya.
This is used instead of __init__, to provide default initialization.
Cobaya does not allow us to override __init__.
Expand All @@ -34,48 +36,60 @@ def initialize(self):
self.Pk_kmax = 1.0

def initialize_with_params(self):
"""Required by Cobaya.
"""Complete the initialization of a CCLConnector object.
Required by Cobaya.
Cobaya calls this after initialize(), so that work can be done after
that point. This version has nothing to do.
"""

def initialize_with_provider(self, provider):
"""Required by Cobaya.
"""Set the object's provider.
Required by Cobaya.
Sets instance's provided to the given provider.
:param provider: A Cobaya provider.
"""
self.provider = provider

def get_can_provide_params(self):
"""Required by Cobaya.
"""Return the list of params provided.
Required by Cobaya.
Returns an empty list.
"""
return []

def get_can_support_params(self) -> list[str]:
"""Required by Cobaya.
"""Return a list containing the names of the mapping's parameter names.
Return a list containing the names of the mapping's parameter names.
Required by Cobaya.
:return: The list of parameter names.
"""
return self.map.get_params_names()

def get_allow_agnostic(self):
"""Required by Cobaya.
"""Is it allowed to pass all unassigned input parameters to this component.
Return False.
Required by Cobaya.
This implementation always returns False.
:return: False
"""
return False

def get_requirements(
self,
) -> dict[str, None | dict[str, npt.NDArray[np.float64]] | dict[str, object]]:
"""Required by Cobaya.
"""Returns a dictionary.
Returns a dictionary with keys:
The dictionary contains the following keys:
omk, Pk_grid, comoving_radial_distance, Hubble,
and with values reflecting the current status of the object.
Required by Cobaya.
:return: a dictionary
"""
pyccl_calculator_requires = {
"omk": None,
Expand All @@ -95,7 +109,12 @@ def must_provide(self, **requirements):
def calculate(
self, state: dict[str, float], want_derived=True, **params_values
) -> None:
"""Calculate the current cosmology, and set state["pyccl"] to the result."""
"""Calculate the current cosmology, and set state["pyccl"] to the result.
:param state: The state dictionary to update.
:param want_derived: Whether to calculate derived parameters or not.
:param params_values: The values of the parameters to use.
"""
self.map.set_params_from_camb(**params_values)

pyccl_params_values = self.map.asdict()
Expand Down Expand Up @@ -125,5 +144,8 @@ def calculate(
state["pyccl"] = cosmo

def get_pyccl(self) -> pyccl.Cosmology:
"""Return the current cosmology."""
"""Return the current cosmology.
:return: The current cosmology
"""
return self.current_state["pyccl"]
6 changes: 5 additions & 1 deletion firecrown/connector/numcosmo/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
"""Module with classes for the numcosmo connector."""
"""Support of Firecrown likelihood use in numcosmo.
The subpackages and modules in this package depend upon numcosmo, and can not
be used without an installation of numcosmo.
"""
53 changes: 38 additions & 15 deletions firecrown/descriptors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Provides type validation as used in connectors.
"""Type validation as used in connectors.
Validators are created using the constructor for each class.
Access to the data done through the object name, not through any named function.
Expand All @@ -11,7 +11,7 @@
.. code:: python
class SampleValidatedTHing:
class SampleValidatedThing:
x = TypeFloat(1.0, 3.0, allow_none=True)
def __init__(self):
Expand All @@ -37,6 +37,12 @@ def __init__(
maxvalue: None | float = None,
allow_none: bool = False,
) -> None:
"""Initialize the TypeFloat object.
:param minvalue: The minimum value allowed for the attribute.
:param maxvalue: The maximum value allowed for the attribute.
:param allow_none: Whether the attribute can be None.
"""
self.minvalue = minvalue
self.maxvalue = maxvalue
self.allow_none = allow_none
Expand All @@ -63,20 +69,29 @@ def _is_constrained(self) -> bool:
return not ((self.minvalue is None) and (self.maxvalue is None))

def __set_name__(self, _, name: str) -> None:
"""Create the name of the private instance variable that will hold the value."""
"""Create the name of the private instance variable that will hold the value.
:param name: The name of the private instance variable to be created.
"""
self.private_name = "_" + name # pylint: disable-msg=W0201

def __get__(self, obj, objtype=None) -> float:
"""Accessor method, which reads controlled value.
This is invoked whenever the validated variable is read.
:param obj: The object that contains the validated variable.
:param objtype: The type of the object that contains the validated variable.
"""
return getattr(obj, self.private_name)

def __set__(self, obj, value: None | float) -> None:
"""Setter for the validated variable.
This function invokes the `validate` method of the derived class.
:param obj: The object that contains the validated variable.
:param value: The new value of the validated variable.
"""
self.validate(value)
setattr(obj, self.private_name, value)
Expand All @@ -85,16 +100,8 @@ def __set__(self, obj, value: None | float) -> None:
class TypeString:
"""String attribute descriptor.
TypeString provides several different means of validation of the controlled
string attribute, all of which are optional.
`minsize` provides a required minimum length for the string.
`maxsize` provides a required maximum length for the string
`predicate` allows specification of a function that must return true
when a string is provided to allow use of that string.
:classs:`TypeString` provides several different means of validation of the
controlled string attribute, all of which are optional.
"""

def __init__(
Expand All @@ -103,7 +110,12 @@ def __init__(
maxsize: None | int = None,
predicate: None | Callable[[str], bool] = None,
) -> None:
"""Initialize the TypeString object."""
"""Initialize the TypeString object.
:param minsize: The minimum length allowed for the string.
:param maxsize: The maximum length allowed for the string.
:param predicate: A function that returns true if the string is allowed.
"""
self.minsize = minsize
self.maxsize = maxsize
self.predicate = predicate
Expand All @@ -113,6 +125,8 @@ def validate(self, value: None | str) -> None:
Raise an exception if the provided `value` does not meet all of the
required conditions enforced by this validator.
:param value: The value to be validated.
"""
if not isinstance(value, str):
raise TypeError(f"Expected {value!r} to be an str")
Expand All @@ -128,20 +142,29 @@ def validate(self, value: None | str) -> None:
raise ValueError(f"Expected {self.predicate} to be true for {value!r}")

def __set_name__(self, _, name: str) -> None:
"""Create the name of the private instance variable that will hold the value."""
"""Create the name of the private instance variable that will hold the value.
:param name: The name of the private instance variable to be created.
"""
self.private_name = "_" + name # pylint: disable-msg=W0201

def __get__(self, obj, objtype=None) -> str:
"""Accessor method, which reads controlled value.
This is invoked whenever the validated variable is read.
:param obj: The object that contains the validated variable.
:param objtype: The type of the object that contains the validated variable.
"""
return getattr(obj, self.private_name)

def __set__(self, obj, value: None | str) -> None:
"""Setter for the validated variable.
This function invokes the `validate` method of the derived class.
:param obj: The object that contains the validated variable.
:param value: The new value of the validated variable.
"""
self.validate(value)
setattr(obj, self.private_name, value)
9 changes: 5 additions & 4 deletions firecrown/modeling_tools.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Basic module for Cosmology and cosmological tools definitions.
"""Basic Cosmology and cosmological tools definitions.
This module contains the ModelingTools class, which is built around the
:class:`pyccl.Cosmology` class. This is used by likelihoods that need to access
reusable objects, such as perturbation theory or halo model calculators.
:mod:`modeling_tools` contains the :class:`ModelingTools` class, which is
built around the :class:`pyccl.Cosmology` class. This is used by likelihoods
that need to access reusable objects, such as perturbation theory or halo model
calculators.
"""

from __future__ import annotations
Expand Down
11 changes: 9 additions & 2 deletions firecrown/parameters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
"""Classes and functions to support groups of named parameters."""
"""Classes and functions to support groups of named parameters.
These are used in Firecrown in preference to the Python dictionary in order to
provide better type safety.
"""

from __future__ import annotations
from typing import Iterable, Iterator, Sequence
Expand All @@ -18,7 +22,10 @@ def parameter_get_full_name(prefix: None | str, param: str) -> str:
The parameter name can not be empty, even if accompanied by a prefix;
this is enforced in the code.
Ill-formed parameter names result in raising a ValueError.
:param prefix: optional prefix
:param param: name
:return: full name
:raises ValueError: if the parameter name is empty
"""
if len(param) == 0:
raise ValueError("param must not be an empty string")
Expand Down
Loading

0 comments on commit a0ee415

Please sign in to comment.