nvalchemi.enhanced_sampling.EnhancedSampling#

class nvalchemi.enhanced_sampling.EnhancedSampling(*, model, engine=None, engine_kwargs=<factory>, n_steps=None, extra_hooks=<factory>, cache_engine=True, biases=<factory>, steps_per_epoch=10000, compile_biases=False, prime_after_update=True, replica_exchange=None)[source]#

Declarative recipe for biased dynamics on a BaseDynamics engine.

A sibling of any other DynamicsStrategy: construction validates the configuration, build_hooks() contributes the enhanced-sampling hook family, and DynamicsStrategy.run drives the engine. The model, the integrator, the thermostat, and every other hook behave exactly as they would unbiased.

biases#

Mapping of unique name to bias. A bias is any BaseModelMixin that maps a Batch to ModelOutputs and carries a name — there is no separate bias protocol. May be empty, which reduces the strategy to identity stamping — what pure temperature replica exchange needs, since the ladder alone drives the sampling.

Type:

dict[str, Any]

steps_per_epoch#

Steps per consistency epoch, the StatefulHook synchronisation boundary at which AdaptivePotentialMixin.commit() fires.

Type:

int

compile_biases#

When True, torch.compile each conservative bias’s energy(). Not forward() — that path calls requires_grad_(), which torch.compile cannot trace; see the ConservativeBias docstring.

Type:

bool

prime_after_update#

When True (default), re-evaluate biases and rewrite the batch’s total forces after an update() bumps a bias’s state version, so that anything reading batch.forces between steps sees the current bias rather than the previous one.

Type:

bool

replica_exchange#

Optional ladder. When given, the strategy also contributes the PairSwapHook the ladder configures. A runtime object rather than a declarative knob, so it is excluded from to_spec_dict() the way biases and extra_hooks are.

Type:

ReplicaExchange | None

cache_engine#

Always True; see One strategy, one trajectory below.

Type:

bool

Raises:
  • TypeError – If any value in biases is not a BaseModelMixin, or if replica_exchange is given for an engine that cannot rebind a thermodynamic state.

  • ValueError – If steps_per_epoch is below 1, a bias’s name disagrees with its key in biases, no engine is given, or cache_engine is False.

Parameters:
  • model (BaseModelMixin)

  • engine (Annotated[type | None, BeforeValidator(func=~nvalchemi._serialization._validate_type, json_schema_input_type=PydanticUndefined), PlainSerializer(func=~nvalchemi._serialization._serialize_type, return_type=PydanticUndefined, when_used=always)])

  • engine_kwargs (dict[str, Any])

  • n_steps (Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Strict(strict=True), Gt(gt=0)])] | None)

  • extra_hooks (list[Hook])

  • cache_engine (bool)

  • biases (dict[str, Any])

  • steps_per_epoch (int)

  • compile_biases (bool)

  • prime_after_update (bool)

  • replica_exchange (ReplicaExchange | None)

Examples

>>> sampling = EnhancedSampling(
...     model=model,
...     engine=NVTLangevin,
...     engine_kwargs={"dt": 0.5, "temperature": 300.0, "friction": 0.01},
...     biases={"umbrella": umbrella, "wall": lower_wall},
... )
>>> batch = sampling.run(batch, n_steps=1000)

Notes

Hook ordering

build_hooks() returns the strategy’s own hooks before extra_hooks, so at AFTER_COMPUTE the bias contribution is applied before any caller-supplied hook runs. A safety hook such as MaxForceClampHook therefore clamps the total force, which is the physically meaningful quantity, rather than the model force alone. Bias observations that need unbiased physical forces are captured inside BiasHook before the contribution is applied, so they are unaffected.

Among the strategy’s own hooks the order is identity, bias, exchange, commit. Exchange precedes commit because the commit publishes shared history, and doing it before the swap would publish under labels that are about to change — the same order checkpoint() drains in.

One strategy, one trajectory

The hook family is built once, at construction, because it holds the run’s bookkeeping: the walker counter, the committed epoch, the attempted segment, and each bias’s delivery record. That is also what a checkpoint saves and restore() writes back. So the engine is cached — cache_engine defaults to True and False is refused — and dynamics() returns it. Calling build_engine() again would hand a second engine the first one’s bookkeeping; construct a second strategy instead.

build_hooks()[source]#

Return the enhanced-sampling hooks, then extra_hooks.

Returns:

Identity, bias, exchange (when configured) and epoch-commit hooks, followed by whatever the base contributes.

Return type:

list[Hook]

checkpoint(path, batch=None)[source]#

Write a transactional checkpoint at a consistency-epoch boundary.

The boundary is not a convention — it is the only point where there are no pending update() calls and no in-flight epoch commit, so a checkpoint taken anywhere else could capture a bias mid-mutation.

