hoomd
Overview
Define box dimensions. 

A mutable collection of operations which act on a 

Define a simulation. 

Selfcontained copy of the simulation 

The state of a 
Details
HOOMDblue python API.
hoomd
provides a high level user interface for defining and executing
simulations using HOOMD.
 class hoomd.Box(Lx, Ly, Lz=0, xy=0, xz=0, yz=0)
Define box dimensions.
 Parameters
Lx (float) – box extent in the x direction \([\mathrm{length}]\).
Ly (float) – box extent in the y direction \([\mathrm{length}]\).
Lz (float) – box extent in the z direction \([\mathrm{length}]\).
xy (float) – tilt factor xy \([\mathrm{dimensionless}]\).
xz (float) – tilt factor xz \([\mathrm{dimensionless}]\).
yz (float) – tilt factor yz \([\mathrm{dimensionless}]\).
Simulation boxes in hoomd are specified by six parameters,
Lx
,Ly
,Lz
,xy
,xz
, andyz
.Box
provides a way to specify all six parameters for a given box and perform some common operations with them. ABox
can be passed to an initialization method or to assigned to a savedState
variable (state.box = new_box
) to set the simulation box.Access attributes directly:
box = hoomd.Box.cube(L=20) box.xy = 1.0 box.yz = 0.5 box.Lz = 40
Two dimensional systems
2D simulations in HOOMD use boxes with
Lz == 0
. 2D boxes ignorexz
andyz
. If a newBox
is assigned to a system with different dimensionality, a warning will be shown.In 2D boxes, volume is in units of area.
Factory Methods
Box
has factory methods to enable easier creation of boxes:cube
,square
,from_matrix
, andfrom_box
. See the method documentation for usage.Examples: * Cubic box with given length:
hoomd.Box.cube(L=1)
* Square box with given length:hoomd.Box.square(L=1)
* From an upper triangular matrix:hoomd.Box.from_matrix(matrix)
* Specify values:hoomd.Box(Lx=1., Ly=2., Lz=3., xy=1., xz=2., yz=3.)
 property L
The box lengths,
[Lx, Ly, Lz]
\([\mathrm{length}]\).Can be set with a float which sets all lengths, or a length 3 vector.
 Type
(3, )
numpy.ndarray
offloat
 __eq__(other)
Test if boxes are equal.
 __neq__(other)
Test if boxes are not equal.
 __reduce__()
Reduce values to picklable format.
 __repr__()
Executable representation of the object.
 classmethod cube(L)
Create a cube with side lengths
L
.
 property dimensions
The dimensionality of the box.
If
Lz == 0
, the box is treated as 2D, otherwise it is 3D. This property is not settable. Type
 classmethod from_box(box)
Initialize a Box instance from a boxlike object.
 Parameters
box – A boxlike object
Note
Objects that can be converted to HOOMDblue boxes include lists like
[Lx, Ly, Lz, xy, xz, yz]
, dictionaries with keys'Lx', 'Ly', 'Lz', 'xy', 'xz', 'yz'
, objects with attributesLx, Ly, Lz, xy, xz, yz
, 3x3 matrices (seefrom_matrix
), or existinghoomd.Box
objects.If any of
Lz, xy, xz, yz
are not provided, they will be set to 0.If all values are provided, a triclinic box will be constructed. If only
Lx, Ly, Lz
are provided, an orthorhombic box will be constructed. If onlyLx, Ly
are provided, a rectangular (2D) box will be constructed. Returns
The resulting box object.
 Return type
 classmethod from_matrix(box_matrix)
Create a box from an upper triangular matrix.
 Parameters
box_matrix ((3, 3)
numpy.ndarray
offloat
) –An upper triangular matrix representing a box. The values for
Lx
,Ly
,Lz
,xy
,xz
, andyz
are related to the matrix by the following expressions.[[Lx, Ly * xy, Lz * xz], [0, Ly, Lz * yz], [0, 0, Lz]]
 Returns
The created box.
 Return type
 property is2D
Flag whether the box is 2D.
If
Lz == 0
, the box is treated as 2D, otherwise it is 3D. This property is not settable. Type
 property lattice_vectors
