Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing missing branches #488

Merged
merged 5 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ jobs:
pylint --rcfile examples/pylintrc examples
- name: Running unit tests
shell: bash -l {0}
run: python -m pytest -vv --runslow --cov firecrown --cov-report xml
run: python -m pytest -vv --runslow --cov firecrown --cov-report xml --cov-branch
- name: Running integration tests
shell: bash -l {0}
run: python -m pytest -vv -s --integration tests/integration
Expand Down
3 changes: 1 addition & 2 deletions firecrown/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""A package for the creation of DESC likelihoods.
"""
"""A package for the creation of DESC likelihoods."""

from firecrown.version import __version__

Expand Down
4 changes: 2 additions & 2 deletions firecrown/connector/numcosmo/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def get_hiprim(hi_cosmo: Nc.HICosmo) -> Nc.HIPrimPowerLaw:


def get_amplitude_parameters(
ccl_factory: fac.CCLFactory,
amplitude_parameter: fac.PoweSpecAmplitudeParameter,
p_ml: None | Nc.PowspecML,
hi_cosmo: Nc.HICosmo,
) -> tuple[float | None, float | None]:
Expand All @@ -39,7 +39,7 @@ def get_amplitude_parameters(
sigma8: float | None = None

# mypy verifies that the match statement below is exhaustive
match ccl_factory.amplitude_parameter:
match amplitude_parameter:
case fac.PoweSpecAmplitudeParameter.SIGMA8:
if p_ml is None:
raise ValueError("PowspecML object must be provided when using sigma8.")
Expand Down
18 changes: 11 additions & 7 deletions firecrown/connector/numcosmo/numcosmo.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
from firecrown.modeling_tools import ModelingTools
from firecrown.ccl_factory import (
CCLCalculatorArgs,
CCLFactory,
CCLCreationMode,
PoweSpecAmplitudeParameter,
)
from firecrown.connector.numcosmo import helpers

Expand Down Expand Up @@ -175,7 +175,7 @@ def _set_dist(self, value: Nc.Distance) -> None:
)

def set_params_from_numcosmo(
self, mset: Ncm.MSet, ccl_factory: CCLFactory
self, mset: Ncm.MSet, amplitude_parameter: PoweSpecAmplitudeParameter
) -> None: # pylint: disable-msg=too-many-locals
"""Set the parameters of the contained Mapping object.

