PICSLike Class

The PICSLike class provides comprehensive pixel-based likelihood computation for cosmological parameter estimation. The implementation features MPI parallelization, exact covariance matrix treatment, and integration with the broader CosmoForge analysis pipeline.

Mathematical Background

The pixel-based likelihood evaluates how well theoretical predictions match observed data in pixel space:

\[\ln \mathcal{L}(\theta) = -\frac{1}{2} \chi^2(\theta) = -\frac{1}{2} (\mathbf{d} - \mathbf{s}(\theta))^T \mathbf{C}^{-1}(\theta) (\mathbf{d} - \mathbf{s}(\theta))\]

where:

  • \(\mathbf{d}\) is the observed data vector

  • \(\mathbf{s}(\theta)\) is the theoretical signal for parameters \(\theta\)

  • \(\mathbf{C}(\theta) = \mathbf{S}(\theta) + \mathbf{N}\) is the total covariance matrix

Class Documentation

class picslike.picslike.PICSLike(params_file=None, compression=None, **kwargs)[source]

Bases: Core, MPISharedMemoryMixin

Pixel-based likelihood computation for cosmological parameter inference.

This class implements pixel-space likelihood analysis for CMB observations, providing an alternative to harmonic-space methods. It inherits from cosmocore.Core and extends it with pixel-based likelihood functionality including parameter grid management, signal covariance computation, and likelihood evaluation across parameter space.

The likelihood function computed is:

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

where the total covariance matrix C includes both signal and noise contributions and is recomputed for each parameter point θ in the grid.

Parameters:
  • params_file (str, optional) – Path to YAML parameter file containing analysis configuration.

  • **kwargs (dict) – Additional keyword arguments passed to the Core parent class.

comm

MPI communicator for parallel computation.

Type:

MPI.Comm

rank

MPI process rank (0 for master process).

Type:

int

size

Total number of MPI processes.

Type:

int

maps

Collection of observed data maps.

Type:

FieldCollection

parameter_grid

Grid of parameter values and corresponding theoretical spectra.

Type:

ParameterGrid

likelihood_result

Container for computed likelihood values and statistics.

Type:

LikelihoodResult

data_vector

Flattened data vector from observed maps.

Type:

numpy.ndarray

noise_covariance

Noise covariance matrix.

Type:

numpy.ndarray

Examples

Basic pixel-based likelihood analysis:

>>> from cosmoforge.picslike import PICSLike
>>> picslike = PICSLike("config/pixel_analysis.yaml")
>>> picslike.setup_parameter_grid(param_ranges, theoretical_spectra)
>>> picslike.compute_likelihood_grid()
>>> chi2_values = picslike.get_chi_squared()
>>> best_fit = picslike.get_best_fit()

MPI parallel execution:

>>> # Run with: mpirun -n 4 python pixel_analysis.py
>>> picslike = PICSLike("config/pixel_config.yaml")
>>> picslike.compute_likelihood_grid()  # Distributed across processes

Notes

The pixel-based likelihood computation is parallelized using MPI, with each process handling a subset of parameter grid points. The method scales well with the number of parameter points but can be memory-intensive for large maps due to covariance matrix storage and inversion.

For analyses with many parameters or high-resolution maps, consider using appropriate computational resources and memory optimization strategies.

See also

cosmocore.Core

Base class providing fundamental analysis infrastructure

ParameterGrid

Helper class for parameter space management

LikelihoodResult

Container for likelihood computation results

__init__(params_file=None, compression=None, **kwargs)[source]

Initialize pixel-based likelihood computation class.

Parameters:
  • params_file (str, optional) – Path to YAML configuration file.

  • compression (dict, optional) – Computation basis configuration (method, epsilon, basis, mode_fraction).

  • **kwargs (Any) – Additional arguments passed to Core.

property lmax_signal: int

Signal-cov ceiling (ADR 0009).

Resolution order: explicit setter, then params.lmax_signal, then 4 * nside.

compute_signal_matrix(param_point)[source]

Compute signal covariance matrix for a given parameter point.

Returns:

Signal covariance matrix S, shape (n_active_pixels, n_active_pixels).

Return type:

np.ndarray

Raises:

ValueError – If noise covariance matrices not set up.

prepare_covariance_matrix()[source]

Prepare total covariance C = S + N and compute its inverse.

Modifies self.signal_matrix in-place to form total covariance, then inverts it.

setup_maps()[source]

Read observational map data from FITS files.

Loads maps with proper pixel selection, field extraction, and calibration. For cross-correlation (do_cross=True), loads both primary and secondary maps. Output shape: (n_active_pixels, n_simulations).

Raises:
set_simulation_index(sim_idx)[source]

Set which simulation to use for likelihood computation.

Parameters:

sim_idx (int) – Index of the simulation to use (0-based indexing). Must be within the range [0, nsims-1].

