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;
451 * @return DOCUMENT ME!
454 public String getDisplayId(boolean jvsuffix)
456 StringBuffer result = new StringBuffer(name);
459 result.append("/" + start + "-" + end);
462 return result.toString();
466 * Sets the sequence name. If the name ends in /start-end, then the start-end
467 * values are parsed out and set, and the suffix is removed from the name.
472 public void setName(String theName)
481 * @return DOCUMENT ME!
484 public String getName()
496 public void setStart(int start)
504 * @return DOCUMENT ME!
507 public int getStart()
519 public void setEnd(int end)
527 * @return DOCUMENT ME!
538 * @return DOCUMENT ME!
541 public int getLength()
543 return this.sequence.length;
553 public void setSequence(String seq)
555 this.sequence = seq.toCharArray();
561 public String getSequenceAsString()
563 return new String(sequence);
567 public String getSequenceAsString(int start, int end)
569 return new String(getSequence(start, end));
573 public char[] getSequence()
576 return sequence == null ? null : Arrays.copyOf(sequence,
583 * @see jalview.datamodel.SequenceI#getSequence(int, int)
586 public char[] getSequence(int start, int end)
592 // JBPNote - left to user to pad the result here (TODO:Decide on this
594 if (start >= sequence.length)
599 if (end >= sequence.length)
601 end = sequence.length;
604 char[] reply = new char[end - start];
605 System.arraycopy(sequence, start, reply, 0, end - start);
611 public SequenceI getSubSequence(int start, int end)
617 char[] seq = getSequence(start, end);
622 int nstart = findPosition(start);
623 int nend = findPosition(end) - 1;
624 // JBPNote - this is an incomplete copy.
625 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
626 nseq.setDescription(description);
627 if (datasetSequence != null)
629 nseq.setDatasetSequence(datasetSequence);
633 nseq.setDatasetSequence(this);
639 * Returns the character of the aligned sequence at the given position (base
640 * zero), or space if the position is not within the sequence's bounds
645 public char getCharAt(int i)
647 if (i >= 0 && i < sequence.length)
658 * Sets the sequence description, and also parses out any special formats of
664 public void setDescription(String desc)
666 this.description = desc;
670 public void setGeneLoci(String speciesId, String assemblyId,
671 String chromosomeId, MapList map)
673 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
678 * Returns the gene loci mapping for the sequence (may be null)
683 public GeneLociI getGeneLoci()
685 DBRefEntry[] refs = getDBRefs();
688 for (final DBRefEntry ref : refs)
690 if (ref instanceof GeneLociI)
692 return (GeneLociI) ref;
700 * Answers the description
705 public String getDescription()
707 return this.description;
714 public int findIndex(int pos)
717 * use a valid, hopefully nearby, cursor if available
719 if (isValidCursor(cursor))
721 return findIndex(pos, cursor);
729 * traverse sequence from the start counting gaps; make a note of
730 * the column of the first residue to save in the cursor
732 while ((i < sequence.length) && (j <= end) && (j <= pos))
734 if (!Comparison.isGap(sequence[i]))
745 if (j == end && j < pos)
750 updateCursor(pos, i, startColumn);
755 * Updates the cursor to the latest found residue and column position
762 * column position of the first sequence residue
764 protected void updateCursor(int residuePos, int column, int startColumn)
767 * preserve end residue column provided cursor was valid
769 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
771 if (residuePos == this.end)
776 cursor = new SequenceCursor(this, residuePos, column, startColumn,
777 endColumn, this.changeCount);
781 * Answers the aligned column position (1..) for the given residue position
782 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
783 * The hint may be left of, at, or to the right of the required position.
789 protected int findIndex(final int pos, SequenceCursor curs)
791 if (!isValidCursor(curs))
794 * wrong or invalidated cursor, compute de novo
796 return findIndex(pos);
799 if (curs.residuePosition == pos)
801 return curs.columnPosition;
805 * move left or right to find pos from hint.position
807 int col = curs.columnPosition - 1; // convert from base 1 to base 0
808 int newPos = curs.residuePosition;
809 int delta = newPos > pos ? -1 : 1;
811 while (newPos != pos)
813 col += delta; // shift one column left or right
818 if (col == sequence.length)
820 col--; // return last column if we failed to reach pos
823 if (!Comparison.isGap(sequence[col]))
829 col++; // convert back to base 1
832 * only update cursor if we found the target position
836 updateCursor(pos, col, curs.firstColumnPosition);
846 public int findPosition(final int column)
849 * use a valid, hopefully nearby, cursor if available
851 if (isValidCursor(cursor))
853 return findPosition(column + 1, cursor);
856 // TODO recode this more naturally i.e. count residues only
857 // as they are found, not 'in anticipation'
860 * traverse the sequence counting gaps; note the column position
861 * of the first residue, to save in the cursor
863 int firstResidueColumn = 0;
864 int lastPosFound = 0;
865 int lastPosFoundColumn = 0;
866 int seqlen = sequence.length;
868 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
870 lastPosFound = start;
871 lastPosFoundColumn = 0;
877 while (j < column && j < seqlen)
879 if (!Comparison.isGap(sequence[j]))
882 lastPosFoundColumn = j;
883 if (pos == this.start)
885 firstResidueColumn = j;
891 if (j < seqlen && !Comparison.isGap(sequence[j]))
894 lastPosFoundColumn = j;
895 if (pos == this.start)
897 firstResidueColumn = j;
902 * update the cursor to the last residue position found (if any)
903 * (converting column position to base 1)
905 if (lastPosFound != 0)
907 updateCursor(lastPosFound, lastPosFoundColumn + 1,
908 firstResidueColumn + 1);
915 * Answers true if the given cursor is not null, is for this sequence object,
916 * and has a token value that matches this object's changeCount, else false.
917 * This allows us to ignore a cursor as 'stale' if the sequence has been
918 * modified since the cursor was created.
923 protected boolean isValidCursor(SequenceCursor curs)
925 if (curs == null || curs.sequence != this || curs.token != changeCount)
930 * sanity check against range
932 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
936 if (curs.residuePosition < start || curs.residuePosition > end)
944 * Answers the sequence position (start..) for the given aligned column
945 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
946 * may lie left of, at, or to the right of the column position.
952 protected int findPosition(final int col, SequenceCursor curs)
954 if (!isValidCursor(curs))
957 * wrong or invalidated cursor, compute de novo
959 return findPosition(col - 1);// ugh back to base 0
962 if (curs.columnPosition == col)
964 cursor = curs; // in case this method becomes public
965 return curs.residuePosition; // easy case :-)
968 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
971 * sequence lies entirely to the left of col
972 * - return last residue + 1
977 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
980 * sequence lies entirely to the right of col
981 * - return first residue
986 // todo could choose closest to col out of column,
987 // firstColumnPosition, lastColumnPosition as a start point
990 * move left or right to find pos from cursor position
992 int firstResidueColumn = curs.firstColumnPosition;
993 int column = curs.columnPosition - 1; // to base 0
994 int newPos = curs.residuePosition;
995 int delta = curs.columnPosition > col ? -1 : 1;
996 boolean gapped = false;
997 int lastFoundPosition = curs.residuePosition;
998 int lastFoundPositionColumn = curs.columnPosition;
1000 while (column != col - 1)
1002 column += delta; // shift one column left or right
1003 if (column < 0 || column == sequence.length)
1007 gapped = Comparison.isGap(sequence[column]);
1011 lastFoundPosition = newPos;
1012 lastFoundPositionColumn = column + 1;
1013 if (lastFoundPosition == this.start)
1015 firstResidueColumn = column + 1;
1020 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1022 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1023 firstResidueColumn);
1027 * hack to give position to the right if on a gap
1028 * or beyond the length of the sequence (see JAL-2562)
1030 if (delta > 0 && (gapped || column >= sequence.length))
1042 public ContiguousI findPositions(int fromColumn, int toColumn)
1044 if (toColumn < fromColumn || fromColumn < 1)
1050 * find the first non-gapped position, if any
1052 int firstPosition = 0;
1053 int col = fromColumn - 1;
1054 int length = sequence.length;
1055 while (col < length && col < toColumn)
1057 if (!Comparison.isGap(sequence[col]))
1059 firstPosition = findPosition(col++);
1065 if (firstPosition == 0)
1071 * find the last non-gapped position
1073 int lastPosition = firstPosition;
1074 while (col < length && col < toColumn)
1076 if (!Comparison.isGap(sequence[col++]))
1082 return new Range(firstPosition, lastPosition);
1086 * Returns an int array where indices correspond to each residue in the
1087 * sequence and the element value gives its position in the alignment
1089 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1090 * residues in SequenceI object
1093 public int[] gapMap()
1095 String seq = jalview.analysis.AlignSeq.extractGaps(
1096 jalview.util.Comparison.GapChars, new String(sequence));
1097 int[] map = new int[seq.length()];
1101 while (j < sequence.length)
1103 if (!jalview.util.Comparison.isGap(sequence[j]))
1115 * Build a bitset corresponding to sequence gaps
1117 * @return a BitSet where set values correspond to gaps in the sequence
1120 public BitSet gapBitset()
1122 BitSet gaps = new BitSet(sequence.length);
1124 while (j < sequence.length)
1126 if (jalview.util.Comparison.isGap(sequence[j]))
1136 public int[] findPositionMap()
1138 int map[] = new int[sequence.length];
1141 int seqlen = sequence.length;
1142 while ((j < seqlen))
1145 if (!jalview.util.Comparison.isGap(sequence[j]))
1156 public List<int[]> getInsertions()
1158 ArrayList<int[]> map = new ArrayList<>();
1159 int lastj = -1, j = 0;
1161 int seqlen = sequence.length;
1162 while ((j < seqlen))
1164 if (jalview.util.Comparison.isGap(sequence[j]))
1175 map.add(new int[] { lastj, j - 1 });
1183 map.add(new int[] { lastj, j - 1 });
1190 public BitSet getInsertionsAsBits()
1192 BitSet map = new BitSet();
1193 int lastj = -1, j = 0;
1195 int seqlen = sequence.length;
1196 while ((j < seqlen))
1198 if (jalview.util.Comparison.isGap(sequence[j]))
1224 public void deleteChars(final int i, final int j)
1226 int newstart = start, newend = end;
1227 if (i >= sequence.length || i < 0)
1232 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1233 boolean createNewDs = false;
1234 // TODO: take a (second look) at the dataset creation validation method for
1235 // the very large sequence case
1237 int startIndex = findIndex(start) - 1;
1238 int endIndex = findIndex(end) - 1;
1239 int startDeleteColumn = -1; // for dataset sequence deletions
1240 int deleteCount = 0;
1242 for (int s = i; s < j && s < sequence.length; s++)
1244 if (Comparison.isGap(sequence[s]))
1249 if (startDeleteColumn == -1)
1251 startDeleteColumn = findPosition(s) - start;
1259 if (startIndex == s)
1262 * deleting characters from start of sequence; new start is the
1263 * sequence position of the next column (position to the right
1264 * if the column position is gapped)
1266 newstart = findPosition(j);
1274 * deleting characters at end of sequence; new end is the sequence
1275 * position of the column before the deletion; subtract 1 if this is
1276 * gapped since findPosition returns the next sequence position
1278 newend = findPosition(i - 1);
1279 if (Comparison.isGap(sequence[i - 1]))
1294 if (createNewDs && this.datasetSequence != null)
1297 * if deletion occured in the middle of the sequence,
1298 * construct a new dataset sequence and delete the residues
1299 * that were deleted from the aligned sequence
1301 Sequence ds = new Sequence(datasetSequence);
1302 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1303 datasetSequence = ds;
1304 // TODO: remove any non-inheritable properties ?
1305 // TODO: create a sequence mapping (since there is a relation here ?)
1314 public void insertCharAt(int i, int length, char c)
1316 char[] tmp = new char[sequence.length + length];
1318 if (i >= sequence.length)
1320 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1321 i = sequence.length;
1325 System.arraycopy(sequence, 0, tmp, 0, i);
1335 if (i < sequence.length)
1337 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1345 public void insertCharAt(int i, char c)
1347 insertCharAt(i, 1, c);
1351 public String getVamsasId()
1357 public void setVamsasId(String id)
1363 public void setDBRefs(DBRefEntry[] dbref)
1365 if (dbrefs == null && datasetSequence != null
1366 && this != datasetSequence)
1368 datasetSequence.setDBRefs(dbref);
1374 DBRefUtils.ensurePrimaries(this);
1379 public DBRefEntry[] getDBRefs()
1381 if (dbrefs == null && datasetSequence != null
1382 && this != datasetSequence)
1384 return datasetSequence.getDBRefs();
1390 public void addDBRef(DBRefEntry entry)
1392 if (datasetSequence != null)
1394 datasetSequence.addDBRef(entry);
1400 dbrefs = new DBRefEntry[0];
1403 for (DBRefEntryI dbr : dbrefs)
1405 if (dbr.updateFrom(entry))
1408 * found a dbref that either matched, or could be
1409 * updated from, the new entry - no need to add it
1416 * extend the array to make room for one more
1418 // TODO use an ArrayList instead
1419 int j = dbrefs.length;
1420 DBRefEntry[] temp = new DBRefEntry[j + 1];
1421 System.arraycopy(dbrefs, 0, temp, 0, j);
1422 temp[temp.length - 1] = entry;
1426 DBRefUtils.ensurePrimaries(this);
1430 public void setDatasetSequence(SequenceI seq)
1434 throw new IllegalArgumentException(
1435 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1437 if (seq != null && seq.getDatasetSequence() != null)
1439 throw new IllegalArgumentException(
1440 "Implementation error: cascading dataset sequences are not allowed.");
1442 datasetSequence = seq;
1446 public SequenceI getDatasetSequence()
1448 return datasetSequence;
1452 public AlignmentAnnotation[] getAnnotation()
1454 return annotation == null ? null
1456 .toArray(new AlignmentAnnotation[annotation.size()]);
1460 public boolean hasAnnotation(AlignmentAnnotation ann)
1462 return annotation == null ? false : annotation.contains(ann);
1466 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1468 if (this.annotation == null)
1470 this.annotation = new Vector<>();
1472 if (!this.annotation.contains(annotation))
1474 this.annotation.addElement(annotation);
1476 annotation.setSequenceRef(this);
1480 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1482 if (this.annotation != null)
1484 this.annotation.removeElement(annotation);
1485 if (this.annotation.size() == 0)
1487 this.annotation = null;
1493 * test if this is a valid candidate for another sequence's dataset sequence.
1496 private boolean isValidDatasetSequence()
1498 if (datasetSequence != null)
1502 for (int i = 0; i < sequence.length; i++)
1504 if (jalview.util.Comparison.isGap(sequence[i]))
1513 public SequenceI deriveSequence()
1515 Sequence seq = null;
1516 if (datasetSequence == null)
1518 if (isValidDatasetSequence())
1520 // Use this as dataset sequence
1521 seq = new Sequence(getName(), "", 1, -1);
1522 seq.setDatasetSequence(this);
1523 seq.initSeqFrom(this, getAnnotation());
1528 // Create a new, valid dataset sequence
1529 createDatasetSequence();
1532 return new Sequence(this);
1535 private boolean _isNa;
1537 private int _seqhash = 0;
1540 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1544 public boolean isProtein()
1546 if (datasetSequence != null)
1548 return datasetSequence.isProtein();
1550 if (_seqhash != sequence.hashCode())
1552 _seqhash = sequence.hashCode();
1553 _isNa = Comparison.isNucleotide(this);
1561 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1564 public SequenceI createDatasetSequence()
1566 if (datasetSequence == null)
1568 Sequence dsseq = new Sequence(getName(),
1569 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1570 getSequenceAsString()),
1571 getStart(), getEnd());
1573 datasetSequence = dsseq;
1575 dsseq.setDescription(description);
1576 // move features and database references onto dataset sequence
1577 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1578 sequenceFeatureStore = null;
1579 dsseq.dbrefs = dbrefs;
1581 // TODO: search and replace any references to this sequence with
1582 // references to the dataset sequence in Mappings on dbref
1583 dsseq.pdbIds = pdbIds;
1585 datasetSequence.updatePDBIds();
1586 if (annotation != null)
1588 // annotation is cloned rather than moved, to preserve what's currently
1590 for (AlignmentAnnotation aa : annotation)
1592 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1593 _aa.sequenceRef = datasetSequence;
1594 _aa.adjustForAlignment(); // uses annotation's own record of
1595 // sequence-column mapping
1596 datasetSequence.addAlignmentAnnotation(_aa);
1600 return datasetSequence;
1607 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1611 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1613 if (annotation != null)
1615 annotation.removeAllElements();
1617 if (annotations != null)
1619 for (int i = 0; i < annotations.length; i++)
1621 if (annotations[i] != null)
1623 addAlignmentAnnotation(annotations[i]);
1630 public AlignmentAnnotation[] getAnnotation(String label)
1632 if (annotation == null || annotation.size() == 0)
1637 Vector<AlignmentAnnotation> subset = new Vector<>();
1638 Enumeration<AlignmentAnnotation> e = annotation.elements();
1639 while (e.hasMoreElements())
1641 AlignmentAnnotation ann = e.nextElement();
1642 if (ann.label != null && ann.label.equals(label))
1644 subset.addElement(ann);
1647 if (subset.size() == 0)
1651 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1653 e = subset.elements();
1654 while (e.hasMoreElements())
1656 anns[i++] = e.nextElement();
1658 subset.removeAllElements();
1663 public boolean updatePDBIds()
1665 if (datasetSequence != null)
1667 // TODO: could merge DBRefs
1668 return datasetSequence.updatePDBIds();
1670 if (dbrefs == null || dbrefs.length == 0)
1674 boolean added = false;
1675 for (DBRefEntry dbr : dbrefs)
1677 if (DBRefSource.PDB.equals(dbr.getSource()))
1680 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1681 * PDB id is not already present in a 'matching' PDBEntry
1682 * Constructor parses out a chain code if appended to the accession id
1683 * (a fudge used to 'store' the chain code in the DBRef)
1685 PDBEntry pdbe = new PDBEntry(dbr);
1686 added |= addPDBId(pdbe);
1693 public void transferAnnotation(SequenceI entry, Mapping mp)
1695 if (datasetSequence != null)
1697 datasetSequence.transferAnnotation(entry, mp);
1700 if (entry.getDatasetSequence() != null)
1702 transferAnnotation(entry.getDatasetSequence(), mp);
1705 // transfer any new features from entry onto sequence
1706 if (entry.getSequenceFeatures() != null)
1709 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1710 for (SequenceFeature feature : sfs)
1712 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1713 : new SequenceFeature[] { new SequenceFeature(feature) };
1716 for (int sfi = 0; sfi < sf.length; sfi++)
1718 addSequenceFeature(sf[sfi]);
1724 // transfer PDB entries
1725 if (entry.getAllPDBEntries() != null)
1727 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1728 while (e.hasMoreElements())
1730 PDBEntry pdb = e.nextElement();
1734 // transfer database references
1735 DBRefEntry[] entryRefs = entry.getDBRefs();
1736 if (entryRefs != null)
1738 for (int r = 0; r < entryRefs.length; r++)
1740 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1741 if (newref.getMap() != null && mp != null)
1743 // remap ref using our local mapping
1745 // we also assume all version string setting is done by dbSourceProxy
1747 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1748 * newref.setSource(dbSource); }
1756 public void setRNA(RNA r)
1768 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1771 List<AlignmentAnnotation> result = new ArrayList<>();
1772 if (this.annotation != null)
1774 for (AlignmentAnnotation ann : annotation)
1776 if (ann.calcId != null && ann.calcId.equals(calcId)
1777 && ann.label != null && ann.label.equals(label))
1787 public String toString()
1789 return getDisplayId(false);
1793 public PDBEntry getPDBEntry(String pdbIdStr)
1795 if (getDatasetSequence() != null)
1797 return getDatasetSequence().getPDBEntry(pdbIdStr);
1803 List<PDBEntry> entries = getAllPDBEntries();
1804 for (PDBEntry entry : entries)
1806 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1815 public List<DBRefEntry> getPrimaryDBRefs()
1817 if (datasetSequence != null)
1819 return datasetSequence.getPrimaryDBRefs();
1821 if (dbrefs == null || dbrefs.length == 0)
1823 return Collections.emptyList();
1825 synchronized (dbrefs)
1827 List<DBRefEntry> primaries = new ArrayList<>();
1828 DBRefEntry[] tmp = new DBRefEntry[1];
1829 for (DBRefEntry ref : dbrefs)
1831 if (!ref.isPrimaryCandidate())
1837 MapList mp = ref.getMap().getMap();
1838 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1840 // map only involves a subsequence, so cannot be primary
1844 // whilst it looks like it is a primary ref, we also sanity check type
1845 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1846 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1848 // PDB dbrefs imply there should be a PDBEntry associated
1849 // TODO: tighten PDB dbrefs
1850 // formally imply Jalview has actually downloaded and
1851 // parsed the pdb file. That means there should be a cached file
1852 // handle on the PDBEntry, and a real mapping between sequence and
1853 // extracted sequence from PDB file
1854 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1855 if (pdbentry != null && pdbentry.getFile() != null)
1861 // check standard protein or dna sources
1863 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1864 if (res != null && res[0] == tmp[0])
1878 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1881 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1882 int endPos = fromColumn == toColumn ? startPos
1883 : findPosition(toColumn - 1);
1885 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1887 if (datasetSequence != null)
1889 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1894 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1898 * if end column is gapped, endPos may be to the right,
1899 * and we may have included adjacent or enclosing features;
1900 * remove any that are not enclosing, non-contact features
1902 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1903 && Comparison.isGap(sequence[toColumn - 1]);
1904 if (endPos > this.end || endColumnIsGapped)
1906 ListIterator<SequenceFeature> it = result.listIterator();
1907 while (it.hasNext())
1909 SequenceFeature sf = it.next();
1910 int sfBegin = sf.getBegin();
1911 int sfEnd = sf.getEnd();
1912 int featureStartColumn = findIndex(sfBegin);
1913 if (featureStartColumn > toColumn)
1917 else if (featureStartColumn < fromColumn)
1919 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1921 if (featureEndColumn < fromColumn)
1925 else if (featureEndColumn > toColumn && sf.isContactFeature())
1928 * remove an enclosing feature if it is a contact feature
1940 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1941 * token that has to match the one presented by the cursor
1944 public void sequenceChanged()
1953 public int replace(char c1, char c2)
1960 synchronized (sequence)
1962 for (int c = 0; c < sequence.length; c++)
1964 if (sequence[c] == c1)
1980 public String getSequenceStringFromIterator(Iterator<int[]> it)
1982 StringBuilder newSequence = new StringBuilder();
1983 while (it.hasNext())
1985 int[] block = it.next();
1988 newSequence.append(getSequence(block[0], block[1] + 1));
1992 newSequence.append(getSequence(block[0], block[1]));
1996 return newSequence.toString();
2000 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2004 if (!regions.hasNext())
2006 return findIndex(getStart()) - 1;
2009 // Simply walk along the sequence whilst watching for region
2011 int hideStart = getLength();
2013 boolean foundStart = false;
2015 // step through the non-gapped positions of the sequence
2016 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2018 // get alignment position of this residue in the sequence
2019 int p = findIndex(i) - 1;
2021 // update region start/end
2022 while (hideEnd < p && regions.hasNext())
2024 int[] region = regions.next();
2025 hideStart = region[0];
2026 hideEnd = region[1];
2030 hideStart = getLength();
2032 // update boundary for sequence
2044 // otherwise, sequence was completely hidden