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.Enumeration;
29 import java.util.HashMap;
30 import java.util.Hashtable;
32 import java.util.Map.Entry;
40 public class AlignmentAnnotation
43 * If true, this annotations is calculated every edit, eg consensus, quality
44 * or conservation graphs
46 public boolean autoCalculated = false;
49 * unique ID for this annotation, used to match up the same annotation row
50 * shown in multiple views and alignments
52 public String annotationId;
55 * the sequence this annotation is associated with (or null)
57 public SequenceI sequenceRef;
59 /** label shown in dropdown menus and in the annotation label area */
62 /** longer description text shown as a tooltip */
63 public String description;
65 /** Array of annotations placed in the current coordinate system */
66 public Annotation[] annotations;
68 public ArrayList<SimpleBP> bps = null;
71 * RNA secondary structure contact positions
73 public SequenceFeature[] _rnasecstr = null;
76 * position of annotation resulting in invalid WUSS parsing or -1
78 private long invalidrnastruc = -1;
81 * Updates the _rnasecstr field Determines the positions that base pair and
82 * the positions of helices based on secondary structure from a Stockholm file
86 private void _updateRnaSecStr(CharSequence RNAannot)
90 _rnasecstr = Rna.GetBasePairs(RNAannot);
91 bps = Rna.GetModeleBP(RNAannot);
93 } catch (WUSSParseException px)
95 // DEBUG System.out.println(px);
96 invalidrnastruc = px.getProblemPos();
98 if (invalidrnastruc > -1)
102 Rna.HelixMap(_rnasecstr);
103 // setRNAStruc(RNAannot);
105 if (_rnasecstr != null && _rnasecstr.length > 0)
107 // show all the RNA secondary structure annotation symbols.
109 showAllColLabels = true;
110 scaleColLabel = true;
112 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
116 * map of positions in the associated annotation
118 public java.util.Hashtable<Integer, Annotation> sequenceMapping;
121 public float graphMin;
124 public float graphMax;
127 * Score associated with label and description.
129 public double score = Double.NaN;
132 * flag indicating if annotation has a score.
134 public boolean hasScore = false;
136 public GraphLine threshold;
138 // Graphical hints and tips
140 /** Can this row be edited by the user ? */
141 public boolean editable = false;
143 /** Indicates if annotation has a graphical symbol track */
144 public boolean hasIcons; //
146 /** Indicates if annotation has a text character label */
147 public boolean hasText;
149 /** is the row visible */
150 public boolean visible = true;
152 public int graphGroup = -1;
154 /** Displayed height of row in pixels */
155 public int height = 0;
157 public int graph = 0;
159 public int graphHeight = 40;
161 public boolean padGaps = false;
163 public static final int NO_GRAPH = 0;
165 public static final int BAR_GRAPH = 1;
167 public static final int LINE_GRAPH = 2;
169 public boolean belowAlignment = true;
171 public SequenceGroup groupRef = null;
174 * display every column label, even if there is a row of identical labels
176 public boolean showAllColLabels = false;
179 * scale the column label to fit within the alignment column.
181 public boolean scaleColLabel = false;
184 * centre the column labels relative to the alignment column
186 public boolean centreColLabels = false;
188 private boolean isrna;
193 * @see java.lang.Object#finalize()
195 protected void finalize() throws Throwable
202 public static int getGraphValueFromString(String string)
204 if (string.equalsIgnoreCase("BAR_GRAPH"))
208 else if (string.equalsIgnoreCase("LINE_GRAPH"))
218 // JBPNote: what does this do ?
219 public void ConcenStru(CharSequence RNAannot) throws WUSSParseException
221 bps = Rna.GetModeleBP(RNAannot);
225 * Creates a new AlignmentAnnotation object.
228 * short label shown under sequence labels
230 * text displayed on mouseover
232 * set of positional annotation elements
234 public AlignmentAnnotation(String label, String description,
235 Annotation[] annotations)
240 this.description = description;
241 this.annotations = annotations;
243 validateRangeAndDisplay();
247 * Checks if annotation labels represent secondary structures
250 void areLabelsSecondaryStructure()
252 boolean nonSSLabel = false;
254 StringBuffer rnastring = new StringBuffer();
257 for (int i = 0; i < annotations.length; i++)
259 if (annotations[i] == null)
263 if (annotations[i].secondaryStructure == 'H'
264 || annotations[i].secondaryStructure == 'E')
269 // Check for RNA secondary structure
271 // System.out.println(annotations[i].secondaryStructure);
272 // TODO: 2.8.2 should this ss symbol validation check be a function in
273 // RNA/ResidueProperties ?
274 if (annotations[i].secondaryStructure == '('
275 || annotations[i].secondaryStructure == '['
276 || annotations[i].secondaryStructure == '<'
277 || annotations[i].secondaryStructure == '{'
278 || annotations[i].secondaryStructure == 'A'
279 || annotations[i].secondaryStructure == 'B'
280 || annotations[i].secondaryStructure == 'C'
281 || annotations[i].secondaryStructure == 'D'
282 || annotations[i].secondaryStructure == 'E'
283 || annotations[i].secondaryStructure == 'F'
284 || annotations[i].secondaryStructure == 'G'
285 || annotations[i].secondaryStructure == 'H'
286 || annotations[i].secondaryStructure == 'I'
287 || annotations[i].secondaryStructure == 'J'
288 || annotations[i].secondaryStructure == 'K'
289 || annotations[i].secondaryStructure == 'L'
290 || annotations[i].secondaryStructure == 'M'
291 || annotations[i].secondaryStructure == 'N'
292 || annotations[i].secondaryStructure == 'O'
293 || annotations[i].secondaryStructure == 'P'
294 || annotations[i].secondaryStructure == 'Q'
295 || annotations[i].secondaryStructure == 'R'
296 || annotations[i].secondaryStructure == 'S'
297 || annotations[i].secondaryStructure == 'T'
298 || annotations[i].secondaryStructure == 'U'
299 || annotations[i].secondaryStructure == 'V'
300 || annotations[i].secondaryStructure == 'W'
301 || annotations[i].secondaryStructure == 'X'
302 || annotations[i].secondaryStructure == 'Y'
303 || annotations[i].secondaryStructure == 'Z')
310 // System.out.println("displaychar " + annotations[i].displayCharacter);
312 if (annotations[i].displayCharacter == null
313 || annotations[i].displayCharacter.length() == 0)
315 rnastring.append('.');
318 if (annotations[i].displayCharacter.length() == 1)
320 firstChar = annotations[i].displayCharacter.charAt(0);
321 // check to see if it looks like a sequence or is secondary structure
323 if (annotations[i].secondaryStructure != ' '
326 // Uncomment to only catch case where
327 // displayCharacter==secondary
329 // to correctly redisplay SS annotation imported from Stockholm,
330 // exported to JalviewXML and read back in again.
332 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
367 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
369 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
382 rnastring.append(annotations[i].displayCharacter.charAt(1));
385 if (annotations[i].displayCharacter.length() > 0)
394 for (int j = 0; j < annotations.length; j++)
396 if (annotations[j] != null
397 && annotations[j].secondaryStructure != ' ')
399 annotations[j].displayCharacter = String
400 .valueOf(annotations[j].secondaryStructure);
401 annotations[j].secondaryStructure = ' ';
410 _updateRnaSecStr(new AnnotCharSequence());
414 annotationId = this.hashCode() + "";
418 * flyweight access to positions in the alignment annotation row for RNA
424 private class AnnotCharSequence implements CharSequence
430 public AnnotCharSequence()
432 this(0, annotations.length);
435 public AnnotCharSequence(int start, int end)
442 public CharSequence subSequence(int start, int end)
444 return new AnnotCharSequence(offset + start, offset + end);
454 public char charAt(int index)
457 return ((index + offset < 0) || (index + offset) >= max
458 || annotations[index + offset] == null || (dc = annotations[index
459 + offset].displayCharacter.trim()).length() < 1) ? '.' : dc
463 public String toString()
465 char[] string = new char[max - offset];
466 int mx = annotations.length;
468 for (int i = offset; i < mx; i++)
471 string[i] = (annotations[i] == null || (dc = annotations[i].displayCharacter
472 .trim()).length() < 1) ? '.' : dc.charAt(0);
474 return new String(string);
478 private long _lastrnaannot = -1;
480 public String getRNAStruc()
484 String rnastruc = new AnnotCharSequence().toString();
485 if (_lastrnaannot != rnastruc.hashCode())
487 // ensure rna structure contacts are up to date
488 _lastrnaannot = rnastruc.hashCode();
489 _updateRnaSecStr(rnastruc);
497 * Creates a new AlignmentAnnotation object.
512 public AlignmentAnnotation(String label, String description,
513 Annotation[] annotations, float min, float max, int graphType)
515 // graphs are not editable
516 editable = graphType == 0;
519 this.description = description;
520 this.annotations = annotations;
524 validateRangeAndDisplay();
528 * checks graphMin and graphMax, secondary structure symbols, sets graphType
529 * appropriately, sets null labels to the empty string if appropriate.
531 public void validateRangeAndDisplay()
534 if (annotations == null)
536 visible = false; // try to prevent renderer from displaying.
537 return; // this is a non-annotation row annotation - ie a sequence score.
540 int graphType = graph;
541 float min = graphMin;
542 float max = graphMax;
543 boolean drawValues = true;
548 for (int i = 0; i < annotations.length; i++)
550 if (annotations[i] == null)
555 if (drawValues && annotations[i].displayCharacter != null
556 && annotations[i].displayCharacter.length() > 1)
561 if (annotations[i].value > max)
563 max = annotations[i].value;
566 if (annotations[i].value < min)
568 min = annotations[i].value;
570 if (_linecolour == null && annotations[i].colour != null)
572 _linecolour = annotations[i].colour;
575 // ensure zero is origin for min/max ranges on only one side of zero
592 areLabelsSecondaryStructure();
594 if (!drawValues && graphType != NO_GRAPH)
596 for (int i = 0; i < annotations.length; i++)
598 if (annotations[i] != null)
600 annotations[i].displayCharacter = "X";
607 * Copy constructor creates a new independent annotation row with the same
608 * associated sequenceRef
612 public AlignmentAnnotation(AlignmentAnnotation annotation)
614 this.label = new String(annotation.label);
615 if (annotation.description != null)
617 this.description = new String(annotation.description);
619 this.graphMin = annotation.graphMin;
620 this.graphMax = annotation.graphMax;
621 this.graph = annotation.graph;
622 this.graphHeight = annotation.graphHeight;
623 this.graphGroup = annotation.graphGroup;
624 this.groupRef = annotation.groupRef;
625 this.editable = annotation.editable;
626 this.autoCalculated = annotation.autoCalculated;
627 this.hasIcons = annotation.hasIcons;
628 this.hasText = annotation.hasText;
629 this.height = annotation.height;
630 this.label = annotation.label;
631 this.padGaps = annotation.padGaps;
632 this.visible = annotation.visible;
633 this.centreColLabels = annotation.centreColLabels;
634 this.scaleColLabel = annotation.scaleColLabel;
635 this.showAllColLabels = annotation.showAllColLabels;
636 this.calcId = annotation.calcId;
637 if (annotation.properties!=null)
639 properties = new HashMap<String,String>();
640 for (Map.Entry<String, String> val:annotation.properties.entrySet())
642 properties.put(val.getKey(), val.getValue());
645 if (this.hasScore = annotation.hasScore)
647 this.score = annotation.score;
649 if (annotation.threshold != null)
651 threshold = new GraphLine(annotation.threshold);
653 Annotation[] ann = annotation.annotations;
654 if (annotation.annotations != null)
656 this.annotations = new Annotation[ann.length];
657 for (int i = 0; i < ann.length; i++)
661 annotations[i] = new Annotation(ann[i]);
662 if (_linecolour != null)
664 _linecolour = annotations[i].colour;
669 if (annotation.sequenceRef != null)
671 this.sequenceRef = annotation.sequenceRef;
672 if (annotation.sequenceMapping != null)
675 sequenceMapping = new Hashtable();
676 Enumeration pos = annotation.sequenceMapping.keys();
677 while (pos.hasMoreElements())
679 // could optimise this!
680 p = (Integer) pos.nextElement();
681 Annotation a = annotation.sequenceMapping.get(p);
688 for (int i = 0; i < ann.length; i++)
692 sequenceMapping.put(p, annotations[i]);
699 this.sequenceMapping = null;
703 // TODO: check if we need to do this: JAL-952
704 // if (this.isrna=annotation.isrna)
706 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
708 validateRangeAndDisplay(); // construct hashcodes, etc.
712 * clip the annotation to the columns given by startRes and endRes (inclusive)
713 * and prune any existing sequenceMapping to just those columns.
718 public void restrict(int startRes, int endRes)
720 if (annotations == null)
729 if (startRes >= annotations.length)
731 startRes = annotations.length - 1;
733 if (endRes >= annotations.length)
735 endRes = annotations.length - 1;
737 if (annotations == null)
741 Annotation[] temp = new Annotation[endRes - startRes + 1];
742 if (startRes < annotations.length)
744 System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
747 if (sequenceRef != null)
749 // Clip the mapping, if it exists.
750 int spos = sequenceRef.findPosition(startRes);
751 int epos = sequenceRef.findPosition(endRes);
752 if (sequenceMapping != null)
754 Hashtable newmapping = new Hashtable();
755 Enumeration e = sequenceMapping.keys();
756 while (e.hasMoreElements())
758 Integer pos = (Integer) e.nextElement();
759 if (pos.intValue() >= spos && pos.intValue() <= epos)
761 newmapping.put(pos, sequenceMapping.get(pos));
764 sequenceMapping.clear();
765 sequenceMapping = newmapping;
772 * set the annotation row to be at least length Annotations
775 * minimum number of columns required in the annotation row
776 * @return false if the annotation row is greater than length
778 public boolean padAnnotation(int length)
780 if (annotations == null)
782 return true; // annotation row is correct - null == not visible and
785 if (annotations.length < length)
787 Annotation[] na = new Annotation[length];
788 System.arraycopy(annotations, 0, na, 0, annotations.length);
792 return annotations.length > length;
799 * @return DOCUMENT ME!
801 public String toString()
803 StringBuffer buffer = new StringBuffer();
805 for (int i = 0; i < annotations.length; i++)
807 if (annotations[i] != null)
811 buffer.append(annotations[i].value);
815 buffer.append(annotations[i].secondaryStructure);
819 buffer.append(annotations[i].displayCharacter);
825 // TODO: remove disgusting hack for 'special' treatment of consensus line.
826 if (label.indexOf("Consensus") == 0)
830 for (int i = 0; i < annotations.length; i++)
832 if (annotations[i] != null)
834 buffer.append(annotations[i].description);
841 return buffer.toString();
844 public void setThreshold(GraphLine line)
849 public GraphLine getThreshold()
855 * Attach the annotation to seqRef, starting from startRes position. If
856 * alreadyMapped is true then the indices of the annotation[] array are
857 * sequence positions rather than alignment column positions.
861 * @param alreadyMapped
863 public void createSequenceMapping(SequenceI seqRef, int startRes,
864 boolean alreadyMapped)
871 sequenceRef = seqRef;
872 if (annotations == null)
876 sequenceMapping = new java.util.Hashtable();
880 for (int i = 0; i < annotations.length; i++)
882 if (annotations[i] != null)
886 seqPos = seqRef.findPosition(i);
890 seqPos = i + startRes;
893 sequenceMapping.put(new Integer(seqPos), annotations[i]);
899 public void adjustForAlignment()
901 if (sequenceRef == null)
906 if (annotations == null)
911 int a = 0, aSize = sequenceRef.getLength();
920 Annotation[] temp = new Annotation[aSize];
923 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
925 index = new Integer(a);
926 if (sequenceMapping.containsKey(index))
928 position = sequenceRef.findIndex(a) - 1;
930 temp[position] = sequenceMapping.get(index);
938 * remove any null entries in annotation row and return the number of non-null
939 * annotation elements.
943 public int compactAnnotationArray()
945 int i = 0, iSize = annotations.length;
948 if (annotations[i] == null)
952 System.arraycopy(annotations, i + 1, annotations, i, iSize - i
962 Annotation[] ann = annotations;
963 annotations = new Annotation[i];
964 System.arraycopy(ann, 0, annotations, 0, i);
970 * Associate this annotion with the aligned residues of a particular sequence.
971 * sequenceMapping will be updated in the following way: null sequenceI -
972 * existing mapping will be discarded but annotations left in mapped
973 * positions. valid sequenceI not equal to current sequenceRef: mapping is
974 * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
975 * parameter to specify correspondence between current and new sequenceRef
979 public void setSequenceRef(SequenceI sequenceI)
981 if (sequenceI != null)
983 if (sequenceRef != null)
985 boolean rIsDs=sequenceRef.getDatasetSequence()==null,tIsDs=sequenceI.getDatasetSequence()==null;
986 if (sequenceRef != sequenceI
987 && (rIsDs && !tIsDs && sequenceRef != sequenceI
988 .getDatasetSequence())
989 && (!rIsDs && tIsDs && sequenceRef.getDatasetSequence() != sequenceI)
990 && (!rIsDs && !tIsDs && sequenceRef.getDatasetSequence() != sequenceI
991 .getDatasetSequence())
992 && !sequenceRef.equals(sequenceI))
994 // if sequenceRef isn't intersecting with sequenceI
995 // throw away old mapping and reconstruct.
997 if (sequenceMapping != null)
999 sequenceMapping = null;
1000 // compactAnnotationArray();
1002 createSequenceMapping(sequenceI, 1, true);
1003 adjustForAlignment();
1007 // Mapping carried over
1008 sequenceRef = sequenceI;
1013 // No mapping exists
1014 createSequenceMapping(sequenceI, 1, true);
1015 adjustForAlignment();
1020 // throw away the mapping without compacting.
1021 sequenceMapping = null;
1029 public double getScore()
1038 public void setScore(double score)
1046 * @return true if annotation has an associated score
1048 public boolean hasScore()
1050 return hasScore || !Double.isNaN(score);
1054 * Score only annotation
1057 * @param description
1060 public AlignmentAnnotation(String label, String description, double score)
1062 this(label, description, null);
1067 * copy constructor with edit based on the hidden columns marked in colSel
1069 * @param alignmentAnnotation
1072 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1073 ColumnSelection colSel)
1075 this(alignmentAnnotation);
1076 if (annotations == null)
1080 colSel.makeVisibleAnnotation(this);
1083 public void setPadGaps(boolean padgaps, char gapchar)
1085 this.padGaps = padgaps;
1089 for (int i = 0; i < annotations.length; i++)
1091 if (annotations[i] == null)
1093 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1096 else if (annotations[i].displayCharacter == null
1097 || annotations[i].displayCharacter.equals(" "))
1099 annotations[i].displayCharacter = String.valueOf(gapchar);
1106 * format description string for display
1109 * @return Get the annotation description string optionally prefixed by
1110 * associated sequence name (if any)
1112 public String getDescription(boolean seqname)
1114 if (seqname && this.sequenceRef != null)
1116 int i = description.toLowerCase().indexOf("<html>");
1119 // move the html tag to before the sequence reference.
1120 return "<html>" + sequenceRef.getName() + " : "
1121 + description.substring(i + 6);
1123 return sequenceRef.getName() + " : " + description;
1128 public boolean isValidStruc()
1130 return invalidrnastruc == -1;
1133 public long getInvalidStrucPos()
1135 return invalidrnastruc;
1139 * machine readable ID string indicating what generated this annotation
1141 protected String calcId = "";
1144 * properties associated with the calcId
1146 protected Map<String, String> properties = new HashMap<String, String>();
1149 * base colour for line graphs. If null, will be set automatically by
1150 * searching the alignment annotation
1152 public java.awt.Color _linecolour;
1154 public String getCalcId()
1159 public void setCalcId(String calcId)
1161 this.calcId = calcId;
1164 public boolean isRNA()
1170 * transfer annotation to the given sequence using the given mapping from the
1171 * current positions or an existing sequence mapping
1175 * map involving sq as To or From
1177 public void liftOver(SequenceI sq, Mapping sp2sq)
1179 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1181 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and Protein reference frames
1182 throw new Error("liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1184 boolean mapIsTo = (sp2sq != null) ? (sp2sq.getTo() == sq || sp2sq
1185 .getTo() == sq.getDatasetSequence()) : false;
1187 // TODO build a better annotation element map and get rid of annotations[]
1188 Hashtable<Integer, Annotation> mapForsq = new Hashtable();
1189 if (sequenceMapping != null)
1193 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1195 Integer mpos = Integer.valueOf(mapIsTo ? sp2sq
1196 .getMappedPosition(ie.getKey()) : sp2sq.getPosition(ie
1198 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1200 mapForsq.put(mpos, ie.getValue());
1203 sequenceMapping = mapForsq;
1205 adjustForAlignment();
1215 * like liftOver but more general.
1217 * Takes an array of int pairs that will be used to update the internal
1218 * sequenceMapping and so shuffle the annotated positions
1221 * - new sequence reference for the annotation row - if null,
1222 * sequenceRef is left unchanged
1224 * array of ints containing corresponding positions
1226 * - column for current coordinate system (-1 for index+1)
1228 * - column for destination coordinate system (-1 for index+1)
1230 * - offset added to index when referencing either coordinate system
1231 * @note no checks are made as to whether from and/or to are sensible
1232 * @note caller should add the remapped annotation to newref if they have not
1235 public void remap(SequenceI newref, int[][] mapping, int from, int to,
1238 if (mapping != null)
1240 Hashtable<Integer, Annotation> old = sequenceMapping, remap = new Hashtable<Integer, Annotation>();
1242 for (int mp[] : mapping)
1248 Annotation ann = null;
1251 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1255 if (mp != null && mp.length > from)
1257 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1264 remap.put(Integer.valueOf(idxoffset + index), ann);
1268 if (to > -1 && to < mp.length)
1270 remap.put(Integer.valueOf(mp[to]), ann);
1275 sequenceMapping = remap;
1279 sequenceRef = newref;
1281 adjustForAlignment();
1285 public String getProperty(String property)
1287 if (properties == null)
1291 return properties.get(property);
1294 public void setProperty(String property, String value)
1296 if (properties==null)
1298 properties = new HashMap<String,String>();
1300 properties.put(property, value);
1303 public boolean hasProperties()
1305 return properties != null && properties.size() > 0;
1308 public Collection<String> getProperties()
1310 if (properties == null)
1312 return Collections.EMPTY_LIST;
1314 return properties.keySet();