Skip to main content

CosmoCore: common algebra for harmonic-pixel handling.

Project description

CosmoCore

PyPI Python Documentation Performance

CosmoCore Documentation | API Reference | Main Documentation

CosmoCore is the foundational package of CosmoForge, providing core functionality for the analysis of spin-0 and spin-2 fields on the sphere, including field management, computation basis methods, matrix operations, I/O utilities, and spherical harmonic operations.

Overview

CosmoCore serves as the base layer for all cosmological computations in CosmoForge. It provides:

  • Field Management: Scalar (spin-0) and tensor (spin-2) field handling with HEALPix integration
  • Basis: Harmonic and pixel computation basis for Fisher matrix computation, with multi-field and spin-2 support
  • Matrix Operations: Optimized LAPACK-based linear algebra with Numba acceleration
  • Harmonic Analysis: Power spectrum management, beam handling, and spherical harmonic transforms
  • Pixel Operations: Signal matrix computation and HEALPix pixel-based operations
  • I/O Utilities: Reading and writing of cosmological data formats

Key Components

Computation Basis

Two computation basis methods for efficient Fisher matrix and QML estimation:

  • HarmonicBasis (Tegmark-like): Direct transformation to harmonic space (n_pix -> n_modes). Fast when n_modes << n_pix. Supports optional m-block compression (compress=True) that approximates K as block-diagonal in azimuthal number m, giving ~lmax^2 speedup.
  • PixelBasis (Gjerlow-like): Pixel-space projector with eigenvalue truncation (n_pix -> n_kept). Supports multiple basis choices and per-field threshold tuning.
  • create_computation_basis: Factory function for creating basis instances by name.

Both methods support:

  • Multi-field: Multiple components with independent sky coverage and noise
  • Spin-2 polarization: E/B mode decomposition with spin-weighted spherical harmonics
  • Per-field eigenspectrum inspection: compute_eigenspectrum_per_field() for choosing eigenmode thresholds, with E/B breakdown for spin-2 fields
  • Visualization: plot_eigenvalue_spectrum() and plot_eigenvalue_comparison() with per-component subplots

Fields

  • ScalarField: Spin-0 field implementation (e.g. CMB temperature, convergence)
  • PolarizationField: Spin-2 field implementation (e.g. CMB polarization, cosmic shear)
  • FieldCollection: Container for managing multiple fields
  • create_field: Factory function for field creation

Managers

  • SpectraManager: Power spectrum handling and normalization
  • BeamManager: Instrumental beam function management

Binning

  • Bins: Multipole binning specification for bandpower estimation. Supports uniform bins (Bins.fromdeltal) and custom non-uniform bins. Both bounds are inclusive. Used by QUBE for binned QML estimation.

Mathematical Operations

  • Legendre Polynomials: legendre_00, legendre_02, legendre_22, legendre_plm
  • Matrix Operations: matrix_mult, matrix_inverse_symm, matrix_trace, matrix_slogdet_symm
  • Harmonic Transforms: cl_to_vec, vec_to_cl
  • Wigner d-matrices: Spin-weighted harmonic basis functions
  • SMW Formula: Sherman-Morrison-Woodbury compressed inverse and log-determinant

Core

  • Core: Base class for cosmological analysis pipelines
  • InputParams: Parameter file management
  • CosmoLogger / Timer: Logging and profiling utilities

Installation

Install from PyPI

pip install cosmocore

To enable MPI parallelism (requires a system MPI implementation):

pip install cosmocore[mpi]

Or install the full CosmoForge umbrella (cosmocore + qube-qml + picslike):

pip install cosmoforge

Install from source

git clone https://github.com/ggalloni/CosmoForge.git
cd CosmoForge
uv sync --all-packages --all-extras --dev

Usage

Computation Basis Workflow

from cosmocore.basis import PixelBasis
import numpy as np

# Set up pixel basis
ppc = PixelBasis(N, N_inv, theta, phi, lmax=100)
ppc.setup()

# Inspect per-field eigenspectra to choose thresholds
fig, axes = ppc.plot_eigenvalue_spectrum(basis="noise_weighted")

