-
Notifications
You must be signed in to change notification settings - Fork 670
/
Copy pathtest_groups.py
1614 lines (1363 loc) · 53.2 KB
/
test_groups.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
#
import itertools
import numpy as np
from numpy.testing import (
assert_array_equal,
assert_equal,
)
import pytest
import operator
import warnings
import MDAnalysis as mda
from MDAnalysis.exceptions import NoDataError
from MDAnalysisTests import make_Universe, no_deprecated_call
from MDAnalysisTests.datafiles import PSF, DCD, TPR
from MDAnalysis.core import groups
class TestGroupProperties(object):
""" Test attributes common to all groups
"""
@pytest.fixture()
def u(self):
return make_Universe(trajectory=True)
@pytest.fixture()
def group_dict(self, u):
return {
'atom': u.atoms,
'residue': u.residues,
'segment': u.segments
}
uni = make_Universe() # can't use fixtures in @pytest.mark.parametrize
def test_dimensions(self, u, group_dict):
dimensions = np.arange(6)
for group in group_dict.values():
group.dimensions = dimensions.copy()
assert_array_equal(group.dimensions, dimensions)
assert_equal(u.dimensions, group.dimensions)
@pytest.mark.parametrize('group', (uni.atoms[:2], uni.residues[:2],
uni.segments[:2]))
def test_group_isunique(self, group):
assert len(group) == 2
# Initially, cache must be empty:
with pytest.raises(KeyError):
_ = group._cache['isunique']
# Check for correct value and type:
assert group.isunique is True
# Check if cache is set correctly:
assert group._cache['isunique'] is True
# Add duplicate element to group:
group += group[0]
assert len(group) == 3
# Cache must be reset since the group changed:
with pytest.raises(KeyError):
_ = group._cache['isunique']
# Check for correct value and type:
assert group.isunique is False
# Check if cache is set correctly:
assert group._cache['isunique'] is False
#Check empty group:
group = group[[]]
assert len(group) == 0
# Cache must be empty:
with pytest.raises(KeyError):
_ = group._cache['isunique']
# Check for correct value and type:
assert group.isunique is True
# Check if cache is set correctly:
assert group._cache['isunique'] is True
@pytest.mark.parametrize('group', (uni.atoms[:2], uni.residues[:2],
uni.segments[:2]))
def test_group_unique(self, group):
# check unique group:
assert len(group) == 2
# assert caches are empty:
with pytest.raises(KeyError):
_ = group._cache['isunique']
with pytest.raises(KeyError):
_ = group._cache['unique']
# assert that group.unique of the unique group references itself:
assert group.unique is group
# check if caches have been set:
assert group._cache['isunique'] is True
assert group._cache['unique'] is group
# add duplicate element to group:
group += group[0]
assert len(group) == 3
# assert caches are cleared since the group changed:
with pytest.raises(KeyError):
_ = group._cache['isunique']
with pytest.raises(KeyError):
_ = group._cache['unique']
# assert that group.unique of the non-unique group doesn't reference
# itself:
assert group.unique is not group
# check if caches have been set correctly:
assert group._cache['isunique'] is False
assert group._cache['unique'] is group.unique
# check length and type:
assert len(group.unique) == 2
assert type(group.unique) is type(group)
# check if caches of group.unique have been set correctly:
assert group.unique._cache['isunique'] is True
assert group.unique._cache['unique'] is group.unique
# assert that repeated access yields the same object (not a copy):
unique_group = group.unique
assert unique_group is group.unique
class TestGroupSlicing(object):
"""All Groups (Atom, Residue, Segment) should slice like a numpy array
TODO
----
TopologyGroup is technically called group, add this in too!
"""
u = make_Universe()
# test universe is 5:1 mapping 3 times
group_dict = {
'atom': u.atoms,
'residue': u.residues,
'segment': u.segments
}
singulars = {
'atom': groups.Atom,
'residue': groups.Residue,
'segment': groups.Segment
}
slices = (
slice(0, 10),
slice(0, 2),
slice(1, 3),
slice(0, 2, 2),
slice(0, -1),
slice(5, 1, -1),
slice(10, 0, -2),
)
length = {'atom': 125,
'residue': 25,
'segment': 5}
levels = ('atom', 'residue', 'segment')
@pytest.fixture(params=levels)
def level(self, request):
return request.param
@pytest.fixture
def group(self, level):
return self.group_dict[level]
@pytest.fixture
def nparray(self, level):
return np.arange(self.length[level])
@pytest.fixture
def singular(self, level):
return self.singulars[level]
def test_n_atoms(self, group):
assert len(group.atoms) == group.n_atoms
def test_n_residues(self, group):
assert len(group.residues) == group.n_residues
def test_n_segments(self, group):
assert len(group.segments) == group.n_segments
def test_len(self, group, level):
ref = self.length[level]
assert len(group) == ref
@pytest.mark.parametrize('func', [list, np.array])
def test_boolean_slicing(self, group, func):
# func is the container type that will be used to slice
group = group[:5]
sli = func([True, False, False, True, True])
result = group[sli]
assert len(result) == 3
for ref, val in zip(sli, group):
if ref:
assert val in result
else:
assert val not in result
def test_indexerror(self, group, level):
idx = self.length[level]
with pytest.raises(IndexError):
group.__getitem__(idx)
@pytest.mark.parametrize('sl,func', itertools.product((
slice(0, 10),
slice(0, 2),
slice(1, 3),
slice(0, 2, 2),
slice(0, -1),
slice(5, 1, -1),
slice(10, 0, -2),
), [list, lambda x: np.array(x, dtype=np.int64)]))
def test_slice(self, group, nparray, sl, func):
"""Check that slicing a np array is identical"""
g2 = group[sl]
o2 = nparray[sl]
assert len(g2) == len(o2)
# Check identity of items in the sliced result
for o, g in zip(o2, g2):
if o in nparray:
assert g in g2
else:
assert g not in g2
@pytest.mark.parametrize('idx', [0, 1, -1, -2])
def test_integer_getitem(self, group, nparray, idx, singular):
a = group[idx]
ref = nparray[idx]
assert a.ix == ref
assert isinstance(a, singular)
def _yield_groups(group_dict, singles, levels, groupclasses, repeat):
for level in levels:
for groups in itertools.product([group_dict[level], singles[level]],
repeat=repeat):
yield list(groups) + [groupclasses[level]]
class TestGroupAddition(object):
"""Tests for combining Group objects
Contents
--------
Addition of Groups should work like list addition
Addition of Singular objects should make Group
A + A -> AG
AG + A -> AG
A + AG -> AG
AG + AG -> AG
Cross level addition (eg AG + RG) raises TypeError
Sum() should work on an iterable of many same level Components/Groups
Groups contain items "x in y"
"""
u = make_Universe()
levels = ['atom', 'residue', 'segment']
group_dict = {
'atom': u.atoms[:5],
'residue': u.residues[:5],
'segment': u.segments[:5],
}
singles = {
'atom': u.atoms[0],
'residue': u.residues[0],
'segment': u.segments[0],
}
groupclasses = {
'atom': groups.AtomGroup,
'residue': groups.ResidueGroup,
'segment': groups.SegmentGroup,
}
# TODO: actually use this
singleclasses = {
'atom': groups.Atom,
'residue': groups.Residue,
'segment': groups.Segment
}
@pytest.fixture(params=levels)
def level(self, request):
return request.param
@pytest.fixture
def group(self, level):
return self.group_dict[level]
@pytest.fixture
def single(self, level):
return self.singles[level]
@pytest.fixture
def two_groups(self, group, single):
return itertools.product([group, single], repeat=2)
@pytest.fixture
def three_groups(self, group, single):
return itertools.product([group, single], repeat=3)
@staticmethod
def itr(x):
# singular objects don't iterate
try:
x[0]
except TypeError:
return [x]
else:
return x
@pytest.mark.parametrize(
'a, b, refclass',
_yield_groups(group_dict, singles, levels, groupclasses, repeat=2)
)
def test_addition(self, a, b, refclass):
"""Combine a and b, check length, returned type and ordering"""
newgroup = a + b
reflen = len(self.itr(a)) + len(self.itr(b))
assert len(newgroup) == reflen
assert isinstance(newgroup, refclass)
# Check ordering of created Group
for x, y in zip(newgroup, itertools.chain(self.itr(a), self.itr(b))):
assert x == y
@pytest.mark.parametrize(
'a, b, c, refclass',
_yield_groups(group_dict, singles, levels, groupclasses, repeat=3)
)
def test_sum(self, a, b, c, refclass):
# weird hack in radd allows this
summed = sum([a, b, c])
assert isinstance(summed, refclass)
assert_equal(len(summed),
len(self.itr(a)) + len(self.itr(b)) + len(self.itr(c)))
for x, y in zip(summed,
itertools.chain(self.itr(a), self.itr(b), self.itr(c))):
assert x == y
@pytest.mark.parametrize(
'a, b, c, refclass',
_yield_groups(group_dict, singles, levels, groupclasses, repeat=3)
)
def test_bad_sum(self, a, b, c, refclass):
# sum with bad first argument
with pytest.raises(TypeError):
sum([10, a, b, c])
def test_contains(self, group):
assert group[2] in group
def test_contains_false(self, group):
assert not group[3] in group[:2]
@pytest.mark.parametrize(
'one_level, other_level',
[
(l1, l2)
for l1, l2
in itertools.product(levels, repeat=2)
if l1 != l2
]
)
def test_contains_wronglevel(self, one_level, other_level):
group = self.group_dict[one_level]
group2 = self.group_dict[other_level]
assert not group[2] in group2
@pytest.mark.parametrize(
'a, b',
[
(typeA[alevel], typeB[blevel])
for (typeA, typeB), (alevel, blevel)
in itertools.product(
itertools.product([singles, group_dict], repeat=2),
itertools.permutations(levels, 2)
)
]
)
def test_crosslevel(self, a, b):
with pytest.raises(TypeError):
a + b
class TestGroupLevelTransition(object):
"""Test moving between different hierarchy levels
AtomGroup
^
v
ResidueGroup
^
v
SegmentGroup
*group_to_*group tests moves between levels
_unique tests check that Upshifts only return unique higher level
_listcomp tests check that Downshifts INCLUDE repeated elements
"""
@pytest.fixture()
def u(self):
return make_Universe()
def test_atomgroup_to_atomgroup(self, u):
atm = u.atoms.atoms
assert len(atm) == 125
assert isinstance(atm, groups.AtomGroup)
assert atm is u.atoms
def test_atomgroup_to_residuegroup(self, u):
atm = u.atoms
res = atm.residues
assert len(res) == 25
assert isinstance(res, groups.ResidueGroup)
assert res == u.residues
assert res is not u.residues
assert res._cache['isunique'] is True
assert res._cache['unique'] is res
def test_atomgroup_to_segmentgroup(self, u):
seg = u.atoms.segments
assert len(seg) == 5
assert isinstance(seg, groups.SegmentGroup)
assert seg == u.segments
assert seg is not u.segments
assert seg._cache['isunique'] is True
assert seg._cache['unique'] is seg
def test_residuegroup_to_atomgroup(self, u):
res = u.residues
atm = res.atoms
assert len(atm) == 125
assert isinstance(atm, groups.AtomGroup)
assert atm == u.atoms
assert atm is not u.atoms
# clear res' uniqueness caches:
if 'unique' in res._cache.keys():
del res._cache['unique']
if 'isunique' in res._cache.keys():
del res._cache['isunique']
atm = res.atoms
# assert uniqueness caches of atm are empty:
with pytest.raises(KeyError):
_ = atm._cache['isunique']
with pytest.raises(KeyError):
_ = atm._cache['unique']
# populate uniqueness cache of res:
assert res.isunique
atm = res.atoms
# assert uniqueness caches of atm are set:
assert atm._cache['isunique'] is True
assert atm._cache['unique'] is atm
def test_residuegroup_to_residuegroup(self, u):
res = u.residues.residues
assert len(res) == 25
assert isinstance(res, groups.ResidueGroup)
assert res is u.residues
def test_residuegroup_to_segmentgroup(self, u):
seg = u.residues.segments
assert len(seg) == 5
assert isinstance(seg, groups.SegmentGroup)
assert seg == u.segments
assert seg is not u.segments
assert seg._cache['isunique'] is True
assert seg._cache['unique'] is seg
def test_segmentgroup_to_atomgroup(self, u):
seg = u.segments
atm = seg.atoms
assert len(atm) == 125
assert isinstance(atm, groups.AtomGroup)
assert atm == u.atoms
assert atm is not u.atoms
# clear seg's uniqueness caches:
if 'unique' in seg._cache.keys():
del seg._cache['unique']
if 'isunique' in seg._cache.keys():
del seg._cache['isunique']
atm = seg.atoms
# assert uniqueness caches of atm are empty:
with pytest.raises(KeyError):
_ = atm._cache['isunique']
with pytest.raises(KeyError):
_ = atm._cache['unique']
# populate uniqueness cache of seg:
assert seg.isunique
atm = seg.atoms
# assert uniqueness caches of atm are set:
assert atm._cache['isunique'] is True
assert atm._cache['unique'] is atm
def test_segmentgroup_to_residuegroup(self, u):
seg = u.segments
res = seg.residues
assert len(res) == 25
assert isinstance(res, groups.ResidueGroup)
assert res == u.residues
assert res is not u.residues
# clear seg's uniqueness caches:
if 'unique' in seg._cache.keys():
del seg._cache['unique']
if 'isunique' in seg._cache.keys():
del seg._cache['isunique']
res = seg.residues
# assert uniqueness caches of res are empty:
with pytest.raises(KeyError):
_ = res._cache['isunique']
with pytest.raises(KeyError):
_ = res._cache['unique']
# populate uniqueness cache of seg:
assert seg.isunique
res = seg.residues
# assert uniqueness caches of res are set:
assert res._cache['isunique'] is True
assert res._cache['unique'] is res
def test_segmentgroup_to_segmentgroup(self, u):
seg = u.segments.segments
assert len(seg) == 5
assert isinstance(seg, groups.SegmentGroup)
assert seg is u.segments
def test_atom_to_residue(self, u):
res = u.atoms[0].residue
assert isinstance(res, groups.Residue)
def test_atom_to_segment(self, u):
seg = u.atoms[0].segment
assert isinstance(seg, groups.Segment)
def test_residue_to_atomgroup(self, u):
ag = u.residues[0].atoms
assert isinstance(ag, groups.AtomGroup)
assert len(ag) == 5
assert ag._cache['isunique'] is True
assert ag._cache['unique'] is ag
del ag._cache['unique']
del ag._cache['isunique']
assert ag.isunique
def test_residue_to_segment(self, u):
seg = u.residues[0].segment
assert isinstance(seg, groups.Segment)
def test_segment_to_atomgroup(self, u):
ag = u.segments[0].atoms
assert isinstance(ag, groups.AtomGroup)
assert len(ag) == 25
assert ag._cache['isunique'] is True
assert ag._cache['unique'] is ag
del ag._cache['unique']
del ag._cache['isunique']
assert ag.isunique
def test_segment_to_residuegroup(self, u):
rg = u.segments[0].residues
assert isinstance(rg, groups.ResidueGroup)
assert len(rg) == 5
assert rg._cache['isunique'] is True
assert rg._cache['unique'] is rg
del rg._cache['unique']
del rg._cache['isunique']
assert rg.isunique
def test_atomgroup_to_residuegroup_unique(self, u):
ag = u.atoms[:5] + u.atoms[10:15] + u.atoms[:5]
rg = ag.residues
assert len(rg) == 2
assert rg._cache['isunique'] is True
assert rg._cache['unique'] is rg
def test_atomgroup_to_segmentgroup_unique(self, u):
ag = u.atoms[0] + u.atoms[-1] + u.atoms[0]
sg = ag.segments
assert len(sg) == 2
assert sg._cache['isunique'] is True
assert sg._cache['unique'] is sg
def test_residuegroup_to_segmentgroup_unique(self, u):
rg = u.residues[0] + u.residues[6] + u.residues[1]
sg = rg.segments
assert len(sg) == 2
assert sg._cache['isunique'] is True
assert sg._cache['unique'] is sg
def test_residuegroup_to_atomgroup_listcomp(self, u):
rg = u.residues[0] + u.residues[0] + u.residues[4]
ag = rg.atoms
assert len(ag) == 15
# assert uniqueness caches of ag are empty:
with pytest.raises(KeyError):
_ = ag._cache['isunique']
with pytest.raises(KeyError):
_ = ag._cache['unique']
# populate uniqueness cache of rg:
assert not rg.isunique
ag = rg.atoms
# assert uniqueness caches of ag are still empty:
with pytest.raises(KeyError):
_ = ag._cache['isunique']
with pytest.raises(KeyError):
_ = ag._cache['unique']
def test_segmentgroup_to_residuegroup_listcomp(self, u):
sg = u.segments[0] + u.segments[0] + u.segments[1]
rg = sg.residues
assert len(rg) == 15
# assert uniqueness caches of rg are empty:
with pytest.raises(KeyError):
_ = rg._cache['isunique']
with pytest.raises(KeyError):
_ = rg._cache['unique']
# populate uniqueness cache of sg:
assert not sg.isunique
rg = sg.residues
# assert uniqueness caches of rg are still empty:
with pytest.raises(KeyError):
_ = rg._cache['isunique']
with pytest.raises(KeyError):
_ = rg._cache['unique']
def test_segmentgroup_to_atomgroup_listcomp(self, u):
sg = u.segments[0] + u.segments[0] + u.segments[1]
ag = sg.atoms
assert len(ag) == 75
# assert uniqueness caches of ag are empty:
with pytest.raises(KeyError):
_ = ag._cache['isunique']
with pytest.raises(KeyError):
_ = ag._cache['unique']
# populate uniqueness cache of sg:
assert not sg.isunique
ag = sg.atoms
# assert uniqueness caches of ag are still empty:
with pytest.raises(KeyError):
_ = ag._cache['isunique']
with pytest.raises(KeyError):
_ = ag._cache['unique']
class TestComponentComparisons(object):
"""Use of operators (< > == != <= >=) with Atom, Residue, and Segment"""
u = make_Universe()
levels = [u.atoms, u.residues, u.segments]
@pytest.fixture(params=levels)
def abc(self, request):
level = request.param
return level[0], level[1], level[2]
@pytest.fixture
def a(self, abc):
return abc[0]
@pytest.fixture
def b (self, abc):
return abc[1]
@pytest.fixture
def c(self, abc):
return abc[2]
def test_lt(self, a, b, c):
assert a < b
assert a < c
assert not b < a
assert not a < a
def test_gt(self, a, b, c):
assert b > a
assert c > a
assert not a > c
assert not a > a
def test_ge(self, a, b, c):
assert b >= a
assert c >= a
assert b >= b
assert not b >= c
def test_le(self, a, b, c):
assert b <= c
assert b <= b
assert not b <= a
def test_neq(self, a, b, c):
assert a != b
assert not a != a
def test_eq(self, a, b, c):
assert a == a
assert not a == b
def test_sorting(self, a, b, c):
assert sorted([b, a, c]) == [a, b, c]
@pytest.mark.parametrize(
'x, y',
itertools.permutations((u.atoms[0], u.residues[0], u.segments[0]), 2)
)
def test_crosslevel_cmp(self, x, y):
with pytest.raises(TypeError):
operator.lt(x, y)
with pytest.raises(TypeError):
operator.le(x, y)
with pytest.raises(TypeError):
operator.gt(x, y)
with pytest.raises(TypeError):
operator.ge(x, y)
@pytest.mark.parametrize(
'x, y',
itertools.permutations((u.atoms[0], u.residues[0], u.segments[0]), 2)
)
def test_crosslevel_eq(self, x, y):
with pytest.raises(TypeError):
operator.eq(x, y)
with pytest.raises(TypeError):
operator.ne(x, y)
class TestMetaclassMagic(object):
# tests for the weird voodoo we do with metaclasses
def test_new_class(self):
u = make_Universe(trajectory=True)
# should be able to subclass AtomGroup as normal
class NewGroup(groups.AtomGroup):
pass
ng = NewGroup(np.array([0, 1, 2]), u)
assert isinstance(ng, NewGroup)
ag = u.atoms[[0, 1, 2]]
assert_array_equal(ng.positions, ag.positions)
class TestGroupBy(object):
# tests for the method 'groupby'
@pytest.fixture()
def u(self):
return make_Universe(('segids', 'charges', 'resids'))
def test_groupby_float(self, u):
gb = u.atoms.groupby('charges')
for ref in [-1.5, -0.5, 0.0, 0.5, 1.5]:
assert ref in gb
g = gb[ref]
assert all(g.charges == ref)
assert len(g) == 25
@pytest.mark.parametrize('string', ['segids', b'segids', u'segids'])
def test_groupby_string(self, u, string):
gb = u.atoms.groupby(string)
assert len(gb) == 5
for ref in ['SegA', 'SegB', 'SegC', 'SegD', 'SegE']:
assert ref in gb
g = gb[ref]
assert all(g.segids == ref)
assert len(g) == 25
def test_groupby_int(self, u):
gb = u.atoms.groupby('resids')
for g in gb.values():
assert len(g) == 5
# tests for multiple attributes as arguments
def test_groupby_float_string(self, u):
gb = u.atoms.groupby(['charges', 'segids'])
for ref in [-1.5, -0.5, 0.0, 0.5, 1.5]:
for subref in ['SegA','SegB','SegC','SegD','SegE']:
assert (ref, subref) in gb.keys()
a = gb[(ref, subref)]
assert len(a) == 5
assert all(a.charges == ref)
assert all(a.segids == subref)
def test_groupby_int_float(self, u):
gb = u.atoms.groupby(['resids', 'charges'])
uplim=int(len(gb)/5+1)
for ref in range(1, uplim):
for subref in [-1.5, -0.5, 0.0, 0.5, 1.5]:
assert (ref, subref) in gb.keys()
a = gb[(ref, subref)]
assert len(a) == 1
assert all(a.resids == ref)
assert all(a.charges == subref)
def test_groupby_string_int(self, u):
gb = u.atoms.groupby(['segids', 'resids'])
assert len(gb) == 25
res = 1
for ref in ['SegA','SegB','SegC','SegD','SegE']:
for subref in range(0, 5):
assert (ref, res) in gb.keys()
a = gb[(ref, res)]
assert all(a.segids == ref)
assert all(a.resids == res)
res += 1
class TestReprs(object):
@pytest.fixture()
def u(self):
return mda.Universe(PSF, DCD)
def test_atom_repr(self, u):
at = u.atoms[0]
assert repr(at) == '<Atom 1: N of type 56 of resname MET, resid 1 and segid 4AKE>'
def test_residue_repr(self, u):
res = u.residues[0]
assert repr(res) == '<Residue MET, 1>'
def test_segment_repr(self, u):
seg = u.segments[0]
assert repr(seg) == '<Segment 4AKE>'
def test_atomgroup_repr(self, u):
ag = u.atoms[:10]
assert repr(ag) == '<AtomGroup with 10 atoms>'
def test_atomgroup_str_short(self, u):
ag = u.atoms[:2]
assert str(ag) == '<AtomGroup [<Atom 1: N of type 56 of resname MET, resid 1 and segid 4AKE>, <Atom 2: HT1 of type 2 of resname MET, resid 1 and segid 4AKE>]>'
def test_atomgroup_str_long(self, u):
ag = u.atoms[:11]
assert str(ag).startswith('<AtomGroup [<Atom 1: N of type 56 of resname MET,')
assert '...' in str(ag)
assert str(ag).endswith(', resid 1 and segid 4AKE>]>')
def test_residuegroup_repr(self, u):
rg = u.residues[:10]
assert repr(rg) == '<ResidueGroup with 10 residues>'
def test_residuegroup_str_short(self, u):
rg = u.residues[:2]
assert str(rg) == '<ResidueGroup [<Residue MET, 1>, <Residue ARG, 2>]>'
def test_residuegroup_str_long(self, u):
rg = u.residues[:11]
assert str(rg).startswith('<ResidueGroup [<Residue MET, 1>,')
assert '...' in str(rg)
assert str(rg).endswith(', <Residue ALA, 11>]>')
def test_segmentgroup_repr(self, u):
sg = u.segments[:10]
assert repr(sg) == '<SegmentGroup with 1 segment>'
def test_segmentgroup_str(self, u):
sg = u.segments[:10]
assert str(sg) == '<SegmentGroup [<Segment 4AKE>]>'
def _yield_mix(groups, components):
indices = list(range(len(components)))
for left, right in itertools.permutations(indices, 2):
yield (groups[left], components[right])
yield (components[left], groups[right])
def _yield_sliced_groups(u, slice_left, slice_right):
for level in ('atoms', 'residues', 'segments'):
yield (getattr(u, level)[slice_left], getattr(u, level)[slice_right])
class TestGroupBaseOperators(object):
u = make_Universe()
components = (u.atoms[0], u.residues[0], u.segments[0])
component_groups = (u.atoms, u.residues, u.segments)
@pytest.fixture(params=('atoms', 'residues', 'segments'))
def level(self, request):
return request.param
@pytest.fixture
def groups_simple(self, level):
n_segments = 10
n_residues = n_segments * 5
n_atoms = n_residues * 5
u = make_Universe(size=(n_atoms, n_residues, n_segments))
# 0123456789
# a ****
# b *****
# c **
# e ***
# d empty
#
# None of the group start at 0, nor ends at the end. Each group
# has a different size. The end of a slice is not the last element.
# This increase the odds of catching errors.
a = getattr(u, level)[1:5]
b = getattr(u, level)[3:8]
c = getattr(u, level)[3:5]
d = getattr(u, level)[0:0]
e = getattr(u, level)[5:8]
return a, b, c, d, e
@pytest.fixture
def groups_duplicated_and_scrambled(self, level):
# The content of the groups is the same as for make_groups, but the
# elements can appear several times and their order is scrambled.
n_segments = 10
n_residues = n_segments * 5
n_atoms = n_residues * 5
u = make_Universe(size=(n_atoms, n_residues, n_segments))
a = getattr(u, level)[[1, 3, 2, 1, 2, 4, 4]]
b = getattr(u, level)[[7, 4, 4, 6, 5, 3, 7, 6]]
c = getattr(u, level)[[4, 4, 3, 4, 3, 3]]
d = getattr(u, level)[0:0]
e = getattr(u, level)[[6, 5, 7, 7, 6]]
return a, b, c, d, e
@pytest.fixture(params=('simple', 'scrambled'))
def groups(self, request, groups_simple, groups_duplicated_and_scrambled):
return {'simple': groups_simple,
'scrambled': groups_duplicated_and_scrambled}[request.param]
def test_len(self, groups_simple):
a, b, c, d, e = groups_simple
assert_equal(len(a), 4)
assert_equal(len(b), 5)
assert_equal(len(c), 2)
assert_equal(len(d), 0)
assert_equal(len(e), 3)
def test_len_duplicated_and_scrambled(self, groups_duplicated_and_scrambled):
a, b, c, d, e = groups_duplicated_and_scrambled
assert_equal(len(a), 7)
assert_equal(len(b), 8)
assert_equal(len(c), 6)
assert_equal(len(d), 0)
assert_equal(len(e), 5)
def test_equal(self, groups):
a, b, c, d, e = groups
assert a == a
assert a != b
assert not a == b
assert not a[0:1] == a[0], \
'Element should not equal single element group.'
@pytest.mark.parametrize('group', (u.atoms[:2], u.residues[:2],
u.segments[:2]))
def test_copy(self, group):
# make sure uniqueness caches of group are empty:
with pytest.raises(KeyError):
_ = group._cache['isunique']
with pytest.raises(KeyError):
_ = group._cache['unique']
# make a copy:
cgroup = group.copy()
# check if cgroup is an identical copy of group:
assert type(cgroup) is type(group)
assert cgroup is not group
assert cgroup == group
# check if the copied group's uniqueness caches are empty:
with pytest.raises(KeyError):
_ = cgroup._cache['isunique']
with pytest.raises(KeyError):
_ = cgroup._cache['unique']
# populate group's uniqueness caches:
assert group.isunique
# make a copy:
cgroup = group.copy()
# check if the copied group's uniqueness caches are set correctly:
assert cgroup._cache['isunique'] is True
assert cgroup._cache['unique'] is cgroup