polyphys.simulate.data#
LAMMPS data files — polyphys.simulate.data#
The data module reads and writes LAMMPS data
files, the input of the read_data command, for molecular systems of
atoms, bonds, and angles. A data file built here serves two ends: a start
configuration that LAMMPS reads and runs, and a topology that analysis tools
such as MDAnalysis read with a dump.
Added in version 0.6.0.
Contents#
DataFile holds the contents of one data file as NumPy arrays, its
box as a Box, and checks them.
read_data() reads a file into it, raising BrokenDataError, a
LammpsFormatError, for a file that does not
follow the format; write_data() writes one out. with_frame()
takes the positions and the box of a dump frame
(DumpFrame) and the rest from a template, to
give a dump its matching topology.
Format#
A data file is a header and a body. The first line is a title and is skipped. The header lines give counts and the box, in any order:
8 atoms
1 atom types
8 bonds
1 bond types
0.0 6.0 xlo xhi
0.0 6.0 ylo yhi
0.0 6.0 zlo zhi
1.0 0.5 -0.5 xy xz yz
The body is a sequence of sections, each a keyword line followed by one line
per entry: Masses (type mass), Atoms (columns by atom style, see
DataFile), Velocities (atom-ID vx vy vz), Bonds
(ID type atom1 atom2), and Angles (ID type atom1 atom2 atom3).
# starts a comment and blank lines are skipped. Atoms # bond names the
atom style in a comment. A file whose name ends in .gz is read through
gzip. Atom lines may end with the three image flags, on
all lines or on none; LAMMPS sets missing image flags and velocities to zero.
Supported atom styles: atomic, bond, angle, molecular, and
full. Sections with names ending in Coeffs (force-field coefficients)
are skipped when read and never written; the input script sets them, as
write_data nocoeff assumes. Dihedrals, impropers, type labels, and
general triclinic boxes are not supported.
The module converts no units; values are in the units of the run.
Complexity#
read_data() and write_data() take \(O(n_a + n_b + n_t)\)
time and memory for \(n_a\) atoms, \(n_b\) bonds, and \(n_t\)
angles; with_frame() takes \(O(n_a \log n_a)\) time to match atom
IDs.
References
The format follows the LAMMPS documentation of read_data and write_data.
Dependencies#
Python standard library: dataclasses, logging, pathlib
Third-party: numpy
PolyPhys:
polyphys.simulate.core,polyphys.simulate.dump
Functions
|
Read a LAMMPS data file. |
|
Return template with the positions and the box of a dump frame. |
|
Write a LAMMPS data file. |
Classes
|
The contents of one LAMMPS data file. |
Exceptions
A LAMMPS data file does not follow the data-file format. |
- exception polyphys.simulate.data.BrokenDataError[source]#
Bases:
polyphys.simulate.core.LammpsFormatErrorA LAMMPS data file does not follow the data-file format.
Added in version 0.6.0.
Examples
>>> import tempfile >>> with tempfile.TemporaryDirectory() as tmp: ... path = Path(tmp) / "empty.data" ... _ = path.write_text("title\n\n2 atoms\n") ... try: ... read_data(path) ... except BrokenDataError as err: ... print(str(err).split(": ", 1)[1]) the file has a header but no body
- class polyphys.simulate.data.DataFile(atom_style, box, ids, types, positions, n_atom_types, masses=None, mol_ids=None, charges=None, image_flags=None, velocities=None, bonds=<factory>, angles=<factory>, n_bond_types=0, n_angle_types=0)[source]#
Bases:
objectThe contents of one LAMMPS data file.
The arrays are copied, made read-only, and checked on construction; use
dataclasses.replace()to change a field.Added in version 0.6.0.
- Variables:
atom_style (
{'atomic', 'bond', 'angle', 'molecular', 'full'}) – The LAMMPS atom style. It sets the Atoms columns:atom-ID atom-type x y zforatomic;atom-ID molecule-ID atom-type x y zforbond,angle, andmolecular; andatom-ID molecule-ID atom-type q x y zforfull.atomichas no bonds,bondno angles.box (
Box) – The simulation box. A triclinic box writes itsxy xz yzline; the boundary flags are not part of a data file.ids (
numpy.ndarray) – Shape(n_atoms,), int64: unique atom IDs, from 1.types (
numpy.ndarray) – Shape(n_atoms,), int64: atom types, from 1 to n_atom_types.positions (
numpy.ndarray) – Shape(n_atoms, 3), float64: coordinates in the length unit of the run. The writer does not check that they lie in the box: LAMMPS remaps an atom outside it across a periodic boundary and loses one outside a non-periodic boundary.n_atom_types (
int) – Number of atom types, 1 or more; a type may be unused.masses (
numpy.ndarrayorNone) – Shape(n_atom_types,): the mass of type \(k\) at index \(k - 1\), or None to write noMassessection and leave the masses to the input script.mol_ids (
numpy.ndarrayorNone) – Shape(n_atoms,), int64: molecule IDs, required by every style butatomicand None for it.charges (
numpy.ndarrayorNone) – Shape(n_atoms,): charges, required byfulland None for the others.image_flags (
numpy.ndarrayorNone) – Shape(n_atoms, 3), int64: image flags, or None to write none (LAMMPS then sets them to zero).velocities (
numpy.ndarrayorNone) – Shape(n_atoms, 3): velocities, or None to write noVelocitiessection (LAMMPS then sets them to zero).bonds (
numpy.ndarray) – Shape(n_bonds, 3), int64:type, atom1, atom2per bond, the atoms by ID. Bond IDs are not kept: the writer numbers bonds from 1 in row order. A ring is a chain with one more bond.angles (
numpy.ndarray) – Shape(n_angles, 4), int64:type, atom1, atom2, atom3per angle, withatom2the vertex.n_angle_types (n_bond_types,) – Numbers of bond and angle types; 1 or more when there are bonds or angles.
- Raises:
ValueError – If the atom style is unknown, an array has the wrong shape or non-integer values where integers are needed, an atom ID repeats or is below 1, a type is out of range, a bond or angle names an atom ID that does not exist, or a field is given that the style does not allow or omitted where it needs one.
- Parameters:
atom_style (str)
box (Box)
ids (NDArray[int64])
types (NDArray[int64])
positions (NDArray[float64])
n_atom_types (int)
masses (NDArray[float64] | None)
mol_ids (NDArray[int64] | None)
charges (NDArray[float64] | None)
image_flags (NDArray[int64] | None)
velocities (NDArray[float64] | None)
bonds (NDArray[int64])
angles (NDArray[int64])
n_bond_types (int)
n_angle_types (int)
Examples
A ring of three beads with a closing bond:
>>> ring = DataFile( ... atom_style="bond", box=Box(lo=np.zeros(3), hi=np.full(3, 10.0)), ... ids=np.arange(1, 4), types=np.ones(3, dtype=int), ... positions=np.array([[5.0, 5.0, 5.0], [6.0, 5.0, 5.0], ... [5.5, 5.9, 5.0]]), ... n_atom_types=1, mol_ids=np.ones(3, dtype=int), ... bonds=np.array([[1, 1, 2], [1, 2, 3], [1, 3, 1]]), n_bond_types=1) >>> ring.n_atoms, ring.n_bonds, ring.n_angles (3, 3, 0)
- angles: numpy.typing.NDArray[numpy.int64]#
- bonds: numpy.typing.NDArray[numpy.int64]#
- charges: numpy.typing.NDArray[numpy.float64] | None = None#
- ids: numpy.typing.NDArray[numpy.int64]#
- image_flags: numpy.typing.NDArray[numpy.int64] | None = None#
- masses: numpy.typing.NDArray[numpy.float64] | None = None#
- mol_ids: numpy.typing.NDArray[numpy.int64] | None = None#
- positions: numpy.typing.NDArray[numpy.float64]#
- types: numpy.typing.NDArray[numpy.int64]#
- unwrapped_positions()[source]#
Return the positions unwrapped by the image flags.
- Returns:
Shape
(n_atoms, 3), float64: the positions moved by the image flags along the box edge vectors, byunwrap(); a copy of the positions when there are no image flags, which LAMMPS reads as zero. Time and memory are \(O(n_a)\).- Return type:
Examples
>>> pair = DataFile( ... atom_style="atomic", ... box=Box(lo=np.zeros(3), hi=np.full(3, 10.0)), ... ids=np.array([1, 2]), types=np.array([1, 1]), ... positions=np.array([[9.5, 5.0, 5.0], [0.5, 5.0, 5.0]]), ... n_atom_types=1, image_flags=np.array([[-1, 0, 0], [0, 0, 0]])) >>> pair.unwrapped_positions() array([[-0.5, 5. , 5. ], [ 0.5, 5. , 5. ]])
- velocities: numpy.typing.NDArray[numpy.float64] | None = None#
- polyphys.simulate.data.read_data(path, atom_style=None)[source]#
Read a LAMMPS data file.
Added in version 0.6.0.
- Parameters:
path (
str|pathlib.Path) – The data file, read as UTF-8; a name ending in.gzis read through gzip.atom_style (
str|None) – The atom style, one of those ofDataFile. Needed when theAtomsline has no style comment such asAtoms # bond; when both are given they must agree.
- Returns:
Atoms sorted by ID; bonds and angles sorted by their IDs, which are then dropped.
- Return type:
- Raises:
BrokenDataError – If the file does not follow the format, uses a feature this module does not support (see the module documentation), or gives no atom style, or two that disagree. The message names the file and, where it can, the line, from 1.
Notes
Sections whose names end in
Coeffsare skipped and logged at level DEBUG. Time and memory are \(O(L)\) in the length \(L\) of the file.Examples
>>> import tempfile >>> text = '''Two beads and one bond ... ... 2 atoms ... 1 atom types ... 1 bonds ... 1 bond types ... 0 5 xlo xhi ... 0 5 ylo yhi ... 0 5 zlo zhi ... ... Bond Coeffs # fene ... ... 1 30.0 1.5 1.0 1.0 ... ... Atoms # bond ... ... 2 1 1 3.0 2.5 2.5 0 0 0 ... 1 1 1 2.0 2.5 2.5 0 0 0 ... ... Bonds ... ... 1 1 1 2 ... ''' >>> with tempfile.TemporaryDirectory() as tmp: ... path = Path(tmp) / "pair.data" ... _ = path.write_text(text) ... data = read_data(path) >>> data.atom_style, data.ids, data.bonds ('bond', array([1, 2]), array([[1, 1, 2]])) >>> data.positions[:, 0] array([2., 3.])
- polyphys.simulate.data.with_frame(template, frame)[source]#
Return template with the positions and the box of a dump frame.
Use it to write the topology that goes with a dump, for analysis: the atoms, types, masses, bonds, and angles come from template, and the positions and box from frame.
Added in version 0.6.0.
- Parameters:
template (
polyphys.simulate.data.DataFile) – A data file of the same system, such as the one the run started from.frame (
polyphys.simulate.dump.DumpFrame) – A frame with anidcolumn and wrapped coordinate columns,x y zor the scaledxs ys zs. Unwrapped columns alone,xu yu zuorxsu ysu zsu, are not accepted.
- Returns:
template with, matched by atom ID: the frame’s wrapped positions; its image flags if it has
ix iy iz, else none; its velocities if it hasvx vy vz, else none; and its box.- Return type:
- Raises:
ValueError – If the frame has no
idcolumn, its atom IDs differ from those of template, or itstypecolumn, when present, disagrees with the template’s types.KeyError – If the frame has no wrapped coordinate columns, as in a dump of unwrapped coordinates only.
Notes
The template’s image flags and velocities belong to its own positions, so they are never carried over. Time is \(O(n_a \log n_a)\), memory \(O(n_a)\).
Examples
>>> template = DataFile( ... atom_style="bond", box=Box(lo=np.zeros(3), hi=np.full(3, 10.0)), ... ids=np.array([1, 2]), types=np.array([1, 1]), ... positions=np.array([[1.0, 5.0, 5.0], [2.0, 5.0, 5.0]]), ... n_atom_types=1, mol_ids=np.array([1, 1]), ... bonds=np.array([[1, 1, 2]]), n_bond_types=1) >>> frame = DumpFrame(timestep=1000, ... box=Box(lo=np.zeros(3), hi=np.full(3, 8.0)), ... columns=("id", "type", "xs", "ys", "zs"), ... data=np.array([[2, 1, 0.5, 0.5, 0.5], ... [1, 1, 0.375, 0.5, 0.5]])) >>> moved = with_frame(template, frame) >>> moved.positions array([[3., 4., 4.], [4., 4., 4.]]) >>> moved.box.hi, moved.bonds (array([8., 8., 8.]), array([[1, 1, 2]]))
- polyphys.simulate.data.write_data(data, path, *, title=None)[source]#
Write a LAMMPS data file.
Added in version 0.6.0.
- Parameters:
data (
polyphys.simulate.data.DataFile) – The contents to write.path (
str|pathlib.Path) – The file to write; an existing file is overwritten.title (
str|None) – The first line, which LAMMPS skips; one line, defaulting to a line that names this module.
- Returns:
path.
- Return type:
- Raises:
ValueError – If title has a line break.
Notes
The header gives
atomsandatom types;bondsandbond typesfor every style with bonds;anglesandangle typesfor every style with angles; the box; andxy xz yzwhen its box is triclinic. Then comeMassesif given,Atoms # <style>with image flags if given,Velocitiesif given, andBondsandAnglesif there are any, numbered from 1. Floats are written as the shortest decimal that reads back to the same float64, soread_data(write_data(data, path))returns data unchanged. No coefficient section is written. Time and memory are \(O(n_a + n_b + n_t)\).Examples
>>> import tempfile >>> pair = DataFile( ... atom_style="atomic", box=Box(lo=np.zeros(3), hi=np.full(3, 5.0)), ... ids=np.array([1, 2]), types=np.array([1, 2]), ... positions=np.array([[2.0, 2.5, 2.5], [3.1, 2.5, 2.5]]), ... n_atom_types=2) >>> with tempfile.TemporaryDirectory() as tmp: ... path = write_data(pair, Path(tmp) / "pair.data", title="Two beads") ... print(path.read_text()) Two beads 2 atoms 2 atom types 0.0 5.0 xlo xhi 0.0 5.0 ylo yhi 0.0 5.0 zlo zhi Atoms # atomic 1 1 2.0 2.5 2.5 2 2 3.1 2.5 2.5