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