]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/usearch.rb
0bc72352d648c92d958a82aed390b3118518d4d2
[biopieces.git] / code_ruby / lib / maasha / usearch.rb
1 # Copyright (C) 2011 Martin A. Hansen.
2
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
7
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16
17 # http://www.gnu.org/copyleft/gpl.html
18
19 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
20
21 # This software is part of the Biopieces framework (www.biopieces.org).
22
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
24
25 require 'maasha/fasta'
26
27 # Error class for all exceptions to do with Usearch.
28 class UsearchError < StandardError; end
29
30 class Usearch
31   include Enumerable
32
33   def initialize(infile, outfile, options)
34     @infile  = infile
35     @outfile = outfile
36     @options = options
37     @command = []
38
39     raise UsearchError, %{Empty input file -> "#{@infile}"} if File.size(@infile) == 0
40   end
41
42   # Method that calls Usearch sorting for sorting a FASTA file
43   # according to decending sequence length.
44   def sortbylength
45     # usearch -sortbylength seqs.fasta -output seqs_sorted.fasta -minseqlength 64
46     @command << "usearch -sortbylength #{@infile} -output #{@infile}.sort"
47
48                 execute
49
50     File.rename "#{@infile}.sort", @infile
51   end
52
53   # Method that calls Usearch sorting for sorting a FASTA file
54   # according to cluster size.
55   def sortbysize
56     # usearch -sortbysize seqs.fasta -output seqs_sorted.fasta -minsize 4
57     @command << "usearch -sortbysize #{@infile} -output #{@infile}.sort"
58
59                 execute
60
61     File.rename "#{@infile}.sort", @infile
62   end
63
64   # Method to execute cluster_fast.
65   def cluster_fast
66     # usearch -cluster_fast query.fasta -id 0.9 -centroids nr.fasta -uc clusters.uc
67     @command << "usearch -cluster_fast #{@infile} -id #{@options[:identity]} -uc #{@outfile}"
68
69     execute
70   end
71
72   # Method to execute cluster_smallmem.
73   # NB sequences must be sorted with sortbylength or sortbysize.
74   def cluster_smallmem
75     # usearch -cluster_smallmem query.fasta -id 0.9 -centroids nr.fasta -uc clusters.uc
76     @command << "usearch -cluster_smallmem #{@infile} -id #{@options[:identity]} -uc #{@outfile}"
77     @command << "-strand both" if @options[:comp]
78
79     execute
80   end
81
82   # Method to execute database search.
83   def usearch
84     @command << "usearch --query #{@infile} --db #{@options[:database]} --userout #{@outfile}"
85     @command << "--userfields target+tloz+thiz+query+bits+strand"
86     @command << "--id #{@options[:identity]}"  if @options[:identity]
87     @command << "--evalue #{@options[:e_val]}" if @options[:e_val]
88     @command << "--rev"
89
90                 execute
91   end
92
93   # Method to execute uchime chimera detection.
94   def uchime
95     @command << "usearch --uchime #{@infile} --db #{@options[:database]} --uchimeout #{@outfile}"
96
97     execute
98   end
99
100   # Method to execute ustar alignment.
101   def ustar
102     command = %Q{grep "^[SH]" #{@outfile} > #{@outfile}.sub}
103     system(command)
104     raise "Command failed: #{command}" unless $?.success?
105
106     File.rename "#{@outfile}.sub", @outfile
107
108     @command << "usearch --uc2fastax #{@outfile} --input #{@infile} --output #{@infile}.sub"
109
110     execute
111
112     @command << "usearch --staralign #{@infile}.sub --output #{@outfile}"
113
114     execute
115
116     File.delete "#{@infile}.sub"
117   end
118
119         # Method to parse a Uclust .uc file and for each line of data
120         # yield a Biopiece record.
121   def each_cluster
122     record = {}
123
124     File.open(@outfile, "r") do |ios|
125       ios.each_line do |line|
126         if line !~ /^#/
127           fields = line.chomp.split("\t")
128
129           next if fields[0] == 'C'
130
131           record[:TYPE]     = fields[0]
132           record[:CLUSTER]  = fields[1].to_i
133           record[:IDENT]    = fields[3].to_f
134           record[:Q_ID]     = fields[8]
135
136           yield record
137         end
138       end
139     end
140
141     self # conventionally
142   end
143
144         # Method to parse a Useach user defined tabular file and for each line of data
145         # yield a Biopiece record.
146   def each_hit
147     record = {}
148
149     File.open(@outfile, "r") do |ios|
150       ios.gets   # skip comment line
151       ios.each_line do |line|
152         fields = line.chomp.split("\t")
153
154         record[:REC_TYPE] = "USEARCH"
155         record[:S_ID]     = fields[0]
156         record[:S_BEG]    = fields[1].to_i
157         record[:S_END]    = fields[2].to_i
158         record[:Q_ID]     = fields[3]
159         record[:SCORE]    = fields[4].to_f
160         record[:STRAND]   = fields[5]
161
162         yield record
163       end
164     end
165
166     self # conventionally
167   end
168
169   # Method to parse a FASTA file with Ustar alignments and for each alignment
170   # yield an Align object.
171   def each_alignment
172     old_cluster = 0
173     entries     = []
174
175     Fasta.open(@outfile, "r") do |ios|
176       ios.each do |entry|
177         entry.seq.tr!('.', '-')   # Replace . with - in Ustar alignments.
178         cluster, identity, name = entry.seq_name.split('|')
179         cluster = cluster.to_i
180
181         if cluster == old_cluster
182           entries << entry
183         else
184           fix_alignment(entries)
185
186           yield Align.new(entries)
187
188           old_cluster = cluster
189           entries     = []
190           entries << entry
191         end
192       end
193
194       yield Align.new(entries) unless entries.empty?
195     end
196
197     self # conventionally
198   end
199
200   private
201
202   # Method that fixed Ustar bug resulting in alignments with uneven 
203   # sequence length.
204   def fix_alignment(entries)
205     if entries.size > 1
206       min, max = entries.minmax { |a, b| a.length <=> b.length } 
207
208       if min.length != max.length
209         entries.each do |entry|
210           entry.seq << '-' * (max.length - entry.length)
211         end
212       end
213     end
214   end
215
216         # Method to execute a command using a system() call.
217         # The command is composed of bits from the @command variable.
218         def execute
219                 @command << "--quiet" unless @options[:verbose]
220                 command = @command.join(" ")
221     $stderr.puts "Running command: #{command}" if @options[:verbose]
222     system(command)
223     raise "Command failed: #{command}" unless $?.success?
224
225                 @command = []
226         end
227 end
228
229 __END__
230