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 static final int CUSTOMRENDERER = 4;
294 public boolean belowAlignment = true;
296 public SequenceGroup groupRef = null;
299 * display every column label, even if there is a row of identical labels
301 public boolean showAllColLabels = false;
304 * scale the column label to fit within the alignment column.
306 public boolean scaleColLabel = false;
309 * centre the column labels relative to the alignment column
311 public boolean centreColLabels = false;
313 private boolean isrna;
315 public static int getGraphValueFromString(String string)
317 if (string.equalsIgnoreCase("BAR_GRAPH"))
321 else if (string.equalsIgnoreCase("LINE_GRAPH"))
332 * Creates a new AlignmentAnnotation object.
335 * short label shown under sequence labels
337 * text displayed on mouseover
339 * set of positional annotation elements
341 public AlignmentAnnotation(String label, String description,
342 Annotation[] annotations)
348 this.description = description;
349 this.annotations = annotations;
351 validateRangeAndDisplay();
355 * Checks if annotation labels represent secondary structures
358 void areLabelsSecondaryStructure()
360 boolean nonSSLabel = false;
362 StringBuffer rnastring = new StringBuffer();
365 for (int i = 0; i < annotations.length; i++)
367 // DEBUG System.out.println(i + ": " + annotations[i]);
368 if (annotations[i] == null)
372 if (annotations[i].secondaryStructure == 'H'
373 || annotations[i].secondaryStructure == 'E')
375 // DEBUG System.out.println( "/H|E/ '" +
376 // annotations[i].secondaryStructure + "'");
380 // Check for RNA secondary structure
382 // DEBUG System.out.println( "/else/ '" +
383 // annotations[i].secondaryStructure + "'");
384 // TODO: 2.8.2 should this ss symbol validation check be a function in
385 // RNA/ResidueProperties ?
386 // allow for DSSP extended code:
387 // https://www.wikidoc.org/index.php/Secondary_structure#The_DSSP_code
388 // GHITEBS as well as C and X (for missing?)
389 if (annotations[i].secondaryStructure == '('
390 || annotations[i].secondaryStructure == '['
391 || annotations[i].secondaryStructure == '<'
392 || annotations[i].secondaryStructure == '{'
393 || annotations[i].secondaryStructure == 'A'
394 // || annotations[i].secondaryStructure == 'B'
395 // || annotations[i].secondaryStructure == 'C'
396 || annotations[i].secondaryStructure == 'D'
397 // || annotations[i].secondaryStructure == 'E' // ambiguous on
398 // its own -- already checked above
399 || annotations[i].secondaryStructure == 'F'
400 // || annotations[i].secondaryStructure == 'G'
401 // || annotations[i].secondaryStructure == 'H' // ambiguous on
402 // its own -- already checked above
403 // || annotations[i].secondaryStructure == 'I'
404 || annotations[i].secondaryStructure == 'J'
405 || annotations[i].secondaryStructure == 'K'
406 || annotations[i].secondaryStructure == 'L'
407 || annotations[i].secondaryStructure == 'M'
408 || annotations[i].secondaryStructure == 'N'
409 || annotations[i].secondaryStructure == 'O'
410 || annotations[i].secondaryStructure == 'P'
411 || annotations[i].secondaryStructure == 'Q'
412 || annotations[i].secondaryStructure == 'R'
413 // || annotations[i].secondaryStructure == 'S'
414 // || annotations[i].secondaryStructure == 'T'
415 || annotations[i].secondaryStructure == 'U'
416 || annotations[i].secondaryStructure == 'V'
417 || annotations[i].secondaryStructure == 'W'
418 // || annotations[i].secondaryStructure == 'X'
419 || annotations[i].secondaryStructure == 'Y'
420 || annotations[i].secondaryStructure == 'Z')
427 // System.out.println("displaychar " + annotations[i].displayCharacter);
429 if (annotations[i].displayCharacter == null
430 || annotations[i].displayCharacter.length() == 0)
432 rnastring.append('.');
435 if (annotations[i].displayCharacter.length() == 1)
437 firstChar = annotations[i].displayCharacter.charAt(0);
438 // check to see if it looks like a sequence or is secondary structure
440 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
441 // Uncomment to only catch case where
442 // displayCharacter==secondary
444 // to correctly redisplay SS annotation imported from Stockholm,
445 // exported to JalviewXML and read back in again.
447 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
448 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
449 && firstChar != '(' && firstChar != '[' && firstChar != '<'
450 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
451 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
452 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
453 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
454 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
455 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
456 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
457 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
458 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
460 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
462 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
475 rnastring.append(annotations[i].displayCharacter.charAt(1));
478 if (annotations[i].displayCharacter.length() > 0)
487 for (int j = 0; j < annotations.length; j++)
489 if (annotations[j] != null
490 && annotations[j].secondaryStructure != ' ')
492 annotations[j].displayCharacter = String
493 .valueOf(annotations[j].secondaryStructure);
494 annotations[j].secondaryStructure = ' ';
503 _updateRnaSecStr(new AnnotCharSequence());
509 * flyweight access to positions in the alignment annotation row for RNA
515 private class AnnotCharSequence implements CharSequence
521 public AnnotCharSequence()
523 this(0, annotations.length);
526 AnnotCharSequence(int start, int end)
533 public CharSequence subSequence(int start, int end)
535 return new AnnotCharSequence(offset + start, offset + end);
545 public char charAt(int index)
547 return ((index + offset < 0) || (index + offset) >= max
548 || annotations[index + offset] == null
549 || (annotations[index + offset].secondaryStructure <= ' ')
551 : annotations[index + offset].displayCharacter == null
553 + offset].displayCharacter
556 + offset].secondaryStructure
558 + offset].displayCharacter
563 public String toString()
565 char[] string = new char[max - offset];
566 int mx = annotations.length;
568 for (int i = offset; i < mx; i++)
570 string[i] = (annotations[i] == null
571 || (annotations[i].secondaryStructure <= 32))
573 : (annotations[i].displayCharacter == null
574 || annotations[i].displayCharacter
576 ? annotations[i].secondaryStructure
577 : annotations[i].displayCharacter
580 return new String(string);
584 private long _lastrnaannot = -1;
586 public String getRNAStruc()
590 String rnastruc = new AnnotCharSequence().toString();
591 if (_lastrnaannot != rnastruc.hashCode())
593 // ensure rna structure contacts are up to date
594 _lastrnaannot = rnastruc.hashCode();
595 _updateRnaSecStr(rnastruc);
603 * Creates a new AlignmentAnnotation object.
618 public AlignmentAnnotation(String label, String description,
619 Annotation[] annotations, float min, float max, int graphType)
622 // graphs are not editable
623 editable = graphType == 0;
626 this.description = description;
627 this.annotations = annotations;
631 validateRangeAndDisplay();
635 * checks graphMin and graphMax, secondary structure symbols, sets graphType
636 * appropriately, sets null labels to the empty string if appropriate.
638 public void validateRangeAndDisplay()
641 if (annotations == null)
643 visible = false; // try to prevent renderer from displaying.
644 invalidrnastruc = -1;
645 return; // this is a non-annotation row annotation - ie a sequence score.
648 int graphType = graph;
649 float min = graphMin;
650 float max = graphMax;
651 boolean drawValues = true;
656 for (int i = 0; i < annotations.length; i++)
658 if (annotations[i] == null)
663 if (drawValues && annotations[i].displayCharacter != null
664 && annotations[i].displayCharacter.length() > 1)
669 if (annotations[i].value > max)
671 max = annotations[i].value;
674 if (annotations[i].value < min)
676 min = annotations[i].value;
678 if (_linecolour == null && annotations[i].colour != null)
680 _linecolour = annotations[i].colour;
683 // ensure zero is origin for min/max ranges on only one side of zero
700 areLabelsSecondaryStructure();
702 if (!drawValues && graphType != NO_GRAPH)
704 for (int i = 0; i < annotations.length; i++)
706 if (annotations[i] != null)
708 annotations[i].displayCharacter = "";
715 * Copy constructor creates a new independent annotation row with the same
716 * associated sequenceRef
720 public AlignmentAnnotation(AlignmentAnnotation annotation)
723 this.label = new String(annotation.label);
724 if (annotation.description != null)
726 this.description = new String(annotation.description);
728 this.graphMin = annotation.graphMin;
729 this.graphMax = annotation.graphMax;
730 this.graph = annotation.graph;
731 this.graphHeight = annotation.graphHeight;
732 this.graphGroup = annotation.graphGroup;
733 this.groupRef = annotation.groupRef;
734 this.editable = annotation.editable;
735 this.autoCalculated = annotation.autoCalculated;
736 this.hasIcons = annotation.hasIcons;
737 this.hasText = annotation.hasText;
738 this.height = annotation.height;
739 this.label = annotation.label;
740 this.padGaps = annotation.padGaps;
741 this.visible = annotation.visible;
742 this.centreColLabels = annotation.centreColLabels;
743 this.scaleColLabel = annotation.scaleColLabel;
744 this.showAllColLabels = annotation.showAllColLabels;
745 this.calcId = annotation.calcId;
746 if (annotation.properties != null)
748 properties = new HashMap<>();
749 for (Map.Entry<String, String> val : annotation.properties.entrySet())
751 properties.put(val.getKey(), val.getValue());
754 if (this.hasScore = annotation.hasScore)
756 this.score = annotation.score;
758 if (annotation.threshold != null)
760 threshold = new GraphLine(annotation.threshold);
762 Annotation[] ann = annotation.annotations;
763 if (annotation.annotations != null)
765 this.annotations = new Annotation[ann.length];
766 for (int i = 0; i < ann.length; i++)
770 annotations[i] = new Annotation(ann[i]);
771 if (_linecolour != null)
773 _linecolour = annotations[i].colour;
778 if (annotation.sequenceRef != null)
780 this.sequenceRef = annotation.sequenceRef;
781 if (annotation.sequenceMapping != null)
784 sequenceMapping = new HashMap<>();
785 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
787 while (pos.hasNext())
789 // could optimise this!
791 Annotation a = annotation.sequenceMapping.get(p);
798 for (int i = 0; i < ann.length; i++)
802 sequenceMapping.put(p, annotations[i]);
810 this.sequenceMapping = null;
814 // TODO: check if we need to do this: JAL-952
815 // if (this.isrna=annotation.isrna)
817 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
819 validateRangeAndDisplay(); // construct hashcodes, etc.
823 * clip the annotation to the columns given by startRes and endRes (inclusive)
824 * and prune any existing sequenceMapping to just those columns.
829 public void restrict(int startRes, int endRes)
831 if (annotations == null)
840 if (startRes >= annotations.length)
842 startRes = annotations.length - 1;
844 if (endRes >= annotations.length)
846 endRes = annotations.length - 1;
848 if (annotations == null)
852 Annotation[] temp = new Annotation[endRes - startRes + 1];
853 if (startRes < annotations.length)
855 System.arraycopy(annotations, startRes, temp, 0,
856 endRes - startRes + 1);
858 if (sequenceRef != null)
860 // Clip the mapping, if it exists.
861 int spos = sequenceRef.findPosition(startRes);
862 int epos = sequenceRef.findPosition(endRes);
863 if (sequenceMapping != null)
865 Map<Integer, Annotation> newmapping = new HashMap<>();
866 Iterator<Integer> e = sequenceMapping.keySet().iterator();
869 Integer pos = e.next();
870 if (pos.intValue() >= spos && pos.intValue() <= epos)
872 newmapping.put(pos, sequenceMapping.get(pos));
875 sequenceMapping.clear();
876 sequenceMapping = newmapping;
883 * set the annotation row to be at least length Annotations
886 * minimum number of columns required in the annotation row
887 * @return false if the annotation row is greater than length
889 public boolean padAnnotation(int length)
891 if (annotations == null)
893 return true; // annotation row is correct - null == not visible and
896 if (annotations.length < length)
898 Annotation[] na = new Annotation[length];
899 System.arraycopy(annotations, 0, na, 0, annotations.length);
903 return annotations.length > length;
910 * @return DOCUMENT ME!
913 public String toString()
915 if (annotations == null)
919 StringBuilder buffer = new StringBuilder(256);
921 for (int i = 0; i < annotations.length; i++)
923 if (annotations[i] != null)
927 buffer.append(annotations[i].value);
931 buffer.append(annotations[i].secondaryStructure);
935 buffer.append(annotations[i].displayCharacter);
941 // TODO: remove disgusting hack for 'special' treatment of consensus line.
942 if (label.indexOf("Consensus") == 0)
946 for (int i = 0; i < annotations.length; i++)
948 if (annotations[i] != null)
950 buffer.append(annotations[i].description);
957 return buffer.toString();
960 public void setThreshold(GraphLine line)
965 public GraphLine getThreshold()
971 * Attach the annotation to seqRef, starting from startRes position. If
972 * alreadyMapped is true then the indices of the annotation[] array are
973 * sequence positions rather than alignment column positions.
977 * @param alreadyMapped
979 public void createSequenceMapping(SequenceI seqRef, int startRes,
980 boolean alreadyMapped)
987 sequenceRef = seqRef;
988 if (annotations == null)
992 sequenceMapping = new HashMap<>();
996 for (int i = 0; i < annotations.length; i++)
998 if (annotations[i] != null)
1002 seqPos = seqRef.findPosition(i);
1006 seqPos = i + startRes;
1009 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1016 * When positional annotation and a sequence reference is present, clears and
1017 * resizes the annotations array to the current alignment width, and adds
1018 * annotation according to aligned positions of the sequenceRef given by
1021 public void adjustForAlignment()
1023 if (sequenceRef == null)
1028 if (annotations == null)
1033 int a = 0, aSize = sequenceRef.getLength();
1042 Annotation[] temp = new Annotation[aSize];
1044 if (sequenceMapping != null)
1046 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1048 index = Integer.valueOf(a);
1049 Annotation annot = sequenceMapping.get(index);
1052 position = sequenceRef.findIndex(a) - 1;
1054 temp[position] = annot;
1062 * remove any null entries in annotation row and return the number of non-null
1063 * annotation elements.
1067 public int compactAnnotationArray()
1069 int i = 0, iSize = annotations.length;
1072 if (annotations[i] == null)
1076 System.arraycopy(annotations, i + 1, annotations, i,
1086 Annotation[] ann = annotations;
1087 annotations = new Annotation[i];
1088 System.arraycopy(ann, 0, annotations, 0, i);
1094 * Associate this annotation with the aligned residues of a particular
1095 * sequence. sequenceMapping will be updated in the following way: null
1096 * sequenceI - existing mapping will be discarded but annotations left in
1097 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1098 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1099 * parameter to specify correspondence between current and new sequenceRef
1103 public void setSequenceRef(SequenceI sequenceI)
1105 if (sequenceI != null)
1107 if (sequenceRef != null)
1109 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1110 tIsDs = sequenceI.getDatasetSequence() == null;
1111 if (sequenceRef != sequenceI
1113 && sequenceRef != sequenceI.getDatasetSequence())
1115 && sequenceRef.getDatasetSequence() != sequenceI)
1116 && (!rIsDs && !tIsDs
1117 && sequenceRef.getDatasetSequence() != sequenceI
1118 .getDatasetSequence())
1119 && !sequenceRef.equals(sequenceI))
1121 // if sequenceRef isn't intersecting with sequenceI
1122 // throw away old mapping and reconstruct.
1124 if (sequenceMapping != null)
1126 sequenceMapping = null;
1127 // compactAnnotationArray();
1129 createSequenceMapping(sequenceI, 1, true);
1130 adjustForAlignment();
1134 // Mapping carried over
1135 sequenceRef = sequenceI;
1140 // No mapping exists
1141 createSequenceMapping(sequenceI, 1, true);
1142 adjustForAlignment();
1147 // throw away the mapping without compacting.
1148 sequenceMapping = null;
1156 public double getScore()
1165 public void setScore(double score)
1173 * @return true if annotation has an associated score
1175 public boolean hasScore()
1177 return hasScore || !Double.isNaN(score);
1181 * Score only annotation
1184 * @param description
1187 public AlignmentAnnotation(String label, String description, double score)
1189 this(label, description, null);
1194 * copy constructor with edit based on the hidden columns marked in colSel
1196 * @param alignmentAnnotation
1199 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1200 HiddenColumns hidden)
1202 this(alignmentAnnotation);
1203 if (annotations == null)
1207 makeVisibleAnnotation(hidden);
1210 public void setPadGaps(boolean padgaps, char gapchar)
1212 this.padGaps = padgaps;
1216 for (int i = 0; i < annotations.length; i++)
1218 if (annotations[i] == null)
1220 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1223 else if (annotations[i].displayCharacter == null
1224 || annotations[i].displayCharacter.equals(" "))
1226 annotations[i].displayCharacter = String.valueOf(gapchar);
1233 * format description string for display
1236 * @return Get the annotation description string optionally prefixed by
1237 * associated sequence name (if any)
1239 public String getDescription(boolean seqname)
1241 if (seqname && this.sequenceRef != null)
1243 int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1246 // move the html tag to before the sequence reference.
1247 return "<html>" + sequenceRef.getName() + " : "
1248 + description.substring(i + 6);
1250 return sequenceRef.getName() + " : " + description;
1255 public boolean isValidStruc()
1257 return invalidrnastruc == -1;
1260 public long getInvalidStrucPos()
1262 return invalidrnastruc;
1266 * machine readable ID string indicating what generated this annotation
1268 protected String calcId = "";
1271 * properties associated with the calcId
1273 protected Map<String, String> properties = new HashMap<>();
1276 * base colour for line graphs. If null, will be set automatically by
1277 * searching the alignment annotation
1279 public java.awt.Color _linecolour;
1281 public String getCalcId()
1286 public void setCalcId(String calcId)
1288 this.calcId = calcId;
1291 public boolean isRNA()
1297 * transfer annotation to the given sequence using the given mapping from the
1298 * current positions or an existing sequence mapping
1302 * map involving sq as To or From
1304 public void liftOver(SequenceI sq, Mapping sp2sq)
1306 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1308 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1309 // Protein reference frames
1311 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1313 boolean mapIsTo = (sp2sq != null)
1314 ? (sp2sq.getTo() == sq
1315 || sp2sq.getTo() == sq.getDatasetSequence())
1318 // TODO build a better annotation element map and get rid of annotations[]
1319 Map<Integer, Annotation> mapForsq = new HashMap<>();
1320 if (sequenceMapping != null)
1324 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1326 Integer mpos = Integer
1327 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1328 : sp2sq.getPosition(ie.getKey()));
1329 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1331 mapForsq.put(mpos, ie.getValue());
1334 sequenceMapping = mapForsq;
1336 adjustForAlignment();
1346 * like liftOver but more general.
1348 * Takes an array of int pairs that will be used to update the internal
1349 * sequenceMapping and so shuffle the annotated positions
1352 * - new sequence reference for the annotation row - if null,
1353 * sequenceRef is left unchanged
1355 * array of ints containing corresponding positions
1357 * - column for current coordinate system (-1 for index+1)
1359 * - column for destination coordinate system (-1 for index+1)
1361 * - offset added to index when referencing either coordinate system
1362 * @note no checks are made as to whether from and/or to are sensible
1363 * @note caller should add the remapped annotation to newref if they have not
1366 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1367 int from, int to, int idxoffset)
1369 if (mapping != null)
1371 Map<Integer, Annotation> old = sequenceMapping;
1372 Map<Integer, Annotation> remap = new HashMap<>();
1374 for (int mp[] : mapping.values())
1380 Annotation ann = null;
1383 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1387 if (mp != null && mp.length > from)
1389 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1396 remap.put(Integer.valueOf(idxoffset + index), ann);
1400 if (to > -1 && to < mp.length)
1402 remap.put(Integer.valueOf(mp[to]), ann);
1407 sequenceMapping = remap;
1411 sequenceRef = newref;
1413 adjustForAlignment();
1417 public String getProperty(String property)
1419 if (properties == null)
1423 return properties.get(property);
1426 public void setProperty(String property, String value)
1428 if (properties == null)
1430 properties = new HashMap<>();
1432 properties.put(property, value);
1435 public boolean hasProperties()
1437 return properties != null && properties.size() > 0;
1440 public Collection<String> getProperties()
1442 if (properties == null)
1444 return Collections.emptyList();
1446 return properties.keySet();
1450 * Returns the Annotation for the given sequence position (base 1) if any,
1456 public Annotation getAnnotationForPosition(int position)
1458 return sequenceMapping == null ? null : sequenceMapping.get(position);
1463 * Set the id to "ann" followed by a counter that increments so as to be
1464 * unique for the lifetime of the JVM
1466 protected final void setAnnotationId()
1468 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1472 * Returns the match for the last unmatched opening RNA helix pair symbol
1473 * preceding the given column, or '(' if nothing found to match.
1478 public String getDefaultRnaHelixSymbol(int column)
1480 String result = "(";
1481 if (annotations == null)
1487 * for each preceding column, if it contains an open bracket,
1488 * count whether it is still unmatched at column, if so return its pair
1489 * (likely faster than the fancy alternative using stacks)
1491 for (int col = column - 1; col >= 0; col--)
1493 Annotation annotation = annotations[col];
1494 if (annotation == null)
1498 String displayed = annotation.displayCharacter;
1499 if (displayed == null || displayed.length() != 1)
1503 char symbol = displayed.charAt(0);
1504 if (!Rna.isOpeningParenthesis(symbol))
1510 * found an opening bracket symbol
1511 * count (closing-opening) symbols of this type that follow it,
1512 * up to and excluding the target column; if the count is less
1513 * than 1, the opening bracket is unmatched, so return its match
1515 String closer = String
1516 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1517 String opener = String.valueOf(symbol);
1519 for (int j = col + 1; j < column; j++)
1521 if (annotations[j] != null)
1523 String s = annotations[j].displayCharacter;
1524 if (closer.equals(s))
1528 else if (opener.equals(s))
1542 protected static synchronized long nextId()
1549 * @return true for rows that have a range of values in their annotation set
1551 public boolean isQuantitative()
1553 return graphMin < graphMax;
1557 * delete any columns in alignmentAnnotation that are hidden (including
1558 * sequence associated annotation).
1560 * @param hiddenColumns
1561 * the set of hidden columns
1563 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1565 if (annotations != null)
1567 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1572 * delete any columns in alignmentAnnotation that are hidden (including
1573 * sequence associated annotation).
1576 * remove any annotation to the right of this column
1578 * remove any annotation to the left of this column
1579 * @param hiddenColumns
1580 * the set of hidden columns
1582 public void makeVisibleAnnotation(int start, int end,
1583 HiddenColumns hiddenColumns)
1585 if (annotations != null)
1587 if (hiddenColumns.hasHiddenColumns())
1589 removeHiddenAnnotation(start, end, hiddenColumns);
1593 restrict(start, end);
1599 * The actual implementation of deleting hidden annotation columns
1602 * remove any annotation to the right of this column
1604 * remove any annotation to the left of this column
1605 * @param hiddenColumns
1606 * the set of hidden columns
1608 private void removeHiddenAnnotation(int start, int end,
1609 HiddenColumns hiddenColumns)
1611 // mangle the alignmentAnnotation annotation array
1612 ArrayList<Annotation[]> annels = new ArrayList<>();
1613 Annotation[] els = null;
1617 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1621 int annotationLength;
1622 while (blocks.hasNext())
1624 int[] block = blocks.next();
1625 annotationLength = block[1] - block[0] + 1;
1627 if (blocks.hasNext())
1629 // copy just the visible segment of the annotation row
1630 copylength = annotationLength;
1634 if (annotationLength + block[0] <= annotations.length)
1636 // copy just the visible segment of the annotation row
1637 copylength = annotationLength;
1641 // copy to the end of the annotation row
1642 copylength = annotations.length - block[0];
1646 els = new Annotation[annotationLength];
1648 System.arraycopy(annotations, block[0], els, 0, copylength);
1649 w += annotationLength;
1654 annotations = new Annotation[w];
1657 for (Annotation[] chnk : annels)
1659 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1665 public static Iterable<AlignmentAnnotation> findAnnotations(
1666 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1670 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1671 for (AlignmentAnnotation ann : list)
1673 if ((calcId == null || (ann.getCalcId() != null
1674 && ann.getCalcId().equals(calcId)))
1675 && (seq == null || (ann.sequenceRef != null
1676 && ann.sequenceRef == seq))
1678 || (ann.label != null && ann.label.equals(label))))
1687 * Answer true if any annotation matches the calcId passed in (if not null).
1690 * annotation to search
1694 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1698 if (calcId != null && !"".equals(calcId))
1700 for (AlignmentAnnotation a : list)
1702 if (a.getCalcId() == calcId)
1711 public static Iterable<AlignmentAnnotation> findAnnotation(
1712 List<AlignmentAnnotation> list, String calcId)
1715 List<AlignmentAnnotation> aa = new ArrayList<>();
1720 for (AlignmentAnnotation a : list)
1723 if (a.getCalcId() == calcId || (a.getCalcId() != null
1724 && calcId != null && a.getCalcId().equals(calcId)))