Skip to content

Commit

Permalink
Clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
ggalloni committed Sep 10, 2024
1 parent 4700060 commit 501d279
Show file tree
Hide file tree
Showing 10 changed files with 3 additions and 194 deletions.
9 changes: 0 additions & 9 deletions soliket/bandpass/bandpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@
from cobaya.tools import are_different_params_lists

from soliket.constants import T_CMB, h_Planck, k_Boltzmann
from soliket.utils import check_yaml_types

# Converts from cmb units to brightness.
# Numerical factors not included, it needs proper normalization when used.
Expand Down Expand Up @@ -131,14 +130,6 @@ class BandPass(Theory):
enforce_types: bool = True

def initialize(self):
check_yaml_types(self, {
"data_folder": str,
"read_from_sacc": bool,
"top_hat_band": dict,
"external_bandpass": dict,
"params": dict,
})

self.expected_params_bp = ["bandint_shift_LAT_93",
"bandint_shift_LAT_145",
"bandint_shift_LAT_225"]
Expand Down
9 changes: 0 additions & 9 deletions soliket/ccl/ccl.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,6 @@
from cobaya.theory import Provider, Theory
from cobaya.tools import LoggedError

from soliket.utils import check_yaml_types


class CCL(Theory):
"""A theory code wrapper for CCL."""
Expand All @@ -108,13 +106,6 @@ def initialize(self) -> None:
else:
self.ccl = ccl

check_yaml_types(self, {
"kmax": (int, float),
"nonlinear": bool,
"z": (float, List[float], np.ndarray),
"extra_args": dict,
})

self._var_pairs = set()
self._required_results = {}

Expand Down
11 changes: 0 additions & 11 deletions soliket/cosmopower/cosmopower.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@
from cobaya.theories.cosmo import BoltzmannBase
from cobaya.theory import Theory

from soliket.utils import check_yaml_types

try:
import cosmopower as cp
Expand All @@ -114,13 +113,6 @@ class CosmoPower(BoltzmannBase):
enforce_types: bool = True

def initialize(self) -> None:
check_yaml_types(self, {
"network_path": str,
"network_settings": dict,
"stop_at_error": bool,
"renames": Dict[str, str],
"extra_args": dict,
})

super().initialize()

Expand Down Expand Up @@ -312,9 +304,6 @@ class CosmoPowerDerived(Theory):
"""A theory class that can calculate derived parameters from CosmoPower networks."""

def initialize(self) -> None:
check_yaml_types(self, {
"derived_parameters": List[str],
})
super().initialize()

if self.network_settings is None:
Expand Down
19 changes: 0 additions & 19 deletions soliket/cross_correlation/cross_correlation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from typing import Any, ClassVar, Dict, List, Optional, Tuple, Union
import numpy as np

from soliket.utils import check_yaml_types

try:
from numpy import trapezoid
Expand All @@ -33,11 +32,6 @@ class CrossCorrelationLikelihood(GaussianLikelihood):
provider: Provider

def initialize(self):
check_yaml_types(self, {
"datapath": str,
"use_spectra": (str, List[tuple]),
"ncovsims": int,
})

self._get_sacc_data()
self._check_tracers()
Expand Down Expand Up @@ -156,10 +150,6 @@ class GalaxyKappaLikelihood(CrossCorrelationLikelihood):
_allowable_tracers: ClassVar[List[str]] = ['cmb_convergence', 'galaxy_density']
params: dict

def initialize(self):
check_yaml_types(self, {"params": dict})
super().initialize()

def _get_theory(self, **params_values: dict) -> np.ndarray:
ccl, cosmo = self._get_CCL_results()

Expand Down Expand Up @@ -204,15 +194,6 @@ class ShearKappaLikelihood(CrossCorrelationLikelihood):
ia_mode: Optional[str]
params: dict

def initialize(self):
check_yaml_types(self, {
"params": dict,
"z_nuisance_mode": (str, bool),
"m_nuisance_mode": bool,
"ia_mode": str,
})
super().initialize()

def _get_theory(self, **params_values: dict) -> np.ndarray:
ccl, cosmo = self._get_CCL_results()
cl_binned_list: List[np.ndarray] = []
Expand Down
29 changes: 0 additions & 29 deletions soliket/foreground/foreground.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@
from cobaya.theory import Provider, Theory
from cobaya.tools import are_different_params_lists

from soliket.utils import check_yaml_types


class Foreground(Theory):
spectra: dict
Expand All @@ -80,33 +78,6 @@ def initialize(self):
from fgspectra import frequency as fgf
from fgspectra import power as fgp

check_yaml_types(self, {
"spectra": dict,
"foregrounds": dict,
"params": dict,
})

check_yaml_types(
self.spectra,
{
"polarizations": List[str],
"lmin": int,
"lmax": int,
"exp_ch": List[str],
"eff_freqs": List[float]
},
)

check_yaml_types(
self.foregrounds,
{"components": Dict[str, list], "normalisation": dict},
)

check_yaml_types(
self.foregrounds["normalisation"],
{"nu_0": float, "ell_0": int, "T_CMB": float},
)

self.expected_params_fg = ["a_tSZ", "a_kSZ", "a_p", "beta_p",
"a_c", "beta_c", "a_s", "a_gtt", "a_gte", "a_gee",
"a_psee", "a_pste", "xi", "T_d"]
Expand Down
14 changes: 0 additions & 14 deletions soliket/halo_model/halo_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@
# from cobaya.theories.cosmo.boltzmannbase import PowerSpectrumInterpolator
from scipy.interpolate import RectBivariateSpline

from soliket.utils import check_yaml_types


