Skip to content

SimulationCore & Low-Level API ​

This page documents the low-level GPU stepping engine centered on SimulationState, build_simulation, explicit integrator specs, ParticleGroups, Filters, and collision counting. Normal simulation scripts should prefer the declarative Workflow API; use this layer when you need direct access to GPU-resident CuArray buffers, manual stepping, or custom host orchestration.

Minimal low-level stepping pattern ​

julia
using ParticleDynamics

N = 64
dt = 2.0f-4
sigma = 1.0f0
rcut = Float32(2^(1 / 6)) * sigma

st = build_simulation(
    N=N,
    box=(40.0f0, 40.0f0),
    cutoff=rcut,
    skin=0.4f0,
    cap=Int32(32),
    neigh_interval=10,
    epsilon=10.0f0,
    sigma=sigma,
    gamma=50.0f0,
    temperature=1.0f0,
    nonbonded=:wca,
    precision=:f32,
)

# Assign a non-overlapping configuration before the first step.
copyto!(st.rx, Float32[2 * mod(i - 1, 8) - 7 for i in 1:N])
copyto!(st.ry, Float32[2 * ((i - 1) ÷ 8) - 7 for i in 1:N])

# Construct and reuse an explicit integrator spec.
spec = baoab_fast(st; gamma=50.0f0, temperature=1.0f0, dt=dt)
step_many!(st, spec, dt, 200; compute_energy=false)

Cached forces and manual state edits ​

st.force_valid records whether st.fx, st.fy (st.fz) can supply the next initial kick or Brownian drift. After mutating coordinates, types, topology, force parameters, or an external potential's internal state directly on st, call invalidate_forces!(st) (and sync_unwrapped!(st) if unwrapped positions are enabled). Velocity-only edits do not require force invalidation. An exception during a step invalidates the force cache without rolling back partially advanced coordinates or velocities.

Timestep consistency ​

step!, step_graph!, and step_many! require a finite positive timestep. For Langevin and Brownian specs, dt must match the constructor timestep (after conversion to state precision) because noise amplitudes and Ornstein–Uhlenbeck coefficients are cached for that dt. For static force/energy/virial evaluation without advancing dynamics, call evaluate_configuration!(st, EvaluationRequest(energy=true, virial=true)). For deterministic microcanonical MD, use nve(st; dt=...) rather than passing zero friction to stochastic specs that divide by gamma.

Core state and stepping ​

ParticleDynamics.SimulationCore Module

Low-level simulation core: SimulationState, force and energy evaluation, integrator specs, stepping, minimization and pressure control. The commonly used names are re-exported from ParticleDynamics; advanced helpers are reached as ParticleDynamics.SimulationCore.name.

ParticleDynamics.DeviceEngine Module
julia
DeviceEngine

Device-resident, graph-replayed MD engine that replaced the staged step engine. It holds the GPU neighbor control, spatial sorting, persistent global observables, cooperative traversal and row construction, displacement-only maintenance, and control-kernel fusion.

Organized as a strict 6-layer acyclic include DAG: Layer 1 — Core primitives (ordering, observables, traversal, pair models, builder, fusion, RNG) Layer 2 — Engine features & thermostats (ENGINE_FEATURES registry) Layer 3 — Water & decoupled solute/constraint fast paths (engine/water/) Layer 4 — Cluster-pair backend, 1-4 exceptions & force scheduling (engine/cluster/) Layer 5 — Run control, graph capture & device barostats (engine/run/, engine/barostat/) Layer 6 — StateEngine lifecycle, boundary recovery & batch scheduler (engine/state/)

ParticleDynamics.SimulationCore.SimulationState Type
julia
SimulationState{T}

Structure-of-arrays storage for all GPU-resident buffers required to evolve a non-equilibrium simulation. Users normally do not construct this type manually; build_simulation assembles an allocated instance with concrete CuArray fields and consistent dimensionality inferred from the box argument.

