Skip to content

I/O & Initial Configurations ​

API reference for workflow writers, standalone CSV/XYZ/GSD file helpers, restart frame containers, and host-side 2D/3D lattice configuration generators. See Trajectories and tables, Continue a simulation, and Initial configurations for usage guides.

Workflow writers ​

ParticleDynamics.Workflow.Writer Type
julia
Writer

Abstract workflow output writer.

Custom subtypes participate in the workflow run loop through open multiple dispatch by implementing:

  • _write_writer_sample!(sim, ctx, writer, step, time)

and optionally specializing:

  • writer_needs_unwrapped(writer)

  • writer_needs_energy(writer)

  • _validate_writer(writer)

  • _writer_schedule(writer)

  • _normalize_writer_requests(sim, writer)

  • _prepare_writer_context(sim, writer)

  • _open_writer!(ctx, writer)

  • _close_writer!(ctx, writer)

  • _start_frame(writer), _start_needs_forces(writer), _start_needs_virial(writer)

ParticleDynamics.Workflow.TableWriter Type
julia
TableWriter(filename; every=nothing, schedule=nothing, observables=[], mode=:replace, delimiter=",", format=:scientific, append=false, style=:auto)

Scheduled text-table writer for workflow observables.

ParticleDynamics.Workflow.GSDWriter Type
julia
GSDWriter(filename; every=nothing, schedule=nothing, group=Group(:all, AllSelection()), write_start=true, mode=:replace, append=false, types=:automatic, diameter=:automatic, write_unwrapped=false, sync_on_write=true, write_forces=false, write_virial=false, observables=[])

Scheduled GSD trajectory writer for workflow simulations.

ParticleDynamics.Workflow.InMemoryWriter Type
julia
InMemoryWriter(; every=nothing, schedule=nothing, fields=[:positions], observables=[], write_start=false)

Scheduled writer that keeps frames and/or sampled workflow observables in host memory instead of a file, for analysis and debugging inside the same Julia session. fields selects any of :positions, :unwrapped_positions, :velocities, :forces, :energy, :virial:

  • per-particle data (:positions, :unwrapped_positions, :velocities, :forces) is stored in particle-id order, i.e. the order of the ParticleSystem, independent of the engine's spatial sorting;

  • :energy stores the total kinetic and potential energy;

  • :virial stores the total virial tensor.

observables accepts the same obs or obs => [:field, ...] entries as TableWriter and GSDWriter. When observables is non-empty and fields is omitted, only the requested observables are recorded.

Velocities are not recorded for Brownian dynamics (overdamped motion has none). Frames accumulate across stages and run! calls until empty!(writer); read them with recorded_data.

ParticleDynamics.Workflow.recorded_data Function
julia
recorded_data(writer::InMemoryWriter) -> NamedTuple

Frames recorded so far. step holds the step of each frame. Per-particle fields are N × D × nframes arrays (data.positions[:, :, k] is frame k, rows in particle-id order), energy gives kinetic_energy and potential_energy vectors, and virial is a D × D × nframes array. Any recorded observables are exposed as per-observable NamedTuples keyed by observable_name(obs) (e.g. data.pressure.pressure, data.pressure.volume). The arrays are copies; the writer keeps recording.

Low-level file and GSD restart helpers ​

ParticleDynamics.Writers.write_observables_csv! Function
julia
write_observables_csv!(path, step; Epot, Ekin, dq)

Append a single line with step, Epot, Ekin, Qtot.

julia
write_observables_csv!(path, st, spec)

Write observables collected through SimulationCore.collect_step_observables, including a compatibility Qtot column.

ParticleDynamics.Writers.write_xyz! Function
julia
write_xyz!(path; rx, ry[, rz], atomsym="A")

Write a single XYZ frame from SoA coordinate arrays.

ParticleDynamics.Writers.gsd_open Function
julia
gsd_open(path; application="ParticleDynamics", schema="hoomd", append=false)

Open a GSD trajectory for appending frames. Used extensively in examples/. By default this starts a fresh file. Set append=true to continue writing frames into an existing file without truncating it. Call gsd_close when finished or use the do-block form.

julia
gsd_open(f::Function, path; kwargs...)

Convenience do-block form that guarantees the GSD handle is closed, even if an exception occurs during writing. Example:

julia
Writers.gsd_open("traj.gsd") do h
    for step in 1:ns
        Writers.write_gsd_frame!(h, st; step)
    end
end
ParticleDynamics.Writers.gsd_close Function

Close a previously opened GSD handle.

ParticleDynamics.Writers.write_gsd_frame! Function
julia
write_gsd_frame!(h, st; diameter=nothing, mass=nothing, charge=nothing,
                  types_names=["A"], step=0,
                  write_forces=false, write_unwrapped=false,
                  write_virial=false, sync_on_write=false, logs=())

