Metadata-Version: 2.4
Name: gle_sim
Version: 0.1.0
Classifier: Programming Language :: Python
Classifier: Programming Language :: Rust
Requires-Dist: pydantic>=2.5
Requires-Dist: numpy>=1.15
Requires-Dist: scipy>=1.9
Requires-Dist: toml>=0.1
Requires-Dist: matplotlib>=3.1
Requires-Dist: pytest>=7 ; extra == 'tests'
Provides-Extra: tests
Summary: Integrate GLE via Markovian Embedding.
Author: lucastepper <lucas.tepper.91@gmail.com>
Author-email: lucastepper <lucas.tepper.91@gmail.com>
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# GLE Sim

**Generalized Langevin dynamics via Markovian embedding**

A module for simulating stochastic processes based on generalized Langevin
equations (GLEs). The dynamics are simulated using an extended Markovian system,
in which the coordinate of interest is coupled to auxiliary degrees of freedom.
Integrating out these auxiliary variables yields GLE dynamics with exponential
or exponentially damped oscillatory memory kernels.

## Installation

Run the following command from within the repository:

```sh
pip install .
```

## Examples

To run a GLE simulation, create a configuration object and pass it to
`gle_sim.integrate`:

```python
import numpy as np
import gle_sim

config = gle_sim.Config.default()
config.pmf = gle_sim.Harmonic(k=15.0)
config.kernel = gle_sim.Exponential(
    gammas=np.array([100.0]),
    taus=np.array([1.0]),
)
config.steps = 10_000
config.dt = 0.001
config.x0 = 0.0
config.v0 = 0.0
config.seed = 42

trajectory = gle_sim.integrate(config)
```

### Configuration attributes

| Attribute | Description |
| --- | --- |
| `integrator` | Integration method: `euler_maruyama`, `runge_kutta_4`, `leap_frog`, `improved_euler`, or `runge_kutta_4_pos_mass`. |
| `pmf` | Potential of mean force, such as `Harmonic` or `DoubleWell`; `None` means no potential. |
| `kernel` | Memory kernel, a list of kernels, or `None`. |
| `steps` | Number of integration steps. |
| `stride` | Save the position every this many integration steps; defaults to 1. |
| `dt` | Integration time step. |
| `kbt` | Thermal energy, $k_\mathrm{B}T$. |
| `mass` | Constant particle mass. |
| `x0`, `v0` | Initial position and velocity; `None` uses the simulator's initialization procedure. |
| `seed` | Random number seed; `None` generates a new seed for each simulation. |
| `last_seed` | Read-only record of the most recently generated seed. |
| `nthreads` | Number of parallel trajectories; values less than or equal to zero use the available CPU count. |
| `verbose` | Print a brief configuration summary when integrating. |
| `mass_of_x` | Sampled position-dependent masses for `runge_kutta_4_pos_mass`. |
| `values_mass_of_x` | Positions corresponding to `mass_of_x`. |
| `spline_matrix_mass` | Cubic spline coefficients for the position-dependent mass. |
| `mass_fit_params` | Coefficients `[a, b, c, d, e, f]` for the position-dependent mass fit $m(x) = a\exp[(x/b)^c] + d + ex + fx^2$, as an alternative to the spline inputs. |

Use `gle_sim.get_config(...)` to construct a configuration from keyword arguments.
It also generates `spline_matrix_mass` when `mass_of_x` and `values_mass_of_x` are
provided without spline coefficients.

### PMF options

Set `config.pmf` to one of the following `gle_sim` objects, or to `None` for no
potential:

| PMF | Attributes and behavior |
| --- | --- |
| `Harmonic` | `k`: spring constant, with $U(x) = kx^2/2$. |
| `DoubleWell` | `u0`: barrier height; `l`: distance from the origin to either minimum, with $U(x) = u_0[(x/l)^2 - 1]^2$. |
| `LinearInterpolation` | `values`: position grid; `fe`: potential values on the grid; `check_grad` (default `True`): check that boundary gradients point toward the interior. Uses linear interpolation of the numerically computed potential gradient. |
| `CubicSplineInterpolation` | `values`: position grid; `fe`: potential values on the grid; `spl_m`: cubic spline coefficients. Use `CubicSplineInterpolation.from_values_fe(values, fe)` to compute the coefficients automatically. |