# Apply eigenmode truncation with chosen threshold
ppc.apply_compression(epsilon=1e-4, basis="noise_weighted")

# Compute Fisher matrix
fisher = ppc.compute_fisher_matrix(C_ell)

Multi-Field with Spin-2 Polarization

from cosmocore.basis import PixelBasis

# T (spin-0) + QU (spin-2) setup
ppc = PixelBasis(
    N, N_inv,
    theta=(theta_t, theta_p),
    phi=(phi_t, phi_p),
    lmax=100,
    spins=[0, 2],
)
ppc.setup()

# Per-field eigenspectrum with E/B breakdown
spectra = ppc.compute_eigenspectrum_per_field(basis="noise_weighted")
for entry in spectra:
    print(f"{entry['label']}: {len(entry['eigenvalues'])} modes")

# Per-field thresholds (scalar for T, E/B tuple for polarization)
ppc.apply_compression(epsilon=[1e-4, (1e-4, 1e-3)])

# Multi-field Fisher matrix. C_ell_dict is keyed by SpectrumKey and
# spectra_list is a list of SpectrumKey instances enumerating which
# spectra to include (e.g. TT, EE, BB, TE).
fisher = ppc.compute_fisher_matrix(C_ell_dict, spectra_list)

Field Creation

from cosmocore import create_field, FieldCollection

# Create temperature field
temp_field = create_field(
    spin=0, nside=32, lmax=64,
    mask=mask_array, labels="T"
)

# Create polarization field
pol_field = create_field(
    spin=2, nside=32, lmax=64,
    mask=mask_array, labels=["E", "B"]
)

# Create field collection
collection = FieldCollection(params, [temp_field, pol_field])

Power Spectrum Management

from cosmocore import SpectraManager, BeamManager

spectra_mgr = SpectraManager(fields)
beam_mgr = BeamManager(fields)

spectra_mgr.set_cls_from_file("fiducial_cls.txt", params)
beam_mgr.apply_smoothing(spectra_mgr)

Matrix Operations

from cosmocore import matrix_mult, matrix_inverse_symm, matrix_trace

C = matrix_mult(A, B)
inv_A = matrix_inverse_symm(A)
tr_AB = matrix_trace(A, B)

Configuration

CosmoCore uses parameter files for configuration:

# Field configuration
nside: 32
lmax: 64
spins: [0, 2]  # Temperature and polarization
labels: ["T", "E", "B"]

# I/O configuration
maskfile: "data/mask.fits"
inputclfile: "data/fiducial_cls.txt"
input_convention: Dl  # "Cl" (default) or "Dl" for input files
output_convention: Cl  # "Cl" (default) or "Dl" for QML output
covmatfile1: "data/noise_cov.bin"

# Beam configuration
smoothing_type: gaussian
fwhmarcmin: 5.0
beam_file: "data/beam.fits"

Architecture

cosmocore/
├── __init__.py              # Public API
├── core.py                  # Core base class
├── fields.py                # Field implementations (Scalar, Polarization)
├── settings.py              # Parameter management
├── beam.py                  # Beam and pixwin manager
├── bins.py                  # Multipole binning (Bins, Bins.fromdeltal)
├── spectrum_key.py          # SpectrumKey, SpectrumKind, SymmetryMode
├── spectra_io.py            # Spectra I/O and SpectraManager
├── signal_kernels.py        # Per-ell Legendre signal kernels
├── in_out.py                # File I/O utilities
├── mpi_utils.py             # MPI helpers (shared-memory mixin)
├── logger.py                # Logging and timing
├── basics/                  # Mathematical primitives
│   ├── linalg.py            #   Matrix operations (mult, inverse, trace)
│   ├── legendre.py          #   Legendre polynomial evaluation
│   ├── wigner.py            #   Wigner d-matrices for spin-2
│   ├── geometry.py          #   Rotation angles and coordinate transforms
│   ├── indexing.py          #   Spectrum index utilities
│   └── smw.py               #   Sherman-Morrison-Woodbury formula
├── basis/                   # Computation basis for Fisher/QML
│   ├── base.py              #   Abstract base class and SMW types
│   ├── harmonic_basis.py    #   Harmonic basis builder (V operator, Lambda)
│   ├── harmonic.py          #   HarmonicBasis (Tegmark-like)
│   └── pixel.py             #   PixelBasis (Gjerlow-like)
└── conventions/             # Domain-specific naming
    └── cmb.py               #   CMB aliases (TT/EE/BB/EB/TE/...)

