JAL-1841 JAL-2215 add the ‘ignore gaps’ structure consensus fraction
[jalview.git] / src / jalview / analysis / StructureFrequency.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.analysis;
22
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.SequenceFeature;
26 import jalview.datamodel.SequenceI;
27 import jalview.util.Comparison;
28 import jalview.util.Format;
29
30 import java.util.ArrayList;
31 import java.util.Hashtable;
32
33 /**
34  * Takes in a vector or array of sequences and column start and column end and
35  * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
36  * This class is used extensively in calculating alignment colourschemes that
37  * depend on the amount of conservation in each alignment column.
38  * 
39  * @author $author$
40  * @version $Revision$
41  */
42 public class StructureFrequency
43 {
44   public static final int STRUCTURE_PROFILE_LENGTH = 74;
45
46   // No need to store 1000s of strings which are not
47   // visible to the user.
48   public static final String MAXCOUNT = "C";
49
50   public static final String MAXRESIDUE = "R";
51
52   public static final String PID_GAPS = "G";
53
54   public static final String PID_NOGAPS = "N";
55
56   public static final String PROFILE = "P";
57
58   public static final String PAIRPROFILE = "B";
59
60   /**
61    * Returns the 3' position of a base pair
62    * 
63    * @param pairs
64    *          Secondary structure annotation
65    * @param indice
66    *          5' position of a base pair
67    * @return 3' position of a base pair
68    */
69   public static int findPair(SequenceFeature[] pairs, int indice)
70   {
71
72     for (int i = 0; i < pairs.length; i++)
73     {
74       if (pairs[i].getBegin() == indice)
75
76       {
77
78         return pairs[i].getEnd();
79
80       }
81     }
82     return -1;
83   }
84
85   /**
86    * Method to calculate a 'base pair consensus row', very similar to nucleotide
87    * consensus but takes into account a given structure
88    * 
89    * @param sequences
90    * @param start
91    * @param end
92    * @param result
93    * @param profile
94    * @param rnaStruc
95    */
96   public static final void calculate(SequenceI[] sequences, int start,
97           int end, Hashtable[] result, boolean profile,
98           AlignmentAnnotation rnaStruc)
99   {
100
101     Hashtable residueHash;
102     String maxResidue;
103     char[] struc = rnaStruc.getRNAStruc().toCharArray();
104
105     SequenceFeature[] rna = rnaStruc._rnasecstr;
106     char c, s, cEnd;
107     int bpEnd = -1;
108     int jSize = sequences.length;
109     int[] values;
110     int[][] pairs;
111     float percentage;
112
113     for (int i = start; i < end; i++) // foreach column
114     {
115       int canonicalOrWobblePairCount = 0;
116       int otherPairCount = 0;
117       int nongap = 0;
118       maxResidue = "-";
119       values = new int[255];
120       pairs = new int[255][255];
121       bpEnd = -1;
122       if (i < struc.length)
123       {
124         s = struc[i];
125       }
126       else
127       {
128         s = '-';
129       }
130       if (s == '.' || s == ' ')
131       {
132         s = '-';
133       }
134
135       if (!Rna.isOpeningParenthesis(s))
136       {
137         if (s == '-')
138         {
139           values['-']++;
140         }
141       }
142       else
143       {
144         bpEnd = findPair(rna, i);
145
146         if (bpEnd > -1)
147         {
148           for (int j = 0; j < jSize; j++) // foreach row
149           {
150             if (sequences[j] == null)
151             {
152               System.err
153                       .println("WARNING: Consensus skipping null sequence - possible race condition.");
154               continue;
155             }
156
157             c = sequences[j].getCharAt(i);
158             cEnd = sequences[j].getCharAt(bpEnd);
159
160             if (Comparison.isGap(c) || Comparison.isGap(cEnd))
161             {
162               values['-']++;
163               continue;
164             }
165             nongap++;
166             /*
167              * ensure upper-case for counting purposes
168              */
169             if ('a' <= c && 'z' >= c)
170             {
171               c += 'A' - 'a';
172             }
173             if ('a' <= cEnd && 'z' >= cEnd)
174             {
175               cEnd += 'A' - 'a';
176             }
177             if (Rna.isCanonicalOrWobblePair(c, cEnd))
178             {
179               values['(']++;
180               maxResidue = "(";
181               canonicalOrWobblePairCount++;
182             }
183             else
184             {
185               values['[']++;
186               maxResidue = "[";
187               otherPairCount++;
188             }
189             pairs[c][cEnd]++;
190           }
191         }
192       }
193
194       residueHash = new Hashtable();
195       if (profile)
196       {
197         // TODO 1-dim array with jsize in [0], nongapped in [1]; or Pojo
198         residueHash.put(PROFILE, new int[][] { values,
199             new int[] { jSize, (jSize - values['-']) } });
200
201         residueHash.put(PAIRPROFILE, pairs);
202       }
203
204       /*
205        * the count is the number of valid pairs (as a percentage, determines
206        * the relative size of the profile logo)
207        */
208       int count = canonicalOrWobblePairCount;
209
210       /*
211        * currently displaying as '(' if most pairs are valid, or as
212        * '[' if there are more invalid than valid pairs 
213        */
214       if (!maxResidue.equals("-"))
215       {
216         maxResidue = canonicalOrWobblePairCount >= otherPairCount ? "("
217                 : "[";
218       }
219       residueHash.put(MAXCOUNT, new Integer(count));
220       residueHash.put(MAXRESIDUE, maxResidue);
221
222       percentage = ((float) count * 100) / jSize;
223       residueHash.put(PID_GAPS, new Float(percentage));
224
225       percentage = ((float) count * 100) / nongap;
226       residueHash.put(PID_NOGAPS, new Float(percentage));
227
228       if (result[i] == null)
229       {
230         result[i] = residueHash;
231       }
232       if (bpEnd > 0)
233       {
234         values[')'] = values['('];
235         values[']'] = values['['];
236         values['('] = 0;
237         values['['] = 0;
238         maxResidue = maxResidue.equals("(") ? ")" : "]";
239
240         residueHash = new Hashtable();
241         if (profile)
242         {
243           residueHash.put(PROFILE, new int[][] { values,
244               new int[] { jSize, (jSize - values['-']) } });
245
246           residueHash.put(PAIRPROFILE, pairs);
247         }
248
249         residueHash.put(MAXCOUNT, new Integer(count));
250         residueHash.put(MAXRESIDUE, maxResidue);
251
252         percentage = ((float) count * 100) / jSize;
253         residueHash.put(PID_GAPS, new Float(percentage));
254
255         percentage = ((float) count * 100) / nongap;
256         residueHash.put(PID_NOGAPS, new Float(percentage));
257
258         result[bpEnd] = residueHash;
259       }
260     }
261   }
262
263   /**
264    * Compute all or part of the annotation row from the given consensus
265    * hashtable
266    * 
267    * @param consensus
268    *          - pre-allocated annotation row
269    * @param hconsensus
270    * @param iStart
271    * @param width
272    * @param ignoreGapsInConsensusCalculation
273    * @param includeAllConsSymbols
274    */
275   public static void completeConsensus(AlignmentAnnotation consensus,
276           Hashtable[] hconsensus, int iStart, int width,
277           boolean ignoreGapsInConsensusCalculation,
278           boolean includeAllConsSymbols, long nseq)
279   {
280     float tval, value;
281     if (consensus == null || consensus.annotations == null
282             || consensus.annotations.length < width)
283     {
284       // called with a bad alignment annotation row - wait for it to be
285       // initialised properly
286       return;
287     }
288     String fmtstr = "%3.1f";
289     int precision = 2;
290     while (nseq > 100)
291     {
292       precision++;
293       nseq /= 10;
294     }
295     if (precision > 2)
296     {
297       fmtstr = "%" + (2 + precision) + "." + precision + "f";
298     }
299     Format fmt = new Format(fmtstr);
300
301     for (int i = iStart; i < width; i++)
302     {
303       Hashtable hci;
304       if (i >= hconsensus.length || ((hci = hconsensus[i]) == null))
305       {
306         // happens if sequences calculated over were shorter than alignment
307         // width
308         consensus.annotations[i] = null;
309         continue;
310       }
311       value = 0;
312       Float fv;
313       if (ignoreGapsInConsensusCalculation)
314       {
315         fv = (Float) hci.get(StructureFrequency.PID_NOGAPS);
316       }
317       else
318       {
319         fv = (Float) hci.get(StructureFrequency.PID_GAPS);
320       }
321       if (fv == null)
322       {
323         consensus.annotations[i] = null;
324         // data has changed below us .. give up and
325         continue;
326       }
327       value = fv.floatValue();
328       String maxRes = hci.get(StructureFrequency.MAXRESIDUE).toString();
329       String mouseOver = hci.get(StructureFrequency.MAXRESIDUE) + " ";
330       if (maxRes.length() > 1)
331       {
332         mouseOver = "[" + maxRes + "] ";
333         maxRes = "+";
334       }
335       int[][] profile = (int[][]) hci.get(StructureFrequency.PROFILE);
336       int[][] pairs = (int[][]) hci.get(StructureFrequency.PAIRPROFILE);
337
338       if (pairs != null && includeAllConsSymbols) // Just responsible for the
339       // tooltip
340       // TODO Update tooltips for Structure row
341       {
342         mouseOver = "";
343
344         /*
345          * TODO It's not sure what is the purpose of the alphabet and wheter it
346          * is useful for structure?
347          * 
348          * if (alphabet != null) { for (int c = 0; c < alphabet.length; c++) {
349          * tval = ((float) profile[0][alphabet[c]]) 100f / (float)
350          * profile[1][ignoreGapsInConsensusCalculation ? 1 : 0]; mouseOver +=
351          * ((c == 0) ? "" : "; ") + alphabet[c] + " " + ((int) tval) + "%"; } }
352          * else {
353          */
354         int[][] ca = new int[625][];
355         float[] vl = new float[625];
356         int x = 0;
357         for (int c = 65; c < 90; c++)
358         {
359           for (int d = 65; d < 90; d++)
360           {
361             ca[x] = new int[] { c, d };
362             vl[x] = pairs[c][d];
363             x++;
364           }
365         }
366         jalview.util.QuickSort.sort(vl, ca);
367         int p = 0;
368
369         /*
370          * profile[1] is {total, ungappedTotal}
371          */
372         final int divisor = profile[1][ignoreGapsInConsensusCalculation ? 1
373                 : 0];
374         for (int c = 624; c > 0; c--)
375         {
376           if (vl[c] > 0)
377           {
378             tval = (vl[c] * 100f / divisor);
379             mouseOver += ((p == 0) ? "" : "; ") + (char) ca[c][0]
380                     + (char) ca[c][1] + " " + fmt.form(tval) + "%";
381             p++;
382
383           }
384         }
385
386         // }
387       }
388       else
389       {
390         mouseOver += (fmt.form(value) + "%");
391       }
392       consensus.annotations[i] = new Annotation(maxRes, mouseOver, ' ',
393               value);
394     }
395   }
396
397   /**
398    * get the sorted base-pair profile for the given position of the consensus
399    * 
400    * @param hconsensus
401    * @return profile of the given column
402    */
403   public static int[] extractProfile(Hashtable hconsensus,
404           boolean ignoreGapsInConsensusCalculation)
405   {
406     int[] rtnval = new int[STRUCTURE_PROFILE_LENGTH]; // 2*(5*5)+2
407     int[][] profile = (int[][]) hconsensus.get(StructureFrequency.PROFILE);
408     int[][] pairs = (int[][]) hconsensus
409             .get(StructureFrequency.PAIRPROFILE);
410
411     if (profile == null)
412     {
413       return null;
414     }
415
416     // TODO fix the object length, also do it in completeConsensus
417     // Object[] ca = new Object[625];
418     int[][] ca = new int[625][];
419     float[] vl = new float[625];
420     int x = 0;
421     for (int c = 65; c < 90; c++)
422     {
423       for (int d = 65; d < 90; d++)
424       {
425         ca[x] = new int[] { c, d };
426         vl[x] = pairs[c][d];
427         x++;
428       }
429     }
430     jalview.util.QuickSort.sort(vl, ca);
431
432     int valuesCount = 0;
433     rtnval[1] = 0;
434     int offset = 2;
435     final int divisor = profile[1][ignoreGapsInConsensusCalculation ? 1 : 0];
436     for (int c = 624; c > 0; c--)
437     {
438       if (vl[c] > 0)
439       {
440         rtnval[offset++] = ca[c][0];
441         rtnval[offset++] = ca[c][1];
442         rtnval[offset] = (int) (vl[c] * 100f / divisor);
443         rtnval[1] += rtnval[offset++];
444         valuesCount++;
445       }
446     }
447     rtnval[0] = valuesCount;
448
449     // insert profile type code in position 0
450     int[] result = new int[rtnval.length + 1];
451     result[0] = AlignmentAnnotation.STRUCTURE_PROFILE;
452     System.arraycopy(rtnval, 0, result, 1, rtnval.length);
453     return result;
454   }
455
456   public static void main(String args[])
457   {
458     // Short test to see if checkBpType works
459     ArrayList<String> test = new ArrayList<String>();
460     test.add("A");
461     test.add("c");
462     test.add("g");
463     test.add("T");
464     test.add("U");
465     for (String i : test)
466     {
467       for (String j : test)
468       {
469         System.out.println(i + "-" + j + ": "
470                 + Rna.isCanonicalOrWobblePair(i.charAt(0), j.charAt(0)));
471       }
472     }
473   }
474 }