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