nvalchemi.enhanced_sampling.AdaptiveBiasingForce#

class nvalchemi.enhanced_sampling.AdaptiveBiasingForce(atom_indices, temperature, cv_range, *, name='abf', n_bins=100, min_samples=200, full_samples=None, max_force=None, frequency=1)[source]#

Estimate and cancel the mean force along a pair distance.

Metadynamics fills a basin with hills; ABF instead measures the mean force \(\partial A/\partial \xi\) in each bin of the collective variable and applies its negative, so the residual force along the CV averages to zero and the walker diffuses freely. The estimate is the free-energy gradient, so no reweighting is needed at the end — free_energy() integrates it directly.

For the pair distance \(r = |\mathbf{r}_j - \mathbf{r}_i|\) the estimator is

\[\frac{\partial A}{\partial r} = \left\langle -\frac{(\mathbf{F}_j - \mathbf{F}_i)\cdot\hat{\mathbf{u}}}{2} \;-\; \frac{2 k_B T}{r} \right\rangle_r\]

with \(\hat{\mathbf{u}} = (\mathbf{r}_j - \mathbf{r}_i)/r\). The second term is the metric correction, and it is not optional: see Notes.

Parameters:
  • atom_indices (Tensor) – The pair (i, j), shape [2] for the same pair in every graph or [B, 2] for one per graph. Indices are local to each graph.

  • temperature (float) – Simulation temperature in Kelvin. Enters the metric correction, so it must match the thermostat; a mismatch biases the estimate.

  • cv_range (tuple[float, float]) – (r_min, r_max) in angstrom, the binned interval. Outside it no force is applied and no sample is recorded.

  • name (str) – Unique bias identifier.

  • n_bins (int) – Number of uniform bins across cv_range.

  • min_samples (int) – Samples a bin needs before any bias force is applied from it. An estimate from a handful of samples is noise, and applying it would drive the walker on the strength of that noise.

  • full_samples (int | None) – Samples at which the applied fraction reaches 1. Defaults to 2 * min_samples. Between the two the force ramps linearly; equal to min_samples it is a step, applying nothing until the threshold and full force at it.

  • max_force (float | None) – Optional cap on |dA/dr| in eV/A. A bin that has been visited once at a bad geometry can hold a large estimate; the cap bounds what that can do to the trajectory.

  • frequency (int) – Steps between update() calls. 1 (every step) is the usual choice — ABF wants every uncorrelated sample it can get.

Raises:

ValueError – For a malformed atom_indices, a non-positive temperature, an empty or inverted cv_range, fewer than one bin, a negative min_samples, full_samples < min_samples, or a non-positive max_force.

Notes

The metric correction is not optional

Projecting Cartesian forces onto \(\nabla\xi\) and averaging gives the mean force in the constrained ensemble, not the gradient of the free energy of the unconstrained one. The two differ by the Jacobian of the coordinate change — for a distance in three dimensions the shell volume grows as \(r^2\), contributing \(-2k_B T/r\).

Omitting it does not produce noise, it produces a smoothly wrong answer: two non-interacting particles would be reported as having a flat PMF when the true one is \(-2k_B T\ln r\). That is why this class takes an atom pair rather than a general cv callable — the correction is specific to this coordinate, and accepting an arbitrary CV would mean applying a distance-shaped correction to something that is not a distance.

Force-only, and therefore excluded from replica exchange

forward() returns forces and no energy. There is no potential to report: the applied force is not the gradient of any function the bias holds, which is exactly what makes ABF non-conservative. supplies_exchange_energy is False, and ReplicaExchange refuses such a bias rather than evaluating an acceptance rule that needs a cross-state bias energy.

Observation ordering

stage is AFTER_COMPUTE, where batch.forces still holds the unbiased physical force. Observing after the bias is applied would feed the estimator its own output, and it would converge to whatever it had already decided.

Examples

>>> import torch
>>> from nvalchemi.enhanced_sampling import AdaptiveBiasingForce
>>> abf = AdaptiveBiasingForce(
...     atom_indices=torch.tensor([0, 1]),
...     temperature=300.0,
...     cv_range=(2.0, 6.0),
...     n_bins=40,
... )
>>> int(abf.bin_counts.sum())
0
property bin_centers: Tensor#

Return the CV value at the middle of each bin, shape [n_bins].

bin_index(values)[source]#

Return the bin each CV value falls in, shape [...].

