Skip to content

Where to Touch: Developer Modification Cookbook ​

Practical, file-by-file modification recipes and minimal code skeletons for extending ParticleDynamics. Items 1, 2, and 8 work purely through open multiple dispatch in user code without editing any file inside src/.


1. Custom Short-Range Pair Potential (AbstractPairPotential) ​

User-extensible (0 internal files to edit). Runs inside DeviceEngine's 2D and 3D cooperative warp traversal on the :ell backend with full energies, configurational virials, NPT barostats, bonds, exclusions, FIRE/SteepestDescent minimization, and spatial_reorder=true.

Relevant Internal Wiring (for reference) ​

  • Trait definitions & reference implementations (MorsePotential, YukawaPotential): src/simulation/ExternalPotential.jl

  • Device bridge (CustomPairModel): src/engine/PairModels.jl

  • Spatial-reorder array registration (_split_custom_sorted_arrays): src/engine/state/EngineBuild.jl

  • Fingerprint (_pair_potential_sig): src/engine/state/Fingerprint.jl

  • Model dispatch (_lj_pair_model): src/engine/state/EngineSupport.jl

Minimal Code Skeleton (with per-particle spatial-reorder-safe arrays) ​

julia
using CUDA, ParticleDynamics
using ParticleDynamics: SimulationCore

struct CustomBuckingham{T<:AbstractFloat,Q} <: AbstractPairPotential
    A::T
    rho::T
    C::T
    rcut::T
    rc2::T
    weights::Q   # optional per-particle CuVector{T} (or nothing)
end

# Strip CuArray fields when adapting the struct into kernel arguments:
# per-particle arrays travel via `pair_data` so CUDA.jl converts them cleanly.
CUDA.Adapt.adapt_structure(to, p::CustomBuckingham{T}) where {T} =
    CustomBuckingham{T,Nothing}(p.A, p.rho, p.C, p.rcut, p.rc2, nothing)

SimulationCore.pair_cutoff(p::CustomBuckingham) = p.rcut
SimulationCore.pair_data(p::CustomBuckingham, st) = p.weights === nothing ? () : (p.weights,)

# CRITICAL for spatial_reorder=true: register every per-particle CuArray (1D length N or 2D N x M)
# so OrderingWorkspace permutes it in lockstep with particle coordinates on every sort.
SimulationCore.sorted_particle_arrays(p::CustomBuckingham, st) =
    p.weights === nothing ? () : (p.weights,)

SimulationCore.pair_fingerprint(p::CustomBuckingham) =
    (CustomBuckingham, p.A, p.rho, p.C, p.rcut, p.weights === nothing ? nothing : pointer(p.weights))

# Hoisted once per atom i outside the neighbor loop:
@inline SimulationCore.pair_context(p::CustomBuckingham, data, i) =
    isempty(data) ? one(p.A) : (@inbounds data[1][i])

# Device-inlined pair evaluation: return (inside::Bool, (-dU/dr)/r, U(r))
@inline function SimulationCore.pair_eval(p::CustomBuckingham, data, wi, j, r2::T) where {T}
    inside = (r2 > zero(T)) & (r2 < T(p.rc2))
    inside || return false, zero(T), zero(T)
    wj = isempty(data) ? one(T) : T(@inbounds data[1][j])
    w = T(wi) * wj
    r = sqrt(r2)
    invr2 = one(T) / r2
    invr6 = invr2 * invr2 * invr2
    e = exp(-r / T(p.rho))
    u = w * (T(p.A) * e - T(p.C) * invr6)
    fr = w * (T(p.A) * e / (T(p.rho) * r) - T(6) * T(p.C) * invr6 * invr2)
    return true, fr, u
end

# Attach via build_simulation(...; pair_potential=pot) or attach_pair_potential!(st, pot)

Spatial-reorder rule: When sorted_particle_arrays(pot, st) is non-empty, call attach_pair_potential! before the first spatial reorder (or pass pair_potential=pot directly to build_simulation).


2. Native-Julia GPU MLIP (AbstractExternalPotential) ​

User-extensible (0 internal files to edit). AbstractExternalPotential supports both legacy host-synced providers (split CUDA graphs calling external_forces! on the host, as used by Python-bridged examples) and zero-sync GPU-capturable native-Julia MLIPs captured directly inside DeviceEngine's CUDA graphs.