Raises:

ValueError – If sim_idx is out of range for the available simulations.

Return type:

None

Notes

In a real analysis, this would typically be 0 since you have only one observational dataset. For Monte Carlo studies, you might want to compute likelihoods for different simulations separately.

setup_parameter_grid()[source]

Set up parameter grid from config and load associated theoretical spectra.

Return type:

None

compute()[source]

Compute likelihood across the entire parameter grid for all simulations.

Evaluates the likelihood function at each point in the parameter grid for each simulation, distributing the computation across MPI processes for efficiency. The signal covariance matrix is recomputed for each parameter point using the corresponding theoretical power spectrum.

Return type:

None

Notes

This is the main computational routine that: 1. Distributes parameter grid points across MPI processes 2. For each simulation:

  • Computes signal covariance matrix for each parameter point

  • Inverts total covariance matrix (signal + noise)

  • Evaluates likelihood function

  1. Gathers results from all processes

  2. Stores collection of LikelihoodResult objects (one per simulation)

The computation scales as O(N_sim * N_param * N_pix^3) where N_sim is the number of simulations, N_param is the number of parameter points and N_pix is the number of pixels.

get_chi_squared()[source]

Get chi-squared values from likelihood computation.

Returns:

chi_squared – Array of chi-squared values corresponding to parameter grid points.

Return type:

numpy.ndarray

Raises:

RuntimeError – If likelihood computation has not been performed.

get_log_likelihood()[source]

Get log-likelihood values from likelihood computation.

Returns:

log_likelihood – Array of log-likelihood values corresponding to parameter grid points.

Return type:

numpy.ndarray

Raises:

RuntimeError – If likelihood computation has not been performed.

get_best_fit()[source]

Get best-fit parameter values from likelihood computation.

Returns:

best_fit_params – Dictionary mapping parameter names to their best-fit values.

Return type:

dict[str, float]

Raises:

RuntimeError – If likelihood computation has not been performed.

get_simulation_results()[source]

Get likelihood results for each individual simulation.

Returns:

One LikelihoodResult per simulation.

Return type:

list[LikelihoodResult]

Raises:

RuntimeError – If compute() has not been called.

get_mean_likelihood_result()[source]

Get the mean likelihood result averaged over all simulations.

Returns:

Mean likelihood result for plotting and analysis.

Return type:

LikelihoodResult

Raises:

RuntimeError – If compute() has not been called.

save_results(output_path)[source]

Save likelihood results to file.

Parameters:

output_path (str) – Base path for saving. Individual sims saved as output_path_sim_XX.

Return type:

None

run()[source]

Execute the complete pixel-based likelihood analysis pipeline.

Pipeline: setup fields/geometry/covariance, configure parameter grid, compute likelihood across parameter space, gather results.

Key Methods

Initialization and Setup

PICSLike.__init__(params_file=None, compression=None, **kwargs)[source]

Initialize pixel-based likelihood computation class.

Parameters:
  • params_file (str, optional) – Path to YAML configuration file.

  • compression (dict, optional) – Computation basis configuration (method, epsilon, basis, mode_fraction).

  • **kwargs (Any) – Additional arguments passed to Core.

PICSLike.setup_parameter_grid()[source]

Set up parameter grid from config and load associated theoretical spectra.

Return type:

None

PICSLike.setup_maps()[source]

Read observational map data from FITS files.

Loads maps with proper pixel selection, field extraction, and calibration. For cross-correlation (do_cross=True), loads both primary and secondary maps. Output shape: (n_active_pixels, n_simulations).

Raises:

Core Computation

PICSLike.compute_signal_matrix(param_point)[source]

Compute signal covariance matrix for a given parameter point.

Returns:

Signal covariance matrix S, shape (n_active_pixels, n_active_pixels).

Return type:

np.ndarray

Raises:

ValueError – If noise covariance matrices not set up.

PICSLike.prepare_covariance_matrix()[source]

Prepare total covariance C = S + N and compute its inverse.

Modifies self.signal_matrix in-place to form total covariance, then inverts it.

PICSLike.compute()[source]

Compute likelihood across the entire parameter grid for all simulations.

Evaluates the likelihood function at each point in the parameter grid for each simulation, distributing the computation across MPI processes for efficiency. The signal covariance matrix is recomputed for each parameter point using the corresponding theoretical power spectrum.

Return type:

None

Notes

This is the main computational routine that: 1. Distributes parameter grid points across MPI processes 2. For each simulation:

  • Computes signal covariance matrix for each parameter point

  • Inverts total covariance matrix (signal + noise)

  • Evaluates likelihood function

  1. Gathers results from all processes

  2. Stores collection of LikelihoodResult objects (one per simulation)

