File: test_pick_open_reference_otus.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 (1179 lines) | stat: -rwxr-xr-x 64,867 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
#!/usr/bin/env python
# File created on 02 Nov 2011
from __future__ import division

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

from glob import glob
from os import chdir, getcwd
from os.path import exists
from shutil import rmtree
from cogent import LoadTree, LoadSeqs
from cogent.util.unit_test import TestCase, main
from cogent.util.misc import remove_files
from qiime.util import (load_qiime_config,
                        count_seqs,
                        get_tmp_filename,
                        get_qiime_temp_dir)
from qiime.workflow.util import (call_commands_serially,
                                 no_status_updates,
                                 WorkflowError)
from qiime.parse import (parse_qiime_parameters,
                         fields_to_dict)
from qiime.test import (initiate_timeout,
                        disable_timeout,
                        get_test_data_fps)
from qiime.workflow.pick_open_reference_otus import (
                                pick_subsampled_open_reference_otus,
                                iterative_pick_subsampled_open_reference_otus,
                                final_repset_from_iteration_repsets)
from biom.parse import parse_biom_table

allowed_seconds_per_test = 120

class PickSubsampledReferenceOtusThroughOtuTableTests(TestCase):
    """ """
    
    def setUp(self):
        """
        """
        self.start_dir = getcwd()
        self.qiime_config = load_qiime_config()
        self.dirs_to_remove = []
        self.files_to_remove = []
        
        self.tmp_dir = get_qiime_temp_dir()
        self.test_data = get_test_data_fps()
        
        # override default reference data for reduced runtime and better
        # defined tests
        self.params = parse_qiime_parameters([
         "assign_taxonomy:id_to_taxonomy_fp	%s" % self.test_data['refseqs_tax'][0],
         "assign_taxonomy:reference_seqs_fp	%s" % self.test_data['refseqs'][0],
         "align_seqs:template_fp	%s" % self.test_data['refseqs_aligned'][0],
         "filter_alignment:lane_mask_fp	%s" % self.test_data['refseqs_aligned_lanemask'][0]])
        
        self.wf_out = get_tmp_filename(tmp_dir=self.tmp_dir,
         prefix='qiime_wf_out',suffix='',result_constructor=str)
        self.dirs_to_remove.append(self.wf_out)
        
        initiate_timeout(allowed_seconds_per_test)
    
    def tearDown(self):
        """ """
        # turn off the alarm
        disable_timeout()
        # change back to the start dir - some workflows change directory
        chdir(self.start_dir)
        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_pick_subsampled_open_reference_otus(self):
        """pick_subsampled_open_reference_otus functions as expected
        """
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=False,
                                  logger=None,
                                  status_update_callback=no_status_updates)
        otu_map_w_singletons_fp = '%s/final_otu_map.txt' % self.wf_out
        final_failure_fp = '%s/final_failures.txt' % self.wf_out
        final_repset_fp = '%s/rep_set.fna' % self.wf_out
        new_refseqs_fp = '%s/new_refseqs.fna' % self.wf_out
        prefilter_failures_fp = glob('%s/prefilter_otus/*_failures.txt' % self.wf_out)[0]
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out

        self.assertTrue(exists(otu_map_w_singletons_fp),"OTU map doesn't exist")
        self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
        self.assertTrue(exists(final_repset_fp),"Final representative set doesn't exist")
        self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist")
        self.assertTrue(exists(prefilter_failures_fp),"Prefilter failures file doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(otu_table_fp),"Final BIOM table doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),"PyNAST failures file doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 6
        self.assertEqual(len(otu_table.ObservationIds),6)
        
        # the correct sequences failed the prefilter
        prefilter_failure_ids = [s.strip() for s in open(prefilter_failures_fp,'U')]
        self.assertEqual(len(prefilter_failure_ids),24)
        self.assertTrue('t1_1' in prefilter_failure_ids)
        self.assertTrue('p1_2' in prefilter_failure_ids)
        self.assertTrue('not16S.1_130' in prefilter_failure_ids)
        self.assertTrue('not16S.1_151' in prefilter_failure_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        # 
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(otu_map_w_singletons_fp))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        self.assertTrue('wf.test.otu.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,6)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])

    def test_pick_subsampled_open_reference_otus_rdp_tax_assign(self):
        """pick_subsampled_open_reference_otus fns when assigning tax with rdp
        """
        self.params.update(
         parse_qiime_parameters(['assign_taxonomy:assignment_method rdp',
          'assign_taxonomy:reference_seqs_fp %s' %  self.test_data['refseqs'][0],
          'assign_taxonomy:id_to_taxonomy_fp %s' %  self.test_data['refseqs_tax'][0]]))
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=False,
                                  logger=None,
                                  status_update_callback=no_status_updates)
        otu_map_w_singletons_fp = '%s/final_otu_map.txt' % self.wf_out
        final_failure_fp = '%s/final_failures.txt' % self.wf_out
        final_repset_fp = '%s/rep_set.fna' % self.wf_out
        new_refseqs_fp = '%s/new_refseqs.fna' % self.wf_out
        prefilter_failures_fp = glob('%s/prefilter_otus/*_failures.txt' % self.wf_out)[0]
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out
        rdp_tax_fp = '%s/rdp_assigned_taxonomy/rep_set_tax_assignments.txt' % self.wf_out

        self.assertTrue(exists(otu_map_w_singletons_fp),"OTU map doesn't exist")
        self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
        self.assertTrue(exists(final_repset_fp),"Final representative set doesn't exist")
        self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist")
        self.assertTrue(exists(prefilter_failures_fp),"Prefilter failures file doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(otu_table_fp),"Final BIOM table doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),"PyNAST failures file doesn't exist")
        self.assertTrue(exists(rdp_tax_fp),"rdp taxonomy assignment result doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 6
        self.assertEqual(len(otu_table.ObservationIds),6)
        
        # the correct sequences failed the prefilter
        prefilter_failure_ids = [s.strip() for s in open(prefilter_failures_fp,'U')]
        self.assertEqual(len(prefilter_failure_ids),24)
        self.assertTrue('t1_1' in prefilter_failure_ids)
        self.assertTrue('p1_2' in prefilter_failure_ids)
        self.assertTrue('not16S.1_130' in prefilter_failure_ids)
        self.assertTrue('not16S.1_151' in prefilter_failure_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        # 
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(otu_map_w_singletons_fp))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        self.assertTrue('wf.test.otu.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,6)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])


    def test_pick_subsampled_open_reference_otus_usearch(self):
        """pick_subsampled_open_reference_otus functions as expected with usearch
        """
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=False,
                                  logger=None,
                                  denovo_otu_picking_method='usearch61',
                                  reference_otu_picking_method='usearch61_ref',
                                  status_update_callback=no_status_updates)
        otu_map_w_singletons_fp = '%s/final_otu_map.txt' % self.wf_out
        final_failure_fp = '%s/final_failures.txt' % self.wf_out
        final_repset_fp = '%s/rep_set.fna' % self.wf_out
        new_refseqs_fp = '%s/new_refseqs.fna' % self.wf_out
        prefilter_failures_fp = glob('%s/prefilter_otus/*_failures.txt' % self.wf_out)[0]
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out

        self.assertTrue(exists(otu_map_w_singletons_fp),"OTU map doesn't exist")
        self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
        self.assertTrue(exists(final_repset_fp),"Final representative set doesn't exist")
        self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist")
        self.assertTrue(exists(prefilter_failures_fp),"Prefilter failures file doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(otu_table_fp),"Final BIOM table doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),"PyNAST failures file doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 6
        self.assertEqual(len(otu_table.ObservationIds),6)
        
        # the correct sequences failed the prefilter
        prefilter_failure_ids = [s.strip() for s in open(prefilter_failures_fp,'U')]
        self.assertEqual(len(prefilter_failure_ids),24)
        self.assertTrue('t1_1' in prefilter_failure_ids)
        self.assertTrue('p1_2' in prefilter_failure_ids)
        self.assertTrue('not16S.1_130' in prefilter_failure_ids)
        self.assertTrue('not16S.1_151' in prefilter_failure_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        # 
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(otu_map_w_singletons_fp))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        self.assertTrue('wf.test.otu.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,6)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])

    def test_pick_subsampled_open_reference_otus_suppress_assign_tax(self):
        """pick_subsampled_open_reference_otus functions without assign tax step
        """
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=False,
                                  logger=None,
                                  status_update_callback=no_status_updates,
                                  run_assign_tax=False)

        otu_table_fp = '%s/otu_table_mc2_no_pynast_failures.biom' % self.wf_out
        otu_table_w_tax_fp = '%s/otu_table_mc2_w_tax.biom' % self.wf_out
        
        self.assertFalse(exists(otu_table_w_tax_fp),
                         "OTU table w tax exists (it shouldn't).")
        self.assertTrue(exists(otu_table_fp),"OTU table doesn't exist.")

    def test_pick_subsampled_open_reference_otus_suppress_align_and_tree(self):
        """pick_subsampled_open_reference_otus functions without align/tree step
        """
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=False,
                                  logger=None,
                                  status_update_callback=no_status_updates,
                                  run_align_and_tree=False)

        otu_table_fp = '%s/otu_table_mc2_w_tax.biom' % self.wf_out
        tree_fp = '%s/rep_set.tre' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out

        self.assertTrue(exists(otu_table_fp),"OTU table doesn't exist.")
        self.assertFalse(exists(tree_fp),
                         "Tree exists (it shouldn't).")
        self.assertFalse(exists(pynast_failures_fp),
                         "PyNAST failures file exists (it shouldn't).")


    def test_pick_subsampled_open_reference_otus_no_prefilter(self):
        """pick_subsampled_open_reference_otus functions as expected without prefilter
        """
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  prefilter_percent_id=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=False,
                                  logger=None,
                                  status_update_callback=no_status_updates)
                                  
        prefilter_output_directory = '%s/prefilter_otus/'
        self.assertFalse(exists(prefilter_output_directory))
        
        otu_map_w_singletons_fp = '%s/final_otu_map.txt' % self.wf_out
        final_failure_fp = '%s/final_failures.txt' % self.wf_out
        final_repset_fp = '%s/rep_set.fna' % self.wf_out
        new_refseqs_fp = '%s/new_refseqs.fna' % self.wf_out
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out

        self.assertTrue(exists(otu_map_w_singletons_fp),"OTU map doesn't exist")
        self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
        self.assertTrue(exists(final_repset_fp),"Final representative set doesn't exist")
        self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(otu_table_fp),"Final BIOM table doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),"PyNAST failures file doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 6 (note: this is the same as without the prefilter
        # because these reads are getting filtered from the final otu table because
        # they fail to align with PyNAST)
        self.assertEqual(len(otu_table.ObservationIds),6)
        
        # sequences that are ordinarily prefiltered are in the OTU map
        otu_map_seq_ids = []
        for l in open(otu_map_w_singletons_fp,'U'):
            otu_map_seq_ids.extend(l.strip().split()[1:])
        self.assertTrue('t1_1' in otu_map_seq_ids)
        self.assertTrue('p1_2' in otu_map_seq_ids)
        self.assertTrue('not16S.1_130' in otu_map_seq_ids)
        self.assertTrue('not16S.1_151' in otu_map_seq_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(otu_map_w_singletons_fp))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        self.assertTrue('wf.test.otu.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,6)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])


    def test_pick_subsampled_open_reference_otus_parallel(self):
        """pick_subsampled_open_reference_otus functions as expected in parallel
        """
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=True,
                                  suppress_step4=False,
                                  logger=None,
                                  status_update_callback=no_status_updates)
        otu_map_w_singletons_fp = '%s/final_otu_map.txt' % self.wf_out
        final_failure_fp = '%s/final_failures.txt' % self.wf_out
        final_repset_fp = '%s/rep_set.fna' % self.wf_out
        new_refseqs_fp = '%s/new_refseqs.fna' % self.wf_out
        prefilter_failures_fp = glob('%s/prefilter_otus/*_failures.txt' % self.wf_out)[0]
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out

        self.assertTrue(exists(otu_map_w_singletons_fp),"OTU map doesn't exist")
        self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
        self.assertTrue(exists(final_repset_fp),"Final representative set doesn't exist")
        self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist")
        self.assertTrue(exists(prefilter_failures_fp),"Prefilter failures file doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(otu_table_fp),"Final BIOM table doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),"PyNAST failures file doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 6
        self.assertEqual(len(otu_table.ObservationIds),6)
        
        # the correct sequences failed the prefilter
        prefilter_failure_ids = [s.strip() for s in open(prefilter_failures_fp,'U')]
        self.assertEqual(len(prefilter_failure_ids),24)
        self.assertTrue('t1_1' in prefilter_failure_ids)
        self.assertTrue('p1_2' in prefilter_failure_ids)
        self.assertTrue('not16S.1_130' in prefilter_failure_ids)
        self.assertTrue('not16S.1_151' in prefilter_failure_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        # 
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(otu_map_w_singletons_fp))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        self.assertTrue('wf.test.otu.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,6)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])


    def test_pick_subsampled_open_reference_otus_suppress_step4(self):
        """pick_subsampled_open_reference_otus functions as expected wo step 4
        """
        pick_subsampled_open_reference_otus(input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=self.params,
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=True,
                                  logger=None,
                                  status_update_callback=no_status_updates)
                                  
        step4_output_dir = '%s/step4_otus/' % self.wf_out
        self.assertFalse(exists(step4_output_dir),
                         "Step 4 output directory exists - it shouldn't.")
        
        otu_map_w_singletons_fp = '%s/final_otu_map.txt' % self.wf_out
        final_failure_fp = '%s/final_failures.txt' % self.wf_out
        final_repset_fp = '%s/rep_set.fna' % self.wf_out
        new_refseqs_fp = '%s/new_refseqs.fna' % self.wf_out
        prefilter_failures_fp = glob('%s/prefilter_otus/*_failures.txt' % self.wf_out)[0]
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out

        self.assertTrue(exists(otu_map_w_singletons_fp),"OTU map doesn't exist")
        self.assertTrue(exists(final_failure_fp),"Final failures file doesn't exist")
        self.assertTrue(exists(final_repset_fp),"Final representative set doesn't exist")
        self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist")
        self.assertTrue(exists(prefilter_failures_fp),"Prefilter failures file doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(otu_table_fp),"Final BIOM table doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),"PyNAST failures file doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of sequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is either 4, 5 or 6 (it can vary due to the random 
        # subsampling)
        num_obs_ids = len(otu_table.ObservationIds)
        self.assertTrue(4 <= num_obs_ids <= 6,
        "Obtained %d observations, but expected 4, 5 or 6." % num_obs_ids)
        
        # the correct sequences failed the prefilter
        prefilter_failure_ids = [s.strip() for s in open(prefilter_failures_fp,'U')]
        self.assertEqual(len(prefilter_failure_ids),24)
        self.assertTrue('t1_1' in prefilter_failure_ids)
        self.assertTrue('p1_2' in prefilter_failure_ids)
        self.assertTrue('not16S.1_130' in prefilter_failure_ids)
        self.assertTrue('not16S.1_151' in prefilter_failure_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        # 
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(otu_map_w_singletons_fp))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        self.assertTrue('wf.test.otu.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment (and we already checked that we're happy with that number
        # above when it was compared to the number of OTUs)
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])

    def test_pick_subsampled_open_reference_otus_invalid_input(self):
        """pick_subsampled_open_reference_otus raises error on refseqs in params file
        """
        self.assertRaises(WorkflowError,
         pick_subsampled_open_reference_otus,
                                  input_fp=self.test_data['seqs'][0], 
                                  refseqs_fp=self.test_data['refseqs'][0],
                                  output_dir=self.wf_out,
                                  percent_subsample=0.5,
                                  new_ref_set_id='wf.test.otu',
                                  command_handler=call_commands_serially,
                                  params=parse_qiime_parameters(
                                   ['pick_otus:refseqs_fp %s' % self.test_data['refseqs'][0]]),
                                  prefilter_refseqs_fp=None,
                                  qiime_config=self.qiime_config,
                                  step1_otu_map_fp=None,
                                  step1_failures_fasta_fp=None,
                                  parallel=False,
                                  suppress_step4=False,
                                  logger=None,
                                  status_update_callback=no_status_updates)

    def test_iterative_pick_subsampled_open_reference_otus_no_prefilter(self):
        """pick_subsampled_open_reference_otus functions as expected without prefilter
        """
        iterative_pick_subsampled_open_reference_otus(
          input_fps=[self.test_data['seqs'][0], self.test_data['extra_seqs'][0]],
          refseqs_fp=self.test_data['refseqs'][0],
          output_dir=self.wf_out,
          percent_subsample=0.5,
          new_ref_set_id='wf.test.otu',
          command_handler=call_commands_serially,
          params=self.params,
          qiime_config=self.qiime_config,
          prefilter_refseqs_fp=None,
          prefilter_percent_id=None,
          step1_otu_map_fp=None,
          step1_failures_fasta_fp=None,
          parallel=False,
          suppress_step4=False,
          logger=None,
          status_update_callback=no_status_updates)
        
        for i in (0,1):
            final_otu_map_fp = '%s/%d/final_otu_map.txt' % (self.wf_out,i)
            final_failure_fp = '%s/%d/final_failures.txt' % (self.wf_out,i)
            otu_table_fp = '%s/%d/otu_table_mc2.biom' % (self.wf_out,i)
            repset_fp = '%s/%d/rep_set.fna' % (self.wf_out,i)
            new_refseqs_fp = '%s/%d/new_refseqs.fna' % (self.wf_out,i)
            
            self.assertTrue(exists(final_otu_map_fp),"Final OTU map doesn't exist")
            self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
            self.assertTrue(exists(otu_table_fp),"OTU table doesn't exist.")
            self.assertTrue(exists(repset_fp),"Rep set doesn't exist.")
            self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist.")


        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out
        iter0_otu_map_w_singletons = '%s/0/final_otu_map.txt' % self.wf_out
        iter1_otu_map_w_singletons = '%s/1/final_otu_map.txt' % self.wf_out
        
        self.assertTrue(exists(otu_table_fp),"Final OTU table doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),
                        "PyNAST failurs file doesn't exist")
        self.assertTrue(exists(iter0_otu_map_w_singletons),
                        "Iteration 0 OTU map with singletons doesn't exist")
        self.assertTrue(exists(iter1_otu_map_w_singletons),
                        "Iteration 1 OTU map with singletons doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 7 (note: this is the same as without the prefilter
        # because these reads are getting filtered from the final otu table because
        # they fail to align with PyNAST)
        self.assertEqual(len(otu_table.ObservationIds),7)
        
        # sequences that are ordinarily prefiltered are in the OTU map
        otu_map_seq_ids = []
        for l in open(iter0_otu_map_w_singletons,'U'):
            otu_map_seq_ids.extend(l.strip().split()[1:])
        self.assertTrue('t1_1' in otu_map_seq_ids)
        self.assertTrue('p1_2' in otu_map_seq_ids)
        self.assertTrue('not16S.1_130' in otu_map_seq_ids)
        self.assertTrue('not16S.1_151' in otu_map_seq_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(iter0_otu_map_w_singletons))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        # OTU from first iteration is in final map
        self.assertTrue('wf.test.otu.0.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")
        # OTU from second iteration is in final map
        otu_map = fields_to_dict(open(iter1_otu_map_w_singletons))
        self.assertTrue('wf.test.otu.1.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")
         
        # OTUs from each iteration are in the final OTU table
        self.assertTrue('295053' in otu_table.ObservationIds)
        self.assertTrue('wf.test.otu.1.ReferenceOTU0' in otu_table.ObservationIds)

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,7)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])
        
    def test_iterative_pick_subsampled_open_reference_otus(self):
        """pick_subsampled_open_reference_otus functions as expected with prefilter
        """
        iterative_pick_subsampled_open_reference_otus(
          input_fps=[self.test_data['seqs'][0], self.test_data['extra_seqs'][0]],
          refseqs_fp=self.test_data['refseqs'][0],
          output_dir=self.wf_out,
          percent_subsample=0.5,
          new_ref_set_id='wf.test.otu',
          command_handler=call_commands_serially,
          params=self.params,
          qiime_config=self.qiime_config,
          prefilter_refseqs_fp=None,
          step1_otu_map_fp=None,
          step1_failures_fasta_fp=None,
          parallel=False,
          suppress_step4=False,
          logger=None,
          status_update_callback=no_status_updates)
        
        for i in (0,1):
            final_otu_map_fp = '%s/%d/final_otu_map.txt' % (self.wf_out,i)
            final_failure_fp = '%s/%d/final_failures.txt' % (self.wf_out,i)
            otu_table_fp = '%s/%d/otu_table_mc2.biom' % (self.wf_out,i)
            repset_fp = '%s/%d/rep_set.fna' % (self.wf_out,i)
            new_refseqs_fp = '%s/%d/new_refseqs.fna' % (self.wf_out,i)
            
            self.assertTrue(exists(final_otu_map_fp),"Final OTU map doesn't exist")
            self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
            self.assertTrue(exists(otu_table_fp),"OTU table doesn't exist.")
            self.assertTrue(exists(repset_fp),"Rep set doesn't exist.")
            self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist.")


        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out
        iter0_otu_map_w_singletons = '%s/0/final_otu_map.txt' % self.wf_out
        iter1_otu_map_w_singletons = '%s/1/final_otu_map.txt' % self.wf_out
        
        self.assertTrue(exists(otu_table_fp),"Final OTU table doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),
                        "PyNAST failurs file doesn't exist")
        self.assertTrue(exists(iter0_otu_map_w_singletons),
                        "Iteration 0 OTU map with singletons doesn't exist")
        self.assertTrue(exists(iter1_otu_map_w_singletons),
                        "Iteration 1 OTU map with singletons doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 7 (note: this is the same as without the prefilter
        # because these reads are getting filtered from the final otu table because
        # they fail to align with PyNAST)
        self.assertEqual(len(otu_table.ObservationIds),7)
        
        # non-16S sequences are prefiltered, so not in the OTU map
        otu_map_seq_ids = []
        for l in open(iter0_otu_map_w_singletons,'U'):
            otu_map_seq_ids.extend(l.strip().split()[1:])
        self.assertFalse('t1_1' in otu_map_seq_ids)
        self.assertFalse('p1_2' in otu_map_seq_ids)
        self.assertFalse('not16S.1_130' in otu_map_seq_ids)
        self.assertFalse('not16S.1_151' in otu_map_seq_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(iter0_otu_map_w_singletons))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        # OTU from first iteration is in final map
        self.assertTrue('wf.test.otu.0.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")
        # OTU from second iteration is in final map
        otu_map = fields_to_dict(open(iter1_otu_map_w_singletons))
        self.assertTrue('wf.test.otu.1.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")
         
        # OTUs from each iteration are in the final OTU table
        self.assertTrue('295053' in otu_table.ObservationIds)
        self.assertTrue('wf.test.otu.1.ReferenceOTU0' in otu_table.ObservationIds)

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,7)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])


    def test_iterative_pick_subsampled_open_reference_otus_parallel(self):
        """pick_subsampled_open_reference_otus functions as expected in parallel
        """
        iterative_pick_subsampled_open_reference_otus(
          input_fps=[self.test_data['seqs'][0], self.test_data['extra_seqs'][0]],
          refseqs_fp=self.test_data['refseqs'][0],
          output_dir=self.wf_out,
          percent_subsample=0.5,
          new_ref_set_id='wf.test.otu',
          command_handler=call_commands_serially,
          params=self.params,
          qiime_config=self.qiime_config,
          prefilter_refseqs_fp=None,
          step1_otu_map_fp=None,
          step1_failures_fasta_fp=None,
          parallel=True,
          suppress_step4=False,
          logger=None,
          status_update_callback=no_status_updates)
        
        for i in (0,1):
            final_otu_map_fp = '%s/%d/final_otu_map.txt' % (self.wf_out,i)
            final_failure_fp = '%s/%d/final_failures.txt' % (self.wf_out,i)
            otu_table_fp = '%s/%d/otu_table_mc2.biom' % (self.wf_out,i)
            repset_fp = '%s/%d/rep_set.fna' % (self.wf_out,i)
            new_refseqs_fp = '%s/%d/new_refseqs.fna' % (self.wf_out,i)
            
            self.assertTrue(exists(final_otu_map_fp),"Final OTU map doesn't exist")
            self.assertFalse(exists(final_failure_fp),\
                         "Final failures file shouldn't exist, but it does")
            self.assertTrue(exists(otu_table_fp),"OTU table doesn't exist.")
            self.assertTrue(exists(repset_fp),"Rep set doesn't exist.")
            self.assertTrue(exists(new_refseqs_fp),"New refseqs file doesn't exist.")


        otu_table_fp = '%s/otu_table_mc2_w_tax_no_pynast_failures.biom' % self.wf_out
        tree_fp = '%s/rep_set.tre' % self.wf_out
        aln_fp = '%s/pynast_aligned_seqs/rep_set_aligned.fasta' % self.wf_out
        pynast_failures_fp = '%s/pynast_aligned_seqs/rep_set_failures.fasta' % self.wf_out
        iter0_otu_map_w_singletons = '%s/0/final_otu_map.txt' % self.wf_out
        iter1_otu_map_w_singletons = '%s/1/final_otu_map.txt' % self.wf_out
        
        self.assertTrue(exists(otu_table_fp),"Final OTU table doesn't exist")
        self.assertTrue(exists(tree_fp),"Final tree doesn't exist")
        self.assertTrue(exists(aln_fp),"Final alignment doesn't exist")
        self.assertTrue(exists(pynast_failures_fp),
                        "PyNAST failurs file doesn't exist")
        self.assertTrue(exists(iter0_otu_map_w_singletons),
                        "Iteration 0 OTU map with singletons doesn't exist")
        self.assertTrue(exists(iter1_otu_map_w_singletons),
                        "Iteration 1 OTU map with singletons doesn't exist")
        
        # all OTUs in final OTU table occur more than once
        otu_table = parse_biom_table(open(otu_table_fp,'U'))
        for row in otu_table.iterObservationData():
            self.assertTrue(sum(row) >= 2,"Singleton OTU detected in OTU table.")
        # number of OTUs in final OTU table equals the number of seequences in
        # the alignment...
        self.assertEqual(len(otu_table.ObservationIds),count_seqs(aln_fp)[0])
        # ... and that number is 7 (note: this is the same as without the prefilter
        # because these reads are getting filtered from the final otu table because
        # they fail to align with PyNAST)
        self.assertEqual(len(otu_table.ObservationIds),7)
        
        # non-16S sequences are prefiltered, so not in the OTU map
        otu_map_seq_ids = []
        for l in open(iter0_otu_map_w_singletons,'U'):
            otu_map_seq_ids.extend(l.strip().split()[1:])
        self.assertFalse('t1_1' in otu_map_seq_ids)
        self.assertFalse('p1_2' in otu_map_seq_ids)
        self.assertFalse('not16S.1_130' in otu_map_seq_ids)
        self.assertFalse('not16S.1_151' in otu_map_seq_ids)
        
        # confirm that the new reference sequences is the same length as the
        # input reference sequences plus the number of new non-singleton otus
        self.assertEqual(count_seqs(new_refseqs_fp)[0],
                         count_seqs(self.test_data['refseqs'][0])[0] +
                         len([o for o in otu_table.ObservationIds 
                              if o.startswith('wf.test.otu')]) +
                         count_seqs(pynast_failures_fp)[0])
        
        # spot check a few of the otus to confirm that we're getting reference and new
        # otus in the final otu map. This is done on the OTU map singletons get filtered
        # before building the otu table
        otu_map = fields_to_dict(open(iter0_otu_map_w_singletons))
        self.assertTrue('295053' in otu_map,\
         "Reference OTU (295053) is not in the final OTU map.")
        self.assertTrue('42684' in otu_map,\
         "Failure OTU (42684) is not in the final OTU map.")
        # OTU from first iteration is in final map
        self.assertTrue('wf.test.otu.0.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")
        # OTU from second iteration is in final map
        otu_map = fields_to_dict(open(iter1_otu_map_w_singletons))
        self.assertTrue('wf.test.otu.1.ReferenceOTU0' in otu_map,\
         "Failure OTU (wf.test.otu.ReferenceOTU0) is not in the final OTU map.")
         
        # OTUs from each iteration are in the final OTU table
        self.assertTrue('295053' in otu_table.ObservationIds)
        self.assertTrue('wf.test.otu.1.ReferenceOTU0' in otu_table.ObservationIds)

        # confirm that number of tips in the tree is the same as the number of sequences
        # in the alignment
        num_tree_tips = len(LoadTree(tree_fp).tips())
        num_align_seqs = LoadSeqs(aln_fp).getNumSeqs()
        self.assertEqual(num_tree_tips,num_align_seqs)
        self.assertEqual(num_tree_tips,7)
        
        # OTU table without singletons or pynast failures has same number of 
        # otus as there are aligned sequences
        self.assertEqual(len(otu_table.ObservationIds),num_align_seqs)
        
        # Reference OTUs have correct taxonomy assignment (can't confirm the )
        obs_idx = otu_table.getObservationIndex('295053')
        self.assertEqual(otu_table.ObservationMetadata[obs_idx]['taxonomy'],
         ["k__Bacteria", "p__Proteobacteria", "c__Gammaproteobacteria", 
          "o__Enterobacteriales", "f__Enterobacteriaceae", "g__", "s__"])
        # All observations have 'taxonomy' metadata, and are at least assigned
        # to 'bacteria'
        for o in otu_table.iterObservations():
            self.assertTrue(o[2]['taxonomy'][0] in ['k__Bacteria','Unassigned'])

    def test_final_repset_from_iteration_repsets(self):
        """ final_repset_from_iteration_repsets functions as expected """
        repset1 = """>o1
ACCGT
>o2
AGG
>o3
ACCGTT""".split('\n')

        repset2 = """>o4
TACCGT
>o5
TAGG
>o6
TACCGTT""".split('\n')

        repset3 = """>o4
CAT
>o7
AAAA
>o1
A""".split('\n')
        
        exp = [("o1","ACCGT"), ("o2","AGG"), ("o3","ACCGTT"),
                ("o4","TACCGT"), ("o5","TAGG"), ("o6","TACCGTT")]
        actual = list(final_repset_from_iteration_repsets([repset1,repset2]))
        self.assertEqual(actual,exp)

        exp = [("o1","ACCGT"), ("o2","AGG"), ("o3","ACCGTT"),
                ("o4","TACCGT"), ("o5","TAGG"), ("o6","TACCGTT"),('o7','AAAA')]
        actual = list(final_repset_from_iteration_repsets([repset1,repset2,repset3]))
        self.assertEqual(actual,exp)

if __name__ == "__main__":
    main()