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