This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
/
stats.py
1895 lines (1604 loc) · 82.9 KB
/
stats.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
from __future__ import division
__author__ = "Michael Dwan"
__copyright__ = "Copyright 2012, The QIIME project"
__credits__ = ["Jai Ram Rideout", "Michael Dwan", "Logan Knecht",
"Damien Coy", "Levi McCracken", "Andrew Cochran",
"Jose Carlos Clemente Litran", "Greg Caporaso"]
__license__ = "GPL"
__version__ = "1.8.0"
__maintainer__ = "Jai Ram Rideout"
__email__ = "jai.rideout@gmail.com"
"""
This module provides functionality for the application of various statistical
methods to QIIME-formatted datasets.
The module provides an API that allows users to easily apply any number of
statistical analyses and just as easily retrieve the results. The module also
provides a hierarchy of statistical classes that can be inherited from to
create new statistical method implementations.
"""
from os.path import join
from types import ListType
from copy import deepcopy
from matplotlib import use
use('Agg', warn=False)
from matplotlib.pyplot import figure
from numpy import (argsort, array, asarray, ceil, empty, fill_diagonal, finfo,
log2, mean, ones, sqrt, tri, unique, zeros, ndarray, floor, median, nan)
from numpy import argsort, min as np_min, max as np_max, log10
from numpy.random import permutation
from cogent.util.misc import combinate, create_dir
from cogent.maths.stats.test import t_one_sample
from biom.table import table_factory, DenseOTUTable
from qiime.pycogent_backports.test import (mantel_test, mc_t_two_sample,
pearson, permute_2d, spearman)
from qiime.format import format_p_value_for_num_iters, format_biom_table
from qiime.format import format_p_value_for_num_iters
from qiime.util import DistanceMatrix, MetadataMap
# Top-level stats functions.
tail_types = ['low', 'high', 'two-sided']
tail_type_desc = {
'low': ('one-sided (low)', '<'),
'high': ('one-sided (high)', '>'),
'two-sided': ('two-sided', '!=')
}
def all_pairs_t_test(labels, dists, tail_type='two-sided',
num_permutations=999):
"""Perform two-sample t-test on all pairs of grouped distances.
Performs Student's two-sample t-test on all pairs of distributions,
optionally using Monte Carlo permutations to compute the nonparametric
p-value in addition to the parametric p-value.
Returns a formatted string (suitable for writing to a file) containing the
results of the tests.
This code is based on Jeremy Widmann's
qiime.make_distance_histograms.monte_carlo_group_distances code.
Arguments:
labels - list of labels corresponding to each of the distributions
dists - list of lists, where each inner list is a distribution of
numbers (observations)
tail_type - type of hypothesis test to perform. One of 'two-sided',
'high', or 'low'
num_permutations - the number of Monte Carlo permutations to use. If
zero, the nonparametric p-value will not be calculated and will be
'N/A' in the returned string.
"""
result = ''
if len(labels) != len(dists):
raise ValueError("The number of distribution labels must match the "
"number of distributions.")
if tail_type not in tail_types:
raise ValueError("Invalid tail type '%s'. Must be one of %r." %
(tail_type, tail_types))
if num_permutations < 0:
raise ValueError("Invalid number of permutations: %d. Must be greater "
"than or equal to zero." % num_permutations)
result += '# The tests of significance were performed using a ' + \
tail_type_desc[tail_type][0] + ' Student\'s two-sample t-test.\n'
result += ('# Alternative hypothesis: Group 1 mean %s Group 2 mean\n' %
tail_type_desc[tail_type][1])
if num_permutations > 0:
result += '# The nonparametric p-values were calculated using ' + \
'%d Monte Carlo permutations.\n' % num_permutations
result += '# The nonparametric p-values contain the correct ' + \
'number of significant digits.\n'
result += '# Entries marked with "N/A" could not be calculated because ' + \
'at least one of the groups\n# of distances was empty, ' + \
'both groups each contained only a single distance, or\n' + \
'# the test could not be performed (e.g. no variance in ' + \
'groups with the same mean).\nGroup 1\tGroup 2\t' + \
't statistic\tParametric p-value\tParametric p-value ' + \
'(Bonferroni-corrected)\tNonparametric p-value\t' + \
'Nonparametric p-value (Bonferroni-corrected)\n'
stats = _perform_pairwise_tests(labels, dists, tail_type, num_permutations)
for stat in stats:
stat = ['N/A' if e is nan else e for e in stat]
result += '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % (stat[0], stat[1], stat[2],
stat[3], stat[4],
format_p_value_for_num_iters(stat[5], num_permutations) if
stat[5] != 'N/A' else 'N/A',
format_p_value_for_num_iters(stat[6], num_permutations) if
stat[6] != 'N/A' else 'N/A')
return result
def _perform_pairwise_tests(labels, dists, tail_type, num_permutations):
"""Perform t-test for all pairs of distributions.
Computes corrected p-values in addition to uncorrected.
"""
result = []
# Convert our notion of tail type into the format expected by
# PyCogent.
if tail_type == 'two-sided':
tail_type = None
# Compare each pair of distributions, keeping track of the number of actual
# tests that were successfully performed so that we can correct for
# multiple comparisons.
num_tests = 0
for g1_idx, (g1_label, g1_dist) in enumerate(zip(labels[:-1], dists[:-1])):
for g2_label, g2_dist in zip(
labels[(g1_idx + 1):], dists[(g1_idx + 1):]):
if ((len(g1_dist) == 1 and len(g2_dist) == 1) or
(len(g1_dist) < 1 or len(g2_dist) < 1)):
# Not enough data to run the test.
obs_t, param_p_val, nonparam_p_val = nan, nan, nan
else:
obs_t, param_p_val, _, nonparam_p_val = mc_t_two_sample(
g1_dist, g2_dist, tails=tail_type,
permutations=num_permutations)
result.append([g1_label, g2_label, obs_t, param_p_val, None,
nonparam_p_val, None])
if obs_t is not nan:
num_tests += 1
# Correct the p-values for multiple comparisons, now that we know how many
# tests succeeded.
for stat in result:
stat[4] = stat[3] if stat[3] is nan else min(stat[3] * num_tests, 1)
stat[6] = stat[5] if stat[5] is nan else min(stat[5] * num_tests, 1)
return result
def quantile(data, quantiles):
"""calculates quantiles of a dataset matching a given list of probabilities
Input:
data: 1-D list or numpy array with data to calculate the quantiles
quantiles: list of probabilities, floating point values between 0 and 1
Output:
A list of elements drawn from 'data' that corresponding to the list of
probabilities. This by default is using R. type 7 method for computation of
the quantiles.
"""
assert type(data) == list or type(data) == ndarray, "Data must be either"+\
" a Python list or a NumPy 1-D array"
assert type(quantiles) == list or type(quantiles) == ndarray, "Quantiles"+\
" must be either a Python list or a NumPy 1-D array"
assert all(map(lambda x: x>=0 and x<=1, quantiles)), "All the elements "+\
"in the quantiles list must be greater than 0 and lower than one"
# unless the user wanted, do not modify the data
data = deepcopy(data)
if type(data) != ndarray:
data = array(data)
data.sort()
output = []
# if needed different quantile methods could be used
for one_quantile in quantiles:
output.append(_quantile(data, one_quantile))
return output
def _quantile(data, quantile):
"""gets a single quantile value for a dataset using R. type 7 method
Input:
data: sorted 1-d numpy array with float or int elements
quantile: floating point value between 0 and 1
Output:
quantile value of data
This function is based on cogent.maths.stats.util.NumbersI
"""
index = quantile*(len(data)-1)
bottom_index = int(floor(index))
top_index = int(ceil(index))
difference = index-bottom_index
output = (1-difference)*data[bottom_index]+difference*data[top_index]
return output
class DistanceMatrixStats(object):
"""Base class for distance matrix-based statistical methods.
This class provides an interface to setting and accessing an arbitrary
number of distance matrices. Users of this class can optionally specify the
number of allowable distance matrices and their minimum allowable size (the
default is no restrictions on either of these).
It is the parent class of CorrelationStats and CategoryStats.
"""
def __init__(self, dms, num_dms=-1, min_dm_size=-1,
suppress_symmetry_and_hollowness_check=False):
"""Default constructor.
Initializes an instance with the provided list of distance matrices.
Arguments:
dms - a list of DistanceMatrix objects
num_dms - the exact number of allowable distance matrices. If -1
(the default), there is no restriction on how many distance
matrices the user can set
min_dm_size - the minimum size that all distance matrices must have
that are stored by this instance. If -1, no size restriction
suppress_symmetry_and_hollowness_check - by default, the input
distance matrices will be checked for symmetry and hollowness.
It is recommended to leave this check in place for safety, as
the check is fairly fast. However, if you *know* you have
symmetric and hollow distance matrices, you can disable this
check for small performance gains on extremely large distance
matrices. Alternatively, if the statistical method works on
asymmetric and/or non-hollow distance matrices, you can disable
this check to allow for these types of distance matrices
"""
self._num_dms = num_dms
self._min_dm_size = min_dm_size
self._suppress_symmetry_and_hollowness_check = \
suppress_symmetry_and_hollowness_check
self.DistanceMatrices = dms
@property
def DistanceMatrices(self):
"""Returns the list of distance matrices."""
return self._dms
@DistanceMatrices.setter
def DistanceMatrices(self, dms):
"""Sets the list of distance matrices to the supplied list.
Arguments:
dms - the new list of distance matrices being assigned
"""
if not isinstance(dms, ListType):
raise TypeError("The item passed in as the new list was not a "
"list data type.")
if self._num_dms >= 0 and len(dms) != self._num_dms:
raise ValueError("Cannot set %d distance matrices. Must provide "
"exactly %d distance matrices." % (len(dms),
self._num_dms))
for dm in dms:
if not isinstance(dm, DistanceMatrix):
raise TypeError('Invalid type: %s; expected DistanceMatrix' %
dm.__class__.__name__)
if self._min_dm_size >= 0 and dm.Size < self._min_dm_size:
raise ValueError("Distance matrix of size %dx%d is smaller "
"than the minimum allowable distance matrix "
"size of %dx%d for this analysis." %
(dm.Size, dm.Size, self._min_dm_size,
self._min_dm_size))
if not self._suppress_symmetry_and_hollowness_check:
if not dm.is_symmetric_and_hollow():
raise ValueError("The distance matrix must be symmetric "
"and hollow.")
self._dms = dms
def __call__(self, num_perms=999):
"""Runs the statistical method and returns relevant results.
The return value of this method is a python dictionary with arbitrary
key/value pairs of results, since each statistical method returns
different results.
This method returns an empty result set (it is essentially not
implemented) and should be implemented by subclasses to perform their
specific statistical analysis. Subclasses should call the parent
class' __call__ method first to obtain any results from the parent and
then add more results to the dict that is obtained from the parent.
Arguments:
num_perms - the number of permutations to use in the statistical
method. If the method is not permutation-based, simply ignore
this argument
"""
if num_perms < 0:
raise ValueError("The number of permutations must be greater than "
"or equal to zero.")
return {}
class CorrelationStats(DistanceMatrixStats):
"""Base class for distance matrix correlation statistical methods.
It is subclassed by correlation methods such as partial Mantel and Mantel
that compare two or more distance matrices.
A valid instance of CorrelationStats must have at least one distance
matrix, and all distance matrices must have matching dimensions and sample
IDs (i.e. matching row/column labels). This check is in place to prevent
the accidental comparison on two distance matrices that have sample IDs in
different orders. Essentially, all of the distance matrices must be
"compatible".
Users of this class can optionally specify the number of allowable distance
matrices and their minimum allowable size (the default is no restrictions
on either of these).
"""
def __init__(self, dms, num_dms=-1, min_dm_size=-1,
suppress_symmetry_and_hollowness_check=False):
"""Default constructor.
Creates a new instance with the provided list of distance matrices.
Arguments:
dms - a list of DistanceMatrix objects
num_dms - the exact number of allowable distance matrices. If -1
(the default), there is no restriction on how many distance
matrices the user can set
min_dm_size - the minimum size that all distance matrices must have
that are stored by this instance. If -1, no size restriction
suppress_symmetry_and_hollowness_check - by default, the input
distance matrices will be checked for symmetry and hollowness.
It is recommended to leave this check in place for safety, as
the check is fairly fast. However, if you *know* you have
symmetric and hollow distance matrices, you can disable this
check for small performance gains on extremely large distance
matrices. Alternatively, if the statistical method works on
asymmetric and/or non-hollow distance matrices, you can disable
this check to allow for these types of distance matrices
"""
super(CorrelationStats, self).__init__(dms, num_dms, min_dm_size,
suppress_symmetry_and_hollowness_check)
@property
def DistanceMatrices(self):
# Must re-declare so we can override property setter below.
return super(CorrelationStats, self).DistanceMatrices
@DistanceMatrices.setter
def DistanceMatrices(self, dms):
"""Sets the list of distance matrices to the supplied list.
This method overrides the parent method and enforces more checks to
ensure that at least one distance matrix is provided and that all of
the distance matrices are compatible.
Arguments:
dms - the new list of distance matrices being assigned
"""
# Must call superclass property setter this way (super doesn't work).
DistanceMatrixStats.DistanceMatrices.fset(self, dms)
if len(dms) < 1:
raise ValueError("Must provide at least one distance matrix.")
size = dms[0].Size
sample_ids = dms[0].SampleIds
for dm in dms:
if dm.Size != size:
raise ValueError("All distance matrices must have the same "
"number of rows and columns.")
if dm.SampleIds != sample_ids:
raise ValueError("All distance matrices must have matching "
"sample IDs.")
class CategoryStats(DistanceMatrixStats):
"""Base class for categorical statistical analyses.
It is subclassed by categorical statistical methods such as DB-RDA or BEST.
Categorical statistical methods usually have some categorical grouping of
samples, and the significance of this grouping is usually what is tested.
For example, are treatment samples significantly different from control
samples? This is not always the case (e.g. DB-RDA is an ordination
technique), but most of the categorical methods follow this general design.
A valid instance of CategoryStats must have at least one distance matrix
and a single metadata map containing the sample IDs of the distance matrix
or matrices.
"""
def __init__(self, mdmap, dms, cats, num_dms=-1, min_dm_size=-1,
random_fn=permutation,
suppress_symmetry_and_hollowness_check=False,
suppress_category_uniqueness_check=False,
suppress_numeric_category_check=True,
suppress_single_category_value_check=False):
"""Default constructor.
Creates a new instance with the provided distance matrices,
metadata map, and list of categories.
Arguments:
mdmap - a MetadataMap instance
dms - a list of DistanceMatrix objects
cats - a list of strings denoting categories in the metadata map
that will be used by this analysis (i.e. the grouping
variable(s))
num_dms - the exact number of allowable distance matrices. If -1
(the default), there is no restriction on how many distance
matrices the user can set
min_dm_size - the minimum size that all distance matrices must have
that are stored by this instance. If -1, no size restriction
random_fn - the function to use when randomizing the grouping
of samples in a category during calculation of the p-value. It
must return a value and must be callable
suppress_symmetry_and_hollowness_check - by default, the input
distance matrices will be checked for symmetry and hollowness.
It is recommended to leave this check in place for safety, as
the check is fairly fast. However, if you *know* you have
symmetric and hollow distance matrices, you can disable this
check for small performance gains on extremely large distance
matrices. Alternatively, if the statistical method works on
asymmetric and/or non-hollow distance matrices, you can disable
this check to allow for these types of distance matrices
suppress_category_uniqueness_check - by default, each input
category will be checked to ensure that not all values are
unique (i.e. some duplicated values exist). In other words,
this check makes sure that the category will group samples such
that there exists at least one group of samples that is
composed of two or more samples. Many categorical statistical
methods (such as ANOSIM and PERMANOVA) need this requirement to
be met to avoid erroneous math (e.g. division by zero) due to a
lack of 'within' distances. An example of a unique category
would be SampleID, where each category value is unique
suppress_numeric_category_check - if False, each category's values
will be checked to ensure they can be converted to a float.
Useful for methods that only accept numeric categories
suppress_single_category_value_check - if False, each category's
values will be checked to ensure they are not all the same.
Many of the methods will not work if every value is the same
(i.e. there is only one single group of samples)
"""
super(CategoryStats, self).__init__(dms, num_dms, min_dm_size,
suppress_symmetry_and_hollowness_check)
self._suppress_category_uniqueness_check = \
suppress_category_uniqueness_check
self._suppress_numeric_category_check = suppress_numeric_category_check
self._suppress_single_category_value_check = \
suppress_single_category_value_check
self.MetadataMap = mdmap
self.Categories = cats
self.RandomFunction = random_fn
self._validate_compatibility()
@property
def MetadataMap(self):
"""Returns the instance's metadata map.
The metadata map is returned as a MetadataMap class instance.
"""
return self._metadata_map
@MetadataMap.setter
def MetadataMap(self, new_mdmap):
"""Sets the instance's metadata map.
Arguments:
new_mdmap - A MetadataMap object instance
"""
if not isinstance(new_mdmap, MetadataMap):
raise TypeError('Invalid type: %s; not MetadataMap' %
new_mdmap.__class__.__name__)
self._metadata_map = new_mdmap
@property
def Categories(self):
"""Gets the instance's categories.
Returns a list of mapping file category name strings.
"""
return self._categories
@Categories.setter
def Categories(self, new_categories):
"""Sets the instance's list of categories.
Arguments:
new_categories - A list of category name strings. These must be
present in the current metadata map
"""
if not isinstance(new_categories, ListType):
raise TypeError("The supplied categories must be a list of "
"strings.")
for new_cat in new_categories:
if not isinstance(new_cat, str):
raise TypeError("Invalid category: not of type 'string'")
elif new_cat not in self._metadata_map.CategoryNames:
raise ValueError("The category '%s' is not in the mapping "
"file." % new_cat)
if not self._suppress_numeric_category_check:
if not self._metadata_map.isNumericCategory(new_cat):
raise TypeError("The category '%s' is not numeric. Not "
"all values could be converted to numbers."
% new_cat)
if not self._suppress_category_uniqueness_check:
if self._metadata_map.hasUniqueCategoryValues(new_cat):
raise ValueError("All values in category '%s' are unique. "
"This statistical method cannot operate "
"on a category with unique values (e.g. "
"there are no 'within' distances because "
"each group of samples contains only a "
"single sample)." % new_cat)
if not self._suppress_single_category_value_check:
if self._metadata_map.hasSingleCategoryValue(new_cat):
raise ValueError("All values in category '%s' are the "
"same. This statistical method cannot "
"operate on a category that creates only "
"a single group of samples (e.g. there "
"are no 'between' distances because "
"there is only a single group)."
% new_cat)
self._categories = new_categories
@property
def RandomFunction(self):
"""Returns the randomization function used in p-value calculations."""
return self._random_fn
@RandomFunction.setter
def RandomFunction(self, random_fn):
"""Setter for the randomization function used in p-value calcs.
Arguments:
random_fn - the function to use when randomizing the grouping
during calculation of the p-value. It must return a value and
must be callable
"""
if hasattr(random_fn, '__call__'):
self._random_fn = random_fn
else:
raise TypeError("The supplied function reference is not callable.")
def _validate_compatibility(self):
"""Checks that the current dms, map, and categories are compatible.
This method will raise an error if any of the sample IDs in any of the
distance matrices are not found in the metadata map. Ordering of
sample IDs is not taken into account. An error will also be raised if
any categories cannot be found in the mapping file.
This method exists because we do not have a method to set distance
matrices, metadata map, and categories at the same time.
"""
for dm in self.DistanceMatrices:
for samp_id in dm.SampleIds:
if samp_id not in self.MetadataMap.SampleIds:
raise ValueError("The sample ID '%s' was not found in the "
"metadata map." % samp_id)
for cat in self.Categories:
if cat not in self.MetadataMap.CategoryNames:
raise ValueError("The category '%s' was not found in the "
"metadata map." % cat)
def __call__(self, num_perms=999):
"""Runs the statistical method and returns relevant results.
The return value of this method is a python dictionary with arbitrary
key/value pairs of results, since each statistical method returns
different results.
This method returns an empty result set (it is essentially not
implemented) and should be implemented by subclasses to perform their
specific statistical analysis. Subclasses should call the parent
class' __call__ method first to obtain any results from the parent and
then add more results to the dict that is obtained from the parent.
Arguments:
num_perms - the number of permutations to use in the statistical
method. If the method is not permutation-based, simply ignore
this argument
"""
# Make sure the *current* distance matrices and metadata map are
# compatible before continuing.
self._validate_compatibility()
return super(CategoryStats, self).__call__(num_perms)
class Anosim(CategoryStats):
"""Class for the ANOSIM categorical statistical analysis.
Briefly, ANOSIM tests whether two or more groups of samples are
significantly different. The user of the class specifies a category in the
metadata map to group samples by.
This code is heavily based on Andrew Cochran's original procedural version.
"""
def __init__(self, mdmap, dm, cat, random_fn=permutation,
suppress_symmetry_and_hollowness_check=False):
"""Initializes an instance with the specified analysis parameters.
WARNING: Only symmetric, hollow distance matrices may be used as input.
Asymmetric distance matrices, such as those obtained by the UniFrac
Gain metric (i.e. beta_diversity.py -m unifrac_g), should not be used
as input.
Arguments:
mdmap - the MetadataMap instance to obtain grouping info from
dm - the DistanceMatrix instance to obtain distances from
cat - the category string to group samples by (must be in the
metadata map)
random_fn - the function to use when randomizing the grouping
during calculation of the p-value. It must return a value and
must be callable
suppress_symmetry_and_hollowness_check - by default, the input
distance matrix will be checked for symmetry and hollowness.
It is recommended to leave this check in place for safety, as
the check is fairly fast. However, if you *know* you have
a symmetric and hollow distance matrix, you can disable this
check for small performance gains on extremely large distance
matrices
"""
super(Anosim, self).__init__(mdmap, [dm], [cat], num_dms=1,
random_fn=random_fn, suppress_symmetry_and_hollowness_check=\
suppress_symmetry_and_hollowness_check)
def __call__(self, num_perms=999):
"""Runs ANOSIM on the current distance matrix and sample grouping.
Returns a dict containing the results. The following keys are set:
method_name - name of the statistical method
r_value - the ANOSIM R statistic computed by the test
p_value - the p-value computed by the test, or 'NA' if the number
of permutations was zero
num_perms - the number of permutations used when calculating the
p-value
Arguments:
num_perms - the number of permutations to use when calculating the
p-value
"""
results = super(Anosim, self).__call__(num_perms)
category = self.Categories[0]
samples = self.DistanceMatrices[0].SampleIds
# Create the group map, which maps sample ID to category value (e.g.
# sample 1 to 'control' and sample 2 to 'fast').
group_map = {}
for samp_id in samples:
group_map[samp_id] = self.MetadataMap.getCategoryValue(
samp_id, category)
# Calculate the R statistic with the grouping found in the current
# metadata map.
r_stat = self._anosim(group_map)
if num_perms > 0:
# Calculate the p-value based on the number of permutations.
perm_stats = []
for i in range(num_perms):
# Randomize grouping. We don't use values() in order to
# preserve ordering in case the user's random function doesn't
# change the order of the items in the list.
grouping_random = [group_map[sample] for sample in samples]
grouping_random = self.RandomFunction(grouping_random)
for j, sample in enumerate(samples):
group_map[sample] = grouping_random[j]
perm_stats.append(self._anosim(group_map))
# Calculate the p-value.
p_value = (sum(perm_stats >= r_stat) + 1) / (num_perms + 1)
else:
p_value = 1.0
results['method_name'] = 'ANOSIM'
results['r_value'] = r_stat
results['p_value'] = p_value
results['num_perms'] = num_perms
return results
def _anosim(self, group_map):
"""Computes ANOSIM on the supplied grouping, returning the R value.
The R value is between -1 and 1 and indicates the strength of the
grouping.
Arguments:
group_map - a python dict mapping sample ID to category value (e.g.
sample 1 to 'control' and sample 2 to 'fast'). This map must
contain a key for each sample ID in the current distance
matrix
"""
dm = self.DistanceMatrices[0]
dm_size = dm.Size
# Create grouping matrix, where a one means that the two samples are in
# the same group (e.g. control) and a zero means that they aren't.
within_between = zeros((dm_size, dm_size))
for i, i_sample in enumerate(dm.SampleIds):
for j, j_sample in enumerate(dm.SampleIds):
if group_map[i_sample] == group_map[j_sample]:
within_between[i][j] = 1
# Extract upper triangle from the distance and grouping matrices.
distances = dm.DataMatrix[tri(dm_size) == 0]
grouping = within_between[tri(dm_size) == 0]
# Sort extracted data.
sorted_distances = []
sorted_grouping = []
for idx in argsort(distances):
sorted_distances.append(distances[idx])
sorted_grouping.append(grouping[idx])
# Account for rank ties, then compute R statistic.
rank_list = range(1, len(sorted_distances) + 1)
adjusted_rank_list = self._remove_ties(sorted_distances, rank_list)
return self._compute_r_value(adjusted_rank_list, sorted_grouping,
dm_size)
def _remove_ties(self, sorted_dists, ranks):
"""Replaces repeat values with the average of them.
Returns a list containing the adjusted ranks.
Arguments:
sorted_dists: list of the sorted distances
ranks: list containing the ranks of each of the differences
"""
result = []
ties = []
tie_count = 0
tie_flag = 0
for i in range(len(sorted_dists) - 1):
# Store state information.
curr_dist = sorted_dists[i]
next_dist = sorted_dists[i+1]
rank_val = ranks[i]
# A tie has not occured yet.
if tie_flag == 0:
if curr_dist == next_dist:
# We have a tie, so add the current rank to the tie list.
tie_count = tie_count + 1
ties.append(rank_val)
first_tie_index = i
tie_flag = 1
else:
# If no tie, fill in the list with the current rank.
result.append(rank_val)
else:
# A tie has already occured.
if curr_dist == next_dist:
# If another tie occurs, add the current rank to the tie
# list.
tie_count = tie_count + 1
ties.append(rank_val)
else:
# No more ties, average their values and attach to adjusted
# rank list.
ties.append(rank_val)
last_tie_index = i
result.extend(self._get_adjusted_vals(ties,
first_tie_index, last_tie_index))
tie_flag = 0
tie_count = 0
ties = []
# If there is a tie that extends to the final position, we must process
# it here to avoid out of list bounds errors.
if tie_flag == 1:
ties.append(ranks[i+1])
last_tie_index = i + 1
result.extend(self._get_adjusted_vals(ties, first_tie_index,
last_tie_index))
else:
result.append(ranks[i+1])
return result
def _get_adjusted_vals(self, ties, first_tie_idx, last_tie_idx):
"""Helper function to _remove_ties. Consolidates repeated code."""
adjusted_val = sum(ties) / len(ties)
return [adjusted_val] * ((last_tie_idx - first_tie_idx) + 1)
def _compute_r_value(self, adjusted_ranks, sorted_groups, num_samps):
"""Code that performs the actual math involved in solving ANOSIM.
Returns the ANOSIM R value (between -1 and 1).
Arguments:
adjusted_ranks - list of the ranks, adjusted for ties
sorted_groups - list associating distances to groups
num_samps: how many total samples
"""
adjusted_ranks = array(adjusted_ranks)
sorted_groups = array(sorted_groups)
# Compute r_W and r_B.
r_W = mean(adjusted_ranks[sorted_groups==1])
r_B = mean(adjusted_ranks[sorted_groups==0])
divisor = num_samps * ((num_samps - 1) / 4)
return (r_B - r_W) / divisor
class Permanova(CategoryStats):
"""Class for the PERMANOVA statistical method.
This is a non-parametric, permutation-based method to determine the
significance of sample grouping.
This code is heavily based on Andrew Cochran's original procedural version.
"""
def __init__(self, mdmap, dm, cat, random_fn=permutation,
suppress_symmetry_and_hollowness_check=False):
"""Initializes an instance with the specified analysis parameters.
WARNING: Only symmetric, hollow distance matrices may be used as input.
Asymmetric distance matrices, such as those obtained by the UniFrac
Gain metric (i.e. beta_diversity.py -m unifrac_g), should not be used
as input.
Arguments:
mdmap - the MetadataMap instance to obtain grouping info from
dm - the DistanceMatrix instance to obtain distances from
cat - the category string to group samples by (must be in the
metadata map)
num_perms - the number of permutations to use when calculating the
p-value. If zero, the p-value will not be calculated. Must be
greater than or equal to zero
random_fn - the function to use when randomizing the grouping
during calculation of the p-value. It must return a value and
must be callable
suppress_symmetry_and_hollowness_check - by default, the input
distance matrix will be checked for symmetry and hollowness.
It is recommended to leave this check in place for safety, as
the check is fairly fast. However, if you *know* you have
a symmetric and hollow distance matrix, you can disable this
check for small performance gains on extremely large distance
matrices
"""
super(Permanova, self).__init__(mdmap, [dm], [cat], num_dms=1,
random_fn=random_fn, suppress_symmetry_and_hollowness_check=\
suppress_symmetry_and_hollowness_check)
def __call__(self, num_perms=999):
"""Runs PERMANOVA on the current distance matrix and sample grouping.
Returns a dict containing the results. The following keys are set:
method_name - name of the statistical method
f_value - the PERMANOVA F statistic computed by the test
p_value - the p-value computed by the test, or 'NA' if the number
of permutations was zero
num_perms - the number of permutations used when calculating the
p-value
Arguments:
num_perms - the number of permutations to use when calculating the
p-value
"""
results = super(Permanova, self).__call__(num_perms)
category = self.Categories[0]
samples = self.DistanceMatrices[0].SampleIds
# Create the group map, which maps sample ID to category value (e.g.
# sample 1 to 'control' and sample 2 to 'fast').
group_map = {}
for samp_id in samples:
group_map[samp_id] = self.MetadataMap.getCategoryValue(
samp_id, category)
# Calculate the F statistic with the grouping found in the current
# metadata map.
f_stat = self._permanova(group_map)
if num_perms > 0:
# Calculate the p-value based on the number of permutations.
perm_stats = []
for i in range(num_perms):
# Randomize grouping. We don't use values() in order to
# preserve ordering in case the user's random function doesn't
# change the order of the items in the list.
grouping_random = [group_map[sample] for sample in samples]
grouping_random = self.RandomFunction(grouping_random)
for j, sample in enumerate(samples):
group_map[sample] = grouping_random[j]
perm_stats.append(self._permanova(group_map))
# Calculate the p-value.
p_value = (sum(perm_stats >= f_stat) + 1) / (num_perms + 1)
else:
p_value = 1.0
results['method_name'] = 'PERMANOVA'
results['f_value'] = f_stat
results['p_value'] = p_value
results['num_perms'] = num_perms
return results
def _permanova(self, grouping):
"""Computes PERMANOVA pseudo-F-statistic.
Arguments:
grouping - a python dict mapping sample ID to category value (e.g.
sample 1 to 'control' and sample 2 to 'fast'). This map must
contain a key for each sample ID in the current distance
matrix
"""
samples = self.DistanceMatrices[0].SampleIds
dm = self.DistanceMatrices[0]
# Number of samples in each group.
unique_n = []
group_map = {}
# Extract the unique list of group labels.
gl_unique = unique(array(grouping.values()))
# Calculate number of groups and unique 'n's.
number_groups = len(gl_unique)
for i, i_string in enumerate(gl_unique):
group_map[i_string] = i
unique_n.append(grouping.values().count(i_string))
# Create grouping matrix.
grouping_matrix = -1 * ones((dm.Size, dm.Size))
for i, i_sample in enumerate(samples):
grouping_i = grouping[i_sample]
for j, j_sample in enumerate(samples):
if grouping_i == grouping[j_sample]:
grouping_matrix[i][j] = group_map[grouping[i_sample]]
# Extract upper triangle.
distances = dm[tri(dm.Size) == 0]
groups = grouping_matrix[tri(len(grouping_matrix)) == 0]
# Compute F value.
return self._compute_f_value(distances, groups, dm.Size,
number_groups, unique_n)
def _compute_f_value(self, distances, groupings, number_samples,
number_groups, unique_n):
"""Performs the calculations for the F value.
Arguments:
distances - a list of the distances
groupings - a list associating the distances to their groups
number_samples - how many samples there are
number_groups - how many groups there are
unique_n - list containing how many samples are in each within
group
"""
a = number_groups
N = number_samples
# Calculate s_T.
s_T = sum(distances * distances) / N
# Calculate s_W for each group, this accounts for different group
# sizes.
s_W = 0
for i in range(number_groups):
group_ix = groupings==i
diffs = distances[group_ix]
s_W = s_W + sum(diffs**2) / unique_n[i]
# Execute the formula.
s_A = s_T - s_W
return (s_A / (a-1)) / (s_W / (N-a))
class Best(CategoryStats):
"""Class for the BEST/BioEnv statistical analysis.
Based on vegan::bioenv function, which is an implementation of the BEST
statistical method.
"""
def __init__(self, dm, metadata_map, cats,
suppress_symmetry_and_hollowness_check=False):
"""Default constructor.