-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathtest_table.py
4530 lines (3915 loc) · 182 KB
/
test_table.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
# ----------------------------------------------------------------------------
# Copyright (c) 2011-2017, The BIOM Format Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
import os
from json import loads
from tempfile import NamedTemporaryFile
from unittest import TestCase, main
from io import StringIO
import numpy.testing as npt
import numpy as np
from scipy.sparse import lil_matrix, csr_matrix, csc_matrix
import scipy.sparse
import pandas.util.testing as pdt
import pandas as pd
import pytest
from biom import example_table, load_table, concat
from biom.exception import (UnknownAxisError, UnknownIDError, TableException,
DisjointIDError)
from biom.util import unzip, HAVE_H5PY, H5PY_VLEN_STR
from biom.table import (Table, prefer_self, index_list, list_nparray_to_sparse,
list_dict_to_sparse, dict_to_sparse,
coo_arrays_to_sparse, list_list_to_sparse,
nparray_to_sparse, list_sparse_to_sparse,
_identify_bad_value, general_parser)
from biom.parse import parse_biom_table
from biom.err import errstate
np.random.seed(1234)
if HAVE_H5PY:
import h5py
try:
import anndata
anndata.__version__
HAVE_ANNDATA = True
except ImportError:
HAVE_ANNDATA = False
try:
import skbio
HAVE_SKBIO = True
except ImportError:
HAVE_SKBIO = False
__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2011-2017, The BIOM Format Development Team"
__credits__ = ["Daniel McDonald", "Jai Ram Rideout", "Justin Kuczynski",
"Greg Caporaso", "Jose Clemente", "Adam Robbins-Pianka",
"Joshua Shorenstein", "Jose Antonio Navas Molina",
"Jorge Canardo Alastuey", "Steven Brown"]
__license__ = "BSD"
__url__ = "http://biom-format.org"
__maintainer__ = "Daniel McDonald"
__email__ = "daniel.mcdonald@colorado.edu"
class SupportTests(TestCase):
def test_head(self):
# example table is 2 x 3, so no change in contained data
exp = example_table
obs = example_table.head()
self.assertIsNot(obs, exp)
self.assertEqual(obs, exp)
def test_head_bounded(self):
obs = example_table.head(1)
exp = Table(np.array([[0., 1., 2.]]), ['O1'], ['S1', 'S2', 'S3'],
[{'taxonomy': ['Bacteria', 'Firmicutes']}],
[{'environment': 'A'}, {'environment': 'B'},
{'environment': 'A'}])
self.assertEqual(obs, exp)
obs = example_table.head(m=2)
exp = Table(np.array([[0., 1.], [3., 4.]]), ['O1', 'O2'], ['S1', 'S2'],
[{'taxonomy': ['Bacteria', 'Firmicutes']},
{'taxonomy': ['Bacteria', 'Bacteroidetes']}],
[{'environment': 'A'}, {'environment': 'B'}])
self.assertEqual(obs, exp)
def test_head_overstep(self):
# silently works
exp = example_table
obs = example_table.head(10000)
self.assertIsNot(obs, exp)
self.assertEqual(obs, exp)
def test_head_zero_or_neg(self):
with self.assertRaises(IndexError):
example_table.head(0)
with self.assertRaises(IndexError):
example_table.head(-1)
with self.assertRaises(IndexError):
example_table.head(m=0)
with self.assertRaises(IndexError):
example_table.head(m=-1)
with self.assertRaises(IndexError):
example_table.head(0, 5)
with self.assertRaises(IndexError):
example_table.head(5, 0)
def test_remove_empty_sample(self):
t = example_table.copy()
t._data[:, 0] = 0
t.remove_empty()
exp = example_table.filter({'S2', 'S3'}, inplace=False)
self.assertEqual(t, exp)
def test_remove_empty_obs(self):
t = example_table.copy()
t._data[0, :] = 0
t.remove_empty()
exp = example_table.filter({'O2', }, axis='observation',
inplace=False)
self.assertEqual(t, exp)
def test_remove_empty_both(self):
t = example_table.copy()
t._data[:, 0] = 0
t._data[0, :] = 0
obs_base = t.copy()
obs = obs_base.remove_empty(inplace=False)
exp = example_table.filter({'S2', 'S3'}, inplace=False)
exp = exp.filter({'O2', }, axis='observation', inplace=False)
self.assertEqual(obs, exp)
def test_remove_empty_identity(self):
obs = example_table.copy()
obs.remove_empty()
exp = example_table.copy()
self.assertEqual(obs, exp)
def test_concat_table_type(self):
table1 = example_table.copy()
table1.type = 'foo'
table2 = example_table.copy()
table2.update_ids({'S1': 'S4', 'S2': 'S5', 'S3': 'S6'})
exp = Table(np.array([[0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5]]),
['O1', 'O2'],
['S1', 'S2', 'S3', 'S4', 'S5', 'S6'],
example_table.metadata(axis='observation'),
list(example_table.metadata()) * 2,
type='foo')
obs = table1.concat([table2, ], axis='sample')
self.assertEqual(obs, exp)
def test_concat_single_table_nonlist(self):
table2 = example_table.copy()
table2.update_ids({'S1': 'S4', 'S2': 'S5', 'S3': 'S6'})
exp = Table(np.array([[0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5]]),
['O1', 'O2'],
['S1', 'S2', 'S3', 'S4', 'S5', 'S6'],
example_table.metadata(axis='observation'),
list(example_table.metadata()) * 2)
obs = example_table.concat(table2, axis='sample')
self.assertEqual(obs, exp)
def test_concat_empty(self):
exp = example_table.copy()
obs = example_table.concat([])
self.assertEqual(obs, exp)
def test_concat_wrapper(self):
table2 = example_table.copy()
table2.update_ids({'S1': 'S4', 'S2': 'S5', 'S3': 'S6'})
exp = Table(np.array([[0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5]]),
['O1', 'O2'],
['S1', 'S2', 'S3', 'S4', 'S5', 'S6'],
example_table.metadata(axis='observation'),
list(example_table.metadata()) * 2)
obs = concat([example_table, table2], axis='sample')
self.assertEqual(obs, exp)
def test_concat_samples(self):
table2 = example_table.copy()
table2.update_ids({'S1': 'S4', 'S2': 'S5', 'S3': 'S6'})
exp = Table(np.array([[0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5]]),
['O1', 'O2'],
['S1', 'S2', 'S3', 'S4', 'S5', 'S6'],
example_table.metadata(axis='observation'),
list(example_table.metadata()) * 2)
obs = example_table.concat([table2, ], axis='sample')
self.assertEqual(obs, exp)
def test_concat_observations(self):
table2 = example_table.copy()
table2.update_ids({'O1': 'O3', 'O2': 'O4'}, axis='observation')
exp = Table(np.array([[0, 1, 2],
[3, 4, 5],
[0, 1, 2],
[3, 4, 5]]),
['O1', 'O2', 'O3', 'O4'],
['S1', 'S2', 'S3'],
list(example_table.metadata(axis='observation')) * 2,
example_table.metadata())
obs = example_table.concat([table2, ], axis='observation')
self.assertEqual(obs, exp)
def test_concat_multiple(self):
table2 = example_table.copy()
table2.update_ids({'O1': 'O3', 'O2': 'O4'}, axis='observation')
table3 = example_table.copy()
table3.update_ids({'O1': 'O5', 'O2': 'O6'}, axis='observation')
exp = Table(np.array([[0, 1, 2],
[3, 4, 5],
[0, 1, 2],
[3, 4, 5],
[0, 1, 2],
[3, 4, 5]]),
['O1', 'O2', 'O3', 'O4', 'O5', 'O6'],
['S1', 'S2', 'S3'],
list(example_table.metadata(axis='observation')) * 3,
example_table.metadata())
obs = example_table.concat([table2, table3], axis='observation')
self.assertEqual(obs, exp)
def test_concat_different_order(self):
table2 = example_table.sort_order(['S3', 'S2', 'S1'])
table2.update_ids({'S1': 'S4', 'S2': 'S5', 'S3': 'S6'})
table2 = table2.sort_order(['O2', 'O1'], axis='observation')
table3 = example_table.sort_order(['S2', 'S1', 'S3'])
table3.update_ids({'S1': 'S7', 'S2': 'S8', 'S3': 'S9'})
exp = Table(np.array([[0, 1, 2, 2, 1, 0, 1, 0, 2],
[3, 4, 5, 5, 4, 3, 4, 3, 5]]),
['O1', 'O2'],
['S1', 'S2', 'S3', 'S6', 'S5', 'S4', 'S8', 'S7', 'S9'],
example_table.metadata(axis='observation'),
list(example_table.metadata()) +
list(table2.metadata()) +
list(table3.metadata()))
obs = example_table.concat([table2, table3], axis='sample')
self.assertEqual(obs, exp)
def test_concat_pad_on_subset(self):
table2 = example_table.copy()
table2.update_ids({'O2': 'O3'}, axis='observation', strict=False)
table2.update_ids({'S1': 'S4', 'S2': 'S5', 'S3': 'S6'})
exp_obs_md = list(example_table.metadata(axis='observation'))
exp_obs_md.append(example_table.metadata('O2', axis='observation'))
exp = Table(np.array([[0, 1, 2, 0, 1, 2],
[3, 4, 5, 0, 0, 0],
[0, 0, 0, 3, 4, 5]]),
['O1', 'O2', 'O3'],
['S1', 'S2', 'S3', 'S4', 'S5', 'S6'],
exp_obs_md,
list(example_table.metadata()) * 2)
obs = example_table.concat([table2, ], axis='sample')
self.assertEqual(obs, exp)
def test_concat_no_metadata_bug(self):
table1 = example_table.copy()
table1._sample_metadata = None
table1._observation_metadata = None
table2 = example_table.copy()
table2._sample_metadata = None
table2._observation_metadata = None
table2.update_ids({'O2': 'O3'}, axis='observation', strict=False)
table2.update_ids({'S1': 'S4', 'S2': 'S5', 'S3': 'S6'})
exp = Table(np.array([[0, 1, 2, 0, 1, 2],
[3, 4, 5, 0, 0, 0],
[0, 0, 0, 3, 4, 5]]),
['O1', 'O2', 'O3'],
['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])
obs = table1.concat([table2, ], axis='sample')
self.assertEqual(obs, exp)
def test_concat_raise_overlap(self):
with self.assertRaises(DisjointIDError):
example_table.concat([example_table])
with self.assertRaises(DisjointIDError):
example_table.concat([example_table], axis='observation')
def test_align_to_no_overlap(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['w', 'x'], ['y', 'z'])
with self.assertRaises(DisjointIDError):
a.align_to(b)
def test_align_to_overlap_observation(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['b', 'a'], ['y', 'z'])
exp = Table(np.array([[2, 3], [0, 1]]), ['a', 'b'], ['y', 'z'])
obs = b.align_to(a, axis='observation')
self.assertEqual(obs, exp)
def test_align_to_overlap_observation_no_overlap(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['x', 'y'], ['y', 'z'])
with self.assertRaises(DisjointIDError):
b.align_to(a, axis='observation')
def test_align_to_overlap_sample_no_overlap(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['b', 'a'], ['y', 'z'])
with self.assertRaises(DisjointIDError):
b.align_to(a, axis='sample')
def test_align_to_overlap_both_no_overlap(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['b', 'a'], ['y', 'z'])
with self.assertRaises(DisjointIDError):
# should fail if one axis doesn't overlap
b.align_to(a, axis='both')
def test_align_to_overlap_autodetect_observation(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['b', 'a'], ['y', 'z'])
exp = Table(np.array([[2, 3], [0, 1]]), ['a', 'b'], ['y', 'z'])
obs = b.align_to(a)
self.assertEqual(obs, exp)
def test_align_to_overlap_sample(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['d', 'c'])
exp = Table(np.array([[1, 0], [3, 2]]), ['a', 'b'], ['c', 'd'])
obs = b.align_to(a, axis='sample')
self.assertEqual(obs, exp)
def test_align_to_overlap_autodetect_sample(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['d', 'c'])
exp = Table(np.array([[1, 0], [3, 2]]), ['a', 'b'], ['c', 'd'])
obs = b.align_to(a)
self.assertEqual(obs, exp)
def test_align_to_overlap_both(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['b', 'a'], ['d', 'c'])
exp = Table(np.array([[3, 2], [1, 0]]), ['a', 'b'], ['c', 'd'])
obs = b.align_to(a, axis='both')
self.assertEqual(obs, exp)
def test_align_to_overlap_autodetect_both(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[0, 1], [2, 3]]), ['b', 'a'], ['d', 'c'])
exp = Table(np.array([[3, 2], [1, 0]]), ['a', 'b'], ['c', 'd'])
obs = b.align_to(a)
self.assertEqual(obs, exp)
def test_align_to_overlap_autodetect_vary_values(self):
a = Table(np.array([[0, 1], [2, 3]]), ['a', 'b'], ['c', 'd'])
b = Table(np.array([[10, 11], [12, 13]]), ['b', 'a'], ['d', 'c'])
exp = Table(np.array([[13, 12], [11, 10]]), ['a', 'b'], ['c', 'd'])
obs = b.align_to(a)
self.assertEqual(obs, exp)
def test_table_sparse_nparray(self):
"""beat the table sparsely to death"""
# nparray test
samp_ids = ['1', '2', '3', '4']
obs_ids = ['a', 'b', 'c']
nparray = np.array([[1, 2, 3, 4], [-1, 6, 7, 8], [9, 10, 11, 12]])
data = nparray_to_sparse(
np.array([[1, 2, 3, 4], [-1, 6, 7, 8], [9, 10, 11, 12]]))
exp = Table(data, obs_ids, samp_ids)
obs = Table(nparray, obs_ids, samp_ids)
self.assertEqual(obs, exp)
def test_table_sparse_list_nparray(self):
"""beat the table sparsely to death"""
# list of nparray test
samp_ids = ['1', '2', '3', '4']
obs_ids = ['a', 'b', 'c']
list_np = [np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]),
np.array([9, 10, 11, 12])]
data = list_nparray_to_sparse(list_np)
exp = Table(data, obs_ids, samp_ids)
obs = Table(list_np, obs_ids, samp_ids)
self.assertEqual(obs, exp)
def test_table_sparse_dict(self):
"""beat the table sparsely to death"""
# dict test
samp_ids = range(24)
obs_ids = range(101)
dict_input = {(0, 0): 1, (0, 10): 5, (100, 23): -3}
d_input = np.zeros((101, 24), dtype=float)
d_input[0, 0] = 1
d_input[0, 10] = 5
d_input[100, 23] = -3
data = nparray_to_sparse(d_input)
exp = Table(data, obs_ids, samp_ids)
obs = Table(dict_input, obs_ids, samp_ids)
self.assertEqual(obs, exp)
def test_table_sparse_list_dict(self):
"""beat the table sparsely to death"""
# list of dict test
samp_ids = range(11)
obs_ids = range(3)
ld_input = np.zeros((3, 11), dtype=float)
ld_input[0, 5] = 10
ld_input[0, 10] = 2
ld_input[1, 1] = 15
ld_input[2, 3] = 7
data = nparray_to_sparse(ld_input)
exp = Table(data, obs_ids, samp_ids)
list_dict = [{(0, 5): 10, (10, 10): 2}, {(0, 1): 15}, {(0, 3): 7}]
obs = Table(list_dict, obs_ids, samp_ids)
self.assertEqual(obs, exp)
def test_table_sparse_list_list(self):
"""beat the table sparsely to death"""
# list list test
samp_ids = range(3)
obs_ids = range(2)
exp_data = lil_matrix((2, 3))
exp_data[0, 1] = 5
exp_data[1, 2] = 10
exp = Table(exp_data, obs_ids, samp_ids)
input_ = [[0, 1, 5], [1, 2, 10]]
obs = Table(input_, obs_ids, samp_ids)
self.assertEqual(obs, exp)
def test_table_exception(self):
"""Make sure a TableException can be raised"""
def f():
raise TableException
self.assertRaises(TableException, f)
def test_prefer_self(self):
"""prefer x"""
exp = 1
obs = prefer_self(1, 2)
self.assertEqual(obs, exp)
exp = 2
obs = prefer_self(None, 2)
self.assertEqual(obs, exp)
exp = None
obs = prefer_self(None, None)
self.assertEqual(obs, exp)
def test_index_list(self):
"""returns a dict for list lookups"""
exp = {'a': 2, 'b': 0, 'c': 1}
obs = index_list(['b', 'c', 'a'])
self.assertEqual(obs, exp)
class TableTests(TestCase):
def setUp(self):
self.simple_derived = Table(
np.array([[5, 6], [7, 8]]), [3, 4], [1, 2])
self.vals = {(0, 0): 5, (0, 1): 6, (1, 0): 7, (1, 1): 8}
self.st1 = Table(self.vals, ['1', '2'], ['a', 'b'])
self.st2 = Table(self.vals, ['1', '2'], ['a', 'b'])
self.vals3 = {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4}
self.vals4 = {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4}
self.st3 = Table(self.vals3, ['2', '3'], ['b', 'c'])
self.st4 = Table(self.vals4, ['3', '4'], ['c', 'd'])
self.st_rich = Table(self.vals,
['1', '2'], ['a', 'b'],
[{'taxonomy': ['k__a', 'p__b']},
{'taxonomy': ['k__a', 'p__c']}],
[{'barcode': 'aatt'}, {'barcode': 'ttgg'}],
)
self.st_group_rich = Table(
self.vals, ['1', '2'], ['a', 'b'],
[{'taxonomy': ['k__a', 'p__b']}, {'taxonomy': ['k__a', 'p__c']}],
[{'barcode': 'aatt'}, {'barcode': 'ttgg'}],
observation_group_metadata={'tree': ('newick', '(a:0.3,b:0.4);')},
sample_group_metadata={'category': ('newick', '(1:0.3,2:0.4);')}
)
self.empty_st = Table([], [], [])
self.vals5 = {(0, 1): 2, (1, 1): 4}
self.st5 = Table(self.vals5, ['5', '6'], ['a', 'b'])
self.vals6 = {(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 0}
self.st6 = Table(self.vals6, ['5', '6'], ['a', 'b'])
self.vals7 = {(0, 0): 5, (0, 1): 7, (1, 0): 8, (1, 1): 0}
self.st7 = Table(self.vals7, ['5', '6'], ['a', 'b'])
self.single_sample_st = Table(
np.array([[2.0], [0.0], [1.0]]), ['O1', 'O2', 'O3'],
['S1'])
self.single_obs_st = Table(np.array([[2.0, 0.0, 1.0]]),
['01'], ['S1', 'S2', 'S3'])
self.to_remove = []
# 1 0 2
# 3 0 4
self.mat1 = Table(np.array([[1, 0, 2], [3, 0, 4]]),
['o1', 'o2'], ['s1', 's2', 's3'])
# Empty/null cases (i.e., 0x0, 0xn, nx0).
def ids(X):
return ['x%d' % e for e in range(0, X)]
self.null1 = Table(np.zeros((0, 0)), [], [])
self.null2 = Table(
np.zeros((0, 42), dtype=float), [], ids(42))
self.null3 = Table(
np.zeros((42, 0), dtype=float), ids(42), [])
self.nulls = [self.null1, self.null2, self.null3]
# 0 0
# 0 0
self.empty = Table(np.zeros((2, 2)), ids(2), ids(2))
# 1 0 3
h = np.array([[1.0, 0.0, 3.0]])
self.row_vec = Table(h, ids(1), ids(3))
# 1
# 0
# 3
h = np.array([[1], [0], [3]])
self.col_vec = Table(h, ids(3), ids(1))
# 1x1
h = np.array([[42]])
self.single_ele = Table(h, ['b'], ['a'])
# Explicit zeros.
self.explicit_zeros = Table(np.array([[0, 0, 1], [1, 0, 0],
[1, 0, 2]]),
['a', 'b', 'c'], ['x', 'y', 'z'])
def tearDown(self):
if self.to_remove:
for f in self.to_remove:
os.remove(f)
def test_data_property(self):
exp = self.simple_derived._data
obs = self.simple_derived.matrix_data
self.assertEqual((obs != exp).nnz, 0)
with self.assertRaises(AttributeError):
self.simple_derived.matrix_data = 'foo'
def test_repr(self):
"""__repr__ method of biom.table.Table"""
# table
data = np.asarray([[0, 0, 0], [0, 1, 0], [0, 0, 0]])
t = Table(data, ['a', 'b', 'c'], ['x', 'y', 'z'])
self.assertEqual("3 x 3 <class 'biom.table.Table'> with 1 nonzero "
"entries (11% dense)", repr(t))
# empty table
data = np.asarray([[]])
t = Table(data, [], [])
self.assertEqual("0 x 0 <class 'biom.table.Table'> with 0 nonzero "
"entries (0% dense)", repr(t))
def test_init_with_nparray(self):
"""to_sparse in constructor should be triggered"""
data = np.array([[1, 2], [3, 4]])
samp_ids = ['a', 'b']
obs_ids = ['1', '2']
exp = Table(data, obs_ids, samp_ids)
obs = Table(data, obs_ids, samp_ids)
self.assertEqual(obs, exp)
def test_min_observation(self):
exp = np.array([5, 7])
obs = self.simple_derived.min('observation')
npt.assert_equal(obs, exp)
def test_min_sample(self):
exp = np.array([5, 6])
obs = self.simple_derived.min('sample')
npt.assert_equal(obs, exp)
def test_min_whole(self):
exp = 5
obs = self.simple_derived.min('whole')
npt.assert_equal(obs, exp)
def test_max_observation(self):
exp = np.array([6, 8])
obs = self.simple_derived.max('observation')
npt.assert_equal(obs, exp)
def test_max_sample(self):
exp = np.array([7, 8])
obs = self.simple_derived.max('sample')
npt.assert_equal(obs, exp)
def test_max_whole(self):
exp = 8
obs = self.simple_derived.max('whole')
npt.assert_equal(obs, exp)
def test_general_parser(self):
test_and_exp = [(b'foo', 'foo'),
('foo', 'foo'),
(b'', ''),
('', ''),
(b'10', '10'),
('10', '10'),
(b'3.14', '3.14'),
('3.14', '3.14')]
for test, exp in test_and_exp:
obs = general_parser(test)
self.assertEqual(obs, exp)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_non_hdf5_file_or_group(self):
with self.assertRaises(ValueError):
Table.from_hdf5(10)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_empty_md(self):
"""Parse a hdf5 formatted BIOM table w/o metadata"""
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/empty.biom'))
os.chdir(cwd)
self.assertTrue(t._sample_metadata is None)
self.assertTrue(t._observation_metadata is None)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_custom_parsers(self):
def parser(item):
return general_parser(item).upper()
parse_fs = {'BODY_SITE': parser}
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/test.biom'),
parse_fs=parse_fs)
os.chdir(cwd)
for m in t.metadata():
self.assertIn(m['BODY_SITE'], ('GUT', 'SKIN', b'GUT', b'SKIN'))
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_issue_731(self):
t = Table.from_hdf5(h5py.File('test_data/test.biom'))
self.assertTrue(isinstance(t.table_id, str))
self.assertTrue(isinstance(t.type, str))
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5(self):
"""Parse a hdf5 formatted BIOM table"""
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/test.biom'))
os.chdir(cwd)
npt.assert_equal(t.ids(), ('Sample1', 'Sample2', 'Sample3',
'Sample4', 'Sample5', 'Sample6'))
npt.assert_equal(t.ids(axis='observation'),
('GG_OTU_1', 'GG_OTU_2', 'GG_OTU_3',
'GG_OTU_4', 'GG_OTU_5'))
exp_obs_md = (
{'taxonomy': [
'k__Bacteria',
'p__Proteobacteria',
'c__Gammaproteobacteria',
'o__Enterobacteriales',
'f__Enterobacteriaceae',
'g__Escherichia',
's__',
]},
{'taxonomy': [
'k__Bacteria',
'p__Cyanobacteria',
'c__Nostocophycideae',
'o__Nostocales',
'f__Nostocaceae',
'g__Dolichospermum',
's__',
]},
{'taxonomy': [
'k__Archaea',
'p__Euryarchaeota',
'c__Methanomicrobia',
'o__Methanosarcinales',
'f__Methanosarcinaceae',
'g__Methanosarcina',
's__',
]},
{'taxonomy': [
'k__Bacteria',
'p__Firmicutes',
'c__Clostridia',
'o__Halanaerobiales',
'f__Halanaerobiaceae',
'g__Halanaerobium',
's__Halanaerobiumsaccharolyticum',
]},
{'taxonomy': [
'k__Bacteria',
'p__Proteobacteria',
'c__Gammaproteobacteria',
'o__Enterobacteriales',
'f__Enterobacteriaceae',
'g__Escherichia',
's__',
]})
self.assertEqual(t._observation_metadata, exp_obs_md)
exp_samp_md = ({'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CGCTTATCGAGA',
'Description': 'human gut',
'BODY_SITE': 'gut'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CATACCAGTAGC',
'Description': 'human gut',
'BODY_SITE': 'gut'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTCTCTACCTGT',
'Description': 'human gut',
'BODY_SITE': 'gut'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTCTCGGCCTGT',
'Description': 'human skin',
'BODY_SITE': 'skin'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTCTCTACCAAT',
'Description': 'human skin',
'BODY_SITE': 'skin'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTAACTACCAAT',
'Description': 'human skin',
'BODY_SITE': 'skin'})
self.assertEqual(t._sample_metadata, exp_samp_md)
exp = [np.array([0., 0., 1., 0., 0., 0.]),
np.array([5., 1., 0., 2., 3., 1.]),
np.array([0., 0., 1., 4., 0., 2.]),
np.array([2., 1., 1., 0., 0., 1.]),
np.array([0., 1., 1., 0., 0., 0.])]
npt.assert_equal(list(t.iter_data(axis="observation")), exp)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_sample_subset_no_metadata(self):
"""Parse a sample subset of a hdf5 formatted BIOM table"""
samples = [b'Sample2', b'Sample4', b'Sample6']
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/test.biom'), ids=samples,
subset_with_metadata=False)
os.chdir(cwd)
npt.assert_equal(t.ids(), ['Sample2', 'Sample4', 'Sample6'])
npt.assert_equal(t.ids(axis='observation'),
['GG_OTU_1', 'GG_OTU_2', 'GG_OTU_3', 'GG_OTU_4',
'GG_OTU_5'])
exp_obs_md = None
self.assertEqual(t._observation_metadata, exp_obs_md)
exp_samp_md = None
self.assertEqual(t._sample_metadata, exp_samp_md)
exp = [np.array([0, 0, 0]),
np.array([1., 2., 1.]),
np.array([0., 4., 2.]),
np.array([1., 0., 1.]),
np.array([1., 0., 0.])]
npt.assert_equal(list(t.iter_data(axis='observation')), exp)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_sample_subset(self):
"""Parse a sample subset of a hdf5 formatted BIOM table"""
samples = ['Sample2', 'Sample4', 'Sample6']
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/test.biom'), ids=samples)
os.chdir(cwd)
npt.assert_equal(t.ids(), ['Sample2', 'Sample4', 'Sample6'])
npt.assert_equal(t.ids(axis='observation'),
['GG_OTU_2', 'GG_OTU_3', 'GG_OTU_4', 'GG_OTU_5'])
exp_obs_md = (
{'taxonomy': [
'k__Bacteria',
'p__Cyanobacteria',
'c__Nostocophycideae',
'o__Nostocales',
'f__Nostocaceae',
'g__Dolichospermum',
's__',
]},
{'taxonomy': [
'k__Archaea',
'p__Euryarchaeota',
'c__Methanomicrobia',
'o__Methanosarcinales',
'f__Methanosarcinaceae',
'g__Methanosarcina',
's__',
]},
{'taxonomy': [
'k__Bacteria',
'p__Firmicutes',
'c__Clostridia',
'o__Halanaerobiales',
'f__Halanaerobiaceae',
'g__Halanaerobium',
's__Halanaerobiumsaccharolyticum',
]},
{'taxonomy': [
'k__Bacteria',
'p__Proteobacteria',
'c__Gammaproteobacteria',
'o__Enterobacteriales',
'f__Enterobacteriaceae',
'g__Escherichia',
's__',
]})
self.assertEqual(t._observation_metadata, exp_obs_md)
exp_samp_md = ({'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CATACCAGTAGC',
'Description': 'human gut',
'BODY_SITE': 'gut'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTCTCGGCCTGT',
'Description': 'human skin',
'BODY_SITE': 'skin'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTAACTACCAAT',
'Description': 'human skin',
'BODY_SITE': 'skin'})
self.assertEqual(t._sample_metadata, exp_samp_md)
exp = [np.array([1., 2., 1.]),
np.array([0., 4., 2.]),
np.array([1., 0., 1.]),
np.array([1., 0., 0.])]
npt.assert_equal(list(t.iter_data(axis='observation')), exp)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_observation_subset_no_metadata(self):
"""Parse a observation subset of a hdf5 formatted BIOM table"""
observations = [b'GG_OTU_1', b'GG_OTU_3', b'GG_OTU_5']
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/test.biom'),
ids=observations, axis='observation',
subset_with_metadata=False)
os.chdir(cwd)
npt.assert_equal(t.ids(), ['Sample1', 'Sample2', 'Sample3',
'Sample4', 'Sample5', 'Sample6'])
npt.assert_equal(t.ids(axis='observation'),
['GG_OTU_1', 'GG_OTU_3', 'GG_OTU_5'])
exp_obs_md = None
self.assertEqual(t._observation_metadata, exp_obs_md)
exp_samp_md = None
self.assertEqual(t._sample_metadata, exp_samp_md)
exp = [np.array([0, 0., 1., 0., 0, 0.]),
np.array([0, 0., 1., 4., 0, 2.]),
np.array([0, 1., 1., 0., 0, 0.])]
npt.assert_equal(list(t.iter_data(axis='observation')), exp)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_observation_subset(self):
"""Parse a observation subset of a hdf5 formatted BIOM table"""
observations = ['GG_OTU_1', 'GG_OTU_3', 'GG_OTU_5']
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/test.biom'),
ids=observations, axis='observation')
os.chdir(cwd)
npt.assert_equal(t.ids(), ['Sample2', 'Sample3', 'Sample4',
'Sample6'])
npt.assert_equal(t.ids(axis='observation'),
['GG_OTU_1', 'GG_OTU_3', 'GG_OTU_5'])
exp_obs_md = (
{'taxonomy': [
'k__Bacteria',
'p__Proteobacteria',
'c__Gammaproteobacteria',
'o__Enterobacteriales',
'f__Enterobacteriaceae',
'g__Escherichia',
's__',
]},
{'taxonomy': [
'k__Archaea',
'p__Euryarchaeota',
'c__Methanomicrobia',
'o__Methanosarcinales',
'f__Methanosarcinaceae',
'g__Methanosarcina',
's__',
]},
{'taxonomy': [
'k__Bacteria',
'p__Proteobacteria',
'c__Gammaproteobacteria',
'o__Enterobacteriales',
'f__Enterobacteriaceae',
'g__Escherichia',
's__',
]})
self.assertEqual(t._observation_metadata, exp_obs_md)
exp_samp_md = ({'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CATACCAGTAGC',
'Description': 'human gut',
'BODY_SITE': 'gut'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTCTCTACCTGT',
'Description': 'human gut',
'BODY_SITE': 'gut'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTCTCGGCCTGT',
'Description': 'human skin',
'BODY_SITE': 'skin'},
{'LinkerPrimerSequence': 'CATGCTGCCTCCCGTAGGAGT',
'BarcodeSequence': 'CTAACTACCAAT',
'Description': 'human skin',
'BODY_SITE': 'skin'})
self.assertEqual(t._sample_metadata, exp_samp_md)
exp = [np.array([0., 1., 0., 0.]),
np.array([0., 1., 4., 2.]),
np.array([1., 1., 0., 0.])]
npt.assert_equal(list(t.iter_data(axis='observation')), exp)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_subset_error(self):
"""hdf5 biom table parse throws error with invalid parameters"""
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
# Raises an error if not all the given samples are in the OTU table
with self.assertRaises(ValueError):
Table.from_hdf5(h5py.File('test_data/test.biom'),
ids=['Sample2', 'DoesNotExist', 'Sample6'])
# Raises an error if not all the given observation are in the OTU table
with self.assertRaises(ValueError):
Table.from_hdf5(h5py.File('test_data/test.biom'),
ids=['GG_OTU_1', 'DoesNotExist'],
axis='observation')
os.chdir(cwd)
@pytest.mark.skipif(HAVE_H5PY is False, reason='H5PY is not installed')
def test_from_hdf5_empty_table(self):
"""HDF5 biom parse successfully loads an empty table"""
cwd = os.getcwd()
if '/' in __file__:
os.chdir(__file__.rsplit('/', 1)[0])
t = Table.from_hdf5(h5py.File('test_data/empty.biom'))
os.chdir(cwd)
npt.assert_equal(t.ids(), [])
npt.assert_equal(t.ids(axis='observation'), [])
self.assertEqual(t._observation_metadata, None)
self.assertEqual(t._sample_metadata, None)
npt.assert_equal(list(t.iter_data(axis='observation')), [])