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