JAL-1620 version bump and release notes
[jalview.git] / src / jalview / analysis / Conservation.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2b1)
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
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 java.awt.Color;
24 import java.util.*;
25
26 import jalview.datamodel.*;
27
28 /**
29  * Calculates conservation values for a given set of sequences
30  * 
31  * @author $author$
32  * @version $Revision$
33  */
34 public class Conservation
35 {
36   SequenceI[] sequences;
37
38   int start;
39
40   int end;
41
42   Vector seqNums; // vector of int vectors where first is sequence checksum
43
44   int maxLength = 0; // used by quality calcs
45
46   boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
47
48   Hashtable[] total;
49
50   boolean canonicaliseAa = true; // if true then conservation calculation will
51
52   // map all symbols to canonical aa numbering
53   // rather than consider conservation of that
54   // symbol
55
56   /** Stores calculated quality values */
57   public Vector quality;
58
59   /** Stores maximum and minimum values of quality values */
60   public Double[] qualityRange = new Double[2];
61
62   String consString = "";
63
64   Sequence consSequence;
65
66   Hashtable propHash;
67
68   int threshold;
69
70   String name = "";
71
72   int[][] cons2;
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
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
376       if (percentageGaps > pgaps)
377       {
378         resultHash = total[i - start];
379
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
389           // Do we want to count +ve conservation or +ve and -ve cons.?
390           if (consflag)
391           {
392             if (result.intValue() == 1)
393             {
394               count++;
395             }
396           }
397           else
398           {
399             if (result.intValue() != -1)
400             {
401               count++;
402             }
403           }
404         }
405
406         if (count < 10)
407         {
408           consString.append(count); // Conserved props!=Identity
409         }
410         else
411         {
412           consString.append((gapcons[0] == 1) ? "*" : "+");
413         }
414       }
415       else
416       {
417         consString.append('-');
418       }
419     }
420
421     consSequence = new Sequence(name, consString.toString(), start, end);
422   }
423
424   /**
425    * 
426    * 
427    * @return Conservation sequence
428    */
429   public Sequence getConsSequence()
430   {
431     return consSequence;
432   }
433
434   // From Alignment.java in jalview118
435   public void findQuality()
436   {
437     findQuality(0, maxLength - 1);
438   }
439
440   /**
441    * DOCUMENT ME!
442    */
443   private void percentIdentity2()
444   {
445     seqNums = new Vector();
446     // calcSeqNum(s);
447     int i = 0, iSize = sequences.length;
448     // Do we need to calculate this again?
449     for (i = 0; i < iSize; i++)
450     {
451       calcSeqNum(i);
452     }
453
454     if ((cons2 == null) || seqNumsChanged)
455     {
456       cons2 = new int[maxLength][24];
457
458       // Initialize the array
459       for (int j = 0; j < 24; j++)
460       {
461         for (i = 0; i < maxLength; i++)
462         {
463           cons2[i][j] = 0;
464         }
465       }
466
467       int[] sqnum;
468       int j = 0;
469
470       while (j < sequences.length)
471       {
472         sqnum = (int[]) seqNums.elementAt(j);
473
474         for (i = 1; i < sqnum.length; i++)
475         {
476           cons2[i - 1][sqnum[i]]++;
477         }
478
479         for (i = sqnum.length - 1; i < maxLength; i++)
480         {
481           cons2[i][23]++; // gap count
482         }
483
484         j++;
485       }
486
487       // unnecessary ?
488
489       /*
490        * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
491        * maxj = -1;
492        * 
493        * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
494        * maxi = i; maxj = j; } } }
495        */
496     }
497   }
498
499   /**
500    * Calculates the quality of the set of sequences
501    * 
502    * @param start
503    *          Start residue
504    * @param end
505    *          End residue
506    */
507   public void findQuality(int start, int end)
508   {
509     quality = new Vector();
510
511     double max = -10000;
512     int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
513
514     // Loop over columns // JBPNote Profiling info
515     // long ts = System.currentTimeMillis();
516     // long te = System.currentTimeMillis();
517     percentIdentity2();
518
519     int size = seqNums.size();
520     int[] lengths = new int[size];
521     double tot, bigtot, sr, tmp;
522     double[] x, xx;
523     int l, j, i, ii, i2, k, seqNum;
524
525     for (l = 0; l < size; l++)
526     {
527       lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
528     }
529
530     for (j = start; j <= end; j++)
531     {
532       bigtot = 0;
533
534       // First Xr = depends on column only
535       x = new double[24];
536
537       for (ii = 0; ii < 24; ii++)
538       {
539         x[ii] = 0;
540
541         for (i2 = 0; i2 < 24; i2++)
542         {
543           x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
544         }
545
546         x[ii] /= size;
547       }
548
549       // Now calculate D for each position and sum
550       for (k = 0; k < size; k++)
551       {
552         tot = 0;
553         xx = new double[24];
554         seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
555                 : 23; // Sequence, or gap at the end
556
557         // This is a loop over r
558         for (i = 0; i < 23; i++)
559         {
560           sr = 0;
561
562           sr = (double) BLOSUM62[i][seqNum] + 4;
563
564           // Calculate X with another loop over residues
565           // System.out.println("Xi " + i + " " + x[i] + " " + sr);
566           xx[i] = x[i] - sr;
567
568           tot += (xx[i] * xx[i]);
569         }
570
571         bigtot += Math.sqrt(tot);
572       }
573
574       // This is the quality for one column
575       if (max < bigtot)
576       {
577         max = bigtot;
578       }
579
580       // bigtot = bigtot * (size-cons2[j][23])/size;
581       quality.addElement(new Double(bigtot));
582
583       // Need to normalize by gaps
584     }
585
586     double newmax = -10000;
587
588     for (j = start; j <= end; j++)
589     {
590       tmp = ((Double) quality.elementAt(j)).doubleValue();
591       tmp = ((max - tmp) * (size - cons2[j][23])) / size;
592
593       // System.out.println(tmp+ " " + j);
594       quality.setElementAt(new Double(tmp), j);
595
596       if (tmp > newmax)
597       {
598         newmax = tmp;
599       }
600     }
601
602     // System.out.println("Quality " + s);
603     qualityRange[0] = new Double(0);
604     qualityRange[1] = new Double(newmax);
605   }
606
607   /**
608    * complete the given consensus and quuality annotation rows. Note: currently
609    * this method will enlarge the given annotation row if it is too small,
610    * otherwise will leave its length unchanged.
611    * 
612    * @param conservation
613    *          conservation annotation row
614    * @param quality2
615    *          (optional - may be null)
616    * @param istart
617    *          first column for conservation
618    * @param alWidth
619    *          extent of conservation
620    */
621   public void completeAnnotations(AlignmentAnnotation conservation,
622           AlignmentAnnotation quality2, int istart, int alWidth)
623   {
624     char[] sequence = getConsSequence().getSequence();
625     float minR;
626     float minG;
627     float minB;
628     float maxR;
629     float maxG;
630     float maxB;
631     minR = 0.3f;
632     minG = 0.0f;
633     minB = 0f;
634     maxR = 1.0f - minR;
635     maxG = 0.9f - minG;
636     maxB = 0f - minB; // scalable range for colouring both Conservation and
637     // Quality
638
639     float min = 0f;
640     float max = 11f;
641     float qmin = 0f;
642     float qmax = 0f;
643
644     char c;
645
646     if (conservation.annotations != null
647             && conservation.annotations.length < alWidth)
648     {
649       conservation.annotations = new Annotation[alWidth];
650     }
651
652     if (quality2 != null)
653     {
654       quality2.graphMax = qualityRange[1].floatValue();
655       if (quality2.annotations != null
656               && quality2.annotations.length < alWidth)
657       {
658         quality2.annotations = new Annotation[alWidth];
659       }
660       qmin = qualityRange[0].floatValue();
661       qmax = qualityRange[1].floatValue();
662     }
663
664     for (int i = 0; i < alWidth; i++)
665     {
666       float value = 0;
667
668       c = sequence[i];
669
670       if (Character.isDigit(c))
671       {
672         value = (int) (c - '0');
673       }
674       else if (c == '*')
675       {
676         value = 11;
677       }
678       else if (c == '+')
679       {
680         value = 10;
681       }
682
683       float vprop = value - min;
684       vprop /= max;
685       conservation.annotations[i] = new Annotation(String.valueOf(c),
686               String.valueOf(value), ' ', value, new Color(minR
687                       + (maxR * vprop), minG + (maxG * vprop), minB
688                       + (maxB * vprop)));
689
690       // Quality calc
691       if (quality2 != null)
692       {
693         value = ((Double) quality.elementAt(i)).floatValue();
694         vprop = value - qmin;
695         vprop /= qmax;
696         quality2.annotations[i] = new Annotation(" ",
697                 String.valueOf(value), ' ', value, new Color(minR
698                         + (maxR * vprop), minG + (maxG * vprop), minB
699                         + (maxB * vprop)));
700       }
701     }
702   }
703
704   /**
705    * construct and call the calculation methods on a new Conservation object
706    * 
707    * @param name
708    *          - name of conservation
709    * @param consHash
710    *          - hash table of properties for each amino acid (normally
711    *          ResidueProperties.propHash)
712    * @param threshold
713    *          - minimum number of conserved residues needed to indicate
714    *          conservation (typically 3)
715    * @param seqs
716    * @param start
717    *          first column in calculation window
718    * @param end
719    *          last column in calculation window
720    * @param posOrNeg
721    *          positive (true) or negative (false) conservation
722    * @param consPercGaps
723    *          percentage of gaps tolerated in column
724    * @param calcQuality
725    *          flag indicating if alignment quality should be calculated
726    * @return Conservation object ready for use in visualization
727    */
728   public static Conservation calculateConservation(String name,
729           Hashtable consHash, int threshold, List<SequenceI> seqs,
730           int start, int end, boolean posOrNeg, int consPercGaps,
731           boolean calcQuality)
732   {
733     Conservation cons = new Conservation(name, consHash, threshold, seqs,
734             start, end);
735     return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
736   }
737
738   /**
739    * @param b
740    *          positive (true) or negative (false) conservation
741    * @param consPercGaps
742    *          percentage of gaps tolerated in column
743    * @param calcQuality
744    *          flag indicating if alignment quality should be calculated
745    * @return Conservation object ready for use in visualization
746    */
747   public static Conservation calculateConservation(Conservation cons,
748           boolean b, int consPercGaps, boolean calcQuality)
749   {
750     cons.calculate();
751     cons.verdict(b, consPercGaps);
752
753     if (calcQuality)
754     {
755       cons.findQuality();
756     }
757
758     return cons;
759   }
760 }