File: test_downstream.py

package info (click to toggle)
qiime 1.8.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 130,508 kB
  • ctags: 10,145
  • sloc: python: 110,826; haskell: 379; sh: 169; makefile: 125
file content (515 lines) | stat: -rwxr-xr-x 22,636 bytes parent folder | download
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
#!/usr/bin/env python
# File created on 20 Feb 2013
from __future__ import division

__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Greg Caporaso", "Kyle Bittinger", "Jai Ram Rideout"]
__license__ = "GPL"
__version__ = "1.8.0"
__maintainer__ = "Greg Caporaso"
__email__ = "gregcaporaso@gmail.com"

import sys
from StringIO import StringIO
from shutil import rmtree
from glob import glob
from os.path import join, exists, getsize, split, splitext
from cogent.util.unit_test import TestCase, main
from cogent.util.misc import remove_files
from qiime.compare_alpha_diversity import compare_alpha_diversities
from qiime.util import (get_tmp_filename,
                        load_qiime_config,
                        get_qiime_temp_dir,
                        create_dir)
from qiime.parse import (parse_qiime_parameters,
                         parse_distmat_to_dict)
from qiime.test import (initiate_timeout,
                        disable_timeout,
                        get_test_data_fps)
from qiime.workflow.util import (call_commands_serially,
                                 no_status_updates)
from qiime.workflow.downstream import (run_beta_diversity_through_plots,
                                       run_alpha_rarefaction,
                                       run_jackknifed_beta_diversity,
                                       run_summarize_taxa_through_plots)

