py_core package
Subpackages
Submodules
py_core.Fx_avg module
- py_core.Fx_avg.xx(x, i)[source]
Propagator average per path: \(\frac{1}{N-1}\sum_{j=0}^{N-2} x_{j+i}\, x_{j}\).
Parameters
- xndarray
Matrix of paths, shape (N_c, N-1), where N_c is the number of configurations and N-1 is the number of lattice sites per path (periodic boundary conditions).
- iint
Time-separation index; the correlator is \(\langle x_{j+i} x_j \rangle\).
Returns
- ndarray
Array of per-path averages, shape (N_c,).
py_core.Fx_avg_tilde module
Observable functionals with the change of variable that cancels the ghost mode.
The change of variable is \(x = \tilde{x} + \frac{1}{24}(dt^2\Delta^{(2)} + dt^2\omega^2)\tilde{x}\); the MCMC samples \(\tilde{x}\), and these classes transform to \(x\) before evaluating the propagator correlators.
- py_core.Fx_avg_tilde.D(x)[source]
Discrete second difference with PBC: \(D(x)_i = x_{i+1} + x_{i-1} - 2x_i = dt^2\Delta^{(2)}x_i\).
Parameters
- xndarray
Matrix of paths, shape (N_c, N-1), with periodic boundary conditions.
Returns
- ndarray
Matrix of finite differences \(dt^2 \Delta^{(2)}\) with PBC, same shape as x.
- class py_core.Fx_avg_tilde.xx_tilde(dt, omega=1.0)[source]
Bases:
objectPropagator correlator \(\langle x(t_2)x(t_1)\rangle\) evaluated after the ghost-removing change of variable \(x = \tilde{x} + \frac{1}{24}(dt^2\Delta^{(2)} + dt^2\omega^2)\tilde{x}\).
Parameters
- dtfloat
Lattice spacing.
- omegafloat, optional
Angular frequency, by default 1.0.
py_core.bin_size module
- py_core.bin_size.get_uncorr_n_partitions(rwalk, Fx, **kwargs)[source]
Estimate the number of partitions needed for uncorrelated measurements of an observable.
Parameters
- rwalkRwalk
Rwalk object with a sampled MCMC chain.
- Fxcallable
The observable functional to be measured.
- **kwargs
Additional keyword arguments forwarded to
Rwalk.get_Fx_avg_partitioned().
Returns
- int
Number of partitions such that partitioned averages are statistically consistent (ratio of successive sigmas within 10% of 1).
Raises
- ValueError
If the sample size is less than 2.
py_core.harmonic_oscillator module
- py_core.harmonic_oscillator.fdiff_kinetic(x, i, dt, m=1.0)[source]
Computes a kinetic term contribution for the discretized action:
\(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
- xndarray
current path
- iint
index of t
- dtfloat
time step
- mfloat, optional
mass of the particle, by default 1.
- py_core.harmonic_oscillator.quadratic_potential(x, dt, m=1.0, omega=1.0)[source]
Computes the quadratic potential of a harmonic oscillator. Notice that the
fdiff_kineticfunction computes the kinetic term integrated (multiplied by dt), while thequadratic_potentialfunction computes the potential term without the dt multiplication; thus the caller must multiply by dt to get the correct contribution to the action.Parameters
- xfloat or ndarrays
position value(s)
- dtfloat
time step (not used in computation, but kept for API consistency)
- mfloat, optional
mass of the particle, by default 1.
- omegafloat, optional
angular frequency, by default 1.
Returns
- float or ndarray
potential value(s) without dt multiplication (caller must multiply by dt)
- class py_core.harmonic_oscillator.mesh(t0=0.0, tf=1.0, n=100)[source]
Bases:
objectThis class represents the time mesh for the path integral. It represents a linear time mesh from
t0totfwithnpoints, it is the basic class to represent a lattice.Constructs a time mesh from
t0totfParameters
- t0float, optional
Initial time, by default 0.
- tffloat, optional
Final time, by default 1.
- nint, optional
Number of points in the time mesh, by default 100
- class py_core.harmonic_oscillator.path(time_mesh=None, path=None)[source]
Bases:
objectThis class represents a path with fixed starting and arrival points (
x0,xf)Constructs a path with fixed starting and arrival points. REMARK: starting and arrival points will be automatically be assigned with the shared values
x0,xfParameters
- time_meshndarray, optional
range of time values, by default mesh()
- pathndarray, optional
array of position values, by default np.zeros(mesh.n)
- x0 = 0.0
shared starting point for all paths
- xf = 0.0
shared arrival point for all paths
- __init__(time_mesh=None, path=None)[source]
Constructs a path with fixed starting and arrival points. REMARK: starting and arrival points will be automatically be assigned with the shared values
x0,xfParameters
- time_meshndarray, optional
range of time values, by default mesh()
- pathndarray, optional
array of position values, by default np.zeros(mesh.n)
- class py_core.harmonic_oscillator.action(ipath=None, m=1.0, potential=CPUDispatcher(<function quadratic_potential>), kinetic=CPUDispatcher(<function fdiff_kinetic>), **kwargs)[source]
Bases:
objectThis class represents the Euclidean action of a path.
Euclidean action functional class.
Parameters
- ipathndarray, optional
array of position values, by default None constructs a default path
- mfloat, optional
mass of the particle, by default 1.
- potentialpotential functional, optional
potential energy function, by default quadratic_potential
- kinetickinetic functional, optional
kinetic energy function, by default fdiff_kinetic, only matters for single site evaluation of the action, i.e. the
S_ithmethod. If a functional is provided, all other methods are unaffected.- **kwargs
Additional keyword arguments forwarded to the potential functional (e.g.
omega).
- __init__(ipath=None, m=1.0, potential=CPUDispatcher(<function quadratic_potential>), kinetic=CPUDispatcher(<function fdiff_kinetic>), **kwargs)[source]
Euclidean action functional class.
Parameters
- ipathndarray, optional
array of position values, by default None constructs a default path
- mfloat, optional
mass of the particle, by default 1.
- potentialpotential functional, optional
potential energy function, by default quadratic_potential
- kinetickinetic functional, optional
kinetic energy function, by default fdiff_kinetic, only matters for single site evaluation of the action, i.e. the
S_ithmethod. If a functional is provided, all other methods are unaffected.- **kwargs
Additional keyword arguments forwarded to the potential functional (e.g.
omega).
- normalization(N=None)[source]
Computes the measure normalization:
\(\left(\frac{m}{2\pi dt}\right)^{(N-1)/2}\)
Parameters
- Nint
Number of points in the time-mesh
Returns
- float
correct normalization factor for the path integral measure (Euclidean PI).
- exp_S(ipath=None)[source]
Computes the exponential of (minus) the action of a path
Parameters
- ipathndarray, 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
- log_jacobian(ipath)[source]
Computes the jacobian of \(x(y)\) in the change of variable \(1/(1+\exp(x_{i})) = y_{i}\), this is a diffeomorphism \(\mathbb{R} \to (0,1)\).
Parameters
- ipathndarray
array of \(y_i\) values
Returns
- float
jacobian of the transformation
- y_x(x)[source]
Computes the change of variable \(1/(1+\exp(x_{i})) = y_{i}\), this is a diffeomorphism \(\mathbb{R} \to (0,1)\).
Parameters
- xndarray
array of \(x_i\) values
Returns
- float
array of \(y_i\) values
- x_y(y)[source]
Computes the inverse change of variable \(\log\left(\frac{1}{y_i}-1\right) = x_{i}\), this is a diffeomorphism \((0,1) \to \mathbb{R}\).
Parameters
- yndarray
array of \(y_i\) values
Returns
- float
array of \(x_i\) values
- exp_S_log(ipath=None)[source]
Computes the path integral argument after the change of variable \(1/(1+\exp(x_{i})) = y_{i}\), thus the argument provided must be \(y_i\) in \((0,1)\), not the original \(x_i\). The change of variable is a diffeomorphism \(\mathbb{R} \to (0,1)\).
Parameters
- ipathndarray, optional
array of \(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
- exp_S_log_closed(ipath=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]))[source]
Computes the path integral argument after the change of variable \(1/(1+\exp(x_{i})) = y_{i}\), thus the argument provided must be \(y_i\) in \((0,1)\), not the original \(x_i\). The change of variable is a diffeomorphism \(\mathbb{R} \to (0,1)\).
The path is closed, thus the action is computed with periodic boundary conditions, \(x_0 = x_f\). The
ipathargument must be a matrix of paths, each path must be of the form:[\(x_0,x_1, \ldots, x_{N-1}\)],
the method will automatically append \(x_0 = x_f\) to the end of each path.
Parameters
- ipathndarray of shape (n_paths, n_points), optional
matrix of paths. Defaults to path().path.
- Raises:
ValueError: The path matrix cannot be empty,
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.
- exp_S_closed(ipath=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]))[source]
Computes the path integral argument for a closed path.
The path is closed, thus the action is computed with periodic boundary conditions, \(x_0 = x_f\). The
ipathargument must be a matrix of paths, each path must be of the form:[\(x_0,x_1, \ldots, x_{N-1}\)],
the method will automatically append \(x_0 = x_f\) to the end of each path.
Parameters
- ipathndarray of shape (n_paths, n_points), optional
matrix of paths. Defaults to path().path.
- Raises:
ValueError: If
ipathis empty.- Returns:
ndarray of shape (n_paths,): path integral argument for each closed path, including the normalization factor for the measure.
- S_closed(ipath)[source]
Computes the Euclidean action of closed paths (PBC, \(x_0 = x_f\)).
Parameters
- ipathndarray
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,).
- S_ith(ipath, i)[source]
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
- ipathndarray
current path to evaluate
- iint
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.
py_core.kinetic_term module
- py_core.kinetic_term.fdiff_kinetic_improved(x, i, dt, m=1.0)[source]
Computes the improved finite differences second time derivative times dt for x[i]. This term has O(dt^4) error, however it generates a ghost mode. Explicitly, the term is given by:
\(\frac{1}{2} m x_{i}\left(\Delta^{(2)} - \frac{dt^2}{12}\left(\Delta^{(2)}\right)^2\right)x_{i} dt\)
Parameters
- xndarray
current path
- iint
lattice site index
- dtfloat
time step
- mfloat, optional
mass of the particle. Defaults to 1.0.
Returns
- float
The improved finite differences second time derivative times dt for x[i].
- py_core.kinetic_term.fdiff_kinetic_imp(x, i, dt, m=1.0)[source]
Computes the improved kinetic term for x[i] after the change of variables used to remove the ghost mode. Explicitly, the term is given by:
\(- m \frac{1}{2}x_{i} \Delta^{(2)} x_{i} dt\)
Parameters
- xndarray
current path
- iint
lattice site index
- dtfloat
time step
- mfloat, optional
mass of the particle. Defaults to 1.0.
Returns
- float
The improved kinetic term for x[i].
- py_core.kinetic_term.V_imp(x, dt, m=1.0, omega=1.0)[source]
Computes the improved potential term for x after the change of variables used to remove the ghost mode. Explicitly, the term is given by:
\(\frac{1}{2} m (\omega x)^2 \left(1 + \frac{dt^2 \omega^2}{12}\right)\)
Parameters
- xfloat
Current path value.
- dtfloat
Time step.
- mfloat, optional
Mass of the particle. Defaults to 1.0.
- omegafloat, optional
Angular frequency. Defaults to 1.0.
Returns
- float
The improved potential term for x.
py_core.metropolis module
- class py_core.metropolis.Rwalk(Nsteps=3, x=0.5, dx=0.1, SEED=1)[source]
Bases:
objectRandom 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 __).
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
- Nstepsint, 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.
- xfloat, optional
Endpoint value for the path. Default is 0.5.
- dxfloat, optional
Standard deviation of the Gaussian noise used in the Metropolis-Hastings algorithm. Default is 0.1.
- SEEDint, optional
Random seed for reproducibility. Default is 1.
Raises
- ValueError
If Nsteps is less than 3.
- __init__(Nsteps=3, x=0.5, dx=0.1, SEED=1)[source]
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
- Nstepsint, 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.
- xfloat, optional
Endpoint value for the path. Default is 0.5.
- dxfloat, optional
Standard deviation of the Gaussian noise used in the Metropolis-Hastings algorithm. Default is 0.1.
- SEEDint, optional
Random seed for reproducibility. Default is 1.
Raises
- ValueError
If Nsteps is less than 3.
- evolve(s0, index, action)[source]
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
- s0float
Previously computed action value.
- indexint
Index of the starting path in the paths array.
- actionho.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.
- thermalize(action=None, nthermal=1000)[source]
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
- actionho.action, optional
Action functional object. If None, defaults to ho.action().
- nthermalint, optional
Number of thermalization steps. Default is 1000.
Raises
- ValueError
If nthermal is not a positive integer.
- sample(action=None, nsample=1000, Ncor=1, progress_bar=True)[source]
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
- actionho.action, optional
Action functional object. If None, defaults to ho.action().
- nsampleint, optional
Number of samples to generate. Default is 1000.
- Ncorint, 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_barbool, 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.
- get_ratio()[source]
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.
- get_dx()[source]
Get the current value of
dx.dxis the standard deviation of the Gaussian noise used in the Metropolis-Hastings algorithm.Returns
- float
Current value of
dx.
- get_paths()[source]
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).
- get_path(index=0)[source]
Get the i-th path in the current sample.
Parameters
- indexint, 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).
- get_Fx_avg(fx, **kwargs)[source]
Compute the average value of a functional over the generated paths.
Parameters
- fxcallable
Functional to be averaged over the generated paths. This should be a function that accepts a paths array and returns an array of values.
- **kwargsdict
Additional keyword arguments to be passed to the functional.
Returns
- float
The average value of the functional over the generated paths.
- get_Fx_avg_partitioned(n_partitions, fx, **kwargs)[source]
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_partitionsint
Number of partitions to divide the paths into. Must be at least 1.
- fxcallable
Functional to be averaged over the generated paths.
- **kwargsdict
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.
- converge_acceptance_ratio(ratio_target=0.5, precision=0.01, action=None, nthermal=1000, nsample=100, max_iterations=100, progress_bar=True)[source]
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_targetfloat, optional
Desired fraction of proposed moves to accept. Must be strictly between 0 and 1. Default is 0.5.
- precisionfloat, optional
Absolute tolerance used to decide when the acceptance ratio is sufficiently close to ratio_target. Default is 0.01.
- actionho.action, optional
Action functional object used to calculate the change in action for proposed moves. If None, the harmonic-oscillator action is used.
- nthermalint, optional
Number of initial sweeps used to thermalize the paths before measuring the acceptance ratio. Default is 1000.
- nsampleint, optional
Number of sampling sweeps used after each step-size adjustment to measure the current acceptance ratio. Default is 100.
- max_iterationsint, optional
Maximum number of iterations to perform. Default is 100.
- progress_barbool, 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.