bayespecon.diagnostics.bayesfactor.compile_log_posterior

bayespecon.diagnostics.bayesfactor.compile_log_posterior(pymc_model)[source]

Compile a PyMC model’s log-posterior into a callable for bridge sampling.

This is the Python equivalent of the R bridgesampling package’s automatic log_prob extraction from Stan models. The compiled function evaluates the full unnormalized log-posterior \(\log p(y \mid \theta) p(\theta)\) at any parameter vector, including all pm.Potential terms (e.g., Jacobians like \(\log|I - \rho W|\)).

Parameters:
pymc_model : pymc.Model

A compiled PyMC model object (e.g., model._pymc_model after calling fit()).

Returns:

  • log_posterior_fn (callable) – A function f(theta_flat) -> float that evaluates the log unnormalized posterior at a flat parameter vector in the unconstrained (transformed) space.

  • param_names (list of str) – Names of the free parameters in the unconstrained space (e.g., "sigma_log__" instead of "sigma"), matching the order in theta_flat.

  • param_info (dict) – Dict with keys "shapes" and "sizes" mapping parameter names to their shapes and total scalar sizes.

  • constrained_to_unconstrained (callable) – A function f(constrained_samples_dict) -> ndarray that converts a dict of constrained posterior samples (as stored in idata.posterior, keyed by original parameter names like "sigma") into a flat array in the unconstrained space, in the same order as param_names. This is needed because PyMC’s compile_logp() operates in the unconstrained space, but posterior samples are stored in the constrained space.

Examples

After fitting a model:

model = SAR(y=y, X=X, W=W)
model.fit(draws=2000, idata_kwargs={"log_likelihood": True})

logp_fn, names, info, to_unconstrained = compile_log_posterior(model.pymc_model)
# Convert constrained posterior samples to unconstrained space
theta = to_unconstrained(model.inference_data.posterior)
print(logp_fn(theta[0]))  # evaluate at first sample