8cfe728c7a4911a3e5b52bcca1d28294ae02d7c7
[jalview.git] / src / jalview / datamodel / AlignmentAnnotation.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 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.datamodel;
20
21 import java.util.Enumeration;
22 import java.util.Hashtable;
23
24 /**
25  * DOCUMENT ME!
26  *
27  * @author $author$
28  * @version $Revision$
29  */
30 public class AlignmentAnnotation
31 {
32   /** If true, this annotations is calculated every edit,
33    * eg consensus, quality or conservation graphs */
34   public boolean autoCalculated = false;
35
36   public String annotationId;
37
38   public SequenceI sequenceRef;
39
40   /** DOCUMENT ME!! */
41   public String label;
42
43   /** DOCUMENT ME!! */
44   public String description;
45
46   /** DOCUMENT ME!! */
47   public Annotation[] annotations;
48
49   public java.util.Hashtable sequenceMapping;
50
51   /** DOCUMENT ME!! */
52   public float graphMin;
53
54   /** DOCUMENT ME!! */
55   public float graphMax;
56
57   /**
58    * Score associated with label and description.
59    */
60   public double score= Double.NaN;
61   /**
62    * flag indicating if annotation has a score.
63    */
64   public boolean hasScore=false;
65
66   public GraphLine threshold;
67
68   // Graphical hints and tips
69
70   /** DOCUMENT ME!! */
71   public boolean editable = false;
72
73   /** DOCUMENT ME!! */
74   public boolean hasIcons; //
75
76   /** DOCUMENT ME!! */
77   public boolean hasText;
78
79   /** DOCUMENT ME!! */
80   public boolean visible = true;
81
82   public int graphGroup = -1;
83
84   /** DOCUMENT ME!! */
85   public int height = 0;
86
87   public int graph = 0;
88
89   public int graphHeight = 40;
90
91   public boolean padGaps = false;
92
93   public static final int NO_GRAPH = 0;
94
95   public static final int BAR_GRAPH = 1;
96
97   public static final int LINE_GRAPH = 2;
98
99   public boolean belowAlignment = true;
100
101
102   public static int getGraphValueFromString(String string)
103   {
104     if (string.equalsIgnoreCase("BAR_GRAPH"))
105     {
106       return BAR_GRAPH;
107     }
108     else if (string.equalsIgnoreCase("LINE_GRAPH"))
109     {
110       return LINE_GRAPH;
111     }
112     else
113     {
114       return NO_GRAPH;
115     }
116   }
117
118   /**
119    * Creates a new AlignmentAnnotation object.
120    *
121    * @param label DOCUMENT ME!
122    * @param description DOCUMENT ME!
123    * @param annotations DOCUMENT ME!about:blank
124 Loading...
125    */
126   public AlignmentAnnotation(String label, String description,
127                              Annotation[] annotations)
128   {
129     // always editable?
130     editable = true;
131     this.label = label;
132     this.description = description;
133     this.annotations = annotations;
134
135      validateRangeAndDisplay();
136   }
137
138   void areLabelsSecondaryStructure()
139   {
140     boolean nonSSLabel = false;
141     for (int i = 0; i < annotations.length; i++)
142     {
143       if (annotations[i] == null)
144       {
145         continue;
146       }
147       if (annotations[i].secondaryStructure == 'H' ||
148           annotations[i].secondaryStructure == 'E')
149       {
150           hasIcons = true;
151       }
152
153       if(annotations[i].displayCharacter==null)
154       {
155         continue;
156       }
157
158       if (annotations[i].displayCharacter.length() == 1
159           && !annotations[i].displayCharacter.equals("H")
160           && !annotations[i].displayCharacter.equals("E")
161           && !annotations[i].displayCharacter.equals("-")
162           && !annotations[i].displayCharacter.equals("."))
163         {
164           if (jalview.schemes.ResidueProperties.aaIndex
165                   [annotations[i].displayCharacter.charAt(0)] < 23)
166           {
167             nonSSLabel = true;
168           }
169         }
170
171         if (annotations[i].displayCharacter.length() > 0)
172         {
173           hasText = true;
174         }
175       }
176
177     if (nonSSLabel)
178     {
179       hasIcons = false;
180       for (int j = 0; j < annotations.length; j++)
181       {
182         if (annotations[j] != null && annotations[j].secondaryStructure != ' ')
183         {
184           annotations[j].displayCharacter
185               = String.valueOf(annotations[j].secondaryStructure);
186           annotations[j].secondaryStructure = ' ';
187         }
188
189       }
190     }
191
192     annotationId = this.hashCode() + "";
193   }
194   /**
195    * Creates a new AlignmentAnnotation object.
196    *
197    * @param label DOCUMENT ME!
198    * @param description DOCUMENT ME!
199    * @param annotations DOCUMENT ME!
200    * @param min DOCUMENT ME!
201    * @param max DOCUMENT ME!
202    * @param winLength DOCUMENT ME!
203    */
204   public AlignmentAnnotation(String label, String description,
205                              Annotation[] annotations, float min, float max,
206                              int graphType)
207   {
208     // graphs are not editable
209     editable = graphType==0;
210
211     this.label = label;
212     this.description = description;
213     this.annotations = annotations;
214     graph = graphType;
215     graphMin = min;
216     graphMax = max;
217     validateRangeAndDisplay();
218   }
219   /**
220    * checks graphMin and graphMax,
221    * secondary structure symbols,
222    * sets graphType appropriately,
223    * sets null labels to the empty string
224    * if appropriate.
225    */
226   private void validateRangeAndDisplay() {
227
228     if (annotations==null)
229     {
230       visible=false; // try to prevent renderer from displaying.
231       return; // this is a non-annotation row annotation - ie a sequence score.
232     }
233
234     int graphType = graph;
235     float min = graphMin;
236     float max = graphMax;
237     boolean drawValues = true;
238
239     if (min == max)
240     {
241       min = 999999999;
242       for (int i = 0; i < annotations.length; i++)
243       {
244         if (annotations[i] == null)
245         {
246           continue;
247         }
248
249         if (drawValues
250             && annotations[i].displayCharacter!=null
251             && annotations[i].displayCharacter.length() > 1)
252         {
253           drawValues = false;
254         }
255
256         if (annotations[i].value > max)
257         {
258           max = annotations[i].value;
259         }
260
261         if (annotations[i].value < min)
262         {
263           min = annotations[i].value;
264         }
265       }
266     }
267
268     graphMin = min;
269     graphMax = max;
270
271     areLabelsSecondaryStructure();
272
273     if (!drawValues && graphType != NO_GRAPH)
274     {
275       for (int i = 0; i < annotations.length; i++)
276       {
277         if (annotations[i] != null)
278         {
279           annotations[i].displayCharacter = "";
280         }
281       }
282     }
283   }
284
285   /**
286    * Copy constructor
287    * creates a new independent annotation row with the same associated sequenceRef
288    * @param annotation
289    */
290   public AlignmentAnnotation(AlignmentAnnotation annotation)
291   {
292     this.label = new String(annotation.label);
293     if (annotation.description != null)
294       this.description = new String(annotation.description);
295     this.graphMin = annotation.graphMin;
296     this.graphMax = annotation.graphMax;
297     this.graph = annotation.graph;
298     this.graphHeight = annotation.graphHeight;
299     this.graphGroup = annotation.graphGroup;
300     this.editable = annotation.editable;
301     this.autoCalculated = annotation.autoCalculated;
302     this.hasIcons = annotation.hasIcons;
303     this.hasText = annotation.hasText;
304     this.height = annotation.height;
305     this.label = annotation.label;
306     this.padGaps = annotation.padGaps;
307     this.visible = annotation.visible;
308     if (this.hasScore = annotation.hasScore)
309     {
310       this.score = annotation.score;
311     }
312     if (threshold!=null) {
313       threshold = new GraphLine(annotation.threshold);
314     }
315     if (annotation.annotations!=null) {
316       Annotation[] ann = annotation.annotations;
317       this.annotations = new Annotation[ann.length];
318       for (int i=0; i<ann.length; i++) {
319         annotations[i] = new Annotation(ann[i]);
320       };
321       if (annotation.sequenceRef!=null) {
322         this.sequenceRef = annotation.sequenceRef;
323         if (annotation.sequenceMapping!=null)
324         {
325           Integer p=null;
326           sequenceMapping = new Hashtable();
327           Enumeration pos=annotation.sequenceMapping.keys();
328           while (pos.hasMoreElements()) {
329             // could optimise this!
330             p = (Integer) pos.nextElement();
331             Annotation a = (Annotation) annotation.sequenceMapping.get(p);
332             if (a==null)
333             {
334               continue;
335             }
336             for (int i=0; i<ann.length; i++)
337             {
338               if (ann[i]==a)
339               {
340                 sequenceMapping.put(p, annotations[i]);
341               }
342             }
343           }
344         } else {
345           this.sequenceMapping = null;
346         }
347       }
348     }
349     validateRangeAndDisplay(); // construct hashcodes, etc.
350   }
351
352   /**
353    * clip the annotation to the columns given by startRes and endRes (inclusive)
354    * and prune any existing sequenceMapping to just those columns.
355    * @param startRes
356    * @param endRes
357    */
358   public void restrict(int startRes, int endRes)
359   {
360     if (annotations==null)
361     {
362       // non-positional
363       return;
364     }
365     if (startRes<0)
366       startRes=0;
367     if (startRes>=annotations.length)
368       startRes = annotations.length-1;
369     if (endRes>=annotations.length)
370       endRes = annotations.length-1;
371     if (annotations==null)
372       return;
373     Annotation[] temp = new Annotation[endRes-startRes+1];
374     if (startRes<annotations.length)
375     {
376       System.arraycopy(annotations, startRes, temp, 0, endRes-startRes+1);
377     }
378     if (sequenceRef!=null) {
379       // Clip the mapping, if it exists.
380       int spos = sequenceRef.findPosition(startRes);
381       int epos = sequenceRef.findPosition(endRes);
382       if (sequenceMapping!=null)
383       {
384         Hashtable newmapping = new Hashtable();
385         Enumeration e = sequenceMapping.keys();
386         while (e.hasMoreElements())
387         {
388           Integer pos = (Integer) e.nextElement();
389           if (pos.intValue()>=spos && pos.intValue()<=epos)
390           {
391             newmapping.put(pos, sequenceMapping.get(pos));
392           }
393         }
394         sequenceMapping.clear();
395         sequenceMapping = newmapping;
396       }
397     }
398     annotations=temp;
399   }
400   /**
401    * set the annotation row to be at least length Annotations
402    * @param length minimum number of columns required in the annotation row
403    * @return false if the annotation row is greater than length
404    */
405   public boolean padAnnotation(int length) {
406     if (annotations==null)
407     {
408       return true; // annotation row is correct - null == not visible and undefined length
409     }
410     if (annotations.length<length)
411     {
412       Annotation[] na = new Annotation[length];
413       System.arraycopy(annotations, 0, na, 0, annotations.length);
414       annotations = na;
415       return true;
416     }
417     return annotations.length>length;
418
419   }
420
421   /**
422    * DOCUMENT ME!
423    *
424    * @return DOCUMENT ME!
425    */
426   public String toString()
427   {
428     StringBuffer buffer = new StringBuffer();
429
430     for (int i = 0; i < annotations.length; i++)
431     {
432       if (annotations[i] != null)
433       {
434         if (graph != 0)
435         {
436           buffer.append(annotations[i].value);
437         }
438         else if (hasIcons)
439         {
440           buffer.append(annotations[i].secondaryStructure);
441         }
442         else
443         {
444           buffer.append(annotations[i].displayCharacter);
445         }
446       }
447
448       buffer.append(", ");
449     }
450
451     if (label.equals("Consensus"))
452     {
453       buffer.append("\n");
454
455       for (int i = 0; i < annotations.length; i++)
456       {
457         if (annotations[i] != null)
458         {
459           buffer.append(annotations[i].description);
460         }
461
462         buffer.append(", ");
463       }
464     }
465
466     return buffer.toString();
467   }
468
469   public void setThreshold(GraphLine line)
470   {
471     threshold = line;
472   }
473
474   public GraphLine getThreshold()
475   {
476     return threshold;
477   }
478
479   /**
480    * Attach the annotation to seqRef, starting from startRes position. If alreadyMapped is true then the indices of the annotation[] array are sequence positions rather than alignment column positions.
481    * @param seqRef
482    * @param startRes
483    * @param alreadyMapped
484    */
485   public void createSequenceMapping(SequenceI seqRef,
486                                     int startRes,
487                                     boolean alreadyMapped)
488   {
489
490     if (seqRef == null)
491     {
492       return;
493     }
494     sequenceRef=seqRef;
495     if (annotations==null)
496     {
497       return;
498     }
499     sequenceMapping = new java.util.Hashtable();
500
501     int seqPos;
502
503     for (int i = 0; i < annotations.length; i++)
504     {
505       if (annotations[i] != null)
506       {
507         if (alreadyMapped)
508         {
509           seqPos = seqRef.findPosition(i);
510         }
511         else
512         {
513           seqPos = i + startRes;
514         }
515
516         sequenceMapping.put(new Integer(seqPos), annotations[i]);
517       }
518     }
519
520   }
521
522   public void adjustForAlignment()
523   {
524     if (sequenceRef==null)
525       return;
526
527     if (annotations==null)
528     {
529       return;
530     }
531
532     int a = 0, aSize = sequenceRef.getLength();
533
534     if (aSize == 0)
535     {
536       //Its been deleted
537       return;
538     }
539
540     int position;
541     Annotation[] temp = new Annotation[aSize];
542     Integer index;
543
544     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
545     {
546       index = new Integer(a);
547       if (sequenceMapping.containsKey(index))
548       {
549         position = sequenceRef.findIndex(a) - 1;
550
551         temp[position] = (Annotation) sequenceMapping.get(index);
552       }
553     }
554
555     annotations = temp;
556   }
557   /**
558    * remove any null entries in annotation row and return the
559    * number of non-null annotation elements.
560    * @return
561    */
562   public int compactAnnotationArray() {
563     int i=0,iSize=annotations.length;
564     while (i<iSize)
565     {
566       if (annotations[i]==null) {
567         if (i+1<iSize)
568           System.arraycopy(annotations, i+1, annotations, i, iSize-i-1);
569         iSize--;
570       } else {
571         i++;
572       }
573     }
574     Annotation[] ann = annotations;
575     annotations = new Annotation[i];
576     System.arraycopy(ann, 0, annotations, 0, i);
577     ann = null;
578     return iSize;
579   }
580
581   /**
582    * Associate this annotion with the aligned residues of a particular sequence.
583    * sequenceMapping will be updated in the following way:
584    *   null sequenceI - existing mapping will be discarded but annotations left in mapped positions.
585    *   valid sequenceI not equal to current sequenceRef: mapping is discarded and rebuilt assuming 1:1 correspondence
586    *   TODO: overload with parameter to specify correspondence between current and new sequenceRef
587    * @param sequenceI
588    */
589   public void setSequenceRef(SequenceI sequenceI)
590   {
591     if (sequenceI != null)
592     {
593       if (sequenceRef != null)
594       {
595         if (sequenceRef != sequenceI && !sequenceRef.equals(sequenceI) && sequenceRef.getDatasetSequence()!=sequenceI.getDatasetSequence())
596         {
597           // if sequenceRef isn't intersecting with sequenceI
598           // throw away old mapping and reconstruct.
599           sequenceRef = null;
600           if (sequenceMapping != null)
601           {
602             sequenceMapping = null;
603             // compactAnnotationArray();
604           }
605           createSequenceMapping(sequenceI, 1, true);
606           adjustForAlignment();
607         }
608         else
609         {
610           // Mapping carried over
611           sequenceRef = sequenceI;
612         }
613       }
614       else
615       {
616         // No mapping exists
617         createSequenceMapping(sequenceI, 1, true);
618         adjustForAlignment();
619       }
620     }
621     else
622     {
623       // throw away the mapping without compacting.
624       sequenceMapping = null;
625       sequenceRef = null;
626     }
627   }
628
629   /**
630    * @return the score
631    */
632   public double getScore()
633   {
634     return score;
635   }
636
637   /**
638    * @param score the score to set
639    */
640   public void setScore(double score)
641   {
642     hasScore=true;
643     this.score = score;
644   }
645   /**
646    *
647    * @return true if annotation has an associated score
648    */
649   public boolean hasScore()
650   {
651     return hasScore || !Double.isNaN(score);
652   }
653   /**
654    * Score only annotation
655    * @param label
656    * @param description
657    * @param score
658    */
659   public AlignmentAnnotation(String label, String description, double score)
660   {
661     this(label, description, null);
662     setScore(score);
663   }
664   /**
665    * copy constructor with edit based on the hidden columns marked in colSel
666    * @param alignmentAnnotation
667    * @param colSel
668    */
669   public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
670           ColumnSelection colSel)
671   {
672     this(alignmentAnnotation);
673     if (annotations==null)
674     {
675       return;
676     }
677     colSel.makeVisibleAnnotation(this);
678   }
679
680   public void setPadGaps(boolean padgaps, char gapchar)
681   {
682     this.padGaps = padgaps;
683     if(padgaps)
684     {
685       hasText = true;
686       for(int i=0; i<annotations.length; i++)
687       {
688         if(annotations[i]==null)
689           annotations[i] = new Annotation(String.valueOf(gapchar),null,' ',0f);
690         else if(annotations[i].displayCharacter==null ||annotations[i].displayCharacter.equals(" "))
691           annotations[i].displayCharacter=String.valueOf(gapchar);
692       }
693     }
694   }
695 }