Parameters:
  • path (str | Path) – Destination Zarr store.

  • batch (Batch | None) – The batch to save. Defaults to the one last seen by the identity hook.

Raises:
  • RuntimeError – If no engine has been built or no batch is available, meaning nothing has been run or primed.

  • ValueError – If the current step is not an epoch boundary; the message names the next valid step.

Return type:

None

dynamics()[source]#

Return the engine this strategy drives, building it on first use.

The same slot DynamicsStrategy.run caches into, so this, run(), prime_forces() and restore() all reach one engine.

Returns:

The cached engine. Stable across calls, so step counters and thermostat state persist.

Return type:

BaseDynamics

classmethod from_spec_dict(spec, *, model, biases=None, replica_exchange=None, extra_hooks=None)[source]#

Rebuild a strategy from to_spec_dict() output.

biases and replica_exchange are excluded from the spec — they are live objects with state, like model — so they are supplied here the same way. Without this override the base would rebuild a strategy with neither, and the restored run would be unbiased with nothing to say so.

Parameters:
  • spec (Mapping[str, Any]) – JSON-decoded strategy configuration.

  • model (BaseModelMixin) – The potential the engine calls.

  • biases (Mapping[str, BaseModelMixin] | None) – Name to bias, as passed at construction.

  • replica_exchange (ReplicaExchange | None) – The ladder, as passed at construction.

  • extra_hooks (Sequence[Hook] | None) – Runtime hooks appended after hooks rebuilt from the spec.

Returns:

A freshly validated strategy.

Return type:

EnhancedSampling

Raises:

ValueError – If spec already carries biases or replica_exchange.

property last_outputs: dict[str, Tensor]#

Diagnostics from the most recent force evaluation.

physical/<field> is the model alone, bias/<name>/<field> one bias’s contribution, bias_total/<field> the sum across biases, and total/<field> physical plus bias as read back from the batch.

model_config = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'revalidate_instances': 'never', 'validate_assignment': False}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

prime_forces(batch)[source]#

Run one force evaluation without advancing dynamics.

Populates batch.energy / forces / stress with the total (physical plus bias) values at the current coordinates. Needed before the first step of a warm-started run, where a consumer may read forces before any step has happened.

Parameters:

batch (Batch) – The batch to prime.

Returns:

The same batch, primed in place.

Return type:

Batch

Raises:

ValueError – If the batch has no forces field to write into.

Notes

Does not advance sampling state. Identity is stamped directly rather than by dispatching BEFORE_STEP, so no exchange is attempted and no epoch is committed from here — priming after a restore leaves the run exactly where the checkpoint left it.

compute() writes its outputs back with copy_ into fields that must already exist — a model output whose batch field is absent is silently discarded rather than created. That is the toolkit’s contract (AtomicData(..., forces=torch.zeros(n, 3))), so the check below turns a silent no-op into a named error.

restore(path, device=None)[source]#

Restore a checkpoint exactly, and prime forces before returning.

The caller must have reconstructed the same model, engine and biases first; this validates that they match what was saved. Model weights are not restored — load them through the model’s own API before calling here. The compatibility metadata proves the architecture agrees, not that the weights do.

Parameters:
  • path (str | Path) – Source Zarr store.

  • device (torch.device | str | None) – Device for the restored batch. Defaults to the model’s own.

Returns:

The restored batch, force-primed and ready to run.

Return type:

Batch

Raises:

ValueError – If the checkpoint is uncommitted, fails a checksum, or was written by a different model, engine, or bias set.

run(batch, n_steps=None, *, prime=True)[source]#

Run biased dynamics.

Primes forces first by default. A velocity-Verlet-style integrator reads batch.forces in its first half-step, before any model call — so without priming, step 0 integrates against whatever the buffer happened to hold (zeros, for a freshly built batch), making it the one step in the run that ignores the bias.

Parameters:
  • batch (Batch) – The initial batch.

  • n_steps (int | None) – Number of steps; falls back to n_steps.

  • prime (bool) – Set False to skip priming when the caller has already evaluated forces at these coordinates.

Returns:

The batch after all steps.

Return type:

Batch

state_dict()[source]#

Return sampling counters plus each adaptive bias’s state.

Returns:

Nested mapping; bias state lives under biases/<name>.

Return type:

Mapping[str, Any]

warm_start(frames)[source]#

Replay prior frames into every adaptive bias, in order.

Approximate by construction: it reconstructs bias history but not velocities, RNG, or integrator state. Use restore() when exact reproducibility matters.

Parameters:

frames (Batch) – Prior frames in chronological order, one graph per frame.

Raises:

RuntimeError – If called after restore(); the two are mutually exclusive and applying a warm start over a restored state would silently corrupt it.

Return type:

None