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 jalview.analysis.AlignSeq;
24 import jalview.datamodel.features.SequenceFeatures;
25 import jalview.datamodel.features.SequenceFeaturesI;
26 import jalview.util.Comparison;
27 import jalview.util.DBRefUtils;
28 import jalview.util.MapList;
29 import jalview.util.StringUtils;
30 import jalview.workers.InformationThread;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.BitSet;
35 import java.util.Collections;
36 import java.util.Enumeration;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.ListIterator;
40 import java.util.Vector;
42 import fr.orsay.lri.varna.models.rna.RNA;
46 * Implements the SequenceI interface for a char[] based sequence object
48 public class Sequence extends ASequence implements SequenceI
52 * A subclass that gives us access to modCount, which tracks whether there
53 * have been any changes. We use this to update
59 @SuppressWarnings("serial")
60 public class DBModList<T> extends ArrayList<DBRefEntry>
63 protected int getModCount()
70 SequenceI datasetSequence;
74 private char[] sequence;
76 private String description;
82 private Vector<PDBEntry> pdbIds;
84 private String vamsasId;
86 HiddenMarkovModel hmm;
88 boolean isHMMConsensusSequence = false;
90 private DBModList<DBRefEntry> dbrefs; // controlled access
93 * a flag to let us know that elements have changed in dbrefs
97 private int refModCount = 0;
102 * This annotation is displayed below the alignment but the positions are tied
103 * to the residues of this sequence
105 * TODO: change to List<>
107 private Vector<AlignmentAnnotation> annotation;
109 private SequenceFeaturesI sequenceFeatureStore;
112 * A cursor holding the approximate current view position to the sequence,
113 * as determined by findIndex or findPosition or findPositions.
114 * Using a cursor as a hint allows these methods to be more performant for
117 private SequenceCursor cursor;
120 * A number that should be incremented whenever the sequence is edited.
121 * If the value matches the cursor token, then we can trust the cursor,
122 * if not then it should be recomputed.
124 private int changeCount;
127 * Creates a new Sequence object.
130 * display name string
132 * string to form a possibly gapped sequence out of
134 * first position of non-gap residue in the sequence
136 * last position of ungapped residues (nearly always only used for
139 public Sequence(String name, String sequence, int start, int end)
142 initSeqAndName(name, sequence.toCharArray(), start, end);
145 public Sequence(String name, char[] sequence, int start, int end)
148 initSeqAndName(name, sequence, start, end);
152 * Stage 1 constructor - assign name, sequence, and set start and end fields.
153 * start and end are updated values from name2 if it ends with /start-end
160 protected void initSeqAndName(String name2, char[] sequence2, int start2,
164 this.sequence = sequence2;
172 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
173 * start and end respectively and removes the suffix from the name
180 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
183 int slashPos = name.lastIndexOf('/');
184 if (slashPos > -1 && slashPos < name.length() - 1)
186 String suffix = name.substring(slashPos + 1);
187 String[] range = suffix.split("-");
188 if (range.length == 2)
192 int from = Integer.valueOf(range[0]);
193 int to = Integer.valueOf(range[1]);
194 if (from > 0 && to >= from)
196 name = name.substring(0, slashPos);
201 } catch (NumberFormatException e)
203 // leave name unchanged if suffix is invalid
210 * Ensures that 'end' is not before the end of the sequence, that is,
211 * (end-start+1) is at least as long as the count of ungapped positions. Note
212 * that end is permitted to be beyond the end of the sequence data.
214 void checkValidRange()
217 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
220 for (int j = 0; j < sequence.length; j++)
222 if (!Comparison.isGap(sequence[j]))
241 * default constructor
245 sequenceFeatureStore = new SequenceFeatures();
249 * Creates a new Sequence object.
256 public Sequence(String name, String sequence)
258 this(name, sequence, 1, -1);
262 * Creates a new Sequence object with new AlignmentAnnotations but inherits
263 * any existing dataset sequence reference. If non exists, everything is
267 * if seq is a dataset sequence, behaves like a plain old copy
270 public Sequence(SequenceI seq)
272 this(seq, seq.getAnnotation());
276 * Create a new sequence object with new features, DBRefEntries, and PDBIds
277 * but inherits any existing dataset sequence reference, and duplicate of any
278 * annotation that is present in the given annotation array.
281 * the sequence to be copied
282 * @param alAnnotation
283 * an array of annotation including some associated with seq
285 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
288 initSeqFrom(seq, alAnnotation);
292 * does the heavy lifting when cloning a dataset sequence, or coping data from
293 * dataset to a new derived sequence.
296 * - source of attributes.
297 * @param alAnnotation
298 * - alignment annotation present on seq that should be copied onto
301 protected void initSeqFrom(SequenceI seq,
302 AlignmentAnnotation[] alAnnotation)
304 char[] oseq = seq.getSequence(); // returns a copy of the array
305 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
307 description = seq.getDescription();
308 if (seq != datasetSequence)
310 setDatasetSequence(seq.getDatasetSequence());
314 * only copy DBRefs and seqfeatures if we really are a dataset sequence
316 if (datasetSequence == null)
318 List<DBRefEntry> dbr = seq.getDBRefs();
321 for (int i = 0, n = dbr.size(); i < n; i++)
323 addDBRef(new DBRefEntry(dbr.get(i)));
328 * make copies of any sequence features
330 for (SequenceFeature sf : seq.getSequenceFeatures())
332 addSequenceFeature(new SequenceFeature(sf));
336 if (seq.getAnnotation() != null)
338 AlignmentAnnotation[] sqann = seq.getAnnotation();
339 for (int i = 0; i < sqann.length; i++)
341 if (sqann[i] == null)
345 boolean found = (alAnnotation == null);
348 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
350 found = (alAnnotation[apos] == sqann[i]);
355 // only copy the given annotation
356 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
357 addAlignmentAnnotation(newann);
361 if (seq.getAllPDBEntries() != null)
363 Vector<PDBEntry> ids = seq.getAllPDBEntries();
364 for (PDBEntry pdb : ids)
366 this.addPDBId(new PDBEntry(pdb));
369 if (seq.getHMM() != null)
371 this.hmm = new HiddenMarkovModel(seq.getHMM(), this);
377 public void setSequenceFeatures(List<SequenceFeature> features)
379 if (datasetSequence != null)
381 datasetSequence.setSequenceFeatures(features);
384 sequenceFeatureStore = new SequenceFeatures(features);
388 public synchronized boolean addSequenceFeature(SequenceFeature sf)
390 if (sf.getType() == null)
393 "SequenceFeature type may not be null: " + sf.toString());
397 if (datasetSequence != null)
399 return datasetSequence.addSequenceFeature(sf);
402 return sequenceFeatureStore.add(sf);
406 public void deleteFeature(SequenceFeature sf)
408 if (datasetSequence != null)
410 datasetSequence.deleteFeature(sf);
414 sequenceFeatureStore.delete(sf);
424 public List<SequenceFeature> getSequenceFeatures()
426 if (datasetSequence != null)
428 return datasetSequence.getSequenceFeatures();
430 return sequenceFeatureStore.getAllFeatures();
434 public SequenceFeaturesI getFeatures()
436 return datasetSequence != null ? datasetSequence.getFeatures()
437 : sequenceFeatureStore;
441 public boolean addPDBId(PDBEntry entry)
445 pdbIds = new Vector<>();
450 for (PDBEntry pdbe : pdbIds)
452 if (pdbe.updateFrom(entry))
457 pdbIds.addElement(entry);
468 public void setPDBId(Vector<PDBEntry> id)
476 * @return DOCUMENT ME!
479 public Vector<PDBEntry> getAllPDBEntries()
481 return pdbIds == null ? new Vector<>() : pdbIds;
485 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
490 public String getDisplayId(boolean jvsuffix)
496 StringBuilder result = new StringBuilder(name);
497 result.append("/").append(start).append("-").append(end);
499 return result.toString();
503 * Sets the sequence name. If the name ends in /start-end, then the start-end
504 * values are parsed out and set, and the suffix is removed from the name.
509 public void setName(String theName)
518 * @return DOCUMENT ME!
521 public String getName()
533 public void setStart(int start)
542 * @return DOCUMENT ME!
545 public int getStart()
557 public void setEnd(int end)
565 * @return DOCUMENT ME!
576 * @return DOCUMENT ME!
579 public int getLength()
581 return this.sequence.length;
591 public void setSequence(String seq)
593 this.sequence = seq.toCharArray();
599 public String getSequenceAsString()
601 return new String(sequence);
605 public String getSequenceAsString(int start, int end)
607 return new String(getSequence(start, end));
611 public char[] getSequence()
614 return sequence == null ? null
615 : Arrays.copyOf(sequence, sequence.length);
621 * @see jalview.datamodel.SequenceI#getSequence(int, int)
624 public char[] getSequence(int start, int end)
630 // JBPNote - left to user to pad the result here (TODO:Decide on this
632 if (start >= sequence.length)
637 if (end >= sequence.length)
639 end = sequence.length;
642 char[] reply = new char[end - start];
643 System.arraycopy(sequence, start, reply, 0, end - start);
649 public SequenceI getSubSequence(int start, int end)
655 char[] seq = getSequence(start, end);
660 int nstart = findPosition(start);
661 int nend = findPosition(end) - 1;
662 // JBPNote - this is an incomplete copy.
663 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
664 nseq.setDescription(description);
665 if (datasetSequence != null)
667 nseq.setDatasetSequence(datasetSequence);
671 nseq.setDatasetSequence(this);
677 * Returns the character of the aligned sequence at the given position (base
678 * zero), or space if the position is not within the sequence's bounds
683 public char getCharAt(int i)
685 if (i >= 0 && i < sequence.length)
696 * Sets the sequence description, and also parses out any special formats of
702 public void setDescription(String desc)
704 this.description = desc;
708 public void setGeneLoci(String speciesId, String assemblyId,
709 String chromosomeId, MapList map)
711 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
716 * Returns the gene loci mapping for the sequence (may be null)
721 public GeneLociI getGeneLoci()
723 List<DBRefEntry> refs = getDBRefs();
726 for (final DBRefEntry ref : refs)
728 if (ref instanceof GeneLociI)
730 return (GeneLociI) ref;
738 * Answers the description
743 public String getDescription()
745 return this.description;
752 public int findIndex(int pos)
755 * use a valid, hopefully nearby, cursor if available
757 if (isValidCursor(cursor))
759 return findIndex(pos, cursor);
767 * traverse sequence from the start counting gaps; make a note of
768 * the column of the first residue to save in the cursor
770 while ((i < sequence.length) && (j <= end) && (j <= pos))
772 if (!Comparison.isGap(sequence[i]))
783 if (j == end && j < pos)
788 updateCursor(pos, i, startColumn);
793 * Updates the cursor to the latest found residue and column position
800 * column position of the first sequence residue
802 protected void updateCursor(int residuePos, int column, int startColumn)
805 * preserve end residue column provided cursor was valid
807 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
809 if (residuePos == this.end)
814 cursor = new SequenceCursor(this, residuePos, column, startColumn,
815 endColumn, this.changeCount);
819 * Answers the aligned column position (1..) for the given residue position
820 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
821 * The hint may be left of, at, or to the right of the required position.
827 protected int findIndex(final int pos, SequenceCursor curs)
829 if (!isValidCursor(curs))
832 * wrong or invalidated cursor, compute de novo
834 return findIndex(pos);
837 if (curs.residuePosition == pos)
839 return curs.columnPosition;
843 * move left or right to find pos from hint.position
845 int col = curs.columnPosition - 1; // convert from base 1 to base 0
846 int newPos = curs.residuePosition;
847 int delta = newPos > pos ? -1 : 1;
849 while (newPos != pos)
851 col += delta; // shift one column left or right
856 if (col == sequence.length)
858 col--; // return last column if we failed to reach pos
861 if (!Comparison.isGap(sequence[col]))
867 col++; // convert back to base 1
870 * only update cursor if we found the target position
874 updateCursor(pos, col, curs.firstColumnPosition);
884 public int findPosition(final int column)
887 * use a valid, hopefully nearby, cursor if available
889 if (isValidCursor(cursor))
891 return findPosition(column + 1, cursor);
894 // TODO recode this more naturally i.e. count residues only
895 // as they are found, not 'in anticipation'
898 * traverse the sequence counting gaps; note the column position
899 * of the first residue, to save in the cursor
901 int firstResidueColumn = 0;
902 int lastPosFound = 0;
903 int lastPosFoundColumn = 0;
904 int seqlen = sequence.length;
906 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
908 lastPosFound = start;
909 lastPosFoundColumn = 0;
915 while (j < column && j < seqlen)
917 if (!Comparison.isGap(sequence[j]))
920 lastPosFoundColumn = j;
921 if (pos == this.start)
923 firstResidueColumn = j;
929 if (j < seqlen && !Comparison.isGap(sequence[j]))
932 lastPosFoundColumn = j;
933 if (pos == this.start)
935 firstResidueColumn = j;
940 * update the cursor to the last residue position found (if any)
941 * (converting column position to base 1)
943 if (lastPosFound != 0)
945 updateCursor(lastPosFound, lastPosFoundColumn + 1,
946 firstResidueColumn + 1);
953 * Answers true if the given cursor is not null, is for this sequence object,
954 * and has a token value that matches this object's changeCount, else false.
955 * This allows us to ignore a cursor as 'stale' if the sequence has been
956 * modified since the cursor was created.
961 protected boolean isValidCursor(SequenceCursor curs)
963 if (curs == null || curs.sequence != this || curs.token != changeCount)
968 * sanity check against range
970 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
974 if (curs.residuePosition < start || curs.residuePosition > end)
982 * Answers the sequence position (start..) for the given aligned column
983 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
984 * may lie left of, at, or to the right of the column position.
990 protected int findPosition(final int col, SequenceCursor curs)
992 if (!isValidCursor(curs))
995 * wrong or invalidated cursor, compute de novo
997 return findPosition(col - 1);// ugh back to base 0
1000 if (curs.columnPosition == col)
1002 cursor = curs; // in case this method becomes public
1003 return curs.residuePosition; // easy case :-)
1006 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1009 * sequence lies entirely to the left of col
1010 * - return last residue + 1
1015 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1018 * sequence lies entirely to the right of col
1019 * - return first residue
1024 // todo could choose closest to col out of column,
1025 // firstColumnPosition, lastColumnPosition as a start point
1028 * move left or right to find pos from cursor position
1030 int firstResidueColumn = curs.firstColumnPosition;
1031 int column = curs.columnPosition - 1; // to base 0
1032 int newPos = curs.residuePosition;
1033 int delta = curs.columnPosition > col ? -1 : 1;
1034 boolean gapped = false;
1035 int lastFoundPosition = curs.residuePosition;
1036 int lastFoundPositionColumn = curs.columnPosition;
1038 while (column != col - 1)
1040 column += delta; // shift one column left or right
1041 if (column < 0 || column == sequence.length)
1045 gapped = Comparison.isGap(sequence[column]);
1049 lastFoundPosition = newPos;
1050 lastFoundPositionColumn = column + 1;
1051 if (lastFoundPosition == this.start)
1053 firstResidueColumn = column + 1;
1058 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1060 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1061 firstResidueColumn);
1065 * hack to give position to the right if on a gap
1066 * or beyond the length of the sequence (see JAL-2562)
1068 if (delta > 0 && (gapped || column >= sequence.length))
1080 public ContiguousI findPositions(int fromColumn, int toColumn)
1082 fromColumn = Math.max(fromColumn, 1);
1083 if (toColumn < fromColumn)
1089 * find the first non-gapped position, if any
1091 int firstPosition = 0;
1092 int col = fromColumn - 1;
1093 int length = sequence.length;
1094 while (col < length && col < toColumn)
1096 if (!Comparison.isGap(sequence[col]))
1098 firstPosition = findPosition(col++);
1104 if (firstPosition == 0)
1110 * find the last non-gapped position
1112 int lastPosition = firstPosition;
1113 while (col < length && col < toColumn)
1115 if (!Comparison.isGap(sequence[col++]))
1121 return new Range(firstPosition, lastPosition);
1125 * Returns an int array where indices correspond to each residue in the
1126 * sequence and the element value gives its position in the alignment
1128 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1129 * residues in SequenceI object
1132 public int[] gapMap()
1134 String seq = jalview.analysis.AlignSeq.extractGaps(
1135 jalview.util.Comparison.GapChars, new String(sequence));
1136 int[] map = new int[seq.length()];
1140 while (j < sequence.length)
1142 if (!jalview.util.Comparison.isGap(sequence[j]))
1154 * Build a bitset corresponding to sequence gaps
1156 * @return a BitSet where set values correspond to gaps in the sequence
1159 public BitSet gapBitset()
1161 BitSet gaps = new BitSet(sequence.length);
1163 while (j < sequence.length)
1165 if (jalview.util.Comparison.isGap(sequence[j]))
1175 public int[] findPositionMap()
1177 int map[] = new int[sequence.length];
1180 int seqlen = sequence.length;
1181 while ((j < seqlen))
1184 if (!jalview.util.Comparison.isGap(sequence[j]))
1195 public List<int[]> getInsertions()
1197 ArrayList<int[]> map = new ArrayList<>();
1198 int lastj = -1, j = 0;
1200 int seqlen = sequence.length;
1201 while ((j < seqlen))
1203 if (jalview.util.Comparison.isGap(sequence[j]))
1214 map.add(new int[] { lastj, j - 1 });
1222 map.add(new int[] { lastj, j - 1 });
1229 public BitSet getInsertionsAsBits()
1231 BitSet map = new BitSet();
1232 int lastj = -1, j = 0;
1234 int seqlen = sequence.length;
1235 while ((j < seqlen))
1237 if (jalview.util.Comparison.isGap(sequence[j]))
1263 public void deleteChars(final int i, final int j)
1265 int newstart = start, newend = end;
1266 if (i >= sequence.length || i < 0)
1271 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1272 boolean createNewDs = false;
1273 // TODO: take a (second look) at the dataset creation validation method for
1274 // the very large sequence case
1276 int startIndex = findIndex(start) - 1;
1277 int endIndex = findIndex(end) - 1;
1278 int startDeleteColumn = -1; // for dataset sequence deletions
1279 int deleteCount = 0;
1281 for (int s = i; s < j && s < sequence.length; s++)
1283 if (Comparison.isGap(sequence[s]))
1288 if (startDeleteColumn == -1)
1290 startDeleteColumn = findPosition(s) - start;
1298 if (startIndex == s)
1301 * deleting characters from start of sequence; new start is the
1302 * sequence position of the next column (position to the right
1303 * if the column position is gapped)
1305 newstart = findPosition(j);
1313 * deleting characters at end of sequence; new end is the sequence
1314 * position of the column before the deletion; subtract 1 if this is
1315 * gapped since findPosition returns the next sequence position
1317 newend = findPosition(i - 1);
1318 if (Comparison.isGap(sequence[i - 1]))
1333 if (createNewDs && this.datasetSequence != null)
1336 * if deletion occured in the middle of the sequence,
1337 * construct a new dataset sequence and delete the residues
1338 * that were deleted from the aligned sequence
1340 Sequence ds = new Sequence(datasetSequence);
1341 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1342 datasetSequence = ds;
1343 // TODO: remove any non-inheritable properties ?
1344 // TODO: create a sequence mapping (since there is a relation here ?)
1353 public void insertCharAt(int i, int length, char c)
1355 char[] tmp = new char[sequence.length + length];
1357 if (i >= sequence.length)
1359 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1360 i = sequence.length;
1364 System.arraycopy(sequence, 0, tmp, 0, i);
1374 if (i < sequence.length)
1376 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1384 public void insertCharAt(int i, char c)
1386 insertCharAt(i, 1, c);
1390 public String getVamsasId()
1396 public void setVamsasId(String id)
1403 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1405 if (dbrefs == null && datasetSequence != null
1406 && this != datasetSequence)
1408 datasetSequence.setDBRefs(newDBrefs);
1416 public DBModList<DBRefEntry> getDBRefs()
1418 if (dbrefs == null && datasetSequence != null
1419 && this != datasetSequence)
1421 return datasetSequence.getDBRefs();
1427 public void addDBRef(DBRefEntry entry)
1429 if (datasetSequence != null)
1431 datasetSequence.addDBRef(entry);
1437 dbrefs = new DBModList<>();
1440 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1442 if (dbrefs.get(ib).updateFrom(entry))
1445 * found a dbref that either matched, or could be
1446 * updated from, the new entry - no need to add it
1454 // * extend the array to make room for one more
1456 // // TODO use an ArrayList instead
1457 // int j = dbrefs.length;
1458 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1459 // System.arraycopy(dbrefs, 0, temp, 0, j);
1460 // temp[temp.length - 1] = entry;
1468 public void setDatasetSequence(SequenceI seq)
1472 throw new IllegalArgumentException(
1473 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1475 if (seq != null && seq.getDatasetSequence() != null)
1477 throw new IllegalArgumentException(
1478 "Implementation error: cascading dataset sequences are not allowed.");
1480 datasetSequence = seq;
1484 public SequenceI getDatasetSequence()
1486 return datasetSequence;
1490 public AlignmentAnnotation[] getAnnotation()
1492 return annotation == null ? null
1494 .toArray(new AlignmentAnnotation[annotation.size()]);
1498 public boolean hasAnnotation(AlignmentAnnotation ann)
1500 return annotation == null ? false : annotation.contains(ann);
1504 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1506 if (this.annotation == null)
1508 this.annotation = new Vector<>();
1510 if (!this.annotation.contains(annotation))
1512 this.annotation.addElement(annotation);
1514 annotation.setSequenceRef(this);
1518 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1520 if (this.annotation != null)
1522 this.annotation.removeElement(annotation);
1523 if (this.annotation.size() == 0)
1525 this.annotation = null;
1531 * test if this is a valid candidate for another sequence's dataset sequence.
1534 private boolean isValidDatasetSequence()
1536 if (datasetSequence != null)
1540 for (int i = 0; i < sequence.length; i++)
1542 if (jalview.util.Comparison.isGap(sequence[i]))
1551 public SequenceI deriveSequence()
1553 Sequence seq = null;
1554 if (datasetSequence == null)
1556 if (isValidDatasetSequence())
1558 // Use this as dataset sequence
1559 seq = new Sequence(getName(), "", 1, -1);
1560 seq.setDatasetSequence(this);
1561 seq.initSeqFrom(this, getAnnotation());
1566 // Create a new, valid dataset sequence
1567 createDatasetSequence();
1570 return new Sequence(this);
1573 private boolean _isNa;
1575 private int _seqhash = 0;
1577 private List<DBRefEntry> primaryRefs;
1580 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1584 public boolean isProtein()
1586 if (datasetSequence != null)
1588 return datasetSequence.isProtein();
1590 if (_seqhash != sequence.hashCode())
1592 _seqhash = sequence.hashCode();
1593 _isNa = Comparison.isNucleotide(this);
1601 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1604 public SequenceI createDatasetSequence()
1606 if (datasetSequence == null)
1608 Sequence dsseq = new Sequence(getName(),
1609 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1610 getSequenceAsString()),
1611 getStart(), getEnd());
1613 datasetSequence = dsseq;
1615 dsseq.setDescription(description);
1616 // move features and database references onto dataset sequence
1617 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1618 sequenceFeatureStore = null;
1619 dsseq.dbrefs = dbrefs;
1621 // TODO: search and replace any references to this sequence with
1622 // references to the dataset sequence in Mappings on dbref
1623 dsseq.pdbIds = pdbIds;
1625 datasetSequence.updatePDBIds();
1626 if (annotation != null)
1628 // annotation is cloned rather than moved, to preserve what's currently
1630 for (AlignmentAnnotation aa : annotation)
1632 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1633 _aa.sequenceRef = datasetSequence;
1634 _aa.adjustForAlignment(); // uses annotation's own record of
1635 // sequence-column mapping
1636 datasetSequence.addAlignmentAnnotation(_aa);
1640 return datasetSequence;
1647 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1651 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1653 if (annotation != null)
1655 annotation.removeAllElements();
1657 if (annotations != null)
1659 for (int i = 0; i < annotations.length; i++)
1661 if (annotations[i] != null)
1663 addAlignmentAnnotation(annotations[i]);
1670 public AlignmentAnnotation[] getAnnotation(String label)
1672 if (annotation == null || annotation.size() == 0)
1677 Vector<AlignmentAnnotation> subset = new Vector<>();
1678 Enumeration<AlignmentAnnotation> e = annotation.elements();
1679 while (e.hasMoreElements())
1681 AlignmentAnnotation ann = e.nextElement();
1682 if (ann.label != null && ann.label.equals(label))
1684 subset.addElement(ann);
1687 if (subset.size() == 0)
1691 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1693 e = subset.elements();
1694 while (e.hasMoreElements())
1696 anns[i++] = e.nextElement();
1698 subset.removeAllElements();
1703 public boolean updatePDBIds()
1705 if (datasetSequence != null)
1707 // TODO: could merge DBRefs
1708 return datasetSequence.updatePDBIds();
1710 if (dbrefs == null || dbrefs.size() == 0)
1714 boolean added = false;
1715 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1717 DBRefEntry dbr = dbrefs.get(ib);
1718 if (DBRefSource.PDB.equals(dbr.getSource()))
1721 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1722 * PDB id is not already present in a 'matching' PDBEntry
1723 * Constructor parses out a chain code if appended to the accession id
1724 * (a fudge used to 'store' the chain code in the DBRef)
1726 PDBEntry pdbe = new PDBEntry(dbr);
1727 added |= addPDBId(pdbe);
1734 public void transferAnnotation(SequenceI entry, Mapping mp)
1736 if (datasetSequence != null)
1738 datasetSequence.transferAnnotation(entry, mp);
1741 if (entry.getDatasetSequence() != null)
1743 transferAnnotation(entry.getDatasetSequence(), mp);
1746 // transfer any new features from entry onto sequence
1747 if (entry.getSequenceFeatures() != null)
1750 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1751 for (SequenceFeature feature : sfs)
1753 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1754 : new SequenceFeature[]
1755 { new SequenceFeature(feature) };
1758 for (int sfi = 0; sfi < sf.length; sfi++)
1760 addSequenceFeature(sf[sfi]);
1766 // transfer PDB entries
1767 if (entry.getAllPDBEntries() != null)
1769 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1770 while (e.hasMoreElements())
1772 PDBEntry pdb = e.nextElement();
1776 // transfer database references
1777 List<DBRefEntry> entryRefs = entry.getDBRefs();
1778 if (entryRefs != null)
1780 for (int r = 0, n = entryRefs.size(); r < n; r++)
1782 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1783 if (newref.getMap() != null && mp != null)
1785 // remap ref using our local mapping
1787 // we also assume all version string setting is done by dbSourceProxy
1789 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1790 * newref.setSource(dbSource); }
1798 public void setRNA(RNA r)
1810 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1813 List<AlignmentAnnotation> result = new ArrayList<>();
1814 if (this.annotation != null)
1816 for (AlignmentAnnotation ann : annotation)
1818 String id = ann.getCalcId();
1819 if (id != null && id.equals(calcId)
1820 && ann.label != null && ann.label.equals(label))
1830 public String toString()
1832 return getDisplayId(false);
1836 public PDBEntry getPDBEntry(String pdbIdStr)
1838 if (getDatasetSequence() != null)
1840 return getDatasetSequence().getPDBEntry(pdbIdStr);
1846 List<PDBEntry> entries = getAllPDBEntries();
1847 for (PDBEntry entry : entries)
1849 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1857 private List<DBRefEntry> tmpList;
1860 public List<DBRefEntry> getPrimaryDBRefs()
1862 if (datasetSequence != null)
1864 return datasetSequence.getPrimaryDBRefs();
1866 if (dbrefs == null || dbrefs.size() == 0)
1868 return Collections.emptyList();
1870 synchronized (dbrefs)
1872 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1874 return primaryRefs; // no changes
1876 refModCount = dbrefs.getModCount();
1877 List<DBRefEntry> primaries = (primaryRefs == null
1878 ? (primaryRefs = new ArrayList<>())
1881 if (tmpList == null)
1883 tmpList = new ArrayList<>();
1884 tmpList.add(null); // for replacement
1886 for (int i = 0, n = dbrefs.size(); i < n; i++)
1888 DBRefEntry ref = dbrefs.get(i);
1889 if (!ref.isPrimaryCandidate())
1895 MapList mp = ref.getMap().getMap();
1896 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1898 // map only involves a subsequence, so cannot be primary
1902 // whilst it looks like it is a primary ref, we also sanity check type
1903 if (DBRefSource.PDB_CANONICAL_NAME
1904 .equals(ref.getCanonicalSourceName()))
1906 // PDB dbrefs imply there should be a PDBEntry associated
1907 // TODO: tighten PDB dbrefs
1908 // formally imply Jalview has actually downloaded and
1909 // parsed the pdb file. That means there should be a cached file
1910 // handle on the PDBEntry, and a real mapping between sequence and
1911 // extracted sequence from PDB file
1912 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1913 if (pdbentry == null || pdbentry.getFile() == null)
1920 // check standard protein or dna sources
1921 tmpList.set(0, ref);
1922 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1924 if (res == null || res.get(0) != tmpList.get(0))
1932 // version must be not null, as otherwise it will not be a candidate,
1934 DBRefUtils.ensurePrimaries(this, primaries);
1940 public HiddenMarkovModel getHMM()
1946 public void setHMM(HiddenMarkovModel hmm)
1952 public boolean hasHMMAnnotation()
1954 if (this.annotation == null) {
1957 for (AlignmentAnnotation ann : annotation)
1959 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1971 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1974 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1975 int endPos = fromColumn == toColumn ? startPos
1976 : findPosition(toColumn - 1);
1978 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1982 * if end column is gapped, endPos may be to the right,
1983 * and we may have included adjacent or enclosing features;
1984 * remove any that are not enclosing, non-contact features
1986 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1987 && Comparison.isGap(sequence[toColumn - 1]);
1988 if (endPos > this.end || endColumnIsGapped)
1990 ListIterator<SequenceFeature> it = result.listIterator();
1991 while (it.hasNext())
1993 SequenceFeature sf = it.next();
1994 int sfBegin = sf.getBegin();
1995 int sfEnd = sf.getEnd();
1996 int featureStartColumn = findIndex(sfBegin);
1997 if (featureStartColumn > toColumn)
2001 else if (featureStartColumn < fromColumn)
2003 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2005 if (featureEndColumn < fromColumn)
2009 else if (featureEndColumn > toColumn && sf.isContactFeature())
2012 * remove an enclosing feature if it is a contact feature
2024 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2025 * token that has to match the one presented by the cursor
2028 public void sequenceChanged()
2037 public int replace(char c1, char c2)
2044 synchronized (sequence)
2046 for (int c = 0; c < sequence.length; c++)
2048 if (sequence[c] == c1)
2064 public String getSequenceStringFromIterator(Iterator<int[]> it)
2066 StringBuilder newSequence = new StringBuilder();
2067 while (it.hasNext())
2069 int[] block = it.next();
2072 newSequence.append(getSequence(block[0], block[1] + 1));
2076 newSequence.append(getSequence(block[0], block[1]));
2080 return newSequence.toString();
2084 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2088 if (!regions.hasNext())
2090 return findIndex(getStart()) - 1;
2093 // Simply walk along the sequence whilst watching for region
2095 int hideStart = getLength();
2097 boolean foundStart = false;
2099 // step through the non-gapped positions of the sequence
2100 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2102 // get alignment position of this residue in the sequence
2103 int p = findIndex(i) - 1;
2105 // update region start/end
2106 while (hideEnd < p && regions.hasNext())
2108 int[] region = regions.next();
2109 hideStart = region[0];
2110 hideEnd = region[1];
2114 hideStart = getLength();
2116 // update boundary for sequence
2128 // otherwise, sequence was completely hidden
2133 public boolean hasHMMProfile()