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;
813 // TODO: check if we need to do this: JAL-952
814 // if (this.isrna=annotation.isrna)
816 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
818 validateRangeAndDisplay(); // construct hashcodes, etc.
822 * clip the annotation to the columns given by startRes and endRes (inclusive)
823 * and prune any existing sequenceMapping to just those columns.
828 public void restrict(int startRes, int endRes)
830 if (annotations == null)
839 if (startRes >= annotations.length)
841 startRes = annotations.length - 1;
843 if (endRes >= annotations.length)
845 endRes = annotations.length - 1;
847 if (annotations == null)
851 Annotation[] temp = new Annotation[endRes - startRes + 1];
852 if (startRes < annotations.length)
854 System.arraycopy(annotations, startRes, temp, 0,
855 endRes - startRes + 1);
857 if (sequenceRef != null)
859 // Clip the mapping, if it exists.
860 int spos = sequenceRef.findPosition(startRes);
861 int epos = sequenceRef.findPosition(endRes);
862 if (sequenceMapping != null)
864 Map<Integer, Annotation> newmapping = new HashMap<>();
865 Iterator<Integer> e = sequenceMapping.keySet().iterator();
868 Integer pos = e.next();
869 if (pos.intValue() >= spos && pos.intValue() <= epos)
871 newmapping.put(pos, sequenceMapping.get(pos));
874 sequenceMapping.clear();
875 sequenceMapping = newmapping;
882 * set the annotation row to be at least length Annotations
885 * minimum number of columns required in the annotation row
886 * @return false if the annotation row is greater than length
888 public boolean padAnnotation(int length)
890 if (annotations == null)
892 return true; // annotation row is correct - null == not visible and
895 if (annotations.length < length)
897 Annotation[] na = new Annotation[length];
898 System.arraycopy(annotations, 0, na, 0, annotations.length);
902 return annotations.length > length;
909 * @return DOCUMENT ME!
912 public String toString()
914 if (annotations == null)
918 StringBuilder buffer = new StringBuilder(256);
920 for (int i = 0; i < annotations.length; i++)
922 if (annotations[i] != null)
926 buffer.append(annotations[i].value);
930 buffer.append(annotations[i].secondaryStructure);
934 buffer.append(annotations[i].displayCharacter);
940 // TODO: remove disgusting hack for 'special' treatment of consensus line.
941 if (label.indexOf("Consensus") == 0)
945 for (int i = 0; i < annotations.length; i++)
947 if (annotations[i] != null)
949 buffer.append(annotations[i].description);
956 return buffer.toString();
959 public void setThreshold(GraphLine line)
964 public GraphLine getThreshold()
970 * Attach the annotation to seqRef, starting from startRes position. If
971 * alreadyMapped is true then the indices of the annotation[] array are
972 * sequence positions rather than alignment column positions.
976 * @param alreadyMapped
978 public void createSequenceMapping(SequenceI seqRef, int startRes,
979 boolean alreadyMapped)
986 sequenceRef = seqRef;
987 if (annotations == null)
991 sequenceMapping = new HashMap<>();
995 for (int i = 0; i < annotations.length; i++)
997 if (annotations[i] != null)
1001 seqPos = seqRef.findPosition(i);
1005 seqPos = i + startRes;
1008 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1015 * When positional annotation and a sequence reference is present, clears and
1016 * resizes the annotations array to the current alignment width, and adds
1017 * annotation according to aligned positions of the sequenceRef given by
1020 public void adjustForAlignment()
1022 if (sequenceRef == null)
1027 if (annotations == null)
1032 int a = 0, aSize = sequenceRef.getLength();
1041 Annotation[] temp = new Annotation[aSize];
1043 if (sequenceMapping != null)
1045 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1047 index = Integer.valueOf(a);
1048 Annotation annot = sequenceMapping.get(index);
1051 position = sequenceRef.findIndex(a) - 1;
1053 temp[position] = annot;
1061 * remove any null entries in annotation row and return the number of non-null
1062 * annotation elements.
1066 public int compactAnnotationArray()
1068 int i = 0, iSize = annotations.length;
1071 if (annotations[i] == null)
1075 System.arraycopy(annotations, i + 1, annotations, i,
1085 Annotation[] ann = annotations;
1086 annotations = new Annotation[i];
1087 System.arraycopy(ann, 0, annotations, 0, i);
1093 * Associate this annotation with the aligned residues of a particular
1094 * sequence. sequenceMapping will be updated in the following way: null
1095 * sequenceI - existing mapping will be discarded but annotations left in
1096 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1097 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1098 * parameter to specify correspondence between current and new sequenceRef
1102 public void setSequenceRef(SequenceI sequenceI)
1104 if (sequenceI != null)
1106 if (sequenceRef != null)
1108 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1109 tIsDs = sequenceI.getDatasetSequence() == null;
1110 if (sequenceRef != sequenceI
1112 && sequenceRef != sequenceI.getDatasetSequence())
1114 && sequenceRef.getDatasetSequence() != sequenceI)
1115 && (!rIsDs && !tIsDs
1116 && sequenceRef.getDatasetSequence() != sequenceI
1117 .getDatasetSequence())
1118 && !sequenceRef.equals(sequenceI))
1120 // if sequenceRef isn't intersecting with sequenceI
1121 // throw away old mapping and reconstruct.
1123 if (sequenceMapping != null)
1125 sequenceMapping = null;
1126 // compactAnnotationArray();
1128 createSequenceMapping(sequenceI, 1, true);
1129 adjustForAlignment();
1133 // Mapping carried over
1134 sequenceRef = sequenceI;
1139 // No mapping exists
1140 createSequenceMapping(sequenceI, 1, true);
1141 adjustForAlignment();
1146 // throw away the mapping without compacting.
1147 sequenceMapping = null;
1155 public double getScore()
1164 public void setScore(double score)
1172 * @return true if annotation has an associated score
1174 public boolean hasScore()
1176 return hasScore || !Double.isNaN(score);
1180 * Score only annotation
1183 * @param description
1186 public AlignmentAnnotation(String label, String description, double score)
1188 this(label, description, null);
1193 * copy constructor with edit based on the hidden columns marked in colSel
1195 * @param alignmentAnnotation
1198 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1199 HiddenColumns hidden)
1201 this(alignmentAnnotation);
1202 if (annotations == null)
1206 makeVisibleAnnotation(hidden);
1209 public void setPadGaps(boolean padgaps, char gapchar)
1211 this.padGaps = padgaps;
1215 for (int i = 0; i < annotations.length; i++)
1217 if (annotations[i] == null)
1219 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1222 else if (annotations[i].displayCharacter == null
1223 || annotations[i].displayCharacter.equals(" "))
1225 annotations[i].displayCharacter = String.valueOf(gapchar);
1232 * format description string for display
1235 * @return Get the annotation description string optionally prefixed by
1236 * associated sequence name (if any)
1238 public String getDescription(boolean seqname)
1240 if (seqname && this.sequenceRef != null)
1242 int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1245 // move the html tag to before the sequence reference.
1246 return "<html>" + sequenceRef.getName() + " : "
1247 + description.substring(i + 6);
1249 return sequenceRef.getName() + " : " + description;
1254 public boolean isValidStruc()
1256 return invalidrnastruc == -1;
1259 public long getInvalidStrucPos()
1261 return invalidrnastruc;
1265 * machine readable ID string indicating what generated this annotation
1267 protected String calcId = "";
1270 * properties associated with the calcId
1272 protected Map<String, String> properties = new HashMap<>();
1275 * base colour for line graphs. If null, will be set automatically by
1276 * searching the alignment annotation
1278 public java.awt.Color _linecolour;
1280 public String getCalcId()
1285 public void setCalcId(String calcId)
1287 this.calcId = calcId;
1290 public boolean isRNA()
1296 * transfer annotation to the given sequence using the given mapping from the
1297 * current positions or an existing sequence mapping
1301 * map involving sq as To or From
1303 public void liftOver(SequenceI sq, Mapping sp2sq)
1305 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1307 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1308 // Protein reference frames
1310 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1312 boolean mapIsTo = (sp2sq != null)
1313 ? (sp2sq.getTo() == sq
1314 || sp2sq.getTo() == sq.getDatasetSequence())
1317 // TODO build a better annotation element map and get rid of annotations[]
1318 Map<Integer, Annotation> mapForsq = new HashMap<>();
1319 if (sequenceMapping != null)
1323 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1325 Integer mpos = Integer
1326 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1327 : sp2sq.getPosition(ie.getKey()));
1328 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1330 mapForsq.put(mpos, ie.getValue());
1333 sequenceMapping = mapForsq;
1335 adjustForAlignment();
1345 * like liftOver but more general.
1347 * Takes an array of int pairs that will be used to update the internal
1348 * sequenceMapping and so shuffle the annotated positions
1351 * - new sequence reference for the annotation row - if null,
1352 * sequenceRef is left unchanged
1354 * array of ints containing corresponding positions
1356 * - column for current coordinate system (-1 for index+1)
1358 * - column for destination coordinate system (-1 for index+1)
1360 * - offset added to index when referencing either coordinate system
1361 * @note no checks are made as to whether from and/or to are sensible
1362 * @note caller should add the remapped annotation to newref if they have not
1365 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1366 int from, int to, int idxoffset)
1368 if (mapping != null)
1370 Map<Integer, Annotation> old = sequenceMapping;
1371 Map<Integer, Annotation> remap = new HashMap<>();
1373 for (int mp[] : mapping.values())
1379 Annotation ann = null;
1382 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1386 if (mp != null && mp.length > from)
1388 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1395 remap.put(Integer.valueOf(idxoffset + index), ann);
1399 if (to > -1 && to < mp.length)
1401 remap.put(Integer.valueOf(mp[to]), ann);
1406 sequenceMapping = remap;
1410 sequenceRef = newref;
1412 adjustForAlignment();
1416 public String getProperty(String property)
1418 if (properties == null)
1422 return properties.get(property);
1425 public void setProperty(String property, String value)
1427 if (properties == null)
1429 properties = new HashMap<>();
1431 properties.put(property, value);
1434 public boolean hasProperties()
1436 return properties != null && properties.size() > 0;
1439 public Collection<String> getProperties()
1441 if (properties == null)
1443 return Collections.emptyList();
1445 return properties.keySet();
1449 * Returns the Annotation for the given sequence position (base 1) if any,
1455 public Annotation getAnnotationForPosition(int position)
1457 return sequenceMapping == null ? null : sequenceMapping.get(position);
1462 * Set the id to "ann" followed by a counter that increments so as to be
1463 * unique for the lifetime of the JVM
1465 protected final void setAnnotationId()
1467 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1471 * Returns the match for the last unmatched opening RNA helix pair symbol
1472 * preceding the given column, or '(' if nothing found to match.
1477 public String getDefaultRnaHelixSymbol(int column)
1479 String result = "(";
1480 if (annotations == null)
1486 * for each preceding column, if it contains an open bracket,
1487 * count whether it is still unmatched at column, if so return its pair
1488 * (likely faster than the fancy alternative using stacks)
1490 for (int col = column - 1; col >= 0; col--)
1492 Annotation annotation = annotations[col];
1493 if (annotation == null)
1497 String displayed = annotation.displayCharacter;
1498 if (displayed == null || displayed.length() != 1)
1502 char symbol = displayed.charAt(0);
1503 if (!Rna.isOpeningParenthesis(symbol))
1509 * found an opening bracket symbol
1510 * count (closing-opening) symbols of this type that follow it,
1511 * up to and excluding the target column; if the count is less
1512 * than 1, the opening bracket is unmatched, so return its match
1514 String closer = String
1515 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1516 String opener = String.valueOf(symbol);
1518 for (int j = col + 1; j < column; j++)
1520 if (annotations[j] != null)
1522 String s = annotations[j].displayCharacter;
1523 if (closer.equals(s))
1527 else if (opener.equals(s))
1541 protected static synchronized long nextId()
1548 * @return true for rows that have a range of values in their annotation set
1550 public boolean isQuantitative()
1552 return graphMin < graphMax;
1556 * delete any columns in alignmentAnnotation that are hidden (including
1557 * sequence associated annotation).
1559 * @param hiddenColumns
1560 * the set of hidden columns
1562 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1564 if (annotations != null)
1566 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1571 * delete any columns in alignmentAnnotation that are hidden (including
1572 * sequence associated annotation).
1575 * remove any annotation to the right of this column
1577 * remove any annotation to the left of this column
1578 * @param hiddenColumns
1579 * the set of hidden columns
1581 public void makeVisibleAnnotation(int start, int end,
1582 HiddenColumns hiddenColumns)
1584 if (annotations != null)
1586 if (hiddenColumns.hasHiddenColumns())
1588 removeHiddenAnnotation(start, end, hiddenColumns);
1592 restrict(start, end);
1598 * The actual implementation of deleting hidden annotation columns
1601 * remove any annotation to the right of this column
1603 * remove any annotation to the left of this column
1604 * @param hiddenColumns
1605 * the set of hidden columns
1607 private void removeHiddenAnnotation(int start, int end,
1608 HiddenColumns hiddenColumns)
1610 // mangle the alignmentAnnotation annotation array
1611 ArrayList<Annotation[]> annels = new ArrayList<>();
1612 Annotation[] els = null;
1616 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1620 int annotationLength;
1621 while (blocks.hasNext())
1623 int[] block = blocks.next();
1624 annotationLength = block[1] - block[0] + 1;
1626 if (blocks.hasNext())
1628 // copy just the visible segment of the annotation row
1629 copylength = annotationLength;
1633 if (annotationLength + block[0] <= annotations.length)
1635 // copy just the visible segment of the annotation row
1636 copylength = annotationLength;
1640 // copy to the end of the annotation row
1641 copylength = annotations.length - block[0];
1645 els = new Annotation[annotationLength];
1647 System.arraycopy(annotations, block[0], els, 0, copylength);
1648 w += annotationLength;
1653 annotations = new Annotation[w];
1656 for (Annotation[] chnk : annels)
1658 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1664 public static Iterable<AlignmentAnnotation> findAnnotations(
1665 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1669 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1670 for (AlignmentAnnotation ann : list)
1672 if ((calcId == null || (ann.getCalcId() != null
1673 && ann.getCalcId().equals(calcId)))
1674 && (seq == null || (ann.sequenceRef != null
1675 && ann.sequenceRef == seq))
1677 || (ann.label != null && ann.label.equals(label))))
1686 * Answer true if any annotation matches the calcId passed in (if not null).
1689 * annotation to search
1693 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1697 if (calcId != null && !"".equals(calcId))
1699 for (AlignmentAnnotation a : list)
1701 if (a.getCalcId() == calcId)
1710 public static Iterable<AlignmentAnnotation> findAnnotation(
1711 List<AlignmentAnnotation> list, String calcId)
1714 List<AlignmentAnnotation> aa = new ArrayList<>();
1719 for (AlignmentAnnotation a : list)
1722 if (a.getCalcId() == calcId || (a.getCalcId() != null
1723 && calcId != null && a.getCalcId().equals(calcId)))