Values outside cv_range are reported as -1; they contribute no sample and receive no force, so they belong to no bin.

Parameters:

values (Tensor) – CV values in angstrom.

Returns:

Integer bin indices, or -1 for out-of-range values.

Return type:

Tensor

property bin_width: float#

Return the width of one CV bin, in angstrom.

compute_embeddings(data, **kwargs)[source]#

Not implemented — ABF produces no embeddings.

Parameters:
  • data (AtomicData | Batch) – The input system.

  • **kwargs (Any) – Unused; accepted for interface compatibility.

Returns:

Never returns.

Return type:

AtomicData | Batch

Raises:

NotImplementedError – Always.

config_fingerprint()[source]#

Return the settings the accumulated histogram is only valid under.

cv_range and n_bins decide what each bin means; restoring a histogram under a different pair silently relabels every bin. temperature scales the metric correction already folded into force_sum, so samples taken at 300 K cannot be extended at 900 K. atom_indices names the coordinate itself. min_samples / full_samples / max_force change what the same counts apply.

Returns:

The checked configuration.

Return type:

dict[str, Any]

property embedding_shapes: dict[str, tuple[int, ...]]#

ABF applies a tabulated force, not a network.

Type:

No embeddings

extra_repr()#

Format the model config for nn.Module.__repr__.

Parameters:

self (Any)

Return type:

str

forward(data, **kwargs)[source]#

Return the bias force, with no energy.

Read-only with respect to the estimator: the current estimate is applied but never updated here, so it is safe to call repeatedly on the same batch.

Parameters:
  • data (AtomicData | Batch) – The live batch.

  • **kwargs (Any) – Unused; accepted for interface compatibility with model wrappers.

Returns:

forces, this bias’s state_version, and per-walker diagnostics/*: the CV value, its bin (-1 outside cv_range, matching bin_index()), the applied_gradient actually used (ramped and capped, so not the same as mean_force()), the bin’s sample count, its ramp fraction, and in_range. Every per-bin quantity reads zero for a walker outside the range, so the diagnostics agree with the force rather than reporting the nearest edge bin’s statistics. There is no energy: the applied force is not the gradient of any function this bias holds.

Return type:

ModelOutputs

free_energy()[source]#

Return the PMF at each bin center, shape [n_bins].

Integrates the mean-force estimate by the trapezoid rule, shifted so the minimum over sampled bins is zero. This is the payoff of the method: unlike metadynamics there is nothing to deconvolve, because the accumulated quantity already is the free-energy gradient.

Returns:

Free energy in eV. Bins never visited are nan.

Return type:

Tensor

Raises:

RuntimeError – If no bin has been sampled, or if an unvisited bin sits between two visited ones. Integration carries the profile across the gap, so a hole in the middle would silently contaminate every value beyond it.

mean_force()[source]#

Return the per-bin mean-force estimate, shape [n_bins].

Returns:

dA/dr in eV/A per bin. Unvisited bins are nan rather than zero: a bin with no samples has no estimate, and zero is a perfectly plausible mean force that would hide that.

Return type:

Tensor

ramp_fraction()[source]#

Return the applied fraction per bin, shape [n_bins].

Zero at or below min_samples, one at or above full_samples, linear between. Ramping rather than switching on at the threshold avoids a force discontinuity of exactly the size the threshold exists to prevent.

full_samples == min_samples is a step: nothing until the threshold, full force at it. That is a legitimate choice — it is the classic hard-threshold form, and it is what min_samples=0 gives by default — so it is handled rather than rejected. It needs its own branch because the linear form would divide by a zero span, and clamping that span to 1 would delay full force by one sample.

A bin with no samples has no estimate, so it reports zero whatever the thresholds are.

Returns:

Fractions in [0, 1].

Return type:

Tensor

supplies_exchange_energy: bool = False#

The acceptance rule needs a cross-state bias energy; this has none.

update(ctx, stage)[source]#

Accumulate one mean-force sample per walker.

Parameters:
  • ctx (BiasContext) – The AFTER_COMPUTE capture, whose ctx.batch.forces are the unbiased physical forces. ctx.contribution is this bias’s own preceding output and is deliberately unused: an estimator fed its own output converges to whatever it had already decided.

  • stage (DynamicsStage) – The stage being dispatched, always stage.

Raises:

ValueError – If the captured frame carries no forces to project.

Return type:

None