dcdfile.py 8.77 KB
Newer Older
1
2
"""
dcdfile.py: Used for writing DCD files.
3
4
5
6
7
8

This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roadmap for
Medical Research, grant U54 GM072970. See https://simtk.org.

9
Portions copyright (c) 2012-2025 Stanford University and the Authors.
10
11
12
Authors: Peter Eastman
Contributors:

Justin MacCallum's avatar
Justin MacCallum committed
13
Permission is hereby granted, free of charge, to any person obtaining a
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
30
"""
31
from __future__ import absolute_import
32
33
34
35
36
37
38
__author__ = "Peter Eastman"
__version__ = "1.0"

import array
import os
import time
import struct
39
import math
Peter Eastman's avatar
Peter Eastman committed
40
from openmm.unit import picoseconds, nanometers, is_quantity, norm
41
42
from openmm import Vec3
from openmm.app.internal.unitcell import computeLengthsAndAngles
43

44
45
class DCDFile(object):
    """DCDFile provides methods for creating DCD files.
Justin MacCallum's avatar
Justin MacCallum committed
46

47
48
49
50
51
    DCD is a file format for storing simulation trajectories.  It is supported by many programs, such
    as CHARMM, NAMD, and X-PLOR.  Note, however, that different programs produce subtly different
    versions of the format.  This class generates the CHARMM version.  Also note that there is no
    standard byte ordering (big-endian or little-endian) for this format.  This class always generates
    files with little-endian ordering.
Justin MacCallum's avatar
Justin MacCallum committed
52

53
    To use this class, create a DCDFile object, then call writeModel() once for each model in the file."""
Justin MacCallum's avatar
Justin MacCallum committed
54

peastman's avatar
peastman committed
55
56
    def __init__(self, file, topology, dt, firstStep=0, interval=1, append=False):
        """Create a DCD file and write out the header, or open an existing file to append.
Justin MacCallum's avatar
Justin MacCallum committed
57

Robert McGibbon's avatar
Robert McGibbon committed
58
59
60
61
62
63
64
65
66
67
68
69
70
        Parameters
        ----------
        file : file
            A file to write to
        topology : Topology
            The Topology defining the molecular system being written
        dt : time
            The time step used in the trajectory
        firstStep : int=0
            The index of the first step in the trajectory
        interval : int=1
            The frequency (measured in time steps) at which states are written
            to the trajectory
peastman's avatar
peastman committed
71
72
        append : bool=False
            If True, open an existing DCD file to append to.  If False, create a new file.
73
74
75
76
77
78
79
80
81
        """
        self._file = file
        self._topology = topology
        self._firstStep = firstStep
        self._interval = interval
        self._modelCount = 0
        if is_quantity(dt):
            dt = dt.value_in_unit(picoseconds)
        dt /= 0.04888821
82
        self._dt = dt
83
84
85
        boxFlag = 0
        if topology.getUnitCellDimensions() is not None:
            boxFlag = 1
peastman's avatar
peastman committed
86
        if append:
87
88
89
90
91
            file.seek(0, os.SEEK_SET)
            headerBytes = struct.unpack('<i', file.read(4))[0]
            headerMagic = file.read(4)
            if headerBytes != 84 or headerMagic != b'CORD':
                raise ValueError('Cannot append to DCD file with invalid header')
peastman's avatar
peastman committed
92
            self._modelCount = struct.unpack('<i', file.read(4))[0]
93
94
95
            file.seek(92, os.SEEK_SET)
            commentsBytes = struct.unpack('<i', file.read(4))[0]
            file.seek(104 + commentsBytes, os.SEEK_SET)
peastman's avatar
peastman committed
96
            numAtoms = struct.unpack('<i', file.read(4))[0]
97
            if numAtoms != topology.getNumAtoms():
98
                raise ValueError(f'Cannot append from system with {topology.getNumAtoms()} atoms to DCD file with {numAtoms} atoms')
peastman's avatar
peastman committed
99
100
        else:
            header = struct.pack('<i4c9if', 84, b'C', b'O', b'R', b'D', 0, firstStep, interval, 0, 0, 0, 0, 0, 0, dt)
101
            header += struct.pack('<13i', boxFlag, 0, 0, 0, 0, 0, 0, 0, 0, 24, 84, 164, 2)
peastman's avatar
peastman committed
102
103
            header += struct.pack('<80s', b'Created by OpenMM')
            header += struct.pack('<80s', b'Created '+time.asctime(time.localtime(time.time())).encode('ascii'))
104
            header += struct.pack('<4i', 164, 4, topology.getNumAtoms(), 4)
peastman's avatar
peastman committed
105
            file.write(header)
Justin MacCallum's avatar
Justin MacCallum committed
106

