JAL-2089 patch broken merge to master for Release 2.10.0b1
[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, canonical = 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               canonicalOrWobblePairCount++;
180               if (Rna.isCanonicalPair(c, cEnd))
181               {
182                 canonical++;
183               }
184             }
185             else
186             {
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       values['('] = canonicalOrWobblePairCount;
204       values['['] = canonical;
205       values['{'] = otherPairCount;
206       /*
207        * the count is the number of valid pairs (as a percentage, determines
208        * the relative size of the profile logo)
209        */
210       int count = canonicalOrWobblePairCount;
211
212       /*
213        * display '(' if most pairs are canonical, or as
214        * '[' if there are more wobble pairs. 
215        */
216       if (canonicalOrWobblePairCount > 0 || otherPairCount > 0)
217       {
218         if (canonicalOrWobblePairCount >= otherPairCount)
219         {
220           maxResidue = (canonicalOrWobblePairCount - canonical) < canonical ? "("
221                   : "[";
222         }
223         else
224         {
225           maxResidue = "{";
226         }
227       }
228       residueHash.put(MAXCOUNT, new Integer(count));
229       residueHash.put(MAXRESIDUE, maxResidue);
230
231       percentage = ((float) count * 100) / jSize;
232       residueHash.put(PID_GAPS, new Float(percentage));
233
234       percentage = ((float) count * 100) / nongap;
235       residueHash.put(PID_NOGAPS, new Float(percentage));
236
237       if (result[i] == null)
238       {
239         result[i] = residueHash;
240       }
241       if (bpEnd > 0)
242       {
243         values[')'] = values['('];
244         values[']'] = values['['];
245         values['}'] = values['{'];
246         values['('] = 0;
247         values['['] = 0;
248         values['{'] = 0;
249         maxResidue = maxResidue.equals("(") ? ")"
250                 : maxResidue.equals("[") ? "]" : "}";
251
252         residueHash = new Hashtable();
253         if (profile)
254         {
255           residueHash.put(PROFILE, new int[][] { values,
256               new int[] { jSize, (jSize - values['-']) } });
257
258           residueHash.put(PAIRPROFILE, pairs);
259         }
260
261         residueHash.put(MAXCOUNT, new Integer(count));
262         residueHash.put(MAXRESIDUE, maxResidue);
263
264         percentage = ((float) count * 100) / jSize;
265         residueHash.put(PID_GAPS, new Float(percentage));
266
267         percentage = ((float) count * 100) / nongap;
268         residueHash.put(PID_NOGAPS, new Float(percentage));
269
270         result[bpEnd] = residueHash;
271       }
272     }
273   }
274
275   /**
276    * Compute all or part of the annotation row from the given consensus
277    * hashtable
278    * 
279    * @param consensus
280    *          - pre-allocated annotation row
281    * @param hconsensus
282    * @param iStart
283    * @param width
284    * @param ignoreGapsInConsensusCalculation
285    * @param includeAllConsSymbols
286    */
287   public static void completeConsensus(AlignmentAnnotation consensus,
288           Hashtable[] hconsensus, int iStart, int width,
289           boolean ignoreGapsInConsensusCalculation,
290           boolean includeAllConsSymbols, long nseq)
291   {
292     float tval, value;
293     if (consensus == null || consensus.annotations == null
294             || consensus.annotations.length < width)
295     {
296       // called with a bad alignment annotation row - wait for it to be
297       // initialised properly
298       return;
299     }
300     String fmtstr = "%3.1f";
301     int precision = 2;
302     while (nseq > 100)
303     {
304       precision++;
305       nseq /= 10;
306     }
307     if (precision > 2)
308     {
309       fmtstr = "%" + (2 + precision) + "." + precision + "f";
310     }
311     Format fmt = new Format(fmtstr);
312
313     for (int i = iStart; i < width; i++)
314     {
315       Hashtable hci;
316       if (i >= hconsensus.length || ((hci = hconsensus[i]) == null))
317       {
318         // happens if sequences calculated over were shorter than alignment
319         // width
320         consensus.annotations[i] = null;
321         continue;
322       }
323       value = 0;
324       Float fv;
325       if (ignoreGapsInConsensusCalculation)
326       {
327         fv = (Float) hci.get(StructureFrequency.PID_NOGAPS);
328       }
329       else
330       {
331         fv = (Float) hci.get(StructureFrequency.PID_GAPS);
332       }
333       if (fv == null)
334       {
335         consensus.annotations[i] = null;
336         // data has changed below us .. give up and
337         continue;
338       }
339       value = fv.floatValue();
340       String maxRes = hci.get(StructureFrequency.MAXRESIDUE).toString();
341       String mouseOver = hci.get(StructureFrequency.MAXRESIDUE) + " ";
342       if (maxRes.length() > 1)
343       {
344         mouseOver = "[" + maxRes + "] ";
345         maxRes = "+";
346       }
347       int[][] profile = (int[][]) hci.get(StructureFrequency.PROFILE);
348       int[][] pairs = (int[][]) hci.get(StructureFrequency.PAIRPROFILE);
349
350       if (pairs != null && includeAllConsSymbols) // Just responsible for the
351       // tooltip
352       // TODO Update tooltips for Structure row
353       {
354         mouseOver = "";
355
356         /*
357          * TODO It's not sure what is the purpose of the alphabet and wheter it
358          * is useful for structure?
359          * 
360          * if (alphabet != null) { for (int c = 0; c < alphabet.length; c++) {
361          * tval = ((float) profile[0][alphabet[c]]) 100f / (float)
362          * profile[1][ignoreGapsInConsensusCalculation ? 1 : 0]; mouseOver +=
363          * ((c == 0) ? "" : "; ") + alphabet[c] + " " + ((int) tval) + "%"; } }
364          * else {
365          */
366         int[][] ca = new int[625][];
367         float[] vl = new float[625];
368         int x = 0;
369         for (int c = 65; c < 90; c++)
370         {
371           for (int d = 65; d < 90; d++)
372           {
373             ca[x] = new int[] { c, d };
374             vl[x] = pairs[c][d];
375             x++;
376           }
377         }
378         jalview.util.QuickSort.sort(vl, ca);
379         int p = 0;
380
381         /*
382          * profile[1] is {total, ungappedTotal}
383          */
384         final int divisor = profile[1][ignoreGapsInConsensusCalculation ? 1
385                 : 0];
386         for (int c = 624; c > 0; c--)
387         {
388           if (vl[c] > 0)
389           {
390             tval = (vl[c] * 100f / divisor);
391             mouseOver += ((p == 0) ? "" : "; ") + (char) ca[c][0]
392                     + (char) ca[c][1] + " " + fmt.form(tval) + "%";
393             p++;
394
395           }
396         }
397
398         // }
399       }
400       else
401       {
402         mouseOver += (fmt.form(value) + "%");
403       }
404       consensus.annotations[i] = new Annotation(maxRes, mouseOver, ' ',
405               value);
406     }
407   }
408
409   /**
410    * get the sorted base-pair profile for the given position of the consensus
411    * 
412    * @param hconsensus
413    * @return profile of the given column
414    */
415   public static int[] extractProfile(Hashtable hconsensus,
416           boolean ignoreGapsInConsensusCalculation)
417   {
418     int[] rtnval = new int[STRUCTURE_PROFILE_LENGTH]; // 2*(5*5)+2
419     int[][] profile = (int[][]) hconsensus.get(StructureFrequency.PROFILE);
420     int[][] pairs = (int[][]) hconsensus
421             .get(StructureFrequency.PAIRPROFILE);
422
423     if (profile == null)
424     {
425       return null;
426     }
427
428     // TODO fix the object length, also do it in completeConsensus
429     // Object[] ca = new Object[625];
430     int[][] ca = new int[625][];
431     float[] vl = new float[625];
432     int x = 0;
433     for (int c = 65; c < 90; c++)
434     {
435       for (int d = 65; d < 90; d++)
436       {
437         ca[x] = new int[] { c, d };
438         vl[x] = pairs[c][d];
439         x++;
440       }
441     }
442     jalview.util.QuickSort.sort(vl, ca);
443
444     int valuesCount = 0;
445     rtnval[1] = 0;
446     int offset = 2;
447     final int divisor = profile[1][ignoreGapsInConsensusCalculation ? 1 : 0];
448     for (int c = 624; c > 0; c--)
449     {
450       if (vl[c] > 0)
451       {
452         rtnval[offset++] = ca[c][0];
453         rtnval[offset++] = ca[c][1];
454         rtnval[offset] = (int) (vl[c] * 100f / divisor);
455         rtnval[1] += rtnval[offset++];
456         valuesCount++;
457       }
458     }
459     rtnval[0] = valuesCount;
460
461     // insert profile type code in position 0
462     int[] result = new int[rtnval.length + 1];
463     result[0] = AlignmentAnnotation.STRUCTURE_PROFILE;
464     System.arraycopy(rtnval, 0, result, 1, rtnval.length);
465     return result;
466   }
467
468   public static void main(String args[])
469   {
470     // Short test to see if checkBpType works
471     ArrayList<String> test = new ArrayList<String>();
472     test.add("A");
473     test.add("c");
474     test.add("g");
475     test.add("T");
476     test.add("U");
477     for (String i : test)
478     {
479       for (String j : test)
480       {
481         System.out.println(i + "-" + j + ": "
482                 + Rna.isCanonicalOrWobblePair(i.charAt(0), j.charAt(0)));
483       }
484     }
485   }
486 }