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