This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 269
/
pick_otus.py
2140 lines (1784 loc) · 80.5 KB
/
pick_otus.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["Rob Knight", "Greg Caporaso", "Kyle Bittinger", "Jens Reeder",
"William Walters", "Jose Carlos Clemente Litran",
"Adam Robbins-Pianka", "Jose Antonio Navas Molina"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Greg Caporaso"
__email__ = "gregcaporaso@gmail.com"
"""Contains code for OTU picking, using several techniques.
This module has the responsibility for taking a set of sequences and
grouping those sequences by similarity.
"""
from copy import copy
from itertools import ifilter
from os.path import splitext, split, abspath, join, dirname
from os import makedirs, close, rename
from itertools import imap
from tempfile import mkstemp
from bfillings.mothur import parse_otu_list as mothur_parse
from skbio.util import remove_files, flatten
from skbio.tree import CompressedTrie, fasta_to_pairlist
from skbio.parse.sequences import parse_fasta
from skbio.alignment import SequenceCollection
from skbio.sequence import DNA
from qiime.util import FunctionWithParams, get_qiime_temp_dir
from qiime.sort import sort_fasta_by_abundance
from qiime.parse import fields_to_dict
from bfillings.blast import blast_seqs, Blastall, BlastResult
from bfillings.formatdb import build_blast_db_from_fasta_path
from bfillings.mothur import Mothur
from bfillings.cd_hit import cdhit_clusters_from_seqs
from bfillings.uclust import get_clusters_from_fasta_filepath
from bfillings.sortmerna_v2 import (build_database_sortmerna,
sortmerna_ref_cluster)
from bfillings.usearch import (usearch_qf,
usearch61_denovo_cluster,
usearch61_ref_cluster)
from bfillings.sumaclust_v1 import sumaclust_denovo_cluster
from bfillings.swarm_v127 import swarm_denovo_cluster
class OtuPicker(FunctionWithParams):
"""An OtuPicker dereplicates a set of sequences at a given similarity.
This is an abstract class: subclasses should implement the __call__
method.
"""
Name = 'OtuPicker'
def __init__(self, params):
"""Return new OtuPicker object with specified params.
Note: expect params to contain both generic and per-method (e.g. for
cdhit) params, so leaving it as a dict rather than setting
attributes. Some standard entries in params are:
Algorithm: algorithm used (e.g. nearest-neighbor, furthest-neighbor)
Similarity: similarity threshold, e.g. 0.97
Application: 3rd-party application used, if any, e.g. cdhit
"""
self.Params = params
def __call__(self, seq_path, result_path=None, log_path=None):
"""Returns dict mapping {otu_id:[seq_ids]} for each otu.
Parameters:
seq_path: path to file of sequences
result_path: path to file of results. If specified, should
dump the result to the desired path instead of returning it.
log_path: path to log, which should include dump of params.
"""
raise NotImplementedError("OtuPicker is an abstract class")
def _prefilter_exact_prefixes(self, seqs, prefix_length=100):
"""
"""
unique_prefixes = {}
for seq_id, seq in seqs:
seq_len = len(seq)
seq_id = seq_id.split()[0]
current_prefix = seq[:prefix_length]
try:
prefix_data = unique_prefixes[current_prefix]
if seq_len > prefix_data[2]:
# if this is the longest seq with this prefix so far,
# update the list of seq_ids, the best seq_len, and the
# best hit seq_id
prefix_data[0].append(seq_id)
prefix_data[1] = seq_id
prefix_data[2] = seq_len
prefix_data[3] = seq
else:
# if longer have been seen, only update the list of seq_ids
prefix_data[0].append(seq_id)
except KeyError:
# list of seq_ids mapped to this prefix, best hit seq_id, best
# hit seq_len
unique_prefixes[current_prefix] = [[seq_id],
seq_id,
seq_len,
seq]
# construct the result objects
filtered_seqs = []
seq_id_map = {}
for data in unique_prefixes.values():
filtered_seqs.append((data[1], data[3]))
seq_id_map[data[1]] = data[0]
return filtered_seqs, seq_id_map
def _prefilter_exact_matches(self, seqs):
"""
"""
unique_sequences = {}
seq_id_map = {}
filtered_seqs = []
for seq_id, seq in seqs:
seq_id = seq_id.split()[0]
try:
temp_seq_id = unique_sequences[seq]
except KeyError:
# unseen sequence so create a new temp_seq_id,
# a new unique_sequence entry, and new seq_id_map
# entry, and add the sequence to the list of
# filtered seqs -- this will retain the order
# of the input sequences too
temp_seq_id = 'QiimeExactMatch.%s' % seq_id
unique_sequences[seq] = temp_seq_id
seq_id_map[temp_seq_id] = []
filtered_seqs.append((temp_seq_id, seq))
seq_id_map[temp_seq_id].append(seq_id)
return filtered_seqs, seq_id_map
def _prefilter_with_trie(self, seq_path):
trunc_id = lambda a_b: (a_b[0].split()[0], a_b[1])
# get the prefix map
with open(seq_path, 'U') as seq_lines:
t = CompressedTrie(fasta_to_pairlist(imap(trunc_id,
parse_fasta(seq_lines))))
mapping = t.prefix_map
for key in mapping.keys():
mapping[key].append(key)
# collect the representative seqs
filtered_seqs = []
for (label, seq) in parse_fasta(open(seq_path)):
label = label.split()[0]
if label in mapping:
filtered_seqs.append((label, seq))
return filtered_seqs, mapping
def _map_filtered_clusters_to_full_clusters(self, clusters, filter_map):
"""
Input: clusters, a list of cluster lists
filter_map, the seq_id in each clusters
is the key to the filter_map
containing all seq_ids with
duplicate FASTA sequences
Output: an extended list of cluster lists
"""
results = []
for cluster in clusters:
full_cluster = []
for seq_id in cluster:
full_cluster += filter_map[seq_id]
results.append(full_cluster)
return results
class SortmernaV2OtuPicker(OtuPicker):
""" SortMeRNA-based version 2 OTU picker: clusters queries by their 'best'
alignment to a reference seed.
The 'best' alignment for a query is the one with:
1. the lowest E-value score (at most 1)
2. percent sequence identity greater than or equal to the OTU
similarity threshold (default in Params['similarity'] = 0.97)
3. percent query coverage greater than or equal to the OTU
coverage threshold (default in Params['coverage'] = 0.97)
"""
def __init__(self, params):
""" Return a new SortmernaV2OtuPicker object with specified params.
"""
OtuPicker.__init__(self, params)
def __call__(self, seq_path, result_path=None, log_path=None,
sortmerna_db=None, refseqs_fp=None, failure_path=None):
""" Purpose : Call to construct the reference database (if not provided)
and to launch sortmerna.
Parameters: seq_path, path to reads file;
result_path, path to OTU mapping file;
log_path, path to QIIME log file;
sortmerna_db, path to sortmerna indexed database;
refseqs_fp, path to reference sequences;
failure_path, path to text file of reads failing
to align with similarity & coverage thresholds;
Return : None (output is always written to file)
"""
self.log_lines = []
prefilter_identical_sequences =\
self.Params['prefilter_identical_sequences']
# Indexed database not provided, build it
if not sortmerna_db:
# write index to output directory
self.sortmerna_db, self.files_to_remove = \
build_database_sortmerna(abspath(refseqs_fp),
max_pos=self.Params['max_pos'],
output_dir=dirname(abspath(result_path)))
self.log_lines.append('Reference seqs fp (to build '
'sortmerna database): %s' %
abspath(refseqs_fp))
# Indexed database provided
else:
self.sortmerna_db = sortmerna_db
self.files_to_remove = []
self.log_lines.append('SortMeRNA database: %s' % self.sortmerna_db)
original_fasta_path = seq_path
# Collapse identical sequences to a new file
if prefilter_identical_sequences:
exact_match_id_map, seq_path =\
self._apply_identical_sequences_prefilter(seq_path)
# Call sortmerna for reference clustering
cluster_map, failures, smr_files_to_remove =\
sortmerna_ref_cluster(seq_path=seq_path,
sortmerna_db=self.sortmerna_db,
refseqs_fp=refseqs_fp,
result_path=result_path,
tabular=self.Params['blast'],
max_e_value=self.Params['max_e_value'],
similarity=self.Params['similarity'],
coverage=self.Params['coverage'],
threads=self.Params['threads'],
best=self.Params['best'],
HALT_EXEC=False)
# Remove temporary files
self.files_to_remove.extend(smr_files_to_remove)
remove_files(self.files_to_remove, error_on_missing=False)
# Expand identical sequences to create full OTU map
if prefilter_identical_sequences:
cluster_names = cluster_map.keys()
clusters = [cluster_map[c] for c in cluster_names]
clusters =\
self._map_filtered_clusters_to_full_clusters(
clusters, exact_match_id_map)
cluster_map = dict(zip(cluster_names, clusters))
# Expand failures
temp_failures = []
for fa in failures:
temp_failures.extend(exact_match_id_map[fa])
failures = temp_failures
self.log_lines.append('Num OTUs: %d' % len(cluster_map))
self.log_lines.append('Num failures: %d' % len(failures))
# Write failures to file
if failure_path is not None:
failure_file = open(failure_path, 'w')
failure_file.write('\n'.join(failures))
failure_file.write('\n')
failure_file.close()
# Write OTU map
if result_path:
# If the user provided a result_path, write the
# results to file with one tab-separated line per
# cluster (this will over-write the default SortMeRNA
# OTU map with the extended OTU map)
of = open(result_path, 'w')
for cluster_id, cluster in cluster_map.items():
of.write('%s\t%s\n' % (cluster_id, '\t'.join(cluster)))
of.close()
result = None
self.log_lines.append('Result path: %s\n' % result_path)
else:
# if the user did not provide a result_path, store
# the clusters in a dict of {otu_id:[seq_ids]}, where
# otu_id is arbitrary
result = cluster_map
self.log_lines.append('Result path: None, returned as dict.')
# Log the run
if log_path:
log_file = open(log_path, 'w')
self.log_lines = [str(self)] + self.log_lines
log_file.write('\n'.join(self.log_lines))
log_file.write('\n')
return result
def _apply_identical_sequences_prefilter(self, seq_path):
"""
Input : a filepath to input FASTA reads
Method: prepares and writes de-replicated reads
to a temporary FASTA file, calls
parent method to do the actual
de-replication
Return: exact_match_id_map, a dictionary storing
de-replicated amplicon ID as key and
all original FASTA IDs with identical
sequences as values;
unique_seqs_fp, filepath to FASTA file
holding only de-replicated sequences
"""
# Creating mapping for de-replicated reads
with open(seq_path, 'U') as s_path:
seqs_to_cluster, exact_match_id_map =\
self._prefilter_exact_matches(parse_fasta(s_path))
# Create temporary file for storing the de-replicated reads
fd, unique_seqs_fp = mkstemp(
prefix='SortMeRNAExactMatchFilter', suffix='.fasta')
close(fd)
self.files_to_remove.append(unique_seqs_fp)
# Write de-replicated reads to file
unique_seqs_f = open(unique_seqs_fp, 'w')
for seq_id, seq in seqs_to_cluster:
unique_seqs_f.write('>%s count=%d;\n%s\n' %
(seq_id,
len(exact_match_id_map[seq_id]),
seq))
unique_seqs_f.close()
# Clean up the seqs_to_cluster as we don't need
# it again
del(seqs_to_cluster)
return exact_match_id_map, unique_seqs_fp
class BlastOtuPicker(OtuPicker):
"""Blast-based OTU picker: clusters sequence by their 'best' blast hit.
The 'best blast hit' for a sequence is defined as the database
sequence which achieves the longest alignment with percent sequence
identity greater than or equal to the OTU similarity threshold
(default in Params['Similarity'] = 0.97). Database hits must have an
e-value threshold less than or equal to the max_e_value threshold
(default in Params['max_e_value'] as 1e-10).
"""
def __init__(self, params):
"""Return new BlastOtuPicker object with specified params.
"""
_params = {'max_e_value': 1e-10,
'seqs_per_blast_run': 1000,
'Similarity': 0.97,
'min_aligned_percent': 0.50,
'blast_program': 'blastn',
'is_protein': False}
_params.update(params)
OtuPicker.__init__(self, _params)
def __call__(self, seq_path, result_path=None, log_path=None,
blast_db=None, refseqs_fp=None):
self.log_lines = []
if not blast_db:
self.blast_db, self.db_files_to_remove = \
build_blast_db_from_fasta_path(abspath(refseqs_fp),
is_protein=self.Params[
'is_protein'],
output_dir=get_qiime_temp_dir())
self.log_lines.append('Reference seqs fp (to build blast db): %s' %
abspath(refseqs_fp))
else:
self.blast_db = blast_db
self.db_files_to_remove = []
self.log_lines.append('Blast database: %s' % self.blast_db)
clusters, failures = self._cluster_seqs(parse_fasta(open(seq_path)))
self.log_lines.append('Num OTUs: %d' % len(clusters))
if result_path:
# if the user provided a result_path, write the
# results to file with one tab-separated line per
# cluster
of = open(result_path, 'w')
for cluster_id, cluster in clusters.items():
of.write('%s\t%s\n' % (cluster_id, '\t'.join(cluster)))
of.close()
result = None
self.log_lines.append('Result path: %s\n' % result_path)
else:
# if the user did not provide a result_path, store
# the clusters in a dict of {otu_id:[seq_ids]}, where
# otu_id is arbitrary
result = clusters
self.log_lines.append('Result path: None, returned as dict.')
if log_path:
# if the user provided a log file path, log the run
log_file = open(log_path, 'w')
self.log_lines = [str(self)] + self.log_lines
log_file.write('\n'.join(self.log_lines))
failures.sort()
log_file.write('Num failures: %d\n' % len(failures))
log_file.write('Failures: %s\n' % '\t'.join(failures))
remove_files(self.db_files_to_remove, error_on_missing=False)
# return the result (note this is None if the data was
# written to file)
return result
def _cluster_seqs(self, seqs):
"""
"""
# blast seqs seq_per_blast_run at a time
# Build object to keep track of the current set of sequences to be
# blasted, and the results (i.e., seq_id -> (taxonomy,quaility score)
# mapping)
seqs_per_blast_run = self.Params['seqs_per_blast_run']
current_seqs = []
result = {}
failures = []
# Iterate over the (seq_id, seq) pairs
for seq_id, seq in seqs:
# append the current seq_id,seq to list of seqs to be blasted
current_seqs.append((seq_id, seq))
# When there are self.SeqsPerBlastRun in the list, blast them
if len(current_seqs) == seqs_per_blast_run:
# update the result object
current_clusters, current_failures =\
self._blast_seqs(current_seqs)
result = self._update_cluster_map(result, current_clusters)
failures += current_failures
# reset the list of seqs to be blasted
current_seqs = []
# Cluster the remaining sequences
current_clusters, current_failures = self._blast_seqs(current_seqs)
result = self._update_cluster_map(result, current_clusters)
failures += current_failures
return result, failures
def _update_cluster_map(self, cluster_map, new_clusters):
for cluster_id, seq_ids in new_clusters.items():
try:
cluster_map[cluster_id] += seq_ids
except KeyError:
cluster_map[cluster_id] = seq_ids
return cluster_map
def _blast_seqs(self, seqs):
"""
"""
result = {}
failures = []
if not seqs:
return result, failures
# Get the blast hits with e-values less than self.Params['max_e_value']
# and percent identity greater than self.Params['Similarity']
blast_hits = get_blast_hits(seqs, self.blast_db,
max_e_value=self.Params['max_e_value'],
min_pct_identity=self.Params['Similarity'],
min_aligned_percent=self.Params[
'min_aligned_percent'],
blast_program=self.Params['blast_program'])
# Choose the longest alignment out of the acceptable blast hits --
# the result will therefore be the blast hit with at least
# self.Params['Similarity'] percent identity to the input sequence
seq_id_to_best_blast_hit = \
self._choose_longest_blast_hit(blast_hits)
for seq_id, blast_hit in seq_id_to_best_blast_hit.items():
if blast_hit is None:
failures.append(seq_id)
else:
cluster_id = blast_hit['SUBJECT ID']
try:
result[cluster_id].append(seq_id)
except KeyError:
result[cluster_id] = [seq_id]
return result, failures
def _choose_longest_blast_hit(self, blast_hits):
""" choose the longest blast match
This function assumes that the blast_hits below
self.Params['Similarity'] have already been filtered out,
and therefore the longest alignment is the best blast pick.
"""
result = {}
# iterate over the queries and their acceptable blast hits
for query, blast_hits in blast_hits.items():
choice = None
len_longest = 0
# iterate over the acceptable blast hits
for blast_hit in blast_hits:
# if the alignment is the longest we've seen so far (or
# the first), hold on to it as a possible best hit
len_current = blast_hit['ALIGNMENT LENGTH']
if len_current > len_longest:
choice = blast_hit
len_longest = len_current
query = query.split()[0] # get rid of spaces
result[query] = choice
return result
class BlastxOtuPicker(BlastOtuPicker):
"""Blastx-based OTU picker: clusters sequence by their 'best' blast hit.
The 'best blast hit' for a sequence is defined as the database
sequence which achieves the longest alignment with percent sequence
identity greater than or equal to the OTU similarity threshold
(default in Params['Similarity'] = 0.97). Database hits must have an
e-value threshold less than or equal to the max_e_value threshold
(default in Params['max_e_value'] as 1e-10).
"""
def __init__(self, params):
"""Return new BlastOtuPicker object with specified params.
"""
_params = {'max_e_value': 1e-3,
'seqs_per_blast_run': 1000,
'Similarity': 0.75,
'min_aligned_percent': 0.50,
'blast_program': 'blastx',
'is_protein': True}
_params.update(params)
OtuPicker.__init__(self, _params)
# START MOVE TO BLAST APP CONTROLLER
# The following two functions should be move to the blast application
# controller. When that's done, qiime.assign_taxonomy needs to be updated
# to use these functions rather that the member functions which these
# are replicas of. Note that when moving to the blast app controller,
# tests should be extractable from test_assign_taxonomy.py.
# THIS FUNCTION SHOULD DO THE SeqsPerBlastRun splitting, would be _much_
# cleaner that way.
def get_blast_hits(seqs,
blast_db,
max_e_value=1e-10,
min_pct_identity=0.75,
min_aligned_percent=0.50,
blast_program='blastn'):
""" blast each seq in seqs against blast_db and retain good hits
"""
max_evalue = max_e_value
min_percent_identity = min_pct_identity
seq_ids = [s[0] for s in seqs]
result = {}
blast_result = blast_seqs(
seqs, Blastall, blast_db=blast_db,
params={'-p': blast_program, '-n': 'F'},
add_seq_names=False)
if blast_result['StdOut']:
lines = [x for x in blast_result['StdOut']]
blast_result = BlastResult(lines)
else:
return {}.fromkeys(seq_ids, [])
for seq_id, seq in seqs:
blast_result_id = seq_id.split()[0]
max_alignment_length = len(seq)
if blast_program == 'blastx':
# if this is a translated blast search, the max alignment
# length is the number of 3mers in seq
max_alignment_length /= 3
min_alignment_length = max_alignment_length * min_aligned_percent
result[seq_id] = []
if blast_result_id in blast_result:
for e in blast_result[blast_result_id][0]:
if (float(e['E-VALUE']) <= max_evalue and
float(e['% IDENTITY']) / 100. >= min_percent_identity and
int(e['ALIGNMENT LENGTH']) >= min_alignment_length):
result[seq_id].append(e)
return result
# END MOVE TO BLAST APP CONTROLLER
class SumaClustOtuPicker(OtuPicker):
""" SumaClust is a de novo OTU picker, following the same clustering
algorithm as Uclust. It is open source and supports multithreading,
both SIMD and OpenMP.
Clusters are created by their similarity threshold (default 0.97).
If a query does not match any seed with this similarity threshold,
it is used to create a new seed.
Exact clustering (with parameter -e) assigns queries to the
best-matching seed, rather than to the first seed with similarity
threshold.
"""
def __init__(self, params):
""" Return a new SumaClustOtuPicker object with specified params.
The defaults are set in the SumaClust API (see bfillings)
"""
OtuPicker.__init__(self, params)
def _apply_identical_sequences_prefilter(self, seq_path):
"""
Input : a filepath to input FASTA reads
Method: prepares and writes de-replicated reads
to a temporary FASTA file, calls
parent method to do the actual
de-replication
Return: exact_match_id_map, a dictionary storing
de-replicated amplicon ID as key and
all original FASTA IDs with identical
sequences as values;
unique_seqs_fp, filepath to FASTA file
holding only de-replicated sequences
"""
# creating mapping for de-replicated reads
seqs_to_cluster, exact_match_id_map =\
self._prefilter_exact_matches(parse_fasta(open(seq_path, 'U')))
# create temporary file for storing the de-replicated reads
fd, unique_seqs_fp = mkstemp(
prefix='SumaClustExactMatchFilter', suffix='.fasta')
close(fd)
self.files_to_remove.append(unique_seqs_fp)
# write de-replicated reads to file
unique_seqs_f = open(unique_seqs_fp, 'w')
for seq_id, seq in seqs_to_cluster:
unique_seqs_f.write('>%s count=%d;\n%s\n'
% (seq_id,
len(exact_match_id_map[seq_id]),
seq))
unique_seqs_f.close()
# clean up the seqs_to_cluster list as it can be big and we
# don't need it again
del(seqs_to_cluster)
return exact_match_id_map, unique_seqs_fp
def __call__(self, seq_path=None, result_path=None, log_path=None):
self.log_lines = []
self.files_to_remove = []
prefilter_identical_sequences =\
self.Params['prefilter_identical_sequences']
original_fasta_path = seq_path
# Collapse idetical sequences to a new file
if prefilter_identical_sequences:
exact_match_id_map, seq_path =\
self._apply_identical_sequences_prefilter(seq_path)
# Run SumaClust, return a dict of output files
clusters = sumaclust_denovo_cluster(
seq_path=abspath(seq_path),
result_path=abspath(result_path),
shortest_len=self.Params['l'],
similarity=self.Params['similarity'],
threads=self.Params['threads'],
exact=self.Params['exact'],
HALT_EXEC=False)
# Clean up any temp files that were created
remove_files(self.files_to_remove)
# Create file for expanded OTU map
if prefilter_identical_sequences:
clusters = self._map_filtered_clusters_to_full_clusters(
clusters, exact_match_id_map)
self.log_lines.append('Num OTUs: %d' % len(clusters))
# Add prefix ID to de novo OTUs
otu_id_prefix = self.Params['denovo_otu_id_prefix']
if otu_id_prefix is None:
clusters = dict(enumerate(clusters))
else:
clusters = dict(('%s%d' % (otu_id_prefix, i), c)
for i, c in enumerate(clusters))
if result_path:
# If the user provided a result_path, write the
# results to file with one tab-separated line per
# cluster (this will over-write the default SumaClust
# OTU map with the extended OTU map)
of = open(result_path, 'w')
for cluster_id, cluster in clusters.items():
of.write('%s\t%s\n' % (cluster_id, '\t'.join(cluster)))
of.close()
result = None
self.log_lines.append('Result path: %s\n' % result_path)
else:
# if the user did not provide a result_path, store
# the clusters in a dict of {otu_id:[seq_ids]}, where
# otu_id is arbitrary
result = clusters
self.log_lines.append('Result path: None, returned as dict.')
# Log the run
if log_path:
log_file = open(log_path, 'w')
self.log_lines.insert(0, str(self))
log_file.write('\n'.join(self.log_lines))
log_file.close()
return result
class SwarmOtuPicker(OtuPicker):
""" Swarm is a de novo OTU picker, an exact clustering method based
on a single-linkage algorithm. It is open source and supports
SSE2 multithreading.
Clusters are created by their local clustering threshold 'd',
which is computed as the number of nucleotide differences
(substitution, insertion or deletion) between two amplicons
in the optimal pairwise global alignment.
This class is compatible with Swarm v.1.2.7
"""
def __init__(self, params):
""" Return a new SwarmOtuPicker object with specified params.
The defaults are set in the Swarm API
"""
OtuPicker.__init__(self, params)
def __call__(self, seq_path=None, result_path=None, log_path=None):
self.log_lines = []
# Run Swarm, return a list of lists (clusters)
clusters = swarm_denovo_cluster(
seq_path=seq_path,
d=self.Params['resolution'],
threads=self.Params['threads'],
HALT_EXEC=False)
self.log_lines.append('Num OTUs: %d' % len(clusters))
# Add prefix ID to de novo OTUs
otu_id_prefix = self.Params['denovo_otu_id_prefix']
if otu_id_prefix is None:
clusters = dict(enumerate(clusters))
else:
clusters = dict(('%s%d' % (otu_id_prefix, i), c)
for i, c in enumerate(clusters))
if result_path:
# If the user provided a result_path, write the
# results to file with one tab-separated line per
# cluster
of = open(result_path, 'w')
for cluster_id, cluster in clusters.items():
of.write('%s\t%s\n' % (cluster_id, '\t'.join(cluster)))
of.close()
result = None
self.log_lines.append('Result path: %s\n' % result_path)
else:
# if the user did not provide a result_path, store
# the clusters in a dict of {otu_id:[seq_ids]}, where
# otu_id is arbitrary
result = clusters
self.log_lines.append('Result path: None, returned as dict.')
# Log the run
if log_path:
log_file = open(log_path, 'w')
self.log_lines.insert(0, str(self))
log_file.write('\n'.join(self.log_lines))
log_file.close()
return result
class PrefixSuffixOtuPicker(OtuPicker):
Name = 'PrefixSuffixOtuPicker'
def __init__(self, params):
"""Return new OtuPicker object with specified params.
params contains both generic and per-method (e.g. for
cdhit application controller) params.
Some generic entries in params are:
Algorithm: algorithm used
Similarity: similarity threshold, default 0.97, corresponding to
genus-level OTUs ('Similarity' is a synonym for the '-c' parameter
to the cd-hit application controllers)
Application: 3rd-party application used
"""
_params = {'Similarity': 0.97,
'Algorithm': 'Prefix/suffix exact matching'}
_params.update(params)
OtuPicker.__init__(self, _params)
def __call__(self, seq_path, result_path=None, log_path=None,
prefix_length=50, suffix_length=50):
"""Returns dict mapping {otu_id:[seq_ids]} for each otu.
Parameters:
seq_path: path to file of sequences
result_path: path to file of results. If specified,
dumps the result to the desired path instead of returning it.
log_path: path to log, which includes dump of params.
prefix_prefilter_length: prefilters the sequence collection so
sequences whose first prefix_prefilter_length characters are
identical will automatically be grouped into the same OTU [off by
default, 100 is typically a good value if this filtering is
desired] -- useful for large sequence collections, when cdhit doesn't
scale well
"""
log_lines = []
log_lines.append('Prefix length: %d' % prefix_length)
log_lines.append('Suffix length: %d' % suffix_length)
assert prefix_length >= 0, 'Prefix length (%d) must be >= 0' % prefix_length
assert suffix_length >= 0, 'Suffix length (%d) must be >= 0' % suffix_length
clusters = self._collapse_exact_matches(parse_fasta(open(seq_path)),
prefix_length, suffix_length)
log_lines.append('Num OTUs: %d' % len(clusters))
if result_path:
# if the user provided a result_path, write the
# results to file with one tab-separated line per
# cluster
of = open(result_path, 'w')
for i, cluster in enumerate(clusters):
of.write('%s\t%s\n' % (i, '\t'.join(cluster)))
of.close()
result = None
log_lines.append('Result path: %s' % result_path)
else:
# if the user did not provide a result_path, store
# the clusters in a dict of {otu_id:[seq_ids]}, where
# otu_id is arbitrary
result = dict(enumerate(clusters))
log_lines.append('Result path: None, returned as dict.')
if log_path:
# if the user provided a log file path, log the run
log_file = open(log_path, 'w')
log_lines = [str(self)] + log_lines
log_file.write('\n'.join(log_lines))
# return the result (note this is None if the data was
# written to file)
return result
def _build_seq_hash(self, seq, prefix_length, suffix_length):
""" Merge the prefix and suffix into a hash for the OTU
"""
len_seq = len(seq)
if len_seq <= prefix_length + suffix_length:
return seq
prefix = seq[:prefix_length]
suffix = seq[len_seq - suffix_length:]
return prefix + suffix
def _collapse_exact_matches(self, seqs, prefix_length, suffix_length):
""" Cluster sequences into sets with identical prefix/suffix
"""
cluster_map = {}
for seq_id, seq in seqs:
seq_id = seq_id.split()[0]
seq_hash = self._build_seq_hash(seq, prefix_length, suffix_length)
try:
cluster_map[seq_hash].append(seq_id)
except KeyError:
cluster_map[seq_hash] = [seq_id]
return cluster_map.values()
class TrieOtuPicker(OtuPicker):
Name = 'TrieOtuPicker'
def __init__(self, params):
"""Return new OtuPicker object with specified params.
params contains both generic and per-method (e.g. for
cdhit application controller) params.
Some generic entries in params are:
Algorithm: algorithm used
Similarity: similarity threshold, default 0.97, corresponding to
genus-level OTUs ('Similarity' is a synonym for the '-c' parameter
to the cd-hit application controllers)
Application: 3rd-party application used
"""
_params = {'Similarity': 0.97,
'Algorithm': 'Trie prefix or suffix matching',
'Reverse': False}
_params.update(params)
OtuPicker.__init__(self, _params)
def __call__(self, seq_path, result_path=None, log_path=None):
"""Returns dict mapping {otu_id:[seq_ids]} for each otu.
Parameters:
seq_path: path to file of sequences
result_path: path to file of results. If specified,
dumps the result to the desired path instead of returning it.
log_path: path to log, which includes dump of params.
"""
log_lines = []
# Get the appropriate sequence iterator
if self.Params['Reverse']:
# Reverse the sequences prior to building the prefix map.
# This effectively creates a suffix map.
# Also removes descriptions from seq identifier lines
seqs = imap(lambda s: (s[0].split()[0], s[1][::-1]),
parse_fasta(open(seq_path)))
log_lines.append(
'Seqs reversed for suffix mapping (rather than prefix mapping).')
else:
# remove descriptions from seq identifier lines
seqs = imap(lambda s: (s[0].split()[0], s[1]),
parse_fasta(open(seq_path)))
# Build the mapping
t = CompressedTrie(fasta_to_pairlist(seqs))
mapping = t.prefix_map
log_lines.append('Num OTUs: %d' % len(mapping))
if result_path:
# if the user provided a result_path, write the
# results to file with one tab-separated line per
# cluster
of = open(result_path, 'w')
for i, (otu_id, members) in enumerate(mapping.iteritems()):
of.write('%s\t%s\n' % (i, '\t'.join([otu_id] + members)))
of.close()
result = None
log_lines.append('Result path: %s' % result_path)
else:
# if the user did not provide a result_path, store
# the clusters in a dict of {otu_id:[seq_ids]}, where
# otu_id is arbitrary
# add key to cluster_members
for key in mapping.keys():
mapping[key].append(key)
result = dict(enumerate(mapping.values()))
log_lines.append('Result path: None, returned as dict.')
if log_path:
# if the user provided a log file path, log the run
log_file = open(log_path, 'w')
log_lines = [str(self)] + log_lines
log_file.write('\n'.join(log_lines))
# return the result (note this is None if the data was