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