Box lattice vectors.
The lattice vectors are readonly.
 Type
(3, 3)
numpy.ndarray
offloat
 property matrix
The upper triangular matrix that defines the box.
Can be used to set the box to one defined by an upper triangular matrix.
[[Lx, Ly * xy, Lz * xz], [0, Ly, Lz * yz], [0, 0, Lz]]
 Type
(3, 3)
numpy.ndarray
float
 property periodic
The periodicity of each dimension.
 Type
(3, )
numpy.ndarray
ofbool
 scale(s)
Scale box dimensions.
Scales the box in place by the given scale factors. Tilt factors are not modified.
 classmethod square(L)
Create a square with side lengths
L
.
 property tilts
The box tilts,
[xy, xz, yz]
.Can be set using one tilt for all axes or three tilts. If the box is 2D
xz
andyz
will automatically be set to zero. Type
(3, )
numpy.ndarray
offloat
 property volume
Volume of the box.
\([\mathrm{length}^{2}]\) in 2D and \([\mathrm{length}^{3}]\) in 3D.
When setting volume the aspect ratio of the box is maintained while the lengths are changed.
 Type
 class hoomd.Operations
A mutable collection of operations which act on a
hoomd.Simulation
.The
Operations
class contains all the operations acting on a simulation. These operations are classes that perform various actions on ahoomd.Simulation
. Operations can be added and removed at any point from ahoomd.Operations
instance. The class provides the interface defined bycollections.abc.Collection
. Other methods for manipulating instances attempt to mimic Python objects where possible, but the class is not simply a mutable list or set. Since there are multiple types of operations in HOOMDblue,Operations
objects manage multiple independent sequences described below.The types of operations which can be added to an
Operations
object are tuners, updaters, integrators, writers, and computes. AnOperations
can only ever hold one integrator at a time. On the other hand, anOperations
object can hold any number of tuners, updaters, writers, or computes. To see examples of these types of operations seehoomd.tune
(tuners),hoomd.update
(updaters),hoomd.hpmc.integrate
orhoomd.md.Integrator
(integrators),hoomd.write
(writers), andhoomd.md.thermo
(computes).A given instance of an operation class can only be added to a single
Operations
container. Likewise, a single instance cannot be added to the sameOperations
container more than once.All
Operations
instances start with ahoomd.tune.ParticleSorter
instance in theirtuners
attribute. This increases simulation performance. However, users can choose to modify or remove this tuner if desired.Note
An
Operations
object is created by default when a new simulation is created. __contains__(operation)
Whether an operation is contained in this container.
 Parameters
operation – Returns whether this exact operation is contained in the collection.
 __getstate__()
Get the current state of the operations container for pickling.
 __iadd__(operation)
Works the same as
Operations.add
. Parameters
operation (
hoomd.operation.Operation
) – A HOOMDblue tuner, updater, integrator, writer, or compute to add to the object.
 __isub__(operation)
Works the same as
Operations.remove
. Parameters
operation (
hoomd.operation.Operation
) – A HOOMDblue integrator, tuner, updater, integrator, analzyer, or compute to remove from the collection.
 __iter__()
Iterates through all contained operations.
 __len__()
Return the number of operations contained in this collection.
 add(operation)
Add an operation to this container.
Adds the provided operation to the appropriate attribute of the
Operations
instance. Parameters
operation (
hoomd.operation.Operation
) – A HOOMDblue tuner, updater, integrator, writer, or compute, to add to the collection. Raises
ValueError – If
operation
already belongs to this or anotherOperations
instance.TypeError – If
operation
is not of a valid type.
Note
Since only one integrator can be associated with an
Operations
object at a time, this removes the current integrator when called with an integrator operation. Also, theintegrator
property cannot be set toNone
using this function. Useoperations.integrator = None
explicitly for this.
 property computes
A list of tuner operations.
Holds the list of tuners associated with this collection. The list can be modified as a standard Python list.
 Type
list[
hoomd.operation.Compute
]
 property integrator
