JAL-885; Implementation of StructureFrequency.java and according
[jalview.git] / src / jalview / analysis / AAFrequency.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, 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         System.out.println("AAFrequence.calculate");
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) / (float) jSize;
176       residueHash.put(PID_GAPS, new Float(percentage));
177
178       percentage = ((float) maxCount * 100) / (float) 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       if (i >= hconsensus.length)
223       {
224         // happens if sequences calculated over were shorter than alignment
225         // width
226         consensus.annotations[i] = null;
227         continue;
228       }
229       value = 0;
230       if (ignoreGapsInConsensusCalculation)
231       {
232         value = ((Float) hconsensus[i].get(AAFrequency.PID_NOGAPS))
233                 .floatValue();
234       }
235       else
236       {
237         value = ((Float) hconsensus[i].get(AAFrequency.PID_GAPS))
238                 .floatValue();
239       }
240
241       String maxRes = hconsensus[i].get(AAFrequency.MAXRESIDUE).toString();
242       String mouseOver = hconsensus[i].get(AAFrequency.MAXRESIDUE) + " ";
243       if (maxRes.length() > 1)
244       {
245         mouseOver = "[" + maxRes + "] ";
246         maxRes = "+";
247       }
248       int[][] profile = (int[][]) hconsensus[i].get(AAFrequency.PROFILE);
249       if (profile != null && includeAllConsSymbols)
250       {
251         mouseOver = "";
252         if (alphabet != null)
253         {
254           for (int c = 0; c < alphabet.length; c++)
255           {
256             tval = ((float) profile[0][alphabet[c]])
257                     * 100f
258                     / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
259                             : 0];
260             mouseOver += ((c == 0) ? "" : "; ") + alphabet[c] + " "
261                     + ((int) tval) + "%";
262           }
263         }
264         else
265         {
266           Object[] ca = new Object[profile[0].length];
267           float[] vl = new float[profile[0].length];
268           for (int c = 0; c < ca.length; c++)
269           {
270             ca[c] = new char[]
271             { (char) c };
272             vl[c] = (float) profile[0][c];
273           }
274           ;
275           jalview.util.QuickSort.sort(vl, ca);
276           for (int p = 0, c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
277           {
278             if (((char[]) ca[c])[0] != '-')
279             {
280               tval = ((float) profile[0][((char[]) ca[c])[0]])
281                       * 100f
282                       / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
283                               : 0];
284               mouseOver += ((p == 0) ? "" : "; ") + ((char[]) ca[c])[0]
285                       + " " + ((int) tval) + "%";
286               p++;
287
288             }
289           }
290
291         }
292       }
293       else
294       {
295         mouseOver += ((int) value + "%");
296       }
297       consensus.annotations[i] = new Annotation(maxRes, mouseOver, ' ',
298               value);
299     }
300   }
301
302   /**
303    * get the sorted profile for the given position of the consensus
304    * 
305    * @param hconsensus
306    * @return
307    */
308   public static int[] extractProfile(Hashtable hconsensus,
309           boolean ignoreGapsInConsensusCalculation)
310   {
311     int[] rtnval = new int[64];
312     int[][] profile = (int[][]) hconsensus.get(AAFrequency.PROFILE);
313     if (profile == null)
314       return null;
315     Object[] ca = new Object[profile[0].length];
316     float[] vl = new float[profile[0].length];
317     for (int c = 0; c < ca.length; c++)
318     {
319       ca[c] = new char[]
320       { (char) c };
321       vl[c] = (float) profile[0][c];
322     }
323     ;
324     jalview.util.QuickSort.sort(vl, ca);
325     rtnval[0] = 1;
326     for (int c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
327     {
328       if (((char[]) ca[c])[0] != '-')
329       {
330         rtnval[rtnval[0]++] = ((char[]) ca[c])[0];
331         rtnval[rtnval[0]++] = (int) (((float) profile[0][((char[]) ca[c])[0]]) * 100f / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
332                 : 0]);
333       }
334     }
335     return rtnval;
336   }
337 }