JAL-736 source formatting
[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             if (!canonicaliseAa && 'a' <= c && c <= 'z')
239             {
240               c -= (32); // 32 = 'a' - 'A'
241             }
242           }
243           values[c]++;
244         }
245         else
246         {
247           values['-']++;
248         }
249       }
250
251       // What is the count threshold to count the residues in residueHash()
252       thresh = (threshold * (jSize)) / 100;
253
254       // loop over all the found residues
255       resultHash = new Hashtable();
256       for (char v = '-'; v < 'Z'; v++)
257       {
258
259         if (values[v] > thresh)
260         {
261           res = String.valueOf(v);
262
263           // Now loop over the properties
264           enumeration2 = propHash.keys();
265
266           while (enumeration2.hasMoreElements())
267           {
268             type = (String) enumeration2.nextElement();
269             ht = (Hashtable) propHash.get(type);
270
271             // Have we ticked this before?
272             if (!resultHash.containsKey(type))
273             {
274               if (ht.containsKey(res))
275               {
276                 resultHash.put(type, ht.get(res));
277               }
278               else
279               {
280                 resultHash.put(type, ht.get("-"));
281               }
282             }
283             else if (((Integer) resultHash.get(type)).equals(ht
284                     .get(res)) == false)
285             {
286               resultHash.put(type, new Integer(-1));
287             }
288           }
289         }
290       }
291
292       if (total.length > 0)
293       {
294         total[i - start] = resultHash;
295       }
296     }
297   }
298
299   /*****************************************************************************
300    * count conservation for the j'th column of the alignment
301    * 
302    * @return { gap count, conserved residue count}
303    */
304   public int[] countConsNGaps(int j)
305   {
306     int count = 0;
307     int cons = 0;
308     int nres = 0;
309     int[] r = new int[2];
310     char f = '$';
311     int i, iSize = sequences.length;
312     char c;
313
314     for (i = 0; i < iSize; i++)
315     {
316       if (j >= sequences[i].getLength())
317       {
318         count++;
319         continue;
320       }
321
322       c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
323
324       if (jalview.util.Comparison.isGap((c)))
325       {
326         count++;
327       }
328       else
329       {
330         nres++;
331
332         if (nres == 1)
333         {
334           f = c;
335           cons++;
336         }
337         else if (f == c)
338         {
339           cons++;
340         }
341       }
342     }
343
344     r[0] = (nres == cons) ? 1 : 0;
345     r[1] = count;
346
347     return r;
348   }
349
350   /**
351    * Calculates the conservation sequence
352    * 
353    * @param consflag
354    *          if true, poitiveve conservation; false calculates negative
355    *          conservation
356    * @param percentageGaps
357    *          commonly used value is 25
358    */
359   public void verdict(boolean consflag, float percentageGaps)
360   {
361     StringBuffer consString = new StringBuffer();
362     String type;
363     Integer result;
364     int[] gapcons;
365     int totGaps, count;
366     float pgaps;
367     Hashtable resultHash;
368     Enumeration enumeration;
369
370     // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
371     // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
372     // DOES NOT EXIST IN JALVIEW 2.1.2
373     for (int i = 0; i < start; i++)
374     {
375       consString.append('-');
376     }
377     consSymbs = new String[end-start+1];
378     for (int i = start; i <= end; i++)
379     {
380       gapcons = countConsNGaps(i);
381       totGaps = gapcons[1];
382       pgaps = ((float) totGaps * 100) / sequences.length;
383       consSymbs[i-start]=new String();
384       
385       if (percentageGaps > pgaps)
386       {
387         resultHash = total[i - start];
388         // Now find the verdict
389         count = 0;
390         enumeration = resultHash.keys();
391
392         while (enumeration.hasMoreElements())
393         {
394           type = (String) enumeration.nextElement();
395           result = (Integer) resultHash.get(type);
396           // Do we want to count +ve conservation or +ve and -ve cons.?
397           if (consflag)
398           {
399             if (result.intValue() == 1)
400             {
401               consSymbs[i-start] = type+" "+consSymbs[i-start];
402               count++;
403             }
404           }
405           else
406           {
407             if (result.intValue() != -1)
408             {
409               { 
410                  if (result.intValue()==0) {
411                    consSymbs[i-start] = consSymbs[i-start]+ " !"+type;
412                  } else {
413                    consSymbs[i-start] = type+" "+consSymbs[i-start];
414                  }
415               }
416               
417               count++;
418             }
419           }
420         }
421
422         if (count < 10)
423         {
424           consString.append(count); // Conserved props!=Identity
425         }
426         else
427         {
428           consString.append((gapcons[0] == 1) ? "*" : "+");
429         }
430       }
431       else
432       {
433         consString.append('-');
434       }
435     }
436
437     consSequence = new Sequence(name, consString.toString(), start, end);
438   }
439
440   /**
441    * 
442    * 
443    * @return Conservation sequence
444    */
445   public Sequence getConsSequence()
446   {
447     return consSequence;
448   }
449
450   // From Alignment.java in jalview118
451   public void findQuality()
452   {
453     findQuality(0, maxLength - 1);
454   }
455
456   /**
457    * DOCUMENT ME!
458    */
459   private void percentIdentity2()
460   {
461     seqNums = new Vector();
462     // calcSeqNum(s);
463     int i = 0, iSize = sequences.length;
464     // Do we need to calculate this again?
465     for (i = 0; i < iSize; i++)
466     {
467       calcSeqNum(i);
468     }
469
470     if ((cons2 == null) || seqNumsChanged)
471     {
472       cons2 = new int[maxLength][24];
473
474       // Initialize the array
475       for (int j = 0; j < 24; j++)
476       {
477         for (i = 0; i < maxLength; i++)
478         {
479           cons2[i][j] = 0;
480         }
481       }
482
483       int[] sqnum;
484       int j = 0;
485
486       while (j < sequences.length)
487       {
488         sqnum = (int[]) seqNums.elementAt(j);
489
490         for (i = 1; i < sqnum.length; i++)
491         {
492           cons2[i - 1][sqnum[i]]++;
493         }
494
495         for (i = sqnum.length - 1; i < maxLength; i++)
496         {
497           cons2[i][23]++; // gap count
498         }
499
500         j++;
501       }
502
503       // unnecessary ?
504
505       /*
506        * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
507        * maxj = -1;
508        * 
509        * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
510        * maxi = i; maxj = j; } } }
511        */
512     }
513   }
514
515   /**
516    * Calculates the quality of the set of sequences
517    * 
518    * @param start
519    *          Start residue
520    * @param end
521    *          End residue
522    */
523   public void findQuality(int start, int end)
524   {
525     quality = new Vector();
526
527     double max = -10000;
528     int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
529
530     // Loop over columns // JBPNote Profiling info
531     // long ts = System.currentTimeMillis();
532     // long te = System.currentTimeMillis();
533     percentIdentity2();
534
535     int size = seqNums.size();
536     int[] lengths = new int[size];
537     double tot, bigtot, sr, tmp;
538     double[] x, xx;
539     int l, j, i, ii, i2, k, seqNum;
540
541     for (l = 0; l < size; l++)
542     {
543       lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
544     }
545
546     for (j = start; j <= end; j++)
547     {
548       bigtot = 0;
549
550       // First Xr = depends on column only
551       x = new double[24];
552
553       for (ii = 0; ii < 24; ii++)
554       {
555         x[ii] = 0;
556
557         for (i2 = 0; i2 < 24; i2++)
558         {
559           x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
560         }
561
562         x[ii] /= size;
563       }
564
565       // Now calculate D for each position and sum
566       for (k = 0; k < size; k++)
567       {
568         tot = 0;
569         xx = new double[24];
570         seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
571                 : 23; // Sequence, or gap at the end
572
573         // This is a loop over r
574         for (i = 0; i < 23; i++)
575         {
576           sr = 0;
577
578           sr = (double) BLOSUM62[i][seqNum] + 4;
579
580           // Calculate X with another loop over residues
581           // System.out.println("Xi " + i + " " + x[i] + " " + sr);
582           xx[i] = x[i] - sr;
583
584           tot += (xx[i] * xx[i]);
585         }
586
587         bigtot += Math.sqrt(tot);
588       }
589
590       // This is the quality for one column
591       if (max < bigtot)
592       {
593         max = bigtot;
594       }
595
596       // bigtot = bigtot * (size-cons2[j][23])/size;
597       quality.addElement(new Double(bigtot));
598
599       // Need to normalize by gaps
600     }
601
602     double newmax = -10000;
603
604     for (j = start; j <= end; j++)
605     {
606       tmp = ((Double) quality.elementAt(j)).doubleValue();
607       tmp = ((max - tmp) * (size - cons2[j][23])) / size;
608
609       // System.out.println(tmp+ " " + j);
610       quality.setElementAt(new Double(tmp), j);
611
612       if (tmp > newmax)
613       {
614         newmax = tmp;
615       }
616     }
617
618     // System.out.println("Quality " + s);
619     qualityRange[0] = new Double(0);
620     qualityRange[1] = new Double(newmax);
621   }
622
623   /**
624    * complete the given consensus and quuality annotation rows. Note: currently
625    * this method will enlarge the given annotation row if it is too small,
626    * otherwise will leave its length unchanged.
627    * 
628    * @param conservation
629    *          conservation annotation row
630    * @param quality2
631    *          (optional - may be null)
632    * @param istart
633    *          first column for conservation
634    * @param alWidth
635    *          extent of conservation
636    */
637   public void completeAnnotations(AlignmentAnnotation conservation,
638           AlignmentAnnotation quality2, int istart, int alWidth)
639   {
640     char[] sequence = getConsSequence().getSequence();
641     float minR;
642     float minG;
643     float minB;
644     float maxR;
645     float maxG;
646     float maxB;
647     minR = 0.3f;
648     minG = 0.0f;
649     minB = 0f;
650     maxR = 1.0f - minR;
651     maxG = 0.9f - minG;
652     maxB = 0f - minB; // scalable range for colouring both Conservation and
653     // Quality
654
655     float min = 0f;
656     float max = 11f;
657     float qmin = 0f;
658     float qmax = 0f;
659
660     char c;
661
662     if (conservation.annotations != null
663             && conservation.annotations.length < alWidth)
664     {
665       conservation.annotations = new Annotation[alWidth];
666     }
667
668     if (quality2 != null)
669     {
670       quality2.graphMax = qualityRange[1].floatValue();
671       if (quality2.annotations != null
672               && quality2.annotations.length < alWidth)
673       {
674         quality2.annotations = new Annotation[alWidth];
675       }
676       qmin = qualityRange[0].floatValue();
677       qmax = qualityRange[1].floatValue();
678     }
679
680     for (int i = 0; i < alWidth; i++)
681     {
682       float value = 0;
683
684       c = sequence[i];
685
686       if (Character.isDigit(c))
687       {
688         value = c - '0';
689       }
690       else if (c == '*')
691       {
692         value = 11;
693       }
694       else if (c == '+')
695       {
696         value = 10;
697       }
698
699       float vprop = value - min;
700       vprop /= max;
701       conservation.annotations[i] = new Annotation(String.valueOf(c),
702               consSymbs[i-start], ' ', value, new Color(minR
703                       + (maxR * vprop), minG + (maxG * vprop), minB
704                       + (maxB * vprop)));
705
706       // Quality calc
707       if (quality2 != null)
708       {
709         value = ((Double) quality.elementAt(i)).floatValue();
710         vprop = value - qmin;
711         vprop /= qmax;
712         quality2.annotations[i] = new Annotation(" ",
713                 String.valueOf(value), ' ', value, new Color(minR
714                         + (maxR * vprop), minG + (maxG * vprop), minB
715                         + (maxB * vprop)));
716       }
717     }
718   }
719
720   /**
721    * construct and call the calculation methods on a new Conservation object
722    * 
723    * @param name
724    *          - name of conservation
725    * @param consHash
726    *          - hash table of properties for each amino acid (normally
727    *          ResidueProperties.propHash)
728    * @param threshold
729    *          - minimum number of conserved residues needed to indicate
730    *          conservation (typically 3)
731    * @param seqs
732    * @param start
733    *          first column in calculation window
734    * @param end
735    *          last column in calculation window
736    * @param posOrNeg
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(String name,
745           Hashtable consHash, int threshold, List<SequenceI> seqs,
746           int start, int end, boolean posOrNeg, int consPercGaps,
747           boolean calcQuality)
748   {
749     Conservation cons = new Conservation(name, consHash, threshold, seqs,
750             start, end);
751     return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
752   }
753
754   /**
755    * @param b
756    *          positive (true) or negative (false) conservation
757    * @param consPercGaps
758    *          percentage of gaps tolerated in column
759    * @param calcQuality
760    *          flag indicating if alignment quality should be calculated
761    * @return Conservation object ready for use in visualization
762    */
763   public static Conservation calculateConservation(Conservation cons,
764           boolean b, int consPercGaps, boolean calcQuality)
765   {
766     cons.calculate();
767     cons.verdict(b, consPercGaps);
768
769     if (calcQuality)
770     {
771       cons.findQuality();
772     }
773
774     return cons;
775   }
776 }