Skip to content

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-sampling remains 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 ​

CVDefinitionUnit
Coordinate { index }One Cartesian componentÅ
Distance { i, j }Distance between atoms i and jÅ
Angle { i, j, k }Angle i–j–krad
Dihedral { i, j, k, l }Dihedral i–j–k–lrad

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:

Vb(s,t)=∑khkexp⁡(−(s−sk)22σ2).

The well-tempered height decays with the local bias:

hk=h0exp⁡(−Vb(sk,t)RΔT),ΔT=(γ−1)T.

γ > 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

Fb=−∂Vb∂s∂s∂x.

Integrator ​

The implementation uses velocity Verlet with an Ornstein–Uhlenbeck Langevin thermostat:

vn+1=e−γΔtvn+kBTm(1−e−2γΔt)ξn.

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:

F(s)≈−γγ−1Vb(s),

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 ​

rust
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 ​

rust
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:

FieldMeaning
cv_traceStep, CV, unbiased potential and bias energy
gaussiansStep, centre, height and width of every deposit
free_energyGrid bounds, bins and F(s) in kcal/mol
reweighted_free_energyHistogram-reweighted F(s) in kcal/mol
final_coordsFinal flat coordinates in Å
final_cvFinal CV value
notesConvergence 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:

V(s)=(1−1γ)kBTln⁡(P(s)Pmax+ϵ),

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.

rust
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

wi←eβV(si),P(s)=∑iwiK(s,si)∑iwi,

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:

rust
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:

FieldMeaning
traceStep, two CV values, potential and bias
kernels2D centres and importance weights
free_energy2D bias-derived surface
reweighted_free_energy2D 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):

F(s)=−kBTln⁡(∑i∈seVb(si)/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

nblocks=⌈Nblock_size⌉,

and the reported error for bin s is the standard error of the mean block weight, converted to kcal/mol:

SE(Fs)≈kBTVar(wb,s)/nblocksw―b,s.
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_bins lies in 2..=4_194_304, grid_max > grid_min is finite, temperature_k > 0 and block_size >= 1; an empty trace or non-finite cv/bias is rejected.
  • reweight_free_energy_correlated needs at least two blocks: a block_size equal 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); increase block_size or reduce grid_bins if 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 null values.
  • Python maps validation failures to ValueError; WASM returns {"error": "..."}.
rust
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

Pacc=min[1,e(βi−βj)(Ui−Uj)],β=1kBT.

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.

rust
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 ​

GateObservableResult
Distance CV gradientAnalytic vs finite difference< 1e-12
1D double wellVisits both minimamin < -0.5, max > 0.5
UFF gradientAnalytic vs finite difference< 1e-4 kcal/mol/Å
UFF metadynamics200-step ethanol runfinite trace and deposits
Invalid bias factorγ = 1rejected
Replica exchange4 replicas, 500 stepsswap proposals recorded, all final coordinates finite
OPES double well4,000 stepsboth minima visited
2D OPES harmonic well2,000 stepsfinite trace and surfaces
OPES flow fixed point50,000 steps, 200 iterationsresidual 4.7e-11, 1D PMF RMSE 0.245
2D reweighting constant biasflat tracefinite bins zero
Reweighting constant biasflat tracezero surface
Block reweighting3 samples, block 2finite 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 ​

SurfaceEntry point
CLImetadynamics, opes (UFF molecule, optional JSON config)
WASMrun_uff_metadynamics, run_uff_opes, reweight_free_energy, reweight_free_energy_correlated, reweight_free_energy_2d
Pythonsame 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 ​

  1. Add multi-dimensional CVs and a grid in more than one dimension.
  2. Implement the exact OPES differential flow equations.
  3. Extend multi-CV grids above two dimensions.
  4. Add autocorrelation-aware error propagation.
  5. Wire the bias into the existing NVT/NPT dynamics module.
  6. Benchmark a known free-energy landscape against long unbiased MD.

Released under the MIT License.