22import os
33
44import numpy as np
5- from numpy .typing import NDArray
6- from scipy .stats import norm
5+ import scipy .stats
76
87
98def set_up_logger ():
@@ -35,15 +34,16 @@ def _init_rng(chain_index, loop_idx):
3534 return rng
3635
3736
38- def generate_next_state (x , prop_std , rng , chain_index ):
37+ def generate_next_state (x , proposal , rng , chain_index ):
3938 """Generate the next candidate state in a modified Metropolis algorithm.
4039
4140 Parameters
4241 ----------
4342 x
4443 Current state on which the candidate state will depend.
45- prop_std
46- Proposal distribution standard deviation.
44+ proposal
45+ Type and arguments to a Scipy distribution that should be used as the proposal.
46+ The proposal must be a symmetrical distribution, centred on zero.
4747 rng
4848 Random number generator to be used in this function.
4949 chain_index
@@ -59,6 +59,9 @@ def generate_next_state(x, prop_std, rng, chain_index):
5959 for this chain.
6060 """
6161
62+ dist_type = proposal .pop ("type" )
63+ prop_dist = getattr (scipy .stats , dist_type )(** proposal )
64+
6265 loop_idx = {
6366 loop_name : int (loop_idx )
6467 for loop_name , loop_idx in (
@@ -76,12 +79,13 @@ def generate_next_state(x, prop_std, rng, chain_index):
7679 current_state = x
7780 xi = np .empty (dim )
7881
79- proposal = norm (loc = current_state , scale = prop_std )
80- xi_hat = np .atleast_1d (proposal .rvs (random_state = rng ))
81- accept_ratios = np .divide (* norm .pdf ([xi_hat , current_state ]))
82+ xi_hat = np .atleast_1d (current_state + prop_dist .rvs (size = dim , random_state = rng ))
83+ accept_ratios = np .divide (* scipy .stats .norm .pdf ([xi_hat , current_state ]))
8284 accept_idx = rng .random (len (accept_ratios )) < np .minimum (1 , accept_ratios )
8385
8486 xi [accept_idx ] = xi_hat [accept_idx ]
8587 xi [~ accept_idx ] = current_state [~ accept_idx ]
8688
87- return {"x" : xi , "rng" : rng }
89+ mcmc_accept_rate = np .mean (accept_idx )
90+
91+ return {"x" : xi , "mcmc_accept_rate" : mcmc_accept_rate , "rng" : rng }
0 commit comments