2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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;
26 import jalview.util.MapList;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
44 public class AlignmentAnnotation
46 private static final String ANNOTATION_ID_PREFIX = "ann";
49 * Identifers for different types of profile data
51 public static final int SEQUENCE_PROFILE = 0;
53 public static final int STRUCTURE_PROFILE = 1;
55 public static final int CDNA_PROFILE = 2;
57 private static long counter = 0;
60 * If true, this annotations is calculated every edit, eg consensus, quality
61 * or conservation graphs
63 public boolean autoCalculated = false;
66 * unique ID for this annotation, used to match up the same annotation row
67 * shown in multiple views and alignments
69 public String annotationId;
72 * the sequence this annotation is associated with (or null)
74 public SequenceI sequenceRef;
76 /** label shown in dropdown menus and in the annotation label area */
79 /** longer description text shown as a tooltip */
80 public String description;
82 /** Array of annotations placed in the current coordinate system */
83 public Annotation[] annotations;
85 public List<SimpleBP> bps = null;
88 * RNA secondary structure contact positions
90 public SequenceFeature[] _rnasecstr = null;
93 * position of annotation resulting in invalid WUSS parsing or -1. -2 means
94 * there was no RNA structure in this annotation
96 private long invalidrnastruc = -2;
99 * Updates the _rnasecstr field Determines the positions that base pair and
100 * the positions of helices based on secondary structure from a Stockholm file
102 * @param rnaAnnotation
104 private void _updateRnaSecStr(CharSequence rnaAnnotation)
108 _rnasecstr = Rna.getHelixMap(rnaAnnotation);
109 invalidrnastruc = -1;
110 } catch (WUSSParseException px)
112 // DEBUG System.out.println(px);
113 invalidrnastruc = px.getProblemPos();
115 if (invalidrnastruc > -1)
120 if (_rnasecstr != null && _rnasecstr.length > 0)
122 // show all the RNA secondary structure annotation symbols.
124 showAllColLabels = true;
125 scaleColLabel = true;
128 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
132 private void _markRnaHelices()
135 // Figure out number of helices
136 // Length of rnasecstr is the number of pairs of positions that base pair
137 // with each other in the secondary structure
138 for (int x = 0; x < _rnasecstr.length; x++)
142 * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
143 * this.annotation._rnasecstr[x].getBegin());
145 // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
149 val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
154 } catch (NumberFormatException q)
159 annotations[_rnasecstr[x].getBegin()].value = val;
160 annotations[_rnasecstr[x].getEnd()].value = val;
162 // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
163 // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
169 * Get the RNA Secondary Structure SequenceFeature Array if present
171 public SequenceFeature[] getRnaSecondaryStructure()
173 return this._rnasecstr;
177 * Check the RNA Secondary Structure is equivalent to one in given
178 * AlignmentAnnotation param
180 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that)
182 return rnaSecondaryStructureEquivalent(that, true);
185 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that, boolean compareType)
187 SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
188 SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
189 if (thisSfArray == null || thatSfArray == null)
191 return thisSfArray == null && thatSfArray == null;
193 if (thisSfArray.length != thatSfArray.length)
197 Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
199 Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
201 for (int i=0; i < thisSfArray.length; i++) {
202 SequenceFeature thisSf = thisSfArray[i];
203 SequenceFeature thatSf = thatSfArray[i];
205 if (thisSf.getType() == null || thatSf.getType() == null) {
206 if (thisSf.getType() == null && thatSf.getType() == null) {
212 if (! thisSf.getType().equals(thatSf.getType())) {
216 if (!(thisSf.getBegin() == thatSf.getBegin()
217 && thisSf.getEnd() == thatSf.getEnd()))
227 * map of positions in the associated annotation
229 private Map<Integer, Annotation> sequenceMapping;
232 * lower range for quantitative data
234 public float graphMin;
237 * Upper range for quantitative data
239 public float graphMax;
242 * Score associated with label and description.
244 public double score = Double.NaN;
247 * flag indicating if annotation has a score.
249 public boolean hasScore = false;
251 public GraphLine threshold;
253 // Graphical hints and tips
255 /** Can this row be edited by the user ? */
256 public boolean editable = false;
258 /** Indicates if annotation has a graphical symbol track */
259 public boolean hasIcons; //
261 /** Indicates if annotation has a text character label */
262 public boolean hasText;
264 /** is the row visible */
265 public boolean visible = true;
267 public int graphGroup = -1;
269 /** Displayed height of row in pixels */
270 public int height = 0;
272 public int graph = 0;
274 public int graphHeight = 40;
276 public boolean padGaps = false;
278 public static final int NO_GRAPH = 0;
280 public static final int BAR_GRAPH = 1;
282 public static final int LINE_GRAPH = 2;
284 public boolean belowAlignment = true;
286 public SequenceGroup groupRef = null;
289 * display every column label, even if there is a row of identical labels
291 public boolean showAllColLabels = false;
294 * scale the column label to fit within the alignment column.
296 public boolean scaleColLabel = false;
299 * centre the column labels relative to the alignment column
301 public boolean centreColLabels = false;
303 private boolean isrna;
305 public static int getGraphValueFromString(String string)
307 if (string.equalsIgnoreCase("BAR_GRAPH"))
311 else if (string.equalsIgnoreCase("LINE_GRAPH"))
322 * Creates a new AlignmentAnnotation object.
325 * short label shown under sequence labels
327 * text displayed on mouseover
329 * set of positional annotation elements
331 public AlignmentAnnotation(String label, String description,
332 Annotation[] annotations)
338 this.description = description;
339 this.annotations = annotations;
341 validateRangeAndDisplay();
345 * Checks if annotation labels represent secondary structures
348 void areLabelsSecondaryStructure()
350 boolean nonSSLabel = false;
352 StringBuffer rnastring = new StringBuffer();
355 for (int i = 0; i < annotations.length; i++)
357 // DEBUG System.out.println(i + ": " + annotations[i]);
358 if (annotations[i] == null)
362 if (annotations[i].secondaryStructure == 'H'
363 || annotations[i].secondaryStructure == 'E')
365 // DEBUG System.out.println( "/H|E/ '" +
366 // annotations[i].secondaryStructure + "'");
370 // Check for RNA secondary structure
372 // DEBUG System.out.println( "/else/ '" +
373 // annotations[i].secondaryStructure + "'");
374 // TODO: 2.8.2 should this ss symbol validation check be a function in
375 // RNA/ResidueProperties ?
376 if (annotations[i].secondaryStructure == '('
377 || annotations[i].secondaryStructure == '['
378 || annotations[i].secondaryStructure == '<'
379 || annotations[i].secondaryStructure == '{'
380 || annotations[i].secondaryStructure == 'A'
381 || annotations[i].secondaryStructure == 'B'
382 || annotations[i].secondaryStructure == 'C'
383 || annotations[i].secondaryStructure == 'D'
384 // || annotations[i].secondaryStructure == 'E' // ambiguous on
385 // its own -- already checked above
386 || annotations[i].secondaryStructure == 'F'
387 || annotations[i].secondaryStructure == 'G'
388 // || annotations[i].secondaryStructure == 'H' // ambiguous on
389 // its own -- already checked above
390 || annotations[i].secondaryStructure == 'I'
391 || annotations[i].secondaryStructure == 'J'
392 || annotations[i].secondaryStructure == 'K'
393 || annotations[i].secondaryStructure == 'L'
394 || annotations[i].secondaryStructure == 'M'
395 || annotations[i].secondaryStructure == 'N'
396 || annotations[i].secondaryStructure == 'O'
397 || annotations[i].secondaryStructure == 'P'
398 || annotations[i].secondaryStructure == 'Q'
399 || annotations[i].secondaryStructure == 'R'
400 || annotations[i].secondaryStructure == 'S'
401 || annotations[i].secondaryStructure == 'T'
402 || annotations[i].secondaryStructure == 'U'
403 || annotations[i].secondaryStructure == 'V'
404 || annotations[i].secondaryStructure == 'W'
405 || annotations[i].secondaryStructure == 'X'
406 || annotations[i].secondaryStructure == 'Y'
407 || annotations[i].secondaryStructure == 'Z')
414 // System.out.println("displaychar " + annotations[i].displayCharacter);
416 if (annotations[i].displayCharacter == null
417 || annotations[i].displayCharacter.length() == 0)
419 rnastring.append('.');
422 if (annotations[i].displayCharacter.length() == 1)
424 firstChar = annotations[i].displayCharacter.charAt(0);
425 // check to see if it looks like a sequence or is secondary structure
427 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
428 // Uncomment to only catch case where
429 // displayCharacter==secondary
431 // to correctly redisplay SS annotation imported from Stockholm,
432 // exported to JalviewXML and read back in again.
434 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
435 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
436 && firstChar != '(' && firstChar != '[' && firstChar != '<'
437 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
438 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
439 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
440 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
441 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
442 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
443 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
444 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
445 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
447 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
449 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
462 rnastring.append(annotations[i].displayCharacter.charAt(1));
465 if (annotations[i].displayCharacter.length() > 0)
474 for (int j = 0; j < annotations.length; j++)
476 if (annotations[j] != null
477 && annotations[j].secondaryStructure != ' ')
479 annotations[j].displayCharacter = String
480 .valueOf(annotations[j].secondaryStructure);
481 annotations[j].secondaryStructure = ' ';
490 _updateRnaSecStr(new AnnotCharSequence());
496 * flyweight access to positions in the alignment annotation row for RNA
502 private class AnnotCharSequence implements CharSequence
508 public AnnotCharSequence()
510 this(0, annotations.length);
513 AnnotCharSequence(int start, int end)
520 public CharSequence subSequence(int start, int end)
522 return new AnnotCharSequence(offset + start, offset + end);
532 public char charAt(int index)
534 return ((index + offset < 0) || (index + offset) >= max
535 || annotations[index + offset] == null
536 || (annotations[index + offset].secondaryStructure <= ' ')
538 : annotations[index + offset].displayCharacter == null
540 + offset].displayCharacter
543 + offset].secondaryStructure
545 + offset].displayCharacter
550 public String toString()
552 char[] string = new char[max - offset];
553 int mx = annotations.length;
555 for (int i = offset; i < mx; i++)
557 string[i] = (annotations[i] == null
558 || (annotations[i].secondaryStructure <= 32))
560 : (annotations[i].displayCharacter == null
561 || annotations[i].displayCharacter
563 ? annotations[i].secondaryStructure
564 : annotations[i].displayCharacter
567 return new String(string);
571 private long _lastrnaannot = -1;
573 public String getRNAStruc()
577 String rnastruc = new AnnotCharSequence().toString();
578 if (_lastrnaannot != rnastruc.hashCode())
580 // ensure rna structure contacts are up to date
581 _lastrnaannot = rnastruc.hashCode();
582 _updateRnaSecStr(rnastruc);
590 * Creates a new AlignmentAnnotation object.
605 public AlignmentAnnotation(String label, String description,
606 Annotation[] annotations, float min, float max, int graphType)
609 // graphs are not editable
610 editable = graphType == 0;
613 this.description = description;
614 this.annotations = annotations;
618 validateRangeAndDisplay();
622 * checks graphMin and graphMax, secondary structure symbols, sets graphType
623 * appropriately, sets null labels to the empty string if appropriate.
625 public void validateRangeAndDisplay()
628 if (annotations == null)
630 visible = false; // try to prevent renderer from displaying.
631 invalidrnastruc = -1;
632 return; // this is a non-annotation row annotation - ie a sequence score.
635 int graphType = graph;
636 float min = graphMin;
637 float max = graphMax;
638 boolean drawValues = true;
643 for (int i = 0; i < annotations.length; i++)
645 if (annotations[i] == null)
650 if (drawValues && annotations[i].displayCharacter != null
651 && annotations[i].displayCharacter.length() > 1)
656 if (annotations[i].value > max)
658 max = annotations[i].value;
661 if (annotations[i].value < min)
663 min = annotations[i].value;
665 if (_linecolour == null && annotations[i].colour != null)
667 _linecolour = annotations[i].colour;
670 // ensure zero is origin for min/max ranges on only one side of zero
687 areLabelsSecondaryStructure();
689 if (!drawValues && graphType != NO_GRAPH)
691 for (int i = 0; i < annotations.length; i++)
693 if (annotations[i] != null)
695 annotations[i].displayCharacter = "";
702 * Copy constructor creates a new independent annotation row with the same
703 * associated sequenceRef
707 public AlignmentAnnotation(AlignmentAnnotation annotation)
710 this.label = new String(annotation.label);
711 if (annotation.description != null)
713 this.description = new String(annotation.description);
715 this.graphMin = annotation.graphMin;
716 this.graphMax = annotation.graphMax;
717 this.graph = annotation.graph;
718 this.graphHeight = annotation.graphHeight;
719 this.graphGroup = annotation.graphGroup;
720 this.groupRef = annotation.groupRef;
721 this.editable = annotation.editable;
722 this.autoCalculated = annotation.autoCalculated;
723 this.hasIcons = annotation.hasIcons;
724 this.hasText = annotation.hasText;
725 this.height = annotation.height;
726 this.label = annotation.label;
727 this.padGaps = annotation.padGaps;
728 this.visible = annotation.visible;
729 this.centreColLabels = annotation.centreColLabels;
730 this.scaleColLabel = annotation.scaleColLabel;
731 this.showAllColLabels = annotation.showAllColLabels;
732 this.calcId = annotation.calcId;
733 if (annotation.properties != null)
735 properties = new HashMap<>();
736 for (Map.Entry<String, String> val : annotation.properties.entrySet())
738 properties.put(val.getKey(), val.getValue());
741 if (this.hasScore = annotation.hasScore)
743 this.score = annotation.score;
745 if (annotation.threshold != null)
747 threshold = new GraphLine(annotation.threshold);
749 Annotation[] ann = annotation.annotations;
750 if (annotation.annotations != null)
752 this.annotations = new Annotation[ann.length];
753 for (int i = 0; i < ann.length; i++)
757 annotations[i] = new Annotation(ann[i]);
758 if (_linecolour != null)
760 _linecolour = annotations[i].colour;
765 if (annotation.sequenceRef != null)
767 this.sequenceRef = annotation.sequenceRef;
768 if (annotation.sequenceMapping != null)
771 sequenceMapping = new HashMap<>();
772 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
774 while (pos.hasNext())
776 // could optimise this!
778 Annotation a = annotation.sequenceMapping.get(p);
785 for (int i = 0; i < ann.length; i++)
789 sequenceMapping.put(p, annotations[i]);
797 this.sequenceMapping = null;
800 // TODO: check if we need to do this: JAL-952
801 // if (this.isrna=annotation.isrna)
803 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
805 validateRangeAndDisplay(); // construct hashcodes, etc.
809 * clip the annotation to the columns given by startRes and endRes (inclusive)
810 * and prune any existing sequenceMapping to just those columns.
815 public void restrict(int startRes, int endRes)
817 if (annotations == null)
826 if (startRes >= annotations.length)
828 startRes = annotations.length - 1;
830 if (endRes >= annotations.length)
832 endRes = annotations.length - 1;
834 if (annotations == null)
838 Annotation[] temp = new Annotation[endRes - startRes + 1];
839 if (startRes < annotations.length)
841 System.arraycopy(annotations, startRes, temp, 0,
842 endRes - startRes + 1);
844 if (sequenceRef != null)
846 // Clip the mapping, if it exists.
847 int spos = sequenceRef.findPosition(startRes);
848 int epos = sequenceRef.findPosition(endRes);
849 if (sequenceMapping != null)
851 Map<Integer, Annotation> newmapping = new HashMap<>();
852 Iterator<Integer> e = sequenceMapping.keySet().iterator();
855 Integer pos = e.next();
856 if (pos.intValue() >= spos && pos.intValue() <= epos)
858 newmapping.put(pos, sequenceMapping.get(pos));
861 sequenceMapping.clear();
862 sequenceMapping = newmapping;
869 * set the annotation row to be at least length Annotations
872 * minimum number of columns required in the annotation row
873 * @return false if the annotation row is greater than length
875 public boolean padAnnotation(int length)
877 if (annotations == null)
879 return true; // annotation row is correct - null == not visible and
882 if (annotations.length < length)
884 Annotation[] na = new Annotation[length];
885 System.arraycopy(annotations, 0, na, 0, annotations.length);
889 return annotations.length > length;
896 * @return DOCUMENT ME!
899 public String toString()
901 if (annotations == null)
905 StringBuilder buffer = new StringBuilder(256);
907 for (int i = 0; i < annotations.length; i++)
909 if (annotations[i] != null)
913 buffer.append(annotations[i].value);
917 buffer.append(annotations[i].secondaryStructure);
921 buffer.append(annotations[i].displayCharacter);
927 // TODO: remove disgusting hack for 'special' treatment of consensus line.
928 if (label.indexOf("Consensus") == 0)
932 for (int i = 0; i < annotations.length; i++)
934 if (annotations[i] != null)
936 buffer.append(annotations[i].description);
943 return buffer.toString();
946 public void setThreshold(GraphLine line)
951 public GraphLine getThreshold()
957 * Attach the annotation to seqRef, starting from startRes position. If
958 * alreadyMapped is true then the indices of the annotation[] array are
959 * sequence positions rather than alignment column positions.
963 * @param alreadyMapped
965 public void createSequenceMapping(SequenceI seqRef, int startRes,
966 boolean alreadyMapped)
973 sequenceRef = seqRef;
974 if (annotations == null)
978 sequenceMapping = new HashMap<>();
982 for (int i = 0; i < annotations.length; i++)
984 if (annotations[i] != null)
988 seqPos = seqRef.findPosition(i);
992 seqPos = i + startRes;
995 sequenceMapping.put(new Integer(seqPos), annotations[i]);
1002 * When positional annotation and a sequence reference is present, clears and
1003 * resizes the annotations array to the current alignment width, and adds
1004 * annotation according to aligned positions of the sequenceRef given by
1007 public void adjustForAlignment()
1009 if (sequenceRef == null)
1014 if (annotations == null)
1019 int a = 0, aSize = sequenceRef.getLength();
1028 Annotation[] temp = new Annotation[aSize];
1030 if (sequenceMapping != null)
1032 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1034 index = new Integer(a);
1035 Annotation annot = sequenceMapping.get(index);
1038 position = sequenceRef.findIndex(a) - 1;
1040 temp[position] = annot;
1048 * remove any null entries in annotation row and return the number of non-null
1049 * annotation elements.
1053 public int compactAnnotationArray()
1055 int i = 0, iSize = annotations.length;
1058 if (annotations[i] == null)
1062 System.arraycopy(annotations, i + 1, annotations, i,
1072 Annotation[] ann = annotations;
1073 annotations = new Annotation[i];
1074 System.arraycopy(ann, 0, annotations, 0, i);
1080 * Associate this annotation with the aligned residues of a particular
1081 * sequence. sequenceMapping will be updated in the following way: null
1082 * sequenceI - existing mapping will be discarded but annotations left in
1083 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1084 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1085 * parameter to specify correspondence between current and new sequenceRef
1089 public void setSequenceRef(SequenceI sequenceI)
1091 if (sequenceI != null)
1093 if (sequenceRef != null)
1095 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1096 tIsDs = sequenceI.getDatasetSequence() == null;
1097 if (sequenceRef != sequenceI
1099 && sequenceRef != sequenceI.getDatasetSequence())
1101 && sequenceRef.getDatasetSequence() != sequenceI)
1102 && (!rIsDs && !tIsDs
1103 && sequenceRef.getDatasetSequence() != sequenceI
1104 .getDatasetSequence())
1105 && !sequenceRef.equals(sequenceI))
1107 // if sequenceRef isn't intersecting with sequenceI
1108 // throw away old mapping and reconstruct.
1110 if (sequenceMapping != null)
1112 sequenceMapping = null;
1113 // compactAnnotationArray();
1115 createSequenceMapping(sequenceI, 1, true);
1116 adjustForAlignment();
1120 // Mapping carried over
1121 sequenceRef = sequenceI;
1126 // No mapping exists
1127 createSequenceMapping(sequenceI, 1, true);
1128 adjustForAlignment();
1133 // throw away the mapping without compacting.
1134 sequenceMapping = null;
1142 public double getScore()
1151 public void setScore(double score)
1159 * @return true if annotation has an associated score
1161 public boolean hasScore()
1163 return hasScore || !Double.isNaN(score);
1167 * Score only annotation
1170 * @param description
1173 public AlignmentAnnotation(String label, String description, double score)
1175 this(label, description, null);
1180 * copy constructor with edit based on the hidden columns marked in colSel
1182 * @param alignmentAnnotation
1185 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1186 HiddenColumns hidden)
1188 this(alignmentAnnotation);
1189 if (annotations == null)
1193 makeVisibleAnnotation(hidden);
1196 public void setPadGaps(boolean padgaps, char gapchar)
1198 this.padGaps = padgaps;
1202 for (int i = 0; i < annotations.length; i++)
1204 if (annotations[i] == null)
1206 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1209 else if (annotations[i].displayCharacter == null
1210 || annotations[i].displayCharacter.equals(" "))
1212 annotations[i].displayCharacter = String.valueOf(gapchar);
1219 * format description string for display
1222 * @return Get the annotation description string optionally prefixed by
1223 * associated sequence name (if any)
1225 public String getDescription(boolean seqname)
1227 if (seqname && this.sequenceRef != null)
1229 int i = description.toLowerCase().indexOf("<html>");
1232 // move the html tag to before the sequence reference.
1233 return "<html>" + sequenceRef.getName() + " : "
1234 + description.substring(i + 6);
1236 return sequenceRef.getName() + " : " + description;
1241 public boolean isValidStruc()
1243 return invalidrnastruc == -1;
1246 public long getInvalidStrucPos()
1248 return invalidrnastruc;
1252 * machine readable ID string indicating what generated this annotation
1254 protected String calcId = "";
1257 * properties associated with the calcId
1259 protected Map<String, String> properties = new HashMap<>();
1262 * base colour for line graphs. If null, will be set automatically by
1263 * searching the alignment annotation
1265 public java.awt.Color _linecolour;
1267 public String getCalcId()
1272 public void setCalcId(String calcId)
1274 this.calcId = calcId;
1277 public boolean isRNA()
1283 * transfer annotation to the given sequence using the given mapping from the
1284 * current positions or an existing sequence mapping
1288 * map involving sq as To or From
1290 public void liftOver(SequenceI sq, Mapping sp2sq)
1292 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1294 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1295 // Protein reference frames
1297 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1299 boolean mapIsTo = (sp2sq != null)
1300 ? (sp2sq.getTo() == sq
1301 || sp2sq.getTo() == sq.getDatasetSequence())
1304 // TODO build a better annotation element map and get rid of annotations[]
1305 Map<Integer, Annotation> mapForsq = new HashMap<>();
1306 if (sequenceMapping != null)
1310 int[] reg = new int[MapList.LEN];
1311 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1313 reg[MapList.POS] = ie.getKey();
1314 int mpos = sp2sq.getPosition(reg, mapIsTo);
1315 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1317 mapForsq.put(mpos, ie.getValue());
1320 sequenceMapping = mapForsq;
1322 adjustForAlignment();
1332 * like liftOver but more general.
1334 * Takes an array of int pairs that will be used to update the internal
1335 * sequenceMapping and so shuffle the annotated positions
1338 * - new sequence reference for the annotation row - if null,
1339 * sequenceRef is left unchanged
1341 * array of ints containing corresponding positions
1343 * - column for current coordinate system (-1 for index+1)
1345 * - column for destination coordinate system (-1 for index+1)
1347 * - offset added to index when referencing either coordinate system
1348 * @note no checks are made as to whether from and/or to are sensible
1349 * @note caller should add the remapped annotation to newref if they have not
1352 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1353 int from, int to, int idxoffset)
1355 if (mapping != null)
1357 Map<Integer, Annotation> old = sequenceMapping;
1358 Map<Integer, Annotation> remap = new HashMap<>();
1360 for (int mp[] : mapping.values())
1366 Annotation ann = null;
1369 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1373 if (mp != null && mp.length > from)
1375 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1382 remap.put(Integer.valueOf(idxoffset + index), ann);
1386 if (to > -1 && to < mp.length)
1388 remap.put(Integer.valueOf(mp[to]), ann);
1393 sequenceMapping = remap;
1397 sequenceRef = newref;
1399 adjustForAlignment();
1403 public String getProperty(String property)
1405 if (properties == null)
1409 return properties.get(property);
1412 public void setProperty(String property, String value)
1414 if (properties == null)
1416 properties = new HashMap<>();
1418 properties.put(property, value);
1421 public boolean hasProperties()
1423 return properties != null && properties.size() > 0;
1426 public Collection<String> getProperties()
1428 if (properties == null)
1430 return Collections.emptyList();
1432 return properties.keySet();
1436 * Returns the Annotation for the given sequence position (base 1) if any,
1442 public Annotation getAnnotationForPosition(int position)
1444 return sequenceMapping == null ? null : sequenceMapping.get(position);
1449 * Set the id to "ann" followed by a counter that increments so as to be
1450 * unique for the lifetime of the JVM
1452 protected final void setAnnotationId()
1454 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1458 * Returns the match for the last unmatched opening RNA helix pair symbol
1459 * preceding the given column, or '(' if nothing found to match.
1464 public String getDefaultRnaHelixSymbol(int column)
1466 String result = "(";
1467 if (annotations == null)
1473 * for each preceding column, if it contains an open bracket,
1474 * count whether it is still unmatched at column, if so return its pair
1475 * (likely faster than the fancy alternative using stacks)
1477 for (int col = column - 1; col >= 0; col--)
1479 Annotation annotation = annotations[col];
1480 if (annotation == null)
1484 String displayed = annotation.displayCharacter;
1485 if (displayed == null || displayed.length() != 1)
1489 char symbol = displayed.charAt(0);
1490 if (!Rna.isOpeningParenthesis(symbol))
1496 * found an opening bracket symbol
1497 * count (closing-opening) symbols of this type that follow it,
1498 * up to and excluding the target column; if the count is less
1499 * than 1, the opening bracket is unmatched, so return its match
1501 String closer = String
1502 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1503 String opener = String.valueOf(symbol);
1505 for (int j = col + 1; j < column; j++)
1507 if (annotations[j] != null)
1509 String s = annotations[j].displayCharacter;
1510 if (closer.equals(s))
1514 else if (opener.equals(s))
1528 protected static synchronized long nextId()
1535 * @return true for rows that have a range of values in their annotation set
1537 public boolean isQuantitative()
1539 return graphMin < graphMax;
1543 * delete any columns in alignmentAnnotation that are hidden (including
1544 * sequence associated annotation).
1546 * @param hiddenColumns
1547 * the set of hidden columns
1549 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1551 if (annotations != null)
1553 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1558 * delete any columns in alignmentAnnotation that are hidden (including
1559 * sequence associated annotation).
1562 * remove any annotation to the right of this column
1564 * remove any annotation to the left of this column
1565 * @param hiddenColumns
1566 * the set of hidden columns
1568 public void makeVisibleAnnotation(int start, int end,
1569 HiddenColumns hiddenColumns)
1571 if (annotations != null)
1573 if (hiddenColumns.hasHiddenColumns())
1575 removeHiddenAnnotation(start, end, hiddenColumns);
1579 restrict(start, end);
1585 * The actual implementation of deleting hidden annotation columns
1588 * remove any annotation to the right of this column
1590 * remove any annotation to the left of this column
1591 * @param hiddenColumns
1592 * the set of hidden columns
1594 private void removeHiddenAnnotation(int start, int end,
1595 HiddenColumns hiddenColumns)
1597 // mangle the alignmentAnnotation annotation array
1598 ArrayList<Annotation[]> annels = new ArrayList<>();
1599 Annotation[] els = null;
1603 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1607 int annotationLength;
1608 while (blocks.hasNext())
1610 int[] block = blocks.next();
1611 annotationLength = block[1] - block[0] + 1;
1613 if (blocks.hasNext())
1615 // copy just the visible segment of the annotation row
1616 copylength = annotationLength;
1620 if (annotationLength + block[0] <= annotations.length)
1622 // copy just the visible segment of the annotation row
1623 copylength = annotationLength;
1627 // copy to the end of the annotation row
1628 copylength = annotations.length - block[0];
1632 els = new Annotation[annotationLength];
1634 System.arraycopy(annotations, block[0], els, 0, copylength);
1635 w += annotationLength;
1640 annotations = new Annotation[w];
1643 for (Annotation[] chnk : annels)
1645 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1651 public static Iterable<AlignmentAnnotation> findAnnotations(
1652 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1656 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1657 for (AlignmentAnnotation ann : list)
1659 if ((calcId == null || (ann.getCalcId() != null
1660 && ann.getCalcId().equals(calcId)))
1661 && (seq == null || (ann.sequenceRef != null
1662 && ann.sequenceRef == seq))
1664 || (ann.label != null && ann.label.equals(label))))
1673 * Answer true if any annotation matches the calcId passed in (if not null).
1676 * annotation to search
1680 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1684 if (calcId != null && !"".equals(calcId))
1686 for (AlignmentAnnotation a : list)
1688 if (a.getCalcId() == calcId)
1697 public static Iterable<AlignmentAnnotation> findAnnotation(
1698 List<AlignmentAnnotation> list, String calcId)
1701 List<AlignmentAnnotation> aa = new ArrayList<>();
1706 for (AlignmentAnnotation a : list)
1709 if (a.getCalcId() == calcId || (a.getCalcId() != null
1710 && calcId != null && a.getCalcId().equals(calcId)))