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