## GLEs

For a constant mass and a position-independent memory kernel, the standard GLE
can be written as

```math
m\frac{dv(t)}{dt}
= -\frac{dU}{dx}\bigl(x(t)\bigr)
- \int_0^t \Gamma(t-s)\,v(s)\,ds
+ R(t).
```

Here, $x(t)$ and $v(t) = \frac{dx(t)}{dt}$ are the position and velocity, $m$ is the particle mass,
$U(x)$ is the potential of mean force, and $\Gamma(t)$ is the memory kernel.

### Exponential and oscillating kernels

Set `config.kernel` to an `Exponential` or `Oscillating` object. Each entry in
the parameter arrays describes one term in the kernel sum:

```python
exponential = gle_sim.Exponential(
    gammas=np.array([100.0]),
    taus=np.array([1.0]),
    ys0=None,
)
oscillating = gle_sim.Oscillating(
    gammas=np.array([10.0]),
    taus=np.array([0.2]),
    omegas=np.array([8.5]),
    ys0=None,
    vys0=None,
)
```

Here, `gammas` contains the friction parameters $\gamma_i$, `taus` contains the
decay times $\tau_i$, and `omegas` contains the angular frequencies $\omega_i$.
The optional `ys0` and `vys0` arrays specify initial auxiliary coordinates and
velocities; `None` uses the simulator's initialization procedure.

The exponential fit is

```math
\Gamma_{\mathrm{exp}}(t)
= \sum_i \frac{\gamma_i}{\tau_i}\exp(-t/\tau_i).
```

The exponentially damped oscillating fit is

```math
\Gamma_{\mathrm{osc}}(t)
= \sum_i \frac{\gamma_i\tau_i}{2}
  \left(\omega_i^2 + \frac{1}{\tau_i^2}\right)
  \exp(-t/\tau_i)
  \left[\cos(\omega_i t)
  + \frac{\sin(\omega_i t)}{\tau_i\omega_i}\right].
```

For these constant-mass kernels, `gammas` has units of mass/time, `taus` has
units of time, and `omegas` has units of inverse time.

### Position-dependent mass with a position-independent kernel

We can also integrate the coordinate-dependent GLE

```math
\frac{dv(t)}{dt}
= -\frac{U_{\mathrm{eff}}'(x(t),v(t))}{m(x(t))}
- \int_0^t \Gamma(t-s)\,v(s)\,ds
+ F_R(t).
```

The effective potential is

```math
U_{\mathrm{eff}}(x,v)
= U_{\mathrm{pmf}}(x) + \frac{m(x)}{2}v^2
+ \frac{k_\mathrm{B}T}{2}\ln m(x).
```

Use `integrator="runge_kutta_4_pos_mass"` with a position-dependent mass
(`mass_of_x` and `values_mass_of_x`, or `mass_fit_params`) and an `Exponential`
kernel (only the exponential option is
available). Here, `gammas` has units of **1/time**.

### Position-dependent mass and kernel

When the memory also depends on position, the corresponding form is

```math
\frac{dv(t)}{dt}
= -\frac{U_{\mathrm{eff}}'(x(t),v(t))}{m(x(t))}
- \int_0^t \Gamma(t-s,x(s))\,v(s)\,ds
+ F_R(t),
```

where the prime denotes differentiation with respect to $x$ at fixed $v$.

Use this case by combining the same position-dependent mass inputs and
`runge_kutta_4_pos_mass` integrator with `gle_sim.ExponentialPosMem`. Supply
`taus` and either `gammas` on a position grid `values`, or `gamma_fit_params`
with `gamma_fit_ranges`. The friction parameters $\gamma_i(x)$, represented
by `gammas` or the fitted functions, have units of **1/time**.

For the polynomial fit, row $i$ of `gamma_fit_params` contains coefficients
`[c_i0, c_i1, ...]` in ascending power order, and row $i$ of
`gamma_fit_ranges` contains the bounds $[a_i,b_i]$:

```math
\gamma_i(x) = \max\left(0,\sum_{j=0}^{p}c_{ij}\tilde x_i^j\right),
\qquad \tilde x_i = \min(b_i,\max(a_i,x)).
```