Key fields that user code may read or mutate:

  • rx, ry[, rz], vx, vy[, vz], fx, fy[, fz]: positions, velocities, and force accumulators in GPU memory. Arrays are sized N and remain allocated during ordinary stepping; optional spatial reordering can replace them. After manual position/force-model edits, call invalidate_forces!(st).

  • rx_unwrap, ry_unwrap[, rz_unwrap]: optional unwrapped positions that track continuous motion across periodic boundaries (enabled via unwrapped_positions).

  • nbh: neighbor matrix (either dense cell list or sentinel all-pairs) built with the NeighborLists.build_neighbors_* family using the requested cutoff, skin, and capacity.

  • mass, dt: nominal build-time timestep plus the scalar fast-path mass used when all particles share one mass. Heterogeneous-mass states additionally populate mass_particle and inv_mass_particle with per-particle data.

  • Epot, Ekin, virial, dq, dU plus the corresponding *_accum buffers: energy, virial, and heat observables that can be sampled directly on the GPU.

  • virial_nonbonded, virial_bonded, virial_tensor, virial_tensor_accum: GPU-resident configurational virial tensors. These store the raw pairwise virial W = Σ r_ij ⊗ F_ij using the same minimum-image displacement used in the force kernels. The scalar virial field stores the trace of W for backward compatibility with existing examples. These buffers are refreshed on force evaluations with compute_energy=true.

  • virial_global, virial_global_accum: global virial terms without a per-particle decomposition (the reciprocal-space electrostatic tensor). System totals (virial_tensor, collect_step_observables) include them.

  • vdw_modifier: Lennard-Jones energy convention at the cutoff, :none or :potential_shift (see set_vdw_modifier!).

  • nonbonded_backend, cluster, cluster_config: short-range traversal selected with set_nonbonded_backend! and its lazily built engine.

  • charge: optional per-particle charges; electrostatics: optional long-range Coulomb solver attached with attach_electrostatics!.

  • energy_valid: true only while the energy and virial buffers belong to the current coordinates, i.e. after a force evaluation with compute_energy=true and before any position change or invalidate_forces!. Force-only evaluations clear it. Workflow observables refresh stale energies before sampling.

  • typeid: per-particle type ids used by Filters and mixed-size LJ kernels.

  • freeze_*: optional buffers used by the freeze/tether helpers in Filters.

  • coll_*: optional buffers that appear when collision counting is enabled via enable_collision_counting!.

All other fields are internal implementation details (neighbor rebuild state, bond lists, cached LJ parameters, etc.) and should be treated as read-only. Current backend abstraction is storage-level only: SimulationState remains CuArray-backed today, and the execution kernels are still CUDA-specific.

ParticleDynamics.SimulationCore.build_simulation Function
julia
build_simulation(; N, box, cutoff=1, skin=0.4, cap=Int32(96),
                  neigh_interval=20, use_neighborlist=true,
                  epsilon=1, sigma=1, gamma=1, temperature=1,
                  noise_corr_time=nothing, dt=0.001,
                  mass=1, bonds=nothing, bonding=nothing,
                  nonbonded=:lj, softrep_params=nothing, backend=:cuda,
                  precision=:f32, unwrapped_positions::Bool=false,
                  spatial_reorder::Bool=true, reorder_interval::Int=500,
                  exclude_bonded_pairs::Bool=true, neighbor_cutoff=nothing,
                  charges=nothing, nonbonded_backend=:ell, prune_buffer=nothing)

Construct a SimulationState with GPU-resident SoA arrays and a neighbor list configured for the requested potential. All inputs are keyword arguments so that scripts can copy known-good parameter sets directly from the examples/ directory without ambiguity.

