import numpy as np
from numba import njit
[docs]
@njit(boundscheck=True, fastmath=True)
def fdiff_kinetic(x, i, dt, m=1.0):
r"""
Computes a kinetic term contribution for the discretized action:
:math:`T = \frac{m \left(x_{i}^2 - x_{i}(x_{i+1} + x_{i-1})\right)}{dt}`
REMARK: the kinetic term is already integrated (multiplied by dt).
Parameters
----------
x : ndarray
current path
i : int
index of t
dt : float
time step
m : float, optional
mass of the particle, by default 1.
"""
return m * (x[i] ** 2 - x[i] * (x[i - 1] + x[(i + 1) % x.size])) / dt
[docs]
@njit(fastmath=True)
def quadratic_potential(x, dt, m=1.0, omega=1.0):
"""
Computes the quadratic potential of a harmonic oscillator.
Notice that the :code:`fdiff_kinetic` function computes the kinetic term integrated (multiplied by dt), while
the :code:`quadratic_potential` function computes the potential term without the dt multiplication;
thus the caller must multiply by dt to get the correct contribution to the action.
Parameters
----------
x : float or ndarrays
position value(s)
dt : float
time step (not used in computation, but kept for API consistency)
m : float, optional
mass of the particle, by default 1.
omega : float, optional
angular frequency, by default 1.
Returns
-------
float or ndarray
potential value(s) without dt multiplication (caller must multiply by dt)
"""
return 0.5 * m * omega**2 * x**2
[docs]
class mesh:
"""
This class represents the time mesh for the path integral.
It represents a linear time mesh from :code:`t0` to :code:`tf` with :code:`n` points,
it is the basic class to represent a lattice.
"""
[docs]
def __init__(self, t0=0.0, tf=1.0, n=100):
"""
Constructs a time mesh from :code:`t0` to :code:`tf`
Parameters
----------
t0 : float, optional
Initial time, by default 0.
tf : float, optional
Final time, by default 1.
n : int, optional
Number of points in the time mesh, by default 100
"""
n = int(n)
if n < 2:
raise ValueError("Number of time steps must be at least 2.")
self.t0 = t0
self.tf = tf
self.n = n
self.dt = (tf - t0) / (n - 1)
self.t = np.linspace(t0, tf, n)
[docs]
class path:
"""
This class represents a path with fixed starting and arrival points (:code:`x0`, :code:`xf`)
"""
x0 = 0.0
"""
shared starting point for all paths
"""
xf = 0.0
"""
shared arrival point for all paths
"""
[docs]
def __init__(self, time_mesh=None, path=None):
"""
Constructs a path with fixed starting and arrival points.
REMARK: starting and arrival points will be automatically be assigned
with the shared values :code:`x0`, :code:`xf`
Parameters
----------
time_mesh : ndarray, optional
range of time values, by default mesh()
path : ndarray, optional
array of position values, by default np.zeros(mesh.n)
"""
if time_mesh is None:
time_mesh = mesh()
if path is None:
path = np.zeros(time_mesh.n)
if path.size != time_mesh.n:
raise ValueError("Path size must match time mesh size.")
self.mesh = time_mesh
self.path = path
self.path[0] = self.x0
self.path[-1] = self.xf
[docs]
def set_point(self, i=0, x=0.0):
"""
Explicitly sets the value of the i-th position.
Parameters
----------
i : int, optional
position index, by default 0
x : float, optional
position value, by default 0.
"""
self.path[i] = x
[docs]
class action:
"""
This class represents the Euclidean action of a path.
"""
[docs]
def __init__(
self, ipath=None, m=1.0, potential=quadratic_potential, kinetic=fdiff_kinetic, **kwargs
):
"""
Euclidean action functional class.
Parameters
----------
ipath : ndarray, optional
array of position values, by default None constructs a default path
m : float, optional
mass of the particle, by default 1.
potential : potential functional, optional
potential energy function, by default quadratic_potential
kinetic : kinetic functional, optional
kinetic energy function, by default fdiff_kinetic, only matters for
single site evaluation of the action, i.e. the :code:`S_ith` method. If
a functional is provided, all other methods are unaffected.
**kwargs
Additional keyword arguments forwarded to the potential functional
(e.g. ``omega``).
"""
if ipath is None:
ipath = path()
self.potential = potential
self.kinetic = kinetic
self.path = ipath
self.x0 = ipath.x0
self.xf = ipath.xf
self.dt = ipath.mesh.dt
self.m = m
self.kwargs = kwargs
[docs]
def normalization(self, N=None):
r"""
Computes the measure normalization:
:math:`\left(\frac{m}{2\pi dt}\right)^{(N-1)/2}`
Parameters
----------
N : int
Number of points in the time-mesh
Returns
-------
float
correct normalization factor for the path integral measure (Euclidean PI).
"""
if N is None:
N = self.path.mesh.n
return (self.m / (2 * np.pi * self.dt)) ** ((N - 1) / 2)
[docs]
def exp_S(self, ipath=None):
"""
Computes the exponential of (minus) the action of a path
Parameters
----------
ipath : ndarray, optional
array of intermediate position values (endpoints excluded),
by default self.path.path[1:-1]
Returns
-------
ndarray
exponential of (minus) the action for each path, including the
measure normalization factor
"""
if ipath is None:
ipath = self.path.path[1:-1]
ipath = np.asarray(ipath, dtype=float)
if ipath.size == 0:
raise ValueError("Path cannot be empty.")
if ipath.ndim == 1:
ipath = ipath[None, :] # reshape a 1D array to a single row matrix, as we expect a matrix of paths
x = np.empty((ipath.shape[0], ipath.shape[1] + 2), dtype=float)
x[:, 0] = self.x0
x[:, -1] = self.xf
x[:, 1:-1] = ipath
dx = np.diff(x, axis=1)
kinetic = 0.5 * self.m * np.sum((dx**2) / self.dt, axis=1)
potential = (
np.sum(self.potential(x[:, :-1], self.dt, m=self.m, **self.kwargs), axis=1) * self.dt
)
return np.exp(-(kinetic + potential)) * self.normalization(x.shape[1])
[docs]
def log_jacobian(self, ipath):
r"""
Computes the jacobian of :math:`x(y)` in the change of variable :math:`1/(1+\exp(x_{i})) = y_{i}`,
this is a diffeomorphism :math:`\mathbb{R} \to (0,1)`.
Parameters
----------
ipath : ndarray
array of :math:`y_i` values
Returns
-------
float
jacobian of the transformation
"""
return np.prod(1 / (ipath * (1 - ipath)), axis=1)
[docs]
def y_x(self, x):
r"""
Computes the change of variable :math:`1/(1+\exp(x_{i})) = y_{i}`,
this is a diffeomorphism :math:`\mathbb{R} \to (0,1)`.
Parameters
----------
x : ndarray
array of :math:`x_i` values
Returns
-------
float
array of :math:`y_i` values
"""
return 1 / (1 + np.exp(x))
[docs]
def x_y(self, y):
r"""
Computes the inverse change of variable :math:`\log\left(\frac{1}{y_i}-1\right) = x_{i}`,
this is a diffeomorphism :math:`(0,1) \to \mathbb{R}`.
Parameters
----------
y : ndarray
array of :math:`y_i` values
Returns
-------
float
array of :math:`x_i` values
"""
return np.log(1 / y - 1)
[docs]
def exp_S_log(self, ipath=None):
r"""
Computes the path integral argument after the change of variable :math:`1/(1+\exp(x_{i})) = y_{i}`,
thus the argument provided must be :math:`y_i` in :math:`(0,1)`, not the original :math:`x_i`.
The change of variable is a diffeomorphism :math:`\mathbb{R} \to (0,1)`.
Parameters
----------
ipath : ndarray, optional
array of :math:`y_i` values in (0,1), by default the transformed
intermediate points of self.path
Returns
-------
ndarray
Jacobian * exp(-S) for each path, including the measure normalization
"""
if ipath is None:
ipath = np.array([self.y_x(self.path.path[1:-1])])
if ipath.size == 0:
raise ValueError("Path cannot be empty.")
if ipath.ndim == 1:
ipath = ipath[None, :] # reshape a 1D array to a single row matrix, as we expect a matrix of paths
x = np.empty((ipath.shape[0], ipath.shape[1] + 2), dtype=float)
x[:, 0] = self.x0
x[:, -1] = self.xf
x[:, 1:-1] = self.x_y(ipath)
jacobian = self.log_jacobian(ipath)
dx = np.diff(x, axis=1)
kinetic = 0.5 * self.m * np.sum((dx**2) / self.dt, axis=1)
# remark: the potential term is multiplied by dt here, but not in the potential function itself
potential = (
np.sum(self.potential(x[:, :-1], self.dt, m=self.m, **self.kwargs), axis=1) * self.dt
)
return (
np.exp(-(kinetic + potential)) * jacobian * self.normalization(x.shape[1])
)
[docs]
def exp_S_log_closed(self, ipath=path().path):
r"""Computes the path integral argument after the change of variable :math:`1/(1+\exp(x_{i})) = y_{i}`,
thus the argument provided must be :math:`y_i` in :math:`(0,1)`, not the original :math:`x_i`.
The change of variable is a diffeomorphism :math:`\mathbb{R} \to (0,1)`.
The path is closed, thus the action is computed with periodic boundary conditions, :math:`x_0 = x_f`.
The :code:`ipath` argument must be a matrix of paths, each path must be of the form:
[:math:`x_0,x_1, \ldots, x_{N-1}`],
the method will automatically append :math:`x_0 = x_f` to the end of each path.
Parameters
----------
ipath : ndarray of shape (n_paths, n_points), optional
matrix of paths. Defaults to path().path.
Raises:
ValueError: The path matrix cannot be empty, :code:`ipath.size` > 0.
Returns:
ndarray of shape (n_paths,): array of the path integral argument for each path,
after the change of variable and including the jacobian; includes the normalization factor for the measure.
"""
ipath = np.asarray(ipath, dtype=float)
if ipath.size == 0:
raise ValueError("Path cannot be empty.")
if ipath.ndim == 1:
ipath = ipath[None, :]
jacobian = self.log_jacobian(ipath)
x = self.x_y(ipath)
x = np.column_stack([x, x[:, :1]]) # make x0 = xf: append x0
dx = np.diff(x, axis=1)
kinetic = 0.5 * self.m * np.sum((dx**2) / self.dt, axis=1)
# remark: the potential term is multiplied by dt here, but not in the potential function itself
potential = (
np.sum(self.potential(x[:, :-1], self.dt, m=self.m), axis=1) * self.dt
)
return (
np.exp(-(kinetic + potential)) * self.normalization(x.shape[1]) * jacobian
)
[docs]
def exp_S_closed(self, ipath=path().path):
r"""Computes the path integral argument for a closed path.
The path is closed, thus the action is computed with periodic boundary conditions, :math:`x_0 = x_f`.
The :code:`ipath` argument must be a matrix of paths, each path must be of the form:
[:math:`x_0,x_1, \ldots, x_{N-1}`],
the method will automatically append :math:`x_0 = x_f` to the end of each path.
Parameters
----------
ipath : ndarray of shape (n_paths, n_points), optional
matrix of paths. Defaults to path().path.
Raises:
ValueError: If :code:`ipath` is empty.
Returns:
ndarray of shape (n_paths,): path integral argument for each closed
path, including the normalization factor for the measure.
"""
ipath = np.asarray(ipath, dtype=float)
if ipath.size == 0:
raise ValueError("Path cannot be empty.")
if ipath.ndim == 1:
ipath = ipath[None, :]
x = ipath
x = np.column_stack([x, x[:, :1]]) # make x0 = xf
dx = np.diff(x, axis=1)
kinetic = 0.5 * self.m * np.sum((dx**2) / self.dt, axis=1)
# remark: the potential term is multiplied by dt here, but not in the potential function itself
potential = (
np.sum(self.potential(x[:, :-1], self.dt, m=self.m), axis=1) * self.dt
)
return np.exp(-(kinetic + potential)) * self.normalization(x.shape[1])
[docs]
def S_closed(self, ipath):
"""Computes the Euclidean action of closed paths (PBC, :math:`x_0 = x_f`).
Parameters
----------
ipath : ndarray
Matrix of paths, shape (n_paths, n_points); the first column is
automatically appended as the last (closure).
Returns
-------
ndarray
Action value for each path, shape (n_paths,).
"""
ipath = np.asarray(ipath, dtype=float)
if ipath.size == 0:
raise ValueError("Path cannot be empty.")
if ipath.ndim == 1:
ipath = ipath[None, :]
x = ipath
x = np.column_stack([x, x[:, :1]]) # make x0 = xf
dx = np.diff(x, axis=1)
kinetic = 0.5 * self.m * np.sum((dx**2) / self.dt, axis=1)
# remark: the potential term is multiplied by dt here, but not in the potential function itself
potential = (
np.sum(self.potential(x[:, :-1], self.dt, m=self.m, **self.kwargs), axis=1) * self.dt
)
return kinetic + potential
[docs]
def S_ith(self, ipath, i):
"""Computes the contribution to the action
of the single site, that is all the terms in the action
in which the i-th site appears.
Parameters
----------
ipath : ndarray
current path to evaluate
i : int
index of the site
Returns
-------
float
single site contribution to the action, that is all the terms in the action in which the i-th site appears.
"""
# remark: the potential term is multiplied by dt here, but not in the potential function itself
# the kinetic term must already be integrated (multiplied by dt) in the self.kinetic function.
return self.potential(ipath[i], self.dt, m=self.m, **self.kwargs) * self.dt + self.kinetic(
ipath, i, self.dt, self.m
)