File: test_pd.py

package info (click to toggle)
python-skbio 0.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,924 kB
  • sloc: python: 67,527; ansic: 672; makefile: 225
file content (401 lines) | stat: -rw-r--r-- 16,231 bytes parent folder | download | duplicates (2)
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
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# ----------------------------------------------------------------------------

from unittest import TestCase, main
from io import StringIO
import os

import numpy as np
import pandas as pd

from skbio import TreeNode
from skbio.util import get_data_path
from skbio.tree import DuplicateNodeError, MissingNodeError
from skbio.diversity.alpha import faith_pd, phydiv


class FaithPDTests(TestCase):

    def setUp(self):
        self.counts = np.array([0, 1, 1, 4, 2, 5, 2, 4, 1, 2])
        self.b1 = np.array([[1, 3, 0, 1, 0],
                            [0, 2, 0, 4, 4],
                            [0, 0, 6, 2, 1],
                            [0, 0, 1, 1, 1],
                            [2, 0, 3, 0, 0]])
        self.sids1 = list('ABCDE')
        self.oids1 = ['OTU%d' % i for i in range(1, 6)]
        self.t1 = TreeNode.read(StringIO(
            '(((((OTU1:0.5,OTU2:0.5):0.5,OTU3:1.0):1.0):'
            '0.0,(OTU4:0.75,OTU5:0.75):1.25):0.0)root;'))
        self.t1_w_extra_tips = TreeNode.read(
           StringIO('(((((OTU1:0.5,OTU2:0.5):0.5,OTU3:1.0):1.0):0.0,(OTU4:'
                    '0.75,(OTU5:0.25,(OTU6:0.5,OTU7:0.5):0.5):0.5):1.25):0.0'
                    ')root;'))

    def test_faith_pd(self):
        # expected results derived from QIIME 1.9.1, which
        # is a completely different implementation skbio's initial
        # phylogenetic diversity implementation
        actual = faith_pd(self.b1[0], self.oids1, self.t1)
        expected = 4.5
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[1], self.oids1, self.t1)
        expected = 4.75
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[2], self.oids1, self.t1)
        expected = 4.75
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[3], self.oids1, self.t1)
        expected = 4.75
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[4], self.oids1, self.t1)
        expected = 3.0
        self.assertAlmostEqual(actual, expected)

    def test_faith_pd_extra_tips(self):
        # results are the same despite presences of unobserved tips in tree
        actual = faith_pd(self.b1[0], self.oids1, self.t1_w_extra_tips)
        expected = faith_pd(self.b1[0], self.oids1, self.t1)
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[1], self.oids1, self.t1_w_extra_tips)
        expected = faith_pd(self.b1[1], self.oids1, self.t1)
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[2], self.oids1, self.t1_w_extra_tips)
        expected = faith_pd(self.b1[2], self.oids1, self.t1)
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[3], self.oids1, self.t1_w_extra_tips)
        expected = faith_pd(self.b1[3], self.oids1, self.t1)
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd(self.b1[4], self.oids1, self.t1_w_extra_tips)
        expected = 3.0
        self.assertAlmostEqual(actual, expected)

    def test_faith_pd_none_observed(self):
        actual = faith_pd(np.array([], dtype=int),
                          np.array([], dtype=int),
                          self.t1)
        expected = 0.0
        self.assertAlmostEqual(actual, expected)
        actual = faith_pd([0, 0, 0, 0, 0], self.oids1, self.t1)
        expected = 0.0
        self.assertAlmostEqual(actual, expected)

    def test_faith_pd_all_observed(self):
        actual = faith_pd([1, 1, 1, 1, 1], self.oids1, self.t1)
        expected = sum(n.length for n in self.t1.traverse()
                       if n.length is not None)
        self.assertAlmostEqual(actual, expected)

        actual = faith_pd([1, 2, 3, 4, 5], self.oids1, self.t1)
        expected = sum(n.length for n in self.t1.traverse()
                       if n.length is not None)
        self.assertAlmostEqual(actual, expected)

    def test_faith_pd_one_observed(self):
        actual = faith_pd([1, 0, 0, 0, 0], self.oids1, self.t1)
        expected = 2.0
        self.assertAlmostEqual(actual, expected)

    def test_faith_pd_minimal(self):
        # two tips
        tree = TreeNode.read(StringIO('(OTU1:0.25, OTU2:0.25)root;'))
        actual = faith_pd([1, 0], ['OTU1', 'OTU2'], tree)
        expected = 0.25
        self.assertEqual(actual, expected)

    def test_faith_pd_qiime_tiny_test(self):
        # the following table and tree are derived from the QIIME 1.9.1
        # "tiny-test" data
        tt_table_fp = get_data_path(
            os.path.join('qiime-191-tt', 'otu-table.tsv'), 'data')
        tt_tree_fp = get_data_path(
            os.path.join('qiime-191-tt', 'tree.nwk'), 'data')

        self.q_table = pd.read_csv(tt_table_fp, sep='\t', skiprows=1,
                                   index_col=0)
        self.q_tree = TreeNode.read(tt_tree_fp)

        expected_fp = get_data_path(
            os.path.join('qiime-191-tt', 'faith-pd.txt'), 'data')
        expected = pd.read_csv(expected_fp, sep='\t', index_col=0)
        for sid in self.q_table.columns:
            actual = faith_pd(self.q_table[sid],
                              taxa=self.q_table.index,
                              tree=self.q_tree)
            self.assertAlmostEqual(actual, expected['PD_whole_tree'][sid])

    def test_faith_pd_root_not_observed(self):
        # expected values computed by hand
        tree = TreeNode.read(
            StringIO('((OTU1:0.1, OTU2:0.2):0.3, (OTU3:0.5, OTU4:0.7):1.1)'
                     'root;'))
        taxa = ['OTU%d' % i for i in range(1, 5)]
        # root node not observed, but branch between (OTU1, OTU2) and root
        # is considered observed
        actual = faith_pd([1, 1, 0, 0], taxa, tree)
        expected = 0.6
        self.assertAlmostEqual(actual, expected)

        # root node not observed, but branch between (OTU3, OTU4) and root
        # is considered observed
        actual = faith_pd([0, 0, 1, 1], taxa, tree)
        expected = 2.3
        self.assertAlmostEqual(actual, expected)

    def test_faith_pd_invalid_input(self):
        # tree has duplicated tip ids
        t = TreeNode.read(
            StringIO('(((((OTU1:0.5,OTU2:0.5):0.5,OTU3:1.0):1.0):0.0,(OTU4:'
                     '0.75,OTU2:0.75):1.25):0.0)root;'))
        counts = [1, 2, 3]
        taxa = ['OTU1', 'OTU2', 'OTU3']
        self.assertRaises(DuplicateNodeError, faith_pd, counts, taxa,
                          t)

        # unrooted tree as input
        t = TreeNode.read(StringIO('((OTU1:0.1, OTU2:0.2):0.3, OTU3:0.5,'
                                   'OTU4:0.7);'))
        counts = [1, 2, 3]
        taxa = ['OTU1', 'OTU2', 'OTU3']
        self.assertRaises(ValueError, faith_pd, counts, taxa, t)

        # taxa has duplicated ids
        t = TreeNode.read(
            StringIO('(((((OTU1:0.5,OTU2:0.5):0.5,OTU3:1.0):1.0):0.0,(OTU4:'
                     '0.75,OTU5:0.75):1.25):0.0)root;'))
        counts = [1, 2, 3]
        taxa = ['OTU1', 'OTU2', 'OTU2']
        self.assertRaises(ValueError, faith_pd, counts, taxa, t)

        # len of vectors not equal
        t = TreeNode.read(
            StringIO('(((((OTU1:0.5,OTU2:0.5):0.5,OTU3:1.0):1.0):0.0,(OTU4:'
                     '0.75,OTU5:0.75):1.25):0.0)root;'))
        counts = [1, 2]
        taxa = ['OTU1', 'OTU2', 'OTU3']
        self.assertRaises(ValueError, faith_pd, counts, taxa, t)
        counts = [1, 2, 3]
        taxa = ['OTU1', 'OTU2']
        self.assertRaises(ValueError, faith_pd, counts, taxa, t)

        # negative counts
        t = TreeNode.read(
            StringIO('(((((OTU1:0.5,OTU2:0.5):0.5,OTU3:1.0):1.0):0.0,(OTU4:'
                     '0.75,OTU5:0.75):1.25):0.0)root;'))
        counts = [1, 2, -3]
        taxa = ['OTU1', 'OTU2', 'OTU3']
        self.assertRaises(ValueError, faith_pd, counts, taxa, t)

        # tree with no branch lengths
        t = TreeNode.read(
            StringIO('((((OTU1,OTU2),OTU3)),(OTU4,OTU5));'))
        counts = [1, 2, 3]
        taxa = ['OTU1', 'OTU2', 'OTU3']
        self.assertRaises(ValueError, faith_pd, counts, taxa, t)

        # tree missing some branch lengths
        t = TreeNode.read(
            StringIO('(((((OTU1,OTU2:0.5):0.5,OTU3:1.0):1.0):0.0,(OTU4:'
                     '0.75,OTU5:0.75):1.25):0.0)root;'))
        counts = [1, 2, 3]
        taxa = ['OTU1', 'OTU2', 'OTU3']
        self.assertRaises(ValueError, faith_pd, counts, taxa, t)

        # taxa not present in tree
        t = TreeNode.read(
            StringIO('(((((OTU1:0.5,OTU2:0.5):0.5,OTU3:1.0):1.0):0.0,(OTU4:'
                     '0.75,OTU5:0.75):1.25):0.0)root;'))
        counts = [1, 2, 3]
        taxa = ['OTU1', 'OTU2', 'OTU42']
        self.assertRaises(MissingNodeError, faith_pd, counts, taxa, t)


