2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.datamodel;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Locale;
32 import java.util.Map.Entry;
34 import jalview.analysis.Rna;
35 import jalview.analysis.SecStrConsensus.SimpleBP;
36 import jalview.analysis.WUSSParseException;
44 public class AlignmentAnnotation
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 public static enum TFType
101 DEFAULT, PLDDT, DOSE;
105 * the type of temperature factor plot (if it is one)
107 private TFType tfType = TFType.DEFAULT;
109 public void setTFType(TFType t)
114 public TFType getTFType()
120 * Updates the _rnasecstr field Determines the positions that base pair and
121 * the positions of helices based on secondary structure from a Stockholm file
123 * @param rnaAnnotation
125 private void _updateRnaSecStr(CharSequence rnaAnnotation)
129 _rnasecstr = Rna.getHelixMap(rnaAnnotation);
130 invalidrnastruc = -1;
131 } catch (WUSSParseException px)
133 // DEBUG System.out.println(px);
134 invalidrnastruc = px.getProblemPos();
136 if (invalidrnastruc > -1)
141 if (_rnasecstr != null && _rnasecstr.length > 0)
143 // show all the RNA secondary structure annotation symbols.
145 showAllColLabels = true;
146 scaleColLabel = true;
149 // System.out.println("featuregroup " + _rnasecstr[0].getFeatureGroup());
153 private void _markRnaHelices()
156 // Figure out number of helices
157 // Length of rnasecstr is the number of pairs of positions that base pair
158 // with each other in the secondary structure
159 for (int x = 0; x < _rnasecstr.length; x++)
163 * System.out.println(this.annotation._rnasecstr[x] + " Begin" +
164 * this.annotation._rnasecstr[x].getBegin());
166 // System.out.println(this.annotation._rnasecstr[x].getFeatureGroup());
170 val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
175 } catch (NumberFormatException q)
180 annotations[_rnasecstr[x].getBegin()].value = val;
181 annotations[_rnasecstr[x].getEnd()].value = val;
183 // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
184 // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
190 * Get the RNA Secondary Structure SequenceFeature Array if present
192 public SequenceFeature[] getRnaSecondaryStructure()
194 return this._rnasecstr;
198 * Check the RNA Secondary Structure is equivalent to one in given
199 * AlignmentAnnotation param
201 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that)
203 return rnaSecondaryStructureEquivalent(that, true);
206 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that,
209 SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
210 SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
211 if (thisSfArray == null || thatSfArray == null)
213 return thisSfArray == null && thatSfArray == null;
215 if (thisSfArray.length != thatSfArray.length)
219 Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
221 Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
223 for (int i = 0; i < thisSfArray.length; i++)
225 SequenceFeature thisSf = thisSfArray[i];
226 SequenceFeature thatSf = thatSfArray[i];
229 if (thisSf.getType() == null || thatSf.getType() == null)
231 if (thisSf.getType() == null && thatSf.getType() == null)
240 if (!thisSf.getType().equals(thatSf.getType()))
245 if (!(thisSf.getBegin() == thatSf.getBegin()
246 && thisSf.getEnd() == thatSf.getEnd()))
256 * map of positions in the associated annotation
258 private Map<Integer, Annotation> sequenceMapping;
261 * lower range for quantitative data
263 public float graphMin;
266 * Upper range for quantitative data
268 public float graphMax;
271 * Score associated with label and description.
273 public double score = Double.NaN;
276 * flag indicating if annotation has a score.
278 public boolean hasScore = false;
280 public GraphLine threshold;
282 // Graphical hints and tips
284 /** Can this row be edited by the user ? */
285 public boolean editable = false;
287 /** Indicates if annotation has a graphical symbol track */
288 public boolean hasIcons; //
290 /** Indicates if annotation has a text character label */
291 public boolean hasText;
293 /** is the row visible */
294 public boolean visible = true;
296 public int graphGroup = -1;
298 /** Displayed height of row in pixels */
299 public int height = 0;
301 public int graph = 0;
303 public int graphHeight = 40;
305 public boolean padGaps = false;
307 public static final int NO_GRAPH = 0;
309 public static final int BAR_GRAPH = 1;
311 public static final int LINE_GRAPH = 2;
313 public static final int CUSTOMRENDERER = 4;
315 public boolean belowAlignment = true;
317 public SequenceGroup groupRef = null;
320 * display every column label, even if there is a row of identical labels
322 public boolean showAllColLabels = false;
325 * scale the column label to fit within the alignment column.
327 public boolean scaleColLabel = false;
330 * centre the column labels relative to the alignment column
332 public boolean centreColLabels = false;
334 private boolean isrna;
336 public static int getGraphValueFromString(String string)
338 if (string.equalsIgnoreCase("BAR_GRAPH"))
342 else if (string.equalsIgnoreCase("LINE_GRAPH"))
353 * Creates a new AlignmentAnnotation object.
356 * short label shown under sequence labels
358 * text displayed on mouseover
360 * set of positional annotation elements
362 public AlignmentAnnotation(String label, String description,
363 Annotation[] annotations)
369 this.description = description;
370 this.annotations = annotations;
372 validateRangeAndDisplay();
376 * Checks if annotation labels represent secondary structures
379 void areLabelsSecondaryStructure()
381 boolean nonSSLabel = false;
383 StringBuffer rnastring = new StringBuffer();
386 for (int i = 0; i < annotations.length; i++)
388 // DEBUG System.out.println(i + ": " + annotations[i]);
389 if (annotations[i] == null)
393 if (annotations[i].secondaryStructure == 'H'
394 || annotations[i].secondaryStructure == 'E')
396 // DEBUG System.out.println( "/H|E/ '" +
397 // annotations[i].secondaryStructure + "'");
401 // Check for RNA secondary structure
403 // DEBUG System.out.println( "/else/ '" +
404 // annotations[i].secondaryStructure + "'");
405 // TODO: 2.8.2 should this ss symbol validation check be a function in
406 // RNA/ResidueProperties ?
407 // allow for DSSP extended code:
408 // https://www.wikidoc.org/index.php/Secondary_structure#The_DSSP_code
409 // GHITEBS as well as C and X (for missing?)
410 if (annotations[i].secondaryStructure == '('
411 || annotations[i].secondaryStructure == '['
412 || annotations[i].secondaryStructure == '<'
413 || annotations[i].secondaryStructure == '{'
414 || annotations[i].secondaryStructure == 'A'
415 // || annotations[i].secondaryStructure == 'B'
416 // || annotations[i].secondaryStructure == 'C'
417 || annotations[i].secondaryStructure == 'D'
418 // || annotations[i].secondaryStructure == 'E' // ambiguous on
419 // its own -- already checked above
420 || annotations[i].secondaryStructure == 'F'
421 // || annotations[i].secondaryStructure == 'G'
422 // || annotations[i].secondaryStructure == 'H' // ambiguous on
423 // its own -- already checked above
424 // || annotations[i].secondaryStructure == 'I'
425 || annotations[i].secondaryStructure == 'J'
426 || annotations[i].secondaryStructure == 'K'
427 || annotations[i].secondaryStructure == 'L'
428 || annotations[i].secondaryStructure == 'M'
429 || annotations[i].secondaryStructure == 'N'
430 || annotations[i].secondaryStructure == 'O'
431 || annotations[i].secondaryStructure == 'P'
432 || annotations[i].secondaryStructure == 'Q'
433 || annotations[i].secondaryStructure == 'R'
434 // || annotations[i].secondaryStructure == 'S'
435 // || annotations[i].secondaryStructure == 'T'
436 || annotations[i].secondaryStructure == 'U'
437 || annotations[i].secondaryStructure == 'V'
438 || annotations[i].secondaryStructure == 'W'
439 // || annotations[i].secondaryStructure == 'X'
440 || annotations[i].secondaryStructure == 'Y'
441 || annotations[i].secondaryStructure == 'Z')
448 // System.out.println("displaychar " + annotations[i].displayCharacter);
450 if (annotations[i].displayCharacter == null
451 || annotations[i].displayCharacter.length() == 0)
453 rnastring.append('.');
456 if (annotations[i].displayCharacter.length() == 1)
458 firstChar = annotations[i].displayCharacter.charAt(0);
459 // check to see if it looks like a sequence or is secondary structure
461 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
462 // Uncomment to only catch case where
463 // displayCharacter==secondary
465 // to correctly redisplay SS annotation imported from Stockholm,
466 // exported to JalviewXML and read back in again.
468 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
469 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
470 && firstChar != '(' && firstChar != '[' && firstChar != '<'
471 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
472 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
473 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
474 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
475 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
476 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
477 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
478 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
479 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
481 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
483 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
496 rnastring.append(annotations[i].displayCharacter.charAt(1));
499 if (annotations[i].displayCharacter.length() > 0)
508 for (int j = 0; j < annotations.length; j++)
510 if (annotations[j] != null
511 && annotations[j].secondaryStructure != ' ')
513 annotations[j].displayCharacter = String
514 .valueOf(annotations[j].secondaryStructure);
515 annotations[j].secondaryStructure = ' ';
524 _updateRnaSecStr(new AnnotCharSequence());
530 * flyweight access to positions in the alignment annotation row for RNA
536 private class AnnotCharSequence implements CharSequence
542 public AnnotCharSequence()
544 this(0, annotations.length);
547 AnnotCharSequence(int start, int end)
554 public CharSequence subSequence(int start, int end)
556 return new AnnotCharSequence(offset + start, offset + end);
566 public char charAt(int index)
568 return ((index + offset < 0) || (index + offset) >= max
569 || annotations[index + offset] == null
570 || (annotations[index + offset].secondaryStructure <= ' ')
572 : annotations[index + offset].displayCharacter == null
574 + offset].displayCharacter
577 + offset].secondaryStructure
579 + offset].displayCharacter
584 public String toString()
586 char[] string = new char[max - offset];
587 int mx = annotations.length;
589 for (int i = offset; i < mx; i++)
591 string[i] = (annotations[i] == null
592 || (annotations[i].secondaryStructure <= 32))
594 : (annotations[i].displayCharacter == null
595 || annotations[i].displayCharacter
597 ? annotations[i].secondaryStructure
598 : annotations[i].displayCharacter
601 return new String(string);
605 private long _lastrnaannot = -1;
607 public String getRNAStruc()
611 String rnastruc = new AnnotCharSequence().toString();
612 if (_lastrnaannot != rnastruc.hashCode())
614 // ensure rna structure contacts are up to date
615 _lastrnaannot = rnastruc.hashCode();
616 _updateRnaSecStr(rnastruc);
624 * Creates a new AlignmentAnnotation object.
639 public AlignmentAnnotation(String label, String description,
640 Annotation[] annotations, float min, float max, int graphType)
643 // graphs are not editable
644 editable = graphType == 0;
647 this.description = description;
648 this.annotations = annotations;
652 validateRangeAndDisplay();
656 * checks graphMin and graphMax, secondary structure symbols, sets graphType
657 * appropriately, sets null labels to the empty string if appropriate.
659 public void validateRangeAndDisplay()
662 if (annotations == null)
664 visible = false; // try to prevent renderer from displaying.
665 invalidrnastruc = -1;
666 return; // this is a non-annotation row annotation - ie a sequence score.
669 int graphType = graph;
670 float min = graphMin;
671 float max = graphMax;
672 boolean drawValues = true;
677 for (int i = 0; i < annotations.length; i++)
679 if (annotations[i] == null)
684 if (drawValues && annotations[i].displayCharacter != null
685 && annotations[i].displayCharacter.length() > 1)
690 if (annotations[i].value > max)
692 max = annotations[i].value;
695 if (annotations[i].value < min)
697 min = annotations[i].value;
699 if (_linecolour == null && annotations[i].colour != null)
701 _linecolour = annotations[i].colour;
704 // ensure zero is origin for min/max ranges on only one side of zero
721 areLabelsSecondaryStructure();
723 if (!drawValues && graphType != NO_GRAPH)
725 for (int i = 0; i < annotations.length; i++)
727 if (annotations[i] != null)
729 annotations[i].displayCharacter = "";
736 * Copy constructor creates a new independent annotation row with the same
737 * associated sequenceRef
741 public AlignmentAnnotation(AlignmentAnnotation annotation)
744 this.label = new String(annotation.label);
745 if (annotation.description != null)
747 this.description = new String(annotation.description);
749 this.graphMin = annotation.graphMin;
750 this.graphMax = annotation.graphMax;
751 this.graph = annotation.graph;
752 this.graphHeight = annotation.graphHeight;
753 this.graphGroup = annotation.graphGroup;
754 this.groupRef = annotation.groupRef;
755 this.editable = annotation.editable;
756 this.autoCalculated = annotation.autoCalculated;
757 this.hasIcons = annotation.hasIcons;
758 this.hasText = annotation.hasText;
759 this.height = annotation.height;
760 this.label = annotation.label;
761 this.padGaps = annotation.padGaps;
762 this.visible = annotation.visible;
763 this.centreColLabels = annotation.centreColLabels;
764 this.scaleColLabel = annotation.scaleColLabel;
765 this.showAllColLabels = annotation.showAllColLabels;
766 this.calcId = annotation.calcId;
767 if (annotation.properties != null)
769 properties = new HashMap<>();
770 for (Map.Entry<String, String> val : annotation.properties.entrySet())
772 properties.put(val.getKey(), val.getValue());
775 if (this.hasScore = annotation.hasScore)
777 this.score = annotation.score;
779 if (annotation.threshold != null)
781 threshold = new GraphLine(annotation.threshold);
783 Annotation[] ann = annotation.annotations;
784 if (annotation.annotations != null)
786 this.annotations = new Annotation[ann.length];
787 for (int i = 0; i < ann.length; i++)
791 annotations[i] = new Annotation(ann[i]);
792 if (_linecolour != null)
794 _linecolour = annotations[i].colour;
799 if (annotation.sequenceRef != null)
801 this.sequenceRef = annotation.sequenceRef;
802 if (annotation.sequenceMapping != null)
805 sequenceMapping = new HashMap<>();
806 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
808 while (pos.hasNext())
810 // could optimise this!
812 Annotation a = annotation.sequenceMapping.get(p);
819 for (int i = 0; i < ann.length; i++)
823 sequenceMapping.put(p, annotations[i]);
831 this.sequenceMapping = null;
835 // TODO: check if we need to do this: JAL-952
836 // if (this.isrna=annotation.isrna)
838 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
840 validateRangeAndDisplay(); // construct hashcodes, etc.
844 * clip the annotation to the columns given by startRes and endRes (inclusive)
845 * and prune any existing sequenceMapping to just those columns.
850 public void restrict(int startRes, int endRes)
852 if (annotations == null)
861 if (startRes >= annotations.length)
863 startRes = annotations.length - 1;
865 if (endRes >= annotations.length)
867 endRes = annotations.length - 1;
869 if (annotations == null)
873 Annotation[] temp = new Annotation[endRes - startRes + 1];
874 if (startRes < annotations.length)
876 System.arraycopy(annotations, startRes, temp, 0,
877 endRes - startRes + 1);
879 if (sequenceRef != null)
881 // Clip the mapping, if it exists.
882 int spos = sequenceRef.findPosition(startRes);
883 int epos = sequenceRef.findPosition(endRes);
884 if (sequenceMapping != null)
886 Map<Integer, Annotation> newmapping = new HashMap<>();
887 Iterator<Integer> e = sequenceMapping.keySet().iterator();
890 Integer pos = e.next();
891 if (pos.intValue() >= spos && pos.intValue() <= epos)
893 newmapping.put(pos, sequenceMapping.get(pos));
896 sequenceMapping.clear();
897 sequenceMapping = newmapping;
904 * set the annotation row to be at least length Annotations
907 * minimum number of columns required in the annotation row
908 * @return false if the annotation row is greater than length
910 public boolean padAnnotation(int length)
912 if (annotations == null)
914 return true; // annotation row is correct - null == not visible and
917 if (annotations.length < length)
919 Annotation[] na = new Annotation[length];
920 System.arraycopy(annotations, 0, na, 0, annotations.length);
924 return annotations.length > length;
931 * @return DOCUMENT ME!
934 public String toString()
936 if (annotations == null)
940 StringBuilder buffer = new StringBuilder(256);
942 for (int i = 0; i < annotations.length; i++)
944 if (annotations[i] != null)
948 buffer.append(annotations[i].value);
952 buffer.append(annotations[i].secondaryStructure);
956 buffer.append(annotations[i].displayCharacter);
962 // TODO: remove disgusting hack for 'special' treatment of consensus line.
963 if (label.indexOf("Consensus") == 0)
967 for (int i = 0; i < annotations.length; i++)
969 if (annotations[i] != null)
971 buffer.append(annotations[i].description);
978 return buffer.toString();
981 public void setThreshold(GraphLine line)
986 public GraphLine getThreshold()
992 * Attach the annotation to seqRef, starting from startRes position. If
993 * alreadyMapped is true then the indices of the annotation[] array are
994 * sequence positions rather than alignment column positions.
998 * @param alreadyMapped
1000 public void createSequenceMapping(SequenceI seqRef, int startRes,
1001 boolean alreadyMapped)
1008 sequenceRef = seqRef;
1009 if (annotations == null)
1013 sequenceMapping = new HashMap<>();
1017 for (int i = 0; i < annotations.length; i++)
1019 if (annotations[i] != null)
1023 seqPos = seqRef.findPosition(i);
1027 seqPos = i + startRes;
1030 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1037 * When positional annotation and a sequence reference is present, clears and
1038 * resizes the annotations array to the current alignment width, and adds
1039 * annotation according to aligned positions of the sequenceRef given by
1042 public void adjustForAlignment()
1044 if (sequenceRef == null)
1049 if (annotations == null)
1054 int a = 0, aSize = sequenceRef.getLength();
1063 Annotation[] temp = new Annotation[aSize];
1065 if (sequenceMapping != null)
1067 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1069 index = Integer.valueOf(a);
1070 Annotation annot = sequenceMapping.get(index);
1073 position = sequenceRef.findIndex(a) - 1;
1075 temp[position] = annot;
1083 * remove any null entries in annotation row and return the number of non-null
1084 * annotation elements.
1088 public int compactAnnotationArray()
1090 int i = 0, iSize = annotations.length;
1093 if (annotations[i] == null)
1097 System.arraycopy(annotations, i + 1, annotations, i,
1107 Annotation[] ann = annotations;
1108 annotations = new Annotation[i];
1109 System.arraycopy(ann, 0, annotations, 0, i);
1115 * Associate this annotation with the aligned residues of a particular
1116 * sequence. sequenceMapping will be updated in the following way: null
1117 * sequenceI - existing mapping will be discarded but annotations left in
1118 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1119 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1120 * parameter to specify correspondence between current and new sequenceRef
1124 public void setSequenceRef(SequenceI sequenceI)
1126 if (sequenceI != null)
1128 if (sequenceRef != null)
1130 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1131 tIsDs = sequenceI.getDatasetSequence() == null;
1132 if (sequenceRef != sequenceI
1134 && sequenceRef != sequenceI.getDatasetSequence())
1136 && sequenceRef.getDatasetSequence() != sequenceI)
1137 && (!rIsDs && !tIsDs
1138 && sequenceRef.getDatasetSequence() != sequenceI
1139 .getDatasetSequence())
1140 && !sequenceRef.equals(sequenceI))
1142 // if sequenceRef isn't intersecting with sequenceI
1143 // throw away old mapping and reconstruct.
1145 if (sequenceMapping != null)
1147 sequenceMapping = null;
1148 // compactAnnotationArray();
1150 createSequenceMapping(sequenceI, 1, true);
1151 adjustForAlignment();
1155 // Mapping carried over
1156 sequenceRef = sequenceI;
1161 // No mapping exists
1162 createSequenceMapping(sequenceI, 1, true);
1163 adjustForAlignment();
1168 // throw away the mapping without compacting.
1169 sequenceMapping = null;
1177 public double getScore()
1186 public void setScore(double score)
1194 * @return true if annotation has an associated score
1196 public boolean hasScore()
1198 return hasScore || !Double.isNaN(score);
1202 * Score only annotation
1205 * @param description
1208 public AlignmentAnnotation(String label, String description, double score)
1210 this(label, description, null);
1215 * copy constructor with edit based on the hidden columns marked in colSel
1217 * @param alignmentAnnotation
1220 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1221 HiddenColumns hidden)
1223 this(alignmentAnnotation);
1224 if (annotations == null)
1228 makeVisibleAnnotation(hidden);
1231 public void setPadGaps(boolean padgaps, char gapchar)
1233 this.padGaps = padgaps;
1237 for (int i = 0; i < annotations.length; i++)
1239 if (annotations[i] == null)
1241 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1244 else if (annotations[i].displayCharacter == null
1245 || annotations[i].displayCharacter.equals(" "))
1247 annotations[i].displayCharacter = String.valueOf(gapchar);
1254 * format description string for display
1257 * @return Get the annotation description string optionally prefixed by
1258 * associated sequence name (if any)
1260 public String getDescription(boolean seqname)
1262 if (seqname && this.sequenceRef != null)
1264 int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1267 // move the html tag to before the sequence reference.
1268 return "<html>" + sequenceRef.getName() + " : "
1269 + description.substring(i + 6);
1271 return sequenceRef.getName() + " : " + description;
1276 public boolean isValidStruc()
1278 return invalidrnastruc == -1;
1281 public long getInvalidStrucPos()
1283 return invalidrnastruc;
1287 * machine readable ID string indicating what generated this annotation
1289 protected String calcId = "";
1292 * properties associated with the calcId
1294 protected Map<String, String> properties = new HashMap<>();
1297 * base colour for line graphs. If null, will be set automatically by
1298 * searching the alignment annotation
1300 public java.awt.Color _linecolour;
1302 public String getCalcId()
1307 public void setCalcId(String calcId)
1309 this.calcId = calcId;
1312 public boolean isRNA()
1318 * transfer annotation to the given sequence using the given mapping from the
1319 * current positions or an existing sequence mapping
1323 * map involving sq as To or From
1325 public void liftOver(SequenceI sq, Mapping sp2sq)
1327 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1329 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1330 // Protein reference frames
1332 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1334 boolean mapIsTo = (sp2sq != null)
1335 ? (sp2sq.getTo() == sq
1336 || sp2sq.getTo() == sq.getDatasetSequence())
1339 // TODO build a better annotation element map and get rid of annotations[]
1340 Map<Integer, Annotation> mapForsq = new HashMap<>();
1341 if (sequenceMapping != null)
1345 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1347 Integer mpos = Integer
1348 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1349 : sp2sq.getPosition(ie.getKey()));
1350 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1352 mapForsq.put(mpos, ie.getValue());
1355 sequenceMapping = mapForsq;
1357 adjustForAlignment();
1367 * like liftOver but more general.
1369 * Takes an array of int pairs that will be used to update the internal
1370 * sequenceMapping and so shuffle the annotated positions
1373 * - new sequence reference for the annotation row - if null,
1374 * sequenceRef is left unchanged
1376 * array of ints containing corresponding positions
1378 * - column for current coordinate system (-1 for index+1)
1380 * - column for destination coordinate system (-1 for index+1)
1382 * - offset added to index when referencing either coordinate system
1383 * @note no checks are made as to whether from and/or to are sensible
1384 * @note caller should add the remapped annotation to newref if they have not
1387 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1388 int from, int to, int idxoffset)
1390 if (mapping != null)
1392 Map<Integer, Annotation> old = sequenceMapping;
1393 Map<Integer, Annotation> remap = new HashMap<>();
1395 for (int mp[] : mapping.values())
1401 Annotation ann = null;
1404 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1408 if (mp != null && mp.length > from)
1410 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1417 remap.put(Integer.valueOf(idxoffset + index), ann);
1421 if (to > -1 && to < mp.length)
1423 remap.put(Integer.valueOf(mp[to]), ann);
1428 sequenceMapping = remap;
1432 sequenceRef = newref;
1434 adjustForAlignment();
1438 public String getProperty(String property)
1440 if (properties == null)
1444 return properties.get(property);
1447 public void setProperty(String property, String value)
1449 if (properties == null)
1451 properties = new HashMap<>();
1453 properties.put(property, value);
1456 public boolean hasProperties()
1458 return properties != null && properties.size() > 0;
1461 public Collection<String> getProperties()
1463 if (properties == null)
1465 return Collections.emptyList();
1467 return properties.keySet();
1471 * Returns the Annotation for the given sequence position (base 1) if any,
1477 public Annotation getAnnotationForPosition(int position)
1479 return sequenceMapping == null ? null : sequenceMapping.get(position);
1484 * Set the id to "ann" followed by a counter that increments so as to be
1485 * unique for the lifetime of the JVM
1487 protected final void setAnnotationId()
1489 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1493 * Returns the match for the last unmatched opening RNA helix pair symbol
1494 * preceding the given column, or '(' if nothing found to match.
1499 public String getDefaultRnaHelixSymbol(int column)
1501 String result = "(";
1502 if (annotations == null)
1508 * for each preceding column, if it contains an open bracket,
1509 * count whether it is still unmatched at column, if so return its pair
1510 * (likely faster than the fancy alternative using stacks)
1512 for (int col = column - 1; col >= 0; col--)
1514 Annotation annotation = annotations[col];
1515 if (annotation == null)
1519 String displayed = annotation.displayCharacter;
1520 if (displayed == null || displayed.length() != 1)
1524 char symbol = displayed.charAt(0);
1525 if (!Rna.isOpeningParenthesis(symbol))
1531 * found an opening bracket symbol
1532 * count (closing-opening) symbols of this type that follow it,
1533 * up to and excluding the target column; if the count is less
1534 * than 1, the opening bracket is unmatched, so return its match
1536 String closer = String
1537 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1538 String opener = String.valueOf(symbol);
1540 for (int j = col + 1; j < column; j++)
1542 if (annotations[j] != null)
1544 String s = annotations[j].displayCharacter;
1545 if (closer.equals(s))
1549 else if (opener.equals(s))
1563 protected static synchronized long nextId()
1570 * @return true for rows that have a range of values in their annotation set
1572 public boolean isQuantitative()
1574 return graphMin < graphMax;
1578 * delete any columns in alignmentAnnotation that are hidden (including
1579 * sequence associated annotation).
1581 * @param hiddenColumns
1582 * the set of hidden columns
1584 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1586 if (annotations != null)
1588 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1593 * delete any columns in alignmentAnnotation that are hidden (including
1594 * sequence associated annotation).
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 public void makeVisibleAnnotation(int start, int end,
1604 HiddenColumns hiddenColumns)
1606 if (annotations != null)
1608 if (hiddenColumns.hasHiddenColumns())
1610 removeHiddenAnnotation(start, end, hiddenColumns);
1614 restrict(start, end);
1620 * The actual implementation of deleting hidden annotation columns
1623 * remove any annotation to the right of this column
1625 * remove any annotation to the left of this column
1626 * @param hiddenColumns
1627 * the set of hidden columns
1629 private void removeHiddenAnnotation(int start, int end,
1630 HiddenColumns hiddenColumns)
1632 // mangle the alignmentAnnotation annotation array
1633 ArrayList<Annotation[]> annels = new ArrayList<>();
1634 Annotation[] els = null;
1638 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1642 int annotationLength;
1643 while (blocks.hasNext())
1645 int[] block = blocks.next();
1646 annotationLength = block[1] - block[0] + 1;
1648 if (blocks.hasNext())
1650 // copy just the visible segment of the annotation row
1651 copylength = annotationLength;
1655 if (annotationLength + block[0] <= annotations.length)
1657 // copy just the visible segment of the annotation row
1658 copylength = annotationLength;
1662 // copy to the end of the annotation row
1663 copylength = annotations.length - block[0];
1667 els = new Annotation[annotationLength];
1669 System.arraycopy(annotations, block[0], els, 0, copylength);
1670 w += annotationLength;
1675 annotations = new Annotation[w];
1678 for (Annotation[] chnk : annels)
1680 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1686 public static Iterable<AlignmentAnnotation> findAnnotations(
1687 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1691 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1692 for (AlignmentAnnotation ann : list)
1694 if ((calcId == null || (ann.getCalcId() != null
1695 && ann.getCalcId().equals(calcId)))
1696 && (seq == null || (ann.sequenceRef != null
1697 && ann.sequenceRef == seq))
1699 || (ann.label != null && ann.label.equals(label))))
1708 * Answer true if any annotation matches the calcId passed in (if not null).
1711 * annotation to search
1715 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1719 if (calcId != null && !"".equals(calcId))
1721 for (AlignmentAnnotation a : list)
1723 if (a.getCalcId() == calcId)
1732 public static Iterable<AlignmentAnnotation> findAnnotation(
1733 List<AlignmentAnnotation> list, String calcId)
1736 List<AlignmentAnnotation> aa = new ArrayList<>();
1741 for (AlignmentAnnotation a : list)
1744 if (a.getCalcId() == calcId || (a.getCalcId() != null
1745 && calcId != null && a.getCalcId().equals(calcId)))