Merge branch 'develop' (JAL-4102 2.11.2.6 patch release) into features/r2_11_2_alphaf...
[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     }
814     // TODO: check if we need to do this: JAL-952
815     // if (this.isrna=annotation.isrna)
816     {
817       // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
818     }
819     validateRangeAndDisplay(); // construct hashcodes, etc.
820   }
821
822   /**
823    * clip the annotation to the columns given by startRes and endRes (inclusive)
824    * and prune any existing sequenceMapping to just those columns.
825    * 
826    * @param startRes
827    * @param endRes
828    */
829   public void restrict(int startRes, int endRes)
830   {
831     if (annotations == null)
832     {
833       // non-positional
834       return;
835     }
836     if (startRes < 0)
837     {
838       startRes = 0;
839     }
840     if (startRes >= annotations.length)
841     {
842       startRes = annotations.length - 1;
843     }
844     if (endRes >= annotations.length)
845     {
846       endRes = annotations.length - 1;
847     }
848     if (annotations == null)
849     {
850       return;
851     }
852     Annotation[] temp = new Annotation[endRes - startRes + 1];
853     if (startRes < annotations.length)
854     {
855       System.arraycopy(annotations, startRes, temp, 0,
856               endRes - startRes + 1);
857     }
858     if (sequenceRef != null)
859     {
860       // Clip the mapping, if it exists.
861       int spos = sequenceRef.findPosition(startRes);
862       int epos = sequenceRef.findPosition(endRes);
863       if (sequenceMapping != null)
864       {
865         Map<Integer, Annotation> newmapping = new HashMap<>();
866         Iterator<Integer> e = sequenceMapping.keySet().iterator();
867         while (e.hasNext())
868         {
869           Integer pos = e.next();
870           if (pos.intValue() >= spos && pos.intValue() <= epos)
871           {
872             newmapping.put(pos, sequenceMapping.get(pos));
873           }
874         }
875         sequenceMapping.clear();
876         sequenceMapping = newmapping;
877       }
878     }
879     annotations = temp;
880   }
881
882   /**
883    * set the annotation row to be at least length Annotations
884    * 
885    * @param length
886    *          minimum number of columns required in the annotation row
887    * @return false if the annotation row is greater than length
888    */
889   public boolean padAnnotation(int length)
890   {
891     if (annotations == null)
892     {
893       return true; // annotation row is correct - null == not visible and
894       // undefined length
895     }
896     if (annotations.length < length)
897     {
898       Annotation[] na = new Annotation[length];
899       System.arraycopy(annotations, 0, na, 0, annotations.length);
900       annotations = na;
901       return true;
902     }
903     return annotations.length > length;
904
905   }
906
907   /**
908    * DOCUMENT ME!
909    * 
910    * @return DOCUMENT ME!
911    */
912   @Override
913   public String toString()
914   {
915     if (annotations == null)
916     {
917       return "";
918     }
919     StringBuilder buffer = new StringBuilder(256);
920
921     for (int i = 0; i < annotations.length; i++)
922     {
923       if (annotations[i] != null)
924       {
925         if (graph != 0)
926         {
927           buffer.append(annotations[i].value);
928         }
929         else if (hasIcons)
930         {
931           buffer.append(annotations[i].secondaryStructure);
932         }
933         else
934         {
935           buffer.append(annotations[i].displayCharacter);
936         }
937       }
938
939       buffer.append(", ");
940     }
941     // TODO: remove disgusting hack for 'special' treatment of consensus line.
942     if (label.indexOf("Consensus") == 0)
943     {
944       buffer.append("\n");
945
946       for (int i = 0; i < annotations.length; i++)
947       {
948         if (annotations[i] != null)
949         {
950           buffer.append(annotations[i].description);
951         }
952
953         buffer.append(", ");
954       }
955     }
956
957     return buffer.toString();
958   }
959
960   public void setThreshold(GraphLine line)
961   {
962     threshold = line;
963   }
964
965   public GraphLine getThreshold()
966   {
967     return threshold;
968   }
969
970   /**
971    * Attach the annotation to seqRef, starting from startRes position. If
972    * alreadyMapped is true then the indices of the annotation[] array are
973    * sequence positions rather than alignment column positions.
974    * 
975    * @param seqRef
976    * @param startRes
977    * @param alreadyMapped
978    */
979   public void createSequenceMapping(SequenceI seqRef, int startRes,
980           boolean alreadyMapped)
981   {
982
983     if (seqRef == null)
984     {
985       return;
986     }
987     sequenceRef = seqRef;
988     if (annotations == null)
989     {
990       return;
991     }
992     sequenceMapping = new HashMap<>();
993
994     int seqPos;
995
996     for (int i = 0; i < annotations.length; i++)
997     {
998       if (annotations[i] != null)
999       {
1000         if (alreadyMapped)
1001         {
1002           seqPos = seqRef.findPosition(i);
1003         }
1004         else
1005         {
1006           seqPos = i + startRes;
1007         }
1008
1009         sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1010       }
1011     }
1012
1013   }
1014
1015   /**
1016    * When positional annotation and a sequence reference is present, clears and
1017    * resizes the annotations array to the current alignment width, and adds
1018    * annotation according to aligned positions of the sequenceRef given by
1019    * sequenceMapping.
1020    */
1021   public void adjustForAlignment()
1022   {
1023     if (sequenceRef == null)
1024     {
1025       return;
1026     }
1027
1028     if (annotations == null)
1029     {
1030       return;
1031     }
1032
1033     int a = 0, aSize = sequenceRef.getLength();
1034
1035     if (aSize == 0)
1036     {
1037       // Its been deleted
1038       return;
1039     }
1040
1041     int position;
1042     Annotation[] temp = new Annotation[aSize];
1043     Integer index;
1044     if (sequenceMapping != null)
1045     {
1046       for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1047       {
1048         index = Integer.valueOf(a);
1049         Annotation annot = sequenceMapping.get(index);
1050         if (annot != null)
1051         {
1052           position = sequenceRef.findIndex(a) - 1;
1053
1054           temp[position] = annot;
1055         }
1056       }
1057     }
1058     annotations = temp;
1059   }
1060
1061   /**
1062    * remove any null entries in annotation row and return the number of non-null
1063    * annotation elements.
1064    * 
1065    * @return
1066    */
1067   public int compactAnnotationArray()
1068   {
1069     int i = 0, iSize = annotations.length;
1070     while (i < iSize)
1071     {
1072       if (annotations[i] == null)
1073       {
1074         if (i + 1 < iSize)
1075         {
1076           System.arraycopy(annotations, i + 1, annotations, i,
1077                   iSize - i - 1);
1078         }
1079         iSize--;
1080       }
1081       else
1082       {
1083         i++;
1084       }
1085     }
1086     Annotation[] ann = annotations;
1087     annotations = new Annotation[i];
1088     System.arraycopy(ann, 0, annotations, 0, i);
1089     ann = null;
1090     return iSize;
1091   }
1092
1093   /**
1094    * Associate this annotation with the aligned residues of a particular
1095    * sequence. sequenceMapping will be updated in the following way: null
1096    * sequenceI - existing mapping will be discarded but annotations left in
1097    * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1098    * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1099    * parameter to specify correspondence between current and new sequenceRef
1100    * 
1101    * @param sequenceI
1102    */
1103   public void setSequenceRef(SequenceI sequenceI)
1104   {
1105     if (sequenceI != null)
1106     {
1107       if (sequenceRef != null)
1108       {
1109         boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1110                 tIsDs = sequenceI.getDatasetSequence() == null;
1111         if (sequenceRef != sequenceI
1112                 && (rIsDs && !tIsDs
1113                         && sequenceRef != sequenceI.getDatasetSequence())
1114                 && (!rIsDs && tIsDs
1115                         && sequenceRef.getDatasetSequence() != sequenceI)
1116                 && (!rIsDs && !tIsDs
1117                         && sequenceRef.getDatasetSequence() != sequenceI
1118                                 .getDatasetSequence())
1119                 && !sequenceRef.equals(sequenceI))
1120         {
1121           // if sequenceRef isn't intersecting with sequenceI
1122           // throw away old mapping and reconstruct.
1123           sequenceRef = null;
1124           if (sequenceMapping != null)
1125           {
1126             sequenceMapping = null;
1127             // compactAnnotationArray();
1128           }
1129           createSequenceMapping(sequenceI, 1, true);
1130           adjustForAlignment();
1131         }
1132         else
1133         {
1134           // Mapping carried over
1135           sequenceRef = sequenceI;
1136         }
1137       }
1138       else
1139       {
1140         // No mapping exists
1141         createSequenceMapping(sequenceI, 1, true);
1142         adjustForAlignment();
1143       }
1144     }
1145     else
1146     {
1147       // throw away the mapping without compacting.
1148       sequenceMapping = null;
1149       sequenceRef = null;
1150     }
1151   }
1152
1153   /**
1154    * @return the score
1155    */
1156   public double getScore()
1157   {
1158     return score;
1159   }
1160
1161   /**
1162    * @param score
1163    *          the score to set
1164    */
1165   public void setScore(double score)
1166   {
1167     hasScore = true;
1168     this.score = score;
1169   }
1170
1171   /**
1172    * 
1173    * @return true if annotation has an associated score
1174    */
1175   public boolean hasScore()
1176   {
1177     return hasScore || !Double.isNaN(score);
1178   }
1179
1180   /**
1181    * Score only annotation
1182    * 
1183    * @param label
1184    * @param description
1185    * @param score
1186    */
1187   public AlignmentAnnotation(String label, String description, double score)
1188   {
1189     this(label, description, null);
1190     setScore(score);
1191   }
1192
1193   /**
1194    * copy constructor with edit based on the hidden columns marked in colSel
1195    * 
1196    * @param alignmentAnnotation
1197    * @param colSel
1198    */
1199   public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1200           HiddenColumns hidden)
1201   {
1202     this(alignmentAnnotation);
1203     if (annotations == null)
1204     {
1205       return;
1206     }
1207     makeVisibleAnnotation(hidden);
1208   }
1209
1210   public void setPadGaps(boolean padgaps, char gapchar)
1211   {
1212     this.padGaps = padgaps;
1213     if (padgaps)
1214     {
1215       hasText = true;
1216       for (int i = 0; i < annotations.length; i++)
1217       {
1218         if (annotations[i] == null)
1219         {
1220           annotations[i] = new Annotation(String.valueOf(gapchar), null,
1221                   ' ', 0f, null);
1222         }
1223         else if (annotations[i].displayCharacter == null
1224                 || annotations[i].displayCharacter.equals(" "))
1225         {
1226           annotations[i].displayCharacter = String.valueOf(gapchar);
1227         }
1228       }
1229     }
1230   }
1231
1232   /**
1233    * format description string for display
1234    * 
1235    * @param seqname
1236    * @return Get the annotation description string optionally prefixed by
1237    *         associated sequence name (if any)
1238    */
1239   public String getDescription(boolean seqname)
1240   {
1241     if (seqname && this.sequenceRef != null)
1242     {
1243       int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1244       if (i > -1)
1245       {
1246         // move the html tag to before the sequence reference.
1247         return "<html>" + sequenceRef.getName() + " : "
1248                 + description.substring(i + 6);
1249       }
1250       return sequenceRef.getName() + " : " + description;
1251     }
1252     return description;
1253   }
1254
1255   public boolean isValidStruc()
1256   {
1257     return invalidrnastruc == -1;
1258   }
1259
1260   public long getInvalidStrucPos()
1261   {
1262     return invalidrnastruc;
1263   }
1264
1265   /**
1266    * machine readable ID string indicating what generated this annotation
1267    */
1268   protected String calcId = "";
1269
1270   /**
1271    * properties associated with the calcId
1272    */
1273   protected Map<String, String> properties = new HashMap<>();
1274
1275   /**
1276    * base colour for line graphs. If null, will be set automatically by
1277    * searching the alignment annotation
1278    */
1279   public java.awt.Color _linecolour;
1280
1281   public String getCalcId()
1282   {
1283     return calcId;
1284   }
1285
1286   public void setCalcId(String calcId)
1287   {
1288     this.calcId = calcId;
1289   }
1290
1291   public boolean isRNA()
1292   {
1293     return isrna;
1294   }
1295
1296   /**
1297    * transfer annotation to the given sequence using the given mapping from the
1298    * current positions or an existing sequence mapping
1299    * 
1300    * @param sq
1301    * @param sp2sq
1302    *          map involving sq as To or From
1303    */
1304   public void liftOver(SequenceI sq, Mapping sp2sq)
1305   {
1306     if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1307     {
1308       // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1309       // Protein reference frames
1310       throw new Error(
1311               "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1312     }
1313     boolean mapIsTo = (sp2sq != null)
1314             ? (sp2sq.getTo() == sq
1315                     || sp2sq.getTo() == sq.getDatasetSequence())
1316             : false;
1317
1318     // TODO build a better annotation element map and get rid of annotations[]
1319     Map<Integer, Annotation> mapForsq = new HashMap<>();
1320     if (sequenceMapping != null)
1321     {
1322       if (sp2sq != null)
1323       {
1324         for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1325         {
1326           Integer mpos = Integer
1327                   .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1328                           : sp2sq.getPosition(ie.getKey()));
1329           if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1330           {
1331             mapForsq.put(mpos, ie.getValue());
1332           }
1333         }
1334         sequenceMapping = mapForsq;
1335         sequenceRef = sq;
1336         adjustForAlignment();
1337       }
1338       else
1339       {
1340         // trim positions
1341       }
1342     }
1343   }
1344
1345   /**
1346    * like liftOver but more general.
1347    * 
1348    * Takes an array of int pairs that will be used to update the internal
1349    * sequenceMapping and so shuffle the annotated positions
1350    * 
1351    * @param newref
1352    *          - new sequence reference for the annotation row - if null,
1353    *          sequenceRef is left unchanged
1354    * @param mapping
1355    *          array of ints containing corresponding positions
1356    * @param from
1357    *          - column for current coordinate system (-1 for index+1)
1358    * @param to
1359    *          - column for destination coordinate system (-1 for index+1)
1360    * @param idxoffset
1361    *          - offset added to index when referencing either coordinate system
1362    * @note no checks are made as to whether from and/or to are sensible
1363    * @note caller should add the remapped annotation to newref if they have not
1364    *       already
1365    */
1366   public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1367           int from, int to, int idxoffset)
1368   {
1369     if (mapping != null)
1370     {
1371       Map<Integer, Annotation> old = sequenceMapping;
1372       Map<Integer, Annotation> remap = new HashMap<>();
1373       int index = -1;
1374       for (int mp[] : mapping.values())
1375       {
1376         if (index++ < 0)
1377         {
1378           continue;
1379         }
1380         Annotation ann = null;
1381         if (from == -1)
1382         {
1383           ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1384         }
1385         else
1386         {
1387           if (mp != null && mp.length > from)
1388           {
1389             ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1390           }
1391         }
1392         if (ann != null)
1393         {
1394           if (to == -1)
1395           {
1396             remap.put(Integer.valueOf(idxoffset + index), ann);
1397           }
1398           else
1399           {
1400             if (to > -1 && to < mp.length)
1401             {
1402               remap.put(Integer.valueOf(mp[to]), ann);
1403             }
1404           }
1405         }
1406       }
1407       sequenceMapping = remap;
1408       old.clear();
1409       if (newref != null)
1410       {
1411         sequenceRef = newref;
1412       }
1413       adjustForAlignment();
1414     }
1415   }
1416
1417   public String getProperty(String property)
1418   {
1419     if (properties == null)
1420     {
1421       return null;
1422     }
1423     return properties.get(property);
1424   }
1425
1426   public void setProperty(String property, String value)
1427   {
1428     if (properties == null)
1429     {
1430       properties = new HashMap<>();
1431     }
1432     properties.put(property, value);
1433   }
1434
1435   public boolean hasProperties()
1436   {
1437     return properties != null && properties.size() > 0;
1438   }
1439
1440   public Collection<String> getProperties()
1441   {
1442     if (properties == null)
1443     {
1444       return Collections.emptyList();
1445     }
1446     return properties.keySet();
1447   }
1448
1449   /**
1450    * Returns the Annotation for the given sequence position (base 1) if any,
1451    * else null
1452    * 
1453    * @param position
1454    * @return
1455    */
1456   public Annotation getAnnotationForPosition(int position)
1457   {
1458     return sequenceMapping == null ? null : sequenceMapping.get(position);
1459
1460   }
1461
1462   /**
1463    * Set the id to "ann" followed by a counter that increments so as to be
1464    * unique for the lifetime of the JVM
1465    */
1466   protected final void setAnnotationId()
1467   {
1468     this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1469   }
1470
1471   /**
1472    * Returns the match for the last unmatched opening RNA helix pair symbol
1473    * preceding the given column, or '(' if nothing found to match.
1474    * 
1475    * @param column
1476    * @return
1477    */
1478   public String getDefaultRnaHelixSymbol(int column)
1479   {
1480     String result = "(";
1481     if (annotations == null)
1482     {
1483       return result;
1484     }
1485
1486     /*
1487      * for each preceding column, if it contains an open bracket, 
1488      * count whether it is still unmatched at column, if so return its pair
1489      * (likely faster than the fancy alternative using stacks)
1490      */
1491     for (int col = column - 1; col >= 0; col--)
1492     {
1493       Annotation annotation = annotations[col];
1494       if (annotation == null)
1495       {
1496         continue;
1497       }
1498       String displayed = annotation.displayCharacter;
1499       if (displayed == null || displayed.length() != 1)
1500       {
1501         continue;
1502       }
1503       char symbol = displayed.charAt(0);
1504       if (!Rna.isOpeningParenthesis(symbol))
1505       {
1506         continue;
1507       }
1508
1509       /*
1510        * found an opening bracket symbol
1511        * count (closing-opening) symbols of this type that follow it,
1512        * up to and excluding the target column; if the count is less
1513        * than 1, the opening bracket is unmatched, so return its match
1514        */
1515       String closer = String
1516               .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1517       String opener = String.valueOf(symbol);
1518       int count = 0;
1519       for (int j = col + 1; j < column; j++)
1520       {
1521         if (annotations[j] != null)
1522         {
1523           String s = annotations[j].displayCharacter;
1524           if (closer.equals(s))
1525           {
1526             count++;
1527           }
1528           else if (opener.equals(s))
1529           {
1530             count--;
1531           }
1532         }
1533       }
1534       if (count < 1)
1535       {
1536         return closer;
1537       }
1538     }
1539     return result;
1540   }
1541
1542   protected static synchronized long nextId()
1543   {
1544     return counter++;
1545   }
1546
1547   /**
1548    * 
1549    * @return true for rows that have a range of values in their annotation set
1550    */
1551   public boolean isQuantitative()
1552   {
1553     return graphMin < graphMax;
1554   }
1555
1556   /**
1557    * delete any columns in alignmentAnnotation that are hidden (including
1558    * sequence associated annotation).
1559    * 
1560    * @param hiddenColumns
1561    *          the set of hidden columns
1562    */
1563   public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1564   {
1565     if (annotations != null)
1566     {
1567       makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1568     }
1569   }
1570
1571   /**
1572    * delete any columns in alignmentAnnotation that are hidden (including
1573    * sequence associated annotation).
1574    * 
1575    * @param start
1576    *          remove any annotation to the right of this column
1577    * @param end
1578    *          remove any annotation to the left of this column
1579    * @param hiddenColumns
1580    *          the set of hidden columns
1581    */
1582   public void makeVisibleAnnotation(int start, int end,
1583           HiddenColumns hiddenColumns)
1584   {
1585     if (annotations != null)
1586     {
1587       if (hiddenColumns.hasHiddenColumns())
1588       {
1589         removeHiddenAnnotation(start, end, hiddenColumns);
1590       }
1591       else
1592       {
1593         restrict(start, end);
1594       }
1595     }
1596   }
1597
1598   /**
1599    * The actual implementation of deleting hidden annotation columns
1600    * 
1601    * @param start
1602    *          remove any annotation to the right of this column
1603    * @param end
1604    *          remove any annotation to the left of this column
1605    * @param hiddenColumns
1606    *          the set of hidden columns
1607    */
1608   private void removeHiddenAnnotation(int start, int end,
1609           HiddenColumns hiddenColumns)
1610   {
1611     // mangle the alignmentAnnotation annotation array
1612     ArrayList<Annotation[]> annels = new ArrayList<>();
1613     Annotation[] els = null;
1614
1615     int w = 0;
1616
1617     Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1618             end + 1, false);
1619
1620     int copylength;
1621     int annotationLength;
1622     while (blocks.hasNext())
1623     {
1624       int[] block = blocks.next();
1625       annotationLength = block[1] - block[0] + 1;
1626
1627       if (blocks.hasNext())
1628       {
1629         // copy just the visible segment of the annotation row
1630         copylength = annotationLength;
1631       }
1632       else
1633       {
1634         if (annotationLength + block[0] <= annotations.length)
1635         {
1636           // copy just the visible segment of the annotation row
1637           copylength = annotationLength;
1638         }
1639         else
1640         {
1641           // copy to the end of the annotation row
1642           copylength = annotations.length - block[0];
1643         }
1644       }
1645
1646       els = new Annotation[annotationLength];
1647       annels.add(els);
1648       System.arraycopy(annotations, block[0], els, 0, copylength);
1649       w += annotationLength;
1650     }
1651
1652     if (w != 0)
1653     {
1654       annotations = new Annotation[w];
1655
1656       w = 0;
1657       for (Annotation[] chnk : annels)
1658       {
1659         System.arraycopy(chnk, 0, annotations, w, chnk.length);
1660         w += chnk.length;
1661       }
1662     }
1663   }
1664
1665   public static Iterable<AlignmentAnnotation> findAnnotations(
1666           Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1667           String label)
1668   {
1669
1670     ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1671     for (AlignmentAnnotation ann : list)
1672     {
1673       if ((calcId == null || (ann.getCalcId() != null
1674               && ann.getCalcId().equals(calcId)))
1675               && (seq == null || (ann.sequenceRef != null
1676                       && ann.sequenceRef == seq))
1677               && (label == null
1678                       || (ann.label != null && ann.label.equals(label))))
1679       {
1680         aa.add(ann);
1681       }
1682     }
1683     return aa;
1684   }
1685
1686   /**
1687    * Answer true if any annotation matches the calcId passed in (if not null).
1688    * 
1689    * @param list
1690    *          annotation to search
1691    * @param calcId
1692    * @return
1693    */
1694   public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1695           String calcId)
1696   {
1697
1698     if (calcId != null && !"".equals(calcId))
1699     {
1700       for (AlignmentAnnotation a : list)
1701       {
1702         if (a.getCalcId() == calcId)
1703         {
1704           return true;
1705         }
1706       }
1707     }
1708     return false;
1709   }
1710
1711   public static Iterable<AlignmentAnnotation> findAnnotation(
1712           List<AlignmentAnnotation> list, String calcId)
1713   {
1714
1715     List<AlignmentAnnotation> aa = new ArrayList<>();
1716     if (calcId == null)
1717     {
1718       return aa;
1719     }
1720     for (AlignmentAnnotation a : list)
1721     {
1722
1723       if (a.getCalcId() == calcId || (a.getCalcId() != null
1724               && calcId != null && a.getCalcId().equals(calcId)))
1725       {
1726         aa.add(a);
1727       }
1728     }
1729     return aa;
1730   }
1731
1732 }