class PhyDivTests(TestCase):

    def setUp(self):
        self.tree = TreeNode.read(StringIO(
            '(((a:0.4,b:0.5):0.7,((c:0.1,d:0.2):0.6,(e:0.2,f:0.3):0.4):0.2)'
            ':0.1,g:1.2):0.2;'))

        # each dash (-) represents branch length = 0.05
        #
        #                          /--------a
        #          /--------------|
        #         |                \----------b
        #         |
        #      /--|                    /--c
        #     |   |      /------------|
        #     |   |     |              \----d
        #     |    \----|
        # ----|         |          /----e
        #     |          \--------|
        #     |                    \------f
        #     |
        #      \------------------------g

        self.taxa = list('abcdef')
        self.data = np.array([
            [1, 2, 0, 0, 0, 0],   # clade (a, b)
            [0, 0, 3, 4, 0, 0],   # clade (c, d)
            [0, 0, 0, 0, 5, 6],   # clade (e, f)
            [0, 0, 3, 4, 5, 6],   # non-basal, monophyletic group (c, d, e, f)
            [1, 2, 3, 4, 0, 0]])  # basal, non-monophyletic group (a, b, c, d)

    def test_phydiv_rooted_unweighted(self):
        # equivalent to faith_pd
        for datum in self.data:
            obs = phydiv(datum, self.taxa, self.tree)
            exp = faith_pd(datum, self.taxa, self.tree)
            self.assertAlmostEqual(obs, exp)

    def test_phydiv_unrooted_unweighted(self):
        # equivalent to faith_pd without path to root
        exps = [0.9, 0.3, 0.5, 1.8, 2.7]
        for datum, exp in zip(self.data, exps):
            obs = phydiv(datum, self.taxa, self.tree, rooted=False)
            self.assertAlmostEqual(obs, exp)

        # edge case: one taxon
        obs = phydiv([1], ['a'], self.tree, rooted=False)
        self.assertEqual(obs, 0)

        # edge case: zero taxon
        obs = phydiv([0], ['a'], self.tree, rooted=False)
        self.assertEqual(obs, 0)

        # edge case: no taxon
        obs = phydiv([], [], self.tree, rooted=False)
        self.assertEqual(obs, 0)

    def test_phydiv_rooted_weighted(self):
        # group (a, b)
        # = (0.4 * 1 + 0.5 * 2 + (0.7 + 0.1 + 0.2) * (1 + 2)) / (1 + 2)
        obs = phydiv(self.data[0], self.taxa, self.tree, weight=True)
        exp = 1.46666667
        self.assertAlmostEqual(obs, exp)

        # group (c, d)
        # = (0.1 * 3 + 0.2 * 4 + (0.6 + 0.2 + 0.1 + 0.2) * (3 + 4)) / (3 + 4)
        obs = phydiv(self.data[1], self.taxa, self.tree, weight=True)
        exp = 1.25714286
        self.assertAlmostEqual(obs, exp)

        # group (c, d, e, f)
        # = (0.1 * 3 + 0.2 * 4 + 0.2 * 5 + 0.3 * 6 + 0.6 * (3 + 4) + 0.4 *
        #   (5 + 6) + (0.2 + 0.1 + 0.2) * (3 + 4 + 5 + 6)) / (3 + 4 + 5 + 6)
        obs = phydiv(self.data[3], self.taxa, self.tree, weight=True)
        exp = 1.19444444
        self.assertAlmostEqual(obs, exp)

        # group (a, b, c, d)
        # = (0.4 * 1 + 0.5 * 2 + 0.1 * 3 + 0.2 * 4 + 0.7 * (1 + 2) + (0.6 +
        #   0.2) * (3 + 4) + (0.1 + 0.2) * (1 + 2 + 3 + 4)) / (1 + 2 + 3 + 4)
        obs = phydiv(self.data[4], self.taxa, self.tree, weight=True)
        exp = 1.32
        self.assertAlmostEqual(obs, exp)

    def test_phydiv_unrooted_weighted(self):
        # a.k.a., balance-weighted PD
        # group (a, b)
        # = (0.4 + 0.5) * 2 * min(1, 2) / (1 + 2)
        obs = phydiv(self.data[0], self.taxa, self.tree,
                     rooted=False, weight=True)
        exp = 0.6
        self.assertAlmostEqual(obs, exp)

        # group (c, d)
        # = (0.1 + 0.2) * 2 * min(3, 4) / (3 + 4)
        obs = phydiv(self.data[1], self.taxa, self.tree,
                     rooted=False, weight=True)
        exp = 0.25714286
        self.assertAlmostEqual(obs, exp)

        # group (c, d, e, f)
        # = 2 * (0.1 * min(3, 4 + 5 + 6) + 0.2 * min(4, 3 + 5 + 6) + 0.2 *
        #   min(5, 3 + 4 + 6) + 0.3 * min(6, 3 + 4 + 5) + (0.6 + 0.4) *
        #   min(3 + 4, 5 + 6)) / (3 + 4 + 5 + 6)
        obs = phydiv(self.data[3], self.taxa, self.tree,
                     rooted=False, weight=True)
        exp = 1.21111111
        self.assertAlmostEqual(obs, exp)

        # group (a, b, c, d)
        # = 2 * (0.4 * min(1, 2 + 3 + 4) + 0.5 * min(2, 1 + 3 + 4) + (0.7 +
        #   0.6 + 0.2) * min(1 + 2, 3 + 4) + 0.1 * min(3, 1 + 2 + 4) + 0.2 *
        #   min(4, 1 + 2 + 3)) / (1 + 2 + 3 + 4)
        obs = phydiv(self.data[4], self.taxa, self.tree,
                     rooted=False, weight=True)
        exp = 1.4
        self.assertAlmostEqual(obs, exp)

        # edge cases
        self.assertEqual(phydiv([1], ['a'], self.tree, False, True), 0)
        self.assertEqual(phydiv([0], ['a'], self.tree, False, True), 0)
        self.assertEqual(phydiv([], [], self.tree, False, True), 0)

    def test_phydiv_weight_param(self):
        # group (a, b), unrooted
        # = (0.4 + 0.5) * (2 * min(1, 2) / (1 + 2)) ** theta
        obs = phydiv(self.data[0], self.taxa, self.tree, False, 0.5)
        exp = 0.73484692
        self.assertAlmostEqual(obs, exp)
        obs = phydiv(self.data[0], self.taxa, self.tree, False, 0.25)
        exp = 0.81324180
        self.assertAlmostEqual(obs, exp)
        # fall back to unweighted
        obs = phydiv(self.data[0], self.taxa, self.tree, False, 0)
        exp = 0.9
        # fall back to fully-weighted
        self.assertAlmostEqual(obs, exp)
        obs = phydiv(self.data[0], self.taxa, self.tree, False, 1)
        exp = 0.6
        self.assertAlmostEqual(obs, exp)

        # rooted
        # = (0.4 * 1 ** theta + 0.5 * 2 ** theta + (0.7 + 0.1 + 0.2) *
        #   (1 + 2) ** theta) / (1 + 2) ** theta
        obs = phydiv(self.data[0], self.taxa, self.tree, True, 0.5)
        exp = 1.63918840
        self.assertAlmostEqual(obs, exp)
        obs = phydiv(self.data[0], self.taxa, self.tree, True, 0.25)
        exp = 1.75573528
        self.assertAlmostEqual(obs, exp)

        # edge cases
        self.assertEqual(phydiv([1], ['a'], self.tree, False, 0.5), 0)
        self.assertEqual(phydiv([0], ['a'], self.tree, False, 0.5), 0)
        self.assertEqual(phydiv([], [], self.tree, False, 0.5), 0)

    def test_phydiv_tree_unrooted(self):
        # convert tree to unrooted
        outgroup = self.tree.find('g')
        ingroup = outgroup.siblings()[0]
        unrooted = ingroup.copy()
        unrooted.extend([outgroup.copy()])
        unrooted.length += self.tree.length or 0.0

        # auto-enter unrooted mode
        obs = phydiv(self.data[0], self.taxa, unrooted)
        exp = phydiv(self.data[0], self.taxa, self.tree, rooted=False)
        self.assertEqual(obs, exp)

        # force rooted mode
        obs = phydiv(self.data[0], self.taxa, unrooted, rooted=True)
        exp = phydiv(self.data[0], self.taxa, self.tree)
        self.assertEqual(obs, exp)

    def test_phydiv_invalid_weight(self):
        params = (self.data[0], self.taxa, self.tree)
        self.assertRaises(ValueError, phydiv, *params, weight='hello')
        self.assertRaises(ValueError, phydiv, *params, weight=-0.5)
        self.assertRaises(ValueError, phydiv, *params, weight=2.0)


if __name__ == "__main__":
    main()