LikelihoodResult Class
The LikelihoodResult class stores and analyzes the results of likelihood computations, providing methods for best-fit extraction, confidence intervals, and marginalization.
Overview
LikelihoodResult provides:
Storage of chi-squared and log-likelihood values across parameter grid
Best-fit parameter extraction from likelihood surface
Confidence interval computation via profile likelihood
Parameter marginalization for 1D posteriors
Result persistence and loading
Class Documentation
- class picslike.likelihood_result.LikelihoodResult(parameter_grid, chi_squared_values, log_likelihood_values)[source]
Bases:
objectContainer for pixel-based likelihood computation results.
This class stores and manages results from likelihood analysis, providing methods for result analysis, best-fit parameter extraction, confidence interval computation, and result persistence.
- Parameters:
parameter_grid (ParameterGrid) – Parameter grid used in the likelihood computation.
chi_squared_values (numpy.ndarray) – Chi-squared values for each parameter grid point.
log_likelihood_values (numpy.ndarray) – Log-likelihood values for each parameter grid point.
- parameter_grid
Parameter grid used in the computation.
- Type:
ParameterGrid
- chi_squared_values
Array of chi-squared values.
- Type:
- log_likelihood_values
Array of log-likelihood values.
- Type:
- likelihood_values
Array of likelihood values (exponential of log-likelihood).
- Type:
Examples
Basic result analysis:
>>> result = LikelihoodResult(grid, chi2_values, log_like_values) >>> best_fit = result.get_best_fit() >>> confidence_intervals = result.get_confidence_intervals() >>> result.save("analysis_results.pkl")
Statistical analysis:
>>> # Get 68% confidence intervals >>> intervals_68 = result.get_confidence_intervals(confidence_level=0.68) >>> # Get marginalized likelihood for specific parameter >>> marg_like = result.get_marginalized_likelihood('omega_b')
Notes
The class assumes that likelihood values correspond to parameter grid points in the same order. It provides both chi-squared and likelihood perspectives on the same underlying computation.
- __init__(parameter_grid, chi_squared_values, log_likelihood_values)[source]
Initialize likelihood result container.
- Parameters:
parameter_grid (ParameterGrid) – Parameter grid used in the likelihood computation.
chi_squared_values (numpy.ndarray) – Chi-squared values for each parameter grid point.
log_likelihood_values (numpy.ndarray) – Log-likelihood values for each parameter grid point.
- Raises:
ValueError – If array dimensions are inconsistent with parameter grid.
- get_best_fit()[source]
Get best-fit parameter values.
- Returns:
best_fit_params – Dictionary mapping parameter names to their best-fit values.
- Return type:
Notes
Returns the parameter combination with the highest likelihood (lowest chi-squared value). In case of ties, returns the first occurrence.
- get_chi_squared_minimum()[source]
Get minimum chi-squared value.
- Returns:
chi_squared_min – Minimum chi-squared value in the analysis.
- Return type:
- get_maximum_likelihood()[source]
Get maximum likelihood value.
- Returns:
likelihood_max – Maximum likelihood value in the analysis.
- Return type:
- get_confidence_intervals(confidence_level=0.68)[source]
Compute confidence intervals for each parameter.
- Parameters:
confidence_level (float, optional) – Confidence level for interval computation (default: 0.68 for 1σ).
- Returns:
confidence_intervals – Dictionary mapping parameter names to (lower, upper) confidence bounds.
- Return type:
Notes
Computes confidence intervals by finding parameter ranges that contain the specified fraction of the total likelihood. Uses marginalized likelihood distributions for each parameter.
- get_marginalized_likelihood(parameter_name)[source]
Get marginalized likelihood for a specific parameter.
- Parameters:
parameter_name (str) – Name of the parameter to marginalize over.
- Returns:
marginalized_likelihood – Marginalized likelihood distribution for the parameter.
- Return type:
- Raises:
ValueError – If parameter name is not found in the grid.
Notes
Computes the marginalized likelihood by integrating (summing) over all other parameters in the grid. The result is normalized to unit area under the curve.
- save(output_path)[source]
Save likelihood results to file.
Notes
Saves the complete LikelihoodResult object using pickle format. The saved file can be loaded later for further analysis or visualization.
- classmethod load(input_path)[source]
Load likelihood results from file.
- Parameters:
input_path (str or Path) – Path to saved results file.
- Returns:
result – Loaded likelihood result object.
- Return type:
LikelihoodResult
- Raises:
FileNotFoundError – If the input file does not exist.
- get_summary_statistics()[source]
Get summary statistics for the likelihood analysis.
- Returns:
summary – Dictionary containing summary statistics including best-fit values, chi-squared minimum, and confidence intervals.
- Return type:
Notes
Provides a comprehensive summary of the analysis results suitable for reporting and quick interpretation of the results.
Key Methods
Initialization
- LikelihoodResult.__init__(parameter_grid, chi_squared_values, log_likelihood_values)[source]
Initialize likelihood result container.
- Parameters:
parameter_grid (ParameterGrid) – Parameter grid used in the likelihood computation.
chi_squared_values (numpy.ndarray) – Chi-squared values for each parameter grid point.
log_likelihood_values (numpy.ndarray) – Log-likelihood values for each parameter grid point.
- Raises:
ValueError – If array dimensions are inconsistent with parameter grid.
Best-Fit Analysis
- LikelihoodResult.get_best_fit()[source]
Get best-fit parameter values.
- Returns:
best_fit_params – Dictionary mapping parameter names to their best-fit values.
- Return type:
Notes
Returns the parameter combination with the highest likelihood (lowest chi-squared value). In case of ties, returns the first occurrence.
- LikelihoodResult.get_chi_squared_minimum()[source]
Get minimum chi-squared value.
- Returns:
chi_squared_min – Minimum chi-squared value in the analysis.
- Return type:
Statistical Analysis
- LikelihoodResult.get_confidence_intervals(confidence_level=0.68)[source]
Compute confidence intervals for each parameter.
- Parameters:
confidence_level (float, optional) – Confidence level for interval computation (default: 0.68 for 1σ).
- Returns:
confidence_intervals – Dictionary mapping parameter names to (lower, upper) confidence bounds.
- Return type:
Notes
Computes confidence intervals by finding parameter ranges that contain the specified fraction of the total likelihood. Uses marginalized likelihood distributions for each parameter.
- LikelihoodResult.get_marginalized_likelihood(parameter_name)[source]
Get marginalized likelihood for a specific parameter.
- Parameters:
parameter_name (str) – Name of the parameter to marginalize over.
- Returns:
marginalized_likelihood – Marginalized likelihood distribution for the parameter.
- Return type:
- Raises:
ValueError – If parameter name is not found in the grid.
Notes
Computes the marginalized likelihood by integrating (summing) over all other parameters in the grid. The result is normalized to unit area under the curve.
- LikelihoodResult.get_summary_statistics()[source]
Get summary statistics for the likelihood analysis.
- Returns:
summary – Dictionary containing summary statistics including best-fit values, chi-squared minimum, and confidence intervals.
- Return type:
Notes
Provides a comprehensive summary of the analysis results suitable for reporting and quick interpretation of the results.
Persistence
- LikelihoodResult.save(output_path)[source]
Save likelihood results to file.
Notes
Saves the complete LikelihoodResult object using pickle format. The saved file can be loaded later for further analysis or visualization.
- classmethod LikelihoodResult.load(input_path)[source]
Load likelihood results from file.
- Parameters:
input_path (str or Path) – Path to saved results file.
- Returns:
result – Loaded likelihood result object.
- Return type:
LikelihoodResult
- Raises:
FileNotFoundError – If the input file does not exist.
Usage Examples
Creating a LikelihoodResult
import numpy as np
from picslike import LikelihoodResult, ParameterGrid
# Assuming you have a parameter grid and computed chi-squared values
chi2_values = np.array([...]) # Chi-squared at each grid point
log_like_values = -0.5 * chi2_values
result = LikelihoodResult(
parameter_grid=grid,
chi_squared_values=chi2_values,
log_likelihood_values=log_like_values,
)
Extracting Best-Fit Parameters
# Get best-fit parameter values
best_fit = result.get_best_fit()
print(f"Best-fit omega_b: {best_fit['omega_b']:.5f}")
print(f"Best-fit omega_c: {best_fit['omega_c']:.4f}")
# Get minimum chi-squared
chi2_min = result.get_chi_squared_minimum()
print(f"Minimum chi-squared: {chi2_min:.2f}")
Computing Confidence Intervals
# 68% confidence intervals (1-sigma)
intervals_68 = result.get_confidence_intervals(0.68)
for param, (lower, upper) in intervals_68.items():
print(f"{param}: [{lower:.5f}, {upper:.5f}]")
# 95% confidence intervals (2-sigma)
intervals_95 = result.get_confidence_intervals(0.95)
Marginalizing Over Parameters
# Get 1D marginalized likelihood for omega_b
marg_omega_b = result.get_marginalized_likelihood("omega_b")
# Plot marginalized likelihood
import matplotlib.pyplot as plt
omega_b_values = grid.parameter_ranges["omega_b"]
plt.plot(omega_b_values, marg_omega_b)
plt.xlabel(r"$\Omega_b$")
plt.ylabel("Marginalized Likelihood")
plt.show()
Summary Statistics
# Get comprehensive summary
summary = result.get_summary_statistics()
print(f"Number of parameters: {summary['n_parameters']}")
print(f"Total grid points: {summary['n_grid_points']}")
print(f"Chi-squared minimum: {summary['chi2_min']:.2f}")
print(f"Best-fit values: {summary['best_fit']}")
Saving and Loading Results
# Save results to file
result.save("output/likelihood_results.npz")
# Load results from file
loaded_result = LikelihoodResult.load("output/likelihood_results.npz")
# Verify loaded correctly
assert loaded_result.get_chi_squared_minimum() == result.get_chi_squared_minimum()
Result Format
The LikelihoodResult stores:
parameter_grid: The ParameterGrid used for computation
chi_squared_values: 1D array of chi-squared values indexed by grid point
log_likelihood_values: 1D array of log-likelihood values
File Format
Results are saved in NumPy’s compressed archive format (.npz):
# Contents of saved file
{
"chi_squared_values": np.ndarray,
"log_likelihood_values": np.ndarray,
"parameter_names": list,
"parameter_ranges": dict,
# ... additional metadata
}
Statistical Notes
Confidence Intervals
Confidence intervals are computed using the profile likelihood method:
For a single parameter, the confidence levels correspond to:
68% (1σ): \(\Delta \chi^2 < 1.0\)
95% (2σ): \(\Delta \chi^2 < 4.0\)
99% (3σ): \(\Delta \chi^2 < 9.0\)
Marginalization
Marginalized likelihoods are computed by integrating over nuisance parameters:
For grid-based evaluation, this is approximated as a sum over grid points.
See Also
picslike.picslike.PICSLike: Main likelihood computation classpicslike.parameter_grid.ParameterGrid: Parameter space management