JAL-1569 rna pair code in secondary structure character of annotation
[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       return ((index + offset < 0) || (index + offset) >= max
490               || annotations[index + offset] == null || (annotations[index
491  + offset].secondaryStructure < ' ') ? ' '
492               : annotations[index + offset].secondaryStructure);
493     }
494
495     public String toString()
496     {
497       char[] string = new char[max - offset];
498       int mx = annotations.length;
499
500       for (int i = offset; i < mx; i++)
501       {
502         string[i] = (annotations[i] == null || (annotations[i].secondaryStructure < 32)) ? ' '
503                 : annotations[i].secondaryStructure;
504       }
505       return new String(string);
506     }
507   };
508
509   private long _lastrnaannot = -1;
510
511   public String getRNAStruc()
512   {
513     if (isrna)
514     {
515       String rnastruc = new AnnotCharSequence().toString();
516       if (_lastrnaannot != rnastruc.hashCode())
517       {
518         // ensure rna structure contacts are up to date
519         _lastrnaannot = rnastruc.hashCode();
520         _updateRnaSecStr(rnastruc);
521       }
522       return rnastruc;
523     }
524     return null;
525   }
526
527   /**
528    * Creates a new AlignmentAnnotation object.
529    * 
530    * @param label
531    *          DOCUMENT ME!
532    * @param description
533    *          DOCUMENT ME!
534    * @param annotations
535    *          DOCUMENT ME!
536    * @param min
537    *          DOCUMENT ME!
538    * @param max
539    *          DOCUMENT ME!
540    * @param winLength
541    *          DOCUMENT ME!
542    */
543   public AlignmentAnnotation(String label, String description,
544           Annotation[] annotations, float min, float max, int graphType)
545   {
546     // graphs are not editable
547     editable = graphType == 0;
548
549     this.label = label;
550     this.description = description;
551     this.annotations = annotations;
552     graph = graphType;
553     graphMin = min;
554     graphMax = max;
555     validateRangeAndDisplay();
556   }
557
558   /**
559    * checks graphMin and graphMax, secondary structure symbols, sets graphType
560    * appropriately, sets null labels to the empty string if appropriate.
561    */
562   public void validateRangeAndDisplay()
563   {
564
565     if (annotations == null)
566     {
567       visible = false; // try to prevent renderer from displaying.
568       return; // this is a non-annotation row annotation - ie a sequence score.
569     }
570
571     int graphType = graph;
572     float min = graphMin;
573     float max = graphMax;
574     boolean drawValues = true;
575     _linecolour = null;
576     if (min == max)
577     {
578       min = 999999999;
579       for (int i = 0; i < annotations.length; i++)
580       {
581         if (annotations[i] == null)
582         {
583           continue;
584         }
585
586         if (drawValues && annotations[i].displayCharacter != null
587                 && annotations[i].displayCharacter.length() > 1)
588         {
589           drawValues = false;
590         }
591
592         if (annotations[i].value > max)
593         {
594           max = annotations[i].value;
595         }
596
597         if (annotations[i].value < min)
598         {
599           min = annotations[i].value;
600         }
601         if (_linecolour == null && annotations[i].colour != null)
602         {
603           _linecolour = annotations[i].colour;
604         }
605       }
606       // ensure zero is origin for min/max ranges on only one side of zero
607       if (min > 0)
608       {
609         min = 0;
610       }
611       else
612       {
613         if (max < 0)
614         {
615           max = 0;
616         }
617       }
618     }
619
620     graphMin = min;
621     graphMax = max;
622
623     areLabelsSecondaryStructure();
624
625     if (!drawValues && graphType != NO_GRAPH)
626     {
627       for (int i = 0; i < annotations.length; i++)
628       {
629         if (annotations[i] != null)
630         {
631           annotations[i].displayCharacter = "X";
632         }
633       }
634     }
635   }
636
637   /**
638    * Copy constructor creates a new independent annotation row with the same
639    * associated sequenceRef
640    * 
641    * @param annotation
642    */
643   public AlignmentAnnotation(AlignmentAnnotation annotation)
644   {
645     this.label = new String(annotation.label);
646     if (annotation.description != null)
647     {
648       this.description = new String(annotation.description);
649     }
650     this.graphMin = annotation.graphMin;
651     this.graphMax = annotation.graphMax;
652     this.graph = annotation.graph;
653     this.graphHeight = annotation.graphHeight;
654     this.graphGroup = annotation.graphGroup;
655     this.groupRef = annotation.groupRef;
656     this.editable = annotation.editable;
657     this.autoCalculated = annotation.autoCalculated;
658     this.hasIcons = annotation.hasIcons;
659     this.hasText = annotation.hasText;
660     this.height = annotation.height;
661     this.label = annotation.label;
662     this.padGaps = annotation.padGaps;
663     this.visible = annotation.visible;
664     this.centreColLabels = annotation.centreColLabels;
665     this.scaleColLabel = annotation.scaleColLabel;
666     this.showAllColLabels = annotation.showAllColLabels;
667     this.calcId = annotation.calcId;
668     if (annotation.properties!=null)
669     {
670       properties = new HashMap<String,String>();
671       for (Map.Entry<String, String> val:annotation.properties.entrySet())
672       {
673         properties.put(val.getKey(), val.getValue());
674       }
675     }
676     if (this.hasScore = annotation.hasScore)
677     {
678       this.score = annotation.score;
679     }
680     if (annotation.threshold != null)
681     {
682       threshold = new GraphLine(annotation.threshold);
683     }
684     Annotation[] ann = annotation.annotations;
685     if (annotation.annotations != null)
686     {
687       this.annotations = new Annotation[ann.length];
688       for (int i = 0; i < ann.length; i++)
689       {
690         if (ann[i] != null)
691         {
692           annotations[i] = new Annotation(ann[i]);
693           if (_linecolour != null)
694           {
695             _linecolour = annotations[i].colour;
696           }
697         }
698       }
699     }
700     if (annotation.sequenceRef != null)
701     {
702       this.sequenceRef = annotation.sequenceRef;
703       if (annotation.sequenceMapping != null)
704       {
705         Integer p = null;
706         sequenceMapping = new Hashtable();
707         Enumeration pos = annotation.sequenceMapping.keys();
708         while (pos.hasMoreElements())
709         {
710           // could optimise this!
711           p = (Integer) pos.nextElement();
712           Annotation a = annotation.sequenceMapping.get(p);
713           if (a == null)
714           {
715             continue;
716           }
717           if (ann != null)
718           {
719             for (int i = 0; i < ann.length; i++)
720             {
721               if (ann[i] == a)
722               {
723                 sequenceMapping.put(p, annotations[i]);
724               }
725             }
726           }
727         }
728       }
729       else
730       {
731         this.sequenceMapping = null;
732       }
733     }
734     // TODO: check if we need to do this: JAL-952
735     // if (this.isrna=annotation.isrna)
736     {
737       // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
738     }
739     validateRangeAndDisplay(); // construct hashcodes, etc.
740   }
741
742   /**
743    * clip the annotation to the columns given by startRes and endRes (inclusive)
744    * and prune any existing sequenceMapping to just those columns.
745    * 
746    * @param startRes
747    * @param endRes
748    */
749   public void restrict(int startRes, int endRes)
750   {
751     if (annotations == null)
752     {
753       // non-positional
754       return;
755     }
756     if (startRes < 0)
757     {
758       startRes = 0;
759     }
760     if (startRes >= annotations.length)
761     {
762       startRes = annotations.length - 1;
763     }
764     if (endRes >= annotations.length)
765     {
766       endRes = annotations.length - 1;
767     }
768     if (annotations == null)
769     {
770       return;
771     }
772     Annotation[] temp = new Annotation[endRes - startRes + 1];
773     if (startRes < annotations.length)
774     {
775       System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
776               + 1);
777     }
778     if (sequenceRef != null)
779     {
780       // Clip the mapping, if it exists.
781       int spos = sequenceRef.findPosition(startRes);
782       int epos = sequenceRef.findPosition(endRes);
783       if (sequenceMapping != null)
784       {
785         Hashtable newmapping = new Hashtable();
786         Enumeration e = sequenceMapping.keys();
787         while (e.hasMoreElements())
788         {
789           Integer pos = (Integer) e.nextElement();
790           if (pos.intValue() >= spos && pos.intValue() <= epos)
791           {
792             newmapping.put(pos, sequenceMapping.get(pos));
793           }
794         }
795         sequenceMapping.clear();
796         sequenceMapping = newmapping;
797       }
798     }
799     annotations = temp;
800   }
801
802   /**
803    * set the annotation row to be at least length Annotations
804    * 
805    * @param length
806    *          minimum number of columns required in the annotation row
807    * @return false if the annotation row is greater than length
808    */
809   public boolean padAnnotation(int length)
810   {
811     if (annotations == null)
812     {
813       return true; // annotation row is correct - null == not visible and
814       // undefined length
815     }
816     if (annotations.length < length)
817     {
818       Annotation[] na = new Annotation[length];
819       System.arraycopy(annotations, 0, na, 0, annotations.length);
820       annotations = na;
821       return true;
822     }
823     return annotations.length > length;
824
825   }
826
827   /**
828    * DOCUMENT ME!
829    * 
830    * @return DOCUMENT ME!
831    */
832   public String toString()
833   {
834     StringBuffer buffer = new StringBuffer();
835
836     for (int i = 0; i < annotations.length; i++)
837     {
838       if (annotations[i] != null)
839       {
840         if (graph != 0)
841         {
842           buffer.append(annotations[i].value);
843         }
844         else if (hasIcons)
845         {
846           buffer.append(annotations[i].secondaryStructure);
847         }
848         else
849         {
850           buffer.append(annotations[i].displayCharacter);
851         }
852       }
853
854       buffer.append(", ");
855     }
856     // TODO: remove disgusting hack for 'special' treatment of consensus line.
857     if (label.indexOf("Consensus") == 0)
858     {
859       buffer.append("\n");
860
861       for (int i = 0; i < annotations.length; i++)
862       {
863         if (annotations[i] != null)
864         {
865           buffer.append(annotations[i].description);
866         }
867
868         buffer.append(", ");
869       }
870     }
871
872     return buffer.toString();
873   }
874
875   public void setThreshold(GraphLine line)
876   {
877     threshold = line;
878   }
879
880   public GraphLine getThreshold()
881   {
882     return threshold;
883   }
884
885   /**
886    * Attach the annotation to seqRef, starting from startRes position. If
887    * alreadyMapped is true then the indices of the annotation[] array are
888    * sequence positions rather than alignment column positions.
889    * 
890    * @param seqRef
891    * @param startRes
892    * @param alreadyMapped
893    */
894   public void createSequenceMapping(SequenceI seqRef, int startRes,
895           boolean alreadyMapped)
896   {
897
898     if (seqRef == null)
899     {
900       return;
901     }
902     sequenceRef = seqRef;
903     if (annotations == null)
904     {
905       return;
906     }
907     sequenceMapping = new java.util.Hashtable();
908
909     int seqPos;
910
911     for (int i = 0; i < annotations.length; i++)
912     {
913       if (annotations[i] != null)
914       {
915         if (alreadyMapped)
916         {
917           seqPos = seqRef.findPosition(i);
918         }
919         else
920         {
921           seqPos = i + startRes;
922         }
923
924         sequenceMapping.put(new Integer(seqPos), annotations[i]);
925       }
926     }
927
928   }
929
930   public void adjustForAlignment()
931   {
932     if (sequenceRef == null)
933     {
934       return;
935     }
936
937     if (annotations == null)
938     {
939       return;
940     }
941
942     int a = 0, aSize = sequenceRef.getLength();
943
944     if (aSize == 0)
945     {
946       // Its been deleted
947       return;
948     }
949
950     int position;
951     Annotation[] temp = new Annotation[aSize];
952     Integer index;
953
954     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
955     {
956       index = new Integer(a);
957       if (sequenceMapping.containsKey(index))
958       {
959         position = sequenceRef.findIndex(a) - 1;
960
961         temp[position] = sequenceMapping.get(index);
962       }
963     }
964
965     annotations = temp;
966   }
967
968   /**
969    * remove any null entries in annotation row and return the number of non-null
970    * annotation elements.
971    * 
972    * @return
973    */
974   public int compactAnnotationArray()
975   {
976     int i = 0, iSize = annotations.length;
977     while (i < iSize)
978     {
979       if (annotations[i] == null)
980       {
981         if (i + 1 < iSize)
982         {
983           System.arraycopy(annotations, i + 1, annotations, i, iSize - i
984                   - 1);
985         }
986         iSize--;
987       }
988       else
989       {
990         i++;
991       }
992     }
993     Annotation[] ann = annotations;
994     annotations = new Annotation[i];
995     System.arraycopy(ann, 0, annotations, 0, i);
996     ann = null;
997     return iSize;
998   }
999
1000   /**
1001    * Associate this annotion with the aligned residues of a particular sequence.
1002    * sequenceMapping will be updated in the following way: null sequenceI -
1003    * existing mapping will be discarded but annotations left in mapped
1004    * positions. valid sequenceI not equal to current sequenceRef: mapping is
1005    * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1006    * parameter to specify correspondence between current and new sequenceRef
1007    * 
1008    * @param sequenceI
1009    */
1010   public void setSequenceRef(SequenceI sequenceI)
1011   {
1012     if (sequenceI != null)
1013     {
1014       if (sequenceRef != null)
1015       {
1016         boolean rIsDs=sequenceRef.getDatasetSequence()==null,tIsDs=sequenceI.getDatasetSequence()==null;
1017         if (sequenceRef != sequenceI
1018                 && (rIsDs && !tIsDs && sequenceRef != sequenceI
1019                         .getDatasetSequence())
1020                 && (!rIsDs && tIsDs && sequenceRef.getDatasetSequence() != sequenceI)
1021                 && (!rIsDs && !tIsDs && sequenceRef.getDatasetSequence() != sequenceI
1022                         .getDatasetSequence())
1023                 && !sequenceRef.equals(sequenceI))
1024         {
1025           // if sequenceRef isn't intersecting with sequenceI
1026           // throw away old mapping and reconstruct.
1027           sequenceRef = null;
1028           if (sequenceMapping != null)
1029           {
1030             sequenceMapping = null;
1031             // compactAnnotationArray();
1032           }
1033           createSequenceMapping(sequenceI, 1, true);
1034           adjustForAlignment();
1035         }
1036         else
1037         {
1038           // Mapping carried over
1039           sequenceRef = sequenceI;
1040         }
1041       }
1042       else
1043       {
1044         // No mapping exists
1045         createSequenceMapping(sequenceI, 1, true);
1046         adjustForAlignment();
1047       }
1048     }
1049     else
1050     {
1051       // throw away the mapping without compacting.
1052       sequenceMapping = null;
1053       sequenceRef = null;
1054     }
1055   }
1056
1057   /**
1058    * @return the score
1059    */
1060   public double getScore()
1061   {
1062     return score;
1063   }
1064
1065   /**
1066    * @param score
1067    *          the score to set
1068    */
1069   public void setScore(double score)
1070   {
1071     hasScore = true;
1072     this.score = score;
1073   }
1074
1075   /**
1076    * 
1077    * @return true if annotation has an associated score
1078    */
1079   public boolean hasScore()
1080   {
1081     return hasScore || !Double.isNaN(score);
1082   }
1083
1084   /**
1085    * Score only annotation
1086    * 
1087    * @param label
1088    * @param description
1089    * @param score
1090    */
1091   public AlignmentAnnotation(String label, String description, double score)
1092   {
1093     this(label, description, null);
1094     setScore(score);
1095   }
1096
1097   /**
1098    * copy constructor with edit based on the hidden columns marked in colSel
1099    * 
1100    * @param alignmentAnnotation
1101    * @param colSel
1102    */
1103   public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1104           ColumnSelection colSel)
1105   {
1106     this(alignmentAnnotation);
1107     if (annotations == null)
1108     {
1109       return;
1110     }
1111     colSel.makeVisibleAnnotation(this);
1112   }
1113
1114   public void setPadGaps(boolean padgaps, char gapchar)
1115   {
1116     this.padGaps = padgaps;
1117     if (padgaps)
1118     {
1119       hasText = true;
1120       for (int i = 0; i < annotations.length; i++)
1121       {
1122         if (annotations[i] == null)
1123         {
1124           annotations[i] = new Annotation(String.valueOf(gapchar), null,
1125                   ' ', 0f, null);
1126         }
1127         else if (annotations[i].displayCharacter == null
1128                 || annotations[i].displayCharacter.equals(" "))
1129         {
1130           annotations[i].displayCharacter = String.valueOf(gapchar);
1131         }
1132       }
1133     }
1134   }
1135
1136   /**
1137    * format description string for display
1138    * 
1139    * @param seqname
1140    * @return Get the annotation description string optionally prefixed by
1141    *         associated sequence name (if any)
1142    */
1143   public String getDescription(boolean seqname)
1144   {
1145     if (seqname && this.sequenceRef != null)
1146     {
1147       int i = description.toLowerCase().indexOf("<html>");
1148       if (i > -1)
1149       {
1150         // move the html tag to before the sequence reference.
1151         return "<html>" + sequenceRef.getName() + " : "
1152                 + description.substring(i + 6);
1153       }
1154       return sequenceRef.getName() + " : " + description;
1155     }
1156     return description;
1157   }
1158
1159   public boolean isValidStruc()
1160   {
1161     return invalidrnastruc == -1;
1162   }
1163
1164   public long getInvalidStrucPos()
1165   {
1166     return invalidrnastruc;
1167   }
1168
1169   /**
1170    * machine readable ID string indicating what generated this annotation
1171    */
1172   protected String calcId = "";
1173
1174   /**
1175    * properties associated with the calcId
1176    */
1177   protected Map<String, String> properties = new HashMap<String, String>();
1178
1179   /**
1180    * base colour for line graphs. If null, will be set automatically by
1181    * searching the alignment annotation
1182    */
1183   public java.awt.Color _linecolour;
1184
1185   public String getCalcId()
1186   {
1187     return calcId;
1188   }
1189
1190   public void setCalcId(String calcId)
1191   {
1192     this.calcId = calcId;
1193   }
1194
1195   public boolean isRNA()
1196   {
1197     return isrna;
1198   }
1199
1200   /**
1201    * transfer annotation to the given sequence using the given mapping from the
1202    * current positions or an existing sequence mapping
1203    * 
1204    * @param sq
1205    * @param sp2sq
1206    *          map involving sq as To or From
1207    */
1208   public void liftOver(SequenceI sq, Mapping sp2sq)
1209   {
1210     if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1211     {
1212       // TODO: employ getWord/MappedWord to transfer annotation between cDNA and Protein reference frames
1213       throw new Error("liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1214     }
1215     boolean mapIsTo = (sp2sq != null) ? (sp2sq.getTo() == sq || sp2sq
1216             .getTo() == sq.getDatasetSequence()) : false;
1217
1218     // TODO build a better annotation element map and get rid of annotations[]
1219     Hashtable<Integer, Annotation> mapForsq = new Hashtable();
1220     if (sequenceMapping != null)
1221     {
1222       if (sp2sq != null)
1223       {
1224         for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1225         {
1226           Integer mpos = Integer.valueOf(mapIsTo ? sp2sq
1227                   .getMappedPosition(ie.getKey()) : sp2sq.getPosition(ie
1228                   .getKey()));
1229           if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1230           {
1231             mapForsq.put(mpos, ie.getValue());
1232           }
1233         }
1234         sequenceMapping = mapForsq;
1235         sequenceRef = sq;
1236         adjustForAlignment();
1237       }
1238       else
1239       {
1240         // trim positions
1241       }
1242     }
1243   }
1244
1245   /**
1246    * like liftOver but more general.
1247    * 
1248    * Takes an array of int pairs that will be used to update the internal
1249    * sequenceMapping and so shuffle the annotated positions
1250    * 
1251    * @param newref
1252    *          - new sequence reference for the annotation row - if null,
1253    *          sequenceRef is left unchanged
1254    * @param mapping
1255    *          array of ints containing corresponding positions
1256    * @param from
1257    *          - column for current coordinate system (-1 for index+1)
1258    * @param to
1259    *          - column for destination coordinate system (-1 for index+1)
1260    * @param idxoffset
1261    *          - offset added to index when referencing either coordinate system
1262    * @note no checks are made as to whether from and/or to are sensible
1263    * @note caller should add the remapped annotation to newref if they have not
1264    *       already
1265    */
1266   public void remap(SequenceI newref, int[][] mapping, int from, int to,
1267           int idxoffset)
1268   {
1269     if (mapping != null)
1270     {
1271       Hashtable<Integer, Annotation> old = sequenceMapping, remap = new Hashtable<Integer, Annotation>();
1272       int index = -1;
1273       for (int mp[] : mapping)
1274       {
1275         if (index++ < 0)
1276         {
1277           continue;
1278         }
1279         Annotation ann = null;
1280         if (from == -1)
1281         {
1282           ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1283         }
1284         else
1285         {
1286           if (mp != null && mp.length > from)
1287           {
1288             ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1289           }
1290         }
1291         if (ann != null)
1292         {
1293           if (to == -1)
1294           {
1295             remap.put(Integer.valueOf(idxoffset + index), ann);
1296           }
1297           else
1298           {
1299             if (to > -1 && to < mp.length)
1300             {
1301               remap.put(Integer.valueOf(mp[to]), ann);
1302             }
1303           }
1304         }
1305       }
1306       sequenceMapping = remap;
1307       old.clear();
1308       if (newref != null)
1309       {
1310         sequenceRef = newref;
1311       }
1312       adjustForAlignment();
1313     }
1314   }
1315
1316   public String getProperty(String property)
1317   {
1318     if (properties == null)
1319     {
1320       return null;
1321     }
1322     return properties.get(property);
1323   }
1324
1325   public void setProperty(String property, String value)
1326   {
1327     if (properties==null)
1328     {
1329       properties = new HashMap<String,String>();
1330     }
1331     properties.put(property, value);
1332   }
1333
1334   public boolean hasProperties()
1335   {
1336     return properties != null && properties.size() > 0;
1337   }
1338
1339   public Collection<String> getProperties()
1340   {
1341     if (properties == null)
1342     {
1343       return Collections.EMPTY_LIST;
1344     }
1345     return properties.keySet();
1346   }
1347 }