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 this.centreColLabels=annotation.centreColLabels;
522 this.scaleColLabel=annotation.scaleColLabel;
523 this.showAllColLabels=annotation.showAllColLabels;
524 this.calcId = annotation.calcId;
525 if (this.hasScore = annotation.hasScore)
527 this.score = annotation.score;
529 if (annotation.threshold != null)
531 threshold = new GraphLine(annotation.threshold);
533 if (annotation.annotations != null)
535 Annotation[] ann = annotation.annotations;
536 this.annotations = new Annotation[ann.length];
537 for (int i = 0; i < ann.length; i++)
539 annotations[i] = new Annotation(ann[i]);
542 if (annotation.sequenceRef != null)
544 this.sequenceRef = annotation.sequenceRef;
545 if (annotation.sequenceMapping != null)
548 sequenceMapping = new Hashtable();
549 Enumeration pos = annotation.sequenceMapping.keys();
550 while (pos.hasMoreElements())
552 // could optimise this!
553 p = (Integer) pos.nextElement();
554 Annotation a = (Annotation) annotation.sequenceMapping.get(p);
559 for (int i = 0; i < ann.length; i++)
563 sequenceMapping.put(p, annotations[i]);
570 this.sequenceMapping = null;
574 // TODO: check if we need to do this: JAL-952
575 //if (this.isrna=annotation.isrna)
577 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
579 validateRangeAndDisplay(); // construct hashcodes, etc.
583 * clip the annotation to the columns given by startRes and endRes (inclusive)
584 * and prune any existing sequenceMapping to just those columns.
589 public void restrict(int startRes, int endRes)
591 if (annotations == null)
598 if (startRes >= annotations.length)
599 startRes = annotations.length - 1;
600 if (endRes >= annotations.length)
601 endRes = annotations.length - 1;
602 if (annotations == null)
604 Annotation[] temp = new Annotation[endRes - startRes + 1];
605 if (startRes < annotations.length)
607 System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
610 if (sequenceRef != null)
612 // Clip the mapping, if it exists.
613 int spos = sequenceRef.findPosition(startRes);
614 int epos = sequenceRef.findPosition(endRes);
615 if (sequenceMapping != null)
617 Hashtable newmapping = new Hashtable();
618 Enumeration e = sequenceMapping.keys();
619 while (e.hasMoreElements())
621 Integer pos = (Integer) e.nextElement();
622 if (pos.intValue() >= spos && pos.intValue() <= epos)
624 newmapping.put(pos, sequenceMapping.get(pos));
627 sequenceMapping.clear();
628 sequenceMapping = newmapping;
635 * set the annotation row to be at least length Annotations
638 * minimum number of columns required in the annotation row
639 * @return false if the annotation row is greater than length
641 public boolean padAnnotation(int length)
643 if (annotations == null)
645 return true; // annotation row is correct - null == not visible and
648 if (annotations.length < length)
650 Annotation[] na = new Annotation[length];
651 System.arraycopy(annotations, 0, na, 0, annotations.length);
655 return annotations.length > length;
662 * @return DOCUMENT ME!
664 public String toString()
666 StringBuffer buffer = new StringBuffer();
668 for (int i = 0; i < annotations.length; i++)
670 if (annotations[i] != null)
674 buffer.append(annotations[i].value);
678 buffer.append(annotations[i].secondaryStructure);
682 buffer.append(annotations[i].displayCharacter);
688 // TODO: remove disgusting hack for 'special' treatment of consensus line.
689 if (label.indexOf("Consensus") == 0)
693 for (int i = 0; i < annotations.length; i++)
695 if (annotations[i] != null)
697 buffer.append(annotations[i].description);
704 return buffer.toString();
707 public void setThreshold(GraphLine line)
712 public GraphLine getThreshold()
718 * Attach the annotation to seqRef, starting from startRes position. If
719 * alreadyMapped is true then the indices of the annotation[] array are
720 * sequence positions rather than alignment column positions.
724 * @param alreadyMapped
726 public void createSequenceMapping(SequenceI seqRef, int startRes,
727 boolean alreadyMapped)
734 sequenceRef = seqRef;
735 if (annotations == null)
739 sequenceMapping = new java.util.Hashtable();
743 for (int i = 0; i < annotations.length; i++)
745 if (annotations[i] != null)
749 seqPos = seqRef.findPosition(i);
753 seqPos = i + startRes;
756 sequenceMapping.put(new Integer(seqPos), annotations[i]);
762 public void adjustForAlignment()
764 if (sequenceRef == null)
767 if (annotations == null)
772 int a = 0, aSize = sequenceRef.getLength();
781 Annotation[] temp = new Annotation[aSize];
784 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
786 index = new Integer(a);
787 if (sequenceMapping.containsKey(index))
789 position = sequenceRef.findIndex(a) - 1;
791 temp[position] = (Annotation) sequenceMapping.get(index);
799 * remove any null entries in annotation row and return the number of non-null
800 * annotation elements.
804 public int compactAnnotationArray()
806 int i = 0, iSize = annotations.length;
809 if (annotations[i] == null)
812 System.arraycopy(annotations, i + 1, annotations, i, iSize - i
821 Annotation[] ann = annotations;
822 annotations = new Annotation[i];
823 System.arraycopy(ann, 0, annotations, 0, i);
829 * Associate this annotion with the aligned residues of a particular sequence.
830 * sequenceMapping will be updated in the following way: null sequenceI -
831 * existing mapping will be discarded but annotations left in mapped
832 * positions. valid sequenceI not equal to current sequenceRef: mapping is
833 * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
834 * parameter to specify correspondence between current and new sequenceRef
838 public void setSequenceRef(SequenceI sequenceI)
840 if (sequenceI != null)
842 if (sequenceRef != null)
844 if (sequenceRef != sequenceI
845 && !sequenceRef.equals(sequenceI)
846 && sequenceRef.getDatasetSequence() != sequenceI
847 .getDatasetSequence())
849 // if sequenceRef isn't intersecting with sequenceI
850 // throw away old mapping and reconstruct.
852 if (sequenceMapping != null)
854 sequenceMapping = null;
855 // compactAnnotationArray();
857 createSequenceMapping(sequenceI, 1, true);
858 adjustForAlignment();
862 // Mapping carried over
863 sequenceRef = sequenceI;
869 createSequenceMapping(sequenceI, 1, true);
870 adjustForAlignment();
875 // throw away the mapping without compacting.
876 sequenceMapping = null;
884 public double getScore()
893 public void setScore(double score)
901 * @return true if annotation has an associated score
903 public boolean hasScore()
905 return hasScore || !Double.isNaN(score);
909 * Score only annotation
915 public AlignmentAnnotation(String label, String description, double score)
917 this(label, description, null);
922 * copy constructor with edit based on the hidden columns marked in colSel
924 * @param alignmentAnnotation
927 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
928 ColumnSelection colSel)
930 this(alignmentAnnotation);
931 if (annotations == null)
935 colSel.makeVisibleAnnotation(this);
938 public void setPadGaps(boolean padgaps, char gapchar)
940 this.padGaps = padgaps;
944 for (int i = 0; i < annotations.length; i++)
946 if (annotations[i] == null)
947 annotations[i] = new Annotation(String.valueOf(gapchar), null,
949 else if (annotations[i].displayCharacter == null
950 || annotations[i].displayCharacter.equals(" "))
951 annotations[i].displayCharacter = String.valueOf(gapchar);
957 * format description string for display
960 * @return Get the annotation description string optionally prefixed by
961 * associated sequence name (if any)
963 public String getDescription(boolean seqname)
965 if (seqname && this.sequenceRef != null)
967 int i=description.toLowerCase().indexOf("<html>");
970 // move the html tag to before the sequence reference.
971 return "<html>"+sequenceRef.getName()+" : "+description.substring(i+6);
973 return sequenceRef.getName() + " : " + description;
978 public boolean isValidStruc()
980 return invalidrnastruc==-1;
982 public long getInvalidStrucPos()
984 return invalidrnastruc;
988 * machine readable ID string indicating what generated this annotation
990 protected String calcId="";
991 public String getCalcId()
996 public void setCalcId(String calcId)
998 this.calcId = calcId;