File: test_geometry.py

package info (click to toggle)
mdtraj 1.11.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 79,324 kB
  • sloc: python: 25,216; ansic: 6,266; cpp: 5,685; xml: 1,252; makefile: 192
file content (573 lines) | stat: -rw-r--r-- 17,272 bytes parent folder | download
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
52
53
54
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
90
91
92
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
134
135
136
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
#         Molecular Dynamics Trajectories.
# Copyright 2012-2017 Stanford University and the Authors
#
# Authors: Robert McGibbon
# Contributors:
#
# MDTraj is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with MDTraj. If not, see <http://www.gnu.org/licenses/>.
##############################################################################


import itertools

import numpy as np
import pytest

import mdtraj as md
import mdtraj.geometry
from mdtraj.testing import eq

RUN_PERFORMANCE_TESTS = False


def test_rg(get_fn):
    t0 = md.load(get_fn("traj.h5"))
    Rg = mdtraj.geometry.rg.compute_rg(t0)
    Rg0 = np.loadtxt(get_fn("Rg_traj_ref.dat"))
    eq(Rg, Rg0)


def test_distances(get_fn):
    t0 = md.load(get_fn("traj.h5"))
    atom_pairs = np.loadtxt(get_fn("atom_pairs.dat"), "int")
    distances = mdtraj.geometry.distance.compute_distances(t0, atom_pairs)
    distances0 = np.loadtxt(get_fn("atom_distances_traj_ref.dat"))
    eq(distances, distances0)


def test_center_of_mass():
    top = md.Topology()
    chain = top.add_chain()
    resi = top.add_residue("NA", chain)
    top.add_atom("H1", md.element.hydrogen, resi)
    top.add_atom("H2", md.element.hydrogen, resi)
    top.add_atom("O", md.element.oxygen, resi)

    xyz = np.array(
        [
            [
                # Frame 1 - Right triangle
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0],
            ],
            [
                # Frame 2
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [0.5, 0.5, 0.0],
            ],
        ],
    )
    traj = md.Trajectory(xyz, top)
    com_test = mdtraj.geometry.distance.compute_center_of_mass(traj)

    com_actual = (1 / 18.015324) * np.array(
        [
            [1.007947, 1.007947, 0.0],
            [1.007947 + 0.5 * 15.99943, 1.007947 + 0.5 * 15.99943, 0.0],
        ],
    )

    eq(com_actual, com_test, decimal=4)

    # test with selection string
    com_test = mdtraj.geometry.distance.compute_center_of_mass(traj, select="index 0")

    com_actual = np.array(
        [
            [1.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
        ],
    )

    eq(com_actual, com_test, decimal=4)


def test_center_of_geometry():
    top = md.Topology()
    chain = top.add_chain()
    resi = top.add_residue("NA", chain)
    top.add_atom("H1", md.element.hydrogen, resi)
    top.add_atom("H2", md.element.hydrogen, resi)
    top.add_atom("O", md.element.oxygen, resi)

    xyz = np.array(
        [
            [
                # Frame 1 - Right triangle
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0],
            ],
            [
                # Frame 2
                [1.0, 0.0, 0.0],
                [0.0, 1.0, 0.0],
                [0.5, 0.5, 0.0],
            ],
        ],
    )
    traj = md.Trajectory(xyz, top)
    center_test = mdtraj.geometry.distance.compute_center_of_geometry(traj)

    center_actual = np.array(
        [
            [1.0 / 3, 1.0 / 3, 0.0],
            [1.5 / 3, 1.5 / 3, 0.0],
        ],
    )

    eq(center_actual, center_test, decimal=4)


def test_dihedral_indices(get_fn):
    traj = md.load(get_fn("1bpi.pdb"))
    # Manually compare generated indices to known answers.
    phi0_ind = np.array([3, 12, 13, 14]) - 1  # Taken from PDB, so subtract 1
    psi0_ind = np.array([1, 2, 3, 12]) - 1  # Taken from PDB, so subtract 1

    ind = mdtraj.geometry.dihedral.indices_phi(traj.topology)
    eq(ind[0], phi0_ind)

    ind = mdtraj.geometry.dihedral.indices_psi(traj.topology)
    eq(ind[0], psi0_ind)


