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;
100 * Updates the _rnasecstr field Determines the positions that base pair and
101 * the positions of helices based on secondary structure from a Stockholm file
103 * @param rnaAnnotation
105 private void _updateRnaSecStr(CharSequence rnaAnnotation)
109 _rnasecstr = Rna.getHelixMap(rnaAnnotation);
110 invalidrnastruc = -1;
111 } catch (WUSSParseException px)
113 // DEBUG System.out.println(px);
114 invalidrnastruc = px.getProblemPos();
116 if (invalidrnastruc > -1)
121 if (_rnasecstr != null && _rnasecstr.length > 0)
123 // show all the RNA secondary structure annotation symbols.
125 showAllColLabels = true;
126 scaleColLabel = true;
129 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
133 private void _markRnaHelices()
136 // Figure out number of helices
137 // Length of rnasecstr is the number of pairs of positions that base pair
138 // with each other in the secondary structure
139 for (int x = 0; x < _rnasecstr.length; x++)
143 * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
144 * this.annotation._rnasecstr[x].getBegin());
146 // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
150 val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
155 } catch (NumberFormatException q)
160 annotations[_rnasecstr[x].getBegin()].value = val;
161 annotations[_rnasecstr[x].getEnd()].value = val;
163 // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
164 // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
170 * Get the RNA Secondary Structure SequenceFeature Array if present
172 public SequenceFeature[] getRnaSecondaryStructure()
174 return this._rnasecstr;
178 * Check the RNA Secondary Structure is equivalent to one in given
179 * AlignmentAnnotation param
181 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that)
183 return rnaSecondaryStructureEquivalent(that, true);
186 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that,
189 SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
190 SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
191 if (thisSfArray == null || thatSfArray == null)
193 return thisSfArray == null && thatSfArray == null;
195 if (thisSfArray.length != thatSfArray.length)
199 Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
201 Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
203 for (int i = 0; i < thisSfArray.length; i++)
205 SequenceFeature thisSf = thisSfArray[i];
206 SequenceFeature thatSf = thatSfArray[i];
209 if (thisSf.getType() == null || thatSf.getType() == null)
211 if (thisSf.getType() == null && thatSf.getType() == null)
220 if (!thisSf.getType().equals(thatSf.getType()))
225 if (!(thisSf.getBegin() == thatSf.getBegin()
226 && thisSf.getEnd() == thatSf.getEnd()))
236 * map of positions in the associated annotation
238 private Map<Integer, Annotation> sequenceMapping;
241 * lower range for quantitative data
243 public float graphMin;
246 * Upper range for quantitative data
248 public float graphMax;
251 * Score associated with label and description.
253 public double score = Double.NaN;
256 * flag indicating if annotation has a score.
258 public boolean hasScore = false;
260 public GraphLine threshold;
262 // Graphical hints and tips
264 /** Can this row be edited by the user ? */
265 public boolean editable = false;
267 /** Indicates if annotation has a graphical symbol track */
268 public boolean hasIcons; //
270 /** Indicates if annotation has a text character label */
271 public boolean hasText;
273 /** is the row visible */
274 public boolean visible = true;
276 public int graphGroup = -1;
278 /** Displayed height of row in pixels */
279 public int height = 0;
281 public int graph = 0;
283 public int graphHeight = 40;
285 public boolean padGaps = false;
287 public static final int NO_GRAPH = 0;
289 public static final int BAR_GRAPH = 1;
291 public static final int LINE_GRAPH = 2;
293 public boolean belowAlignment = true;
295 public SequenceGroup groupRef = null;
298 * display every column label, even if there is a row of identical labels
300 public boolean showAllColLabels = false;
303 * scale the column label to fit within the alignment column.
305 public boolean scaleColLabel = false;
308 * centre the column labels relative to the alignment column
310 public boolean centreColLabels = false;
312 private boolean isrna;
314 public static int getGraphValueFromString(String string)
316 if (string.equalsIgnoreCase("BAR_GRAPH"))
320 else if (string.equalsIgnoreCase("LINE_GRAPH"))
331 * Creates a new AlignmentAnnotation object.
334 * short label shown under sequence labels
336 * text displayed on mouseover
338 * set of positional annotation elements
340 public AlignmentAnnotation(String label, String description,
341 Annotation[] annotations)
347 this.description = description;
348 this.annotations = annotations;
350 validateRangeAndDisplay();
354 * Checks if annotation labels represent secondary structures
357 void areLabelsSecondaryStructure()
359 boolean nonSSLabel = false;
361 StringBuffer rnastring = new StringBuffer();
364 for (int i = 0; i < annotations.length; i++)
366 // DEBUG System.out.println(i + ": " + annotations[i]);
367 if (annotations[i] == null)
371 if (annotations[i].secondaryStructure == 'H'
372 || annotations[i].secondaryStructure == 'E')
374 // DEBUG System.out.println( "/H|E/ '" +
375 // annotations[i].secondaryStructure + "'");
379 // Check for RNA secondary structure
381 // DEBUG System.out.println( "/else/ '" +
382 // annotations[i].secondaryStructure + "'");
383 // TODO: 2.8.2 should this ss symbol validation check be a function in
384 // RNA/ResidueProperties ?
385 if (annotations[i].secondaryStructure == '('
386 || annotations[i].secondaryStructure == '['
387 || annotations[i].secondaryStructure == '<'
388 || annotations[i].secondaryStructure == '{'
389 || annotations[i].secondaryStructure == 'A'
390 || annotations[i].secondaryStructure == 'B'
391 || annotations[i].secondaryStructure == 'C'
392 || annotations[i].secondaryStructure == 'D'
393 // || annotations[i].secondaryStructure == 'E' // ambiguous on
394 // its own -- already checked above
395 || annotations[i].secondaryStructure == 'F'
396 || annotations[i].secondaryStructure == 'G'
397 // || annotations[i].secondaryStructure == 'H' // ambiguous on
398 // its own -- already checked above
399 || annotations[i].secondaryStructure == 'I'
400 || annotations[i].secondaryStructure == 'J'
401 || annotations[i].secondaryStructure == 'K'
402 || annotations[i].secondaryStructure == 'L'
403 || annotations[i].secondaryStructure == 'M'
404 || annotations[i].secondaryStructure == 'N'
405 || annotations[i].secondaryStructure == 'O'
406 || annotations[i].secondaryStructure == 'P'
407 || annotations[i].secondaryStructure == 'Q'
408 || annotations[i].secondaryStructure == 'R'
409 || annotations[i].secondaryStructure == 'S'
410 || annotations[i].secondaryStructure == 'T'
411 || annotations[i].secondaryStructure == 'U'
412 || annotations[i].secondaryStructure == 'V'
413 || annotations[i].secondaryStructure == 'W'
414 || annotations[i].secondaryStructure == 'X'
415 || annotations[i].secondaryStructure == 'Y'
416 || annotations[i].secondaryStructure == 'Z')
423 // System.out.println("displaychar " + annotations[i].displayCharacter);
425 if (annotations[i].displayCharacter == null
426 || annotations[i].displayCharacter.length() == 0)
428 rnastring.append('.');
431 if (annotations[i].displayCharacter.length() == 1)
433 firstChar = annotations[i].displayCharacter.charAt(0);
434 // check to see if it looks like a sequence or is secondary structure
436 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
437 // Uncomment to only catch case where
438 // displayCharacter==secondary
440 // to correctly redisplay SS annotation imported from Stockholm,
441 // exported to JalviewXML and read back in again.
443 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
444 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
445 && firstChar != '(' && firstChar != '[' && firstChar != '<'
446 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
447 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
448 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
449 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
450 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
451 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
452 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
453 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
454 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
456 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
458 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
471 rnastring.append(annotations[i].displayCharacter.charAt(1));
474 if (annotations[i].displayCharacter.length() > 0)
483 for (int j = 0; j < annotations.length; j++)
485 if (annotations[j] != null
486 && annotations[j].secondaryStructure != ' ')
488 annotations[j].displayCharacter = String
489 .valueOf(annotations[j].secondaryStructure);
490 annotations[j].secondaryStructure = ' ';
499 _updateRnaSecStr(new AnnotCharSequence());
505 * flyweight access to positions in the alignment annotation row for RNA
511 private class AnnotCharSequence implements CharSequence
517 public AnnotCharSequence()
519 this(0, annotations.length);
522 AnnotCharSequence(int start, int end)
529 public CharSequence subSequence(int start, int end)
531 return new AnnotCharSequence(offset + start, offset + end);
541 public char charAt(int index)
543 return ((index + offset < 0) || (index + offset) >= max
544 || annotations[index + offset] == null
545 || (annotations[index + offset].secondaryStructure <= ' ')
547 : annotations[index + offset].displayCharacter == null
549 + offset].displayCharacter
552 + offset].secondaryStructure
554 + offset].displayCharacter
559 public String toString()
561 char[] string = new char[max - offset];
562 int mx = annotations.length;
564 for (int i = offset; i < mx; i++)
566 string[i] = (annotations[i] == null
567 || (annotations[i].secondaryStructure <= 32))
569 : (annotations[i].displayCharacter == null
570 || annotations[i].displayCharacter
572 ? annotations[i].secondaryStructure
573 : annotations[i].displayCharacter
576 return new String(string);
580 private long _lastrnaannot = -1;
582 public String getRNAStruc()
586 String rnastruc = new AnnotCharSequence().toString();
587 if (_lastrnaannot != rnastruc.hashCode())
589 // ensure rna structure contacts are up to date
590 _lastrnaannot = rnastruc.hashCode();
591 _updateRnaSecStr(rnastruc);
599 * Creates a new AlignmentAnnotation object.
614 public AlignmentAnnotation(String label, String description,
615 Annotation[] annotations, float min, float max, int graphType)
618 // graphs are not editable
619 editable = graphType == 0;
622 this.description = description;
623 this.annotations = annotations;
627 validateRangeAndDisplay();
631 * checks graphMin and graphMax, secondary structure symbols, sets graphType
632 * appropriately, sets null labels to the empty string if appropriate.
634 public void validateRangeAndDisplay()
637 if (annotations == null)
639 visible = false; // try to prevent renderer from displaying.
640 invalidrnastruc = -1;
641 return; // this is a non-annotation row annotation - ie a sequence score.
644 int graphType = graph;
645 float min = graphMin;
646 float max = graphMax;
647 boolean drawValues = true;
652 for (int i = 0; i < annotations.length; i++)
654 if (annotations[i] == null)
659 if (drawValues && annotations[i].displayCharacter != null
660 && annotations[i].displayCharacter.length() > 1)
665 if (annotations[i].value > max)
667 max = annotations[i].value;
670 if (annotations[i].value < min)
672 min = annotations[i].value;
674 if (_linecolour == null && annotations[i].colour != null)
676 _linecolour = annotations[i].colour;
679 // ensure zero is origin for min/max ranges on only one side of zero
696 areLabelsSecondaryStructure();
698 if (!drawValues && graphType != NO_GRAPH)
700 for (int i = 0; i < annotations.length; i++)
702 if (annotations[i] != null)
704 annotations[i].displayCharacter = "";
711 * Copy constructor creates a new independent annotation row with the same
712 * associated sequenceRef
716 public AlignmentAnnotation(AlignmentAnnotation annotation)
719 this.label = new String(annotation.label);
720 if (annotation.description != null)
722 this.description = new String(annotation.description);
724 this.graphMin = annotation.graphMin;
725 this.graphMax = annotation.graphMax;
726 this.graph = annotation.graph;
727 this.graphHeight = annotation.graphHeight;
728 this.graphGroup = annotation.graphGroup;
729 this.groupRef = annotation.groupRef;
730 this.editable = annotation.editable;
731 this.autoCalculated = annotation.autoCalculated;
732 this.hasIcons = annotation.hasIcons;
733 this.hasText = annotation.hasText;
734 this.height = annotation.height;
735 this.label = annotation.label;
736 this.padGaps = annotation.padGaps;
737 this.visible = annotation.visible;
738 this.centreColLabels = annotation.centreColLabels;
739 this.scaleColLabel = annotation.scaleColLabel;
740 this.showAllColLabels = annotation.showAllColLabels;
741 this.calcId = annotation.calcId;
742 if (annotation.properties != null)
744 properties = new HashMap<>();
745 for (Map.Entry<String, String> val : annotation.properties.entrySet())
747 properties.put(val.getKey(), val.getValue());
750 if (this.hasScore = annotation.hasScore)
752 this.score = annotation.score;
754 if (annotation.threshold != null)
756 threshold = new GraphLine(annotation.threshold);
758 Annotation[] ann = annotation.annotations;
759 if (annotation.annotations != null)
761 this.annotations = new Annotation[ann.length];
762 for (int i = 0; i < ann.length; i++)
766 annotations[i] = new Annotation(ann[i]);
767 if (_linecolour != null)
769 _linecolour = annotations[i].colour;
774 if (annotation.sequenceRef != null)
776 this.sequenceRef = annotation.sequenceRef;
777 if (annotation.sequenceMapping != null)
780 sequenceMapping = new HashMap<>();
781 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
783 while (pos.hasNext())
785 // could optimise this!
787 Annotation a = annotation.sequenceMapping.get(p);
794 for (int i = 0; i < ann.length; i++)
798 sequenceMapping.put(p, annotations[i]);
806 this.sequenceMapping = null;
809 // TODO: check if we need to do this: JAL-952
810 // if (this.isrna=annotation.isrna)
812 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
814 validateRangeAndDisplay(); // construct hashcodes, etc.
818 * clip the annotation to the columns given by startRes and endRes (inclusive)
819 * and prune any existing sequenceMapping to just those columns.
824 public void restrict(int startRes, int endRes)
826 if (annotations == null)
835 if (startRes >= annotations.length)
837 startRes = annotations.length - 1;
839 if (endRes >= annotations.length)
841 endRes = annotations.length - 1;
843 if (annotations == null)
847 Annotation[] temp = new Annotation[endRes - startRes + 1];
848 if (startRes < annotations.length)
850 System.arraycopy(annotations, startRes, temp, 0,
851 endRes - startRes + 1);
853 if (sequenceRef != null)
855 // Clip the mapping, if it exists.
856 int spos = sequenceRef.findPosition(startRes);
857 int epos = sequenceRef.findPosition(endRes);
858 if (sequenceMapping != null)
860 Map<Integer, Annotation> newmapping = new HashMap<>();
861 Iterator<Integer> e = sequenceMapping.keySet().iterator();
864 Integer pos = e.next();
865 if (pos.intValue() >= spos && pos.intValue() <= epos)
867 newmapping.put(pos, sequenceMapping.get(pos));
870 sequenceMapping.clear();
871 sequenceMapping = newmapping;
878 * set the annotation row to be at least length Annotations
881 * minimum number of columns required in the annotation row
882 * @return false if the annotation row is greater than length
884 public boolean padAnnotation(int length)
886 if (annotations == null)
888 return true; // annotation row is correct - null == not visible and
891 if (annotations.length < length)
893 Annotation[] na = new Annotation[length];
894 System.arraycopy(annotations, 0, na, 0, annotations.length);
898 return annotations.length > length;
905 * @return DOCUMENT ME!
908 public String toString()
910 if (annotations == null)
914 StringBuilder buffer = new StringBuilder(256);
916 for (int i = 0; i < annotations.length; i++)
918 if (annotations[i] != null)
922 buffer.append(annotations[i].value);
926 buffer.append(annotations[i].secondaryStructure);
930 buffer.append(annotations[i].displayCharacter);
936 // TODO: remove disgusting hack for 'special' treatment of consensus line.
937 if (label.indexOf("Consensus") == 0)
941 for (int i = 0; i < annotations.length; i++)
943 if (annotations[i] != null)
945 buffer.append(annotations[i].description);
952 return buffer.toString();
955 public void setThreshold(GraphLine line)
960 public GraphLine getThreshold()
966 * Attach the annotation to seqRef, starting from startRes position. If
967 * alreadyMapped is true then the indices of the annotation[] array are
968 * sequence positions rather than alignment column positions.
972 * @param alreadyMapped
974 public void createSequenceMapping(SequenceI seqRef, int startRes,
975 boolean alreadyMapped)
982 sequenceRef = seqRef;
983 if (annotations == null)
987 sequenceMapping = new HashMap<>();
991 for (int i = 0; i < annotations.length; i++)
993 if (annotations[i] != null)
997 seqPos = seqRef.findPosition(i);
1001 seqPos = i + startRes;
1004 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1011 * When positional annotation and a sequence reference is present, clears and
1012 * resizes the annotations array to the current alignment width, and adds
1013 * annotation according to aligned positions of the sequenceRef given by
1016 public void adjustForAlignment()
1018 if (sequenceRef == null)
1023 if (annotations == null)
1028 int a = 0, aSize = sequenceRef.getLength();
1037 Annotation[] temp = new Annotation[aSize];
1039 if (sequenceMapping != null)
1041 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1043 index = Integer.valueOf(a);
1044 Annotation annot = sequenceMapping.get(index);
1047 position = sequenceRef.findIndex(a) - 1;
1049 temp[position] = annot;
1057 * remove any null entries in annotation row and return the number of non-null
1058 * annotation elements.
1062 public int compactAnnotationArray()
1064 int i = 0, iSize = annotations.length;
1067 if (annotations[i] == null)
1071 System.arraycopy(annotations, i + 1, annotations, i,
1081 Annotation[] ann = annotations;
1082 annotations = new Annotation[i];
1083 System.arraycopy(ann, 0, annotations, 0, i);
1089 * Associate this annotation with the aligned residues of a particular
1090 * sequence. sequenceMapping will be updated in the following way: null
1091 * sequenceI - existing mapping will be discarded but annotations left in
1092 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1093 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1094 * parameter to specify correspondence between current and new sequenceRef
1098 public void setSequenceRef(SequenceI sequenceI)
1100 if (sequenceI != null)
1102 if (sequenceRef != null)
1104 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1105 tIsDs = sequenceI.getDatasetSequence() == null;
1106 if (sequenceRef != sequenceI
1108 && sequenceRef != sequenceI.getDatasetSequence())
1110 && sequenceRef.getDatasetSequence() != sequenceI)
1111 && (!rIsDs && !tIsDs
1112 && sequenceRef.getDatasetSequence() != sequenceI
1113 .getDatasetSequence())
1114 && !sequenceRef.equals(sequenceI))
1116 // if sequenceRef isn't intersecting with sequenceI
1117 // throw away old mapping and reconstruct.
1119 if (sequenceMapping != null)
1121 sequenceMapping = null;
1122 // compactAnnotationArray();
1124 createSequenceMapping(sequenceI, 1, true);
1125 adjustForAlignment();
1129 // Mapping carried over
1130 sequenceRef = sequenceI;
1135 // No mapping exists
1136 createSequenceMapping(sequenceI, 1, true);
1137 adjustForAlignment();
1142 // throw away the mapping without compacting.
1143 sequenceMapping = null;
1151 public double getScore()
1160 public void setScore(double score)
1168 * @return true if annotation has an associated score
1170 public boolean hasScore()
1172 return hasScore || !Double.isNaN(score);
1176 * Score only annotation
1179 * @param description
1182 public AlignmentAnnotation(String label, String description, double score)
1184 this(label, description, null);
1189 * copy constructor with edit based on the hidden columns marked in colSel
1191 * @param alignmentAnnotation
1194 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1195 HiddenColumns hidden)
1197 this(alignmentAnnotation);
1198 if (annotations == null)
1202 makeVisibleAnnotation(hidden);
1205 public void setPadGaps(boolean padgaps, char gapchar)
1207 this.padGaps = padgaps;
1211 for (int i = 0; i < annotations.length; i++)
1213 if (annotations[i] == null)
1215 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1218 else if (annotations[i].displayCharacter == null
1219 || annotations[i].displayCharacter.equals(" "))
1221 annotations[i].displayCharacter = String.valueOf(gapchar);
1228 * format description string for display
1231 * @return Get the annotation description string optionally prefixed by
1232 * associated sequence name (if any)
1234 public String getDescription(boolean seqname)
1236 if (seqname && this.sequenceRef != null)
1238 int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1241 // move the html tag to before the sequence reference.
1242 return "<html>" + sequenceRef.getName() + " : "
1243 + description.substring(i + 6);
1245 return sequenceRef.getName() + " : " + description;
1250 public boolean isValidStruc()
1252 return invalidrnastruc == -1;
1255 public long getInvalidStrucPos()
1257 return invalidrnastruc;
1261 * machine readable ID string indicating what generated this annotation
1263 protected String calcId = "";
1266 * properties associated with the calcId
1268 protected Map<String, String> properties = new HashMap<>();
1271 * base colour for line graphs. If null, will be set automatically by
1272 * searching the alignment annotation
1274 public java.awt.Color _linecolour;
1276 public String getCalcId()
1281 public void setCalcId(String calcId)
1283 this.calcId = calcId;
1286 public boolean isRNA()
1292 * transfer annotation to the given sequence using the given mapping from the
1293 * current positions or an existing sequence mapping
1297 * map involving sq as To or From
1299 public void liftOver(SequenceI sq, Mapping sp2sq)
1301 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1303 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1304 // Protein reference frames
1306 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1308 boolean mapIsTo = (sp2sq != null)
1309 ? (sp2sq.getTo() == sq
1310 || sp2sq.getTo() == sq.getDatasetSequence())
1313 // TODO build a better annotation element map and get rid of annotations[]
1314 Map<Integer, Annotation> mapForsq = new HashMap<>();
1315 if (sequenceMapping != null)
1319 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1321 Integer mpos = Integer
1322 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1323 : sp2sq.getPosition(ie.getKey()));
1324 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1326 mapForsq.put(mpos, ie.getValue());
1329 sequenceMapping = mapForsq;
1331 adjustForAlignment();
1341 * like liftOver but more general.
1343 * Takes an array of int pairs that will be used to update the internal
1344 * sequenceMapping and so shuffle the annotated positions
1347 * - new sequence reference for the annotation row - if null,
1348 * sequenceRef is left unchanged
1350 * array of ints containing corresponding positions
1352 * - column for current coordinate system (-1 for index+1)
1354 * - column for destination coordinate system (-1 for index+1)
1356 * - offset added to index when referencing either coordinate system
1357 * @note no checks are made as to whether from and/or to are sensible
1358 * @note caller should add the remapped annotation to newref if they have not
1361 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1362 int from, int to, int idxoffset)
1364 if (mapping != null)
1366 Map<Integer, Annotation> old = sequenceMapping;
1367 Map<Integer, Annotation> remap = new HashMap<>();
1369 for (int mp[] : mapping.values())
1375 Annotation ann = null;
1378 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1382 if (mp != null && mp.length > from)
1384 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1391 remap.put(Integer.valueOf(idxoffset + index), ann);
1395 if (to > -1 && to < mp.length)
1397 remap.put(Integer.valueOf(mp[to]), ann);
1402 sequenceMapping = remap;
1406 sequenceRef = newref;
1408 adjustForAlignment();
1412 public String getProperty(String property)
1414 if (properties == null)
1418 return properties.get(property);
1421 public void setProperty(String property, String value)
1423 if (properties == null)
1425 properties = new HashMap<>();
1427 properties.put(property, value);
1430 public boolean hasProperties()
1432 return properties != null && properties.size() > 0;
1435 public Collection<String> getProperties()
1437 if (properties == null)
1439 return Collections.emptyList();
1441 return properties.keySet();
1445 * Returns the Annotation for the given sequence position (base 1) if any,
1451 public Annotation getAnnotationForPosition(int position)
1453 return sequenceMapping == null ? null : sequenceMapping.get(position);
1458 * Set the id to "ann" followed by a counter that increments so as to be
1459 * unique for the lifetime of the JVM
1461 protected final void setAnnotationId()
1463 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1467 * Returns the match for the last unmatched opening RNA helix pair symbol
1468 * preceding the given column, or '(' if nothing found to match.
1473 public String getDefaultRnaHelixSymbol(int column)
1475 String result = "(";
1476 if (annotations == null)
1482 * for each preceding column, if it contains an open bracket,
1483 * count whether it is still unmatched at column, if so return its pair
1484 * (likely faster than the fancy alternative using stacks)
1486 for (int col = column - 1; col >= 0; col--)
1488 Annotation annotation = annotations[col];
1489 if (annotation == null)
1493 String displayed = annotation.displayCharacter;
1494 if (displayed == null || displayed.length() != 1)
1498 char symbol = displayed.charAt(0);
1499 if (!Rna.isOpeningParenthesis(symbol))
1505 * found an opening bracket symbol
1506 * count (closing-opening) symbols of this type that follow it,
1507 * up to and excluding the target column; if the count is less
1508 * than 1, the opening bracket is unmatched, so return its match
1510 String closer = String
1511 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1512 String opener = String.valueOf(symbol);
1514 for (int j = col + 1; j < column; j++)
1516 if (annotations[j] != null)
1518 String s = annotations[j].displayCharacter;
1519 if (closer.equals(s))
1523 else if (opener.equals(s))
1537 protected static synchronized long nextId()
1544 * @return true for rows that have a range of values in their annotation set
1546 public boolean isQuantitative()
1548 return graphMin < graphMax;
1552 * delete any columns in alignmentAnnotation that are hidden (including
1553 * sequence associated annotation).
1555 * @param hiddenColumns
1556 * the set of hidden columns
1558 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1560 if (annotations != null)
1562 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1567 * delete any columns in alignmentAnnotation that are hidden (including
1568 * sequence associated annotation).
1571 * remove any annotation to the right of this column
1573 * remove any annotation to the left of this column
1574 * @param hiddenColumns
1575 * the set of hidden columns
1577 public void makeVisibleAnnotation(int start, int end,
1578 HiddenColumns hiddenColumns)
1580 if (annotations != null)
1582 if (hiddenColumns.hasHiddenColumns())
1584 removeHiddenAnnotation(start, end, hiddenColumns);
1588 restrict(start, end);
1594 * The actual implementation of deleting hidden annotation columns
1597 * remove any annotation to the right of this column
1599 * remove any annotation to the left of this column
1600 * @param hiddenColumns
1601 * the set of hidden columns
1603 private void removeHiddenAnnotation(int start, int end,
1604 HiddenColumns hiddenColumns)
1606 // mangle the alignmentAnnotation annotation array
1607 ArrayList<Annotation[]> annels = new ArrayList<>();
1608 Annotation[] els = null;
1612 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1616 int annotationLength;
1617 while (blocks.hasNext())
1619 int[] block = blocks.next();
1620 annotationLength = block[1] - block[0] + 1;
1622 if (blocks.hasNext())
1624 // copy just the visible segment of the annotation row
1625 copylength = annotationLength;
1629 if (annotationLength + block[0] <= annotations.length)
1631 // copy just the visible segment of the annotation row
1632 copylength = annotationLength;
1636 // copy to the end of the annotation row
1637 copylength = annotations.length - block[0];
1641 els = new Annotation[annotationLength];
1643 System.arraycopy(annotations, block[0], els, 0, copylength);
1644 w += annotationLength;
1649 annotations = new Annotation[w];
1652 for (Annotation[] chnk : annels)
1654 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1660 public static Iterable<AlignmentAnnotation> findAnnotations(
1661 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1665 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1666 for (AlignmentAnnotation ann : list)
1668 if ((calcId == null || (ann.getCalcId() != null
1669 && ann.getCalcId().equals(calcId)))
1670 && (seq == null || (ann.sequenceRef != null
1671 && ann.sequenceRef == seq))
1673 || (ann.label != null && ann.label.equals(label))))
1682 * Answer true if any annotation matches the calcId passed in (if not null).
1685 * annotation to search
1689 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1693 if (calcId != null && !"".equals(calcId))
1695 for (AlignmentAnnotation a : list)
1697 if (a.getCalcId() == calcId)
1706 public static Iterable<AlignmentAnnotation> findAnnotation(
1707 List<AlignmentAnnotation> list, String calcId)
1710 List<AlignmentAnnotation> aa = new ArrayList<>();
1715 for (AlignmentAnnotation a : list)
1718 if (a.getCalcId() == calcId || (a.getCalcId() != null
1719 && calcId != null && a.getCalcId().equals(calcId)))