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;
59 * position of annotation resulting in invalid WUSS parsing or -1
61 private long invalidrnastruc = -1;
64 * Updates the _rnasecstr field Determines the positions that base pair and
65 * the positions of helices based on secondary structure from a Stockholm file
69 private void _updateRnaSecStr(CharSequence RNAannot)
73 _rnasecstr = Rna.GetBasePairs(RNAannot);
75 } catch (WUSSParseException px)
77 invalidrnastruc = px.getProblemPos();
79 if (invalidrnastruc > -1)
83 Rna.HelixMap(_rnasecstr);
84 // setRNAStruc(RNAannot);
86 if (_rnasecstr != null && _rnasecstr.length > 0)
88 // show all the RNA secondary structure annotation symbols.
90 showAllColLabels = true;
93 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
96 public java.util.Hashtable sequenceMapping;
99 public float graphMin;
102 public float graphMax;
105 * Score associated with label and description.
107 public double score = Double.NaN;
110 * flag indicating if annotation has a score.
112 public boolean hasScore = false;
114 public GraphLine threshold;
116 // Graphical hints and tips
118 /** Can this row be edited by the user ? */
119 public boolean editable = false;
121 /** Indicates if annotation has a graphical symbol track */
122 public boolean hasIcons; //
124 /** Indicates if annotation has a text character label */
125 public boolean hasText;
127 /** is the row visible */
128 public boolean visible = true;
130 public int graphGroup = -1;
132 /** Displayed height of row in pixels */
133 public int height = 0;
135 public int graph = 0;
137 public int graphHeight = 40;
139 public boolean padGaps = false;
141 public static final int NO_GRAPH = 0;
143 public static final int BAR_GRAPH = 1;
145 public static final int LINE_GRAPH = 2;
147 public boolean belowAlignment = true;
149 public SequenceGroup groupRef = null;
152 * display every column label, even if there is a row of identical labels
154 public boolean showAllColLabels = false;
157 * scale the column label to fit within the alignment column.
159 public boolean scaleColLabel = false;
162 * centre the column labels relative to the alignment column
164 public boolean centreColLabels = false;
166 private boolean isrna;
171 * @see java.lang.Object#finalize()
173 protected void finalize() throws Throwable
180 public static int getGraphValueFromString(String string)
182 if (string.equalsIgnoreCase("BAR_GRAPH"))
186 else if (string.equalsIgnoreCase("LINE_GRAPH"))
197 * Creates a new AlignmentAnnotation object.
200 * short label shown under sequence labels
202 * text displayed on mouseover
204 * set of positional annotation elements
206 public AlignmentAnnotation(String label, String description,
207 Annotation[] annotations)
212 this.description = description;
213 this.annotations = annotations;
215 validateRangeAndDisplay();
219 * Checks if annotation labels represent secondary structures
222 void areLabelsSecondaryStructure()
224 boolean nonSSLabel = false;
226 StringBuffer rnastring = new StringBuffer();
229 for (int i = 0; i < annotations.length; i++)
231 if (annotations[i] == null)
235 if (annotations[i].secondaryStructure == 'H'
236 || annotations[i].secondaryStructure == 'E')
241 // Check for RNA secondary structure
243 if (annotations[i].secondaryStructure == 'S')
250 // System.out.println("displaychar " + annotations[i].displayCharacter);
252 if (annotations[i].displayCharacter == null
253 || annotations[i].displayCharacter.length() == 0)
255 rnastring.append('.');
258 if (annotations[i].displayCharacter.length() == 1)
260 firstChar = annotations[i].displayCharacter.charAt(0);
261 // check to see if it looks like a sequence or is secondary structure
263 if (annotations[i].secondaryStructure != ' '
266 // Uncomment to only catch case where
267 // displayCharacter==secondary
269 // to correctly redisplay SS annotation imported from Stockholm,
270 // exported to JalviewXML and read back in again.
272 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
278 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
280 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
293 rnastring.append(annotations[i].displayCharacter.charAt(1));
296 if (annotations[i].displayCharacter.length() > 0)
305 for (int j = 0; j < annotations.length; j++)
307 if (annotations[j] != null
308 && annotations[j].secondaryStructure != ' ')
310 annotations[j].displayCharacter = String
311 .valueOf(annotations[j].secondaryStructure);
312 annotations[j].secondaryStructure = ' ';
321 _updateRnaSecStr(new AnnotCharSequence());
325 annotationId = this.hashCode() + "";
329 * flyweight access to positions in the alignment annotation row for RNA
335 private class AnnotCharSequence implements CharSequence
341 public AnnotCharSequence()
343 this(0, annotations.length);
346 public AnnotCharSequence(int start, int end)
353 public CharSequence subSequence(int start, int end)
355 return new AnnotCharSequence(offset + start, offset + end);
365 public char charAt(int index)
368 return ((index + offset < 0) || (index + offset) >= max
369 || annotations[index + offset] == null || (dc = annotations[index
370 + offset].displayCharacter.trim()).length() < 1) ? '.' : dc
374 public String toString()
376 char[] string = new char[max - offset];
377 int mx = annotations.length;
379 for (int i = offset; i < mx; i++)
382 string[i] = (annotations[i] == null || (dc = annotations[i].displayCharacter
383 .trim()).length() < 1) ? '.' : dc.charAt(0);
385 return new String(string);
389 private long _lastrnaannot = -1;
391 public String getRNAStruc()
395 String rnastruc = new AnnotCharSequence().toString();
396 if (_lastrnaannot != rnastruc.hashCode())
398 // ensure rna structure contacts are up to date
399 _lastrnaannot = rnastruc.hashCode();
400 _updateRnaSecStr(rnastruc);
408 * Creates a new AlignmentAnnotation object.
423 public AlignmentAnnotation(String label, String description,
424 Annotation[] annotations, float min, float max, int graphType)
426 // graphs are not editable
427 editable = graphType == 0;
430 this.description = description;
431 this.annotations = annotations;
435 validateRangeAndDisplay();
439 * checks graphMin and graphMax, secondary structure symbols, sets graphType
440 * appropriately, sets null labels to the empty string if appropriate.
442 public void validateRangeAndDisplay()
445 if (annotations == null)
447 visible = false; // try to prevent renderer from displaying.
448 return; // this is a non-annotation row annotation - ie a sequence score.
451 int graphType = graph;
452 float min = graphMin;
453 float max = graphMax;
454 boolean drawValues = true;
459 for (int i = 0; i < annotations.length; i++)
461 if (annotations[i] == null)
466 if (drawValues && annotations[i].displayCharacter != null
467 && annotations[i].displayCharacter.length() > 1)
472 if (annotations[i].value > max)
474 max = annotations[i].value;
477 if (annotations[i].value < min)
479 min = annotations[i].value;
481 if (_linecolour == null && annotations[i].colour != null)
483 _linecolour = annotations[i].colour;
486 // ensure zero is origin for min/max ranges on only one side of zero
503 areLabelsSecondaryStructure();
505 if (!drawValues && graphType != NO_GRAPH)
507 for (int i = 0; i < annotations.length; i++)
509 if (annotations[i] != null)
511 annotations[i].displayCharacter = "";
518 * Copy constructor creates a new independent annotation row with the same
519 * associated sequenceRef
523 public AlignmentAnnotation(AlignmentAnnotation annotation)
525 this.label = new String(annotation.label);
526 if (annotation.description != null)
527 this.description = new String(annotation.description);
528 this.graphMin = annotation.graphMin;
529 this.graphMax = annotation.graphMax;
530 this.graph = annotation.graph;
531 this.graphHeight = annotation.graphHeight;
532 this.graphGroup = annotation.graphGroup;
533 this.groupRef = annotation.groupRef;
534 this.editable = annotation.editable;
535 this.autoCalculated = annotation.autoCalculated;
536 this.hasIcons = annotation.hasIcons;
537 this.hasText = annotation.hasText;
538 this.height = annotation.height;
539 this.label = annotation.label;
540 this.padGaps = annotation.padGaps;
541 this.visible = annotation.visible;
542 this.centreColLabels = annotation.centreColLabels;
543 this.scaleColLabel = annotation.scaleColLabel;
544 this.showAllColLabels = annotation.showAllColLabels;
545 this.calcId = annotation.calcId;
546 if (this.hasScore = annotation.hasScore)
548 this.score = annotation.score;
550 if (annotation.threshold != null)
552 threshold = new GraphLine(annotation.threshold);
554 if (annotation.annotations != null)
556 Annotation[] ann = annotation.annotations;
557 this.annotations = new Annotation[ann.length];
558 for (int i = 0; i < ann.length; i++)
562 annotations[i] = new Annotation(ann[i]);
563 if (_linecolour!=null)
565 _linecolour = annotations[i].colour;
570 if (annotation.sequenceRef != null)
572 this.sequenceRef = annotation.sequenceRef;
573 if (annotation.sequenceMapping != null)
576 sequenceMapping = new Hashtable();
577 Enumeration pos = annotation.sequenceMapping.keys();
578 while (pos.hasMoreElements())
580 // could optimise this!
581 p = (Integer) pos.nextElement();
582 Annotation a = (Annotation) annotation.sequenceMapping.get(p);
587 for (int i = 0; i < ann.length; i++)
591 sequenceMapping.put(p, annotations[i]);
598 this.sequenceMapping = null;
602 // TODO: check if we need to do this: JAL-952
603 // if (this.isrna=annotation.isrna)
605 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
607 validateRangeAndDisplay(); // construct hashcodes, etc.
611 * clip the annotation to the columns given by startRes and endRes (inclusive)
612 * and prune any existing sequenceMapping to just those columns.
617 public void restrict(int startRes, int endRes)
619 if (annotations == null)
626 if (startRes >= annotations.length)
627 startRes = annotations.length - 1;
628 if (endRes >= annotations.length)
629 endRes = annotations.length - 1;
630 if (annotations == null)
632 Annotation[] temp = new Annotation[endRes - startRes + 1];
633 if (startRes < annotations.length)
635 System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
638 if (sequenceRef != null)
640 // Clip the mapping, if it exists.
641 int spos = sequenceRef.findPosition(startRes);
642 int epos = sequenceRef.findPosition(endRes);
643 if (sequenceMapping != null)
645 Hashtable newmapping = new Hashtable();
646 Enumeration e = sequenceMapping.keys();
647 while (e.hasMoreElements())
649 Integer pos = (Integer) e.nextElement();
650 if (pos.intValue() >= spos && pos.intValue() <= epos)
652 newmapping.put(pos, sequenceMapping.get(pos));
655 sequenceMapping.clear();
656 sequenceMapping = newmapping;
663 * set the annotation row to be at least length Annotations
666 * minimum number of columns required in the annotation row
667 * @return false if the annotation row is greater than length
669 public boolean padAnnotation(int length)
671 if (annotations == null)
673 return true; // annotation row is correct - null == not visible and
676 if (annotations.length < length)
678 Annotation[] na = new Annotation[length];
679 System.arraycopy(annotations, 0, na, 0, annotations.length);
683 return annotations.length > length;
690 * @return DOCUMENT ME!
692 public String toString()
694 StringBuffer buffer = new StringBuffer();
696 for (int i = 0; i < annotations.length; i++)
698 if (annotations[i] != null)
702 buffer.append(annotations[i].value);
706 buffer.append(annotations[i].secondaryStructure);
710 buffer.append(annotations[i].displayCharacter);
716 // TODO: remove disgusting hack for 'special' treatment of consensus line.
717 if (label.indexOf("Consensus") == 0)
721 for (int i = 0; i < annotations.length; i++)
723 if (annotations[i] != null)
725 buffer.append(annotations[i].description);
732 return buffer.toString();
735 public void setThreshold(GraphLine line)
740 public GraphLine getThreshold()
746 * Attach the annotation to seqRef, starting from startRes position. If
747 * alreadyMapped is true then the indices of the annotation[] array are
748 * sequence positions rather than alignment column positions.
752 * @param alreadyMapped
754 public void createSequenceMapping(SequenceI seqRef, int startRes,
755 boolean alreadyMapped)
762 sequenceRef = seqRef;
763 if (annotations == null)
767 sequenceMapping = new java.util.Hashtable();
771 for (int i = 0; i < annotations.length; i++)
773 if (annotations[i] != null)
777 seqPos = seqRef.findPosition(i);
781 seqPos = i + startRes;
784 sequenceMapping.put(new Integer(seqPos), annotations[i]);
790 public void adjustForAlignment()
792 if (sequenceRef == null)
795 if (annotations == null)
800 int a = 0, aSize = sequenceRef.getLength();
809 Annotation[] temp = new Annotation[aSize];
812 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
814 index = new Integer(a);
815 if (sequenceMapping.containsKey(index))
817 position = sequenceRef.findIndex(a) - 1;
819 temp[position] = (Annotation) sequenceMapping.get(index);
827 * remove any null entries in annotation row and return the number of non-null
828 * annotation elements.
832 public int compactAnnotationArray()
834 int i = 0, iSize = annotations.length;
837 if (annotations[i] == null)
840 System.arraycopy(annotations, i + 1, annotations, i, iSize - i
849 Annotation[] ann = annotations;
850 annotations = new Annotation[i];
851 System.arraycopy(ann, 0, annotations, 0, i);
857 * Associate this annotion with the aligned residues of a particular sequence.
858 * sequenceMapping will be updated in the following way: null sequenceI -
859 * existing mapping will be discarded but annotations left in mapped
860 * positions. valid sequenceI not equal to current sequenceRef: mapping is
861 * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
862 * parameter to specify correspondence between current and new sequenceRef
866 public void setSequenceRef(SequenceI sequenceI)
868 if (sequenceI != null)
870 if (sequenceRef != null)
872 if (sequenceRef != sequenceI
873 && !sequenceRef.equals(sequenceI)
874 && sequenceRef.getDatasetSequence() != sequenceI
875 .getDatasetSequence())
877 // if sequenceRef isn't intersecting with sequenceI
878 // throw away old mapping and reconstruct.
880 if (sequenceMapping != null)
882 sequenceMapping = null;
883 // compactAnnotationArray();
885 createSequenceMapping(sequenceI, 1, true);
886 adjustForAlignment();
890 // Mapping carried over
891 sequenceRef = sequenceI;
897 createSequenceMapping(sequenceI, 1, true);
898 adjustForAlignment();
903 // throw away the mapping without compacting.
904 sequenceMapping = null;
912 public double getScore()
921 public void setScore(double score)
929 * @return true if annotation has an associated score
931 public boolean hasScore()
933 return hasScore || !Double.isNaN(score);
937 * Score only annotation
943 public AlignmentAnnotation(String label, String description, double score)
945 this(label, description, null);
950 * copy constructor with edit based on the hidden columns marked in colSel
952 * @param alignmentAnnotation
955 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
956 ColumnSelection colSel)
958 this(alignmentAnnotation);
959 if (annotations == null)
963 colSel.makeVisibleAnnotation(this);
966 public void setPadGaps(boolean padgaps, char gapchar)
968 this.padGaps = padgaps;
972 for (int i = 0; i < annotations.length; i++)
974 if (annotations[i] == null)
975 annotations[i] = new Annotation(String.valueOf(gapchar), null,
977 else if (annotations[i].displayCharacter == null
978 || annotations[i].displayCharacter.equals(" "))
979 annotations[i].displayCharacter = String.valueOf(gapchar);
985 * format description string for display
988 * @return Get the annotation description string optionally prefixed by
989 * associated sequence name (if any)
991 public String getDescription(boolean seqname)
993 if (seqname && this.sequenceRef != null)
995 int i = description.toLowerCase().indexOf("<html>");
998 // move the html tag to before the sequence reference.
999 return "<html>" + sequenceRef.getName() + " : "
1000 + description.substring(i + 6);
1002 return sequenceRef.getName() + " : " + description;
1007 public boolean isValidStruc()
1009 return invalidrnastruc == -1;
1012 public long getInvalidStrucPos()
1014 return invalidrnastruc;
1018 * machine readable ID string indicating what generated this annotation
1020 protected String calcId = "";
1023 * base colour for line graphs. If null, will be set automatically by
1024 * searching the alignment annotation
1026 public java.awt.Color _linecolour;
1028 public String getCalcId()
1033 public void setCalcId(String calcId)
1035 this.calcId = calcId;