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