cosmocore.core module
Core analysis classes for cosmological computations.
This module provides the foundational classes for cosmological power spectrum analysis, Fisher matrix calculations, and related computations. The Core class serves as an abstract base class for specific analysis tools like QML and Fisher matrix estimators.
Classes
- Core
Abstract base class for cosmological analysis tools.
Notes
The core module follows a clean architecture pattern with separation of concerns between data management (fields), computation (pixel/harmonic), and I/O operations. The Core class provides common functionality that can be extended by concrete analysis implementations.
- class cosmocore.core.Core(params=None)[source]
Bases:
ABCAbstract base class for cosmological analysis tools.
This class provides common functionality for Fisher matrix calculations, power spectrum analysis, and other cosmological computations. It handles parameter management, field setup, and coordinate system operations.
- Parameters:
params (InputParams or str or dict or None, optional) – Analysis parameters. Can be: - InputParams instance: Use directly - str: Path to parameter file to load - dict: Parameter dictionary to initialize InputParams - None: Use default parameters
- params
Analysis parameters and configuration.
- Type:
Notes
This is an abstract class that cannot be instantiated directly. Use concrete subclasses that implement the required abstract methods for specific analysis tasks.
- __init__(params=None)[source]
Initialize the core analysis framework.
- Parameters:
params (InputParams or str or dict or None, optional) – Analysis parameters in various formats.
- read_params(params)[source]
Read and validate analysis parameters.
- Parameters:
params (InputParams or str or dict) – Parameters in various formats: - InputParams: Use directly - str: Path to parameter file - dict: Dictionary to initialize InputParams
- Raises:
TypeError – If params format is not recognized.
Notes
This method provides flexible parameter input handling for different use cases (script files, interactive sessions, programmatic access).
- setup_fields()[source]
Set up cosmological fields using the new clean architecture.
- Returns:
Collection of fields configured according to analysis parameters.
- Return type:
Notes
This method: 1. Loads masks from file using the parameters 2. Creates appropriate field types (scalar/polarization) based on spin 3. Assembles fields into a collection for joint analysis
The field creation uses type-safe factory functions to ensure proper initialization based on the spin parameter.
- setup_geometry()[source]
Set up geometry including active pixels and pointing vectors.
- Returns:
Tuple containing (active_pixels, pointing_vectors) where: - active_pixels: Object array of active pixel indices per field component - pointing_vectors: Tuple of unit vector arrays for each component
- Return type:
- Raises:
ValueError – If fields have not been set up before calling this method.
Notes
This method: 1. Extracts active pixel counts from each field 2. Computes 3D pointing vectors for each active pixel 3. Computes theta (colatitude) and phi (longitude) for computation basis 4. Sets pointing vectors in the field collection 5. Optionally outputs geometry data to file
The pointing vectors are unit vectors in 3D space pointing to pixel centers, used for spherical harmonic transforms and coordinate operations.
- setup_covariance_matrices()[source]
Set up noise covariance matrices for the analysis.
- Returns:
Tuple containing (primary_covariance, secondary_covariance) where: - primary_covariance: Main noise covariance matrix - secondary_covariance: Optional second covariance matrix for cross-analysis
- Return type:
- Raises:
ValueError – If geometry has not been set up before calling this method.
Notes
This method: 1. Reads noise covariance matrices from file 2. Applies calibration corrections 3. Optionally outputs reduced covariance matrices 4. Sets up secondary covariance for cross-correlation analysis if enabled
The covariance matrices are essential for proper weighting in maximum likelihood and Fisher matrix calculations.
- setup_cls(lmax=None)[source]
Set up power spectra using the new field design.
- Parameters:
lmax (int, optional) – Maximum multipole to use. If None, uses core_params.lmax. This allows loading Cls up to a different lmax than the analysis lmax.
Notes
This method configures theoretical power spectra for the field collection, loading from file and applying necessary normalizations.
- Raises:
ValueError – If fields have not been set up before calling this method.
- setup_beams(lmax=None)[source]
Set up beam functions for each field using the new design.
- Parameters:
lmax (int, optional) – Maximum multipole to use. If None, uses core_params.lmax. This allows computing beams up to a different lmax than the analysis lmax.
Notes
This method configures beam window functions for instrumental effects correction in harmonic space analysis.
- Raises:
ValueError – If fields have not been set up before calling this method.
- setup_computation_basis(method='auto', epsilon=None, mode_fraction=None, beam=None, compression_target='noise_weighted', C_ell=None, lmax_signal=None, use_smw_optimization=True, compress=False, delta_m=0)[source]
Create and configure a computation basis for SMW-based operations.
Sets up the Sherman-Morrison-Woodbury framework for efficient covariance operations. Geometry and covariance matrices must be set up first. The harmonic path enables the SMW switch optimisation when
params.lmax < lmax_signal— signal from multipoles outside the inference window[lmin, lmax]is absorbed into an effective noise term, reducing the harmonic subspace dimension while preserving accuracy on the inferred multipoles (ADR 0009).- Parameters:
method (str, default "harmonic") – Computation basis to use: - “harmonic”: Tegmark-style direct harmonic transformation - “pixel”: Gjerløw-style pixel-space projector with eigenvalue truncation
epsilon (float or None, optional) – Eigenvalue threshold for pixel basis. Modes with eigenvalue <
epsilon * max_eigenvalueare discarded.None(the default) signals direct mode — no compression intent, V operator never materialised. Pass a value (e.g.1e-6) to opt into the V-based / eigenmode-truncated path.lmax_signal (int or None, optional) – Signal-cov ceiling. If None, defaults to
params.lmax_signalor4 * nside.mode_fraction (float or None, optional) – Fraction of modes to keep (between 0 and 1). Keeps the top modes ordered by eigenvalue. Mutually exclusive with epsilon.
beam (numpy.ndarray or None, optional) – Beam window function B_ℓ for ℓ=0..lmax_signal. If None and beams have been set up via setup_beams(), the first field’s beam is automatically extracted from the beam manager.
compression_target (str, default "noise_weighted") – Selector for the matrix to eigendecompose during pixel compression. Options:
"harmonic","noise_weighted","total_covariance","snr".C_ell (numpy.ndarray or None, optional) – Power spectrum for bases that require it (“total_covariance”, “snr”).
use_smw_optimization (bool, default True) – For harmonic basis, whether to absorb signal outside the inference window into effective noise. Reduces computation while preserving accuracy.
- Returns:
Configured computation basis instance.
- Return type:
ComputationBasis
- Raises:
ValueError – If geometry or covariance matrices have not been set up.
Examples
>>> core = SomeConcreteCore("config.yaml") >>> core.setup_fields() >>> core.setup_geometry() >>> core.setup_covariance_matrices() >>> core.setup_beams() >>> # Harmonic basis (default) >>> cm = core.setup_computation_basis(method="harmonic") >>> # Pixel basis with SNR compression target >>> cm = core.setup_computation_basis( ... method="pixel", ... compression_target="snr", ... C_ell=C_ell, ... epsilon=1e-4, ... )
- get_total_covariance(C_ell)[source]
Get total covariance matrix C = N + S.
If a computation basis is enabled, returns the projected covariance. Otherwise, returns the full pixel-space covariance.
- Parameters:
C_ell (numpy.ndarray) – Power spectrum values for ell = 2 to lmax.
- Returns:
Total covariance matrix (compressed or full).
- Return type:
- get_covariance_inverse(C_ell)[source]
Get inverse covariance matrix C^{-1}.
If a computation basis is enabled, returns the projected inverse. Otherwise, computes the full inverse.
- Parameters:
C_ell (numpy.ndarray) – Power spectrum values for ell = 2 to lmax.
- Returns:
Inverse covariance matrix (compressed or full).
- Return type:
- get_covariance_logdet(C_ell)[source]
Get log determinant of covariance matrix log|C|.
If a computation basis is enabled, uses SMW formula for exact result. Otherwise, computes directly.
- Parameters:
C_ell (numpy.ndarray or dict) – Power spectrum values (array) or dict with 3-tuple keys.
- Returns:
Log determinant of covariance matrix.
- Return type:
- get_derivative_matrix(ell, key, *, symmetry_mode=None)[source]
Get derivative matrix dC/dC_ell for a
SpectrumKey.If a computation basis is enabled, returns the projected derivative. Otherwise, returns full pixel-space derivative for the slab that
keyresolves to inself.spectra_list.- Parameters:
ell (int) – Multipole for derivative.
key (SpectrumKey) – Identifies the spectrum (component pair + spin kind).
symmetry_mode (SymmetryMode or None) – Forwarded to the basis-layer derivative builder;
Nonekeeps the SYMMETRIC default.
- Raises:
RuntimeError – On the no-basis path when
self.spectra_listis unpopulated andparams.nspectra > 1. Callers in multi-spectrum contexts must populatespectra_list(Fisher/Spectra do this incompute); single-spectrum callers can leave it unset.- Return type:
- set_binning(bins)[source]
Configure multipole binning.
- Parameters:
bins (Bins) – Binning specification defining multipole ranges and weights. Must satisfy
bins.lmin == params.lminandbins.lmax <= params.lmax: the per-spectrumbeam_smoothingblock built byFisher.runis keyed byparams.lminand has lengthparams.lmax - params.lmin + 1, and the binned-derivative paths index it asbeam_smoothing[ell - bins.lmin]. A binning that drifts below the inference floor or above the ceiling silently misaligns the beam weights.- Return type:
- get_binned_derivative_matrix(bin_idx, key, *, beam_smoothing=None, symmetry_mode=None)[source]
Compute binned derivative dC^b = Sum_{ell in bin} b²_ell dC^ell,
where the sum runs over ℓ in the bin with unit weight, b²_ell is the beam smoothing factor, and dC^ell = dC/dC_ell is the per-multipole derivative matrix.
When beam_smoothing is provided, beam window functions are applied per-ℓ so that the resulting Fisher matrix is in beam-smoothed space. Without it, the derivative is just the unweighted sum dC^b = Sum_{ell in bin} dC^ell.
- Parameters:
bin_idx (int) – Index of the bin.
key (SpectrumKey) – Identifies the spectrum (component pair + spin kind).
beam_smoothing (np.ndarray or None) – Per-ell beam smoothing factors b²_ell (length n_ell, starting at ell=params.lmin; ADR 0009).
symmetry_mode (SymmetryMode or None) – Forwarded to the per-ℓ derivative builder. None keeps the SYMMETRIC default.
- Return type:
- quadratic_form(data, C_ell)[source]
Compute quadratic form d^T C^{-1} d.
If a computation basis is enabled, uses efficient SMW-based computation. Otherwise, computes directly with full matrices.
- Parameters:
data (numpy.ndarray) – Data vector in pixel space.
C_ell (numpy.ndarray or dict) – Power spectrum values (array) or dict with 3-tuple keys.
- Returns:
Quadratic form value d^T C^{-1} d.
- Return type:
- log(message, level=1)[source]
Log a message based on feedback level (backward compatibility).
- Parameters:
Notes
This method maintains backward compatibility with the existing feedback system while using the enhanced logger infrastructure. Messages are logged with appropriate formatting and can be output to both console and file if configured.