JAL-1827 added overloaded method for convenience
[jalview.git] / src / jalview / util / Comparison.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.util;
22
23 import jalview.datamodel.SequenceI;
24
25 import java.util.ArrayList;
26 import java.util.List;
27
28 /**
29  * Assorted methods for analysing or comparing sequences.
30  */
31 public class Comparison
32 {
33   private static final int EIGHTY_FIVE = 85;
34
35   private static final int TO_UPPER_CASE = 'a' - 'A';
36
37   private static final char GAP_SPACE = ' ';
38
39   private static final char GAP_DOT = '.';
40
41   private static final char GAP_DASH = '-';
42
43   public static final String GapChars = new String(new char[] { GAP_SPACE,
44       GAP_DOT, GAP_DASH });
45
46   /**
47    * DOCUMENT ME!
48    * 
49    * @param ii
50    *          DOCUMENT ME!
51    * @param jj
52    *          DOCUMENT ME!
53    * 
54    * @return DOCUMENT ME!
55    */
56   public static final float compare(SequenceI ii, SequenceI jj)
57   {
58     return Comparison.compare(ii, jj, 0, ii.getLength() - 1);
59   }
60
61   /**
62    * this was supposed to be an ungapped pid calculation
63    * 
64    * @param ii
65    *          SequenceI
66    * @param jj
67    *          SequenceI
68    * @param start
69    *          int
70    * @param end
71    *          int
72    * @return float
73    */
74   public static float compare(SequenceI ii, SequenceI jj, int start, int end)
75   {
76     String si = ii.getSequenceAsString();
77     String sj = jj.getSequenceAsString();
78
79     int ilen = si.length() - 1;
80     int jlen = sj.length() - 1;
81
82     while (Comparison.isGap(si.charAt(start + ilen)))
83     {
84       ilen--;
85     }
86
87     while (Comparison.isGap(sj.charAt(start + jlen)))
88     {
89       jlen--;
90     }
91
92     int count = 0;
93     int match = 0;
94     float pid = -1;
95
96     if (ilen > jlen)
97     {
98       for (int j = 0; j < jlen; j++)
99       {
100         if (si.substring(start + j, start + j + 1).equals(
101                 sj.substring(start + j, start + j + 1)))
102         {
103           match++;
104         }
105
106         count++;
107       }
108
109       pid = (float) match / (float) ilen * 100;
110     }
111     else
112     {
113       for (int j = 0; j < jlen; j++)
114       {
115         if (si.substring(start + j, start + j + 1).equals(
116                 sj.substring(start + j, start + j + 1)))
117         {
118           match++;
119         }
120
121         count++;
122       }
123
124       pid = (float) match / (float) jlen * 100;
125     }
126
127     return pid;
128   }
129
130   /**
131    * this is a gapped PID calculation
132    * 
133    * @param s1
134    *          SequenceI
135    * @param s2
136    *          SequenceI
137    * @return float
138    */
139   public final static float PID(String seq1, String seq2)
140   {
141     return PID(seq1, seq2, 0, seq1.length());
142   }
143
144   static final int caseShift = 'a' - 'A';
145
146   // Another pid with region specification
147   public final static float PID(String seq1, String seq2, int start, int end)
148   {
149     return PID(seq1, seq2, start, end, true, false);
150   }
151
152   /**
153    * Calculate percent identity for a pair of sequences over a particular range,
154    * with different options for ignoring gaps.
155    * 
156    * @param seq1
157    * @param seq2
158    * @param start
159    *          - position in seqs
160    * @param end
161    *          - position in seqs
162    * @param wcGaps
163    *          - if true - gaps match any character, if false, do not match
164    *          anything
165    * @param ungappedOnly
166    *          - if true - only count PID over ungapped columns
167    * @return
168    */
169   public final static float PID(String seq1, String seq2, int start,
170           int end, boolean wcGaps, boolean ungappedOnly)
171   {
172     int s1len = seq1.length();
173     int s2len = seq2.length();
174
175     int len = Math.min(s1len, s2len);
176
177     if (end < len)
178     {
179       len = end;
180     }
181
182     if (len < start)
183     {
184       start = len - 1; // we just use a single residue for the difference
185     }
186
187     int elen = len - start, bad = 0;
188     char chr1;
189     char chr2;
190     boolean agap;
191     for (int i = start; i < len; i++)
192     {
193       chr1 = seq1.charAt(i);
194
195       chr2 = seq2.charAt(i);
196       agap = isGap(chr1) || isGap(chr2);
197       if ('a' <= chr1 && chr1 <= 'z')
198       {
199         // TO UPPERCASE !!!
200         // Faster than toUpperCase
201         chr1 -= caseShift;
202       }
203       if ('a' <= chr2 && chr2 <= 'z')
204       {
205         // TO UPPERCASE !!!
206         // Faster than toUpperCase
207         chr2 -= caseShift;
208       }
209
210       if (chr1 != chr2)
211       {
212         if (agap)
213         {
214           if (ungappedOnly)
215           {
216             elen--;
217           }
218           else if (!wcGaps)
219           {
220             bad++;
221           }
222         }
223         else
224         {
225           bad++;
226         }
227       }
228
229     }
230     if (elen < 1)
231     {
232       return 0f;
233     }
234     return ((float) 100 * (elen - bad)) / elen;
235   }
236
237   /**
238    * Answers true if the supplied character is a recognised gap character, else
239    * false. Currently hard-coded to recognise '-', '-' or ' ' (hyphen / dot /
240    * space).
241    * 
242    * @param c
243    * 
244    * @return
245    */
246   public static final boolean isGap(char c)
247   {
248     return (c == GAP_DASH || c == GAP_DOT || c == GAP_SPACE) ? true : false;
249   }
250
251   /**
252    * Answers true if more than 85% of the sequence residues (ignoring gaps) are
253    * A, G, C, T or U, else false. This is just a heuristic guess and may give a
254    * wrong answer (as AGCT are also amino acid codes).
255    * 
256    * @param seqs
257    * @return
258    */
259   public static final boolean isNucleotide(SequenceI[] seqs)
260   {
261     if (seqs == null)
262     {
263       return false;
264     }
265     char[][] letters = new char[seqs.length][];
266     for (int i = 0; i < seqs.length; i++)
267     {
268       char[] sequence = seqs[i].getSequence();
269       if (sequence != null)
270       {
271         letters[i] = sequence;
272       }
273     }
274
275     return areNucleotide(letters);
276   }
277
278   /**
279    * Answers true if more than 85% of the sequence residues (ignoring gaps) are
280    * A, G, C, T or U, else false. This is just a heuristic guess and may give a
281    * wrong answer (as AGCT are also amino acid codes).
282    * 
283    * @param letters
284    * @return
285    */
286   public static final boolean areNucleotide(char[][] letters)
287   {
288     int ntCount = 0;
289     int aaCount = 0;
290     for (char[] seq : letters)
291     {
292       if (seq == null)
293       {
294         continue;
295       }
296       // TODO could possibly make an informed guess just from the first sequence
297       // to save a lengthy calculation
298       for (char c : seq)
299       {
300         if ('a' <= c && c <= 'z')
301         {
302           c -= TO_UPPER_CASE;
303         }
304
305         if (c == 'A' || c == 'G' || c == 'C' || c == 'T' || c == 'U')
306         {
307           ntCount++;
308         }
309         else if (!Comparison.isGap(c))
310         {
311           aaCount++;
312         }
313       }
314     }
315
316     /*
317      * Check for nucleotide count > 85% of total count (in a form that evades
318      * int / float conversion or divide by zero).
319      */
320     if (ntCount * 100 > EIGHTY_FIVE * (ntCount + aaCount))
321     {
322       return true;
323     }
324     else
325     {
326       return false;
327     }
328
329   }
330
331   /**
332    * Convenience overload of isNucleotide
333    * 
334    * @param seqs
335    * @return
336    */
337   public static boolean isNucleotide(SequenceI[][] seqs)
338   {
339     if (seqs == null)
340     {
341       return false;
342     }
343     List<SequenceI> flattened = new ArrayList<SequenceI>();
344     for (SequenceI[] ss : seqs)
345     {
346       for (SequenceI s : ss)
347       {
348         flattened.add(s);
349       }
350     }
351     final SequenceI[] oneDArray = flattened.toArray(new SequenceI[flattened
352             .size()]);
353     return isNucleotide(oneDArray);
354   }
355 }