An MD or HPMC integrator object.
Operations
objects have an initialintegrator
property ofNone
. Can be set to MD or HPMC integrators. The property can also be set toNone
.
 remove(operation)
Remove an operation from the
Operations
object.Remove the item from the collection whose id is the same as
operation
. See https://docs.python.org/3/library/functions.html#id for the concept of a Python object id. Parameters
operation (
hoomd.operation.Operation
) – A HOOMDblue integrator, tuner, updater, integrator, or compute to remove from the container. Raises
ValueError – If
operation
is not found in this container.TypeError – If
operation
is not of a valid type.
 property tuners
A list of tuner operations.
Holds the list of tuners associated with this collection. The list can be modified as a standard Python list.
 Type
list[
hoomd.operation.Tuner
]
 property updaters
A list of updater operations.
Holds the list of updaters associated with this collection. The list can be modified as a standard Python list.
 Type
list[
hoomd.operation.Updater
]
 property writers
A list of writer operations.
Holds the list of writers associated with this collection. The list can be modified as a standard Python list.
 Type
list[
hoomd.operation.Writer
]
 class hoomd.Simulation(device, seed=None)
Define a simulation.
 Parameters
device (
hoomd.device.Device
) – Device to execute the simulation.seed (int) – Random number seed.
Simulation
is the central class in HOOMDblue that defines a simulation, including thestate
of the system, theoperations
that apply to the state during a simulationrun
, and thedevice
to use when executing the simulation.seed
sets the seed for the random number generator used by all operations added to thisSimulation
. property always_compute_pressure
Always compute the virial and pressure (defaults to
False
).By default, HOOMD only computes the virial and pressure on timesteps where it is needed (when
hoomd.write.GSD
writes log data to a file or when using an NPT integrator). Setalways_compute_pressure
to True to make the per particle virial, net virial, and system pressure available to query any time by property or through thehoomd.logging.Logger
interface.Note
Enabling this flag will result in a moderate performance penalty when using MD pair potentials.
 Type
 create_state_from_gsd(filename, frame= 1, domain_decomposition=(None, None, None))
Create the simulation state from a GSD file.
 Parameters
filename (str) – GSD file to read
frame (int) – Index of the frame to read from the file. Negative values index back from the last frame in the file.
domain_decomposition (tuple) – Choose how to distribute the state across MPI ranks with domain decomposition. Provide a tuple of 3 integers indicating the number of evenly spaced domains in the x, y, and z directions (e.g.
(8,4,2)
). Provide a tuple of 3 lists of floats to set the fraction of the simulation box to include in each domain. The sum of each list of floats must be 1.0 (e.g.([0.25, 0.75], [0.2, 0.8], [1.0])
).
Note
Set any or all of the
domain_decomposition
tuple elements toNone
andcreate_state_from_gsd
will select a value that minimizes the surface area between the domains (e.g.(2,None,None)
). The domains are spaced evenly along each automatically selected direction. The default value of(None, None, None)
will automatically select the number of domains in all directions.
 create_state_from_snapshot(snapshot, domain_decomposition=(None, None, None))
Create the simulation state from a
Snapshot
. Parameters
snapshot (Snapshot or gsd.hoomd.Snapshot) – Snapshot to initialize the state from. A
gsd.hoomd.Snapshot
will first be converted to ahoomd.Snapshot
.domain_decomposition (tuple) – Choose how to distribute the state across MPI ranks with domain decomposition. Provide a tuple of 3 integers indicating the number of evenly spaced domains in the x, y, and z directions (e.g.
(8,4,2)
). Provide a tuple of 3 lists of floats to set the fraction of the simulation box to include in each domain. The sum of each list of floats must be 1.0 (e.g.([0.25, 0.75], [0.2, 0.8], [1.0])
).
When
timestep
isNone
before calling,create_state_from_snapshot
setstimestep
to 0.Note
Set any or all of the
domain_decomposition
tuple elements toNone
andcreate_state_from_gsd
will select a value that minimizes the surface area between the domains (e.g.(2,None,None)
). The domains are spaced evenly along each automatically selected direction. The default value of(None, None, None)
will automatically select the number of domains in all directions.
 property device
