JAL-1503 update version in GPL header
[jalview.git] / src / jalview / analysis / AAFrequency.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
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         // calculate for non-gapped too
187         percentage = ((float) maxCount * 100) / nongap;
188       }
189       residueHash.put(PID_NOGAPS, new Float(percentage));
190       
191       result[i] = residueHash;
192     }
193   }
194
195   /**
196    * Compute all or part of the annotation row from the given consensus
197    * hashtable
198    * 
199    * @param consensus
200    *          - pre-allocated annotation row
201    * @param hconsensus
202    * @param iStart
203    * @param width
204    * @param ignoreGapsInConsensusCalculation
205    * @param includeAllConsSymbols
206    * @param nseq 
207    */
208   public static void completeConsensus(AlignmentAnnotation consensus,
209           Hashtable[] hconsensus, int iStart, int width,
210           boolean ignoreGapsInConsensusCalculation,
211           boolean includeAllConsSymbols, long nseq)
212   {
213     completeConsensus(consensus, hconsensus, iStart, width,
214             ignoreGapsInConsensusCalculation, includeAllConsSymbols, null, nseq); // new
215                                                                             // char[]
216     // { 'A', 'C', 'G', 'T', 'U' });
217   }
218
219   public static void completeConsensus(AlignmentAnnotation consensus,
220           Hashtable[] hconsensus, int iStart, int width,
221           boolean ignoreGapsInConsensusCalculation,
222           boolean includeAllConsSymbols, char[] alphabet, long nseq)
223   {
224     float tval, value;
225     if (consensus == null || consensus.annotations == null
226             || consensus.annotations.length < width)
227     {
228       // called with a bad alignment annotation row - wait for it to be
229       // initialised properly
230       return;
231     }
232     String fmtstr="%3.1f";
233     int precision=0;
234     while (nseq>=10) {
235       precision++;
236       nseq/=10;
237     }
238     final Format fmt;
239     if (precision>1)
240     {
241       //if (precision>2)
242       {
243         fmtstr = "%"+(2+precision)+"."+(precision)+"f";
244       }
245       fmt = new Format(fmtstr);
246     } else {
247       fmt = null;
248     }
249     for (int i = iStart; i < width; i++)
250     {
251       Hashtable hci;
252       if (i >= hconsensus.length || ((hci = hconsensus[i]) == null))
253       {
254         // happens if sequences calculated over were shorter than alignment
255         // width
256         consensus.annotations[i] = null;
257         continue;
258       }
259       value = 0;
260       Float fv;
261       if (ignoreGapsInConsensusCalculation)
262       {
263         fv = (Float) hci.get(AAFrequency.PID_NOGAPS);
264       }
265       else
266       {
267         fv = (Float) hci.get(AAFrequency.PID_GAPS);
268       }
269       if (fv == null)
270       {
271         consensus.annotations[i] = null;
272         // data has changed below us .. give up and
273         continue;
274       }
275       value = fv.floatValue();
276       String maxRes = hci.get(AAFrequency.MAXRESIDUE).toString();
277       String mouseOver = hci.get(AAFrequency.MAXRESIDUE) + " ";
278       if (maxRes.length() > 1)
279       {
280         mouseOver = "[" + maxRes + "] ";
281         maxRes = "+";
282       }
283       int[][] profile = (int[][]) hci.get(AAFrequency.PROFILE);
284       if (profile != null && includeAllConsSymbols)
285       {
286         mouseOver = "";
287         if (alphabet != null)
288         {
289           for (int c = 0; c < alphabet.length; c++)
290           {
291             tval = profile[0][alphabet[c]] * 100f
292                     / profile[1][ignoreGapsInConsensusCalculation ? 1 : 0];
293             mouseOver += ((c == 0) ? "" : "; ") + alphabet[c] + " "
294                     + ((fmt!=null) ? fmt.form(tval) : ((int) tval)) + "%";
295           }
296         }
297         else
298         {
299           Object[] ca = new Object[profile[0].length];
300           float[] vl = new float[profile[0].length];
301           for (int c = 0; c < ca.length; c++)
302           {
303             ca[c] = new char[]
304             { (char) c };
305             vl[c] = profile[0][c];
306           }
307           ;
308           jalview.util.QuickSort.sort(vl, ca);
309           for (int p = 0, c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
310           {
311             if (((char[]) ca[c])[0] != '-')
312             {
313               tval = profile[0][((char[]) ca[c])[0]]
314                       * 100f
315                       / profile[1][ignoreGapsInConsensusCalculation ? 1 : 0];
316               mouseOver += ((p == 0) ? "" : "; ") + ((char[]) ca[c])[0]
317                       + " " + ((fmt!=null) ? fmt.form(tval) : ((int) tval)) + "%";
318               p++;
319
320             }
321           }
322
323         }
324       }
325       else
326       {
327         mouseOver += ((fmt!=null) ? fmt.form(value) : ((int) value)) + "%";
328       }
329       consensus.annotations[i] = new Annotation(maxRes, mouseOver, ' ',
330               value);
331     }
332   }
333
334   /**
335    * get the sorted profile for the given position of the consensus
336    * 
337    * @param hconsensus
338    * @return
339    */
340   public static int[] extractProfile(Hashtable hconsensus,
341           boolean ignoreGapsInConsensusCalculation)
342   {
343     int[] rtnval = new int[64];
344     int[][] profile = (int[][]) hconsensus.get(AAFrequency.PROFILE);
345     if (profile == null)
346       return null;
347     Object[] ca = new Object[profile[0].length];
348     float[] vl = new float[profile[0].length];
349     for (int c = 0; c < ca.length; c++)
350     {
351       ca[c] = new char[]
352       { (char) c };
353       vl[c] = profile[0][c];
354     }
355     ;
356     jalview.util.QuickSort.sort(vl, ca);
357     rtnval[0] = 2;
358     rtnval[1] = 0;
359     for (int c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
360     {
361       if (((char[]) ca[c])[0] != '-')
362       {
363         rtnval[rtnval[0]++] = ((char[]) ca[c])[0];
364         rtnval[rtnval[0]] = (int) (profile[0][((char[]) ca[c])[0]] * 100f / profile[1][ignoreGapsInConsensusCalculation ? 1
365                 : 0]);
366         rtnval[1] += rtnval[rtnval[0]++];
367       }
368     }
369     return rtnval;
370   }
371 }