107
    def writeModel(self, positions, unitCellDimensions=None, periodicBoxVectors=None):
108
        """Write out a model to the DCD file.
Justin MacCallum's avatar
Justin MacCallum committed
109

Robert McGibbon's avatar
Robert McGibbon committed
110
111
112
113
114
115
        The periodic box can be specified either by the unit cell dimensions
        (for a rectangular box), or the full set of box vectors (for an
        arbitrary triclinic box).  If neither is specified, the box vectors
        specified in the Topology will be used. Regardless of the value
        specified, no dimensions will be written if the Topology does not
        represent a periodic system.
116

Robert McGibbon's avatar
Robert McGibbon committed
117
118
119
120
121
122
123
124
        Parameters
        ----------
        positions : list
            The list of atomic positions to write
        unitCellDimensions : Vec3=None
            The dimensions of the crystallographic unit cell.
        periodicBoxVectors : tuple of Vec3=None
            The vectors defining the periodic box.
125
        """
Raul's avatar
Raul committed
126
        if self._topology.getNumAtoms() != len(positions):
Justin MacCallum's avatar
Justin MacCallum committed
127
            raise ValueError('The number of positions must match the number of atoms')
128
129
        if is_quantity(positions):
            positions = positions.value_in_unit(nanometers)
130
        import numpy as np
131
        positions = np.asarray(positions)
132
        if np.isnan(positions).any():
133
            raise ValueError('Particle position is NaN.  For more information, see https://github.com/openmm/openmm/wiki/Frequently-Asked-Questions#nan')
134
        if np.isinf(positions).any():
135
            raise ValueError('Particle position is infinite.  For more information, see https://github.com/openmm/openmm/wiki/Frequently-Asked-Questions#nan')
136
        file = self._file
Justin MacCallum's avatar
Justin MacCallum committed
137

138
139
140
141
142
143
144
145
146
147
148
        self._modelCount += 1
        if self._interval > 1 and self._firstStep+self._modelCount*self._interval > 1<<31:
            # This will exceed the range of a 32 bit integer.  To avoid crashing or producing a corrupt file,
            # update the header to say the trajectory consisted of a smaller number of larger steps (so the
            # total trajectory length remains correct).
            self._firstStep //= self._interval
            self._dt *= self._interval
            self._interval = 1
            file.seek(0, os.SEEK_SET)
            file.write(struct.pack('<i4c9if', 84, b'C', b'O', b'R', b'D', 0, self._firstStep, self._interval, 0, 0, 0, 0, 0, 0, self._dt))

149
        # Update the header.
Justin MacCallum's avatar
Justin MacCallum committed
150

151
152
153
        file.seek(8, os.SEEK_SET)
        file.write(struct.pack('<i', self._modelCount))
        file.seek(20, os.SEEK_SET)
154
        file.write(struct.pack('<i', self._firstStep+(self._modelCount-1)*self._interval))
155
        # Write the data.
Justin MacCallum's avatar
Justin MacCallum committed
156

157
        file.seek(0, os.SEEK_END)
158
159
        boxVectors = self._topology.getPeriodicBoxVectors()
        if boxVectors is not None:
160
161
            if periodicBoxVectors is not None:
                boxVectors = periodicBoxVectors
162
163
164
165
166
            elif unitCellDimensions is not None:
                if is_quantity(unitCellDimensions):
                    unitCellDimensions = unitCellDimensions.value_in_unit(nanometers)
                boxVectors = (Vec3(unitCellDimensions[0], 0, 0), Vec3(0, unitCellDimensions[1], 0), Vec3(0, 0, unitCellDimensions[2]))*nanometers
            (a_length, b_length, c_length, alpha, beta, gamma) = computeLengthsAndAngles(boxVectors)
167
168
169
            a_length = a_length * 10.  # computeLengthsAndAngles returns unitless nanometers, but need angstroms here.
            b_length = b_length * 10.  # computeLengthsAndAngles returns unitless nanometers, but need angstroms here.
            c_length = c_length * 10.  # computeLengthsAndAngles returns unitless nanometers, but need angstroms here.
170
171
172
173
            angle1 = math.sin(math.pi/2-gamma)
            angle2 = math.sin(math.pi/2-beta)
            angle3 = math.sin(math.pi/2-alpha)
            file.write(struct.pack('<i6di', 48, a_length, angle1, b_length, angle2, angle3, c_length, 48))
174
175
176
177
178
179
        length = struct.pack('<i', 4*len(positions))
        for i in range(3):
            file.write(length)
            data = array.array('f', (10*x[i] for x in positions))
            data.tofile(file)
            file.write(length)
peastman's avatar
peastman committed
180
181
182
183
        try:
            file.flush()
        except AttributeError:
            pass