Device used to execute the simulation.
 Type
 property final_timestep
run
will end at this timestep.final_timestep
is the timestep on which the currently executingrun
will complete.(
Loggable
: category=”scalar”) Type
 property operations
The operations that apply to the state.
 Type
 run(steps, write_at_start=False)
Advance the simulation a number of steps.
 Parameters
Note
Initialize the simulation’s state before calling
run
.During each step
run
,Simulation
applies itsoperations
to the state in the order: Tuners, Updaters, Integrator, then Writers following the logic in this pseudocode:if write_at_start: for writer in operations.writers: if writer.trigger(timestep): writer.write(timestep) end_step = timestep + steps while timestep < end_step: for tuner in operations.tuners: if tuner.trigger(timestep): tuner.tune(timestep) for updater in operations.updaters: if updater.trigger(timestep): updater.update(timestep) if operations.integrator is not None: operations.integrator(timestep) timestep += 1 for writer in operations.writers: if writer.trigger(timestep): writer.write(timestep)
This order of operations ensures that writers (such as
hoomd.write.GSD
) capture the final output of the last step of the run loop. For example, a writer with a triggerhoomd.trigger.Periodic(period=100, phase=0)
active during arun(500)
would write on steps 100, 200, 300, 400, and 500. Setwrite_at_start=True
on the first call torun
to also obtain output at step 0.Warning
Using
write_at_start=True
in subsequent calls torun
will result in duplicate output frames.
 property seed
Random number seed.
Seeds are in the range [0, 65535]. When set,
seed
will take only the lowest 16 bits of the given value.HOOMDblue uses a deterministic counter based pseudorandom number generator. Any time a random value is needed, HOOMDblue computes it as a function of the user provided seed
seed
(16 bits), the currenttimestep
(lower 40 bits), particle identifiers, MPI ranks, and other unique identifying values as needed to sample uncorrelated values:random_value = f(seed, timestep, ...)
(
Loggable
: category=”scalar”) Type
 property state
The current simulation state.
 Type
 property timestep
Current time step of the simulation.
Note
Functions like
create_state_from_gsd
will set the initial timestep from the input. Settimestep
before creating the simulation state to override values fromcreate_
methods:sim.timestep = 5000 sim.create_state_from_gsd('gsd_at_step_10000000.gsd') assert sim.timestep == 5000
(
Loggable
: category=”scalar”) Type
 property tps
The average number of time steps per second.
tps
is the number of steps executed divided by the elapsed walltime in seconds. It is updated during therun
loop and remains fixed afterrun
completes.Note
The start time and step are reset at the beginning of each call to
run
.(
Loggable
: category=”scalar”) Type
 class hoomd.Snapshot(communicator=None)
Selfcontained copy of the simulation
State
. Parameters
communicator (Communicator) – MPI communicator to be used with the simulation.
 communicator
MPI communicator.
 Type
Note
Snapshot
is ducktype compatible withgsd.hoomd.Snapshot
except that arrays inSnapshot
are not assignable. You can edit their contents: e.g.snapshot.particles.typeid[:] == 0
.Warning
Data is only present on the root rank:
if snapshot.communicator.rank == 0: pos = snapshot.particles.position[0]
 property angles
Angles.
 angles.typeid
Angle type id.
 Type
(N,)
numpy.ndarray
ofuint32
 angles.group
Tags of the particles in the angle.
 Type
(N, 3)
numpy.ndarray
ofuint32
Note
Set
N
to change the size of the arrays.
 property bonds
Bonds.
 bonds.typeid
Bond type id.
 Type
(N,)
numpy.ndarray
ofuint32
 bonds.group
Tags of the particles in the bond.
 Type
(N, 2)
numpy.ndarray
ofuint32
Note
Set
N
to change the size of the arrays.
 property configuration
Snapshot box configuration.
 box
Simulation box parameters
[Lx, Ly, Lz, xy, xz, yz]
.
Note
box
accepts any values thatBox.from_box
allows when setting.
 property constraints
Constraints.
 constraints.value
Constraint length.
 Type
