fix for null annotations
[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 float score= Float.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 = true;
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         padGaps = false;
146         continue;
147       }
148       if (annotations[i].secondaryStructure == 'H' ||
149           annotations[i].secondaryStructure == 'E')
150       {
151           hasIcons = true;
152       }
153
154       if(annotations[i].displayCharacter==null)
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         else
176           padGaps = false;
177       }
178
179     if (nonSSLabel)
180     {
181       hasIcons = false;
182       for (int j = 0; j < annotations.length; j++)
183       {
184         if (annotations[j] != null && annotations[j].secondaryStructure != ' ')
185         {
186           annotations[j].displayCharacter
187               = String.valueOf(annotations[j].secondaryStructure);
188           annotations[j].secondaryStructure = ' ';
189         }
190
191       }
192     }
193
194     annotationId = this.hashCode() + "";
195   }
196   /**
197    * Creates a new AlignmentAnnotation object.
198    *
199    * @param label DOCUMENT ME!
200    * @param description DOCUMENT ME!
201    * @param annotations DOCUMENT ME!
202    * @param min DOCUMENT ME!
203    * @param max DOCUMENT ME!
204    * @param winLength DOCUMENT ME!
205    */
206   public AlignmentAnnotation(String label, String description,
207                              Annotation[] annotations, float min, float max,
208                              int graphType)
209   {
210     // graphs are not editable
211     editable = graphType==0;
212
213     this.label = label;
214     this.description = description;
215     this.annotations = annotations;
216     graph = graphType;
217     graphMin = min;
218     graphMax = max;
219     validateRangeAndDisplay();
220   }
221   /**
222    * checks graphMin and graphMax,
223    * secondary structure symbols,
224    * sets graphType appropriately,
225    * sets null labels to the empty string
226    * if appropriate.
227    */
228   private void validateRangeAndDisplay() {
229
230     if (annotations==null)
231     {
232       visible=false; // try to prevent renderer from displaying.
233       return; // this is a non-annotation row annotation - ie a sequence score.
234     }
235
236     int graphType = graph;
237     float min = graphMin;
238     float max = graphMax;
239     boolean drawValues = true;
240
241     if (min == max)
242     {
243       min = 999999999;
244       for (int i = 0; i < annotations.length; i++)
245       {
246         if (annotations[i] == null)
247         {
248           continue;
249         }
250
251         if (drawValues
252             && annotations[i].displayCharacter!=null
253             && annotations[i].displayCharacter.length() > 1)
254         {
255           drawValues = false;
256         }
257
258         if (annotations[i].value > max)
259         {
260           max = annotations[i].value;
261         }
262
263         if (annotations[i].value < min)
264         {
265           min = annotations[i].value;
266         }
267       }
268     }
269
270     graphMin = min;
271     graphMax = max;
272
273     areLabelsSecondaryStructure();
274
275     if (!drawValues && graphType != NO_GRAPH)
276     {
277       for (int i = 0; i < annotations.length; i++)
278       {
279         if (annotations[i] != null)
280         {
281           annotations[i].displayCharacter = "";
282         }
283       }
284     }
285   }
286
287   /**
288    * Copy constructor
289    * creates a new independent annotation row with the same associated sequenceRef
290    * @param annotation
291    */
292   public AlignmentAnnotation(AlignmentAnnotation annotation)
293   {
294     this.label = new String(annotation.label);
295     if (annotation.description != null)
296       this.description = new String(annotation.description);
297     this.graphMin = annotation.graphMin;
298     this.graphMax = annotation.graphMax;
299     this.graph = annotation.graph;
300     this.graphHeight = annotation.graphHeight;
301     this.graphGroup = annotation.graphGroup;
302     this.editable = annotation.editable;
303     this.autoCalculated = annotation.autoCalculated;
304     this.hasIcons = annotation.hasIcons;
305     this.hasText = annotation.hasText;
306     this.height = annotation.height;
307     this.label = annotation.label;
308     this.padGaps = annotation.padGaps;
309     if (threshold!=null) {
310       threshold = new GraphLine(annotation.threshold);
311     }
312     if (annotation.annotations!=null) {
313       Annotation[] ann = annotation.annotations;
314       this.annotations = new Annotation[ann.length];
315       for (int i=0; i<ann.length; i++) {
316         annotations[i] = new Annotation(ann[i]);
317       };
318       if (annotation.sequenceRef!=null) {
319         this.sequenceRef = annotation.sequenceRef;
320         if (annotation.sequenceMapping!=null)
321         {
322           Integer p=null;
323           sequenceMapping = new Hashtable();
324           Enumeration pos=annotation.sequenceMapping.keys();
325           while (pos.hasMoreElements()) {
326             // could optimise this!
327             p = (Integer) pos.nextElement();
328             Annotation a = (Annotation) annotation.sequenceMapping.get(p);
329             if (a==null)
330             {
331               continue;
332             }
333             for (int i=0; i<ann.length; i++)
334             {
335               if (ann[i]==a)
336               {
337                 sequenceMapping.put(p, annotations[i]);
338               }
339             }
340           }
341         } else {
342           this.sequenceMapping = null;
343         }
344       }
345     }
346     validateRangeAndDisplay(); // construct hashcodes, etc.
347   }
348
349   /**
350    * clip the annotation to the columns given by startRes and endRes (inclusive)
351    * and prune any existing sequenceMapping to just those columns.
352    * @param startRes
353    * @param endRes
354    */
355   public void restrict(int startRes, int endRes)
356   {
357     if (annotations==null)
358       return;
359     Annotation[] temp = new Annotation[endRes-startRes+1];
360     if (startRes<annotations.length)
361     {
362       System.arraycopy(annotations, startRes, temp, 0, Math.min(endRes, annotations.length-1)-startRes+1);
363     }
364     if (sequenceRef!=null) {
365       // Clip the mapping, if it exists.
366       int spos = sequenceRef.findPosition(startRes);
367       int epos = sequenceRef.findPosition(endRes);
368       if (sequenceMapping!=null)
369       {
370         Hashtable newmapping = new Hashtable();
371         Enumeration e = sequenceMapping.keys();
372         while (e.hasMoreElements())
373         {
374           Integer pos = (Integer) e.nextElement();
375           if (pos.intValue()>=spos && pos.intValue()<=epos)
376           {
377             newmapping.put(pos, sequenceMapping.get(pos));
378           }
379         }
380         sequenceMapping.clear();
381         sequenceMapping = newmapping;
382       }
383     }
384     annotations=temp;
385   }
386   /**
387    * set the annotation row to be at least length Annotations
388    * @param length minimum number of columns required in the annotation row
389    * @return false if the annotation row is greater than length
390    */
391   public boolean padAnnotation(int length) {
392     if (annotations==null)
393     {
394       annotations = new Annotation[length];
395       return true;
396     }
397     if (annotations.length<length)
398     {
399       Annotation[] na = new Annotation[length];
400       System.arraycopy(annotations, 0, na, 0, annotations.length);
401       annotations = na;
402       return true;
403     }
404     return annotations.length>length;
405
406   }
407
408   /**
409    * DOCUMENT ME!
410    *
411    * @return DOCUMENT ME!
412    */
413   public String toString()
414   {
415     StringBuffer buffer = new StringBuffer();
416
417     for (int i = 0; i < annotations.length; i++)
418     {
419       if (annotations[i] != null)
420       {
421         if (graph != 0)
422         {
423           buffer.append(annotations[i].value);
424         }
425         else if (hasIcons)
426         {
427           buffer.append(annotations[i].secondaryStructure);
428         }
429         else
430         {
431           buffer.append(annotations[i].displayCharacter);
432         }
433       }
434
435       buffer.append(", ");
436     }
437
438     if (label.equals("Consensus"))
439     {
440       buffer.append("\n");
441
442       for (int i = 0; i < annotations.length; i++)
443       {
444         if (annotations[i] != null)
445         {
446           buffer.append(annotations[i].description);
447         }
448
449         buffer.append(", ");
450       }
451     }
452
453     return buffer.toString();
454   }
455
456   public void setThreshold(GraphLine line)
457   {
458     threshold = line;
459   }
460
461   public GraphLine getThreshold()
462   {
463     return threshold;
464   }
465
466   /**
467    * 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.
468    * @param seqRef
469    * @param startRes
470    * @param alreadyMapped
471    */
472   public void createSequenceMapping(SequenceI seqRef,
473                                     int startRes,
474                                     boolean alreadyMapped)
475   {
476
477     if (seqRef == null)
478     {
479       return;
480     }
481     if (annotations==null)
482     {
483       return;
484     }
485     sequenceMapping = new java.util.Hashtable();
486
487     sequenceRef = seqRef;
488     int seqPos;
489
490     for (int i = 0; i < annotations.length; i++)
491     {
492       if (annotations[i] != null)
493       {
494         if (alreadyMapped)
495         {
496           seqPos = seqRef.findPosition(i);
497         }
498         else
499         {
500           seqPos = i + startRes;
501         }
502
503         sequenceMapping.put(new Integer(seqPos), annotations[i]);
504       }
505     }
506
507   }
508
509   public void adjustForAlignment()
510   {
511     if (sequenceRef==null)
512       return;
513
514     if (annotations==null)
515     {
516       return;
517     }
518
519     int a = 0, aSize = sequenceRef.getLength();
520
521     if (aSize == 0)
522     {
523       //Its been deleted
524       return;
525     }
526
527     int position;
528     Annotation[] temp = new Annotation[aSize];
529     Integer index;
530
531     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
532     {
533       index = new Integer(a);
534       if (sequenceMapping.containsKey(index))
535       {
536         position = sequenceRef.findIndex(a) - 1;
537
538         temp[position] = (Annotation) sequenceMapping.get(index);
539       }
540     }
541
542     annotations = temp;
543   }
544   /**
545    * remove any null entries in annotation row and return the
546    * number of non-null annotation elements.
547    * @return
548    */
549   private int compactAnnotationArray() {
550     int j=0;
551     for (int i=0;i<annotations.length; i++) {
552       if (annotations[i]!=null && j!=i) {
553         annotations[j++] = annotations[i];
554       }
555     }
556     Annotation[] ann = annotations;
557     annotations = new Annotation[j];
558     System.arraycopy(ann, 0, annotations, 0, j);
559     ann = null;
560     return j;
561   }
562
563   /**
564    * Associate this annotion with the aligned residues of a particular sequence.
565    * sequenceMapping will be updated in the following way:
566    *   null sequenceI - existing mapping will be discarded but annotations left in mapped positions.
567    *   valid sequenceI not equal to current sequenceRef: mapping is discarded and rebuilt assuming 1:1 correspondence
568    *   TODO: overload with parameter to specify correspondence between current and new sequenceRef
569    * @param sequenceI
570    */
571   public void setSequenceRef(SequenceI sequenceI)
572   {
573     if (sequenceI != null)
574     {
575       if (sequenceRef != null)
576       {
577         if (sequenceRef != sequenceI && !sequenceRef.equals(sequenceI) && sequenceRef.getDatasetSequence()!=sequenceI.getDatasetSequence())
578         {
579           // if sequenceRef isn't intersecting with sequenceI
580           // throw away old mapping and reconstruct.
581           sequenceRef = null;
582           if (sequenceMapping != null)
583           {
584             sequenceMapping = null;
585             // compactAnnotationArray();
586           }
587           createSequenceMapping(sequenceI, 1, true);
588           adjustForAlignment();
589         }
590         else
591         {
592           // Mapping carried over
593           sequenceRef = sequenceI;
594         }
595       }
596       else
597       {
598         // No mapping exists
599         createSequenceMapping(sequenceI, 1, true);
600         adjustForAlignment();
601       }
602     }
603     else
604     {
605       // throw away the mapping without compacting.
606       sequenceMapping = null;
607       sequenceRef = null;
608     }
609   }
610
611   /**
612    * @return the score
613    */
614   public float getScore()
615   {
616     return score;
617   }
618
619   /**
620    * @param score the score to set
621    */
622   public void setScore(float score)
623   {
624     this.score = score;
625   }
626   /**
627    *
628    * @return true if annotation has an associated score
629    */
630   public boolean hasScore()
631   {
632     return hasScore;
633   }
634 }