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