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;
48 public String annotationId;
50 public SequenceI sequenceRef;
56 public String description;
59 public Annotation[] annotations;
61 public ArrayList<SimpleBP> bps = null;
64 * RNA secondary structure contact positions
66 public SequenceFeature[] _rnasecstr = null;
69 * position of annotation resulting in invalid WUSS parsing or -1
71 private long invalidrnastruc = -1;
74 * Updates the _rnasecstr field Determines the positions that base pair and
75 * the positions of helices based on secondary structure from a Stockholm file
79 private void _updateRnaSecStr(CharSequence RNAannot)
83 _rnasecstr = Rna.GetBasePairs(RNAannot);
84 bps = Rna.GetModeleBP(RNAannot);
86 } catch (WUSSParseException px)
88 // DEBUG System.out.println(px);
89 invalidrnastruc = px.getProblemPos();
91 if (invalidrnastruc > -1)
95 Rna.HelixMap(_rnasecstr);
96 // setRNAStruc(RNAannot);
98 if (_rnasecstr != null && _rnasecstr.length > 0)
100 // show all the RNA secondary structure annotation symbols.
102 showAllColLabels = true;
103 scaleColLabel = true;
105 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
108 public java.util.Hashtable<Integer, Annotation> sequenceMapping;
111 public float graphMin;
114 public float graphMax;
117 * Score associated with label and description.
119 public double score = Double.NaN;
122 * flag indicating if annotation has a score.
124 public boolean hasScore = false;
126 public GraphLine threshold;
128 // Graphical hints and tips
130 /** Can this row be edited by the user ? */
131 public boolean editable = false;
133 /** Indicates if annotation has a graphical symbol track */
134 public boolean hasIcons; //
136 /** Indicates if annotation has a text character label */
137 public boolean hasText;
139 /** is the row visible */
140 public boolean visible = true;
142 public int graphGroup = -1;
144 /** Displayed height of row in pixels */
145 public int height = 0;
147 public int graph = 0;
149 public int graphHeight = 40;
151 public boolean padGaps = false;
153 public static final int NO_GRAPH = 0;
155 public static final int BAR_GRAPH = 1;
157 public static final int LINE_GRAPH = 2;
159 public boolean belowAlignment = true;
161 public SequenceGroup groupRef = null;
164 * display every column label, even if there is a row of identical labels
166 public boolean showAllColLabels = false;
169 * scale the column label to fit within the alignment column.
171 public boolean scaleColLabel = false;
174 * centre the column labels relative to the alignment column
176 public boolean centreColLabels = false;
178 private boolean isrna;
183 * @see java.lang.Object#finalize()
185 protected void finalize() throws Throwable
192 public static int getGraphValueFromString(String string)
194 if (string.equalsIgnoreCase("BAR_GRAPH"))
198 else if (string.equalsIgnoreCase("LINE_GRAPH"))
208 // JBPNote: what does this do ?
209 public void ConcenStru(CharSequence RNAannot) throws WUSSParseException
211 bps = Rna.GetModeleBP(RNAannot);
215 * Creates a new AlignmentAnnotation object.
218 * short label shown under sequence labels
220 * text displayed on mouseover
222 * set of positional annotation elements
224 public AlignmentAnnotation(String label, String description,
225 Annotation[] annotations)
230 this.description = description;
231 this.annotations = annotations;
233 validateRangeAndDisplay();
237 * Checks if annotation labels represent secondary structures
240 void areLabelsSecondaryStructure()
242 boolean nonSSLabel = false;
244 StringBuffer rnastring = new StringBuffer();
247 for (int i = 0; i < annotations.length; i++)
249 if (annotations[i] == null)
253 if (annotations[i].secondaryStructure == 'H'
254 || annotations[i].secondaryStructure == 'E')
259 // Check for RNA secondary structure
261 // System.out.println(annotations[i].secondaryStructure);
262 // TODO: 2.8.2 should this ss symbol validation check be a function in
263 // RNA/ResidueProperties ?
264 if (annotations[i].secondaryStructure == '('
265 || annotations[i].secondaryStructure == '['
266 || annotations[i].secondaryStructure == '<'
267 || annotations[i].secondaryStructure == '{'
268 || annotations[i].secondaryStructure == 'A'
269 || annotations[i].secondaryStructure == 'B'
270 || annotations[i].secondaryStructure == 'C'
271 || annotations[i].secondaryStructure == 'D'
272 || annotations[i].secondaryStructure == 'E'
273 || annotations[i].secondaryStructure == 'F'
274 || annotations[i].secondaryStructure == 'G'
275 || annotations[i].secondaryStructure == 'H'
276 || annotations[i].secondaryStructure == 'I'
277 || annotations[i].secondaryStructure == 'J'
278 || annotations[i].secondaryStructure == 'K'
279 || annotations[i].secondaryStructure == 'L'
280 || annotations[i].secondaryStructure == 'M'
281 || annotations[i].secondaryStructure == 'N'
282 || annotations[i].secondaryStructure == 'O'
283 || annotations[i].secondaryStructure == 'P'
284 || annotations[i].secondaryStructure == 'Q'
285 || annotations[i].secondaryStructure == 'R'
286 || annotations[i].secondaryStructure == 'S'
287 || annotations[i].secondaryStructure == 'T'
288 || annotations[i].secondaryStructure == 'U'
289 || annotations[i].secondaryStructure == 'V'
290 || annotations[i].secondaryStructure == 'W'
291 || annotations[i].secondaryStructure == 'X'
292 || annotations[i].secondaryStructure == 'Y'
293 || annotations[i].secondaryStructure == 'Z')
300 // System.out.println("displaychar " + annotations[i].displayCharacter);
302 if (annotations[i].displayCharacter == null
303 || annotations[i].displayCharacter.length() == 0)
305 rnastring.append('.');
308 if (annotations[i].displayCharacter.length() == 1)
310 firstChar = annotations[i].displayCharacter.charAt(0);
311 // check to see if it looks like a sequence or is secondary structure
313 if (annotations[i].secondaryStructure != ' '
316 // Uncomment to only catch case where
317 // displayCharacter==secondary
319 // to correctly redisplay SS annotation imported from Stockholm,
320 // exported to JalviewXML and read back in again.
322 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
357 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
359 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
372 rnastring.append(annotations[i].displayCharacter.charAt(1));
375 if (annotations[i].displayCharacter.length() > 0)
384 for (int j = 0; j < annotations.length; j++)
386 if (annotations[j] != null
387 && annotations[j].secondaryStructure != ' ')
389 annotations[j].displayCharacter = String
390 .valueOf(annotations[j].secondaryStructure);
391 annotations[j].secondaryStructure = ' ';
400 _updateRnaSecStr(new AnnotCharSequence());
404 annotationId = this.hashCode() + "";
408 * flyweight access to positions in the alignment annotation row for RNA
414 private class AnnotCharSequence implements CharSequence
420 public AnnotCharSequence()
422 this(0, annotations.length);
425 public AnnotCharSequence(int start, int end)
432 public CharSequence subSequence(int start, int end)
434 return new AnnotCharSequence(offset + start, offset + end);
444 public char charAt(int index)
447 return ((index + offset < 0) || (index + offset) >= max
448 || annotations[index + offset] == null || (dc = annotations[index
449 + offset].displayCharacter.trim()).length() < 1) ? '.' : dc
453 public String toString()
455 char[] string = new char[max - offset];
456 int mx = annotations.length;
458 for (int i = offset; i < mx; i++)
461 string[i] = (annotations[i] == null || (dc = annotations[i].displayCharacter
462 .trim()).length() < 1) ? '.' : dc.charAt(0);
464 return new String(string);
468 private long _lastrnaannot = -1;
470 public String getRNAStruc()
474 String rnastruc = new AnnotCharSequence().toString();
475 if (_lastrnaannot != rnastruc.hashCode())
477 // ensure rna structure contacts are up to date
478 _lastrnaannot = rnastruc.hashCode();
479 _updateRnaSecStr(rnastruc);
487 * Creates a new AlignmentAnnotation object.
502 public AlignmentAnnotation(String label, String description,
503 Annotation[] annotations, float min, float max, int graphType)
505 // graphs are not editable
506 editable = graphType == 0;
509 this.description = description;
510 this.annotations = annotations;
514 validateRangeAndDisplay();
518 * checks graphMin and graphMax, secondary structure symbols, sets graphType
519 * appropriately, sets null labels to the empty string if appropriate.
521 public void validateRangeAndDisplay()
524 if (annotations == null)
526 visible = false; // try to prevent renderer from displaying.
527 return; // this is a non-annotation row annotation - ie a sequence score.
530 int graphType = graph;
531 float min = graphMin;
532 float max = graphMax;
533 boolean drawValues = true;
538 for (int i = 0; i < annotations.length; i++)
540 if (annotations[i] == null)
545 if (drawValues && annotations[i].displayCharacter != null
546 && annotations[i].displayCharacter.length() > 1)
551 if (annotations[i].value > max)
553 max = annotations[i].value;
556 if (annotations[i].value < min)
558 min = annotations[i].value;
560 if (_linecolour == null && annotations[i].colour != null)
562 _linecolour = annotations[i].colour;
565 // ensure zero is origin for min/max ranges on only one side of zero
582 areLabelsSecondaryStructure();
584 if (!drawValues && graphType != NO_GRAPH)
586 for (int i = 0; i < annotations.length; i++)
588 if (annotations[i] != null)
590 annotations[i].displayCharacter = "X";
597 * Copy constructor creates a new independent annotation row with the same
598 * associated sequenceRef
602 public AlignmentAnnotation(AlignmentAnnotation annotation)
604 this.label = new String(annotation.label);
605 if (annotation.description != null)
607 this.description = new String(annotation.description);
609 this.graphMin = annotation.graphMin;
610 this.graphMax = annotation.graphMax;
611 this.graph = annotation.graph;
612 this.graphHeight = annotation.graphHeight;
613 this.graphGroup = annotation.graphGroup;
614 this.groupRef = annotation.groupRef;
615 this.editable = annotation.editable;
616 this.autoCalculated = annotation.autoCalculated;
617 this.hasIcons = annotation.hasIcons;
618 this.hasText = annotation.hasText;
619 this.height = annotation.height;
620 this.label = annotation.label;
621 this.padGaps = annotation.padGaps;
622 this.visible = annotation.visible;
623 this.centreColLabels = annotation.centreColLabels;
624 this.scaleColLabel = annotation.scaleColLabel;
625 this.showAllColLabels = annotation.showAllColLabels;
626 this.calcId = annotation.calcId;
627 if (this.hasScore = annotation.hasScore)
629 this.score = annotation.score;
631 if (annotation.threshold != null)
633 threshold = new GraphLine(annotation.threshold);
635 if (annotation.annotations != null)
637 Annotation[] ann = annotation.annotations;
638 this.annotations = new Annotation[ann.length];
639 for (int i = 0; i < ann.length; i++)
643 annotations[i] = new Annotation(ann[i]);
644 if (_linecolour != null)
646 _linecolour = annotations[i].colour;
651 if (annotation.sequenceRef != null)
653 this.sequenceRef = annotation.sequenceRef;
654 if (annotation.sequenceMapping != null)
657 sequenceMapping = new Hashtable();
658 Enumeration pos = annotation.sequenceMapping.keys();
659 while (pos.hasMoreElements())
661 // could optimise this!
662 p = (Integer) pos.nextElement();
663 Annotation a = annotation.sequenceMapping.get(p);
668 for (int i = 0; i < ann.length; i++)
672 sequenceMapping.put(p, annotations[i]);
679 this.sequenceMapping = null;
683 // TODO: check if we need to do this: JAL-952
684 // if (this.isrna=annotation.isrna)
686 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
688 validateRangeAndDisplay(); // construct hashcodes, etc.
692 * clip the annotation to the columns given by startRes and endRes (inclusive)
693 * and prune any existing sequenceMapping to just those columns.
698 public void restrict(int startRes, int endRes)
700 if (annotations == null)
709 if (startRes >= annotations.length)
711 startRes = annotations.length - 1;
713 if (endRes >= annotations.length)
715 endRes = annotations.length - 1;
717 if (annotations == null)
721 Annotation[] temp = new Annotation[endRes - startRes + 1];
722 if (startRes < annotations.length)
724 System.arraycopy(annotations, startRes, temp, 0, endRes - startRes
727 if (sequenceRef != null)
729 // Clip the mapping, if it exists.
730 int spos = sequenceRef.findPosition(startRes);
731 int epos = sequenceRef.findPosition(endRes);
732 if (sequenceMapping != null)
734 Hashtable newmapping = new Hashtable();
735 Enumeration e = sequenceMapping.keys();
736 while (e.hasMoreElements())
738 Integer pos = (Integer) e.nextElement();
739 if (pos.intValue() >= spos && pos.intValue() <= epos)
741 newmapping.put(pos, sequenceMapping.get(pos));
744 sequenceMapping.clear();
745 sequenceMapping = newmapping;
752 * set the annotation row to be at least length Annotations
755 * minimum number of columns required in the annotation row
756 * @return false if the annotation row is greater than length
758 public boolean padAnnotation(int length)
760 if (annotations == null)
762 return true; // annotation row is correct - null == not visible and
765 if (annotations.length < length)
767 Annotation[] na = new Annotation[length];
768 System.arraycopy(annotations, 0, na, 0, annotations.length);
772 return annotations.length > length;
779 * @return DOCUMENT ME!
781 public String toString()
783 StringBuffer buffer = new StringBuffer();
785 for (int i = 0; i < annotations.length; i++)
787 if (annotations[i] != null)
791 buffer.append(annotations[i].value);
795 buffer.append(annotations[i].secondaryStructure);
799 buffer.append(annotations[i].displayCharacter);
805 // TODO: remove disgusting hack for 'special' treatment of consensus line.
806 if (label.indexOf("Consensus") == 0)
810 for (int i = 0; i < annotations.length; i++)
812 if (annotations[i] != null)
814 buffer.append(annotations[i].description);
821 return buffer.toString();
824 public void setThreshold(GraphLine line)
829 public GraphLine getThreshold()
835 * Attach the annotation to seqRef, starting from startRes position. If
836 * alreadyMapped is true then the indices of the annotation[] array are
837 * sequence positions rather than alignment column positions.
841 * @param alreadyMapped
843 public void createSequenceMapping(SequenceI seqRef, int startRes,
844 boolean alreadyMapped)
851 sequenceRef = seqRef;
852 if (annotations == null)
856 sequenceMapping = new java.util.Hashtable();
860 for (int i = 0; i < annotations.length; i++)
862 if (annotations[i] != null)
866 seqPos = seqRef.findPosition(i);
870 seqPos = i + startRes;
873 sequenceMapping.put(new Integer(seqPos), annotations[i]);
879 public void adjustForAlignment()
881 if (sequenceRef == null)
886 if (annotations == null)
891 int a = 0, aSize = sequenceRef.getLength();
900 Annotation[] temp = new Annotation[aSize];
903 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
905 index = new Integer(a);
906 if (sequenceMapping.containsKey(index))
908 position = sequenceRef.findIndex(a) - 1;
910 temp[position] = sequenceMapping.get(index);
918 * remove any null entries in annotation row and return the number of non-null
919 * annotation elements.
923 public int compactAnnotationArray()
925 int i = 0, iSize = annotations.length;
928 if (annotations[i] == null)
932 System.arraycopy(annotations, i + 1, annotations, i, iSize - i
942 Annotation[] ann = annotations;
943 annotations = new Annotation[i];
944 System.arraycopy(ann, 0, annotations, 0, i);
950 * Associate this annotion with the aligned residues of a particular sequence.
951 * sequenceMapping will be updated in the following way: null sequenceI -
952 * existing mapping will be discarded but annotations left in mapped
953 * positions. valid sequenceI not equal to current sequenceRef: mapping is
954 * discarded and rebuilt assuming 1:1 correspondence TODO: overload with
955 * parameter to specify correspondence between current and new sequenceRef
959 public void setSequenceRef(SequenceI sequenceI)
961 if (sequenceI != null)
963 if (sequenceRef != null)
965 boolean rIsDs=sequenceRef.getDatasetSequence()==null,tIsDs=sequenceI.getDatasetSequence()==null;
966 if (sequenceRef != sequenceI
967 && (rIsDs && !tIsDs && sequenceRef != sequenceI
968 .getDatasetSequence())
969 && (!rIsDs && tIsDs && sequenceRef.getDatasetSequence() != sequenceI)
970 && (!rIsDs && !tIsDs && sequenceRef.getDatasetSequence() != sequenceI
971 .getDatasetSequence())
972 && !sequenceRef.equals(sequenceI))
974 // if sequenceRef isn't intersecting with sequenceI
975 // throw away old mapping and reconstruct.
977 if (sequenceMapping != null)
979 sequenceMapping = null;
980 // compactAnnotationArray();
982 createSequenceMapping(sequenceI, 1, true);
983 adjustForAlignment();
987 // Mapping carried over
988 sequenceRef = sequenceI;
994 createSequenceMapping(sequenceI, 1, true);
995 adjustForAlignment();
1000 // throw away the mapping without compacting.
1001 sequenceMapping = null;
1009 public double getScore()
1018 public void setScore(double score)
1026 * @return true if annotation has an associated score
1028 public boolean hasScore()
1030 return hasScore || !Double.isNaN(score);
1034 * Score only annotation
1037 * @param description
1040 public AlignmentAnnotation(String label, String description, double score)
1042 this(label, description, null);
1047 * copy constructor with edit based on the hidden columns marked in colSel
1049 * @param alignmentAnnotation
1052 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1053 ColumnSelection colSel)
1055 this(alignmentAnnotation);
1056 if (annotations == null)
1060 colSel.makeVisibleAnnotation(this);
1063 public void setPadGaps(boolean padgaps, char gapchar)
1065 this.padGaps = padgaps;
1069 for (int i = 0; i < annotations.length; i++)
1071 if (annotations[i] == null)
1073 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1076 else if (annotations[i].displayCharacter == null
1077 || annotations[i].displayCharacter.equals(" "))
1079 annotations[i].displayCharacter = String.valueOf(gapchar);
1086 * format description string for display
1089 * @return Get the annotation description string optionally prefixed by
1090 * associated sequence name (if any)
1092 public String getDescription(boolean seqname)
1094 if (seqname && this.sequenceRef != null)
1096 int i = description.toLowerCase().indexOf("<html>");
1099 // move the html tag to before the sequence reference.
1100 return "<html>" + sequenceRef.getName() + " : "
1101 + description.substring(i + 6);
1103 return sequenceRef.getName() + " : " + description;
1108 public boolean isValidStruc()
1110 return invalidrnastruc == -1;
1113 public long getInvalidStrucPos()
1115 return invalidrnastruc;
1119 * machine readable ID string indicating what generated this annotation
1121 protected String calcId = "";
1124 * properties associated with the calcId
1126 protected Map<String, String> properties = new HashMap<String, String>();
1129 * base colour for line graphs. If null, will be set automatically by
1130 * searching the alignment annotation
1132 public java.awt.Color _linecolour;
1134 public String getCalcId()
1139 public void setCalcId(String calcId)
1141 this.calcId = calcId;
1144 public boolean isRNA()
1150 * transfer annotation to the given sequence using the given mapping from the
1151 * current positions or an existing sequence mapping
1155 * map involving sq as To or From
1157 public void liftOver(SequenceI sq, Mapping sp2sq)
1159 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1161 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and Protein reference frames
1162 throw new Error("liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1164 boolean mapIsTo = (sp2sq != null) ? (sp2sq.getTo() == sq || sp2sq
1165 .getTo() == sq.getDatasetSequence()) : false;
1167 // TODO build a better annotation element map and get rid of annotations[]
1168 Hashtable<Integer, Annotation> mapForsq = new Hashtable();
1169 if (sequenceMapping != null)
1173 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1175 Integer mpos = Integer.valueOf(mapIsTo ? sp2sq
1176 .getMappedPosition(ie.getKey()) : sp2sq.getPosition(ie
1178 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1180 mapForsq.put(mpos, ie.getValue());
1183 sequenceMapping = mapForsq;
1185 adjustForAlignment();
1195 * like liftOver but more general.
1197 * Takes an array of int pairs that will be used to update the internal
1198 * sequenceMapping and so shuffle the annotated positions
1201 * - new sequence reference for the annotation row - if null,
1202 * sequenceRef is left unchanged
1204 * array of ints containing corresponding positions
1206 * - column for current coordinate system (-1 for index+1)
1208 * - column for destination coordinate system (-1 for index+1)
1210 * - offset added to index when referencing either coordinate system
1211 * @note no checks are made as to whether from and/or to are sensible
1212 * @note caller should add the remapped annotation to newref if they have not
1215 public void remap(SequenceI newref, int[][] mapping, int from, int to,
1218 if (mapping != null)
1220 Hashtable<Integer, Annotation> old = sequenceMapping, remap = new Hashtable<Integer, Annotation>();
1222 for (int mp[] : mapping)
1228 Annotation ann = null;
1231 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1235 if (mp != null && mp.length > from)
1237 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1244 remap.put(Integer.valueOf(idxoffset + index), ann);
1248 if (to > -1 && to < mp.length)
1250 remap.put(Integer.valueOf(mp[to]), ann);
1255 sequenceMapping = remap;
1259 sequenceRef = newref;
1261 adjustForAlignment();
1265 public Object getProperty(String property)
1267 if (properties == null)
1271 return properties.get(property);
1274 public void setProperty(String property, String value)
1276 if (properties==null)
1278 properties = new HashMap<String,String>();
1280 properties.put(property, value);