Write one frame of st to the open GSD handle h (HOOMD schema) at step.

Positions, and (unless the last integrator step was position-only) velocities, are always written. diameter, mass, and charge accept nothing (use GSD or covalent-element defaults, copying masses and charges from st), a scalar, or a per-particle or per-type vector (expanded via types_names).

While a long-range electrostatics solver is attached, the frame also records its exact settings (log/electrostatics/settings) and exception lists (log/electrostatics/exceptions, log/electrostatics/lj_exceptions) for restarts; see electrostatics_from_gsd. Standalone LJ exceptions and attached lattice-dispersion solvers are recorded the same way (log/nonbonded/lj_exceptions, log/dispersion/settings, log/dispersion/exceptions).

Set write_forces, write_unwrapped, or write_virial to additionally store forces, unwrapped positions in particles/position_unwrapped (requires unwrapped_positions=true in build_simulation), or the current per-particle configurational virial tensor from st.virial_tensor in native component order ((xx, yy, xy) in 2D; (xx, yy, zz, xy, xz, yz) in 3D). Output is written in build-time particle order regardless of any internal spatial reordering.

ParticleDynamics.Writers.read_gsd_frame! Function
julia
read_gsd_frame!(file_path; frame=nothing, step=nothing) -> GSDFrameData

Read a valid frame from a GSD file and return a GSDFrameData.

The returned object can still be destructured into the legacy tuple step, rx, ry, rz, vx, vy, vz, typeid, types, box, force for backwards compatibility, while also exposing rich metadata (frame.topology, frame.particle_properties, frame.configuration, …) that can be fed directly into ParticleDynamics initialisation routines.

Arguments:

  • file_path: path to the GSD file.

  • frame: optional 1-based frame index (-1 selects the last frame). Mutually exclusive with step.

  • step: optional simulation timestep (configuration/step) to select. Mutually exclusive with frame.

  • When both frame and step are nothing, the most recent complete frame is returned.

Chunks omitted in frames after frame 1 inherit from the most recent earlier frame following the GSD specification.

Throws:

  • ArgumentError if mandatory chunks are missing, both frame and step are supplied, or the requested frame/step does not exist.
ParticleDynamics.Writers.read_gsd_log Function
julia
read_gsd_log(path, name; frame=nothing, step=nothing) -> Vector{Float64} or nothing

Read the Float64 log chunk name (e.g. "log/electrostatics/settings") of the given 1-based frame (-1 or nothing = last) or matching simulation step (configuration/step). Frames that do not repeat the chunk inherit it from the closest earlier frame, following the GSD convention.

ParticleDynamics.Writers.GSDFrameData Type

Container returned by read_gsd_frame!.