Key behaviors:

  • The simulation dimensionality (2D vs 3D) is inferred from the length of box. Positions/velocities/forces allocate the corresponding CuArrays.

  • For nonbonded = :wca the neighbor cutoff is forced to the physical WCA value r_c = 2^(1/6) σ even if a larger cutoff was passed, guaranteeing that kernels reuse the validated parameter sets from the packaged examples.

  • temperature accepts either a scalar or length-N vector and is used to initialize velocities. Stochastic integrator parameters are constructed later via explicit specs such as velocityverlet and eulermaruyama.

  • mass accepts either a scalar or a length-N vector. Initial velocities are drawn from a Maxwell–Boltzmann distribution with width sqrt(kT / m) for particles with positive mass, then centered to remove center-of-mass drift.

  • When unwrapped_positions=true, additional rx_unwrap/ry_unwrap/rz_unwrap buffers track continuous positions across periodic boundaries.

  • With spatial_reorder=true (the default) and a dense cell list, NVE runs periodically permute all per-particle arrays into cell-sorted order (at most once per reorder_interval steps, at a neighbor rebuild). This keeps storage order aligned with space, which is essential for force-kernel memory locality at large N. st.tag[k] records the build-time id of the particle in slot k, and GSD/restart output is written in build-time order. Filters.Indices are particle ids and are mapped to current slots through st.tag; typeid-based selections remain valid because typeid is permuted consistently. Pass spatial_reorder=false if external code indexes the state arrays directly by fixed particle number.

  • nonbonded = :none builds a state without a short-range vdW term (pure charged or purely bonded systems); cutoff then only sizes the neighbor list.

  • neighbor_cutoff widens the neighbor-list radius beyond the vdW cutoff (e.g. to a longer real-space Coulomb cutoff) without changing the vdW potential, which keeps applying its own cutoff.

  • charges (length N, caller's charge unit) allocates st.charge; attach a long-range solver with attach_electrostatics!.

  • vdw_modifier = :potential_shift shifts each Lennard-Jones pair energy to zero at its cutoff (forces unchanged; see set_vdw_modifier!).

  • nonbonded_backend = :cluster evaluates Lennard-Jones and real-space Coulomb with the fused cluster-pair engine instead of per-particle neighbor rows (3D; see set_nonbonded_backend!, which also documents prune_buffer).

Example (2D WCA fluid, N=4096):

julia
st = build_simulation(N=4096, box=(250f0, 250f0),
                      cutoff=Float32(2^(1/6)), skin=Float32(2^(1/6))/2,
                      cap=Int32(250), neigh_interval=50,
                      epsilon=1f4, sigma=1f0,
                      gamma=615f0, temperature=10f0,
                      dt=1f-5, nonbonded=:wca, precision=:f32)
copyto!(st.rx, Float32[3 * mod(i - 1, 64) - 95 for i in 1:4096])
copyto!(st.ry, Float32[3 * ((i - 1) ÷ 64) - 95 for i in 1:4096])
vv = velocityverlet(st; gamma=615f0, temperature=10f0, dt=1f-5)
step!(st, vv, 1f-5; compute_energy=false)

Returns an allocated SimulationState. Assign particle coordinates before the first step; the initial dense neighbor build is deferred until the first force evaluation or explicit neighbor update. Stochastic controls such as noise_corr_time now belong to the explicit integrator spec rather than the core simulation state.

ParticleDynamics.SimulationCore.step! Function
julia
step!(st, spec, dt; compute_energy=true)

Canonical explicit stepping API. Every step runs on the device engine (ParticleDynamics.DeviceEngine adds the methods for each integrator).

julia
step!(st, vv, dt; compute_energy=true)

Compatibility wrapper for explicit VVParams stepping.

julia
step!(st, bao, dt; compute_energy=true)

Compatibility wrapper for explicit BAOABParams stepping.

julia
step!(st, bp, dt; compute_energy=true)

Compatibility wrapper for explicit Brownian midpoint stepping.

julia
step!(st, em, dt; compute_energy=true)

Compatibility wrapper for explicit Euler-Maruyama stepping.

julia
step!(st, nhc, dt; compute_energy=true)

Compatibility wrapper for explicit Nose-Hoover Chain parameter stepping.

julia
step!(st, csvr_params, dt; compute_energy=true)

Compatibility wrapper for explicit CSVR parameter stepping.

ParticleDynamics.SimulationCore.step_graph! Function
julia
step_graph!(st, spec, dt; compute_energy=true)

Same as step!: every step is a captured CUDA-graph replay on the device engine.

julia
step_graph!(st, vv, dt; compute_energy=true)

Compatibility wrapper for explicit VVParams graph stepping.

julia
step_graph!(st, bao, dt; compute_energy=true)

Compatibility wrapper for explicit BAOABParams graph stepping.

julia
step_graph!(st, bp, dt; compute_energy=true)

Compatibility wrapper for explicit Brownian midpoint graph stepping.

julia
step_graph!(st, em, dt; compute_energy=true)

Compatibility wrapper for explicit Euler-Maruyama graph stepping.

julia
step_graph!(st, nhc, dt; compute_energy=true)

Compatibility wrapper for explicit Nose-Hoover chain graph stepping.

julia
step_graph!(st, csvr_params, dt; compute_energy=true)

Compatibility wrapper for explicit CSVR graph stepping.

ParticleDynamics.SimulationCore.step_many! Function
julia
step_many!(st, spec, dt, nsteps; compute_energy=false)

Advance st by nsteps timesteps using K-step batched CUDA graphs across plain un-sampled intervals and falling back seamlessly to 1-step graphs at barostat, observable, or host-hook boundaries. Produces bit-exact trajectories relative to calling step! nsteps times.

ParticleDynamics.SimulationCore.sync_unwrapped! Function
julia
sync_unwrapped!(st)

Copy the wrapped positions into the unwrapped buffers. Call this after manually overwriting st.rx/st.ry/st.rz when unwrapped_positions=true.

ParticleDynamics.SimulationCore.invalidate_forces! Function
julia
invalidate_forces!(st) -> st

Invalidate cached forces after manually changing coordinates, force parameters, particle types, topology, or an external provider's internal state. The next step initializes its first force before using it, independently of st.step. This does not resize or reconfigure neighbor ranges: parameter/box changes must also update the appropriate neighbor container. Velocity-only edits do not require force invalidation.

Configuration evaluation and observables ​

ParticleDynamics.SimulationCore.EvaluationRequest Type
julia
EvaluationRequest(; forces=true, energy=false, virial=false)

Quantities requested from evaluate_configuration!. Energy and virial are produced by the same kernels, so requesting either refreshes both.

ParticleDynamics.SimulationCore.evaluate_configuration! Function
julia
evaluate_configuration!(st, request=EvaluationRequest(); freeze_spring=st.force_freeze_spring) -> st

Make the active force slot, and the energy/virial buffers when requested, describe the current coordinates. Buffers that are already current are reused. An energy or virial request currently also recomputes forces, since the energy kernels produce them anyway.

ParticleDynamics.SimulationCore.total_potential_energy Function
julia
total_potential_energy(st) -> Float64

Whole-system potential energy at the current coordinates, including global terms that are distributed into Epot (the electrostatic mesh energy). The reduction runs on the device in Float64 even for Float32 states. Stale energy buffers are refreshed first.

ParticleDynamics.SimulationCore.total_kinetic_energy Function
julia
total_kinetic_energy(st) -> Float64

Σ m v²/2 over all particles (device reduction in Float64).

ParticleDynamics.SimulationCore.total_virial_trace Function
julia
total_virial_trace(st) -> Float64

Trace of the whole-system configurational virial tr(W), W = Σ r ⊗ F, including global terms and the velocity-dependent rigid-water constraint tensor when attached. Constraint forces are not added to the kick buffers. Device reduction in Float64; stale buffers are refreshed first.

ParticleDynamics.SimulationCore.total_configurational_virial Function
julia
total_configurational_virial(st) -> NamedTuple

Whole-system configurational virial tensor (Float64 components in virial_components order), including global terms.

ParticleDynamics.SimulationCore.collect_step_observables Function
julia
collect_step_observables(st, spec) -> NamedTuple

Collect universal diagnostics, integrator-specific diagnostics, and bath heat / entropy totals accumulated since the last reset of the relevant buffers. Refreshes stale energies/virials when !st.energy_valid and accumulates totals in Float64.

ParticleDynamics.SimulationCore.reset_bath_exchange_accumulators! Function
julia
reset_bath_exchange_accumulators!(st, spec)

Reset the accumulators used for bath heat and entropy diagnostics. This leaves positions, velocities, and thermostat internal state untouched.

ParticleDynamics.SimulationCore.accumulate_virial! Function
julia
accumulate_virial!(st)

Add the instantaneous virial trace and total virial tensor into their per-interval accumulators, including the global (reciprocal electrostatic) tensor. st.virial remains the scalar per-particle trace of the configurational virial tensor for backward compatibility.

ParticleDynamics.SimulationCore.virial_components Function
julia
virial_components(st)

Return the component ordering used by the current simulation state's virial tensors.

  • 2D: (:xx, :yy, :xy)

  • 3D: (:xx, :yy, :zz, :xy, :xz, :yz)

ParticleDynamics.SimulationCore.virial_tensor Function
julia
virial_tensor(st; part=:total, accumulated=false)

Return the particle-summed configurational virial tensor components as a NamedTuple. The stored sign convention is the raw configurational virial W = Σ r_ij ⊗ F_ij, so pressure/stress formulas may need an additional minus sign depending on convention.

Component ordering follows:

  • 2D: (:xx, :yy, :xy)

  • 3D: (:xx, :yy, :zz, :xy, :xz, :yz)

part selects :total (per-particle terms, reciprocal-space electrostatic virial and rigid-water constraint virial), :nonbonded (vdW plus real-space Coulomb and exception corrections), :bonded, or :reciprocal (the global electrostatic mesh tensor only).

The primary buffers remain GPU-resident in SimulationState; this helper reduces the selected tensor to a small host-side summary for diagnostics. Virial buffers are refreshed by force evaluations with compute_energy=true. Rigid-water contributions are recomputed from current coordinates, velocities and conservative forces when sampled; they are not stored in st.virial.

Explicit integrator constructors and specs ​

ParticleDynamics.SimulationCore.nve Function
julia
nve(st; dt=st.dt) -> NVESpec

Create a deterministic microcanonical MD integrator using plain velocity Verlet. Unlike the stochastic velocityverlet constructor, this path owns no thermostat or noise parameters and advances only under conservative forces.

ParticleDynamics.SimulationCore.velocityverlet Function
julia
velocityverlet(st; gamma=nothing, friction_rate=nothing, tau=nothing, temperature,
               noise_corr_time=nothing, ou_scales=nothing, mass=st.mass, dt=st.dt) -> VVSpec

Construct a GJF/Langevin velocity-Verlet spec with integrator-owned stochastic buffers. Supply exactly one of gamma, friction_rate (uniform  ), or tau ( ).

ParticleDynamics.SimulationCore.baoab Function
julia
baoab(st; gamma=nothing, friction_rate=nothing, tau=nothing, temperature,
      noise_corr_time=nothing, ou_scales=nothing, mass=st.mass, dt=st.dt,
      track_thermo=true) -> BAOABSpec

Construct a BAOAB Langevin spec with integrator-owned stochastic buffers. Supply exactly one of gamma, friction_rate (uniform  ), or tau ( ). Set track_thermo=false (or call baoab_fast) to omit per-step stochastic-thermodynamics dU and dq accumulation.

ParticleDynamics.SimulationCore.baoab_fast Function
julia
baoab_fast(st; gamma=nothing, friction_rate=nothing, tau=nothing, temperature,
           noise_corr_time=nothing, ou_scales=nothing, mass=st.mass, dt=st.dt) -> BAOABSpec

Copy of baoab with per-step stochastic-thermodynamics dU and dq accumulation disabled (track_thermo=false), producing identical Langevin trajectories without per-atom dU/dq global memory read-modify-writes.

ParticleDynamics.SimulationCore.baoa Function
julia
baoa(st; gamma=nothing, friction_rate=nothing, tau=nothing, temperature,
     noise_corr_time=nothing, ou_scales=nothing, mass=st.mass, dt=st.dt) -> BAOASpec

BAOA variant of baoab without the final B kick.

ParticleDynamics.SimulationCore.gsm Function
julia
gsm(st; gamma=nothing, friction_rate=nothing, tau=nothing, temperature,
    noise_corr_time=nothing, ou_scales=nothing, mass=st.mass, dt=st.dt) -> GSMSpec

Construct a GSM spec.

ParticleDynamics.SimulationCore.eulerheun Function
julia
eulerheun(st; gamma, temperature, noise_corr_time=nothing, ou_scales=nothing,
          dt=st.dt) -> BrownianSpec

Build a midpoint Brownian spec with integrator-owned stochastic buffers.

ParticleDynamics.SimulationCore.eulermaruyama Function
julia
eulermaruyama(st; gamma, temperature, noise_corr_time=nothing, ou_scales=nothing,
              dt=st.dt) -> EMSpec

Return an Euler-Maruyama spec for overdamped dynamics (examples/3D_BD.jl).

ParticleDynamics.SimulationCore.nosehooverchain Function
julia
nosehooverchain(st; temperature=1, tau=1, chain_length=5, substeps=5,
                mass=st.mass, chain_masses=nothing, propagator=:gromacs) -> NHCSpec

Create a deterministic NVT integrator specification using a Nose-Hoover Chain. When chain_masses is omitted, masses are initialized from (dof, T, tau) using the standard Q₁ = g T τ², Qⱼ = T τ² (j>1) rule. propagator selects the chain update scheme: :gromacs is the package default and uses a GPU port of the reversible Suzuki-Yoshida propagator used by GROMACS, :lammps uses a GPU port of the reversible tloop chain update used by LAMMPS, and :legacy preserves the original package implementation. For propagator=:gromacs, substeps=5 matches the default fifth-order outer repetition used there; for propagator=:lammps, substeps corresponds to LAMMPS tloop and substeps=1 matches the LAMMPS default.

ParticleDynamics.SimulationCore.csvr Function
julia
csvr(st; temperature=1, tau=1, mass=st.mass, interval=1) -> CSVRSpec
csvr(st; temperatures, taus, mass=st.mass, interval=1) -> CSVRSpec

Create a deterministic MD integrator using the Bussi canonical-sampling through velocity rescaling (CSVR) thermostat. The thermostat acts on one or more baths defined by filter assignments, with one global velocity-rescaling factor drawn per bath every interval steps (GROMACS nsttcouple), each coupling integrating the thermostat over interval·dt.

ParticleDynamics.IntegratorInterfaces.AbstractIntegratorSpec Type
julia
AbstractIntegratorSpec{T}

Base type of the integrator specs (VV, BAOAB, BAOA, GSM, Brownian, EM, NHC, CSVR, NVE). The device engine (ParticleDynamics.DeviceEngine) steps every spec in captured CUDA graphs; the protocol here validates inputs and sizes per-spec workspaces.

ParticleDynamics.SimulationCore.IntegratorSpec Type
julia
IntegratorSpec

Alias of AbstractIntegratorSpec.

ParticleDynamics.SimulationCore.NVESpec Type
julia
NVESpec{T}

Concrete integrator specification for deterministic microcanonical (NVE) dynamics using plain velocity Verlet.

ParticleDynamics.SimulationCore.VVSpec Type

Concrete spec for the package's Langevin/GJF velocityverlet path.

ParticleDynamics.SimulationCore.BAOABSpec Type

BAOAB splitting spec.

ParticleDynamics.SimulationCore.BAOASpec Type

BAOA splitting (no trailing B half-kick).

ParticleDynamics.SimulationCore.GSMSpec Type

Generalized simulation scheme (GSM) spec, which reuses the BAOAB parameter type.

ParticleDynamics.SimulationCore.BrownianSpec Type

Midpoint Brownian integrator spec created by eulerheun.

ParticleDynamics.SimulationCore.EMSpec Type

Euler-Maruyama overdamped spec created by eulermaruyama.

ParticleDynamics.SimulationCore.NHCParams Type
julia
NHCParams{T}

Parameter container for deterministic Nose-Hoover Chain (NHC) thermostatting. chain_masses stores the thermostat inertia values Q_j.

ParticleDynamics.SimulationCore.NHCSpec Type
julia
NHCSpec{T}

Concrete integrator specification for NVT dynamics with a Nose-Hoover Chain thermostat.

ParticleDynamics.SimulationCore.CSVRParams Type
julia
CSVRParams{T}

Parameter container for the canonical-sampling-through-velocity-rescaling (CSVR/Bussi) thermostat. The thermostat acts on the kinetic energy of each assigned bath with target temperature target_temperature[b] and response time tau[b].

ParticleDynamics.SimulationCore.CSVRSpec Type
julia
CSVRSpec{T}

Concrete integrator specification for deterministic NVT dynamics with a stochastic global Bussi/CSVR thermostat.

Integrator interface hooks ​

ParticleDynamics.IntegratorInterfaces.collect_integrator_observables Function
julia
collect_integrator_observables(spec, st) -> NamedTuple

Optional integrator-specific observables merged into generic writer/logging pipelines.

ParticleDynamics.IntegratorInterfaces.ensure_integrator_workspace! Function
julia
ensure_integrator_workspace!(spec, st)

Ensure any lazily allocated integrator-local work buffers exist and are shaped for the provided simulation state.

ParticleDynamics.IntegratorInterfaces.integrator_id Function
julia
integrator_id(spec) -> UInt8

Small numeric id used for compatibility flags (e.g. writer behavior).

ParticleDynamics.IntegratorInterfaces.integrator_name Function
julia
integrator_name(spec) -> Symbol

Stable symbolic name used in diagnostics and stage traces.

ParticleDynamics.IntegratorInterfaces.validate_integrator_inputs! Function
julia
validate_integrator_inputs!(spec, st, dt)

Validate runtime preconditions for one step. Integrators should check constraints such as positive friction where required.

Particle groups and filters ​

ParticleDynamics.ParticleGroups Module

Particle selection and grouping subsystem for thermostats, observables, and diagnostics.

This module provides a unified interface for particle selections that can be used across:

  • Thermostat applications (different baths or controls)

  • Observable computations (subset-specific diagnostics)

  • Writer/diagnostic scheduling

  • Filters and constraints

The key abstraction is ParticleGroup, which materializes a particle selection as either host indices or device indices, reusable across multiple operations.

ParticleDynamics.ParticleGroups.ParticleSelection Type

Abstract base for particle selection specifications.

Concrete subtypes include All, TypeIDs, Indices, and can be extended by users for custom selection logic.

ParticleDynamics.ParticleGroups.ParticleGroup Type
julia
ParticleGroup

Materialized particle selection containing both host and device indices. Reusable across multiple operations without recomputation.

Instances are created via materialize(selection, state).

ParticleDynamics.ParticleGroups.All Type

Select all particles.

ParticleDynamics.ParticleGroups.TypeIDs Type

Select particles by type ID. Accepts a single Int or a vector.

ParticleDynamics.ParticleGroups.Indices Type

Select particles by explicit list of indices.

ParticleDynamics.ParticleGroups.materialize Function
julia
materialize(sel::ParticleSelection, state) -> ParticleGroup

Create a reusable materialized group from a selection and state.

ParticleDynamics.ParticleGroups.apply_scalar! Function
julia
apply_scalar!(dest::CuArray, group::ParticleGroup, value)

Assign value to all elements of dest indexed by group.

ParticleDynamics.ParticleGroups.apply_values! Function
julia
apply_values!(dest::CuArray, group::ParticleGroup, values)

Assign distinct values per group member.

ParticleDynamics.ParticleGroups.gather Function
julia
gather(src::CuArray, group::ParticleGroup) -> Vector

Collect values from device array indexed by group onto the host.

ParticleDynamics.ParticleGroups.sum_values Function
julia
sum_values(src::CuArray, group::ParticleGroup) -> Scalar

Sum values from device array indexed by group.

ParticleDynamics.ParticleGroups.count Function
julia
count(group::ParticleGroup) -> Int

Number of particles in the group.

julia
count(sel::ParticleSelection, state) -> Int

Number of particles matched by a selection.

ParticleDynamics.ParticleGroups.resolve Function
julia
resolve(sel::ParticleSelection, state) -> Vector{Int}

Resolve a selection specification to host indices.

ParticleDynamics.ParticleGroups.resolve_gpu Function
julia
resolve_gpu(sel::ParticleSelection, state) -> CuArray{Int32}

Resolve a selection specification to device indices.

Filters module ​

ParticleDynamics.Filters Module

Particle-selection helpers used to assign per-group parameters (temperatures, frictions, correlation times).

ParticleDynamics.Filters.All Type

Select all particles.

ParticleDynamics.Filters.Filter Type

Base type for particle selections that operate on SimulationState.

ParticleDynamics.Filters.Indices Type

Explicit list of particle ids (build-time numbering, 1:N). With spatial sorting they are resolved to the particles' current storage slots through st.tag, so an index filter always selects the same particles. A resolved Selection holds slots: re-resolve it after the state has been sorted.

ParticleDynamics.Filters.Selection Type

GPU/host selection pair returned by selection. Access .host for CPU arrays and .device for CuArray{Int32} indexing.

ParticleDynamics.Filters.TypeIDs Type

Filter by type IDs (st.typeid). Accepts a single Int or a vector.

ParticleDynamics.Filters.assign_csvr_baths! Function
julia
assign_csvr_baths!(spec, st, filter=>bath_id, ...)

Assign per-particle CSVR bath ids from filter pairs. bath_id == 0 leaves selected (or uncovered) particles unthermostatted (NVE); later pairs overwrite earlier ones.

ParticleDynamics.Filters.assign_nhc_baths! Function
julia
assign_nhc_baths!(spec, st, filter=>bath_id, ...)

Assign per-particle NHC bath ids from filter pairs. bath_id == 0 leaves selected (or uncovered) particles unthermostatted (NVE), matching the device engine and Workflow; later pairs overwrite earlier ones. Recomputes automatic chain masses Q_1[b] = dof[b] * T[b] * tau[b]^2 from the actual per-bath DOF.

ParticleDynamics.Filters.assign_scalar! Function
julia
assign_scalar!(dest, st[, filter], value)

Fill elements of dest referenced by filter (or all particles) with value. This underpins set_friction! and set_temperature!.

ParticleDynamics.Filters.assign_values! Function
julia
assign_values!(dest, st[, filter], values)

Assign distinct values per particle according to values. Useful when setting custom noise scales per lattice site.

ParticleDynamics.Filters.count Function
julia
count(filter, st)

Number of particles matched by filter.

ParticleDynamics.Filters.freeze_particles! Function
julia
freeze_particles!(st; filter=All(), mode=:hold, steps=nothing, k=0, include_energy=true)

Freeze the selected particles for a fixed number of steps.

  • mode=:hold clamps positions to their anchors and zeroes velocities on held particles.

  • mode=:spring adds a harmonic tether with stiffness k to the current positions.

  • steps: number of steps to keep the freeze active; nothing keeps it on until unfreeze_particles! is called.

  • include_energy: add tether energy to Epot when mode=:spring.

ParticleDynamics.Filters.gather Function
julia
gather(src, st[, filter]) -> Vector

Collect the values referenced by filter onto the host. Used in the tests to verify that per-type energies match expectations.

ParticleDynamics.Filters.resolve Function
julia
resolve(filter, st) -> Vector{Int}

Return host indices matching filter. Used in the Filters unit tests to verify type-based selections.

ParticleDynamics.Filters.resolve_gpu Function
julia
resolve_gpu(filter, st) -> CuArray{Int32}

GPU version of resolve, used by assign_scalar! and friends when updating CuArray buffers directly.

ParticleDynamics.Filters.selection Function
julia
selection(st, filter) -> Selection

Allocate a Selection (host+device indices) for repeated use.

ParticleDynamics.Filters.set_corr_time! Function
julia
set_corr_time!(spec, τ)
set_corr_time!(spec, st, τ; filter=All())
set_corr_time!(st, spec, τ; filter=All())

Set per-particle correlation times for OU noise processes on the integrator spec.

ParticleDynamics.Filters.set_friction! Function
julia
set_friction!(spec, γ)
set_friction!(spec, st, γ; filter=All())
set_friction!(st, spec, γ; filter=All())

Integrator-parameter control for per-particle friction coefficients.

ParticleDynamics.Filters.set_friction_rate! Function
julia
set_friction_rate!(spec, st, rate; filter=All())
set_friction_rate!(st, spec, rate; filter=All())

Assign a uniform collision rate rate (  ) on the selected particles, writing per-particle friction   into the integrator's friction buffer. Using a uniform collision rate ensures identical damping factors   across atoms of different masses in holonomically constrained molecules.

ParticleDynamics.Filters.set_noise_scale! Function
julia
set_noise_scale!(spec, value)
set_noise_scale!(spec, st, value; filter=All())
set_noise_scale!(st, spec, value; filter=All())

Integrator-parameter control for the stochastic noise amplitude.

ParticleDynamics.Filters.set_ou_spectrum! Function
julia
set_ou_spectrum!(spec, st, taus, scales; filter=All(), dt=spec.params.dt)
set_ou_spectrum!(st, spec, taus, scales; filter=All(), dt=spec.params.dt)

Configure a generalized OU spectrum on the selected particles. This explicit OU path stores the active spectrum separately from the white-noise noise_scale buffer, so thermal Gaussian noise and active OU forcing can be combined on the same particles. Scalars are treated as one-mode spectra.

ParticleDynamics.Filters.set_temperature! Function
julia
set_temperature!(spec, dt, T)
set_temperature!(spec, st, dt, T; filter=All())
set_temperature!(st, spec, dt, T; filter=All())

Set the effective thermostat temperature through the integrator-owned noise_scale and gamma buffers. dt must match the spec's cached timestep.

ParticleDynamics.Filters.set_thermostat_temperature! Function
julia
set_thermostat_temperature!(spec::NHCSpec, T)

Set all NHC bath target temperatures to T.

ParticleDynamics.Filters.set_thermostat_timescale! Function
julia
set_thermostat_timescale!(spec::NHCSpec, tau; rescale_chain_masses=true)

Set all NHC bath response timescales. By default chain masses are rescaled by (tau_new / tau_old)^2 per updated bath.

ParticleDynamics.Filters.sum Function
julia
sum(src, st[, filter])

Sum the selected entries of src, returning a scalar on the host.

ParticleDynamics.Filters.unfreeze_particles! Function
julia
unfreeze_particles!(st)

Disable any active freeze/tethering.

Collision counting ​

ParticleDynamics.Collisions.enable_collision_counting! Function
julia
enable_collision_counting!(st; ntypes=nothing, bins=:all_pairs)

Attach GPU buffers that count contact-entry events (pairs whose separation crosses below the collision cutoff). With ntypes=2, a two-temperature run logs cold/cold, cold/hot, and hot/hot encounters.

Arguments

  • ntypes: Number of particle types; defaults to maximum(Array(st.typeid)).

  • bins: Currently only :all_pairs, which bins every unordered type pair.

Examples

julia
enable_collision_counting!(st; ntypes=2, bins=:all_pairs)
vv = velocityverlet(st; gamma=gamma, temperature=temperature, dt=dt)
for _ in 1:1_000_000
    step!(st, vv, dt; compute_energy=false)
end
counts = collisions_read_counts!(st) ./ (dt * 1_000_000)
ParticleDynamics.Collisions.disable_collision_counting! Function
julia
disable_collision_counting!(st)

Tear down all collision-counting buffers.

ParticleDynamics.Collisions.collisions_reset_counts! Function
julia
collisions_reset_counts!(st)

Clear the histogram without reinitializing the contact state. Handy after a warmup period.

ParticleDynamics.Collisions.collisions_read_counts! Function
julia
collisions_read_counts!(st) -> Vector{Int64}

Copy device counters to host. The vector ordering matches the bin assignment printed by enable_collision_counting! (unordered type pairs).

ParticleDynamics.Collisions.set_collision_pair_cutoffs! Function
julia
set_collision_pair_cutoffs!(st, rcut_pair)

Override the contact cutoff used for counting with an ntypes×ntypes matrix. Each entry stores the distance (not squared).

ParticleDynamics.Collisions._collisions_reinit_on_rebuild! Function

Called when the neighbor list is rebuilt. Resizes and reinitializes coll_prev to reflect current contacts by default. Internal force-time rebuilds use preserve_history=true to reconstruct rows from the last sampled physical coordinates, retaining entry events even when a previously absent pair enters.

ParticleDynamics.Collisions._collisions_snapshot! Function

Re-snapshot the contact reference positions (cell changes, restored trials, minimization).

ParticleDynamics.Collisions._collisions_update_after_positions! Function

Called after a physical position stage and any required neighbor rebuild. Split integrators can sample more than once per step; temporary midpoint force probes are not samples. Detects entry events and increments per-bin counters.

Core definitions and periodic wrapping ​

ParticleDynamics.Definitions Module

Domain and potential parameter definitions shared by ParticleDynamics modules.

Definitions exposes the light-weight structs that describe the simulation domain (periodic boxes), nonbonded parameters (Lennard-Jones, soft repulsive, per-type mixing), and bonded potentials (harmonic, FENE). The same types are used consistently across Simulation, NonBondedForces, and the examples.

ParticleDynamics.Definitions.OUSpectrum Type
julia
OUSpectrum{T}

Container for the correlated active-noise process used by the stochastic integrators.

Interpretation:

  • each column is one active particle

  • each row is one OU mode assigned to that particle

  • tau[k, j] is the correlation time of mode k on particle j

  • scale[k, j] is the stationary standard deviation of that OU mode

For one mode, the internal OU state η is updated exactly as

η_{n+1} = a η_n + c ξ_n

with

  • a = exp(-dt / τ)

  • c = scale * sqrt(1 - a^2)

  • ξ_n ~ Normal(0, 1)

This choice guarantees that, at stationarity,

  • mean(η) = 0

  • std(η) = scale

So scale is the long-time RMS size of the OU state itself.

The total active contribution for one particle coordinate is the sum of that particle's active modes. The stochastic integrator then converts that active signal into an actual displacement or velocity update. For example, on the Brownian Euler-Maruyama path the position update uses Δx_active = η_x / gamma, so the typical active step size is set by scale / gamma.

When an OUSpectrum is attached explicitly through ActiveOrnsteinUhlenbeck or Filters.set_ou_spectrum!, it is kept separate from the thermal white-noise noise_scale buffer. To model a thermal AOUP, combine the explicit OU spectrum with a separate Brownian or Langevin thermal term.

The τ <= 0 limit is treated as white noise by setting a = 0 and c = scale, so each step draws an independent η = scale * ξ.

ParticleDynamics.Definitions.wrap_pbc2! Function
julia
wrap_pbc2!(rx, ry, box)

Wrap 2D positions back into the periodic box [-L/2, L/2) along both axes. Called after integrator updates to prevent coordinates from drifting too far before the next neighbor rebuild.

ParticleDynamics.Definitions.wrap_pbc3! Function
julia
wrap_pbc3!(rx, ry, rz, box)

3D variant of wrap_pbc2!; keeps coordinates centered during long runs.

ParticleDynamics v1.2.0 · GPU-native molecular dynamics in pure Julia · MIT License