code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def update( adaptation_state: WindowAdaptationState, adaptation_stage: tuple, position: ArrayLikeTree, acceptance_rate: float, ) -> WindowAdaptationState: """Update the adaptation state and parameter values. Parameters ---------- adaptation_state ...
Update the adaptation state and parameter values. Parameters ---------- adaptation_state Current adptation state. adaptation_stage The current stage of the warmup: whether this is a slow window, a fast window and if we are at the last step of a slow w...
update
python
blackjax-devs/blackjax
blackjax/adaptation/window_adaptation.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py
Apache-2.0
def final(warmup_state: WindowAdaptationState) -> tuple[float, Array]: """Return the final values for the step size and mass matrix.""" step_size = jnp.exp(warmup_state.ss_state.log_step_size_avg) inverse_mass_matrix = warmup_state.imm_state.inverse_mass_matrix return step_size, inverse_...
Return the final values for the step size and mass matrix.
final
python
blackjax-devs/blackjax
blackjax/adaptation/window_adaptation.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py
Apache-2.0
def window_adaptation( algorithm, logdensity_fn: Callable, is_mass_matrix_diagonal: bool = True, initial_step_size: float = 1.0, target_acceptance_rate: float = 0.80, progress_bar: bool = False, adaptation_info_fn: Callable = return_all_adapt_info, integrator=mcmc.integrators.velocity_ve...
Adapt the value of the inverse mass matrix and step size parameters of algorithms in the HMC fmaily. See Blackjax.hmc_family Algorithms in the HMC family on a euclidean manifold depend on the value of at least two parameters: the step size, related to the trajectory integrator, and the mass matrix, lin...
window_adaptation
python
blackjax-devs/blackjax
blackjax/adaptation/window_adaptation.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py
Apache-2.0
def build_schedule( num_steps: int, initial_buffer_size: int = 75, final_buffer_size: int = 50, first_window_size: int = 25, ) -> list[tuple[int, bool]]: """Return the schedule for Stan's warmup. The schedule below is intended to be as close as possible to Stan's :cite:p:`stan_hmc_param`. T...
Return the schedule for Stan's warmup. The schedule below is intended to be as close as possible to Stan's :cite:p:`stan_hmc_param`. The warmup period is split into three stages: 1. An initial fast interval to reach the typical set. Only the step size is adapted in this window. 2. "Slow" parameter...
build_schedule
python
blackjax-devs/blackjax
blackjax/adaptation/window_adaptation.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py
Apache-2.0
def build_kernel( logdensity_fn: Callable, integrator: Callable = integrators.isokinetic_mclachlan, divergence_threshold: float = 1000, inverse_mass_matrix=1.0, ): """Build an MHMCHMC kernel where the number of integration steps is chosen randomly. Parameters ---------- integrator ...
Build an MHMCHMC kernel where the number of integration steps is chosen randomly. Parameters ---------- integrator The integrator to use to integrate the Hamiltonian dynamics. divergence_threshold Value of the difference in energy above which we consider that the transition is divergent...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: HMCState, step_size: float, num_integration_steps: int, L_proposal_factor: float = jnp.inf, ) -> tuple[HMCState, HMCInfo]: """Generate a new sample with the MHMCHMC kernel.""" key_momentum, key_integrator = jax.random.spli...
Generate a new sample with the MHMCHMC kernel.
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, L_proposal_factor: float = jnp.inf, inverse_mass_matrix=1.0, *, divergence_threshold: int = 1000, integrator: Callable = integrators.isokinetic_mclachlan, num_integration_steps, ) -> SamplingAlgorithm: """Implements the...
Implements the (basic) user interface for the MHMCHMC kernel. Parameters ---------- logdensity_fn The log-density function we wish to draw samples from. step_size The value to use for the step size in the symplectic integrator. divergence_threshold The absolute value of the ...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py
Apache-2.0
def adjusted_mclmc_proposal( integrator: Callable, step_size: Union[float, ArrayLikeTree], L_proposal_factor: float, num_integration_steps: int = 1, divergence_threshold: float = 1000, *, sample_proposal: Callable = static_binomial_sampling, ) -> Callable: """Vanilla MHMCHMC algorithm. ...
Vanilla MHMCHMC algorithm. The algorithm integrates the trajectory applying a integrator `num_integration_steps` times in one direction to get a proposal and uses a Metropolis-Hastings acceptance step to either reject or accept this proposal. This is what people usually refer to when they talk about "t...
adjusted_mclmc_proposal
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc.py
Apache-2.0
def build_kernel( integration_steps_fn, integrator: Callable = integrators.isokinetic_mclachlan, divergence_threshold: float = 1000, next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1], inverse_mass_matrix=1.0, ): """Build a Dynamic MHMCHMC kernel where the number of integration ...
Build a Dynamic MHMCHMC kernel where the number of integration steps is chosen randomly. Parameters ---------- integrator The integrator to use to integrate the Hamiltonian dynamics. divergence_threshold Value of the difference in energy above which we consider that the transition is di...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc_dynamic.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: DynamicHMCState, logdensity_fn: Callable, step_size: float, L_proposal_factor: float = jnp.inf, ) -> tuple[DynamicHMCState, HMCInfo]: """Generate a new sample with the MHMCHMC kernel.""" num_integration_steps = integration...
Generate a new sample with the MHMCHMC kernel.
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc_dynamic.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, L_proposal_factor: float = jnp.inf, inverse_mass_matrix=1.0, *, divergence_threshold: int = 1000, integrator: Callable = integrators.isokinetic_mclachlan, next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1],...
Implements the (basic) user interface for the dynamic MHMCHMC kernel. Parameters ---------- logdensity_fn The log-density function we wish to draw samples from. step_size The value to use for the step size in the symplectic integrator. divergence_threshold The absolute value...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc_dynamic.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py
Apache-2.0
def adjusted_mclmc_proposal( integrator: Callable, step_size: Union[float, ArrayLikeTree], L_proposal_factor: float, num_integration_steps: int = 1, divergence_threshold: float = 1000, *, sample_proposal: Callable = static_binomial_sampling, ) -> Callable: """Vanilla MHMCHMC algorithm. ...
Vanilla MHMCHMC algorithm. The algorithm integrates the trajectory applying a integrator `num_integration_steps` times in one direction to get a proposal and uses a Metropolis-Hastings acceptance step to either reject or accept this proposal. This is what people usually refer to when they talk about "t...
adjusted_mclmc_proposal
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc_dynamic.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py
Apache-2.0
def rescale(mu): """returns s, such that round(U(0, 1) * s + 0.5) has expected value mu. """ k = jnp.floor(2 * mu - 1) x = k * (mu - 0.5 * (k + 1)) / (k + 1 - mu) return k + x
returns s, such that round(U(0, 1) * s + 0.5) has expected value mu.
rescale
python
blackjax-devs/blackjax
blackjax/mcmc/adjusted_mclmc_dynamic.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/adjusted_mclmc_dynamic.py
Apache-2.0
def build_kernel(): """Build a Barker's proposal kernel. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition. """ def _compute_acceptance_probabili...
Build a Barker's proposal kernel. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition.
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/barker.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py
Apache-2.0
def _compute_acceptance_probability( state: BarkerState, proposal: BarkerState, metric: Metric ) -> Numeric: """Compute the acceptance probability of the Barker's proposal kernel.""" x = state.position y = proposal.position log_x = state.logdensity_grad log_y = propo...
Compute the acceptance probability of the Barker's proposal kernel.
_compute_acceptance_probability
python
blackjax-devs/blackjax
blackjax/mcmc/barker.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: BarkerState, logdensity_fn: Callable, step_size: float, inverse_mass_matrix: metrics.MetricTypes | None = None, ) -> tuple[BarkerState, BarkerInfo]: """Generate a new sample with the Barker kernel.""" if inverse_mass_matrix...
Generate a new sample with the Barker kernel.
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/barker.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, inverse_mass_matrix: metrics.MetricTypes | None = None, ) -> SamplingAlgorithm: """Implements the (basic) user interface for the Barker's proposal :cite:p:`Livingstone2022Barker` kernel with a Gaussian base kernel. The general Bar...
Implements the (basic) user interface for the Barker's proposal :cite:p:`Livingstone2022Barker` kernel with a Gaussian base kernel. The general Barker kernel builder (:meth:`blackjax.mcmc.barker.build_kernel`, alias `blackjax.barker.build_kernel`) can be cumbersome to manipulate. Since most users only need...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/barker.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py
Apache-2.0
def _barker_sample(key, mean, a, scale, metric): r""" Sample from a multivariate Barker's proposal distribution for PyTrees. Parameters ---------- key A PRNG key. mean The mean of the normal distribution, a PyTree. This corresponds to :math:`\mu` in the equation above. a ...
Sample from a multivariate Barker's proposal distribution for PyTrees. Parameters ---------- key A PRNG key. mean The mean of the normal distribution, a PyTree. This corresponds to :math:`\mu` in the equation above. a The parameter :math:`a` in the equation above, the s...
_barker_sample
python
blackjax-devs/blackjax
blackjax/mcmc/barker.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/barker.py
Apache-2.0
def overdamped_langevin(logdensity_grad_fn): """Euler solver for overdamped Langevin diffusion.""" def one_step(rng_key, state: DiffusionState, step_size: float, batch: tuple = ()): position, _, logdensity_grad = state noise = generate_gaussian_noise(rng_key, position) position = jax.tr...
Euler solver for overdamped Langevin diffusion.
overdamped_langevin
python
blackjax-devs/blackjax
blackjax/mcmc/diffusions.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/diffusions.py
Apache-2.0
def build_kernel( integrator: Callable = integrators.velocity_verlet, divergence_threshold: float = 1000, next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1], integration_steps_fn: Callable = lambda key: jax.random.randint(key, (), 1, 10), ): """Build a Dynamic HMC kernel where the n...
Build a Dynamic HMC kernel where the number of integration steps is chosen randomly. Parameters ---------- integrator The symplectic integrator to use to integrate the Hamiltonian dynamics. divergence_threshold Value of the difference in energy above which we consider that the transitio...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/dynamic_hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: DynamicHMCState, logdensity_fn: Callable, step_size: float, inverse_mass_matrix: Array, **integration_steps_kwargs, ) -> tuple[DynamicHMCState, HMCInfo]: """Generate a new sample with the HMC kernel.""" num_integrat...
Generate a new sample with the HMC kernel.
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/dynamic_hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, inverse_mass_matrix: Array, *, divergence_threshold: int = 1000, integrator: Callable = integrators.velocity_verlet, next_random_arg_fn: Callable = lambda key: jax.random.split(key)[1], integration_steps_fn: Callable = lamb...
Implements the (basic) user interface for the dynamic HMC kernel. Parameters ---------- logdensity_fn The log-density function we wish to draw samples from. step_size The value to use for the step size in the symplectic integrator. inverse_mass_matrix The value to use for th...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/dynamic_hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py
Apache-2.0
def halton_trajectory_length( i: Array, trajectory_length_adjustment: float, max_bits: int = 10 ) -> int: """Generate a quasi-random number of integration steps.""" s = rescale(trajectory_length_adjustment) return jnp.asarray(jnp.rint(0.5 + halton_sequence(i, max_bits) * s), dtype=int)
Generate a quasi-random number of integration steps.
halton_trajectory_length
python
blackjax-devs/blackjax
blackjax/mcmc/dynamic_hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/dynamic_hmc.py
Apache-2.0
def build_kernel(cov_matrix: Array, mean: Array): """Build an Elliptical Slice sampling kernel :cite:p:`murray2010elliptical`. Parameters ---------- cov_matrix The value of the covariance matrix of the gaussian prior distribution from the posterior we wish to sample. Returns --...
Build an Elliptical Slice sampling kernel :cite:p:`murray2010elliptical`. Parameters ---------- cov_matrix The value of the covariance matrix of the gaussian prior distribution from the posterior we wish to sample. Returns ------- A kernel that takes a rng_key and a Pytree that...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/elliptical_slice.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py
Apache-2.0
def as_top_level_api( loglikelihood_fn: Callable, *, mean: Array, cov: Array, ) -> SamplingAlgorithm: """Implements the (basic) user interface for the Elliptical Slice sampling kernel. Examples -------- A new Elliptical Slice sampling kernel can be initialized and used with the followi...
Implements the (basic) user interface for the Elliptical Slice sampling kernel. Examples -------- A new Elliptical Slice sampling kernel can be initialized and used with the following code: .. code:: ellip_slice = blackjax.elliptical_slice(loglikelihood_fn, cov_matrix) state = ellip_...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/elliptical_slice.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py
Apache-2.0
def elliptical_proposal( logdensity_fn: Callable, momentum_generator: Callable, mean: Array, ) -> Callable: """Build an Ellitpical slice sampling kernel. The algorithm samples a latent parameter, traces an ellipse connecting the initial position and the latent parameter and does slice sampling ...
Build an Ellitpical slice sampling kernel. The algorithm samples a latent parameter, traces an ellipse connecting the initial position and the latent parameter and does slice sampling on this ellipse to output a new sample from the posterior distribution. Parameters ---------- logdensity_fn ...
elliptical_proposal
python
blackjax-devs/blackjax
blackjax/mcmc/elliptical_slice.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py
Apache-2.0
def slice_fn(vals): """Perform slice sampling around the ellipsis. Checks if the proposed position's likelihood is larger than the slice variable. Returns the position if True, shrinks the bracket for sampling `theta` and samples a new proposal if False. As ...
Perform slice sampling around the ellipsis. Checks if the proposed position's likelihood is larger than the slice variable. Returns the position if True, shrinks the bracket for sampling `theta` and samples a new proposal if False. As the bracket `[theta_min, theta_max]...
slice_fn
python
blackjax-devs/blackjax
blackjax/mcmc/elliptical_slice.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py
Apache-2.0
def ellipsis(position, momentum, theta, mean): """Generate proposal from the ellipsis. Given a scalar theta indicating a point on the circumference of the ellipsis and the shared mean vector for both position and momentum variables, generate proposed position and momentum to later accept or reject ...
Generate proposal from the ellipsis. Given a scalar theta indicating a point on the circumference of the ellipsis and the shared mean vector for both position and momentum variables, generate proposed position and momentum to later accept or reject depending on the slice variable.
ellipsis
python
blackjax-devs/blackjax
blackjax/mcmc/elliptical_slice.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/elliptical_slice.py
Apache-2.0
def build_kernel( noise_fn: Callable = lambda _: 0.0, divergence_threshold: float = 1000, ): """Build a Generalized HMC kernel. The Generalized HMC kernel performs a similar procedure to the standard HMC kernel with the difference of a persistent momentum variable and a non-reversible Metropoli...
Build a Generalized HMC kernel. The Generalized HMC kernel performs a similar procedure to the standard HMC kernel with the difference of a persistent momentum variable and a non-reversible Metropolis-Hastings step instead of the standard Metropolis-Hastings acceptance step. This means that; apart from...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/ghmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: GHMCState, logdensity_fn: Callable, step_size: float, momentum_inverse_scale: ArrayLikeTree, alpha: float, delta: float, ) -> tuple[GHMCState, hmc.HMCInfo]: """Generate new sample with the Generalized HMC kernel. ...
Generate new sample with the Generalized HMC kernel. Parameters ---------- rng_key JAX's pseudo random number generating key. state Current state of the chain. logdensity_fn (Unnormalized) Log density function being targeted. step_size...
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/ghmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py
Apache-2.0
def update_momentum(rng_key, state, alpha, momentum_generator): """Persistent update of the momentum variable. Performs a persistent update of the momentum, taking as input the previous momentum, a random number generating key, the parameter alpha and the momentum generator function. Outputs an upd...
Persistent update of the momentum variable. Performs a persistent update of the momentum, taking as input the previous momentum, a random number generating key, the parameter alpha and the momentum generator function. Outputs an updated momentum that is a mixture of the previous momentum a new sample ...
update_momentum
python
blackjax-devs/blackjax
blackjax/mcmc/ghmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, momentum_inverse_scale: ArrayLikeTree, alpha: float, delta: float, *, divergence_threshold: int = 1000, noise_gn: Callable = lambda _: 0.0, ) -> SamplingAlgorithm: """Implements the (basic) user interface for the Genera...
Implements the (basic) user interface for the Generalized HMC kernel. The Generalized HMC kernel performs a similar procedure to the standard HMC kernel with the difference of a persistent momentum variable and a non-reversible Metropolis-Hastings step instead of the standard Metropolis-Hastings acceptance...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/ghmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/ghmc.py
Apache-2.0
def build_kernel( integrator: Callable = integrators.velocity_verlet, divergence_threshold: float = 1000, ): """Build a HMC kernel. Parameters ---------- integrator The symplectic integrator to use to integrate the Hamiltonian dynamics. divergence_threshold Value of the diff...
Build a HMC kernel. Parameters ---------- integrator The symplectic integrator to use to integrate the Hamiltonian dynamics. divergence_threshold Value of the difference in energy above which we consider that the transition is divergent. Returns ------- A kernel tha...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: HMCState, logdensity_fn: Callable, step_size: float, inverse_mass_matrix: metrics.MetricTypes, num_integration_steps: int, ) -> tuple[HMCState, HMCInfo]: """Generate a new sample with the HMC kernel.""" metric = me...
Generate a new sample with the HMC kernel.
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, inverse_mass_matrix: metrics.MetricTypes, num_integration_steps: int, *, divergence_threshold: int = 1000, integrator: Callable = integrators.velocity_verlet, ) -> SamplingAlgorithm: """Implements the (basic) user interface...
Implements the (basic) user interface for the HMC kernel. The general hmc kernel builder (:meth:`blackjax.mcmc.hmc.build_kernel`, alias `blackjax.hmc.build_kernel`) can be cumbersome to manipulate. Since most users only need to specify the kernel parameters at initialization time, we provide a helper f...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py
Apache-2.0
def hmc_proposal( integrator: Callable, kinetic_energy: metrics.KineticEnergy, step_size: Union[float, ArrayLikeTree], num_integration_steps: int = 1, divergence_threshold: float = 1000, *, sample_proposal: Callable = static_binomial_sampling, ) -> Callable: """Vanilla HMC algorithm. ...
Vanilla HMC algorithm. The algorithm integrates the trajectory applying a symplectic integrator `num_integration_steps` times in one direction to get a proposal and uses a Metropolis-Hastings acceptance step to either reject or accept this proposal. This is what people usually refer to when they talk a...
hmc_proposal
python
blackjax-devs/blackjax
blackjax/mcmc/hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py
Apache-2.0
def flip_momentum( state: integrators.IntegratorState, ) -> integrators.IntegratorState: """Flip the momentum at the end of the trajectory. To guarantee time-reversibility (hence detailed balance) we need to flip the last state's momentum. If we run the hamiltonian dynamics starting from the last s...
Flip the momentum at the end of the trajectory. To guarantee time-reversibility (hence detailed balance) we need to flip the last state's momentum. If we run the hamiltonian dynamics starting from the last state with flipped momentum we should indeed retrieve the initial state (with flipped momentum). ...
flip_momentum
python
blackjax-devs/blackjax
blackjax/mcmc/hmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/hmc.py
Apache-2.0
def generalized_two_stage_integrator( operator1: Callable, operator2: Callable, coefficients: list[float], format_output_fn: Callable = lambda x: x, ): """Generalized numerical integrator for solving ODEs. The generalized integrator performs numerical integration of a ODE system by alernati...
Generalized numerical integrator for solving ODEs. The generalized integrator performs numerical integration of a ODE system by alernating between stage 1 and stage 2 updates. The update scheme is decided by the coefficients, The scheme should be palindromic, i.e. the coefficients of the update scheme ...
generalized_two_stage_integrator
python
blackjax-devs/blackjax
blackjax/mcmc/integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py
Apache-2.0
def generate_euclidean_integrator(coefficients): """Generate symplectic integrator for solving a Hamiltonian system. The resulting integrator is volume-preserve and preserves the symplectic structure of phase space. """ def euclidean_integrator( logdensity_fn: Callable, kinetic_energy_fn: ...
Generate symplectic integrator for solving a Hamiltonian system. The resulting integrator is volume-preserve and preserves the symplectic structure of phase space.
generate_euclidean_integrator
python
blackjax-devs/blackjax
blackjax/mcmc/integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py
Apache-2.0
def update( momentum: ArrayTree, logdensity_grad: ArrayTree, step_size: float, coef: float, previous_kinetic_energy_change=None, is_last_call=False, ): """Momentum update based on Esh dynamics. The momentum updating map of the esh dynamics as derived ...
Momentum update based on Esh dynamics. The momentum updating map of the esh dynamics as derived in :cite:p:`steeg2021hamiltonian` There are no exponentials e^delta, which prevents overflows when the gradient norm is large.
update
python
blackjax-devs/blackjax
blackjax/mcmc/integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py
Apache-2.0
def partially_refresh_momentum(momentum, rng_key, step_size, L): """Adds a small noise to momentum and normalizes. Parameters ---------- rng_key The pseudo-random number generator key used to generate random numbers. momentum PyTree that the structure the output should to match. ...
Adds a small noise to momentum and normalizes. Parameters ---------- rng_key The pseudo-random number generator key used to generate random numbers. momentum PyTree that the structure the output should to match. step_size Step size L controls rate of momentum cha...
partially_refresh_momentum
python
blackjax-devs/blackjax
blackjax/mcmc/integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py
Apache-2.0
def solve_fixed_point_iteration( func: Callable[[ArrayTree], Tuple[ArrayTree, ArrayTree]], x0: ArrayTree, *, convergence_tol: float = 1e-6, divergence_tol: float = 1e10, max_iters: int = 100, norm_fn: Callable[[ArrayTree], float] = lambda x: jnp.max(jnp.abs(x)), ) -> Tuple[ArrayTree, ArrayTr...
Solve for x = func(x) using a fixed point iteration
solve_fixed_point_iteration
python
blackjax-devs/blackjax
blackjax/mcmc/integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py
Apache-2.0
def implicit_midpoint( logdensity_fn: Callable, kinetic_energy_fn: KineticEnergy, *, solver: FixedPointSolver = solve_fixed_point_iteration, **solver_kwargs: Any, ) -> Integrator: """The implicit midpoint integrator with support for non-stationary kinetic energy This is an integrator based ...
The implicit midpoint integrator with support for non-stationary kinetic energy This is an integrator based on :cite:t:`brofos2021evaluating`, which provides support for kinetic energies that depend on position. This integrator requires that the kinetic energy function takes two arguments: position and mom...
implicit_midpoint
python
blackjax-devs/blackjax
blackjax/mcmc/integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/integrators.py
Apache-2.0
def build_kernel(): """Build a MALA kernel. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition. """ def transition_energy(state, new_state, step_s...
Build a MALA kernel. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition.
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/mala.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py
Apache-2.0
def transition_energy(state, new_state, step_size): """Transition energy to go from `state` to `new_state`""" theta = jax.tree_util.tree_map( lambda x, new_x, g: x - new_x - step_size * g, state.position, new_state.position, new_state.logdensity_grad, ...
Transition energy to go from `state` to `new_state`
transition_energy
python
blackjax-devs/blackjax
blackjax/mcmc/mala.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: MALAState, logdensity_fn: Callable, step_size: float ) -> tuple[MALAState, MALAInfo]: """Generate a new sample with the MALA kernel.""" grad_fn = jax.value_and_grad(logdensity_fn) integrator = diffusions.overdamped_langevin(grad_fn) key_i...
Generate a new sample with the MALA kernel.
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/mala.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, ) -> SamplingAlgorithm: """Implements the (basic) user interface for the MALA kernel. The general mala kernel builder (:meth:`blackjax.mcmc.mala.build_kernel`, alias `blackjax.mala.build_kernel`) can be cumbersome to manipulate. Since...
Implements the (basic) user interface for the MALA kernel. The general mala kernel builder (:meth:`blackjax.mcmc.mala.build_kernel`, alias `blackjax.mala.build_kernel`) can be cumbersome to manipulate. Since most users only need to specify the kernel parameters at initialization time, we provide a helper f...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/mala.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mala.py
Apache-2.0
def svd_from_covariance(covariance: Array) -> CovarianceSVD: """Compute the singular value decomposition of the covariance matrix. Parameters ---------- covariance The covariance matrix. Returns ------- A ``CovarianceSVD`` object. """ U, Gamma, U_t = jnp.linalg.svd(covaria...
Compute the singular value decomposition of the covariance matrix. Parameters ---------- covariance The covariance matrix. Returns ------- A ``CovarianceSVD`` object.
svd_from_covariance
python
blackjax-devs/blackjax
blackjax/mcmc/marginal_latent_gaussian.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py
Apache-2.0
def generate_mean_shifted_logprob(logdensity_fn, mean, covariance): """Generate a log-density function that is shifted by a constant Parameters ---------- logdensity_fn The original log-density function mean The mean of the prior Gaussian density covariance The covarianc...
Generate a log-density function that is shifted by a constant Parameters ---------- logdensity_fn The original log-density function mean The mean of the prior Gaussian density covariance The covariance of the prior Gaussian density. Returns ------- A log-density...
generate_mean_shifted_logprob
python
blackjax-devs/blackjax
blackjax/mcmc/marginal_latent_gaussian.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py
Apache-2.0
def init(position, logdensity_fn, U_t): """Initialize the marginal version of the auxiliary gradient-based sampler. Parameters ---------- position The initial position of the chain. logdensity_fn The logarithm of the likelihood function for the latent Gaussian model. U_t ...
Initialize the marginal version of the auxiliary gradient-based sampler. Parameters ---------- position The initial position of the chain. logdensity_fn The logarithm of the likelihood function for the latent Gaussian model. U_t The unitary array of the covariance matrix. ...
init
python
blackjax-devs/blackjax
blackjax/mcmc/marginal_latent_gaussian.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py
Apache-2.0
def build_kernel(cov_svd: CovarianceSVD): """Build the marginal version of the auxiliary gradient-based sampler. Parameters ---------- cov_svd The singular value decomposition of the covariance matrix. Returns ------- A kernel that takes a rng_key and a Pytree that contains the cur...
Build the marginal version of the auxiliary gradient-based sampler. Parameters ---------- cov_svd The singular value decomposition of the covariance matrix. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a ne...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/marginal_latent_gaussian.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/marginal_latent_gaussian.py
Apache-2.0
def build_kernel( logdensity_fn, inverse_mass_matrix, integrator, desired_energy_var_max_ratio=jnp.inf, desired_energy_var=5e-4, ): """Build a HMC kernel. Parameters ---------- integrator The symplectic integrator to use to integrate the Hamiltonian dynamics. L t...
Build a HMC kernel. Parameters ---------- integrator The symplectic integrator to use to integrate the Hamiltonian dynamics. L the momentum decoherence rate. step_size step size of the integrator. Returns ------- A kernel that takes a rng_key and a Pytree that c...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/mclmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mclmc.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, L, step_size, integrator=isokinetic_mclachlan, inverse_mass_matrix=1.0, desired_energy_var_max_ratio=jnp.inf, ) -> SamplingAlgorithm: """The general mclmc kernel builder (:meth:`blackjax.mcmc.mclmc.build_kernel`, alias `blackjax.mclmc.build_kern...
The general mclmc kernel builder (:meth:`blackjax.mcmc.mclmc.build_kernel`, alias `blackjax.mclmc.build_kernel`) can be cumbersome to manipulate. Since most users only need to specify the kernel parameters at initialization time, we provide a helper function that specializes the general kernel. We also...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/mclmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/mclmc.py
Apache-2.0
def default_metric(metric: MetricTypes) -> Metric: """Convert an input metric into a ``Metric`` object following sensible default rules The metric can be specified in three different ways: - A ``Metric`` object that implements the full interface - An ``Array`` which is assumed to specify the inverse m...
Convert an input metric into a ``Metric`` object following sensible default rules The metric can be specified in three different ways: - A ``Metric`` object that implements the full interface - An ``Array`` which is assumed to specify the inverse mass matrix of a static metric - A function that ...
default_metric
python
blackjax-devs/blackjax
blackjax/mcmc/metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py
Apache-2.0
def gaussian_euclidean( inverse_mass_matrix: Array, ) -> Metric: r"""Hamiltonian dynamic on euclidean manifold with normally-distributed momentum :cite:p:`betancourt2013general`. The gaussian euclidean metric is a euclidean metric further characterized by setting the conditional probability density...
Hamiltonian dynamic on euclidean manifold with normally-distributed momentum :cite:p:`betancourt2013general`. The gaussian euclidean metric is a euclidean metric further characterized by setting the conditional probability density :math:`\pi(momentum|position)` to follow a standard gaussian distributio...
gaussian_euclidean
python
blackjax-devs/blackjax
blackjax/mcmc/metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py
Apache-2.0
def is_turning( momentum_left: ArrayLikeTree, momentum_right: ArrayLikeTree, momentum_sum: ArrayLikeTree, position_left: Optional[ArrayLikeTree] = None, position_right: Optional[ArrayLikeTree] = None, ) -> bool: """Generalized U-turn criterion :cite:p:`betancourt2013g...
Generalized U-turn criterion :cite:p:`betancourt2013generalizing,nuts_uturn`. Parameters ---------- momentum_left Momentum of the leftmost point of the trajectory. momentum_right Momentum of the rightmost point of the trajectory. momentum_sum ...
is_turning
python
blackjax-devs/blackjax
blackjax/mcmc/metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py
Apache-2.0
def scale( position: ArrayLikeTree, element: ArrayLikeTree, *, inv: bool, trans: bool, ) -> ArrayLikeTree: """Scale elements by the mass matrix. Parameters ---------- position The current position. Not used in this metric. ...
Scale elements by the mass matrix. Parameters ---------- position The current position. Not used in this metric. elements Elements to scale inv Whether to scale the elements by the inverse mass matrix or the mass matrix. If True, t...
scale
python
blackjax-devs/blackjax
blackjax/mcmc/metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py
Apache-2.0
def scale( position: ArrayLikeTree, element: ArrayLikeTree, *, inv: bool, trans: bool, ) -> ArrayLikeTree: """Scale elements by the mass matrix. Parameters ---------- position The current position. Returns ------- ...
Scale elements by the mass matrix. Parameters ---------- position The current position. Returns ------- scaled_elements The scaled elements.
scale
python
blackjax-devs/blackjax
blackjax/mcmc/metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/metrics.py
Apache-2.0
def build_kernel( integrator: Callable = integrators.velocity_verlet, divergence_threshold: int = 1000, ): """Build an iterative NUTS kernel. This algorithm is an iteration on the original NUTS algorithm :cite:p:`hoffman2014no` with two major differences: - We do not use slice samplig but mult...
Build an iterative NUTS kernel. This algorithm is an iteration on the original NUTS algorithm :cite:p:`hoffman2014no` with two major differences: - We do not use slice samplig but multinomial sampling for the proposal :cite:p:`betancourt2017conceptual`; - The trajectory expansion is not recursiv...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/nuts.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: hmc.HMCState, logdensity_fn: Callable, step_size: float, inverse_mass_matrix: metrics.MetricTypes, max_num_doublings: int = 10, ) -> tuple[hmc.HMCState, NUTSInfo]: """Generate a new sample with the NUTS kernel.""" ...
Generate a new sample with the NUTS kernel.
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/nuts.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, inverse_mass_matrix: metrics.MetricTypes, *, max_num_doublings: int = 10, divergence_threshold: int = 1000, integrator: Callable = integrators.velocity_verlet, ) -> SamplingAlgorithm: """Implements the (basic) user interfac...
Implements the (basic) user interface for the nuts kernel. Examples -------- A new NUTS kernel can be initialized and used with the following code: .. code:: nuts = blackjax.nuts(logdensity_fn, step_size, inverse_mass_matrix) state = nuts.init(position) new_state, info = nuts...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/nuts.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py
Apache-2.0
def iterative_nuts_proposal( integrator: Callable, kinetic_energy: metrics.KineticEnergy, uturn_check_fn: metrics.CheckTurning, max_num_expansions: int = 10, divergence_threshold: float = 1000, ) -> Callable: """Iterative NUTS proposal. Parameters ---------- integrator Sympl...
Iterative NUTS proposal. Parameters ---------- integrator Symplectic integrator used to build the trajectory step by step. kinetic_energy Function that computes the kinetic energy. uturn_check_fn: Function that determines whether the trajectory is turning on itself (...
iterative_nuts_proposal
python
blackjax-devs/blackjax
blackjax/mcmc/nuts.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/nuts.py
Apache-2.0
def init( position: ArrayLikeTree, logdensity_fn: Callable, period: int ) -> PeriodicOrbitalState: """Create a periodic orbital state from a position. Parameters ---------- position the current values of the random variables whose posterior we want to sample from. Can be anything fr...
Create a periodic orbital state from a position. Parameters ---------- position the current values of the random variables whose posterior we want to sample from. Can be anything from a list, a (named) tuple or a dict of arrays. The arrays can either be Numpy or JAX arrays. logd...
init
python
blackjax-devs/blackjax
blackjax/mcmc/periodic_orbital.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py
Apache-2.0
def build_kernel( bijection: Callable = integrators.velocity_verlet, ): """Build a Periodic Orbital kernel :cite:p:`neklyudov2022orbital`. Parameters ---------- bijection transformation used to build the orbit (given a step size). Returns ------- A kernel that takes a rng_key a...
Build a Periodic Orbital kernel :cite:p:`neklyudov2022orbital`. Parameters ---------- bijection transformation used to build the orbit (given a step size). Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new...
build_kernel
python
blackjax-devs/blackjax
blackjax/mcmc/periodic_orbital.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: PeriodicOrbitalState, logdensity_fn: Callable, step_size: float, inverse_mass_matrix: Array, period: int, ) -> tuple[PeriodicOrbitalState, PeriodicOrbitalInfo]: """Generate a new orbit with the Periodic Orbital kernel. ...
Generate a new orbit with the Periodic Orbital kernel. Choose a step from the orbit with probability proportional to its weights. Then shift the direction (or alternatively sample a new direction randomly), in order to make the algorithm irreversible, and compute a new orbit from the se...
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/periodic_orbital.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, inverse_mass_matrix: Array, # assume momentum is always Gaussian period: int, *, bijection: Callable = integrators.velocity_verlet, ) -> SamplingAlgorithm: """Implements the (basic) user interface for the Periodic orbital MCMC...
Implements the (basic) user interface for the Periodic orbital MCMC kernel. Each iteration of the periodic orbital MCMC outputs ``period`` weighted samples from a single Hamiltonian orbit connecting the previous sample and momentum (latent) variable with precision matrix ``inverse_mass_matrix``, evaluated ...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/periodic_orbital.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py
Apache-2.0
def periodic_orbital_proposal( bijection: Callable, kinetic_energy_fn: Callable, period: int, step_size: float, ) -> Callable: """Periodic Orbital algorithm. The algorithm builds and orbit and computes the weights for each of its steps by applying a bijection `period` times, both forwards a...
Periodic Orbital algorithm. The algorithm builds and orbit and computes the weights for each of its steps by applying a bijection `period` times, both forwards and backwards depending on the direction of the initial state. Parameters ---------- bijection continuous, differentialble and...
periodic_orbital_proposal
python
blackjax-devs/blackjax
blackjax/mcmc/periodic_orbital.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py
Apache-2.0
def generate( direction: int, init_state: integrators.IntegratorState ) -> tuple[PeriodicOrbitalState, PeriodicOrbitalInfo]: """Generate orbit by applying bijection forwards and backwards on period. As described in algorithm 2 of :cite:p:`neklyudov2022orbital`, each iteration of the periodi...
Generate orbit by applying bijection forwards and backwards on period. As described in algorithm 2 of :cite:p:`neklyudov2022orbital`, each iteration of the periodic orbital MCMC takes a position and its direction, i.e. its step in the orbit, then it runs the bijection backwards until it reaches...
generate
python
blackjax-devs/blackjax
blackjax/mcmc/periodic_orbital.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/periodic_orbital.py
Apache-2.0
def proposal_generator(energy_fn: Callable) -> tuple[Callable, Callable]: """ Parameters ---------- energy_fn A function that computes the energy associated to a given state Returns ------- Two functions, one to generate an initial proposal when no step has been taken, another ...
Parameters ---------- energy_fn A function that computes the energy associated to a given state Returns ------- Two functions, one to generate an initial proposal when no step has been taken, another to generate proposals after each step.
proposal_generator
python
blackjax-devs/blackjax
blackjax/mcmc/proposal.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/proposal.py
Apache-2.0
def update(initial_energy: float, new_state: TrajectoryState) -> Proposal: """Generate a new proposal from a trajectory state. The trajectory state records information about the position in the state space and corresponding logdensity. A proposal also carries a weight that is equal to t...
Generate a new proposal from a trajectory state. The trajectory state records information about the position in the state space and corresponding logdensity. A proposal also carries a weight that is equal to the difference between the current energy and the previous one. It thus carries...
update
python
blackjax-devs/blackjax
blackjax/mcmc/proposal.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/proposal.py
Apache-2.0
def progressive_biased_sampling( rng_key: PRNGKey, proposal: Proposal, new_proposal: Proposal ) -> Proposal: """Baised proposal sampling :cite:p:`betancourt2017conceptual`. Unlike uniform sampling, biased sampling favors new proposals. It thus biases the transition away from the trajectory's initial st...
Baised proposal sampling :cite:p:`betancourt2017conceptual`. Unlike uniform sampling, biased sampling favors new proposals. It thus biases the transition away from the trajectory's initial state.
progressive_biased_sampling
python
blackjax-devs/blackjax
blackjax/mcmc/proposal.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/proposal.py
Apache-2.0
def compute_asymmetric_acceptance_ratio(transition_energy_fn: Callable) -> Callable: """Generate a meta function to compute the transition between two states. In particular, both states are used to compute the energies to consider in weighting the proposal, to account for asymmetries. Parameters -...
Generate a meta function to compute the transition between two states. In particular, both states are used to compute the energies to consider in weighting the proposal, to account for asymmetries. Parameters ---------- transition_energy_fn A function that computes the energy of a transiti...
compute_asymmetric_acceptance_ratio
python
blackjax-devs/blackjax
blackjax/mcmc/proposal.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/proposal.py
Apache-2.0
def static_binomial_sampling( rng_key: PRNGKey, log_p_accept: float, proposal, new_proposal ): """Accept or reject a proposal. In the static setting, the probability with which the new proposal is accepted is a function of the difference in energy between the previous and the current states. If the...
Accept or reject a proposal. In the static setting, the probability with which the new proposal is accepted is a function of the difference in energy between the previous and the current states. If the current energy is lower than the previous one then the new proposal is accepted with probability 1. ...
static_binomial_sampling
python
blackjax-devs/blackjax
blackjax/mcmc/proposal.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/proposal.py
Apache-2.0
def nonreversible_slice_sampling( slice: Array, delta_energy: float, proposal, new_proposal ): """Slice sampling for non-reversible Metropolis-Hasting update. Performs a non-reversible update of a uniform [0, 1] value for Metropolis-Hastings accept/reject decisions :cite:p:`neal2020non`, in addition ...
Slice sampling for non-reversible Metropolis-Hasting update. Performs a non-reversible update of a uniform [0, 1] value for Metropolis-Hastings accept/reject decisions :cite:p:`neal2020non`, in addition to the accept/reject step of a current state and new proposal.
nonreversible_slice_sampling
python
blackjax-devs/blackjax
blackjax/mcmc/proposal.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/proposal.py
Apache-2.0
def normal(sigma: Array) -> Callable: """Normal Random Walk proposal. Propose a new position such that its distance to the current position is normally distributed. Suitable for continuous variables. Parameter --------- sigma: vector or matrix that contains the standard deviation of th...
Normal Random Walk proposal. Propose a new position such that its distance to the current position is normally distributed. Suitable for continuous variables. Parameter --------- sigma: vector or matrix that contains the standard deviation of the centered normal distribution from w...
normal
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def build_additive_step(): """Build a Random Walk Rosenbluth-Metropolis-Hastings kernel Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition. """ def...
Build a Random Walk Rosenbluth-Metropolis-Hastings kernel Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition.
build_additive_step
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def additive_step_random_walk( logdensity_fn: Callable, random_step: Callable ) -> SamplingAlgorithm: """Implements the user interface for the Additive Step RMH Examples -------- A new kernel can be initialized and used with the following code: .. code:: rw = blackjax.additive_step_r...
Implements the user interface for the Additive Step RMH Examples -------- A new kernel can be initialized and used with the following code: .. code:: rw = blackjax.additive_step_random_walk(logdensity_fn, random_step) state = rw.init(position) new_state, info = rw.step(rng_ke...
additive_step_random_walk
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def build_irmh() -> Callable: """ Build an Independent Random Walk Rosenbluth-Metropolis-Hastings kernel. This implies that the proposal distribution does not depend on the particle being mutated :cite:p:`wang2022exact`. Returns ------- A kernel that takes a rng_key and a Pytree that contains t...
Build an Independent Random Walk Rosenbluth-Metropolis-Hastings kernel. This implies that the proposal distribution does not depend on the particle being mutated :cite:p:`wang2022exact`. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and...
build_irmh
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: RWState, logdensity_fn: Callable, proposal_distribution: Callable, proposal_logdensity_fn: Optional[Callable] = None, ) -> tuple[RWState, RWInfo]: """ Parameters ---------- proposal_distribution ...
Parameters ---------- proposal_distribution A function that, given a PRNGKey, is able to produce a sample in the same domain of the target distribution. proposal_logdensity_fn: For non-symmetric proposals, a function that returns the log-density ...
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def irmh_as_top_level_api( logdensity_fn: Callable, proposal_distribution: Callable, proposal_logdensity_fn: Optional[Callable] = None, ) -> SamplingAlgorithm: """Implements the (basic) user interface for the independent RMH. Examples -------- A new kernel can be initialized and used with ...
Implements the (basic) user interface for the independent RMH. Examples -------- A new kernel can be initialized and used with the following code: .. code:: rmh = blackjax.irmh(logdensity_fn, proposal_distribution) state = rmh.init(position) new_state, info = rmh.step(rng_key...
irmh_as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def build_rmh(): """Build a Rosenbluth-Metropolis-Hastings kernel. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition. """ def kernel( rng...
Build a Rosenbluth-Metropolis-Hastings kernel. Returns ------- A kernel that takes a rng_key and a Pytree that contains the current state of the chain and that returns a new state of the chain along with information about the transition.
build_rmh
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def kernel( rng_key: PRNGKey, state: RWState, logdensity_fn: Callable, transition_generator: Callable, proposal_logdensity_fn: Optional[Callable] = None, ) -> tuple[RWState, RWInfo]: """Move the chain by one step using the Rosenbluth Metropolis Hastings algori...
Move the chain by one step using the Rosenbluth Metropolis Hastings algorithm. Parameters ---------- rng_key: The pseudo-random number generator key used to generate random numbers. logdensity_fn: A function that returns the log-probability at a...
kernel
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def rmh_as_top_level_api( logdensity_fn: Callable, proposal_generator: Callable[[PRNGKey, ArrayLikeTree], ArrayTree], proposal_logdensity_fn: Optional[Callable[[ArrayLikeTree], ArrayTree]] = None, ) -> SamplingAlgorithm: """Implements the user interface for the RMH. Examples -------- A new...
Implements the user interface for the RMH. Examples -------- A new kernel can be initialized and used with the following code: .. code:: rmh = blackjax.rmh(logdensity_fn, proposal_generator) state = rmh.init(position) new_state, info = rmh.step(rng_key, state) We can JIT...
rmh_as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/random_walk.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/random_walk.py
Apache-2.0
def as_top_level_api( logdensity_fn: Callable, step_size: float, mass_matrix: Union[metrics.Metric, Callable], num_integration_steps: int, *, divergence_threshold: int = 1000, integrator: Callable = integrators.implicit_midpoint, ) -> SamplingAlgorithm: """A Riemannian Manifold Hamiltoni...
A Riemannian Manifold Hamiltonian Monte Carlo kernel Of note, this kernel is simply an alias of the ``hmc`` kernel with a different choice of default integrator (``implicit_midpoint`` instead of ``velocity_verlet``) since RMHMC is typically used for Hamiltonian systems that are not separable. Para...
as_top_level_api
python
blackjax-devs/blackjax
blackjax/mcmc/rmhmc.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/rmhmc.py
Apache-2.0
def _leaf_idx_to_ckpt_idxs(n): """Find the checkpoint id from a step number.""" # computes the number of non-zero bits except the last bit # e.g. 6 -> 2, 7 -> 2, 13 -> 2 idx_max = jnp.bitwise_count(n >> 1).astype(jnp.int32) # computes the number of contiguous last non-zero bits ...
Find the checkpoint id from a step number.
_leaf_idx_to_ckpt_idxs
python
blackjax-devs/blackjax
blackjax/mcmc/termination.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/termination.py
Apache-2.0
def _is_iterative_turning(checkpoints, momentum_sum, momentum): """Checks whether there is a U-turn in the iteratively built expanded trajectory. These checks only need to be performed as specific points. """ r, _ = jax.flatten_util.ravel_pytree(momentum) r_sum, _ = jax.flatten...
Checks whether there is a U-turn in the iteratively built expanded trajectory. These checks only need to be performed as specific points.
_is_iterative_turning
python
blackjax-devs/blackjax
blackjax/mcmc/termination.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/termination.py
Apache-2.0
def append_to_trajectory(trajectory: Trajectory, state: IntegratorState) -> Trajectory: """Append a state to the (right of the) trajectory to form a new trajectory.""" momentum_sum = jax.tree_util.tree_map( jnp.add, trajectory.momentum_sum, state.momentum ) return Trajectory( trajectory....
Append a state to the (right of the) trajectory to form a new trajectory.
append_to_trajectory
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def reorder_trajectories( direction: int, trajectory: Trajectory, new_trajectory: Trajectory ) -> tuple[Trajectory, Trajectory]: """Order the two trajectories depending on the direction.""" return jax.lax.cond( direction > 0, lambda _: ( trajectory, new_trajectory, ...
Order the two trajectories depending on the direction.
reorder_trajectories
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def static_integration( integrator: Callable, direction: int = 1, ) -> Callable: """Generate a trajectory by integrating several times in one direction.""" def integrate( initial_state: IntegratorState, step_size, num_integration_steps ) -> IntegratorState: directed_step_size = jax....
Generate a trajectory by integrating several times in one direction.
static_integration
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def dynamic_progressive_integration( integrator: Callable, kinetic_energy: Callable, update_termination_state: Callable, is_criterion_met: Callable, divergence_threshold: float, ): """Integrate a trajectory and update the proposal sequentially in one direction until the termination criterion...
Integrate a trajectory and update the proposal sequentially in one direction until the termination criterion is met. Parameters ---------- integrator The symplectic integrator used to integrate the hamiltonian trajectory. kinetic_energy Function to compute the current value of the k...
dynamic_progressive_integration
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def integrate( rng_key: PRNGKey, initial_state: IntegratorState, direction: int, termination_state, max_num_steps: int, step_size, initial_energy, ): """Integrate the trajectory starting from `initial_state` and update the proposal sequentially...
Integrate the trajectory starting from `initial_state` and update the proposal sequentially (hence progressive) until the termination criterion is met (hence dynamic). Parameters ---------- rng_key Key used by JAX's random number generator. initial_state ...
integrate
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def do_keep_integrating(loop_state): """Decide whether we should continue integrating the trajectory""" integration_state, (is_diverging, has_terminated) = loop_state return ( (integration_state.step < max_num_steps) & ~has_terminated &...
Decide whether we should continue integrating the trajectory
do_keep_integrating
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def dynamic_recursive_integration( integrator: Callable, kinetic_energy: Callable, uturn_check_fn: Callable, divergence_threshold: float, use_robust_uturn_check: bool = False, ): """Integrate a trajectory and update the proposal recursively in Python until the termination criterion is met. ...
Integrate a trajectory and update the proposal recursively in Python until the termination criterion is met. This is the implementation of Algorithm 6 from :cite:p:`hoffman2014no` with multinomial sampling. The implemenation here is mostly for validating the progressive implementation to make sure the ...
dynamic_recursive_integration
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def buildtree_integrate( rng_key: PRNGKey, initial_state: IntegratorState, direction: int, tree_depth: int, step_size, initial_energy: float, ): """Integrate the trajectory starting from `initial_state` and update the proposal recursively with tree dou...
Integrate the trajectory starting from `initial_state` and update the proposal recursively with tree doubling until the termination criterion is met. The function `buildtree_integrate` calls itself for tree_depth > 0, thus invokes the recursive scheme that builds a trajectory by doubling a bina...
buildtree_integrate
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def dynamic_multiplicative_expansion( trajectory_integrator: Callable, uturn_check_fn: Callable, max_num_expansions: int = 10, rate: int = 2, ) -> Callable: """Sample a trajectory and update the proposal sequentially until the termination criterion is met. The trajectory is sampled with the...
Sample a trajectory and update the proposal sequentially until the termination criterion is met. The trajectory is sampled with the following procedure: 1. Pick a direction at random; 2. Integrate `num_step` steps in this direction; 3. If the integration has stopped prematurely, do not update the p...
dynamic_multiplicative_expansion
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def do_keep_expanding(loop_state) -> bool: """Determine whether we need to keep expanding the trajectory.""" expansion_state, (is_diverging, is_turning) = loop_state return ( (expansion_state.step < max_num_expansions) & ~is_diverging &...
Determine whether we need to keep expanding the trajectory.
do_keep_expanding
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def expand_once(loop_state): """Expand the current trajectory. At each step we draw a direction at random, build a subtrajectory starting from the leftmost or rightmost point of the current trajectory that is twice as long as the current trajectory. Once tha...
Expand the current trajectory. At each step we draw a direction at random, build a subtrajectory starting from the leftmost or rightmost point of the current trajectory that is twice as long as the current trajectory. Once that is done, possibly update the current propo...
expand_once
python
blackjax-devs/blackjax
blackjax/mcmc/trajectory.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/mcmc/trajectory.py
Apache-2.0
def dual_averaging( t0: int = 10, gamma: float = 0.05, kappa: float = 0.75 ) -> tuple[Callable, Callable, Callable]: """Find the state that minimizes an objective function using a primal-dual subgradient method. See :cite:p:`nesterov2009primal` for a detailed explanation of the algorithm and its mathem...
Find the state that minimizes an objective function using a primal-dual subgradient method. See :cite:p:`nesterov2009primal` for a detailed explanation of the algorithm and its mathematical properties. Parameters ---------- t0: float >= 0 Free parameter that stabilizes the initial iter...
dual_averaging
python
blackjax-devs/blackjax
blackjax/optimizers/dual_averaging.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/optimizers/dual_averaging.py
Apache-2.0
def init(x_init: float) -> DualAveragingState: """Initialize the state of the dual averaging scheme. The parameter :math:`\\mu` is set to :math:`\\log(10 \\x_init)` where :math:`\\x_init` is the initial value of the state. """ mu: float = jnp.log(10 * x_init) step = 1 ...
Initialize the state of the dual averaging scheme. The parameter :math:`\mu` is set to :math:`\log(10 \x_init)` where :math:`\x_init` is the initial value of the state.
init
python
blackjax-devs/blackjax
blackjax/optimizers/dual_averaging.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/optimizers/dual_averaging.py
Apache-2.0
def update(da_state: DualAveragingState, gradient) -> DualAveragingState: """Update the state of the Dual Averaging adaptive algorithm. Parameters ---------- gradient: The gradient of the function to optimize with respect to the state `x`, computed at the current...
Update the state of the Dual Averaging adaptive algorithm. Parameters ---------- gradient: The gradient of the function to optimize with respect to the state `x`, computed at the current value of `x`. da_state: The current state of the dual averaging ...
update
python
blackjax-devs/blackjax
blackjax/optimizers/dual_averaging.py
https://github.com/blackjax-devs/blackjax/blob/master/blackjax/optimizers/dual_averaging.py
Apache-2.0