Behaves like the legacy tuple (step, rx, ry, rz, vx, vy, vz, typeid, types, box, force) when destructured/iterated, while exposing richer metadata via fields:

  • step, N, D, box: configuration metadata.

  • rx, ry, rz, vx, vy, vz: particle state vectors (host arrays).

  • typeid, types: 1-based ids and type names.

  • forceM: optional force matrix (N×3, same precision as positions).

  • particle_properties: dictionary with optional particle properties (mass, charge, diameter, body, orientation, etc) converted to sensible Julia arrays. When present, custom force/virial chunks are also exposed as :force and :virial; other particles/property/* chunks appear under the :property key.

  • per_type_properties: dictionary for particles/type_* chunks (e.g. :shapes for per-type shape JSON blobs).

  • topology: a GSDTopology with bonds/angles/… converted to 1-based indices.

  • configuration: hierarchical NamedTuple combining metadata, particle data, topology and any extra configuration chunks for convenience.

ParticleDynamics.Writers.GSDTopology Type

Structured topological information decoded from a GSD frame.

Each field is a NamedTuple describing the corresponding collection and contains both the original 0-based data (group0, typeid0) and the converted 1-based indices (group, typeid) that can be passed directly to ParticleDynamics utilities such as BondedForces.build_bondlist.

Initial configuration generators ​

ParticleDynamics.InitGenerators Module

High-level initial configuration generators for 2D/3D simulations.

The helper functions in this module reproduce the hexagonal arrangements used throughout examples/ (random hex placements, concentric circles, etc.) and provide 3D close-packed counterparts so scripts can lift proven particle packings without rewriting geometry code.

ParticleDynamics.InitGenerators.box_from_phi_2d Function
julia
box_from_phi_2d(N, ϕ, σ; T=Float32, aspect=1)

Compute a rectangular 2D box (Lx, Ly) whose area fraction matches the target ϕ when populated with N disks of diameter σ. aspect = Lx/Ly and defaults to 1 (square). For example, (N=2000, ϕ=0.5, σ=1.0) fixes the box before a random hex-based placement.

ParticleDynamics.InitGenerators.box_from_phi_3d Function
julia
box_from_phi_3d(N, ϕ, σ; T=Float32, aspect=1)

Compute a 3D box (Lx, Ly, Lz) whose volume fraction matches the target ϕ when populated with N spheres of diameter σ. aspect = Lx/Ly, while Ly = Lz to keep the transverse directions equal.

ParticleDynamics.InitGenerators.hex_sites_in_box_2d Function
julia
hex_sites_in_box_2d(box, σ)

Enumerate hexagonal lattice sites inside a periodic rectangular box of side lengths box. a = σ fixes the nearest-neighbor spacing. Rows are centered in the box, and if an odd row count would place periodic images closer than a, the last row is dropped to avoid overlaps while minimizing empty space.

ParticleDynamics.InitGenerators.hex_random_2d Function
julia
hex_random_2d(N, σ, ϕ; T=Float32, rng=Random.default_rng(), fit_box=true, aspect=1)

Sample N distinct hexagonal lattice sites at random inside the box computed by box_from_phi_2d, e.g. with σ = 1.0, ϕ = 0.5, before assigning type IDs. When fit_box=true, the lattice spacing is adjusted so an even row count fits exactly in Ly, avoiding overlaps across the periodic y-wrap without leaving an empty strip. The spacing is only increased (never reduced below σ); an error is raised if there is insufficient room. Use aspect to set Lx/Ly (defaults to 1).

Returns

  • box: rectangular box tuple (Lx, Ly) in the requested precision.

  • positions: vector of SVector{2,T} coordinates centered in [-Lx/2, Lx/2) and [-Ly/2, Ly/2).

  • indices: indices into the full lattice site list (handy for re-sampling).

ParticleDynamics.InitGenerators.hex_circle_2d Function
julia
hex_circle_2d(N, σ, ϕ; T=Float32, aspect=1)

Return the innermost N hex-lattice sites (ordered by radius) so that the configuration forms a densely packed circular cluster. Use aspect to set Lx/Ly (defaults to 1).

ParticleDynamics.InitGenerators.hex_circle_in_box_2d Function
julia
hex_circle_in_box_2d(N, box; margin=0)

Variant used when the box is fixed a priori (e.g. restart from a recorded GSD). The helper shrinks the lattice spacing until at least N sites fall inside the target circle of radius min(box)/2 - margin.

ParticleDynamics.InitGenerators.hex_circle_plus_random_2d Function
julia
hex_circle_plus_random_2d(N, σ, ϕ, frac_circle; T=Float32, rng=Random.default_rng(), aspect=1)

Hybrid generator: frac_circle of the particles occupy the innermost circle while the rest are randomly drawn from sites outside that radius. The return value bundles the circle and random indices so scripts can assign different types or temperatures to each set. Use aspect to set Lx/Ly (defaults to 1).

ParticleDynamics.InitGenerators.hex_slab_coexistence_2d Function
julia
hex_slab_coexistence_2d(N, σ, ϕ, slab_height; frac_cold=0.5, T=Float32, rng=Random.default_rng(), fit_box=true)

Build a 2D direct-coexistence layout: the left half of the box is a homogeneous mixture (cold/hot split by frac_cold), while the right half is split into a cold slab (touching the midplane x=0) and a hot bath to its right. The slab spans the full y direction (slab_height). The box width Lx is computed from ϕ and slab_height. The slab width is set by taking the leftmost N_cold/2 lattice sites in x >= 0, so the slab is fully packed.

ParticleDynamics.InitGenerators.fcc_sites_in_box_3d Function
julia
fcc_sites_in_box_3d(box, σ)

Enumerate FCC lattice sites inside a periodic box of side lengths box. The nearest-neighbor spacing is σ (lattice constant a = σ√2).

ParticleDynamics.InitGenerators.fcc_random_3d Function
julia
fcc_random_3d(N, σ, ϕ; T=Float32, rng=Random.default_rng(), aspect=1)

Sample N distinct FCC lattice sites at random inside the box computed by box_from_phi_3d. The nearest-neighbor spacing is σ. Use aspect to set Lx/Ly while keeping Ly = Lz (defaults to 1).

ParticleDynamics.InitGenerators.fcc_slab_coexistence_3d Function
julia
fcc_slab_coexistence_3d(N, σ, ϕ, slab_height; frac_cold=0.5, T=Float32, rng=Random.default_rng())

3D counterpart of hex_slab_coexistence_2d using an FCC lattice. The cold slab spans the full y,z extents, with slab_height setting both Ly and Lz. The slab width is set by taking the leftmost N_cold/2 lattice sites in x >= 0, so the slab is fully packed.

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