nvalchemi.enhanced_sampling.RMSDMetaDynamicsBias#

class nvalchemi.enhanced_sampling.RMSDMetaDynamicsBias(k_push, alpha, *, name='rmsd_metadynamics', atom_indices=None, frequency=500, storage='fifo', max_references=None, history='shared', ramp_depositions=1, references=None, compute_stress=False)[source]#

Repulsive Gaussian bias over retained reference structures.

\[V(x, t) = \sum_r f_r(t)\, k_\mathrm{push} \exp\!\left(-\alpha\, \mathrm{RMSD}_A(x, x_r)^2\right)\]

where \(\mathrm{RMSD}_A\) is the Cartesian RMSD after optimal translation and rotation. Each deposition appends the current geometry to the reference set, so the bias pushes the system away from everywhere it has already been. This is the conformer-exploration scheme used by xTB/CREST metadynamics.

Unlike WellTemperedMetaDynamicsBias, there is no collective variable to choose: the “CV” is the whole (selected) geometry, which is what makes it a general-purpose explorer for molecules whose interesting degrees of freedom are not known in advance. The price is that it has no free-energy interpretation — it is a structure-generation method, not an estimator, and there is deliberately no free_energy here.

Parameters:
  • k_push (float) – Per-reference bias amplitude in eV. Must be positive; a negative amplitude would attract the system to structures it has already visited.

  • alpha (float) – Gaussian width parameter in A^-2. Larger is narrower.

  • name (str) – Unique bias identifier.

  • atom_indices (Tensor | None) – Atom indices within each graph to align and compare, shape [M]. None uses every atom. The usual choice is heavy atoms only: hydrogens rotating on a methyl group produce RMSD the exploration does not care about.

  • frequency (int) – Dynamics steps between depositions. The Hook attribute, with the meaning it has everywhere else.

  • storage (str) – "fifo" (default), "preallocated", or "grow". FIFO is the xTB-compatible default and is not a compromise here the way it is for well-tempered metadynamics: with no free energy to reconstruct, discarding the oldest references is a deliberate choice to keep pushing outward rather than accumulating an ever-stiffer cage.

  • max_references (int | None) – Capacity. Required for "preallocated" and "fifo"; the initial chunk for "grow".

  • history (str) – "shared", "state", or "walker", as for well-tempered metadynamics. The latter two require the batch to carry thermodynamic_state_id / walker_id and raise if it does not; EnhancedSampling stamps both on every step, so only direct evaluation has to supply them.

  • ramp_depositions (int) – Deposition events over which a new reference ramps from zero to full amplitude. A freshly deposited reference is at RMSD zero, so without a ramp it switches on at its full value exactly where the system is standing, which is the worst possible place for a force discontinuity. Defaults to 1.

  • references (Tensor | None) – Optional warm start, shape [R, M, 3], in chronological order. The xTB convention of seeding with a displaced copy of the initial structure is expressed by passing it here.

  • compute_stress (bool) – Passed through to ConservativeBias. Defaults to False: this bias rejects periodic systems, so there is no cell to differentiate with respect to.

Raises:

ValueError – For a non-positive k_push or alpha, an invalid storage policy or history mode, a missing capacity, a malformed atom_indices, or warm-start references of the wrong shape.

Notes

Periodic systems are rejected

Cartesian RMSD against a stored reference is not well defined under periodic boundary conditions: an atom that diffuses across a cell face is physically unmoved but Cartesian-displaced by a lattice vector, so the RMSD jumps and the bias delivers a large spurious force. Making this correct needs a minimum-image-aware, correspondence-resolving metric. Rather than return a plausible wrong number, evaluate() raises.

Periodicity is read from batch.pbc, not from the presence of a cell. A molecular batch carrying a bounding box with pbc all-False is accepted, which is the common case for a solvated or boxed molecule; a slab (pbc=[True, True, False]) is rejected, since wrapping along any axis is enough to break the metric. A non-zero cell with no pbc flags at all is refused as undeclared rather than assumed non-periodic.

Fixed atom correspondence

Atom i is always compared against atom i of the reference. No permutation search is performed, so two structures identical up to relabelling of equivalent atoms register as distinct.

Examples

>>> import torch
>>> from nvalchemi.enhanced_sampling import RMSDMetaDynamicsBias
>>> bias = RMSDMetaDynamicsBias(
...     k_push=0.02, alpha=0.5, max_references=50,
...     atom_indices=torch.tensor([0, 1, 2]),
... )
>>> bias.reference_count.item()
0
config_fingerprint()[source]#

Return the settings the retained references are only valid under.

k_push and alpha set how hard and how far the stored structures repel; restoring a reference set under different values keeps the geometries but changes what they do. atom_indices is held as a buffer and names which atoms the stored coordinates are, so without this check the caller’s selection would be silently overwritten by the checkpoint’s.

max_references is absent for the same reason max_hills is absent from the well-tempered fingerprint.

Returns:

The checked configuration.

Return type:

dict[str, Any]

energy(current)[source]#

Return the accumulated RMSD bias, shape [B, 1].

Parameters:

current (Batch) – Batch with strained positions supplied by ConservativeBias.evaluate().

Returns:

Shape [B, 1] in eV.

Return type:

Tensor

extra_repr()#

Format the model config for nn.Module.__repr__.

Parameters:

self (Any)

Return type:

str

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

Reject periodic batches, then derive energy and forces.

Parameters:
Returns:

As ConservativeBias.forward().

Return type:

ModelOutputs

Raises:

ValueError – If the batch is periodic according to batch.pbc, if it carries a non-zero cell with no pbc flags, or if graphs in the batch have differing atom counts while atom_indices is None.

load_state_dict(state, *args, **kwargs)[source]#

Restore state, resizing the reference buffers to the checkpoint.

Both storage="grow" and a bias whose site count was fixed at its first deposition can carry buffer shapes that the constructor did not produce, which nn.Module.load_state_dict would reject.

Parameters:
  • state (Mapping[str, Any]) – Mapping from state_dict().

  • *args (Any) – Forwarded up the MRO.

  • **kwargs (Any) – Forwarded up the MRO.

Returns:

Whatever the next load_state_dict returns.

Return type:

Any

repulsion(coords, owner_key)[source]#

Return the accumulated repulsion, shape [B].

Contains no data-dependent Python branch, so it compiles with fullgraph=True.

Parameters:
  • coords (Tensor) – Compared coordinates, shape [B, M, 3].

  • owner_key (Tensor) – History key per graph, shape [B].

Returns:

Bias energy per graph in eV, shape [B].

Return type:

Tensor

update(ctx, stage)[source]#

Append the current geometry to the reference set, one per walker.

Parameters:
  • ctx (BiasContext) – The capture. ctx.batch is the post-step frame; the bias’s own preceding contribution is on ctx.contribution.

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

Return type:

None