improved removal of identical seqs
[jalview.git] / forester / ruby / evoruby / lib / evo / msa / msa.rb
1 #
2 # = lib/evo/msa/msa.rb - Msa class
3 #
4 # Copyright::  Copyright (C) 2006-2007 Christian M. Zmasek
5 # License::    GNU Lesser General Public License (LGPL)
6 #
7 # $Id: msa.rb,v 1.11 2009/01/03 00:42:08 cmzmasek Exp $
8 #
9
10
11 require 'lib/evo/util/constants'
12 require 'lib/evo/util/util'
13 require 'lib/evo/sequence/sequence'
14
15 module Evoruby
16
17   class Msa
18
19     def initialize()
20       @sequences = Array.new
21       @identical_seqs_detected = Array.new
22     end
23
24
25     def add_sequence( sequence )
26       @sequences.push( sequence )
27     end
28
29     def add( name, molecular_sequence_str )
30       add_sequence( Sequence.new( name, molecular_sequence_str ) )
31     end
32
33     def get_sequence( index )
34       if ( index < 0 || index > get_number_of_seqs() - 1 )
35         error_msg = "attempt to get sequence " <<
36          index.to_s << " in alignment of " << get_number_of_seqs().to_s <<
37          " sequences"
38         raise ArgumentError, error_msg
39       end
40       return @sequences[ index ]
41     end
42
43     def remove_sequence!( index )
44       if ( index < 0 || index > get_number_of_seqs() - 1 )
45         error_msg = "attempt to remove sequence " <<
46          index.to_s << " in alignment of " << get_number_of_seqs().to_s <<
47          " sequences"
48         raise ArgumentError, error_msg
49       end
50       @sequences.delete_at( index )
51     end
52
53     def get_identical_seqs_detected
54       @identical_seqs_detected
55     end
56
57
58     def is_aligned()
59       if ( get_number_of_seqs < 1 )
60         return false
61       else
62         l = @sequences[ 0 ].get_length()
63         for i in 0 ... get_number_of_seqs()
64           if ( get_sequence( i ).get_length() != l )
65             return false
66           end
67         end
68       end
69       return true
70     end
71
72     def find_by_name( name, case_sensitive, partial_match )
73       indices = Array.new()
74       for i in 0 ... get_number_of_seqs()
75         current_name = get_sequence( i ).get_name()
76         if !case_sensitive
77           current_name = current_name.downcase
78           name = name.downcase
79         end
80         if current_name == name ||
81            ( partial_match && current_name.include?( name ) )
82           indices.push( i )
83         end
84       end
85       indices
86     end
87
88     def find_by_name_start( name, case_sensitive )
89       indices = Array.new()
90       for i in 0 ... get_number_of_seqs()
91         get_sequence( i ).get_name() =~ /^\s*(\S+)/
92         current_name = $1
93         if !case_sensitive
94           current_name = current_name.downcase
95           name = name.downcase
96         end
97         if  ( current_name == name )
98           indices.push( i )
99         end
100       end
101       indices
102     end
103
104     def has?( name, case_sensitive = true, partial_match = false )
105       for i in 0 ... get_number_of_seqs()
106         current_name = get_sequence( i ).get_name()
107         if !case_sensitive
108           current_name = current_name.downcase
109           name = name.downcase
110         end
111         if current_name == name ||
112            ( partial_match && current_name.include?( name ) )
113           return true
114         end
115       end
116       false
117     end
118
119     # throws ArgumentError
120     def get_by_name( name, case_sensitive = true, partial_match = false )
121       indices = find_by_name( name, case_sensitive, partial_match )
122       if ( indices.length > 1 )
123         error_msg = "\"" + name + "\" not unique"
124         raise ArgumentError, error_msg
125       elsif ( indices.length < 1 )
126         error_msg = "\"" + name + "\" not found"
127         raise ArgumentError, error_msg
128       end
129       get_sequence( indices[ 0 ] )
130     end
131
132     # throws ArgumentError
133     def get_by_name_start( name, case_sensitive = true )
134       indices = find_by_name_start( name, case_sensitive )
135       if ( indices.length > 1 )
136         error_msg = "\"" + name + "\" not unique"
137         raise ArgumentError, error_msg
138       elsif ( indices.length < 1 )
139         error_msg = "\"" + name + "\" not found"
140         raise ArgumentError, error_msg
141       end
142       get_sequence( indices[ 0 ] )
143     end
144
145
146     def get_sub_alignment( seq_numbers )
147       msa = Msa.new()
148       for i in 0 ... seq_numbers.length()
149         msa.add_sequence( get_sequence( seq_numbers[ i ] ).copy() )
150       end
151       return msa
152     end
153
154     def get_number_of_seqs()
155       @sequences.length
156     end
157
158     def get_length()
159       if ( !is_aligned() )
160         error_msg = "attempt to get length of unaligned msa"
161         raise StandardError, error_msg, caller
162       end
163       if ( get_number_of_seqs() < 1 )
164         -1
165       else
166         @sequences[ 0 ].get_length()
167       end
168     end
169
170     def to_str()
171       s = String.new()
172       for i in 0...get_number_of_seqs()
173         s += @sequences[ i ].to_str + Constants::LINE_DELIMITER
174       end
175       s
176     end
177
178     def print_overlap_diagram( min_overlap = 1, io = STDOUT, max_name_length = 10 )
179       if ( !is_aligned() )
180         error_msg = "attempt to get overlap diagram of unaligned msa"
181         raise StandardError, error_msg, caller
182       end
183       for i in 0 ... get_number_of_seqs()
184         io.print( Util.normalize_seq_name( get_sequence( i ).get_name(), max_name_length ) )
185         for j in 0 ... get_number_of_seqs()
186           if i == j
187             io.print( " " )
188           else
189             if overlap?( i, j, min_overlap )
190               io.print( "+" )
191             else
192               io.print( "-" )
193             end
194           end
195         end
196         io.print( Evoruby::Constants::LINE_DELIMITER )
197       end
198     end
199
200     #returns array of Msa with an overlap of min_overlap
201     def split_into_overlapping_msa( min_overlap = 1 )
202       if ( !is_aligned() )
203         error_msg = "attempt to split into overlapping msas of unaligned msa"
204         raise StandardError, error_msg, caller
205       end
206       msas = Array.new()
207       bins = get_overlaps( min_overlap )
208       for i in 0 ... bins.length
209         msas.push( get_sub_alignment( bins[ i ] ) )
210       end
211       msas
212     end
213
214     def overlap?( index_1, index_2, min_overlap = 1 )
215       seq_1 = get_sequence( index_1 )
216       seq_2 = get_sequence( index_2 )
217       overlap_count = 0
218       for i in 0...seq_1.get_length()
219         if !Util.is_aa_gap_character?( seq_1.get_character_code( i ) ) &&
220            !Util.is_aa_gap_character?( seq_2.get_character_code( i ) )
221           overlap_count += 1
222           if overlap_count >= min_overlap
223             return true
224           end
225         end
226       end
227       return false
228     end
229
230     def calculate_overlap( index_1, index_2 )
231       seq_1 = get_sequence( index_1 )
232       seq_2 = get_sequence( index_2 )
233       overlap_count = 0
234       for i in 0...seq_1.get_length
235         if !Util.is_aa_gap_character?( seq_1.get_character_code( i ) ) &&
236            !Util.is_aa_gap_character?( seq_2.get_character_code( i ) )
237           overlap_count += 1
238         end
239       end
240       overlap_count
241     end
242
243     def calculate_identities( index_1, index_2 )
244       seq_1 = get_sequence( index_1 )
245       seq_2 = get_sequence( index_2 )
246       identities_count = 0
247       for i in 0...seq_1.get_length
248         if !Util.is_aa_gap_character?( seq_1.get_character_code( i ) ) &&
249            !Util.is_aa_gap_character?( seq_2.get_character_code( i ) ) &&
250            seq_1.get_character_code( i ) != 63 &&
251            ( seq_1.get_residue( i ).downcase() ==
252              seq_2.get_residue( i ).downcase() )
253           identities_count += 1
254         end
255       end
256       identities_count
257     end
258
259     def remove_gap_only_columns!()
260       remove_columns!( get_gap_only_columns() )
261     end
262
263     def remove_gap_columns!()
264       remove_columns!( get_gap_columns() )
265     end
266
267     # removes columns for which seqs with gap / number of sequences > gap_ratio
268     def remove_gap_columns_w_gap_ratio!( gap_ratio )
269       remove_columns!( get_gap_columns_w_gap_ratio( gap_ratio ) )
270     end
271
272
273     def remove_sequences_by_gap_ratio!( gap_ratio )
274       if ( !is_aligned() )
275         error_msg = "attempt to remove sequences by gap ratio on unaligned msa"
276         raise StandardError, error_msg, caller
277       end
278       n = get_number_of_seqs
279       removed = Array.new
280       for s in 0 ... n
281         if ( get_sequence( ( n - 1 ) - s  ).get_gap_ratio() > gap_ratio )
282           if ( Evoruby::Constants::VERBOSE )
283             puts( "removed: " + get_sequence( ( n - 1 ) - s  ).get_name )
284           end
285           removed << get_sequence( ( n - 1 ) - s  ).get_name
286           remove_sequence!( ( n - 1 ) - s  )
287         end
288       end
289       removed
290     end
291
292
293     def remove_redundant_sequences!( consider_taxonomy = false, verbose = false )
294       n = get_number_of_seqs
295       removed = Array.new
296       to_be_removed = Set.new
297       @identical_seqs_detected = Array.new
298       for i in 0 ... ( n - 1 )
299         for j in ( i + 1 ) ... n
300           if !to_be_removed.include?( i ) && !to_be_removed.include?( j )
301             if  !consider_taxonomy ||
302                ( ( get_sequence( i ).get_taxonomy == nil && get_sequence( j ).get_taxonomy == nil ) ||
303                  ( get_sequence( i ).get_taxonomy == get_sequence( j ).get_taxonomy ) )
304               if Util.clean_seq_str( get_sequence( i ).get_sequence_as_string ) ==
305                  Util.clean_seq_str( get_sequence( j ).get_sequence_as_string )
306                 to_be_removed.add( j )
307
308                 tax_i = ""
309                 tax_j = ""
310                 if get_sequence( i ).get_taxonomy != nil
311                   tax_i = get_sequence( i ).get_taxonomy.get_name
312                 end
313                 if get_sequence( j ).get_taxonomy != nil
314                   tax_j = get_sequence( j ).get_taxonomy.get_name
315                 end
316                 identical_pair = get_sequence( i ).get_name + " [#{tax_i}] == " + get_sequence( j ).get_name + " [#{tax_j}]"
317                 @identical_seqs_detected.push( identical_pair )
318                 if verbose
319                   puts identical_pair
320                 end
321               end
322             end
323           end
324         end
325       end
326     
327       to_be_removed_ary = to_be_removed.to_a.sort.reverse
328
329       to_be_removed_ary.each { | index |
330         removed.push( get_sequence( index ).get_name )
331         remove_sequence!( index )
332       }
333       removed
334     end
335
336
337     def remove_sequences_by_non_gap_length!( min_non_gap_length )
338       if ( !is_aligned() )
339         error_msg = "attempt to remove sequences by non gap length on unaligned msa"
340         raise StandardError, error_msg, caller
341       end
342       n = get_number_of_seqs
343       l = get_length
344       removed = Array.new
345       for s in 0 ... n
346         if ( ( l - get_sequence( ( n - 1 ) - s ).get_gap_length ) < min_non_gap_length )
347           if ( Evoruby::Constants::VERBOSE )
348             puts( "removed: " + get_sequence( ( n - 1 ) - s  ).get_name )
349           end
350           removed << get_sequence( ( n - 1 ) - s  ).get_name
351           remove_sequence!( ( n - 1 ) - s )
352         end
353       end
354       removed
355     end
356
357     def trim!( first, last )
358       cols = Array.new()
359       for i in 0 ... get_length()
360         if ( i < first || i > last )
361           cols.push( i )
362         end
363       end
364       remove_columns!( cols )
365     end
366
367     def get_gap_only_columns()
368       if ( !is_aligned() )
369         error_msg = "attempt to get gap only columns of unaligned msa"
370         raise StandardError, error_msg, caller
371       end
372       cols = Array.new()
373       for c in 0 ... get_length
374         nogap_char_found = false
375         for s in 0 ... get_number_of_seqs
376           unless Util.is_aa_gap_character?( get_sequence( s ).get_character_code( c ) )
377             nogap_char_found = true
378             break
379           end
380         end
381         unless nogap_char_found
382           cols.push( c )
383         end
384       end
385       return cols
386     end
387
388     def calculate_gap_proportion()
389       if ( !is_aligned() )
390         error_msg = "attempt to get gap only columns of unaligned msa"
391         raise StandardError, error_msg, caller
392       end
393       total_sum = 0.0
394       gap_sum = 0.0
395       for c in 0 ... get_length
396         for s in 0 ... get_number_of_seqs
397           total_sum = total_sum + 1
398           if Util.is_aa_gap_character?( get_sequence( s ).get_character_code( c ) )
399             gap_sum = gap_sum  + 1
400           end
401         end
402
403       end
404       return gap_sum / total_sum
405     end
406
407     def get_gap_columns()
408       if ( !is_aligned() )
409         error_msg = "attempt to get gap columns of unaligned msa"
410         raise StandardError, error_msg, caller
411       end
412       cols = Array.new()
413       for c in 0 ... get_length
414         gap_char_found = false
415         for s in 0 ... get_number_of_seqs
416           if Util.is_aa_gap_character?( get_sequence( s ).get_character_code( c ) )
417             gap_char_found = true
418             break
419           end
420         end
421         if gap_char_found
422           cols.push( c )
423         end
424       end
425       return cols
426     end
427
428     # gap_ratio = seqs with gap / number of sequences
429     # returns column indices for which seqs with gap / number of sequences > gap_ratio
430     def get_gap_columns_w_gap_ratio( gap_ratio )
431       if ( !is_aligned() )
432         error_msg = "attempt to get gap columns with gap_ratio of unaligned msa"
433         raise StandardError, error_msg, caller
434       end
435       if ( gap_ratio < 0 || gap_ratio > 1 )
436         error_msg = "gap ratio must be between 0 and 1 inclusive"
437         raise ArgumentError, error_msg, caller
438       end
439       cols = Array.new()
440       for c in 0 ... get_length
441         gap_chars_found = 0
442         for s in 0 ... get_number_of_seqs
443           if Util.is_aa_gap_character?( get_sequence( s ).get_character_code( c ) )
444             gap_chars_found += 1
445           end
446         end
447         if ( ( gap_chars_found.to_f / get_number_of_seqs ) > gap_ratio )
448           cols.push( c )
449         end
450       end
451       return cols
452     end
453
454
455     # Split an alignment into n alignemnts of equal size, except last one
456     def split( n, verbose = false )
457       if ( n < 2 || n > get_number_of_seqs )
458         error_msg = "attempt to split into less than two or more than the number of sequences"
459         raise StandardError, error_msg, caller
460       end
461       msas = Array.new()
462       r = get_number_of_seqs % n
463       x = get_number_of_seqs / n
464       for i in 0 ... n
465         msa = Msa.new()
466         s = 0
467
468         if ( ( r > 0 ) && ( i == ( n - 1 ) ) )
469           y = x + r
470           if ( verbose )
471             puts( i.to_s + ": " + y.to_s )
472           end
473           for j in 0 ... y
474             msa.add_sequence( get_sequence( ( i * x ) + j ) )
475           end
476         else
477           if ( verbose )
478             puts( i.to_s + ": " + x.to_s )
479           end
480           for j in 0 ... x
481             msa.add_sequence( get_sequence( ( i * x ) + j ) )
482           end
483         end
484         msas.push( msa )
485       end
486       msas
487     end
488
489
490     private
491
492     def get_overlaps( min_overlap = 1 )
493       if ( !is_aligned() )
494         error_msg = "attempt to get overlaps of unaligned msa"
495         raise StandardError, error_msg, caller
496       end
497       bins = Array.new()
498       for i in 0 ... get_number_of_seqs()
499         found_bin = false
500         for j in 0 ... bins.length
501           current_bin = bins[ j ]
502           # does seq i overlap with all seqs in current_bin?
503           all_overlap = true
504           for z in 0 ... current_bin.length
505             unless overlap?( i, current_bin[ z ], min_overlap )
506               all_overlap = false
507               break
508             end
509           end
510           if all_overlap
511             current_bin.push( i )
512             found_bin = true
513           end
514         end
515         unless found_bin
516           new_bin = Array.new()
517           new_bin.push( i )
518           bins.push( new_bin )
519         end
520       end
521       return bins
522     end
523
524     def remove_columns!( cols )
525       if ( !is_aligned() )
526         error_msg = "attempt to remove columns of unaligned msa"
527         raise StandardError, error_msg, caller
528       end
529       cols.reverse!()
530       for c in 0 ... cols.length()
531         col = cols[ c ]
532         for s in 0 ... get_number_of_seqs()
533           get_sequence( s ).delete_residue!( col )
534         end
535       end
536       return self
537     end
538
539
540   end # class Msa
541
542 end # module Evoruby
543