Why this matters for MLIPs: Implementing is_device_capturable(pot) == true and enqueue_external_forces!(pot, run, energy, virial) replaces Python-bridged MLIPs (such as examples/mace/MACEPotential.jl and examples/orb/OrbPotential.jl) with zero host synchronizations, zero Python/GIL round-trips, full step_many! K-step CUDA-graph batching, and native DeviceCRescale / MonteCarloBarostatSpec NPT + FIRE minimization support.

Trait Matrix (src/simulation/ExternalPotential.jl & src/engine/ExternalPotential.jl) ​

Trait / HookDefaultNative-Julia GPU MLIP SettingEffect
external_force_mode(pot):replace:replace (full MLIP) or :additive (Delta-ML / external bias):replace disables internal pair/bonded kernels (NoPairs()); :additive accumulates onto all internal terms (including :cluster & electrostatics).
is_device_capturable(pot)falsetrueEliminates SplitStep host syncs; captures enqueue_external_forces! directly inside CUDA graphs and enables step_many!, RigidWater, and ConstraintClusters.
enqueue_external_forces!(pot, run, energy, virial)(throws)Launch pure-GPU kernels guarded by NL._device_if_valid!Reads run.r, run.neighbors.geom, run.neighbors.list; writes (:replace) or adds (:additive) run.f, run.energy (if energy), and run.virial / run.virial_global (if virial).
provides_virial(pot)falsetrueEnables DeviceCRescale NPT, mechanical_pressure, and virial_tensor. If no mesh solver owns run.virial_global, ExternalPotentialFeature automatically zeroes it before your hook and folds it into run.virial[1, :] afterward.
needs_neighbor_list(pot)falsetrue (if MLIP reads run.neighbors.list)Keeps DeviceEngine's ELL neighbor list updated across drifts, NPT box changes, and FIRE minimization.
external_energy(pot, st)delegates to forcesOptional fast energy-only GPU kernelAccelerates MonteCarloBarostatSpec / MonteCarloVolumeMove trial evaluations without computing forces on rejected volume moves.
external_fingerprint(pot)(typeof(pot), objectid(pot))Tuple of model parameter hashes / buffer pointersForces graph recapture whenever weights, cutoffs, or scratch buffers change.

Minimal Native-Julia GPU MLIP Skeleton ​

julia
using CUDA, ParticleDynamics
using ParticleDynamics: SimulationCore, NeighborLists, Workflow
const NL = NeighborLists

struct NativeJuliaMLIP{W} <: AbstractExternalPotential
    weights::W             # GPU-resident weights / feature tables
    cutoff::Float64
    version::UInt64
end

SimulationCore.external_force_mode(::NativeJuliaMLIP) = :replace
SimulationCore.is_device_capturable(::NativeJuliaMLIP) = true
SimulationCore.provides_virial(::NativeJuliaMLIP) = true
SimulationCore.needs_neighbor_list(::NativeJuliaMLIP) = true
SimulationCore.external_fingerprint(p::NativeJuliaMLIP) = (NativeJuliaMLIP, p.cutoff, p.version)

function SimulationCore.enqueue_external_forces!(p::NativeJuliaMLIP, run, energy::Bool, virial::Bool)
    ws = run.neighbors
    nb = ws.list
    N  = length(run.r[1])
    # Always guard capturable launches with NL._device_if_valid!(ws.state, ...)
    # so capacity-overflow or barostat-fallback latches cleanly skip force execution.
    @cuda threads=256 blocks=cld(N, 256) NL._device_if_valid!(
        ws.state, _my_mlip_kernel!,
        run.r, run.f, run.energy, run.virial, run.virial_global,
        nb.neighbors_index, nb.neighbors_flat, nb.counts, ws.geom,
        p.weights, Val(energy), Val(virial),
    )
    return nothing
end

# Optional fast energy-only path for MonteCarloBarostatSpec:
function SimulationCore.external_energy(p::NativeJuliaMLIP, st)
    # Run energy-only GPU kernel on st.rx/ry/rz & st.box3 and return Float64 total
    return total_potential_energy(st)
end

