JAL-736 hack to show the conserved property values in the tooltip
[jalview.git] / src / jalview / analysis / Conservation.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3  * Copyright (C) 2014 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 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  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 package jalview.analysis;
20
21 import java.awt.Color;
22 import java.util.*;
23
24 import jalview.datamodel.*;
25
26 /**
27  * Calculates conservation values for a given set of sequences
28  * 
29  * @author $author$
30  * @version $Revision$
31  */
32 public class Conservation
33 {
34   SequenceI[] sequences;
35
36   int start;
37
38   int end;
39
40   Vector seqNums; // vector of int vectors where first is sequence checksum
41
42   int maxLength = 0; // used by quality calcs
43
44   boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
45
46   Hashtable[] total;
47
48   boolean canonicaliseAa = true; // if true then conservation calculation will
49
50   // map all symbols to canonical aa numbering
51   // rather than consider conservation of that
52   // symbol
53
54   /** Stores calculated quality values */
55   public Vector quality;
56
57   /** Stores maximum and minimum values of quality values */
58   public Double[] qualityRange = new Double[2];
59
60   String consString = "";
61
62   Sequence consSequence;
63
64   Hashtable propHash;
65
66   int threshold;
67
68   String name = "";
69
70   int[][] cons2;
71
72   private String[] consSymbs;
73
74   /**
75    * Creates a new Conservation object.
76    * 
77    * @param name
78    *          Name of conservation
79    * @param propHash
80    *          hash of properties for each symbol
81    * @param threshold
82    *          to count the residues in residueHash(). commonly used value is 3
83    * @param sequences
84    *          sequences to be used in calculation
85    * @param start
86    *          start residue position
87    * @param end
88    *          end residue position
89    */
90   public Conservation(String name, Hashtable propHash, int threshold,
91           List<SequenceI> sequences, int start, int end)
92   {
93     this.name = name;
94     this.propHash = propHash;
95     this.threshold = threshold;
96     this.start = start;
97     this.end = end;
98
99     maxLength = end - start + 1; // default width includes bounds of
100     // calculation
101
102     int s, sSize = sequences.size();
103     SequenceI[] sarray = new SequenceI[sSize];
104     this.sequences = sarray;
105     try
106     {
107       for (s = 0; s < sSize; s++)
108       {
109         sarray[s] = (SequenceI) sequences.get(s);
110         if (sarray[s].getLength() > maxLength)
111         {
112           maxLength = sarray[s].getLength();
113         }
114       }
115     } catch (ArrayIndexOutOfBoundsException ex)
116     {
117       // bail - another thread has modified the sequence array, so the current
118       // calculation is probably invalid.
119       this.sequences = new SequenceI[0];
120       maxLength = 0;
121     }
122   }
123
124   /**
125    * Translate sequence i into a numerical representation and store it in the
126    * i'th position of the seqNums array.
127    * 
128    * @param i
129    */
130   private void calcSeqNum(int i)
131   {
132     String sq = null; // for dumb jbuilder not-inited exception warning
133     int[] sqnum = null;
134
135     int sSize = sequences.length;
136
137     if ((i > -1) && (i < sSize))
138     {
139       sq = sequences[i].getSequenceAsString();
140
141       if (seqNums.size() <= i)
142       {
143         seqNums.addElement(new int[sq.length() + 1]);
144       }
145
146       if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
147       {
148         int j;
149         int len;
150         seqNumsChanged = true;
151         len = sq.length();
152
153         if (maxLength < len)
154         {
155           maxLength = len;
156         }
157
158         sqnum = new int[len + 1]; // better to always make a new array -
159         // sequence can change its length
160         sqnum[0] = sq.hashCode();
161
162         for (j = 1; j <= len; j++)
163         {
164           sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
165                   .charAt(j - 1)];
166         }
167
168         seqNums.setElementAt(sqnum, i);
169       }
170       else
171       {
172         System.out.println("SEQUENCE HAS BEEN DELETED!!!");
173       }
174     }
175     else
176     {
177       // JBPNote INFO level debug
178       System.err
179               .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
180     }
181   }
182
183   /**
184    * Calculates the conservation values for given set of sequences
185    */
186   public void calculate()
187   {
188     Hashtable resultHash, ht;
189     int thresh, j, jSize = sequences.length;
190     int[] values; // Replaces residueHash
191     String type, res = null;
192     char c;
193     Enumeration enumeration2;
194
195     total = new Hashtable[maxLength];
196
197     for (int i = start; i <= end; i++)
198     {
199       values = new int[255];
200
201       for (j = 0; j < jSize; j++)
202       {
203         if (sequences[j].getLength() > i)
204         {
205           c = sequences[j].getCharAt(i);
206
207           if (canonicaliseAa)
208           { // lookup the base aa code symbol
209             c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
210                     .getCharAt(i)];
211             if (c > 20)
212             {
213               c = '-';
214             }
215             else
216             {
217               // recover canonical aa symbol
218               c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
219             }
220           }
221           else
222           {
223             // original behaviour - operate on ascii symbols directly
224             // No need to check if its a '-'
225             if (c == '.' || c == ' ')
226             {
227               c = '-';
228             }
229
230             if (!canonicaliseAa && 'a' <= c && c <= 'z')
231             {
232               c -= (32); // 32 = 'a' - 'A'
233             }
234           }
235           values[c]++;
236         }
237         else
238         {
239           values['-']++;
240         }
241       }
242
243       // What is the count threshold to count the residues in residueHash()
244       thresh = (threshold * (jSize)) / 100;
245
246       // loop over all the found residues
247       resultHash = new Hashtable();
248       for (char v = '-'; v < 'Z'; v++)
249       {
250
251         if (values[v] > thresh)
252         {
253           res = String.valueOf(v);
254
255           // Now loop over the properties
256           enumeration2 = propHash.keys();
257
258           while (enumeration2.hasMoreElements())
259           {
260             type = (String) enumeration2.nextElement();
261             ht = (Hashtable) propHash.get(type);
262
263             // Have we ticked this before?
264             if (!resultHash.containsKey(type))
265             {
266               if (ht.containsKey(res))
267               {
268                 resultHash.put(type, ht.get(res));
269               }
270               else
271               {
272                 resultHash.put(type, ht.get("-"));
273               }
274             }
275             else if (((Integer) resultHash.get(type)).equals((Integer) ht
276                     .get(res)) == false)
277             {
278               resultHash.put(type, new Integer(-1));
279             }
280           }
281         }
282       }
283
284       if (total.length > 0)
285       {
286         total[i - start] = resultHash;
287       }
288     }
289   }
290
291   /*****************************************************************************
292    * count conservation for the j'th column of the alignment
293    * 
294    * @return { gap count, conserved residue count}
295    */
296   public int[] countConsNGaps(int j)
297   {
298     int count = 0;
299     int cons = 0;
300     int nres = 0;
301     int[] r = new int[2];
302     char f = '$';
303     int i, iSize = sequences.length;
304     char c;
305
306     for (i = 0; i < iSize; i++)
307     {
308       if (j >= sequences[i].getLength())
309       {
310         count++;
311         continue;
312       }
313
314       c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
315
316       if (jalview.util.Comparison.isGap((c)))
317       {
318         count++;
319       }
320       else
321       {
322         nres++;
323
324         if (nres == 1)
325         {
326           f = c;
327           cons++;
328         }
329         else if (f == c)
330         {
331           cons++;
332         }
333       }
334     }
335
336     r[0] = (nres == cons) ? 1 : 0;
337     r[1] = count;
338
339     return r;
340   }
341
342   /**
343    * Calculates the conservation sequence
344    * 
345    * @param consflag
346    *          if true, poitiveve conservation; false calculates negative
347    *          conservation
348    * @param percentageGaps
349    *          commonly used value is 25
350    */
351   public void verdict(boolean consflag, float percentageGaps)
352   {
353     StringBuffer consString = new StringBuffer();
354     String type;
355     Integer result;
356     int[] gapcons;
357     int totGaps, count;
358     float pgaps;
359     Hashtable resultHash;
360     Enumeration enumeration;
361
362     // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
363     // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
364     // DOES NOT EXIST IN JALVIEW 2.1.2
365     for (int i = 0; i < start; i++)
366     {
367       consString.append('-');
368     }
369     consSymbs = new String[end-start+1];
370     for (int i = start; i <= end; i++)
371     {
372       gapcons = countConsNGaps(i);
373       totGaps = gapcons[1];
374       pgaps = ((float) totGaps * 100) / (float) sequences.length;
375       consSymbs[i-start]=new String();
376       
377       if (percentageGaps > pgaps)
378       {
379         resultHash = total[i - start];
380         // Now find the verdict
381         count = 0;
382         enumeration = resultHash.keys();
383
384         while (enumeration.hasMoreElements())
385         {
386           type = (String) enumeration.nextElement();
387           result = (Integer) resultHash.get(type);
388           // Do we want to count +ve conservation or +ve and -ve cons.?
389           if (consflag)
390           {
391             if (result.intValue() == 1)
392             {
393               consSymbs[i-start] = type+" "+consSymbs[i-start];
394               count++;
395             }
396           }
397           else
398           {
399             if (result.intValue() != -1)
400             {
401               { 
402                  if (result.intValue()==0) {
403                    consSymbs[i-start] = consSymbs[i-start]+ " !"+type;
404                  } else {
405                    consSymbs[i-start] = type+" "+consSymbs[i-start];
406                  }
407               }
408               
409               count++;
410             }
411           }
412         }
413
414         if (count < 10)
415         {
416           consString.append(count); // Conserved props!=Identity
417         }
418         else
419         {
420           consString.append((gapcons[0] == 1) ? "*" : "+");
421         }
422       }
423       else
424       {
425         consString.append('-');
426       }
427     }
428
429     consSequence = new Sequence(name, consString.toString(), start, end);
430   }
431
432   /**
433    * 
434    * 
435    * @return Conservation sequence
436    */
437   public Sequence getConsSequence()
438   {
439     return consSequence;
440   }
441
442   // From Alignment.java in jalview118
443   public void findQuality()
444   {
445     findQuality(0, maxLength - 1);
446   }
447
448   /**
449    * DOCUMENT ME!
450    */
451   private void percentIdentity2()
452   {
453     seqNums = new Vector();
454     // calcSeqNum(s);
455     int i = 0, iSize = sequences.length;
456     // Do we need to calculate this again?
457     for (i = 0; i < iSize; i++)
458     {
459       calcSeqNum(i);
460     }
461
462     if ((cons2 == null) || seqNumsChanged)
463     {
464       cons2 = new int[maxLength][24];
465
466       // Initialize the array
467       for (int j = 0; j < 24; j++)
468       {
469         for (i = 0; i < maxLength; i++)
470         {
471           cons2[i][j] = 0;
472         }
473       }
474
475       int[] sqnum;
476       int j = 0;
477
478       while (j < sequences.length)
479       {
480         sqnum = (int[]) seqNums.elementAt(j);
481
482         for (i = 1; i < sqnum.length; i++)
483         {
484           cons2[i - 1][sqnum[i]]++;
485         }
486
487         for (i = sqnum.length - 1; i < maxLength; i++)
488         {
489           cons2[i][23]++; // gap count
490         }
491
492         j++;
493       }
494
495       // unnecessary ?
496
497       /*
498        * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
499        * maxj = -1;
500        * 
501        * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
502        * maxi = i; maxj = j; } } }
503        */
504     }
505   }
506
507   /**
508    * Calculates the quality of the set of sequences
509    * 
510    * @param start
511    *          Start residue
512    * @param end
513    *          End residue
514    */
515   public void findQuality(int start, int end)
516   {
517     quality = new Vector();
518
519     double max = -10000;
520     int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
521
522     // Loop over columns // JBPNote Profiling info
523     // long ts = System.currentTimeMillis();
524     // long te = System.currentTimeMillis();
525     percentIdentity2();
526
527     int size = seqNums.size();
528     int[] lengths = new int[size];
529     double tot, bigtot, sr, tmp;
530     double[] x, xx;
531     int l, j, i, ii, i2, k, seqNum;
532
533     for (l = 0; l < size; l++)
534     {
535       lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
536     }
537
538     for (j = start; j <= end; j++)
539     {
540       bigtot = 0;
541
542       // First Xr = depends on column only
543       x = new double[24];
544
545       for (ii = 0; ii < 24; ii++)
546       {
547         x[ii] = 0;
548
549         for (i2 = 0; i2 < 24; i2++)
550         {
551           x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
552         }
553
554         x[ii] /= size;
555       }
556
557       // Now calculate D for each position and sum
558       for (k = 0; k < size; k++)
559       {
560         tot = 0;
561         xx = new double[24];
562         seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
563                 : 23; // Sequence, or gap at the end
564
565         // This is a loop over r
566         for (i = 0; i < 23; i++)
567         {
568           sr = 0;
569
570           sr = (double) BLOSUM62[i][seqNum] + 4;
571
572           // Calculate X with another loop over residues
573           // System.out.println("Xi " + i + " " + x[i] + " " + sr);
574           xx[i] = x[i] - sr;
575
576           tot += (xx[i] * xx[i]);
577         }
578
579         bigtot += Math.sqrt(tot);
580       }
581
582       // This is the quality for one column
583       if (max < bigtot)
584       {
585         max = bigtot;
586       }
587
588       // bigtot = bigtot * (size-cons2[j][23])/size;
589       quality.addElement(new Double(bigtot));
590
591       // Need to normalize by gaps
592     }
593
594     double newmax = -10000;
595
596     for (j = start; j <= end; j++)
597     {
598       tmp = ((Double) quality.elementAt(j)).doubleValue();
599       tmp = ((max - tmp) * (size - cons2[j][23])) / size;
600
601       // System.out.println(tmp+ " " + j);
602       quality.setElementAt(new Double(tmp), j);
603
604       if (tmp > newmax)
605       {
606         newmax = tmp;
607       }
608     }
609
610     // System.out.println("Quality " + s);
611     qualityRange[0] = new Double(0);
612     qualityRange[1] = new Double(newmax);
613   }
614
615   /**
616    * complete the given consensus and quuality annotation rows. Note: currently
617    * this method will enlarge the given annotation row if it is too small,
618    * otherwise will leave its length unchanged.
619    * 
620    * @param conservation
621    *          conservation annotation row
622    * @param quality2
623    *          (optional - may be null)
624    * @param istart
625    *          first column for conservation
626    * @param alWidth
627    *          extent of conservation
628    */
629   public void completeAnnotations(AlignmentAnnotation conservation,
630           AlignmentAnnotation quality2, int istart, int alWidth)
631   {
632     char[] sequence = getConsSequence().getSequence();
633     float minR;
634     float minG;
635     float minB;
636     float maxR;
637     float maxG;
638     float maxB;
639     minR = 0.3f;
640     minG = 0.0f;
641     minB = 0f;
642     maxR = 1.0f - minR;
643     maxG = 0.9f - minG;
644     maxB = 0f - minB; // scalable range for colouring both Conservation and
645     // Quality
646
647     float min = 0f;
648     float max = 11f;
649     float qmin = 0f;
650     float qmax = 0f;
651
652     char c;
653
654     if (conservation.annotations != null
655             && conservation.annotations.length < alWidth)
656     {
657       conservation.annotations = new Annotation[alWidth];
658     }
659
660     if (quality2 != null)
661     {
662       quality2.graphMax = qualityRange[1].floatValue();
663       if (quality2.annotations != null
664               && quality2.annotations.length < alWidth)
665       {
666         quality2.annotations = new Annotation[alWidth];
667       }
668       qmin = qualityRange[0].floatValue();
669       qmax = qualityRange[1].floatValue();
670     }
671
672     for (int i = 0; i < alWidth; i++)
673     {
674       float value = 0;
675
676       c = sequence[i];
677
678       if (Character.isDigit(c))
679       {
680         value = (int) (c - '0');
681       }
682       else if (c == '*')
683       {
684         value = 11;
685       }
686       else if (c == '+')
687       {
688         value = 10;
689       }
690
691       float vprop = value - min;
692       vprop /= max;
693       conservation.annotations[i] = new Annotation(String.valueOf(c),
694               consSymbs[i-start], ' ', value, new Color(minR
695                       + (maxR * vprop), minG + (maxG * vprop), minB
696                       + (maxB * vprop)));
697
698       // Quality calc
699       if (quality2 != null)
700       {
701         value = ((Double) quality.elementAt(i)).floatValue();
702         vprop = value - qmin;
703         vprop /= qmax;
704         quality2.annotations[i] = new Annotation(" ",
705                 String.valueOf(value), ' ', value, new Color(minR
706                         + (maxR * vprop), minG + (maxG * vprop), minB
707                         + (maxB * vprop)));
708       }
709     }
710   }
711
712   /**
713    * construct and call the calculation methods on a new Conservation object
714    * 
715    * @param name
716    *          - name of conservation
717    * @param consHash
718    *          - hash table of properties for each amino acid (normally
719    *          ResidueProperties.propHash)
720    * @param threshold
721    *          - minimum number of conserved residues needed to indicate
722    *          conservation (typically 3)
723    * @param seqs
724    * @param start
725    *          first column in calculation window
726    * @param end
727    *          last column in calculation window
728    * @param posOrNeg
729    *          positive (true) or negative (false) conservation
730    * @param consPercGaps
731    *          percentage of gaps tolerated in column
732    * @param calcQuality
733    *          flag indicating if alignment quality should be calculated
734    * @return Conservation object ready for use in visualization
735    */
736   public static Conservation calculateConservation(String name,
737           Hashtable consHash, int threshold, List<SequenceI> seqs,
738           int start, int end, boolean posOrNeg, int consPercGaps,
739           boolean calcQuality)
740   {
741     Conservation cons = new Conservation(name, consHash, threshold, seqs,
742             start, end);
743     return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
744   }
745
746   /**
747    * @param b
748    *          positive (true) or negative (false) conservation
749    * @param consPercGaps
750    *          percentage of gaps tolerated in column
751    * @param calcQuality
752    *          flag indicating if alignment quality should be calculated
753    * @return Conservation object ready for use in visualization
754    */
755   public static Conservation calculateConservation(Conservation cons,
756           boolean b, int consPercGaps, boolean calcQuality)
757   {
758     cons.calculate();
759     cons.verdict(b, consPercGaps);
760
761     if (calcQuality)
762     {
763       cons.findQuality();
764     }
765
766     return cons;
767   }
768 }