(N, )
numpy.ndarray
offloat
 constraints.group
Tags of the particles in the constraint.
 Type
(N, 2)
numpy.ndarray
ofuint32
Note
Set
N
to change the size of the arrays.
 property dihedrals
Dihedrals.
 dihedrals.typeid
Dihedral type id.
 Type
(N,)
numpy.ndarray
ofuint32
 dihedrals.group
Tags of the particles in the dihedral.
 Type
(N, 4)
numpy.ndarray
ofuint32
Note
Set
N
to change the size of the arrays.
 classmethod from_gsd_snapshot(gsd_snap, communicator)
Constructs a
hoomd.Snapshot
from agsd.hoomd.Snapshot
object. Parameters
gsd_snap (
gsd.hoomd.Snapshot
) – The gsd snapshot to convert to ahoomd.Snapshot
.communicator (hoomd.communicator.Communicator) – The MPI communicator to use for the snapshot. This prevents the snapshot from being stored on every rank.
Note
from_gsd_snapshot
only accesses thegsd_snap
argument on rank 0. In MPI simulations, avoid duplicating memory and file reads by reading GSD files only on rank 0 and passinggsd_snap=None
on other ranks.
 property impropers
Impropers.
 impropers.typeid
Improper type id.
 Type
(N,)
numpy.ndarray
ofuint32
 impropers.group
Tags of the particles in the improper.
 Type
(N, 4)
numpy.ndarray
ofuint32
Note
Set
N
to change the size of the arrays.
 property pairs
Special pairs.
 pairs.typeid
Special pair type id.
 Type
(N,)
numpy.ndarray
ofuint32
 pairs.group
Tags of the particles in the special pair.
 Type
(N, 2)
numpy.ndarray
ofuint32
Note
Set
N
to change the size of the arrays.
 property particles
Particles.
 particles.position
Particle position \([\mathrm{length}]\).
 Type
(N, 3)
numpy.ndarray
offloat
 particles.orientation
Particle orientation.
 Type
(N, 4)
numpy.ndarray
offloat
 particles.typeid
Particle type id.
 Type
(N, )
numpy.ndarray
ofuint32
 particles.mass
Particle mass \([\mathrm{mass}]\).
 Type
(N, )
numpy.ndarray
offloat
 particles.charge
Particle charge \([\mathrm{charge}]\).
 Type
(N, )
numpy.ndarray
offloat
 particles.diameter
Particle diameter \([\mathrm{length}]\).
 Type
(N, )
numpy.ndarray
offloat
 particles.body
Particle body.
 Type
(N, )
numpy.ndarray
ofint32
 particles.moment_inertia
Particle moment of inertia \([\mathrm{mass} \cdot \mathrm{length}^2]\).
 Type
(N, 3)
numpy.ndarray
offloat
 particles.velocity
Particle velocity \([\mathrm{velocity}]\).
 Type
(N, 3)
numpy.ndarray
offloat
 particles.angmom
Particle angular momentum \([\mathrm{mass} \cdot \mathrm{velocity} \cdot \mathrm{length}]\).
 Type
(N, 4)
numpy.ndarray
offloat
 particles.image
Particle image.
 Type
(N, 3)
numpy.ndarray
ofint32
Note
Set
N
to change the size of the arrays.
 replicate(nx, ny, nz=1)
Replicate the snapshot along the periodic box directions.
 Parameters
Performs the same operation as
State.replicate
on aSnapshot
. Returns
self
 wrap()
Wrap particles into the snapshot box.
 Returns
self
 class hoomd.State(simulation, snapshot, domain_decomposition)
