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;
37 import jalview.structure.StructureImportSettings;
45 public class AlignmentAnnotation
48 private static final String ANNOTATION_ID_PREFIX = "ann";
51 * Identifers for different types of profile data
53 public static final int SEQUENCE_PROFILE = 0;
55 public static final int STRUCTURE_PROFILE = 1;
57 public static final int CDNA_PROFILE = 2;
59 private static long counter = 0;
62 * If true, this annotations is calculated every edit, eg consensus, quality
63 * or conservation graphs
65 public boolean autoCalculated = false;
68 * unique ID for this annotation, used to match up the same annotation row
69 * shown in multiple views and alignments
71 public String annotationId;
74 * the sequence this annotation is associated with (or null)
76 public SequenceI sequenceRef;
78 /** label shown in dropdown menus and in the annotation label area */
81 /** longer description text shown as a tooltip */
82 public String description;
84 /** Array of annotations placed in the current coordinate system */
85 public Annotation[] annotations;
87 public List<SimpleBP> bps = null;
90 * RNA secondary structure contact positions
92 public SequenceFeature[] _rnasecstr = null;
95 * position of annotation resulting in invalid WUSS parsing or -1. -2 means
96 * there was no RNA structure in this annotation
98 private long invalidrnastruc = -2;
101 * the type of temperature factor plot (if it is one)
103 private StructureImportSettings.TFType tfType = StructureImportSettings.TFType.DEFAULT;
105 public void setTFType(StructureImportSettings.TFType t)
110 public StructureImportSettings.TFType getTFType()
116 * Updates the _rnasecstr field Determines the positions that base pair and
117 * the positions of helices based on secondary structure from a Stockholm file
119 * @param rnaAnnotation
121 private void _updateRnaSecStr(CharSequence rnaAnnotation)
125 _rnasecstr = Rna.getHelixMap(rnaAnnotation);
126 invalidrnastruc = -1;
127 } catch (WUSSParseException px)
129 // DEBUG jalview.bin.Console.outPrintln(px);
130 invalidrnastruc = px.getProblemPos();
132 if (invalidrnastruc > -1)
137 if (_rnasecstr != null && _rnasecstr.length > 0)
139 // show all the RNA secondary structure annotation symbols.
141 showAllColLabels = true;
142 scaleColLabel = true;
145 // jalview.bin.Console.outPrintln("featuregroup " +
146 // _rnasecstr[0].getFeatureGroup());
150 private void _markRnaHelices()
153 // Figure out number of helices
154 // Length of rnasecstr is the number of pairs of positions that base pair
155 // with each other in the secondary structure
156 for (int x = 0; x < _rnasecstr.length; x++)
160 * jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x] + " Begin" +
161 * this.annotation._rnasecstr[x].getBegin());
163 // jalview.bin.Console.outPrintln(this.annotation._rnasecstr[x].getFeatureGroup());
167 val = Integer.valueOf(_rnasecstr[x].getFeatureGroup());
172 } catch (NumberFormatException q)
177 annotations[_rnasecstr[x].getBegin()].value = val;
178 annotations[_rnasecstr[x].getEnd()].value = val;
180 // annotations[_rnasecstr[x].getBegin()].displayCharacter = "" + val;
181 // annotations[_rnasecstr[x].getEnd()].displayCharacter = "" + val;
187 * Get the RNA Secondary Structure SequenceFeature Array if present
189 public SequenceFeature[] getRnaSecondaryStructure()
191 return this._rnasecstr;
195 * Check the RNA Secondary Structure is equivalent to one in given
196 * AlignmentAnnotation param
198 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that)
200 return rnaSecondaryStructureEquivalent(that, true);
203 public boolean rnaSecondaryStructureEquivalent(AlignmentAnnotation that,
206 SequenceFeature[] thisSfArray = this.getRnaSecondaryStructure();
207 SequenceFeature[] thatSfArray = that.getRnaSecondaryStructure();
208 if (thisSfArray == null || thatSfArray == null)
210 return thisSfArray == null && thatSfArray == null;
212 if (thisSfArray.length != thatSfArray.length)
216 Arrays.sort(thisSfArray, new SFSortByEnd()); // probably already sorted
218 Arrays.sort(thatSfArray, new SFSortByEnd()); // probably already sorted
220 for (int i = 0; i < thisSfArray.length; i++)
222 SequenceFeature thisSf = thisSfArray[i];
223 SequenceFeature thatSf = thatSfArray[i];
226 if (thisSf.getType() == null || thatSf.getType() == null)
228 if (thisSf.getType() == null && thatSf.getType() == null)
237 if (!thisSf.getType().equals(thatSf.getType()))
242 if (!(thisSf.getBegin() == thatSf.getBegin()
243 && thisSf.getEnd() == thatSf.getEnd()))
253 * map of positions in the associated annotation
255 private Map<Integer, Annotation> sequenceMapping;
258 * lower range for quantitative data
260 public float graphMin;
263 * Upper range for quantitative data
265 public float graphMax;
268 * Score associated with label and description.
270 public double score = Double.NaN;
273 * flag indicating if annotation has a score.
275 public boolean hasScore = false;
277 public GraphLine threshold;
279 // Graphical hints and tips
281 /** Can this row be edited by the user ? */
282 public boolean editable = false;
284 /** Indicates if annotation has a graphical symbol track */
285 public boolean hasIcons; //
287 /** Indicates if annotation has a text character label */
288 public boolean hasText;
290 /** is the row visible */
291 public boolean visible = true;
293 public int graphGroup = -1;
295 /** Displayed height of row in pixels */
296 public int height = 0;
298 public int graph = 0;
300 public int graphHeight = 40;
302 public boolean padGaps = false;
304 public static final int NO_GRAPH = 0;
306 public static final int BAR_GRAPH = 1;
308 public static final int LINE_GRAPH = 2;
310 public static final int CONTACT_MAP = 4;
313 * property that when set to non-empty string disables display of column
314 * groups defined on the contact matrix
316 public static final String CONTACT_MAP_NOGROUPS = "CMNOGRPS";
318 public boolean belowAlignment = true;
320 public SequenceGroup groupRef = null;
323 * display every column label, even if there is a row of identical labels
325 public boolean showAllColLabels = false;
328 * scale the column label to fit within the alignment column.
330 public boolean scaleColLabel = false;
333 * centre the column labels relative to the alignment column
335 public boolean centreColLabels = false;
337 private boolean isrna;
339 public static int getGraphValueFromString(String string)
341 if (string.equalsIgnoreCase("BAR_GRAPH"))
345 else if (string.equalsIgnoreCase("LINE_GRAPH"))
356 * Creates a new AlignmentAnnotation object.
359 * short label shown under sequence labels
361 * text displayed on mouseover
363 * set of positional annotation elements
365 public AlignmentAnnotation(String label, String description,
366 Annotation[] annotations)
372 this.description = description;
373 this.annotations = annotations;
375 validateRangeAndDisplay();
379 * Checks if annotation labels represent secondary structures
382 void areLabelsSecondaryStructure()
384 boolean nonSSLabel = false;
386 StringBuffer rnastring = new StringBuffer();
389 for (int i = 0; i < annotations.length; i++)
391 // DEBUG jalview.bin.Console.outPrintln(i + ": " + annotations[i]);
392 if (annotations[i] == null)
396 if (annotations[i].secondaryStructure == 'H'
397 || annotations[i].secondaryStructure == 'E')
399 // DEBUG jalview.bin.Console.outPrintln( "/H|E/ '" +
400 // annotations[i].secondaryStructure + "'");
404 // Check for RNA secondary structure
406 // DEBUG jalview.bin.Console.outPrintln( "/else/ '" +
407 // annotations[i].secondaryStructure + "'");
408 // TODO: 2.8.2 should this ss symbol validation check be a function in
409 // RNA/ResidueProperties ?
410 // allow for DSSP extended code:
411 // https://www.wikidoc.org/index.php/Secondary_structure#The_DSSP_code
412 // GHITEBS as well as C and X (for missing?)
413 if (annotations[i].secondaryStructure == '('
414 || annotations[i].secondaryStructure == '['
415 || annotations[i].secondaryStructure == '<'
416 || annotations[i].secondaryStructure == '{'
417 || annotations[i].secondaryStructure == 'A'
418 // || annotations[i].secondaryStructure == 'B'
419 // || annotations[i].secondaryStructure == 'C'
420 || annotations[i].secondaryStructure == 'D'
421 // || annotations[i].secondaryStructure == 'E' // ambiguous on
422 // its own -- already checked above
423 || annotations[i].secondaryStructure == 'F'
424 // || annotations[i].secondaryStructure == 'G'
425 // || annotations[i].secondaryStructure == 'H' // ambiguous on
426 // its own -- already checked above
427 // || annotations[i].secondaryStructure == 'I'
428 || annotations[i].secondaryStructure == 'J'
429 || annotations[i].secondaryStructure == 'K'
430 || annotations[i].secondaryStructure == 'L'
431 || annotations[i].secondaryStructure == 'M'
432 || annotations[i].secondaryStructure == 'N'
433 || annotations[i].secondaryStructure == 'O'
434 || annotations[i].secondaryStructure == 'P'
435 || annotations[i].secondaryStructure == 'Q'
436 || annotations[i].secondaryStructure == 'R'
437 // || annotations[i].secondaryStructure == 'S'
438 // || annotations[i].secondaryStructure == 'T'
439 || annotations[i].secondaryStructure == 'U'
440 || annotations[i].secondaryStructure == 'V'
441 || annotations[i].secondaryStructure == 'W'
442 // || annotations[i].secondaryStructure == 'X'
443 || annotations[i].secondaryStructure == 'Y'
444 || annotations[i].secondaryStructure == 'Z')
451 // jalview.bin.Console.outPrintln("displaychar " +
452 // annotations[i].displayCharacter);
454 if (annotations[i].displayCharacter == null
455 || annotations[i].displayCharacter.length() == 0)
457 rnastring.append('.');
460 if (annotations[i].displayCharacter.length() == 1)
462 firstChar = annotations[i].displayCharacter.charAt(0);
463 // check to see if it looks like a sequence or is secondary structure
465 if (annotations[i].secondaryStructure != ' ' && !hasIcons &&
466 // Uncomment to only catch case where
467 // displayCharacter==secondary
469 // to correctly redisplay SS annotation imported from Stockholm,
470 // exported to JalviewXML and read back in again.
472 // annotations[i].displayCharacter.charAt(0)==annotations[i].secondaryStructure
473 firstChar != ' ' && firstChar != '$' && firstChar != 0xCE
474 && firstChar != '(' && firstChar != '[' && firstChar != '<'
475 && firstChar != '{' && firstChar != 'A' && firstChar != 'B'
476 && firstChar != 'C' && firstChar != 'D' && firstChar != 'E'
477 && firstChar != 'F' && firstChar != 'G' && firstChar != 'H'
478 && firstChar != 'I' && firstChar != 'J' && firstChar != 'K'
479 && firstChar != 'L' && firstChar != 'M' && firstChar != 'N'
480 && firstChar != 'O' && firstChar != 'P' && firstChar != 'Q'
481 && firstChar != 'R' && firstChar != 'S' && firstChar != 'T'
482 && firstChar != 'U' && firstChar != 'V' && firstChar != 'W'
483 && firstChar != 'X' && firstChar != 'Y' && firstChar != 'Z'
485 && firstChar < jalview.schemes.ResidueProperties.aaIndex.length)
487 if (jalview.schemes.ResidueProperties.aaIndex[firstChar] < 23) // TODO:
500 rnastring.append(annotations[i].displayCharacter.charAt(1));
503 if (annotations[i].displayCharacter.length() > 0)
512 for (int j = 0; j < annotations.length; j++)
514 if (annotations[j] != null
515 && annotations[j].secondaryStructure != ' ')
517 annotations[j].displayCharacter = String
518 .valueOf(annotations[j].secondaryStructure);
519 annotations[j].secondaryStructure = ' ';
528 _updateRnaSecStr(new AnnotCharSequence());
534 * flyweight access to positions in the alignment annotation row for RNA
540 private class AnnotCharSequence implements CharSequence
546 public AnnotCharSequence()
548 this(0, annotations.length);
551 AnnotCharSequence(int start, int end)
558 public CharSequence subSequence(int start, int end)
560 return new AnnotCharSequence(offset + start, offset + end);
570 public char charAt(int index)
572 return ((index + offset < 0) || (index + offset) >= max
573 || annotations[index + offset] == null
574 || (annotations[index + offset].secondaryStructure <= ' ')
576 : annotations[index + offset].displayCharacter == null
578 + offset].displayCharacter
581 + offset].secondaryStructure
583 + offset].displayCharacter
588 public String toString()
590 char[] string = new char[max - offset];
591 int mx = annotations.length;
593 for (int i = offset; i < mx; i++)
595 string[i] = (annotations[i] == null
596 || (annotations[i].secondaryStructure <= 32))
598 : (annotations[i].displayCharacter == null
599 || annotations[i].displayCharacter
601 ? annotations[i].secondaryStructure
602 : annotations[i].displayCharacter
605 return new String(string);
609 private long _lastrnaannot = -1;
611 public String getRNAStruc()
615 String rnastruc = new AnnotCharSequence().toString();
616 if (_lastrnaannot != rnastruc.hashCode())
618 // ensure rna structure contacts are up to date
619 _lastrnaannot = rnastruc.hashCode();
620 _updateRnaSecStr(rnastruc);
628 * Creates a new AlignmentAnnotation object.
643 public AlignmentAnnotation(String label, String description,
644 Annotation[] annotations, float min, float max, int graphType)
647 // graphs are not editable
648 editable = graphType == 0;
651 this.description = description;
652 this.annotations = annotations;
656 validateRangeAndDisplay();
660 * checks graphMin and graphMax, secondary structure symbols, sets graphType
661 * appropriately, sets null labels to the empty string if appropriate.
663 public void validateRangeAndDisplay()
666 if (annotations == null)
668 visible = false; // try to prevent renderer from displaying.
669 invalidrnastruc = -1;
670 return; // this is a non-annotation row annotation - ie a sequence score.
673 int graphType = graph;
674 float min = graphMin;
675 float max = graphMax;
676 boolean drawValues = true;
681 for (int i = 0; i < annotations.length; i++)
683 if (annotations[i] == null)
688 if (drawValues && annotations[i].displayCharacter != null
689 && annotations[i].displayCharacter.length() > 1)
694 if (annotations[i].value > max)
696 max = annotations[i].value;
699 if (annotations[i].value < min)
701 min = annotations[i].value;
703 if (_linecolour == null && annotations[i].colour != null)
705 _linecolour = annotations[i].colour;
708 // ensure zero is origin for min/max ranges on only one side of zero
725 areLabelsSecondaryStructure();
727 if (!drawValues && graphType != NO_GRAPH)
729 for (int i = 0; i < annotations.length; i++)
731 if (annotations[i] != null)
733 annotations[i].displayCharacter = "";
740 * Copy constructor creates a new independent annotation row with the same
741 * associated sequenceRef
745 public AlignmentAnnotation(AlignmentAnnotation annotation)
748 this.label = new String(annotation.label);
749 if (annotation.description != null)
751 this.description = new String(annotation.description);
753 this.graphMin = annotation.graphMin;
754 this.graphMax = annotation.graphMax;
755 this.graph = annotation.graph;
756 this.graphHeight = annotation.graphHeight;
757 this.graphGroup = annotation.graphGroup;
758 this.groupRef = annotation.groupRef;
759 this.editable = annotation.editable;
760 this.autoCalculated = annotation.autoCalculated;
761 this.hasIcons = annotation.hasIcons;
762 this.hasText = annotation.hasText;
763 this.height = annotation.height;
764 this.label = annotation.label;
765 this.padGaps = annotation.padGaps;
766 this.visible = annotation.visible;
767 this.centreColLabels = annotation.centreColLabels;
768 this.scaleColLabel = annotation.scaleColLabel;
769 this.showAllColLabels = annotation.showAllColLabels;
770 this.calcId = annotation.calcId;
771 if (annotation.properties != null)
773 properties = new HashMap<>();
774 for (Map.Entry<String, String> val : annotation.properties.entrySet())
776 properties.put(val.getKey(), val.getValue());
779 if (this.hasScore = annotation.hasScore)
781 this.score = annotation.score;
783 if (annotation.threshold != null)
785 threshold = new GraphLine(annotation.threshold);
787 Annotation[] ann = annotation.annotations;
788 if (annotation.annotations != null)
790 this.annotations = new Annotation[ann.length];
791 for (int i = 0; i < ann.length; i++)
795 annotations[i] = new Annotation(ann[i]);
796 if (_linecolour != null)
798 _linecolour = annotations[i].colour;
803 if (annotation.sequenceRef != null)
805 this.sequenceRef = annotation.sequenceRef;
806 if (annotation.sequenceMapping != null)
809 sequenceMapping = new HashMap<>();
810 Iterator<Integer> pos = annotation.sequenceMapping.keySet()
812 while (pos.hasNext())
814 // could optimise this!
816 Annotation a = annotation.sequenceMapping.get(p);
823 for (int i = 0; i < ann.length; i++)
827 sequenceMapping.put(p, annotations[i]);
835 this.sequenceMapping = null;
839 // TODO: check if we need to do this: JAL-952
840 // if (this.isrna=annotation.isrna)
842 // _rnasecstr=new SequenceFeature[annotation._rnasecstr];
844 validateRangeAndDisplay(); // construct hashcodes, etc.
848 * clip the annotation to the columns given by startRes and endRes (inclusive)
849 * and prune any existing sequenceMapping to just those columns.
854 public void restrict(int startRes, int endRes)
856 if (annotations == null)
865 if (startRes >= annotations.length)
867 startRes = annotations.length - 1;
869 if (endRes >= annotations.length)
871 endRes = annotations.length - 1;
873 if (annotations == null)
877 Annotation[] temp = new Annotation[endRes - startRes + 1];
878 if (startRes < annotations.length)
880 System.arraycopy(annotations, startRes, temp, 0,
881 endRes - startRes + 1);
883 if (sequenceRef != null)
885 // Clip the mapping, if it exists.
886 int spos = sequenceRef.findPosition(startRes);
887 int epos = sequenceRef.findPosition(endRes);
888 if (sequenceMapping != null)
890 Map<Integer, Annotation> newmapping = new HashMap<>();
891 Iterator<Integer> e = sequenceMapping.keySet().iterator();
894 Integer pos = e.next();
895 if (pos.intValue() >= spos && pos.intValue() <= epos)
897 newmapping.put(pos, sequenceMapping.get(pos));
900 sequenceMapping.clear();
901 sequenceMapping = newmapping;
908 * set the annotation row to be at least length Annotations
911 * minimum number of columns required in the annotation row
912 * @return false if the annotation row is greater than length
914 public boolean padAnnotation(int length)
916 if (annotations == null)
918 return true; // annotation row is correct - null == not visible and
921 if (annotations.length < length)
923 Annotation[] na = new Annotation[length];
924 System.arraycopy(annotations, 0, na, 0, annotations.length);
928 return annotations.length > length;
935 * @return DOCUMENT ME!
938 public String toString()
940 if (annotations == null)
944 StringBuilder buffer = new StringBuilder(256);
946 for (int i = 0; i < annotations.length; i++)
948 if (annotations[i] != null)
952 buffer.append(annotations[i].value);
956 buffer.append(annotations[i].secondaryStructure);
960 buffer.append(annotations[i].displayCharacter);
966 // TODO: remove disgusting hack for 'special' treatment of consensus line.
967 if (label.indexOf("Consensus") == 0)
971 for (int i = 0; i < annotations.length; i++)
973 if (annotations[i] != null)
975 buffer.append(annotations[i].description);
982 return buffer.toString();
985 public void setThreshold(GraphLine line)
990 public GraphLine getThreshold()
996 * Attach the annotation to seqRef, starting from startRes position. If
997 * alreadyMapped is true then the indices of the annotation[] array are
998 * sequence positions rather than alignment column positions.
1002 * @param alreadyMapped
1004 public void createSequenceMapping(SequenceI seqRef, int startRes,
1005 boolean alreadyMapped)
1012 sequenceRef = seqRef;
1013 if (annotations == null)
1017 sequenceMapping = new HashMap<>();
1021 for (int i = 0; i < annotations.length; i++)
1023 if (annotations[i] != null)
1027 seqPos = seqRef.findPosition(i);
1031 seqPos = i + startRes;
1034 sequenceMapping.put(Integer.valueOf(seqPos), annotations[i]);
1041 * When positional annotation and a sequence reference is present, clears and
1042 * resizes the annotations array to the current alignment width, and adds
1043 * annotation according to aligned positions of the sequenceRef given by
1046 public void adjustForAlignment()
1048 if (sequenceRef == null)
1053 if (annotations == null)
1058 int a = 0, aSize = sequenceRef.getLength();
1067 Annotation[] temp = new Annotation[aSize];
1069 if (sequenceMapping != null)
1071 for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
1073 index = Integer.valueOf(a);
1074 Annotation annot = sequenceMapping.get(index);
1077 position = sequenceRef.findIndex(a) - 1;
1079 temp[position] = annot;
1087 * remove any null entries in annotation row and return the number of non-null
1088 * annotation elements.
1092 public int compactAnnotationArray()
1094 int i = 0, iSize = annotations.length;
1097 if (annotations[i] == null)
1101 System.arraycopy(annotations, i + 1, annotations, i,
1111 Annotation[] ann = annotations;
1112 annotations = new Annotation[i];
1113 System.arraycopy(ann, 0, annotations, 0, i);
1119 * Associate this annotation with the aligned residues of a particular
1120 * sequence. sequenceMapping will be updated in the following way: null
1121 * sequenceI - existing mapping will be discarded but annotations left in
1122 * mapped positions. valid sequenceI not equal to current sequenceRef: mapping
1123 * is discarded and rebuilt assuming 1:1 correspondence TODO: overload with
1124 * parameter to specify correspondence between current and new sequenceRef
1128 public void setSequenceRef(SequenceI sequenceI)
1130 if (sequenceI != null)
1132 if (sequenceRef != null)
1134 boolean rIsDs = sequenceRef.getDatasetSequence() == null,
1135 tIsDs = sequenceI.getDatasetSequence() == null;
1136 if (sequenceRef != sequenceI
1138 && sequenceRef != sequenceI.getDatasetSequence())
1140 && sequenceRef.getDatasetSequence() != sequenceI)
1141 && (!rIsDs && !tIsDs
1142 && sequenceRef.getDatasetSequence() != sequenceI
1143 .getDatasetSequence())
1144 && !sequenceRef.equals(sequenceI))
1146 // if sequenceRef isn't intersecting with sequenceI
1147 // throw away old mapping and reconstruct.
1149 if (sequenceMapping != null)
1151 sequenceMapping = null;
1152 // compactAnnotationArray();
1154 createSequenceMapping(sequenceI, 1, true);
1155 adjustForAlignment();
1159 // Mapping carried over
1160 sequenceRef = sequenceI;
1165 // No mapping exists
1166 createSequenceMapping(sequenceI, 1, true);
1167 adjustForAlignment();
1172 // throw away the mapping without compacting.
1173 sequenceMapping = null;
1181 public double getScore()
1190 public void setScore(double score)
1198 * @return true if annotation has an associated score
1200 public boolean hasScore()
1202 return hasScore || !Double.isNaN(score);
1206 * Score only annotation
1209 * @param description
1212 public AlignmentAnnotation(String label, String description, double score)
1214 this(label, description, null);
1219 * copy constructor with edit based on the hidden columns marked in colSel
1221 * @param alignmentAnnotation
1224 public AlignmentAnnotation(AlignmentAnnotation alignmentAnnotation,
1225 HiddenColumns hidden)
1227 this(alignmentAnnotation);
1228 if (annotations == null)
1232 makeVisibleAnnotation(hidden);
1235 public void setPadGaps(boolean padgaps, char gapchar)
1237 this.padGaps = padgaps;
1241 for (int i = 0; i < annotations.length; i++)
1243 if (annotations[i] == null)
1245 annotations[i] = new Annotation(String.valueOf(gapchar), null,
1248 else if (annotations[i].displayCharacter == null
1249 || annotations[i].displayCharacter.equals(" "))
1251 annotations[i].displayCharacter = String.valueOf(gapchar);
1258 * format description string for display
1261 * @return Get the annotation description string optionally prefixed by
1262 * associated sequence name (if any)
1264 public String getDescription(boolean seqname)
1266 if (seqname && this.sequenceRef != null)
1268 int i = description.toLowerCase(Locale.ROOT).indexOf("<html>");
1271 // move the html tag to before the sequence reference.
1272 return "<html>" + sequenceRef.getName() + " : "
1273 + description.substring(i + 6);
1275 return sequenceRef.getName() + " : " + description;
1280 public boolean isValidStruc()
1282 return invalidrnastruc == -1;
1285 public long getInvalidStrucPos()
1287 return invalidrnastruc;
1291 * machine readable ID string indicating what generated this annotation
1293 protected String calcId = "";
1296 * properties associated with the calcId
1298 protected Map<String, String> properties = new HashMap<>();
1301 * base colour for line graphs. If null, will be set automatically by
1302 * searching the alignment annotation
1304 public java.awt.Color _linecolour;
1306 public String getCalcId()
1311 public void setCalcId(String calcId)
1313 this.calcId = calcId;
1316 public boolean isRNA()
1322 * transfer annotation to the given sequence using the given mapping from the
1323 * current positions or an existing sequence mapping
1327 * map involving sq as To or From
1329 public void liftOver(SequenceI sq, Mapping sp2sq)
1331 if (sp2sq.getMappedWidth() != sp2sq.getWidth())
1333 // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
1334 // Protein reference frames
1336 "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
1338 boolean mapIsTo = (sp2sq != null)
1339 ? (sp2sq.getTo() == sq
1340 || sp2sq.getTo() == sq.getDatasetSequence())
1343 // TODO build a better annotation element map and get rid of annotations[]
1344 Map<Integer, Annotation> mapForsq = new HashMap<>();
1345 if (sequenceMapping != null)
1349 for (Entry<Integer, Annotation> ie : sequenceMapping.entrySet())
1351 Integer mpos = Integer
1352 .valueOf(mapIsTo ? sp2sq.getMappedPosition(ie.getKey())
1353 : sp2sq.getPosition(ie.getKey()));
1354 if (mpos >= sq.getStart() && mpos <= sq.getEnd())
1356 mapForsq.put(mpos, ie.getValue());
1359 sequenceMapping = mapForsq;
1361 adjustForAlignment();
1371 * like liftOver but more general.
1373 * Takes an array of int pairs that will be used to update the internal
1374 * sequenceMapping and so shuffle the annotated positions
1377 * - new sequence reference for the annotation row - if null,
1378 * sequenceRef is left unchanged
1380 * array of ints containing corresponding positions
1382 * - column for current coordinate system (-1 for index+1)
1384 * - column for destination coordinate system (-1 for index+1)
1386 * - offset added to index when referencing either coordinate system
1387 * @note no checks are made as to whether from and/or to are sensible
1388 * @note caller should add the remapped annotation to newref if they have not
1391 public void remap(SequenceI newref, HashMap<Integer, int[]> mapping,
1392 int from, int to, int idxoffset)
1394 if (mapping != null)
1396 Map<Integer, Annotation> old = sequenceMapping;
1397 Map<Integer, Annotation> remap = new HashMap<>();
1399 for (int mp[] : mapping.values())
1405 Annotation ann = null;
1408 ann = sequenceMapping.get(Integer.valueOf(idxoffset + index));
1412 if (mp != null && mp.length > from)
1414 ann = sequenceMapping.get(Integer.valueOf(mp[from]));
1421 remap.put(Integer.valueOf(idxoffset + index), ann);
1425 if (to > -1 && to < mp.length)
1427 remap.put(Integer.valueOf(mp[to]), ann);
1432 sequenceMapping = remap;
1436 sequenceRef = newref;
1438 adjustForAlignment();
1442 public String getProperty(String property)
1444 if (properties == null)
1448 return properties.get(property);
1451 public void setProperty(String property, String value)
1453 if (properties == null)
1455 properties = new HashMap<>();
1457 properties.put(property, value);
1460 public boolean hasProperties()
1462 return properties != null && properties.size() > 0;
1465 public Collection<String> getProperties()
1467 if (properties == null)
1469 return Collections.emptyList();
1471 return properties.keySet();
1475 * Returns the Annotation for the given sequence position (base 1) if any,
1481 public Annotation getAnnotationForPosition(int position)
1483 return sequenceMapping == null ? null : sequenceMapping.get(position);
1488 * Set the id to "ann" followed by a counter that increments so as to be
1489 * unique for the lifetime of the JVM
1491 protected final void setAnnotationId()
1493 this.annotationId = ANNOTATION_ID_PREFIX + Long.toString(nextId());
1497 * Returns the match for the last unmatched opening RNA helix pair symbol
1498 * preceding the given column, or '(' if nothing found to match.
1503 public String getDefaultRnaHelixSymbol(int column)
1505 String result = "(";
1506 if (annotations == null)
1512 * for each preceding column, if it contains an open bracket,
1513 * count whether it is still unmatched at column, if so return its pair
1514 * (likely faster than the fancy alternative using stacks)
1516 for (int col = column - 1; col >= 0; col--)
1518 Annotation annotation = annotations[col];
1519 if (annotation == null)
1523 String displayed = annotation.displayCharacter;
1524 if (displayed == null || displayed.length() != 1)
1528 char symbol = displayed.charAt(0);
1529 if (!Rna.isOpeningParenthesis(symbol))
1535 * found an opening bracket symbol
1536 * count (closing-opening) symbols of this type that follow it,
1537 * up to and excluding the target column; if the count is less
1538 * than 1, the opening bracket is unmatched, so return its match
1540 String closer = String
1541 .valueOf(Rna.getMatchingClosingParenthesis(symbol));
1542 String opener = String.valueOf(symbol);
1544 for (int j = col + 1; j < column; j++)
1546 if (annotations[j] != null)
1548 String s = annotations[j].displayCharacter;
1549 if (closer.equals(s))
1553 else if (opener.equals(s))
1567 protected static synchronized long nextId()
1574 * @return true for rows that have a range of values in their annotation set
1576 public boolean isQuantitative()
1578 return graphMin < graphMax;
1582 * delete any columns in alignmentAnnotation that are hidden (including
1583 * sequence associated annotation).
1585 * @param hiddenColumns
1586 * the set of hidden columns
1588 public void makeVisibleAnnotation(HiddenColumns hiddenColumns)
1590 if (annotations != null)
1592 makeVisibleAnnotation(0, annotations.length, hiddenColumns);
1597 * delete any columns in alignmentAnnotation that are hidden (including
1598 * sequence associated annotation).
1601 * remove any annotation to the right of this column
1603 * remove any annotation to the left of this column
1604 * @param hiddenColumns
1605 * the set of hidden columns
1607 public void makeVisibleAnnotation(int start, int end,
1608 HiddenColumns hiddenColumns)
1610 if (annotations != null)
1612 if (hiddenColumns.hasHiddenColumns())
1614 removeHiddenAnnotation(start, end, hiddenColumns);
1618 restrict(start, end);
1624 * The actual implementation of deleting hidden annotation columns
1627 * remove any annotation to the right of this column
1629 * remove any annotation to the left of this column
1630 * @param hiddenColumns
1631 * the set of hidden columns
1633 private void removeHiddenAnnotation(int start, int end,
1634 HiddenColumns hiddenColumns)
1636 // mangle the alignmentAnnotation annotation array
1637 ArrayList<Annotation[]> annels = new ArrayList<>();
1638 Annotation[] els = null;
1642 Iterator<int[]> blocks = hiddenColumns.getVisContigsIterator(start,
1646 int annotationLength;
1647 while (blocks.hasNext())
1649 int[] block = blocks.next();
1650 annotationLength = block[1] - block[0] + 1;
1652 if (blocks.hasNext())
1654 // copy just the visible segment of the annotation row
1655 copylength = annotationLength;
1659 if (annotationLength + block[0] <= annotations.length)
1661 // copy just the visible segment of the annotation row
1662 copylength = annotationLength;
1666 // copy to the end of the annotation row
1667 copylength = annotations.length - block[0];
1671 els = new Annotation[annotationLength];
1673 System.arraycopy(annotations, block[0], els, 0, copylength);
1674 w += annotationLength;
1679 annotations = new Annotation[w];
1682 for (Annotation[] chnk : annels)
1684 System.arraycopy(chnk, 0, annotations, w, chnk.length);
1690 public static Iterable<AlignmentAnnotation> findAnnotations(
1691 Iterable<AlignmentAnnotation> list, SequenceI seq, String calcId,
1695 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1696 for (AlignmentAnnotation ann : list)
1698 if ((calcId == null || (ann.getCalcId() != null
1699 && ann.getCalcId().equals(calcId)))
1700 && (seq == null || (ann.sequenceRef != null
1701 && ann.sequenceRef == seq))
1703 || (ann.label != null && ann.label.equals(label))))
1712 * Answer true if any annotation matches the calcId passed in (if not null).
1715 * annotation to search
1719 public static boolean hasAnnotation(List<AlignmentAnnotation> list,
1723 if (calcId != null && !"".equals(calcId))
1725 for (AlignmentAnnotation a : list)
1727 if (a.getCalcId() == calcId)
1736 public static Iterable<AlignmentAnnotation> findAnnotation(
1737 List<AlignmentAnnotation> list, String calcId)
1740 List<AlignmentAnnotation> aa = new ArrayList<>();
1745 for (AlignmentAnnotation a : list)
1748 if (a.getCalcId() == calcId || (a.getCalcId() != null
1749 && calcId != null && a.getCalcId().equals(calcId)))
1758 * convenience method to check for the 'CONTACT_MAP_NOGROUPS' property for
1759 * this alignment annotation row
1761 * @return true if no CONTACT_MAP_NOGROUPS property is found, or it is set to
1764 public boolean isShowGroupsForContactMatrix()
1766 return getProperty(AlignmentAnnotation.CONTACT_MAP_NOGROUPS) == null
1768 getProperty(AlignmentAnnotation.CONTACT_MAP_NOGROUPS));
1772 * set the 'CONTACT_MAP_NOGROUPS' property for this alignment annotation row
1774 * @see isShowGroupsForContactMatrix
1776 public void setShowGroupsForContactMatrix(boolean showGroups)
1778 setProperty(AlignmentAnnotation.CONTACT_MAP_NOGROUPS,
1779 showGroups ? "" : "nogroups");