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.api.DBRefEntryI;
25 import jalview.datamodel.features.SequenceFeatures;
26 import jalview.datamodel.features.SequenceFeaturesI;
27 import jalview.util.Comparison;
28 import jalview.util.DBRefUtils;
29 import jalview.util.MapList;
30 import jalview.util.StringUtils;
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
50 SequenceI datasetSequence;
54 private char[] sequence;
62 Vector<PDBEntry> pdbIds;
71 * This annotation is displayed below the alignment but the positions are tied
72 * to the residues of this sequence
74 * TODO: change to List<>
76 Vector<AlignmentAnnotation> annotation;
78 private SequenceFeaturesI sequenceFeatureStore;
81 * A cursor holding the approximate current view position to the sequence,
82 * as determined by findIndex or findPosition or findPositions.
83 * Using a cursor as a hint allows these methods to be more performant for
86 private SequenceCursor cursor;
89 * A number that should be incremented whenever the sequence is edited.
90 * If the value matches the cursor token, then we can trust the cursor,
91 * if not then it should be recomputed.
93 private int changeCount;
96 * Creates a new Sequence object.
101 * string to form a possibly gapped sequence out of
103 * first position of non-gap residue in the sequence
105 * last position of ungapped residues (nearly always only used for
108 public Sequence(String name, String sequence, int start, int end)
111 initSeqAndName(name, sequence.toCharArray(), start, end);
114 public Sequence(String name, char[] sequence, int start, int end)
117 initSeqAndName(name, sequence, start, end);
121 * Stage 1 constructor - assign name, sequence, and set start and end fields.
122 * start and end are updated values from name2 if it ends with /start-end
129 protected void initSeqAndName(String name2, char[] sequence2, int start2,
133 this.sequence = sequence2;
141 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
142 * start and end respectively and removes the suffix from the name
149 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
152 int slashPos = name.lastIndexOf('/');
153 if (slashPos > -1 && slashPos < name.length() - 1)
155 String suffix = name.substring(slashPos + 1);
156 String[] range = suffix.split("-");
157 if (range.length == 2)
161 int from = Integer.valueOf(range[0]);
162 int to = Integer.valueOf(range[1]);
163 if (from > 0 && to >= from)
165 name = name.substring(0, slashPos);
170 } catch (NumberFormatException e)
172 // leave name unchanged if suffix is invalid
179 * Ensures that 'end' is not before the end of the sequence, that is,
180 * (end-start+1) is at least as long as the count of ungapped positions. Note
181 * that end is permitted to be beyond the end of the sequence data.
183 void checkValidRange()
186 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
189 for (int j = 0; j < sequence.length; j++)
191 if (!Comparison.isGap(sequence[j]))
210 * default constructor
214 sequenceFeatureStore = new SequenceFeatures();
218 * Creates a new Sequence object.
225 public Sequence(String name, String sequence)
227 this(name, sequence, 1, -1);
231 * Creates a new Sequence object with new AlignmentAnnotations but inherits
232 * any existing dataset sequence reference. If non exists, everything is
236 * if seq is a dataset sequence, behaves like a plain old copy
239 public Sequence(SequenceI seq)
241 this(seq, seq.getAnnotation());
245 * Create a new sequence object with new features, DBRefEntries, and PDBIds
246 * but inherits any existing dataset sequence reference, and duplicate of any
247 * annotation that is present in the given annotation array.
250 * the sequence to be copied
251 * @param alAnnotation
252 * an array of annotation including some associated with seq
254 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
257 initSeqFrom(seq, alAnnotation);
261 * does the heavy lifting when cloning a dataset sequence, or coping data from
262 * dataset to a new derived sequence.
265 * - source of attributes.
266 * @param alAnnotation
267 * - alignment annotation present on seq that should be copied onto
270 protected void initSeqFrom(SequenceI seq,
271 AlignmentAnnotation[] alAnnotation)
273 char[] oseq = seq.getSequence(); // returns a copy of the array
274 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
276 description = seq.getDescription();
277 if (seq != datasetSequence)
279 setDatasetSequence(seq.getDatasetSequence());
283 * only copy DBRefs and seqfeatures if we really are a dataset sequence
285 if (datasetSequence == null)
287 if (seq.getDBRefs() != null)
289 DBRefEntry[] dbr = seq.getDBRefs();
290 for (int i = 0; i < dbr.length; i++)
292 addDBRef(new DBRefEntry(dbr[i]));
297 * make copies of any sequence features
299 for (SequenceFeature sf : seq.getSequenceFeatures())
301 addSequenceFeature(new SequenceFeature(sf));
305 if (seq.getAnnotation() != null)
307 AlignmentAnnotation[] sqann = seq.getAnnotation();
308 for (int i = 0; i < sqann.length; i++)
310 if (sqann[i] == null)
314 boolean found = (alAnnotation == null);
317 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
319 found = (alAnnotation[apos] == sqann[i]);
324 // only copy the given annotation
325 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
326 addAlignmentAnnotation(newann);
330 if (seq.getAllPDBEntries() != null)
332 Vector<PDBEntry> ids = seq.getAllPDBEntries();
333 for (PDBEntry pdb : ids)
335 this.addPDBId(new PDBEntry(pdb));
341 public void setSequenceFeatures(List<SequenceFeature> features)
343 if (datasetSequence != null)
345 datasetSequence.setSequenceFeatures(features);
348 sequenceFeatureStore = new SequenceFeatures(features);
352 public synchronized boolean addSequenceFeature(SequenceFeature sf)
354 if (sf.getType() == null)
356 System.err.println("SequenceFeature type may not be null: "
361 if (datasetSequence != null)
363 return datasetSequence.addSequenceFeature(sf);
366 return sequenceFeatureStore.add(sf);
370 public void deleteFeature(SequenceFeature sf)
372 if (datasetSequence != null)
374 datasetSequence.deleteFeature(sf);
378 sequenceFeatureStore.delete(sf);
388 public List<SequenceFeature> getSequenceFeatures()
390 if (datasetSequence != null)
392 return datasetSequence.getSequenceFeatures();
394 return sequenceFeatureStore.getAllFeatures();
398 public SequenceFeaturesI getFeatures()
400 return datasetSequence != null ? datasetSequence.getFeatures()
401 : sequenceFeatureStore;
405 public boolean addPDBId(PDBEntry entry)
409 pdbIds = new Vector<>();
414 for (PDBEntry pdbe : pdbIds)
416 if (pdbe.updateFrom(entry))
421 pdbIds.addElement(entry);
432 public void setPDBId(Vector<PDBEntry> id)
440 * @return DOCUMENT ME!
443 public Vector<PDBEntry> getAllPDBEntries()
445 return pdbIds == null ? new Vector<>() : pdbIds;
449 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
454 public String getDisplayId(boolean jvsuffix)
460 StringBuilder result = new StringBuilder(name);
461 result.append("/").append(start).append("-").append(end);
463 return result.toString();
467 * Sets the sequence name. If the name ends in /start-end, then the start-end
468 * values are parsed out and set, and the suffix is removed from the name.
473 public void setName(String theName)
482 * @return DOCUMENT ME!
485 public String getName()
497 public void setStart(int start)
506 * @return DOCUMENT ME!
509 public int getStart()
521 public void setEnd(int end)
529 * @return DOCUMENT ME!
540 * @return DOCUMENT ME!
543 public int getLength()
545 return this.sequence.length;
555 public void setSequence(String seq)
557 this.sequence = seq.toCharArray();
563 public String getSequenceAsString()
565 return new String(sequence);
569 public String getSequenceAsString(int start, int end)
571 return new String(getSequence(start, end));
575 public char[] getSequence()
578 return sequence == null ? null : Arrays.copyOf(sequence,
585 * @see jalview.datamodel.SequenceI#getSequence(int, int)
588 public char[] getSequence(int start, int end)
594 // JBPNote - left to user to pad the result here (TODO:Decide on this
596 if (start >= sequence.length)
601 if (end >= sequence.length)
603 end = sequence.length;
606 char[] reply = new char[end - start];
607 System.arraycopy(sequence, start, reply, 0, end - start);
613 public SequenceI getSubSequence(int start, int end)
619 char[] seq = getSequence(start, end);
624 int nstart = findPosition(start);
625 int nend = findPosition(end) - 1;
626 // JBPNote - this is an incomplete copy.
627 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
628 nseq.setDescription(description);
629 if (datasetSequence != null)
631 nseq.setDatasetSequence(datasetSequence);
635 nseq.setDatasetSequence(this);
641 * Returns the character of the aligned sequence at the given position (base
642 * zero), or space if the position is not within the sequence's bounds
647 public char getCharAt(int i)
649 if (i >= 0 && i < sequence.length)
660 * Sets the sequence description, and also parses out any special formats of
666 public void setDescription(String desc)
668 this.description = desc;
672 public void setGeneLoci(String speciesId, String assemblyId,
673 String chromosomeId, MapList map)
675 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
680 * Returns the gene loci mapping for the sequence (may be null)
685 public GeneLociI getGeneLoci()
687 DBRefEntry[] refs = getDBRefs();
690 for (final DBRefEntry ref : refs)
692 if (ref instanceof GeneLociI)
694 return (GeneLociI) ref;
702 * Answers the description
707 public String getDescription()
709 return this.description;
716 public int findIndex(int pos)
719 * use a valid, hopefully nearby, cursor if available
721 if (isValidCursor(cursor))
723 return findIndex(pos, cursor);
731 * traverse sequence from the start counting gaps; make a note of
732 * the column of the first residue to save in the cursor
734 while ((i < sequence.length) && (j <= end) && (j <= pos))
736 if (!Comparison.isGap(sequence[i]))
747 if (j == end && j < pos)
752 updateCursor(pos, i, startColumn);
757 * Updates the cursor to the latest found residue and column position
764 * column position of the first sequence residue
766 protected void updateCursor(int residuePos, int column, int startColumn)
769 * preserve end residue column provided cursor was valid
771 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
773 if (residuePos == this.end)
778 cursor = new SequenceCursor(this, residuePos, column, startColumn,
779 endColumn, this.changeCount);
783 * Answers the aligned column position (1..) for the given residue position
784 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
785 * The hint may be left of, at, or to the right of the required position.
791 protected int findIndex(final int pos, SequenceCursor curs)
793 if (!isValidCursor(curs))
796 * wrong or invalidated cursor, compute de novo
798 return findIndex(pos);
801 if (curs.residuePosition == pos)
803 return curs.columnPosition;
807 * move left or right to find pos from hint.position
809 int col = curs.columnPosition - 1; // convert from base 1 to base 0
810 int newPos = curs.residuePosition;
811 int delta = newPos > pos ? -1 : 1;
813 while (newPos != pos)
815 col += delta; // shift one column left or right
820 if (col == sequence.length)
822 col--; // return last column if we failed to reach pos
825 if (!Comparison.isGap(sequence[col]))
831 col++; // convert back to base 1
834 * only update cursor if we found the target position
838 updateCursor(pos, col, curs.firstColumnPosition);
848 public int findPosition(final int column)
851 * use a valid, hopefully nearby, cursor if available
853 if (isValidCursor(cursor))
855 return findPosition(column + 1, cursor);
858 // TODO recode this more naturally i.e. count residues only
859 // as they are found, not 'in anticipation'
862 * traverse the sequence counting gaps; note the column position
863 * of the first residue, to save in the cursor
865 int firstResidueColumn = 0;
866 int lastPosFound = 0;
867 int lastPosFoundColumn = 0;
868 int seqlen = sequence.length;
870 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
872 lastPosFound = start;
873 lastPosFoundColumn = 0;
879 while (j < column && j < seqlen)
881 if (!Comparison.isGap(sequence[j]))
884 lastPosFoundColumn = j;
885 if (pos == this.start)
887 firstResidueColumn = j;
893 if (j < seqlen && !Comparison.isGap(sequence[j]))
896 lastPosFoundColumn = j;
897 if (pos == this.start)
899 firstResidueColumn = j;
904 * update the cursor to the last residue position found (if any)
905 * (converting column position to base 1)
907 if (lastPosFound != 0)
909 updateCursor(lastPosFound, lastPosFoundColumn + 1,
910 firstResidueColumn + 1);
917 * Answers true if the given cursor is not null, is for this sequence object,
918 * and has a token value that matches this object's changeCount, else false.
919 * This allows us to ignore a cursor as 'stale' if the sequence has been
920 * modified since the cursor was created.
925 protected boolean isValidCursor(SequenceCursor curs)
927 if (curs == null || curs.sequence != this || curs.token != changeCount)
932 * sanity check against range
934 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
938 if (curs.residuePosition < start || curs.residuePosition > end)
946 * Answers the sequence position (start..) for the given aligned column
947 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
948 * may lie left of, at, or to the right of the column position.
954 protected int findPosition(final int col, SequenceCursor curs)
956 if (!isValidCursor(curs))
959 * wrong or invalidated cursor, compute de novo
961 return findPosition(col - 1);// ugh back to base 0
964 if (curs.columnPosition == col)
966 cursor = curs; // in case this method becomes public
967 return curs.residuePosition; // easy case :-)
970 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
973 * sequence lies entirely to the left of col
974 * - return last residue + 1
979 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
982 * sequence lies entirely to the right of col
983 * - return first residue
988 // todo could choose closest to col out of column,
989 // firstColumnPosition, lastColumnPosition as a start point
992 * move left or right to find pos from cursor position
994 int firstResidueColumn = curs.firstColumnPosition;
995 int column = curs.columnPosition - 1; // to base 0
996 int newPos = curs.residuePosition;
997 int delta = curs.columnPosition > col ? -1 : 1;
998 boolean gapped = false;
999 int lastFoundPosition = curs.residuePosition;
1000 int lastFoundPositionColumn = curs.columnPosition;
1002 while (column != col - 1)
1004 column += delta; // shift one column left or right
1005 if (column < 0 || column == sequence.length)
1009 gapped = Comparison.isGap(sequence[column]);
1013 lastFoundPosition = newPos;
1014 lastFoundPositionColumn = column + 1;
1015 if (lastFoundPosition == this.start)
1017 firstResidueColumn = column + 1;
1022 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1024 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1025 firstResidueColumn);
1029 * hack to give position to the right if on a gap
1030 * or beyond the length of the sequence (see JAL-2562)
1032 if (delta > 0 && (gapped || column >= sequence.length))
1044 public ContiguousI findPositions(int fromColumn, int toColumn)
1046 if (toColumn < fromColumn || fromColumn < 1)
1052 * find the first non-gapped position, if any
1054 int firstPosition = 0;
1055 int col = fromColumn - 1;
1056 int length = sequence.length;
1057 while (col < length && col < toColumn)
1059 if (!Comparison.isGap(sequence[col]))
1061 firstPosition = findPosition(col++);
1067 if (firstPosition == 0)
1073 * find the last non-gapped position
1075 int lastPosition = firstPosition;
1076 while (col < length && col < toColumn)
1078 if (!Comparison.isGap(sequence[col++]))
1084 return new Range(firstPosition, lastPosition);
1088 * Returns an int array where indices correspond to each residue in the
1089 * sequence and the element value gives its position in the alignment
1091 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1092 * residues in SequenceI object
1095 public int[] gapMap()
1097 String seq = jalview.analysis.AlignSeq.extractGaps(
1098 jalview.util.Comparison.GapChars, new String(sequence));
1099 int[] map = new int[seq.length()];
1103 while (j < sequence.length)
1105 if (!jalview.util.Comparison.isGap(sequence[j]))
1117 * Build a bitset corresponding to sequence gaps
1119 * @return a BitSet where set values correspond to gaps in the sequence
1122 public BitSet gapBitset()
1124 BitSet gaps = new BitSet(sequence.length);
1126 while (j < sequence.length)
1128 if (jalview.util.Comparison.isGap(sequence[j]))
1138 public int[] findPositionMap()
1140 int map[] = new int[sequence.length];
1143 int seqlen = sequence.length;
1144 while ((j < seqlen))
1147 if (!jalview.util.Comparison.isGap(sequence[j]))
1158 public List<int[]> getInsertions()
1160 ArrayList<int[]> map = new ArrayList<>();
1161 int lastj = -1, j = 0;
1163 int seqlen = sequence.length;
1164 while ((j < seqlen))
1166 if (jalview.util.Comparison.isGap(sequence[j]))
1177 map.add(new int[] { lastj, j - 1 });
1185 map.add(new int[] { lastj, j - 1 });
1192 public BitSet getInsertionsAsBits()
1194 BitSet map = new BitSet();
1195 int lastj = -1, j = 0;
1197 int seqlen = sequence.length;
1198 while ((j < seqlen))
1200 if (jalview.util.Comparison.isGap(sequence[j]))
1226 public void deleteChars(final int i, final int j)
1228 int newstart = start, newend = end;
1229 if (i >= sequence.length || i < 0)
1234 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1235 boolean createNewDs = false;
1236 // TODO: take a (second look) at the dataset creation validation method for
1237 // the very large sequence case
1239 int startIndex = findIndex(start) - 1;
1240 int endIndex = findIndex(end) - 1;
1241 int startDeleteColumn = -1; // for dataset sequence deletions
1242 int deleteCount = 0;
1244 for (int s = i; s < j && s < sequence.length; s++)
1246 if (Comparison.isGap(sequence[s]))
1251 if (startDeleteColumn == -1)
1253 startDeleteColumn = findPosition(s) - start;
1261 if (startIndex == s)
1264 * deleting characters from start of sequence; new start is the
1265 * sequence position of the next column (position to the right
1266 * if the column position is gapped)
1268 newstart = findPosition(j);
1276 * deleting characters at end of sequence; new end is the sequence
1277 * position of the column before the deletion; subtract 1 if this is
1278 * gapped since findPosition returns the next sequence position
1280 newend = findPosition(i - 1);
1281 if (Comparison.isGap(sequence[i - 1]))
1296 if (createNewDs && this.datasetSequence != null)
1299 * if deletion occured in the middle of the sequence,
1300 * construct a new dataset sequence and delete the residues
1301 * that were deleted from the aligned sequence
1303 Sequence ds = new Sequence(datasetSequence);
1304 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1305 datasetSequence = ds;
1306 // TODO: remove any non-inheritable properties ?
1307 // TODO: create a sequence mapping (since there is a relation here ?)
1316 public void insertCharAt(int i, int length, char c)
1318 char[] tmp = new char[sequence.length + length];
1320 if (i >= sequence.length)
1322 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1323 i = sequence.length;
1327 System.arraycopy(sequence, 0, tmp, 0, i);
1337 if (i < sequence.length)
1339 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1347 public void insertCharAt(int i, char c)
1349 insertCharAt(i, 1, c);
1353 public String getVamsasId()
1359 public void setVamsasId(String id)
1365 public void setDBRefs(DBRefEntry[] dbref)
1367 if (dbrefs == null && datasetSequence != null
1368 && this != datasetSequence)
1370 datasetSequence.setDBRefs(dbref);
1376 DBRefUtils.ensurePrimaries(this);
1381 public DBRefEntry[] getDBRefs()
1383 if (dbrefs == null && datasetSequence != null
1384 && this != datasetSequence)
1386 return datasetSequence.getDBRefs();
1392 public void addDBRef(DBRefEntry entry)
1394 if (datasetSequence != null)
1396 datasetSequence.addDBRef(entry);
1402 dbrefs = new DBRefEntry[0];
1405 for (DBRefEntryI dbr : dbrefs)
1407 if (dbr.updateFrom(entry))
1410 * found a dbref that either matched, or could be
1411 * updated from, the new entry - no need to add it
1418 * extend the array to make room for one more
1420 // TODO use an ArrayList instead
1421 int j = dbrefs.length;
1422 DBRefEntry[] temp = new DBRefEntry[j + 1];
1423 System.arraycopy(dbrefs, 0, temp, 0, j);
1424 temp[temp.length - 1] = entry;
1428 DBRefUtils.ensurePrimaries(this);
1432 public void setDatasetSequence(SequenceI seq)
1436 throw new IllegalArgumentException(
1437 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1439 if (seq != null && seq.getDatasetSequence() != null)
1441 throw new IllegalArgumentException(
1442 "Implementation error: cascading dataset sequences are not allowed.");
1444 datasetSequence = seq;
1448 public SequenceI getDatasetSequence()
1450 return datasetSequence;
1454 public AlignmentAnnotation[] getAnnotation()
1456 return annotation == null ? null
1458 .toArray(new AlignmentAnnotation[annotation.size()]);
1462 public boolean hasAnnotation(AlignmentAnnotation ann)
1464 return annotation == null ? false : annotation.contains(ann);
1468 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1470 if (this.annotation == null)
1472 this.annotation = new Vector<>();
1474 if (!this.annotation.contains(annotation))
1476 this.annotation.addElement(annotation);
1478 annotation.setSequenceRef(this);
1482 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1484 if (this.annotation != null)
1486 this.annotation.removeElement(annotation);
1487 if (this.annotation.size() == 0)
1489 this.annotation = null;
1495 * test if this is a valid candidate for another sequence's dataset sequence.
1498 private boolean isValidDatasetSequence()
1500 if (datasetSequence != null)
1504 for (int i = 0; i < sequence.length; i++)
1506 if (jalview.util.Comparison.isGap(sequence[i]))
1515 public SequenceI deriveSequence()
1517 Sequence seq = null;
1518 if (datasetSequence == null)
1520 if (isValidDatasetSequence())
1522 // Use this as dataset sequence
1523 seq = new Sequence(getName(), "", 1, -1);
1524 seq.setDatasetSequence(this);
1525 seq.initSeqFrom(this, getAnnotation());
1530 // Create a new, valid dataset sequence
1531 createDatasetSequence();
1534 return new Sequence(this);
1537 private boolean _isNa;
1539 private int _seqhash = 0;
1542 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1546 public boolean isProtein()
1548 if (datasetSequence != null)
1550 return datasetSequence.isProtein();
1552 if (_seqhash != sequence.hashCode())
1554 _seqhash = sequence.hashCode();
1555 _isNa = Comparison.isNucleotide(this);
1563 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1566 public SequenceI createDatasetSequence()
1568 if (datasetSequence == null)
1570 Sequence dsseq = new Sequence(getName(),
1571 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1572 getSequenceAsString()),
1573 getStart(), getEnd());
1575 datasetSequence = dsseq;
1577 dsseq.setDescription(description);
1578 // move features and database references onto dataset sequence
1579 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1580 sequenceFeatureStore = null;
1581 dsseq.dbrefs = dbrefs;
1583 // TODO: search and replace any references to this sequence with
1584 // references to the dataset sequence in Mappings on dbref
1585 dsseq.pdbIds = pdbIds;
1587 datasetSequence.updatePDBIds();
1588 if (annotation != null)
1590 // annotation is cloned rather than moved, to preserve what's currently
1592 for (AlignmentAnnotation aa : annotation)
1594 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1595 _aa.sequenceRef = datasetSequence;
1596 _aa.adjustForAlignment(); // uses annotation's own record of
1597 // sequence-column mapping
1598 datasetSequence.addAlignmentAnnotation(_aa);
1602 return datasetSequence;
1609 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1613 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1615 if (annotation != null)
1617 annotation.removeAllElements();
1619 if (annotations != null)
1621 for (int i = 0; i < annotations.length; i++)
1623 if (annotations[i] != null)
1625 addAlignmentAnnotation(annotations[i]);
1632 public AlignmentAnnotation[] getAnnotation(String label)
1634 if (annotation == null || annotation.size() == 0)
1639 Vector<AlignmentAnnotation> subset = new Vector<>();
1640 Enumeration<AlignmentAnnotation> e = annotation.elements();
1641 while (e.hasMoreElements())
1643 AlignmentAnnotation ann = e.nextElement();
1644 if (ann.label != null && ann.label.equals(label))
1646 subset.addElement(ann);
1649 if (subset.size() == 0)
1653 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1655 e = subset.elements();
1656 while (e.hasMoreElements())
1658 anns[i++] = e.nextElement();
1660 subset.removeAllElements();
1665 public boolean updatePDBIds()
1667 if (datasetSequence != null)
1669 // TODO: could merge DBRefs
1670 return datasetSequence.updatePDBIds();
1672 if (dbrefs == null || dbrefs.length == 0)
1676 boolean added = false;
1677 for (DBRefEntry dbr : dbrefs)
1679 if (DBRefSource.PDB.equals(dbr.getSource()))
1682 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1683 * PDB id is not already present in a 'matching' PDBEntry
1684 * Constructor parses out a chain code if appended to the accession id
1685 * (a fudge used to 'store' the chain code in the DBRef)
1687 PDBEntry pdbe = new PDBEntry(dbr);
1688 added |= addPDBId(pdbe);
1695 public void transferAnnotation(SequenceI entry, Mapping mp)
1697 if (datasetSequence != null)
1699 datasetSequence.transferAnnotation(entry, mp);
1702 if (entry.getDatasetSequence() != null)
1704 transferAnnotation(entry.getDatasetSequence(), mp);
1707 // transfer any new features from entry onto sequence
1708 if (entry.getSequenceFeatures() != null)
1711 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1712 for (SequenceFeature feature : sfs)
1714 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1715 : new SequenceFeature[] { new SequenceFeature(feature) };
1718 for (int sfi = 0; sfi < sf.length; sfi++)
1720 addSequenceFeature(sf[sfi]);
1726 // transfer PDB entries
1727 if (entry.getAllPDBEntries() != null)
1729 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1730 while (e.hasMoreElements())
1732 PDBEntry pdb = e.nextElement();
1736 // transfer database references
1737 DBRefEntry[] entryRefs = entry.getDBRefs();
1738 if (entryRefs != null)
1740 for (int r = 0; r < entryRefs.length; r++)
1742 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1743 if (newref.getMap() != null && mp != null)
1745 // remap ref using our local mapping
1747 // we also assume all version string setting is done by dbSourceProxy
1749 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1750 * newref.setSource(dbSource); }
1758 public void setRNA(RNA r)
1770 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1773 List<AlignmentAnnotation> result = new ArrayList<>();
1774 if (this.annotation != null)
1776 for (AlignmentAnnotation ann : annotation)
1778 if (ann.calcId != null && ann.calcId.equals(calcId)
1779 && ann.label != null && ann.label.equals(label))
1789 public String toString()
1791 return getDisplayId(false);
1795 public PDBEntry getPDBEntry(String pdbIdStr)
1797 if (getDatasetSequence() != null)
1799 return getDatasetSequence().getPDBEntry(pdbIdStr);
1805 List<PDBEntry> entries = getAllPDBEntries();
1806 for (PDBEntry entry : entries)
1808 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1817 public List<DBRefEntry> getPrimaryDBRefs()
1819 if (datasetSequence != null)
1821 return datasetSequence.getPrimaryDBRefs();
1823 if (dbrefs == null || dbrefs.length == 0)
1825 return Collections.emptyList();
1827 synchronized (dbrefs)
1829 List<DBRefEntry> primaries = new ArrayList<>();
1830 DBRefEntry[] tmp = new DBRefEntry[1];
1831 for (DBRefEntry ref : dbrefs)
1833 if (!ref.isPrimaryCandidate())
1839 MapList mp = ref.getMap().getMap();
1840 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1842 // map only involves a subsequence, so cannot be primary
1846 // whilst it looks like it is a primary ref, we also sanity check type
1847 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1848 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1850 // PDB dbrefs imply there should be a PDBEntry associated
1851 // TODO: tighten PDB dbrefs
1852 // formally imply Jalview has actually downloaded and
1853 // parsed the pdb file. That means there should be a cached file
1854 // handle on the PDBEntry, and a real mapping between sequence and
1855 // extracted sequence from PDB file
1856 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1857 if (pdbentry != null && pdbentry.getFile() != null)
1863 // check standard protein or dna sources
1865 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1866 if (res != null && res[0] == tmp[0])
1880 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1883 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1884 int endPos = fromColumn == toColumn ? startPos
1885 : findPosition(toColumn - 1);
1887 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1891 * if end column is gapped, endPos may be to the right,
1892 * and we may have included adjacent or enclosing features;
1893 * remove any that are not enclosing, non-contact features
1895 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1896 && Comparison.isGap(sequence[toColumn - 1]);
1897 if (endPos > this.end || endColumnIsGapped)
1899 ListIterator<SequenceFeature> it = result.listIterator();
1900 while (it.hasNext())
1902 SequenceFeature sf = it.next();
1903 int sfBegin = sf.getBegin();
1904 int sfEnd = sf.getEnd();
1905 int featureStartColumn = findIndex(sfBegin);
1906 if (featureStartColumn > toColumn)
1910 else if (featureStartColumn < fromColumn)
1912 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1914 if (featureEndColumn < fromColumn)
1918 else if (featureEndColumn > toColumn && sf.isContactFeature())
1921 * remove an enclosing feature if it is a contact feature
1933 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1934 * token that has to match the one presented by the cursor
1937 public void sequenceChanged()
1946 public int replace(char c1, char c2)
1953 synchronized (sequence)
1955 for (int c = 0; c < sequence.length; c++)
1957 if (sequence[c] == c1)
1973 public String getSequenceStringFromIterator(Iterator<int[]> it)
1975 StringBuilder newSequence = new StringBuilder();
1976 while (it.hasNext())
1978 int[] block = it.next();
1981 newSequence.append(getSequence(block[0], block[1] + 1));
1985 newSequence.append(getSequence(block[0], block[1]));
1989 return newSequence.toString();
1993 public int firstResidueOutsideIterator(Iterator<int[]> regions)
1997 if (!regions.hasNext())
1999 return findIndex(getStart()) - 1;
2002 // Simply walk along the sequence whilst watching for region
2004 int hideStart = getLength();
2006 boolean foundStart = false;
2008 // step through the non-gapped positions of the sequence
2009 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2011 // get alignment position of this residue in the sequence
2012 int p = findIndex(i) - 1;
2014 // update region start/end
2015 while (hideEnd < p && regions.hasNext())
2017 int[] region = regions.next();
2018 hideStart = region[0];
2019 hideEnd = region[1];
2023 hideStart = getLength();
2025 // update boundary for sequence
2037 // otherwise, sequence was completely hidden