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