def test_dihedral_index_offset_generation(get_fn):
    traj = md.load(get_fn("1bpi.pdb"))
    top = traj.topology

    # The atom indices of the first phi angle
    result = np.array([2, 11, 12, 13])
    print([e.name for e in traj.topology.atoms])
    ind1 = mdtraj.geometry.dihedral.indices_phi(top)
    rid2, ind2 = mdtraj.geometry.dihedral._atom_sequence(top, ["-C", "N", "CA", "C"])
    rid3, ind3 = mdtraj.geometry.dihedral._atom_sequence(
        top,
        ["-C", "N", "CA", "C"],
        [-1, 0, 0, 0],
    )
    rid4, ind4 = mdtraj.geometry.dihedral._atom_sequence(
        top,
        ["C", "N", "CA", "C"],
        [-1, 0, 0, 0],
    )

    eq(ind1, ind2)
    eq(ind1, ind3)
    eq(ind1, ind4)
    eq(ind1[0], result)


def test_dihedral_0(get_fn):
    """We compared phi and psi angles from pymol to MDTraj output."""
    traj = md.load(get_fn("1bpi.pdb"))[0]
    indices, phi = mdtraj.geometry.dihedral.compute_phi(traj)
    phi0 = np.array([-34.50956, -50.869690]) * np.pi / 180.0  # Pymol
    eq(phi[0, 0:2], phi0, decimal=4)
    eq(indices[0], np.array([2, 11, 12, 13]))

    indices, psi = mdtraj.geometry.dihedral.compute_psi(traj)
    psi0 = np.array([134.52554, 144.880173]) * np.pi / 180.0  # Pymol
    eq(psi[0, 0:2], psi0, decimal=4)
    eq(indices[0], np.array([0, 1, 2, 11]))

    indices, chi = mdtraj.geometry.dihedral.compute_chi1(traj)
    chi0 = np.array([-43.37841, -18.14592]) * np.pi / 180.0  # Pymol
    eq(chi[0, 0:2], chi0, decimal=4)
    eq(indices[0], np.array([0, 1, 4, 5]))


def test_dihedral_1():
    n_atoms = 4
    np.random.seed(42)
    xyz = np.random.randn(5, n_atoms, 3)
    t = md.Trajectory(xyz=xyz, topology=None)
    indices = list(itertools.combinations(range(n_atoms), 4))
    r1 = md.geometry.compute_dihedrals(t, indices, opt=False)
    r2 = md.geometry.compute_dihedrals(t, indices, opt=True)
    eq(r1, r2)


def test_dihedral_triclinic():
    n_atoms = 4
    np.random.seed(42)
    xyz = np.random.randn(5, n_atoms, 3)
    t = md.Trajectory(
        xyz=xyz,
        topology=None,
        unitcell_lengths=np.outer(np.ones(5), np.array([1.5, 1.5, 1.5])),
        unitcell_angles=np.outer(np.ones(5), np.array([95, 100, 110])),
    )
    indices = list(itertools.combinations(range(n_atoms), 4))
    r1 = md.geometry.compute_dihedrals(t, indices, opt=False)
    r2 = md.geometry.compute_dihedrals(t, indices, opt=True)
    eq(r1, r2)


def test_angle_0():
    xyz = np.array(
        [
            [
                [0, 0, 0],
                [0, 1, 0],
                [1, 1, 0],
            ],
        ],
    )
    t = md.Trajectory(xyz=xyz, topology=None)
    result = np.array(np.pi / 2).reshape(1, 1)
    eq(result, md.geometry.compute_angles(t, [[0, 1, 2]], opt=False))
    eq(result, md.geometry.compute_angles(t, [[0, 1, 2]], opt=True))


def test_angle_periodic_0():
    xyz = np.array(
        [
            [
                [0, 0, 0],
                [0, 1, 0],
                [1, 1, 0],
            ],
        ],
    )
    t = md.Trajectory(
        xyz=xyz,
        topology=None,
        unitcell_lengths=np.array([10, 10, 10]),
        unitcell_angles=np.array([90, 90, 90]),
    )
    result = np.array(np.pi / 2).reshape(1, 1)
    eq(result, md.geometry.compute_angles(t, [[0, 1, 2]], opt=False))
    eq(result, md.geometry.compute_angles(t, [[0, 1, 2]], opt=True))


