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;
459 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
464 public String getDisplayId(boolean jvsuffix)
470 StringBuilder result = new StringBuilder(name);
471 result.append("/").append(start).append("-").append(end);
473 return result.toString();
477 * Sets the sequence name. If the name ends in /start-end, then the start-end
478 * values are parsed out and set, and the suffix is removed from the name.
483 public void setName(String theName)
492 * @return DOCUMENT ME!
495 public String getName()
507 public void setStart(int start)
515 * @return DOCUMENT ME!
518 public int getStart()
530 public void setEnd(int end)
538 * @return DOCUMENT ME!
549 * @return DOCUMENT ME!
552 public int getLength()
554 return this.sequence.length;
564 public void setSequence(String seq)
566 this.sequence = seq.toCharArray();
572 public String getSequenceAsString()
574 return new String(sequence);
578 public String getSequenceAsString(int start, int end)
580 return new String(getSequence(start, end));
584 public char[] getSequence()
587 return sequence == null ? null : Arrays.copyOf(sequence,
594 * @see jalview.datamodel.SequenceI#getSequence(int, int)
597 public char[] getSequence(int start, int end)
603 // JBPNote - left to user to pad the result here (TODO:Decide on this
605 if (start >= sequence.length)
610 if (end >= sequence.length)
612 end = sequence.length;
615 char[] reply = new char[end - start];
616 System.arraycopy(sequence, start, reply, 0, end - start);
622 public SequenceI getSubSequence(int start, int end)
628 char[] seq = getSequence(start, end);
633 int nstart = findPosition(start);
634 int nend = findPosition(end) - 1;
635 // JBPNote - this is an incomplete copy.
636 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
637 nseq.setDescription(description);
638 if (datasetSequence != null)
640 nseq.setDatasetSequence(datasetSequence);
644 nseq.setDatasetSequence(this);
650 * Returns the character of the aligned sequence at the given position (base
651 * zero), or space if the position is not within the sequence's bounds
656 public char getCharAt(int i)
658 if (i >= 0 && i < sequence.length)
669 * Sets the sequence description, and also parses out any special formats of
675 public void setDescription(String desc)
677 this.description = desc;
681 public void setGeneLoci(String speciesId, String assemblyId,
682 String chromosomeId, MapList map)
684 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
689 * Returns the gene loci mapping for the sequence (may be null)
694 public GeneLociI getGeneLoci()
696 DBRefEntry[] refs = getDBRefs();
699 for (final DBRefEntry ref : refs)
701 if (ref instanceof GeneLociI)
703 return (GeneLociI) ref;
711 * Answers the description
716 public String getDescription()
718 return this.description;
725 public int findIndex(int pos)
728 * use a valid, hopefully nearby, cursor if available
730 if (isValidCursor(cursor))
732 return findIndex(pos, cursor);
740 * traverse sequence from the start counting gaps; make a note of
741 * the column of the first residue to save in the cursor
743 while ((i < sequence.length) && (j <= end) && (j <= pos))
745 if (!Comparison.isGap(sequence[i]))
756 if (j == end && j < pos)
761 updateCursor(pos, i, startColumn);
766 * Updates the cursor to the latest found residue and column position
773 * column position of the first sequence residue
775 protected void updateCursor(int residuePos, int column, int startColumn)
778 * preserve end residue column provided cursor was valid
780 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
782 if (residuePos == this.end)
787 cursor = new SequenceCursor(this, residuePos, column, startColumn,
788 endColumn, this.changeCount);
792 * Answers the aligned column position (1..) for the given residue position
793 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
794 * The hint may be left of, at, or to the right of the required position.
800 protected int findIndex(final int pos, SequenceCursor curs)
802 if (!isValidCursor(curs))
805 * wrong or invalidated cursor, compute de novo
807 return findIndex(pos);
810 if (curs.residuePosition == pos)
812 return curs.columnPosition;
816 * move left or right to find pos from hint.position
818 int col = curs.columnPosition - 1; // convert from base 1 to base 0
819 int newPos = curs.residuePosition;
820 int delta = newPos > pos ? -1 : 1;
822 while (newPos != pos)
824 col += delta; // shift one column left or right
829 if (col == sequence.length)
831 col--; // return last column if we failed to reach pos
834 if (!Comparison.isGap(sequence[col]))
840 col++; // convert back to base 1
843 * only update cursor if we found the target position
847 updateCursor(pos, col, curs.firstColumnPosition);
857 public int findPosition(final int column)
860 * use a valid, hopefully nearby, cursor if available
862 if (isValidCursor(cursor))
864 return findPosition(column + 1, cursor);
867 // TODO recode this more naturally i.e. count residues only
868 // as they are found, not 'in anticipation'
871 * traverse the sequence counting gaps; note the column position
872 * of the first residue, to save in the cursor
874 int firstResidueColumn = 0;
875 int lastPosFound = 0;
876 int lastPosFoundColumn = 0;
877 int seqlen = sequence.length;
879 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
881 lastPosFound = start;
882 lastPosFoundColumn = 0;
888 while (j < column && j < seqlen)
890 if (!Comparison.isGap(sequence[j]))
893 lastPosFoundColumn = j;
894 if (pos == this.start)
896 firstResidueColumn = j;
902 if (j < seqlen && !Comparison.isGap(sequence[j]))
905 lastPosFoundColumn = j;
906 if (pos == this.start)
908 firstResidueColumn = j;
913 * update the cursor to the last residue position found (if any)
914 * (converting column position to base 1)
916 if (lastPosFound != 0)
918 updateCursor(lastPosFound, lastPosFoundColumn + 1,
919 firstResidueColumn + 1);
926 * Answers true if the given cursor is not null, is for this sequence object,
927 * and has a token value that matches this object's changeCount, else false.
928 * This allows us to ignore a cursor as 'stale' if the sequence has been
929 * modified since the cursor was created.
934 protected boolean isValidCursor(SequenceCursor curs)
936 if (curs == null || curs.sequence != this || curs.token != changeCount)
941 * sanity check against range
943 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
947 if (curs.residuePosition < start || curs.residuePosition > end)
955 * Answers the sequence position (start..) for the given aligned column
956 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
957 * may lie left of, at, or to the right of the column position.
963 protected int findPosition(final int col, SequenceCursor curs)
965 if (!isValidCursor(curs))
968 * wrong or invalidated cursor, compute de novo
970 return findPosition(col - 1);// ugh back to base 0
973 if (curs.columnPosition == col)
975 cursor = curs; // in case this method becomes public
976 return curs.residuePosition; // easy case :-)
979 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
982 * sequence lies entirely to the left of col
983 * - return last residue + 1
988 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
991 * sequence lies entirely to the right of col
992 * - return first residue
997 // todo could choose closest to col out of column,
998 // firstColumnPosition, lastColumnPosition as a start point
1001 * move left or right to find pos from cursor position
1003 int firstResidueColumn = curs.firstColumnPosition;
1004 int column = curs.columnPosition - 1; // to base 0
1005 int newPos = curs.residuePosition;
1006 int delta = curs.columnPosition > col ? -1 : 1;
1007 boolean gapped = false;
1008 int lastFoundPosition = curs.residuePosition;
1009 int lastFoundPositionColumn = curs.columnPosition;
1011 while (column != col - 1)
1013 column += delta; // shift one column left or right
1014 if (column < 0 || column == sequence.length)
1018 gapped = Comparison.isGap(sequence[column]);
1022 lastFoundPosition = newPos;
1023 lastFoundPositionColumn = column + 1;
1024 if (lastFoundPosition == this.start)
1026 firstResidueColumn = column + 1;
1031 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1033 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1034 firstResidueColumn);
1038 * hack to give position to the right if on a gap
1039 * or beyond the length of the sequence (see JAL-2562)
1041 if (delta > 0 && (gapped || column >= sequence.length))
1053 public ContiguousI findPositions(int fromColumn, int toColumn)
1055 if (toColumn < fromColumn || fromColumn < 1)
1061 * find the first non-gapped position, if any
1063 int firstPosition = 0;
1064 int col = fromColumn - 1;
1065 int length = sequence.length;
1066 while (col < length && col < toColumn)
1068 if (!Comparison.isGap(sequence[col]))
1070 firstPosition = findPosition(col++);
1076 if (firstPosition == 0)
1082 * find the last non-gapped position
1084 int lastPosition = firstPosition;
1085 while (col < length && col < toColumn)
1087 if (!Comparison.isGap(sequence[col++]))
1093 return new Range(firstPosition, lastPosition);
1097 * Returns an int array where indices correspond to each residue in the
1098 * sequence and the element value gives its position in the alignment
1100 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1101 * residues in SequenceI object
1104 public int[] gapMap()
1106 String seq = jalview.analysis.AlignSeq.extractGaps(
1107 jalview.util.Comparison.GapChars, new String(sequence));
1108 int[] map = new int[seq.length()];
1112 while (j < sequence.length)
1114 if (!jalview.util.Comparison.isGap(sequence[j]))
1126 * Build a bitset corresponding to sequence gaps
1128 * @return a BitSet where set values correspond to gaps in the sequence
1131 public BitSet gapBitset()
1133 BitSet gaps = new BitSet(sequence.length);
1135 while (j < sequence.length)
1137 if (jalview.util.Comparison.isGap(sequence[j]))
1147 public int[] findPositionMap()
1149 int map[] = new int[sequence.length];
1152 int seqlen = sequence.length;
1153 while ((j < seqlen))
1156 if (!jalview.util.Comparison.isGap(sequence[j]))
1167 public List<int[]> getInsertions()
1169 ArrayList<int[]> map = new ArrayList<>();
1170 int lastj = -1, j = 0;
1172 int seqlen = sequence.length;
1173 while ((j < seqlen))
1175 if (jalview.util.Comparison.isGap(sequence[j]))
1186 map.add(new int[] { lastj, j - 1 });
1194 map.add(new int[] { lastj, j - 1 });
1201 public BitSet getInsertionsAsBits()
1203 BitSet map = new BitSet();
1204 int lastj = -1, j = 0;
1206 int seqlen = sequence.length;
1207 while ((j < seqlen))
1209 if (jalview.util.Comparison.isGap(sequence[j]))
1235 public void deleteChars(final int i, final int j)
1237 int newstart = start, newend = end;
1238 if (i >= sequence.length || i < 0)
1243 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1244 boolean createNewDs = false;
1245 // TODO: take a (second look) at the dataset creation validation method for
1246 // the very large sequence case
1248 int startIndex = findIndex(start) - 1;
1249 int endIndex = findIndex(end) - 1;
1250 int startDeleteColumn = -1; // for dataset sequence deletions
1251 int deleteCount = 0;
1253 for (int s = i; s < j && s < sequence.length; s++)
1255 if (Comparison.isGap(sequence[s]))
1260 if (startDeleteColumn == -1)
1262 startDeleteColumn = findPosition(s) - start;
1270 if (startIndex == s)
1273 * deleting characters from start of sequence; new start is the
1274 * sequence position of the next column (position to the right
1275 * if the column position is gapped)
1277 newstart = findPosition(j);
1285 * deleting characters at end of sequence; new end is the sequence
1286 * position of the column before the deletion; subtract 1 if this is
1287 * gapped since findPosition returns the next sequence position
1289 newend = findPosition(i - 1);
1290 if (Comparison.isGap(sequence[i - 1]))
1305 if (createNewDs && this.datasetSequence != null)
1308 * if deletion occured in the middle of the sequence,
1309 * construct a new dataset sequence and delete the residues
1310 * that were deleted from the aligned sequence
1312 Sequence ds = new Sequence(datasetSequence);
1313 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1314 datasetSequence = ds;
1315 // TODO: remove any non-inheritable properties ?
1316 // TODO: create a sequence mapping (since there is a relation here ?)
1325 public void insertCharAt(int i, int length, char c)
1327 char[] tmp = new char[sequence.length + length];
1329 if (i >= sequence.length)
1331 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1332 i = sequence.length;
1336 System.arraycopy(sequence, 0, tmp, 0, i);
1346 if (i < sequence.length)
1348 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1356 public void insertCharAt(int i, char c)
1358 insertCharAt(i, 1, c);
1362 public String getVamsasId()
1368 public void setVamsasId(String id)
1374 public void setDBRefs(DBRefEntry[] dbref)
1376 if (dbrefs == null && datasetSequence != null
1377 && this != datasetSequence)
1379 datasetSequence.setDBRefs(dbref);
1385 DBRefUtils.ensurePrimaries(this);
1390 public DBRefEntry[] getDBRefs()
1392 if (dbrefs == null && datasetSequence != null
1393 && this != datasetSequence)
1395 return datasetSequence.getDBRefs();
1401 public void addDBRef(DBRefEntry entry)
1403 if (datasetSequence != null)
1405 datasetSequence.addDBRef(entry);
1411 dbrefs = new DBRefEntry[0];
1414 for (DBRefEntryI dbr : dbrefs)
1416 if (dbr.updateFrom(entry))
1419 * found a dbref that either matched, or could be
1420 * updated from, the new entry - no need to add it
1427 * extend the array to make room for one more
1429 // TODO use an ArrayList instead
1430 int j = dbrefs.length;
1431 DBRefEntry[] temp = new DBRefEntry[j + 1];
1432 System.arraycopy(dbrefs, 0, temp, 0, j);
1433 temp[temp.length - 1] = entry;
1437 DBRefUtils.ensurePrimaries(this);
1441 public void setDatasetSequence(SequenceI seq)
1445 throw new IllegalArgumentException(
1446 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1448 if (seq != null && seq.getDatasetSequence() != null)
1450 throw new IllegalArgumentException(
1451 "Implementation error: cascading dataset sequences are not allowed.");
1453 datasetSequence = seq;
1457 public SequenceI getDatasetSequence()
1459 return datasetSequence;
1463 public AlignmentAnnotation[] getAnnotation()
1465 return annotation == null ? null
1467 .toArray(new AlignmentAnnotation[annotation.size()]);
1471 public boolean hasAnnotation(AlignmentAnnotation ann)
1473 return annotation == null ? false : annotation.contains(ann);
1477 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1479 if (this.annotation == null)
1481 this.annotation = new Vector<>();
1483 if (!this.annotation.contains(annotation))
1485 this.annotation.addElement(annotation);
1487 annotation.setSequenceRef(this);
1491 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1493 if (this.annotation != null)
1495 this.annotation.removeElement(annotation);
1496 if (this.annotation.size() == 0)
1498 this.annotation = null;
1504 * test if this is a valid candidate for another sequence's dataset sequence.
1507 private boolean isValidDatasetSequence()
1509 if (datasetSequence != null)
1513 for (int i = 0; i < sequence.length; i++)
1515 if (jalview.util.Comparison.isGap(sequence[i]))
1524 public SequenceI deriveSequence()
1526 Sequence seq = null;
1527 if (datasetSequence == null)
1529 if (isValidDatasetSequence())
1531 // Use this as dataset sequence
1532 seq = new Sequence(getName(), "", 1, -1);
1533 seq.setDatasetSequence(this);
1534 seq.initSeqFrom(this, getAnnotation());
1539 // Create a new, valid dataset sequence
1540 createDatasetSequence();
1543 return new Sequence(this);
1546 private boolean _isNa;
1548 private int _seqhash = 0;
1551 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1555 public boolean isProtein()
1557 if (datasetSequence != null)
1559 return datasetSequence.isProtein();
1561 if (_seqhash != sequence.hashCode())
1563 _seqhash = sequence.hashCode();
1564 _isNa = Comparison.isNucleotide(this);
1572 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1575 public SequenceI createDatasetSequence()
1577 if (datasetSequence == null)
1579 Sequence dsseq = new Sequence(getName(),
1580 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1581 getSequenceAsString()),
1582 getStart(), getEnd());
1584 datasetSequence = dsseq;
1586 dsseq.setDescription(description);
1587 // move features and database references onto dataset sequence
1588 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1589 sequenceFeatureStore = null;
1590 dsseq.dbrefs = dbrefs;
1592 // TODO: search and replace any references to this sequence with
1593 // references to the dataset sequence in Mappings on dbref
1594 dsseq.pdbIds = pdbIds;
1596 datasetSequence.updatePDBIds();
1597 if (annotation != null)
1599 // annotation is cloned rather than moved, to preserve what's currently
1601 for (AlignmentAnnotation aa : annotation)
1603 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1604 _aa.sequenceRef = datasetSequence;
1605 _aa.adjustForAlignment(); // uses annotation's own record of
1606 // sequence-column mapping
1607 datasetSequence.addAlignmentAnnotation(_aa);
1611 return datasetSequence;
1618 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1622 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1624 if (annotation != null)
1626 annotation.removeAllElements();
1628 if (annotations != null)
1630 for (int i = 0; i < annotations.length; i++)
1632 if (annotations[i] != null)
1634 addAlignmentAnnotation(annotations[i]);
1641 public AlignmentAnnotation[] getAnnotation(String label)
1643 if (annotation == null || annotation.size() == 0)
1648 Vector<AlignmentAnnotation> subset = new Vector<>();
1649 Enumeration<AlignmentAnnotation> e = annotation.elements();
1650 while (e.hasMoreElements())
1652 AlignmentAnnotation ann = e.nextElement();
1653 if (ann.label != null && ann.label.equals(label))
1655 subset.addElement(ann);
1658 if (subset.size() == 0)
1662 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1664 e = subset.elements();
1665 while (e.hasMoreElements())
1667 anns[i++] = e.nextElement();
1669 subset.removeAllElements();
1674 public boolean updatePDBIds()
1676 if (datasetSequence != null)
1678 // TODO: could merge DBRefs
1679 return datasetSequence.updatePDBIds();
1681 if (dbrefs == null || dbrefs.length == 0)
1685 boolean added = false;
1686 for (DBRefEntry dbr : dbrefs)
1688 if (DBRefSource.PDB.equals(dbr.getSource()))
1691 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1692 * PDB id is not already present in a 'matching' PDBEntry
1693 * Constructor parses out a chain code if appended to the accession id
1694 * (a fudge used to 'store' the chain code in the DBRef)
1696 PDBEntry pdbe = new PDBEntry(dbr);
1697 added |= addPDBId(pdbe);
1704 public void transferAnnotation(SequenceI entry, Mapping mp)
1706 if (datasetSequence != null)
1708 datasetSequence.transferAnnotation(entry, mp);
1711 if (entry.getDatasetSequence() != null)
1713 transferAnnotation(entry.getDatasetSequence(), mp);
1716 // transfer any new features from entry onto sequence
1717 if (entry.getSequenceFeatures() != null)
1720 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1721 for (SequenceFeature feature : sfs)
1723 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1724 : new SequenceFeature[] { new SequenceFeature(feature) };
1727 for (int sfi = 0; sfi < sf.length; sfi++)
1729 addSequenceFeature(sf[sfi]);
1735 // transfer PDB entries
1736 if (entry.getAllPDBEntries() != null)
1738 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1739 while (e.hasMoreElements())
1741 PDBEntry pdb = e.nextElement();
1745 // transfer database references
1746 DBRefEntry[] entryRefs = entry.getDBRefs();
1747 if (entryRefs != null)
1749 for (int r = 0; r < entryRefs.length; r++)
1751 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1752 if (newref.getMap() != null && mp != null)
1754 // remap ref using our local mapping
1756 // we also assume all version string setting is done by dbSourceProxy
1758 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1759 * newref.setSource(dbSource); }
1767 public void setRNA(RNA r)
1779 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1782 List<AlignmentAnnotation> result = new ArrayList<>();
1783 if (this.annotation != null)
1785 for (AlignmentAnnotation ann : annotation)
1787 String id = ann.getCalcId();
1788 if (id != null && id.equals(calcId)
1789 && ann.label != null && ann.label.equals(label))
1799 public String toString()
1801 return getDisplayId(false);
1805 public PDBEntry getPDBEntry(String pdbIdStr)
1807 if (getDatasetSequence() != null)
1809 return getDatasetSequence().getPDBEntry(pdbIdStr);
1815 List<PDBEntry> entries = getAllPDBEntries();
1816 for (PDBEntry entry : entries)
1818 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1827 public List<DBRefEntry> getPrimaryDBRefs()
1829 if (datasetSequence != null)
1831 return datasetSequence.getPrimaryDBRefs();
1833 if (dbrefs == null || dbrefs.length == 0)
1835 return Collections.emptyList();
1837 synchronized (dbrefs)
1839 List<DBRefEntry> primaries = new ArrayList<>();
1840 DBRefEntry[] tmp = new DBRefEntry[1];
1841 for (DBRefEntry ref : dbrefs)
1843 if (!ref.isPrimaryCandidate())
1849 MapList mp = ref.getMap().getMap();
1850 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1852 // map only involves a subsequence, so cannot be primary
1856 // whilst it looks like it is a primary ref, we also sanity check type
1857 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1858 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1860 // PDB dbrefs imply there should be a PDBEntry associated
1861 // TODO: tighten PDB dbrefs
1862 // formally imply Jalview has actually downloaded and
1863 // parsed the pdb file. That means there should be a cached file
1864 // handle on the PDBEntry, and a real mapping between sequence and
1865 // extracted sequence from PDB file
1866 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1867 if (pdbentry != null && pdbentry.getFile() != null)
1873 // check standard protein or dna sources
1875 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1876 if (res != null && res[0] == tmp[0])
1887 public HiddenMarkovModel getHMM()
1893 public void setHMM(HiddenMarkovModel hmm)
1899 public boolean hasHMMAnnotation()
1901 if (this.annotation == null) {
1904 for (AlignmentAnnotation ann : annotation)
1906 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1918 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1921 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1922 int endPos = fromColumn == toColumn ? startPos
1923 : findPosition(toColumn - 1);
1925 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1927 if (datasetSequence != null)
1929 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1934 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1938 * if end column is gapped, endPos may be to the right,
1939 * and we may have included adjacent or enclosing features;
1940 * remove any that are not enclosing, non-contact features
1942 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1943 && Comparison.isGap(sequence[toColumn - 1]);
1944 if (endPos > this.end || endColumnIsGapped)
1946 ListIterator<SequenceFeature> it = result.listIterator();
1947 while (it.hasNext())
1949 SequenceFeature sf = it.next();
1950 int sfBegin = sf.getBegin();
1951 int sfEnd = sf.getEnd();
1952 int featureStartColumn = findIndex(sfBegin);
1953 if (featureStartColumn > toColumn)
1957 else if (featureStartColumn < fromColumn)
1959 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1961 if (featureEndColumn < fromColumn)
1965 else if (featureEndColumn > toColumn && sf.isContactFeature())
1968 * remove an enclosing feature if it is a contact feature
1980 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1981 * token that has to match the one presented by the cursor
1984 public void sequenceChanged()
1993 public int replace(char c1, char c2)
2000 synchronized (sequence)
2002 for (int c = 0; c < sequence.length; c++)
2004 if (sequence[c] == c1)
2020 public String getSequenceStringFromIterator(Iterator<int[]> it)
2022 StringBuilder newSequence = new StringBuilder();
2023 while (it.hasNext())
2025 int[] block = it.next();
2028 newSequence.append(getSequence(block[0], block[1] + 1));
2032 newSequence.append(getSequence(block[0], block[1]));
2036 return newSequence.toString();
2040 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2044 if (!regions.hasNext())
2046 return findIndex(getStart()) - 1;
2049 // Simply walk along the sequence whilst watching for region
2051 int hideStart = getLength();
2053 boolean foundStart = false;
2055 // step through the non-gapped positions of the sequence
2056 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2058 // get alignment position of this residue in the sequence
2059 int p = findIndex(i) - 1;
2061 // update region start/end
2062 while (hideEnd < p && regions.hasNext())
2064 int[] region = regions.next();
2065 hideStart = region[0];
2066 hideEnd = region[1];
2070 hideStart = getLength();
2072 // update boundary for sequence
2084 // otherwise, sequence was completely hidden
2089 public boolean hasHMMProfile()