JAL-885; StructureConservation row is displayed at the bottom of the
[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   /**
185    * Method to calculate a 'base pair consensus row', very similar 
186    * to nucleotide consensus but takes into account a given structure
187    * @param sequences
188    * @param start
189    * @param end
190    * @param result
191    * @param profile
192    * @param rnaStruc
193    */
194   public static final void calculate(SequenceI[] sequences, int start,
195                   int end, Hashtable[] result, boolean profile, AlignmentAnnotation rnaStruc){
196
197           Hashtable residueHash;
198           String maxResidue;
199           char[] seq, struc=rnaStruc.getRNAStruc().toCharArray();
200           SequenceFeature[] rna =rnaStruc._rnasecstr;
201           char c,s,cEnd;
202           int count,nonGap=0,i,bpEnd=-1,j,jSize = sequences.length;
203           int[] values = new int[255];
204           float percentage;
205           
206           for (i = start; i < end; i++) //foreach column
207           {
208                   residueHash = new Hashtable();
209                   maxResidue="";
210                   values = new int[255];
211                   bpEnd=-1;
212
213                   s = struc[i];
214                   if (s == '.' || s == ' ')
215                   {
216                           s = '-';
217                   }
218
219                   if(s == '-'){
220                           values['-']++;
221                   }
222                   else
223                   {
224                           for (j = 0; j < jSize; j++) //foreach row
225                           {
226                                   if (sequences[j]==null)
227                                   {
228                                           System.err.println("WARNING: Consensus skipping null sequence - possible race condition.");
229                                           continue;
230                                   }
231                                   seq = sequences[j].getSequence();
232                                   
233                                   if (seq.length > i)
234                                   {
235                                           c = seq[i];
236
237                                           //standard representation for gaps in sequence and structure
238                                           if (c == '.' || c == ' ')
239                                           {
240                                                   c = '-';
241                                           }
242
243                                           if (c == '-')
244                                           {
245                                                   values['-']++;
246                                                   continue;
247                                           }
248                                           if(s == '('){
249                                                   bpEnd=rna[(rna.length-1-nonGap)].getEnd();              
250                                                   cEnd=seq[bpEnd];
251                                                   if(checkBpType(c,cEnd)){
252                                                           values['H']++; //H means it's a helix (structured)
253                                                   }
254                                           }
255                                   }
256                           }
257                           nonGap++;
258                   }
259                   /*UPDATE this for new values
260               if (profile)
261               {
262                 residueHash.put(PROFILE, new int[][]
263                 { values, new int[]
264                 { jSize, nongap } });
265               }
266                    */
267
268                   count=values['H'];
269                   
270                   if (count == 0)
271                   {
272                           maxResidue = "-";
273                   }else{
274                           maxResidue="H";
275                   }
276                   
277                   residueHash.put(MAXCOUNT, new Integer(count));
278               residueHash.put(MAXRESIDUE, maxResidue);
279               
280                   percentage = ((float) count * 100) / (float) jSize;
281                   residueHash.put(PID_GAPS, new Float(percentage));
282
283                   //percentage = ((float) count * 100) / (float) nongap;
284                   //residueHash.put(PID_NOGAPS, new Float(percentage));
285                   if(result[i]==null){
286                           result[i] = residueHash;
287                   }
288                   if(bpEnd>0){
289                           result[bpEnd]=residueHash;
290                   }
291
292           }
293   }
294
295          
296   /**
297    * Method to check if a base-pair is a canonical or a wobble bp 
298    * @param up 5' base
299    * @param down 3' base
300    * @return True if it is a canonical/wobble bp
301    */
302   public static boolean checkBpType(char up, char down){
303           if(up>'Z'){up-=32;}
304           if(down>'Z'){down-=32;}
305           
306           switch (up){
307                 case 'A': 
308                         switch (down){
309                                 case 'T': return true;
310                                 case 'U': return true;
311                         }
312                 break;
313                 case 'C': 
314                         switch (down){
315                                 case 'G': return true;
316                         }
317                 break;
318                 case 'T': 
319                         switch (down){
320                                 case 'A': return true;
321                                 case 'G': return true;
322                                 }
323                 break;
324                 case 'G': 
325                         switch (down){
326                                 case 'C': return true;
327                                 case 'T': return true;
328                                 case 'U': return true;
329                         }
330                 break;
331                 case 'U': 
332                         switch (down){
333                                 case 'A': return true;
334                                 case 'G': return true;
335                         }
336                 break;
337           }       
338           return false;
339   }
340   
341   /**
342    * Compute all or part of the annotation row from the given consensus
343    * hashtable
344    * 
345    * @param consensus
346    *          - pre-allocated annotation row
347    * @param hconsensus
348    * @param iStart
349    * @param width
350    * @param ignoreGapsInConsensusCalculation
351    * @param includeAllConsSymbols
352    */
353   public static void completeConsensus(AlignmentAnnotation consensus,
354           Hashtable[] hconsensus, int iStart, int width,
355           boolean ignoreGapsInConsensusCalculation,
356           boolean includeAllConsSymbols)
357   {
358     completeConsensus(consensus, hconsensus, iStart, width,
359             ignoreGapsInConsensusCalculation, includeAllConsSymbols, null); // new
360                                                                             // char[]
361     // { 'A', 'C', 'G', 'T', 'U' });
362   }
363
364   public static void completeConsensus(AlignmentAnnotation consensus,
365           Hashtable[] hconsensus, int iStart, int width,
366           boolean ignoreGapsInConsensusCalculation,
367           boolean includeAllConsSymbols, char[] alphabet)
368   {
369     float tval, value;
370     if (consensus == null || consensus.annotations == null
371             || consensus.annotations.length < width)
372     {
373       // called with a bad alignment annotation row - wait for it to be
374       // initialised properly
375       return;
376     }
377     for (int i = iStart; i < width; i++)
378     {
379       if (i >= hconsensus.length)
380       {
381         // happens if sequences calculated over were shorter than alignment
382         // width
383         consensus.annotations[i] = null;
384         continue;
385       }
386       value = 0;
387       if (ignoreGapsInConsensusCalculation)
388       {
389         value = ((Float) hconsensus[i].get(StructureFrequency.PID_NOGAPS))
390                 .floatValue();
391       }
392       else
393       {
394         value = ((Float) hconsensus[i].get(StructureFrequency.PID_GAPS))
395                 .floatValue();
396       }
397       
398       String maxRes = hconsensus[i].get(StructureFrequency.MAXRESIDUE).toString();
399       String mouseOver = hconsensus[i].get(StructureFrequency.MAXRESIDUE) + " ";
400       if (maxRes.length() > 1)
401       {
402         mouseOver = "[" + maxRes + "] ";
403         maxRes = "+";
404       }
405       int[][] profile = (int[][]) hconsensus[i].get(StructureFrequency.PROFILE);
406       if (profile != null && includeAllConsSymbols)
407       {
408         mouseOver = "";
409         if (alphabet != null)
410         {
411           for (int c = 0; c < alphabet.length; c++)
412           {
413             tval = ((float) profile[0][alphabet[c]])
414                     * 100f
415                     / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
416                             : 0];
417             mouseOver += ((c == 0) ? "" : "; ") + alphabet[c] + " "
418                     + ((int) tval) + "%";
419           }
420         }
421         else
422         {
423           Object[] ca = new Object[profile[0].length];
424           float[] vl = new float[profile[0].length];
425           for (int c = 0; c < ca.length; c++)
426           {
427             ca[c] = new char[]
428             { (char) c };
429             vl[c] = (float) profile[0][c];
430           }
431           ;
432           jalview.util.QuickSort.sort(vl, ca);
433           for (int p = 0, c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
434           {
435             if (((char[]) ca[c])[0] != '-')
436             {
437               tval = ((float) profile[0][((char[]) ca[c])[0]])
438                       * 100f
439                       / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
440                               : 0];
441               mouseOver += ((p == 0) ? "" : "; ") + ((char[]) ca[c])[0]
442                       + " " + ((int) tval) + "%";
443               p++;
444
445             }
446           }
447
448         }
449       }
450       else
451       {
452         mouseOver += ((int) value + "%");
453       }
454       consensus.annotations[i] = new Annotation(maxRes, mouseOver, ' ',
455               value);
456     }
457   }
458
459   /**
460    * get the sorted profile for the given position of the consensus
461    * 
462    * @param hconsensus
463    * @return
464    */
465   public static int[] extractProfile(Hashtable hconsensus,
466           boolean ignoreGapsInConsensusCalculation)
467   {
468     int[] rtnval = new int[64];
469     int[][] profile = (int[][]) hconsensus.get(StructureFrequency.PROFILE);
470     if (profile == null)
471       return null;
472     Object[] ca = new Object[profile[0].length];
473     float[] vl = new float[profile[0].length];
474     for (int c = 0; c < ca.length; c++)
475     {
476       ca[c] = new char[]
477       { (char) c };
478       vl[c] = (float) profile[0][c];
479     }
480     ;
481     jalview.util.QuickSort.sort(vl, ca);
482     rtnval[0] = 1;
483     for (int c = ca.length - 1; profile[0][((char[]) ca[c])[0]] > 0; c--)
484     {
485       if (((char[]) ca[c])[0] != '-')
486       {
487         rtnval[rtnval[0]++] = ((char[]) ca[c])[0];
488         rtnval[rtnval[0]++] = (int) (((float) profile[0][((char[]) ca[c])[0]]) * 100f / (float) profile[1][ignoreGapsInConsensusCalculation ? 1
489                 : 0]);
490       }
491     }
492     return rtnval;
493   }
494
495   enum base {A,T,g,C};
496  
497   
498   public static void main(String args[]){
499           //Short test to see if checkBpType works
500           ArrayList<String> test = new ArrayList<String>();
501           test.add("A");
502           test.add("c");
503           test.add("g");
504           test.add("T");
505           test.add("U");
506           for (String i : test) {
507                   for (String j : test) {
508                           System.out.println(i+"-"+j+": "+StructureFrequency.checkBpType(i.charAt(0),j.charAt(0)));
509                   }
510           }
511   }
512 }