# Workflow wiring (works with FIRE, NVE/BAOAB/CSVR/NHC, StochasticCellRescaling, MonteCarloBarostat):
force = ExternalPotentialForce(potential=mlip)
# Or low-level: attach_external_potential!(st, mlip)

Compatibility notes:

  • FIRE / SteepestDescent: minimize!(st, FIRE(...)) uses an evaluation-only StateEngine (src/engine/state/BoundaryRecovery.jl), automatically calling enqueue_external_forces! and keeping run.neighbors updated when needs_neighbor_list(pot) == true.

  • NPT: DeviceCRescale requires is_device_capturable(pot) == true && provides_virial(pot) == true. MonteCarloBarostatSpec accepts any is_device_capturable(pot) == true provider or any host provider with a specialized external_energy(pot, st).

  • Constraints: :replace mode supports RigidWaterConstraint and ConstraintClusterSpec whenever is_device_capturable(pot) == true (in :additive mode both work unconditionally).


3. Adding a New Bonded Force Family ​

Typed bonded potentials (K = 2, 3, 4, extensible to K = 5 e.g. CMAP) run through BondedForces.BondedTerms (src/bonded/).

Files to Touch ​

  1. src/bonded/BondedGeometry.jl — Define struct MyTermKind <: BondedPotential end and @inline _local_forces(::MyTermKind, coeffs, p, pos) returning (F::NTuple{K,SVector{D,T}}, U::T, ok::Bool) (zero allocations, 0 B .local spill).

  2. src/bonded/BondedTermsCore.jl — Optionally specialize _build_fast_coeffs(::MyTermKind, coeffs, ::Type{T}) and _build_packed_topology for coalesced 16-byte/8-byte loads; export any new constructor in src/BondedForces.jl.

  3. src/bonded/BondedGroupedKernels.jl — Verify Val(K) arity support in _bonded_interaction_kernel!, _bonded_direct_chunk_kernel!, and _bonded_grouped_kernel!.

  4. src/workflow/Bonded.jl — Add the user-facing struct MyTermForce <: Force descriptor and wire it into _compile_bonded_forces (selecting the matching Topology section and validating parameters).

  5. src/workflow/Forces.jl — Add MyTermForce to the BondedSectionForce union so compile_forces routes it automatically.

  6. src/ParticleDynamics.jl — Re-export MyTermForce from .Workflow.

  7. test/test_bonded_families.jl & test/test_workflow_bonded.jl — Add finite-difference force/virial checks in Float32 & Float64, plus 2D/3D and spatial_reorder=true tests.


4. Adding a New Integrator or Thermostat ​

Every integrator is stepped exclusively by DeviceEngine inside captured CUDA graphs.