The state of a
hoomd.Simulation
object.Note
This object cannot be directly instantiated. Use
hoomd.Simulation.create_state_from_gsd
andhoomd.Simulation.create_state_from_snapshot
to instantiate aState
object as part of a simulation.Overview
State
stores the data that describes the thermodynamic microstate of ahoomd.Simulation
object. This data consists of the box, particles, bonds, angles, dihedrals, impropers, special pairs, and constraints.Box
The simulation
box
describes the area in space that contains the particles and the periodic boundary conditions to apply. SeeBox
for a full description.Particles
The state contains
N_particles
particles. Each particle has a position, orientation, type id, body, mass, moment of inertia, charge, diameter, velocity, angular momentum, image, and tag:\(\vec{r}\): position \([\mathrm{length}]\)  x,y,z cartesian coordinates defining the position of the particle in the box
\(\mathbf{q}\): orientation \([\mathrm{dimensionless}]\)  (s, \(\vec{a}\)), unit quaternion defining the rotation from the particle’s local reference frame to the box reference frame.
\(t_\mathrm{id}\): type id \([\mathrm{dimensionless}]\)  integer in the range
[0,len(particle_types)
) that identifies the particle’s type.particle_types
maps type ids to names with:name = particle_types[t_id]
.\(b_\mathrm{id}\): body id \([\mathrm{dimensionless}]\)  integer that identifies the particle’s rigid body. A value of
1
indicates that this particle does not belong to a body. A positive value indicates that the particle belongs to the body \(b_\mathrm{id}\). This particle is the central particle of a body when the body id is equal to the tag \(b_\mathrm{id} = p_\mathrm{tag}\). (used bymd.constrain.Rigid
)\(m\): mass \([\mathrm{mass}]\)  the particle’s mass.
\(I\): moment of inertia \([\mathrm{mass} \cdot \mathrm{length}^2]\)  \(I_{xx}\), \(I_{yy}\), \(I_{zz}\) elements of the diagonal moment of inertia tensor in the particle’s local reference frame. The offdiagonal elements are 0.
\(q\): charge \([\mathrm{charge}]\)
\(d\): diameter \([\mathrm{length}]\)  deprecated in v3.0.0. HOOMDblue reads and writes particle diameters, but does not use them in any computations. As of the current beta release, diameter is still used in
md.pair.SLJ
andmd.pair.DLVO
.\(\vec{v}\): velocity \([\mathrm{velocity}]\)  x,y,z components of the particle’s velocity in the box’s reference frame.
\(\mathbf{P_S}\): angular momentum \([\mathrm{mass} \cdot \mathrm{velocity} \cdot \mathrm{length}]\)  in a quaternion representation (see note).
\(\vec{n}\) : image \([\mathrm{dimensionless}]\)  integers x,y,z that record how many times the particle has crossed each of the periodic box boundaries.
\(p_\mathrm{tag}\) : tag \([\mathrm{dimensionless}]\)  integer that uniquely identifies a given particle. The particles are in tag order when writing and initializing to/from a GSD file or snapshot: \(p_\mathrm{tag,i} = i\). When accessing data in local snapshots, particles may be in any order.
Note
HOOMD stores angular momentum as a quaternion because that is the form used when integrating the equations of motion (see Kamberaj 2005). The angular momentum quaternion \(\mathbf{P_S}\) is defined with respect to the orientation quaternion of the particle \(\mathbf{q}\) and the vector angular momentum of the particle, lifted into pure imaginary quaternion form \(\mathbf{S}^{(4)}\) as:
\[\mathbf{P_S} = 2 \mathbf{q} \times \mathbf{S}^{(4)}\]. Following this, the angular momentum vector \(\vec{S}\) in the particle’s local reference frame is:
\[\vec{S} = \frac{1}{2}im(\mathbf{q}^* \times \mathbf{P_S})\]Bonds
The state contains
N_bonds
bonds,N_angles
angles,N_dihedrals
dihedrals,N_impropers
impropers, andN_special_pairs
special pairs. Each of these data structures is similar, differing in the number of particles in the group and what operations use them. Bonds, angles, dihedrals, and impropers contain 2, 3, 4, and 4 particles per group respectively. Bonds specify the toplogy used when computing energies and forces inmd.bond
, angles define the same formd.angle
, dihedrals formd.dihedral
and impropers formd.improper
. These collectively implement bonding potentials used in molecular dynamics force fields. Like bonds, special pairs define connections between two particles, but special pairs are intended to adjust the 14 pairwise interactions in some molecular dynamics force fields: seemd.special_pair
. Each bonded group is defined by a type id, the group members, and a tag.\(t_\mathrm{id}\): type id \([\mathrm{dimensionless}]\)  integer in the range
[0,len(bond_types)
) that identifies the bond’s type.bond_types
maps type ids to names with:name = bond_types[t_id]
. Similarly,angle_types
lists the angle types,dihedral_types
lists the dihedral types,improper_types
lists the improper types, andspecial_pair_types
lists the special pair types.group members: a list of integers in the range
[0,max(p_tag)]
that defines the tags of the particles in the bond (2), angle (3), dihedral (4), improper (4), or special pair (2).\(b_\mathrm{tag}\) : tag \([\mathrm{dimensionless}]\)  integer that uniquely identifies a given bond. The bonds are in tag order when writing and initializing to/from a GSD file or snapshot \(b_\mathrm{tag,i} = i\). When accessing data in local snapshots, bonds may be in any order.
Constraints
The state contains
N_constraints
distance constraints between particles. These constraints are enforced bymd.constrain.Distance
. Each distance constraint consists of a distance value and the group members.group members: a list of 2 integers in the range
[0,max(p_tag)]
that defines the tags of the particles in the constraint.\(d\): constraint value \([\mathrm{length}]\)  the distance between particles in the constraint.
MPI
When running in serial or on 1 MPI rank, the entire simulation state is stored in that process. When using more than 1 MPI rank, HOOMDblue employs a domain decomposition approach to split the simulation box an integer number of times in the x, y, and z directions. Each MPI rank stores and operates on the particles local to that rank, those contained within the region defined by the split planes. Each MPI rank communicates with its neighbors to obtain the properties of particles near the boundary between ranks (ghost particles) so that it can compute interactions across the boundary.
Accessing Data
Two complementary APIs provide access to the state data: local snapshots that access data directly available on the local MPI rank (including the local and ghost particles) and global snapshots that collect the entire state on rank 0. See
State.cpu_local_snapshot
,State.gpu_local_snapshot
,State.get_snapshot
, andState.set_snapshot
for information about these data access patterns. property cpu_local_snapshot
Expose simulation data on the CPU.
Provides access directly to the system state’s particle, bond, angle, dihedral, improper, constaint, and pair data through a context manager. Data in
State.cpu_local_snapshot
is MPI rank local, and thehoomd.data.LocalSnapshot
object is only usable within a context manager (i.e.with sim.state.cpu_local_snapshot as data:
). Attempts to assess data outside the context manager will result in errors. The local snapshot interface is similar to that ofhoomd.Snapshot
.The
hoomd.data.LocalSnapshot
data access is mediated throughhoomd.array.HOOMDArray
objects. This lets us ensure memory safety when directly accessing HOOMDblue’s data. The interface provides zerocopy access (zerocopy is guaranteed on CPU, access may be zerocopy if running on GPU).Changing the data in the buffers exposed by the local snapshot will change the data across the HOOMDblue simulation. For a trivial example, this example would set all particle zaxis positions to 0.
with sim.state.cpu_local_snapshot as data: data.particles.position[:, 2] = 0
Note
The state’s box and the number of particles, bonds, angles, dihedrals, impropers, constaints, and pairs cannot change within the context manager.
Note
Getting a local snapshot object is order \(O(1)\) and setting a single value is of order \(O(1)\).
 property domain_decomposition
