JAL-920 compute a consensus for single sequence
[jalview.git] / src / jalview / analysis / AAFrequency.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.analysis;
19
20 import java.util.*;
21
22 import jalview.util.Format;
23 import jalview.datamodel.*;
24
25 /**
26  * Takes in a vector or array of sequences and column start and column end and
27  * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
28  * This class is used extensively in calculating alignment colourschemes that
29  * depend on the amount of conservation in each alignment column.
30  * 
31  * @author $author$
32  * @version $Revision$
33  */
34 public class AAFrequency
35 {
36   // No need to store 1000s of strings which are not
37   // visible to the user.
38   public static final String MAXCOUNT = "C";
39
40   public static final String MAXRESIDUE = "R";
41
42   public static final String PID_GAPS = "G";
43
44   public static final String PID_NOGAPS = "N";
45
46   public static final String PROFILE = "P";
47
48   public static final Hashtable[] calculate(List<SequenceI> list,
49           int start, int end)
50   {
51     return calculate(list, start, end, false);
52   }
53
54   public static final Hashtable[] calculate(List<SequenceI> sequences,
55           int start, int end, boolean profile)
56   {
57     SequenceI[] seqs = new SequenceI[sequences.size()];
58     int width = 0;
59     synchronized (sequences)
60     {
61       for (int i = 0; i < sequences.size(); i++)
62       {
63         seqs[i] = sequences.get(i);
64         if (seqs[i].getLength() > width)
65         {
66           width = seqs[i].getLength();
67         }
68       }
69
70       Hashtable[] reply = new Hashtable[width];
71
72       if (end >= width)
73       {
74         end = width;
75       }
76
77       calculate(seqs, start, end, reply, profile);
78       return reply;
79     }
80   }
81
82   public static final void calculate(SequenceI[] sequences, int start,
83           int end, Hashtable[] result)
84   {
85     calculate(sequences, start, end, result, false);
86   }
87
88   public static final void calculate(SequenceI[] sequences, int start,
89           int end, Hashtable[] result, boolean profile)
90   {
91     Hashtable residueHash;
92     int maxCount, nongap, i, j, v, jSize = sequences.length;
93     String maxResidue;
94     char c='-';
95     float percentage;
96
97     int[] values = new int[255];
98
99     char[] seq;
100
101     for (i = start; i < end; i++)
102     {
103       residueHash = new Hashtable();
104       maxCount = 0;
105       maxResidue = "";
106       nongap = 0;
107       values = new int[255];
108       
109       for (j = 0; j < jSize; j++)
110       {
111         if (sequences[j] == null)
112         {
113           System.err
114                   .println("WARNING: Consensus skipping null sequence - possible race condition.");
115           continue;
116         }
117         seq = sequences[j].getSequence();
118         if (seq.length > i)
119         {
120           c = seq[i];
121
122           if (c == '.' || c == ' ')
123           {
124             c = '-';
125           }
126
127           if (c == '-')
128           {
129             values['-']++;
130             continue;
131           }
132           else if ('a' <= c && c <= 'z')
133           {
134             c -= 32; // ('a' - 'A');
135           }
136
137           nongap++;
138           values[c]++;
139
140         }
141         else
142         {
143           values['-']++;
144         }
145       }
146       if (jSize==1)
147       {
148         maxResidue = String.valueOf(c);
149         maxCount=1;
150       } else {for (v = 'A'; v < 'Z'; v++)
151       {
152         if (values[v] < 2 || values[v] < maxCount)
153         {
154           continue;
155         }
156
157         if (values[v] > maxCount)
158         {
159           maxResidue = String.valueOf((char) v);
160         }
161         else if (values[v] == maxCount)
162         {
163           maxResidue += String.valueOf((char) v);
164         }
165         maxCount = values[v];
166       }
167       }
168       if (maxResidue.length() == 0)
169       {
170         maxResidue = "-";
171       }
172       if (profile)
173       {
174         residueHash.put(PROFILE, new int[][]
175         { values, new int[]
176         { jSize, nongap } });
177       }
178       residueHash.put(MAXCOUNT, new Integer(maxCount));
179       residueHash.put(MAXRESIDUE, maxResidue);
180
181       percentage = ((float) maxCount * 100) / jSize;
182       residueHash.put(PID_GAPS, new Float(percentage));
183
184       percentage = ((float) maxCount * 100) / nongap;
185       residueHash.put(PID_NOGAPS, new Float(percentage));
186       result[i] = residueHash;
187     }
188   }
189
190   /**
191    * Compute all or part of the annotation row from the given consensus
192    * hashtable
193    * 
194    * @param consensus
195    *          - pre-allocated annotation row
196    * @param hconsensus
197    * @param iStart
198    * @param width
199    * @param ignoreGapsInConsensusCalculation
200    * @param includeAllConsSymbols
201    * @param nseq 
202    */
203   public static void completeConsensus(AlignmentAnnotation consensus,
204           Hashtable[] hconsensus, int iStart, int width,
205           boolean ignoreGapsInConsensusCalculation,
206           boolean includeAllConsSymbols, long nseq)
207   {
208     completeConsensus(consensus, hconsensus, iStart, width,
209             ignoreGapsInConsensusCalculation, includeAllConsSymbols, null, nseq); // new
210                                                                             // char[]
211     // { 'A', 'C', 'G', 'T', 'U' });
212   }
213
214   public static void completeConsensus(AlignmentAnnotation consensus,
215           Hashtable[] hconsensus, int iStart, int width,
216           boolean ignoreGapsInConsensusCalculation,
217           boolean includeAllConsSymbols, char[] alphabet, long nseq)
218   {
219     float tval, value;
220     if (consensus == null || consensus.annotations == null
221             || consensus.annotations.length < width)
222     {
223       // called with a bad alignment annotation row - wait for it to be
224       // initialised properly
225       return;
226     }
227     String fmtstr="%3.1f";
228     int precision=2;
229     while (nseq>100) {
230       precision++;
231       nseq/=10;
232     }
233     if (precision>2)
234     {
235       fmtstr = "%"+(2+precision)+"."+precision+"f";
236     }
237     Format fmt = new Format(fmtstr);
238     for (int i = iStart; i < width; i++)
239     {
240       Hashtable hci;
241       if (i >= hconsensus.length || ((hci = hconsensus[i]) == null))
242       {
243         // happens if sequences calculated over were shorter than alignment
244         // width
245         consensus.annotations[i] = null;
246         continue;
247       }
248       value = 0;
249       Float fv;
250       if (ignoreGapsInConsensusCalculation)
251       {
252         fv = (Float) hci.get(AAFrequency.PID_NOGAPS);
253       }
254       else
255       {
256         fv = (Float) hci.get(AAFrequency.PID_GAPS);
257       }
258       if (fv == null)
259       {
260         consensus.annotations[i] = null;
261         // data has changed below us .. give up and
262         continue;
263       }
264       value = fv.floatValue();
265       String maxRes = hci.get(AAFrequency.MAXRESIDUE).toString();
266       String mouseOver = hci.get(AAFrequency.MAXRESIDUE) + " ";
267       if (maxRes.length() > 1)
268       {
269         mouseOver = "[" + maxRes + "] ";
270         maxRes = "+";
271       }
272       int[][] profile = (int[][]) hci.get(AAFrequency.PROFILE);
273       if (profile != null && includeAllConsSymbols)
274       {
275         mouseOver = "";
276         if (alphabet != null)
277         {
278           for (int c = 0; c < alphabet.length; c++)
279           {
280             tval = profile[0][alphabet[c]] * 100f
281                     / profile[1][ignoreGapsInConsensusCalculation ? 1 : 0];
282             mouseOver += ((c == 0) ? "" : "; ") + alphabet[c] + " "
283                     + fmt.form(tval) + "%";
284           }
285         }
286         else
287         {
288           Object[] ca = new Object[profile[0].length];
289           float[] vl = new float[profile[0].length];
290           for (int c = 0; c < ca.length; c++)
291           {
292             ca[c] = new char[]
293             { (char) c };
294             vl[c] = profile[0][c];
295           }
296           ;
297           jalview.util.QuickSort.sort(vl, ca);
298           for (int p = 0, c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
299           {
300             if (((char[]) ca[c])[0] != '-')
301             {
302               tval = profile[0][((char[]) ca[c])[0]]
303                       * 100f
304                       / profile[1][ignoreGapsInConsensusCalculation ? 1 : 0];
305               mouseOver += ((p == 0) ? "" : "; ") + ((char[]) ca[c])[0]
306                       + " " + fmt.form(tval) + "%";
307               p++;
308
309             }
310           }
311
312         }
313       }
314       else
315       {
316         mouseOver += (fmt.form(value) + "%");
317       }
318       consensus.annotations[i] = new Annotation(maxRes, mouseOver, ' ',
319               value);
320     }
321   }
322
323   /**
324    * get the sorted profile for the given position of the consensus
325    * 
326    * @param hconsensus
327    * @return
328    */
329   public static int[] extractProfile(Hashtable hconsensus,
330           boolean ignoreGapsInConsensusCalculation)
331   {
332     int[] rtnval = new int[64];
333     int[][] profile = (int[][]) hconsensus.get(AAFrequency.PROFILE);
334     if (profile == null)
335       return null;
336     Object[] ca = new Object[profile[0].length];
337     float[] vl = new float[profile[0].length];
338     for (int c = 0; c < ca.length; c++)
339     {
340       ca[c] = new char[]
341       { (char) c };
342       vl[c] = profile[0][c];
343     }
344     ;
345     jalview.util.QuickSort.sort(vl, ca);
346     rtnval[0] = 2;
347     rtnval[1] = 0;
348     for (int c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
349     {
350       if (((char[]) ca[c])[0] != '-')
351       {
352         rtnval[rtnval[0]++] = ((char[]) ca[c])[0];
353         rtnval[rtnval[0]] = (int) (profile[0][((char[]) ca[c])[0]] * 100f / profile[1][ignoreGapsInConsensusCalculation ? 1
354                 : 0]);
355         rtnval[1] += rtnval[rtnval[0]++];
356       }
357     }
358     return rtnval;
359   }
360 }