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