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