This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 269
/
stats.py
2459 lines (2050 loc) · 90.4 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",
"Will Van Treuren"]
__license__ = "GPL"
__version__ = "1.9.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 scipy.stats import (spearmanr, kruskal, mannwhitneyu, kendalltau,
power_divergence, ttest_1samp, ttest_ind)
from scipy.stats.distributions import (chi2, norm, f as fdist, t as tdist)
from scipy.special import ndtri
from collections import defaultdict
from os.path import join
from types import ListType
from copy import deepcopy
from itertools import combinations
from matplotlib import use
use('Agg', warn=False)
from matplotlib.pyplot import figure
from numpy import (argsort, array, ceil, empty, fill_diagonal, finfo,
log2, mean, ones, sqrt, tri, unique, zeros, ndarray, floor,
median, nan, min as np_min, max as np_max, absolute,
arctanh, asarray, e, hstack, isinf, isnan,
log, mean, nan, nonzero, sqrt, std, take, tanh,
transpose, seterr as np_seterr, var, arange, corrcoef,
trace, ravel, float as np_float, finfo, asarray, isnan,
isinf, abs)
from numpy.random import permutation, shuffle, randint
from biom.table import Table
from skbio.stats.distance import DistanceMatrix, mantel
from skbio.util import create_dir
from qiime.format import format_p_value_for_num_iters
from qiime.util import MetadataMap, write_biom_table
np_seterr(divide='warn')
MACHEP = finfo(np_float).eps
# 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 from QIIME 1.8.0.
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 = []
# 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 not isnan(obs_t):
num_tests += 1
# Correct the p-values for multiple comparisons, now that we know how many
# tests succeeded.
for stat in result:
corr_param_p_val = stat[3]
if corr_param_p_val is not None and not isnan(corr_param_p_val):
corr_param_p_val = min(corr_param_p_val * num_tests, 1)
stat[4] = corr_param_p_val
corr_nonparam_p_val = stat[5]
if corr_nonparam_p_val is not None and not isnan(corr_nonparam_p_val):
corr_nonparam_p_val = min(corr_nonparam_p_val * num_tests, 1)
stat[6] = corr_nonparam_p_val
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 isinstance(data, list) or isinstance(data, ndarray), "Data must be either" +\
" a Python list or a NumPy 1-D array"
assert isinstance(quantiles, list) or isinstance(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 not isinstance(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.
"""
def __init__(self, dms, num_dms=-1, min_dm_size=-1):
"""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
"""
self._num_dms = num_dms
self._min_dm_size = min_dm_size
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.shape[0] < 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.shape[0], dm.shape[0], self._min_dm_size,
self._min_dm_size))
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
correlogram 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).
"""
@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].shape[0]
sample_ids = dms[0].ids
for dm in dms:
if dm.shape[0] != size:
raise ValueError("All distance matrices must have the same "
"number of rows and columns.")
if dm.ids != sample_ids:
raise ValueError("All distance matrices must have matching "
"sample IDs.")
class MantelCorrelogram(CorrelationStats):
"""Class for the Mantel correlogram statistical method.
This class provides the functionality to run a Mantel correlogram analysis
on two distance matrices. In a nutshell, the distances are split into
distance classes and a Mantel test is run over each distance class. A
Mantel correlogram is created, which is basically a plot of distance
classes versus Mantel statistics.
Uses Sturge's rule to determine the number of distance classes, and
Pearson's method to compute the correlation at each distance class. The
corrected p-values are computed using Bonferroni correction.
"""
def __init__(self, eco_dm, geo_dm, alpha=0.05,
variable_size_distance_classes=False):
"""Constructs a new MantelCorrelogram instance.
Arguments:
eco_dm - a DistanceMatrix object representing the ecological
distances between samples (e.g. UniFrac distance matrix)
geo_dm - a DistanceMatrix object representing some other distance
measure between samples (most commonly geographical distances,
but could also be distances in pH, temperature, etc.)
alpha - the alpha value to use when marking the Mantel correlogram
plot for significance
variable_size_distance_classes - if True, distance classes (bins)
will vary in size such that each distance class (bin) will have
the same number of distances. If False, all distance classes
will have the same size, though the number of distances in each
class may not be equal. Having variable-sized distance classes
can help maintain statistical power if there are large
differences in the number of distances in each class
"""
super(MantelCorrelogram, self).__init__([eco_dm, geo_dm], num_dms=2,
min_dm_size=3)
self.Alpha = alpha
self.VariableSizeDistanceClasses = variable_size_distance_classes
@property
def Alpha(self):
"""Returns the alpha value."""
return self._alpha
@Alpha.setter
def Alpha(self, alpha):
"""Sets the alpha value.
Arguments:
alpha - the value of alpha. Must be between 0 and 1, inclusive
"""
if alpha >= 0 and alpha <= 1:
self._alpha = alpha
else:
raise ValueError("Alpha must be between 0 and 1.")
def __call__(self, num_perms=999):
"""Runs a Mantel correlogram test over the current distance matrices.
Returns a dict containing the results. The following keys are set:
method_name - name of the statistical method
class_index - list of distance class indices (the center of each
distance class)
num_dist - list of the number of distances in each distance class
mantel_r - list of the Mantel r statistics for each distance class
mantel_p - list of the p-values for each distance class
mantel_p_corr - list of the p-values for each distance class,
corrected for multiple tests
correlogram_plot - a matplotlib Figure object containing the
correlogram
Arguments:
num_perms - the number of permutations to use when calculating the
p-values
Note: This code is heavily based on the implementation of
mantel.correlog in R's vegan package.
"""
results = super(MantelCorrelogram, self).__call__(num_perms)
eco_dm = self.DistanceMatrices[0]
geo_dm = self.DistanceMatrices[1]
dm_size = eco_dm.shape[0]
# Find the number of lower triangular elements (excluding the
# diagonal).
num_dists = dm_size * (dm_size - 1) // 2
# Use Sturge's rule to determine the number of distance classes.
num_classes = int(ceil(1 + log2(num_dists)))
# Create the matrix of distance classes. Each element in the matrix
# contains what distance class the original element is in. Also find
# the distance class indices, which are the midpoints in each distance
# class.
dist_class_matrix, class_indices = self._find_distance_classes(
geo_dm, num_classes)
# Start assembling the results.
results['method_name'] = 'Mantel Correlogram'
results['class_index'] = []
results['num_dist'] = []
results['mantel_r'] = []
results['mantel_p'] = []
# Create a model matrix for each distance class, then compute a Mantel
# test using it and the original eco distance matrix. A model matrix
# contains ones for each element that is in the current distance class,
# and zeros otherwise (zeros on the diagonal as well).
for class_num in range(num_classes):
results['class_index'].append(class_indices[class_num])
model_matrix = zeros([dm_size, dm_size], dtype=int)
for i in range(dm_size):
for j in range(dm_size):
curr_ele = dist_class_matrix[i][j]
if curr_ele == class_num and i != j:
model_matrix[i][j] = 1
model_matrix = DistanceMatrix(model_matrix, geo_dm.ids)
# Count the number of distances in the current distance class.
num_distances = int(model_matrix.data.sum())
results['num_dist'].append(num_distances)
if num_distances == 0:
results['mantel_r'].append(None)
results['mantel_p'].append(None)
else:
row_sums = model_matrix.data.sum(axis=1)
row_sums = map(int, row_sums)
has_zero_sum = 0 in row_sums
# Only stop running Mantel tests if we've gone through half of
# the distance classes and at least one row has a sum of zero
# (i.e. the sample doesn't have any distances that fall in the
# current class).
if not (class_num > ((num_classes // 2) - 1) and has_zero_sum):
# Compute the correlation coefficient without performing
# permutation tests in order to check its sign below.
orig_stat, _, _ = mantel(
model_matrix, eco_dm, method='pearson',
permutations=0, strict=True)
# Negate the Mantel r statistic because we are using
# distance matrices, not similarity matrices (this is a
# necessary step, see Legendre's Numerical Ecology
# algorithm reference for more details).
results['mantel_r'].append(-orig_stat)
# Compute a one-tailed p-value in the direction of the
# sign.
if orig_stat < 0:
tail_type = 'less'
else:
tail_type = 'greater'
_, p_val, _ = mantel(
model_matrix, eco_dm, method='pearson',
permutations=num_perms, alternative=tail_type,
strict=True)
results['mantel_p'].append(p_val)
else:
results['mantel_r'].append(None)
results['mantel_p'].append(None)
# Correct p-values for multiple testing.
results['mantel_p_corr'] = self._correct_p_values(results['mantel_p'])
# Construct a correlogram of distance class versus mantel correlation
# statistic and fill in each point that is statistically significant.
results['correlogram_plot'] = self._generate_correlogram(
results['class_index'], results['mantel_r'],
results['mantel_p_corr'])
return results
def _find_distance_classes(self, dm, num_classes):
"""Computes a distance class matrix and distance class midpoints.
Returns a matrix of the same dimensions as the input matrix but each
element indicates which distance class (0..num_classes-1) the original
element belongs to. The diagonal will always have a value of -1,
indicating that it is not apart of any distance class. Also returns a
list of distance class midpoints.
Distance classes are determined by the minimum and maximum values in
the input matrix and the number of specified classes. If
self.VariableSizeDistanceClasses is True, distance classes will each
contain the same number of distances (but may vary in size). If False,
distance classes will be of equal size (but possibly with unequal
numbers of distances).
Arguments:
dm - the input DistanceMatrix object to compute distance classes on
num_classes - the number of desired distance classes
"""
if num_classes < 1:
raise ValueError("Cannot have fewer than one distance class.")
dm_lower_flat = dm.condensed_form()
size = dm.shape[0]
if self.VariableSizeDistanceClasses:
class_size = int(ceil(len(dm_lower_flat) / num_classes))
order = argsort(array(dm_lower_flat))
# Create the matrix of distance classes. Every element in the
# matrix tells what distance class the original element belongs to.
# Each element in the original matrix is traversed in sorted
# (min -> max) order, and the current distance class is incremented
# once it is "filled" with class_size distances.
dist_class_matrix = empty([size, size], dtype=int)
class_indices = []
curr_class = 0
class_start = dm_lower_flat[order[0]]
for i, sorted_idx in enumerate(order):
row_idx, col_idx = self._find_row_col_indices(sorted_idx)
class_end = dm_lower_flat[sorted_idx]
# Matrix is symmetric.
dist_class_matrix[row_idx][col_idx] = curr_class
dist_class_matrix[col_idx][row_idx] = curr_class
# Check if we've filled up our current class or are at the last
# iteration (the final distance class may not completely fill
# up).
if (i + 1) % class_size == 0 or i == len(order) - 1:
curr_class += 1
class_indices.append(class_start +
(class_end - class_start) / 2)
class_start = class_end
if curr_class < num_classes:
# Our last class was empty, so record the last distance seen
# (which will be the max) as the class index.
class_indices.append(class_end)
# Fill diagonal with -1, as it does not belong to any distance
# class.
fill_diagonal(dist_class_matrix, -1)
else:
# Compute the breakpoints of the distance classes based on the
# number of specified classes and the ranges of values in the lower
# triangular portion of the distance matrix (excluding the
# diagonal).
break_points = self._find_break_points(np_min(dm_lower_flat),
np_max(dm_lower_flat),
num_classes)
# Find the class indices (the midpoints between breakpoints).
class_indices = []
for bp_index, break_point in \
enumerate(break_points[0:num_classes]):
next_bp = break_points[bp_index + 1]
class_indices.append(break_point +
(0.5 * (next_bp - break_point)))
# Create the matrix of distance classes. Every element in the
# matrix tells what distance class the original element belongs to.
dist_class_matrix = empty([size, size], dtype=int)
for i in range(size):
for j in range(size):
if i != j:
curr_ele = dm[i][j]
bps = [(k - 1) for k, bp in enumerate(break_points)
if bp >= curr_ele]
min_bp = min(bps)
# If we somehow got a negative breakpoint (possible
# sometimes due to rounding error), put it in the first
# distance class.
dist_class_matrix[i][j] = min_bp if min_bp >= 0 else 0
else:
dist_class_matrix[i][j] = -1
return dist_class_matrix, class_indices
def _find_row_col_indices(self, idx):
"""Returns row, col for idx into flattened lower triangular matrix.
It is assumed that the index points to a matrix that was flattened,
containing only the lower triangular elements (excluding the diagonal)
in left-to-right, top-to-bottom order (such as that given by
DistanceMatrix.condensed_form()).
"""
if idx < 0:
raise IndexError("The index %d must be greater than or equal to "
"zero." % idx)
# First find the row we're at. The number of elements at each row
# increases by one each time.
curr_idx = 0
delta = 1
while curr_idx <= idx:
curr_idx += delta
delta += 1
# We subtract one because delta gives us one row past our target.
row = delta - 1
# Now that we know the row index, we subtract the number of elements
# below the row (given by (n*n-n)/2) to find the column that idx is at.
col = int(idx - ((row * row - row) / 2))
return row, col
def _find_break_points(self, start, end, num_classes):
"""Finds the points to break a range into equal width classes.
Returns a list of floats indicating breakpoints in the range.
Arguments:
start - the minimum value in the range
end - the maximum value in the range
num_classes - the number of classes to break the range into
"""
if start >= end:
raise ValueError("Cannot find breakpoints because the starting "
"point is greater than or equal to the ending "
"point.")
if num_classes < 1:
raise ValueError("Cannot have fewer than one distance class.")
width = (end - start) / num_classes
break_points = [start + width * class_num
for class_num in range(num_classes)]
break_points.append(float(end))
# Move the first breakpoint a little bit to the left. Machine epsilon
# is taken from:
# http://en.wikipedia.org/wiki/Machine_epsilon#
# Approximation_using_Python
epsilon = finfo(float).eps
break_points[0] = break_points[0] - epsilon
return break_points
def _correct_p_values(self, p_vals):
"""Corrects p-values for multiple testing using Bonferroni correction.
This method of correction is non-progressive. If any of the p-values
are None or NaN, they are not counted towards the number of tests used
in the correction.
Returns a list of Bonferroni-corrected p-values for those that are not
None/NaN. Those that are None/NaN are simply returned. The ordering of
p-values is maintained.
Arguments:
p_vals - list of p-values (of type float or None)
"""
num_tests = len([p_val for p_val in p_vals
if p_val is not None and not isnan(p_val)])
corrected_p_vals = []
for p_val in p_vals:
if p_val is not None and not isnan(p_val):
corrected_p_vals.append(min(p_val * num_tests, 1))
else:
corrected_p_vals.append(p_val)
return corrected_p_vals
def _generate_correlogram(self, class_indices, mantel_stats,
corrected_p_vals):
"""Generates a matplotlib plot of the Mantel correlogram.
Returns a matplotlib Figure instance, which can then be manipulated
further or saved to a file as necessary.
Arguments:
class_indices - list of distance class indices (for the x-axis)
mantel_stats - list of Mantel r stats (for the y-axis)
corrected_p_vals - list of corrected p-values (for filling in
points to indicate significance)
"""
# Plot distance class index versus mantel correlation statistic.
fig = figure()
ax = fig.add_subplot(111)
ax.plot(class_indices, mantel_stats, 'ks-', mfc='white', mew=1)
# Fill in each point that is significant (based on alpha).
signif_classes = []
signif_stats = []
for idx, p_val in enumerate(corrected_p_vals):
if p_val is not None and not isnan(p_val) and p_val <= self.Alpha:
signif_classes.append(class_indices[idx])
signif_stats.append(mantel_stats[idx])
ax.plot(signif_classes, signif_stats, 'ks', mfc='k')
ax.set_title("Mantel Correlogram")
ax.set_xlabel("Distance class index")
ax.set_ylabel("Mantel correlation statistic")
return fig
class PartialMantel(CorrelationStats):
"""Class for the partial Mantel matrix correlation statistical method.
This class provides the functionality to run a partial Mantel analysis on
three distance matrices. A partial Mantel test essentially computes the
Pearson correlation between two distance matrices after first controlling
for the effects of a third distance matrix (the control matrix).
"""
def __init__(self, dm1, dm2, cdm):
"""Constructs a new PartialMantel instance.
Arguments:
dm1 - first DistanceMatrix object to be compared
dm2 - second DistanceMatrix object to be compared
cdm - the control DistanceMatrix object
"""
super(PartialMantel, self).__init__([dm1, dm2, cdm], num_dms=3,
min_dm_size=3)
def __call__(self, num_perms=999):
"""Runs a partial Mantel test on the current distance matrices.
Returns a dict containing the results. The following keys are set:
method_name - name of the statistical method
mantel_p - the p-value computed by the test
mantel_r - the Mantel r statistic computed by the test
Arguments:
num_perms - the number of times to permute the distance matrix
while calculating the p-value
Credit: The code herein is based loosely on the implementation found in
R's vegan package.
"""
res = super(PartialMantel, self).__call__(num_perms)
# Calculate the correlation statistic.
corr = lambda rxy, rxz, ryz: (rxy - rxz * ryz) / (sqrt(1 -
rxz ** 2) * sqrt(1 - ryz ** 2))
# Load initial/placeholder values in the results dictionary.
res['method_name'] = 'Partial Mantel'
res['mantel_r'] = None
res['mantel_p'] = None
dm1, dm2, cdm = self.DistanceMatrices
dm1_flat = dm1.condensed_form()
dm2_flat = dm2.condensed_form()
cdm_flat = cdm.condensed_form()
# Get the initial r-values before permuting.
rval1 = pearson(dm1_flat, dm2_flat)
rval2 = pearson(dm1_flat, cdm_flat)
rval3 = pearson(dm2_flat, cdm_flat)
# Calculate the original test statistic (r-value).
orig_stat = corr(rval1, rval2, rval3)
# Calculate permuted r-values and p-values, storing them for use in the
# calculation of the final statistic.
perm_stats = []
numerator = 0
for i in range(0, num_perms):
# Permute the first distance matrix and calculate new r and
# p-values.
p1 = permute_2d(dm1, permutation(dm1.shape[0]))
dm1_perm = DistanceMatrix(p1, dm1.ids)
dm1_perm_flat = dm1_perm.condensed_form()
rval1 = pearson(dm1_perm_flat, dm2_flat)
rval2 = pearson(dm1_perm_flat, cdm_flat)
perm_stats.append(corr(rval1, rval2, rval3))
if perm_stats[-1] >= orig_stat:
numerator += 1
# Load the final statistics into the result dictionary.
res['mantel_r'] = orig_stat
res['mantel_p'] = (numerator + 1) / (num_perms + 1)
return res
def paired_difference_analyses(personal_ids_to_state_values,
analysis_categories,
state_values,
output_dir,
line_color="black",
ymin=None,
ymax=None):
"""run paired difference analysis one sample t-tests and generate plots
Apply one-sample t-tests and generate plots to test for changes in
certain values with a state change. A state change here refers to a
pre/post-type experimental design, such as pre-treatment to
post-treatment, and the values that are being tested for change can
be things like alpha diversity, abundance of specific taxa, a principal
coordinate value (e.g., PC1 value before and after treatment), and so
on.
The one-sample t-test is applied on each pair of differences. So, if
experiment was based on looking for changes in proteobacteria abundance
with treatment, you would have pre- and post-treatment proteobacteria
abundances for a number of individuals. The difference would be computed
between those, and the null hypothesis is that the mean of those differences
is equal to zero (i.e., no change with treatment).
Line plots are also generated to show the change on a per-individual basis.
personal_ids_to_state_values: a 2d dictionary mapping personal ids to potential
analysis categories, which each contain a pre/post value. this might look like
the following:
{'firmicutes-abundance':
{'subject1':[0.45,0.55],
'subject2':[0.11,0.52]},
'bacteroidetes-abundace':
{'subject1':[0.28,0.21],
'subject2':[0.11,0.01]}
}
examples of functions that can be useful for generating these data are
qiime.parse.extract_per_individual_state_metadata_from_sample_metadata and
qiime.parse.extract_per_individual_state_metadata_from_sample_metadata_and_biom
analysis_categories: a list of categories to include in analyses (e.g,
['firmicutes-abundance', 'bacteroidetes-abundace'])
state_values: an ordered list describing each of the states being compared (these
are the x labels in the resulting plots)
output_dir: directory where output should be written (will be created if
it doesn't exist)
ymin: minimum y-value in plots (if it should be consistent across
plots - by default will be chosen on a per-plot basis)
ymax: maximum y-value in plots (if it should be consistent across
plots - by default will be chosen on a per-plot basis)
"""
if len(state_values) != 2:
raise ValueError("Only two state values can be provided. "
"Support currently exists only for pre/post experimental design.")
# create the output directory if it doesn't already exist
create_dir(output_dir)
num_analysis_categories = len(analysis_categories)
x_values = range(len(state_values))
paired_difference_output_fp = \
join(output_dir, 'paired_difference_comparisons.txt')
paired_difference_output_f = open(paired_difference_output_fp, 'w')
# write header line to output file
paired_difference_output_f.write(
"#Metadata category\tNum differences (i.e., n)\tMean difference\t"
"Median difference\tt one sample\tt one sample parametric p-value\t"
"t one sample parametric p-value (Bonferroni-corrected)\n")
paired_difference_t_test_results = {}
biom_table_fp = join(output_dir, 'differences.biom')
biom_sids_fp = join(output_dir, 'differences_sids.txt')
biom_observation_ids = []
biom_data = []
# need a list of personal_ids to build the biom table -
# ugly, but get it working first
personal_ids = []
for c in personal_ids_to_state_values.values():
personal_ids.extend(c.keys())
personal_ids = list(set(personal_ids))
# initiate list of output file paths to return
output_fps = [paired_difference_output_fp,
biom_table_fp,
biom_sids_fp]
num_successful_tests = 0
included_personal_ids = defaultdict(list)
for category_number, analysis_category in enumerate(analysis_categories):
personal_ids_to_state_metadatum = personal_ids_to_state_values[
analysis_category]
analysis_category_fn_label = analysis_category.replace(' ', '-')
plot_output_fp = join(
output_dir,
'%s.pdf' %
analysis_category_fn_label)
fig = figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# initialize a list to store the distribution of changes
# with state change
differences = []
pre_values = []
post_values = []
store_biom_datum = True
for personal_id in personal_ids:
data = personal_ids_to_state_metadatum[personal_id]
if None in data:
# if any of the data points are missing, don't store
# a difference for this individual, and don't store
# the category in the BIOM table
store_biom_datum = False
raise ValueError("Some data points are missing, "
"cannot create biom file.")
else:
# otherwise compute the difference between the ending
# and starting state
pre_value = data[0]
post_value = data[1]
included_personal_ids[personal_id].append(pre_value)
included_personal_ids[personal_id].append(post_value)
pre_values.append(pre_value)
post_values.append(post_value)
difference = post_value - pre_value
differences.append(difference)
# and plot the start and stop values as a line
axes.plot(x_values, data, line_color, linewidth=0.5)
if store_biom_datum:
biom_observation_ids.append(analysis_category)
biom_data.append(differences)
# run stats for current analysis category
n = len(differences)
mean_differences = mean(differences)
median_differences = median(differences)
t_one_sample_results = t_one_sample(differences)
t = t_one_sample_results[0]
p_value = t_one_sample_results[1]
if p_value is not None:
num_successful_tests += 1