2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.datamodel;
23 import jalview.analysis.Rna;
24 import jalview.analysis.SecStrConsensus.SimpleBP;
25 import jalview.analysis.WUSSParseException;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.Map.Entry;
43 public class AlignmentAnnotation
45 private static final String ANNOTATION_ID_PREFIX = "ann";
48 * Identifers for different types of profile data
50 public static final int SEQUENCE_PROFILE = 0;
52 public static final int STRUCTURE_PROFILE = 1;
54 public static final int CDNA_PROFILE = 2;
56 private static long counter = 0;
59 * If true, this annotations is calculated every edit, eg consensus, quality
60 * or conservation graphs
62 public boolean autoCalculated = false;
65 * unique ID for this annotation, used to match up the same annotation row
66 * shown in multiple views and alignments
68 public String annotationId;
71 * the sequence this annotation is associated with (or null)
73 public SequenceI sequenceRef;
75 /** label shown in dropdown menus and in the annotation label area */
78 /** longer description text shown as a tooltip */
79 public String description;
81 /** Array of annotations placed in the current coordinate system */
82 public Annotation[] annotations;
84 public List<SimpleBP> bps = null;
87 * RNA secondary structure contact positions
89 public SequenceFeature[] _rnasecstr = null;
92 * position of annotation resulting in invalid WUSS parsing or -1. -2 means
93 * there was no RNA structure in this annotation
95 private long invalidrnastruc = -2;
98 * Updates the _rnasecstr field Determines the positions that base pair and
99 * the positions of helices based on secondary structure from a Stockholm file
101 * @param rnaAnnotation
103 private void _updateRnaSecStr(CharSequence rnaAnnotation)
107 _rnasecstr = Rna.getHelixMap(rnaAnnotation);
108 invalidrnastruc = -1;
109 } catch (WUSSParseException px)
111 // DEBUG System.out.println(px);
112 invalidrnastruc = px.getProblemPos();
114 if (invalidrnastruc > -1)
119 if (_rnasecstr != null && _rnasecstr.length > 0)
121 // show all the RNA secondary structure annotation symbols.
123 showAllColLabels = true;
124 scaleColLabel = true;
127 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
131 private void _markRnaHelices()
134 // Figure out number of helices
135 // Length of rnasecstr is the number of pairs of positions that base pair
136 // with each other in the secondary structure
137 for (int x = 0; x < _rnasecstr.length; x++)
141 * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
142 * this.annotation._rnasecstr[x].getBegin());
144 // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
148 val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
153 } catch (NumberFormatException q)
158 annotations[_rnasecstr[x].getBegin()].value = val;
159 annotations[_rnasecstr[x].getEnd()].value = val;
161 // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
162 // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
168 * Get the RNA Secondary Structure SequenceFeature Array if present
170 public SequenceFeature[] getRnaSecondaryStructure()
172 return this._rnasecstr;
176 * Check the RNA Secondary Structure is equivalent to one in given
177 * AlignmentAnnotation param
179 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that)
181 return rnaSecondaryStructureEquivalent(that, true);
184 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that, boolean compareType)
186 SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
187 SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
188 if (thisSfArray == null || thatSfArray == null)
190 return thisSfArray == null && thatSfArray == null;
192 if (thisSfArray.length != thatSfArray.length)
196 Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
198 Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
200 for (int i=0; i < thisSfArray.length; i++) {
201 SequenceFeature thisSf = thisSfArray[i];
202 SequenceFeature thatSf = thatSfArray[i];
204 if (thisSf.getType() == null || thatSf.getType() == null) {
205 if (thisSf.getType() == null && thatSf.getType() == null) {
211 if (! thisSf.getType().equals(thatSf.getType())) {
215 if (!(thisSf.getBegin() == thatSf.getBegin()
216 && thisSf.getEnd() == thatSf.getEnd()))
226 * map of positions in the associated annotation
228 private Map<Integer, Annotation> sequenceMapping;
231 * lower range for quantitative data
233 public float graphMin;
236 * Upper range for quantitative data
238 public float graphMax;
241 * Score associated with label and description.
243 public double score = Double.NaN;
246 * flag indicating if annotation has a score.
248 public boolean hasScore = false;
250 public GraphLine threshold;
252 // Graphical hints and tips
254 /** Can this row be edited by the user ? */
255 public boolean editable = false;
257 /** Indicates if annotation has a graphical symbol track */
258 public boolean hasIcons; //
260 /** Indicates if annotation has a text character label */
261 public boolean hasText;
263 /** is the row visible */
264 public boolean visible = true;
266 public int graphGroup = -1;
268 /** Displayed height of row in pixels */
269 public int height = 0;
271 public int graph = 0;
273 public int graphHeight = 40;
275 public boolean padGaps = false;
277 public static final int NO_GRAPH = 0;
279 public static final int BAR_GRAPH = 1;
281 public static final int LINE_GRAPH = 2;
283 public boolean belowAlignment = true;
285 public SequenceGroup groupRef = null;
288 * display every column label, even if there is a row of identical labels
290 public boolean showAllColLabels = false;
293 * scale the column label to fit within the alignment column.
295 public boolean scaleColLabel = false;
298 * centre the column labels relative to the alignment column
300 public boolean centreColLabels = false;
302 private boolean isrna;
304 public static int getGraphValueFromString(String string)
306 if (string.equalsIgnoreCase("BAR_GRAPH"))
310 else if (string.equalsIgnoreCase("LINE_GRAPH"))
321 * Creates a new AlignmentAnnotation object.
324 * short label shown under sequence labels
326 * text displayed on mouseover
328 * set of positional annotation elements
330 public AlignmentAnnotation(String label, String description,
331 Annotation[] annotations)
337 this.description = description;
338 this.annotations = annotations;
340 validateRangeAndDisplay();
344 * Checks if annotation labels represent secondary structures
347 void areLabelsSecondaryStructure()
349 boolean nonSSLabel = false;
351 StringBuffer rnastring = new StringBuffer();
354 for (int i = 0; i < annotations.length; i++)
356 // DEBUG System.out.println(i + ": " + annotations[i]);
357 if (annotations[i] == null)
361 if (annotations[i].secondaryStructure == 'H'
362 || annotations[i].secondaryStructure == 'E')
364 // DEBUG System.out.println( "/H|E/ '" +
365 // annotations[i].secondaryStructure + "'");
369 // Check for RNA secondary structure
371 // DEBUG System.out.println( "/else/ '" +
372 // annotations[i].secondaryStructure + "'");
373 // TODO: 2.8.2 should this ss symbol validation check be a function in
374 // RNA/ResidueProperties ?
375 if (annotations[i].secondaryStructure == '('
376 || annotations[i].secondaryStructure == '['
377 || annotations[i].secondaryStructure == '<'
378 || annotations[i].secondaryStructure == '{'
379 || annotations[i].secondaryStructure == 'A'
380 || annotations[i].secondaryStructure == 'B'
381 || annotations[i].secondaryStructure == 'C'
382 || annotations[i].secondaryStructure == 'D'
383 // || annotations[i].secondaryStructure == 'E' // ambiguous on
384 // its own -- already checked above
385 || annotations[i].secondaryStructure == 'F'
386 || annotations[i].secondaryStructure == 'G'
387 // || annotations[i].secondaryStructure == 'H' // ambiguous on
388 // its own -- already checked above
389 || annotations[i].secondaryStructure == 'I'
390 || annotations[i].secondaryStructure == 'J'
391 || annotations[i].secondaryStructure == 'K'
392 || annotations[i].secondaryStructure == 'L'
393 || annotations[i].secondaryStructure == 'M'
394 || annotations[i].secondaryStructure == 'N'
395 || annotations[i].secondaryStructure == 'O'
396 || annotations[i].secondaryStructure == 'P'
397 || annotations[i].secondaryStructure == 'Q'
398 || annotations[i].secondaryStructure == 'R'
399 || annotations[i].secondaryStructure == 'S'
400 || annotations[i].secondaryStructure == 'T'
401 || annotations[i].secondaryStructure == 'U'
402 || annotations[i].secondaryStructure == 'V'
403 || annotations[i].secondaryStructure == 'W'
404 || annotations[i].secondaryStructure == 'X'
405 || annotations[i].secondaryStructure == 'Y'
406 || annotations[i].secondaryStructure == 'Z')
413 // System.out.println("displaychar " + annotations[i].displayCharacter);
415 if (annotations[i].displayCharacter == null
416 || annotations[i].displayCharacter.length() == 0)
418 rnastring.append('.');
421 if (annotations[i].displayCharacter.length() == 1)
423 firstChar = annotations[i].displayCharacter.charAt(0);
424 // check to see if it looks like a sequence or is secondary structure
426 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
427 // Uncomment to only catch case where
428 // displayCharacter==secondary
430 // to correctly redisplay SS annotation imported from Stockholm,
431 // exported to JalviewXML and read back in again.
433 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
434 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
435 && firstChar != '(' && firstChar != '[' && firstChar != '<'
436 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
437 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
438 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
439 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
440 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
441 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
442 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
443 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
444 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
446 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
448 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
461 rnastring.append(annotations[i].displayCharacter.charAt(1));
464 if (annotations[i].displayCharacter.length() > 0)
473 for (int j = 0; j < annotations.length; j++)
475 if (annotations[j] != null
476 && annotations[j].secondaryStructure != ' ')
478 annotations[j].displayCharacter = String
479 .valueOf(annotations[j].secondaryStructure);
480 annotations[j].secondaryStructure = ' ';
489 _updateRnaSecStr(new AnnotCharSequence());
495 * flyweight access to positions in the alignment annotation row for RNA
501 private class AnnotCharSequence implements CharSequence
507 public AnnotCharSequence()
509 this(0, annotations.length);
512 AnnotCharSequence(int start, int end)
519 public CharSequence subSequence(int start, int end)
521 return new AnnotCharSequence(offset + start, offset + end);
531 public char charAt(int index)
533 return ((index + offset < 0) || (index + offset) >= max
534 || annotations[index + offset] == null
535 || (annotations[index + offset].secondaryStructure <= ' ')
537 : annotations[index + offset].displayCharacter == null
539 + offset].displayCharacter
542 + offset].secondaryStructure
544 + offset].displayCharacter
549 public String toString()
551 char[] string = new char[max - offset];
552 int mx = annotations.length;
554 for (int i = offset; i < mx; i++)
556 string[i] = (annotations[i] == null
557 || (annotations[i].secondaryStructure <= 32))
559 : (annotations[i].displayCharacter == null
560 || annotations[i].displayCharacter
562 ? annotations[i].secondaryStructure
563 : annotations[i].displayCharacter
566 return new String(string);
570 private long _lastrnaannot = -1;
572 public String getRNAStruc()
576 String rnastruc = new AnnotCharSequence().toString();
577 if (_lastrnaannot != rnastruc.hashCode())
579 // ensure rna structure contacts are up to date
580 _lastrnaannot = rnastruc.hashCode();
581 _updateRnaSecStr(rnastruc);
589 * Creates a new AlignmentAnnotation object.
604 public AlignmentAnnotation(String label, String description,
605 Annotation[] annotations, float min, float max, int graphType)
608 // graphs are not editable
609 editable = graphType == 0;
612 this.description = description;
613 this.annotations = annotations;
617 validateRangeAndDisplay();
621 * checks graphMin and graphMax, secondary structure symbols, sets graphType
622 * appropriately, sets null labels to the empty string if appropriate.
624 public void validateRangeAndDisplay()
627 if (annotations == null)
629 visible = false; // try to prevent renderer from displaying.
630 invalidrnastruc = -1;
631 return; // this is a non-annotation row annotation - ie a sequence score.
634 int graphType = graph;
635 float min = graphMin;
636 float max = graphMax;
637 boolean drawValues = true;
642 for (int i = 0; i < annotations.length; i++)
644 if (annotations[i] == null)
649 if (drawValues && annotations[i].displayCharacter != null
650 && annotations[i].displayCharacter.length() > 1)
655 if (annotations[i].value > max)
657 max = annotations[i].value;
660 if (annotations[i].value < min)
662 min = annotations[i].value;
664 if (_linecolour == null && annotations[i].colour != null)
666 _linecolour = annotations[i].colour;
669 // ensure zero is origin for min/max ranges on only one side of zero
686 areLabelsSecondaryStructure();
688 if (!drawValues && graphType != NO_GRAPH)
690 for (int i = 0; i < annotations.length; i++)
692 if (annotations[i] != null)
694 annotations[i].displayCharacter = "";
701 * Copy constructor creates a new independent annotation row with the same
702 * associated sequenceRef
706 public AlignmentAnnotation(AlignmentAnnotation annotation)
709 this.label = new String(annotation.label);
710 if (annotation.description != null)
712 this.description = new String(annotation.description);
714 this.graphMin = annotation.graphMin;
715 this.graphMax = annotation.graphMax;
716 this.graph = annotation.graph;
717 this.graphHeight = annotation.graphHeight;
718 this.graphGroup = annotation.graphGroup;
719 this.groupRef = annotation.groupRef;
720 this.editable = annotation.editable;
721 this.autoCalculated = annotation.autoCalculated;
722 this.hasIcons = annotation.hasIcons;
723 this.hasText = annotation.hasText;
724 this.height = annotation.height;
725 this.label = annotation.label;
726 this.padGaps = annotation.padGaps;
727 this.visible = annotation.visible;
728 this.centreColLabels = annotation.centreColLabels;
729 this.scaleColLabel = annotation.scaleColLabel;
730 this.showAllColLabels = annotation.showAllColLabels;
731 this.calcId = annotation.calcId;
732 if (annotation.properties != null)
734 properties = new HashMap<>();
735 for (Map.Entry<String, String> val : annotation.properties.entrySet())
737 properties.put(val.getKey(), val.getValue());
740 if (this.hasScore = annotation.hasScore)
742 this.score = annotation.score;
744 if (annotation.threshold != null)
746 threshold = new GraphLine(annotation.threshold);
748 Annotation[] ann = annotation.annotations;
749 if (annotation.annotations != null)
751 this.annotations = new Annotation[ann.length];
752 for (int i = 0; i < ann.length; i++)
756 annotations[i] = new Annotation(ann[i]);
757 if (_linecolour != null)
759 _linecolour = annotations[i].colour;
764 if (annotation.sequenceRef != null)
766 this.sequenceRef = annotation.sequenceRef;
767 if (annotation.sequenceMapping != null)
770 sequenceMapping = new HashMap<>();
771 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
773 while (pos.hasNext())
775 // could optimise this!
777 Annotation a = annotation.sequenceMapping.get(p);
784 for (int i = 0; i < ann.length; i++)
788 sequenceMapping.put(p, annotations[i]);
796 this.sequenceMapping = null;
799 // TODO: check if we need to do this: JAL-952
800 // if (this.isrna=annotation.isrna)
802 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
804 validateRangeAndDisplay(); // construct hashcodes, etc.
808 * clip the annotation to the columns given by startRes and endRes (inclusive)
809 * and prune any existing sequenceMapping to just those columns.
814 public void restrict(int startRes, int endRes)
816 if (annotations == null)
825 if (startRes >= annotations.length)
827 startRes = annotations.length - 1;
829 if (endRes >= annotations.length)
831 endRes = annotations.length - 1;
833 if (annotations == null)
837 Annotation[] temp = new Annotation[endRes - startRes + 1];
838 if (startRes < annotations.length)
840 System.arraycopy(annotations, startRes, temp, 0,
841 endRes - startRes + 1);
843 if (sequenceRef != null)
845 // Clip the mapping, if it exists.
846 int spos = sequenceRef.findPosition(startRes);
847 int epos = sequenceRef.findPosition(endRes);
848 if (sequenceMapping != null)
850 Map<Integer, Annotation> newmapping = new HashMap<>();
851 Iterator<Integer> e = sequenceMapping.keySet().iterator();
854 Integer pos = e.next();
855 if (pos.intValue() >= spos && pos.intValue() <= epos)
857 newmapping.put(pos, sequenceMapping.get(pos));
860 sequenceMapping.clear();
861 sequenceMapping = newmapping;
868 * set the annotation row to be at least length Annotations
871 * minimum number of columns required in the annotation row
872 * @return false if the annotation row is greater than length
874 public boolean padAnnotation(int length)
876 if (annotations == null)
878 return true; // annotation row is correct - null == not visible and
881 if (annotations.length < length)
883 Annotation[] na = new Annotation[length];
884 System.arraycopy(annotations, 0, na, 0, annotations.length);
888 return annotations.length > length;
895 * @return DOCUMENT ME!
898 public String toString()
900 if (annotations == null)
904 StringBuilder buffer = new StringBuilder(256);
906 for (int i = 0; i < annotations.length; i++)
908 if (annotations[i] != null)
912 buffer.append(annotations[i].value);
916 buffer.append(annotations[i].secondaryStructure);
920 buffer.append(annotations[i].displayCharacter);
926 // TODO: remove disgusting hack for 'special' treatment of consensus line.
927 if (label.indexOf("Consensus") == 0)
931 for (int i = 0; i < annotations.length; i++)
933 if (annotations[i] != null)
935 buffer.append(annotations[i].description);
942 return buffer.toString();
945 public void setThreshold(GraphLine line)
950 public GraphLine getThreshold()
956 * Attach the annotation to seqRef, starting from startRes position. If
957 * alreadyMapped is true then the indices of the annotation[] array are
958 * sequence positions rather than alignment column positions.
962 * @param alreadyMapped
964 public void createSequenceMapping(SequenceI seqRef, int startRes,
965 boolean alreadyMapped)
972 sequenceRef = seqRef;
973 if (annotations == null)
977 sequenceMapping = new HashMap<>();
981 for (int i = 0; i < annotations.length; i++)
983 if (annotations[i] != null)
987 seqPos = seqRef.findPosition(i);
991 seqPos = i + startRes;
994 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1001 * When positional annotation and a sequence reference is present, clears and
1002 * resizes the annotations array to the current alignment width, and adds
1003 * annotation according to aligned positions of the sequenceRef given by
1006 public void adjustForAlignment()
1008 if (sequenceRef == null)
1013 if (annotations == null)
1018 int a = 0, aSize = sequenceRef.getLength();
1027 Annotation[] temp = new Annotation[aSize];
1029 if (sequenceMapping != null)
1031 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1033 index = Integer.valueOf(a);
1034 Annotation annot = sequenceMapping.get(index);
1037 position = sequenceRef.findIndex(a) - 1;
1039 temp[position] = annot;
1047 * remove any null entries in annotation row and return the number of non-null
1048 * annotation elements.
1052 public int compactAnnotationArray()
1054 int i = 0, iSize = annotations.length;
1057 if (annotations[i] == null)
1061 System.arraycopy(annotations, i + 1, annotations, i,
1071 Annotation[] ann = annotations;
1072 annotations = new Annotation[i];
1073 System.arraycopy(ann, 0, annotations, 0, i);
1079 * Associate this annotation with the aligned residues of a particular
1080 * sequence. sequenceMapping will be updated in the following way: null
1081 * sequenceI - existing mapping will be discarded but annotations left in
1082 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1083 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1084 * parameter to specify correspondence between current and new sequenceRef
1088 public void setSequenceRef(SequenceI sequenceI)
1090 if (sequenceI != null)
1092 if (sequenceRef != null)
1094 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1095 tIsDs = sequenceI.getDatasetSequence() == null;
1096 if (sequenceRef != sequenceI
1098 && sequenceRef != sequenceI.getDatasetSequence())
1100 && sequenceRef.getDatasetSequence() != sequenceI)
1101 && (!rIsDs && !tIsDs
1102 && sequenceRef.getDatasetSequence() != sequenceI
1103 .getDatasetSequence())
1104 && !sequenceRef.equals(sequenceI))
1106 // if sequenceRef isn't intersecting with sequenceI
1107 // throw away old mapping and reconstruct.
1109 if (sequenceMapping != null)
1111 sequenceMapping = null;
1112 // compactAnnotationArray();
1114 createSequenceMapping(sequenceI, 1, true);
1115 adjustForAlignment();
1119 // Mapping carried over
1120 sequenceRef = sequenceI;
1125 // No mapping exists
1126 createSequenceMapping(sequenceI, 1, true);
1127 adjustForAlignment();
1132 // throw away the mapping without compacting.
1133 sequenceMapping = null;
1141 public double getScore()
1150 public void setScore(double score)
1158 * @return true if annotation has an associated score
1160 public boolean hasScore()
1162 return hasScore || !Double.isNaN(score);
1166 * Score only annotation
1169 * @param description
1172 public AlignmentAnnotation(String label, String description, double score)
1174 this(label, description, null);
1179 * copy constructor with edit based on the hidden columns marked in colSel
1181 * @param alignmentAnnotation
1184 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1185 HiddenColumns hidden)
1187 this(alignmentAnnotation);
1188 if (annotations == null)
1192 makeVisibleAnnotation(hidden);
1195 public void setPadGaps(boolean padgaps, char gapchar)
1197 this.padGaps = padgaps;
1201 for (int i = 0; i < annotations.length; i++)
1203 if (annotations[i] == null)
1205 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1208 else if (annotations[i].displayCharacter == null
1209 || annotations[i].displayCharacter.equals(" "))
1211 annotations[i].displayCharacter = String.valueOf(gapchar);
1218 * format description string for display
1221 * @return Get the annotation description string optionally prefixed by
1222 * associated sequence name (if any)
1224 public String getDescription(boolean seqname)
1226 if (seqname && this.sequenceRef != null)
1228 int i = description.toLowerCase().indexOf("<html>");
1231 // move the html tag to before the sequence reference.
1232 return "<html>" + sequenceRef.getName() + " : "
1233 + description.substring(i + 6);
1235 return sequenceRef.getName() + " : " + description;
1240 public boolean isValidStruc()
1242 return invalidrnastruc == -1;
1245 public long getInvalidStrucPos()
1247 return invalidrnastruc;
1251 * machine readable ID string indicating what generated this annotation
1253 protected String calcId = "";
1256 * properties associated with the calcId
1258 protected Map<String, String> properties = new HashMap<>();
1261 * base colour for line graphs. If null, will be set automatically by
1262 * searching the alignment annotation
1264 public java.awt.Color _linecolour;
1266 public String getCalcId()
1271 public void setCalcId(String calcId)
1273 this.calcId = calcId;
1276 public boolean isRNA()
1282 * transfer annotation to the given sequence using the given mapping from the
1283 * current positions or an existing sequence mapping
1287 * map involving sq as To or From
1289 public void liftOver(SequenceI sq, Mapping sp2sq)
1291 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1293 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1294 // Protein reference frames
1296 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1298 boolean mapIsTo = (sp2sq != null)
1299 ? (sp2sq.getTo() == sq
1300 || sp2sq.getTo() == sq.getDatasetSequence())
1303 // TODO build a better annotation element map and get rid of annotations[]
1304 Map<Integer, Annotation> mapForsq = new HashMap<>();
1305 if (sequenceMapping != null)
1309 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1311 Integer mpos = Integer
1312 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1313 : sp2sq.getPosition(ie.getKey()));
1314 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1316 mapForsq.put(mpos, ie.getValue());
1319 sequenceMapping = mapForsq;
1321 adjustForAlignment();
1331 * like liftOver but more general.
1333 * Takes an array of int pairs that will be used to update the internal
1334 * sequenceMapping and so shuffle the annotated positions
1337 * - new sequence reference for the annotation row - if null,
1338 * sequenceRef is left unchanged
1340 * array of ints containing corresponding positions
1342 * - column for current coordinate system (-1 for index+1)
1344 * - column for destination coordinate system (-1 for index+1)
1346 * - offset added to index when referencing either coordinate system
1347 * @note no checks are made as to whether from and/or to are sensible
1348 * @note caller should add the remapped annotation to newref if they have not
1351 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1352 int from, int to, int idxoffset)
1354 if (mapping != null)
1356 Map<Integer, Annotation> old = sequenceMapping;
1357 Map<Integer, Annotation> remap = new HashMap<>();
1359 for (int mp[] : mapping.values())
1365 Annotation ann = null;
1368 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1372 if (mp != null && mp.length > from)
1374 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1381 remap.put(Integer.valueOf(idxoffset + index), ann);
1385 if (to > -1 && to < mp.length)
1387 remap.put(Integer.valueOf(mp[to]), ann);
1392 sequenceMapping = remap;
1396 sequenceRef = newref;
1398 adjustForAlignment();
1402 public String getProperty(String property)
1404 if (properties == null)
1408 return properties.get(property);
1411 public void setProperty(String property, String value)
1413 if (properties == null)
1415 properties = new HashMap<>();
1417 properties.put(property, value);
1420 public boolean hasProperties()
1422 return properties != null && properties.size() > 0;
1425 public Collection<String> getProperties()
1427 if (properties == null)
1429 return Collections.emptyList();
1431 return properties.keySet();
1435 * Returns the Annotation for the given sequence position (base 1) if any,
1441 public Annotation getAnnotationForPosition(int position)
1443 return sequenceMapping == null ? null : sequenceMapping.get(position);
1448 * Set the id to "ann" followed by a counter that increments so as to be
1449 * unique for the lifetime of the JVM
1451 protected final void setAnnotationId()
1453 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1457 * Returns the match for the last unmatched opening RNA helix pair symbol
1458 * preceding the given column, or '(' if nothing found to match.
1463 public String getDefaultRnaHelixSymbol(int column)
1465 String result = "(";
1466 if (annotations == null)
1472 * for each preceding column, if it contains an open bracket,
1473 * count whether it is still unmatched at column, if so return its pair
1474 * (likely faster than the fancy alternative using stacks)
1476 for (int col = column - 1; col >= 0; col--)
1478 Annotation annotation = annotations[col];
1479 if (annotation == null)
1483 String displayed = annotation.displayCharacter;
1484 if (displayed == null || displayed.length() != 1)
1488 char symbol = displayed.charAt(0);
1489 if (!Rna.isOpeningParenthesis(symbol))
1495 * found an opening bracket symbol
1496 * count (closing-opening) symbols of this type that follow it,
1497 * up to and excluding the target column; if the count is less
1498 * than 1, the opening bracket is unmatched, so return its match
1500 String closer = String
1501 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1502 String opener = String.valueOf(symbol);
1504 for (int j = col + 1; j < column; j++)
1506 if (annotations[j] != null)
1508 String s = annotations[j].displayCharacter;
1509 if (closer.equals(s))
1513 else if (opener.equals(s))
1527 protected static synchronized long nextId()
1534 * @return true for rows that have a range of values in their annotation set
1536 public boolean isQuantitative()
1538 return graphMin < graphMax;
1542 * delete any columns in alignmentAnnotation that are hidden (including
1543 * sequence associated annotation).
1545 * @param hiddenColumns
1546 * the set of hidden columns
1548 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1550 if (annotations != null)
1552 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1557 * delete any columns in alignmentAnnotation that are hidden (including
1558 * sequence associated annotation).
1561 * remove any annotation to the right of this column
1563 * remove any annotation to the left of this column
1564 * @param hiddenColumns
1565 * the set of hidden columns
1567 public void makeVisibleAnnotation(int start, int end,
1568 HiddenColumns hiddenColumns)
1570 if (annotations != null)
1572 if (hiddenColumns.hasHiddenColumns())
1574 removeHiddenAnnotation(start, end, hiddenColumns);
1578 restrict(start, end);
1584 * The actual implementation of deleting hidden annotation columns
1587 * remove any annotation to the right of this column
1589 * remove any annotation to the left of this column
1590 * @param hiddenColumns
1591 * the set of hidden columns
1593 private void removeHiddenAnnotation(int start, int end,
1594 HiddenColumns hiddenColumns)
1596 // mangle the alignmentAnnotation annotation array
1597 ArrayList<Annotation[]> annels = new ArrayList<>();
1598 Annotation[] els = null;
1602 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1606 int annotationLength;
1607 while (blocks.hasNext())
1609 int[] block = blocks.next();
1610 annotationLength = block[1] - block[0] + 1;
1612 if (blocks.hasNext())
1614 // copy just the visible segment of the annotation row
1615 copylength = annotationLength;
1619 if (annotationLength + block[0] <= annotations.length)
1621 // copy just the visible segment of the annotation row
1622 copylength = annotationLength;
1626 // copy to the end of the annotation row
1627 copylength = annotations.length - block[0];
1631 els = new Annotation[annotationLength];
1633 System.arraycopy(annotations, block[0], els, 0, copylength);
1634 w += annotationLength;
1639 annotations = new Annotation[w];
1642 for (Annotation[] chnk : annels)
1644 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1650 public static Iterable<AlignmentAnnotation> findAnnotations(
1651 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1655 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1656 for (AlignmentAnnotation ann : list)
1658 if ((calcId == null || (ann.getCalcId() != null
1659 && ann.getCalcId().equals(calcId)))
1660 && (seq == null || (ann.sequenceRef != null
1661 && ann.sequenceRef == seq))
1663 || (ann.label != null && ann.label.equals(label))))
1672 * Answer true if any annotation matches the calcId passed in (if not null).
1675 * annotation to search
1679 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1683 if (calcId != null && !"".equals(calcId))
1685 for (AlignmentAnnotation a : list)
1687 if (a.getCalcId() == calcId)
1696 public static Iterable<AlignmentAnnotation> findAnnotation(
1697 List<AlignmentAnnotation> list, String calcId)
1700 List<AlignmentAnnotation> aa = new ArrayList<>();
1705 for (AlignmentAnnotation a : list)
1708 if (a.getCalcId() == calcId || (a.getCalcId() != null
1709 && calcId != null && a.getCalcId().equals(calcId)))