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