Enhanced sampling: well-tempered metadynamics
The first v2.x enhanced-sampling implementation adds a collective-variable bias to a potential. It is designed to sit on top of the existing UFF force field, but the engine is generic: any type implementing the Potential trait can be sampled. The module covers well-tempered metadynamics, an OPES-style kernel-density bias, histogram reweighting and temperature replica exchange, all with a Langevin thermostat.
Status. Implemented: WTMetaD, importance-weighted OPES, a self-consistent 1D flow, 2D multi-CV OPES/reweighting, block reweighting and temperature replica exchange are in Rust, Python, WASM and the CLI (metadynamics/opes). The exact OPES differential flow is still pending. F134 validates the self-consistent importance-weight flow to a fixed-point residual < 1e-8. See the v2.x roadmap.
Feature. Core since 2.2.0;
alpha-enhanced-samplingremains as an empty compatibility alias.
Why metadynamics
A plain MD trajectory visits the basins it can reach on the simulation time scale. A free-energy difference between two basins, a conformational transition or a desorption event may need much longer. Metadynamics adds a history-dependent bias along a collective variable (CV) so the system is pushed out of visited regions and the bias converges to the negative free energy.
Collective variables
| CV | Definition | Unit |
|---|---|---|
Coordinate { index } | One Cartesian component | Å |
Distance { i, j } | Distance between atoms i and j | Å |
Angle { i, j, k } | Angle i–j–k | rad |
Dihedral { i, j, k, l } | Dihedral i–j–k–l | rad |
Distance uses an analytic Cartesian gradient. Angle and dihedral use a central difference with a 1e-5 Å step; this is robust at the linear limits where the analytic expression is easy to get wrong.
Well-tempered bias
Gaussians are deposited along the CV:
The well-tempered height decays with the local bias:
γ > 1 is the bias factor, h0 the initial height and σ the Gaussian width. A larger γ keeps the bias lower and samples longer; a smaller σ gives a finer resolution but needs more deposits.
The bias force added to the physical force is
Integrator
The implementation uses velocity Verlet with an Ornstein–Uhlenbeck Langevin thermostat:
The friction is configured in ps⁻¹ and converted to fs⁻¹ internally. Masses are in amu; the same conversion factor as the existing MD module is used.
The thermostat must remove the energy the deposition injects. With the default 0.2 kcal/mol every 50 steps of 0.5 fs, a 1 ps⁻¹ friction lets a light walker run hot and underestimate the barrier; F110 uses 10 ps⁻¹ and recovers a 3 kcal/mol double-well barrier to 0.02 kcal/mol.
Free-energy surface
At the end of the run, the total bias is evaluated on a one-dimensional grid:
the well-tempered limit V_b → (1 − 1/γ) F, shifted so that min(F) = 0. The result also contains the CV trace, every deposited Gaussian and the final coordinates. The surface is only meaningful after the bias has converged; a short run is flagged in notes.
API
Generic potential
use sci_form::enhanced_sampling::{
CollectiveVariable, MetaDynamicsConfig, Potential, run_metadynamics,
};
struct Harmonic { k: f64 }
impl Potential for Harmonic {
fn energy(&self, x: &[f64]) -> f64 { 0.5 * self.k * x[0] * x[0] }
fn gradient(&self, x: &[f64], g: &mut [f64]) { g[0] = self.k * x[0]; }
}
let config = MetaDynamicsConfig {
cv: CollectiveVariable::Coordinate { index: 0 },
max_steps: 5_000,
..MetaDynamicsConfig::default()
};
let result = run_metadynamics(&Harmonic { k: 1.0 }, &[1.0], &[1.0], &config)?;masses_amu has one value per Cartesian coordinate, matching the flat coordinate array. The molecule helper repeats each atomic mass three times.
UFF molecule
use sci_form::enhanced_sampling::{CollectiveVariable, MetaDynamicsConfig};
use sci_form::run_uff_metadynamics;
let conformer = sci_form::embed("CCO", 42);
let config = MetaDynamicsConfig {
cv: CollectiveVariable::Dihedral { i: 0, j: 1, k: 2, l: 3 },
max_steps: 20_000,
sigma: 0.2,
grid_min: -3.14,
grid_max: 3.14,
grid_bins: 121,
..MetaDynamicsConfig::default()
};
let result = run_uff_metadynamics("CCO", &conformer.coords, &config)?;The returned MetaDynamicsResult has:
| Field | Meaning |
|---|---|
cv_trace | Step, CV, unbiased potential and bias energy |
gaussians | Step, centre, height and width of every deposit |
free_energy | Grid bounds, bins and F(s) in kcal/mol |
reweighted_free_energy | Histogram-reweighted F(s) in kcal/mol |
final_coords | Final flat coordinates in Å |
final_cv | Final CV value |
notes | Convergence and scope caveats |
OPES-style bias
run_opes replaces the Gaussian history with an importance-weighted kernel-density estimate of the CV values. Each deposited kernel carries w_i = exp(βV(s_i)), so the density is the reweighted estimate P(s) = Σ w_i K(s,s_i) / Σ w_i:
where P is the weighted Gaussian kernel density and P_max is its maximum on the deposited kernels. The reported surface is F(s) = −k_BT ln P(s) = −V(s)/(1 − 1/γ), shifted to min(F) = 0; the 2D multi-CV surface uses the same relation. The bias is zero at the most visited point and negative where the density is low, which lowers the effective barrier. This is an importance-weighted OPES approximation on a bounded grid; it does not integrate the exact OPES differential flow equation.
use sci_form::enhanced_sampling::{OpesConfig, run_opes};
let config = OpesConfig {
cv: CollectiveVariable::Coordinate { index: 0 },
max_steps: 5_000,
..OpesConfig::default()
};
let result = run_opes(&potential, &initial_coords, &masses, &config)?;OpesResult contains the CV trace, the deposited kernels, the bias-derived surface and the reweighted surface.
Self-consistent OPES flow
The kernel weights are not a single-pass estimate. At every deposit, the engine iterates
for flow_iterations fixed-point steps (5 by default) and records the final residual in OpesResult::flow_residual / flow_converged. F134 drives the residual below 1e-8 on a harmonic surface. This is the importance-weight flow on the kernel set; it is not the exact time-dependent OPES differential equation.
Multi-CV OPES
run_multi_opes implements a two-dimensional OPES surface:
use sci_form::enhanced_sampling_multi::MultiOpesConfig;
use sci_form::run_multi_opes;
let config = MultiOpesConfig {
max_steps: 10_000,
pace_steps: 100,
x_min: -2.0,
x_max: 2.0,
y_min: -2.0,
y_max: 2.0,
..MultiOpesConfig::default()
};
let result = run_multi_opes(&potential, &initial_coords, &masses, &config)?;MultiOpesResult contains:
| Field | Meaning |
|---|---|
trace | Step, two CV values, potential and bias |
kernels | 2D centres and importance weights |
free_energy | 2D bias-derived surface |
reweighted_free_energy | 2D histogram-reweighted surface |
reweight_free_energy_2d builds the reweighted surface directly from a trace.
Validation and limits
run_multi_opes requires non-empty initial_coords and masses_amu of equal length, finite coordinates and finite positive masses. The configuration must have finite positive sigma_x/sigma_y, bias_factor > 1, positive finite temperature and time step, non-negative friction, non-zero pace_steps, max_steps and trace_stride, at least two bins per axis, finite grid bounds with max > min, positive regularization and at least one flow iteration. The initial potential energy and both CV values must be finite; a non-finite trajectory or free-energy surface is a numerical error.
Both dense surfaces use nx × ny bins. The product is checked for overflow and capped at 4,194,304 points (about 32 MiB per f64 surface). The same limit applies to reweight_free_energy_2d, which also rejects empty traces, non-finite CV/bias values and reweighting weights that overflow. The simulation is deterministic for a fixed seed.
Reweighting
reweight_free_energy converts a biased CV trace into an unbiased histogram. Each sample is weighted by exp(+V_bias/kBT):
The result is shifted so the minimum is zero. Samples outside the grid are clamped to the nearest edge bin.
For correlated samples, use reweight_free_energy_correlated with a block_size. It returns the same surface plus a per-bin block standard error. With N trace points, the number of blocks is
and the reported error for bin
flowchart LR
A["CV trace<br/>cv, bias"] --> B["validate config + finite values"]
B --> C["per-bin weights<br/>exp(bias/kBT)"]
C --> D["surface<br/>-kBT ln(sum w)"]
C --> E["blocks of block_size"]
E --> F["per-bin block SE"]
D --> G["ReweightResult"]
F --> G
Validation contracts:
grid_binslies in2..=4_194_304,grid_max > grid_minis finite,temperature_k > 0andblock_size >= 1; an empty trace or non-finitecv/biasis rejected.reweight_free_energy_correlatedneeds at least two blocks: ablock_sizeequal to or larger than the trace length returns a validation error instead of reporting a fake zero error.- The correlated block matrix is capped at 4,194,304 cells (
n_blocks × grid_bins); increaseblock_sizeor reducegrid_binsif the request exceeds it. - A weight that overflows or underflows to zero is a numerical error; it never produces a non-finite surface or JSON
nullvalues. - Python maps validation failures to
ValueError; WASM returns{"error": "..."}.
use sci_form::enhanced_sampling::{
ReweightConfig, reweight_free_energy, reweight_free_energy_correlated,
};
let config = ReweightConfig {
grid_min: -1.5,
grid_max: 1.5,
grid_bins: 61,
temperature_k: 300.0,
block_size: 20,
};
let surface = reweight_free_energy(&result.cv_trace, &config)?;
let correlated = reweight_free_energy_correlated(&result.cv_trace, &config)?;
assert_eq!(correlated.surface.values.len(), surface.values.len());
assert_eq!(correlated.standard_error.len(), surface.values.len());Replica exchange
The same module also provides temperature replica exchange. Each replica runs at its own temperature, and adjacent pairs are exchanged every swap_interval steps with
The result contains one potential-energy trace per replica, every swap proposal with its Metropolis exponent, and the final coordinates. It is a generic Potential engine, so it works with the analytic double well and with the UFF adapter.
use sci_form::enhanced_sampling::{ReplicaExchangeConfig, run_replica_exchange};
let config = ReplicaExchangeConfig {
temperatures_k: vec![300.0, 400.0, 500.0, 600.0],
max_steps: 10_000,
..ReplicaExchangeConfig::default()
};
let result = run_replica_exchange(&potential, &initial_coords, &masses, &config)?;Replica exchange is not a substitute for a converged metadynamics bias; it improves barrier crossing when the replicas overlap in energy. The swap acceptance rate should be inspected in result.swaps.
Validation
| Gate | Observable | Result |
|---|---|---|
| Distance CV gradient | Analytic vs finite difference | < 1e-12 |
| 1D double well | Visits both minima | min < -0.5, max > 0.5 |
| UFF gradient | Analytic vs finite difference | < 1e-4 kcal/mol/Å |
| UFF metadynamics | 200-step ethanol run | finite trace and deposits |
| Invalid bias factor | γ = 1 | rejected |
| Replica exchange | 4 replicas, 500 steps | swap proposals recorded, all final coordinates finite |
| OPES double well | 4,000 steps | both minima visited |
| 2D OPES harmonic well | 2,000 steps | finite trace and surfaces |
| OPES flow fixed point | 50,000 steps, 200 iterations | residual 4.7e-11, 1D PMF RMSE 0.245 |
| 2D reweighting constant bias | flat trace | finite bins zero |
| Reweighting constant bias | flat trace | zero surface |
| Block reweighting | 3 samples, block 2 | finite non-negative standard errors |
Malformed sampling input is an input error: Python raises ValueError for a zero/negative height or sigma, bias_factor <= 1, zero pace/max/trace stride, non-finite temperature or time step, invalid CV atom indices, coordinate arrays that do not match the UFF molecule, and unknown CV kinds. WASM returns {"error": "..."}.
The double-well test checks exploration, not a converged barrier. A quantitative barrier benchmark needs a longer run and is part of the promotion gate.
Bindings
| Surface | Entry point |
|---|---|
| CLI | metadynamics, opes (UFF molecule, optional JSON config) |
| WASM | run_uff_metadynamics, run_uff_opes, reweight_free_energy, reweight_free_energy_correlated, reweight_free_energy_2d |
| Python | same five functions; results are JSON strings |
The WASM and Python entry points take the serialized configuration types (MetaDynamicsConfig, OpesConfig, ReweightConfig, MultiReweightConfig).
Limitations
- Metadynamics biases one CV per run; multi-dimensional metadynamics is a follow-up. OPES supports 1D and 2D grids.
- The OPES implementation is an importance-weighted bounded-grid approximation, not the exact OPES differential flow equation.
- Multi-CV support is two-dimensional; higher-dimensional grids are not implemented.
- The block error is a simple block-average diagnostic, not a full autocorrelation analysis.
- The bias-derived surface and the reweighted surface can disagree on short runs.
- The Langevin thermostat is the only thermostat in this module; the existing NVT/NPT integrators are not yet coupled to the bias.
- The CV gradient is numerical for angles and dihedrals.
- A bad CV hides the slow mode. The API cannot detect that for the user.
Next steps
- Add multi-dimensional CVs and a grid in more than one dimension.
- Implement the exact OPES differential flow equations.
- Extend multi-CV grids above two dimensions.
- Add autocorrelation-aware error propagation.
- Wire the bias into the existing NVT/NPT dynamics module.
- Benchmark a known free-energy landscape against long unbiased MD.