hoomd.write¶
Overview
Write the last \(N\) stored frames in the GSD format. |
|
Writes simulation trajectories in the DCD format. |
|
User-defined writer. |
|
Write simulation trajectories in the GSD format. |
|
Write loggable simulation data to HDF5 files. |
|
Write delimiter separated values to a stream. |
Details
Writers.
Writers write the state of the simulation, logger quantities, or calculated results to output files or streams:
Burstprovides a sliding window of a simulation trajectory wrote out atBurst.dumpfor use in selective high frequency trajectory data.Combine
GSDwith ahoomd.logging.Loggerto save system properties or per-particle calculated results.Use
HDF5Logto store logged data in HDF5 resizable datasets.Use
Tableto display the status of the simulation periodically to standard out.Implement custom output formats with
CustomWriter.
Writers do not modify the system state.
Tip
OVITO has native support for GSD files, including logged per-particle array quantities and particle shapes.
- class hoomd.write.Burst(trigger, filename, filter=hoomd.filter.All(), mode='ab', dynamic=None, logger=None, max_burst_size=-1, write_at_start=False)¶
Bases:
GSDWrite the last \(N\) stored frames in the GSD format.
When triggered,
Burstadds a frame (up the last \(N\) frames) in a buffer. Calldumpto write the frames to the file. When the the next frame would result in \(N + 1\) frames being stored, the oldest frame is removed and the new frame is added.- Parameters:
trigger (hoomd.trigger.trigger_like) – Select the timesteps to store in the buffer.
filename (str) – File name to write.
filter (hoomd.filter.filter_like) – Select the particles to write. Defaults to
hoomd.filter.All.mode (str) – The file open mode. Defaults to
'ab'.dynamic (list[str]) – Field names and/or field categores to save in all frames. Defaults to
['property'].logger (hoomd.logging.Logger) – Provide log quantities to write. Defaults to
None.max_burst_size (int) – The maximum number of frames to store before between writes. -1 represents no limit. Defaults to -1.
write_at_start (bool) – When
Trueand the file does not exist or has 0 frames: write one frame with the current state of the system whenhoomd.Simulation.runis called. Defaults toFalse.clear_whole_buffer_after_dump (bool) – When
Truethe buffer is emptied after callingdumpeach time. WhenFalse,dumpremoves frames from the buffer until theendindex. Defaults toTrue.
Warning
Bursterrors when attempting to create a file or writing to one with zero frames whenwrite_at_startisFalse.Note
When analyzing files created by
Burst, generally the first frame is not associated with the call toBurst.dump.Example:
burst = hoomd.write.Burst(trigger=hoomd.trigger.Periodic(1_000), filename=burst_filename, max_burst_size=100, write_at_start=True) simulation.operations.writers.append(burst)
See also
The base class
hoomd.write.GSD- max_burst_size¶
The maximum number of frames to store before between writes. -1 represents no limit.
Example:
burst.max_burst_size = 200
- Type:
- write_at_start¶
When
Trueand the file does not exist or has 0 frames: write one frame with the current state of the system whenhoomd.Simulation.runis called (read only).Example:
write_at_start = burst.write_at_start
- Type:
- clear_whole_buffer_after_dump¶
When
Truethe buffer is emptied after callingdumpeach time. WhenFalse,dumpremoves frames from the buffer until theendindex.Example:
burst.clear_buffer_after_dump = False
- Type:
- __len__()¶
Get the current length of the internal frame buffer.
Example:
buffered_frames = len(burst)
- dump(start=0, end=-1)¶
Write stored frames in range to the file and empties the buffer.
This method alllows for custom writing of frames at user specified conditions.
- Parameters:
Example:
burst.dump()
- class hoomd.write.CustomWriter(trigger, action)¶
Bases:
CustomOperation,WriterUser-defined writer.
- Parameters:
action (hoomd.custom.Action) – The action to call.
trigger (hoomd.trigger.trigger_like) – Select the timesteps to call the action.
CustomWriteris ahoomd.operation.Writerthat wraps a user-definedhoomd.custom.Actionobject so the action can be added to ahoomd.Operationsinstance for use withhoomd.Simulationobjects.Writers may read the system state and generate output files or print to output streams. Writers should not modify the system state.
Example:
custom_writer = hoomd.write.CustomWriter( action=custom_action, trigger=hoomd.trigger.Periodic(1000)) simulation.operations.writers.append(custom_writer)
See also
The base class
hoomd.custom.CustomOperation.
- class hoomd.write.DCD(trigger, filename, filter=hoomd.filter.All(), overwrite=False, unwrap_full=False, unwrap_rigid=False, angle_z=False)¶
Bases:
WriterWrites simulation trajectories in the DCD format.
- Parameters:
trigger (hoomd.trigger.Periodic) – Select the timesteps to write.
filename (str) – File name to write.
filter (hoomd.filter.filter_like) – Select the particles to write. Defaults to
hoomd.filter.All.overwrite (bool) – When False, (the default) an existing DCD file will be appended to. When True, an existing DCD file filename will be overwritten.
unwrap_full (bool) – When False, (the default) particle coordinates are always written inside the simulation box. When True, particles will be unwrapped into their current box image before writing to the DCD file.
unwrap_rigid (bool) – When False, (the default) individual particles are written inside the simulation box which breaks up rigid bodies near box boundaries. When True, particles belonging to the same rigid body will be unwrapped so that the body is continuous. The center of mass of the body remains in the simulation box, but some particles may be written just outside it. unwrap_rigid is ignored when unwrap_full is True.
angle_z (bool) – When True, the particle orientation angle is written to the z component (only useful for 2D simulations)
DCDwrites the simulation trajectory to the specified file in the DCD file format. DCD stores only particle positions and the box parameters, in length units, and is limited to simulations where the number of particles is fixed.Warning
When you use
DCDto append to an existing DCD file:The period must be the same or the time data in the file will not be consistent.
DCDwill not write out data at time steps that already are present in the DCD file.
Example:
dcd = hoomd.write.DCD(trigger=hoomd.trigger.Periodic(1_000_000), filename=dcd_filename) simulation.operations.writers.append(dcd)
- filter¶
Select the particles to write (read only).
Example:
filter_ = dcd.filter
- Type:
- overwrite¶
When False, an existing DCD file will be appended to. When True, an existing DCD file filename will be overwritten (read only).
Example:
overwrite = dcd.overwrite
- Type:
- unwrap_full¶
When False, particle coordinates are always written inside the simulation box. When True, particles will be unwrapped into their current box image before writing to the DCD file.
Example:
dcd.unwrap_full = True
- Type:
- unwrap_rigid¶
When False, individual particles are written inside the simulation box which breaks up rigid bodies near box boundaries. When True, particles belonging to the same rigid body will be unwrapped so that the body is continuous. The center of mass of the body remains in the simulation box, but some particles may be written just outside it. unwrap_rigid is ignored when unwrap_full is True.
Example:
dcd.unwrap_rigid = True
- Type:
- class hoomd.write.GSD(trigger, filename, filter=hoomd.filter.All(), mode='ab', truncate=False, dynamic=None, logger=None)¶
Bases:
WriterWrite simulation trajectories in the GSD format.
- Parameters:
trigger (hoomd.trigger.trigger_like) – Select the timesteps to write.
filename (any type that converts to
str) – File name to write.filter (hoomd.filter.filter_like) – Select the particles to write. Defaults to
hoomd.filter.All.mode (str) – The file open mode. Defaults to
'ab'.truncate (bool) – When
True, truncate the file and write a new frame 0 each time this operation triggers. Defaults toFalse.dynamic (list[str]) – Field names and/or field categores to save in all frames. Defaults to
['property'].logger (hoomd.logging.Logger) – Provide log quantities to write. Defaults to
None.
GSDwrites the simulation trajectory to the specified file in the GSD format.GSDcan store all particle, bond, angle, dihedral, improper, pair, and constraint data fields in every frame of the trajectory.GSDcan write trajectories where the number of particles, number of particle types, particle types, diameter, mass, charge, or other quantities change over time.GSDcan also store arbitrary, scalar, string, and array quantities provided by ahoomd.logging.Loggerinstance inlogger.Valid file open modes:
mode
description
'wb'Open the file for writing. Create the file if needed, or overwrite an existing file.
'xb'Create a GSD file exclusively. Raise an exception when the file exists.
'ab'Create the file if needed, or append to an existing file.
To reduce file size,
GSDdoes not write properties that are set to defaults. When masses, orientations, angular momenta, etc… are left default for all particles, these fields will not take up any space in the file, except on frame 1+ when the field is also non-default in frame 0.GSDwrites all non-default fields to frame 0 in the file.To further reduce file sizes,
GSDallows the user to select which specific fields will be considered for writing to frame 1+ in thedynamiclist. When reading a GSD file, the data in frame 0 is read when a quantity is missing in frame i, so any fields not indynamicare fixed for the entire trajectory.The
dynamiclist can contain one or more of the following strings:'property''configuration/box''particles/N''particles/position''particles/orientation'
'momentum''particles/velocity''particles/angmom''particles/image'
'attribute''particles/types''particles/typeid''particles/mass''particles/charge''particles/diameter''particles/body''particles/moment_inertia'
'topology'bonds/*
angles/*
dihedrals/*
impropers/*
constraints/*
pairs/*
When you set a category string (
'property','momentum','attribute'),GSDmakes all the category member’s fields dynamic.Warning
GSDbuffers writes in memory. Abnormal exits (e.g.kill,scancel, reaching walltime limits) may cause loss of data. Ensure that your scripts exit cleanly and callflush()as needed to write buffered frames to the file.See also
See the GSD documentation, GSD HOOMD Schema, and GSD GitHub project for more information on GSD files.
Note
When you use
filterto select a subset of the whole system,GSDwrites only the selected particles in ascending tag order and does not write out topology.Tip
All logged data fields must be present in the first frame in the gsd file to provide the default value. To achieve this, set the
loggerattribute before the operation is triggered to write the first frame in the file.Some (or all) fields may be omitted on later frames. You can set
loggertoNoneor remove specific quantities from the logger, but do not add additional quantities after the first frame.Example:
gsd = hoomd.write.GSD(trigger=hoomd.trigger.Periodic(1_000_000), filename=gsd_filename) simulation.operations.writers.append(gsd)
- filter¶
Select the particles to write (read-only).
Example:
filter_ = gsd.filter
- Type:
- truncate¶
When
True, truncate the file and write a new frame 0 each time this operation triggers (read-only).Example:
truncate = gsd.truncate
- Type:
- dynamic¶
Field names and/or field categores to save in all frames.
Examples:
gsd.dynamic = ['property']
gsd.dynamic = ['property', 'momentum']
gsd.dynamic = ['property', 'particles/image', 'particles/typeid']
- write_diameter¶
When
False, do not writeparticles/diameter. Set toTrueto write non-default particle diameters.Example:
gsd.write_diameter = True
- Type:
- maximum_write_buffer_size¶
Size (in bytes) to buffer in memory before writing to the file.
Example:
gsd.maximum_write_buffer_size = 128 * 1024**2
- Type:
- flush()¶
Flush the write buffer to the file.
Example:
gsd_writer.flush()
Flush all write buffers:
for writer in simulation.operations.writers: if hasattr(writer, 'flush'): writer.flush()
- static write(state, filename, filter=hoomd._hoomd.ParticleFilter, mode='wb', logger=None)¶
Write the given simulation state out to a GSD file.
- Parameters:
state (State) – Simulation state.
filename (str) – File name to write.
filter (hoomd.filter.filter_like) – Select the particles to write.
mode (str) – The file open mode. Defaults to
'wb'.logger (hoomd.logging.Logger) – Provide log quantities to write.
The valid file modes for
writeare'wb'and'xb'.
- class hoomd.write.HDF5Log(trigger, filename, logger, mode='a')¶
Bases:
Write loggable simulation data to HDF5 files.
This class stores resizable scalar and array data in the HDF5 file format.
Note
This class requires that
h5pybe installed.Important
The HDF5 file can be used for other data storage; however, the “hoomd-data” key is reserved for use by this class. An exception will be thrown if this requirement is not met.
Warning
This class cannot handle string, strings, or object loggables.
- Parameters:
trigger (hoomd.trigger.trigger_like) – The trigger to determine when to write to the HDF5 file.
filename (str) – The filename of the HDF5 file to write to.
logger (hoomd.logging.Logger) – The logger instance to use for querying log data.
mode (
str, optional) – The mode to open the file in. Available values are “w”, “x” and “w-”, “a”, and “r+”. Defaults to “a”. See the h5py documentation for more details).
Example:
logger = hoomd.logging.Logger( hoomd.write.HDF5Log.accepted_categories) hdf5_log = hoomd.write.HDF5Log( trigger=hoomd.trigger.Periodic(10_000), filename=hdf5_filename, logger=logger) simulation.operations.writers.append(hdf5_log)
- accepted_categories¶
The enum value for all accepted categories for
HDF5Loginstances which is all categories other than “string”, “strings”, and “object” (seehoomd.logging.LoggerCategories).Example:
accepted_categories = hoomd.write.HDF5Log.accepted_categories
- filename¶
The filename of the HDF5 file written to (read only).
Example:
filename = hdf5_log.filename
- Type:
- logger¶
The logger instance used for querying log data (read only).
Example:
logger = hdf5_log.logger
- Type:
- flush()¶
Write out all data currently buffered in memory.
Examples:
Flush one writer:
hdf5_writer.flush()
Flush all write buffers:
for writer in simulation.operations.writers: if hasattr(writer, 'flush'): writer.flush()
- write(timestep=None)¶
Write out data to the HDF5 file.
Writes out a frame at the current timestep from the composed logger.
Warning
This may not be able to write out quantities which require the pressure tensor, rotational kinetic energy, or external field virial.
Example:
hdf5_writer.write()
Deprecated since version 4.5.0: Use
Simulationto call the operation.
- class hoomd.write.Table(trigger, logger, output=stdout, header_sep='.', delimiter=' ', pretty=True, max_precision=10, max_header_len=None)¶
Bases:
Write delimiter separated values to a stream.
- Parameters:
trigger (hoomd.trigger.trigger_like) – The trigger to determine when to run the Table backend.
logger (hoomd.logging.Logger) – The logger to query for output.
Tablesupports only'scalar'and'string'logger categories.output (
file-likeobject , optional) – A file-like object to output the data from, defaults to standard out. The object must havewriteandflushmethods and amodeattribute. Examples includesys.stdout,sys.stderrand the return value ofopen().header_sep (
str, optional) – String to use to separate names in the logger’s namespace, defaults to'.'. For example, if logging the total energy of anhoomd.md.pair.LJpair force object, the default header would bemd.pair.LJ.energy.delimiter (
str, optional) – String used to separate elements in the space delimited file, defaults to' '.pretty (
bool, optional) – Flags whether to attempt to make output prettier and easier to read (defaults toTrue).max_precision (
int, optional) – If pretty is not set, then this controls the maximum precision to use when outputing numerical values, defaults to 10.max_header_len (
int, optional) –If not
None(the default), limit the outputted header names to lengthmax_header_len. When notNone, names are grabbed from the most specific to the least. For example, if set to 7 the namespace ‘hoomd.md.pair.LJ.energy’ would be set to ‘energy’.Note
At a minimum, the complete most specific part of the namespace will be used regardless of this setting.
Use
Tableto write scalar and stringhoomd.logging.Loggerquantities to standard out or to a file.Warning
When logger quantities include strings with spaces, the default space delimiter will result in files that are not machine readable.
Example:
logger = hoomd.logging.Logger(categories=['scalar', 'string']) table = hoomd.write.Table(trigger=hoomd.trigger.Periodic(10_000), logger=logger)
- logger¶
The logger to query for output.
Tablesupports only'scalar'and'string'logger categories (read-only).Example:
logger = table.logger
- Type:
- output¶
A file-like object to output the data from. The object must have
writeandflushmethods and amodeattribute (read-only).Example:
output = table.output
- Type:
file-likeobject
- header_sep¶
String to use to separate names in the logger’s namespace (read-only).
Example:
header_sep = table.header_sep
- Type:
- delimiter¶
String used to separate elements in the space delimited file (read-only).
Example:
delimiter = table.delimiter
- Type:
- pretty¶
Flags whether to attempt to make output prettier and easier to read (read-only).
Example:
pretty = table.pretty
- Type:
- max_precision¶
If pretty is not set, then this controls the maximum precision to use when outputing numerical values (read-only).
Example:
max_precision = table.max_precision
- Type:
int, optional
- max_header_len¶
Limits the outputted header names to length
max_header_lenwhen notNone(read-only).Example:
max_header_len = table.max_header_len
- Type:
- min_column_width¶
The minimum allowed column width (read-only).
Example:
min_column_width = table.min_column_width
- Type:
- write()¶
Write out data to
self.output.Writes a row from given
hoomd.logging.Loggerobject data.Example:
table.write()