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;
31 import jalview.workers.InformationThread;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.BitSet;
36 import java.util.Collections;
37 import java.util.Enumeration;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.ListIterator;
41 import java.util.Vector;
43 import fr.orsay.lri.varna.models.rna.RNA;
47 * Implements the SequenceI interface for a char[] based sequence object
49 public class Sequence extends ASequence implements SequenceI
51 SequenceI datasetSequence;
55 private char[] sequence;
63 HiddenMarkovModel hmm;
65 boolean isHMMConsensusSequence = false;
67 Vector<PDBEntry> pdbIds;
76 * This annotation is displayed below the alignment but the positions are tied
77 * to the residues of this sequence
79 * TODO: change to List<>
81 Vector<AlignmentAnnotation> annotation;
83 private SequenceFeaturesI sequenceFeatureStore;
86 * A cursor holding the approximate current view position to the sequence,
87 * as determined by findIndex or findPosition or findPositions.
88 * Using a cursor as a hint allows these methods to be more performant for
91 private SequenceCursor cursor;
94 * A number that should be incremented whenever the sequence is edited.
95 * If the value matches the cursor token, then we can trust the cursor,
96 * if not then it should be recomputed.
98 private int changeCount;
101 * Creates a new Sequence object.
104 * display name string
106 * string to form a possibly gapped sequence out of
108 * first position of non-gap residue in the sequence
110 * last position of ungapped residues (nearly always only used for
113 public Sequence(String name, String sequence, int start, int end)
116 initSeqAndName(name, sequence.toCharArray(), start, end);
119 public Sequence(String name, char[] sequence, int start, int end)
122 initSeqAndName(name, sequence, start, end);
126 * Stage 1 constructor - assign name, sequence, and set start and end fields.
127 * start and end are updated values from name2 if it ends with /start-end
134 protected void initSeqAndName(String name2, char[] sequence2, int start2,
138 this.sequence = sequence2;
146 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
147 * start and end respectively and removes the suffix from the name
154 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
157 int slashPos = name.lastIndexOf('/');
158 if (slashPos > -1 && slashPos < name.length() - 1)
160 String suffix = name.substring(slashPos + 1);
161 String[] range = suffix.split("-");
162 if (range.length == 2)
166 int from = Integer.valueOf(range[0]);
167 int to = Integer.valueOf(range[1]);
168 if (from > 0 && to >= from)
170 name = name.substring(0, slashPos);
175 } catch (NumberFormatException e)
177 // leave name unchanged if suffix is invalid
184 * Ensures that 'end' is not before the end of the sequence, that is,
185 * (end-start+1) is at least as long as the count of ungapped positions. Note
186 * that end is permitted to be beyond the end of the sequence data.
188 void checkValidRange()
191 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
194 for (int j = 0; j < sequence.length; j++)
196 if (!Comparison.isGap(sequence[j]))
215 * default constructor
219 sequenceFeatureStore = new SequenceFeatures();
223 * Creates a new Sequence object.
230 public Sequence(String name, String sequence)
232 this(name, sequence, 1, -1);
236 * Creates a new Sequence object with new AlignmentAnnotations but inherits
237 * any existing dataset sequence reference. If non exists, everything is
241 * if seq is a dataset sequence, behaves like a plain old copy
244 public Sequence(SequenceI seq)
246 this(seq, seq.getAnnotation());
250 * Create a new sequence object with new features, DBRefEntries, and PDBIds
251 * but inherits any existing dataset sequence reference, and duplicate of any
252 * annotation that is present in the given annotation array.
255 * the sequence to be copied
256 * @param alAnnotation
257 * an array of annotation including some associated with seq
259 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
262 initSeqFrom(seq, alAnnotation);
266 * does the heavy lifting when cloning a dataset sequence, or coping data from
267 * dataset to a new derived sequence.
270 * - source of attributes.
271 * @param alAnnotation
272 * - alignment annotation present on seq that should be copied onto
275 protected void initSeqFrom(SequenceI seq,
276 AlignmentAnnotation[] alAnnotation)
278 char[] oseq = seq.getSequence(); // returns a copy of the array
279 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
281 description = seq.getDescription();
282 if (seq != datasetSequence)
284 setDatasetSequence(seq.getDatasetSequence());
288 * only copy DBRefs and seqfeatures if we really are a dataset sequence
290 if (datasetSequence == null)
292 if (seq.getDBRefs() != null)
294 DBRefEntry[] dbr = seq.getDBRefs();
295 for (int i = 0; i < dbr.length; i++)
297 addDBRef(new DBRefEntry(dbr[i]));
302 * make copies of any sequence features
304 for (SequenceFeature sf : seq.getSequenceFeatures())
306 addSequenceFeature(new SequenceFeature(sf));
310 if (seq.getAnnotation() != null)
312 AlignmentAnnotation[] sqann = seq.getAnnotation();
313 for (int i = 0; i < sqann.length; i++)
315 if (sqann[i] == null)
319 boolean found = (alAnnotation == null);
322 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
324 found = (alAnnotation[apos] == sqann[i]);
329 // only copy the given annotation
330 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
331 addAlignmentAnnotation(newann);
335 if (seq.getAllPDBEntries() != null)
337 Vector<PDBEntry> ids = seq.getAllPDBEntries();
338 for (PDBEntry pdb : ids)
340 this.addPDBId(new PDBEntry(pdb));
343 if (seq.getHMM() != null)
345 this.hmm = new HiddenMarkovModel(seq.getHMM(), this);
351 public void setSequenceFeatures(List<SequenceFeature> features)
353 if (datasetSequence != null)
355 datasetSequence.setSequenceFeatures(features);
358 sequenceFeatureStore = new SequenceFeatures(features);
362 public synchronized boolean addSequenceFeature(SequenceFeature sf)
364 if (sf.getType() == null)
366 System.err.println("SequenceFeature type may not be null: "
371 if (datasetSequence != null)
373 return datasetSequence.addSequenceFeature(sf);
376 return sequenceFeatureStore.add(sf);
380 public void deleteFeature(SequenceFeature sf)
382 if (datasetSequence != null)
384 datasetSequence.deleteFeature(sf);
388 sequenceFeatureStore.delete(sf);
398 public List<SequenceFeature> getSequenceFeatures()
400 if (datasetSequence != null)
402 return datasetSequence.getSequenceFeatures();
404 return sequenceFeatureStore.getAllFeatures();
408 public SequenceFeaturesI getFeatures()
410 return datasetSequence != null ? datasetSequence.getFeatures()
411 : sequenceFeatureStore;
415 public boolean addPDBId(PDBEntry entry)
419 pdbIds = new Vector<>();
424 for (PDBEntry pdbe : pdbIds)
426 if (pdbe.updateFrom(entry))
431 pdbIds.addElement(entry);
442 public void setPDBId(Vector<PDBEntry> id)
450 * @return DOCUMENT ME!
453 public Vector<PDBEntry> getAllPDBEntries()
455 return pdbIds == null ? new Vector<>() : pdbIds;
461 * @return DOCUMENT ME!
464 public String getDisplayId(boolean jvsuffix)
466 StringBuffer result = new StringBuffer(name);
469 result.append("/" + start + "-" + end);
472 return result.toString();
476 * Sets the sequence name. If the name ends in /start-end, then the start-end
477 * values are parsed out and set, and the suffix is removed from the name.
482 public void setName(String theName)
491 * @return DOCUMENT ME!
494 public String getName()
506 public void setStart(int start)
514 * @return DOCUMENT ME!
517 public int getStart()
529 public void setEnd(int end)
537 * @return DOCUMENT ME!
548 * @return DOCUMENT ME!
551 public int getLength()
553 return this.sequence.length;
563 public void setSequence(String seq)
565 this.sequence = seq.toCharArray();
571 public String getSequenceAsString()
573 return new String(sequence);
577 public String getSequenceAsString(int start, int end)
579 return new String(getSequence(start, end));
583 public char[] getSequence()
586 return sequence == null ? null : Arrays.copyOf(sequence,
593 * @see jalview.datamodel.SequenceI#getSequence(int, int)
596 public char[] getSequence(int start, int end)
602 // JBPNote - left to user to pad the result here (TODO:Decide on this
604 if (start >= sequence.length)
609 if (end >= sequence.length)
611 end = sequence.length;
614 char[] reply = new char[end - start];
615 System.arraycopy(sequence, start, reply, 0, end - start);
621 public SequenceI getSubSequence(int start, int end)
627 char[] seq = getSequence(start, end);
632 int nstart = findPosition(start);
633 int nend = findPosition(end) - 1;
634 // JBPNote - this is an incomplete copy.
635 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
636 nseq.setDescription(description);
637 if (datasetSequence != null)
639 nseq.setDatasetSequence(datasetSequence);
643 nseq.setDatasetSequence(this);
649 * Returns the character of the aligned sequence at the given position (base
650 * zero), or space if the position is not within the sequence's bounds
655 public char getCharAt(int i)
657 if (i >= 0 && i < sequence.length)
668 * Sets the sequence description, and also parses out any special formats of
674 public void setDescription(String desc)
676 this.description = desc;
680 public void setGeneLoci(String speciesId, String assemblyId,
681 String chromosomeId, MapList map)
683 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
688 * Returns the gene loci mapping for the sequence (may be null)
693 public GeneLociI getGeneLoci()
695 DBRefEntry[] refs = getDBRefs();
698 for (final DBRefEntry ref : refs)
700 if (ref instanceof GeneLociI)
702 return (GeneLociI) ref;
710 * Answers the description
715 public String getDescription()
717 return this.description;
724 public int findIndex(int pos)
727 * use a valid, hopefully nearby, cursor if available
729 if (isValidCursor(cursor))
731 return findIndex(pos, cursor);
739 * traverse sequence from the start counting gaps; make a note of
740 * the column of the first residue to save in the cursor
742 while ((i < sequence.length) && (j <= end) && (j <= pos))
744 if (!Comparison.isGap(sequence[i]))
755 if (j == end && j < pos)
760 updateCursor(pos, i, startColumn);
765 * Updates the cursor to the latest found residue and column position
772 * column position of the first sequence residue
774 protected void updateCursor(int residuePos, int column, int startColumn)
777 * preserve end residue column provided cursor was valid
779 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
781 if (residuePos == this.end)
786 cursor = new SequenceCursor(this, residuePos, column, startColumn,
787 endColumn, this.changeCount);
791 * Answers the aligned column position (1..) for the given residue position
792 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
793 * The hint may be left of, at, or to the right of the required position.
799 protected int findIndex(final int pos, SequenceCursor curs)
801 if (!isValidCursor(curs))
804 * wrong or invalidated cursor, compute de novo
806 return findIndex(pos);
809 if (curs.residuePosition == pos)
811 return curs.columnPosition;
815 * move left or right to find pos from hint.position
817 int col = curs.columnPosition - 1; // convert from base 1 to base 0
818 int newPos = curs.residuePosition;
819 int delta = newPos > pos ? -1 : 1;
821 while (newPos != pos)
823 col += delta; // shift one column left or right
828 if (col == sequence.length)
830 col--; // return last column if we failed to reach pos
833 if (!Comparison.isGap(sequence[col]))
839 col++; // convert back to base 1
842 * only update cursor if we found the target position
846 updateCursor(pos, col, curs.firstColumnPosition);
856 public int findPosition(final int column)
859 * use a valid, hopefully nearby, cursor if available
861 if (isValidCursor(cursor))
863 return findPosition(column + 1, cursor);
866 // TODO recode this more naturally i.e. count residues only
867 // as they are found, not 'in anticipation'
870 * traverse the sequence counting gaps; note the column position
871 * of the first residue, to save in the cursor
873 int firstResidueColumn = 0;
874 int lastPosFound = 0;
875 int lastPosFoundColumn = 0;
876 int seqlen = sequence.length;
878 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
880 lastPosFound = start;
881 lastPosFoundColumn = 0;
887 while (j < column && j < seqlen)
889 if (!Comparison.isGap(sequence[j]))
892 lastPosFoundColumn = j;
893 if (pos == this.start)
895 firstResidueColumn = j;
901 if (j < seqlen && !Comparison.isGap(sequence[j]))
904 lastPosFoundColumn = j;
905 if (pos == this.start)
907 firstResidueColumn = j;
912 * update the cursor to the last residue position found (if any)
913 * (converting column position to base 1)
915 if (lastPosFound != 0)
917 updateCursor(lastPosFound, lastPosFoundColumn + 1,
918 firstResidueColumn + 1);
925 * Answers true if the given cursor is not null, is for this sequence object,
926 * and has a token value that matches this object's changeCount, else false.
927 * This allows us to ignore a cursor as 'stale' if the sequence has been
928 * modified since the cursor was created.
933 protected boolean isValidCursor(SequenceCursor curs)
935 if (curs == null || curs.sequence != this || curs.token != changeCount)
940 * sanity check against range
942 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
946 if (curs.residuePosition < start || curs.residuePosition > end)
954 * Answers the sequence position (start..) for the given aligned column
955 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
956 * may lie left of, at, or to the right of the column position.
962 protected int findPosition(final int col, SequenceCursor curs)
964 if (!isValidCursor(curs))
967 * wrong or invalidated cursor, compute de novo
969 return findPosition(col - 1);// ugh back to base 0
972 if (curs.columnPosition == col)
974 cursor = curs; // in case this method becomes public
975 return curs.residuePosition; // easy case :-)
978 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
981 * sequence lies entirely to the left of col
982 * - return last residue + 1
987 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
990 * sequence lies entirely to the right of col
991 * - return first residue
996 // todo could choose closest to col out of column,
997 // firstColumnPosition, lastColumnPosition as a start point
1000 * move left or right to find pos from cursor position
1002 int firstResidueColumn = curs.firstColumnPosition;
1003 int column = curs.columnPosition - 1; // to base 0
1004 int newPos = curs.residuePosition;
1005 int delta = curs.columnPosition > col ? -1 : 1;
1006 boolean gapped = false;
1007 int lastFoundPosition = curs.residuePosition;
1008 int lastFoundPositionColumn = curs.columnPosition;
1010 while (column != col - 1)
1012 column += delta; // shift one column left or right
1013 if (column < 0 || column == sequence.length)
1017 gapped = Comparison.isGap(sequence[column]);
1021 lastFoundPosition = newPos;
1022 lastFoundPositionColumn = column + 1;
1023 if (lastFoundPosition == this.start)
1025 firstResidueColumn = column + 1;
1030 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1032 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1033 firstResidueColumn);
1037 * hack to give position to the right if on a gap
1038 * or beyond the length of the sequence (see JAL-2562)
1040 if (delta > 0 && (gapped || column >= sequence.length))
1052 public ContiguousI findPositions(int fromColumn, int toColumn)
1054 if (toColumn < fromColumn || fromColumn < 1)
1060 * find the first non-gapped position, if any
1062 int firstPosition = 0;
1063 int col = fromColumn - 1;
1064 int length = sequence.length;
1065 while (col < length && col < toColumn)
1067 if (!Comparison.isGap(sequence[col]))
1069 firstPosition = findPosition(col++);
1075 if (firstPosition == 0)
1081 * find the last non-gapped position
1083 int lastPosition = firstPosition;
1084 while (col < length && col < toColumn)
1086 if (!Comparison.isGap(sequence[col++]))
1092 return new Range(firstPosition, lastPosition);
1096 * Returns an int array where indices correspond to each residue in the
1097 * sequence and the element value gives its position in the alignment
1099 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1100 * residues in SequenceI object
1103 public int[] gapMap()
1105 String seq = jalview.analysis.AlignSeq.extractGaps(
1106 jalview.util.Comparison.GapChars, new String(sequence));
1107 int[] map = new int[seq.length()];
1111 while (j < sequence.length)
1113 if (!jalview.util.Comparison.isGap(sequence[j]))
1125 * Build a bitset corresponding to sequence gaps
1127 * @return a BitSet where set values correspond to gaps in the sequence
1130 public BitSet gapBitset()
1132 BitSet gaps = new BitSet(sequence.length);
1134 while (j < sequence.length)
1136 if (jalview.util.Comparison.isGap(sequence[j]))
1146 public int[] findPositionMap()
1148 int map[] = new int[sequence.length];
1151 int seqlen = sequence.length;
1152 while ((j < seqlen))
1155 if (!jalview.util.Comparison.isGap(sequence[j]))
1166 public List<int[]> getInsertions()
1168 ArrayList<int[]> map = new ArrayList<>();
1169 int lastj = -1, j = 0;
1171 int seqlen = sequence.length;
1172 while ((j < seqlen))
1174 if (jalview.util.Comparison.isGap(sequence[j]))
1185 map.add(new int[] { lastj, j - 1 });
1193 map.add(new int[] { lastj, j - 1 });
1200 public BitSet getInsertionsAsBits()
1202 BitSet map = new BitSet();
1203 int lastj = -1, j = 0;
1205 int seqlen = sequence.length;
1206 while ((j < seqlen))
1208 if (jalview.util.Comparison.isGap(sequence[j]))
1234 public void deleteChars(final int i, final int j)
1236 int newstart = start, newend = end;
1237 if (i >= sequence.length || i < 0)
1242 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1243 boolean createNewDs = false;
1244 // TODO: take a (second look) at the dataset creation validation method for
1245 // the very large sequence case
1247 int startIndex = findIndex(start) - 1;
1248 int endIndex = findIndex(end) - 1;
1249 int startDeleteColumn = -1; // for dataset sequence deletions
1250 int deleteCount = 0;
1252 for (int s = i; s < j && s < sequence.length; s++)
1254 if (Comparison.isGap(sequence[s]))
1259 if (startDeleteColumn == -1)
1261 startDeleteColumn = findPosition(s) - start;
1269 if (startIndex == s)
1272 * deleting characters from start of sequence; new start is the
1273 * sequence position of the next column (position to the right
1274 * if the column position is gapped)
1276 newstart = findPosition(j);
1284 * deleting characters at end of sequence; new end is the sequence
1285 * position of the column before the deletion; subtract 1 if this is
1286 * gapped since findPosition returns the next sequence position
1288 newend = findPosition(i - 1);
1289 if (Comparison.isGap(sequence[i - 1]))
1304 if (createNewDs && this.datasetSequence != null)
1307 * if deletion occured in the middle of the sequence,
1308 * construct a new dataset sequence and delete the residues
1309 * that were deleted from the aligned sequence
1311 Sequence ds = new Sequence(datasetSequence);
1312 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1313 datasetSequence = ds;
1314 // TODO: remove any non-inheritable properties ?
1315 // TODO: create a sequence mapping (since there is a relation here ?)
1324 public void insertCharAt(int i, int length, char c)
1326 char[] tmp = new char[sequence.length + length];
1328 if (i >= sequence.length)
1330 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1331 i = sequence.length;
1335 System.arraycopy(sequence, 0, tmp, 0, i);
1345 if (i < sequence.length)
1347 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1355 public void insertCharAt(int i, char c)
1357 insertCharAt(i, 1, c);
1361 public String getVamsasId()
1367 public void setVamsasId(String id)
1373 public void setDBRefs(DBRefEntry[] dbref)
1375 if (dbrefs == null && datasetSequence != null
1376 && this != datasetSequence)
1378 datasetSequence.setDBRefs(dbref);
1384 DBRefUtils.ensurePrimaries(this);
1389 public DBRefEntry[] getDBRefs()
1391 if (dbrefs == null && datasetSequence != null
1392 && this != datasetSequence)
1394 return datasetSequence.getDBRefs();
1400 public void addDBRef(DBRefEntry entry)
1402 if (datasetSequence != null)
1404 datasetSequence.addDBRef(entry);
1410 dbrefs = new DBRefEntry[0];
1413 for (DBRefEntryI dbr : dbrefs)
1415 if (dbr.updateFrom(entry))
1418 * found a dbref that either matched, or could be
1419 * updated from, the new entry - no need to add it
1426 * extend the array to make room for one more
1428 // TODO use an ArrayList instead
1429 int j = dbrefs.length;
1430 DBRefEntry[] temp = new DBRefEntry[j + 1];
1431 System.arraycopy(dbrefs, 0, temp, 0, j);
1432 temp[temp.length - 1] = entry;
1436 DBRefUtils.ensurePrimaries(this);
1440 public void setDatasetSequence(SequenceI seq)
1444 throw new IllegalArgumentException(
1445 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1447 if (seq != null && seq.getDatasetSequence() != null)
1449 throw new IllegalArgumentException(
1450 "Implementation error: cascading dataset sequences are not allowed.");
1452 datasetSequence = seq;
1456 public SequenceI getDatasetSequence()
1458 return datasetSequence;
1462 public AlignmentAnnotation[] getAnnotation()
1464 return annotation == null ? null
1466 .toArray(new AlignmentAnnotation[annotation.size()]);
1470 public boolean hasAnnotation(AlignmentAnnotation ann)
1472 return annotation == null ? false : annotation.contains(ann);
1476 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1478 if (this.annotation == null)
1480 this.annotation = new Vector<>();
1482 if (!this.annotation.contains(annotation))
1484 this.annotation.addElement(annotation);
1486 annotation.setSequenceRef(this);
1490 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1492 if (this.annotation != null)
1494 this.annotation.removeElement(annotation);
1495 if (this.annotation.size() == 0)
1497 this.annotation = null;
1503 * test if this is a valid candidate for another sequence's dataset sequence.
1506 private boolean isValidDatasetSequence()
1508 if (datasetSequence != null)
1512 for (int i = 0; i < sequence.length; i++)
1514 if (jalview.util.Comparison.isGap(sequence[i]))
1523 public SequenceI deriveSequence()
1525 Sequence seq = null;
1526 if (datasetSequence == null)
1528 if (isValidDatasetSequence())
1530 // Use this as dataset sequence
1531 seq = new Sequence(getName(), "", 1, -1);
1532 seq.setDatasetSequence(this);
1533 seq.initSeqFrom(this, getAnnotation());
1538 // Create a new, valid dataset sequence
1539 createDatasetSequence();
1542 return new Sequence(this);
1545 private boolean _isNa;
1547 private int _seqhash = 0;
1550 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1554 public boolean isProtein()
1556 if (datasetSequence != null)
1558 return datasetSequence.isProtein();
1560 if (_seqhash != sequence.hashCode())
1562 _seqhash = sequence.hashCode();
1563 _isNa = Comparison.isNucleotide(this);
1571 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1574 public SequenceI createDatasetSequence()
1576 if (datasetSequence == null)
1578 Sequence dsseq = new Sequence(getName(),
1579 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1580 getSequenceAsString()),
1581 getStart(), getEnd());
1583 datasetSequence = dsseq;
1585 dsseq.setDescription(description);
1586 // move features and database references onto dataset sequence
1587 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1588 sequenceFeatureStore = null;
1589 dsseq.dbrefs = dbrefs;
1591 // TODO: search and replace any references to this sequence with
1592 // references to the dataset sequence in Mappings on dbref
1593 dsseq.pdbIds = pdbIds;
1595 datasetSequence.updatePDBIds();
1596 if (annotation != null)
1598 // annotation is cloned rather than moved, to preserve what's currently
1600 for (AlignmentAnnotation aa : annotation)
1602 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1603 _aa.sequenceRef = datasetSequence;
1604 _aa.adjustForAlignment(); // uses annotation's own record of
1605 // sequence-column mapping
1606 datasetSequence.addAlignmentAnnotation(_aa);
1610 return datasetSequence;
1617 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1621 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1623 if (annotation != null)
1625 annotation.removeAllElements();
1627 if (annotations != null)
1629 for (int i = 0; i < annotations.length; i++)
1631 if (annotations[i] != null)
1633 addAlignmentAnnotation(annotations[i]);
1640 public AlignmentAnnotation[] getAnnotation(String label)
1642 if (annotation == null || annotation.size() == 0)
1647 Vector<AlignmentAnnotation> subset = new Vector<>();
1648 Enumeration<AlignmentAnnotation> e = annotation.elements();
1649 while (e.hasMoreElements())
1651 AlignmentAnnotation ann = e.nextElement();
1652 if (ann.label != null && ann.label.equals(label))
1654 subset.addElement(ann);
1657 if (subset.size() == 0)
1661 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1663 e = subset.elements();
1664 while (e.hasMoreElements())
1666 anns[i++] = e.nextElement();
1668 subset.removeAllElements();
1673 public boolean updatePDBIds()
1675 if (datasetSequence != null)
1677 // TODO: could merge DBRefs
1678 return datasetSequence.updatePDBIds();
1680 if (dbrefs == null || dbrefs.length == 0)
1684 boolean added = false;
1685 for (DBRefEntry dbr : dbrefs)
1687 if (DBRefSource.PDB.equals(dbr.getSource()))
1690 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1691 * PDB id is not already present in a 'matching' PDBEntry
1692 * Constructor parses out a chain code if appended to the accession id
1693 * (a fudge used to 'store' the chain code in the DBRef)
1695 PDBEntry pdbe = new PDBEntry(dbr);
1696 added |= addPDBId(pdbe);
1703 public void transferAnnotation(SequenceI entry, Mapping mp)
1705 if (datasetSequence != null)
1707 datasetSequence.transferAnnotation(entry, mp);
1710 if (entry.getDatasetSequence() != null)
1712 transferAnnotation(entry.getDatasetSequence(), mp);
1715 // transfer any new features from entry onto sequence
1716 if (entry.getSequenceFeatures() != null)
1719 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1720 for (SequenceFeature feature : sfs)
1722 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1723 : new SequenceFeature[] { new SequenceFeature(feature) };
1726 for (int sfi = 0; sfi < sf.length; sfi++)
1728 addSequenceFeature(sf[sfi]);
1734 // transfer PDB entries
1735 if (entry.getAllPDBEntries() != null)
1737 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1738 while (e.hasMoreElements())
1740 PDBEntry pdb = e.nextElement();
1744 // transfer database references
1745 DBRefEntry[] entryRefs = entry.getDBRefs();
1746 if (entryRefs != null)
1748 for (int r = 0; r < entryRefs.length; r++)
1750 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1751 if (newref.getMap() != null && mp != null)
1753 // remap ref using our local mapping
1755 // we also assume all version string setting is done by dbSourceProxy
1757 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1758 * newref.setSource(dbSource); }
1766 public void setRNA(RNA r)
1778 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1781 List<AlignmentAnnotation> result = new ArrayList<>();
1782 if (this.annotation != null)
1784 for (AlignmentAnnotation ann : annotation)
1786 String id = ann.getCalcId();
1787 if (id != null && id.equals(calcId)
1788 && ann.label != null && ann.label.equals(label))
1798 public String toString()
1800 return getDisplayId(false);
1804 public PDBEntry getPDBEntry(String pdbIdStr)
1806 if (getDatasetSequence() != null)
1808 return getDatasetSequence().getPDBEntry(pdbIdStr);
1814 List<PDBEntry> entries = getAllPDBEntries();
1815 for (PDBEntry entry : entries)
1817 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1826 public List<DBRefEntry> getPrimaryDBRefs()
1828 if (datasetSequence != null)
1830 return datasetSequence.getPrimaryDBRefs();
1832 if (dbrefs == null || dbrefs.length == 0)
1834 return Collections.emptyList();
1836 synchronized (dbrefs)
1838 List<DBRefEntry> primaries = new ArrayList<>();
1839 DBRefEntry[] tmp = new DBRefEntry[1];
1840 for (DBRefEntry ref : dbrefs)
1842 if (!ref.isPrimaryCandidate())
1848 MapList mp = ref.getMap().getMap();
1849 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1851 // map only involves a subsequence, so cannot be primary
1855 // whilst it looks like it is a primary ref, we also sanity check type
1856 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1857 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1859 // PDB dbrefs imply there should be a PDBEntry associated
1860 // TODO: tighten PDB dbrefs
1861 // formally imply Jalview has actually downloaded and
1862 // parsed the pdb file. That means there should be a cached file
1863 // handle on the PDBEntry, and a real mapping between sequence and
1864 // extracted sequence from PDB file
1865 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1866 if (pdbentry != null && pdbentry.getFile() != null)
1872 // check standard protein or dna sources
1874 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1875 if (res != null && res[0] == tmp[0])
1886 public HiddenMarkovModel getHMM()
1892 public void setHMM(HiddenMarkovModel hmm)
1898 public boolean hasHMMAnnotation()
1900 if (this.annotation == null) {
1903 for (AlignmentAnnotation ann : annotation)
1905 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1917 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1920 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1921 int endPos = fromColumn == toColumn ? startPos
1922 : findPosition(toColumn - 1);
1924 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1926 if (datasetSequence != null)
1928 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1933 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1937 * if end column is gapped, endPos may be to the right,
1938 * and we may have included adjacent or enclosing features;
1939 * remove any that are not enclosing, non-contact features
1941 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1942 && Comparison.isGap(sequence[toColumn - 1]);
1943 if (endPos > this.end || endColumnIsGapped)
1945 ListIterator<SequenceFeature> it = result.listIterator();
1946 while (it.hasNext())
1948 SequenceFeature sf = it.next();
1949 int sfBegin = sf.getBegin();
1950 int sfEnd = sf.getEnd();
1951 int featureStartColumn = findIndex(sfBegin);
1952 if (featureStartColumn > toColumn)
1956 else if (featureStartColumn < fromColumn)
1958 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1960 if (featureEndColumn < fromColumn)
1964 else if (featureEndColumn > toColumn && sf.isContactFeature())
1967 * remove an enclosing feature if it is a contact feature
1979 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1980 * token that has to match the one presented by the cursor
1983 public void sequenceChanged()
1992 public int replace(char c1, char c2)
1999 synchronized (sequence)
2001 for (int c = 0; c < sequence.length; c++)
2003 if (sequence[c] == c1)
2019 public String getSequenceStringFromIterator(Iterator<int[]> it)
2021 StringBuilder newSequence = new StringBuilder();
2022 while (it.hasNext())
2024 int[] block = it.next();
2027 newSequence.append(getSequence(block[0], block[1] + 1));
2031 newSequence.append(getSequence(block[0], block[1]));
2035 return newSequence.toString();
2039 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2043 if (!regions.hasNext())
2045 return findIndex(getStart()) - 1;
2048 // Simply walk along the sequence whilst watching for region
2050 int hideStart = getLength();
2052 boolean foundStart = false;
2054 // step through the non-gapped positions of the sequence
2055 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2057 // get alignment position of this residue in the sequence
2058 int p = findIndex(i) - 1;
2060 // update region start/end
2061 while (hideEnd < p && regions.hasNext())
2063 int[] region = regions.next();
2064 hideStart = region[0];
2065 hideEnd = region[1];
2069 hideStart = getLength();
2071 // update boundary for sequence
2083 // otherwise, sequence was completely hidden
2088 public boolean hasHMMProfile()