Constraints, Minimization & Barostats
API reference for holonomic constraints (rigid three-site water and general / X–Hₙ constraint clusters), particle-freeze restraints, energy minimization, constant-pressure barostats, and dynamic cell operations. See Bonds, minimization and pressure for usage examples and physical conventions.
Workflow constraints and freeze restraints
ParticleDynamics.Workflow.Constraint Type
ConstraintAbstract workflow constraint or restraint descriptor (holonomic constraints such as RigidWaterConstraint, ConstraintClusterSpec, HBondConstraints, or particle-freeze restraints via FreezeGroup), passed as Integrator(...; constraints=[...]).
ParticleDynamics.Workflow.RigidWaterConstraint Type
RigidWaterConstraint(triples; oh, hh, tolerance=nothing, maxiter=50, settle_mode=:df64)Workflow holonomic constraint descriptor attaching disjoint (O, H1, H2) rigid water molecules via attach_rigid_water!.
ParticleDynamics.Workflow.ConstraintClusterSpec Type
ConstraintClusterSpec(pairs; tolerance=nothing, maxiter=100, project_initial=false, constraint_f64=false)Workflow holonomic constraint descriptor attaching general distance constraints pairs (iterable of (i, j, d) tuples) via attach_constraint_clusters!.
ParticleDynamics.Workflow.HBondConstraints Type
HBondConstraints(; pairs=nothing, hydrogen_types=nothing, mass_cutoff=1.5,
bond_lengths=nothing, tolerance=nothing, maxiter=100,
project_initial=false, constraint_f64=false)
HBondConstraints(pairs; kwargs...)Workflow descriptor constraining hydrogen-involving bonds via attach_constraint_clusters!. Supply explicit (i, j, d) pairs, or omit pairs to automatically select non-water hydrogen bonds from system.topology.bonds using hydrogen_types or atomic mass <= mass_cutoff (resolving target lengths from bond_lengths, matching HarmonicBondForce.r0, or initial minimum-image distances).
ParticleDynamics.Workflow.FreezeGroup Type
FreezeGroup(group; mode=:hold, k=0.0, steps=nothing, include_energy=true)Workflow particle-freeze / position-restraint descriptor calling Filters.freeze_particles! during prepare!(sim).
mode = :hold: clamps positions to anchors and zeroes velocities on held particles.mode = :spring: adds a harmonic tether½ k |r - r₀|²(k > 0).steps: optional duration in steps (nothingkeeps active until removed).include_energy: include tether energy inEpotformode=:spring.
Low-level constraints
ParticleDynamics.ConstraintClusters Module
General-purpose holonomic bond-length ConstraintClusters (SHAKE / RATTLE).
Partitions an arbitrary set of distance constraints [(i, j, d_ij), ...] into vertex-disjoint connected components:
Star clusters (
X–H,X–H₂,X–H₃,X–H₄): 1 central atomc+k ∈ {1, 2, 3, 4}terminal atomsh_1..h_k. Stored in flat coalesced SoA arrays (sorted byk_bondsto eliminate warp divergence), 1 GPU thread per cluster, 100% register-resident inFloat64arithmetic:k = 1: exact analytical quadratic (1 sqrt, zero iterations).k = 2, 3, 4: exact coupledk×kNewton-SHAKE and 1-shot exactk×kRATTLE and instantaneous constraint virial.
General connected clusters (fallback for coupled heavy-atom chains, rings, or degree
≥ 5hubs): BFS spanning-tree periodic unwrapping + iterativeFloat64Gauss-Seidel SHAKE, RATTLE, and constraint virial.
All constraint algebra runs in Float64 even for Float32 simulations.
ParticleDynamics.RigidWaterConstraints Module
Low-level three-site rigid-water constraint primitives.
These kernels support the low-level fixed-cell constrained NVE path through SimulationCore.attach_rigid_water!. They are not an NPT integrator: thermostats, molecular volume moves and restart serialization remain pending. All distances and masses use the caller's consistent unit convention.
ParticleDynamics.SimulationCore.attach_rigid_water! Function
attach_rigid_water!(st, triples; oh, hh, tolerance, maxiter=50, settle_mode=:df64)Attach disjoint (O,H1,H2) triples to a 3D state before stepping. Coordinates must already satisfy the supplied lengths; velocities are projected once. Masses come from the state. Spatial reordering is disabled. This low-level API supports nve only; it does not install SPC/E parameters or nonbonded exclusions. The caller must configure those separately. No COM DOF are subtracted implicitly. Changing masses after attachment is unsupported. settle_mode selects :df64 (default), :f32, or :f64 for Float32 states.
ParticleDynamics.SimulationCore.attach_constraint_clusters! Function
attach_constraint_clusters!(st, constraints; tolerance, maxiter=100, project_initial=false, constraint_f64=false, constraint_mode=:auto)Attach general holonomic distance constraints constraints (iterable of (i, j, d) tuples) to a 3D SimulationState before stepping.
Constraints are partitioned into vertex-disjoint star clusters (X–H, X–H₂, X–H₃, X–H₄) and general connected clusters (chains/rings fallback). Must be vertex-disjoint from st.rigid_water. constraint_mode selects :df64 (default for Float32, Dekker–Knuth double-float warp kernels), :f64 (native Float64, default for Float64 or when constraint_f64=true), or :f32 (opt-in native Float32).
Any matching (i, j) pairs in typed HarmonicBondKind / FENEBondKind bonded families are automatically excluded so constrained bonds do not also receive harmonic bond forces. When project_initial=true, initial coordinates are projected onto the exact constraint manifold (preserving cluster COMs); otherwise initial coordinates must already satisfy constraints within tolerance. Velocities are projected once with RATTLE.
ParticleDynamics.SimulationCore.kinetic_dof Function
kinetic_dof(st; remove_com=false)Whole-system kinetic DOF, subtracting FREEZE_HOLD particles, three constraints per rigid water, and attached constraint-cluster constraints. FREEZE_SPRING particles remain mobile and keep their kinetic DOF. Set remove_com=true only when total COM momentum was actually removed.
ParticleDynamics.SimulationCore.constraint_virial_trace Function
constraint_virial_trace(st; accumulated=false) -> Float64Trace of the rigid-water constraint virial; 0.0 without rigid water. By default the constraint forces are recomputed from the current positions, velocities and forces. accumulated=true returns the sum collected by accumulate_virial! since the accumulators were last zeroed.
ParticleDynamics.SimulationCore.molecular_virial_trace Function
molecular_virial_trace(st) -> Float64Trace of the molecular virial Σ_M R_M·F_M at the current coordinates: the configurational (pair, mesh and bonded) virial without the constraint part, minus the intramolecular term Σ_i (r_i − R_M)·F_i of every rigid water. Particles outside waters count as their own molecules. Without rigid water it is the configurational virial.
Energy minimization
ParticleDynamics.SimulationCore.minimize! Function
minimize!(st; method, force_tolerance, max_displacement, max_iterations=10_000,
max_evaluations=20_000, mobile=nothing, velocities=:zero) -> MinimizationResultMinimize the potential energy of st at fixed box with SteepestDescent or FIRE. force_tolerance (E/L) applies to the largest mobile force; max_displacement (L) caps any coordinate's move per step. mobile is nothing (all particles), a Bool mask or a vector of indices; FREEZE_HOLD particles are always pinned. On return the forces and energies describe the final coordinates; with velocities=:zero (default) physical velocities are zeroed, with :preserve they are left untouched (not optimized).
minimize!(sim::Simulation; method, force_tolerance, max_displacement,
max_iterations=10_000, max_evaluations=20_000, mobile=nothing,
velocities=:zero) -> MinimizationResultMinimize the simulation's declared forces at fixed box. The integrator only supplies forces: methods may be empty and no thermostat runs. mobile is nothing (all particles), a Group, a Symbol group name, a selection or particle indices; other coordinates stay pinned but keep their interactions. MSD/VACF references are reset to the minimized configuration; thermalization is a separate step.
ParticleDynamics.SimulationCore.FIRE Type
FIRE(; dt_initial, dt_max, fictitious_mass=1.0, alpha0=0.1, f_inc=1.1,
f_dec=0.5, f_alpha=0.99, n_min=5, restore_best=true)Velocity-Verlet FIRE with one fictitious mass for all mobile coordinates. dt_initial, dt_max are pseudotimes in the caller's time unit (time = L·√(M/E)); the dimensionless defaults follow Bitzek et al.
ParticleDynamics.SimulationCore.SteepestDescent Type
SteepestDescent(; initial_step, armijo=1e-4, growth=1.2, shrink=0.5)Backtracking steepest descent. The trial step moves the particle with the largest force by h (length units, h ≤ max_displacement) along the force; a trial is accepted when U_trial ≤ U - armijo·h·Σ|F|²/Fmax, otherwise h is multiplied by shrink and retried from the same accepted coordinates.
ParticleDynamics.SimulationCore.MinimizationResult Type
MinimizationResultOutcome of minimize!. converged is true only when the maximum mobile force reached force_tolerance; reason is one of :force_tolerance, :max_iterations, :max_evaluations, :step_too_small, :line_search_failed, :invalid_initial_configuration, :nonfinite_evaluation or :no_mobile_coordinates. Energies are Float64 whole-system totals; forces refer to mobile coordinates of the final state.
Workflow barostats
ParticleDynamics.Workflow.Barostat Type
BarostatAbstract global pressure-control descriptor, passed as Integrator(...; barostat=...).
ParticleDynamics.Workflow.StochasticCellRescaling Type
StochasticCellRescaling(; pressure, kT, compressibility, tau, interval=10,
seed=0x50524553, mode=:isotropic, scale=:atoms)Isotropic stochastic cell rescaling (Bernetti & Bussi 2020) applied every interval steps over the elapsed MD time. Units: pressure E/L³, kT E, compressibility L³/E, tau time. Positions follow the cell (rigid waters and constraint clusters are translated rigidly by molecular COM); velocities are not scaled.
Runs GPU-resident via SimulationCore.attach_pressure_control! (DeviceCRescale) whenever interval >= 2 and the state/integrator is device-barostat eligible (supporting NVE, CSVR, NoseHooverChain, VelocityVerlet, BAOAB, BAOABFast, and GSM), with automatic host fallback otherwise (e.g., interval == 1).
ParticleDynamics.Workflow.MonteCarloBarostat Type
MonteCarloBarostat(; pressure, kT, interval=25, log_volume_step=0.01,
seed=0x4d434231, scale=:atoms, tune=false,
mode=:isotropic, max_dV_frac=nothing)Monte Carlo barostat attempted every interval steps. Runs GPU-resident via SimulationCore.attach_pressure_control! (MonteCarloBarostatSpec) with zero-sync step_many! super-batches whenever eligible, supporting:
mode = :isotropic(uniform scaling ofLx, Ly, Lz),:semiisotropic(alternatingxyandzmoves;pressuremay be a scalar or(P_xy, P_z)), or:z/:z_only(scalingLzat fixed cross-sectionLx * Ly),scale = :atomsor:molecules(rigid COM translation of rigid waters, constraint clusters, and bonded molecules),tune = true(adaptive volume step-size tuning),NVE,CSVR,NoseHooverChain,VelocityVerlet,BAOAB,BAOABFast, andGSM.
ParticleDynamics.Workflow.barostat_diagnostics Function
barostat_diagnostics(sim) -> NamedTupleCurrent volume and pressure-control counters (synchronizing any device-resident barostat state first). Monte Carlo: volume, attempts, acceptance, log_volume_step, rejected_invalid, volume_change, energy_change, pv_work (plus dV_max_xy, dV_max_z, mode, scale, and axis counters on GPU-resident MC). C-rescale: volume, events, volume_change, last_pressure.
ParticleDynamics.Workflow.barostat_state_record Function
barostat_state_record(sim) -> Vector{Float64}Restart record of the active barostat (written to GSD frames as log/barostat/state by GSDWriter): the pressure-control counters plus the time of the last event.
ParticleDynamics.Workflow.restore_barostat! Function
restore_barostat!(sim, record) -> simContinue a barostat stream from a barostat_state_record, e.g. read_gsd_log(path, "log/barostat/state") of the restart frame. Call after prepare! with the same barostat descriptor (the seed is checked).
Low-level pressure control and dynamic cell
ParticleDynamics.SimulationCore.attach_pressure_control! Function
attach_pressure_control!(st, control::StochasticCellRescalingState; interval) -> stDevice-resident pressure control: from the next step! on, the device engine applies the C-rescale event of control every interval steps inside its captured step graphs, with no host synchronization (the virial of the step before each event, the Gaussian draw, the scale, molecular scaling and the mesh refresh all run on the device). The host box (st.box3) and the counters of control are refreshed at host boundaries (observables, evaluations, writers, synchronize_state!). Supported on the cluster-pair backend (3D) with NVE, CSVR or Nosé–Hoover integration; interval ≥ 2. detach_pressure_control! removes it. The host event stochastic_cell_rescale! stays available for other states.
ParticleDynamics.SimulationCore.detach_pressure_control! Function
detach_pressure_control!(st) -> stRemove the device-resident pressure control (the host box is synchronized first).
ParticleDynamics.SimulationCore.MonteCarloBarostatSpec Type
MonteCarloBarostatSpec(; pressure, temperature=nothing, kT=nothing, frequency=25,
mode=:isotropic, scale=:molecules, seed=0x4d434231,
max_dV_frac=0.01, tune=true)Device-resident Monte Carlo barostat specification (OpenMM-style uniform ΔV moves with exact Float64 Metropolis criterion and counter-based Philox RNG). Supports:
mode = :isotropic(scalesLx, Ly, Lzisotropically),mode = :semiisotropic(scalesxyandzindependently, alternating per attempt;pressuremay be a scalar or(P_xy, P_z)),mode = :z/:z_only(scalesLzonly at fixed cross-sectionLx * Ly, for slabs/membranes).scale = :molecules(default: rigid center-of-mass translation of every rigid water, bonded connected component, and monatomic ion/atom) or:atoms.tune = true(default): OpenMM's adaptive step-size rule (every 10 attempts per axis:< 25%acceptance scalesdV_max /= 1.1,> 75%scalesdV_max *= 1.1).
Does not require virials and works with any potential (including non-neutral Ewald/PME/ESP with dynamic U_bg(V), dispersion mesh, rigid waters, bonded biomolecules, and external potentials). Attach with attach_pressure_control!.
ParticleDynamics.SimulationCore.StochasticCellRescalingState Type
StochasticCellRescaling(st; pressure, kT, compressibility, tau, seed)Isotropic stochastic cell rescaling (Bernetti & Bussi 2020), unscaled-momentum formulation in λ = √V:
Pbaro = N kT/V + tr(W)/(3V)
dλ = κλ/(2τ) [Pbaro - P + kT/(2V)] dt + √(kT κ/(2τ)) dWintegrated with one Euler–Maruyama step of the elapsed MD time per event. Coordinates follow the cell; velocities are not scaled. With rigid water, N counts molecules, W is the molecular virial (molecular_virial_trace) and each molecule is translated with its centre of mass (set_cell_and_molecules!).
ParticleDynamics.SimulationCore.stochastic_cell_rescale! Function
stochastic_cell_rescale!(st, cr, h; compute_energy=true)One C-rescale event over elapsed MD time h. Uses a fresh virial at the current coordinates, scales the cell and coordinates, and re-evaluates forces (and energies when requested) at the new cell. A nonpositive or unsupported trial cell is an integration failure: the state is left unchanged and a DomainError is thrown.
ParticleDynamics.SimulationCore.MonteCarloVolumeMove Type
MonteCarloVolumeMove(st; pressure, kT, log_volume_step=0.01, seed)Isotropic log-volume Monte Carlo move: η ~ U(-δ, δ), V' = V e^η, all coordinates scaled by e^(η/3), accepted with min(1, exp(-(U'-U + P(V'-V))/kT + (N+1)η)). Energies in Float64. With rigid water the move is molecular (set_cell_and_molecules!) and N counts each water once.
ParticleDynamics.SimulationCore.monte_carlo_volume_move! Function
monte_carlo_volume_move!(st, mc) -> BoolAttempt one volume move. On rejection the state (cell, coordinates, forces, energies, virials, validity) is restored exactly; the RNG and attempt count still advance. Invalid trial cells or geometries are rejections.
ParticleDynamics.SimulationCore.TrialWorkspace Type
TrialWorkspacePreallocated copy of the committed configuration (cell, coordinates, force slot, energy/virial buffers and their validity) used to restore the exact state after a rejected trial.
ParticleDynamics.SimulationCore.save_trial_state! Function
save_trial_state!(ws, st)Copy the committed configuration and its outputs into ws.
ParticleDynamics.SimulationCore.restore_trial_state! Function
restore_trial_state!(ws, st)Restore exactly the configuration saved by save_trial_state!: cell geometry, coordinates, force slot, energy/virial buffers and validity flags.
ParticleDynamics.SimulationCore.mechanical_pressure Function
mechanical_pressure(st) -> Float64Instantaneous (2K + tr W)/(D V) with the configurational virial W = Σ r⊗F (including global terms). Refreshes stale virials.
ParticleDynamics.SimulationCore.cell_supported Function
cell_supported(st, box) -> Union{Nothing,String}nothing when box is a valid periodic cell for the state's neighbor traversal and cutoffs, otherwise the reason it is not. Never mutates st.
ParticleDynamics.SimulationCore.cell_volume Function
cell_volume(st) -> Float64Box volume (area in 2D).
ParticleDynamics.SimulationCore.set_box! Function
set_box!(st, box) -> stReplace the periodic box lengths (same dimensionality). Coordinates are left unchanged; set_cell_and_positions! scales them with the box. A dense cell list keeps its storage, cutoff, skin and capacity: only its cell grid is recomputed (the small per-cell arrays are reallocated when the grid changes) and it is rebuilt at the next force evaluation (all-pairs traversal needs no change). An attached electrostatics solver keeps its mesh dimensions and FFT plans and recomputes the box-dependent influence function, virial coefficients and background term. Forces and energies are invalidated. Typed stencil lists must be rebuilt by the caller.
ParticleDynamics.SimulationCore.set_cell_and_positions! Function
set_cell_and_positions!(st, box) -> stChange the periodic box to box and scale every particle coordinate with it (fractional coordinates are preserved; velocities are unchanged). Wrapped, unwrapped and freeze-anchor coordinates are scaled consistently; neighbor geometry and an attached electrostatics solver are refreshed through set_box!; forces, energies and virials are invalidated. An unsupported cell throws before anything is modified.
ParticleDynamics.SimulationCore.set_cell_and_molecules! Function
set_cell_and_molecules!(st, box) -> stMolecular counterpart of set_cell_and_positions! for states with rigid water: each water's centre of mass is scaled with the cell and the molecule is translated rigidly (bond lengths, angles and velocities unchanged); every other particle is scaled atom-wise. Wrapped and unwrapped coordinates are scaled consistently, the constraint reference is re-saved, geometry is refreshed through set_box! and forces, energies and virials are invalidated. Without rigid water this is set_cell_and_positions!. An unsupported cell throws before anything is modified.