Skip to main content

CosmoCore: common algebra for harmonic-pixel handling.

Project description

CosmoCore

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.0rc1.tar.gz (105.9 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.0rc1-py3-none-any.whl (118.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: cosmocore-1.0.0rc1.tar.gz
  • Upload date:
  • Size: 105.9 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.0rc1.tar.gz
Algorithm Hash digest
SHA256 0ed0661fddb33aae9fc4c0015d8142ee5bdd5bc97b65496767ccbec67fe27e08
MD5 b8a2dbd7ab604be228149d3c9d36271c
BLAKE2b-256 11eb699c1f4f3ed4b4c6605e9b4f335541bfe594d796cd7e822f4ac7b374017c

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: cosmocore-1.0.0rc1-py3-none-any.whl
  • Upload date:
  • Size: 118.7 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.0rc1-py3-none-any.whl
Algorithm Hash digest
SHA256 9a79a921d146f7fb8186cb827923483a8a98cf1447ca7ab435b12ea7295dddfe
MD5 93e2201cedf6b543af3dcd73f702b503
BLAKE2b-256 4156285ec207fab07fdda43b7ca60bad8e28d2b696967c54673b6b166dac5ae7

See more details on using hashes here.

Provenance

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