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