Skip to main content

PICSLike: Pixel-based Inference with Correlated-Skies Likelihood

Project description

PICSLike logo (light) PICSLike logo (dark)

PyPI Python Documentation Parallelization Method

PICSLike Documentation | Main Documentation

PICSLike (Pixel-based Inference with Correlated-Skies Likelihood) is the pixel-based likelihood analysis engine of CosmoForge, implementing direct likelihood evaluation in map pixel space for cosmological parameter inference from CMB data.

Overview

PICSLike provides pixel-based likelihood computation as an alternative to harmonic-space methods:

  • Pixel-based Likelihood: Direct likelihood evaluation in map pixel space
  • Parameter Grid Analysis: Efficient likelihood computation across parameter grids

The approach is particularly useful for handling incomplete sky coverage, non-Gaussian features, and scenarios where pixel-space analysis offers computational or methodological advantages.

Key Features

Pixel-based Likelihood Analysis

  • Direct likelihood evaluation in pixel space
  • Natural handling of masked regions
  • Support for temperature and polarization data
  • Cross-correlation analysis support
  • Chi-squared and log-likelihood computation

Parameter Grid Management

  • Flexible parameter range specification
  • Theoretical spectra grid management
  • Efficient MPI distribution across parameter points
  • Best-fit parameter extraction
  • Confidence interval computation

Technical Features

  • MPI Parallelization: Distributed computation across parameter grids
  • Memory Optimization: Efficient covariance matrix handling
  • Instrumental Effects: Beam convolution and pixel window functions
  • Flexible Configuration: YAML-based parameter specification

Installation

Install from PyPI

pip install picslike

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