class DownstreamWorkflowTests(TestCase):
    
    def setUp(self):
        """ """
        self.test_data = get_test_data_fps()
        self.files_to_remove = []
        self.dirs_to_remove = []
        
        # Create example output directory
        tmp_dir = get_qiime_temp_dir()
        self.test_out = get_tmp_filename(tmp_dir=tmp_dir,
                                         prefix='core_qiime_analyses_test_',
                                         suffix='',
                                         result_constructor=str)
        self.dirs_to_remove.append(self.test_out)
        create_dir(self.test_out)
        
        self.qiime_config = load_qiime_config()
        self.params = parse_qiime_parameters(params_f1)

        # suppress stderr during tests (one of the systems calls in the 
        # workflow prints a warning, and we can't suppress that warning with 
        # warnings.filterwarnings) here because it comes from within the code 
        # executed through the system call. Found this trick here:
        # http://stackoverflow.com/questions/9949633/suppressing-print-as-stdout-python
        self.saved_stderr = sys.stderr
        sys.stderr = StringIO()
        
        initiate_timeout(180)
    
    def tearDown(self):
        """ """
        disable_timeout()
        
        # reset sys.stderr
        sys.stderr = self.saved_stderr
        
        remove_files(self.files_to_remove)
        # remove directories last, so we don't get errors
        # trying to remove files which may be in the directories
        for d in self.dirs_to_remove:
            if exists(d):
                rmtree(d)
         
    def test_run_beta_diversity_through_plots(self):
        """ run_beta_diversity_through_plots generates expected results
        """
        run_beta_diversity_through_plots(
         self.test_data['biom'][0], 
         self.test_data['map'][0],
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         tree_fp=self.test_data['tree'][0],
         parallel=False, 
         status_update_callback=no_status_updates)
        
        unweighted_unifrac_dm_fp = join(self.test_out,'unweighted_unifrac_dm.txt')
        weighted_unifrac_dm_fp = join(self.test_out,'weighted_unifrac_dm.txt')
        unweighted_unifrac_pc_fp = join(self.test_out,'unweighted_unifrac_pc.txt')
        weighted_unifrac_pc_fp = join(self.test_out,'weighted_unifrac_pc.txt')
        weighted_unifrac_html_fp = join(self.test_out,
        'weighted_unifrac_emperor_pcoa_plot','index.html')

        # check for expected relations between values in the unweighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(unweighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        # check for expected relations between values in the weighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(weighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        
        # check that final output files have non-zero size
        self.assertTrue(getsize(unweighted_unifrac_pc_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_pc_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_html_fp) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)

         
    def test_run_beta_diversity_through_plots_even_sampling(self):
        """ run_beta_diversity_through_plots functions with even sampling
        """

        run_beta_diversity_through_plots(
         self.test_data['biom'][0], 
         self.test_data['map'][0],
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         sampling_depth=20,
         tree_fp=self.test_data['tree'][0],
         parallel=False, 
         status_update_callback=no_status_updates)

        unweighted_unifrac_dm_fp = join(self.test_out,'unweighted_unifrac_dm.txt')
        weighted_unifrac_dm_fp = join(self.test_out,'weighted_unifrac_dm.txt')
        unweighted_unifrac_pc_fp = join(self.test_out,'unweighted_unifrac_pc.txt')
        weighted_unifrac_pc_fp = join(self.test_out,'weighted_unifrac_pc.txt')
        weighted_unifrac_html_fp = join(self.test_out,
        'weighted_unifrac_emperor_pcoa_plot','index.html')

        # check for expected relations between values in the unweighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(unweighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        # check for expected relations between values in the weighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(weighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        
        # check that final output files have non-zero size
        self.assertTrue(getsize(unweighted_unifrac_pc_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_pc_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_html_fp) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)
      
    def test_run_beta_diversity_through_plots_parallel(self):
        """ run_beta_diversity_through_plots generates expected results in parallel
        """
        run_beta_diversity_through_plots(
         self.test_data['biom'][0], 
         self.test_data['map'][0],
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         tree_fp=self.test_data['tree'][0],
         parallel=True, 
         status_update_callback=no_status_updates)
        
        unweighted_unifrac_dm_fp = join(self.test_out,'unweighted_unifrac_dm.txt')
        weighted_unifrac_dm_fp = join(self.test_out,'weighted_unifrac_dm.txt')
        unweighted_unifrac_pc_fp = join(self.test_out,'unweighted_unifrac_pc.txt')
        weighted_unifrac_pc_fp = join(self.test_out,'weighted_unifrac_pc.txt')
        weighted_unifrac_html_fp = join(self.test_out,
        'weighted_unifrac_emperor_pcoa_plot','index.html')

        # check for expected relations between values in the unweighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(unweighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        # check for expected relations between values in the weighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(weighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        
        # check that final output files have non-zero size
        self.assertTrue(getsize(unweighted_unifrac_pc_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_pc_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_html_fp) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)
        
    def test_run_alpha_rarefaction(self):
        """ run_alpha_rarefaction generates expected results """

        run_alpha_rarefaction(
         self.test_data['biom'][0], 
         self.test_data['map'][0],
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         tree_fp=self.test_data['tree'][0],
         num_steps=5, 
         parallel=False, 
         min_rare_depth=3,
         max_rare_depth=18,
         status_update_callback=no_status_updates)
         
        html_fp = join(self.test_out,'alpha_rarefaction_plots',
         'rarefaction_plots.html')
        pd_averages_fp = join(self.test_out,'alpha_rarefaction_plots',
         'average_tables','PD_whole_treeSampleType.txt')
        pd_collated_fp = join(self.test_out,'alpha_div_collated',
         'PD_whole_tree.txt')
        
        # Confirm that palm and gut alpha diversities are different,
        # and suggestive of statistical significance (we only have a 
        # few sequences, so we don't get significant results)
        ttest_res, alpha_avg = compare_alpha_diversities(open(pd_collated_fp), 
                                      open(self.test_data['map'][0]),
                                      'SampleType', 
                                      18,
                                      test_type='parametric')
        feces_palm_t = ttest_res[('feces','L_palm')][0]
        self.assertTrue(feces_palm_t < 0, 
         "t-statistic too high: %1.3f, but should be less than 0"\
          % feces_palm_t)
        
        # check that final output files have non-zero size
        self.assertTrue(getsize(html_fp) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)
        
         
    def test_run_alpha_rarefaction_stderr_and_stddev(self):
        """ run_alpha_rarefaction generates expected results """

        run_alpha_rarefaction(
         self.test_data['biom'][0], 
         self.test_data['map'][0],
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         tree_fp=self.test_data['tree'][0],
         num_steps=5, 
         parallel=False, 
         min_rare_depth=3,
         max_rare_depth=18,
         status_update_callback=no_status_updates,
         plot_stderr_and_stddev=True)
         
        html_fp_stderr = join(self.test_out,'alpha_rarefaction_plots_stderr',
         'rarefaction_plots.html')
        pd_averages_fp_stderr = join(self.test_out,'alpha_rarefaction_plots_stderr',
         'average_tables','PD_whole_treeSampleType.txt')
        html_fp_stddev = join(self.test_out,'alpha_rarefaction_plots_stddev',
         'rarefaction_plots.html')
        pd_averages_fp_stddev = join(self.test_out,'alpha_rarefaction_plots_stddev',
         'average_tables','PD_whole_treeSampleType.txt')
        pd_collated_fp = join(self.test_out,'alpha_div_collated',
         'PD_whole_tree.txt')
        
        # Confirm that palm and gut alpha diversities are different,
        # and suggestive of statistical significance (we only have a 
        # few sequences, so we don't get significant results)
        ttest_res, alpha_avg = compare_alpha_diversities(open(pd_collated_fp), 
                                      open(self.test_data['map'][0]),
                                      'SampleType', 
                                      18,
                                      test_type='parametric')
        feces_palm_t = ttest_res[('feces','L_palm')][0]
        self.assertTrue(feces_palm_t < 0, 
         "t-statistic too high: %1.3f, but should be less than 0"\
          % feces_palm_t)
        
        # check that final output files have non-zero size
        self.assertTrue(getsize(html_fp_stderr) > 0)
        self.assertTrue(getsize(html_fp_stddev) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)
        
    def test_run_alpha_rarefaction_parallel(self):
        """ run_alpha_rarefaction generates expected results when run in parallel
        """

        run_alpha_rarefaction(
         self.test_data['biom'][0], 
         self.test_data['map'][0],
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         tree_fp=self.test_data['tree'][0],
         num_steps=5, 
         parallel=True, 
         min_rare_depth=3,
         max_rare_depth=18,
         status_update_callback=no_status_updates)
         
        html_fp = join(self.test_out,'alpha_rarefaction_plots',
         'rarefaction_plots.html')
        pd_averages_fp = join(self.test_out,'alpha_rarefaction_plots',
         'average_tables','PD_whole_treeSampleType.txt')
        pd_collated_fp = join(self.test_out,'alpha_div_collated',
         'PD_whole_tree.txt')
        
        # Confirm that palm and gut alpha diversities are different,
        # and suggestive of statistical significance (we only have a 
        # few sequences, so we don't get significant results)
        ttest_res, alpha_avg = compare_alpha_diversities(open(pd_collated_fp), 
                                      open(self.test_data['map'][0]),
                                      'SampleType', 
                                      18,
                                      test_type='parametric')
        feces_palm_t = ttest_res[('feces','L_palm')][0]
        self.assertTrue(feces_palm_t < 0, 
         "t-statistic too high: %1.3f, but should be less than 0"\
          % feces_palm_t)
        
        # check that final output files have non-zero size
        self.assertTrue(getsize(html_fp) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)
         
    def test_run_jackknifed_beta_diversity(self):
        """ run_jackknifed_beta_diversity generates expected results """

        run_jackknifed_beta_diversity(
         self.test_data['biom'][0],
         self.test_data['tree'][0],
         20,
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         self.test_data['map'][0],
         parallel=False,
         status_update_callback=no_status_updates)
         
        weighted_unifrac_upgma_tree_fp = join(self.test_out,
         'weighted_unifrac',
         'upgma_cmp','jackknife_named_nodes.tre')
        unweighted_unifrac_upgma_tree_fp = join(
         self.test_out,'unweighted_unifrac','upgma_cmp',
         'jackknife_named_nodes.tre')
        weighted_unifrac_emperor_index_fp = join(
         self.test_out,'weighted_unifrac','emperor_pcoa_plots',
         'index.html')
        unweighted_unifrac_emperor_index_fp = join(
         self.test_out,'unweighted_unifrac','emperor_pcoa_plots',
         'index.html')
        
        input_file_basename = splitext(split(self.test_data['biom'][0])[1])[0]
        unweighted_unifrac_dm_fp = join(self.test_out,
         'unweighted_unifrac_%s.txt' % input_file_basename)
        weighted_unifrac_dm_fp = join(self.test_out,
         'weighted_unifrac_%s.txt' % input_file_basename)
         
       # check for expected relations between values in the unweighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(unweighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        # check for expected relations between values in the weighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(weighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
         
        # check that final output files have non-zero size
        self.assertTrue(getsize(weighted_unifrac_upgma_tree_fp) > 0)
        self.assertTrue(getsize(unweighted_unifrac_upgma_tree_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_emperor_index_fp) > 0)
        self.assertTrue(getsize(unweighted_unifrac_emperor_index_fp) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)
        
    def test_run_jackknifed_beta_diversity_parallel(self):
        """ run_jackknifed_beta_diversity generates expected results """

        run_jackknifed_beta_diversity(
         self.test_data['biom'][0],
         self.test_data['tree'][0],
         20,
         self.test_out, 
         call_commands_serially,
         self.params,
         self.qiime_config,
         self.test_data['map'][0],
         parallel=True,
         status_update_callback=no_status_updates)
         
        weighted_unifrac_upgma_tree_fp = join(self.test_out,
         'weighted_unifrac',
         'upgma_cmp','jackknife_named_nodes.tre')
        unweighted_unifrac_upgma_tree_fp = join(
         self.test_out,'unweighted_unifrac','upgma_cmp',
         'jackknife_named_nodes.tre')
        weighted_unifrac_emperor_index_fp = join(
         self.test_out,'weighted_unifrac','emperor_pcoa_plots',
         'index.html')
        unweighted_unifrac_emperor_index_fp = join(
         self.test_out,'unweighted_unifrac','emperor_pcoa_plots',
         'index.html')
        
        input_file_basename = splitext(split(self.test_data['biom'][0])[1])[0]
        unweighted_unifrac_dm_fp = join(self.test_out,
         'unweighted_unifrac_%s.txt' % input_file_basename)
        weighted_unifrac_dm_fp = join(self.test_out,
         'weighted_unifrac_%s.txt' % input_file_basename)
         
       # check for expected relations between values in the unweighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(unweighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
        # check for expected relations between values in the weighted unifrac
        # distance matrix
        dm = parse_distmat_to_dict(open(weighted_unifrac_dm_fp))
        self.assertTrue(dm['f1']['f2'] < dm['f1']['p1'],
         "Distance between pair of fecal samples is larger than distance"
         " between fecal and palm sample (unweighted unifrac).")
        self.assertEqual(dm['f1']['f1'],0)
         
        # check that final output files have non-zero size
        self.assertTrue(getsize(weighted_unifrac_upgma_tree_fp) > 0)
        self.assertTrue(getsize(unweighted_unifrac_upgma_tree_fp) > 0)
        self.assertTrue(getsize(weighted_unifrac_emperor_index_fp) > 0)
        self.assertTrue(getsize(unweighted_unifrac_emperor_index_fp) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)

    def test_run_summarize_taxa_through_plots(self):
        """ run_summarize_taxa_through_plots generates expected results
        """
        run_summarize_taxa_through_plots(
         self.test_data['biom'][0],
         self.test_data['map'][0],
         self.test_out,
         mapping_cat=None,
         sort=False,
         command_handler=call_commands_serially,
         params=self.params,
         qiime_config=self.qiime_config,
         status_update_callback=no_status_updates)
        
        # Check that summarized taxonomy files have non-zero size
        input_file_basename = splitext(split(self.test_data['biom'][0])[1])[0]
        for i in [2,3,4,5,6]:
            sum_taxa_file=join(self.test_out,input_file_basename+'_L%s.txt' \
                            % (str(i)))
            self.assertTrue(getsize(sum_taxa_file) > 0)
        
        # Check the html files are generated
        self.assertTrue(getsize(join(self.test_out,'taxa_summary_plots',
                            'area_charts.html')) > 0)
        
        self.assertTrue(getsize(join(self.test_out,'taxa_summary_plots',
                            'area_charts.html')) > 0)
        
        # Check that the log file is created and has size > 0
        log_fp = glob(join(self.test_out,'log*.txt'))[0]
        self.assertTrue(getsize(log_fp) > 0)

params_f1 = """
multiple_rarefactions:num-reps	1
multiple_rarefactions_even_depth:num-reps	5
""".split('\n')

if __name__ == "__main__":
    main()