hoomd¶
Overview
Define box dimensions. |
|
A mutable collection of operations which act on a |
|
Define a simulation. |
|
The state of a |
Details
HOOMD-blue 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 (distance units).
Ly (float) – box extent in the y direction (distance units).
Lz (float) – box extent in the z direction (distance units).
xy (float) – tilt factor xy (dimensionless).
xz (float) – tilt factor xz (dimensionless).
yz (float) – tilt factor yz (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 all values:
hoomd.Box(Lx=1., Ly=2., Lz=3., xy=1., xz=2., yz=3.)
-
property
L
¶ The box lengths,
[Lx, Ly, Lz]
.Can be set with a float which sets all lengths, or a length 3 vector.
- Type
-
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 box-like object.
- Parameters
box – A box-like object
Note
Objects that can be converted to HOOMD-blue boxes include lists like
[Lx, Ly, Lz, xy, xz, yz]
, dictionaries with keys'Lx', 'Ly', 'Lz', 'xy', 'xz', 'yz', objects with attributes :code:`Lx, Ly, Lz, xy, xz, yz, 3x3 matrices (see `from_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 read-only.
- 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
-
scale
(s)¶ Scale box dimensions.
Scales the box 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
-
property
volume
¶ The current volume (area in 2D) of the box.
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 HOOMD-blue,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.integrate
(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.
-
__iadd__
(operation)¶ Works the same as
Operations.add
.- Parameters
operation (
hoomd.operation.Operation
) – A HOOMD-blue 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 HOOMD-blue 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 HOOMD-blue 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 HOOMD-blue 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 HOOMD-blue 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)¶ Create the simulation state from a GSD file.
-
create_state_from_snapshot
(snapshot)¶ Create the simulations 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
.
When
timestep
isNone
before calling,create_state_from_snapshot
setstimestep
to 0.
-
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.dump.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.HOOMD-blue uses a deterministic counter based pseudorandom number generator. Any time a random value is needed, HOOMD-blue 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
-
property
walltime
¶ The walltime spent during the last call to
run
.walltime
is the number seconds that the last call torun
took to complete. It is updated during therun
loop and remains fixed afterrun
completes.(
Loggable
: category=”scalar”)- Type
-
write_debug_data
(filename)¶ Write debug data to a JSON file.
- Parameters
filename (str) – Name of file to write.
The debug data file contains useful information for others to help you troubleshoot issues.
Note
The file format and particular data written to this file may change from version to version.
Warning
The specified file name will be overwritten.
-
class
hoomd.
Snapshot
(communicator=None)¶ -
property
angles
¶
-
property
bonds
¶
-
property
configuration
¶
-
property
constraints
¶
-
property
dihedrals
¶
-
property
exists
¶
-
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.
-
property
impropers
¶
-
property
pairs
¶
-
property
particles
¶
-
replicate
(nx, ny, nz)¶
-
property
-
class
hoomd.
State
(simulation, snapshot)¶ The state of a
hoomd.Simulation
object.Provides access (read/write) to a
hoomd.Simulation
object’s particle, bond, angle, etc. data. Data access is facilitated through two complementary APIs: global and local snapshots (note that global does not refer to variable scope here). SeeState.snapshot
,State.cpu_local_snapshot
, andState.gpu_local_snapshot
for information about these data access patterns. In addition, many commonly used smaller quantities such as the number of particles in a simulation are available directly throughState
object properties.Note
This object should never be directly instantiated by users. There is no way to set a state created outside of a
hoomd.Simulation
object to a simulation. Usehoomd.Simulation.create_state_from_gsd
andhoomd.Simulation.create_state_from_snapshot
to instantiate aState
object.-
property
box
¶ The current simulation box.
Editing the box directly is not allowed. For example
state.box.scale(1.1)
would not scale the state’s box. To set the state’s box to a new boxstate.box = new_box
must be used.- Type
-
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 HOOMD-blue’s data. The interface provides zero-copy access (zero-copy is guarenteed on CPU, access may be zero-copy if running on GPU).Changing the data in the buffers exposed by the local snapshot will change the data across the HOOMD-blue simulation. For a trivial example, this example would set all particle z-axis 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
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 HOOMD-blue’s data. The interface provides zero-copy 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 HOOMD-blue simulation. For a trivial example, this example would set all particle z-axis 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
()¶
-
property
snapshot
¶ All data of a simulation’s current microstate.
State.snapshot
should be used when all of a simulation’s state information is desired in a single object. When accessed, data across all MPI ranks and from GPUs is gathered on the root MPI rank’s memory. When accessing data in MPI simulations, it is recommended to use aif snapshot.exists:
conditional to prevent attempting to access data on a non-root rank.This property can be set to replace the system state with the given
hoomd.Snapshot
object. Example use cases in which a simulation’s state may be reset from a snapshot include Monte Carlo schemes implemented at the Python script level, where the current snapshot is passed to the Monte Carlo simulation before being passed back after running some Monte Carlo steps.Warning
Using
State.snapshot
multiple times will gather data across MPI ranks and GPUs every time. If the snapshot is needed for more than one use, it is recommended to store it in a variable.Note
Setting or getting a snapshot is an order \(O(N_{particles} + N_{bonds} + \ldots)\) operation.
- Type
-
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 (in energy units)
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 non-zero moment of intertia. Each particle can have 0, 1, 2, or 3 rotational degrees of freedom.See also
md.methods.NVT.thermalize_extra_dof
md.methods.NPT.thermalize_extra_dof
-
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.
-
property
Modules