Skip to content

API reference

OPES

OPES(system, variables, temperature, barrier, frequency, varianceFrequency, biasFactor=None, exploreMode=False, bounded=False, saveFrequency=None, biasDir=None, walkerId=None, warmupSteps=None, compressionThreshold=1.0, useExistingBandwidths=True, kernelShape='gaussian', statsWindowSize=10)

On-the-fly Probability Enhanced Sampling.

Implements OPES and its exploratory variant, following Invernizzi and Parrinello, https://doi.org/10.1021/acs.jpclett.0c00497 and https://doi.org/10.1021/acs.jctc.2c00152.

Parameters:

Name Type Description Default
system

The System to simulate. A CustomCVForce implementing the bias is created and added to it.

required
variables

The collective variables whose sampling should be enhanced.

required
temperature

The temperature at which the simulation is run.

required
barrier

The free energy barrier the simulation should overcome.

required
frequency

Interval in time steps at which to deposit a kernel.

required
varianceFrequency

Interval in time steps at which to update the CV variance. When None, the bandwidth is fixed and taken from each variable's biasWidth, which is interpreted as the standard deviation of the UNBIASED distribution, exactly as both papers define sigma^(0).

required
biasFactor

Defaults to barrier / kT. Must be finite: unlike PLUMED, the uniform-target limit inf is not supported.

None
exploreMode bool

Whether to apply the OPES-explore variant. Must match the mode of a snapshot passed to :meth:setState and of every walker sharing biasDir.

False
bounded bool

Whether non-periodic CVs have reflective boundaries.

False
saveFrequency

Interval in time steps at which to share the bias on disk. Must be a multiple of frequency.

None
biasDir

Directory shared with other walkers.

None
walkerId

This walker's identifier within biasDir. Random when omitted; pass a stable value across restarts so a resumed walker reclaims its own file rather than leaving the previous run's behind as a phantom peer.

None
warmupSteps

When given, run this many steps without depositing kernels while measuring the CV variance, then freeze it.

None
compressionThreshold float

Mahalanobis distance below which kernels are merged.

1.0
useExistingBandwidths bool

Whether the merge search scales by existing kernels' bandwidths.

True
kernelShape str

"gaussian" or "compact".

'gaussian'
statsWindowSize int

Window, in deposition strides, of the running CV-mean estimate. With an adaptive variance, the first kernel also waits this many strides, so that it is sized from a measured variance.

10

addKernel

addKernel(values, biasEnergy, variance=None)

Deposit a kernel into the probability estimates.

Returns whether a kernel was actually deposited: a non-positive variance estimate is skipped rather than deposited, since a zero bandwidth gives the kernel -inf log height and poisons the estimate.

This does not refresh any Context; call :meth:updateContext afterwards if a simulation is running.

getAverageDensity

getAverageDensity()

Z_n, the mean density over the explored CV space.

NaN until the first kernel is deposited, like :meth:getFreeEnergy.

getBias

getBias()

The OPES bias potential on the grid.

With no kernels deposited yet the estimate is empty, and both the log PDF and the log mean density are -inf, whose difference is NaN. The bias is well defined in that limit, though: the regularization term dominates, leaving the flat -barrier floor. Returning it explicitly keeps NaN out of the forces.

getCollectiveVariables

getCollectiveVariables(simulation)

Current values of all collective variables in a Simulation.

getFreeEnergy

getFreeEnergy()

Free energy as a function of the collective variables.

Returned as an N-dimensional array in kJ/mole. The i'th position along an axis corresponds to minValue + i*(maxValue-minValue)/(gridWidth-1), matching the numpy.linspace(minValue, maxValue, gridWidth) axis the estimate is built on. Always the importance-sampling estimate, which converges better than the direct one in explore mode.

Every entry is NaN until the first kernel is deposited: with no samples there is no density to take a logarithm of. Unlike :meth:getBias, this has no defined limit to fall back on, and it never reaches the forces.

getNumKernels

getNumKernels()

Number of kernels in the estimate that defines the bias.

getState

getState()

Flat, npz-writable snapshot of this sampler's accumulated state.

getVariance

getVariance()

Variance currently used to size newly deposited kernels.

setState

setState(state)

Restore from a :meth:getState snapshot.

A snapshot from a single-walker run seeds this walker's own contribution to the shared bias, since that run had no peers.

The restored bias reaches the simulation at the start of the next :meth:step. Call :meth:updateContext to push it into a Context sooner, e.g. before computing energies.

step

step(simulation, steps)

Advance the simulation by a number of time steps.

Parameters:

Name Type Description Default
simulation

The Simulation to advance.

required
steps

The number of time steps to integrate.

required

updateContext

updateContext(context)

Push the current bias into a Context.

The table stores V + barrier, so the energy the force contributes is the bias shifted up by barrier: the unexplored floor sits at 0. OpenMM's tabulated functions are zero outside their range, so a CV that leaves [minValue, maxValue] sees the bias of a region nothing has been deposited in, rather than a jump of barrier.

