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 * Create a new sequence object from a characters array using default values
263 * of 1 and -1 for start and end. The array used to create the sequence is
264 * copied and is not stored internally.
271 public Sequence(String name, char[] sequence)
273 this(name, Arrays.copyOf(sequence, sequence.length), 1, -1);
277 * Creates a new Sequence object with new AlignmentAnnotations but inherits
278 * any existing dataset sequence reference. If non exists, everything is
282 * if seq is a dataset sequence, behaves like a plain old copy
285 public Sequence(SequenceI seq)
287 this(seq, seq.getAnnotation());
291 * Create a new sequence object with new features, DBRefEntries, and PDBIds
292 * but inherits any existing dataset sequence reference, and duplicate of any
293 * annotation that is present in the given annotation array.
296 * the sequence to be copied
297 * @param alAnnotation
298 * an array of annotation including some associated with seq
300 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
303 initSeqFrom(seq, alAnnotation);
307 * does the heavy lifting when cloning a dataset sequence, or coping data from
308 * dataset to a new derived sequence.
311 * - source of attributes.
312 * @param alAnnotation
313 * - alignment annotation present on seq that should be copied onto
316 protected void initSeqFrom(SequenceI seq,
317 AlignmentAnnotation[] alAnnotation)
319 char[] oseq = seq.getSequence(); // returns a copy of the array
320 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
322 description = seq.getDescription();
323 if (seq != datasetSequence)
325 setDatasetSequence(seq.getDatasetSequence());
329 * only copy DBRefs and seqfeatures if we really are a dataset sequence
331 if (datasetSequence == null)
333 List<DBRefEntry> dbr = seq.getDBRefs();
336 for (int i = 0, n = dbr.size(); i < n; i++)
338 addDBRef(new DBRefEntry(dbr.get(i)));
343 * make copies of any sequence features
345 for (SequenceFeature sf : seq.getSequenceFeatures())
347 addSequenceFeature(new SequenceFeature(sf));
351 if (seq.getAnnotation() != null)
353 AlignmentAnnotation[] sqann = seq.getAnnotation();
354 for (int i = 0; i < sqann.length; i++)
356 if (sqann[i] == null)
360 boolean found = (alAnnotation == null);
363 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
365 found = (alAnnotation[apos] == sqann[i]);
370 // only copy the given annotation
371 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
372 addAlignmentAnnotation(newann);
376 if (seq.getAllPDBEntries() != null)
378 Vector<PDBEntry> ids = seq.getAllPDBEntries();
379 for (PDBEntry pdb : ids)
381 this.addPDBId(new PDBEntry(pdb));
384 if (seq.getHMM() != null)
386 this.hmm = new HiddenMarkovModel(seq.getHMM(), this);
392 public void setSequenceFeatures(List<SequenceFeature> features)
394 if (datasetSequence != null)
396 datasetSequence.setSequenceFeatures(features);
399 sequenceFeatureStore = new SequenceFeatures(features);
403 public synchronized boolean addSequenceFeature(SequenceFeature sf)
405 if (sf.getType() == null)
408 "SequenceFeature type may not be null: " + sf.toString());
412 if (datasetSequence != null)
414 return datasetSequence.addSequenceFeature(sf);
417 return sequenceFeatureStore.add(sf);
421 public void deleteFeature(SequenceFeature sf)
423 if (datasetSequence != null)
425 datasetSequence.deleteFeature(sf);
429 sequenceFeatureStore.delete(sf);
439 public List<SequenceFeature> getSequenceFeatures()
441 if (datasetSequence != null)
443 return datasetSequence.getSequenceFeatures();
445 return sequenceFeatureStore.getAllFeatures();
449 public SequenceFeaturesI getFeatures()
451 return datasetSequence != null ? datasetSequence.getFeatures()
452 : sequenceFeatureStore;
456 public boolean addPDBId(PDBEntry entry)
460 pdbIds = new Vector<>();
465 for (PDBEntry pdbe : pdbIds)
467 if (pdbe.updateFrom(entry))
472 pdbIds.addElement(entry);
483 public void setPDBId(Vector<PDBEntry> id)
491 * @return DOCUMENT ME!
494 public Vector<PDBEntry> getAllPDBEntries()
496 return pdbIds == null ? new Vector<>() : pdbIds;
500 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
505 public String getDisplayId(boolean jvsuffix)
511 StringBuilder result = new StringBuilder(name);
512 result.append("/").append(start).append("-").append(end);
514 return result.toString();
518 * Sets the sequence name. If the name ends in /start-end, then the start-end
519 * values are parsed out and set, and the suffix is removed from the name.
524 public void setName(String theName)
533 * @return DOCUMENT ME!
536 public String getName()
548 public void setStart(int start)
557 * @return DOCUMENT ME!
560 public int getStart()
572 public void setEnd(int end)
580 * @return DOCUMENT ME!
591 * @return DOCUMENT ME!
594 public int getLength()
596 return this.sequence.length;
606 public void setSequence(String seq)
608 this.sequence = seq.toCharArray();
614 public String getSequenceAsString()
616 return new String(sequence);
620 public String getSequenceAsString(int start, int end)
622 return new String(getSequence(start, end));
626 public char[] getSequence()
629 return sequence == null ? null
630 : Arrays.copyOf(sequence, sequence.length);
636 * @see jalview.datamodel.SequenceI#getSequence(int, int)
639 public char[] getSequence(int start, int end)
645 // JBPNote - left to user to pad the result here (TODO:Decide on this
647 if (start >= sequence.length)
652 if (end >= sequence.length)
654 end = sequence.length;
657 char[] reply = new char[end - start];
658 System.arraycopy(sequence, start, reply, 0, end - start);
664 public SequenceI getSubSequence(int start, int end)
670 char[] seq = getSequence(start, end);
675 int nstart = findPosition(start);
676 int nend = findPosition(end) - 1;
677 // JBPNote - this is an incomplete copy.
678 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
679 nseq.setDescription(description);
680 if (datasetSequence != null)
682 nseq.setDatasetSequence(datasetSequence);
686 nseq.setDatasetSequence(this);
692 * Returns the character of the aligned sequence at the given position (base
693 * zero), or space if the position is not within the sequence's bounds
698 public char getCharAt(int i)
700 if (i >= 0 && i < sequence.length)
711 * Sets the sequence description, and also parses out any special formats of
717 public void setDescription(String desc)
719 this.description = desc;
723 public void setGeneLoci(String speciesId, String assemblyId,
724 String chromosomeId, MapList map)
726 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
731 * Returns the gene loci mapping for the sequence (may be null)
736 public GeneLociI getGeneLoci()
738 List<DBRefEntry> refs = getDBRefs();
741 for (final DBRefEntry ref : refs)
743 if (ref instanceof GeneLociI)
745 return (GeneLociI) ref;
753 * Answers the description
758 public String getDescription()
760 return this.description;
767 public int findIndex(int pos)
770 * use a valid, hopefully nearby, cursor if available
772 if (isValidCursor(cursor))
774 return findIndex(pos, cursor);
782 * traverse sequence from the start counting gaps; make a note of
783 * the column of the first residue to save in the cursor
785 while ((i < sequence.length) && (j <= end) && (j <= pos))
787 if (!Comparison.isGap(sequence[i]))
798 if (j == end && j < pos)
803 updateCursor(pos, i, startColumn);
808 * Updates the cursor to the latest found residue and column position
815 * column position of the first sequence residue
817 protected void updateCursor(int residuePos, int column, int startColumn)
820 * preserve end residue column provided cursor was valid
822 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
824 if (residuePos == this.end)
829 cursor = new SequenceCursor(this, residuePos, column, startColumn,
830 endColumn, this.changeCount);
834 * Answers the aligned column position (1..) for the given residue position
835 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
836 * The hint may be left of, at, or to the right of the required position.
842 protected int findIndex(final int pos, SequenceCursor curs)
844 if (!isValidCursor(curs))
847 * wrong or invalidated cursor, compute de novo
849 return findIndex(pos);
852 if (curs.residuePosition == pos)
854 return curs.columnPosition;
858 * move left or right to find pos from hint.position
860 int col = curs.columnPosition - 1; // convert from base 1 to base 0
861 int newPos = curs.residuePosition;
862 int delta = newPos > pos ? -1 : 1;
864 while (newPos != pos)
866 col += delta; // shift one column left or right
871 if (col == sequence.length)
873 col--; // return last column if we failed to reach pos
876 if (!Comparison.isGap(sequence[col]))
882 col++; // convert back to base 1
885 * only update cursor if we found the target position
889 updateCursor(pos, col, curs.firstColumnPosition);
899 public int findPosition(final int column)
902 * use a valid, hopefully nearby, cursor if available
904 if (isValidCursor(cursor))
906 return findPosition(column + 1, cursor);
909 // TODO recode this more naturally i.e. count residues only
910 // as they are found, not 'in anticipation'
913 * traverse the sequence counting gaps; note the column position
914 * of the first residue, to save in the cursor
916 int firstResidueColumn = 0;
917 int lastPosFound = 0;
918 int lastPosFoundColumn = 0;
919 int seqlen = sequence.length;
921 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
923 lastPosFound = start;
924 lastPosFoundColumn = 0;
930 while (j < column && j < seqlen)
932 if (!Comparison.isGap(sequence[j]))
935 lastPosFoundColumn = j;
936 if (pos == this.start)
938 firstResidueColumn = j;
944 if (j < seqlen && !Comparison.isGap(sequence[j]))
947 lastPosFoundColumn = j;
948 if (pos == this.start)
950 firstResidueColumn = j;
955 * update the cursor to the last residue position found (if any)
956 * (converting column position to base 1)
958 if (lastPosFound != 0)
960 updateCursor(lastPosFound, lastPosFoundColumn + 1,
961 firstResidueColumn + 1);
968 * Answers true if the given cursor is not null, is for this sequence object,
969 * and has a token value that matches this object's changeCount, else false.
970 * This allows us to ignore a cursor as 'stale' if the sequence has been
971 * modified since the cursor was created.
976 protected boolean isValidCursor(SequenceCursor curs)
978 if (curs == null || curs.sequence != this || curs.token != changeCount)
983 * sanity check against range
985 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
989 if (curs.residuePosition < start || curs.residuePosition > end)
997 * Answers the sequence position (start..) for the given aligned column
998 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
999 * may lie left of, at, or to the right of the column position.
1005 protected int findPosition(final int col, SequenceCursor curs)
1007 if (!isValidCursor(curs))
1010 * wrong or invalidated cursor, compute de novo
1012 return findPosition(col - 1);// ugh back to base 0
1015 if (curs.columnPosition == col)
1017 cursor = curs; // in case this method becomes public
1018 return curs.residuePosition; // easy case :-)
1021 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1024 * sequence lies entirely to the left of col
1025 * - return last residue + 1
1030 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1033 * sequence lies entirely to the right of col
1034 * - return first residue
1039 // todo could choose closest to col out of column,
1040 // firstColumnPosition, lastColumnPosition as a start point
1043 * move left or right to find pos from cursor position
1045 int firstResidueColumn = curs.firstColumnPosition;
1046 int column = curs.columnPosition - 1; // to base 0
1047 int newPos = curs.residuePosition;
1048 int delta = curs.columnPosition > col ? -1 : 1;
1049 boolean gapped = false;
1050 int lastFoundPosition = curs.residuePosition;
1051 int lastFoundPositionColumn = curs.columnPosition;
1053 while (column != col - 1)
1055 column += delta; // shift one column left or right
1056 if (column < 0 || column == sequence.length)
1060 gapped = Comparison.isGap(sequence[column]);
1064 lastFoundPosition = newPos;
1065 lastFoundPositionColumn = column + 1;
1066 if (lastFoundPosition == this.start)
1068 firstResidueColumn = column + 1;
1073 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1075 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1076 firstResidueColumn);
1080 * hack to give position to the right if on a gap
1081 * or beyond the length of the sequence (see JAL-2562)
1083 if (delta > 0 && (gapped || column >= sequence.length))
1095 public ContiguousI findPositions(int fromColumn, int toColumn)
1097 fromColumn = Math.max(fromColumn, 1);
1098 if (toColumn < fromColumn)
1104 * find the first non-gapped position, if any
1106 int firstPosition = 0;
1107 int col = fromColumn - 1;
1108 int length = sequence.length;
1109 while (col < length && col < toColumn)
1111 if (!Comparison.isGap(sequence[col]))
1113 firstPosition = findPosition(col++);
1119 if (firstPosition == 0)
1125 * find the last non-gapped position
1127 int lastPosition = firstPosition;
1128 while (col < length && col < toColumn)
1130 if (!Comparison.isGap(sequence[col++]))
1136 return new Range(firstPosition, lastPosition);
1140 * Returns an int array where indices correspond to each residue in the
1141 * sequence and the element value gives its position in the alignment
1143 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1144 * residues in SequenceI object
1147 public int[] gapMap()
1149 String seq = jalview.analysis.AlignSeq.extractGaps(
1150 jalview.util.Comparison.GapChars, new String(sequence));
1151 int[] map = new int[seq.length()];
1155 while (j < sequence.length)
1157 if (!jalview.util.Comparison.isGap(sequence[j]))
1169 * Build a bitset corresponding to sequence gaps
1171 * @return a BitSet where set values correspond to gaps in the sequence
1174 public BitSet gapBitset()
1176 BitSet gaps = new BitSet(sequence.length);
1178 while (j < sequence.length)
1180 if (jalview.util.Comparison.isGap(sequence[j]))
1190 public int[] findPositionMap()
1192 int map[] = new int[sequence.length];
1195 int seqlen = sequence.length;
1196 while ((j < seqlen))
1199 if (!jalview.util.Comparison.isGap(sequence[j]))
1210 public List<int[]> getInsertions()
1212 ArrayList<int[]> map = new ArrayList<>();
1213 int lastj = -1, j = 0;
1215 int seqlen = sequence.length;
1216 while ((j < seqlen))
1218 if (jalview.util.Comparison.isGap(sequence[j]))
1229 map.add(new int[] { lastj, j - 1 });
1237 map.add(new int[] { lastj, j - 1 });
1244 public BitSet getInsertionsAsBits()
1246 BitSet map = new BitSet();
1247 int lastj = -1, j = 0;
1249 int seqlen = sequence.length;
1250 while ((j < seqlen))
1252 if (jalview.util.Comparison.isGap(sequence[j]))
1278 public void deleteChars(final int i, final int j)
1280 int newstart = start, newend = end;
1281 if (i >= sequence.length || i < 0)
1286 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1287 boolean createNewDs = false;
1288 // TODO: take a (second look) at the dataset creation validation method for
1289 // the very large sequence case
1291 int startIndex = findIndex(start) - 1;
1292 int endIndex = findIndex(end) - 1;
1293 int startDeleteColumn = -1; // for dataset sequence deletions
1294 int deleteCount = 0;
1296 for (int s = i; s < j && s < sequence.length; s++)
1298 if (Comparison.isGap(sequence[s]))
1303 if (startDeleteColumn == -1)
1305 startDeleteColumn = findPosition(s) - start;
1313 if (startIndex == s)
1316 * deleting characters from start of sequence; new start is the
1317 * sequence position of the next column (position to the right
1318 * if the column position is gapped)
1320 newstart = findPosition(j);
1328 * deleting characters at end of sequence; new end is the sequence
1329 * position of the column before the deletion; subtract 1 if this is
1330 * gapped since findPosition returns the next sequence position
1332 newend = findPosition(i - 1);
1333 if (Comparison.isGap(sequence[i - 1]))
1348 if (createNewDs && this.datasetSequence != null)
1351 * if deletion occured in the middle of the sequence,
1352 * construct a new dataset sequence and delete the residues
1353 * that were deleted from the aligned sequence
1355 Sequence ds = new Sequence(datasetSequence);
1356 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1357 datasetSequence = ds;
1358 // TODO: remove any non-inheritable properties ?
1359 // TODO: create a sequence mapping (since there is a relation here ?)
1368 public void insertCharAt(int i, int length, char c)
1370 char[] tmp = new char[sequence.length + length];
1372 if (i >= sequence.length)
1374 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1375 i = sequence.length;
1379 System.arraycopy(sequence, 0, tmp, 0, i);
1389 if (i < sequence.length)
1391 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1399 public void insertCharAt(int i, char c)
1401 insertCharAt(i, 1, c);
1405 public String getVamsasId()
1411 public void setVamsasId(String id)
1418 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1420 if (dbrefs == null && datasetSequence != null
1421 && this != datasetSequence)
1423 datasetSequence.setDBRefs(newDBrefs);
1431 public DBModList<DBRefEntry> getDBRefs()
1433 if (dbrefs == null && datasetSequence != null
1434 && this != datasetSequence)
1436 return datasetSequence.getDBRefs();
1442 public void addDBRef(DBRefEntry entry)
1444 if (datasetSequence != null)
1446 datasetSequence.addDBRef(entry);
1452 dbrefs = new DBModList<>();
1455 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1457 if (dbrefs.get(ib).updateFrom(entry))
1460 * found a dbref that either matched, or could be
1461 * updated from, the new entry - no need to add it
1469 // * extend the array to make room for one more
1471 // // TODO use an ArrayList instead
1472 // int j = dbrefs.length;
1473 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1474 // System.arraycopy(dbrefs, 0, temp, 0, j);
1475 // temp[temp.length - 1] = entry;
1483 public void setDatasetSequence(SequenceI seq)
1487 throw new IllegalArgumentException(
1488 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1490 if (seq != null && seq.getDatasetSequence() != null)
1492 throw new IllegalArgumentException(
1493 "Implementation error: cascading dataset sequences are not allowed.");
1495 datasetSequence = seq;
1499 public SequenceI getDatasetSequence()
1501 return datasetSequence;
1505 public AlignmentAnnotation[] getAnnotation()
1507 return annotation == null ? null
1509 .toArray(new AlignmentAnnotation[annotation.size()]);
1513 public boolean hasAnnotation(AlignmentAnnotation ann)
1515 return annotation == null ? false : annotation.contains(ann);
1519 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1521 if (this.annotation == null)
1523 this.annotation = new Vector<>();
1525 if (!this.annotation.contains(annotation))
1527 this.annotation.addElement(annotation);
1529 annotation.setSequenceRef(this);
1533 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1535 if (this.annotation != null)
1537 this.annotation.removeElement(annotation);
1538 if (this.annotation.size() == 0)
1540 this.annotation = null;
1546 * test if this is a valid candidate for another sequence's dataset sequence.
1549 private boolean isValidDatasetSequence()
1551 if (datasetSequence != null)
1555 for (int i = 0; i < sequence.length; i++)
1557 if (jalview.util.Comparison.isGap(sequence[i]))
1566 public SequenceI deriveSequence()
1568 Sequence seq = null;
1569 if (datasetSequence == null)
1571 if (isValidDatasetSequence())
1573 // Use this as dataset sequence
1574 seq = new Sequence(getName(), "", 1, -1);
1575 seq.setDatasetSequence(this);
1576 seq.initSeqFrom(this, getAnnotation());
1581 // Create a new, valid dataset sequence
1582 createDatasetSequence();
1585 return new Sequence(this);
1588 private boolean _isNa;
1590 private int _seqhash = 0;
1592 private List<DBRefEntry> primaryRefs;
1595 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1599 public boolean isProtein()
1601 if (datasetSequence != null)
1603 return datasetSequence.isProtein();
1605 if (_seqhash != sequence.hashCode())
1607 _seqhash = sequence.hashCode();
1608 _isNa = Comparison.isNucleotide(this);
1616 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1619 public SequenceI createDatasetSequence()
1621 if (datasetSequence == null)
1623 Sequence dsseq = new Sequence(getName(),
1624 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1625 getSequenceAsString()),
1626 getStart(), getEnd());
1628 datasetSequence = dsseq;
1630 dsseq.setDescription(description);
1631 // move features and database references onto dataset sequence
1632 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1633 sequenceFeatureStore = null;
1634 dsseq.dbrefs = dbrefs;
1636 // TODO: search and replace any references to this sequence with
1637 // references to the dataset sequence in Mappings on dbref
1638 dsseq.pdbIds = pdbIds;
1640 datasetSequence.updatePDBIds();
1641 if (annotation != null)
1643 // annotation is cloned rather than moved, to preserve what's currently
1645 for (AlignmentAnnotation aa : annotation)
1647 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1648 _aa.sequenceRef = datasetSequence;
1649 _aa.adjustForAlignment(); // uses annotation's own record of
1650 // sequence-column mapping
1651 datasetSequence.addAlignmentAnnotation(_aa);
1655 return datasetSequence;
1662 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1666 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1668 if (annotation != null)
1670 annotation.removeAllElements();
1672 if (annotations != null)
1674 for (int i = 0; i < annotations.length; i++)
1676 if (annotations[i] != null)
1678 addAlignmentAnnotation(annotations[i]);
1685 public AlignmentAnnotation[] getAnnotation(String label)
1687 if (annotation == null || annotation.size() == 0)
1692 Vector<AlignmentAnnotation> subset = new Vector<>();
1693 Enumeration<AlignmentAnnotation> e = annotation.elements();
1694 while (e.hasMoreElements())
1696 AlignmentAnnotation ann = e.nextElement();
1697 if (ann.label != null && ann.label.equals(label))
1699 subset.addElement(ann);
1702 if (subset.size() == 0)
1706 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1708 e = subset.elements();
1709 while (e.hasMoreElements())
1711 anns[i++] = e.nextElement();
1713 subset.removeAllElements();
1718 public boolean updatePDBIds()
1720 if (datasetSequence != null)
1722 // TODO: could merge DBRefs
1723 return datasetSequence.updatePDBIds();
1725 if (dbrefs == null || dbrefs.size() == 0)
1729 boolean added = false;
1730 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1732 DBRefEntry dbr = dbrefs.get(ib);
1733 if (DBRefSource.PDB.equals(dbr.getSource()))
1736 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1737 * PDB id is not already present in a 'matching' PDBEntry
1738 * Constructor parses out a chain code if appended to the accession id
1739 * (a fudge used to 'store' the chain code in the DBRef)
1741 PDBEntry pdbe = new PDBEntry(dbr);
1742 added |= addPDBId(pdbe);
1749 public void transferAnnotation(SequenceI entry, Mapping mp)
1751 if (datasetSequence != null)
1753 datasetSequence.transferAnnotation(entry, mp);
1756 if (entry.getDatasetSequence() != null)
1758 transferAnnotation(entry.getDatasetSequence(), mp);
1761 // transfer any new features from entry onto sequence
1762 if (entry.getSequenceFeatures() != null)
1765 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1766 for (SequenceFeature feature : sfs)
1768 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1769 : new SequenceFeature[]
1770 { new SequenceFeature(feature) };
1773 for (int sfi = 0; sfi < sf.length; sfi++)
1775 addSequenceFeature(sf[sfi]);
1781 // transfer PDB entries
1782 if (entry.getAllPDBEntries() != null)
1784 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1785 while (e.hasMoreElements())
1787 PDBEntry pdb = e.nextElement();
1791 // transfer database references
1792 List<DBRefEntry> entryRefs = entry.getDBRefs();
1793 if (entryRefs != null)
1795 for (int r = 0, n = entryRefs.size(); r < n; r++)
1797 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1798 if (newref.getMap() != null && mp != null)
1800 // remap ref using our local mapping
1802 // we also assume all version string setting is done by dbSourceProxy
1804 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1805 * newref.setSource(dbSource); }
1813 public void setRNA(RNA r)
1825 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1828 List<AlignmentAnnotation> result = new ArrayList<>();
1829 if (this.annotation != null)
1831 for (AlignmentAnnotation ann : annotation)
1833 String id = ann.getCalcId();
1834 if (id != null && id.equals(calcId)
1835 && ann.label != null && ann.label.equals(label))
1845 public String toString()
1847 return getDisplayId(false);
1851 public PDBEntry getPDBEntry(String pdbIdStr)
1853 if (getDatasetSequence() != null)
1855 return getDatasetSequence().getPDBEntry(pdbIdStr);
1861 List<PDBEntry> entries = getAllPDBEntries();
1862 for (PDBEntry entry : entries)
1864 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1872 private List<DBRefEntry> tmpList;
1875 public List<DBRefEntry> getPrimaryDBRefs()
1877 if (datasetSequence != null)
1879 return datasetSequence.getPrimaryDBRefs();
1881 if (dbrefs == null || dbrefs.size() == 0)
1883 return Collections.emptyList();
1885 synchronized (dbrefs)
1887 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1889 return primaryRefs; // no changes
1891 refModCount = dbrefs.getModCount();
1892 List<DBRefEntry> primaries = (primaryRefs == null
1893 ? (primaryRefs = new ArrayList<>())
1896 if (tmpList == null)
1898 tmpList = new ArrayList<>();
1899 tmpList.add(null); // for replacement
1901 for (int i = 0, n = dbrefs.size(); i < n; i++)
1903 DBRefEntry ref = dbrefs.get(i);
1904 if (!ref.isPrimaryCandidate())
1910 MapList mp = ref.getMap().getMap();
1911 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1913 // map only involves a subsequence, so cannot be primary
1917 // whilst it looks like it is a primary ref, we also sanity check type
1918 if (DBRefSource.PDB_CANONICAL_NAME
1919 .equals(ref.getCanonicalSourceName()))
1921 // PDB dbrefs imply there should be a PDBEntry associated
1922 // TODO: tighten PDB dbrefs
1923 // formally imply Jalview has actually downloaded and
1924 // parsed the pdb file. That means there should be a cached file
1925 // handle on the PDBEntry, and a real mapping between sequence and
1926 // extracted sequence from PDB file
1927 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1928 if (pdbentry == null || pdbentry.getFile() == null)
1935 // check standard protein or dna sources
1936 tmpList.set(0, ref);
1937 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1939 if (res == null || res.get(0) != tmpList.get(0))
1947 // version must be not null, as otherwise it will not be a candidate,
1949 DBRefUtils.ensurePrimaries(this, primaries);
1955 public HiddenMarkovModel getHMM()
1961 public void setHMM(HiddenMarkovModel hmm)
1967 public boolean hasHMMAnnotation()
1969 if (this.annotation == null) {
1972 for (AlignmentAnnotation ann : annotation)
1974 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1986 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1989 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1990 int endPos = fromColumn == toColumn ? startPos
1991 : findPosition(toColumn - 1);
1993 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1997 * if end column is gapped, endPos may be to the right,
1998 * and we may have included adjacent or enclosing features;
1999 * remove any that are not enclosing, non-contact features
2001 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
2002 && Comparison.isGap(sequence[toColumn - 1]);
2003 if (endPos > this.end || endColumnIsGapped)
2005 ListIterator<SequenceFeature> it = result.listIterator();
2006 while (it.hasNext())
2008 SequenceFeature sf = it.next();
2009 int sfBegin = sf.getBegin();
2010 int sfEnd = sf.getEnd();
2011 int featureStartColumn = findIndex(sfBegin);
2012 if (featureStartColumn > toColumn)
2016 else if (featureStartColumn < fromColumn)
2018 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2020 if (featureEndColumn < fromColumn)
2024 else if (featureEndColumn > toColumn && sf.isContactFeature())
2027 * remove an enclosing feature if it is a contact feature
2039 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2040 * token that has to match the one presented by the cursor
2043 public void sequenceChanged()
2052 public int replace(char c1, char c2)
2059 synchronized (sequence)
2061 for (int c = 0; c < sequence.length; c++)
2063 if (sequence[c] == c1)
2079 public String getSequenceStringFromIterator(Iterator<int[]> it)
2081 StringBuilder newSequence = new StringBuilder();
2082 while (it.hasNext())
2084 int[] block = it.next();
2087 newSequence.append(getSequence(block[0], block[1] + 1));
2091 newSequence.append(getSequence(block[0], block[1]));
2095 return newSequence.toString();
2099 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2103 if (!regions.hasNext())
2105 return findIndex(getStart()) - 1;
2108 // Simply walk along the sequence whilst watching for region
2110 int hideStart = getLength();
2112 boolean foundStart = false;
2114 // step through the non-gapped positions of the sequence
2115 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2117 // get alignment position of this residue in the sequence
2118 int p = findIndex(i) - 1;
2120 // update region start/end
2121 while (hideEnd < p && regions.hasNext())
2123 int[] region = regions.next();
2124 hideStart = region[0];
2125 hideEnd = region[1];
2129 hideStart = getLength();
2131 // update boundary for sequence
2143 // otherwise, sequence was completely hidden
2148 public boolean hasHMMProfile()