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