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