Files to Touch ​

  1. src/IntegratorInterfaces.jl — Reuse the AbstractIntegratorSpec{T} protocol (validate_integrator_inputs!, ensure_integrator_workspace!, integrator_id, integrator_name, collect_integrator_observables).

  2. src/simulation/IntegratorSpecs.jl & constructor file (src/simulation/*SpecConstructors.jl) — Define MyParams{T}, MySpec{T} <: AbstractIntegratorSpec{T}, INTEGRATOR_ID_*, _param_version, and convenience constructor.

  3. src/engine/MyIntegrator.jl (+ include in Layer 2 of src/DeviceEngine.jl) — Define the GPU-resident data struct (MyData), drift/kick kernels (using Definitions.box_lengths(box, Val(D)) and philox_normals if stochastic), and compile_integration! hooks.

  4. src/engine/state/Fingerprint.jl — Add _spec_signature(spec::SC.MySpec) and _thermostat(st, spec::SC.MySpec, dt).

  5. src/engine/state/EngineSupport.jl — Add my_supported(st, spec) and wire it into engine_supported, _integrator_reason, _pressure_control_reason, and _rigid_ok if applicable.

  6. src/engine/run/RunTypes.jl & src/engine/state/EngineBuild.jl — Dispatch enqueue_drift!, enqueue_kick!, compile_integration!, _dispose_thermostat!, and register any per-particle arrays in spec_real/spec_int for spatial_reorder.

  7. src/engine/state/BatchScheduler.jl — Add SC.MySpec{T} to the SC.step!, SC.step_graph!, and SC.step_many! union dispatches.

  8. src/filters/ — Wire parameter mutation helpers (set_temperature!, set_friction!, etc.) if group-modifiable.

  9. src/workflow/Integrator.jl / src/workflow/Thermostats.jl & src/ParticleDynamics.jl — Add declarative workflow descriptor and exports.


5. Adding a New Barostat Mode or Coupling ​

Files to Touch ​

  1. src/simulation/Barostats.jl — Extend MonteCarloBarostatSpec / StochasticCellRescalingState (or add a new PressureControl subtype) with host validation, restart state serialization, and diagnostic fields.

  2. src/engine/barostat/BarostatTypes.jl — Add mode constants, buf slot indices, or fields on DeviceCRescale / DeviceMonteCarloBarostat.

  3. src/engine/barostat/CRescale.jl (virial-based) or src/engine/barostat/MCKernels.jl + MCScaleKernels.jl + MCOutOfPlace.jl + MCFallback.jl (MC-based) — Implement axis-specific scale factors (sx, sy, sz) in ws.geom, 3-axis parallel Euler-tour molecular COM translation (<= 10,241 atoms in SMEM + global fallback), out-of-place energy-only trial graphs, and CP.GEOMETRY_SHRINK margin checks (_BARO_NEED_GRID / DN_CRESCALE_FALLBACK / DN_MC_FALLBACK).

  4. src/engine/barostat/BarostatGraphs.jl & src/engine/state/BatchScheduler.jl — Wire capture into _append_mc_fast_body! / capture_event_graph and _select_super_batch_plan (:npt_cr_cycle / :npt_mc_cycle).

  5. src/engine/state/EngineSupport.jl, EngineBuild.jl, BoundaryRecovery.jl — Update _pressure_control_reason, _capture_engine / _capture_cluster_engine, and _sync_pressure_control!.

  6. src/workflow/Barostats.jl — Update _normalize_barostat_mode, _validate_barostat_dynamics, barostat_diagnostics, barostat_state_record, and restore_barostat!.


6. Adding a New Constraint Type ​

Files to Touch ​

  1. src/constraints/ — Implement pure-GPU position (SHAKE/analytical) and velocity (RATTLE) projection kernels + instantaneous constraint virial accumulation in Float64 (or :df64). Avoid div.rn.f64 on inner loops and verify 0 B PTX .local spill (see src/constraints/clusters/GeneralKernels.jl for the SMEM fast-path pattern).

  2. src/SimulationState.jl & src/simulation/ — Add a workspace field on SimulationState, attachment/detachment API (attach_*!, detach_*!), and update kinetic_dof, scaled_units, constraint_virial_trace, and molecular_virial_trace.

  3. src/engine/MyConstraintFeature.jl (+ include & ENGINE_FEATURES entry in src/DeviceEngine.jl) — Implement EngineFeature hooks: make_feature, feature_signature, after_position!, after_kick!, constrained_dof, constrains_velocities, constrain_velocities!, and _dispose_feature!.

  4. src/engine/state/Fingerprint.jl & EngineSupport.jl — Account for constrained DOF per bath in _constraint_dof_per_bath (for CSVR and NHC) and update _rigid_ok.

  5. src/engine/barostat/BarostatTypes.jl & CRescale.jl / MCScaleKernels.jl — Ensure constrained units translate rigidly by molecular COM under NPT cell scaling.

  6. src/workflow/Integrator.jl & src/ParticleDynamics.jl — Subtype Workflow.Constraint, wire attachment in _compile_constraints, and export.


7. Adding a New k-Space Split or Mesh Method ​

Files to Touch ​

  1. src/electrostatics/Splits.jl (Coulomb 1/r) or src/electrostatics/DispersionSplits.jl (dispersion 1/r^6) — Subtype AbstractSplit / AbstractDispersionSplit and implement real-space pair factor, Fourier splitting factor ĥ(k), and self-energy constant Φ(0).

  2. src/electrostatics/windows/BSplineWindows.jl or KaiserESWindows.jl — If adding a new assignment window, subtype AbstractWindow, define its GPU isbits stencil struct, window_order, window_weights, and Fourier transform Ŵ(θ).

  3. src/electrostatics/Spec.jl & src/electrostatics/DispersionSolver.jl — Add the new influence symbol to INFLUENCE_KINDS / DISPERSION_INFLUENCE_KINDS and validate (split, window, influence) combinations.

  4. src/electrostatics/influence/SpectralTables.jl, Kernels.jl, Refresh.jl — Compute optimal AD/ik influence coefficients G(k) and dynamic-box virial coefficients Vc(k).

  5. src/electrostatics/RealSpace.jl & src/clusterpairs/PairFunctor.jl — Fit minimax/Chebyshev real-space correction polynomials in coulomb_polynomial / dispersion_polynomial so ClusterPairs and ChargedPairs (:ell) evaluate the split without per-pair erfc/exp calls.

  6. src/electrostatics/Solver.jl & src/electrostatics/dual/DualWorkspace.jl — Wire mesh transforms, dual_mesh_compatible, and gather_sets.

  7. src/workflow/electrostatics/ElectrostaticsSpecs.jl, ElectrostaticsTuning.jl, ElectrostaticsGSD.jl & src/io/gsd/GSDFrameWrite.jl — Expose workflow constructor, auto-tuning rules, and GSD restart serialization.


8. Adding an Open-Dispatch Workflow.Observable or Workflow.Writer ​

User-extensible (0 internal files to edit). Protocols live in src/workflow/observables/ObservableProtocol.jl and src/workflow/writers/WriterProtocol.jl.

Custom Workflow.Observable Skeleton ​

julia
using CUDA, ParticleDynamics
using ParticleDynamics.Workflow: Observable, Group, _group_filter, _observable_data,
    observable_default_fields, observable_name, _observable_needs_unwrapped,
    _observable_field_requires_energy, _prepare_observable!, _reset_observable!

struct GyrationRadiusObservable <: Observable
    group::Group
    name::Symbol
end
GyrationRadiusObservable(group::Group; name::Symbol=group.name) = GyrationRadiusObservable(group, name)

observable_default_fields(::GyrationRadiusObservable) = (:rg2,)
_observable_needs_unwrapped(::GyrationRadiusObservable) = true
_observable_field_requires_energy(::GyrationRadiusObservable, field) = false

function _observable_data(sim, obs::GyrationRadiusObservable, fields=observable_default_fields(obs); writer_ctx=nothing)
    st = sim.state
    flt = _group_filter(sim, obs.group)
    # Read unwrapped GPU coordinates without scalar indexing:
    rx = st.rx_unwrap; ry = st.ry_unwrap
    gx = ParticleDynamics.Filters.gather(st, flt, rx)
    gy = ParticleDynamics.Filters.gather(st, flt, ry)
    cx = CUDA.sum(gx) / length(gx); cy = CUDA.sum(gy) / length(gy)
    rg2 = Float64(CUDA.mapreduce((x, y) -> (x - cx)^2 + (y - cy)^2, +, gx, gy)) / length(gx)
    return (; rg2)
end

Custom Workflow.Writer Skeleton ​

julia
using ParticleDynamics
using ParticleDynamics.Workflow: Writer, WriterContext, Every, _write_writer_sample!,
    _writer_schedule, writer_needs_energy, sample_observable, observable_name,
    _commit_writer_interval_snapshots!

struct CallbackWriter{F} <: Writer
    callback::F
    observables::Vector{Any}
    every::Int
end
CallbackWriter(cb; observables=Any[], every::Int=100) = CallbackWriter(cb, Any[observables...], every)

_writer_schedule(w::CallbackWriter) = Every(w.every)
writer_needs_energy(::CallbackWriter) = false

function _write_writer_sample!(sim, ctx::WriterContext, writer::CallbackWriter, step::Int, time::Float64)
    empty!(ctx.pending_snapshots)
    samples = Dict{Symbol,NamedTuple}()
    for req in ctx.requests
        samples[observable_name(req.observable)] =
            sample_observable(sim, req.observable; fields=req.fields, writer_ctx=ctx)
    end
    _commit_writer_interval_snapshots!(sim, ctx)
    writer.callback(step, time, samples)
    return ctx
end

Pass instances directly into Simulation(system; ..., observables=[obs], writers=[CallbackWriter(...)]) — prepare! and run! automatically resolve unwrapped-coordinate requirements, energy-evaluation cadences, and step_many! batch intervals between writer stops.

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