-
Notifications
You must be signed in to change notification settings - Fork 95
/
table.py
5533 lines (4622 loc) · 193 KB
/
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
#!/usr/bin/env python
"""
BIOM Table (:mod:`biom.table`)
==============================
The biom-format project provides rich ``Table`` objects to support use of the
BIOM file format. The objects encapsulate matrix data (such as OTU counts) and
abstract the interaction away from the programmer.
.. currentmodule:: biom.table
Classes
-------
.. autosummary::
:toctree: generated/
Table
Examples
--------
First, let's create a toy table to play around with. For this example, we're
going to construct a 10x4 `Table`, or one that has 10 observations and 4
samples. Each observation and sample will be given an arbitrary but unique
name. We'll also add on some metadata.
>>> import numpy as np
>>> from biom.table import Table
>>> data = np.arange(40).reshape(10, 4)
>>> sample_ids = ['S%d' % i for i in range(4)]
>>> observ_ids = ['O%d' % i for i in range(10)]
>>> sample_metadata = [{'environment': 'A'}, {'environment': 'B'},
... {'environment': 'A'}, {'environment': 'B'}]
>>> observ_metadata = [{'taxonomy': ['Bacteria', 'Firmicutes']},
... {'taxonomy': ['Bacteria', 'Firmicutes']},
... {'taxonomy': ['Bacteria', 'Proteobacteria']},
... {'taxonomy': ['Bacteria', 'Proteobacteria']},
... {'taxonomy': ['Bacteria', 'Proteobacteria']},
... {'taxonomy': ['Bacteria', 'Bacteroidetes']},
... {'taxonomy': ['Bacteria', 'Bacteroidetes']},
... {'taxonomy': ['Bacteria', 'Firmicutes']},
... {'taxonomy': ['Bacteria', 'Firmicutes']},
... {'taxonomy': ['Bacteria', 'Firmicutes']}]
>>> table = Table(data, observ_ids, sample_ids, observ_metadata,
... sample_metadata, table_id='Example Table')
Now that we have a table, let's explore it at a high level first.
>>> table
10 x 4 <class 'biom.table.Table'> with 39 nonzero entries (97% dense)
>>> print(table) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0 S1 S2 S3
O0 0.0 1.0 2.0 3.0
O1 4.0 5.0 6.0 7.0
O2 8.0 9.0 10.0 11.0
O3 12.0 13.0 14.0 15.0
O4 16.0 17.0 18.0 19.0
O5 20.0 21.0 22.0 23.0
O6 24.0 25.0 26.0 27.0
O7 28.0 29.0 30.0 31.0
O8 32.0 33.0 34.0 35.0
O9 36.0 37.0 38.0 39.0
>>> print(table.ids()) # doctest: +NORMALIZE_WHITESPACE
['S0' 'S1' 'S2' 'S3']
>>> print(table.ids(axis='observation')) # doctest: +NORMALIZE_WHITESPACE
['O0' 'O1' 'O2' 'O3' 'O4' 'O5' 'O6' 'O7' 'O8' 'O9']
>>> print(table.nnz) # number of nonzero entries
39
While it's fun to just poke at the table, let's dig deeper. First, we're going
to convert `table` into relative abundances (within each sample), and then
filter `table` to just the samples associated with environment 'A'. The
filtering gets fancy: we can pass in an arbitrary function to determine what
samples we want to keep. This function must accept a sparse vector of values,
the corresponding ID and the corresponding metadata, and should return ``True``
or ``False``, where ``True`` indicates that the vector should be retained.
>>> normed = table.norm(axis='sample', inplace=False)
>>> filter_f = lambda values, id_, md: md['environment'] == 'A'
>>> env_a = normed.filter(filter_f, axis='sample', inplace=False)
>>> print(env_a) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0 S2
O0 0.0 0.01
O1 0.0222222222222 0.03
O2 0.0444444444444 0.05
O3 0.0666666666667 0.07
O4 0.0888888888889 0.09
O5 0.111111111111 0.11
O6 0.133333333333 0.13
O7 0.155555555556 0.15
O8 0.177777777778 0.17
O9 0.2 0.19
But, what if we wanted individual tables per environment? While we could just
perform some fancy iteration, we can instead just rely on `Table.partition` for
these operations. `partition`, like `filter`, accepts a function. However, the
`partition` method only passes the corresponding ID and metadata to the
function. The function should return what partition the data are a part of.
Within this example, we're also going to sum up our tables over the partitioned
samples. Please note that we're using the original table (ie, not normalized)
here.
>>> part_f = lambda id_, md: md['environment']
>>> env_tables = table.partition(part_f, axis='sample')
>>> for partition, env_table in env_tables:
... print(partition, env_table.sum('sample'))
A [ 180. 200.]
B [ 190. 210.]
For this last example, and to highlight a bit more functionality, we're going
to first transform the table such that all multiples of three will be retained,
while all non-multiples of three will get set to zero. Following this, we'll
then collpase the table by taxonomy, and then convert the table into
presence/absence data.
First, let's setup the transform. We're going to define a function that takes
the modulus of every value in the vector, and see if it is equal to zero. If it
is equal to zero, we'll keep the value, otherwise we'll set the value to zero.
>>> transform_f = lambda v,i,m: np.where(v % 3 == 0, v, 0)
>>> mult_of_three = tform = table.transform(transform_f, inplace=False)
>>> print(mult_of_three) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0 S1 S2 S3
O0 0.0 0.0 0.0 3.0
O1 0.0 0.0 6.0 0.0
O2 0.0 9.0 0.0 0.0
O3 12.0 0.0 0.0 15.0
O4 0.0 0.0 18.0 0.0
O5 0.0 21.0 0.0 0.0
O6 24.0 0.0 0.0 27.0
O7 0.0 0.0 30.0 0.0
O8 0.0 33.0 0.0 0.0
O9 36.0 0.0 0.0 39.0
Next, we're going to collapse the table over the phylum level taxon. To do
this, we're going to define a helper variable for the index position of the
phylum (see the construction of the table above). Next, we're going to pass
this to `Table.collapse`, and since we want to collapse over the observations,
we'll need to specify 'observation' as the axis.
>>> phylum_idx = 1
>>> collapse_f = lambda id_, md: '; '.join(md['taxonomy'][:phylum_idx + 1])
>>> collapsed = mult_of_three.collapse(collapse_f, axis='observation')
>>> print(collapsed) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0 S1 S2 S3
Bacteria; Firmicutes 7.2 6.6 7.2 8.4
Bacteria; Proteobacteria 4.0 3.0 6.0 5.0
Bacteria; Bacteroidetes 12.0 10.5 0.0 13.5
Finally, let's convert the table to presence/absence data.
>>> pa = collapsed.pa()
>>> print(pa) # doctest: +NORMALIZE_WHITESPACE
# Constructed from biom file
#OTU ID S0 S1 S2 S3
Bacteria; Firmicutes 1.0 1.0 1.0 1.0
Bacteria; Proteobacteria 1.0 1.0 1.0 1.0
Bacteria; Bacteroidetes 1.0 1.0 0.0 1.0
"""
# -----------------------------------------------------------------------------
# Copyright (c) 2011-2020, 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 numpy as np
import scipy.stats
import h5py
from copy import deepcopy
from datetime import datetime
from json import dumps as _json_dumps, JSONEncoder
from functools import reduce, partial
from operator import itemgetter
from collections import defaultdict
from collections.abc import Hashable, Iterable
from numpy import ndarray, asarray, zeros, newaxis
from scipy.sparse import (coo_matrix, csc_matrix, csr_matrix, isspmatrix,
vstack, hstack, dok_matrix)
import pandas as pd
import re
from biom.exception import (TableException, UnknownAxisError, UnknownIDError,
DisjointIDError)
from biom.util import (get_biom_format_version_string,
get_biom_format_url_string, flatten, natsort,
prefer_self, index_list, H5PY_VLEN_STR,
__format_version__)
from biom.err import errcheck
from ._filter import _filter
from ._transform import _transform
from ._subsample import _subsample
__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2011-2020, The BIOM Format Development Team"
__credits__ = ["Daniel McDonald", "Jai Ram Rideout", "Greg Caporaso",
"Jose Clemente", "Justin Kuczynski", "Adam Robbins-Pianka",
"Joshua Shorenstein", "Jose Antonio Navas Molina",
"Jorge Cañardo Alastuey", "Steven Brown"]
__license__ = "BSD"
__url__ = "http://biom-format.org"
__maintainer__ = "Daniel McDonald"
__email__ = "[email protected]"
MATRIX_ELEMENT_TYPE = {'int': int, 'float': float, 'unicode': str,
'int': int, 'float': float, 'unicode': str}
# NpEncoder from:
# https://stackoverflow.com/a/57915246/19741
class NpEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return super(NpEncoder, self).default(obj)
dumps = partial(_json_dumps, cls=NpEncoder)
def _identify_bad_value(dtype, fields):
"""Identify the first value which cannot be cast
Paramters
---------
dtype : type
A type to cast to
fields : Iterable of str
A series of str to cast into dtype
Returns
-------
str or None
A value that cannot be cast
int or None
The index of the value that cannot be cast
"""
badval = None
badidx = None
for idx, v in enumerate(fields):
try:
dtype(v)
except: # noqa
badval = v
badidx = idx
break
return (badval, badidx)
def general_parser(x):
if isinstance(x, bytes):
x = x.decode('utf8')
return x
def vlen_list_of_str_parser(value):
"""Parses the taxonomy value"""
new_value = []
for v in value:
if v:
if isinstance(v, bytes):
v = v.decode('utf8')
new_value.append(v)
return new_value if new_value else None
def general_formatter(grp, header, md, compression):
"""Creates a dataset for a general atomic type category"""
shape = (len(md),)
dtypes = [type(m[header]) for m in md]
# "/" are considered part of the path in hdf5 and must be
# escaped. However, escaping with "\" leads to a truncation
# so let's replace "/" with an unexpected keyword.
sanitized = header.replace('/', '@@SLASH@@')
name = 'metadata/%s' % sanitized
if set(dtypes).issubset({str}):
grp.create_dataset(name, shape=shape,
dtype=H5PY_VLEN_STR,
data=[m[header].encode('utf8') for m in md],
compression=compression)
elif set(dtypes).issubset({list, tuple}):
vlen_list_of_str_formatter(grp, header, md, compression)
else:
formatted = []
dtypes_used = []
for dt, m in zip(dtypes, md):
val = m[header]
if val is None:
val = ''
dt = str
if dt == str:
val = val.encode('utf8')
formatted.append(val)
dtypes_used.append(dt)
if set(dtypes_used).issubset({str}):
dtype_to_use = H5PY_VLEN_STR
else:
dtype_to_use = None
# try our best...
grp.create_dataset(
name, shape=(len(md),),
dtype=dtype_to_use,
data=formatted,
compression=compression)
def vlen_list_of_str_formatter(grp, header, md, compression):
"""Creates a (N, ?) vlen str dataset"""
# It is possible that the value for some sample/observation
# is None. In that case, we still need to see them as
# iterables, but their length will be 0
iterable_checks = []
lengths = []
for m in md:
if m[header] is None:
iterable_checks.append(True)
elif isinstance(m.get(header), str):
iterable_checks.append(False)
else:
iterable_checks.append(
isinstance(m.get(header, []), Iterable))
lengths.append(len(m[header]))
if not np.all(iterable_checks):
if header == 'taxonomy':
# attempt to handle the general case issue where the taxonomy
# was not split on semicolons and represented as a flat string
# instead of a list
def split_and_strip(i):
parts = i.split(';')
return [p.strip() for p in parts]
try:
new_md = []
lengths = []
for m in md:
parts = split_and_strip(m[header])
new_md.append({header: parts})
lengths.append(len(parts))
md = new_md
except: # noqa
raise TypeError("Category '%s' is not formatted properly. The "
"most common issue is when 'taxonomy' is "
"represented as a flat string instead of a "
"list. An attempt was made to split this "
"field on a ';' to coerce it into a list but "
"it failed. An example entry (which is not "
"assured to be the problematic entry) is "
"below:\n%s" % (header, md[0][header]))
else:
raise TypeError(
"Category %s not formatted correctly. Did you pass"
" --process-obs-metadata taxonomy when converting "
" from tsv? Please see Table.to_hdf5 docstring for"
" more information" % header)
max_list_len = max(lengths)
shape = (len(md), max_list_len)
data = np.empty(shape, dtype=object)
for i, m in enumerate(md):
if m[header] is None:
continue
value = np.asarray(m[header])
data[i, :len(value)] = [v.encode('utf8') for v in value]
# Change the None entries on data to empty strings ""
data = np.where(data == np.array(None), "", data)
grp.create_dataset(
'metadata/%s' % header, shape=shape,
dtype=H5PY_VLEN_STR, data=data,
compression=compression)
class Table:
"""The (canonically pronounced 'teh') Table.
Give in to the power of the Table!
Creates an in-memory representation of a BIOM file. BIOM version 1.0 is
based on JSON to provide the overall structure for the format while
versions 2.0 and 2.1 are based on HDF5. For more information see [1]_
and [2]_
Paramaters
----------
data : array_like
An (N,M) sample by observation matrix represented as one of these
types:
* An 1-dimensional array of values
* An n-dimensional array of values
* An empty list
* A list of numpy arrays
* A list of dict
* A list of sparse matrices
* A dictionary of values
* A list of lists
* A sparse matrix of values
observation_ids : array_like of str
A (N,) dataset of the observation IDs, where N is the total number
of IDs
sample_ids : array_like of str
A (M,) dataset of the sample IDs, where M is the total number of IDs
observation_metadata : list of dicts, optional
per observation dictionary of annotations where every key represents a
metadata field that contains specific metadata information,
ie taxonomy, KEGG pathway, etc
sample_metadata : array_like of dicts, optional
per sample dictionary of annotations where every key represents a
metadata field that contains sample specific metadata information, ie
table_id : str, optional
A field that can be used to identify the table
type : str, see notes
The type of table represented
create_date : str, optional
Date that this table was built
generated_by : str, optional
Individual who built the table
observation_group_metadata : list, optional
group that contains observation specific group metadata information
(e.g., phylogenetic tree)
sample_group_metadata : list, optional
group that contains sample specific group metadata information
(e.g., relationships between samples)
Attributes
----------
shape
dtype
nnz
matrix_data
type
table_id
create_date
generated_by
format_version
Notes
-----
Allowed table types are None, "OTU table", "Pathway table", "Function
table", "Ortholog table", "Gene table", "Metabolite table", "Taxon table"
Raises
------
TableException
When an invalid table type is provided.
References
----------
.. [1] http://biom-format.org/documentation/biom_format.html
.. [2] D. McDonald, et al. "The Biological Observation Matrix (BIOM) format
or: how I learned to stop worrying and love the ome-ome"
GigaScience 2012 1:7
"""
def __init__(self, data, observation_ids, sample_ids,
observation_metadata=None, sample_metadata=None,
table_id=None, type=None, create_date=None, generated_by=None,
observation_group_metadata=None, sample_group_metadata=None,
validate=True, observation_index=None, sample_index=None,
**kwargs):
self.type = type
self.table_id = table_id
self.create_date = create_date
self.generated_by = generated_by
self.format_version = __format_version__
if not isspmatrix(data):
shape = (len(observation_ids), len(sample_ids))
input_is_dense = kwargs.get('input_is_dense', False)
self._data = Table._to_sparse(data, input_is_dense=input_is_dense,
shape=shape)
else:
self._data = data.tocsr()
self._data = self._data.astype(float)
self._sample_ids = np.asarray(sample_ids)
self._observation_ids = np.asarray(observation_ids)
if sample_metadata is not None:
# not m will evaluate True if the object tested is None or
# an empty dict, etc.
if {not m for m in sample_metadata} == {True, }:
self._sample_metadata = None
else:
self._sample_metadata = tuple(sample_metadata)
else:
self._sample_metadata = None
if observation_metadata is not None:
# not m will evaluate True if the object tested is None or
# an empty dict, etc.
if {not m for m in observation_metadata} == {True, }:
self._observation_metadata = None
else:
self._observation_metadata = tuple(observation_metadata)
else:
self._observation_metadata = None
self._sample_group_metadata = sample_group_metadata
self._observation_group_metadata = observation_group_metadata
if validate:
errcheck(self)
# These will be set by _index_ids()
self._sample_index = None
self._obs_index = None
self._cast_metadata()
self._index_ids(observation_index, sample_index)
def _index_ids(self, observation_index, sample_index):
"""Sets lookups {id:index in _data}.
Should only be called in constructor as this modifies state.
"""
if sample_index is None:
self._sample_index = index_list(self._sample_ids)
else:
self._sample_index = sample_index
if observation_index is None:
self._obs_index = index_list(self._observation_ids)
else:
self._obs_index = observation_index
def _index(self, axis='sample'):
"""Return the index lookups of the given axis
Parameters
----------
axis : {'sample', 'observation'}, optional
Axis to get the index dict. Defaults to 'sample'
Returns
-------
dict
lookups {id:index}
Raises
------
UnknownAxisError
If provided an unrecognized axis.
"""
if axis == 'sample':
return self._sample_index
elif axis == 'observation':
return self._obs_index
else:
raise UnknownAxisError(axis)
def _conv_to_self_type(self, vals, transpose=False, dtype=None):
"""For converting vectors to a compatible self type"""
if dtype is None:
dtype = self.dtype
if isspmatrix(vals):
return vals
else:
return Table._to_sparse(vals, transpose, dtype)
@staticmethod
def _to_dense(vec):
"""Converts a row/col vector to a dense numpy array.
Always returns a 1-D row vector for consistency with numpy iteration
over arrays.
"""
dense_vec = vec.toarray()
if vec.shape == (1, 1):
# Handle the special case where we only have a single element, but
# we don't want to return a numpy scalar / 0-d array. We still want
# to return a vector of length 1.
return dense_vec.reshape(1)
else:
return np.squeeze(dense_vec)
@staticmethod
def _to_sparse(values, transpose=False, dtype=float, input_is_dense=False,
shape=None):
"""Try to return a populated scipy.sparse matrix.
NOTE: assumes the max value observed in row and col defines the size of
the matrix.
"""
# if it is a vector
if isinstance(values, ndarray) and len(values.shape) == 1:
if transpose:
mat = nparray_to_sparse(values[:, newaxis], dtype)
else:
mat = nparray_to_sparse(values, dtype)
return mat
if isinstance(values, ndarray):
if transpose:
mat = nparray_to_sparse(values.T, dtype)
else:
mat = nparray_to_sparse(values, dtype)
return mat
# the empty list
elif isinstance(values, list) and len(values) == 0:
return coo_matrix((0, 0))
# list of np vectors
elif isinstance(values, list) and isinstance(values[0], ndarray):
mat = list_nparray_to_sparse(values, dtype)
if transpose:
mat = mat.T
return mat
# list of dicts, each representing a row in row order
elif isinstance(values, list) and isinstance(values[0], dict):
mat = list_dict_to_sparse(values, dtype)
if transpose:
mat = mat.T
return mat
# list of scipy.sparse matrices, each representing a row in row order
elif isinstance(values, list) and isspmatrix(values[0]):
mat = list_sparse_to_sparse(values, dtype)
if transpose:
mat = mat.T
return mat
elif isinstance(values, dict):
mat = dict_to_sparse(values, dtype, shape)
if transpose:
mat = mat.T
return mat
elif isinstance(values, list) and isinstance(values[0], list):
if input_is_dense:
d = coo_matrix(values)
mat = coo_arrays_to_sparse((d.data, (d.row, d.col)),
dtype=dtype, shape=shape)
else:
mat = list_list_to_sparse(values, dtype, shape=shape)
return mat
elif isspmatrix(values):
mat = values
if transpose:
mat = mat.transpose()
return mat
else:
raise TableException("Unknown input type")
def _cast_metadata(self):
"""Casts all metadata to defaultdict to support default values.
Should be called after any modifications to sample/observation
metadata.
"""
def cast_metadata(md):
"""Do the actual casting"""
default_md = []
# if we have a list of [None], set to None
if md is not None:
if md.count(None) == len(md):
return None
if md is not None:
for item in md:
d = defaultdict(lambda: None)
if isinstance(item, dict):
d.update(item)
elif item is None:
pass
else:
raise TableException("Unable to cast metadata: %s" %
repr(item))
default_md.append(d)
return tuple(default_md)
return md
self._sample_metadata = cast_metadata(self._sample_metadata)
self._observation_metadata = cast_metadata(self._observation_metadata)
self._sample_group_metadata = (
self._sample_group_metadata
if self._sample_group_metadata else None)
self._observation_group_metadata = (
self._observation_group_metadata
if self._observation_group_metadata else None)
@property
def shape(self):
"""The shape of the underlying contingency matrix"""
return self._data.shape
@property
def dtype(self):
"""The type of the objects in the underlying contingency matrix"""
return self._data.dtype
@property
def nnz(self):
"""Number of non-zero elements of the underlying contingency matrix"""
self._data.eliminate_zeros()
return self._data.nnz
@property
def matrix_data(self):
"""The sparse matrix object"""
return self._data
def length(self, axis='sample'):
"""Return the length of an axis
Parameters
----------
axis : {'sample', 'observation'}, optional
The axis to operate on
Raises
------
UnknownAxisError
If provided an unrecognized axis.
Examples
--------
>>> from biom import example_table
>>> print(example_table.length(axis='sample'))
3
>>> print(example_table.length(axis='observation'))
2
"""
if axis not in ('sample', 'observation'):
raise UnknownAxisError(axis)
return self.shape[1] if axis == 'sample' else self.shape[0]
def add_group_metadata(self, group_md, axis='sample'):
"""Take a dict of group metadata and add it to an axis
Parameters
----------
group_md : dict of tuples
`group_md` should be of the form ``{category: (data type, value)``
axis : {'sample', 'observation'}, optional
The axis to operate on
Raises
------
UnknownAxisError
If provided an unrecognized axis.
"""
if axis == 'sample':
if self._sample_group_metadata is not None:
self._sample_group_metadata.update(group_md)
else:
self._sample_group_metadata = group_md
elif axis == 'observation':
if self._observation_group_metadata is not None:
self._observation_group_metadata.update(group_md)
else:
self._observation_group_metadata = group_md
else:
raise UnknownAxisError(axis)
def del_metadata(self, keys=None, axis='whole'):
"""Remove metadata from an axis
Parameters
----------
keys : list of str, optional
The keys to remove from metadata. If None, all keys from the axis
are removed.
axis : {'sample', 'observation', 'whole'}, optional
The axis to operate on. If 'whole', the operation is applied to
both the sample and observation axes.
Raises
------
UnknownAxisError
If the requested axis does not exist.
Examples
--------
>>> from biom import Table
>>> import numpy as np
>>> tab = Table(np.array([[1, 2], [3, 4]]),
... ['O1', 'O2'],
... ['S1', 'S2'],
... sample_metadata=[{'barcode': 'ATGC', 'env': 'A'},
... {'barcode': 'GGTT', 'env': 'B'}])
>>> tab.del_metadata(keys=['env'])
>>> for id, md in zip(tab.ids(), tab.metadata()):
... print(id, list(md.items()))
S1 [('barcode', 'ATGC')]
S2 [('barcode', 'GGTT')]
"""
if axis == 'whole':
axes = ['sample', 'observation']
elif axis in ('sample', 'observation'):
axes = [axis]
else:
raise UnknownAxisError("%s is not recognized" % axis)
if keys is None:
if axis == 'whole':
self._sample_metadata = None
self._observation_metadata = None
elif axis == 'sample':
self._sample_metadata = None
else:
self._observation_metadata = None
return
for ax in axes:
if self.metadata(axis=ax) is None:
continue
for i, md in zip(self.ids(axis=ax), self.metadata(axis=ax)):
for k in keys:
if k in md:
del md[k]
# for consistency with init on absence of metadata
empties = {True if not md else False
for md in self.metadata(axis=ax)}
if empties == {True, }:
if ax == 'sample':
self._sample_metadata = None
else:
self._observation_metadata = None
def add_metadata(self, md, axis='sample'):
"""Take a dict of metadata and add it to an axis.
Parameters
----------
md : dict of dict
`md` should be of the form ``{id: {dict_of_metadata}}``
axis : {'sample', 'observation'}, optional
The axis to operate on
"""
metadata = self.metadata(axis=axis)
if metadata is not None:
for id_, md_entry in md.items():
if self.exists(id_, axis=axis):
idx = self.index(id_, axis=axis)
metadata[idx].update(md_entry)
else:
ids = self.ids(axis=axis)
if axis == 'sample':
self._sample_metadata = tuple(
md[id_] if id_ in md else None for id_ in ids)
elif axis == 'observation':
self._observation_metadata = tuple(
md[id_] if id_ in md else None for id_ in ids)
else:
raise UnknownAxisError(axis)
self._cast_metadata()
def __getitem__(self, args):
"""Handles row or column slices
Slicing over an individual axis is supported, but slicing over both
axes at the same time is not supported. Partial slices, such as
`foo[0, 5:10]` are not supported, however full slices are supported,
such as `foo[0, :]`.
Parameters
----------
args : tuple or slice
The specific element (by index position) to return or an entire
row or column of the data.
Returns
-------
float or spmatrix
A float is return if a specific element is specified, otherwise a
spmatrix object representing a vector of sparse data is returned.
Raises
------
IndexError
- If the matrix is empty
- If the arguments do not appear to be a tuple
- If a slice on row and column is specified
- If a partial slice is specified
Notes
-----
Switching between slicing rows and columns is inefficient. Slicing of
rows requires a CSR representation, while slicing of columns requires a
CSC representation, and transforms are performed on the data if the
data are not in the required representation. These transforms can be
expensive if done frequently.
.. shownumpydoc
"""
if self.is_empty():
raise IndexError("Cannot retrieve an element from an empty/null "
"table.")
try:
row, col = args
except: # noqa
raise IndexError("Must specify (row, col).")
if isinstance(row, slice) and isinstance(col, slice):
raise IndexError("Can only slice a single axis.")
if isinstance(row, slice):
if row.start is None and row.stop is None:
return self._get_col(col)
else:
raise IndexError("Can only handle full : slices per axis.")
elif isinstance(col, slice):
if col.start is None and col.stop is None:
return self._get_row(row)
else:
raise IndexError("Can only handle full : slices per axis.")
else:
if self._data.getformat() == 'coo':
self._data = self._data.tocsr()
return self._data[row, col]
def _get_row(self, row_idx):
"""Return the row at ``row_idx``.
A row vector will be returned as a scipy.sparse matrix in csr format.
Notes
-----
Switching between slicing rows and columns is inefficient. Slicing of
rows requires a CSR representation, while slicing of columns requires a
CSC representation, and transforms are performed on the data if the
data are not in the required representation. These transforms can be
expensive if done frequently.
"""
self._data = self._data.tocsr()
return self._data.getrow(row_idx)
def _get_col(self, col_idx):
"""Return the column at ``col_idx``.
A column vector will be returned as a scipy.sparse matrix in csc
format.
Notes
-----
Switching between slicing rows and columns is inefficient. Slicing of
rows requires a CSR representation, while slicing of columns requires a
CSC representation, and transforms are performed on the data if the
data are not in the required representation. These transforms can be
expensive if done frequently.
"""
self._data = self._data.tocsc()
return self._data.getcol(col_idx)
def align_to_dataframe(self, metadata, axis='sample'):
""" Aligns dataframe against biom table, only keeping common ids.
Parameters
----------
metadata : pd.DataFrame
The metadata, either respect to the sample metadata
or observation metadata.
axis : {'sample', 'observation'}
The axis on which to operate.
Returns
-------
biom.Table
A filtered biom table.
pd.DataFrame
A filtered metadata table.
Examples
--------
>>> from biom import Table
>>> import numpy as np
>>> import pandas as pd
>>> table = Table(np.array([[0, 0, 1, 1],
... [2, 2, 4, 4],
... [5, 5, 3, 3],
... [0, 0, 0, 1]]),
... ['o1', 'o2', 'o3', 'o4'],
... ['s1', 's2', 's3', 's4'])
>>> metadata = pd.DataFrame([['a', 'control'],
... ['c', 'diseased'],