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 * Copy constructor creates a new independent annotation row with the same
345 * associated sequenceRef
349 public AlignmentAnnotation(AlignmentAnnotation annotation)
352 this.label = new String(annotation.label);
353 if (annotation.description != null)
355 this.description = new String(annotation.description);
357 this.graphMin = annotation.graphMin;
358 this.graphMax = annotation.graphMax;
359 this.graph = annotation.graph;
360 this.graphHeight = annotation.graphHeight;
361 this.graphGroup = annotation.graphGroup;
362 this.groupRef = annotation.groupRef;
363 this.editable = annotation.editable;
364 this.autoCalculated = annotation.autoCalculated;
365 this.hasIcons = annotation.hasIcons;
366 this.hasText = annotation.hasText;
367 this.height = annotation.height;
368 this.label = annotation.label;
369 this.padGaps = annotation.padGaps;
370 this.visible = annotation.visible;
371 this.centreColLabels = annotation.centreColLabels;
372 this.scaleColLabel = annotation.scaleColLabel;
373 this.showAllColLabels = annotation.showAllColLabels;
374 this.calcId = annotation.calcId;
375 if (annotation.properties != null)
377 properties = new HashMap<>();
378 for (Map.Entry<String, String> val : annotation.properties.entrySet())
380 properties.put(val.getKey(), val.getValue());
383 if (this.hasScore = annotation.hasScore)
385 this.score = annotation.score;
387 if (annotation.threshold != null)
389 threshold = new GraphLine(annotation.threshold);
391 Annotation[] ann = annotation.annotations;
392 if (annotation.annotations != null)
394 this.annotations = new Annotation[ann.length];
395 for (int i = 0; i < ann.length; i++)
399 annotations[i] = new Annotation(ann[i]);
400 if (_linecolour != null)
402 _linecolour = annotations[i].colour;
407 if (annotation.sequenceRef != null)
409 this.sequenceRef = annotation.sequenceRef;
410 if (annotation.sequenceMapping != null)
413 sequenceMapping = new HashMap<>();
414 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
416 while (pos.hasNext())
418 // could optimise this!
420 Annotation a = annotation.sequenceMapping.get(p);
427 for (int i = 0; i < ann.length; i++)
431 sequenceMapping.put(p, annotations[i]);
439 this.sequenceMapping = null;
442 // TODO: check if we need to do this: JAL-952
443 // if (this.isrna=annotation.isrna)
445 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
447 validateRangeAndDisplay(); // construct hashcodes, etc.
451 * copy constructor with edit based on the hidden columns marked in colSel
453 * @param alignmentAnnotation
456 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
457 HiddenColumns hidden)
459 this(alignmentAnnotation);
460 if (annotations == null)
464 makeVisibleAnnotation(hidden);
468 * Creates a new AlignmentAnnotation object.
483 public AlignmentAnnotation(String label, String description,
484 Annotation[] annotations, float min, float max, int graphType)
487 // graphs are not editable
488 editable = graphType == 0;
491 this.description = description;
492 this.annotations = annotations;
496 validateRangeAndDisplay();
500 * Score only annotation
506 public AlignmentAnnotation(String label, String description, double score)
508 this(label, description, null);
513 * Updates the _rnasecstr field Determines the positions that base pair and
514 * the positions of helices based on secondary structure from a Stockholm file
516 * @param rnaAnnotation
518 private void _updateRnaSecStr(CharSequence rnaAnnotation)
522 _rnasecstr = Rna.getHelixMap(rnaAnnotation);
523 invalidrnastruc = -1;
524 } catch (WUSSParseException px)
526 // DEBUG System.out.println(px);
527 invalidrnastruc = px.getProblemPos();
529 if (invalidrnastruc > -1)
534 if (_rnasecstr != null && _rnasecstr.length > 0)
536 // show all the RNA secondary structure annotation symbols.
538 showAllColLabels = true;
539 scaleColLabel = true;
542 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
546 private void _markRnaHelices()
549 // Figure out number of helices
550 // Length of rnasecstr is the number of pairs of positions that base pair
551 // with each other in the secondary structure
552 for (int x = 0; x < _rnasecstr.length; x++)
556 * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
557 * this.annotation._rnasecstr[x].getBegin());
559 // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
563 val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
568 } catch (NumberFormatException q)
573 annotations[_rnasecstr[x].getBegin()].value = val;
574 annotations[_rnasecstr[x].getEnd()].value = val;
576 // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
577 // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
583 * Checks if annotation labels represent secondary structures
586 void areLabelsSecondaryStructure()
588 boolean nonSSLabel = false;
590 StringBuffer rnastring = new StringBuffer();
593 for (int i = 0; i < annotations.length; i++)
595 // DEBUG System.out.println(i + ": " + annotations[i]);
596 if (annotations[i] == null)
600 if (annotations[i].secondaryStructure == 'H'
601 || annotations[i].secondaryStructure == 'E')
603 // DEBUG System.out.println( "/H|E/ '" +
604 // annotations[i].secondaryStructure + "'");
608 // Check for RNA secondary structure
610 // DEBUG System.out.println( "/else/ '" +
611 // annotations[i].secondaryStructure + "'");
612 // TODO: 2.8.2 should this ss symbol validation check be a function in
613 // RNA/ResidueProperties ?
614 if (annotations[i].secondaryStructure == '('
615 || annotations[i].secondaryStructure == '['
616 || annotations[i].secondaryStructure == '<'
617 || annotations[i].secondaryStructure == '{'
618 || annotations[i].secondaryStructure == 'A'
619 || annotations[i].secondaryStructure == 'B'
620 || annotations[i].secondaryStructure == 'C'
621 || annotations[i].secondaryStructure == 'D'
622 // || annotations[i].secondaryStructure == 'E' // ambiguous on
623 // its own -- already checked above
624 || annotations[i].secondaryStructure == 'F'
625 || annotations[i].secondaryStructure == 'G'
626 // || annotations[i].secondaryStructure == 'H' // ambiguous on
627 // its own -- already checked above
628 || annotations[i].secondaryStructure == 'I'
629 || annotations[i].secondaryStructure == 'J'
630 || annotations[i].secondaryStructure == 'K'
631 || annotations[i].secondaryStructure == 'L'
632 || annotations[i].secondaryStructure == 'M'
633 || annotations[i].secondaryStructure == 'N'
634 || annotations[i].secondaryStructure == 'O'
635 || annotations[i].secondaryStructure == 'P'
636 || annotations[i].secondaryStructure == 'Q'
637 || annotations[i].secondaryStructure == 'R'
638 || annotations[i].secondaryStructure == 'S'
639 || annotations[i].secondaryStructure == 'T'
640 || annotations[i].secondaryStructure == 'U'
641 || annotations[i].secondaryStructure == 'V'
642 || annotations[i].secondaryStructure == 'W'
643 || annotations[i].secondaryStructure == 'X'
644 || annotations[i].secondaryStructure == 'Y'
645 || annotations[i].secondaryStructure == 'Z')
652 // System.out.println("displaychar " + annotations[i].displayCharacter);
654 if (annotations[i].displayCharacter == null
655 || annotations[i].displayCharacter.length() == 0)
657 rnastring.append('.');
660 if (annotations[i].displayCharacter.length() == 1)
662 firstChar = annotations[i].displayCharacter.charAt(0);
663 // check to see if it looks like a sequence or is secondary structure
665 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
666 // Uncomment to only catch case where
667 // displayCharacter==secondary
669 // to correctly redisplay SS annotation imported from Stockholm,
670 // exported to JalviewXML and read back in again.
672 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
673 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
674 && firstChar != '(' && firstChar != '[' && firstChar != '<'
675 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
676 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
677 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
678 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
679 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
680 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
681 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
682 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
683 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
685 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
687 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
700 rnastring.append(annotations[i].displayCharacter.charAt(1));
703 if (annotations[i].displayCharacter.length() > 0)
712 for (int j = 0; j < annotations.length; j++)
714 if (annotations[j] != null
715 && annotations[j].secondaryStructure != ' ')
717 annotations[j].displayCharacter = String
718 .valueOf(annotations[j].secondaryStructure);
719 annotations[j].secondaryStructure = ' ';
728 _updateRnaSecStr(new AnnotCharSequence());
734 * flyweight access to positions in the alignment annotation row for RNA
740 private class AnnotCharSequence implements CharSequence
746 public AnnotCharSequence()
748 this(0, annotations.length);
751 AnnotCharSequence(int start, int end)
758 public CharSequence subSequence(int start, int end)
760 return new AnnotCharSequence(offset + start, offset + end);
770 public char charAt(int index)
772 return ((index + offset < 0) || (index + offset) >= max
773 || annotations[index + offset] == null
774 || (annotations[index + offset].secondaryStructure <= ' ')
776 : annotations[index + offset].displayCharacter == null
778 + offset].displayCharacter
781 + offset].secondaryStructure
783 + offset].displayCharacter
788 public String toString()
790 char[] string = new char[max - offset];
791 int mx = annotations.length;
793 for (int i = offset; i < mx; i++)
795 string[i] = (annotations[i] == null
796 || (annotations[i].secondaryStructure <= 32))
798 : (annotations[i].displayCharacter == null
799 || annotations[i].displayCharacter
801 ? annotations[i].secondaryStructure
802 : annotations[i].displayCharacter
805 return new String(string);
809 private long _lastrnaannot = -1;
811 public String getRNAStruc()
815 String rnastruc = new AnnotCharSequence().toString();
816 if (_lastrnaannot != rnastruc.hashCode())
818 // ensure rna structure contacts are up to date
819 _lastrnaannot = rnastruc.hashCode();
820 _updateRnaSecStr(rnastruc);
828 * checks graphMin and graphMax, secondary structure symbols, sets graphType
829 * appropriately, sets null labels to the empty string if appropriate.
831 public void validateRangeAndDisplay()
834 if (annotations == null)
836 visible = false; // try to prevent renderer from displaying.
837 invalidrnastruc = -1;
838 return; // this is a non-annotation row annotation - ie a sequence score.
841 int graphType = graph;
842 float min = graphMin;
843 float max = graphMax;
844 boolean drawValues = true;
849 for (int i = 0; i < annotations.length; i++)
851 if (annotations[i] == null)
856 if (drawValues && annotations[i].displayCharacter != null
857 && annotations[i].displayCharacter.length() > 1)
862 if (annotations[i].value > max)
864 max = annotations[i].value;
867 if (annotations[i].value < min)
869 min = annotations[i].value;
871 if (_linecolour == null && annotations[i].colour != null)
873 _linecolour = annotations[i].colour;
876 // ensure zero is origin for min/max ranges on only one side of zero
893 areLabelsSecondaryStructure();
895 if (!drawValues && graphType != NO_GRAPH)
897 for (int i = 0; i < annotations.length; i++)
899 if (annotations[i] != null)
901 annotations[i].displayCharacter = "";
908 * clip the annotation to the columns given by startRes and endRes (inclusive)
909 * and prune any existing sequenceMapping to just those columns.
914 public void restrict(int startRes, int endRes)
916 if (annotations == null)
925 if (startRes >= annotations.length)
927 startRes = annotations.length - 1;
929 if (endRes >= annotations.length)
931 endRes = annotations.length - 1;
933 if (annotations == null)
937 Annotation[] temp = new Annotation[endRes - startRes + 1];
938 if (startRes < annotations.length)
940 System.arraycopy(annotations, startRes, temp, 0,
941 endRes - startRes + 1);
943 if (sequenceRef != null)
945 // Clip the mapping, if it exists.
946 int spos = sequenceRef.findPosition(startRes);
947 int epos = sequenceRef.findPosition(endRes);
948 if (sequenceMapping != null)
950 Map<Integer, Annotation> newmapping = new HashMap<>();
951 Iterator<Integer> e = sequenceMapping.keySet().iterator();
954 Integer pos = e.next();
955 if (pos.intValue() >= spos && pos.intValue() <= epos)
957 newmapping.put(pos, sequenceMapping.get(pos));
960 sequenceMapping.clear();
961 sequenceMapping = newmapping;
968 * set the annotation row to be at least length Annotations
971 * minimum number of columns required in the annotation row
972 * @return false if the annotation row is greater than length
974 public boolean padAnnotation(int length)
976 if (annotations == null)
978 return true; // annotation row is correct - null == not visible and
981 if (annotations.length < length)
983 Annotation[] na = new Annotation[length];
984 System.arraycopy(annotations, 0, na, 0, annotations.length);
988 return annotations.length > length;
995 * @return DOCUMENT ME!
998 public String toString()
1000 if (annotations == null)
1004 StringBuilder buffer = new StringBuilder(256);
1006 for (int i = 0; i < annotations.length; i++)
1008 if (annotations[i] != null)
1012 buffer.append(annotations[i].value);
1016 buffer.append(annotations[i].secondaryStructure);
1020 buffer.append(annotations[i].displayCharacter);
1024 buffer.append(", ");
1026 // TODO: remove disgusting hack for 'special' treatment of consensus line.
1027 if (label.indexOf("Consensus") == 0)
1029 buffer.append("\n");
1031 for (int i = 0; i < annotations.length; i++)
1033 if (annotations[i] != null)
1035 buffer.append(annotations[i].description);
1038 buffer.append(", ");
1042 return buffer.toString();
1045 public void setThreshold(GraphLine line)
1050 public GraphLine getThreshold()
1056 * Attach the annotation to seqRef, starting from startRes position. If
1057 * alreadyMapped is true then the indices of the annotation[] array are
1058 * sequence positions rather than alignment column positions.
1062 * @param alreadyMapped
1063 * - annotation are at aligned columns
1065 public void createSequenceMapping(SequenceI seqRef, int startRes,
1066 boolean alreadyMapped)
1073 sequenceRef = seqRef;
1074 if (annotations == null)
1078 sequenceMapping = new HashMap<>();
1082 for (int i = 0; i < annotations.length; i++)
1084 if (annotations[i] != null)
1088 seqPos = seqRef.findPosition(i);
1092 seqPos = i + startRes;
1095 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1102 * When positional annotation and a sequence reference is present, clears and
1103 * resizes the annotations array to the current alignment width, and adds
1104 * annotation according to aligned positions of the sequenceRef given by
1107 public void adjustForAlignment()
1109 if (sequenceRef == null)
1114 if (annotations == null)
1119 int a = 0, aSize = sequenceRef.getLength();
1128 Annotation[] temp = new Annotation[aSize];
1130 if (sequenceMapping != null)
1132 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1134 index = Integer.valueOf(a);
1135 Annotation annot = sequenceMapping.get(index);
1138 position = sequenceRef.findIndex(a) - 1;
1140 temp[position] = annot;
1148 * remove any null entries in annotation row and return the number of non-null
1149 * annotation elements.
1153 public int compactAnnotationArray()
1155 int i = 0, iSize = annotations.length;
1158 if (annotations[i] == null)
1162 System.arraycopy(annotations, i + 1, annotations, i,
1172 Annotation[] ann = annotations;
1173 annotations = new Annotation[i];
1174 System.arraycopy(ann, 0, annotations, 0, i);
1180 * Associate this annotation with the aligned residues of a particular
1181 * sequence. sequenceMapping will be updated in the following way: null
1182 * sequenceI - existing mapping will be discarded but annotations left in
1183 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1184 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1185 * parameter to specify correspondence between current and new sequenceRef
1189 public void setSequenceRef(SequenceI sequenceI)
1191 if (sequenceI != null)
1193 if (sequenceRef != null)
1195 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1196 tIsDs = sequenceI.getDatasetSequence() == null;
1197 if (sequenceRef != sequenceI
1199 && sequenceRef != sequenceI.getDatasetSequence())
1201 && sequenceRef.getDatasetSequence() != sequenceI)
1202 && (!rIsDs && !tIsDs
1203 && sequenceRef.getDatasetSequence() != sequenceI
1204 .getDatasetSequence())
1205 && !sequenceRef.equals(sequenceI))
1207 // if sequenceRef isn't intersecting with sequenceI
1208 // throw away old mapping and reconstruct.
1210 if (sequenceMapping != null)
1212 sequenceMapping = null;
1213 // compactAnnotationArray();
1215 createSequenceMapping(sequenceI, 1, true);
1216 adjustForAlignment();
1220 // Mapping carried over
1221 sequenceRef = sequenceI;
1226 // No mapping exists
1227 createSequenceMapping(sequenceI, 1, true);
1228 adjustForAlignment();
1233 // throw away the mapping without compacting.
1234 sequenceMapping = null;
1242 public double getScore()
1251 public void setScore(double score)
1259 * @return true if annotation has an associated score
1261 public boolean hasScore()
1263 return hasScore || !Double.isNaN(score);
1266 public void setPadGaps(boolean padgaps, char gapchar)
1268 this.padGaps = padgaps;
1272 for (int i = 0; i < annotations.length; i++)
1274 if (annotations[i] == null)
1276 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1279 else if (annotations[i].displayCharacter == null
1280 || annotations[i].displayCharacter.equals(" "))
1282 annotations[i].displayCharacter = String.valueOf(gapchar);
1289 * format description string for display
1292 * @return Get the annotation description string optionally prefixed by
1293 * associated sequence name (if any)
1295 public String getDescription(boolean seqname)
1297 if (seqname && this.sequenceRef != null)
1299 int i = description.toLowerCase().indexOf("<html>");
1302 // move the html tag to before the sequence reference.
1303 return "<html>" + sequenceRef.getName() + " : "
1304 + description.substring(i + 6);
1306 return sequenceRef.getName() + " : " + description;
1311 public boolean isValidStruc()
1313 return invalidrnastruc == -1;
1316 public long getInvalidStrucPos()
1318 return invalidrnastruc;
1322 * machine readable ID string indicating what generated this annotation
1324 private String calcId = "";
1327 * properties associated with the calcId
1329 protected Map<String, String> properties = new HashMap<>();
1332 * base colour for line graphs. If null, will be set automatically by
1333 * searching the alignment annotation
1335 public java.awt.Color _linecolour;
1337 public String getCalcId()
1342 public void setCalcId(String calcId)
1344 this.calcId = calcId;
1347 public boolean isRNA()
1353 * transfer annotation to the given sequence using the given mapping from the
1354 * current positions or an existing sequence mapping
1358 * map involving sq as To or From
1360 public void liftOver(SequenceI sq, Mapping sp2sq)
1362 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1364 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1365 // Protein reference frames
1367 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1369 boolean mapIsTo = (sp2sq != null)
1370 ? (sp2sq.getTo() == sq
1371 || sp2sq.getTo() == sq.getDatasetSequence())
1374 // TODO build a better annotation element map and get rid of annotations[]
1375 Map<Integer, Annotation> mapForsq = new HashMap<>();
1376 if (sequenceMapping != null)
1380 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1382 Integer mpos = Integer
1383 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1384 : sp2sq.getPosition(ie.getKey()));
1385 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1387 mapForsq.put(mpos, ie.getValue());
1390 sequenceMapping = mapForsq;
1392 adjustForAlignment();
1402 * like liftOver but more general.
1404 * Takes an array of int pairs that will be used to update the internal
1405 * sequenceMapping and so shuffle the annotated positions
1408 * - new sequence reference for the annotation row - if null,
1409 * sequenceRef is left unchanged
1411 * array of ints containing corresponding positions
1413 * - column for current coordinate system (-1 for index+1)
1415 * - column for destination coordinate system (-1 for index+1)
1417 * - offset added to index when referencing either coordinate system
1418 * @note no checks are made as to whether from and/or to are sensible
1419 * @note caller should add the remapped annotation to newref if they have not
1422 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1423 int from, int to, int idxoffset)
1425 if (mapping != null)
1427 Map<Integer, Annotation> old = sequenceMapping;
1428 Map<Integer, Annotation> remap = new HashMap<>();
1430 for (int mp[] : mapping.values())
1436 Annotation ann = null;
1439 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1443 if (mp != null && mp.length > from)
1445 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1452 remap.put(Integer.valueOf(idxoffset + index), ann);
1456 if (to > -1 && to < mp.length)
1458 remap.put(Integer.valueOf(mp[to]), ann);
1463 sequenceMapping = remap;
1467 sequenceRef = newref;
1469 adjustForAlignment();
1473 public String getProperty(String property)
1475 if (properties == null)
1479 return properties.get(property);
1482 public void setProperty(String property, String value)
1484 if (properties == null)
1486 properties = new HashMap<>();
1488 properties.put(property, value);
1491 public boolean hasProperties()
1493 return properties != null && properties.size() > 0;
1496 public Collection<String> getProperties()
1498 if (properties == null)
1500 return Collections.emptyList();
1502 return properties.keySet();
1506 * Returns the Annotation for the given sequence position (base 1) if any,
1512 public Annotation getAnnotationForPosition(int position)
1514 return sequenceMapping == null ? null : sequenceMapping.get(position);
1519 * Set the id to "ann" followed by a counter that increments so as to be
1520 * unique for the lifetime of the JVM
1522 protected final void setAnnotationId()
1524 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1528 * Returns the match for the last unmatched opening RNA helix pair symbol
1529 * preceding the given column, or '(' if nothing found to match.
1534 public String getDefaultRnaHelixSymbol(int column)
1536 String result = "(";
1537 if (annotations == null)
1543 * for each preceding column, if it contains an open bracket,
1544 * count whether it is still unmatched at column, if so return its pair
1545 * (likely faster than the fancy alternative using stacks)
1547 for (int col = column - 1; col >= 0; col--)
1549 Annotation annotation = annotations[col];
1550 if (annotation == null)
1554 String displayed = annotation.displayCharacter;
1555 if (displayed == null || displayed.length() != 1)
1559 char symbol = displayed.charAt(0);
1560 if (!Rna.isOpeningParenthesis(symbol))
1566 * found an opening bracket symbol
1567 * count (closing-opening) symbols of this type that follow it,
1568 * up to and excluding the target column; if the count is less
1569 * than 1, the opening bracket is unmatched, so return its match
1571 String closer = String
1572 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1573 String opener = String.valueOf(symbol);
1575 for (int j = col + 1; j < column; j++)
1577 if (annotations[j] != null)
1579 String s = annotations[j].displayCharacter;
1580 if (closer.equals(s))
1584 else if (opener.equals(s))
1598 protected static synchronized long nextId()
1605 * @return true for rows that have a range of values in their annotation set
1607 public boolean isQuantitative()
1609 return graphMin < graphMax;
1613 * delete any columns in alignmentAnnotation that are hidden (including
1614 * sequence associated annotation).
1616 * @param hiddenColumns
1617 * the set of hidden columns
1619 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1621 if (annotations != null)
1623 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1628 * delete any columns in alignmentAnnotation that are hidden (including
1629 * sequence associated annotation).
1632 * remove any annotation to the right of this column
1634 * remove any annotation to the left of this column
1635 * @param hiddenColumns
1636 * the set of hidden columns
1638 public void makeVisibleAnnotation(int start, int end,
1639 HiddenColumns hiddenColumns)
1641 if (annotations != null)
1643 if (hiddenColumns.hasHiddenColumns())
1645 removeHiddenAnnotation(start, end, hiddenColumns);
1649 restrict(start, end);
1655 * The actual implementation of deleting hidden annotation columns
1658 * remove any annotation to the right of this column
1660 * remove any annotation to the left of this column
1661 * @param hiddenColumns
1662 * the set of hidden columns
1664 private void removeHiddenAnnotation(int start, int end,
1665 HiddenColumns hiddenColumns)
1667 // mangle the alignmentAnnotation annotation array
1668 ArrayList<Annotation[]> annels = new ArrayList<>();
1669 Annotation[] els = null;
1673 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1677 int annotationLength;
1678 while (blocks.hasNext())
1680 int[] block = blocks.next();
1681 annotationLength = block[1] - block[0] + 1;
1683 if (blocks.hasNext())
1685 // copy just the visible segment of the annotation row
1686 copylength = annotationLength;
1690 if (annotationLength + block[0] <= annotations.length)
1692 // copy just the visible segment of the annotation row
1693 copylength = annotationLength;
1697 // copy to the end of the annotation row
1698 copylength = annotations.length - block[0];
1702 els = new Annotation[annotationLength];
1704 System.arraycopy(annotations, block[0], els, 0, copylength);
1705 w += annotationLength;
1710 annotations = new Annotation[w];
1713 for (Annotation[] chnk : annels)
1715 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1721 public static Iterable<AlignmentAnnotation> findAnnotations(
1722 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1725 List<AlignmentAnnotation> aa = new ArrayList<>();
1726 for (AlignmentAnnotation ann : list)
1728 if ((calcId == null || (ann.getCalcId() != null
1729 && ann.getCalcId().equals(calcId)))
1730 && (seq == null || (ann.sequenceRef != null
1731 && ann.sequenceRef == seq))
1733 || (ann.label != null && ann.label.equals(label))))
1742 * Answer true if any annotation matches the calcId passed in (if not null).
1745 * annotation to search
1749 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1753 if (calcId != null && !"".equals(calcId))
1755 for (AlignmentAnnotation a : list)
1757 if (a.getCalcId() == calcId)
1766 public static Iterable<AlignmentAnnotation> findAnnotation(
1767 List<AlignmentAnnotation> list, String calcId)
1769 List<AlignmentAnnotation> aa = new ArrayList<>();
1774 for (AlignmentAnnotation a : list)
1777 if (a.getCalcId() == calcId || (a.getCalcId() != null
1778 && calcId != null && a.getCalcId().equals(calcId)))