ParameterGrid Class
The ParameterGrid class manages the parameter space for likelihood evaluation, including grid generation, theoretical spectrum storage, and MPI work distribution.
Overview
ParameterGrid provides:
Cartesian product grid generation from parameter ranges
Mapping between grid indices and parameter values
Storage and retrieval of theoretical spectra for each grid point
MPI-aware work distribution across processes
Class Documentation
- class picslike.parameter_grid.ParameterGrid(core_params, parameter_ranges, theoretical_spectra=None, root_dir=None, root_filename=None, lmax_signal=None)[source]
Bases:
objectManager for parameter grids and theoretical spectra.
This class handles the organization of parameter spaces for likelihood analysis, including grid generation, spectrum management, and efficient distribution of parameter points across parallel processes.
- Parameters:
parameter_ranges (dict[str, np.ndarray]) – Dictionary mapping parameter names to their value ranges. Each value should be a 1D array of parameter values.
theoretical_spectra (dict[tuple, np.ndarray]) – Dictionary mapping parameter value tuples to theoretical power spectra. Keys are tuples of parameter values in the same order as parameter_ranges.
- theoretical_spectra
Theoretical spectra for each parameter combination.
Examples
Regular parameter grid:
>>> param_ranges = { ... 'omega_b': np.linspace(0.02, 0.025, 5), ... 'omega_c': np.linspace(0.10, 0.14, 5), ... } >>> spectra = {} # Filled with theoretical spectra >>> grid = ParameterGrid(param_ranges, spectra) >>> total_points = grid.get_total_points() # Returns 25
MPI process distribution:
>>> points_for_process = grid.get_points_for_process(rank=0, size=4) >>> # Returns subset of points for MPI rank 0 out of 4 processes
Notes
The class assumes that theoretical spectra are provided for all parameter combinations in the grid. Missing spectra will raise errors during likelihood computation.
- __init__(core_params, parameter_ranges, theoretical_spectra=None, root_dir=None, root_filename=None, lmax_signal=None)[source]
Initialize parameter grid.
- Parameters:
core_params (InputParams) – Analysis parameters containing nside, lmax, etc.
parameter_ranges (dict[str, np.ndarray]) – Dictionary mapping parameter names to value arrays.
theoretical_spectra (dict[tuple, np.ndarray]) – Dictionary mapping parameter tuples to power spectra.
root_dir (str, optional) – Directory containing theoretical spectra files.
root_filename (str, optional) – Root filename for theoretical spectra.
lmax_signal (int, optional) – Maximum multipole for signal computation. If None, uses 4*nside. This ensures spectra are read with the correct lmax even when analysis lmax differs from signal lmax.
- Raises:
ValueError – If parameter ranges are empty or inconsistent with spectra.
- read_theoretical_spectra()[source]
Read theoretical spectra from files, blending with the fiducial in the inference window per ADR 0009.
- Return type:
Notes
For each grid point, loads the parameter-dependent spectrum and (if a fiducial file is configured) replaces multipoles outside the inference window
[lmin, lmax]with the fiducial values. The inference window is read fromcore_params.lminandcore_params.lmax; if either is missing, the fiducial blend is skipped (full parameter spectrum used).
- get_total_points()[source]
Get total number of points in the parameter grid.
- Returns:
total_points – Total number of parameter combinations in the grid.
- Return type:
- get_points_for_process(rank, size)[source]
Get parameter points assigned to a specific MPI process.
- Parameters:
- Returns:
process_points – Parameter points assigned to this process.
- Return type:
Notes
Distributes parameter grid points as evenly as possible across MPI processes. Uses simple round-robin assignment to ensure load balance.
- get_spectrum(param_point)[source]
Get theoretical spectrum for a parameter point.
- Parameters:
param_point (tuple) – Parameter values as a tuple in the order of parameter_names.
- Returns:
spectrum – Theoretical power spectrum for the given parameters.
- Return type:
- Raises:
KeyError – If no spectrum exists for the given parameter point.
Notes
Retrieves the pre-computed theoretical power spectrum corresponding to the specified parameter combination. The spectrum is used for signal covariance matrix computation in likelihood analysis.
- get_parameter_dict(param_point)[source]
Convert parameter tuple to named dictionary.
- Parameters:
param_point (tuple) – Parameter values as a tuple.
- Returns:
param_dict – Dictionary mapping parameter names to values.
- Return type:
Examples
>>> grid = ParameterGrid(param_ranges, spectra) >>> point = (0.022, 0.12) # (omega_b, omega_c) >>> param_dict = grid.get_parameter_dict(point) >>> # Returns {'omega_b': 0.022, 'omega_c': 0.12}
- get_grid_shape()[source]
Get shape of the parameter grid.
- Returns:
grid_shape – Shape of the grid with dimensions corresponding to each parameter.
- Return type:
Notes
Returns the shape of the regular grid formed by the parameter ranges. Useful for reshaping results into multidimensional arrays for visualization and analysis.
- get_parameter_index(param_point)[source]
Get flat index of a parameter point in the grid.
- Parameters:
param_point (tuple) – Parameter values as a tuple.
- Returns:
index – Flat index of the parameter point in the grid.
- Return type:
- Raises:
ValueError – If the parameter point is not found in the grid.
Notes
Converts multidimensional parameter coordinates to a flat index, useful for indexing into result arrays and mapping between parameter space and result storage.
- add_spectrum(param_point, spectrum)[source]
Add theoretical spectrum for a parameter point.
- Parameters:
param_point (tuple) – Parameter values as a tuple.
spectrum (numpy.ndarray) – Theoretical power spectrum to add.
- Return type:
Notes
Allows dynamic addition of theoretical spectra to the grid. Useful for cases where spectra are computed on-the-fly or loaded incrementally.
- __iter__()[source]
Iterate over parameter points in the grid.
- __eq__(other)[source]
Check equality with another ParameterGrid.
Key Methods
Initialization
- ParameterGrid.__init__(core_params, parameter_ranges, theoretical_spectra=None, root_dir=None, root_filename=None, lmax_signal=None)[source]
Initialize parameter grid.
- Parameters:
core_params (InputParams) – Analysis parameters containing nside, lmax, etc.
parameter_ranges (dict[str, np.ndarray]) – Dictionary mapping parameter names to value arrays.
theoretical_spectra (dict[tuple, np.ndarray]) – Dictionary mapping parameter tuples to power spectra.
root_dir (str, optional) – Directory containing theoretical spectra files.
root_filename (str, optional) – Root filename for theoretical spectra.
lmax_signal (int, optional) – Maximum multipole for signal computation. If None, uses 4*nside. This ensures spectra are read with the correct lmax even when analysis lmax differs from signal lmax.
- Raises:
ValueError – If parameter ranges are empty or inconsistent with spectra.
Spectrum Access
Usage Examples
Creating a Parameter Grid
import numpy as np
from picslike import ParameterGrid
from cosmocore import InputParams
# Define core parameters
core_params = InputParams()
core_params.update({
"nside": 512,
"lmax": 1000,
"spins": [0, 2],
"labels": ["T", "E", "B"],
})
# Define parameter ranges
param_ranges = {
"omega_b": np.linspace(0.020, 0.025, 11),
"omega_c": np.linspace(0.10, 0.14, 11),
}
# Pre-compute theoretical spectra for each parameter combination
theoretical_spectra = {}
for omega_b in param_ranges["omega_b"]:
for omega_c in param_ranges["omega_c"]:
# Compute spectra using your Boltzmann code
spectra = compute_spectra(omega_b, omega_c)
theoretical_spectra[(omega_b, omega_c)] = spectra
# Create parameter grid
grid = ParameterGrid(
core_params=core_params,
parameter_ranges=param_ranges,
theoretical_spectra=theoretical_spectra,
)
print(f"Total grid points: {grid.get_total_points()}")
MPI Work Distribution
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
# Get points assigned to this process
my_points = grid.get_points_for_process(rank, size)
print(f"Process {rank}: handling {len(my_points)} parameter points")
for point in my_points:
# Get theoretical spectra for this point
spectra = grid.get_theoretical_spectra(point)
# Compute likelihood at this point...
Iterating Over Grid Points
# Iterate over all grid points
for point in grid.grid_points:
omega_b, omega_c = point
spectra = grid.get_theoretical_spectra(point)
print(f"Point ({omega_b:.4f}, {omega_c:.4f}): {len(spectra)} spectra")
Grid Properties
The ParameterGrid stores:
parameter_ranges: Dictionary mapping parameter names to value arrays
grid_points: Set of all parameter combinations as tuples
theoretical_spectra: Dictionary mapping parameter tuples to spectrum dictionaries
Spectrum Format
Theoretical spectra should be provided as dictionaries with keys for each spectrum type:
spectra = {
"TT": cl_tt, # Temperature auto-spectrum
"EE": cl_ee, # E-mode auto-spectrum
"BB": cl_bb, # B-mode auto-spectrum
"TE": cl_te, # Temperature-E cross-spectrum
"TB": cl_tb, # Temperature-B cross-spectrum (usually zero)
"EB": cl_eb, # E-B cross-spectrum (usually zero)
}
Each spectrum should be a 1D numpy array indexed by multipole \(\ell\).
See Also
picslike.picslike.PICSLike: Main likelihood computation classpicslike.likelihood_result.LikelihoodResult: Results container