The position is clamped to the fitting interval, and negative fitted values
are clipped to zero.

## Integrators

The integrators advance the extended Markovian state $z=(x,v,\ldots)$,
including the auxiliary variables. Write its stochastic dynamics as
$dz=a(z)\,dt+B(z)\,dW$, with step size $h=\mathrm{dt}$ and independent standard
normal vectors $\xi_n$ drawn once per step.

### Euler–Maruyama (`euler_maruyama`)

A single explicit drift and noise update:

```math
z_{n+1}=z_n+h\,a(z_n)+\sqrt h\,B(z_n)\xi_n.
```

### Runge–Kutta 4 (`runge_kutta_4`)

Four stages reuse the same noise draw within each step. Define
$D_n(z)=h\,a(z)+\sqrt h\,B(z)\xi_n$:

```math
\begin{aligned}
k_1&=D_n(z_n), & k_2&=D_n(z_n+k_1/2),\\
k_3&=D_n(z_n+k_2/2), & k_4&=D_n(z_n+k_3),\\
z_{n+1}&=z_n+(k_1+2k_2+2k_3+k_4)/6.
\end{aligned}
```

The fourth-order designation refers to the deterministic RK scheme.

### Leapfrog (`leap_frog`)

A half position step, a full velocity update, and another half position step
are applied to the particle and auxiliary coordinates:

```math
\begin{aligned}
q_{n+1/2}&=q_n+\tfrac h2 u_n,\\
u_{n+1}&=u_n+\Delta u(q_{n+1/2},u_n,\xi_n),\\
q_{n+1}&=q_{n+1/2}+\tfrac h2 u_{n+1}.
\end{aligned}
```

Here $\Delta u$ includes the potential force and the kernel-specific velocity
and noise updates. Only kernels that support auxiliary velocity updates are
accepted.

### Improved Euler (`improved_euler`)

Follows A. J. Roberts, [*Modify the Improved Euler scheme to integrate stochastic
differential equations* (2012)](https://arxiv.org/abs/1210.0933).

A stochastic predictor–corrector uses the same Gaussian draw in both stages
and an independent random sign $S_n\in\{-1,+1\}$:

```math
\begin{aligned}
k_1&=h\,a(z_n)+\sqrt h\,B(z_n)(\xi_n-S_n\mathbf 1),\\
k_2&=h\,a(z_n+k_1)+\sqrt h\,B(z_n+k_1)(\xi_n+S_n\mathbf 1),\\
z_{n+1}&=z_n+\tfrac12(k_1+k_2).
\end{aligned}
```

### Runge–Kutta 4 with position-dependent mass (`runge_kutta_4_pos_mass`)

Uses the same four-stage RK update above, evaluating the mass and its
derivative at each stage. The velocity drift includes the mass correction:

```math
a_v(z)=-\frac{U_{\mathrm{pmf}}'(x)}{m(x)}
-\frac{m'(x)}{2m(x)}\left(v^2+\frac{k_\mathrm{B}T}{m(x)}\right)
+\sum_i\frac{y_i}{\tau_i}.
```

The final term is the auxiliary contribution for the exponential embeddings
described above.

## Transition-path probability sampling

`gle_sim.sample_tps` samples the transition-path histogram during a simulation
without storing the full trajectory. With a configured simulation, specify the
two basin boundaries and number of bins:

```python
config.integrator = "runge_kutta_4"  # or "runge_kutta_4_pos_mass"
tp_hist, n_frames, n_transitions = gle_sim.sample_tps(
    config, start=-0.5, end=0.5, nbins=20
)
```

The results are transition-path frame counts per bin, the number of analyzed
frames, and the number of transitions. Normalize `tp_hist` by the total
occupancy counts in the same bins to obtain the conditional probability
$P(\mathrm{TP}\mid x)$.

## Returning the full state

Build from source with the Rust feature `return_full_state` enabled:

```sh
pip install . --config-settings="build-args=--features return_full_state"
```

`gle_sim.integrate` then returns positions, velocities, and all auxiliary
variables in an array of shape `(nthreads, steps // stride + 1, state_dimension)`,
including the thread axis when `nthreads=1`.

