Source code for astrocook.fitting.bayesian_fitter

import logging
import warnings

import numpy as np
from typing import Collection, Dict, Any, Optional
from .voigt_fitter import VoigtFitter

try:
    import emcee
except ImportError:
    emcee = None

try:
    import dynesty
except ImportError:
    dynesty = None

logger = logging.getLogger(__name__)

# emcee, dynesty and corner are optional dependencies (extra "bayes")
BAYES_INSTALL_HINT = 'pip install "astrocook[bayes]"'


[docs] def require_bayes_engine(engine: str = 'mcmc') -> None: """Raise an ImportError naming the extra if the sampler is not installed. Parameters ---------- engine : {'mcmc', 'nested'}, optional The sampling engine: ``'mcmc'`` needs ``emcee``, ``'nested'`` needs ``dynesty``. """ name, module = (('dynesty', dynesty) if engine.lower() == 'nested' else ('emcee', emcee)) if module is None: raise ImportError( f"The Bayesian fit needs {name}, which is not installed. " f"Install the optional dependencies with: {BAYES_INSTALL_HINT}")
def _log_warnings(caught: list) -> None: """The warnings caught while sampling, to the log: those of dynesty as WARNING lines, once each; the others raised again as they were.""" seen = set() for w in caught: if 'dynesty' in str(w.filename): text = str(w.message) if text not in seen: seen.add(text) logger.warning(f"dynesty: {text}") else: warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
[docs] class BayesianVoigtFitter: """ Bayesian engine for Voigt profile fitting. This class wraps a :class:`~astrocook.fitting.voigt_fitter.VoigtFitter` instance to perform Markov Chain Monte Carlo (MCMC) or Nested Sampling using the exact same physical model, constraints, and data preparation. Parameters ---------- spec : Spectrum The spectral data to fit. systs : SystemList The system list containing the components to model. z_window_kms : float, optional Velocity window (km/s) around component centers to include in the fit mask. Defaults to ``20.0``. """
[docs] def __init__(self, spec: Any, systs: Any, z_window_kms: float = 20.0): self.spec = spec self.systs = systs self.z_window_kms = z_window_kms # We need a VoigtFitter instance to handle the model and constraints self.fitter = VoigtFitter(self.spec, self.systs) # Prepare the data context from the standard fitter self.lower_bounds, self.upper_bounds = self.fitter.prepare_fit_context(z_window_kms=z_window_kms) self.ctx = self.fitter.get_fit_context_data() self.p_initial = self.fitter._constraints.p_free_vector self.ndim = len(self.p_initial)
[docs] def ln_likelihood(self, p_free: np.ndarray) -> float: """ Compute the log-likelihood of a parameter vector. Evaluates the standard Gaussian log-likelihood for the active fit region, incorporating any penalty terms (e.g., Doppler parameter runaways) inherited from the frequentist fitter. Parameters ---------- p_free : np.ndarray The vector of free parameters to evaluate. Returns ------- float The computed log-likelihood, or ``-np.inf`` if evaluation fails. """ try: model = self.ctx['compute_model'](p_free) # Only use pixels in the dynamic mask mask = self.ctx['mask'] resid = (self.ctx['y'][mask] - model[mask]) / self.ctx['dy'][mask] # Additional penalty terms from Frequentist fitter (e.g. b-parameter runaway) # To match the logic of VoigtFitter._residual_function p_full = self.fitter._constraints.map_p_free_to_full(p_free) is_free_mask = self.fitter._constraints._param_map['is_free'] num_params = 4 penalty_chi2 = 0.0 for i in range(len(p_full) // num_params): idx_b = i * num_params + 2 if is_free_mask[idx_b]: b_val = p_full[idx_b] if b_val > 50.0: penalty_chi2 += (5.0 * (b_val - 50.0))**2 return -0.5 * (np.sum(resid**2) + penalty_chi2) except (ValueError, ArithmeticError): # A model that cannot be evaluated has zero likelihood: the # sampler moves on (ValueError covers np.linalg.LinAlgError) return -np.inf
[docs] def ln_prior(self, p_free: np.ndarray) -> float: """ Compute the log-prior probability of a parameter vector. Applies a uniform flat prior defined by the physical boundaries of the free parameters (e.g., column density between 10.0 and 23.0). Parameters ---------- p_free : np.ndarray The vector of free parameters. Returns ------- float ``0.0`` if the parameters are within physical bounds, ``-np.inf`` otherwise. """ if np.any(p_free < self.lower_bounds) or np.any(p_free > self.upper_bounds): return -np.inf return 0.0 # Log of 1/Volume is constant, so we can use 0 for simplicity
[docs] def ln_posterior(self, p_free: np.ndarray) -> float: """ Compute the total log-posterior probability. Calculates the sum of the log-prior and log-likelihood. Parameters ---------- p_free : np.ndarray The vector of free parameters. Returns ------- float The log-posterior probability, or ``-np.inf`` if outside prior bounds. """ lp = self.ln_prior(p_free) if not np.isfinite(lp): return -np.inf return lp + self.ln_likelihood(p_free)
[docs] def run_mcmc(self, nwalkers: Optional[int] = None, nsteps: int = 1000, burn_in: Optional[int] = None, progress: bool = True, seed: Optional[int] = None) -> Dict[str, Any]: """ Execute Markov Chain Monte Carlo (MCMC) sampling using ``emcee``. Initializes walkers around the initial parameter guess and samples the posterior distribution. Parameters ---------- nwalkers : int, optional Number of MCMC walkers. Defaults to ``max(32, 2 * ndim)``: emcee needs at least twice as many walkers as free parameters, so the 32 walkers of before were enough up to 16 free parameters only (F141, phase 6-quater, PR 10-bis); up to 16 the sampling is the same as before. A value below ``2 * ndim`` is refused. nsteps : int, optional Number of sampling steps per walker. Defaults to ``1000``. burn_in : int, optional Number of initial steps to discard as burn-in. Defaults to ``min(200, nsteps // 2)``, so that at least half of the chain is kept. Must be smaller than ``nsteps``. progress : bool, optional If True, pipes progress percentage to the logger. Defaults to ``True``. seed : int, optional Seed of the random numbers (the starting walkers and the moves), for a sampling that can be repeated. Defaults to ``None``: the global generator of NumPy, as before the parameter existed. Returns ------- dict A dictionary containing: - ``'samples'``: The flattened, burn-in discarded chain (np.ndarray). - ``'sampler'``: The raw ``emcee.EnsembleSampler`` object. - ``'medians'``: The median values for each parameter (np.ndarray). - ``'std'``: The standard deviations for each parameter (np.ndarray). Raises ------ ImportError If the ``emcee`` package is not installed. ValueError If ``nsteps < 1``, ``burn_in`` is not smaller than ``nsteps`` (the chain left after the burn-in would be empty), or ``nwalkers`` is less than twice the free parameters. """ require_bayes_engine('mcmc') if nwalkers is None: nwalkers = max(32, 2 * self.ndim) if nwalkers < 2 * self.ndim: raise ValueError( f"nwalkers ({nwalkers}) must be at least twice the free " f"parameters ({self.ndim}).") if nsteps < 1: raise ValueError(f"nsteps must be at least 1 (got {nsteps}).") if burn_in is None: burn_in = min(200, nsteps // 2) if not 0 <= burn_in < nsteps: raise ValueError( f"burn_in ({burn_in}) must be between 0 and nsteps - 1 " f"(nsteps = {nsteps}).") # Initialize walkers in a small cluster around the best-fit / initial guess # We add some noise but stay within bounds # Without a seed, the global generator of NumPy (emcee copies its # state), as before the parameter existed rng = np.random.RandomState(seed) if seed is not None else np.random pos: Any = [] for _ in range(nwalkers): p = self.p_initial + 1e-4 * rng.randn(self.ndim) p = np.clip(p, self.lower_bounds + 1e-8, self.upper_bounds - 1e-8) pos.append(p) pos = np.array(pos) sampler = emcee.EnsembleSampler(nwalkers, self.ndim, self.ln_posterior) if seed is not None: sampler.random_state = rng.get_state() logger.info(f"Sampling with emcee: {nwalkers} walkers, {nsteps} steps.") if progress: # We use manual iteration instead of run_mcmc to pipe progress to the GUI via logging # Astrocook's RecipeProgressDialog looks for '>> PROGRESS: X' messages update_interval = max(1, nsteps // 100) for i, _ in enumerate(sampler.sample(pos, iterations=nsteps, progress=False)): # Update GUI every 1% or at least every step if i % update_interval == 0: pct = int(100 * i / nsteps) logger.info(f">> PROGRESS: {pct}") logger.info(">> PROGRESS: 100") else: sampler.run_mcmc(pos, nsteps, progress=False) # Process results flat_samples = sampler.get_chain(discard=burn_in, flat=True) return { 'samples': flat_samples, 'sampler': sampler, 'medians': np.median(flat_samples, axis=0), 'std': np.std(flat_samples, axis=0) }
[docs] def run_nested(self, nlive: int = 250, progress: bool = True, seed: Optional[int] = None) -> Dict[str, Any]: """ Execute Nested Sampling using ``dynesty``. Samples the parameter space to estimate both the posterior distribution and the Bayesian evidence (log-Z). Parameters ---------- nlive : int, optional Number of live points for the nested sampler. Defaults to ``250``. progress : bool, optional If True, pipes progress (dLogZ) to the logger. Defaults to ``True``. seed : int, optional Seed of the random numbers of the sampler, for a sampling that can be repeated. Defaults to ``None`` (not repeatable). Returns ------- dict A dictionary containing: - ``'results'``: The raw ``dynesty`` results object. - ``'logz'``: The estimated log-evidence. - ``'logzerr'``: The error on the log-evidence. - ``'samples'``: Samples of the posterior with equal weights (``samples_equal`` of dynesty), e.g. for a corner plot. - ``'medians'``: The weighted medians of the parameters (np.ndarray). - ``'std'``: The weighted standard deviations of the parameters (np.ndarray). Notes ----- The points of a nested sampling are not a sample of the posterior: each has its importance weight. The medians and standard deviations were taken from the points without the weights, and came out too wide (on a CIV component, 1.7 in logN and 42 km/s in b instead of 0.005 and 0.14, which the MCMC gives): F140, phase 6-quater, PR 10-bis. Raises ------ ImportError If the ``dynesty`` package is not installed. """ require_bayes_engine('nested') def prior_transform(u): """Transform uniform unit cube to physical bounds.""" return self.lower_bounds + (self.upper_bounds - self.lower_bounds) * u rstate = np.random.default_rng(seed) if seed is not None else None # dynesty warns about the efficiency of its bounds (and other # things the user should know): to the log, once each, not as # warnings that a script or a test would turn into errors with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") dsampler = dynesty.NestedSampler(self.ln_likelihood, prior_transform, self.ndim, nlive=nlive, rstate=rstate) logger.info(f"Nested sampling with dynesty: {nlive} live points.") if progress: import time last_log_time = time.time() # Start manual sampling to safely pipe progress to GUI # We target dlogz=0.1 which is dynesty's standard default target_dlogz = 0.1 for i, it in enumerate(dsampler.sample(dlogz=target_dlogz)): if time.time() - last_log_time > 0.5: # The remaining evidence of this iteration (F139: # dsampler.dlogz, read before, is a dict in dynesty 3) dlogz = getattr(it, 'delta_logz', None) if isinstance(dlogz, (int, float, np.floating)): logger.info(f"Nested sampling, iteration {i}: dlogZ {dlogz:.2f} " f"(target {target_dlogz}).") else: logger.info(f"Nested sampling, iteration {i}.") last_log_time = time.time() # Finalize remaining live points logger.debug("Adding the final live points.") dsampler.add_live_points() else: dsampler.run_nested(print_progress=False) res = dsampler.results weights = res.importance_weights() equal = res.samples_equal(rstate=rstate) _log_warnings(caught) samples = res.samples medians = np.array([dynesty.utils.quantile(samples[:, k], [0.5], weights=weights)[0] for k in range(samples.shape[1])]) mean = np.average(samples, axis=0, weights=weights) std = np.sqrt(np.average((samples - mean) ** 2, axis=0, weights=weights)) return { 'results': res, 'logz': res.logz[-1], 'logzerr': res.logzerr[-1], 'samples': equal, 'medians': medians, 'std': std }
[docs] def apply_results(self, res: Dict[str, Any]) -> Any: """ Apply Bayesian medians and uncertainties back to the system list. Extracts the posterior medians and standard deviations, maps them back to the full parameter vector, and updates the corresponding components in the system list. Fixed or linked parameters maintain their prior state. Parameters ---------- res : dict The results dictionary returned by :meth:`run_mcmc` or :meth:`run_nested`. Returns ------- SystemList A new system list containing the updated parameters and Bayesian errors. """ medians = res['medians'] if 'medians' in res else np.median(res['samples'], axis=0) stds = res['std'] if 'std' in res else np.std(res['samples'], axis=0) # Map p_free back to full parameter vector p_full = self.fitter._constraints.map_p_free_to_full(medians) # Map uncertainties back to full vector (treating frozen as 0 uncertainty) dp_full = np.zeros_like(p_full) is_free_mask = self.fitter._constraints._param_map['is_free'] dp_full[is_free_mask] = stds # We only update components that were part of the active group # This ensures we don't accidentally reset/clear errors for other components new_systs = self.systs active_uuids: Optional[Collection[str]] = self.fitter._constraints._active_uuids if active_uuids is None: # If everything was active (no context), update everything active_uuids = [c.uuid for c in self.fitter._constraints._system_list.components] for uuid in active_uuids: # Find its offset in p_full idx = self.fitter._constraints._uuid_to_idx.get(uuid) if idx is not None: # Update basic parameters (medians) updates = { 'z': p_full[idx], 'logN': p_full[idx+1], 'b': p_full[idx+2], 'btur': p_full[idx+3] } # Update uncertainties ONLY for parameters that were free # Non-free parameters (Frozen or Linked) should keep their previous errors # or stay at None if they didn't have any. if is_free_mask[idx]: updates['dz'] = dp_full[idx] if is_free_mask[idx+1]: updates['dlogN'] = dp_full[idx+1] if is_free_mask[idx+2]: updates['db'] = dp_full[idx+2] if is_free_mask[idx+3]: updates['dbtur'] = dp_full[idx+3] new_systs = new_systs.update_component(uuid, **updates) return new_systs