Number of domains in the x, y, and z directions.
 property domain_decomposition_split_fractions
Box fractions of the domain split planes in the x, y, and z directions.
 get_snapshot()
Make a copy of the simulation current state.
State.get_snapshot
makes a copy of the simulation state and makes it available in a single object.State.set_snapshot
resets the internal state to that in the given snapshot. Use these methods to implement techniques like hybrid MD/MC or umbrella sampling where entire system configurations need to be reset to a previous one after a rejected move.Note
Data across all MPI ranks and from GPUs is gathered on the root MPI rank’s memory. When accessing data in MPI simulations, use a
if snapshot.communicator.rank == 0:
conditional to access data arrays only on the root rank.Note
State.get_snapshot
is an order \(O(N_{particles} + N_{bonds} + \ldots)\) operation.See also
 Returns
The current simulation state
 Return type
 property gpu_local_snapshot
Expose simulation data on the GPU.
Provides access directly to the system state’s particle, bond, angle, dihedral, improper, constaint, and pair data through a context manager. Data in
State.gpu_local_snapshot
is GPU local, and thehoomd.data.LocalSnapshotGPU
object is only usable within a context manager (i.e.with sim.state.gpu_local_snapshot as data:
). Attempts to assess data outside the context manager will result in errors. The local snapshot interface is similar to that ofhoomd.Snapshot
.The
hoomd.data.LocalSnapshotGPU
data access is mediated throughhoomd.array.HOOMDGPUArray
objects. This helps us maintain memory safety when directly accessing HOOMDblue’s data. The interface provides zerocopy access on the GPU (assuming data was last accessed on the GPU).Changing the data in the buffers exposed by the local snapshot will change the data across the HOOMDblue simulation. For a trivial example, this example would set all particle zaxis positions to 0.
with sim.state.gpu_local_snapshot as data: data.particles.position[:, 2] = 0
Warning
This property is only available when running on a GPU(s).
Note
The state’s box and the number of particles, bonds, angles, dihedrals, impropers, constaints, and pairs cannot change within the context manager.
Note
Getting a local snapshot object is order \(O(1)\) and setting a single value is of order \(O(1)\).
 replicate(nx, ny, nz=1)
