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.BitSet;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.Enumeration;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.ListIterator;
32 import java.util.Vector;
34 import fr.orsay.lri.varna.models.rna.RNA;
35 import jalview.analysis.AlignSeq;
36 import jalview.analysis.AlignmentUtils;
37 import jalview.analysis.SeqsetUtils;
38 import jalview.datamodel.features.SequenceFeatures;
39 import jalview.datamodel.features.SequenceFeaturesI;
40 import jalview.util.Comparison;
41 import jalview.util.DBRefUtils;
42 import jalview.util.MapList;
43 import jalview.util.StringUtils;
44 import jalview.ws.datamodel.alphafold.MappableContactMatrix;
48 * Implements the SequenceI interface for a char[] based sequence object
50 public class Sequence extends ASequence implements SequenceI
54 * A subclass that gives us access to modCount, which tracks whether there
55 * have been any changes. We use this to update
61 @SuppressWarnings("serial")
62 public class DBModList<T> extends ArrayList<DBRefEntry>
65 protected int getModCount()
72 SequenceI datasetSequence;
76 private char[] sequence;
78 private String description;
84 private Vector<PDBEntry> pdbIds;
86 private String vamsasId;
88 private DBModList<DBRefEntry> dbrefs; // controlled access
91 * a flag to let us know that elements have changed in dbrefs
95 private int refModCount = 0;
100 * This annotation is displayed below the alignment but the positions are tied
101 * to the residues of this sequence
103 * TODO: change to List<>
105 private Vector<AlignmentAnnotation> annotation;
107 private SequenceFeaturesI sequenceFeatureStore;
110 * A cursor holding the approximate current view position to the sequence,
111 * as determined by findIndex or findPosition or findPositions.
112 * Using a cursor as a hint allows these methods to be more performant for
115 private SequenceCursor cursor;
118 * A number that should be incremented whenever the sequence is edited.
119 * If the value matches the cursor token, then we can trust the cursor,
120 * if not then it should be recomputed.
122 private int changeCount;
125 * Creates a new Sequence object.
128 * display name string
130 * string to form a possibly gapped sequence out of
132 * first position of non-gap residue in the sequence
134 * last position of ungapped residues (nearly always only used for
137 public Sequence(String name, String sequence, int start, int end)
140 initSeqAndName(name, sequence.toCharArray(), start, end);
143 public Sequence(String name, char[] sequence, int start, int end)
146 initSeqAndName(name, sequence, start, end);
150 * Stage 1 constructor - assign name, sequence, and set start and end fields.
151 * start and end are updated values from name2 if it ends with /start-end
158 protected void initSeqAndName(String name2, char[] sequence2, int start2,
162 this.sequence = sequence2;
170 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
171 * start and end respectively and removes the suffix from the name
178 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
181 int slashPos = name.lastIndexOf('/');
182 if (slashPos > -1 && slashPos < name.length() - 1)
184 String suffix = name.substring(slashPos + 1);
185 String[] range = suffix.split("-");
186 if (range.length == 2)
190 int from = Integer.valueOf(range[0]);
191 int to = Integer.valueOf(range[1]);
192 if (from > 0 && to >= from)
194 name = name.substring(0, slashPos);
199 } catch (NumberFormatException e)
201 // leave name unchanged if suffix is invalid
208 * Ensures that 'end' is not before the end of the sequence, that is,
209 * (end-start+1) is at least as long as the count of ungapped positions. Note
210 * that end is permitted to be beyond the end of the sequence data.
212 void checkValidRange()
215 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
218 for (int j = 0; j < sequence.length; j++)
220 if (!Comparison.isGap(sequence[j]))
239 * default constructor
243 sequenceFeatureStore = new SequenceFeatures();
247 * Creates a new Sequence object.
254 public Sequence(String name, String sequence)
256 this(name, sequence, 1, -1);
260 * Creates a new Sequence object with new AlignmentAnnotations but inherits
261 * any existing dataset sequence reference. If non exists, everything is
265 * if seq is a dataset sequence, behaves like a plain old copy
268 public Sequence(SequenceI seq)
270 this(seq, seq.getAnnotation());
274 * Create a new sequence object with new features, DBRefEntries, and PDBIds
275 * but inherits any existing dataset sequence reference, and duplicate of any
276 * annotation that is present in the given annotation array.
279 * the sequence to be copied
280 * @param alAnnotation
281 * an array of annotation including some associated with seq
283 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
286 initSeqFrom(seq, alAnnotation);
290 * does the heavy lifting when cloning a dataset sequence, or coping data from
291 * dataset to a new derived sequence.
294 * - source of attributes.
295 * @param alAnnotation
296 * - alignment annotation present on seq that should be copied onto
299 protected void initSeqFrom(SequenceI seq,
300 AlignmentAnnotation[] alAnnotation)
302 char[] oseq = seq.getSequence(); // returns a copy of the array
303 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
305 description = seq.getDescription();
306 if (seq != datasetSequence)
308 setDatasetSequence(seq.getDatasetSequence());
312 * only copy DBRefs and seqfeatures if we really are a dataset sequence
314 if (datasetSequence == null)
316 List<DBRefEntry> dbr = seq.getDBRefs();
319 for (int i = 0, n = dbr.size(); i < n; i++)
321 addDBRef(new DBRefEntry(dbr.get(i)));
326 * make copies of any sequence features
328 for (SequenceFeature sf : seq.getSequenceFeatures())
330 addSequenceFeature(new SequenceFeature(sf));
334 if (seq.getAnnotation() != null)
336 AlignmentAnnotation[] sqann = seq.getAnnotation();
337 for (int i = 0; i < sqann.length; i++)
339 if (sqann[i] == null)
343 boolean found = (alAnnotation == null);
346 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
348 found = (alAnnotation[apos] == sqann[i]);
353 // only copy the given annotation
354 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
355 ContactMatrixI cm = seq.getContactMatrixFor(sqann[i]);
358 addContactListFor(newann, cm);
360 addAlignmentAnnotation(newann);
364 if (seq.getAllPDBEntries() != null)
366 Vector<PDBEntry> ids = seq.getAllPDBEntries();
367 for (PDBEntry pdb : ids)
369 this.addPDBId(new PDBEntry(pdb));
375 public void setSequenceFeatures(List<SequenceFeature> features)
377 if (datasetSequence != null)
379 datasetSequence.setSequenceFeatures(features);
382 sequenceFeatureStore = new SequenceFeatures(features);
386 public synchronized boolean addSequenceFeature(SequenceFeature sf)
388 if (sf.getType() == null)
391 "SequenceFeature type may not be null: " + sf.toString());
395 if (datasetSequence != null)
397 return datasetSequence.addSequenceFeature(sf);
400 return sequenceFeatureStore.add(sf);
404 public void deleteFeature(SequenceFeature sf)
406 if (datasetSequence != null)
408 datasetSequence.deleteFeature(sf);
412 sequenceFeatureStore.delete(sf);
422 public List<SequenceFeature> getSequenceFeatures()
424 if (datasetSequence != null)
426 return datasetSequence.getSequenceFeatures();
428 return sequenceFeatureStore.getAllFeatures();
432 public SequenceFeaturesI getFeatures()
434 return datasetSequence != null ? datasetSequence.getFeatures()
435 : sequenceFeatureStore;
439 public boolean addPDBId(PDBEntry entry)
443 pdbIds = new Vector<>();
448 for (PDBEntry pdbe : pdbIds)
450 if (pdbe.updateFrom(entry))
455 pdbIds.addElement(entry);
466 public void setPDBId(Vector<PDBEntry> id)
474 * @return DOCUMENT ME!
477 public Vector<PDBEntry> getAllPDBEntries()
479 return pdbIds == null ? new Vector<>() : pdbIds;
483 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
488 public String getDisplayId(boolean jvsuffix)
494 StringBuilder result = new StringBuilder(name);
495 result.append("/").append(start).append("-").append(end);
497 return result.toString();
501 * Sets the sequence name. If the name ends in /start-end, then the start-end
502 * values are parsed out and set, and the suffix is removed from the name.
507 public void setName(String theName)
516 * @return DOCUMENT ME!
519 public String getName()
531 public void setStart(int start)
540 * @return DOCUMENT ME!
543 public int getStart()
555 public void setEnd(int end)
563 * @return DOCUMENT ME!
574 * @return DOCUMENT ME!
577 public int getLength()
579 return this.sequence.length;
589 public void setSequence(String seq)
591 this.sequence = seq.toCharArray();
597 public String getSequenceAsString()
599 return new String(sequence);
603 public String getSequenceAsString(int start, int end)
605 return new String(getSequence(start, end));
609 public char[] getSequence()
612 return sequence == null ? null
613 : Arrays.copyOf(sequence, sequence.length);
619 * @see jalview.datamodel.SequenceI#getSequence(int, int)
622 public char[] getSequence(int start, int end)
628 // JBPNote - left to user to pad the result here (TODO:Decide on this
630 if (start >= sequence.length)
635 if (end >= sequence.length)
637 end = sequence.length;
640 char[] reply = new char[end - start];
641 System.arraycopy(sequence, start, reply, 0, end - start);
647 public SequenceI getSubSequence(int start, int end)
653 char[] seq = getSequence(start, end);
658 int nstart = findPosition(start);
659 int nend = findPosition(end) - 1;
660 // JBPNote - this is an incomplete copy.
661 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
662 nseq.setDescription(description);
663 if (datasetSequence != null)
665 nseq.setDatasetSequence(datasetSequence);
669 nseq.setDatasetSequence(this);
675 * Returns the character of the aligned sequence at the given position (base
676 * zero), or space if the position is not within the sequence's bounds
681 public char getCharAt(int i)
683 if (i >= 0 && i < sequence.length)
694 * Sets the sequence description, and also parses out any special formats of
700 public void setDescription(String desc)
702 this.description = desc;
706 public void setGeneLoci(String speciesId, String assemblyId,
707 String chromosomeId, MapList map)
709 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
714 * Returns the gene loci mapping for the sequence (may be null)
719 public GeneLociI getGeneLoci()
721 List<DBRefEntry> refs = getDBRefs();
724 for (final DBRefEntry ref : refs)
726 if (ref instanceof GeneLociI)
728 return (GeneLociI) ref;
736 * Answers the description
741 public String getDescription()
743 return this.description;
750 public int findIndex(int pos)
753 * use a valid, hopefully nearby, cursor if available
755 if (isValidCursor(cursor))
757 return findIndex(pos, cursor);
765 * traverse sequence from the start counting gaps; make a note of
766 * the column of the first residue to save in the cursor
768 while ((i < sequence.length) && (j <= end) && (j <= pos))
770 if (!Comparison.isGap(sequence[i]))
781 if (j == end && j < pos)
786 updateCursor(pos, i, startColumn);
791 * Updates the cursor to the latest found residue and column position
798 * column position of the first sequence residue
800 protected void updateCursor(int residuePos, int column, int startColumn)
803 * preserve end residue column provided cursor was valid
805 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
807 if (residuePos == this.end)
812 cursor = new SequenceCursor(this, residuePos, column, startColumn,
813 endColumn, this.changeCount);
817 * Answers the aligned column position (1..) for the given residue position
818 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
819 * The hint may be left of, at, or to the right of the required position.
825 protected int findIndex(final int pos, SequenceCursor curs)
827 if (!isValidCursor(curs))
830 * wrong or invalidated cursor, compute de novo
832 return findIndex(pos);
835 if (curs.residuePosition == pos)
837 return curs.columnPosition;
841 * move left or right to find pos from hint.position
843 int col = curs.columnPosition - 1; // convert from base 1 to base 0
844 int newPos = curs.residuePosition;
845 int delta = newPos > pos ? -1 : 1;
847 while (newPos != pos)
849 col += delta; // shift one column left or right
854 if (col == sequence.length)
856 col--; // return last column if we failed to reach pos
859 if (!Comparison.isGap(sequence[col]))
865 col++; // convert back to base 1
868 * only update cursor if we found the target position
872 updateCursor(pos, col, curs.firstColumnPosition);
882 public int findPosition(final int column)
885 * use a valid, hopefully nearby, cursor if available
887 if (isValidCursor(cursor))
889 return findPosition(column + 1, cursor);
892 // TODO recode this more naturally i.e. count residues only
893 // as they are found, not 'in anticipation'
896 * traverse the sequence counting gaps; note the column position
897 * of the first residue, to save in the cursor
899 int firstResidueColumn = 0;
900 int lastPosFound = 0;
901 int lastPosFoundColumn = 0;
902 int seqlen = sequence.length;
904 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
906 lastPosFound = start;
907 lastPosFoundColumn = 0;
913 while (j < column && j < seqlen)
915 if (!Comparison.isGap(sequence[j]))
918 lastPosFoundColumn = j;
919 if (pos == this.start)
921 firstResidueColumn = j;
927 if (j < seqlen && !Comparison.isGap(sequence[j]))
930 lastPosFoundColumn = j;
931 if (pos == this.start)
933 firstResidueColumn = j;
938 * update the cursor to the last residue position found (if any)
939 * (converting column position to base 1)
941 if (lastPosFound != 0)
943 updateCursor(lastPosFound, lastPosFoundColumn + 1,
944 firstResidueColumn + 1);
951 * Answers true if the given cursor is not null, is for this sequence object,
952 * and has a token value that matches this object's changeCount, else false.
953 * This allows us to ignore a cursor as 'stale' if the sequence has been
954 * modified since the cursor was created.
959 protected boolean isValidCursor(SequenceCursor curs)
961 if (curs == null || curs.sequence != this || curs.token != changeCount)
966 * sanity check against range
968 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
972 if (curs.residuePosition < start || curs.residuePosition > end)
980 * Answers the sequence position (start..) for the given aligned column
981 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
982 * may lie left of, at, or to the right of the column position.
988 protected int findPosition(final int col, SequenceCursor curs)
990 if (!isValidCursor(curs))
993 * wrong or invalidated cursor, compute de novo
995 return findPosition(col - 1);// ugh back to base 0
998 if (curs.columnPosition == col)
1000 cursor = curs; // in case this method becomes public
1001 return curs.residuePosition; // easy case :-)
1004 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1007 * sequence lies entirely to the left of col
1008 * - return last residue + 1
1013 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1016 * sequence lies entirely to the right of col
1017 * - return first residue
1022 // todo could choose closest to col out of column,
1023 // firstColumnPosition, lastColumnPosition as a start point
1026 * move left or right to find pos from cursor position
1028 int firstResidueColumn = curs.firstColumnPosition;
1029 int column = curs.columnPosition - 1; // to base 0
1030 int newPos = curs.residuePosition;
1031 int delta = curs.columnPosition > col ? -1 : 1;
1032 boolean gapped = false;
1033 int lastFoundPosition = curs.residuePosition;
1034 int lastFoundPositionColumn = curs.columnPosition;
1036 while (column != col - 1)
1038 column += delta; // shift one column left or right
1039 if (column < 0 || column == sequence.length)
1043 gapped = Comparison.isGap(sequence[column]);
1047 lastFoundPosition = newPos;
1048 lastFoundPositionColumn = column + 1;
1049 if (lastFoundPosition == this.start)
1051 firstResidueColumn = column + 1;
1056 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1058 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1059 firstResidueColumn);
1063 * hack to give position to the right if on a gap
1064 * or beyond the length of the sequence (see JAL-2562)
1066 if (delta > 0 && (gapped || column >= sequence.length))
1078 public ContiguousI findPositions(int fromColumn, int toColumn)
1080 if (toColumn < fromColumn || fromColumn < 1)
1086 * find the first non-gapped position, if any
1088 int firstPosition = 0;
1089 int col = fromColumn - 1;
1090 int length = sequence.length;
1091 while (col < length && col < toColumn)
1093 if (!Comparison.isGap(sequence[col]))
1095 firstPosition = findPosition(col++);
1101 if (firstPosition == 0)
1107 * find the last non-gapped position
1109 int lastPosition = firstPosition;
1110 while (col < length && col < toColumn)
1112 if (!Comparison.isGap(sequence[col++]))
1118 return new Range(firstPosition, lastPosition);
1122 * Returns an int array where indices correspond to each residue in the
1123 * sequence and the element value gives its position in the alignment
1125 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1126 * residues in SequenceI object
1129 public int[] gapMap()
1131 String seq = jalview.analysis.AlignSeq.extractGaps(
1132 jalview.util.Comparison.GapChars, new String(sequence));
1133 int[] map = new int[seq.length()];
1137 while (j < sequence.length)
1139 if (!jalview.util.Comparison.isGap(sequence[j]))
1151 * Build a bitset corresponding to sequence gaps
1153 * @return a BitSet where set values correspond to gaps in the sequence
1156 public BitSet gapBitset()
1158 BitSet gaps = new BitSet(sequence.length);
1160 while (j < sequence.length)
1162 if (jalview.util.Comparison.isGap(sequence[j]))
1172 public int[] findPositionMap()
1174 int map[] = new int[sequence.length];
1177 int seqlen = sequence.length;
1178 while ((j < seqlen))
1181 if (!jalview.util.Comparison.isGap(sequence[j]))
1192 public List<int[]> getInsertions()
1194 ArrayList<int[]> map = new ArrayList<>();
1195 int lastj = -1, j = 0;
1197 int seqlen = sequence.length;
1198 while ((j < seqlen))
1200 if (jalview.util.Comparison.isGap(sequence[j]))
1211 map.add(new int[] { lastj, j - 1 });
1219 map.add(new int[] { lastj, j - 1 });
1226 public BitSet getInsertionsAsBits()
1228 BitSet map = new BitSet();
1229 int lastj = -1, j = 0;
1231 int seqlen = sequence.length;
1232 while ((j < seqlen))
1234 if (jalview.util.Comparison.isGap(sequence[j]))
1260 public void deleteChars(final int i, final int j)
1262 int newstart = start, newend = end;
1263 if (i >= sequence.length || i < 0)
1268 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1269 boolean createNewDs = false;
1270 // TODO: take a (second look) at the dataset creation validation method for
1271 // the very large sequence case
1273 int startIndex = findIndex(start) - 1;
1274 int endIndex = findIndex(end) - 1;
1275 int startDeleteColumn = -1; // for dataset sequence deletions
1276 int deleteCount = 0;
1278 for (int s = i; s < j && s < sequence.length; s++)
1280 if (Comparison.isGap(sequence[s]))
1285 if (startDeleteColumn == -1)
1287 startDeleteColumn = findPosition(s) - start;
1295 if (startIndex == s)
1298 * deleting characters from start of sequence; new start is the
1299 * sequence position of the next column (position to the right
1300 * if the column position is gapped)
1302 newstart = findPosition(j);
1310 * deleting characters at end of sequence; new end is the sequence
1311 * position of the column before the deletion; subtract 1 if this is
1312 * gapped since findPosition returns the next sequence position
1314 newend = findPosition(i - 1);
1315 if (Comparison.isGap(sequence[i - 1]))
1330 if (createNewDs && this.datasetSequence != null)
1333 * if deletion occured in the middle of the sequence,
1334 * construct a new dataset sequence and delete the residues
1335 * that were deleted from the aligned sequence
1337 Sequence ds = new Sequence(datasetSequence);
1338 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1339 datasetSequence = ds;
1340 // TODO: remove any non-inheritable properties ?
1341 // TODO: create a sequence mapping (since there is a relation here ?)
1350 public void insertCharAt(int i, int length, char c)
1352 char[] tmp = new char[sequence.length + length];
1354 if (i >= sequence.length)
1356 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1357 i = sequence.length;
1361 System.arraycopy(sequence, 0, tmp, 0, i);
1371 if (i < sequence.length)
1373 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1381 public void insertCharAt(int i, char c)
1383 insertCharAt(i, 1, c);
1387 public String getVamsasId()
1393 public void setVamsasId(String id)
1400 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1402 if (dbrefs == null && datasetSequence != null
1403 && this != datasetSequence)
1405 datasetSequence.setDBRefs(newDBrefs);
1413 public DBModList<DBRefEntry> getDBRefs()
1415 if (dbrefs == null && datasetSequence != null
1416 && this != datasetSequence)
1418 return datasetSequence.getDBRefs();
1424 public void addDBRef(DBRefEntry entry)
1426 // TODO JAL-3980 maintain as sorted list
1427 if (datasetSequence != null)
1429 datasetSequence.addDBRef(entry);
1435 dbrefs = new DBModList<>();
1437 // TODO JAL-3979 LOOK UP RATHER THAN SWEEP FOR EFFICIENCY
1439 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1441 if (dbrefs.get(ib).updateFrom(entry))
1444 * found a dbref that either matched, or could be
1445 * updated from, the new entry - no need to add it
1453 // * extend the array to make room for one more
1455 // // TODO use an ArrayList instead
1456 // int j = dbrefs.length;
1457 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1458 // System.arraycopy(dbrefs, 0, temp, 0, j);
1459 // temp[temp.length - 1] = entry;
1467 public void setDatasetSequence(SequenceI seq)
1471 throw new IllegalArgumentException(
1472 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1474 if (seq != null && seq.getDatasetSequence() != null)
1476 throw new IllegalArgumentException(
1477 "Implementation error: cascading dataset sequences are not allowed.");
1479 datasetSequence = seq;
1483 public SequenceI getDatasetSequence()
1485 return datasetSequence;
1489 public AlignmentAnnotation[] getAnnotation()
1491 return annotation == null ? null
1493 .toArray(new AlignmentAnnotation[annotation.size()]);
1497 public boolean hasAnnotation(AlignmentAnnotation ann)
1499 return annotation == null ? false : annotation.contains(ann);
1503 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1505 if (this.annotation == null)
1507 this.annotation = new Vector<>();
1509 if (!this.annotation.contains(annotation))
1511 this.annotation.addElement(annotation);
1513 annotation.setSequenceRef(this);
1517 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1519 if (this.annotation != null)
1521 this.annotation.removeElement(annotation);
1522 if (this.annotation.size() == 0)
1524 this.annotation = null;
1530 * test if this is a valid candidate for another sequence's dataset sequence.
1533 private boolean isValidDatasetSequence()
1535 if (datasetSequence != null)
1539 for (int i = 0; i < sequence.length; i++)
1541 if (jalview.util.Comparison.isGap(sequence[i]))
1550 public SequenceI deriveSequence()
1552 Sequence seq = null;
1553 if (datasetSequence == null)
1555 if (isValidDatasetSequence())
1557 // Use this as dataset sequence
1558 seq = new Sequence(getName(), "", 1, -1);
1559 seq.setDatasetSequence(this);
1560 seq.initSeqFrom(this, getAnnotation());
1565 // Create a new, valid dataset sequence
1566 createDatasetSequence();
1569 return new Sequence(this);
1572 private boolean _isNa;
1574 private int _seqhash = 0;
1576 private List<DBRefEntry> primaryRefs;
1579 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1583 public boolean isProtein()
1585 if (datasetSequence != null)
1587 return datasetSequence.isProtein();
1589 if (_seqhash != sequence.hashCode())
1591 _seqhash = sequence.hashCode();
1592 _isNa = Comparison.isNucleotide(this);
1600 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1603 public SequenceI createDatasetSequence()
1605 if (datasetSequence == null)
1607 Sequence dsseq = new Sequence(getName(),
1608 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1609 getSequenceAsString()),
1610 getStart(), getEnd());
1612 datasetSequence = dsseq;
1614 dsseq.setDescription(description);
1615 // move features and database references onto dataset sequence
1616 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1617 sequenceFeatureStore = null;
1618 dsseq.dbrefs = dbrefs;
1620 // TODO: search and replace any references to this sequence with
1621 // references to the dataset sequence in Mappings on dbref
1622 dsseq.pdbIds = pdbIds;
1624 datasetSequence.updatePDBIds();
1625 if (annotation != null)
1627 // annotation is cloned rather than moved, to preserve what's currently
1629 for (AlignmentAnnotation aa : annotation)
1631 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1632 _aa.sequenceRef = datasetSequence;
1633 _aa.adjustForAlignment(); // uses annotation's own record of
1634 // sequence-column mapping
1635 datasetSequence.addAlignmentAnnotation(_aa);
1637 if (_cmholder != null)
1638 { // transfer contact matrices
1639 ContactMatrixI cm = _cmholder.getContactMatrixFor(aa);
1642 datasetSequence.addContactListFor(_aa, cm);
1643 datasetSequence.addContactListFor(aa, cm);
1648 // all matrices should have been transferred. so we clear the local holder
1651 return datasetSequence;
1658 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1662 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1664 if (annotation != null)
1666 annotation.removeAllElements();
1668 if (annotations != null)
1670 for (int i = 0; i < annotations.length; i++)
1672 if (annotations[i] != null)
1674 addAlignmentAnnotation(annotations[i]);
1681 public AlignmentAnnotation[] getAnnotation(String label)
1683 if (annotation == null || annotation.size() == 0)
1688 Vector<AlignmentAnnotation> subset = new Vector<>();
1689 Enumeration<AlignmentAnnotation> e = annotation.elements();
1690 while (e.hasMoreElements())
1692 AlignmentAnnotation ann = e.nextElement();
1693 if (ann.label != null && ann.label.equals(label))
1695 subset.addElement(ann);
1698 if (subset.size() == 0)
1702 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1704 e = subset.elements();
1705 while (e.hasMoreElements())
1707 anns[i++] = e.nextElement();
1709 subset.removeAllElements();
1714 public boolean updatePDBIds()
1716 if (datasetSequence != null)
1718 // TODO: could merge DBRefs
1719 return datasetSequence.updatePDBIds();
1721 if (dbrefs == null || dbrefs.size() == 0)
1725 boolean added = false;
1726 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1728 DBRefEntry dbr = dbrefs.get(ib);
1729 if (DBRefSource.PDB.equals(dbr.getSource()))
1732 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1733 * PDB id is not already present in a 'matching' PDBEntry
1734 * Constructor parses out a chain code if appended to the accession id
1735 * (a fudge used to 'store' the chain code in the DBRef)
1737 PDBEntry pdbe = new PDBEntry(dbr);
1738 added |= addPDBId(pdbe);
1745 public void transferAnnotation(SequenceI entry, Mapping mp)
1747 if (datasetSequence != null)
1749 datasetSequence.transferAnnotation(entry, mp);
1752 if (entry.getDatasetSequence() != null)
1754 transferAnnotation(entry.getDatasetSequence(), mp);
1757 // transfer from entry to sequence
1758 // if entry has a description and sequence doesn't, then transfer
1759 if (entry.getDescription()!=null && (description==null || description.trim().length()==0))
1761 description = entry.getDescription();
1764 // transfer any new features from entry onto sequence
1765 if (entry.getSequenceFeatures() != null)
1768 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1769 for (SequenceFeature feature : sfs)
1771 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1772 : new SequenceFeature[]
1773 { new SequenceFeature(feature) };
1776 for (int sfi = 0; sfi < sf.length; sfi++)
1778 addSequenceFeature(sf[sfi]);
1784 // transfer PDB entries
1785 if (entry.getAllPDBEntries() != null)
1787 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1788 while (e.hasMoreElements())
1790 PDBEntry pdb = e.nextElement();
1794 // transfer database references
1795 List<DBRefEntry> entryRefs = entry.getDBRefs();
1796 if (entryRefs != null)
1798 for (int r = 0, n = entryRefs.size(); r < n; r++)
1800 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1801 if (newref.getMap() != null && mp != null)
1803 // remap ref using our local mapping
1805 // we also assume all version string setting is done by dbSourceProxy
1807 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1808 * newref.setSource(dbSource); }
1816 public void setRNA(RNA r)
1828 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1831 return getAlignmentAnnotations(calcId, label, null, true);
1835 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1836 String label, String description)
1838 return getAlignmentAnnotations(calcId, label, description, false);
1841 private List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1842 String label, String description, boolean ignoreDescription)
1844 List<AlignmentAnnotation> result = new ArrayList<>();
1845 if (this.annotation != null)
1847 for (AlignmentAnnotation ann : annotation)
1849 if ((ann.calcId != null && ann.calcId.equals(calcId))
1850 && (ann.label != null && ann.label.equals(label))
1851 && ((ignoreDescription && description == null)
1852 || (ann.description != null
1853 && ann.description.equals(description))))
1864 public String toString()
1866 return getDisplayId(false);
1870 public PDBEntry getPDBEntry(String pdbIdStr)
1872 if (getDatasetSequence() != null)
1874 return getDatasetSequence().getPDBEntry(pdbIdStr);
1880 List<PDBEntry> entries = getAllPDBEntries();
1881 for (PDBEntry entry : entries)
1883 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1891 private List<DBRefEntry> tmpList;
1894 public List<DBRefEntry> getPrimaryDBRefs()
1896 if (datasetSequence != null)
1898 return datasetSequence.getPrimaryDBRefs();
1900 if (dbrefs == null || dbrefs.size() == 0)
1902 return Collections.emptyList();
1904 synchronized (dbrefs)
1906 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1908 return primaryRefs; // no changes
1910 refModCount = dbrefs.getModCount();
1911 List<DBRefEntry> primaries = (primaryRefs == null
1912 ? (primaryRefs = new ArrayList<>())
1915 if (tmpList == null)
1917 tmpList = new ArrayList<>();
1918 tmpList.add(null); // for replacement
1920 for (int i = 0, n = dbrefs.size(); i < n; i++)
1922 DBRefEntry ref = dbrefs.get(i);
1923 if (!ref.isPrimaryCandidate())
1929 MapList mp = ref.getMap().getMap();
1930 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1932 // map only involves a subsequence, so cannot be primary
1936 // whilst it looks like it is a primary ref, we also sanity check type
1937 if (DBRefSource.PDB_CANONICAL_NAME
1938 .equals(ref.getCanonicalSourceName()))
1940 // PDB dbrefs imply there should be a PDBEntry associated
1941 // TODO: tighten PDB dbrefs
1942 // formally imply Jalview has actually downloaded and
1943 // parsed the pdb file. That means there should be a cached file
1944 // handle on the PDBEntry, and a real mapping between sequence and
1945 // extracted sequence from PDB file
1946 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1947 if (pdbentry == null || pdbentry.getFile() == null)
1954 // check standard protein or dna sources
1955 tmpList.set(0, ref);
1956 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1958 if (res == null || res.get(0) != tmpList.get(0))
1966 // version must be not null, as otherwise it will not be a candidate,
1968 DBRefUtils.ensurePrimaries(this, primaries);
1977 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1980 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1981 int endPos = fromColumn == toColumn ? startPos
1982 : findPosition(toColumn - 1);
1984 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1988 * if end column is gapped, endPos may be to the right,
1989 * and we may have included adjacent or enclosing features;
1990 * remove any that are not enclosing, non-contact features
1992 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1993 && Comparison.isGap(sequence[toColumn - 1]);
1994 if (endPos > this.end || endColumnIsGapped)
1996 ListIterator<SequenceFeature> it = result.listIterator();
1997 while (it.hasNext())
1999 SequenceFeature sf = it.next();
2000 int sfBegin = sf.getBegin();
2001 int sfEnd = sf.getEnd();
2002 int featureStartColumn = findIndex(sfBegin);
2003 if (featureStartColumn > toColumn)
2007 else if (featureStartColumn < fromColumn)
2009 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2011 if (featureEndColumn < fromColumn)
2015 else if (featureEndColumn > toColumn && sf.isContactFeature())
2018 * remove an enclosing feature if it is a contact feature
2030 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2031 * token that has to match the one presented by the cursor
2034 public void sequenceChanged()
2043 public int replace(char c1, char c2)
2050 synchronized (sequence)
2052 for (int c = 0; c < sequence.length; c++)
2054 if (sequence[c] == c1)
2070 public String getSequenceStringFromIterator(Iterator<int[]> it)
2072 StringBuilder newSequence = new StringBuilder();
2073 while (it.hasNext())
2075 int[] block = it.next();
2078 newSequence.append(getSequence(block[0], block[1] + 1));
2082 newSequence.append(getSequence(block[0], block[1]));
2086 return newSequence.toString();
2090 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2094 if (!regions.hasNext())
2096 return findIndex(getStart()) - 1;
2099 // Simply walk along the sequence whilst watching for region
2101 int hideStart = getLength();
2103 boolean foundStart = false;
2105 // step through the non-gapped positions of the sequence
2106 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2108 // get alignment position of this residue in the sequence
2109 int p = findIndex(i) - 1;
2111 // update region start/end
2112 while (hideEnd < p && regions.hasNext())
2114 int[] region = regions.next();
2115 hideStart = region[0];
2116 hideEnd = region[1];
2120 hideStart = getLength();
2122 // update boundary for sequence
2134 // otherwise, sequence was completely hidden
2139 //// Contact Matrix Holder Boilerplate
2141 ContactMapHolderI _cmholder = null;
2143 private ContactMapHolderI getContactMapHolder()
2145 if (datasetSequence!=null) {
2146 return ((Sequence)datasetSequence).getContactMapHolder();
2148 if (_cmholder==null)
2150 _cmholder=new ContactMapHolder();
2155 public Collection<ContactMatrixI> getContactMaps()
2157 return getContactMapHolder().getContactMaps();
2161 public ContactMatrixI getContactMatrixFor(AlignmentAnnotation ann)
2163 return getContactMapHolder().getContactMatrixFor(ann);
2167 public ContactListI getContactListFor(AlignmentAnnotation _aa, int column)
2169 return getContactMapHolder().getContactListFor(_aa, column);
2173 public AlignmentAnnotation addContactList(ContactMatrixI cm)
2175 AlignmentAnnotation aa;
2177 if (datasetSequence != null)
2179 aa = datasetSequence.addContactList(cm);
2180 // clone the annotation for the local sequence
2181 aa = new AlignmentAnnotation(aa);
2182 aa.restrict(start, end);
2183 aa.adjustForAlignment();
2184 getContactMapHolder().addContactListFor(aa,cm);
2185 addAlignmentAnnotation(aa);
2189 // construct new annotation for matrix on dataset sequence
2190 aa = getContactMapHolder().addContactList(cm);
2192 Annotation _aa[] = new Annotation[getLength()];
2194 for (int i = 0; i < _aa.length; _aa[i++] = new Annotation(0.0f))
2198 aa.annotations = _aa;
2199 aa.setSequenceRef(this);
2200 if (cm instanceof MappableContactMatrix
2201 && !((MappableContactMatrix) cm).hasReferenceSeq())
2203 ((MappableContactMatrix) cm).setRefSeq(this);
2205 aa.createSequenceMapping(this, getStart(), false);
2206 addAlignmentAnnotation(aa);
2211 public void addContactListFor(AlignmentAnnotation annotation,
2214 getContactMapHolder().addContactListFor(annotation, cm);