> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/cuda/cupotential/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.nvidia.com/cuda/cupotential/_mcp/server.

# OpenMM NonbondedForce

> Standard and custom pair potentials, lattice sums, and the cuPotential runtime architecture.

`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:

| OpenMM source                 | Mode     | Pair potential                                                                              |
| ----------------------------- | -------- | ------------------------------------------------------------------------------------------- |
| `openmm.NonbondedForce`       | Standard | Built-in Coulomb and Lennard-Jones interactions, with an optional custom cutoff replacement |
| `openmm.CustomNonbondedForce` | Custom   | An expression defining the complete pair potential, including mixing rules                  |

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

```mermaid
flowchart TB
    F["NonbondedForce"] --> C["CutoffInteraction"]
    F --> L["LatticeSumInteractions<br />Kernel · weights · splitting"]
    C -->|Native| D["DSpace · GPU<br />Pairs, switching, exclusions"]
    C -->|Compiled| E["Compile expression"]
    E --> D
    L --> P["Splitting plans"]
    P --> E
    P --> D
    P --> K["KSpace · GPU<br />Spread → FFT → gather"]
    F --> X["Standard exceptions · GPU"]
    D --> R["Energy and forces"]
    K --> R
    X --> R

    classDef cupo fill:#e5f2d5,stroke:#568700,stroke-width:3px,color:#17230a
    classDef plugin fill:#f1f3f5,stroke:#7a818a,color:#20252b
    class D,E,P,K,X cupo
    class F,C,L,R plugin
```

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:

| Configuration                 | Pair evaluator                                                                                                              |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Standard with built-in LJ     | Native where supported; compiled for other compositions, such as noncanonical lattice weights or different P1/P6 splittings |
| Standard with a custom cutoff | Compiled expression, retaining Standard parameter and exception semantics                                                   |
| Custom                        | Compiled expression defining the full pair potential                                                                        |

DSpace handles ordinary-pair exclusions and their reciprocal corrections.
Standard's physical exception replacements use the separate tuples path.

### Scalar energy corrections

```mermaid
flowchart TB
    C["Cutoff tail policy or<br />independent tail reference"] --> T["Tail corrections · CPU<br />Analytical LJ / numerical expression"]
    P["Splitting plans"] --> S["Self-energy +<br />net-charge correction · CPU"]
    T -->|C / volume| R["Added to total energy"]
    S --> R

    classDef cupo fill:#e5f2d5,stroke:#568700,stroke-width:3px,color:#17230a
    classDef plugin fill:#f1f3f5,stroke:#7a818a,color:#20252b
    class P,S cupo
    class C,T,R plugin
