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