Source code for py_core.metropolis

from py_core import harmonic_oscillator as ho
import numpy as np
from tqdm import tqdm

[docs] class Rwalk: """ Random walk in the space of closed paths with `Nsteps` points. A path is represented as x, x1, x2, ..., x(Nsteps-2), x (closed path). This class implements the Metropolis-Hastings algorithm to sample paths weighted by an action functional. It also provides methods to: compute thermal averages after sampling, converge the metropolis acceptance to a given target, and partition averages for binning purposes. Attributes ---------- None : All attributes are private Notes ----- The class maintains internal state for paths, acceptance/rejection counts, and the action functional value. All state attributes are private (prefixed with `__`). """
[docs] def __init__(self, Nsteps=3, x=0.5, dx=0.1, SEED=1): """ Construct an Rwalk object for random walks weighted by an action functional. The random walk is performed in the space of closed paths with `Nsteps` points. Parameters ---------- Nsteps : int, optional Number of points in the path (including the identical endpoints). Must be at least 3 to have at least one intermediate step. Default is 3. x : float, optional Endpoint value for the path. Default is 0.5. dx : float, optional Standard deviation of the Gaussian noise used in the Metropolis-Hastings algorithm. Default is 0.1. SEED : int, optional Random seed for reproducibility. Default is 1. Raises ------ ValueError If Nsteps is less than 3. """ if Nsteps < 3: raise ValueError("Nsteps must be at least 3, to have at least one intermediate step") self.__Nsteps = Nsteps self.__x = x self.__dx = dx self.__paths = np.full((1, Nsteps-1), x, dtype=np.float64) self.__acpt = 0 # accepted evolutions self.__rejt = 0 # rejected evolutions self.__action_v = None # latest computed value of the action functional self.__rng = np.random.default_rng(SEED)
[docs] def evolve(self, s0, index, action): """ Evolve a path using the Metropolis-Hastings algorithm. A random `dx` for each site is extracted from a Gaussian population, and a number `u` is extracted from a uniform(0,1) distribution. If `log(u)` < Delta S, then the new x value is accepted; otherwise, the old path is kept. Parameters ---------- s0 : float Previously computed action value. index : int Index of the starting path in the paths array. action : ho.action Action functional object used for the Metropolis algorithm. Returns ------- ndarray The evolved path. Notes ----- The acceptance check compares exp(-Delta S) < u, which is equivalent to comparing log(u) with -Delta S. This formulation avoids underflow and overflow issues. """ self.__action_v = s0 xprime = np.array(self.__paths[index]) dx = self.__rng.normal(loc=0., scale=self.__dx, size=self.__Nsteps-1) u = np.log(self.__rng.uniform(0, 1, size=self.__Nsteps-1)) for i in range(self.__Nsteps-1): xprime[i] += dx[i] # `index` localizes the path, `i` localizes the lattice site a = action.S_ith(xprime, i) b = action.S_ith(self.__paths[index], i) v = b - a # comparing exp(-Delta S) < u is equivalent to comparing log(u) with -Delta S if u[i] < v: self.__acpt += 1 self.__action_v += -v self.__paths[index, i] = xprime[i] else: self.__rejt += 1 xprime[i] = self.__paths[index, i] return self.__paths[index]
[docs] def thermalize(self, action=None, nthermal=1000): """ Perform thermalization by evolving `nthermal` times. The result is discarded except for the last path, which is used as the starting path for future evolutions. This helps the system reach equilibrium before sampling. Parameters ---------- action : ho.action, optional Action functional object. If None, defaults to `ho.action()`. nthermal : int, optional Number of thermalization steps. Default is 1000. Raises ------ ValueError If nthermal is not a positive integer. """ if action is None: action = ho.action() if nthermal <= 0: raise ValueError("nthermal must be a positive integer") self.__rejt = 0 # resetting acceptance and rejection counters for current sampling self.__acpt = 0 x = self.__paths[-1] s0 = action.S_closed(x).item() for i in range(nthermal): x = self.evolve(s0, -1, action=action) s0 = self.__action_v # update the action value for the next iteration self.__paths[-1] = x # the last path after thermalization is used as the starting path
[docs] def sample(self, action=None, nsample=1000, Ncor=1, progress_bar=True): """ Generate a sample of `nsample` paths using the Metropolis-Hastings algorithm. Paths are weighted by the action functional and generated starting from the last path in the `self.__paths` array. Parameters ---------- action : ho.action, optional Action functional object. If None, defaults to `ho.action()`. nsample : int, optional Number of samples to generate. Default is 1000. Ncor : int, optional Number of evolutions per each sample kept. Default is 1. If Ncor = 1, all paths are kept. If Ncor > 1, only every Ncor-th path is kept. progress_bar : bool, optional Whether to display a progress bar during sampling. Default is True. Returns ------- ndarray Array of generated paths with shape (nsample, Nsteps-1). Raises ------ ValueError If nsample is not a positive integer or if Ncor is None or less than 1. """ if action is None: action = ho.action() if nsample <= 0: raise ValueError("nsample must be a positive integer") if Ncor is None or Ncor < 1: raise ValueError("Ncor must be a positive integer") self.__rejt = 0 # resetting acceptance and rejection counters for current sampling self.__acpt = 0 samples = np.empty((nsample, self.__Nsteps-1)) x0 = self.__paths[0] s0 = action.S_closed(x0) self.__paths = samples # current sample being generated self.__paths[-1] = x0 # the starting path is the last path in the previous thermalization / sample if progress_bar: pbar = tqdm(range(nsample), desc="Sampling") else: pbar = range(nsample) for i in pbar: for j in range(Ncor): samples[i] = self.evolve(s0, i-1, action=action) s0 = self.__action_v # update the action value for the next iteration self.__paths[i] = samples[i] return samples.copy()
[docs] def get_ratio(self): """ Compute the acceptance ratio of the MCMC. The acceptance ratio is the fraction of proposed moves that were accepted. If no samples have been accepted or rejected yet, returns 1. Returns ------- float The acceptance ratio (accepted / (accepted + rejected)). Returns 1.0 if no samples have been processed yet. """ if (self.__acpt + self.__rejt) == 0: return 1 ratio = self.__acpt / (self.__acpt + self.__rejt) return ratio
[docs] def get_dx(self): """ Get the current value of ``dx``. ``dx`` is the standard deviation of the Gaussian noise used in the Metropolis-Hastings algorithm. Returns ------- float Current value of ``dx``. """ return self.__dx
[docs] def get_paths(self): """ Get all the stored paths. Returns ------- ndarray 2-D array where x[i,j] represents the i-th path at the j-th lattice site. Shape is (n_paths, Nsteps-1). """ return self.__paths.copy()
[docs] def get_path(self, index=0): """ Get the i-th path in the current sample. Parameters ---------- index : int, optional Row-index of the path to retrieve from the sample matrix. Default is 0. Returns ------- ndarray The i-th path in the current sample (1-D array of length Nsteps-1). """ return self.__paths[index].copy()
[docs] def get_Fx_avg(self, fx, **kwargs): """ Compute the average value of a functional over the generated paths. Parameters ---------- fx : callable Functional to be averaged over the generated paths. This should be a function that accepts a paths array and returns an array of values. `**kwargs` : dict Additional keyword arguments to be passed to the functional. Returns ------- float The average value of the functional over the generated paths. """ values = fx(self.__paths, **kwargs) # construct an array of f[x_i] return np.mean(values) # compute average of f[x_i] over the generated paths
[docs] def get_Fx_avg_partitioned(self, n_partitions, fx, **kwargs): """ Compute partitioned averages of a functional over the generated paths. The paths are divided into `n_partitions` partitions, and the functional average is computed for each partition. This is useful for binning purposes. Parameters ---------- n_partitions : int Number of partitions to divide the paths into. Must be at least 1. fx : callable Functional to be averaged over the generated paths. `**kwargs` : dict Additional keyword arguments to be passed to the functional. Returns ------- ndarray Array of average values, one for each partition. Raises ------ ValueError If n_partitions is less than 1. """ if n_partitions < 1: raise ValueError("The number of partitions must be at least 1.") partition_size = self.__paths.shape[0] // n_partitions averages = np.empty(n_partitions) for i in range(n_partitions): start_index = i * partition_size end_index = (i+1) * partition_size if i < n_partitions-1 else self.__paths.shape[0] partition_paths = self.__paths[start_index:end_index] values = fx(partition_paths, **kwargs) averages[i] = np.mean(values) return averages
[docs] def converge_acceptance_ratio(self, ratio_target=0.5, precision=0.01, action=None, nthermal=1000, nsample=100, max_iterations=100, progress_bar=True): """ Adjust dx so that the acceptance ratio converges to a target value. This method iteratively adjusts the step size (dx) used in the Metropolis-Hastings algorithm to achieve a desired acceptance ratio. The adjustment follows the heuristic: dx *= (current_ratio / target_ratio) ** 2 Parameters ---------- ratio_target : float, optional Desired fraction of proposed moves to accept. Must be strictly between 0 and 1. Default is 0.5. precision : float, optional Absolute tolerance used to decide when the acceptance ratio is sufficiently close to `ratio_target`. Default is 0.01. action : ho.action, optional Action functional object used to calculate the change in action for proposed moves. If None, the harmonic-oscillator action is used. nthermal : int, optional Number of initial sweeps used to thermalize the paths before measuring the acceptance ratio. Default is 1000. nsample : int, optional Number of sampling sweeps used after each step-size adjustment to measure the current acceptance ratio. Default is 100. max_iterations : int, optional Maximum number of iterations to perform. Default is 100. progress_bar : bool, optional Whether to display a progress bar during convergence. Default is True. Raises ------ ValueError If nthermal, nsample, or max_iterations is not a positive integer, if ratio_target is not between 0 and 1, or if precision is not positive. """ if action is None: action = ho.action() if nthermal < 1: raise ValueError("nthermal must be a positive integer") if nsample < 1: raise ValueError("nsample must be a positive integer") if max_iterations < 1: raise ValueError("max_iterations must be a positive integer") if not (0 < ratio_target < 1): raise ValueError("ratio_target must be between 0 and 1") if precision <= 0: raise ValueError("precision must be a positive number") self.thermalize(action=action, nthermal=nthermal) ratio = self.get_ratio() iterations = 0 if progress_bar: pbar = tqdm(total=max_iterations, desc="Converging acceptance ratio, max iterations: " + str(max_iterations), leave=False) else: pbar = range(max_iterations) while not np.isclose(ratio, ratio_target, atol=precision) and iterations < max_iterations: self.sample(action=action, nsample=nsample, progress_bar=False) ratio = self.get_ratio() self.__dx *= (ratio / ratio_target) ** 2 iterations += 1 if progress_bar: pbar.update(1)