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 java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Locale;
32 import java.util.Map.Entry;
34 import jalview.analysis.Rna;
35 import jalview.analysis.SecStrConsensus.SimpleBP;
36 import jalview.analysis.WUSSParseException;
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,
188 SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
189 SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
190 if (thisSfArray == null || thatSfArray == null)
192 return thisSfArray == null && thatSfArray == null;
194 if (thisSfArray.length != thatSfArray.length)
198 Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
200 Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
202 for (int i = 0; i < thisSfArray.length; i++)
204 SequenceFeature thisSf = thisSfArray[i];
205 SequenceFeature thatSf = thatSfArray[i];
208 if (thisSf.getType() == null || thatSf.getType() == null)
210 if (thisSf.getType() == null && thatSf.getType() == null)
219 if (!thisSf.getType().equals(thatSf.getType()))
224 if (!(thisSf.getBegin() == thatSf.getBegin()
225 && thisSf.getEnd() == thatSf.getEnd()))
235 * map of positions in the associated annotation
237 private Map<Integer, Annotation> sequenceMapping;
240 * lower range for quantitative data
242 public float graphMin;
245 * Upper range for quantitative data
247 public float graphMax;
250 * Score associated with label and description.
252 public double score = Double.NaN;
255 * flag indicating if annotation has a score.
257 public boolean hasScore = false;
259 public GraphLine threshold;
261 // Graphical hints and tips
263 /** Can this row be edited by the user ? */
264 public boolean editable = false;
266 /** Indicates if annotation has a graphical symbol track */
267 public boolean hasIcons; //
269 /** Indicates if annotation has a text character label */
270 public boolean hasText;
272 /** is the row visible */
273 public boolean visible = true;
275 public int graphGroup = -1;
277 /** Displayed height of row in pixels */
278 public int height = 0;
280 public int graph = 0;
282 public int graphHeight = 40;
284 public boolean padGaps = false;
286 public static final int NO_GRAPH = 0;
288 public static final int BAR_GRAPH = 1;
290 public static final int LINE_GRAPH = 2;
292 public boolean belowAlignment = true;
294 public SequenceGroup groupRef = null;
297 * display every column label, even if there is a row of identical labels
299 public boolean showAllColLabels = false;
302 * scale the column label to fit within the alignment column.
304 public boolean scaleColLabel = false;
307 * centre the column labels relative to the alignment column
309 public boolean centreColLabels = false;
311 private boolean isrna;
313 public static int getGraphValueFromString(String string)
315 if (string.equalsIgnoreCase("BAR_GRAPH"))
319 else if (string.equalsIgnoreCase("LINE_GRAPH"))
330 * Creates a new AlignmentAnnotation object.
333 * short label shown under sequence labels
335 * text displayed on mouseover
337 * set of positional annotation elements
339 public AlignmentAnnotation(String label, String description,
340 Annotation[] annotations)
346 this.description = description;
347 this.annotations = annotations;
349 validateRangeAndDisplay();
353 * Checks if annotation labels represent secondary structures
356 void areLabelsSecondaryStructure()
358 boolean nonSSLabel = false;
360 StringBuffer rnastring = new StringBuffer();
363 for (int i = 0; i < annotations.length; i++)
365 // DEBUG System.out.println(i + ": " + annotations[i]);
366 if (annotations[i] == null)
370 if (annotations[i].secondaryStructure == 'H'
371 || annotations[i].secondaryStructure == 'E')
373 // DEBUG System.out.println( "/H|E/ '" +
374 // annotations[i].secondaryStructure + "'");
378 // Check for RNA secondary structure
380 // DEBUG System.out.println( "/else/ '" +
381 // annotations[i].secondaryStructure + "'");
382 // TODO: 2.8.2 should this ss symbol validation check be a function in
383 // RNA/ResidueProperties ?
384 // allow for DSSP extended code:
385 // https://www.wikidoc.org/index.php/Secondary_structure#The_DSSP_code
386 // GHITEBS as well as C and X (for missing?)
387 if (annotations[i].secondaryStructure == '('
388 || annotations[i].secondaryStructure == '['
389 || annotations[i].secondaryStructure == '<'
390 || annotations[i].secondaryStructure == '{'
391 || annotations[i].secondaryStructure == 'A'
392 // || annotations[i].secondaryStructure == 'B'
393 // || annotations[i].secondaryStructure == 'C'
394 || annotations[i].secondaryStructure == 'D'
395 // || annotations[i].secondaryStructure == 'E' // ambiguous on
396 // its own -- already checked above
397 || annotations[i].secondaryStructure == 'F'
398 // || annotations[i].secondaryStructure == 'G'
399 // || annotations[i].secondaryStructure == 'H' // ambiguous on
400 // its own -- already checked above
401 // || annotations[i].secondaryStructure == 'I'
402 || annotations[i].secondaryStructure == 'J'
403 || annotations[i].secondaryStructure == 'K'
404 || annotations[i].secondaryStructure == 'L'
405 || annotations[i].secondaryStructure == 'M'
406 || annotations[i].secondaryStructure == 'N'
407 || annotations[i].secondaryStructure == 'O'
408 || annotations[i].secondaryStructure == 'P'
409 || annotations[i].secondaryStructure == 'Q'
410 || annotations[i].secondaryStructure == 'R'
411 // || annotations[i].secondaryStructure == 'S'
412 // || annotations[i].secondaryStructure == 'T'
413 || annotations[i].secondaryStructure == 'U'
414 || annotations[i].secondaryStructure == 'V'
415 || annotations[i].secondaryStructure == 'W'
416 // || annotations[i].secondaryStructure == 'X'
417 || annotations[i].secondaryStructure == 'Y'
418 || annotations[i].secondaryStructure == 'Z')
425 // System.out.println("displaychar " + annotations[i].displayCharacter);
427 if (annotations[i].displayCharacter == null
428 || annotations[i].displayCharacter.length() == 0)
430 rnastring.append('.');
433 if (annotations[i].displayCharacter.length() == 1)
435 firstChar = annotations[i].displayCharacter.charAt(0);
436 // check to see if it looks like a sequence or is secondary structure
438 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
439 // Uncomment to only catch case where
440 // displayCharacter==secondary
442 // to correctly redisplay SS annotation imported from Stockholm,
443 // exported to JalviewXML and read back in again.
445 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
446 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
447 && firstChar != '(' && firstChar != '[' && firstChar != '<'
448 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
449 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
450 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
451 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
452 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
453 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
454 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
455 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
456 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
458 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
460 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
473 rnastring.append(annotations[i].displayCharacter.charAt(1));
476 if (annotations[i].displayCharacter.length() > 0)
485 for (int j = 0; j < annotations.length; j++)
487 if (annotations[j] != null
488 && annotations[j].secondaryStructure != ' ')
490 annotations[j].displayCharacter = String
491 .valueOf(annotations[j].secondaryStructure);
492 annotations[j].secondaryStructure = ' ';
501 _updateRnaSecStr(new AnnotCharSequence());
507 * flyweight access to positions in the alignment annotation row for RNA
513 private class AnnotCharSequence implements CharSequence
519 public AnnotCharSequence()
521 this(0, annotations.length);
524 AnnotCharSequence(int start, int end)
531 public CharSequence subSequence(int start, int end)
533 return new AnnotCharSequence(offset + start, offset + end);
543 public char charAt(int index)
545 return ((index + offset < 0) || (index + offset) >= max
546 || annotations[index + offset] == null
547 || (annotations[index + offset].secondaryStructure <= ' ')
549 : annotations[index + offset].displayCharacter == null
551 + offset].displayCharacter
554 + offset].secondaryStructure
556 + offset].displayCharacter
561 public String toString()
563 char[] string = new char[max - offset];
564 int mx = annotations.length;
566 for (int i = offset; i < mx; i++)
568 string[i] = (annotations[i] == null
569 || (annotations[i].secondaryStructure <= 32))
571 : (annotations[i].displayCharacter == null
572 || annotations[i].displayCharacter
574 ? annotations[i].secondaryStructure
575 : annotations[i].displayCharacter
578 return new String(string);
582 private long _lastrnaannot = -1;
584 public String getRNAStruc()
588 String rnastruc = new AnnotCharSequence().toString();
589 if (_lastrnaannot != rnastruc.hashCode())
591 // ensure rna structure contacts are up to date
592 _lastrnaannot = rnastruc.hashCode();
593 _updateRnaSecStr(rnastruc);
601 * Creates a new AlignmentAnnotation object.
616 public AlignmentAnnotation(String label, String description,
617 Annotation[] annotations, float min, float max, int graphType)
620 // graphs are not editable
621 editable = graphType == 0;
624 this.description = description;
625 this.annotations = annotations;
629 validateRangeAndDisplay();
633 * checks graphMin and graphMax, secondary structure symbols, sets graphType
634 * appropriately, sets null labels to the empty string if appropriate.
636 public void validateRangeAndDisplay()
639 if (annotations == null)
641 visible = false; // try to prevent renderer from displaying.
642 invalidrnastruc = -1;
643 return; // this is a non-annotation row annotation - ie a sequence score.
646 int graphType = graph;
647 float min = graphMin;
648 float max = graphMax;
649 boolean drawValues = true;
654 for (int i = 0; i < annotations.length; i++)
656 if (annotations[i] == null)
661 if (drawValues && annotations[i].displayCharacter != null
662 && annotations[i].displayCharacter.length() > 1)
667 if (annotations[i].value > max)
669 max = annotations[i].value;
672 if (annotations[i].value < min)
674 min = annotations[i].value;
676 if (_linecolour == null && annotations[i].colour != null)
678 _linecolour = annotations[i].colour;
681 // ensure zero is origin for min/max ranges on only one side of zero
698 areLabelsSecondaryStructure();
700 if (!drawValues && graphType != NO_GRAPH)
702 for (int i = 0; i < annotations.length; i++)
704 if (annotations[i] != null)
706 annotations[i].displayCharacter = "";
713 * Copy constructor creates a new independent annotation row with the same
714 * associated sequenceRef
718 public AlignmentAnnotation(AlignmentAnnotation annotation)
721 this.label = new String(annotation.label);
722 if (annotation.description != null)
724 this.description = new String(annotation.description);
726 this.graphMin = annotation.graphMin;
727 this.graphMax = annotation.graphMax;
728 this.graph = annotation.graph;
729 this.graphHeight = annotation.graphHeight;
730 this.graphGroup = annotation.graphGroup;
731 this.groupRef = annotation.groupRef;
732 this.editable = annotation.editable;
733 this.autoCalculated = annotation.autoCalculated;
734 this.hasIcons = annotation.hasIcons;
735 this.hasText = annotation.hasText;
736 this.height = annotation.height;
737 this.label = annotation.label;
738 this.padGaps = annotation.padGaps;
739 this.visible = annotation.visible;
740 this.centreColLabels = annotation.centreColLabels;
741 this.scaleColLabel = annotation.scaleColLabel;
742 this.showAllColLabels = annotation.showAllColLabels;
743 this.calcId = annotation.calcId;
744 if (annotation.properties != null)
746 properties = new HashMap<>();
747 for (Map.Entry<String, String> val : annotation.properties.entrySet())
749 properties.put(val.getKey(), val.getValue());
752 if (this.hasScore = annotation.hasScore)
754 this.score = annotation.score;
756 if (annotation.threshold != null)
758 threshold = new GraphLine(annotation.threshold);
760 Annotation[] ann = annotation.annotations;
761 if (annotation.annotations != null)
763 this.annotations = new Annotation[ann.length];
764 for (int i = 0; i < ann.length; i++)
768 annotations[i] = new Annotation(ann[i]);
769 if (_linecolour != null)
771 _linecolour = annotations[i].colour;
776 if (annotation.sequenceRef != null)
778 this.sequenceRef = annotation.sequenceRef;
779 if (annotation.sequenceMapping != null)
782 sequenceMapping = new HashMap<>();
783 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
785 while (pos.hasNext())
787 // could optimise this!
789 Annotation a = annotation.sequenceMapping.get(p);
796 for (int i = 0; i < ann.length; i++)
800 sequenceMapping.put(p, annotations[i]);
808 this.sequenceMapping = null;
811 // TODO: check if we need to do this: JAL-952
812 // if (this.isrna=annotation.isrna)
814 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
816 validateRangeAndDisplay(); // construct hashcodes, etc.
820 * clip the annotation to the columns given by startRes and endRes (inclusive)
821 * and prune any existing sequenceMapping to just those columns.
826 public void restrict(int startRes, int endRes)
828 if (annotations == null)
837 if (startRes >= annotations.length)
839 startRes = annotations.length - 1;
841 if (endRes >= annotations.length)
843 endRes = annotations.length - 1;
845 if (annotations == null)
849 Annotation[] temp = new Annotation[endRes - startRes + 1];
850 if (startRes < annotations.length)
852 System.arraycopy(annotations, startRes, temp, 0,
853 endRes - startRes + 1);
855 if (sequenceRef != null)
857 // Clip the mapping, if it exists.
858 int spos = sequenceRef.findPosition(startRes);
859 int epos = sequenceRef.findPosition(endRes);
860 if (sequenceMapping != null)
862 Map<Integer, Annotation> newmapping = new HashMap<>();
863 Iterator<Integer> e = sequenceMapping.keySet().iterator();
866 Integer pos = e.next();
867 if (pos.intValue() >= spos && pos.intValue() <= epos)
869 newmapping.put(pos, sequenceMapping.get(pos));
872 sequenceMapping.clear();
873 sequenceMapping = newmapping;
880 * set the annotation row to be at least length Annotations
883 * minimum number of columns required in the annotation row
884 * @return false if the annotation row is greater than length
886 public boolean padAnnotation(int length)
888 if (annotations == null)
890 return true; // annotation row is correct - null == not visible and
893 if (annotations.length < length)
895 Annotation[] na = new Annotation[length];
896 System.arraycopy(annotations, 0, na, 0, annotations.length);
900 return annotations.length > length;
907 * @return DOCUMENT ME!
910 public String toString()
912 if (annotations == null)
916 StringBuilder buffer = new StringBuilder(256);
918 for (int i = 0; i < annotations.length; i++)
920 if (annotations[i] != null)
924 buffer.append(annotations[i].value);
928 buffer.append(annotations[i].secondaryStructure);
932 buffer.append(annotations[i].displayCharacter);
938 // TODO: remove disgusting hack for 'special' treatment of consensus line.
939 if (label.indexOf("Consensus") == 0)
943 for (int i = 0; i < annotations.length; i++)
945 if (annotations[i] != null)
947 buffer.append(annotations[i].description);
954 return buffer.toString();
957 public void setThreshold(GraphLine line)
962 public GraphLine getThreshold()
968 * Attach the annotation to seqRef, starting from startRes position. If
969 * alreadyMapped is true then the indices of the annotation[] array are
970 * sequence positions rather than alignment column positions.
974 * @param alreadyMapped
976 public void createSequenceMapping(SequenceI seqRef, int startRes,
977 boolean alreadyMapped)
984 sequenceRef = seqRef;
985 if (annotations == null)
989 sequenceMapping = new HashMap<>();
993 for (int i = 0; i < annotations.length; i++)
995 if (annotations[i] != null)
999 seqPos = seqRef.findPosition(i);
1003 seqPos = i + startRes;
1006 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1013 * When positional annotation and a sequence reference is present, clears and
1014 * resizes the annotations array to the current alignment width, and adds
1015 * annotation according to aligned positions of the sequenceRef given by
1018 public void adjustForAlignment()
1020 if (sequenceRef == null)
1025 if (annotations == null)
1030 int a = 0, aSize = sequenceRef.getLength();
1039 Annotation[] temp = new Annotation[aSize];
1041 if (sequenceMapping != null)
1043 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1045 index = Integer.valueOf(a);
1046 Annotation annot = sequenceMapping.get(index);
1049 position = sequenceRef.findIndex(a) - 1;
1051 temp[position] = annot;
1059 * remove any null entries in annotation row and return the number of non-null
1060 * annotation elements.
1064 public int compactAnnotationArray()
1066 int i = 0, iSize = annotations.length;
1069 if (annotations[i] == null)
1073 System.arraycopy(annotations, i + 1, annotations, i,
1083 Annotation[] ann = annotations;
1084 annotations = new Annotation[i];
1085 System.arraycopy(ann, 0, annotations, 0, i);
1091 * Associate this annotation with the aligned residues of a particular
1092 * sequence. sequenceMapping will be updated in the following way: null
1093 * sequenceI - existing mapping will be discarded but annotations left in
1094 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1095 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1096 * parameter to specify correspondence between current and new sequenceRef
1100 public void setSequenceRef(SequenceI sequenceI)
1102 if (sequenceI != null)
1104 if (sequenceRef != null)
1106 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1107 tIsDs = sequenceI.getDatasetSequence() == null;
1108 if (sequenceRef != sequenceI
1110 && sequenceRef != sequenceI.getDatasetSequence())
1112 && sequenceRef.getDatasetSequence() != sequenceI)
1113 && (!rIsDs && !tIsDs
1114 && sequenceRef.getDatasetSequence() != sequenceI
1115 .getDatasetSequence())
1116 && !sequenceRef.equals(sequenceI))
1118 // if sequenceRef isn't intersecting with sequenceI
1119 // throw away old mapping and reconstruct.
1121 if (sequenceMapping != null)
1123 sequenceMapping = null;
1124 // compactAnnotationArray();
1126 createSequenceMapping(sequenceI, 1, true);
1127 adjustForAlignment();
1131 // Mapping carried over
1132 sequenceRef = sequenceI;
1137 // No mapping exists
1138 createSequenceMapping(sequenceI, 1, true);
1139 adjustForAlignment();
1144 // throw away the mapping without compacting.
1145 sequenceMapping = null;
1153 public double getScore()
1162 public void setScore(double score)
1170 * @return true if annotation has an associated score
1172 public boolean hasScore()
1174 return hasScore || !Double.isNaN(score);
1178 * Score only annotation
1181 * @param description
1184 public AlignmentAnnotation(String label, String description, double score)
1186 this(label, description, null);
1191 * copy constructor with edit based on the hidden columns marked in colSel
1193 * @param alignmentAnnotation
1196 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1197 HiddenColumns hidden)
1199 this(alignmentAnnotation);
1200 if (annotations == null)
1204 makeVisibleAnnotation(hidden);
1207 public void setPadGaps(boolean padgaps, char gapchar)
1209 this.padGaps = padgaps;
1213 for (int i = 0; i < annotations.length; i++)
1215 if (annotations[i] == null)
1217 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1220 else if (annotations[i].displayCharacter == null
1221 || annotations[i].displayCharacter.equals(" "))
1223 annotations[i].displayCharacter = String.valueOf(gapchar);
1230 * format description string for display
1233 * @return Get the annotation description string optionally prefixed by
1234 * associated sequence name (if any)
1236 public String getDescription(boolean seqname)
1238 if (seqname && this.sequenceRef != null)
1240 int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1243 // move the html tag to before the sequence reference.
1244 return "<html>" + sequenceRef.getName() + " : "
1245 + description.substring(i + 6);
1247 return sequenceRef.getName() + " : " + description;
1252 public boolean isValidStruc()
1254 return invalidrnastruc == -1;
1257 public long getInvalidStrucPos()
1259 return invalidrnastruc;
1263 * machine readable ID string indicating what generated this annotation
1265 protected String calcId = "";
1268 * properties associated with the calcId
1270 protected Map<String, String> properties = new HashMap<>();
1273 * base colour for line graphs. If null, will be set automatically by
1274 * searching the alignment annotation
1276 public java.awt.Color _linecolour;
1278 public String getCalcId()
1283 public void setCalcId(String calcId)
1285 this.calcId = calcId;
1288 public boolean isRNA()
1294 * transfer annotation to the given sequence using the given mapping from the
1295 * current positions or an existing sequence mapping
1299 * map involving sq as To or From
1301 public void liftOver(SequenceI sq, Mapping sp2sq)
1303 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1305 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1306 // Protein reference frames
1308 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1310 boolean mapIsTo = (sp2sq != null)
1311 ? (sp2sq.getTo() == sq
1312 || sp2sq.getTo() == sq.getDatasetSequence())
1315 // TODO build a better annotation element map and get rid of annotations[]
1316 Map<Integer, Annotation> mapForsq = new HashMap<>();
1317 if (sequenceMapping != null)
1321 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1323 Integer mpos = Integer
1324 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1325 : sp2sq.getPosition(ie.getKey()));
1326 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1328 mapForsq.put(mpos, ie.getValue());
1331 sequenceMapping = mapForsq;
1333 adjustForAlignment();
1343 * like liftOver but more general.
1345 * Takes an array of int pairs that will be used to update the internal
1346 * sequenceMapping and so shuffle the annotated positions
1349 * - new sequence reference for the annotation row - if null,
1350 * sequenceRef is left unchanged
1352 * array of ints containing corresponding positions
1354 * - column for current coordinate system (-1 for index+1)
1356 * - column for destination coordinate system (-1 for index+1)
1358 * - offset added to index when referencing either coordinate system
1359 * @note no checks are made as to whether from and/or to are sensible
1360 * @note caller should add the remapped annotation to newref if they have not
1363 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1364 int from, int to, int idxoffset)
1366 if (mapping != null)
1368 Map<Integer, Annotation> old = sequenceMapping;
1369 Map<Integer, Annotation> remap = new HashMap<>();
1371 for (int mp[] : mapping.values())
1377 Annotation ann = null;
1380 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1384 if (mp != null && mp.length > from)
1386 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1393 remap.put(Integer.valueOf(idxoffset + index), ann);
1397 if (to > -1 && to < mp.length)
1399 remap.put(Integer.valueOf(mp[to]), ann);
1404 sequenceMapping = remap;
1408 sequenceRef = newref;
1410 adjustForAlignment();
1414 public String getProperty(String property)
1416 if (properties == null)
1420 return properties.get(property);
1423 public void setProperty(String property, String value)
1425 if (properties == null)
1427 properties = new HashMap<>();
1429 properties.put(property, value);
1432 public boolean hasProperties()
1434 return properties != null && properties.size() > 0;
1437 public Collection<String> getProperties()
1439 if (properties == null)
1441 return Collections.emptyList();
1443 return properties.keySet();
1447 * Returns the Annotation for the given sequence position (base 1) if any,
1453 public Annotation getAnnotationForPosition(int position)
1455 return sequenceMapping == null ? null : sequenceMapping.get(position);
1460 * Set the id to "ann" followed by a counter that increments so as to be
1461 * unique for the lifetime of the JVM
1463 protected final void setAnnotationId()
1465 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1469 * Returns the match for the last unmatched opening RNA helix pair symbol
1470 * preceding the given column, or '(' if nothing found to match.
1475 public String getDefaultRnaHelixSymbol(int column)
1477 String result = "(";
1478 if (annotations == null)
1484 * for each preceding column, if it contains an open bracket,
1485 * count whether it is still unmatched at column, if so return its pair
1486 * (likely faster than the fancy alternative using stacks)
1488 for (int col = column - 1; col >= 0; col--)
1490 Annotation annotation = annotations[col];
1491 if (annotation == null)
1495 String displayed = annotation.displayCharacter;
1496 if (displayed == null || displayed.length() != 1)
1500 char symbol = displayed.charAt(0);
1501 if (!Rna.isOpeningParenthesis(symbol))
1507 * found an opening bracket symbol
1508 * count (closing-opening) symbols of this type that follow it,
1509 * up to and excluding the target column; if the count is less
1510 * than 1, the opening bracket is unmatched, so return its match
1512 String closer = String
1513 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1514 String opener = String.valueOf(symbol);
1516 for (int j = col + 1; j < column; j++)
1518 if (annotations[j] != null)
1520 String s = annotations[j].displayCharacter;
1521 if (closer.equals(s))
1525 else if (opener.equals(s))
1539 protected static synchronized long nextId()
1546 * @return true for rows that have a range of values in their annotation set
1548 public boolean isQuantitative()
1550 return graphMin < graphMax;
1554 * delete any columns in alignmentAnnotation that are hidden (including
1555 * sequence associated annotation).
1557 * @param hiddenColumns
1558 * the set of hidden columns
1560 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1562 if (annotations != null)
1564 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1569 * delete any columns in alignmentAnnotation that are hidden (including
1570 * sequence associated annotation).
1573 * remove any annotation to the right of this column
1575 * remove any annotation to the left of this column
1576 * @param hiddenColumns
1577 * the set of hidden columns
1579 public void makeVisibleAnnotation(int start, int end,
1580 HiddenColumns hiddenColumns)
1582 if (annotations != null)
1584 if (hiddenColumns.hasHiddenColumns())
1586 removeHiddenAnnotation(start, end, hiddenColumns);
1590 restrict(start, end);
1596 * The actual implementation of deleting hidden annotation columns
1599 * remove any annotation to the right of this column
1601 * remove any annotation to the left of this column
1602 * @param hiddenColumns
1603 * the set of hidden columns
1605 private void removeHiddenAnnotation(int start, int end,
1606 HiddenColumns hiddenColumns)
1608 // mangle the alignmentAnnotation annotation array
1609 ArrayList<Annotation[]> annels = new ArrayList<>();
1610 Annotation[] els = null;
1614 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1618 int annotationLength;
1619 while (blocks.hasNext())
1621 int[] block = blocks.next();
1622 annotationLength = block[1] - block[0] + 1;
1624 if (blocks.hasNext())
1626 // copy just the visible segment of the annotation row
1627 copylength = annotationLength;
1631 if (annotationLength + block[0] <= annotations.length)
1633 // copy just the visible segment of the annotation row
1634 copylength = annotationLength;
1638 // copy to the end of the annotation row
1639 copylength = annotations.length - block[0];
1643 els = new Annotation[annotationLength];
1645 System.arraycopy(annotations, block[0], els, 0, copylength);
1646 w += annotationLength;
1651 annotations = new Annotation[w];
1654 for (Annotation[] chnk : annels)
1656 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1662 public static Iterable<AlignmentAnnotation> findAnnotations(
1663 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1667 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1668 for (AlignmentAnnotation ann : list)
1670 if ((calcId == null || (ann.getCalcId() != null
1671 && ann.getCalcId().equals(calcId)))
1672 && (seq == null || (ann.sequenceRef != null
1673 && ann.sequenceRef == seq))
1675 || (ann.label != null && ann.label.equals(label))))
1684 * Answer true if any annotation matches the calcId passed in (if not null).
1687 * annotation to search
1691 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1695 if (calcId != null && !"".equals(calcId))
1697 for (AlignmentAnnotation a : list)
1699 if (a.getCalcId() == calcId)
1708 public static Iterable<AlignmentAnnotation> findAnnotation(
1709 List<AlignmentAnnotation> list, String calcId)
1712 List<AlignmentAnnotation> aa = new ArrayList<>();
1717 for (AlignmentAnnotation a : list)
1720 if (a.getCalcId() == calcId || (a.getCalcId() != null
1721 && calcId != null && a.getCalcId().equals(calcId)))