Expand Down Expand Up @@ -209,9 +209,9 @@ def set_params_from_numcosmo(
case _:
raise ValueError(f"NumCosmo object {type(hi_cosmo)} not supported.")

A_s, sigma8 = helpers.get_amplitude_parameters(ccl_factory, self.p_ml, hi_cosmo)

assert (A_s is not None) or (sigma8 is not None)
A_s, sigma8 = helpers.get_amplitude_parameters(
amplitude_parameter, self.p_ml, hi_cosmo
)

# pylint: disable=duplicate-code
self.mapping.set_params(
Expand Down Expand Up @@ -570,7 +570,9 @@ def do_prepare( # pylint: disable-msg=arguments-differ
self.likelihood.reset()
self.tools.reset()

self._nc_mapping.set_params_from_numcosmo(mset, self.tools.ccl_factory)
self._nc_mapping.set_params_from_numcosmo(
mset, self.tools.ccl_factory.amplitude_parameter
)
params_map = self._nc_mapping.create_params_map(self.model_list, mset)

self.likelihood.update(params_map)
Expand Down Expand Up @@ -850,7 +852,9 @@ def do_prepare( # pylint: disable-msg=arguments-differ
self.likelihood.reset()
self.tools.reset()

self._nc_mapping.set_params_from_numcosmo(mset, self.tools.ccl_factory)
self._nc_mapping.set_params_from_numcosmo(
mset, self.tools.ccl_factory.amplitude_parameter
)
params_map = self._nc_mapping.create_params_map(self._model_list, mset)

self.likelihood.update(params_map)
Expand Down
3 changes: 1 addition & 2 deletions firecrown/generators/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
"""Classes used to generate metadata for likelihoods and cosmological models.
"""
"""Classes used to generate metadata for likelihoods and cosmological models."""

# flake8: noqa
2 changes: 1 addition & 1 deletion firecrown/generators/inferred_galaxy_zdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ def generate(self) -> npt.NDArray:


def make_measurements(
value: set[Measurement] | list[dict[str, Any]]
value: set[Measurement] | list[dict[str, Any]],
) -> set[Measurement]:
"""Create a Measurement object from a dictionary."""
if isinstance(value, set) and all(
Expand Down
2 changes: 1 addition & 1 deletion firecrown/likelihood/gauss_family/statistic/statistic.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""""Deprecated module with classes related to Statistic."""
"""Deprecated module with classes related to Statistic."""

# flake8: noqa

Expand Down
4 changes: 1 addition & 3 deletions firecrown/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"""Classes used to define and implement the number density functions.

"""
"""Classes used to define and implement the number density functions."""

# flake8: noqa
39 changes: 39 additions & 0 deletions tests/connector/cobaya/test_model_likelihood.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
"""Unit tests for the cobaya Mapping connector."""

import types
import sys
import pytest
import numpy as np
from cobaya.model import get_model, Model
from cobaya.log import LoggedError
from firecrown.connector.cobaya.ccl import CCLConnector
from firecrown.connector.cobaya.likelihood import LikelihoodConnector
from firecrown.likelihood.likelihood import NamedParameters
from firecrown.likelihood.gaussian import ConstGaussian
from firecrown.modeling_tools import ModelingTools
import firecrown.likelihood.statistic as stat
import firecrown.ccl_factory as ccl_factory


def test_cobaya_ccl_initialize():
Expand Down Expand Up @@ -325,3 +331,36 @@ def test_default_factory():
assert isinstance(model_fiducial, Model)
logpost = model_fiducial.logposterior({})
assert np.isfinite(logpost.logpost)


def _factory_as(_: NamedParameters):
return ConstGaussian([stat.TrivialStatistic()]), ModelingTools(
ccl_factory=ccl_factory.CCLFactory(
amplitude_parameter=ccl_factory.PoweSpecAmplitudeParameter.AS
)
)


def _factory_sigma8(_: NamedParameters):
return ConstGaussian([stat.TrivialStatistic()]), ModelingTools(
ccl_factory=ccl_factory.CCLFactory(
amplitude_parameter=ccl_factory.PoweSpecAmplitudeParameter.SIGMA8
)
)


def test_likelihood_connector_from_module():
name = "my_dummy_likelihood_module"
factory_full = f"{name}.factory"
mod = types.ModuleType(factory_full)
mod.factory = _factory_as # type: ignore
sys.modules[name] = mod

lk_connector = LikelihoodConnector(info={"firecrownIni": factory_full})
assert isinstance(lk_connector, LikelihoodConnector)
assert "sigma8" not in lk_connector.get_requirements()

mod.factory = _factory_sigma8 # type: ignore
lk_connector = LikelihoodConnector(info={"firecrownIni": factory_full})
assert isinstance(lk_connector, LikelihoodConnector)
assert "sigma8" in lk_connector.get_requirements()
114 changes: 94 additions & 20 deletions tests/connector/numcosmo/test_numcosmo_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
NumCosmoFactory,
helpers,
)
from firecrown.ccl_factory import CCLFactory, PoweSpecAmplitudeParameter
from firecrown.ccl_factory import PoweSpecAmplitudeParameter

Ncm.cfg_init()

Expand Down Expand Up @@ -167,7 +167,7 @@ def test_numcosmo_mapping_unsupported(map_cosmo_dist: MappingNumCosmo):
mset.set(cosmo)

with pytest.raises(ValueError, match="NumCosmo object .* not supported."):
map_cosmo_dist.set_params_from_numcosmo(mset, CCLFactory())
map_cosmo_dist.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.SIGMA8)


def test_numcosmo_mapping_missing_hiprim(map_cosmo_dist: MappingNumCosmo):
Expand All @@ -181,9 +181,7 @@ def test_numcosmo_mapping_missing_hiprim(map_cosmo_dist: MappingNumCosmo):
with pytest.raises(
ValueError, match="NumCosmo object must include a HIPrim object."
):
map_cosmo_dist.set_params_from_numcosmo(
mset, CCLFactory(amplitude_parameter=PoweSpecAmplitudeParameter.AS)
)
map_cosmo_dist.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.AS)


def test_numcosmo_mapping_invalid_hiprim(map_cosmo_dist: MappingNumCosmo):
Expand All @@ -199,9 +197,7 @@ def test_numcosmo_mapping_invalid_hiprim(map_cosmo_dist: MappingNumCosmo):
with pytest.raises(
ValueError, match="NumCosmo HIPrim object type .* not supported."
):
map_cosmo_dist.set_params_from_numcosmo(
mset, CCLFactory(amplitude_parameter=PoweSpecAmplitudeParameter.AS)
)
map_cosmo_dist.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.AS)


@pytest.mark.parametrize(
Expand All @@ -221,7 +217,7 @@ def test_numcosmo_mapping(numcosmo_cosmo_fixture, request):
mset = Ncm.MSet()
mset.set(cosmo)

map_cosmo.set_params_from_numcosmo(mset, CCLFactory())
map_cosmo.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.SIGMA8)
ccl_args = map_cosmo.calculate_ccl_args(mset)
ccl_cosmo = ccl.CosmologyCalculator(**map_cosmo.mapping.asdict(), **ccl_args)

Expand Down Expand Up @@ -257,8 +253,8 @@ def test_numcosmo_serialize_mapping(numcosmo_cosmo_fixture, request):
mset = Ncm.MSet()
mset.set(cosmo)

map_cosmo.set_params_from_numcosmo(mset, CCLFactory())
map_cosmo_dup.set_params_from_numcosmo(mset, CCLFactory())
map_cosmo.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.SIGMA8)
map_cosmo_dup.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.SIGMA8)

