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.jlDevice bridge (
CustomPairModel):src/engine/PairModels.jlSpatial-reorder array registration (
_split_custom_sorted_arrays):src/engine/state/EngineBuild.jlFingerprint (
_pair_potential_sig):src/engine/state/Fingerprint.jlModel dispatch (
_lj_pair_model):src/engine/state/EngineSupport.jl
Minimal Code Skeleton (with per-particle spatial-reorder-safe arrays)
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, callattach_pair_potential!before the first spatial reorder (or passpair_potential=potdirectly tobuild_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) == trueandenqueue_external_forces!(pot, run, energy, virial)replaces Python-bridged MLIPs (such asexamples/mace/MACEPotential.jlandexamples/orb/OrbPotential.jl) with zero host synchronizations, zero Python/GIL round-trips, fullstep_many!K-step CUDA-graph batching, and nativeDeviceCRescale/MonteCarloBarostatSpecNPT +FIREminimization support.
Trait Matrix (src/simulation/ExternalPotential.jl & src/engine/ExternalPotential.jl)
| Trait / Hook | Default | Native-Julia GPU MLIP Setting | Effect |
|---|---|---|---|
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) | false | true | Eliminates 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) | false | true | Enables 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) | false | true (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 forces | Optional fast energy-only GPU kernel | Accelerates MonteCarloBarostatSpec / MonteCarloVolumeMove trial evaluations without computing forces on rejected volume moves. |
external_fingerprint(pot) | (typeof(pot), objectid(pot)) | Tuple of model parameter hashes / buffer pointers | Forces graph recapture whenever weights, cutoffs, or scratch buffers change. |
Minimal Native-Julia GPU MLIP Skeleton
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-onlyStateEngine(src/engine/state/BoundaryRecovery.jl), automatically callingenqueue_external_forces!and keepingrun.neighborsupdated whenneeds_neighbor_list(pot) == true.NPT:
DeviceCRescalerequiresis_device_capturable(pot) == true && provides_virial(pot) == true.MonteCarloBarostatSpecaccepts anyis_device_capturable(pot) == trueprovider or any host provider with a specializedexternal_energy(pot, st).Constraints:
:replacemode supportsRigidWaterConstraintandConstraintClusterSpecwheneveris_device_capturable(pot) == true(in:additivemode 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
src/bonded/BondedGeometry.jl— Definestruct MyTermKind <: BondedPotential endand@inline _local_forces(::MyTermKind, coeffs, p, pos)returning(F::NTuple{K,SVector{D,T}}, U::T, ok::Bool)(zero allocations,0 B.localspill).src/bonded/BondedTermsCore.jl— Optionally specialize_build_fast_coeffs(::MyTermKind, coeffs, ::Type{T})and_build_packed_topologyfor coalesced 16-byte/8-byte loads; export any new constructor insrc/BondedForces.jl.src/bonded/BondedGroupedKernels.jl— VerifyVal(K)arity support in_bonded_interaction_kernel!,_bonded_direct_chunk_kernel!, and_bonded_grouped_kernel!.src/workflow/Bonded.jl— Add the user-facingstruct MyTermForce <: Forcedescriptor and wire it into_compile_bonded_forces(selecting the matchingTopologysection and validating parameters).src/workflow/Forces.jl— AddMyTermForceto theBondedSectionForceunion socompile_forcesroutes it automatically.src/ParticleDynamics.jl— Re-exportMyTermForcefrom.Workflow.test/test_bonded_families.jl&test/test_workflow_bonded.jl— Add finite-difference force/virial checks in Float32 & Float64, plus 2D/3D andspatial_reorder=truetests.
4. Adding a New Integrator or Thermostat
Every integrator is stepped exclusively by DeviceEngine inside captured CUDA graphs.
Files to Touch
src/IntegratorInterfaces.jl— Reuse theAbstractIntegratorSpec{T}protocol (validate_integrator_inputs!,ensure_integrator_workspace!,integrator_id,integrator_name,collect_integrator_observables).src/simulation/IntegratorSpecs.jl& constructor file (src/simulation/*SpecConstructors.jl) — DefineMyParams{T},MySpec{T} <: AbstractIntegratorSpec{T},INTEGRATOR_ID_*,_param_version, and convenience constructor.src/engine/MyIntegrator.jl(+includein Layer 2 ofsrc/DeviceEngine.jl) — Define the GPU-resident data struct (MyData), drift/kick kernels (usingDefinitions.box_lengths(box, Val(D))andphilox_normalsif stochastic), andcompile_integration!hooks.src/engine/state/Fingerprint.jl— Add_spec_signature(spec::SC.MySpec)and_thermostat(st, spec::SC.MySpec, dt).src/engine/state/EngineSupport.jl— Addmy_supported(st, spec)and wire it intoengine_supported,_integrator_reason,_pressure_control_reason, and_rigid_okif applicable.src/engine/run/RunTypes.jl&src/engine/state/EngineBuild.jl— Dispatchenqueue_drift!,enqueue_kick!,compile_integration!,_dispose_thermostat!, and register any per-particle arrays inspec_real/spec_intforspatial_reorder.src/engine/state/BatchScheduler.jl— AddSC.MySpec{T}to theSC.step!,SC.step_graph!, andSC.step_many!union dispatches.src/filters/— Wire parameter mutation helpers (set_temperature!,set_friction!, etc.) if group-modifiable.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
src/simulation/Barostats.jl— ExtendMonteCarloBarostatSpec/StochasticCellRescalingState(or add a newPressureControlsubtype) with host validation, restart state serialization, and diagnostic fields.src/engine/barostat/BarostatTypes.jl— Add mode constants,bufslot indices, or fields onDeviceCRescale/DeviceMonteCarloBarostat.src/engine/barostat/CRescale.jl(virial-based) orsrc/engine/barostat/MCKernels.jl+MCScaleKernels.jl+MCOutOfPlace.jl+MCFallback.jl(MC-based) — Implement axis-specific scale factors(sx, sy, sz)inws.geom, 3-axis parallel Euler-tour molecular COM translation (<= 10,241atoms in SMEM + global fallback), out-of-place energy-only trial graphs, andCP.GEOMETRY_SHRINKmargin checks (_BARO_NEED_GRID/DN_CRESCALE_FALLBACK/DN_MC_FALLBACK).src/engine/barostat/BarostatGraphs.jl&src/engine/state/BatchScheduler.jl— Wire capture into_append_mc_fast_body!/capture_event_graphand_select_super_batch_plan(:npt_cr_cycle/:npt_mc_cycle).src/engine/state/EngineSupport.jl,EngineBuild.jl,BoundaryRecovery.jl— Update_pressure_control_reason,_capture_engine/_capture_cluster_engine, and_sync_pressure_control!.src/workflow/Barostats.jl— Update_normalize_barostat_mode,_validate_barostat_dynamics,barostat_diagnostics,barostat_state_record, andrestore_barostat!.
6. Adding a New Constraint Type
Files to Touch
src/constraints/— Implement pure-GPU position (SHAKE/analytical) and velocity (RATTLE) projection kernels + instantaneous constraint virial accumulation inFloat64(or:df64). Avoiddiv.rn.f64on inner loops and verify0 BPTX.localspill (seesrc/constraints/clusters/GeneralKernels.jlfor the SMEM fast-path pattern).src/SimulationState.jl&src/simulation/— Add a workspace field onSimulationState, attachment/detachment API (attach_*!,detach_*!), and updatekinetic_dof,scaled_units,constraint_virial_trace, andmolecular_virial_trace.src/engine/MyConstraintFeature.jl(+include&ENGINE_FEATURESentry insrc/DeviceEngine.jl) — ImplementEngineFeaturehooks:make_feature,feature_signature,after_position!,after_kick!,constrained_dof,constrains_velocities,constrain_velocities!, and_dispose_feature!.src/engine/state/Fingerprint.jl&EngineSupport.jl— Account for constrained DOF per bath in_constraint_dof_per_bath(forCSVRandNHC) and update_rigid_ok.src/engine/barostat/BarostatTypes.jl&CRescale.jl/MCScaleKernels.jl— Ensure constrained units translate rigidly by molecular COM under NPT cell scaling.src/workflow/Integrator.jl&src/ParticleDynamics.jl— SubtypeWorkflow.Constraint, wire attachment in_compile_constraints, and export.
7. Adding a New k-Space Split or Mesh Method
Files to Touch
src/electrostatics/Splits.jl(Coulomb1/r) orsrc/electrostatics/DispersionSplits.jl(dispersion1/r^6) — SubtypeAbstractSplit/AbstractDispersionSplitand implement real-space pair factor, Fourier splitting factorĥ(k), and self-energy constantΦ(0).src/electrostatics/windows/BSplineWindows.jlorKaiserESWindows.jl— If adding a new assignment window, subtypeAbstractWindow, define its GPUisbitsstencil struct,window_order,window_weights, and Fourier transformŴ(θ).src/electrostatics/Spec.jl&src/electrostatics/DispersionSolver.jl— Add the newinfluencesymbol toINFLUENCE_KINDS/DISPERSION_INFLUENCE_KINDSand validate(split, window, influence)combinations.src/electrostatics/influence/SpectralTables.jl,Kernels.jl,Refresh.jl— Compute optimal AD/ikinfluence coefficientsG(k)and dynamic-box virial coefficientsVc(k).src/electrostatics/RealSpace.jl&src/clusterpairs/PairFunctor.jl— Fit minimax/Chebyshev real-space correction polynomials incoulomb_polynomial/dispersion_polynomialsoClusterPairsandChargedPairs(:ell) evaluate the split without per-pairerfc/expcalls.src/electrostatics/Solver.jl&src/electrostatics/dual/DualWorkspace.jl— Wire mesh transforms,dual_mesh_compatible, andgather_sets.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
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)
endCustom Workflow.Writer Skeleton
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
endPass 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.