def test_angle_triclinic_0():
    xyz = np.array(
        [
            [
                [0, 0, 0],
                [0, 1, 0],
                [1, 1, 0],
            ],
        ],
    )
    t = md.Trajectory(
        xyz=xyz,
        topology=None,
        unitcell_lengths=np.array([1.5, 1.5, 1.5]),
        unitcell_angles=np.array([95, 100, 110]),
    )
    eq(
        md.geometry.compute_angles(t, [[0, 1, 2]], opt=False),
        md.geometry.compute_angles(t, [[0, 1, 2]], opt=True),
    )


def test_angle_1():
    # the two routines sometimes give slightly different answers for
    # wierd angles really close to 0 or 180. I suspect this is because
    # different implementations of acos -- which are basically implemented
    # taylor series expansions -- are parameterized slightly differently on
    # different libraries/platforms. setting the random number seed helps to
    # ensure that this doesn't break stochastically too often.

    n_atoms = 5
    np.random.seed(24)
    xyz = np.random.randn(50, n_atoms, 3)
    t = md.Trajectory(xyz=xyz, topology=None)
    indices = list(itertools.combinations(range(n_atoms), 3))
    r1 = md.geometry.compute_angles(t, indices, opt=False)
    r2 = md.geometry.compute_angles(t, indices, opt=True)
    assert np.max(np.abs(r1 - r2)) < 1e-2
    assert np.nansum(np.abs(r1 - r2)) / r1.size < 5e-4


@pytest.mark.skipif(not RUN_PERFORMANCE_TESTS, reason="Not doing performance testing")
def test_dihedral_performance():
    n_atoms = 10
    xyz = np.random.randn(5000, n_atoms, 3)
    t = md.Trajectory(xyz=xyz, topology=None)
    indices = np.asarray(
        list(itertools.combinations(range(n_atoms), 4)),
        dtype=np.int32,
    )
    import time

    t1 = time.time()
    md.geometry.compute_dihedrals(t, indices, opt=False)
    t2 = time.time()
    md.geometry.compute_dihedrals(t, indices, opt=True)
    t3 = time.time()

    print("\ndihedral performance:")
    print("numpy:   %f s" % (t2 - t1))
    print("opt sse: %f s" % (t3 - t2))


@pytest.mark.skipif(not RUN_PERFORMANCE_TESTS, reason="Not doing performance testing")
def test_angle_performance():
    n_atoms = 20
    xyz = np.random.randn(10000, n_atoms, 3)
    t = md.Trajectory(xyz=xyz, topology=None)
    indices = np.asarray(
        list(itertools.combinations(range(n_atoms), 3)),
        dtype=np.int32,
    )
    import time

    t1 = time.time()
    _ = md.geometry.compute_angles(t, indices, opt=False)
    t2 = time.time()
    _ = md.geometry.compute_angles(t, indices, opt=True)
    t3 = time.time()

    print("\nangle performance:")
    print("numpy:   %f s" % (t2 - t1))
    print("opt sse: %f s" % (t3 - t2))


def test_angle_nan():
    t = md.Trajectory(
        topology=None,
        xyz=np.array(
            [
                [0, 0, 0.2],
                [0, 0, 0.3],
                [0, 0, 0.0],
            ],
        ),
    )
    angles = md.compute_angles(t, [[0, 1, 2]], opt=True)
    np.testing.assert_array_almost_equal(angles, [[0]])