if map_cosmo_dup.p_ml is None:
assert map_cosmo_dup.p_ml is None
Expand Down Expand Up @@ -457,9 +453,7 @@ def test_numcosmo_mapping_sigma8_missing_pk(map_cosmo_dist: MappingNumCosmo):
with pytest.raises(
ValueError, match="PowspecML object must be provided when using sigma8."
):
map_cosmo_dist.set_params_from_numcosmo(
mset, CCLFactory(amplitude_parameter=PoweSpecAmplitudeParameter.SIGMA8)
)
map_cosmo_dist.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.SIGMA8)


@pytest.fixture(name="numcosmo_cosmo")
Expand All @@ -475,8 +469,9 @@ def test_get_amplitude_parameters_sigma8_no_powerspectrum(numcosmo_cosmo):
with pytest.raises(
ValueError, match="PowspecML object must be provided when using sigma8."
):
ccl_factory = CCLFactory(amplitude_parameter=PoweSpecAmplitudeParameter.SIGMA8)
_, _ = helpers.get_amplitude_parameters(ccl_factory, None, numcosmo_cosmo)
_, _ = helpers.get_amplitude_parameters(
PoweSpecAmplitudeParameter.SIGMA8, None, numcosmo_cosmo
)


def test_accessors_with_no_powerspectrum():
Expand All @@ -491,26 +486,105 @@ def test_accessors_with_no_powerspectrum():
linear = Nc.PowspecMLTransfer.new(Nc.TransferFuncEH.new())
nonlinear = Nc.PowspecMNLHaloFit.new(linear, 3.0, 1.0e-5)
mapping.p_mnl = nonlinear
assert mapping._p is None
assert mapping._p is None # pylint: disable=protected-access


def test_accessors_with_only_linear_powerspectrum():
linear = Nc.PowspecMLTransfer.new(Nc.TransferFuncEH.new())
mapping = MappingNumCosmo(p_ml=linear)
assert mapping._p is not None
assert mapping._p is not None # pylint: disable=protected-access
mapping.p_ml = linear
assert mapping.p_mnl is None

# Change to a different linear power spectrum
other_linear = Nc.PowspecMLTransfer.new(Nc.TransferFuncBBKS.new())
mapping.p_ml = other_linear
assert mapping._p is not None
assert mapping._p is not None # pylint: disable=protected-access
assert mapping.p_ml == other_linear
assert mapping.p_mnl is None

# Add a non-linear component
nonlinear = Nc.PowspecMNLHaloFit.new(other_linear, 3.0, 1.0e-5)
mapping.p_mnl = nonlinear
assert mapping._p is not None
assert mapping._p is not None # pylint: disable=protected-access
assert mapping.p_ml == other_linear
assert mapping.p_mnl == nonlinear


