astrocook.fitting.bayesian_fitter module#

astrocook.fitting.bayesian_fitter.require_bayes_engine(engine: str = 'mcmc') → None[source]#

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.

class astrocook.fitting.bayesian_fitter.BayesianVoigtFitter(spec: Any, systs: Any, z_window_kms: float = 20.0)[source]#

Bases: object

Bayesian engine for Voigt profile fitting.

This class wraps a 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.

__init__(spec: Any, systs: Any, z_window_kms: float = 20.0)[source]#
ln_likelihood(p_free: ndarray) → float[source]#

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:

The computed log-likelihood, or -np.inf if evaluation fails.

Return type:

float

ln_prior(p_free: ndarray) → float[source]#

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:

0.0 if the parameters are within physical bounds, -np.inf otherwise.

Return type:

float

ln_posterior(p_free: ndarray) → float[source]#

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:

The log-posterior probability, or -np.inf if outside prior bounds.

Return type:

float

run_mcmc(nwalkers: int | None = None, nsteps: int = 1000, burn_in: int | None = None, progress: bool = True, seed: int | None = None) → Dict[str, Any][source]#

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:

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).

Return type:

dict

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.

run_nested(nlive: int = 250, progress: bool = True, seed: int | None = None) → Dict[str, Any][source]#

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:

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).

Return type:

dict

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.

apply_results(res: Dict[str, Any]) → Any[source]#

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 run_mcmc() or run_nested().

Returns:

A new system list containing the updated parameters and Bayesian errors.

Return type:

SystemList