-
Notifications
You must be signed in to change notification settings - Fork 673
/
Copy pathtest_atomgroup.py
1780 lines (1488 loc) · 68.7 KB
/
test_atomgroup.py
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
from glob import glob
import itertools
from os import path
import numpy as np
from numpy.testing import (
assert_almost_equal,
assert_equal,
assert_array_almost_equal,
)
import MDAnalysis as mda
from MDAnalysis.exceptions import DuplicateWarning, NoDataError
from MDAnalysis.lib import distances, transformations
from MDAnalysis.core.topologyobjects import (
Bond,
Angle,
Dihedral,
ImproperDihedral,
)
from MDAnalysisTests.datafiles import (
PSF, DCD,
TRZ_psf, TRZ,
two_water_gro,
TPR_xvf, TRR_xvf,
GRO
)
from MDAnalysisTests import make_Universe, no_deprecated_call
from MDAnalysisTests.core.util import UnWrapUniverse
import pytest
class TestAtomGroupToTopology(object):
"""Test the conversion of AtomGroup to TopologyObjects"""
@pytest.fixture()
def u(self):
return mda.Universe(PSF, DCD)
def test_bond(self, u):
ag = u.atoms[:2]
bond = ag.bond
assert isinstance(bond, Bond)
def test_angle(self, u):
ag = u.atoms[:3]
angle = ag.angle
assert isinstance(angle, Angle)
def test_dihedral(self, u):
ag = u.atoms[:4]
dih = ag.dihedral
assert isinstance(dih, Dihedral)
def test_improper(self, u):
ag = u.atoms[:4]
imp = ag.improper
assert isinstance(imp, ImproperDihedral)
@pytest.mark.parametrize('btype,', [
'bond',
'angle',
'dihedral',
'improper'
])
def test_VE(self, btype, u):
ag = u.atoms[:10]
with pytest.raises(ValueError):
getattr(ag, btype)
class TestAtomGroupWriting(object):
@pytest.fixture()
def u(self):
return mda.Universe(PSF, DCD)
def test_write_no_args(self, u, tmpdir):
with tmpdir.as_cwd():
u.atoms.write()
files = glob('*')
assert len(files) == 1
name = path.splitext(path.basename(DCD))[0]
assert_equal(files[0], "{}_0.pdb".format(name))
def test_raises_unknown_format(self, u, tmpdir):
with tmpdir.as_cwd():
with pytest.raises(ValueError):
u.atoms.write('useless.format123')
def test_write_coordinates(self, u, tmpdir):
with tmpdir.as_cwd():
u.atoms.write("test.xtc")
@pytest.mark.parametrize('frames', (
[4],
[2, 3, 3, 1],
slice(2, 6, 1),
))
def test_write_frames(self, u, tmpdir, frames):
destination = str(tmpdir / 'test.dcd')
selection = u.trajectory[frames]
ref_positions = np.stack([ts.positions for ts in selection])
u.atoms.write(destination, frames=frames)
u_new = mda.Universe(destination)
new_positions = np.stack([ts.positions for ts in u_new.trajectory])
assert_array_almost_equal(new_positions, ref_positions)
@pytest.mark.parametrize('frames', (
[4],
[2, 3, 3, 1],
slice(2, 6, 1),
))
def test_write_frame_iterator(self, u, tmpdir, frames):
destination = str(tmpdir / 'test.dcd')
selection = u.trajectory[frames]
ref_positions = np.stack([ts.positions for ts in selection])
u.atoms.write(destination, frames=selection)
u_new = mda.Universe(destination)
new_positions = np.stack([ts.positions for ts in u_new.trajectory])
assert_array_almost_equal(new_positions, ref_positions)
@pytest.mark.parametrize('extension', ('xtc', 'dcd', 'pdb', 'xyz', 'PDB'))
def test_write_frame_none(self, u, tmpdir, extension):
destination = str(tmpdir / 'test.' + extension)
u.atoms.write(destination, frames=None)
u_new = mda.Universe(destination)
new_positions = np.stack([ts.positions for ts in u_new.trajectory])
# Most format only save 3 decimals; XTC even has only 2.
assert_array_almost_equal(
u.atoms.positions[None, ...], new_positions, decimal=2
)
@pytest.mark.parametrize('extension', ('xtc', 'dcd', 'pdb', 'xyz', 'PDB'))
def test_compressed_write_frame_none(self, u, tmpdir, extension):
for ext in ('.gz', '.bz2'):
destination = str(tmpdir / 'test.' + extension + ext)
u.atoms.write(destination, frames=None)
u_new = mda.Universe(destination)
new_positions = np.stack([ts.positions for ts in u_new.trajectory])
assert_array_almost_equal(
u.atoms.positions[None, ...], new_positions, decimal=2
)
def test_compressed_write_frames_all(self, u, tmpdir):
for ext in ('.gz', '.bz2'):
destination = str(tmpdir / 'test.dcd') + ext
u.atoms.write(destination, frames='all')
u_new = mda.Universe(destination)
ref_positions = np.stack([ts.positions for ts in u.trajectory])
new_positions = np.stack([ts.positions for ts in u_new.trajectory])
assert_array_almost_equal(new_positions, ref_positions)
def test_write_frames_all(self, u, tmpdir):
destination = str(tmpdir / 'test.dcd')
u.atoms.write(destination, frames='all')
u_new = mda.Universe(destination)
ref_positions = np.stack([ts.positions for ts in u.trajectory])
new_positions = np.stack([ts.positions for ts in u_new.trajectory])
assert_array_almost_equal(new_positions, ref_positions)
@pytest.mark.parametrize('frames', ('invalid', 8, True, False, 3.2))
def test_write_frames_invalid(self, u, tmpdir, frames):
destination = str(tmpdir / 'test.dcd')
with pytest.raises(TypeError):
u.atoms.write(destination, frames=frames)
def test_incompatible_arguments(self, u, tmpdir):
destination = str(tmpdir / 'test.dcd')
with pytest.raises(ValueError):
u.atoms.write(destination, frames=[0, 1, 2], multiframe=False)
def test_incompatible_trajectories(self, tmpdir):
destination = str(tmpdir / 'test.dcd')
u1 = make_Universe(trajectory=True)
u2 = make_Universe(trajectory=True)
destination = str(tmpdir / 'test.dcd')
with pytest.raises(ValueError):
u1.atoms.write(destination, frames=u2.trajectory)
def test_write_no_traj_move(self, u, tmpdir):
destination = str(tmpdir / 'test.dcd')
u.trajectory[10]
u.atoms.write(destination, frames=[1, 2, 3])
assert u.trajectory.ts.frame == 10
def test_write_selection(self, u, tmpdir):
with tmpdir.as_cwd():
u.atoms.write("test.vmd")
def test_bogus_kwarg_pdb(self, u, tmpdir):
# test for resolution of Issue 877
with tmpdir.as_cwd():
with pytest.raises(TypeError):
u.atoms.write('dummy.pdb', bogus="what?")
class _WriteAtoms(object):
"""Set up the standard AdK system in implicit solvent."""
ext = None # override to test various output writers
precision = 3
@pytest.fixture()
def universe(self):
return mda.Universe(PSF, DCD)
@pytest.fixture()
def outfile(self, tmpdir):
return str(tmpdir) + "writeatoms." + self.ext
def universe_from_tmp(self, outfile):
return mda.Universe(outfile, convert_units=True)
def test_write_atoms(self, universe, outfile):
universe.atoms.write(outfile)
u2 = self.universe_from_tmp(outfile)
assert_almost_equal(
universe.atoms.positions, u2.atoms.positions,
self.precision,
err_msg=("atom coordinate mismatch between original and {0!s} file"
"".format(self.ext)))
def test_compressed_write_atoms(self, universe, outfile):
for compressed_ext in ('.gz', '.bz2'):
universe.atoms.write(outfile + compressed_ext)
u2 = self.universe_from_tmp(outfile + compressed_ext)
assert_almost_equal(
universe.atoms.positions, u2.atoms.positions,
self.precision,
err_msg=("atom coordinate mismatch between original and {0!s} file"
"".format(self.ext)))
def test_write_empty_atomgroup(self, universe, outfile):
sel = universe.select_atoms('name doesntexist')
with pytest.raises(IndexError):
sel.write(outfile)
def test_write_selection(self, universe, outfile):
CA = universe.select_atoms('name CA')
CA.write(outfile)
u2 = self.universe_from_tmp(outfile)
# check EVERYTHING, otherwise we might get false positives!
CA2 = u2.atoms
assert len(u2.atoms) == len(CA.atoms), "written CA selection does " \
"not match original selection"
assert_almost_equal(
CA2.positions, CA.positions, self.precision,
err_msg="CA coordinates do not agree with original")
def test_write_Residue(self, universe, outfile):
G = universe.select_atoms('segid 4AKE and resname ARG').residues[-2].atoms # 2nd but last Arg
G.write(outfile)
u2 = self.universe_from_tmp(outfile)
# check EVERYTHING, otherwise we might get false positives!
G2 = u2.atoms
assert len(u2.atoms) == len(G.atoms), "written R206 Residue does not " \
"match original ResidueGroup"
assert_almost_equal(
G2.positions, G.positions, self.precision,
err_msg="Residue R206 coordinates do not agree with original")
def test_write_ResidueGroup(self, universe, outfile):
G = universe.select_atoms('segid 4AKE and resname LEU')
G.write(outfile)
u2 = self.universe_from_tmp(outfile)
G2 = u2.atoms
assert len(u2.atoms) == len(G.atoms), "written LEU ResidueGroup does " \
"not match original ResidueGroup"
assert_almost_equal(
G2.positions, G.positions, self.precision,
err_msg="ResidueGroup LEU coordinates do not agree with original")
def test_write_Segment(self, universe, outfile):
G = universe.select_atoms('segid 4AKE')
G.write(outfile)
u2 = self.universe_from_tmp(outfile)
G2 = u2.atoms
assert len(u2.atoms) == len(G.atoms), "written s4AKE segment does not" \
" match original segment"
assert_almost_equal(
G2.positions, G.positions, self.precision,
err_msg="segment s4AKE coordinates do not agree with original")
def test_write_Universe(self, universe, outfile):
U = universe
with mda.Writer(outfile) as W:
W.write(U)
u2 = self.universe_from_tmp(outfile)
assert len(u2.atoms) == len(U.atoms), "written 4AKE universe does not" \
" match original universe in size"
assert_almost_equal(
u2.atoms.positions, U.atoms.positions, self.precision,
err_msg=("written universe 4AKE coordinates do not"
" agree with original"))
class TestWritePDB(_WriteAtoms):
ext = "pdb"
precision = 3
class TestWriteGRO(_WriteAtoms):
ext = "gro"
precision = 2
class TestAtomGroupTransformations(object):
@pytest.fixture()
def u(self):
return mda.Universe(PSF, DCD)
@pytest.fixture()
def coords(self, u):
return u.atoms.positions.copy()
@pytest.fixture()
def center_of_geometry(self, u):
return u.atoms.center_of_geometry()
def test_translate(self, u, center_of_geometry):
disp = np.ones(3)
ag = u.atoms.translate(disp)
assert_equal(ag, u.atoms)
cog = u.atoms.center_of_geometry()
diff = cog - center_of_geometry
assert_almost_equal(diff, disp, decimal=5)
def test_rotate(self, u, coords):
# ensure that selection isn't centered at 0, 0, 0
u.atoms.translate((1, 1, 1))
coords += 1
# check identify does nothing
R = np.eye(3)
u.atoms.rotate(R)
assert_almost_equal(u.atoms.positions, coords)
# check default rotation center is at 0, 0, 0. Changing this center
# will break an unpredictable amount of old code.
ag = u.atoms[:2]
ag.positions = np.array([[1, 0, 0], [-1, 0, 0]])
ag.rotate(transformations.rotation_matrix(1, [0, 0, 1])[:3, :3])
assert_almost_equal(ag.positions[0], [np.cos(1), np.sin(1), 0])
# check general rotation cases
vec = np.array([[1, 0, 0], [-1, 0, 0]])
axis = np.array([0, 0, 1])
for angle in np.linspace(0, np.pi):
R = transformations.rotation_matrix(angle, axis)
ag.positions = vec.copy()
res_ag = ag.rotate(R[:3, :3])
assert_equal(ag, res_ag)
assert_almost_equal(ag.positions[0], [np.cos(angle),
np.sin(angle),
0])
ag.positions = vec.copy()
ag.rotate(R[:3, :3], vec[0])
assert_almost_equal(ag.positions[0], vec[0])
assert_almost_equal(ag.positions[1],
[- 2 * np.cos(angle) + 1, - 2 * np.sin(angle), 0],
decimal=6)
def test_rotateby(self, u, coords):
R = np.eye(3)
u.atoms.rotate(R)
assert_almost_equal(u.atoms.positions, coords)
vec = np.array([[1, 0, 0], [-1, 0, 0]])
axis = np.array([0, 0, 1])
ag = u.atoms[:2]
ag.positions = vec
for angle in np.linspace(0, np.pi):
ag.positions = vec.copy()
# needs to be rotated about origin
res_ag = ag.rotateby(np.rad2deg(angle), axis)
assert_equal(res_ag, ag)
assert_almost_equal(ag.positions[0], [np.cos(angle),
np.sin(angle),
0])
ag.positions = vec.copy()
ag.rotateby(np.rad2deg(angle), axis, point=vec[0])
assert_almost_equal(ag.positions[0], vec[0])
assert_almost_equal(ag.positions[1], [- 2 * np.cos(angle) + 1,
- 2 * np.sin(angle),
0])
def test_transform_rotation_only(self, u, coords):
R = np.eye(3)
u.atoms.rotate(R)
assert_almost_equal(u.atoms.positions, coords)
vec = np.array([[1, 0, 0], [-1, 0, 0]])
axis = np.array([0, 0, 1])
ag = u.atoms[:2]
ag.positions = vec
for angle in np.linspace(0, np.pi):
R = transformations.rotation_matrix(angle, axis)
ag.positions = vec.copy()
ag.transform(R)
assert_almost_equal(ag.positions[0], [np.cos(angle),
np.sin(angle),
0])
def test_transform_translation_only(self, u, center_of_geometry):
disp = np.ones(3)
T = np.eye(4)
T[:3, 3] = disp
ag = u.atoms.transform(T)
assert_equal(ag, u.atoms)
cog = u.atoms.center_of_geometry()
diff = cog - center_of_geometry
assert_almost_equal(diff, disp, decimal=5)
def test_transform_translation_and_rotation(self, u):
angle = np.pi / 4
axis = [0, 0, 1]
disp = np.ones(3)
T = transformations.rotation_matrix(angle, axis)
T[:3, 3] = disp
ag = u.atoms[:2]
ag.positions = [[1, 0, 0], [-1, 0, 0]]
ag.transform(T)
assert_almost_equal(ag.positions[0], [np.cos(angle) + 1,
np.sin(angle) + 1,
1])
class TestCenter(object):
@pytest.fixture()
def ag(self):
u = make_Universe(trajectory=True)
return u.atoms[10:30]
def test_center_1(self, ag):
weights = np.zeros(ag.n_atoms)
weights[0] = 1
assert_almost_equal(ag.center(weights),
ag.positions[0])
def test_center_2(self, ag):
weights = np.zeros(ag.n_atoms)
weights[:4] = 1. / 4.
assert_almost_equal(ag.center(weights),
ag.positions[:4].mean(axis=0))
def test_center_duplicates(self, ag):
weights = np.ones(ag.n_atoms)
weights[0] = 2.
ref = ag.center(weights)
ag2 = ag + ag[0]
with pytest.warns(DuplicateWarning):
ctr = ag2.center(None)
assert_almost_equal(ctr, ref, decimal=6)
def test_center_wrong_length(self, ag):
weights = np.ones(ag.n_atoms + 4)
with pytest.raises(ValueError):
ag.center(weights)
def test_center_wrong_shape(self, ag):
weights = np.ones((ag.n_atoms, 2))
with pytest.raises(ValueError):
ag.center(weights)
@pytest.mark.parametrize('level', ('atoms', 'residues', 'segments'))
@pytest.mark.parametrize('compound', ('fragments', 'molecules', 'residues',
'group', 'segments'))
@pytest.mark.parametrize('is_triclinic', (False, True))
def test_center_unwrap(self, level, compound, is_triclinic):
u = UnWrapUniverse(is_triclinic=is_triclinic)
# select group appropriate for compound:
if compound == 'group':
group = u.atoms[39:47] # molecule 12
elif compound == 'segments':
group = u.atoms[23:47] # molecules 10, 11, 12
else:
group = u.atoms
# select topology level:
if level == 'residues':
group = group.residues
elif level == 'segments':
group = group.segments
# get the expected results
center = group.center(weights=None, pbc=False, compound=compound, unwrap=True)
ref_center = u.center(compound=compound)
assert_almost_equal(ref_center, center, decimal=4)
def test_center_unwrap_pbc_true_group(self):
u = UnWrapUniverse(is_triclinic=False)
# select group appropriate for compound:
group = u.atoms[39:47] # molecule 12
with pytest.raises(ValueError):
group.center(weights=None, compound="group", unwrap=True, pbc=True)
class TestSplit(object):
@pytest.fixture()
def universe(self):
return mda.Universe(PSF, DCD)
def test_split_atoms(self, universe):
ag = universe.select_atoms("resid 1:50 and not resname LYS and "
"(name CA or name CB)")
sg = ag.split("atom")
assert len(sg) == len(ag)
for g, ref_atom in zip(sg, ag):
atom = g[0]
assert len(g) == 1
assert_equal(atom.name, ref_atom.name)
assert_equal(atom.resid, ref_atom.resid)
def test_split_residues(self, universe):
ag = universe.select_atoms("resid 1:50 and not resname LYS and "
"(name CA or name CB)")
sg = ag.split("residue")
assert len(sg) == len(ag.residues.resids)
for g, ref_resname in zip(sg, ag.residues.resnames):
if ref_resname == "GLY":
assert len(g) == 1
else:
assert len(g) == 2
for atom in g:
assert_equal(atom.resname, ref_resname)
def test_split_segments(self, universe):
ag = universe.select_atoms("resid 1:50 and not resname LYS and "
"(name CA or name CB)")
sg = ag.split("segment")
assert len(sg) == len(ag.segments.segids)
for g, ref_segname in zip(sg, ag.segments.segids):
for atom in g:
assert_equal(atom.segid, ref_segname)
def test_split_VE(self, universe):
ag = universe.atoms[:40]
with pytest.raises(ValueError):
ag.split('something')
class TestAtomGroupProperties(object):
"""Test working with the properties of Atoms via AtomGroups
Check that:
- getting properties from AG matches the Atom values
- setting properties from AG changes the Atom
- setting the property on Atom changes AG
- _unique_restore_mask works correctly
"""
@staticmethod
def get_new(att_type):
"""Return enough values to change the small g"""
if att_type == 'string':
return ['A', 'B', 'C', 'D', 'E', 'F']
elif att_type == 'float':
return np.array([0.001, 0.002, 0.003, 0.005, 0.012, 0.025], dtype=np.float32)
elif att_type == 'int':
return [4, 6, 8, 1, 5, 4]
@pytest.fixture
def ag(self):
u = make_Universe(('names', 'resids', 'segids', 'types', 'altLocs',
'charges', 'masses', 'radii', 'bfactors',
'occupancies'))
u.atoms.occupancies = 1.0
main = u.atoms
idx = [0, 1, 4, 7, 11, 14]
return main[idx]
attributes = (('name', 'names', 'string'),
('type', 'types', 'string'),
('altLoc', 'altLocs', 'string'),
('charge', 'charges', 'float'),
('mass', 'masses', 'float'),
('radius', 'radii', 'float'),
('bfactor', 'bfactors', 'float'),
('occupancy', 'occupancies', 'float'))
@pytest.mark.parametrize('att, atts, att_type', attributes)
def test_ag_matches_atom(self, att, atts, ag, att_type):
"""Checking Atomgroup property matches Atoms"""
# Check that accessing via AtomGroup is identical to doing
# a list comprehension over AG
ref = [getattr(atom, att) for atom in ag]
assert_equal(ref, getattr(ag, atts),
err_msg="AtomGroup doesn't match Atoms for property: {0}".format(att))
@pytest.mark.parametrize('att, atts, att_type', attributes)
def test_atom_check_ag(self, att, atts, ag, att_type):
"""Changing Atom, checking AtomGroup matches this"""
vals = self.get_new(att_type)
# Set attributes via Atoms
for atom, val in zip(ag, vals):
setattr(atom, att, val)
# Check that AtomGroup returns new values
other = getattr(ag, atts)
assert_equal(vals, other,
err_msg="Change to Atoms not reflected in AtomGroup for property: {0}".format(att))
def test_ag_unique_restore_mask(self, ag):
# assert that ag is unique:
assert ag.isunique
# assert restore mask cache is empty:
with pytest.raises(KeyError):
_ = ag._cache['unique_restore_mask']
# access unique property:
uag = ag.unique
# assert restore mask cache is still empty since ag is unique:
with pytest.raises(KeyError):
_ = ag._cache['unique_restore_mask']
# make sure that accessing the restore mask of the unique AtomGroup
# raises a RuntimeError:
with pytest.raises(RuntimeError):
_ = ag._unique_restore_mask
# add duplicate atoms:
ag += ag
# assert that ag is not unique:
assert not ag.isunique
# assert cache is empty:
with pytest.raises(KeyError):
_ = ag._cache['unique_restore_mask']
# access unique property:
uag = ag.unique
# check if caching works as expected:
assert ag._cache['unique_restore_mask'] is ag._unique_restore_mask
# assert that restore mask cache of ag.unique hasn't been set:
with pytest.raises(RuntimeError):
_ = ag.unique._unique_restore_mask
# assert restore mask can reproduce original ag:
assert ag.unique[ag._unique_restore_mask] == ag
class TestOrphans(object):
"""Test moving Universes out of scope and having A/AG persist
Atoms and AtomGroups from other scopes should work, namely:
- should have access to Universe
- should be able to use the Reader (coordinates)
"""
def test_atom(self):
u = mda.Universe(two_water_gro)
def getter():
u2 = mda.Universe(two_water_gro)
return u2.atoms[1]
atom = getter()
assert atom is not u.atoms[1]
assert len(atom.universe.atoms) == len(u.atoms)
assert_almost_equal(atom.position, u.atoms[1].position)
def test_atomgroup(self):
u = mda.Universe(two_water_gro)
def getter():
u2 = mda.Universe(two_water_gro)
return u2.atoms[:4]
ag = getter()
ag2 = u.atoms[:4]
assert ag is not ag2
assert len(ag.universe.atoms) == len(u.atoms)
assert_almost_equal(ag.positions, ag2.positions)
class TestCrossUniverse(object):
"""Test behaviour when we mix Universes"""
@pytest.mark.parametrize(
# Checks Atom to Atom, Atom to AG, AG to Atom and AG to AG
'index_u1, index_u2',
itertools.product([0, 1], repeat=2)
)
def test_add_mixed_universes(self, index_u1, index_u2):
""" Issue #532
Checks that adding objects from different universes
doesn't proceed quietly.
"""
u1 = mda.Universe(two_water_gro)
u2 = mda.Universe(two_water_gro)
A = [u1.atoms[:2], u1.atoms[3]]
B = [u2.atoms[:3], u2.atoms[0]]
with pytest.raises(ValueError):
A[index_u1] + B[index_u2]
def test_adding_empty_ags(self):
""" Check that empty AtomGroups don't trip up on the Universe check """
u = mda.Universe(two_water_gro)
assert len(u.atoms[[]] + u.atoms[:3]) == 3
assert len(u.atoms[:3] + u.atoms[[]]) == 3
class TestDihedralSelections(object):
dih_prec = 2
@staticmethod
@pytest.fixture(scope='module')
def GRO():
return mda.Universe(GRO)
@staticmethod
@pytest.fixture(scope='module')
def PSFDCD():
return mda.Universe(PSF, DCD)
@staticmethod
@pytest.fixture(scope='class')
def resgroup(GRO):
return GRO.segments[0].residues[8:10]
def test_phi_selection(self, GRO):
phisel = GRO.segments[0].residues[9].phi_selection()
assert_equal(phisel.names, ['C', 'N', 'CA', 'C'])
assert_equal(phisel.residues.resids, [9, 10])
assert_equal(phisel.residues.resnames, ['PRO', 'GLY'])
@pytest.mark.parametrize('kwargs,names', [
({'c_name': 'O'}, ['O', 'N', 'CA', 'O']),
({'n_name': 'O'}, ['C', 'O', 'CA', 'C']),
({'ca_name': 'O'}, ['C', 'N', 'O', 'C'])
])
def test_phi_selection_name(self, GRO, kwargs, names):
phisel = GRO.segments[0].residues[9].phi_selection(**kwargs)
assert_equal(phisel.names, names)
assert_equal(phisel.residues.resids, [9, 10])
assert_equal(phisel.residues.resnames, ['PRO', 'GLY'])
def test_phi_selections_single(self, GRO):
rgsel = GRO.segments[0].residues[[9]].phi_selections()
assert len(rgsel) == 1
phisel = rgsel[0]
assert_equal(phisel.names, ['C', 'N', 'CA', 'C'])
assert_equal(phisel.residues.resids, [9, 10])
assert_equal(phisel.residues.resnames, ['PRO', 'GLY'])
def test_phi_selections(self, resgroup):
rgsel = resgroup.phi_selections()
rssel = [r.phi_selection() for r in resgroup]
assert_equal(rgsel, rssel)
@pytest.mark.parametrize('kwargs,names', [
({'c_name': 'O'}, ['O', 'N', 'CA', 'O']),
({'n_name': 'O'}, ['C', 'O', 'CA', 'C']),
({'ca_name': 'O'}, ['C', 'N', 'O', 'C'])
])
def test_phi_selections_name(self, resgroup, kwargs, names):
rgsel = resgroup.phi_selections(**kwargs)
for ag in rgsel:
assert_equal(ag.names, names)
def test_psi_selection(self, GRO):
psisel = GRO.segments[0].residues[9].psi_selection()
assert_equal(psisel.names, ['N', 'CA', 'C', 'N'])
assert_equal(psisel.residues.resids, [10, 11])
assert_equal(psisel.residues.resnames, ['GLY', 'ALA'])
@pytest.mark.parametrize('kwargs,names', [
({'c_name': 'O'}, ['N', 'CA', 'O', 'N']),
({'n_name': 'O'}, ['O', 'CA', 'C', 'O']),
({'ca_name': 'O'}, ['N', 'O', 'C', 'N']),
])
def test_psi_selection_name(self, GRO, kwargs, names):
psisel = GRO.segments[0].residues[9].psi_selection(**kwargs)
assert_equal(psisel.names, names)
assert_equal(psisel.residues.resids, [10, 11])
assert_equal(psisel.residues.resnames, ['GLY', 'ALA'])
def test_psi_selections_single(self, GRO):
rgsel = GRO.segments[0].residues[[9]].psi_selections()
assert len(rgsel) == 1
psisel = rgsel[0]
assert_equal(psisel.names, ['N', 'CA', 'C', 'N'])
assert_equal(psisel.residues.resids, [10, 11])
assert_equal(psisel.residues.resnames, ['GLY', 'ALA'])
def test_psi_selections(self, resgroup):
rgsel = resgroup.psi_selections()
rssel = [r.psi_selection() for r in resgroup]
assert_equal(rgsel, rssel)
@pytest.mark.parametrize('kwargs,names', [
({'c_name': 'O'}, ['N', 'CA', 'O', 'N']),
({'n_name': 'O'}, ['O', 'CA', 'C', 'O']),
({'ca_name': 'O'}, ['N', 'O', 'C', 'N']),
])
def test_psi_selections_name(self, resgroup, kwargs, names):
rgsel = resgroup.psi_selections(**kwargs)
for ag in rgsel:
assert_equal(ag.names, names)
def test_omega_selection(self, GRO):
osel = GRO.segments[0].residues[7].omega_selection()
assert_equal(osel.names, ['CA', 'C', 'N', 'CA'])
assert_equal(osel.residues.resids, [8, 9])
assert_equal(osel.residues.resnames, ['ALA', 'PRO'])
@pytest.mark.parametrize('kwargs,names', [
({'c_name': 'O'}, ['CA', 'O', 'N', 'CA']),
({'n_name': 'O'}, ['CA', 'C', 'O', 'CA']),
({'ca_name': 'O'}, ['O', 'C', 'N', 'O']),
])
def test_omega_selection_name(self, GRO, kwargs, names):
osel = GRO.segments[0].residues[7].omega_selection(**kwargs)
assert_equal(osel.names, names)
assert_equal(osel.residues.resids, [8, 9])
assert_equal(osel.residues.resnames, ['ALA', 'PRO'])
def test_omega_selections_single(self, GRO):
rgsel = GRO.segments[0].residues[[7]].omega_selections()
assert len(rgsel) == 1
osel = rgsel[0]
assert_equal(osel.names, ['CA', 'C', 'N', 'CA'])
assert_equal(osel.residues.resids, [8, 9])
assert_equal(osel.residues.resnames, ['ALA', 'PRO'])
def test_omega_selections(self, resgroup):
rgsel = resgroup.omega_selections()
rssel = [r.omega_selection() for r in resgroup]
assert_equal(rgsel, rssel)
@pytest.mark.parametrize('kwargs,names', [
({'c_name': 'O'}, ['CA', 'O', 'N', 'CA']),
({'n_name': 'O'}, ['CA', 'C', 'O', 'CA']),
({'ca_name': 'O'}, ['O', 'C', 'N', 'O']),
])
def test_omega_selections_name(self, resgroup, kwargs, names):
rgsel = resgroup.omega_selections(**kwargs)
for ag in rgsel:
assert_equal(ag.names, names)
def test_chi1_selection(self, GRO):
sel = GRO.segments[0].residues[12].chi1_selection() # LYS
assert_equal(sel.names, ['N', 'CA', 'CB', 'CG'])
assert_equal(sel.residues.resids, [13])
assert_equal(sel.residues.resnames, ['LYS'])
@pytest.mark.parametrize('kwargs,names', [
({'n_name': 'O'}, ['O', 'CA', 'CB', 'CG']),
({'ca_name': 'O'}, ['N', 'O', 'CB', 'CG']),
({'cb_name': 'O'}, ['N', 'CA', 'O', 'CG']),
({'cg_name': 'O'}, ['N', 'CA', 'CB', 'O']),
])
def test_chi1_selection_name(self, GRO, kwargs, names):
sel = GRO.segments[0].residues[12].chi1_selection(**kwargs) # LYS
assert_equal(sel.names, names)
assert_equal(sel.residues.resids, [13])
assert_equal(sel.residues.resnames, ['LYS'])
def test_chi1_selections_single(self, GRO):
rgsel = GRO.segments[0].residues[[12]].chi1_selections()
assert len(rgsel) == 1
sel = rgsel[0]
assert_equal(sel.names, ['N', 'CA', 'CB', 'CG'])
assert_equal(sel.residues.resids, [13])
assert_equal(sel.residues.resnames, ['LYS'])
def test_chi1_selections(self, resgroup):
rgsel = resgroup.chi1_selections()
rssel = [r.chi1_selection() for r in resgroup]
assert_equal(rgsel, rssel)
def test_phi_sel_fail(self, GRO):
sel = GRO.residues[0].phi_selection()
assert sel is None
def test_phi_sels_fail(self, GRO):
rgsel = GRO.residues[212:216].phi_selections()
assert rgsel[0] is not None
assert rgsel[1] is not None
assert_equal(rgsel[-2:], [None, None])
def test_psi_sel_fail(self, GRO):
sel = GRO.residues[-1].psi_selection()
assert sel is None
def test_psi_sels_fail(self, GRO):
rgsel = GRO.residues[211:215].psi_selections()
assert rgsel[0] is not None
assert rgsel[1] is not None
assert_equal(rgsel[-2:], [None, None])
def test_omega_sel_fail(self, GRO):
sel = GRO.residues[-1].omega_selection()
assert sel is None
def test_omega_sels_fail(self, GRO):
rgsel = GRO.residues[211:215].omega_selections()
assert rgsel[0] is not None
assert rgsel[1] is not None
assert_equal(rgsel[-2:], [None, None])
def test_ch1_sel_fail(self, GRO):
sel = GRO.segments[0].residues[7].chi1_selection()
assert sel is None # ALA
def test_chi1_sels_fail(self, GRO):
rgsel = GRO.residues[12:14].chi1_selections()
assert rgsel[0] is not None
assert rgsel[1] is None
def test_dihedral_phi(self, PSFDCD):
phisel = PSFDCD.segments[0].residues[9].phi_selection()
assert_almost_equal(phisel.dihedral.value(), -168.57384, self.dih_prec)
def test_dihedral_psi(self, PSFDCD):
psisel = PSFDCD.segments[0].residues[9].psi_selection()
assert_almost_equal(psisel.dihedral.value(), -30.064838, self.dih_prec)
def test_dihedral_omega(self, PSFDCD):
osel = PSFDCD.segments[0].residues[7].omega_selection()
assert_almost_equal(osel.dihedral.value(), -179.93439, self.dih_prec)
def test_dihedral_chi1(self, PSFDCD):
sel = PSFDCD.segments[0].residues[12].chi1_selection() # LYS
assert_almost_equal(sel.dihedral.value(), -58.428127, self.dih_prec)
def test_phi_nodep(self, GRO):
with no_deprecated_call():
phisel = GRO.segments[0].residues[9].phi_selection()
def test_psi_nodep(self, GRO):
with no_deprecated_call():
psisel = GRO.segments[0].residues[9].psi_selection()
def test_omega_nodep(self, GRO):
with no_deprecated_call():
osel = GRO.segments[0].residues[7].omega_selection()
def test_chi1_nodep(self, GRO):
with no_deprecated_call():
sel = GRO.segments[0].residues[12].chi1_selection() # LYS
class TestUnwrapFlag(object):
prec = 3
@pytest.fixture()
def ag(self):
universe = mda.Universe(TRZ_psf, TRZ)
group = universe.residues[0:3]
group.wrap(inplace=True)
return group
@pytest.fixture()
def unordered_ag(self, ag):
ndx = np.arange(len(ag))
np.random.shuffle(ndx)
return ag[ndx]
@pytest.fixture()