2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.datamodel;
20 import jalview.analysis.Rna;
21 import jalview.analysis.WUSSParseException;
23 import java.util.Enumeration;
24 import java.util.Hashtable;
32 public class AlignmentAnnotation
35 * If true, this annotations is calculated every edit, eg consensus, quality
36 * or conservation graphs
38 public boolean autoCalculated = false;
40 public String annotationId;
42 public SequenceI sequenceRef;
48 public String description;
51 public Annotation[] annotations;
54 * RNA secondary structure contact positions
56 public SequenceFeature[] _rnasecstr = null;
58 * position of annotation resulting in invalid WUSS parsing or -1
60 private long invalidrnastruc=-1;
62 * Updates the _rnasecstr field Determines the positions that base pair and
63 * the positions of helices based on secondary structure from a Stockholm file
67 private void _updateRnaSecStr(CharSequence RNAannot)
70 _rnasecstr = Rna.GetBasePairs(RNAannot);
73 catch (WUSSParseException px)
75 invalidrnastruc=px.getProblemPos();
77 if (invalidrnastruc>-1)
81 Rna.HelixMap(_rnasecstr);
82 // setRNAStruc(RNAannot);
84 if (_rnasecstr != null && _rnasecstr.length > 0)
86 // show all the RNA secondary structure annotation symbols.
88 showAllColLabels = true;
91 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
93 public java.util.Hashtable sequenceMapping;
96 public float graphMin;
99 public float graphMax;
102 * Score associated with label and description.
104 public double score = Double.NaN;
107 * flag indicating if annotation has a score.
109 public boolean hasScore = false;
111 public GraphLine threshold;
113 // Graphical hints and tips
115 /** Can this row be edited by the user ? */
116 public boolean editable = false;
118 /** Indicates if annotation has a graphical symbol track */
119 public boolean hasIcons; //
121 /** Indicates if annotation has a text character label */
122 public boolean hasText;
124 /** is the row visible */
125 public boolean visible = true;
127 public int graphGroup = -1;
129 /** Displayed height of row in pixels */
130 public int height = 0;
132 public int graph = 0;
134 public int graphHeight = 40;
136 public boolean padGaps = false;
138 public static final int NO_GRAPH = 0;
140 public static final int BAR_GRAPH = 1;
142 public static final int LINE_GRAPH = 2;
144 public boolean belowAlignment = true;
146 public SequenceGroup groupRef = null;
149 * display every column label, even if there is a row of identical labels
151 public boolean showAllColLabels = false;
154 * scale the column label to fit within the alignment column.
156 public boolean scaleColLabel = false;
159 * centre the column labels relative to the alignment column
161 public boolean centreColLabels = false;
163 private boolean isrna;
168 * @see java.lang.Object#finalize()
170 protected void finalize() throws Throwable
177 public static int getGraphValueFromString(String string)
179 if (string.equalsIgnoreCase("BAR_GRAPH"))
183 else if (string.equalsIgnoreCase("LINE_GRAPH"))
194 * Creates a new AlignmentAnnotation object.
197 * short label shown under sequence labels
199 * text displayed on mouseover
201 * set of positional annotation elements
203 public AlignmentAnnotation(String label, String description,
204 Annotation[] annotations)
209 this.description = description;
210 this.annotations = annotations;
212 validateRangeAndDisplay();
216 * Checks if annotation labels represent secondary structures
219 void areLabelsSecondaryStructure()
221 boolean nonSSLabel = false;
223 StringBuffer rnastring = new StringBuffer();
226 for (int i = 0; i < annotations.length; i++)
228 if (annotations[i] == null)
232 if (annotations[i].secondaryStructure == 'H'
233 || annotations[i].secondaryStructure == 'E')
238 // Check for RNA secondary structure
240 if (annotations[i].secondaryStructure == 'S')
247 // System.out.println("displaychar " + annotations[i].displayCharacter);
249 if (annotations[i].displayCharacter == null
250 || annotations[i].displayCharacter.length() == 0)
252 rnastring.append('.');
255 if (annotations[i].displayCharacter.length() == 1)
257 firstChar = annotations[i].displayCharacter.charAt(0);
258 // check to see if it looks like a sequence or is secondary structure
260 if (annotations[i].secondaryStructure != ' '
263 // Uncomment to only catch case where
264 // displayCharacter==secondary
266 // to correctly redisplay SS annotation imported from Stockholm,
267 // exported to JalviewXML and read back in again.
269 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
275 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
277 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
290 rnastring.append(annotations[i].displayCharacter.charAt(1));
293 if (annotations[i].displayCharacter.length() > 0)
302 for (int j = 0; j < annotations.length; j++)
304 if (annotations[j] != null
305 && annotations[j].secondaryStructure != ' ')
307 annotations[j].displayCharacter = String
308 .valueOf(annotations[j].secondaryStructure);
309 annotations[j].secondaryStructure = ' ';
318 _updateRnaSecStr(new AnnotCharSequence());
322 annotationId = this.hashCode() + "";
325 * flyweight access to positions in the alignment annotation row for RNA processing
329 private class AnnotCharSequence implements CharSequence
334 public AnnotCharSequence() {
335 this(0,annotations.length);
337 public AnnotCharSequence(int start, int end) {
342 public CharSequence subSequence(int start, int end)
344 return new AnnotCharSequence(offset+start, offset+end);
354 public char charAt(int index)
357 return ((index+offset<0) || (index+offset)>=max || annotations[index+offset]==null || (dc=annotations[index+offset].displayCharacter.trim()).length()<1)
358 ? '.' : dc.charAt(0);
360 public String toString()
362 char[] string=new char[max-offset];
363 int mx=annotations.length;
365 for (int i=offset;i<mx;i++)
368 string[i]=(annotations[i]==null || (dc=annotations[i].displayCharacter.trim()).length()<1 )? '.' : dc.charAt(0);
370 return new String(string);
374 private long _lastrnaannot=-1;
375 public String getRNAStruc(){
378 String rnastruc = new AnnotCharSequence().toString();
379 if (_lastrnaannot!=rnastruc.hashCode())
381 // ensure rna structure contacts are up to date
382 _lastrnaannot=rnastruc.hashCode();
383 _updateRnaSecStr(rnastruc);
391 * Creates a new AlignmentAnnotation object.
406 public AlignmentAnnotation(String label, String description,
407 Annotation[] annotations, float min, float max, int graphType)
409 // graphs are not editable
410 editable = graphType == 0;
413 this.description = description;
414 this.annotations = annotations;
418 validateRangeAndDisplay();
422 * checks graphMin and graphMax, secondary structure symbols, sets graphType
423 * appropriately, sets null labels to the empty string if appropriate.
425 public void validateRangeAndDisplay()
428 if (annotations == null)
430 visible = false; // try to prevent renderer from displaying.
431 return; // this is a non-annotation row annotation - ie a sequence score.
434 int graphType = graph;
435 float min = graphMin;
436 float max = graphMax;
437 boolean drawValues = true;
442 for (int i = 0; i < annotations.length; i++)
444 if (annotations[i] == null)
449 if (drawValues && annotations[i].displayCharacter != null
450 && annotations[i].displayCharacter.length() > 1)
455 if (annotations[i].value > max)
457 max = annotations[i].value;
460 if (annotations[i].value < min)
462 min = annotations[i].value;
465 // ensure zero is origin for min/max ranges on only one side of zero
482 areLabelsSecondaryStructure();
484 if (!drawValues && graphType != NO_GRAPH)
486 for (int i = 0; i < annotations.length; i++)
488 if (annotations[i] != null)
490 annotations[i].displayCharacter = "";
497 * Copy constructor creates a new independent annotation row with the same
498 * associated sequenceRef
502 public AlignmentAnnotation(AlignmentAnnotation annotation)
504 this.label = new String(annotation.label);
505 if (annotation.description != null)
506 this.description = new String(annotation.description);
507 this.graphMin = annotation.graphMin;
508 this.graphMax = annotation.graphMax;
509 this.graph = annotation.graph;
510 this.graphHeight = annotation.graphHeight;
511 this.graphGroup = annotation.graphGroup;
512 this.groupRef = annotation.groupRef;
513 this.editable = annotation.editable;
514 this.autoCalculated = annotation.autoCalculated;
515 this.hasIcons = annotation.hasIcons;
516 this.hasText = annotation.hasText;
517 this.height = annotation.height;
518 this.label = annotation.label;
519 this.padGaps = annotation.padGaps;
520 this.visible = annotation.visible;
521 if (this.hasScore = annotation.hasScore)
523 this.score = annotation.score;
525 if (annotation.threshold != null)
527 threshold = new GraphLine(annotation.threshold);
529 if (annotation.annotations != null)
531 Annotation[] ann = annotation.annotations;
532 this.annotations = new Annotation[ann.length];
533 for (int i = 0; i < ann.length; i++)
535 annotations[i] = new Annotation(ann[i]);
538 if (annotation.sequenceRef != null)
540 this.sequenceRef = annotation.sequenceRef;
541 if (annotation.sequenceMapping != null)
544 sequenceMapping = new Hashtable();
545 Enumeration pos = annotation.sequenceMapping.keys();
546 while (pos.hasMoreElements())
548 // could optimise this!
549 p = (Integer) pos.nextElement();
550 Annotation a = (Annotation) annotation.sequenceMapping.get(p);
555 for (int i = 0; i < ann.length; i++)
559 sequenceMapping.put(p, annotations[i]);
566 this.sequenceMapping = null;
570 validateRangeAndDisplay(); // construct hashcodes, etc.
574 * clip the annotation to the columns given by startRes and endRes (inclusive)
575 * and prune any existing sequenceMapping to just those columns.
580 public void restrict(int startRes, int endRes)
582 if (annotations == null)
589 if (startRes >= annotations.length)
590 startRes = annotations.length - 1;
591 if (endRes >= annotations.length)
592 endRes = annotations.length - 1;
593 if (annotations == null)
595 Annotation[] temp = new Annotation[endRes - startRes + 1];
596 if (startRes < annotations.length)
598 System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
601 if (sequenceRef != null)
603 // Clip the mapping, if it exists.
604 int spos = sequenceRef.findPosition(startRes);
605 int epos = sequenceRef.findPosition(endRes);
606 if (sequenceMapping != null)
608 Hashtable newmapping = new Hashtable();
609 Enumeration e = sequenceMapping.keys();
610 while (e.hasMoreElements())
612 Integer pos = (Integer) e.nextElement();
613 if (pos.intValue() >= spos && pos.intValue() <= epos)
615 newmapping.put(pos, sequenceMapping.get(pos));
618 sequenceMapping.clear();
619 sequenceMapping = newmapping;
626 * set the annotation row to be at least length Annotations
629 * minimum number of columns required in the annotation row
630 * @return false if the annotation row is greater than length
632 public boolean padAnnotation(int length)
634 if (annotations == null)
636 return true; // annotation row is correct - null == not visible and
639 if (annotations.length < length)
641 Annotation[] na = new Annotation[length];
642 System.arraycopy(annotations, 0, na, 0, annotations.length);
646 return annotations.length > length;
653 * @return DOCUMENT ME!
655 public String toString()
657 StringBuffer buffer = new StringBuffer();
659 for (int i = 0; i < annotations.length; i++)
661 if (annotations[i] != null)
665 buffer.append(annotations[i].value);
669 buffer.append(annotations[i].secondaryStructure);
673 buffer.append(annotations[i].displayCharacter);
679 // TODO: remove disgusting hack for 'special' treatment of consensus line.
680 if (label.indexOf("Consensus") == 0)
684 for (int i = 0; i < annotations.length; i++)
686 if (annotations[i] != null)
688 buffer.append(annotations[i].description);
695 return buffer.toString();
698 public void setThreshold(GraphLine line)
703 public GraphLine getThreshold()
709 * Attach the annotation to seqRef, starting from startRes position. If
710 * alreadyMapped is true then the indices of the annotation[] array are
711 * sequence positions rather than alignment column positions.
715 * @param alreadyMapped
717 public void createSequenceMapping(SequenceI seqRef, int startRes,
718 boolean alreadyMapped)
725 sequenceRef = seqRef;
726 if (annotations == null)
730 sequenceMapping = new java.util.Hashtable();
734 for (int i = 0; i < annotations.length; i++)
736 if (annotations[i] != null)
740 seqPos = seqRef.findPosition(i);
744 seqPos = i + startRes;
747 sequenceMapping.put(new Integer(seqPos), annotations[i]);
753 public void adjustForAlignment()
755 if (sequenceRef == null)
758 if (annotations == null)
763 int a = 0, aSize = sequenceRef.getLength();
772 Annotation[] temp = new Annotation[aSize];
775 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
777 index = new Integer(a);
778 if (sequenceMapping.containsKey(index))
780 position = sequenceRef.findIndex(a) - 1;
782 temp[position] = (Annotation) sequenceMapping.get(index);
790 * remove any null entries in annotation row and return the number of non-null
791 * annotation elements.
795 public int compactAnnotationArray()
797 int i = 0, iSize = annotations.length;
800 if (annotations[i] == null)
803 System.arraycopy(annotations, i + 1, annotations, i, iSize - i
812 Annotation[] ann = annotations;
813 annotations = new Annotation[i];
814 System.arraycopy(ann, 0, annotations, 0, i);
820 * Associate this annotion with the aligned residues of a particular sequence.
821 * sequenceMapping will be updated in the following way: null sequenceI -
822 * existing mapping will be discarded but annotations left in mapped
823 * positions. valid sequenceI not equal to current sequenceRef: mapping is
824 * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
825 * parameter to specify correspondence between current and new sequenceRef
829 public void setSequenceRef(SequenceI sequenceI)
831 if (sequenceI != null)
833 if (sequenceRef != null)
835 if (sequenceRef != sequenceI
836 && !sequenceRef.equals(sequenceI)
837 && sequenceRef.getDatasetSequence() != sequenceI
838 .getDatasetSequence())
840 // if sequenceRef isn't intersecting with sequenceI
841 // throw away old mapping and reconstruct.
843 if (sequenceMapping != null)
845 sequenceMapping = null;
846 // compactAnnotationArray();
848 createSequenceMapping(sequenceI, 1, true);
849 adjustForAlignment();
853 // Mapping carried over
854 sequenceRef = sequenceI;
860 createSequenceMapping(sequenceI, 1, true);
861 adjustForAlignment();
866 // throw away the mapping without compacting.
867 sequenceMapping = null;
875 public double getScore()
884 public void setScore(double score)
892 * @return true if annotation has an associated score
894 public boolean hasScore()
896 return hasScore || !Double.isNaN(score);
900 * Score only annotation
906 public AlignmentAnnotation(String label, String description, double score)
908 this(label, description, null);
913 * copy constructor with edit based on the hidden columns marked in colSel
915 * @param alignmentAnnotation
918 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
919 ColumnSelection colSel)
921 this(alignmentAnnotation);
922 if (annotations == null)
926 colSel.makeVisibleAnnotation(this);
929 public void setPadGaps(boolean padgaps, char gapchar)
931 this.padGaps = padgaps;
935 for (int i = 0; i < annotations.length; i++)
937 if (annotations[i] == null)
938 annotations[i] = new Annotation(String.valueOf(gapchar), null,
940 else if (annotations[i].displayCharacter == null
941 || annotations[i].displayCharacter.equals(" "))
942 annotations[i].displayCharacter = String.valueOf(gapchar);
948 * format description string for display
951 * @return Get the annotation description string optionally prefixed by
952 * associated sequence name (if any)
954 public String getDescription(boolean seqname)
956 if (seqname && this.sequenceRef != null)
958 int i=description.toLowerCase().indexOf("<html>");
961 // move the html tag to before the sequence reference.
962 return "<html>"+sequenceRef.getName()+" : "+description.substring(i+6);
964 return sequenceRef.getName() + " : " + description;
969 public boolean isValidStruc()
971 return invalidrnastruc==-1;
973 public long getInvalidStrucPos()
975 return invalidrnastruc;