def test_mapping_ccl_args_bg_only():
"""Test the MappingNumCosmo class with background only."""
mapping = MappingNumCosmo(dist=Nc.Distance.new(6.0))
assert mapping.p_ml is None
assert mapping.p_mnl is None

cosmo = Nc.HICosmoDEXcdm()
cosmo.add_submodel(Nc.HIPrimPowerLaw.new())
cosmo.add_submodel(Nc.HIReionCamb.new())

mset = Ncm.MSet.new_array([cosmo])
mset.prepare_fparam_map()

mapping.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.AS)
ccl_args = mapping.calculate_ccl_args(mset)
assert "background" in ccl_args
assert "pk_linear" not in ccl_args
assert "pk_nonlin" not in ccl_args


def test_mapping_ccl_args_bg_pk_ml():
"""Test the MappingNumCosmo class with background and pk_ml."""
mapping = MappingNumCosmo(
dist=Nc.Distance.new(6.0),
p_ml=Nc.PowspecMLTransfer.new(Nc.TransferFuncEH.new()),
)
assert mapping.p_mnl is None

cosmo = Nc.HICosmoDEXcdm()
cosmo.add_submodel(Nc.HIPrimPowerLaw.new())
cosmo.add_submodel(Nc.HIReionCamb.new())

mset = Ncm.MSet.new_array([cosmo])
mset.prepare_fparam_map()

mapping.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.AS)
ccl_args = mapping.calculate_ccl_args(mset)
assert "background" in ccl_args
assert "pk_linear" in ccl_args
assert "pk_nonlin" not in ccl_args


def test_mapping_ccl_args_bg_pk_ml_pk_mnl():
"""Test the MappingNumCosmo class with background, pk_ml and pk_mnl."""
p_ml = Nc.PowspecMLTransfer.new(Nc.TransferFuncEH.new())
mapping = MappingNumCosmo(
dist=Nc.Distance.new(6.0),
p_ml=p_ml,
p_mnl=Nc.PowspecMNLHaloFit.new(p_ml, 3.0, 1.0e-4),
)
assert mapping.p_ml is not None
assert mapping.p_mnl is not None

cosmo = Nc.HICosmoDEXcdm()
cosmo.add_submodel(Nc.HIPrimPowerLaw.new())
cosmo.add_submodel(Nc.HIReionCamb.new())

mset = Ncm.MSet.new_array([cosmo])
mset.prepare_fparam_map()

mapping.set_params_from_numcosmo(mset, PoweSpecAmplitudeParameter.AS)
ccl_args = mapping.calculate_ccl_args(mset)
assert "background" in ccl_args
assert "pk_linear" in ccl_args
assert "pk_nonlin" in ccl_args


def test_mapping_ccl_args_bg_pk_mnl():
"""Test the MappingNumCosmo class with background, pk_ml and pk_mnl."""
p_ml = Nc.PowspecMLTransfer.new(Nc.TransferFuncEH.new())
with pytest.raises(
AssertionError, match="PowspecML object must be provided when using PowspecMNL"
):
_ = MappingNumCosmo(
dist=Nc.Distance.new(6.0),
p_mnl=Nc.PowspecMNLHaloFit.new(p_ml, 3.0, 1.0e-4),
)
3 changes: 1 addition & 2 deletions tests/likelihood/gauss_family/statistic/test_supernova.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Tests for the Supernova statistic.
"""
"""Tests for the Supernova statistic."""

import pytest

Expand Down
3 changes: 1 addition & 2 deletions tests/likelihood/gauss_family/test_const_gaussian.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Unit testsing for ConstGaussian
"""
"""Unit testsing for ConstGaussian"""

import re

Expand Down
3 changes: 1 addition & 2 deletions tests/likelihood/gauss_family/test_student_t.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Unit testsing for Student-t distribution
"""
"""Unit testsing for Student-t distribution"""

import pytest
import numpy as np
Expand Down
3 changes: 1 addition & 2 deletions tests/likelihood/test_factories.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Tests for the module firecrown.likelihood.factories.
"""
"""Tests for the module firecrown.likelihood.factories."""

import re
from pathlib import Path
Expand Down
Loading
Loading