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;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.BitSet;
34 import java.util.Collections;
35 import java.util.Enumeration;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.ListIterator;
39 import java.util.Vector;
41 import fr.orsay.lri.varna.models.rna.RNA;
45 * Implements the SequenceI interface for a char[] based sequence object
47 public class Sequence extends ASequence implements SequenceI
51 * A subclass that gives us access to modCount, which tracks whether there
52 * have been any changes. We use this to update
58 @SuppressWarnings("serial")
59 public class DBModList<T> extends ArrayList<DBRefEntry>
62 protected int getModCount()
69 SequenceI datasetSequence;
73 private char[] sequence;
75 private String description;
81 private Vector<PDBEntry> pdbIds;
83 private String vamsasId;
85 private DBModList<DBRefEntry> dbrefs; // controlled access
88 * a flag to let us know that elements have changed in dbrefs
92 private int refModCount = 0;
97 * This annotation is displayed below the alignment but the positions are tied
98 * to the residues of this sequence
100 * TODO: change to List<>
102 private Vector<AlignmentAnnotation> annotation;
104 private SequenceFeaturesI sequenceFeatureStore;
107 * A cursor holding the approximate current view position to the sequence,
108 * as determined by findIndex or findPosition or findPositions.
109 * Using a cursor as a hint allows these methods to be more performant for
112 private SequenceCursor cursor;
115 * A number that should be incremented whenever the sequence is edited.
116 * If the value matches the cursor token, then we can trust the cursor,
117 * if not then it should be recomputed.
119 private int changeCount;
122 * Creates a new Sequence object.
125 * display name string
127 * string to form a possibly gapped sequence out of
129 * first position of non-gap residue in the sequence
131 * last position of ungapped residues (nearly always only used for
134 public Sequence(String name, String sequence, int start, int end)
137 initSeqAndName(name, sequence.toCharArray(), start, end);
140 public Sequence(String name, char[] sequence, int start, int end)
143 initSeqAndName(name, sequence, start, end);
147 * Stage 1 constructor - assign name, sequence, and set start and end fields.
148 * start and end are updated values from name2 if it ends with /start-end
155 protected void initSeqAndName(String name2, char[] sequence2, int start2,
159 this.sequence = sequence2;
167 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
168 * start and end respectively and removes the suffix from the name
175 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
178 int slashPos = name.lastIndexOf('/');
179 if (slashPos > -1 && slashPos < name.length() - 1)
181 String suffix = name.substring(slashPos + 1);
182 String[] range = suffix.split("-");
183 if (range.length == 2)
187 int from = Integer.valueOf(range[0]);
188 int to = Integer.valueOf(range[1]);
189 if (from > 0 && to >= from)
191 name = name.substring(0, slashPos);
196 } catch (NumberFormatException e)
198 // leave name unchanged if suffix is invalid
205 * Ensures that 'end' is not before the end of the sequence, that is,
206 * (end-start+1) is at least as long as the count of ungapped positions. Note
207 * that end is permitted to be beyond the end of the sequence data.
209 void checkValidRange()
212 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
215 for (int j = 0; j < sequence.length; j++)
217 if (!Comparison.isGap(sequence[j]))
236 * default constructor
240 sequenceFeatureStore = new SequenceFeatures();
244 * Creates a new Sequence object.
251 public Sequence(String name, String sequence)
253 this(name, sequence, 1, -1);
257 * Creates a new Sequence object with new AlignmentAnnotations but inherits
258 * any existing dataset sequence reference. If non exists, everything is
262 * if seq is a dataset sequence, behaves like a plain old copy
265 public Sequence(SequenceI seq)
267 this(seq, seq.getAnnotation());
271 * Create a new sequence object with new features, DBRefEntries, and PDBIds
272 * but inherits any existing dataset sequence reference, and duplicate of any
273 * annotation that is present in the given annotation array.
276 * the sequence to be copied
277 * @param alAnnotation
278 * an array of annotation including some associated with seq
280 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
283 initSeqFrom(seq, alAnnotation);
287 * does the heavy lifting when cloning a dataset sequence, or coping data from
288 * dataset to a new derived sequence.
291 * - source of attributes.
292 * @param alAnnotation
293 * - alignment annotation present on seq that should be copied onto
296 protected void initSeqFrom(SequenceI seq,
297 AlignmentAnnotation[] alAnnotation)
299 char[] oseq = seq.getSequence(); // returns a copy of the array
300 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
302 description = seq.getDescription();
303 if (seq != datasetSequence)
305 setDatasetSequence(seq.getDatasetSequence());
309 * only copy DBRefs and seqfeatures if we really are a dataset sequence
311 if (datasetSequence == null)
313 List<DBRefEntry> dbr = seq.getDBRefs();
316 for (int i = 0, n = dbr.size(); i < n; i++)
318 addDBRef(new DBRefEntry(dbr.get(i)));
323 * make copies of any sequence features
325 for (SequenceFeature sf : seq.getSequenceFeatures())
327 addSequenceFeature(new SequenceFeature(sf));
331 if (seq.getAnnotation() != null)
333 AlignmentAnnotation[] sqann = seq.getAnnotation();
334 for (int i = 0; i < sqann.length; i++)
336 if (sqann[i] == null)
340 boolean found = (alAnnotation == null);
343 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
345 found = (alAnnotation[apos] == sqann[i]);
350 // only copy the given annotation
351 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
352 addAlignmentAnnotation(newann);
356 if (seq.getAllPDBEntries() != null)
358 Vector<PDBEntry> ids = seq.getAllPDBEntries();
359 for (PDBEntry pdb : ids)
361 this.addPDBId(new PDBEntry(pdb));
367 public void setSequenceFeatures(List<SequenceFeature> features)
369 if (datasetSequence != null)
371 datasetSequence.setSequenceFeatures(features);
374 sequenceFeatureStore = new SequenceFeatures(features);
378 public synchronized boolean addSequenceFeature(SequenceFeature sf)
380 if (sf.getType() == null)
383 "SequenceFeature type may not be null: " + sf.toString());
387 if (datasetSequence != null)
389 return datasetSequence.addSequenceFeature(sf);
392 return sequenceFeatureStore.add(sf);
396 public void deleteFeature(SequenceFeature sf)
398 if (datasetSequence != null)
400 datasetSequence.deleteFeature(sf);
404 sequenceFeatureStore.delete(sf);
414 public List<SequenceFeature> getSequenceFeatures()
416 if (datasetSequence != null)
418 return datasetSequence.getSequenceFeatures();
420 return sequenceFeatureStore.getAllFeatures();
424 public SequenceFeaturesI getFeatures()
426 return datasetSequence != null ? datasetSequence.getFeatures()
427 : sequenceFeatureStore;
431 public boolean addPDBId(PDBEntry entry)
435 pdbIds = new Vector<>();
440 for (PDBEntry pdbe : pdbIds)
442 if (pdbe.updateFrom(entry))
447 pdbIds.addElement(entry);
458 public void setPDBId(Vector<PDBEntry> id)
466 * @return DOCUMENT ME!
469 public Vector<PDBEntry> getAllPDBEntries()
471 return pdbIds == null ? new Vector<>() : pdbIds;
475 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
480 public String getDisplayId(boolean jvsuffix)
486 StringBuilder result = new StringBuilder(name);
487 result.append("/").append(start).append("-").append(end);
489 return result.toString();
493 * Sets the sequence name. If the name ends in /start-end, then the start-end
494 * values are parsed out and set, and the suffix is removed from the name.
499 public void setName(String theName)
508 * @return DOCUMENT ME!
511 public String getName()
523 public void setStart(int start)
532 * @return DOCUMENT ME!
535 public int getStart()
547 public void setEnd(int end)
555 * @return DOCUMENT ME!
566 * @return DOCUMENT ME!
569 public int getLength()
571 return this.sequence.length;
581 public void setSequence(String seq)
583 this.sequence = seq.toCharArray();
589 public String getSequenceAsString()
591 return new String(sequence);
595 public String getSequenceAsString(int start, int end)
597 return new String(getSequence(start, end));
601 public char[] getSequence()
604 return sequence == null ? null
605 : Arrays.copyOf(sequence, sequence.length);
611 * @see jalview.datamodel.SequenceI#getSequence(int, int)
614 public char[] getSequence(int start, int end)
620 // JBPNote - left to user to pad the result here (TODO:Decide on this
622 if (start >= sequence.length)
627 if (end >= sequence.length)
629 end = sequence.length;
632 char[] reply = new char[end - start];
633 System.arraycopy(sequence, start, reply, 0, end - start);
639 public SequenceI getSubSequence(int start, int end)
645 char[] seq = getSequence(start, end);
650 int nstart = findPosition(start);
651 int nend = findPosition(end) - 1;
652 // JBPNote - this is an incomplete copy.
653 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
654 nseq.setDescription(description);
655 if (datasetSequence != null)
657 nseq.setDatasetSequence(datasetSequence);
661 nseq.setDatasetSequence(this);
667 * Returns the character of the aligned sequence at the given position (base
668 * zero), or space if the position is not within the sequence's bounds
673 public char getCharAt(int i)
675 if (i >= 0 && i < sequence.length)
686 * Sets the sequence description, and also parses out any special formats of
692 public void setDescription(String desc)
694 this.description = desc;
698 public void setGeneLoci(String speciesId, String assemblyId,
699 String chromosomeId, MapList map)
701 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
706 * Returns the gene loci mapping for the sequence (may be null)
711 public GeneLociI getGeneLoci()
713 List<DBRefEntry> refs = getDBRefs();
716 for (final DBRefEntry ref : refs)
718 if (ref instanceof GeneLociI)
720 return (GeneLociI) ref;
728 * Answers the description
733 public String getDescription()
735 return this.description;
742 public int findIndex(int pos)
745 * use a valid, hopefully nearby, cursor if available
747 if (isValidCursor(cursor))
749 return findIndex(pos, cursor);
757 * traverse sequence from the start counting gaps; make a note of
758 * the column of the first residue to save in the cursor
760 while ((i < sequence.length) && (j <= end) && (j <= pos))
762 if (!Comparison.isGap(sequence[i]))
773 if (j == end && j < pos)
778 updateCursor(pos, i, startColumn);
783 * Updates the cursor to the latest found residue and column position
790 * column position of the first sequence residue
792 protected void updateCursor(int residuePos, int column, int startColumn)
795 * preserve end residue column provided cursor was valid
797 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
799 if (residuePos == this.end)
804 cursor = new SequenceCursor(this, residuePos, column, startColumn,
805 endColumn, this.changeCount);
809 * Answers the aligned column position (1..) for the given residue position
810 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
811 * The hint may be left of, at, or to the right of the required position.
817 protected int findIndex(final int pos, SequenceCursor curs)
819 if (!isValidCursor(curs))
822 * wrong or invalidated cursor, compute de novo
824 return findIndex(pos);
827 if (curs.residuePosition == pos)
829 return curs.columnPosition;
833 * move left or right to find pos from hint.position
835 int col = curs.columnPosition - 1; // convert from base 1 to base 0
836 int newPos = curs.residuePosition;
837 int delta = newPos > pos ? -1 : 1;
839 while (newPos != pos)
841 col += delta; // shift one column left or right
846 if (col == sequence.length)
848 col--; // return last column if we failed to reach pos
851 if (!Comparison.isGap(sequence[col]))
857 col++; // convert back to base 1
860 * only update cursor if we found the target position
864 updateCursor(pos, col, curs.firstColumnPosition);
874 public int findPosition(final int column)
877 * use a valid, hopefully nearby, cursor if available
879 if (isValidCursor(cursor))
881 return findPosition(column + 1, cursor);
884 // TODO recode this more naturally i.e. count residues only
885 // as they are found, not 'in anticipation'
888 * traverse the sequence counting gaps; note the column position
889 * of the first residue, to save in the cursor
891 int firstResidueColumn = 0;
892 int lastPosFound = 0;
893 int lastPosFoundColumn = 0;
894 int seqlen = sequence.length;
896 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
898 lastPosFound = start;
899 lastPosFoundColumn = 0;
905 while (j < column && j < seqlen)
907 if (!Comparison.isGap(sequence[j]))
910 lastPosFoundColumn = j;
911 if (pos == this.start)
913 firstResidueColumn = j;
919 if (j < seqlen && !Comparison.isGap(sequence[j]))
922 lastPosFoundColumn = j;
923 if (pos == this.start)
925 firstResidueColumn = j;
930 * update the cursor to the last residue position found (if any)
931 * (converting column position to base 1)
933 if (lastPosFound != 0)
935 updateCursor(lastPosFound, lastPosFoundColumn + 1,
936 firstResidueColumn + 1);
943 * Answers true if the given cursor is not null, is for this sequence object,
944 * and has a token value that matches this object's changeCount, else false.
945 * This allows us to ignore a cursor as 'stale' if the sequence has been
946 * modified since the cursor was created.
951 protected boolean isValidCursor(SequenceCursor curs)
953 if (curs == null || curs.sequence != this || curs.token != changeCount)
958 * sanity check against range
960 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
964 if (curs.residuePosition < start || curs.residuePosition > end)
972 * Answers the sequence position (start..) for the given aligned column
973 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
974 * may lie left of, at, or to the right of the column position.
980 protected int findPosition(final int col, SequenceCursor curs)
982 if (!isValidCursor(curs))
985 * wrong or invalidated cursor, compute de novo
987 return findPosition(col - 1);// ugh back to base 0
990 if (curs.columnPosition == col)
992 cursor = curs; // in case this method becomes public
993 return curs.residuePosition; // easy case :-)
996 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
999 * sequence lies entirely to the left of col
1000 * - return last residue + 1
1005 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1008 * sequence lies entirely to the right of col
1009 * - return first residue
1014 // todo could choose closest to col out of column,
1015 // firstColumnPosition, lastColumnPosition as a start point
1018 * move left or right to find pos from cursor position
1020 int firstResidueColumn = curs.firstColumnPosition;
1021 int column = curs.columnPosition - 1; // to base 0
1022 int newPos = curs.residuePosition;
1023 int delta = curs.columnPosition > col ? -1 : 1;
1024 boolean gapped = false;
1025 int lastFoundPosition = curs.residuePosition;
1026 int lastFoundPositionColumn = curs.columnPosition;
1028 while (column != col - 1)
1030 column += delta; // shift one column left or right
1031 if (column < 0 || column == sequence.length)
1035 gapped = Comparison.isGap(sequence[column]);
1039 lastFoundPosition = newPos;
1040 lastFoundPositionColumn = column + 1;
1041 if (lastFoundPosition == this.start)
1043 firstResidueColumn = column + 1;
1048 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1050 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1051 firstResidueColumn);
1055 * hack to give position to the right if on a gap
1056 * or beyond the length of the sequence (see JAL-2562)
1058 if (delta > 0 && (gapped || column >= sequence.length))
1070 public ContiguousI findPositions(int fromColumn, int toColumn)
1072 if (toColumn < fromColumn || fromColumn < 1)
1078 * find the first non-gapped position, if any
1080 int firstPosition = 0;
1081 int col = fromColumn - 1;
1082 int length = sequence.length;
1083 while (col < length && col < toColumn)
1085 if (!Comparison.isGap(sequence[col]))
1087 firstPosition = findPosition(col++);
1093 if (firstPosition == 0)
1099 * find the last non-gapped position
1101 int lastPosition = firstPosition;
1102 while (col < length && col < toColumn)
1104 if (!Comparison.isGap(sequence[col++]))
1110 return new Range(firstPosition, lastPosition);
1114 * Returns an int array where indices correspond to each residue in the
1115 * sequence and the element value gives its position in the alignment
1117 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1118 * residues in SequenceI object
1121 public int[] gapMap()
1123 String seq = jalview.analysis.AlignSeq.extractGaps(
1124 jalview.util.Comparison.GapChars, new String(sequence));
1125 int[] map = new int[seq.length()];
1129 while (j < sequence.length)
1131 if (!jalview.util.Comparison.isGap(sequence[j]))
1143 * Build a bitset corresponding to sequence gaps
1145 * @return a BitSet where set values correspond to gaps in the sequence
1148 public BitSet gapBitset()
1150 BitSet gaps = new BitSet(sequence.length);
1152 while (j < sequence.length)
1154 if (jalview.util.Comparison.isGap(sequence[j]))
1164 public int[] findPositionMap()
1166 int map[] = new int[sequence.length];
1169 int seqlen = sequence.length;
1170 while ((j < seqlen))
1173 if (!jalview.util.Comparison.isGap(sequence[j]))
1184 public List<int[]> getInsertions()
1186 ArrayList<int[]> map = new ArrayList<>();
1187 int lastj = -1, j = 0;
1189 int seqlen = sequence.length;
1190 while ((j < seqlen))
1192 if (jalview.util.Comparison.isGap(sequence[j]))
1203 map.add(new int[] { lastj, j - 1 });
1211 map.add(new int[] { lastj, j - 1 });
1218 public BitSet getInsertionsAsBits()
1220 BitSet map = new BitSet();
1221 int lastj = -1, j = 0;
1223 int seqlen = sequence.length;
1224 while ((j < seqlen))
1226 if (jalview.util.Comparison.isGap(sequence[j]))
1252 public void deleteChars(final int i, final int j)
1254 int newstart = start, newend = end;
1255 if (i >= sequence.length || i < 0)
1260 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1261 boolean createNewDs = false;
1262 // TODO: take a (second look) at the dataset creation validation method for
1263 // the very large sequence case
1265 int startIndex = findIndex(start) - 1;
1266 int endIndex = findIndex(end) - 1;
1267 int startDeleteColumn = -1; // for dataset sequence deletions
1268 int deleteCount = 0;
1270 for (int s = i; s < j && s < sequence.length; s++)
1272 if (Comparison.isGap(sequence[s]))
1277 if (startDeleteColumn == -1)
1279 startDeleteColumn = findPosition(s) - start;
1287 if (startIndex == s)
1290 * deleting characters from start of sequence; new start is the
1291 * sequence position of the next column (position to the right
1292 * if the column position is gapped)
1294 newstart = findPosition(j);
1302 * deleting characters at end of sequence; new end is the sequence
1303 * position of the column before the deletion; subtract 1 if this is
1304 * gapped since findPosition returns the next sequence position
1306 newend = findPosition(i - 1);
1307 if (Comparison.isGap(sequence[i - 1]))
1322 if (createNewDs && this.datasetSequence != null)
1325 * if deletion occured in the middle of the sequence,
1326 * construct a new dataset sequence and delete the residues
1327 * that were deleted from the aligned sequence
1329 Sequence ds = new Sequence(datasetSequence);
1330 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1331 datasetSequence = ds;
1332 // TODO: remove any non-inheritable properties ?
1333 // TODO: create a sequence mapping (since there is a relation here ?)
1342 public void insertCharAt(int i, int length, char c)
1344 char[] tmp = new char[sequence.length + length];
1346 if (i >= sequence.length)
1348 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1349 i = sequence.length;
1353 System.arraycopy(sequence, 0, tmp, 0, i);
1363 if (i < sequence.length)
1365 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1373 public void insertCharAt(int i, char c)
1375 insertCharAt(i, 1, c);
1379 public String getVamsasId()
1385 public void setVamsasId(String id)
1392 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1394 if (dbrefs == null && datasetSequence != null
1395 && this != datasetSequence)
1397 datasetSequence.setDBRefs(newDBrefs);
1405 public DBModList<DBRefEntry> getDBRefs()
1407 if (dbrefs == null && datasetSequence != null
1408 && this != datasetSequence)
1410 return datasetSequence.getDBRefs();
1416 public void addDBRef(DBRefEntry entry)
1418 if (datasetSequence != null)
1420 datasetSequence.addDBRef(entry);
1426 dbrefs = new DBModList<>();
1429 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1431 if (dbrefs.get(ib).updateFrom(entry))
1434 * found a dbref that either matched, or could be
1435 * updated from, the new entry - no need to add it
1443 // * extend the array to make room for one more
1445 // // TODO use an ArrayList instead
1446 // int j = dbrefs.length;
1447 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1448 // System.arraycopy(dbrefs, 0, temp, 0, j);
1449 // temp[temp.length - 1] = entry;
1457 public void setDatasetSequence(SequenceI seq)
1461 throw new IllegalArgumentException(
1462 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1464 if (seq != null && seq.getDatasetSequence() != null)
1466 throw new IllegalArgumentException(
1467 "Implementation error: cascading dataset sequences are not allowed.");
1469 datasetSequence = seq;
1473 public SequenceI getDatasetSequence()
1475 return datasetSequence;
1479 public AlignmentAnnotation[] getAnnotation()
1481 return annotation == null ? null
1483 .toArray(new AlignmentAnnotation[annotation.size()]);
1487 public boolean hasAnnotation(AlignmentAnnotation ann)
1489 return annotation == null ? false : annotation.contains(ann);
1493 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1495 if (this.annotation == null)
1497 this.annotation = new Vector<>();
1499 if (!this.annotation.contains(annotation))
1501 this.annotation.addElement(annotation);
1503 annotation.setSequenceRef(this);
1507 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1509 if (this.annotation != null)
1511 this.annotation.removeElement(annotation);
1512 if (this.annotation.size() == 0)
1514 this.annotation = null;
1520 * test if this is a valid candidate for another sequence's dataset sequence.
1523 private boolean isValidDatasetSequence()
1525 if (datasetSequence != null)
1529 for (int i = 0; i < sequence.length; i++)
1531 if (jalview.util.Comparison.isGap(sequence[i]))
1540 public SequenceI deriveSequence()
1542 Sequence seq = null;
1543 if (datasetSequence == null)
1545 if (isValidDatasetSequence())
1547 // Use this as dataset sequence
1548 seq = new Sequence(getName(), "", 1, -1);
1549 seq.setDatasetSequence(this);
1550 seq.initSeqFrom(this, getAnnotation());
1555 // Create a new, valid dataset sequence
1556 createDatasetSequence();
1559 return new Sequence(this);
1562 private boolean _isNa;
1564 private int _seqhash = 0;
1566 private List<DBRefEntry> primaryRefs;
1569 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1573 public boolean isProtein()
1575 if (datasetSequence != null)
1577 return datasetSequence.isProtein();
1579 if (_seqhash != sequence.hashCode())
1581 _seqhash = sequence.hashCode();
1582 _isNa = Comparison.isNucleotide(this);
1590 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1593 public SequenceI createDatasetSequence()
1595 if (datasetSequence == null)
1597 Sequence dsseq = new Sequence(getName(),
1598 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1599 getSequenceAsString()),
1600 getStart(), getEnd());
1602 datasetSequence = dsseq;
1604 dsseq.setDescription(description);
1605 // move features and database references onto dataset sequence
1606 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1607 sequenceFeatureStore = null;
1608 dsseq.dbrefs = dbrefs;
1610 // TODO: search and replace any references to this sequence with
1611 // references to the dataset sequence in Mappings on dbref
1612 dsseq.pdbIds = pdbIds;
1614 datasetSequence.updatePDBIds();
1615 if (annotation != null)
1617 // annotation is cloned rather than moved, to preserve what's currently
1619 for (AlignmentAnnotation aa : annotation)
1621 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1622 _aa.sequenceRef = datasetSequence;
1623 _aa.adjustForAlignment(); // uses annotation's own record of
1624 // sequence-column mapping
1625 datasetSequence.addAlignmentAnnotation(_aa);
1629 return datasetSequence;
1636 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1640 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1642 if (annotation != null)
1644 annotation.removeAllElements();
1646 if (annotations != null)
1648 for (int i = 0; i < annotations.length; i++)
1650 if (annotations[i] != null)
1652 addAlignmentAnnotation(annotations[i]);
1659 public AlignmentAnnotation[] getAnnotation(String label)
1661 if (annotation == null || annotation.size() == 0)
1666 Vector<AlignmentAnnotation> subset = new Vector<>();
1667 Enumeration<AlignmentAnnotation> e = annotation.elements();
1668 while (e.hasMoreElements())
1670 AlignmentAnnotation ann = e.nextElement();
1671 if (ann.label != null && ann.label.equals(label))
1673 subset.addElement(ann);
1676 if (subset.size() == 0)
1680 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1682 e = subset.elements();
1683 while (e.hasMoreElements())
1685 anns[i++] = e.nextElement();
1687 subset.removeAllElements();
1692 public boolean updatePDBIds()
1694 if (datasetSequence != null)
1696 // TODO: could merge DBRefs
1697 return datasetSequence.updatePDBIds();
1699 if (dbrefs == null || dbrefs.size() == 0)
1703 boolean added = false;
1704 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1706 DBRefEntry dbr = dbrefs.get(ib);
1707 if (DBRefSource.PDB.equals(dbr.getSource()))
1710 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1711 * PDB id is not already present in a 'matching' PDBEntry
1712 * Constructor parses out a chain code if appended to the accession id
1713 * (a fudge used to 'store' the chain code in the DBRef)
1715 PDBEntry pdbe = new PDBEntry(dbr);
1716 added |= addPDBId(pdbe);
1723 public void transferAnnotation(SequenceI entry, Mapping mp)
1725 if (datasetSequence != null)
1727 datasetSequence.transferAnnotation(entry, mp);
1730 if (entry.getDatasetSequence() != null)
1732 transferAnnotation(entry.getDatasetSequence(), mp);
1735 // transfer any new features from entry onto sequence
1736 if (entry.getSequenceFeatures() != null)
1739 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1740 for (SequenceFeature feature : sfs)
1742 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1743 : new SequenceFeature[]
1744 { new SequenceFeature(feature) };
1747 for (int sfi = 0; sfi < sf.length; sfi++)
1749 addSequenceFeature(sf[sfi]);
1755 // transfer PDB entries
1756 if (entry.getAllPDBEntries() != null)
1758 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1759 while (e.hasMoreElements())
1761 PDBEntry pdb = e.nextElement();
1765 // transfer database references
1766 List<DBRefEntry> entryRefs = entry.getDBRefs();
1767 if (entryRefs != null)
1769 for (int r = 0, n = entryRefs.size(); r < n; r++)
1771 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1772 if (newref.getMap() != null && mp != null)
1774 // remap ref using our local mapping
1776 // we also assume all version string setting is done by dbSourceProxy
1778 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1779 * newref.setSource(dbSource); }
1787 public void setRNA(RNA r)
1799 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1802 return getAlignmentAnnotations(calcId, label, null, true);
1806 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1807 String label, String description)
1809 return getAlignmentAnnotations(calcId, label, description, false);
1812 private List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1813 String label, String description, boolean ignoreDescription)
1815 List<AlignmentAnnotation> result = new ArrayList<>();
1816 if (this.annotation != null)
1818 for (AlignmentAnnotation ann : annotation)
1820 if ((ann.calcId != null && ann.calcId.equals(calcId))
1821 && (ann.label != null && ann.label.equals(label))
1822 && ((ignoreDescription && description == null)
1823 || (ann.description != null
1824 && ann.description.equals(description))))
1835 public String toString()
1837 return getDisplayId(false);
1841 public PDBEntry getPDBEntry(String pdbIdStr)
1843 if (getDatasetSequence() != null)
1845 return getDatasetSequence().getPDBEntry(pdbIdStr);
1851 List<PDBEntry> entries = getAllPDBEntries();
1852 for (PDBEntry entry : entries)
1854 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1862 private List<DBRefEntry> tmpList;
1865 public List<DBRefEntry> getPrimaryDBRefs()
1867 if (datasetSequence != null)
1869 return datasetSequence.getPrimaryDBRefs();
1871 if (dbrefs == null || dbrefs.size() == 0)
1873 return Collections.emptyList();
1875 synchronized (dbrefs)
1877 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1879 return primaryRefs; // no changes
1881 refModCount = dbrefs.getModCount();
1882 List<DBRefEntry> primaries = (primaryRefs == null
1883 ? (primaryRefs = new ArrayList<>())
1886 if (tmpList == null)
1888 tmpList = new ArrayList<>();
1889 tmpList.add(null); // for replacement
1891 for (int i = 0, n = dbrefs.size(); i < n; i++)
1893 DBRefEntry ref = dbrefs.get(i);
1894 if (!ref.isPrimaryCandidate())
1900 MapList mp = ref.getMap().getMap();
1901 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1903 // map only involves a subsequence, so cannot be primary
1907 // whilst it looks like it is a primary ref, we also sanity check type
1908 if (DBRefSource.PDB_CANONICAL_NAME
1909 .equals(ref.getCanonicalSourceName()))
1911 // PDB dbrefs imply there should be a PDBEntry associated
1912 // TODO: tighten PDB dbrefs
1913 // formally imply Jalview has actually downloaded and
1914 // parsed the pdb file. That means there should be a cached file
1915 // handle on the PDBEntry, and a real mapping between sequence and
1916 // extracted sequence from PDB file
1917 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1918 if (pdbentry == null || pdbentry.getFile() == null)
1925 // check standard protein or dna sources
1926 tmpList.set(0, ref);
1927 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1929 if (res == null || res.get(0) != tmpList.get(0))
1937 // version must be not null, as otherwise it will not be a candidate,
1939 DBRefUtils.ensurePrimaries(this, primaries);
1948 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1951 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1952 int endPos = fromColumn == toColumn ? startPos
1953 : findPosition(toColumn - 1);
1955 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1959 * if end column is gapped, endPos may be to the right,
1960 * and we may have included adjacent or enclosing features;
1961 * remove any that are not enclosing, non-contact features
1963 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1964 && Comparison.isGap(sequence[toColumn - 1]);
1965 if (endPos > this.end || endColumnIsGapped)
1967 ListIterator<SequenceFeature> it = result.listIterator();
1968 while (it.hasNext())
1970 SequenceFeature sf = it.next();
1971 int sfBegin = sf.getBegin();
1972 int sfEnd = sf.getEnd();
1973 int featureStartColumn = findIndex(sfBegin);
1974 if (featureStartColumn > toColumn)
1978 else if (featureStartColumn < fromColumn)
1980 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1982 if (featureEndColumn < fromColumn)
1986 else if (featureEndColumn > toColumn && sf.isContactFeature())
1989 * remove an enclosing feature if it is a contact feature
2001 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2002 * token that has to match the one presented by the cursor
2005 public void sequenceChanged()
2014 public int replace(char c1, char c2)
2021 synchronized (sequence)
2023 for (int c = 0; c < sequence.length; c++)
2025 if (sequence[c] == c1)
2041 public String getSequenceStringFromIterator(Iterator<int[]> it)
2043 StringBuilder newSequence = new StringBuilder();
2044 while (it.hasNext())
2046 int[] block = it.next();
2049 newSequence.append(getSequence(block[0], block[1] + 1));
2053 newSequence.append(getSequence(block[0], block[1]));
2057 return newSequence.toString();
2061 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2065 if (!regions.hasNext())
2067 return findIndex(getStart()) - 1;
2070 // Simply walk along the sequence whilst watching for region
2072 int hideStart = getLength();
2074 boolean foundStart = false;
2076 // step through the non-gapped positions of the sequence
2077 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2079 // get alignment position of this residue in the sequence
2080 int p = findIndex(i) - 1;
2082 // update region start/end
2083 while (hideEnd < p && regions.hasNext())
2085 int[] region = regions.next();
2086 hideStart = region[0];
2087 hideEnd = region[1];
2091 hideStart = getLength();
2093 // update boundary for sequence
2105 // otherwise, sequence was completely hidden