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

CosmoCore is automatically installed as part of CosmoForge:

pip install -e /path/to/CosmoForge

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
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
├── harmonic.py              # Power spectrum and beam managers
├── pixel.py                 # Pixel-based signal matrix operations
├── in_out.py                # I/O utilities
├── 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)

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

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.0rc2.tar.gz (106.1 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.0rc2-py3-none-any.whl (118.9 kB view details)

Uploaded Python 3

File details

Details for the file cosmocore-1.0.0rc2.tar.gz.

File metadata

  • Download URL: cosmocore-1.0.0rc2.tar.gz
  • Upload date:
  • Size: 106.1 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.0rc2.tar.gz
Algorithm Hash digest
SHA256 ac9c407f67d3c54cab3be225d5cd404ebaaab96ef2cb3e75a6b4e9d8194f0ca5
MD5 3b0130240ec3263a1c60c43a0c553797
BLAKE2b-256 4805b6d6313062445f48bb086efcf6fa0eb81ef5740f03331d9d990e8e2a0216

See more details on using hashes here.

Provenance

The following attestation bundles were made for cosmocore-1.0.0rc2.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.0rc2-py3-none-any.whl.

File metadata

  • Download URL: cosmocore-1.0.0rc2-py3-none-any.whl
  • Upload date:
  • Size: 118.9 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.0rc2-py3-none-any.whl
Algorithm Hash digest
SHA256 3f33279635c914b1f3223abbd03843c6e16c7eebfafa558940a26e6774839fa1
MD5 79b5a999b41f0f1e638ade9e505d66b2
BLAKE2b-256 c4327790c7899393fc14b96d16cdfb650e44192f606f0b93f016efc713a98ea6

See more details on using hashes here.

Provenance

The following attestation bundles were made for cosmocore-1.0.0rc2-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