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