]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/usearch.rb
finished refactoring s/has_key?/[]/
[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 SORT_LIMIT = 2_000_000_000   # use mergesort for files biggern than 2Gb.
31
32 class Usearch
33   include Enumerable
34
35   def initialize(infile, outfile, options)
36     @infile  = infile
37     @outfile = outfile
38     @options = options
39     @command = []
40
41     raise UsearchError, %{Empty input file -> "#{@infile}"} if File.size(@infile) == 0
42   end
43
44   # Method that calls Usearch sorting for sorting a FASTA file
45   # according to decending sequence length.
46   def sort_length
47     # usearch -sort seqs.fasta -output seqs.sorted.fasta
48     if File.size(@infile) < SORT_LIMIT
49       @command << "usearch --sort #{@infile} --output #{@infile}.sort"
50     else
51       @command << "usearch --mergesort #{@infile} --output #{@infile}.sort"
52     end
53
54                 execute
55
56     File.rename "#{@infile}.sort", @infile
57   end
58
59   # Method that calls Usearch sorting for sorting a FASTA file
60   # according to cluster size.
61   def sort_size
62     @command << "usearch --sortsize #{@infile} --output #{@infile}.sort"
63
64                 execute
65
66     File.rename "#{@infile}.sort", @infile
67   end
68
69         # Method to execute clustering de novo.
70   def cluster
71     @command << "usearch --cluster #{@infile} --uc #{@outfile} --id #{@options[:identity]}"
72     @command << "--rev" if @options[:comp]
73
74                 execute
75   end
76
77   # Method to execute database search.
78   def usearch
79     @command << "usearch --query #{@infile} --db #{@options[:database]} --userout #{@outfile}"
80     @command << "--userfields target+tloz+thiz+query+bits+strand"
81     @command << "--id #{@options[:identity]}"  if @options[:identity]
82     @command << "--evalue #{@options[:e_val]}" if @options[:e_val]
83     @command << "--rev"
84
85                 execute
86   end
87
88   # Method to execute uchime chimera detection.
89   def uchime
90     @command << "usearch --uchime #{@infile} --db #{@options[:database]} --uchimeout #{@outfile}"
91
92     execute
93   end
94
95   # Method to execute ustar alignment.
96   def ustar
97     command = %Q{grep "^[SH]" #{@outfile} > #{@outfile}.sub}
98     system(command)
99     raise "Command failed: #{command}" unless $?.success?
100
101     File.rename "#{@outfile}.sub", @outfile
102
103     @command << "usearch --uc2fastax #{@outfile} --input #{@infile} --output #{@infile}.sub"
104
105     execute
106
107     @command << "usearch --staralign #{@infile}.sub --output #{@outfile}"
108
109     execute
110
111     File.delete "#{@infile}.sub"
112   end
113
114         # Method to parse a Uclust .uc file and for each line of data
115         # yield a Biopiece record.
116   def each_cluster
117     record = {}
118
119     File.open(@outfile, "r") do |ios|
120       ios.each_line do |line|
121         if line !~ /^#/
122           fields = line.chomp.split("\t")
123
124           next if fields[0] == 'C'
125
126           record[:TYPE]     = fields[0]
127           record[:CLUSTER]  = fields[1].to_i
128           record[:IDENT]    = fields[3].to_f
129           record[:Q_ID]     = fields[8]
130
131           yield record
132         end
133       end
134     end
135
136     self # conventionally
137   end
138
139         # Method to parse a Useach user defined tabular file and for each line of data
140         # yield a Biopiece record.
141   def each_hit
142     record = {}
143
144     File.open(@outfile, "r") do |ios|
145       ios.gets   # skip comment line
146       ios.each_line do |line|
147         fields = line.chomp.split("\t")
148
149         record[:REC_TYPE] = "USEARCH"
150         record[:S_ID]     = fields[0]
151         record[:S_BEG]    = fields[1].to_i
152         record[:S_END]    = fields[2].to_i
153         record[:Q_ID]     = fields[3]
154         record[:SCORE]    = fields[4].to_f
155         record[:STRAND]   = fields[5]
156
157         yield record
158       end
159     end
160
161     self # conventionally
162   end
163
164   # Method to parse a FASTA file with Ustar alignments and for each alignment
165   # yield an Align object.
166   def each_alignment
167     old_cluster = 0
168     entries     = []
169
170     Fasta.open(@outfile, "r") do |ios|
171       ios.each do |entry|
172         entry.seq.tr!('.', '-')   # Replace . with - in Ustar alignments.
173         cluster, identity, name = entry.seq_name.split('|')
174         cluster = cluster.to_i
175
176         if cluster == old_cluster
177           entries << entry
178         else
179           fix_alignment(entries)
180
181           yield Align.new(entries)
182
183           old_cluster = cluster
184           entries     = []
185           entries << entry
186         end
187       end
188
189       yield Align.new(entries) unless entries.empty?
190     end
191   end
192
193   private
194
195   # Method that fixed Ustar bug resulting in alignments with uneven 
196   # sequence length.
197   def fix_alignment(entries)
198     if entries.size > 1
199       min, max = entries.minmax { |a, b| a.length <=> b.length } 
200
201       if min.length != max.length
202         entries.each do |entry|
203           entry.seq << '-' * (max.length - entry.length)
204         end
205       end
206     end
207   end
208
209         # Method to execute a command using a system() call.
210         # The command is composed of bits from the @command variable.
211         def execute
212                 @command.unshift "nice -n 19"
213                 @command << "--quiet" unless @options[:verbose]
214                 command = @command.join(" ")
215     $stderr.puts "Running command: #{command}" if @options[:verbose]
216     system(command)
217     raise "Command failed: #{command}" unless $?.success?
218
219                 @command = []
220         end
221 end
222
223 __END__
224