JAL-1775 patch for regression from Anne Menard’s pseudo knot support JAL-1598
[jalview.git] / src / jalview / datamodel / AlignmentAnnotation.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.datamodel;
22
23 import jalview.analysis.Rna;
24 import jalview.analysis.SecStrConsensus.SimpleBP;
25 import jalview.analysis.WUSSParseException;
26
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.Map;
33 import java.util.Map.Entry;
34
35 /**
36  * DOCUMENT ME!
37  * 
38  * @author $author$
39  * @version $Revision$
40  */
41 public class AlignmentAnnotation
42 {
43   /*
44    * Identifers for different types of profile data
45    */
46   public static final int SEQUENCE_PROFILE = 0;
47
48   public static final int STRUCTURE_PROFILE = 1;
49
50   public static final int CDNA_PROFILE = 2;
51
52   /**
53    * If true, this annotations is calculated every edit, eg consensus, quality
54    * or conservation graphs
55    */
56   public boolean autoCalculated = false;
57
58   /**
59    * unique ID for this annotation, used to match up the same annotation row
60    * shown in multiple views and alignments
61    */
62   public String annotationId;
63
64   /**
65    * the sequence this annotation is associated with (or null)
66    */
67   public SequenceI sequenceRef;
68
69   /** label shown in dropdown menus and in the annotation label area */
70   public String label;
71
72   /** longer description text shown as a tooltip */
73   public String description;
74
75   /** Array of annotations placed in the current coordinate system */
76   public Annotation[] annotations;
77
78   public ArrayList<SimpleBP> bps = null;
79
80   /**
81    * RNA secondary structure contact positions
82    */
83   public SequenceFeature[] _rnasecstr = null;
84
85   /**
86    * position of annotation resulting in invalid WUSS parsing or -1. -2 means
87    * there was no RNA structure in this annotation
88    */
89   private long invalidrnastruc = -2;
90
91   /**
92    * Updates the _rnasecstr field Determines the positions that base pair and
93    * the positions of helices based on secondary structure from a Stockholm file
94    * 
95    * @param RNAannot
96    */
97   private void _updateRnaSecStr(CharSequence RNAannot)
98   {
99     try
100     {
101       _rnasecstr = Rna.GetBasePairs(RNAannot);
102       bps = Rna.GetModeleBP(RNAannot);
103       invalidrnastruc = -1;
104     } catch (WUSSParseException px)
105     {
106       // DEBUG System.out.println(px);
107       invalidrnastruc = px.getProblemPos();
108     }
109     if (invalidrnastruc > -1)
110     {
111       return;
112     }
113     Rna.HelixMap(_rnasecstr);
114     // setRNAStruc(RNAannot);
115
116     if (_rnasecstr != null && _rnasecstr.length > 0)
117     {
118       // show all the RNA secondary structure annotation symbols.
119       isrna = true;
120       showAllColLabels = true;
121       scaleColLabel = true;
122       _markRnaHelices();
123     }
124     // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
125
126   }
127
128   private void _markRnaHelices()
129   {
130     int mxval = 0;
131     // Figure out number of helices
132     // Length of rnasecstr is the number of pairs of positions that base pair
133     // with each other in the secondary structure
134     for (int x = 0; x < _rnasecstr.length; x++)
135     {
136
137       /*
138        * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
139        * this.annotation._rnasecstr[x].getBegin());
140        */
141       // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
142       int val = 0;
143       try
144       {
145         val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
146         if (mxval < val)
147         {
148           mxval = val;
149         }
150       } catch (NumberFormatException q)
151       {
152       }
153       ;
154
155       annotations[_rnasecstr[x].getBegin()].value = val;
156       annotations[_rnasecstr[x].getEnd()].value = val;
157
158       // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
159       // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
160     }
161     setScore(mxval);
162   }
163   /**
164    * map of positions in the associated annotation
165    */
166   private Map<Integer, Annotation> sequenceMapping;
167
168   /** DOCUMENT ME!! */
169   public float graphMin;
170
171   /** DOCUMENT ME!! */
172   public float graphMax;
173
174   /**
175    * Score associated with label and description.
176    */
177   public double score = Double.NaN;
178
179   /**
180    * flag indicating if annotation has a score.
181    */
182   public boolean hasScore = false;
183
184   public GraphLine threshold;
185
186   // Graphical hints and tips
187
188   /** Can this row be edited by the user ? */
189   public boolean editable = false;
190
191   /** Indicates if annotation has a graphical symbol track */
192   public boolean hasIcons; //
193
194   /** Indicates if annotation has a text character label */
195   public boolean hasText;
196
197   /** is the row visible */
198   public boolean visible = true;
199
200   public int graphGroup = -1;
201
202   /** Displayed height of row in pixels */
203   public int height = 0;
204
205   public int graph = 0;
206
207   public int graphHeight = 40;
208
209   public boolean padGaps = false;
210
211   public static final int NO_GRAPH = 0;
212
213   public static final int BAR_GRAPH = 1;
214
215   public static final int LINE_GRAPH = 2;
216
217   public boolean belowAlignment = true;
218
219   public SequenceGroup groupRef = null;
220
221   /**
222    * display every column label, even if there is a row of identical labels
223    */
224   public boolean showAllColLabels = false;
225
226   /**
227    * scale the column label to fit within the alignment column.
228    */
229   public boolean scaleColLabel = false;
230
231   /**
232    * centre the column labels relative to the alignment column
233    */
234   public boolean centreColLabels = false;
235
236   private boolean isrna;
237
238   /*
239    * (non-Javadoc)
240    * 
241    * @see java.lang.Object#finalize()
242    */
243   protected void finalize() throws Throwable
244   {
245     sequenceRef = null;
246     groupRef = null;
247     super.finalize();
248   }
249
250   public static int getGraphValueFromString(String string)
251   {
252     if (string.equalsIgnoreCase("BAR_GRAPH"))
253     {
254       return BAR_GRAPH;
255     }
256     else if (string.equalsIgnoreCase("LINE_GRAPH"))
257     {
258       return LINE_GRAPH;
259     }
260     else
261     {
262       return NO_GRAPH;
263     }
264   }
265
266   // JBPNote: what does this do ?
267   public void ConcenStru(CharSequence RNAannot) throws WUSSParseException
268   {
269     bps = Rna.GetModeleBP(RNAannot);
270   }
271
272   /**
273    * Creates a new AlignmentAnnotation object.
274    * 
275    * @param label
276    *          short label shown under sequence labels
277    * @param description
278    *          text displayed on mouseover
279    * @param annotations
280    *          set of positional annotation elements
281    */
282   public AlignmentAnnotation(String label, String description,
283           Annotation[] annotations)
284   {
285     // always editable?
286     editable = true;
287     this.label = label;
288     this.description = description;
289     this.annotations = annotations;
290
291     validateRangeAndDisplay();
292   }
293
294   /**
295    * Checks if annotation labels represent secondary structures
296    * 
297    */
298   void areLabelsSecondaryStructure()
299   {
300     boolean nonSSLabel = false;
301     isrna = false;
302     StringBuffer rnastring = new StringBuffer();
303
304     char firstChar = 0;
305     for (int i = 0; i < annotations.length; i++)
306     {
307       if (annotations[i] == null)
308       {
309         continue;
310       }
311       if (annotations[i].secondaryStructure == 'H'
312               || annotations[i].secondaryStructure == 'E')
313       {
314         hasIcons |= true;
315       }
316       else
317       // Check for RNA secondary structure
318       {
319         // System.out.println(annotations[i].secondaryStructure);
320         // TODO: 2.8.2 should this ss symbol validation check be a function in
321         // RNA/ResidueProperties ?
322         if (annotations[i].secondaryStructure == '('
323                 || annotations[i].secondaryStructure == '['
324                 || annotations[i].secondaryStructure == '<'
325                 || annotations[i].secondaryStructure == '{'
326                 || annotations[i].secondaryStructure == 'A'
327                 || annotations[i].secondaryStructure == 'B'
328                 || annotations[i].secondaryStructure == 'C'
329                 || annotations[i].secondaryStructure == 'D'
330                 || annotations[i].secondaryStructure == 'E'
331                 || annotations[i].secondaryStructure == 'F'
332                 || annotations[i].secondaryStructure == 'G'
333                 || annotations[i].secondaryStructure == 'H'
334                 || annotations[i].secondaryStructure == 'I'
335                 || annotations[i].secondaryStructure == 'J'
336                 || annotations[i].secondaryStructure == 'K'
337                 || annotations[i].secondaryStructure == 'L'
338                 || annotations[i].secondaryStructure == 'M'
339                 || annotations[i].secondaryStructure == 'N'
340                 || annotations[i].secondaryStructure == 'O'
341                 || annotations[i].secondaryStructure == 'P'
342                 || annotations[i].secondaryStructure == 'Q'
343                 || annotations[i].secondaryStructure == 'R'
344                 || annotations[i].secondaryStructure == 'S'
345                 || annotations[i].secondaryStructure == 'T'
346                 || annotations[i].secondaryStructure == 'U'
347                 || annotations[i].secondaryStructure == 'V'
348                 || annotations[i].secondaryStructure == 'W'
349                 || annotations[i].secondaryStructure == 'X'
350                 || annotations[i].secondaryStructure == 'Y'
351                 || annotations[i].secondaryStructure == 'Z')
352         {
353           hasIcons |= true;
354           isrna |= true;
355         }
356       }
357
358       // System.out.println("displaychar " + annotations[i].displayCharacter);
359
360       if (annotations[i].displayCharacter == null
361               || annotations[i].displayCharacter.length() == 0)
362       {
363         rnastring.append('.');
364         continue;
365       }
366       if (annotations[i].displayCharacter.length() == 1)
367       {
368         firstChar = annotations[i].displayCharacter.charAt(0);
369         // check to see if it looks like a sequence or is secondary structure
370         // labelling.
371         if (annotations[i].secondaryStructure != ' '
372                 && !hasIcons
373                 &&
374                 // Uncomment to only catch case where
375                 // displayCharacter==secondary
376                 // Structure
377                 // to correctly redisplay SS annotation imported from Stockholm,
378                 // exported to JalviewXML and read back in again.
379                 // &&
380                 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
381                 firstChar != ' '
382                 && firstChar != '$'
383                 && firstChar != 0xCE
384                 && firstChar != '('
385                 && firstChar != '['
386                 && firstChar != '>'
387                 && firstChar != '{'
388                 && firstChar != 'A'
389                 && firstChar != 'B'
390                 && firstChar != 'C'
391                 && firstChar != 'D'
392                 && firstChar != 'E'
393                 && firstChar != 'F'
394                 && firstChar != 'G'
395                 && firstChar != 'H'
396                 && firstChar != 'I'
397                 && firstChar != 'J'
398                 && firstChar != 'K'
399                 && firstChar != 'L'
400                 && firstChar != 'M'
401                 && firstChar != 'N'
402                 && firstChar != 'O'
403                 && firstChar != 'P'
404                 && firstChar != 'Q'
405                 && firstChar != 'R'
406                 && firstChar != 'S'
407                 && firstChar != 'T'
408                 && firstChar != 'U'
409                 && firstChar != 'V'
410                 && firstChar != 'W'
411                 && firstChar != 'X'
412                 && firstChar != 'Y'
413                 && firstChar != 'Z'
414                 && firstChar != '-'
415                 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
416         {
417           if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
418                                                                          // parameterise
419                                                                          // to
420                                                                          // gap
421                                                                          // symbol
422                                                                          // number
423           {
424             nonSSLabel = true;
425           }
426         }
427       }
428       else
429       {
430         rnastring.append(annotations[i].displayCharacter.charAt(1));
431       }
432
433       if (annotations[i].displayCharacter.length() > 0)
434       {
435         hasText = true;
436       }
437     }
438
439     if (nonSSLabel)
440     {
441       hasIcons = false;
442       for (int j = 0; j < annotations.length; j++)
443       {
444         if (annotations[j] != null
445                 && annotations[j].secondaryStructure != ' ')
446         {
447           annotations[j].displayCharacter = String
448                   .valueOf(annotations[j].secondaryStructure);
449           annotations[j].secondaryStructure = ' ';
450         }
451
452       }
453     }
454     else
455     {
456       if (isrna)
457       {
458         _updateRnaSecStr(new AnnotCharSequence());
459       }
460     }
461
462     annotationId = this.hashCode() + "";
463   }
464
465   /**
466    * flyweight access to positions in the alignment annotation row for RNA
467    * processing
468    * 
469    * @author jimp
470    * 
471    */
472   private class AnnotCharSequence implements CharSequence
473   {
474     int offset = 0;
475
476     int max = 0;
477
478     public AnnotCharSequence()
479     {
480       this(0, annotations.length);
481     }
482
483     public AnnotCharSequence(int start, int end)
484     {
485       offset = start;
486       max = end;
487     }
488
489     @Override
490     public CharSequence subSequence(int start, int end)
491     {
492       return new AnnotCharSequence(offset + start, offset + end);
493     }
494
495     @Override
496     public int length()
497     {
498       return max - offset;
499     }
500
501     @Override
502     public char charAt(int index)
503     {
504       return ((index + offset < 0) || (index + offset) >= max
505               || annotations[index + offset] == null
506               || (annotations[index + offset].secondaryStructure <= ' ') ? ' '
507               : annotations[index + offset].displayCharacter == null
508                       || annotations[index + offset].displayCharacter
509                               .length() == 0 ? annotations[index + offset].secondaryStructure
510                       : annotations[index + offset].displayCharacter
511                               .charAt(0));
512     }
513
514     @Override
515     public String toString()
516     {
517       char[] string = new char[max - offset];
518       int mx = annotations.length;
519
520       for (int i = offset; i < mx; i++)
521       {
522         string[i] = (annotations[i] == null || (annotations[i].secondaryStructure <= 32)) ? ' '
523                 : (annotations[i].displayCharacter == null
524                         || annotations[i].displayCharacter.length() == 0 ? annotations[i].secondaryStructure
525                         : annotations[i].displayCharacter.charAt(0));
526       }
527       return new String(string);
528     }
529   };
530
531   private long _lastrnaannot = -1;
532
533   public String getRNAStruc()
534   {
535     if (isrna)
536     {
537       String rnastruc = new AnnotCharSequence().toString();
538       if (_lastrnaannot != rnastruc.hashCode())
539       {
540         // ensure rna structure contacts are up to date
541         _lastrnaannot = rnastruc.hashCode();
542         _updateRnaSecStr(rnastruc);
543       }
544       return rnastruc;
545     }
546     return null;
547   }
548
549   /**
550    * Creates a new AlignmentAnnotation object.
551    * 
552    * @param label
553    *          DOCUMENT ME!
554    * @param description
555    *          DOCUMENT ME!
556    * @param annotations
557    *          DOCUMENT ME!
558    * @param min
559    *          DOCUMENT ME!
560    * @param max
561    *          DOCUMENT ME!
562    * @param winLength
563    *          DOCUMENT ME!
564    */
565   public AlignmentAnnotation(String label, String description,
566           Annotation[] annotations, float min, float max, int graphType)
567   {
568     // graphs are not editable
569     editable = graphType == 0;
570
571     this.label = label;
572     this.description = description;
573     this.annotations = annotations;
574     graph = graphType;
575     graphMin = min;
576     graphMax = max;
577     validateRangeAndDisplay();
578   }
579
580   /**
581    * checks graphMin and graphMax, secondary structure symbols, sets graphType
582    * appropriately, sets null labels to the empty string if appropriate.
583    */
584   public void validateRangeAndDisplay()
585   {
586
587     if (annotations == null)
588     {
589       visible = false; // try to prevent renderer from displaying.
590       return; // this is a non-annotation row annotation - ie a sequence score.
591     }
592
593     int graphType = graph;
594     float min = graphMin;
595     float max = graphMax;
596     boolean drawValues = true;
597     _linecolour = null;
598     if (min == max)
599     {
600       min = 999999999;
601       for (int i = 0; i < annotations.length; i++)
602       {
603         if (annotations[i] == null)
604         {
605           continue;
606         }
607
608         if (drawValues && annotations[i].displayCharacter != null
609                 && annotations[i].displayCharacter.length() > 1)
610         {
611           drawValues = false;
612         }
613
614         if (annotations[i].value > max)
615         {
616           max = annotations[i].value;
617         }
618
619         if (annotations[i].value < min)
620         {
621           min = annotations[i].value;
622         }
623         if (_linecolour == null && annotations[i].colour != null)
624         {
625           _linecolour = annotations[i].colour;
626         }
627       }
628       // ensure zero is origin for min/max ranges on only one side of zero
629       if (min > 0)
630       {
631         min = 0;
632       }
633       else
634       {
635         if (max < 0)
636         {
637           max = 0;
638         }
639       }
640     }
641
642     graphMin = min;
643     graphMax = max;
644
645     areLabelsSecondaryStructure();
646
647     if (!drawValues && graphType != NO_GRAPH)
648     {
649       for (int i = 0; i < annotations.length; i++)
650       {
651         if (annotations[i] != null)
652         {
653           annotations[i].displayCharacter = "";
654         }
655       }
656     }
657   }
658
659   /**
660    * Copy constructor creates a new independent annotation row with the same
661    * associated sequenceRef
662    * 
663    * @param annotation
664    */
665   public AlignmentAnnotation(AlignmentAnnotation annotation)
666   {
667     this.label = new String(annotation.label);
668     if (annotation.description != null)
669     {
670       this.description = new String(annotation.description);
671     }
672     this.graphMin = annotation.graphMin;
673     this.graphMax = annotation.graphMax;
674     this.graph = annotation.graph;
675     this.graphHeight = annotation.graphHeight;
676     this.graphGroup = annotation.graphGroup;
677     this.groupRef = annotation.groupRef;
678     this.editable = annotation.editable;
679     this.autoCalculated = annotation.autoCalculated;
680     this.hasIcons = annotation.hasIcons;
681     this.hasText = annotation.hasText;
682     this.height = annotation.height;
683     this.label = annotation.label;
684     this.padGaps = annotation.padGaps;
685     this.visible = annotation.visible;
686     this.centreColLabels = annotation.centreColLabels;
687     this.scaleColLabel = annotation.scaleColLabel;
688     this.showAllColLabels = annotation.showAllColLabels;
689     this.calcId = annotation.calcId;
690     if (annotation.properties!=null)
691     {
692       properties = new HashMap<String,String>();
693       for (Map.Entry<String, String> val:annotation.properties.entrySet())
694       {
695         properties.put(val.getKey(), val.getValue());
696       }
697     }
698     if (this.hasScore = annotation.hasScore)
699     {
700       this.score = annotation.score;
701     }
702     if (annotation.threshold != null)
703     {
704       threshold = new GraphLine(annotation.threshold);
705     }
706     Annotation[] ann = annotation.annotations;
707     if (annotation.annotations != null)
708     {
709       this.annotations = new Annotation[ann.length];
710       for (int i = 0; i < ann.length; i++)
711       {
712         if (ann[i] != null)
713         {
714           annotations[i] = new Annotation(ann[i]);
715           if (_linecolour != null)
716           {
717             _linecolour = annotations[i].colour;
718           }
719         }
720       }
721     }
722     if (annotation.sequenceRef != null)
723     {
724       this.sequenceRef = annotation.sequenceRef;
725       if (annotation.sequenceMapping != null)
726       {
727         Integer p = null;
728         sequenceMapping = new HashMap<Integer, Annotation>();
729         Iterator<Integer> pos = annotation.sequenceMapping.keySet()
730                 .iterator();
731         while (pos.hasNext())
732         {
733           // could optimise this!
734           p = pos.next();
735           Annotation a = annotation.sequenceMapping.get(p);
736           if (a == null)
737           {
738             continue;
739           }
740           if (ann != null)
741           {
742             for (int i = 0; i < ann.length; i++)
743             {
744               if (ann[i] == a)
745               {
746                 sequenceMapping.put(p, annotations[i]);
747               }
748             }
749           }
750         }
751       }
752       else
753       {
754         this.sequenceMapping = null;
755       }
756     }
757     // TODO: check if we need to do this: JAL-952
758     // if (this.isrna=annotation.isrna)
759     {
760       // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
761     }
762     validateRangeAndDisplay(); // construct hashcodes, etc.
763   }
764
765   /**
766    * clip the annotation to the columns given by startRes and endRes (inclusive)
767    * and prune any existing sequenceMapping to just those columns.
768    * 
769    * @param startRes
770    * @param endRes
771    */
772   public void restrict(int startRes, int endRes)
773   {
774     if (annotations == null)
775     {
776       // non-positional
777       return;
778     }
779     if (startRes < 0)
780     {
781       startRes = 0;
782     }
783     if (startRes >= annotations.length)
784     {
785       startRes = annotations.length - 1;
786     }
787     if (endRes >= annotations.length)
788     {
789       endRes = annotations.length - 1;
790     }
791     if (annotations == null)
792     {
793       return;
794     }
795     Annotation[] temp = new Annotation[endRes - startRes + 1];
796     if (startRes < annotations.length)
797     {
798       System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
799               + 1);
800     }
801     if (sequenceRef != null)
802     {
803       // Clip the mapping, if it exists.
804       int spos = sequenceRef.findPosition(startRes);
805       int epos = sequenceRef.findPosition(endRes);
806       if (sequenceMapping != null)
807       {
808         Map<Integer, Annotation> newmapping = new HashMap<Integer, Annotation>();
809         Iterator<Integer> e = sequenceMapping.keySet().iterator();
810         while (e.hasNext())
811         {
812           Integer pos = e.next();
813           if (pos.intValue() >= spos && pos.intValue() <= epos)
814           {
815             newmapping.put(pos, sequenceMapping.get(pos));
816           }
817         }
818         sequenceMapping.clear();
819         sequenceMapping = newmapping;
820       }
821     }
822     annotations = temp;
823   }
824
825   /**
826    * set the annotation row to be at least length Annotations
827    * 
828    * @param length
829    *          minimum number of columns required in the annotation row
830    * @return false if the annotation row is greater than length
831    */
832   public boolean padAnnotation(int length)
833   {
834     if (annotations == null)
835     {
836       return true; // annotation row is correct - null == not visible and
837       // undefined length
838     }
839     if (annotations.length < length)
840     {
841       Annotation[] na = new Annotation[length];
842       System.arraycopy(annotations, 0, na, 0, annotations.length);
843       annotations = na;
844       return true;
845     }
846     return annotations.length > length;
847
848   }
849
850   /**
851    * DOCUMENT ME!
852    * 
853    * @return DOCUMENT ME!
854    */
855   @Override
856   public String toString()
857   {
858     StringBuilder buffer = new StringBuilder(256);
859
860     for (int i = 0; i < annotations.length; i++)
861     {
862       if (annotations[i] != null)
863       {
864         if (graph != 0)
865         {
866           buffer.append(annotations[i].value);
867         }
868         else if (hasIcons)
869         {
870           buffer.append(annotations[i].secondaryStructure);
871         }
872         else
873         {
874           buffer.append(annotations[i].displayCharacter);
875         }
876       }
877
878       buffer.append(", ");
879     }
880     // TODO: remove disgusting hack for 'special' treatment of consensus line.
881     if (label.indexOf("Consensus") == 0)
882     {
883       buffer.append("\n");
884
885       for (int i = 0; i < annotations.length; i++)
886       {
887         if (annotations[i] != null)
888         {
889           buffer.append(annotations[i].description);
890         }
891
892         buffer.append(", ");
893       }
894     }
895
896     return buffer.toString();
897   }
898
899   public void setThreshold(GraphLine line)
900   {
901     threshold = line;
902   }
903
904   public GraphLine getThreshold()
905   {
906     return threshold;
907   }
908
909   /**
910    * Attach the annotation to seqRef, starting from startRes position. If
911    * alreadyMapped is true then the indices of the annotation[] array are
912    * sequence positions rather than alignment column positions.
913    * 
914    * @param seqRef
915    * @param startRes
916    * @param alreadyMapped
917    */
918   public void createSequenceMapping(SequenceI seqRef, int startRes,
919           boolean alreadyMapped)
920   {
921
922     if (seqRef == null)
923     {
924       return;
925     }
926     sequenceRef = seqRef;
927     if (annotations == null)
928     {
929       return;
930     }
931     sequenceMapping = new HashMap<Integer, Annotation>();
932
933     int seqPos;
934
935     for (int i = 0; i < annotations.length; i++)
936     {
937       if (annotations[i] != null)
938       {
939         if (alreadyMapped)
940         {
941           seqPos = seqRef.findPosition(i);
942         }
943         else
944         {
945           seqPos = i + startRes;
946         }
947
948         sequenceMapping.put(new Integer(seqPos), annotations[i]);
949       }
950     }
951
952   }
953
954   public void adjustForAlignment()
955   {
956     if (sequenceRef == null)
957     {
958       return;
959     }
960
961     if (annotations == null)
962     {
963       return;
964     }
965
966     int a = 0, aSize = sequenceRef.getLength();
967
968     if (aSize == 0)
969     {
970       // Its been deleted
971       return;
972     }
973
974     int position;
975     Annotation[] temp = new Annotation[aSize];
976     Integer index;
977
978     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
979     {
980       index = new Integer(a);
981       if (sequenceMapping.containsKey(index))
982       {
983         position = sequenceRef.findIndex(a) - 1;
984
985         temp[position] = sequenceMapping.get(index);
986       }
987     }
988
989     annotations = temp;
990   }
991
992   /**
993    * remove any null entries in annotation row and return the number of non-null
994    * annotation elements.
995    * 
996    * @return
997    */
998   public int compactAnnotationArray()
999   {
1000     int i = 0, iSize = annotations.length;
1001     while (i < iSize)
1002     {
1003       if (annotations[i] == null)
1004       {
1005         if (i + 1 < iSize)
1006         {
1007           System.arraycopy(annotations, i + 1, annotations, i, iSize - i
1008                   - 1);
1009         }
1010         iSize--;
1011       }
1012       else
1013       {
1014         i++;
1015       }
1016     }
1017     Annotation[] ann = annotations;
1018     annotations = new Annotation[i];
1019     System.arraycopy(ann, 0, annotations, 0, i);
1020     ann = null;
1021     return iSize;
1022   }
1023
1024   /**
1025    * Associate this annotion with the aligned residues of a particular sequence.
1026    * sequenceMapping will be updated in the following way: null sequenceI -
1027    * existing mapping will be discarded but annotations left in mapped
1028    * positions. valid sequenceI not equal to current sequenceRef: mapping is
1029    * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1030    * parameter to specify correspondence between current and new sequenceRef
1031    * 
1032    * @param sequenceI
1033    */
1034   public void setSequenceRef(SequenceI sequenceI)
1035   {
1036     if (sequenceI != null)
1037     {
1038       if (sequenceRef != null)
1039       {
1040         boolean rIsDs=sequenceRef.getDatasetSequence()==null,tIsDs=sequenceI.getDatasetSequence()==null;
1041         if (sequenceRef != sequenceI
1042                 && (rIsDs && !tIsDs && sequenceRef != sequenceI
1043                         .getDatasetSequence())
1044                 && (!rIsDs && tIsDs && sequenceRef.getDatasetSequence() != sequenceI)
1045                 && (!rIsDs && !tIsDs && sequenceRef.getDatasetSequence() != sequenceI
1046                         .getDatasetSequence())
1047                 && !sequenceRef.equals(sequenceI))
1048         {
1049           // if sequenceRef isn't intersecting with sequenceI
1050           // throw away old mapping and reconstruct.
1051           sequenceRef = null;
1052           if (sequenceMapping != null)
1053           {
1054             sequenceMapping = null;
1055             // compactAnnotationArray();
1056           }
1057           createSequenceMapping(sequenceI, 1, true);
1058           adjustForAlignment();
1059         }
1060         else
1061         {
1062           // Mapping carried over
1063           sequenceRef = sequenceI;
1064         }
1065       }
1066       else
1067       {
1068         // No mapping exists
1069         createSequenceMapping(sequenceI, 1, true);
1070         adjustForAlignment();
1071       }
1072     }
1073     else
1074     {
1075       // throw away the mapping without compacting.
1076       sequenceMapping = null;
1077       sequenceRef = null;
1078     }
1079   }
1080
1081   /**
1082    * @return the score
1083    */
1084   public double getScore()
1085   {
1086     return score;
1087   }
1088
1089   /**
1090    * @param score
1091    *          the score to set
1092    */
1093   public void setScore(double score)
1094   {
1095     hasScore = true;
1096     this.score = score;
1097   }
1098
1099   /**
1100    * 
1101    * @return true if annotation has an associated score
1102    */
1103   public boolean hasScore()
1104   {
1105     return hasScore || !Double.isNaN(score);
1106   }
1107
1108   /**
1109    * Score only annotation
1110    * 
1111    * @param label
1112    * @param description
1113    * @param score
1114    */
1115   public AlignmentAnnotation(String label, String description, double score)
1116   {
1117     this(label, description, null);
1118     setScore(score);
1119   }
1120
1121   /**
1122    * copy constructor with edit based on the hidden columns marked in colSel
1123    * 
1124    * @param alignmentAnnotation
1125    * @param colSel
1126    */
1127   public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1128           ColumnSelection colSel)
1129   {
1130     this(alignmentAnnotation);
1131     if (annotations == null)
1132     {
1133       return;
1134     }
1135     colSel.makeVisibleAnnotation(this);
1136   }
1137
1138   public void setPadGaps(boolean padgaps, char gapchar)
1139   {
1140     this.padGaps = padgaps;
1141     if (padgaps)
1142     {
1143       hasText = true;
1144       for (int i = 0; i < annotations.length; i++)
1145       {
1146         if (annotations[i] == null)
1147         {
1148           annotations[i] = new Annotation(String.valueOf(gapchar), null,
1149                   ' ', 0f, null);
1150         }
1151         else if (annotations[i].displayCharacter == null
1152                 || annotations[i].displayCharacter.equals(" "))
1153         {
1154           annotations[i].displayCharacter = String.valueOf(gapchar);
1155         }
1156       }
1157     }
1158   }
1159
1160   /**
1161    * format description string for display
1162    * 
1163    * @param seqname
1164    * @return Get the annotation description string optionally prefixed by
1165    *         associated sequence name (if any)
1166    */
1167   public String getDescription(boolean seqname)
1168   {
1169     if (seqname && this.sequenceRef != null)
1170     {
1171       int i = description.toLowerCase().indexOf("<html>");
1172       if (i > -1)
1173       {
1174         // move the html tag to before the sequence reference.
1175         return "<html>" + sequenceRef.getName() + " : "
1176                 + description.substring(i + 6);
1177       }
1178       return sequenceRef.getName() + " : " + description;
1179     }
1180     return description;
1181   }
1182
1183   public boolean isValidStruc()
1184   {
1185     return invalidrnastruc == -1;
1186   }
1187
1188   public long getInvalidStrucPos()
1189   {
1190     return invalidrnastruc;
1191   }
1192
1193   /**
1194    * machine readable ID string indicating what generated this annotation
1195    */
1196   protected String calcId = "";
1197
1198   /**
1199    * properties associated with the calcId
1200    */
1201   protected Map<String, String> properties = new HashMap<String, String>();
1202
1203   /**
1204    * base colour for line graphs. If null, will be set automatically by
1205    * searching the alignment annotation
1206    */
1207   public java.awt.Color _linecolour;
1208
1209   public String getCalcId()
1210   {
1211     return calcId;
1212   }
1213
1214   public void setCalcId(String calcId)
1215   {
1216     this.calcId = calcId;
1217   }
1218
1219   public boolean isRNA()
1220   {
1221     return isrna;
1222   }
1223
1224   /**
1225    * transfer annotation to the given sequence using the given mapping from the
1226    * current positions or an existing sequence mapping
1227    * 
1228    * @param sq
1229    * @param sp2sq
1230    *          map involving sq as To or From
1231    */
1232   public void liftOver(SequenceI sq, Mapping sp2sq)
1233   {
1234     if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1235     {
1236       // TODO: employ getWord/MappedWord to transfer annotation between cDNA and Protein reference frames
1237       throw new Error("liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1238     }
1239     boolean mapIsTo = (sp2sq != null) ? (sp2sq.getTo() == sq || sp2sq
1240             .getTo() == sq.getDatasetSequence()) : false;
1241
1242     // TODO build a better annotation element map and get rid of annotations[]
1243     Map<Integer, Annotation> mapForsq = new HashMap<Integer, Annotation>();
1244     if (sequenceMapping != null)
1245     {
1246       if (sp2sq != null)
1247       {
1248         for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1249         {
1250           Integer mpos = Integer.valueOf(mapIsTo ? sp2sq
1251                   .getMappedPosition(ie.getKey()) : sp2sq.getPosition(ie
1252                   .getKey()));
1253           if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1254           {
1255             mapForsq.put(mpos, ie.getValue());
1256           }
1257         }
1258         sequenceMapping = mapForsq;
1259         sequenceRef = sq;
1260         adjustForAlignment();
1261       }
1262       else
1263       {
1264         // trim positions
1265       }
1266     }
1267   }
1268
1269   /**
1270    * like liftOver but more general.
1271    * 
1272    * Takes an array of int pairs that will be used to update the internal
1273    * sequenceMapping and so shuffle the annotated positions
1274    * 
1275    * @param newref
1276    *          - new sequence reference for the annotation row - if null,
1277    *          sequenceRef is left unchanged
1278    * @param mapping
1279    *          array of ints containing corresponding positions
1280    * @param from
1281    *          - column for current coordinate system (-1 for index+1)
1282    * @param to
1283    *          - column for destination coordinate system (-1 for index+1)
1284    * @param idxoffset
1285    *          - offset added to index when referencing either coordinate system
1286    * @note no checks are made as to whether from and/or to are sensible
1287    * @note caller should add the remapped annotation to newref if they have not
1288    *       already
1289    */
1290   public void remap(SequenceI newref, int[][] mapping, int from, int to,
1291           int idxoffset)
1292   {
1293     if (mapping != null)
1294     {
1295       Map<Integer, Annotation> old = sequenceMapping;
1296       Map<Integer, Annotation> remap = new HashMap<Integer, Annotation>();
1297       int index = -1;
1298       for (int mp[] : mapping)
1299       {
1300         if (index++ < 0)
1301         {
1302           continue;
1303         }
1304         Annotation ann = null;
1305         if (from == -1)
1306         {
1307           ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1308         }
1309         else
1310         {
1311           if (mp != null && mp.length > from)
1312           {
1313             ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1314           }
1315         }
1316         if (ann != null)
1317         {
1318           if (to == -1)
1319           {
1320             remap.put(Integer.valueOf(idxoffset + index), ann);
1321           }
1322           else
1323           {
1324             if (to > -1 && to < mp.length)
1325             {
1326               remap.put(Integer.valueOf(mp[to]), ann);
1327             }
1328           }
1329         }
1330       }
1331       sequenceMapping = remap;
1332       old.clear();
1333       if (newref != null)
1334       {
1335         sequenceRef = newref;
1336       }
1337       adjustForAlignment();
1338     }
1339   }
1340
1341   public String getProperty(String property)
1342   {
1343     if (properties == null)
1344     {
1345       return null;
1346     }
1347     return properties.get(property);
1348   }
1349
1350   public void setProperty(String property, String value)
1351   {
1352     if (properties==null)
1353     {
1354       properties = new HashMap<String,String>();
1355     }
1356     properties.put(property, value);
1357   }
1358
1359   public boolean hasProperties()
1360   {
1361     return properties != null && properties.size() > 0;
1362   }
1363
1364   public Collection<String> getProperties()
1365   {
1366     if (properties == null)
1367     {
1368       return Collections.emptyList();
1369     }
1370     return properties.keySet();
1371   }
1372
1373   /**
1374    * Returns the Annotation for the given sequence position (base 1) if any,
1375    * else null
1376    * 
1377    * @param position
1378    * @return
1379    */
1380   public Annotation getAnnotationForPosition(int position)
1381   {
1382     return sequenceMapping == null ? null : sequenceMapping.get(position);
1383
1384   }
1385 }