Replicate the state of the system along the periodic box directions.
 Parameters
replicate
makes the system statenx * ny * nz
times larger. In each of the new periodic box images, it places a copy of the initial state with the particle positions offset to locate them in the image and the bond, angle, dihedral, improper, and pair group tags offset to apply to the copied particles. All other particle properties (mass, typeid, velocity, charge, …) are copied to the new particles without change.After placing the particles,
replicate
expands the simulation box by a factor ofnx
,ny
, andnz
in the direction of the first, second, and third box lattice vectors respectively and adjusts the particle positions to center them in the new box.
 set_box(box)
Set a new simulation box.
 Parameters
box (Box) – New simulation box.
Note
All particles must be inside the new box.
set_box
does not change any particle properties.See also
 set_snapshot(snapshot)
Restore the state of the simulation from a snapshot.
 Parameters
snapshot (hoomd.Snapshot) – Snapshot of the system from
get_snapshot
Warning
set_snapshot
can only make limited changes to the simulation state. While it can change the number of particles/bonds/etc… or their properties, it cannot change the number or names of the particle/bond/etc.. types.Note
State.set_snapshot
is an order \(O(N_{particles} + N_{bonds} + \ldots)\) operation and is very expensive when the simulation device is a GPU.
 thermalize_particle_momenta(filter, kT)
Assign random values to particle momenta.
 Parameters
filter (hoomd.filter.ParticleFilter) – Particles to modify
kT (float) – Thermal energy to set \([\mathrm{energy}]\)
thermalize_particle_momenta
assigns the selected particle’s velocities and angular momentum to random values drawn from a Gaussian distribution consistent with the given thermal energy kT.Velocity
thermalize_particle_momenta
assigns random velocities to the x and y components of each particle’s velocity. When the simulation box is 3D, it also assigns a random velocity to the z component. When the simulation box is 2D, it sets the z component to 0. Finally, sets the center of mass velocity of the selected particles to 0.Angular momentum
thermalize_particle_momenta
assigns random angular momenta to each rotational degree of freedom that has a nonzero moment of intertia. Each particle can have 0, 1, 2, or 3 rotational degrees of freedom as determine by its moment of inertia.
 property types
dictionary of all types in the state.
Combines the data from
State.particle_types
,State.bond_types
,State.angle_types
,State.dihedral_types
,State.improper_types
, andState.special_pair_types
into a dictionary with keys matching the property names.
 update_group_dof()
Update the number of degrees of freedom in each group.
The groups of particles selected by filters each need to know the number of degrees of freedom given to that group by the simulation’s Integrator. This method is called automatically when:
The Integrator is attached to the simulation
Call it manually to force an update.
Modules