def test_angle_pbc(get_fn):
    traj_uncorrected = md.load(
        get_fn("1am7_uncorrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )
    traj_corrected = md.load(
        get_fn("1am7_corrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )

    indices = []
    for i in range(traj_uncorrected.n_residues):
        r = traj_uncorrected.topology.residue(i)
        indices.append((r.atom(0).index, r.atom(1).index, r.atom(2).index))

    epsilon = 6e-3

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=False,
        periodic=True,
    )
    ang2 = md.geometry.compute_angles(traj_corrected, indices, opt=False, periodic=True)
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=True,
        periodic=True,
    )
    ang2 = md.geometry.compute_angles(traj_corrected, indices, opt=True, periodic=True)
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=True,
        periodic=True,
    )
    ang2 = md.geometry.compute_angles(traj_corrected, indices, opt=True, periodic=False)
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=False,
        periodic=True,
    )
    ang2 = md.geometry.compute_angles(
        traj_corrected,
        indices,
        opt=False,
        periodic=False,
    )
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=True,
        periodic=True,
    )
    ang2 = md.geometry.compute_angles(
        traj_corrected,
        indices,
        opt=False,
        periodic=False,
    )
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=False,
        periodic=True,
    )
    ang2 = md.geometry.compute_angles(traj_corrected, indices, opt=True, periodic=False)
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=False,
        periodic=True,
    )
    ang2 = md.geometry.compute_angles(traj_corrected, indices, opt=True, periodic=True)
    assert np.max(np.abs(ang1 - ang2)) < epsilon


def test_dihedral_pbc(get_fn):
    traj_uncorrected = md.load(
        get_fn("1am7_uncorrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )
    traj_corrected = md.load(
        get_fn("1am7_corrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )

    epsilon = 6e-3

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=False, periodic=True)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=False, periodic=True)[1]
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=True, periodic=True)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=True, periodic=True)[1]
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=True, periodic=True)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=True, periodic=False)[1]
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=False, periodic=True)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=False, periodic=False)[1]
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=True, periodic=True)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=False, periodic=False)[1]
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=False, periodic=True)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=True, periodic=True)[1]
    assert np.max(np.abs(ang1 - ang2)) < epsilon

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=False, periodic=True)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=True, periodic=False)[1]
    assert np.max(np.abs(ang1 - ang2)) < epsilon


def test_dihedral_pbc_fails1(get_fn):
    traj_uncorrected = md.load(
        get_fn("1am7_uncorrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )
    traj_corrected = md.load(
        get_fn("1am7_corrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )

    epsilon = 1e-2

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=False, periodic=False)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=False, periodic=False)[1]
    assert not (np.max(np.abs(ang1 - ang2)) < epsilon)


def test_dihedral_pbc_fails2(get_fn):
    traj_uncorrected = md.load(
        get_fn("1am7_uncorrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )
    traj_corrected = md.load(
        get_fn("1am7_corrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )

    epsilon = 1e-2

    ang1 = md.geometry.compute_phi(traj_uncorrected, opt=True, periodic=False)[1]
    ang2 = md.geometry.compute_phi(traj_corrected, opt=True, periodic=False)[1]
    assert not (np.max(np.abs(ang1 - ang2)) < epsilon)


def test_angle_pbc_fails1(get_fn):
    traj_uncorrected = md.load(
        get_fn("1am7_uncorrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )
    indices = []
    for i in range(traj_uncorrected.n_residues):
        r = traj_uncorrected.topology.residue(i)
        indices.append((r.atom(0).index, r.atom(1).index, r.atom(2).index))
    traj_corrected = md.load(
        get_fn("1am7_corrected.xtc"),
        top=get_fn("1am7_protein.pdb"),
    )

    epsilon = 1e-2

    ang1 = md.geometry.compute_angles(
        traj_uncorrected,
        indices,
        opt=False,
        periodic=False,
    )
    ang2 = md.geometry.compute_angles(
        traj_corrected,
        indices,
        opt=False,
        periodic=False,
    )
    assert not (np.max(np.abs(ang1 - ang2)) < epsilon)


def test_no_indices(get_fn):
    for fn in ["2EQQ.pdb", "1bpi.pdb"]:
        for opt in [True, False]:
            t = md.load(get_fn(fn))
            assert md.compute_distances(
                t,
                np.zeros((0, 2), dtype=int),
                opt=opt,
            ).shape == (t.n_frames, 0)
            assert md.compute_angles(t, np.zeros((0, 3), dtype=int), opt=opt).shape == (
                t.n_frames,
                0,
            )
            assert md.compute_dihedrals(
                t,
                np.zeros((0, 4), dtype=int),
                opt=opt,
            ).shape == (t.n_frames, 0)