Performance Features

Numba Acceleration

Critical functions use Numba JIT compilation for near-C performance:

@njit(cache=True)
def legendre_unified(cos_theta, lmax, pl_00, pl_02, pl_22):
    ...

Memory Optimization

  • In-place operations and pre-allocated buffers for hot paths
  • Efficient memory layouts (Fortran-order for LAPACK calls)
  • SMW formula avoids forming full n_pix x n_pix inverses

Vectorized Operations

  • NumPy/BLAS vectorization for matrix operations
  • Precomputed derivative diagonals for O(l^2) Fisher computation
  • Block-diagonal structure exploited for multi-field computation
  • M-block compression: block-diagonal K in azimuthal number m for ~lmax^2 speedup
  • Field block-diagonal K: automatic detection and exploitation when fields are independent

Testing

Run CosmoCore tests:

uv run pytest src/cosmoforge.cosmocore/tests/

Dependencies

  • NumPy: Numerical computations
  • SciPy: Scientific computing (LAPACK wrappers)
  • Numba: JIT compilation
  • Matplotlib: Eigenspectrum visualization
  • HEALPix: Pixelization (via healpy)

Documentation

Citation

If you use CosmoCore (as part of CosmoForge) in your research, please cite:

Galloni, G. & Pagano, L., CosmoForge I: A unified framework for QML power spectrum estimation and pixel-based likelihood analysis, arXiv:2605.21149 (2026).

@article{GalloniPagano_CosmoForgeI,
    author        = {Galloni, G. and Pagano, L.},
    title         = {{CosmoForge I}: A unified framework for {QML} power spectrum estimation and pixel-based likelihood analysis},
    year          = {2026},
    eprint        = {2605.21149},
    archivePrefix = {arXiv},
    primaryClass  = {astro-ph.CO},
}

References

  • Tegmark, M. "How to measure CMB power spectra without losing information" Phys. Rev. D 55, 5895 (1997)
  • Gjerlow, E. et al. "Component separation for the CMB with a low-resolution analysis" A&A 629, A51 (2019)
  • Gorski, K.M. et al. "HEALPix: A Framework for High-Resolution Discretization and Fast Analysis of Data Distributed on the Sphere" Astrophys. J. 622, 759-771 (2005)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cosmocore-1.0.1.tar.gz (120.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cosmocore-1.0.1-py3-none-any.whl (135.1 kB view details)

Uploaded Python 3

File details

Details for the file cosmocore-1.0.1.tar.gz.

File metadata

  • Download URL: cosmocore-1.0.1.tar.gz
  • Upload date:
  • Size: 120.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for cosmocore-1.0.1.tar.gz
Algorithm Hash digest
SHA256 95b314822bf0f8c4793e1633670cbc6e49186559417bb168abc404a9f0f99349
MD5 c23710e09cde8c25d0149b7b860309b6
BLAKE2b-256 ce9cfa09358a4ab1c0b0ef50897ec094dc422e6efb7f51c3e1f9a33691abecb9

See more details on using hashes here.

Provenance

The following attestation bundles were made for cosmocore-1.0.1.tar.gz:

Publisher: publish.yml on ggalloni/CosmoForge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file cosmocore-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: cosmocore-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 135.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for cosmocore-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1d662fac45cd1bb3822d6015c78928c9b3a8fe6443a8b5a0a44d929a11f16a8c
MD5 1f7319cc42814929a30b9d0ed1a9ebfd
BLAKE2b-256 21bf98fbff7317bbe9ac515650476df05ac03d2fc0dd0c2d3f6e79a47094cf5c

See more details on using hashes here.

Provenance

The following attestation bundles were made for cosmocore-1.0.1-py3-none-any.whl:

Publisher: publish.yml on ggalloni/CosmoForge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page