```

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/volume` to 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](#reuse-the-analytical-lj-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](/cuda/cupotential/theory/splitting) and
[Spreading](/cuda/cupotential/theory/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:

| Source                   | Cutoff interaction                     | Lattice sums           |
| ------------------------ | -------------------------------------- | ---------------------- |
| Standard `PME`           | Lennard-Jones repulsion and dispersion | Coulomb                |
| Standard `LJPME`         | Lennard-Jones repulsion and dispersion | Coulomb and dispersion |
| Standalone custom source | Custom expression                      | None                   |

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](#fuse-a-custom-expression-with-coulomb-and-dispersion-lattice-sums)
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()` or
  `nv.DispersionRadialKernel()`.
* A particle weight expression.
* An optional splitting method: `nv.LatticeSumInteraction.Prolate` (the default)
  or `nv.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:

```python
cutoff = force.getCutoffInteraction()
cutoff.combiningRule = nv.CutoffInteraction.LorentzBerthelot
cutoff.useSwitching = True
cutoff.switchingDistance = 0.8  # nm; must be below this force's cutoff
cutoff.tail = nv.CutoffInteraction.HomogeneousTail
force.setCutoffInteraction(cutoff)

coulomb = force.getLatticeSumInteraction()  # No index selects the Coulomb term.
coulomb.splitting = nv.LatticeSumInteraction.Ewald
force.setLatticeSumInteraction(coulomb)
```

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.

| Source   | Copied definition                                                                                            |
| -------- | ------------------------------------------------------------------------------------------------------------ |
| Standard | Particle parameters, exceptions, particle and exception offsets, cutoff, force group, and globals            |
| Custom   | Expression, per-particle records, globals, exclusions, cutoff, switching, and long-range correction settings |

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.

> **Note**
>
> Only the CUDA platform's `"single"` and `"mixed"` precision modes are supported.

> **Note**
>
> 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](/cuda/cupotential/install) 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](#supported-settings-and-differences): each orthorhombic
box dimension must be at least three times the cutoff, or 2.7 nm for this example.

```python
import openmm as mm
from openmm import app, unit
import nv_openmm_plugin as nv

forcefield = app.ForceField("tip3p.xml")
modeller = app.Modeller(app.Topology(), [])
modeller.addSolvent(
    forcefield,
    model="tip3p",
    boxSize=mm.Vec3(3.0, 3.0, 3.0) * unit.nanometer,
)
system = forcefield.createSystem(
    modeller.topology,
    nonbondedMethod=app.PME,
    nonbondedCutoff=0.9 * unit.nanometer,
    ewaldErrorTolerance=5e-4,
    constraints=app.HBonds,
    rigidWater=True,
)

# This example expects exactly one source NonbondedForce.
sources = [
    (i, force) for i, force in enumerate(system.getForces())
    if isinstance(force, mm.NonbondedForce)
]
if len(sources) != 1:
    raise ValueError("Expected exactly one OpenMM NonbondedForce")
index, source = sources[0]
nonbonded = nv.NonbondedForce(source)
system.addForce(nonbonded)
system.removeForce(index)

integrator = mm.LangevinMiddleIntegrator(
    300 * unit.kelvin,
    1 / unit.picosecond,
    0.002 * unit.picoseconds,
)
integrator.setRandomNumberSeed(2026)
simulation = app.Simulation(
    modeller.topology,
    system,
    integrator,
    platform=mm.Platform.getPlatformByName("CUDA"),
    platformProperties={"Precision": "mixed"},
)
simulation.context.setPositions(modeller.positions)
simulation.minimizeEnergy(maxIterations=100)
simulation.context.setVelocitiesToTemperature(300 * unit.kelvin, 2026)
simulation.step(100)
state = simulation.context.getState(getEnergy=True)
print("Potential energy:", state.getPotentialEnergy())
```

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.

```python
from itertools import product

import openmm as mm
from openmm import unit
import nv_openmm_plugin as nv

# Positions in nm; one parameter record will be added for each particle.
positions = [mm.Vec3(*xyz) for xyz in product((0.2, 0.9, 1.6), repeat=3)]
system = mm.System()
for _ in positions:
    system.addParticle(39.9 * unit.dalton)
system.setDefaultPeriodicBoxVectors(
    mm.Vec3(4.0, 0.0, 0.0) * unit.nanometer,
    mm.Vec3(0.0, 4.0, 0.0) * unit.nanometer,
    mm.Vec3(0.0, 0.0, 4.0) * unit.nanometer,
)

source = mm.CustomNonbondedForce(
    "lambda_lj*4*epsilon*((sigma/r)^12-(sigma/r)^6);"
    "sigma=(sigma1+sigma2)/2;"
    "epsilon=sqrt(epsilon1*epsilon2)"
)
source.addPerParticleParameter("sigma")
source.addPerParticleParameter("epsilon")
source.addGlobalParameter("lambda_lj", 1.0)
source.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)
source.setCutoffDistance(1.25 * unit.nanometer)
source.setUseSwitchingFunction(True)
source.setSwitchingDistance(1.0 * unit.nanometer)
source.setUseLongRangeCorrection(True)

for _ in positions:
    # Custom parameters are numeric values: sigma in nm, epsilon in kJ/mol.
    source.addParticle([0.34, 0.997])
source.addExclusion(0, 1)  # Omit this pair from this force.

# The System contains the converted force; source is its input definition.
force = nv.CustomNonbondedForce(source)
system.addForce(force)

integrator = mm.VerletIntegrator(1.0 * unit.femtosecond)
context = mm.Context(
    system,
    integrator,
    mm.Platform.getPlatformByName("CUDA"),
    {"Precision": "mixed"},
)
context.setPositions(positions * unit.nanometer)
context.setVelocitiesToTemperature(100 * unit.kelvin, 1234)
integrator.step(10)
print("Potential energy:", context.getState(getEnergy=True).getPotentialEnergy())
```

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](https://docs.openmm.org/latest/api-python/generated/openmm.openmm.CustomNonbondedForce.html)
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](#reuse-the-analytical-lj-tail) 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](#example-switching-and-a-homogeneous-tail);
the subsequent `system.addForce(force)` and Context setup are the same:

```python
# The native reference supplies the only tail correction.
source.setUseLongRangeCorrection(False)
reference = mm.NonbondedForce()
reference.setNonbondedMethod(mm.NonbondedForce.PME)
reference.setEwaldErrorTolerance(5e-4)
reference.setCutoffDistance(source.getCutoffDistance())
reference.setUseSwitchingFunction(True)
reference.setSwitchingDistance(source.getSwitchingDistance())
reference.setUseDispersionCorrection(True)
reference.addGlobalParameter("lambda_lj", 1.0)

for i in range(source.getNumParticles()):
    sigma, epsilon = source.getParticleParameters(i)
    reference.addParticle(0.0, sigma, 0.0)
    # Effective epsilon = lambda_lj * epsilon, matching the custom expression.
    reference.addParticleParameterOffset("lambda_lj", i, 0.0, 0.0, epsilon)
for i in range(source.getNumExclusions()):
    a, b = source.getExclusionParticles(i)
    reference.addException(a, b, 0.0, 1.0, 0.0)

force = nv.NonbondedForce(reference)
force.removeLatticeSumInteraction(0)  # This uncharged example needs no Coulomb sum.
force.setCutoffInteraction(source, preserveDispersionCorrection=True)
```

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()` and `setParticleParameterOffset()`.
* **Custom expression:** `getCutoffExpression()` returns a copy of the custom
  force definition.
  Changes are passed back through
  `setCutoffInteraction(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.

```python
from itertools import product

import openmm as mm
from openmm import unit
import nv_openmm_plugin as nv

positions = [mm.Vec3(*xyz) for xyz in product((0.2, 0.9, 1.6, 2.3), repeat=3)]
system = mm.System()
for _ in positions:
    system.addParticle(39.9 * unit.dalton)
system.setDefaultPeriodicBoxVectors(
    mm.Vec3(4.0, 0.0, 0.0) * unit.nanometer,
    mm.Vec3(0.0, 4.0, 0.0) * unit.nanometer,
    mm.Vec3(0.0, 0.0, 4.0) * unit.nanometer,
)

# This definition supplies charges and reciprocal dispersion weights.
standard = mm.NonbondedForce()
standard.setNonbondedMethod(mm.NonbondedForce.LJPME)
standard.setCutoffDistance(1.25 * unit.nanometer)
standard.setEwaldErrorTolerance(5e-4)
standard.setUseDispersionCorrection(False)

# Full unsplit non-Coulomb potential; only repulsion depends on lambda_rep.
cutoff = mm.CustomNonbondedForce(
    "4*epsilon*(lambda_rep*(sigma/r)^12-(sigma/r)^6);"
    "sigma=(sigma1+sigma2)/2;epsilon=sqrt(epsilon1*epsilon2)"
)
cutoff.addPerParticleParameter("sigma")
cutoff.addPerParticleParameter("epsilon")
cutoff.addGlobalParameter("lambda_rep", 1.0)
cutoff.setNonbondedMethod(mm.CustomNonbondedForce.CutoffPeriodic)
cutoff.setCutoffDistance(1.25 * unit.nanometer)
cutoff.setUseSwitchingFunction(False)
cutoff.setUseLongRangeCorrection(False)

for i in range(len(positions)):
    # Numeric parameters use e, nm, and kJ/mol. Total charge is zero.
    standard.addParticle(0.05 if i % 2 == 0 else -0.05, 0.34, 0.997)
    cutoff.addParticle([0.34, 0.997])
standard.addException(0, 1, 0.0, 0.34, 0.0)
cutoff.addExclusion(0, 1)  # Must match the Standard exception pairs.

# LJPME conversion enables both lattice sums with C2 Prolate splitting by default.
force = nv.NonbondedForce(standard)
force.setCutoffInteraction(cutoff)
system.addForce(force)  # One force includes the cutoff and both lattice terms.

integrator = mm.VerletIntegrator(1.0 * unit.femtosecond)
context = mm.Context(
    system, integrator, mm.Platform.getPlatformByName("CUDA"),
    {"Precision": "mixed"},
)
context.setPositions(positions * unit.nanometer)
print("Potential energy:", context.getState(getEnergy=True).getPotentialEnergy())
context.setParameter("lambda_rep", 0.5)
print("Modified repulsion:", context.getState(getEnergy=True).getPotentialEnergy())
```

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^-6` term 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`:

```python
def replace_custom_force(system, force_index):
    source = system.getForce(force_index)
    if not isinstance(source, mm.CustomNonbondedForce):
        raise TypeError("Expected an OpenMM CustomNonbondedForce")
    replacement = nv.CustomNonbondedForce(source)
    system.removeForce(force_index)
    system.addForce(replacement)
    return replacement
```

Conversion and ownership follow the [shared rules](#what-conversion-does).

### Replace or inspect an expression

`setCutoffInteraction()` accepts three forms:

| Input                                 | Effect                                                                                                                                          |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| A stock `openmm.CustomNonbondedForce` | Copies the expression, particle records, globals, and exclusions.                                                                               |
| Bulk keyword arguments                | Installs an expression and parameter table, inheriting the force's cutoff, switching settings, and exclusions.                                  |
| A `nv.CutoffInteraction` descriptor   | Changes the potential and policies using the expression records already attached to the force. Custom mode uses `CutoffInteraction.Expression`. |

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 optional `globalParameters` dictionary. Records
  have one row per existing particle and columns in `parameterNames` order.
  Bare numbers use OpenMM units; `Quantity` inputs 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 through `setExpressionTailCorrection(index, updated)` and
  `updateParametersInContext()`.
* **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](#configure-interaction-definitions).
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()`](#separate-expression-tail-corrections), 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](/cuda/cupotential/c-api/reference#custom-pair-expressions).

### 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](/cuda/cupotential/c-api/reference#custom-pair-expressions).

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:

```python
oxygen = next(atom.index for atom in modeller.topology.atoms()
              if atom.element == app.element.oxygen)
charge, sigma, epsilon = nonbonded.getParticleParameters(oxygen)
nonbonded.setParticleParameters(oxygen, charge, sigma, 0.95 * epsilon)
nonbonded.updateParametersInContext(simulation.context)
print("Updated energy:",
      simulation.context.getState(getEnergy=True).getPotentialEnergy())
```

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:

```python
context.setParameter("lambda_lj", 0.5)
print("Scaled energy:", context.getState(getEnergy=True).getPotentialEnergy())
```

In standalone Custom mode, particle values are updated on the plugin force and
uploaded with `updateParametersInContext()`:

```python
force.setParticleParameters(0, [0.36, 1.1])  # sigma in nm, epsilon in kJ/mol
force.updateParametersInContext(context)
print("Updated energy:", context.getState(getEnergy=True).getPotentialEnergy())
```

## Supported settings and differences

Both modes share the platform and geometry requirements below.

| Setting                | cuPotential behavior                                                                                                                                                          |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Platform and precision | CUDA with [single or mixed precision](#cuda-platform-and-precision).                                                                                                          |
| Periodic box           | Orthorhombic and OpenMM reduced triclinic boxes are supported. Each orthorhombic dimension must be at least three cutoff lengths, including after NPT contraction.            |
| NPT allocation         | The default box safety factor is selected at Context creation. An active barostat allows 1.15 times the initial box lengths; an explicit larger factor can reserve more room. |

### Standard source restrictions

| Setting                    | cuPotential behavior                                                                                                                                                                                                                     |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Accepted source methods    | `PME` and `LJPME`                                                                                                                                                                                                                        |
| Unsupported source methods | `NoCutoff`, `CutoffNonPeriodic`, `CutoffPeriodic`, and `Ewald`                                                                                                                                                                           |
| Accuracy target            | The source Ewald error tolerance must currently be `5e-4`. The reciprocal mesh is chosen from the cutoff and box.                                                                                                                        |
| Explicit PME parameters    | Pinned meshes are rejected. A pinned alpha must agree with the cutoff-derived value. Automatic parameters correspond to `source.setPMEParameters(0, 0, 0, 0)` and, for LJPME, `source.setLJPMEParameters(0, 0, 0, 0)` before conversion. |
| Direct-space suppression   | Conversion does not preserve `source.setIncludeDirectSpace(False)`. A reciprocal-only source regains direct interactions, which can double-count contributions supplied by another force.                                                |

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:

| Feature                    | Custom expressions in cuPotential                                                                                                                                                                  |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Source method              | Standalone Custom accepts `CutoffPeriodic`; the fused example uses a Standard `LJPME` parent.                                                                                                      |
| Parameters                 | Per-particle numeric records and live Context globals                                                                                                                                              |
| Pair selection             | Exclusions, or symmetric expressions using per-particle flags                                                                                                                                      |
| Switching and tails        | Quintic switching and numerical tails for integrable potentials; Standard can retain an analytical LJ reference tail. Reciprocal dispersion disables automatic switching and homogeneous LJ tails. |
| Reciprocal calculations    | Optional Coulomb and attractive dispersion lattice sums; expression coefficients and declared weights must agree.                                                                                  |
| Unsupported stock features | `NoCutoff`, `CutoffNonPeriodic`, interaction groups, tabulated functions, computed values, and energy parameter derivatives                                                                        |

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](/cuda/cupotential/samples) include solvated systems and an alchemical
example combining periodic electrostatics with custom softcore interactions.
See [Tests](/cuda/cupotential/tests) for accuracy checks and
[Benchmarks](/cuda/cupotential#benchmarks) for performance measurements.