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)
505 * @return DOCUMENT ME!
508 public int getStart()
520 public void setEnd(int end)
528 * @return DOCUMENT ME!
539 * @return DOCUMENT ME!
542 public int getLength()
544 return this.sequence.length;
554 public void setSequence(String seq)
556 this.sequence = seq.toCharArray();
562 public String getSequenceAsString()
564 return new String(sequence);
568 public String getSequenceAsString(int start, int end)
570 return new String(getSequence(start, end));
574 public char[] getSequence()
577 return sequence == null ? null : Arrays.copyOf(sequence,
584 * @see jalview.datamodel.SequenceI#getSequence(int, int)
587 public char[] getSequence(int start, int end)
593 // JBPNote - left to user to pad the result here (TODO:Decide on this
595 if (start >= sequence.length)
600 if (end >= sequence.length)
602 end = sequence.length;
605 char[] reply = new char[end - start];
606 System.arraycopy(sequence, start, reply, 0, end - start);
612 public SequenceI getSubSequence(int start, int end)
618 char[] seq = getSequence(start, end);
623 int nstart = findPosition(start);
624 int nend = findPosition(end) - 1;
625 // JBPNote - this is an incomplete copy.
626 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
627 nseq.setDescription(description);
628 if (datasetSequence != null)
630 nseq.setDatasetSequence(datasetSequence);
634 nseq.setDatasetSequence(this);
640 * Returns the character of the aligned sequence at the given position (base
641 * zero), or space if the position is not within the sequence's bounds
646 public char getCharAt(int i)
648 if (i >= 0 && i < sequence.length)
659 * Sets the sequence description, and also parses out any special formats of
665 public void setDescription(String desc)
667 this.description = desc;
671 public void setGeneLoci(String speciesId, String assemblyId,
672 String chromosomeId, MapList map)
674 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
679 * Returns the gene loci mapping for the sequence (may be null)
684 public GeneLociI getGeneLoci()
686 DBRefEntry[] refs = getDBRefs();
689 for (final DBRefEntry ref : refs)
691 if (ref instanceof GeneLociI)
693 return (GeneLociI) ref;
701 * Answers the description
706 public String getDescription()
708 return this.description;
715 public int findIndex(int pos)
718 * use a valid, hopefully nearby, cursor if available
720 if (isValidCursor(cursor))
722 return findIndex(pos, cursor);
730 * traverse sequence from the start counting gaps; make a note of
731 * the column of the first residue to save in the cursor
733 while ((i < sequence.length) && (j <= end) && (j <= pos))
735 if (!Comparison.isGap(sequence[i]))
746 if (j == end && j < pos)
751 updateCursor(pos, i, startColumn);
756 * Updates the cursor to the latest found residue and column position
763 * column position of the first sequence residue
765 protected void updateCursor(int residuePos, int column, int startColumn)
768 * preserve end residue column provided cursor was valid
770 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
772 if (residuePos == this.end)
777 cursor = new SequenceCursor(this, residuePos, column, startColumn,
778 endColumn, this.changeCount);
782 * Answers the aligned column position (1..) for the given residue position
783 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
784 * The hint may be left of, at, or to the right of the required position.
790 protected int findIndex(final int pos, SequenceCursor curs)
792 if (!isValidCursor(curs))
795 * wrong or invalidated cursor, compute de novo
797 return findIndex(pos);
800 if (curs.residuePosition == pos)
802 return curs.columnPosition;
806 * move left or right to find pos from hint.position
808 int col = curs.columnPosition - 1; // convert from base 1 to base 0
809 int newPos = curs.residuePosition;
810 int delta = newPos > pos ? -1 : 1;
812 while (newPos != pos)
814 col += delta; // shift one column left or right
819 if (col == sequence.length)
821 col--; // return last column if we failed to reach pos
824 if (!Comparison.isGap(sequence[col]))
830 col++; // convert back to base 1
833 * only update cursor if we found the target position
837 updateCursor(pos, col, curs.firstColumnPosition);
847 public int findPosition(final int column)
850 * use a valid, hopefully nearby, cursor if available
852 if (isValidCursor(cursor))
854 return findPosition(column + 1, cursor);
857 // TODO recode this more naturally i.e. count residues only
858 // as they are found, not 'in anticipation'
861 * traverse the sequence counting gaps; note the column position
862 * of the first residue, to save in the cursor
864 int firstResidueColumn = 0;
865 int lastPosFound = 0;
866 int lastPosFoundColumn = 0;
867 int seqlen = sequence.length;
869 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
871 lastPosFound = start;
872 lastPosFoundColumn = 0;
878 while (j < column && j < seqlen)
880 if (!Comparison.isGap(sequence[j]))
883 lastPosFoundColumn = j;
884 if (pos == this.start)
886 firstResidueColumn = j;
892 if (j < seqlen && !Comparison.isGap(sequence[j]))
895 lastPosFoundColumn = j;
896 if (pos == this.start)
898 firstResidueColumn = j;
903 * update the cursor to the last residue position found (if any)
904 * (converting column position to base 1)
906 if (lastPosFound != 0)
908 updateCursor(lastPosFound, lastPosFoundColumn + 1,
909 firstResidueColumn + 1);
916 * Answers true if the given cursor is not null, is for this sequence object,
917 * and has a token value that matches this object's changeCount, else false.
918 * This allows us to ignore a cursor as 'stale' if the sequence has been
919 * modified since the cursor was created.
924 protected boolean isValidCursor(SequenceCursor curs)
926 if (curs == null || curs.sequence != this || curs.token != changeCount)
931 * sanity check against range
933 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
937 if (curs.residuePosition < start || curs.residuePosition > end)
945 * Answers the sequence position (start..) for the given aligned column
946 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
947 * may lie left of, at, or to the right of the column position.
953 protected int findPosition(final int col, SequenceCursor curs)
955 if (!isValidCursor(curs))
958 * wrong or invalidated cursor, compute de novo
960 return findPosition(col - 1);// ugh back to base 0
963 if (curs.columnPosition == col)
965 cursor = curs; // in case this method becomes public
966 return curs.residuePosition; // easy case :-)
969 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
972 * sequence lies entirely to the left of col
973 * - return last residue + 1
978 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
981 * sequence lies entirely to the right of col
982 * - return first residue
987 // todo could choose closest to col out of column,
988 // firstColumnPosition, lastColumnPosition as a start point
991 * move left or right to find pos from cursor position
993 int firstResidueColumn = curs.firstColumnPosition;
994 int column = curs.columnPosition - 1; // to base 0
995 int newPos = curs.residuePosition;
996 int delta = curs.columnPosition > col ? -1 : 1;
997 boolean gapped = false;
998 int lastFoundPosition = curs.residuePosition;
999 int lastFoundPositionColumn = curs.columnPosition;
1001 while (column != col - 1)
1003 column += delta; // shift one column left or right
1004 if (column < 0 || column == sequence.length)
1008 gapped = Comparison.isGap(sequence[column]);
1012 lastFoundPosition = newPos;
1013 lastFoundPositionColumn = column + 1;
1014 if (lastFoundPosition == this.start)
1016 firstResidueColumn = column + 1;
1021 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1023 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1024 firstResidueColumn);
1028 * hack to give position to the right if on a gap
1029 * or beyond the length of the sequence (see JAL-2562)
1031 if (delta > 0 && (gapped || column >= sequence.length))
1043 public ContiguousI findPositions(int fromColumn, int toColumn)
1045 if (toColumn < fromColumn || fromColumn < 1)
1051 * find the first non-gapped position, if any
1053 int firstPosition = 0;
1054 int col = fromColumn - 1;
1055 int length = sequence.length;
1056 while (col < length && col < toColumn)
1058 if (!Comparison.isGap(sequence[col]))
1060 firstPosition = findPosition(col++);
1066 if (firstPosition == 0)
1072 * find the last non-gapped position
1074 int lastPosition = firstPosition;
1075 while (col < length && col < toColumn)
1077 if (!Comparison.isGap(sequence[col++]))
1083 return new Range(firstPosition, lastPosition);
1087 * Returns an int array where indices correspond to each residue in the
1088 * sequence and the element value gives its position in the alignment
1090 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1091 * residues in SequenceI object
1094 public int[] gapMap()
1096 String seq = jalview.analysis.AlignSeq.extractGaps(
1097 jalview.util.Comparison.GapChars, new String(sequence));
1098 int[] map = new int[seq.length()];
1102 while (j < sequence.length)
1104 if (!jalview.util.Comparison.isGap(sequence[j]))
1116 * Build a bitset corresponding to sequence gaps
1118 * @return a BitSet where set values correspond to gaps in the sequence
1121 public BitSet gapBitset()
1123 BitSet gaps = new BitSet(sequence.length);
1125 while (j < sequence.length)
1127 if (jalview.util.Comparison.isGap(sequence[j]))
1137 public int[] findPositionMap()
1139 int map[] = new int[sequence.length];
1142 int seqlen = sequence.length;
1143 while ((j < seqlen))
1146 if (!jalview.util.Comparison.isGap(sequence[j]))
1157 public List<int[]> getInsertions()
1159 ArrayList<int[]> map = new ArrayList<>();
1160 int lastj = -1, j = 0;
1162 int seqlen = sequence.length;
1163 while ((j < seqlen))
1165 if (jalview.util.Comparison.isGap(sequence[j]))
1176 map.add(new int[] { lastj, j - 1 });
1184 map.add(new int[] { lastj, j - 1 });
1191 public BitSet getInsertionsAsBits()
1193 BitSet map = new BitSet();
1194 int lastj = -1, j = 0;
1196 int seqlen = sequence.length;
1197 while ((j < seqlen))
1199 if (jalview.util.Comparison.isGap(sequence[j]))
1225 public void deleteChars(final int i, final int j)
1227 int newstart = start, newend = end;
1228 if (i >= sequence.length || i < 0)
1233 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1234 boolean createNewDs = false;
1235 // TODO: take a (second look) at the dataset creation validation method for
1236 // the very large sequence case
1238 int startIndex = findIndex(start) - 1;
1239 int endIndex = findIndex(end) - 1;
1240 int startDeleteColumn = -1; // for dataset sequence deletions
1241 int deleteCount = 0;
1243 for (int s = i; s < j && s < sequence.length; s++)
1245 if (Comparison.isGap(sequence[s]))
1250 if (startDeleteColumn == -1)
1252 startDeleteColumn = findPosition(s) - start;
1260 if (startIndex == s)
1263 * deleting characters from start of sequence; new start is the
1264 * sequence position of the next column (position to the right
1265 * if the column position is gapped)
1267 newstart = findPosition(j);
1275 * deleting characters at end of sequence; new end is the sequence
1276 * position of the column before the deletion; subtract 1 if this is
1277 * gapped since findPosition returns the next sequence position
1279 newend = findPosition(i - 1);
1280 if (Comparison.isGap(sequence[i - 1]))
1295 if (createNewDs && this.datasetSequence != null)
1298 * if deletion occured in the middle of the sequence,
1299 * construct a new dataset sequence and delete the residues
1300 * that were deleted from the aligned sequence
1302 Sequence ds = new Sequence(datasetSequence);
1303 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1304 datasetSequence = ds;
1305 // TODO: remove any non-inheritable properties ?
1306 // TODO: create a sequence mapping (since there is a relation here ?)
1315 public void insertCharAt(int i, int length, char c)
1317 char[] tmp = new char[sequence.length + length];
1319 if (i >= sequence.length)
1321 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1322 i = sequence.length;
1326 System.arraycopy(sequence, 0, tmp, 0, i);
1336 if (i < sequence.length)
1338 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1346 public void insertCharAt(int i, char c)
1348 insertCharAt(i, 1, c);
1352 public String getVamsasId()
1358 public void setVamsasId(String id)
1364 public void setDBRefs(DBRefEntry[] dbref)
1366 if (dbrefs == null && datasetSequence != null
1367 && this != datasetSequence)
1369 datasetSequence.setDBRefs(dbref);
1375 DBRefUtils.ensurePrimaries(this);
1380 public DBRefEntry[] getDBRefs()
1382 if (dbrefs == null && datasetSequence != null
1383 && this != datasetSequence)
1385 return datasetSequence.getDBRefs();
1391 public void addDBRef(DBRefEntry entry)
1393 if (datasetSequence != null)
1395 datasetSequence.addDBRef(entry);
1401 dbrefs = new DBRefEntry[0];
1404 for (DBRefEntryI dbr : dbrefs)
1406 if (dbr.updateFrom(entry))
1409 * found a dbref that either matched, or could be
1410 * updated from, the new entry - no need to add it
1417 * extend the array to make room for one more
1419 // TODO use an ArrayList instead
1420 int j = dbrefs.length;
1421 DBRefEntry[] temp = new DBRefEntry[j + 1];
1422 System.arraycopy(dbrefs, 0, temp, 0, j);
1423 temp[temp.length - 1] = entry;
1427 DBRefUtils.ensurePrimaries(this);
1431 public void setDatasetSequence(SequenceI seq)
1435 throw new IllegalArgumentException(
1436 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1438 if (seq != null && seq.getDatasetSequence() != null)
1440 throw new IllegalArgumentException(
1441 "Implementation error: cascading dataset sequences are not allowed.");
1443 datasetSequence = seq;
1447 public SequenceI getDatasetSequence()
1449 return datasetSequence;
1453 public AlignmentAnnotation[] getAnnotation()
1455 return annotation == null ? null
1457 .toArray(new AlignmentAnnotation[annotation.size()]);
1461 public boolean hasAnnotation(AlignmentAnnotation ann)
1463 return annotation == null ? false : annotation.contains(ann);
1467 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1469 if (this.annotation == null)
1471 this.annotation = new Vector<>();
1473 if (!this.annotation.contains(annotation))
1475 this.annotation.addElement(annotation);
1477 annotation.setSequenceRef(this);
1481 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1483 if (this.annotation != null)
1485 this.annotation.removeElement(annotation);
1486 if (this.annotation.size() == 0)
1488 this.annotation = null;
1494 * test if this is a valid candidate for another sequence's dataset sequence.
1497 private boolean isValidDatasetSequence()
1499 if (datasetSequence != null)
1503 for (int i = 0; i < sequence.length; i++)
1505 if (jalview.util.Comparison.isGap(sequence[i]))
1514 public SequenceI deriveSequence()
1516 Sequence seq = null;
1517 if (datasetSequence == null)
1519 if (isValidDatasetSequence())
1521 // Use this as dataset sequence
1522 seq = new Sequence(getName(), "", 1, -1);
1523 seq.setDatasetSequence(this);
1524 seq.initSeqFrom(this, getAnnotation());
1529 // Create a new, valid dataset sequence
1530 createDatasetSequence();
1533 return new Sequence(this);
1536 private boolean _isNa;
1538 private int _seqhash = 0;
1541 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1545 public boolean isProtein()
1547 if (datasetSequence != null)
1549 return datasetSequence.isProtein();
1551 if (_seqhash != sequence.hashCode())
1553 _seqhash = sequence.hashCode();
1554 _isNa = Comparison.isNucleotide(this);
1562 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1565 public SequenceI createDatasetSequence()
1567 if (datasetSequence == null)
1569 Sequence dsseq = new Sequence(getName(),
1570 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1571 getSequenceAsString()),
1572 getStart(), getEnd());
1574 datasetSequence = dsseq;
1576 dsseq.setDescription(description);
1577 // move features and database references onto dataset sequence
1578 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1579 sequenceFeatureStore = null;
1580 dsseq.dbrefs = dbrefs;
1582 // TODO: search and replace any references to this sequence with
1583 // references to the dataset sequence in Mappings on dbref
1584 dsseq.pdbIds = pdbIds;
1586 datasetSequence.updatePDBIds();
1587 if (annotation != null)
1589 // annotation is cloned rather than moved, to preserve what's currently
1591 for (AlignmentAnnotation aa : annotation)
1593 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1594 _aa.sequenceRef = datasetSequence;
1595 _aa.adjustForAlignment(); // uses annotation's own record of
1596 // sequence-column mapping
1597 datasetSequence.addAlignmentAnnotation(_aa);
1601 return datasetSequence;
1608 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1612 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1614 if (annotation != null)
1616 annotation.removeAllElements();
1618 if (annotations != null)
1620 for (int i = 0; i < annotations.length; i++)
1622 if (annotations[i] != null)
1624 addAlignmentAnnotation(annotations[i]);
1631 public AlignmentAnnotation[] getAnnotation(String label)
1633 if (annotation == null || annotation.size() == 0)
1638 Vector<AlignmentAnnotation> subset = new Vector<>();
1639 Enumeration<AlignmentAnnotation> e = annotation.elements();
1640 while (e.hasMoreElements())
1642 AlignmentAnnotation ann = e.nextElement();
1643 if (ann.label != null && ann.label.equals(label))
1645 subset.addElement(ann);
1648 if (subset.size() == 0)
1652 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1654 e = subset.elements();
1655 while (e.hasMoreElements())
1657 anns[i++] = e.nextElement();
1659 subset.removeAllElements();
1664 public boolean updatePDBIds()
1666 if (datasetSequence != null)
1668 // TODO: could merge DBRefs
1669 return datasetSequence.updatePDBIds();
1671 if (dbrefs == null || dbrefs.length == 0)
1675 boolean added = false;
1676 for (DBRefEntry dbr : dbrefs)
1678 if (DBRefSource.PDB.equals(dbr.getSource()))
1681 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1682 * PDB id is not already present in a 'matching' PDBEntry
1683 * Constructor parses out a chain code if appended to the accession id
1684 * (a fudge used to 'store' the chain code in the DBRef)
1686 PDBEntry pdbe = new PDBEntry(dbr);
1687 added |= addPDBId(pdbe);
1694 public void transferAnnotation(SequenceI entry, Mapping mp)
1696 if (datasetSequence != null)
1698 datasetSequence.transferAnnotation(entry, mp);
1701 if (entry.getDatasetSequence() != null)
1703 transferAnnotation(entry.getDatasetSequence(), mp);
1706 // transfer any new features from entry onto sequence
1707 if (entry.getSequenceFeatures() != null)
1710 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1711 for (SequenceFeature feature : sfs)
1713 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1714 : new SequenceFeature[] { new SequenceFeature(feature) };
1717 for (int sfi = 0; sfi < sf.length; sfi++)
1719 addSequenceFeature(sf[sfi]);
1725 // transfer PDB entries
1726 if (entry.getAllPDBEntries() != null)
1728 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1729 while (e.hasMoreElements())
1731 PDBEntry pdb = e.nextElement();
1735 // transfer database references
1736 DBRefEntry[] entryRefs = entry.getDBRefs();
1737 if (entryRefs != null)
1739 for (int r = 0; r < entryRefs.length; r++)
1741 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1742 if (newref.getMap() != null && mp != null)
1744 // remap ref using our local mapping
1746 // we also assume all version string setting is done by dbSourceProxy
1748 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1749 * newref.setSource(dbSource); }
1757 public void setRNA(RNA r)
1769 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1772 List<AlignmentAnnotation> result = new ArrayList<>();
1773 if (this.annotation != null)
1775 for (AlignmentAnnotation ann : annotation)
1777 if (ann.calcId != null && ann.calcId.equals(calcId)
1778 && ann.label != null && ann.label.equals(label))
1788 public String toString()
1790 return getDisplayId(false);
1794 public PDBEntry getPDBEntry(String pdbIdStr)
1796 if (getDatasetSequence() != null)
1798 return getDatasetSequence().getPDBEntry(pdbIdStr);
1804 List<PDBEntry> entries = getAllPDBEntries();
1805 for (PDBEntry entry : entries)
1807 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1816 public List<DBRefEntry> getPrimaryDBRefs()
1818 if (datasetSequence != null)
1820 return datasetSequence.getPrimaryDBRefs();
1822 if (dbrefs == null || dbrefs.length == 0)
1824 return Collections.emptyList();
1826 synchronized (dbrefs)
1828 List<DBRefEntry> primaries = new ArrayList<>();
1829 DBRefEntry[] tmp = new DBRefEntry[1];
1830 for (DBRefEntry ref : dbrefs)
1832 if (!ref.isPrimaryCandidate())
1838 MapList mp = ref.getMap().getMap();
1839 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1841 // map only involves a subsequence, so cannot be primary
1845 // whilst it looks like it is a primary ref, we also sanity check type
1846 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1847 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1849 // PDB dbrefs imply there should be a PDBEntry associated
1850 // TODO: tighten PDB dbrefs
1851 // formally imply Jalview has actually downloaded and
1852 // parsed the pdb file. That means there should be a cached file
1853 // handle on the PDBEntry, and a real mapping between sequence and
1854 // extracted sequence from PDB file
1855 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1856 if (pdbentry != null && pdbentry.getFile() != null)
1862 // check standard protein or dna sources
1864 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1865 if (res != null && res[0] == tmp[0])
1879 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1882 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1883 int endPos = fromColumn == toColumn ? startPos
1884 : findPosition(toColumn - 1);
1886 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1890 * if end column is gapped, endPos may be to the right,
1891 * and we may have included adjacent or enclosing features;
1892 * remove any that are not enclosing, non-contact features
1894 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1895 && Comparison.isGap(sequence[toColumn - 1]);
1896 if (endPos > this.end || endColumnIsGapped)
1898 ListIterator<SequenceFeature> it = result.listIterator();
1899 while (it.hasNext())
1901 SequenceFeature sf = it.next();
1902 int sfBegin = sf.getBegin();
1903 int sfEnd = sf.getEnd();
1904 int featureStartColumn = findIndex(sfBegin);
1905 if (featureStartColumn > toColumn)
1909 else if (featureStartColumn < fromColumn)
1911 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1913 if (featureEndColumn < fromColumn)
1917 else if (featureEndColumn > toColumn && sf.isContactFeature())
1920 * remove an enclosing feature if it is a contact feature
1932 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1933 * token that has to match the one presented by the cursor
1936 public void sequenceChanged()
1945 public int replace(char c1, char c2)
1952 synchronized (sequence)
1954 for (int c = 0; c < sequence.length; c++)
1956 if (sequence[c] == c1)
1972 public String getSequenceStringFromIterator(Iterator<int[]> it)
1974 StringBuilder newSequence = new StringBuilder();
1975 while (it.hasNext())
1977 int[] block = it.next();
1980 newSequence.append(getSequence(block[0], block[1] + 1));
1984 newSequence.append(getSequence(block[0], block[1]));
1988 return newSequence.toString();
1992 public int firstResidueOutsideIterator(Iterator<int[]> regions)
1996 if (!regions.hasNext())
1998 return findIndex(getStart()) - 1;
2001 // Simply walk along the sequence whilst watching for region
2003 int hideStart = getLength();
2005 boolean foundStart = false;
2007 // step through the non-gapped positions of the sequence
2008 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2010 // get alignment position of this residue in the sequence
2011 int p = findIndex(i) - 1;
2013 // update region start/end
2014 while (hideEnd < p && regions.hasNext())
2016 int[] region = regions.next();
2017 hideStart = region[0];
2018 hideEnd = region[1];
2022 hideStart = getLength();
2024 // update boundary for sequence
2036 // otherwise, sequence was completely hidden