]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/usearch.rb
added check for empty files in usearch.rb
[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.has_key? :identity
82     @command << "--evalue #{@options[:e_val]}" if @options.has_key? :e_val
83     @command << "--rev"
84
85                 execute
86   end
87
88   # Method to execute ustar alignment.
89   def ustar
90     command = %Q{grep "^[SH]" #{@outfile} > #{@outfile}.sub}
91     system(command)
92     raise "Command failed: #{command}" unless $?.success?
93
94     File.rename "#{@outfile}.sub", @outfile
95
96     @command << "usearch --uc2fastax #{@outfile} --input #{@infile} --output #{@infile}.sub"
97
98     execute
99
100     @command << "usearch --staralign #{@infile}.sub --output #{@outfile}"
101
102     execute
103
104     File.delete "#{@infile}.sub"
105   end
106
107         # Method to parse a Uclust .uc file and for each line of data
108         # yield a Biopiece record.
109   def each_cluster
110     record = {}
111
112     File.open(@outfile, "r") do |ios|
113       ios.each_line do |line|
114         if line !~ /^#/
115           fields = line.chomp.split("\t")
116
117           next if fields[0] == 'C'
118
119           record[:TYPE]     = fields[0]
120           record[:CLUSTER]  = fields[1].to_i
121           record[:IDENT]    = fields[3].to_f
122           record[:Q_ID]     = fields[8]
123
124           yield record
125         end
126       end
127     end
128
129     self # conventionally
130   end
131
132         # Method to parse a Useach user defined tabular file and for each line of data
133         # yield a Biopiece record.
134   def each_hit
135     record = {}
136
137     File.open(@outfile, "r") do |ios|
138       ios.gets   # skip comment line
139       ios.each_line do |line|
140         fields = line.chomp.split("\t")
141
142         record[:REC_TYPE] = "USEARCH"
143         record[:S_ID]     = fields[0]
144         record[:S_BEG]    = fields[1].to_i
145         record[:S_END]    = fields[2].to_i
146         record[:Q_ID]     = fields[3]
147         record[:SCORE]    = fields[4].to_f
148         record[:STRAND]   = fields[5]
149
150         yield record
151       end
152     end
153
154     self # conventionally
155   end
156
157   # Method to parse a FASTA file with Ustar alignments and for each alignment
158   # yield an Align object.
159   def each_alignment
160     old_cluster = 0
161     entries     = []
162
163     Fasta.open(@outfile, "r") do |ios|
164       ios.each do |entry|
165         entry.seq.tr!('.', '-')   # Replace . with - in Ustar alignments.
166         cluster, identity, name = entry.seq_name.split('|')
167         cluster = cluster.to_i
168
169         if cluster == old_cluster
170           entries << entry
171         else
172           fix_alignment(entries)
173
174           yield Align.new(entries)
175
176           old_cluster = cluster
177           entries     = []
178           entries << entry
179         end
180       end
181
182       yield Align.new(entries) unless entries.empty?
183     end
184   end
185
186   private
187
188   # Method that fixed Ustar bug resulting in alignments with uneven 
189   # sequence length.
190   def fix_alignment(entries)
191     if entries.size > 1
192       min, max = entries.minmax { |a, b| a.length <=> b.length } 
193
194       if min.length != max.length
195         entries.each do |entry|
196           entry.seq << '-' * (max.length - entry.length)
197         end
198       end
199     end
200   end
201
202         # Method to execute a command using a system() call.
203         # The command is composed of bits from the @command variable.
204         def execute
205                 @command.unshift "nice -n 19"
206                 @command << "--quiet" unless @options[:verbose]
207                 command = @command.join(" ")
208     $stderr.puts "Running command: #{command}" if @options[:verbose]
209     system(command)
210     raise "Command failed: #{command}" unless $?.success?
211
212                 @command = []
213         end
214 end
215
216 __END__
217