OnlineKDE

OnlineKDE(cvSpace, compressionThreshold=1.0, useExistingBandwidths=True, kernelShape='gaussian')

Online kernel density estimate with on-the-fly kernel compression.

Parameters:

Name Type Description Default
cvSpace

The :class:CVSpace the estimate lives on.

required
compressionThreshold float

Merge a new kernel into any existing kernel closer than this, measured as a Mahalanobis distance. Zero disables merging.

1.0
useExistingBandwidths bool

Whether the nearest-neighbour search scales distances by the existing kernels' bandwidths rather than the incoming kernel's.

True
kernelShape str

Either "gaussian" or "compact".

'gaussian'

__iadd__

__iadd__(other)

Absorb every kernel of other.

The weight moments are combined directly rather than re-accumulated from the absorbed kernels: a compressed kernel carries the combined weight of all its samples, so squaring it would overstate the sum of squared weights and collapse the effective sample size.

bandwidthFactor

bandwidthFactor(logWeight)

Silverman shrink factor for a new kernel of the given log weight.

Computed from this estimate's effective sample size with the new kernel's weight already counted, which is what :meth:update applies.

evaluate

evaluate(point)

Log of the normalized density at a single point.

getLogMeanDensity

getLogMeanDensity()

Log of Z_n, the mean density over the compressed kernel centers.

NaN with no kernels deposited yet, for the same reason as :meth:getLogPDF: the mean over an empty set is undefined, so the log(0) and inf - inf along the way are expected, not warned about.

getLogPDF

getLogPDF()

Log of the normalized probability density on the grid.

With no kernels deposited yet, both operands are -inf and the result is the documented NaN (see :meth:getState's empty-KDE note) rather than an error; the subtraction is expected to be undefined here, not a sign that something went wrong.

getNumKernels

getNumKernels()

Number of compressed kernels currently stored.

getState

getState()

Flat, npz-writable snapshot of this estimate.

The CVSpace is deliberately excluded: all walkers share identical CV definitions, so a reader constructs its own and calls setState.

setState

setState(state)

Restore from a :meth:getState snapshot, discarding current contents.

update

update(position, logWeight, variance, factor=None)

Deposit a kernel of the given log weight and per-CV variance.

The bandwidth is shrunk by factor when given, and otherwise by this estimate's own :meth:bandwidthFactor. Passing one lets an estimate that is part of a larger one size kernels by the larger one's sample size.

CVSpace

CVSpace(variables, bounded=False)

The domain of the collective variables: grid, periodicity, boundaries.

Parameters:

Name Type Description Default
variables

Sequence of collective variable descriptions. Each must expose minValue, maxValue, gridWidth and periodic; an openmm.app.BiasVariable qualifies.

required
bounded bool

Whether non-periodic variables have reflective boundaries. When true the internal grid is tripled with mirrored copies on each side, and :meth:foldedGrid folds them back.

False

gridShape property

gridShape

Shape of the CV-space grid, slowest axis first.

numDimensions property

numDimensions

Number of collective variables.

closestNode

closestNode(position)

Index of the grid node nearest to position, in gridShape order.

displacement

displacement(position, endpoint)

Displacement from position to endpoint, minimum-image if periodic.

endpoint

endpoint(position, displacement)

Endpoint reached from position, wrapped into the periodic domain.

foldedGrid

foldedGrid(values)

Fold a tripled bounded grid back onto the physical domain, in log space.

gridDistances

gridDistances(position)

Per-axis distances from position to every grid node.

mirrorPositions

mirrorPositions(position)

Every image of position under the reflective boundaries.

For each non-periodic dimension, reflecting a point off both walls gives two images in addition to the point itself; the images across every dimension combine multiplicatively (a corner sees images of images). Unbounded spaces, or spaces with only periodic CVs, have no images: [position] is returned unchanged.

A kernel centered at any one of these images is, by the symmetry of reflection, exactly as far from a given query point as the original kernel is from that point's own mirror image -- so summing a kernel's density over these images is equivalent to summing the query point's images against the one true kernel, which is what the tripled evaluation grid does. Used to keep :meth:Kernel.evaluate (arbitrary points) consistent with :meth:Kernel.evaluateOnGrid.

Kernel

Kernel(cvSpace, position, bandwidth, logWeight, numSamples=1, shape=GAUSSIAN)

A multivariate kernel with diagonal covariance.

evaluate

evaluate(points)

Log of the kernel at the given point or points.

Reflected at the domain walls when the space is bounded, by summing over the kernel's mirror images (see :meth:CVSpace.mirrorPositions) so this agrees with :meth:evaluateOnGrid. Unbounded spaces have no images, so this reduces to the single-term evaluation.

evaluateOnGrid

evaluateOnGrid()

Log of the kernel on the CV-space grid, in gridShape order.

findNearest

findNearest(centers, bandwidths, ignore=())

Index of and squared Mahalanobis distance to the nearest center.

merge

merge(other)

Absorb other, preserving total weight, mean and second moment.