pip install picslike[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

Documentation

For detailed API documentation and examples:

Quick Start

Basic Pixel-based Likelihood Analysis

from picslike import PICSLike

# Initialize likelihood analysis
picslike = PICSLike("config/pixel_analysis.yaml")

# Run full pipeline
picslike.run()

# Get results
chi_squared = picslike.get_chi_squared()
best_fit = picslike.get_best_fit()
log_likelihood = picslike.get_log_likelihood()

Step-by-Step Execution

from picslike import PICSLike

# Initialize analysis
picslike = PICSLike("config/pixel_config.yaml")

# Setup pipeline components
picslike.setup_parameter_grid()
picslike.setup_fields()
picslike.setup_geometry()
picslike.setup_covariance_matrices()
picslike.setup_cls()
picslike.setup_beams()
picslike.setup_maps()

# Compute likelihood across parameter grid
picslike.compute()

# Save results
picslike.save_results("output/likelihood_results.pkl")

Accessing Simulation Results

from picslike import PICSLike

# Run analysis
picslike = PICSLike("config.yaml")
picslike.run()

# Get individual simulation results
simulation_results = picslike.get_simulation_results()

# Get mean likelihood result
mean_result = picslike.get_mean_likelihood_result()

# Extract summary statistics
summary = mean_result.get_summary_statistics()

In-Memory Inputs (no files)

Every input can be handed over as an array instead of a file path — for callers that already hold their maps, mask and noise covariance and should not have to round-trip them through disk. The config still supplies the scalars; an injected object wins over the corresponding path.

from picslike import PICSLike

like = PICSLike(
    params,
    mask=mask,             # (npix, nfields)
    noise_cov1=noise_cov,  # reduced (n_active, n_active)
    cls_data=cls,          # {label: C_ell}, physical C_ell
    fiducial_cls=cls,
    beam=beam,             # (>=3, lmax+1) T/E/B window functions
    maps1=maps,            # reduced (n_active, n_sims), *already* calibrated
)
like.run()

log_likelihood = like.get_log_likelihood()

Leave the out* paths unset and the run touches no disk at all.

Kwargs: mask, noise_cov1/noise_cov2, maps1/maps2, cls_data, fiducial_cls, beam — the same vocabulary as Fisher/Spectra in QUBE. Each injected object is exactly what the corresponding reader would have returned. Two contracts are asymmetric, because each mirrors what its reader does:

kwarg contract
noise_cov1 reduced to active pixels
maps1 reduced to active pixels

noise_cov1/maps1 are reduced to the active (unmasked) pixels and ordered by the active-pixel index. You do not need a Fisher to learn that ordering — it is a pure function of the mask:

from cosmocore import active_pixel_index

index = active_pixel_index(mask)
maps = maps_full.reshape(nfields * npix, nsims)[index]
cov = cov_full[np.ix_(index, index)]

Worked example (QUBE, same seams): src/cosmoforge.qube/notebooks/in_memory_inputs.ipynb. Rationale: ADR-0017.

Configuration

PICSLike uses YAML configuration files:

Basic Configuration

# Data specification
nside: 32
lmax: 64
fields: "TEB"  # or "TQU"

# Input files
maskfile: "data/mask.fits"
inputclfile: "data/fiducial_cls.txt"
covmatfile1: "data/noise_cov1.bin"
covmatfile2: "data/noise_cov2.bin"  # for cross-correlation

# Analysis parameters
do_cross: false
nsims: 100

Parameter Grid Configuration

# Parameter ranges for likelihood grid
parameters:
  amplitude:
    - 0.5    # min
    - 1.5    # max
    - 11     # n_points
  tilt:
    - -0.5   # min
    - 0.5    # max
    - 11     # n_points

# Theoretical spectra location
root_dir: "data/templates"
root_filename: "dls"

Beam Configuration

# Beam parameters
smoothing_type: gaussian  # none, gaussian, cosine_legacy, cosine_npipe, file
fwhmarcmin: 5.0
beam_file: "data/beam.fits"
apply_pixwin: true

MPI Usage

Run analyses in parallel:

# Pixel-based likelihood analysis
mpirun -n 4 python -c "
from picslike import PICSLike
picslike = PICSLike('config.yaml')
picslike.run()
"

# Full analysis with result saving, via the installed console script
mpirun -n 8 picslike-run config/pixel_analysis.yaml --out results.npz

Analysis Pipeline

Likelihood Computation Pipeline

  1. Setup: Read parameters and initialize fields
  2. Parameter Grid: Configure parameter ranges and load theoretical spectra
  3. Geometry: Compute pixel pointing vectors
  4. Covariance: Load noise covariance matrices
  5. Maps: Read input observation maps
  6. Broadcast: Distribute data across MPI processes
  7. Compute: Evaluate likelihood at each parameter point
  8. Results: Gather and store likelihood values

Likelihood Function

The pixel-based likelihood is computed as:

ln L(theta) = -1/2 * (d - s(theta))^T * C^(-1) * (d - s(theta))

where:

  • d is the observed data vector
  • s(theta) is the theoretical signal for parameters theta
  • C is the total covariance matrix (signal + noise)

API Reference

PICSLike Class

class PICSLike(Core):
    """Pixel-based likelihood analysis implementation."""

    def run(self):
        """Execute complete likelihood analysis."""

    def compute(self):
        """Compute likelihood across parameter grid."""

    def get_chi_squared(self):
        """Get chi-squared values."""

    def get_log_likelihood(self):
        """Get log-likelihood values."""

    def get_best_fit(self):
        """Get best-fit parameter values."""

    def save_results(self, output_path):
        """Save results to file."""

ParameterGrid Class

class ParameterGrid:
    """Manager for parameter grids and theoretical spectra."""

    def get_total_points(self):
        """Get total number of grid points."""

    def get_points_for_process(self, rank, size):
        """Get parameter points for an MPI process."""

    def get_spectrum(self, param_point):
        """Get theoretical spectrum for a parameter point."""

LikelihoodResult Class

class LikelihoodResult:
    """Container for likelihood computation results."""

    def get_best_fit(self):
        """Get best-fit parameter values."""

    def get_confidence_intervals(self, confidence_level=0.68):
        """Compute confidence intervals."""

    def get_marginalized_likelihood(self, parameter_name):
        """Get marginalized likelihood for a parameter."""

    def get_summary_statistics(self):
        """Get comprehensive summary statistics."""

    def save(self, output_path):
        """Save results to file."""

    @classmethod
    def load(cls, input_path):
        """Load results from file."""

Output Files

Likelihood Analysis Outputs

  • likelihood_results.pkl: Complete likelihood results
  • likelihood_results_sim_XX.pkl: Individual simulation results

Result Content

  • Chi-squared values across parameter grid
  • Log-likelihood values
  • Best-fit parameters
  • Confidence intervals (68%, 95%)
  • Marginalized likelihoods

Performance Optimization

Memory Management

  • Efficient covariance matrix handling
  • In-place operations where possible
  • Memory-mapped file I/O for large datasets

Computational Efficiency

  • Signal matrix computation optimized with Numba
  • Optimized BLAS/LAPACK operations
  • MPI load balancing across parameter points

Scaling

Typical performance scaling:

Processes    Speed-up
1           1.0x
2           1.9x
4           3.7x
8           7.3x
16          14.2x

Testing

Run the test suite (from the repository root):

uv run pytest src/cosmoforge.picslike/tests/ -s

Specific tests:

uv run pytest src/cosmoforge.picslike/tests/test_likelihood_result.py -s
uv run pytest src/cosmoforge.picslike/tests/test_parameter_grid.py -s
uv run pytest src/cosmoforge.picslike/tests/test_picslike.py -s

Examples

Mock Data Generation

# Generate mock inputs for temperature-only analysis
python scripts/produce_mock_inputs.py T /data/mocks config.yaml

# Generate with Galactic mask
python scripts/produce_mock_inputs.py TQU /data/mocks config.yaml --mask

Parameter Constraint Analysis

from picslike import PICSLike, LikelihoodResult

# Run likelihood analysis
picslike = PICSLike("config.yaml")
picslike.run()

# Get likelihood result
result = picslike.get_mean_likelihood_result()

# Get confidence intervals
intervals_68 = result.get_confidence_intervals(0.68)
intervals_95 = result.get_confidence_intervals(0.95)

# Get marginalized likelihood for specific parameter
marg_like = result.get_marginalized_likelihood('amplitude')

print(f"Best-fit parameters: {result.get_best_fit()}")
print(f"68% confidence intervals: {intervals_68}")

Scientific Context

Pixel-based likelihood methods provide several advantages:

  1. Incomplete sky coverage: Natural handling of masked regions without harmonic-space complications
  2. Non-Gaussian features: Direct treatment of non-Gaussian signals and systematics
  3. Cross-correlation analysis: Efficient computation of cross-correlations between different maps
  4. Computational efficiency: Faster for certain analysis configurations

Troubleshooting

Common Issues

  1. Memory errors: Reduce nside or use more MPI processes
  2. Missing spectra errors: Ensure theoretical spectra exist for all grid points
  3. MPI hanging: Ensure consistent configuration across processes

Debug Mode

Enable detailed logging:

feedback: 4  # Maximum verbosity

Performance Profiling

import cProfile

def run_analysis():
    picslike = PICSLike("config.yaml")
    picslike.run()

cProfile.run('run_analysis()', 'profile_output.prof')

Contributing

See the main CosmoForge README for contribution guidelines.

Citation

If you use PICSLike (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

  • Wandelt, B.D., Larson, D.L. & Lakshminarayanan, A. "Global, exact cosmic microwave background data analysis using Gibbs sampling" Phys. Rev. D 70, 083511 (2004)
  • Jewell, J., Levin, S. & Anderson, C.H. "Application of Monte Carlo algorithms to the Bayesian analysis of the cosmic microwave background" Astrophys. J. 609, 1-14 (2004)
  • Eriksen, H.K. et al. "Power Spectrum Estimation from High-Resolution Maps by Gibbs Sampling" Astrophys. J. Suppl. 155, 227-241 (2004)
  • Planck Collaboration "Planck 2018 results. V. CMB power spectra and likelihoods" Astron. Astrophys. 641, A5 (2020)
  • Tegmark, M. "How to measure CMB power spectra without losing information" Phys. Rev. D 55, 5895 (1997)

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

picslike-1.1.0.tar.gz (24.2 kB view details)

Uploaded Source

Built Distribution

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

picslike-1.1.0-py3-none-any.whl (25.8 kB view details)

Uploaded Python 3

File details

Details for the file picslike-1.1.0.tar.gz.

File metadata

  • Download URL: picslike-1.1.0.tar.gz
  • Upload date:
  • Size: 24.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for picslike-1.1.0.tar.gz
Algorithm Hash digest
SHA256 39473edacee730cdf8339d83c78bf734dfe1557447636767d4e6c5b5dc2d9704
MD5 5ab0d9b7939a52498652e2ddbeb8a88e
BLAKE2b-256 8038af468ed669d6123f3b9f879847315b558c9f181ff998d3c94311eef0bb57

See more details on using hashes here.

Provenance

The following attestation bundles were made for picslike-1.1.0.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 picslike-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: picslike-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 25.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for picslike-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 37e323fc4eff5a0449c123f70bd53b7d12529dd2767948ee80067f6fada44e5d
MD5 11d387093e254b765b213122db4901c3
BLAKE2b-256 c6cf07831a23bb59bfdeb728680c479f8fbbbd85f4e2040ac34020d74b271f42

See more details on using hashes here.

Provenance

The following attestation bundles were made for picslike-1.1.0-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