The computation scales as O(N_sim * N_param * N_pix^3) where N_sim is the number of simulations, N_param is the number of parameter points and N_pix is the number of pixels.

PICSLike.run()[source]

Execute the complete pixel-based likelihood analysis pipeline.

Pipeline: setup fields/geometry/covariance, configure parameter grid, compute likelihood across parameter space, gather results.

Results Retrieval

PICSLike.get_chi_squared()[source]

Get chi-squared values from likelihood computation.

Returns:

chi_squared – Array of chi-squared values corresponding to parameter grid points.

Return type:

numpy.ndarray

Raises:

RuntimeError – If likelihood computation has not been performed.

PICSLike.get_log_likelihood()[source]

Get log-likelihood values from likelihood computation.

Returns:

log_likelihood – Array of log-likelihood values corresponding to parameter grid points.

Return type:

numpy.ndarray

Raises:

RuntimeError – If likelihood computation has not been performed.

PICSLike.get_best_fit()[source]

Get best-fit parameter values from likelihood computation.

Returns:

best_fit_params – Dictionary mapping parameter names to their best-fit values.

Return type:

dict[str, float]

Raises:

RuntimeError – If likelihood computation has not been performed.

PICSLike.get_simulation_results()[source]

Get likelihood results for each individual simulation.

Returns:

One LikelihoodResult per simulation.

Return type:

list[LikelihoodResult]

Raises:

RuntimeError – If compute() has not been called.

PICSLike.get_mean_likelihood_result()[source]

Get the mean likelihood result averaged over all simulations.

Returns:

Mean likelihood result for plotting and analysis.

Return type:

LikelihoodResult

Raises:

RuntimeError – If compute() has not been called.

PICSLike.save_results(output_path)[source]

Save likelihood results to file.

Parameters:

output_path (str) – Base path for saving. Individual sims saved as output_path_sim_XX.

Return type:

None

Simulation Management

PICSLike.set_simulation_index(sim_idx)[source]

Set which simulation to use for likelihood computation.

Parameters:

sim_idx (int) – Index of the simulation to use (0-based indexing). Must be within the range [0, nsims-1].

Raises:

ValueError – If sim_idx is out of range for the available simulations.

Return type:

None

Notes

In a real analysis, this would typically be 0 since you have only one observational dataset. For Monte Carlo studies, you might want to compute likelihoods for different simulations separately.

Usage Examples

Basic Likelihood Computation

from picslike import PICSLike

# Initialize with configuration file
picslike = PICSLike(params_file="config/analysis.yaml")

# Run complete computation pipeline
picslike.run()

# Get results (master process only)
if picslike.rank == 0:
    chi2 = picslike.get_chi_squared()
    log_like = picslike.get_log_likelihood()
    best_fit = picslike.get_best_fit()

    print(f"Chi-squared at best-fit: {chi2.min():.2f}")
    print(f"Best-fit parameters: {best_fit}")

Step-by-Step Setup

from picslike import PICSLike

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

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

# Run likelihood computation
picslike.compute()

# Save results
if picslike.rank == 0:
    picslike.save_results("output/results.npz")

Multiple Simulations

from picslike import PICSLike

picslike = PICSLike(params_file="config/analysis.yaml")
picslike.run()

# Access individual simulation results
if picslike.rank == 0:
    sim_results = picslike.get_simulation_results()
    for i, result in enumerate(sim_results):
        print(f"Sim {i}: chi2_min = {result.get_chi_squared_minimum():.2f}")

    # Get mean across simulations
    mean_result = picslike.get_mean_likelihood_result()

MPI Parallel Execution

# Run with 8 MPI processes
mpirun -n 8 python -c "
from picslike import PICSLike
picslike = PICSLike(params_file='config.yaml')
picslike.run()
"

Computational Notes

Performance Characteristics

  • Scaling: \(O(N_{param} \times N_{pix}^3)\) where \(N_{param}\) is the number of parameter grid points and \(N_{pix}\) is the number of active pixels

  • Memory: Dominated by covariance matrix storage \(O(N_{pix}^2)\)

  • Parallelization: Parameter grid points distributed across MPI processes

Pipeline Order

The setup methods must be called in the correct order:

  1. setup_parameter_grid() - Define parameter space

  2. setup_fields() - Configure field types (T, Q, U)

  3. setup_geometry() - Set up pixel geometry and masks

  4. setup_covariance_matrices() - Load noise covariance

  5. setup_cls() - Load theoretical power spectra

  6. setup_beams() - Load beam transfer functions

  7. setup_maps() - Load observed maps

  8. compute() - Run likelihood computation

Alternatively, run() executes all steps automatically.

See Also

  • picslike.parameter_grid.ParameterGrid : Parameter space management

  • picslike.likelihood_result.LikelihoodResult : Results container

  • cosmocore : Underlying computational infrastructure