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.Locale;
25 import jalview.analysis.Rna;
26 import jalview.analysis.SecStrConsensus.SimpleBP;
27 import jalview.analysis.WUSSParseException;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.Map.Entry;
45 public class AlignmentAnnotation
47 private static final String ANNOTATION_ID_PREFIX = "ann";
50 * Identifers for different types of profile data
52 public static final int SEQUENCE_PROFILE = 0;
54 public static final int STRUCTURE_PROFILE = 1;
56 public static final int CDNA_PROFILE = 2;
58 private static long counter = 0;
61 * If true, this annotations is calculated every edit, eg consensus, quality
62 * or conservation graphs
64 public boolean autoCalculated = false;
67 * unique ID for this annotation, used to match up the same annotation row
68 * shown in multiple views and alignments
70 public String annotationId;
73 * the sequence this annotation is associated with (or null)
75 public SequenceI sequenceRef;
77 /** label shown in dropdown menus and in the annotation label area */
80 /** longer description text shown as a tooltip */
81 public String description;
83 /** Array of annotations placed in the current coordinate system */
84 public Annotation[] annotations;
86 public List<SimpleBP> bps = null;
89 * RNA secondary structure contact positions
91 public SequenceFeature[] _rnasecstr = null;
94 * position of annotation resulting in invalid WUSS parsing or -1. -2 means
95 * there was no RNA structure in this annotation
97 private long invalidrnastruc = -2;
99 private double bitScore;
101 private double eValue;
104 * Updates the _rnasecstr field Determines the positions that base pair and
105 * the positions of helices based on secondary structure from a Stockholm file
107 * @param rnaAnnotation
109 private void _updateRnaSecStr(CharSequence rnaAnnotation)
113 _rnasecstr = Rna.getHelixMap(rnaAnnotation);
114 invalidrnastruc = -1;
115 } catch (WUSSParseException px)
117 // DEBUG System.out.println(px);
118 invalidrnastruc = px.getProblemPos();
120 if (invalidrnastruc > -1)
125 if (_rnasecstr != null && _rnasecstr.length > 0)
127 // show all the RNA secondary structure annotation symbols.
129 showAllColLabels = true;
130 scaleColLabel = true;
133 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
137 private void _markRnaHelices()
140 // Figure out number of helices
141 // Length of rnasecstr is the number of pairs of positions that base pair
142 // with each other in the secondary structure
143 for (int x = 0; x < _rnasecstr.length; x++)
147 * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
148 * this.annotation._rnasecstr[x].getBegin());
150 // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
154 val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
159 } catch (NumberFormatException q)
164 annotations[_rnasecstr[x].getBegin()].value = val;
165 annotations[_rnasecstr[x].getEnd()].value = val;
167 // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
168 // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
174 * Get the RNA Secondary Structure SequenceFeature Array if present
176 public SequenceFeature[] getRnaSecondaryStructure()
178 return this._rnasecstr;
182 * Check the RNA Secondary Structure is equivalent to one in given
183 * AlignmentAnnotation param
185 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that)
187 return rnaSecondaryStructureEquivalent(that, true);
190 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that, boolean compareType)
192 SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
193 SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
194 if (thisSfArray == null || thatSfArray == null)
196 return thisSfArray == null && thatSfArray == null;
198 if (thisSfArray.length != thatSfArray.length)
202 Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
204 Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
206 for (int i=0; i < thisSfArray.length; i++) {
207 SequenceFeature thisSf = thisSfArray[i];
208 SequenceFeature thatSf = thatSfArray[i];
210 if (thisSf.getType() == null || thatSf.getType() == null) {
211 if (thisSf.getType() == null && thatSf.getType() == null) {
217 if (! thisSf.getType().equals(thatSf.getType())) {
221 if (!(thisSf.getBegin() == thatSf.getBegin()
222 && thisSf.getEnd() == thatSf.getEnd()))
232 * map of positions in the associated annotation
234 private Map<Integer, Annotation> sequenceMapping;
237 * lower range for quantitative data
239 public float graphMin;
242 * Upper range for quantitative data
244 public float graphMax;
247 * Score associated with label and description.
249 public double score = Double.NaN;
252 * flag indicating if annotation has a score.
254 public boolean hasScore = false;
256 public GraphLine threshold;
258 // Graphical hints and tips
260 /** Can this row be edited by the user ? */
261 public boolean editable = false;
263 /** Indicates if annotation has a graphical symbol track */
264 public boolean hasIcons; //
266 /** Indicates if annotation has a text character label */
267 public boolean hasText;
269 /** is the row visible */
270 public boolean visible = true;
272 public int graphGroup = -1;
274 /** Displayed height of row in pixels */
275 public int height = 0;
277 public int graph = 0;
279 public int graphHeight = 40;
281 public boolean padGaps = false;
283 public static final int NO_GRAPH = 0;
285 public static final int BAR_GRAPH = 1;
287 public static final int LINE_GRAPH = 2;
289 public boolean belowAlignment = true;
291 public SequenceGroup groupRef = null;
294 * display every column label, even if there is a row of identical labels
296 public boolean showAllColLabels = false;
299 * scale the column label to fit within the alignment column.
301 public boolean scaleColLabel = false;
304 * centre the column labels relative to the alignment column
306 public boolean centreColLabels = false;
308 private boolean isrna;
310 public static int getGraphValueFromString(String string)
312 if (string.equalsIgnoreCase("BAR_GRAPH"))
316 else if (string.equalsIgnoreCase("LINE_GRAPH"))
327 * Creates a new AlignmentAnnotation object.
330 * short label shown under sequence labels
332 * text displayed on mouseover
334 * set of positional annotation elements
336 public AlignmentAnnotation(String label, String description,
337 Annotation[] annotations)
343 this.description = description;
344 this.annotations = annotations;
346 validateRangeAndDisplay();
350 * Checks if annotation labels represent secondary structures
353 void areLabelsSecondaryStructure()
355 boolean nonSSLabel = false;
357 StringBuffer rnastring = new StringBuffer();
360 for (int i = 0; i < annotations.length; i++)
362 // DEBUG System.out.println(i + ": " + annotations[i]);
363 if (annotations[i] == null)
367 if (annotations[i].secondaryStructure == 'H'
368 || annotations[i].secondaryStructure == 'E')
370 // DEBUG System.out.println( "/H|E/ '" +
371 // annotations[i].secondaryStructure + "'");
375 // Check for RNA secondary structure
377 // DEBUG System.out.println( "/else/ '" +
378 // annotations[i].secondaryStructure + "'");
379 // TODO: 2.8.2 should this ss symbol validation check be a function in
380 // RNA/ResidueProperties ?
381 if (annotations[i].secondaryStructure == '('
382 || annotations[i].secondaryStructure == '['
383 || annotations[i].secondaryStructure == '<'
384 || annotations[i].secondaryStructure == '{'
385 || annotations[i].secondaryStructure == 'A'
386 || annotations[i].secondaryStructure == 'B'
387 || annotations[i].secondaryStructure == 'C'
388 || annotations[i].secondaryStructure == 'D'
389 // || annotations[i].secondaryStructure == 'E' // ambiguous on
390 // its own -- already checked above
391 || annotations[i].secondaryStructure == 'F'
392 || annotations[i].secondaryStructure == 'G'
393 // || annotations[i].secondaryStructure == 'H' // ambiguous on
394 // its own -- already checked above
395 || annotations[i].secondaryStructure == 'I'
396 || annotations[i].secondaryStructure == 'J'
397 || annotations[i].secondaryStructure == 'K'
398 || annotations[i].secondaryStructure == 'L'
399 || annotations[i].secondaryStructure == 'M'
400 || annotations[i].secondaryStructure == 'N'
401 || annotations[i].secondaryStructure == 'O'
402 || annotations[i].secondaryStructure == 'P'
403 || annotations[i].secondaryStructure == 'Q'
404 || annotations[i].secondaryStructure == 'R'
405 || annotations[i].secondaryStructure == 'S'
406 || annotations[i].secondaryStructure == 'T'
407 || annotations[i].secondaryStructure == 'U'
408 || annotations[i].secondaryStructure == 'V'
409 || annotations[i].secondaryStructure == 'W'
410 || annotations[i].secondaryStructure == 'X'
411 || annotations[i].secondaryStructure == 'Y'
412 || annotations[i].secondaryStructure == 'Z')
419 // System.out.println("displaychar " + annotations[i].displayCharacter);
421 if (annotations[i].displayCharacter == null
422 || annotations[i].displayCharacter.length() == 0)
424 rnastring.append('.');
427 if (annotations[i].displayCharacter.length() == 1)
429 firstChar = annotations[i].displayCharacter.charAt(0);
430 // check to see if it looks like a sequence or is secondary structure
432 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
433 // Uncomment to only catch case where
434 // displayCharacter==secondary
436 // to correctly redisplay SS annotation imported from Stockholm,
437 // exported to JalviewXML and read back in again.
439 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
440 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
441 && firstChar != '(' && firstChar != '[' && firstChar != '<'
442 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
443 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
444 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
445 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
446 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
447 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
448 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
449 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
450 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
452 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
454 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
467 rnastring.append(annotations[i].displayCharacter.charAt(1));
470 if (annotations[i].displayCharacter.length() > 0)
479 for (int j = 0; j < annotations.length; j++)
481 if (annotations[j] != null
482 && annotations[j].secondaryStructure != ' ')
484 annotations[j].displayCharacter = String
485 .valueOf(annotations[j].secondaryStructure);
486 annotations[j].secondaryStructure = ' ';
495 _updateRnaSecStr(new AnnotCharSequence());
501 * flyweight access to positions in the alignment annotation row for RNA
507 private class AnnotCharSequence implements CharSequence
513 public AnnotCharSequence()
515 this(0, annotations.length);
518 AnnotCharSequence(int start, int end)
525 public CharSequence subSequence(int start, int end)
527 return new AnnotCharSequence(offset + start, offset + end);
537 public char charAt(int index)
539 return ((index + offset < 0) || (index + offset) >= max
540 || annotations[index + offset] == null
541 || (annotations[index + offset].secondaryStructure <= ' ')
543 : annotations[index + offset].displayCharacter == null
545 + offset].displayCharacter
548 + offset].secondaryStructure
550 + offset].displayCharacter
555 public String toString()
557 char[] string = new char[max - offset];
558 int mx = annotations.length;
560 for (int i = offset; i < mx; i++)
562 string[i] = (annotations[i] == null
563 || (annotations[i].secondaryStructure <= 32))
565 : (annotations[i].displayCharacter == null
566 || annotations[i].displayCharacter
568 ? annotations[i].secondaryStructure
569 : annotations[i].displayCharacter
572 return new String(string);
576 private long _lastrnaannot = -1;
578 public String getRNAStruc()
582 String rnastruc = new AnnotCharSequence().toString();
583 if (_lastrnaannot != rnastruc.hashCode())
585 // ensure rna structure contacts are up to date
586 _lastrnaannot = rnastruc.hashCode();
587 _updateRnaSecStr(rnastruc);
595 * Creates a new AlignmentAnnotation object.
610 public AlignmentAnnotation(String label, String description,
611 Annotation[] annotations, float min, float max, int graphType)
614 // graphs are not editable
615 editable = graphType == 0;
618 this.description = description;
619 this.annotations = annotations;
623 validateRangeAndDisplay();
627 * checks graphMin and graphMax, secondary structure symbols, sets graphType
628 * appropriately, sets null labels to the empty string if appropriate.
630 public void validateRangeAndDisplay()
633 if (annotations == null)
635 visible = false; // try to prevent renderer from displaying.
636 invalidrnastruc = -1;
637 return; // this is a non-annotation row annotation - ie a sequence score.
640 int graphType = graph;
641 float min = graphMin;
642 float max = graphMax;
643 boolean drawValues = true;
648 for (int i = 0; i < annotations.length; i++)
650 if (annotations[i] == null)
655 if (drawValues && annotations[i].displayCharacter != null
656 && annotations[i].displayCharacter.length() > 1)
661 if (annotations[i].value > max)
663 max = annotations[i].value;
666 if (annotations[i].value < min)
668 min = annotations[i].value;
670 if (_linecolour == null && annotations[i].colour != null)
672 _linecolour = annotations[i].colour;
675 // ensure zero is origin for min/max ranges on only one side of zero
692 areLabelsSecondaryStructure();
694 if (!drawValues && graphType != NO_GRAPH)
696 for (int i = 0; i < annotations.length; i++)
698 if (annotations[i] != null)
700 annotations[i].displayCharacter = "";
707 * Copy constructor creates a new independent annotation row with the same
708 * associated sequenceRef
712 public AlignmentAnnotation(AlignmentAnnotation annotation)
715 updateAlignmentAnnotationFrom(annotation);
719 * copy attributes and annotation from an existing annotation (used by copy
720 * constructor). This method does not update the unique annotationId
724 public void updateAlignmentAnnotationFrom(AlignmentAnnotation annotation)
726 this.label = new String(annotation.label);
727 if (annotation.description != null)
729 this.description = new String(annotation.description);
731 this.graphMin = annotation.graphMin;
732 this.graphMax = annotation.graphMax;
733 this.graph = annotation.graph;
734 this.graphHeight = annotation.graphHeight;
735 this.graphGroup = annotation.graphGroup;
736 this.groupRef = annotation.groupRef;
737 this.editable = annotation.editable;
738 this.autoCalculated = annotation.autoCalculated;
739 this.hasIcons = annotation.hasIcons;
740 this.hasText = annotation.hasText;
741 this.height = annotation.height;
742 this.label = annotation.label;
743 this.padGaps = annotation.padGaps;
744 this.visible = annotation.visible;
745 this.centreColLabels = annotation.centreColLabels;
746 this.scaleColLabel = annotation.scaleColLabel;
747 this.showAllColLabels = annotation.showAllColLabels;
748 this.calcId = annotation.calcId;
749 this.bitScore = annotation.bitScore;
750 this.eValue = annotation.eValue;
752 if (annotation.properties != null)
754 properties = new HashMap<>();
755 for (Map.Entry<String, String> val : annotation.properties.entrySet())
757 properties.put(val.getKey(), val.getValue());
760 if (this.hasScore = annotation.hasScore)
762 this.score = annotation.score;
764 if (annotation.threshold != null)
766 threshold = new GraphLine(annotation.threshold);
768 Annotation[] ann = annotation.annotations;
769 if (annotation.annotations != null)
771 this.annotations = new Annotation[ann.length];
772 for (int i = 0; i < ann.length; i++)
776 annotations[i] = new Annotation(ann[i]);
777 if (_linecolour != null)
779 _linecolour = annotations[i].colour;
784 if (annotation.sequenceRef != null)
786 this.sequenceRef = annotation.sequenceRef;
787 if (annotation.sequenceMapping != null)
790 sequenceMapping = new HashMap<>();
791 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
793 while (pos.hasNext())
795 // could optimise this!
797 Annotation a = annotation.sequenceMapping.get(p);
804 for (int i = 0; i < ann.length; i++)
808 sequenceMapping.put(p, annotations[i]);
816 this.sequenceMapping = null;
819 // TODO: check if we need to do this: JAL-952
820 // if (this.isrna=annotation.isrna)
822 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
824 validateRangeAndDisplay(); // construct hashcodes, etc.
828 * clip the annotation to the columns given by startRes and endRes (inclusive)
829 * and prune any existing sequenceMapping to just those columns.
834 public void restrict(int startRes, int endRes)
836 if (annotations == null)
845 if (startRes >= annotations.length)
847 startRes = annotations.length - 1;
849 if (endRes >= annotations.length)
851 endRes = annotations.length - 1;
853 if (annotations == null)
857 Annotation[] temp = new Annotation[endRes - startRes + 1];
858 if (startRes < annotations.length)
860 System.arraycopy(annotations, startRes, temp, 0,
861 endRes - startRes + 1);
863 if (sequenceRef != null)
865 // Clip the mapping, if it exists.
866 int spos = sequenceRef.findPosition(startRes);
867 int epos = sequenceRef.findPosition(endRes);
868 if (sequenceMapping != null)
870 Map<Integer, Annotation> newmapping = new HashMap<>();
871 Iterator<Integer> e = sequenceMapping.keySet().iterator();
874 Integer pos = e.next();
875 if (pos.intValue() >= spos && pos.intValue() <= epos)
877 newmapping.put(pos, sequenceMapping.get(pos));
880 sequenceMapping.clear();
881 sequenceMapping = newmapping;
888 * set the annotation row to be at least length Annotations
891 * minimum number of columns required in the annotation row
892 * @return false if the annotation row is greater than length
894 public boolean padAnnotation(int length)
896 if (annotations == null)
898 return true; // annotation row is correct - null == not visible and
901 if (annotations.length < length)
903 Annotation[] na = new Annotation[length];
904 System.arraycopy(annotations, 0, na, 0, annotations.length);
908 return annotations.length > length;
915 * @return DOCUMENT ME!
918 public String toString()
920 if (annotations == null)
924 StringBuilder buffer = new StringBuilder(256);
926 for (int i = 0; i < annotations.length; i++)
928 if (annotations[i] != null)
932 buffer.append(annotations[i].value);
936 buffer.append(annotations[i].secondaryStructure);
940 buffer.append(annotations[i].displayCharacter);
946 // TODO: remove disgusting hack for 'special' treatment of consensus line.
947 if (label.indexOf("Consensus") == 0)
951 for (int i = 0; i < annotations.length; i++)
953 if (annotations[i] != null)
955 buffer.append(annotations[i].description);
962 return buffer.toString();
965 public void setThreshold(GraphLine line)
970 public GraphLine getThreshold()
976 * Attach the annotation to seqRef, starting from startRes position. If
977 * alreadyMapped is true then the indices of the annotation[] array are
978 * sequence positions rather than alignment column positions.
982 * @param alreadyMapped
983 * - annotation are at aligned columns
985 public void createSequenceMapping(SequenceI seqRef, int startRes,
986 boolean alreadyMapped)
993 sequenceRef = seqRef;
994 if (annotations == null)
998 sequenceMapping = new HashMap<>();
1002 for (int i = 0; i < annotations.length; i++)
1004 if (annotations[i] != null)
1008 seqPos = seqRef.findPosition(i);
1012 seqPos = i + startRes;
1015 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1022 * When positional annotation and a sequence reference is present, clears and
1023 * resizes the annotations array to the current alignment width, and adds
1024 * annotation according to aligned positions of the sequenceRef given by
1027 public void adjustForAlignment()
1029 if (sequenceRef == null)
1034 if (annotations == null)
1039 int a = 0, aSize = sequenceRef.getLength();
1048 Annotation[] temp = new Annotation[aSize];
1050 if (sequenceMapping != null)
1052 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1054 index = Integer.valueOf(a);
1055 Annotation annot = sequenceMapping.get(index);
1058 position = sequenceRef.findIndex(a) - 1;
1060 temp[position] = annot;
1068 * remove any null entries in annotation row and return the number of non-null
1069 * annotation elements.
1073 public int compactAnnotationArray()
1075 int i = 0, iSize = annotations.length;
1078 if (annotations[i] == null)
1082 System.arraycopy(annotations, i + 1, annotations, i,
1092 Annotation[] ann = annotations;
1093 annotations = new Annotation[i];
1094 System.arraycopy(ann, 0, annotations, 0, i);
1100 * Associate this annotation with the aligned residues of a particular
1101 * sequence. sequenceMapping will be updated in the following way: null
1102 * sequenceI - existing mapping will be discarded but annotations left in
1103 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1104 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1105 * parameter to specify correspondence between current and new sequenceRef
1109 public void setSequenceRef(SequenceI sequenceI)
1111 if (sequenceI != null)
1113 if (sequenceRef != null)
1115 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1116 tIsDs = sequenceI.getDatasetSequence() == null;
1117 if (sequenceRef != sequenceI
1119 && sequenceRef != sequenceI.getDatasetSequence())
1121 && sequenceRef.getDatasetSequence() != sequenceI)
1122 && (!rIsDs && !tIsDs
1123 && sequenceRef.getDatasetSequence() != sequenceI
1124 .getDatasetSequence())
1125 && !sequenceRef.equals(sequenceI))
1127 // if sequenceRef isn't intersecting with sequenceI
1128 // throw away old mapping and reconstruct.
1130 if (sequenceMapping != null)
1132 sequenceMapping = null;
1133 // compactAnnotationArray();
1135 createSequenceMapping(sequenceI, 1, true);
1136 adjustForAlignment();
1140 // Mapping carried over
1141 sequenceRef = sequenceI;
1146 // No mapping exists
1147 createSequenceMapping(sequenceI, 1, true);
1148 adjustForAlignment();
1153 // throw away the mapping without compacting.
1154 sequenceMapping = null;
1162 public double getScore()
1171 public void setScore(double score)
1179 * @return true if annotation has an associated score
1181 public boolean hasScore()
1183 return hasScore || !Double.isNaN(score);
1187 * Score only annotation
1190 * @param description
1193 public AlignmentAnnotation(String label, String description, double score)
1195 this(label, description, null);
1200 * copy constructor with edit based on the hidden columns marked in colSel
1202 * @param alignmentAnnotation
1205 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1206 HiddenColumns hidden)
1208 this(alignmentAnnotation);
1209 if (annotations == null)
1213 makeVisibleAnnotation(hidden);
1217 public void setPadGaps(boolean padgaps, char gapchar)
1219 this.padGaps = padgaps;
1223 for (int i = 0; i < annotations.length; i++)
1225 if (annotations[i] == null)
1227 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1230 else if (annotations[i].displayCharacter == null
1231 || annotations[i].displayCharacter.equals(" "))
1233 annotations[i].displayCharacter = String.valueOf(gapchar);
1240 * format description string for display
1243 * @return Get the annotation description string optionally prefixed by
1244 * associated sequence name (if any)
1246 public String getDescription(boolean seqname)
1248 if (seqname && this.sequenceRef != null)
1250 int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1253 // move the html tag to before the sequence reference.
1254 return "<html>" + sequenceRef.getName() + " : "
1255 + description.substring(i + 6);
1257 return sequenceRef.getName() + " : " + description;
1262 public boolean isValidStruc()
1264 return invalidrnastruc == -1;
1267 public long getInvalidStrucPos()
1269 return invalidrnastruc;
1273 * machine readable ID string indicating what generated this annotation
1275 protected String calcId = "";
1278 * properties associated with the calcId
1280 protected Map<String, String> properties = new HashMap<>();
1283 * base colour for line graphs. If null, will be set automatically by
1284 * searching the alignment annotation
1286 public java.awt.Color _linecolour;
1288 public String getCalcId()
1293 public void setCalcId(String calcId)
1295 this.calcId = calcId;
1298 public boolean isRNA()
1304 * transfer annotation to the given sequence using the given mapping from the
1305 * current positions or an existing sequence mapping
1309 * map involving sq as To or From
1311 public void liftOver(SequenceI sq, Mapping sp2sq)
1313 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1315 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1316 // Protein reference frames
1318 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1320 boolean mapIsTo = (sp2sq != null)
1321 ? (sp2sq.getTo() == sq
1322 || sp2sq.getTo() == sq.getDatasetSequence())
1325 // TODO build a better annotation element map and get rid of annotations[]
1326 Map<Integer, Annotation> mapForsq = new HashMap<>();
1327 if (sequenceMapping != null)
1331 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1333 Integer mpos = Integer
1334 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1335 : sp2sq.getPosition(ie.getKey()));
1336 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1338 mapForsq.put(mpos, ie.getValue());
1341 sequenceMapping = mapForsq;
1343 adjustForAlignment();
1353 * like liftOver but more general.
1355 * Takes an array of int pairs that will be used to update the internal
1356 * sequenceMapping and so shuffle the annotated positions
1359 * - new sequence reference for the annotation row - if null,
1360 * sequenceRef is left unchanged
1362 * array of ints containing corresponding positions
1364 * - column for current coordinate system (-1 for index+1)
1366 * - column for destination coordinate system (-1 for index+1)
1368 * - offset added to index when referencing either coordinate system
1369 * @note no checks are made as to whether from and/or to are sensible
1370 * @note caller should add the remapped annotation to newref if they have not
1373 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1374 int from, int to, int idxoffset)
1376 if (mapping != null)
1378 Map<Integer, Annotation> old = sequenceMapping;
1379 Map<Integer, Annotation> remap = new HashMap<>();
1381 for (int mp[] : mapping.values())
1387 Annotation ann = null;
1390 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1394 if (mp != null && mp.length > from)
1396 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1403 remap.put(Integer.valueOf(idxoffset + index), ann);
1407 if (to > -1 && to < mp.length)
1409 remap.put(Integer.valueOf(mp[to]), ann);
1414 sequenceMapping = remap;
1418 sequenceRef = newref;
1420 adjustForAlignment();
1424 public String getProperty(String property)
1426 if (properties == null)
1430 return properties.get(property);
1433 public void setProperty(String property, String value)
1435 if (properties == null)
1437 properties = new HashMap<>();
1439 properties.put(property, value);
1442 public boolean hasProperties()
1444 return properties != null && properties.size() > 0;
1447 public Collection<String> getProperties()
1449 if (properties == null)
1451 return Collections.emptyList();
1453 return properties.keySet();
1457 * Returns the Annotation for the given sequence position (base 1) if any,
1463 public Annotation getAnnotationForPosition(int position)
1465 return sequenceMapping == null ? null : sequenceMapping.get(position);
1470 * Set the id to "ann" followed by a counter that increments so as to be
1471 * unique for the lifetime of the JVM
1473 protected final void setAnnotationId()
1475 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1479 * Returns the match for the last unmatched opening RNA helix pair symbol
1480 * preceding the given column, or '(' if nothing found to match.
1485 public String getDefaultRnaHelixSymbol(int column)
1487 String result = "(";
1488 if (annotations == null)
1494 * for each preceding column, if it contains an open bracket,
1495 * count whether it is still unmatched at column, if so return its pair
1496 * (likely faster than the fancy alternative using stacks)
1498 for (int col = column - 1; col >= 0; col--)
1500 Annotation annotation = annotations[col];
1501 if (annotation == null)
1505 String displayed = annotation.displayCharacter;
1506 if (displayed == null || displayed.length() != 1)
1510 char symbol = displayed.charAt(0);
1511 if (!Rna.isOpeningParenthesis(symbol))
1517 * found an opening bracket symbol
1518 * count (closing-opening) symbols of this type that follow it,
1519 * up to and excluding the target column; if the count is less
1520 * than 1, the opening bracket is unmatched, so return its match
1522 String closer = String
1523 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1524 String opener = String.valueOf(symbol);
1526 for (int j = col + 1; j < column; j++)
1528 if (annotations[j] != null)
1530 String s = annotations[j].displayCharacter;
1531 if (closer.equals(s))
1535 else if (opener.equals(s))
1549 protected static synchronized long nextId()
1556 * @return true for rows that have a range of values in their annotation set
1558 public boolean isQuantitative()
1560 return graphMin < graphMax;
1564 * delete any columns in alignmentAnnotation that are hidden (including
1565 * sequence associated annotation).
1567 * @param hiddenColumns
1568 * the set of hidden columns
1570 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1572 if (annotations != null)
1574 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1579 * delete any columns in alignmentAnnotation that are hidden (including
1580 * sequence associated annotation).
1583 * remove any annotation to the right of this column
1585 * remove any annotation to the left of this column
1586 * @param hiddenColumns
1587 * the set of hidden columns
1589 public void makeVisibleAnnotation(int start, int end,
1590 HiddenColumns hiddenColumns)
1592 if (annotations != null)
1594 if (hiddenColumns.hasHiddenColumns())
1596 removeHiddenAnnotation(start, end, hiddenColumns);
1600 restrict(start, end);
1606 * The actual implementation of deleting hidden annotation columns
1609 * remove any annotation to the right of this column
1611 * remove any annotation to the left of this column
1612 * @param hiddenColumns
1613 * the set of hidden columns
1615 private void removeHiddenAnnotation(int start, int end,
1616 HiddenColumns hiddenColumns)
1618 // mangle the alignmentAnnotation annotation array
1619 ArrayList<Annotation[]> annels = new ArrayList<>();
1620 Annotation[] els = null;
1624 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1628 int annotationLength;
1629 while (blocks.hasNext())
1631 int[] block = blocks.next();
1632 annotationLength = block[1] - block[0] + 1;
1634 if (blocks.hasNext())
1636 // copy just the visible segment of the annotation row
1637 copylength = annotationLength;
1641 if (annotationLength + block[0] <= annotations.length)
1643 // copy just the visible segment of the annotation row
1644 copylength = annotationLength;
1648 // copy to the end of the annotation row
1649 copylength = annotations.length - block[0];
1653 els = new Annotation[annotationLength];
1655 System.arraycopy(annotations, block[0], els, 0, copylength);
1656 w += annotationLength;
1661 annotations = new Annotation[w];
1664 for (Annotation[] chnk : annels)
1666 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1672 public static Iterable<AlignmentAnnotation> findAnnotations(
1673 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1676 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1677 for (AlignmentAnnotation ann : list)
1679 if ((calcId == null || (ann.getCalcId() != null
1680 && ann.getCalcId().equals(calcId)))
1681 && (seq == null || (ann.sequenceRef != null
1682 && ann.sequenceRef == seq))
1684 || (ann.label != null && ann.label.equals(label))))
1693 * Answer true if any annotation matches the calcId passed in (if not null).
1696 * annotation to search
1700 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1704 if (calcId != null && !"".equals(calcId))
1706 for (AlignmentAnnotation a : list)
1708 if (a.getCalcId() == calcId)
1717 public static Iterable<AlignmentAnnotation> findAnnotation(
1718 List<AlignmentAnnotation> list, String calcId)
1720 List<AlignmentAnnotation> aa = new ArrayList<>();
1725 for (AlignmentAnnotation a : list)
1728 if (a.getCalcId() == calcId || (a.getCalcId() != null
1729 && calcId != null && a.getCalcId().equals(calcId)))
1737 public double getBitScore()
1742 public void setBitScore(double bitScore)
1744 this.bitScore = bitScore;
1747 public double getEValue()
1752 public void setEValue(double eValue)
1754 this.eValue = eValue;
1757 public static AlignmentAnnotation findFirstAnnotation(
1758 Iterable<AlignmentAnnotation> alignmentAnnotation, String name,
1759 String calcId, boolean autoCalc, SequenceI seqRef,
1760 SequenceGroup groupRef)
1763 for (AlignmentAnnotation annot : alignmentAnnotation)
1765 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1766 && (calcId == null || annot.getCalcId().equals(calcId))
1767 && annot.sequenceRef == seqRef && annot.groupRef == groupRef)