update author list in license for (JAL-826)
[jalview.git] / src / jalview / analysis / AAFrequency.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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(Vector sequences, int start,
48           int end)
49   {
50     return calculate(sequences, start, end, false);
51   }
52
53   public static final Hashtable[] calculate(Vector sequences, int start,
54           int end, boolean profile)
55   {
56     SequenceI[] seqs = new SequenceI[sequences.size()];
57     int width = 0;
58     for (int i = 0; i < sequences.size(); i++)
59     {
60       seqs[i] = (SequenceI) sequences.elementAt(i);
61       if (seqs[i].getLength() > width)
62       {
63         width = seqs[i].getLength();
64       }
65     }
66
67     Hashtable[] reply = new Hashtable[width];
68
69     if (end >= width)
70     {
71       end = width;
72     }
73
74     calculate(seqs, start, end, reply, profile);
75
76     return reply;
77   }
78
79   public static final void calculate(SequenceI[] sequences, int start,
80           int end, Hashtable[] result)
81   {
82     calculate(sequences, start, end, result, false);
83   }
84
85   public static final void calculate(SequenceI[] sequences, int start,
86           int end, Hashtable[] result, boolean profile)
87   {
88     Hashtable residueHash;
89     int maxCount, nongap, i, j, v, jSize = sequences.length;
90     String maxResidue;
91     char c;
92     float percentage;
93
94     int[] values = new int[255];
95
96     char[] seq;
97
98     for (i = start; i < end; i++)
99     {
100       residueHash = new Hashtable();
101       maxCount = 0;
102       maxResidue = "";
103       nongap = 0;
104       values = new int[255];
105
106       for (j = 0; j < jSize; j++)
107       {
108         if (sequences[j]==null)
109         {
110           System.err.println("WARNING: Consensus skipping null sequence - possible race condition.");
111           continue;
112         }
113         seq = sequences[j].getSequence();
114         if (seq.length > i)
115         {
116           c = seq[i];
117
118           if (c == '.' || c == ' ')
119           {
120             c = '-';
121           }
122
123           if (c == '-')
124           {
125             values['-']++;
126             continue;
127           }
128           else if ('a' <= c && c <= 'z')
129           {
130             c -= 32; // ('a' - 'A');
131           }
132
133           nongap++;
134           values[c]++;
135
136         }
137         else
138         {
139           values['-']++;
140         }
141       }
142
143       for (v = 'A'; v < 'Z'; v++)
144       {
145         if (values[v] < 2 || values[v] < maxCount)
146         {
147           continue;
148         }
149
150         if (values[v] > maxCount)
151         {
152           maxResidue = String.valueOf((char) v);
153         }
154         else if (values[v] == maxCount)
155         {
156           maxResidue += String.valueOf((char) v);
157         }
158         maxCount = values[v];
159       }
160
161       if (maxResidue.length() == 0)
162       {
163         maxResidue = "-";
164       }
165       if (profile)
166       {
167         residueHash.put(PROFILE, new int[][]
168         { values, new int[]
169         { jSize, nongap } });
170       }
171       residueHash.put(MAXCOUNT, new Integer(maxCount));
172       residueHash.put(MAXRESIDUE, maxResidue);
173
174       percentage = ((float) maxCount * 100) / (float) jSize;
175       residueHash.put(PID_GAPS, new Float(percentage));
176
177       percentage = ((float) maxCount * 100) / (float) nongap;
178       residueHash.put(PID_NOGAPS, new Float(percentage));
179       result[i] = residueHash;
180     }
181   }
182
183   /**
184    * Compute all or part of the annotation row from the given consensus
185    * hashtable
186    * 
187    * @param consensus
188    *          - pre-allocated annotation row
189    * @param hconsensus
190    * @param iStart
191    * @param width
192    * @param ignoreGapsInConsensusCalculation
193    * @param includeAllConsSymbols
194    */
195   public static void completeConsensus(AlignmentAnnotation consensus,
196           Hashtable[] hconsensus, int iStart, int width,
197           boolean ignoreGapsInConsensusCalculation,
198           boolean includeAllConsSymbols)
199   {
200     completeConsensus(consensus, hconsensus, iStart, width,
201             ignoreGapsInConsensusCalculation, includeAllConsSymbols, null); // new
202                                                                             // char[]
203     // { 'A', 'C', 'G', 'T', 'U' });
204   }
205
206   public static void completeConsensus(AlignmentAnnotation consensus,
207           Hashtable[] hconsensus, int iStart, int width,
208           boolean ignoreGapsInConsensusCalculation,
209           boolean includeAllConsSymbols, char[] alphabet)
210   {
211     float tval, value;
212     if (consensus == null || consensus.annotations == null
213             || consensus.annotations.length < width)
214     {
215       // called with a bad alignment annotation row - wait for it to be
216       // initialised properly
217       return;
218     }
219     for (int i = iStart; i < width; i++)
220     {
221       if (i >= hconsensus.length)
222       {
223         // happens if sequences calculated over were shorter than alignment
224         // width
225         consensus.annotations[i] = null;
226         continue;
227       }
228       value = 0;
229       if (ignoreGapsInConsensusCalculation)
230       {
231         value = ((Float) hconsensus[i].get(AAFrequency.PID_NOGAPS))
232                 .floatValue();
233       }
234       else
235       {
236         value = ((Float) hconsensus[i].get(AAFrequency.PID_GAPS))
237                 .floatValue();
238       }
239
240       String maxRes = hconsensus[i].get(AAFrequency.MAXRESIDUE).toString();
241       String mouseOver = hconsensus[i].get(AAFrequency.MAXRESIDUE) + " ";
242       if (maxRes.length() > 1)
243       {
244         mouseOver = "[" + maxRes + "] ";
245         maxRes = "+";
246       }
247       int[][] profile = (int[][]) hconsensus[i].get(AAFrequency.PROFILE);
248       if (profile != null && includeAllConsSymbols)
249       {
250         mouseOver = "";
251         if (alphabet != null)
252         {
253           for (int c = 0; c < alphabet.length; c++)
254           {
255             tval = ((float) profile[0][alphabet[c]])
256                     * 100f
257                     / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
258                             : 0];
259             mouseOver += ((c == 0) ? "" : "; ") + alphabet[c] + " "
260                     + ((int) tval) + "%";
261           }
262         }
263         else
264         {
265           Object[] ca = new Object[profile[0].length];
266           float[] vl = new float[profile[0].length];
267           for (int c = 0; c < ca.length; c++)
268           {
269             ca[c] = new char[]
270             { (char) c };
271             vl[c] = (float) profile[0][c];
272           }
273           ;
274           jalview.util.QuickSort.sort(vl, ca);
275           for (int p = 0, c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
276           {
277             if (((char[]) ca[c])[0] != '-')
278             {
279               tval = ((float) profile[0][((char[]) ca[c])[0]])
280                       * 100f
281                       / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
282                               : 0];
283               mouseOver += ((p == 0) ? "" : "; ") + ((char[]) ca[c])[0]
284                       + " " + ((int) tval) + "%";
285               p++;
286
287             }
288           }
289
290         }
291       }
292       else
293       {
294         mouseOver += ((int) value + "%");
295       }
296       consensus.annotations[i] = new Annotation(maxRes, mouseOver, ' ',
297               value);
298     }
299   }
300
301   /**
302    * get the sorted profile for the given position of the consensus
303    * 
304    * @param hconsensus
305    * @return
306    */
307   public static int[] extractProfile(Hashtable hconsensus,
308           boolean ignoreGapsInConsensusCalculation)
309   {
310     int[] rtnval = new int[64];
311     int[][] profile = (int[][]) hconsensus.get(AAFrequency.PROFILE);
312     if (profile == null)
313       return null;
314     Object[] ca = new Object[profile[0].length];
315     float[] vl = new float[profile[0].length];
316     for (int c = 0; c < ca.length; c++)
317     {
318       ca[c] = new char[]
319       { (char) c };
320       vl[c] = (float) profile[0][c];
321     }
322     ;
323     jalview.util.QuickSort.sort(vl, ca);
324     rtnval[0] = 1;
325     for (int c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
326     {
327       if (((char[]) ca[c])[0] != '-')
328       {
329         rtnval[rtnval[0]++] = ((char[]) ca[c])[0];
330         rtnval[rtnval[0]++] = (int) (((float) profile[0][((char[]) ca[c])[0]]) * 100f / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
331                 : 0]);
332       }
333     }
334     return rtnval;
335   }
336 }