TestXtcFile.py 9.33 KB
Newer Older
Raul's avatar
Raul committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
__author__ = "Raul P. Pelaez"
import sys
import os
import unittest
from openmm import unit
import tempfile
from openmm import app
from random import random
import openmm as mm
import numpy as np
from openmm.app.internal.xtc_utils import read_xtc

class TestXtcFile(unittest.TestCase):
    def test_xtc_triclinic(self):
        """Test the XTC file by writing a trajectory and reading it back. Using a triclinic box"""
        with tempfile.TemporaryDirectory() as temp:
            fname = os.path.join(temp, 'traj.xtc')
            pdbfile = app.PDBFile("systems/alanine-dipeptide-implicit.pdb")
            # Set some arbitrary size for the unit cell so that a box is included in the trajectory
            pdbfile.topology.setUnitCellDimensions([10, 10, 10])
            natom = len(list(pdbfile.topology.atoms()))
            nframes = 20
            xtc = app.XTCFile(fname, pdbfile.topology, 0.001)
            coords = []
            box = []
            for i in range(nframes):
                coords.append(
                    [mm.Vec3(random(), random(), random()) for j in range(natom)]
                    * unit.nanometers
                )
                box_i = (
                    mm.Vec3(random(), random(), random()) * unit.nanometers,
                    mm.Vec3(random(), random(), random()) * unit.nanometers,
                    mm.Vec3(random(), random(), random()) * unit.nanometers,
                )
                box.append(np.array([[vec.x, vec.y, vec.z] for vec in box_i]))
                xtc.writeModel(coords[i], periodicBoxVectors=box_i)
            # The  XTCFile class  does not  provide a  way to  read the
            # trajectory back, but the underlying XTC library does
            coords_read, box_read, time, step = read_xtc(fname.encode("utf-8"))
            self.assertEqual(coords_read.shape, (natom, 3, nframes))
            self.assertEqual(box_read.shape, (3, 3, nframes))
            self.assertEqual(len(time), nframes)
            self.assertEqual(len(step), nframes)
            coords = np.array(
                [c.value_in_unit(unit.nanometers) for c in coords]
            ).transpose(1, 2, 0)
            self.assertTrue(np.allclose(coords_read, coords, atol=1e-3))
            box = np.array(box).transpose(1, 2, 0)
            self.assertTrue(np.allclose(box_read, box, atol=1e-3))
            self.assertTrue(
52
                np.allclose(time, np.arange(0, nframes) * 0.001, atol=1e-5)
Raul's avatar
Raul committed
53
            )
54
            self.assertTrue(np.allclose(step, np.arange(0, nframes), atol=1e-5))
Raul's avatar
Raul committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

    def test_xtc_cubic(self):
        """Test the XTC file by writing a trajectory and reading it back. Using a cubic box"""
        with tempfile.TemporaryDirectory() as temp:
            fname = os.path.join(temp, 'traj.xtc')
            pdbfile = app.PDBFile("systems/alanine-dipeptide-implicit.pdb")
            # Set some arbitrary size for the unit cell so that a box is included in the trajectory
            pdbfile.topology.setUnitCellDimensions([10, 10, 10])
            natom = len(list(pdbfile.topology.atoms()))
            nframes=20
            xtc = app.XTCFile(fname, pdbfile.topology, 0.001)
            coords = []
            box = []
            for i in range(nframes):
                coords.append(
                    [mm.Vec3(random(), random(), random()) for j in range(natom)]
                    * unit.nanometers
                )
                box_i = mm.Vec3(random(), random(), random()) * unit.nanometers
                box.append(np.diag(box_i[:3].value_in_unit(unit.nanometers)))
                xtc.writeModel(coords[i], unitCellDimensions=box_i)
            #The  XTCFile class  does not  provide a  way to  read the
            #trajectory back, but the underlying XTC library does
            coords_read, box_read, time, step = read_xtc(fname.encode("utf-8"))
            self.assertEqual(coords_read.shape, (natom,3,nframes))
            self.assertEqual(box_read.shape, (3,3,nframes))
            self.assertEqual(len(time), nframes)
            self.assertEqual(len(step), nframes)
            coords = np.array(
                [c.value_in_unit(unit.nanometers) for c in coords]
            ).transpose(1, 2, 0)
            self.assertTrue(np.allclose(coords_read, coords, atol=1e-3))
            box = np.array(box).transpose(1, 2, 0)
            self.assertTrue(np.allclose(box_read, box, atol=1e-3))
            self.assertTrue(
90
                np.allclose(time, np.arange(0, nframes) * 0.001, atol=1e-5)
Raul's avatar
Raul committed
91
            )
92
            self.assertTrue(np.allclose(step, np.arange(0, nframes), atol=1e-5))
