2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
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
10 * of the License, or (at your option) any later version.
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.
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.
21 package jalview.datamodel;
23 import jalview.analysis.Rna;
24 import jalview.analysis.SecStrConsensus.SimpleBP;
25 import jalview.analysis.WUSSParseException;
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;
34 import java.util.Map.Entry;
42 public class AlignmentAnnotation
45 * If true, this annotations is calculated every edit, eg consensus, quality
46 * or conservation graphs
48 public boolean autoCalculated = false;
51 * unique ID for this annotation, used to match up the same annotation row
52 * shown in multiple views and alignments
54 public String annotationId;
57 * the sequence this annotation is associated with (or null)
59 public SequenceI sequenceRef;
61 /** label shown in dropdown menus and in the annotation label area */
64 /** longer description text shown as a tooltip */
65 public String description;
67 /** Array of annotations placed in the current coordinate system */
68 public Annotation[] annotations;
70 public ArrayList<SimpleBP> bps = null;
73 * RNA secondary structure contact positions
75 public SequenceFeature[] _rnasecstr = null;
78 * position of annotation resulting in invalid WUSS parsing or -1
80 private long invalidrnastruc = -1;
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
88 private void _updateRnaSecStr(CharSequence RNAannot)
92 _rnasecstr = Rna.GetBasePairs(RNAannot);
93 bps = Rna.GetModeleBP(RNAannot);
95 } catch (WUSSParseException px)
97 // DEBUG System.out.println(px);
98 invalidrnastruc = px.getProblemPos();
100 if (invalidrnastruc > -1)
104 Rna.HelixMap(_rnasecstr);
105 // setRNAStruc(RNAannot);
107 if (_rnasecstr != null && _rnasecstr.length > 0)
109 // show all the RNA secondary structure annotation symbols.
111 showAllColLabels = true;
112 scaleColLabel = true;
114 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
118 * map of positions in the associated annotation
120 public java.util.Hashtable<Integer, Annotation> sequenceMapping;
123 public float graphMin;
126 public float graphMax;
129 * Score associated with label and description.
131 public double score = Double.NaN;
134 * flag indicating if annotation has a score.
136 public boolean hasScore = false;
138 public GraphLine threshold;
140 // Graphical hints and tips
142 /** Can this row be edited by the user ? */
143 public boolean editable = false;
145 /** Indicates if annotation has a graphical symbol track */
146 public boolean hasIcons; //
148 /** Indicates if annotation has a text character label */
149 public boolean hasText;
151 /** is the row visible */
152 public boolean visible = true;
154 public int graphGroup = -1;
156 /** Displayed height of row in pixels */
157 public int height = 0;
159 public int graph = 0;
161 public int graphHeight = 40;
163 public boolean padGaps = false;
165 public static final int NO_GRAPH = 0;
167 public static final int BAR_GRAPH = 1;
169 public static final int LINE_GRAPH = 2;
171 public boolean belowAlignment = true;
173 public SequenceGroup groupRef = null;
176 * display every column label, even if there is a row of identical labels
178 public boolean showAllColLabels = false;
181 * scale the column label to fit within the alignment column.
183 public boolean scaleColLabel = false;
186 * centre the column labels relative to the alignment column
188 public boolean centreColLabels = false;
190 private boolean isrna;
195 * @see java.lang.Object#finalize()
197 protected void finalize() throws Throwable
204 public static int getGraphValueFromString(String string)
206 if (string.equalsIgnoreCase("BAR_GRAPH"))
210 else if (string.equalsIgnoreCase("LINE_GRAPH"))
220 // JBPNote: what does this do ?
221 public void ConcenStru(CharSequence RNAannot) throws WUSSParseException
223 bps = Rna.GetModeleBP(RNAannot);
227 * Creates a new AlignmentAnnotation object.
230 * short label shown under sequence labels
232 * text displayed on mouseover
234 * set of positional annotation elements
236 public AlignmentAnnotation(String label, String description,
237 Annotation[] annotations)
242 this.description = description;
243 this.annotations = annotations;
245 validateRangeAndDisplay();
249 * Checks if annotation labels represent secondary structures
252 void areLabelsSecondaryStructure()
254 boolean nonSSLabel = false;
256 StringBuffer rnastring = new StringBuffer();
259 for (int i = 0; i < annotations.length; i++)
261 if (annotations[i] == null)
265 if (annotations[i].secondaryStructure == 'H'
266 || annotations[i].secondaryStructure == 'E')
271 // Check for RNA secondary structure
273 // System.out.println(annotations[i].secondaryStructure);
274 // TODO: 2.8.2 should this ss symbol validation check be a function in
275 // RNA/ResidueProperties ?
276 if (annotations[i].secondaryStructure == '('
277 || annotations[i].secondaryStructure == '['
278 || annotations[i].secondaryStructure == '<'
279 || annotations[i].secondaryStructure == '{'
280 || annotations[i].secondaryStructure == 'A'
281 || annotations[i].secondaryStructure == 'B'
282 || annotations[i].secondaryStructure == 'C'
283 || annotations[i].secondaryStructure == 'D'
284 || annotations[i].secondaryStructure == 'E'
285 || annotations[i].secondaryStructure == 'F'
286 || annotations[i].secondaryStructure == 'G'
287 || annotations[i].secondaryStructure == 'H'
288 || annotations[i].secondaryStructure == 'I'
289 || annotations[i].secondaryStructure == 'J'
290 || annotations[i].secondaryStructure == 'K'
291 || annotations[i].secondaryStructure == 'L'
292 || annotations[i].secondaryStructure == 'M'
293 || annotations[i].secondaryStructure == 'N'
294 || annotations[i].secondaryStructure == 'O'
295 || annotations[i].secondaryStructure == 'P'
296 || annotations[i].secondaryStructure == 'Q'
297 || annotations[i].secondaryStructure == 'R'
298 || annotations[i].secondaryStructure == 'S'
299 || annotations[i].secondaryStructure == 'T'
300 || annotations[i].secondaryStructure == 'U'
301 || annotations[i].secondaryStructure == 'V'
302 || annotations[i].secondaryStructure == 'W'
303 || annotations[i].secondaryStructure == 'X'
304 || annotations[i].secondaryStructure == 'Y'
305 || annotations[i].secondaryStructure == 'Z')
312 // System.out.println("displaychar " + annotations[i].displayCharacter);
314 if (annotations[i].displayCharacter == null
315 || annotations[i].displayCharacter.length() == 0)
317 rnastring.append('.');
320 if (annotations[i].displayCharacter.length() == 1)
322 firstChar = annotations[i].displayCharacter.charAt(0);
323 // check to see if it looks like a sequence or is secondary structure
325 if (annotations[i].secondaryStructure != ' '
328 // Uncomment to only catch case where
329 // displayCharacter==secondary
331 // to correctly redisplay SS annotation imported from Stockholm,
332 // exported to JalviewXML and read back in again.
334 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
369 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
371 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
384 rnastring.append(annotations[i].displayCharacter.charAt(1));
387 if (annotations[i].displayCharacter.length() > 0)
396 for (int j = 0; j < annotations.length; j++)
398 if (annotations[j] != null
399 && annotations[j].secondaryStructure != ' ')
401 annotations[j].displayCharacter = String
402 .valueOf(annotations[j].secondaryStructure);
403 annotations[j].secondaryStructure = ' ';
412 _updateRnaSecStr(new AnnotCharSequence());
416 annotationId = this.hashCode() + "";
420 * flyweight access to positions in the alignment annotation row for RNA
426 private class AnnotCharSequence implements CharSequence
432 public AnnotCharSequence()
434 this(0, annotations.length);
437 public AnnotCharSequence(int start, int end)
444 public CharSequence subSequence(int start, int end)
446 return new AnnotCharSequence(offset + start, offset + end);
456 public char charAt(int index)
459 return ((index + offset < 0) || (index + offset) >= max
460 || annotations[index + offset] == null || (dc = annotations[index
461 + offset].displayCharacter.trim()).length() < 1) ? '.' : dc
465 public String toString()
467 char[] string = new char[max - offset];
468 int mx = annotations.length;
470 for (int i = offset; i < mx; i++)
473 string[i] = (annotations[i] == null || (dc = annotations[i].displayCharacter
474 .trim()).length() < 1) ? '.' : dc.charAt(0);
476 return new String(string);
480 private long _lastrnaannot = -1;
482 public String getRNAStruc()
486 String rnastruc = new AnnotCharSequence().toString();
487 if (_lastrnaannot != rnastruc.hashCode())
489 // ensure rna structure contacts are up to date
490 _lastrnaannot = rnastruc.hashCode();
491 _updateRnaSecStr(rnastruc);
499 * Creates a new AlignmentAnnotation object.
514 public AlignmentAnnotation(String label, String description,
515 Annotation[] annotations, float min, float max, int graphType)
517 // graphs are not editable
518 editable = graphType == 0;
521 this.description = description;
522 this.annotations = annotations;
526 validateRangeAndDisplay();
530 * checks graphMin and graphMax, secondary structure symbols, sets graphType
531 * appropriately, sets null labels to the empty string if appropriate.
533 public void validateRangeAndDisplay()
536 if (annotations == null)
538 visible = false; // try to prevent renderer from displaying.
539 return; // this is a non-annotation row annotation - ie a sequence score.
542 int graphType = graph;
543 float min = graphMin;
544 float max = graphMax;
545 boolean drawValues = true;
550 for (int i = 0; i < annotations.length; i++)
552 if (annotations[i] == null)
557 if (drawValues && annotations[i].displayCharacter != null
558 && annotations[i].displayCharacter.length() > 1)
563 if (annotations[i].value > max)
565 max = annotations[i].value;
568 if (annotations[i].value < min)
570 min = annotations[i].value;
572 if (_linecolour == null && annotations[i].colour != null)
574 _linecolour = annotations[i].colour;
577 // ensure zero is origin for min/max ranges on only one side of zero
594 areLabelsSecondaryStructure();
596 if (!drawValues && graphType != NO_GRAPH)
598 for (int i = 0; i < annotations.length; i++)
600 if (annotations[i] != null)
602 annotations[i].displayCharacter = "X";
609 * Copy constructor creates a new independent annotation row with the same
610 * associated sequenceRef
614 public AlignmentAnnotation(AlignmentAnnotation annotation)
616 this.label = new String(annotation.label);
617 if (annotation.description != null)
619 this.description = new String(annotation.description);
621 this.graphMin = annotation.graphMin;
622 this.graphMax = annotation.graphMax;
623 this.graph = annotation.graph;
624 this.graphHeight = annotation.graphHeight;
625 this.graphGroup = annotation.graphGroup;
626 this.groupRef = annotation.groupRef;
627 this.editable = annotation.editable;
628 this.autoCalculated = annotation.autoCalculated;
629 this.hasIcons = annotation.hasIcons;
630 this.hasText = annotation.hasText;
631 this.height = annotation.height;
632 this.label = annotation.label;
633 this.padGaps = annotation.padGaps;
634 this.visible = annotation.visible;
635 this.centreColLabels = annotation.centreColLabels;
636 this.scaleColLabel = annotation.scaleColLabel;
637 this.showAllColLabels = annotation.showAllColLabels;
638 this.calcId = annotation.calcId;
639 if (annotation.properties!=null)
641 properties = new HashMap<String,String>();
642 for (Map.Entry<String, String> val:annotation.properties.entrySet())
644 properties.put(val.getKey(), val.getValue());
647 if (this.hasScore = annotation.hasScore)
649 this.score = annotation.score;
651 if (annotation.threshold != null)
653 threshold = new GraphLine(annotation.threshold);
655 Annotation[] ann = annotation.annotations;
656 if (annotation.annotations != null)
658 this.annotations = new Annotation[ann.length];
659 for (int i = 0; i < ann.length; i++)
663 annotations[i] = new Annotation(ann[i]);
664 if (_linecolour != null)
666 _linecolour = annotations[i].colour;
671 if (annotation.sequenceRef != null)
673 this.sequenceRef = annotation.sequenceRef;
674 if (annotation.sequenceMapping != null)
677 sequenceMapping = new Hashtable();
678 Enumeration pos = annotation.sequenceMapping.keys();
679 while (pos.hasMoreElements())
681 // could optimise this!
682 p = (Integer) pos.nextElement();
683 Annotation a = annotation.sequenceMapping.get(p);
690 for (int i = 0; i < ann.length; i++)
694 sequenceMapping.put(p, annotations[i]);
702 this.sequenceMapping = null;
705 // TODO: check if we need to do this: JAL-952
706 // if (this.isrna=annotation.isrna)
708 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
710 validateRangeAndDisplay(); // construct hashcodes, etc.
714 * clip the annotation to the columns given by startRes and endRes (inclusive)
715 * and prune any existing sequenceMapping to just those columns.
720 public void restrict(int startRes, int endRes)
722 if (annotations == null)
731 if (startRes >= annotations.length)
733 startRes = annotations.length - 1;
735 if (endRes >= annotations.length)
737 endRes = annotations.length - 1;
739 if (annotations == null)
743 Annotation[] temp = new Annotation[endRes - startRes + 1];
744 if (startRes < annotations.length)
746 System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
749 if (sequenceRef != null)
751 // Clip the mapping, if it exists.
752 int spos = sequenceRef.findPosition(startRes);
753 int epos = sequenceRef.findPosition(endRes);
754 if (sequenceMapping != null)
756 Hashtable newmapping = new Hashtable();
757 Enumeration e = sequenceMapping.keys();
758 while (e.hasMoreElements())
760 Integer pos = (Integer) e.nextElement();
761 if (pos.intValue() >= spos && pos.intValue() <= epos)
763 newmapping.put(pos, sequenceMapping.get(pos));
766 sequenceMapping.clear();
767 sequenceMapping = newmapping;
774 * set the annotation row to be at least length Annotations
777 * minimum number of columns required in the annotation row
778 * @return false if the annotation row is greater than length
780 public boolean padAnnotation(int length)
782 if (annotations == null)
784 return true; // annotation row is correct - null == not visible and
787 if (annotations.length < length)
789 Annotation[] na = new Annotation[length];
790 System.arraycopy(annotations, 0, na, 0, annotations.length);
794 return annotations.length > length;
801 * @return DOCUMENT ME!
803 public String toString()
805 StringBuffer buffer = new StringBuffer();
807 for (int i = 0; i < annotations.length; i++)
809 if (annotations[i] != null)
813 buffer.append(annotations[i].value);
817 buffer.append(annotations[i].secondaryStructure);
821 buffer.append(annotations[i].displayCharacter);
827 // TODO: remove disgusting hack for 'special' treatment of consensus line.
828 if (label.indexOf("Consensus") == 0)
832 for (int i = 0; i < annotations.length; i++)
834 if (annotations[i] != null)
836 buffer.append(annotations[i].description);
843 return buffer.toString();
846 public void setThreshold(GraphLine line)
851 public GraphLine getThreshold()
857 * Attach the annotation to seqRef, starting from startRes position. If
858 * alreadyMapped is true then the indices of the annotation[] array are
859 * sequence positions rather than alignment column positions.
863 * @param alreadyMapped
865 public void createSequenceMapping(SequenceI seqRef, int startRes,
866 boolean alreadyMapped)
873 sequenceRef = seqRef;
874 if (annotations == null)
878 sequenceMapping = new java.util.Hashtable();
882 for (int i = 0; i < annotations.length; i++)
884 if (annotations[i] != null)
888 seqPos = seqRef.findPosition(i);
892 seqPos = i + startRes;
895 sequenceMapping.put(new Integer(seqPos), annotations[i]);
901 public void adjustForAlignment()
903 if (sequenceRef == null)
908 if (annotations == null)
913 int a = 0, aSize = sequenceRef.getLength();
922 Annotation[] temp = new Annotation[aSize];
925 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
927 index = new Integer(a);
928 if (sequenceMapping.containsKey(index))
930 position = sequenceRef.findIndex(a) - 1;
932 temp[position] = sequenceMapping.get(index);
940 * remove any null entries in annotation row and return the number of non-null
941 * annotation elements.
945 public int compactAnnotationArray()
947 int i = 0, iSize = annotations.length;
950 if (annotations[i] == null)
954 System.arraycopy(annotations, i + 1, annotations, i, iSize - i
964 Annotation[] ann = annotations;
965 annotations = new Annotation[i];
966 System.arraycopy(ann, 0, annotations, 0, i);
972 * Associate this annotion with the aligned residues of a particular sequence.
973 * sequenceMapping will be updated in the following way: null sequenceI -
974 * existing mapping will be discarded but annotations left in mapped
975 * positions. valid sequenceI not equal to current sequenceRef: mapping is
976 * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
977 * parameter to specify correspondence between current and new sequenceRef
981 public void setSequenceRef(SequenceI sequenceI)
983 if (sequenceI != null)
985 if (sequenceRef != null)
987 boolean rIsDs=sequenceRef.getDatasetSequence()==null,tIsDs=sequenceI.getDatasetSequence()==null;
988 if (sequenceRef != sequenceI
989 && (rIsDs && !tIsDs && sequenceRef != sequenceI
990 .getDatasetSequence())
991 && (!rIsDs && tIsDs && sequenceRef.getDatasetSequence() != sequenceI)
992 && (!rIsDs && !tIsDs && sequenceRef.getDatasetSequence() != sequenceI
993 .getDatasetSequence())
994 && !sequenceRef.equals(sequenceI))
996 // if sequenceRef isn't intersecting with sequenceI
997 // throw away old mapping and reconstruct.
999 if (sequenceMapping != null)
1001 sequenceMapping = null;
1002 // compactAnnotationArray();
1004 createSequenceMapping(sequenceI, 1, true);
1005 adjustForAlignment();
1009 // Mapping carried over
1010 sequenceRef = sequenceI;
1015 // No mapping exists
1016 createSequenceMapping(sequenceI, 1, true);
1017 adjustForAlignment();
1022 // throw away the mapping without compacting.
1023 sequenceMapping = null;
1031 public double getScore()
1040 public void setScore(double score)
1048 * @return true if annotation has an associated score
1050 public boolean hasScore()
1052 return hasScore || !Double.isNaN(score);
1056 * Score only annotation
1059 * @param description
1062 public AlignmentAnnotation(String label, String description, double score)
1064 this(label, description, null);
1069 * copy constructor with edit based on the hidden columns marked in colSel
1071 * @param alignmentAnnotation
1074 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1075 ColumnSelection colSel)
1077 this(alignmentAnnotation);
1078 if (annotations == null)
1082 colSel.makeVisibleAnnotation(this);
1085 public void setPadGaps(boolean padgaps, char gapchar)
1087 this.padGaps = padgaps;
1091 for (int i = 0; i < annotations.length; i++)
1093 if (annotations[i] == null)
1095 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1098 else if (annotations[i].displayCharacter == null
1099 || annotations[i].displayCharacter.equals(" "))
1101 annotations[i].displayCharacter = String.valueOf(gapchar);
1108 * format description string for display
1111 * @return Get the annotation description string optionally prefixed by
1112 * associated sequence name (if any)
1114 public String getDescription(boolean seqname)
1116 if (seqname && this.sequenceRef != null)
1118 int i = description.toLowerCase().indexOf("<html>");
1121 // move the html tag to before the sequence reference.
1122 return "<html>" + sequenceRef.getName() + " : "
1123 + description.substring(i + 6);
1125 return sequenceRef.getName() + " : " + description;
1130 public boolean isValidStruc()
1132 return invalidrnastruc == -1;
1135 public long getInvalidStrucPos()
1137 return invalidrnastruc;
1141 * machine readable ID string indicating what generated this annotation
1143 protected String calcId = "";
1146 * properties associated with the calcId
1148 protected Map<String, String> properties = new HashMap<String, String>();
1151 * base colour for line graphs. If null, will be set automatically by
1152 * searching the alignment annotation
1154 public java.awt.Color _linecolour;
1156 public String getCalcId()
1161 public void setCalcId(String calcId)
1163 this.calcId = calcId;
1166 public boolean isRNA()
1172 * transfer annotation to the given sequence using the given mapping from the
1173 * current positions or an existing sequence mapping
1177 * map involving sq as To or From
1179 public void liftOver(SequenceI sq, Mapping sp2sq)
1181 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1183 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and Protein reference frames
1184 throw new Error("liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1186 boolean mapIsTo = (sp2sq != null) ? (sp2sq.getTo() == sq || sp2sq
1187 .getTo() == sq.getDatasetSequence()) : false;
1189 // TODO build a better annotation element map and get rid of annotations[]
1190 Hashtable<Integer, Annotation> mapForsq = new Hashtable();
1191 if (sequenceMapping != null)
1195 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1197 Integer mpos = Integer.valueOf(mapIsTo ? sp2sq
1198 .getMappedPosition(ie.getKey()) : sp2sq.getPosition(ie
1200 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1202 mapForsq.put(mpos, ie.getValue());
1205 sequenceMapping = mapForsq;
1207 adjustForAlignment();
1217 * like liftOver but more general.
1219 * Takes an array of int pairs that will be used to update the internal
1220 * sequenceMapping and so shuffle the annotated positions
1223 * - new sequence reference for the annotation row - if null,
1224 * sequenceRef is left unchanged
1226 * array of ints containing corresponding positions
1228 * - column for current coordinate system (-1 for index+1)
1230 * - column for destination coordinate system (-1 for index+1)
1232 * - offset added to index when referencing either coordinate system
1233 * @note no checks are made as to whether from and/or to are sensible
1234 * @note caller should add the remapped annotation to newref if they have not
1237 public void remap(SequenceI newref, int[][] mapping, int from, int to,
1240 if (mapping != null)
1242 Hashtable<Integer, Annotation> old = sequenceMapping, remap = new Hashtable<Integer, Annotation>();
1244 for (int mp[] : mapping)
1250 Annotation ann = null;
1253 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1257 if (mp != null && mp.length > from)
1259 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1266 remap.put(Integer.valueOf(idxoffset + index), ann);
1270 if (to > -1 && to < mp.length)
1272 remap.put(Integer.valueOf(mp[to]), ann);
1277 sequenceMapping = remap;
1281 sequenceRef = newref;
1283 adjustForAlignment();
1287 public String getProperty(String property)
1289 if (properties == null)
1293 return properties.get(property);
1296 public void setProperty(String property, String value)
1298 if (properties==null)
1300 properties = new HashMap<String,String>();
1302 properties.put(property, value);
1305 public boolean hasProperties()
1307 return properties != null && properties.size() > 0;
1310 public Collection<String> getProperties()
1312 if (properties == null)
1314 return Collections.EMPTY_LIST;
1316 return properties.keySet();