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