Raul's avatar
Raul committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

    def test_xtc_box_from_topology(self):
        """Test the XTC file by writing a trajectory and reading it back. Letting the box be set from the topology"""
        with tempfile.TemporaryDirectory() as temp:
            fname = os.path.join(temp, 'traj.xtc')
            pdbfile = app.PDBFile("systems/alanine-dipeptide-implicit.pdb")
            # Set some arbitrary size for the unit cell so that a box is included in the trajectory
            unitCell = mm.Vec3(random(), random(), random()) * unit.nanometers
            pdbfile.topology.setUnitCellDimensions(unitCell)
            natom = len(list(pdbfile.topology.atoms()))
            nframes = 20
            xtc = app.XTCFile(fname, pdbfile.topology, 0.001)
            coords = []
            for i in range(nframes):
                coords.append(
                    [mm.Vec3(random(), random(), random()) for j in range(natom)]
                    * unit.nanometers
                )
                xtc.writeModel(coords[i])
            # The  XTCFile class  does not  provide a  way to  read the
            # trajectory back, but the underlying XTC library does
            coords_read, box_read, time, step = read_xtc(fname.encode("utf-8"))
            self.assertEqual(coords_read.shape, (natom, 3, nframes))
            self.assertEqual(box_read.shape, (3, 3, nframes))
            self.assertEqual(len(time), nframes)
            self.assertEqual(len(step), nframes)
            coords = np.array(
                [c.value_in_unit(unit.nanometers) for c in coords]
            ).transpose(1, 2, 0)
            self.assertTrue(np.allclose(coords_read, coords, atol=1e-3))
            boxVectors = (
                mm.Vec3(unitCell[0].value_in_unit(unit.nanometers), 0, 0),
                mm.Vec3(0, unitCell[1].value_in_unit(unit.nanometers), 0),
                mm.Vec3(0, 0, unitCell[2].value_in_unit(unit.nanometers)),
            )
            boxVectors = np.array(
                [[vec.x, vec.y, vec.z] for vec in boxVectors], dtype=np.float32
            )
            box = np.array(np.tile(boxVectors, (nframes, 1, 1))).transpose(1, 2, 0)
            self.assertTrue(np.allclose(box_read, box, atol=1e-3))
            self.assertTrue(
134
                np.allclose(time, np.arange(0, nframes) * 0.001, atol=1e-5)
Raul's avatar
Raul committed
135
            )
136
            self.assertTrue(np.allclose(step, np.arange(0, nframes), atol=1e-5))
Raul's avatar
Raul committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

    def testLongTrajectory(self):
        """Test writing a trajectory that has more than 2^31 steps."""
        with tempfile.TemporaryDirectory() as temp:
            fname = os.path.join(temp, 'traj.xtc')
            pdbfile = app.PDBFile("systems/alanine-dipeptide-implicit.pdb")
            natom = len(list(pdbfile.topology.atoms()))
            xtc = app.XTCFile(fname, pdbfile.topology, 0.001, interval=1000000000)
            for i in range(5):
                xtc.writeModel(
                    [mm.Vec3(random(), random(), random()) for j in range(natom)]
                    * unit.angstroms
                )

    def testAppend(self):
        """Test appending to an existing trajectory."""
        with tempfile.TemporaryDirectory() as temp:
            fname = os.path.join(temp, 'traj.xtc')
            pdb = app.PDBFile("systems/alanine-dipeptide-implicit.pdb")
            ff = app.ForceField("amber99sb.xml", "tip3p.xml")
            system = ff.createSystem(pdb.topology)

            # Create a simulation and write some frames to a XTC file.

            integrator = mm.VerletIntegrator(0.001 * unit.picoseconds)
            simulation = app.Simulation(
                pdb.topology,
                system,
                integrator,
Peter Eastman's avatar
Peter Eastman committed
166
                mm.Platform.getPlatform("Reference"),
Raul's avatar
Raul committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
            )
            xtc = app.XTCReporter(fname, 2)
            simulation.reporters.append(xtc)
            simulation.context.setPositions(pdb.positions)
            simulation.context.setVelocitiesToTemperature(300 * unit.kelvin)
            simulation.step(10)
            self.assertEqual(5, xtc._xtc._modelCount)
            self.assertEqual(5, xtc._xtc._getNumFrames())
            del simulation
            del xtc

            # Create a new simulation and have it append some more frames.

            integrator = mm.VerletIntegrator(0.001 * unit.picoseconds)
            simulation = app.Simulation(
                pdb.topology,
                system,
                integrator,
Peter Eastman's avatar
Peter Eastman committed
185
                mm.Platform.getPlatform("Reference"),
Raul's avatar
Raul committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
            )
            xtc = app.XTCReporter(fname, 2, append=True)
            simulation.reporters.append(xtc)
            simulation.context.setPositions(pdb.positions)
            simulation.context.setVelocitiesToTemperature(300 * unit.kelvin)
            simulation.step(10)
            self.assertEqual(10, xtc._xtc._modelCount)
            self.assertEqual(10, xtc._xtc._getNumFrames())
            del simulation
            del xtc


if __name__ == "__main__":
    unittest.main()