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