class HaloModel(Theory):
"""Abstract parent class for implementing Halo Models."""
Expand All @@ -57,11 +55,6 @@ class HaloModel(Theory):
provider: Provider

def initialize(self) -> None:
check_yaml_types(self, {
"kmax": (int, float),
"z": (float, List[float], np.ndarray),
"extra_args": dict,
})
self._var_pairs = set()
self._required_results = {}

Expand Down Expand Up @@ -100,13 +93,6 @@ class HaloModel_pyhm(HaloModel):
nM: int

def initialize(self) -> None:
check_yaml_types(self, {
"hmf_name": str,
"hmf_Dv": float,
"Mmin": float,
"Mmax": float,
"nM": int
})
super().initialize()
self.Ms = np.logspace(np.log10(self.Mmin), np.log10(self.Mmax), self.nM)

Expand Down
23 changes: 1 addition & 22 deletions soliket/mflike/mflike.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,14 @@
:width: 400
"""
import os
from typing import Dict, List, Optional, Tuple
from typing import List, Optional, Tuple

import numpy as np
from cobaya.likelihoods.base_classes import InstallableLikelihood
from cobaya.log import LoggedError
from cobaya.theory import Provider

from soliket.gaussian import GaussianData, GaussianLikelihood
from soliket.utils import check_yaml_types


class MFLike(GaussianLikelihood, InstallableLikelihood):
Expand All @@ -51,26 +50,6 @@ class MFLike(GaussianLikelihood, InstallableLikelihood):
provider: Provider

def initialize(self):
check_yaml_types(self, {
"data_folder": str,
"input_file": str,
"cov_Bbl_file": str,
"data": dict,
"defaults": dict,
"lmax_theory": int,
})

check_yaml_types(self.data, {
"experiments": List[str],
"spectra": List[dict],
})

check_yaml_types(self.defaults, {
"polarizations": List[str],
"scales": Dict[str, List[int]],
"symmetrize": bool,
})

# Set default values to data member not initialized via yaml file
self.l_bpws: Optional[np.ndarray] = None
self.spec_meta: Optional[list] = []
Expand Down
16 changes: 0 additions & 16 deletions soliket/mflike/theoryforge_MFLike.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@
from cobaya.theory import Provider, Theory
from cobaya.tools import are_different_params_lists

from soliket.utils import check_yaml_types


class TheoryForge_MFLike(Theory):
# attributes set from .yaml
Expand All @@ -76,20 +74,6 @@ class TheoryForge_MFLike(Theory):
enforce_types: bool = True

def initialize(self):
check_yaml_types(self, {
"data_folder": str,
"exp_ch": List[str],
"eff_freqs": (List[int], List[float]),
"spectra": dict,
"systematics_template": dict,
"params": dict,
})

check_yaml_types(self.spectra, {
"lmin": int,
"lmax": int,
"polarizations": List[str],
})

self.lmin: int = self.spectra["lmin"]
self.lmax: int = self.spectra["lmax"]
Expand Down
49 changes: 1 addition & 48 deletions soliket/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"""

from typing import Optional, Tuple, Dict, Union, get_args, get_origin
from typing import Optional, Tuple, Dict
from importlib import import_module

import numpy as np
Expand Down Expand Up @@ -73,50 +73,3 @@ def get_requirements(self) -> Dict[str, Dict[str, int]]:
"te": self.lmax,
"ee": self.lmax,
"bb": self.lmax, }}


def check_collection_type(value, expected_type, name):
origin_type = get_origin(expected_type)
if origin_type is list:
if isinstance(value, list):
item_type = get_args(expected_type)[0]
for item in value:
check_type(item, item_type, f"{name} item")
return True
elif origin_type is dict:
if isinstance(value, dict):
key_type, val_type = get_args(expected_type)
for key, val in value.items():
check_type(key, key_type, f"{name} key")
check_type(val, val_type, f"{name} value")
return True
return False


def check_type(value, expected_types, name: str) -> None:
if not isinstance(expected_types, tuple):
expected_types = (expected_types,)

if value is None:
return

for expected_type in expected_types:
origin_type = get_origin(expected_type)
if origin_type is None:
if isinstance(value, expected_type):
return
elif check_collection_type(value, expected_type, name):
return

msg = f"{name} must be of type {expected_types}, not {type(value)}"
raise TypeError(msg)


def check_yaml_types(
instance, attributes: Dict[str, Union[type, Tuple[type, ...]]]
) -> None:
for attr_name, expected_types in attributes.items():
value = getattr(instance, attr_name, None)
if value is None and isinstance(instance, dict):
value = instance.get(attr_name, None)
check_type(value, expected_types, attr_name)
18 changes: 1 addition & 17 deletions soliket/xcorr/xcorr.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import sacc
from scipy.interpolate import InterpolatedUnivariateSpline as Spline

from soliket.utils import binner, check_yaml_types
from soliket.utils import binner
from soliket.gaussian import GaussianData, GaussianLikelihood

from .limber import do_limber
Expand Down Expand Up @@ -78,22 +78,6 @@ class XcorrLikelihood(GaussianLikelihood):
provider: Provider

def initialize(self):
check_yaml_types(self, {
"auto_file": str,
"cross_file": str,
"dndz_file": str,
"datapath": str,
"k_tracer_name": str,
"gc_tracer_name": str,
"high_ell": int,
"nz": int,
"Nchi": int,
"Nchi_mag": int,
"Pk_interp_kmax": (int, float),
"b1": (int, float),
"s1": (int, float)
})

name: str = "Xcorr" # noqa F841
self.log.info('Initialising.')

Expand Down

0 comments on commit 501d279

Please sign in to comment.