Bayesian-Inference API
Unified PyXspec Bayesian-inference API.
Provides a single shared BaseResult interface across two samplers, plus convenience wrappers for invoking them from Python:
runChain(...) -> ChainResult (Metropolis-Hastings / Goodman-Weare)
- runHMC(...) -> HMCResult (HMC/NUTS with warmup, mass adapt,
multi-chain, resume)
All result objects expose samples, param_labels, file_name, an __repr__, and a .to_arviz() method. Per-sampler attributes (eps_adapted/mass_diag/divergent on HMCResult, etc.) are layered on top.
arviz is an optional dependency: .to_arviz() imports it lazily and raises with an install hint if missing.
Usage:
import xspec
xspec.AllData.dummyrsp(0.5, 7.0, 200)
m = xspec.Model("powerlaw")
xspec.AllData.fakeit(1, xspec.FakeitSettings(exposure=3.0e4))
xspec.Fit.perform()
res = xspec.runHMC("hmc.fits", samples=500, warmup=500, chains=4)
print(res)
idata = res.to_arviz() # requires `pip install arviz`
- class xspec.BaseResult
Common interface for HMCResult / ChainResult.
Attributes
file_name: str
- samplesnp.ndarray of shape (N, P) (post-burn-in, all chains
concatenated chain-major where applicable)
param_labels: list[str] of length P
n_chains : int (1 for nest single-chain output / MH single chain)
- chain_idsnp.ndarray[int] of length N (constant 0 for nest /
single-chain MH)
- log_postnp.ndarray of length N (per-sample log posterior,
or -0.5 * statistic where stat is being used as a log-likelihood surrogate)
- sample_statsdict[str, np.ndarray] of length-N arrays for
additional per-sample diagnostics (e.g. {"diverging": ..., "tree_depth": ...} on HMCResult). Keys are arviz-friendly.
- summary()
Return a dict[str, dict] keyed by parameter, holding mean/std/q05/q95 of each parameter across all samples (no chain stratification).
- to_arviz()
Return an arviz.InferenceData built from this result.
posterior: (chain, draw, param). sample_stats: per-sample diagnostics with arviz-canonical names (diverging, tree_depth, lp). Single- chain results carry a chain dimension of length 1.
Raises ImportError if arviz is not installed. Install with pip install arviz.
- class xspec.HMCResult(file_name)
HMC/NUTS sampler output.
Reads a FITS file written by the hmc run command (or equivalently the runHMC helper below). Exposes the chain-major samples plus per-sample diagnostics (divergence, NUTS tree depth, chain id), the per-chain adapted (eps, mass) from HMC_ADAPT, and the aggregate run stats from the CHAIN header keywords.
Attributes (In addition to BaseResult attributes)
statistic: np.ndarray
divergent: np.ndarray
tree_depth: np.ndarray
mass_diag:
eps_adapted: float
n_divergent: int
n_accepted: int
mean_accept: float
n_grad: int
termination: str
- class xspec.ChainResult(file_name)
Output of the existing chain command (Metropolis-Hastings or Goodman-Weare). Reads the FITS file written by chain run / loaded into AllChains.
No HMC-specific diagnostics (eps_adapted / mass_diag are absent) and no chain stratification beyond what the FITS file carries (Goodman-Weare's walker partition is preserved when present in the file, otherwise n_chains=1).
Attributes (In addition to BaseResult attributes)
statistic: np.ndarray
chain_type: str
termination: str
- xspec.runHMC(file_name, samples=None, warmup=None, chains=None, stepsize=None, target_accept=None, maxdepth=None, adapt=None, checkpoint=None, divergence_threshold=None, overwrite=True)
Run HMC/NUTS and return an HMCResult.
Arguments left as
None(the default) inherit the currentHmcState-- i.e. whatever value the user has set with thehmc <param> <value>command at the XSPEC prompt or in a previousrunHMCcall. This avoids silently regressing a previously configured setting (e.g.hmc target_accept 0.95) just because the caller didn't pass it. The on-prompt defaults are: samples=1000, warmup=1000, chains=4, stepsize=0.05, target_accept=0.8, maxdepth=10, adapt=True, checkpoint=200, divergence_threshold=1000.- Args:
- file_namestr, FITS output path. ! prefix
semantics handled via overwrite=True.
samples : int or None. Post-warmup samples per chain.
warmup : int or None. Warmup iterations per chain.
- chainsint or None. Number of independent chains.
Concurrency gated by
parallel hmc <N>.- stepsizefloat or None. Initial leapfrog step.
Dual-averaging adapts this during warmup.
- target_acceptfloat or None. Stan-default 0.8 dual-
averaging target. Higher (0.95) for hard posteriors, lower (0.6) for fast exploration.
maxdepth : int or None. NUTS max tree depth.
- adaptbool or None. Master switch for warmup
adaptation. False = fixed eps + identity mass.
- checkpointint or None. Per-chain ckpt interval
(0 disables).
- divergence_thresholdfloat or None. Hamiltonian energy-error
cutoff (Stan default 1000).
- overwritebool, if True force fresh run and discard
any per-chain ckpts at file_name. If False, an interrupted run with compatible ckpts auto-resumes.
- Returns:
HMCResult.
- Raises:
Exception if hmc run refuses (N1 gradient guard, structural rejection) or fails. Exceptions are propagated unchanged from the C++ orchestrator.
- xspec.runChain(file_name, length=None, walkers=None, burn=None, algorithm=None, proposal=None, temperature=None, rand=None, rescale=None)
Run a Metropolis-Hastings or Goodman-Weare chain and return a ChainResult.
Thin wrapper around the existing xspec.Chain class that exists for API symmetry with runHMC / runNested. All keyword arguments default to the current AllChains defaults (see AllChains global).
- Args:
file_name : str, FITS output path.
length : int, total chain length post-burn-in.
walkers : int, Goodman-Weare walker count (must be even).
burn : int, burn-in steps to discard.
algorithm : str, "mh" or "gw".
proposal : str, proposal mechanism (see chain proposal).
temperature : float, simulated tempering temperature.
rand : bool, whether to randomize the start point.
rescale : bool, rescale by parameter standard errors.
- Returns:
ChainResult.