OpenMM NonbondedForce
nv.CustomNonbondedForce is an alias of nv.NonbondedForce. Both names construct
the same cuPotential force on OpenMM’s CUDA platform. The source type selects
its parameter and exception semantics:
Conversion creates a separate force before the simulation’s Context is
constructed. Bonded forces and constraints stay in the System.
Architecture
A force combines a cutoff interaction with optional lattice sums. Both native and compiled pair evaluators use one DSpace neighbor traversal; each lattice term also has a KSpace calculation.
Green boxes with thick borders call libcupo; gray boxes are handled by the
OpenMM plugin. Arrows show contributions and configuration dependencies.
Pair evaluation
The library calls are cupo_expression_* for compilation,
cupo_splitting_plan_* for the plans, cupo_dspace_* and cupo_kspace_* for
pair and reciprocal evaluation, and cupo_tuples_* for Standard exception
replacements. KSpace’s FFT convolution includes the Fourier-space influence
function. Switching applies to the cutoff potential; lattice terms are not
switched.
Standard and Custom describe the public API mode; native and compiled describe the evaluator selected for the interaction:
DSpace handles ordinary-pair exclusions and their reciprocal corrections. Standard’s physical exception replacements use the separate tuples path.
Scalar energy corrections
The plugin calls cupo_splitting_plan_get_self_energy() and
cupo_splitting_plan_get_net_charge_energy() on the CPU. Tail coefficients are
computed within the plugin.
The scalar energy corrections have distinct roles:
- Self-energy: removes the artificial self-interaction introduced by the reciprocal-space splitting. It depends on the plan and squared particle weights.
- Net-charge correction: accounts for a uniform neutralizing background in a charged periodic Coulomb system. It depends on total charge and volume, and vanishes for a neutral system. Dispersion has no net-charge correction.
- Tail correction: estimates the energy omitted by a cutoff and its automatic
switch. The plugin computes the coefficient and adds
C/volume; these terms do not add particle forces or another pair traversal.
Interaction types
The plugin describes a nonbonded force through a CutoffInteraction and optional
LatticeSumInteraction terms. These definitions specify the pair potential and
how its long-range contributions are treated. Both Standard and Custom modes
use this model.
CutoffInteraction
A CutoffInteraction defines a pair potential evaluated within the real-space
cutoff. It can use the built-in Lennard-Jones repulsion and dispersion potential
or a custom radial expression with its own parameter mixing rules.
Two optional features modify the cutoff treatment:
- A quintic switching function tapers the potential to zero between the switching distance and the cutoff. Its derivative is included in the forces.
- A homogeneous tail correction estimates the omitted energy beyond the
cutoff, including energy removed by switching, assuming a uniform particle
distribution. It contributes
C/volumeto the energy.
The tail coefficient is computed analytically for the built-in Lennard-Jones potential and by numerical integration for custom expressions with a convergent tail integral. A custom expression can also retain an analytical Lennard-Jones reference tail.
LatticeSumInteraction
A LatticeSumInteraction defines an interaction with particles and their periodic
images, including contributions beyond the real-space cutoff. Each term specifies
a radial kernel, particle weights, and a splitting method. Supported kernels are
Coulomb (1/r) and attractive dispersion (-1/r^6); their usual weights are
charges and sqrt(C6), respectively.
The splitting determines both the direct-space contribution, evaluated within the cutoff, and the reciprocal-space contribution, evaluated on a mesh using FFTs. The latter includes spreading particle weights onto the mesh, applying the long-range kernel in k-space, and gathering back to the particles. Matching self, background, and exclusion corrections complete the calculation. See Splitting and Spreading for the mathematics.
C2 Prolate and Ewald are alternative splittings of the same periodic interaction. Lattice terms are not switched. Enabling a dispersion lattice sum disables the cutoff interaction’s automatic switching and homogeneous tail correction.
Combining the two
The source force determines the initial interaction definitions:
For an LJPME source, the dispersion lattice sum also changes the direct-space
calculation.
The plugin combines cutoff evaluation and the direct contributions of lattice terms in one neighbor traversal. Custom expressions have different requirements in the two modes:
- In Custom mode, the expression must include the full unsplit potential of each declared lattice term.
- In Standard mode, a custom cutoff expression supplies the full unsplit non-Coulomb potential; the parent force supplies Coulomb.
The plugin applies the matching splitting corrections so that each interaction is counted once. The custom expression example shows how to combine a modified repulsion potential with Coulomb and dispersion lattice sums.
Configure interaction definitions
Both modes support up to one Coulomb (P1) and one dispersion (P6) lattice term.
The constructor nv.LatticeSumInteraction(kernel, weightExpression, splitting)
accepts:
- An explicit radial kernel:
nv.CoulombRadialKernel()ornv.DispersionRadialKernel(). - A particle weight expression.
- An optional splitting method:
nv.LatticeSumInteraction.Prolate(the default) ornv.LatticeSumInteraction.Ewald.
Weight expressions use unsuffixed particle parameters and live globals, with no
distance dependence. Standard exposes q, sigma, and epsilon; Custom uses
its declared parameter names. The target pair interaction is
kernel.coupling*weight_i*weight_j/r**kernel.power. In Custom mode, declaring a
lattice sum requires the matching bare interaction in the full source expression.
Interaction getters return copies; changes take effect through the corresponding setter. This example configures a Standard force’s built-in LJ cutoff and existing Coulomb lattice term before Context creation:
The lattice-term API provides four operations:
addLatticeSumInteraction(term)adds a term.getLatticeSumInteraction(index)returns a copy of a term.setLatticeSumInteraction(index, term)replaces a term.removeLatticeSumInteraction(index)removes a term.
This switching and tail configuration applies when no dispersion lattice sum is
present. CutoffInteraction.NoTail disables the homogeneous correction.
Changes to an existing Context have the following requirements:
- Lattice definitions, combining rules, and switching require reinitialization.
- Native LJ tail-policy changes support
updateParametersInContext(). - Expression tail-policy changes require reinitialization.
What conversion does
nv.NonbondedForce(source) copies its source definition. Later edits to the
source do not affect the plugin force.
For a Standard PME source, conversion also preserves the Lennard-Jones switching and dispersion correction settings. An LJPME source enables reciprocal dispersion instead. Both PME and LJPME sources select C2 Prolate splitting by default, for Coulomb and, when enabled, dispersion. The source method enables reciprocal dispersion; the plugin constructor selects the splitting.
C2 Prolate and Ewald have different numerical errors, so results need not agree
to roundoff. The constructor
nv.NonbondedForce(source, nv.NonbondedForce.AutoBoxSafety, nv.NonbondedForce.PME)
selects Ewald splitting for both lattice terms.
The converted force replaces the original in the System to avoid double
counting. Custom definitions have one parameter record per System particle, in
System particle order.
Only the CUDA platform’s "single" and "mixed" precision modes are supported.
The plugin computes strictly deterministic energies and forces for identical
inputs and the same numerical configuration. OpenMM’s DeterministicForces
property has no effect on these calculations, even when set to "false".
Example: Simulate a periodic water box
This example requires the installed plugin and creates a water box with OpenMM’s bundled TIP3P force field. It uses the stock OpenMM integrator and replaces the nonbonded force with cuPotential.
The 3.0 nm box satisfies the plugin’s periodic-box requirement: each orthorhombic box dimension must be at least three times the cutoff, or 2.7 nm for this example.
The script prints the potential energy after a short NVT run.
Custom expressions
A custom expression can define a standalone Custom force or replace the cutoff potential in Standard mode. The examples below cover a switched LJ expression, a retained analytical tail, and fusion with Coulomb and dispersion lattice sums.
Example: Switching and a homogeneous tail
This example defines a Lennard-Jones potential scaled by the live global
parameter lambda_lj. It switches the potential smoothly between 1.0 and 1.25 nm
and adds a homogeneous long-range correction. The 4 nm box exceeds three times
the cutoff, as required by the plugin’s orthorhombic cell list.
Parameter suffixes 1 and 2 identify the two particles’ values. Arithmetic
mixing for sigma and geometric mixing for epsilon make this potential symmetric
under particle exchange. Definitions after semicolons supply intermediate values.
The OpenMM CustomNonbondedForce reference describes the expression syntax.
Without lattice terms, setUseSwitchingFunction(True) applies a quintic switch
to the entire expression, bringing the energy smoothly to zero at the cutoff and
including the switch’s derivative in the forces. An expression with its own
switch does not need this additional switching function.
The homogeneous correction estimates the energy beyond the cutoff and the energy
removed by the switch, assuming a uniform particle distribution. It adds
C/volume to the energy without another pass over particle pairs:
- Global changes: recently used values of referenced globals reuse cached coefficients. Unused globals do not invalidate the cache. An uncached value requires CPU integration when energy is requested; force-only evaluations defer that work.
- Particle changes: updating particle values replaces the correction and discards its old cache.
- Volume changes: only the denominator changes.
For a custom expression, the plugin computes C by numerical integration.
It integrates a switch written inside the expression literally; that switch
does not define an unswitched reference for the tail. Automatic switching
supplies the switching-deficit correction described above.
The analytical LJ variant below retains the native
Lennard-Jones correction instead.
Reuse the analytical LJ tail
preserveDispersionCorrection=True retains the native analytical tail for a
custom expression that reproduces ordinary Lennard-Jones interactions. The
following block is an alternative construction of force for the custom switching-and-tail example;
the subsequent system.addForce(force) and Context setup are the same:
The force evaluates the custom expression and computes the tail correction from
the native LJ reference, including the switching interval. The native
parameter offsets keep that correction consistent with changes to lambda_lj
for nonnegative lambda. Disabling the source’s numerical correction avoids
counting the tail twice.
This variant uses Standard mode with two parameter definitions:
- Native reference: effective LJ parameters, mixing rules, and switching
settings must match the custom potential. Particle records and offsets are
edited through
setParticleParameters()andsetParticleParameterOffset(). - Custom expression:
getCutoffExpression()returns a copy of the custom force definition. Changes are passed back throughsetCutoffInteraction(updated, preserveDispersionCorrection=True).
Both kinds of particle updates take effect through updateParametersInContext().
Editing the original source or reference does not update the plugin force.
The retained reference supplies the tail of the specified LJ potential. Other integrable custom potentials use numerical correction.
Fuse a custom expression with Coulomb and dispersion lattice sums
A single nv.NonbondedForce can combine a custom cutoff expression with both
Coulomb and dispersion reciprocal calculations. This uses a converted LJPME
force with a custom cutoff interaction supplied through setCutoffInteraction().
The following complete example modifies LJ repulsion through lambda_rep while
keeping the attractive dispersion term and its reciprocal weights fixed.
The plugin evaluates the custom cutoff term and both direct-space splitting corrections in one neighbor traversal. Coulomb and dispersion each retain their reciprocal calculation. LJPME conversion uses C2 Prolate splitting for both by default.
The two definitions have complementary roles:
- Custom expression: the full unsplit non-Coulomb potential, including
the attractive
r^-6term needed for the short-range dispersion contribution. - Parent force: Coulomb and reciprocal dispersion weights
b6_i = 2*sqrt(epsilon_i)*sigma_i**3, with geometric C6 mixing. The plugin applies the cutoff shift and matching splitting corrections. - Shared requirements: matching cutoff, particle count, and exclusion pairs. Changes to attractive coefficients must remain consistent with the parent’s dispersion weights, including during parameter updates.
Here lambda_rep changes only repulsion, so the dispersion weights stay fixed.
Reciprocal dispersion disables automatic switching and homogeneous LJ tails.
Convert a force in an existing System
This helper replaces a stock custom force at a known System index, before
construction of the Context or Simulation:
Conversion and ownership follow the shared rules.
Replace or inspect an expression
setCutoffInteraction() accepts three forms:
The input requirements are:
- Complete definition: matching particle count and cutoff. In Standard mode, exclusions must match the native exception pairs.
- Bulk data: keyword arguments
expression,parameterNames,particleParameters, and an optionalglobalParametersdictionary. Records have one row per existing particle and columns inparameterNamesorder. Bare numbers use OpenMM units;Quantityinputs are converted automatically. - Globals: shared names require matching defaults. Existing globals, including those referenced by separate tails, remain available.
The replacement’s scope depends on the mode:
- Standard: all ordinary non-Coulomb interactions are replaced; native Coulomb and exception laws remain active.
- Custom: the complete pair expression is replaced; declared lattice terms remain active.
For bulk data, tailCorrection=True integrates the complete expression with
ungrouped pair averaging and the switching deficit. The default is False.
This option is incompatible with preserveDispersionCorrection=True or a
dispersion lattice sum. Independent tails remain additive; including the same
tail in more than one definition counts it more than once.
hasCutoffExpression() reports whether either mode uses a custom expression.
getCutoffExpression() returns an owned copy. Particle edits take effect when
that copy is passed back to setCutoffInteraction() followed by
updateParametersInContext(). In Standard mode,
preserveDispersionCorrection=force.getUseDispersionCorrection() retains the
current native-tail setting during replacement. Custom mode has no native LJ
tail to preserve.
The expression records are independent of Standard’s native sigma/epsilon records. Updating those native records changes any retained native LJ tail and dispersion weights, but does not change the custom records.
Separate expression tail corrections
addExpressionTailCorrection(source_custom_force) attaches an independent
C(globals)/volume correction:
- The source must have long-range correction enabled and match the force’s particle count and cutoff.
- Its interaction groups and automatic switching interval determine the CPU tail integral and averaging.
- It adds no GPU pair traversal and does not enable interaction groups in the pair evaluator.
This preserves a source force’s original group-based tail averaging when fusing several interactions into one expression. Integrating the combined expression with ungrouped averaging can give a different tail energy even when the direct pair interactions agree. Independent corrections are additive, so overlapping definitions would count the same tail contribution more than once.
For an existing correction:
- Particle values:
getExpressionTailCorrection(index)returns a copy; edits are applied throughsetExpressionTailCorrection(index, updated)andupdateParametersInContext(). - Expression, parameter layout, or interaction groups: changes require Context reinitialization.
Select particle regions
Particle flags can select pairs within a symmetric expression. For a binary
alchemical parameter, alchemical1+alchemical2-2*alchemical1*alchemical2
selects pairs crossing between the two regions.
select(mask, softcore, ordinary) chooses the potential in one traversal.
Branches and their derivatives are evaluated conditionally, so an inactive
singular branch need not run. Multiplication by a zero mask does not guarantee
that a singular expression is skipped.
Exclusions and periodic electrostatics
addExclusion(i, j) removes a pair’s contribution from this force:
- It does not create a scaled replacement interaction.
- Each force owns its exclusions; those in other forces are not inherited.
- Conversion copies the source exclusions; duplicates are rejected.
Lattice terms
The standalone Custom constructor starts without lattice sums. They are added through the interaction definition API. The Standard-mode fused example above obtains them from its parent force. In Custom mode:
- The full expression must contain each declared bare interaction, including Coulomb, dispersion, mixing rules, and shifts. Lattice declarations apply matching splitting corrections.
- For dispersion, matching Standard/OpenMM’s LJPME direct-energy convention requires an explicit cutoff shift in the non-Coulomb source. The dispersion cutoff constant depends on the selected splitting.
Switching and tails
- Coulomb lattice sum: automatic switching requires a recognizable additive bare Coulomb term using the declared weight field. Only the remaining cutoff potential is switched. Derived weights that prevent recognition require an explicit cutoff switch in the expression, with automatic switching disabled.
- Dispersion lattice sum: automatic switching is unsupported.
A bare 1/r term has a divergent tail integral. For a full Custom expression
containing Coulomb, an LJ tail therefore needs a separate integrable cutoff-only
definition through
addExpressionTailCorrection(), with
the full expression’s automatic long-range correction disabled. Lattice
declarations do not separate that tail integrand. Standard’s cutoff-replacement
expression already omits managed Coulomb.
Exclusion evaluation
Exclusions remove pair contributions by repeated evaluation; the evaluator may still run on an excluded pair. Generated expressions preserve repeatable arithmetic for this cancellation. External evaluator LTOIR must satisfy the safe-execution and repeatability contract described in the custom pair callback reference.
Expression compilation
Expressions use OpenMM’s Lepton syntax. The runtime differentiates the energy
with respect to r, optimizes particle-only subexpressions, compiles the energy
and derivative with NVRTC, and links the resulting LTOIR into the direct-space
traversal with nvJitLink. Each Context owns its prepared particle and global
buffers; parameter updates and atom reorderings refresh affected values without
recompiling. Other frontends can use the same
cupo/expression.h API.
Older code using setLJExpression(), setCellListPack(), or pack-context updates
must use custom per-particle parameters and live globals instead; those APIs
have been removed.
Update parameters in a running Context
Both modes use the same update rules:
- Live globals:
context.setParameter(name, value)takes effect on the next evaluation without recompilation. Changing a default on the force does not change an existing Context. Standard offsets refresh effective particle and exception parameters together. - Particle values: edits on the plugin force are uploaded with
updateParametersInContext(). Expression-definition getters return copies; edits to those copies first pass back through the corresponding setter. - Structural changes: particle count, exception or exclusion pairs, expression code or parameter layout, cutoff, switching, and lattice definitions require rebuilding or reinitializing the Context.
- Tail policies: native LJ tail-policy changes support
updateParametersInContext(); expression tail-policy changes require reinitialization.
Energy derivatives with respect to global parameters are not provided.
Standard parameter updates
The following snippet uses the water-box example’s objects to change one oxygen’s Lennard-Jones epsilon and update the running Context:
The native LJ tail follows effective particle sigma and epsilon, including live
parameter offsets, by default. Charge-only or exception-only changes reuse its
cached coefficient. With setDispersionCorrectionFollowsParameters(False), the
coefficient is evaluated at global defaults, as in stock OpenMM. This change
requires updateParametersInContext() for an existing Context. The setting does
not enable the correction itself; its energy always uses the current box volume.
Custom parameter updates
These snippets use the objects from the custom switching-and-tail example.
Live globals take effect at the next energy or force evaluation without recompiling the expression:
In standalone Custom mode, particle values are updated on the plugin force and
uploaded with updateParametersInContext():
Supported settings and differences
Both modes share the platform and geometry requirements below.
Standard source restrictions
Conversion preserves the source’s exception periodic-boundary flag. Physical
exception replacements use unwrapped displacements when the flag is False
and periodically wrapped displacements when it is True. Reciprocal exclusion
corrections always use periodic wrapping. This can differ from stock OpenMM
when an exception spans periodic images.
Supported features
Custom expressions have the following scope, in addition to the shared platform and geometry requirements:
Expressions must be symmetric under particle exchange. Custom parameters and arithmetic use FP32 even in a mixed-precision Context. CUDA fast math includes approximate division and square root and flushes subnormal values to zero; results need not match stock OpenMM bit for bit.
The samples include solvated systems and an alchemical example combining periodic electrostatics with custom softcore interactions. See Tests for accuracy checks and Benchmarks for performance measurements.