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