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