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.
52 public class Sequence extends ASequence implements SequenceI
54 SequenceI datasetSequence;
58 private char[] sequence;
66 HiddenMarkovModel hmm;
68 boolean isHMMConsensusSequence = false;
70 Vector<PDBEntry> pdbIds;
79 * This annotation is displayed below the alignment but the positions are tied
80 * to the residues of this sequence
82 * TODO: change to List<>
84 Vector<AlignmentAnnotation> annotation;
86 private SequenceFeaturesI sequenceFeatureStore;
89 * A cursor holding the approximate current view position to the sequence,
90 * as determined by findIndex or findPosition or findPositions.
91 * Using a cursor as a hint allows these methods to be more performant for
94 private SequenceCursor cursor;
97 * A number that should be incremented whenever the sequence is edited.
98 * If the value matches the cursor token, then we can trust the cursor,
99 * if not then it should be recomputed.
101 private int changeCount;
104 * Creates a new Sequence object.
107 * display name string
109 * string to form a possibly gapped sequence out of
111 * first position of non-gap residue in the sequence
113 * last position of ungapped residues (nearly always only used for
116 public Sequence(String name, String sequence, int start, int end)
119 initSeqAndName(name, sequence.toCharArray(), start, end);
122 public Sequence(String name, char[] sequence, int start, int end)
125 initSeqAndName(name, sequence, start, end);
129 * Stage 1 constructor - assign name, sequence, and set start and end fields.
130 * start and end are updated values from name2 if it ends with /start-end
137 protected void initSeqAndName(String name2, char[] sequence2, int start2,
141 this.sequence = sequence2;
149 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
150 * start and end respectively and removes the suffix from the name
157 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
160 int slashPos = name.lastIndexOf('/');
161 if (slashPos > -1 && slashPos < name.length() - 1)
163 String suffix = name.substring(slashPos + 1);
164 String[] range = suffix.split("-");
165 if (range.length == 2)
169 int from = Integer.valueOf(range[0]);
170 int to = Integer.valueOf(range[1]);
171 if (from > 0 && to >= from)
173 name = name.substring(0, slashPos);
178 } catch (NumberFormatException e)
180 // leave name unchanged if suffix is invalid
187 * Ensures that 'end' is not before the end of the sequence, that is,
188 * (end-start+1) is at least as long as the count of ungapped positions. Note
189 * that end is permitted to be beyond the end of the sequence data.
191 void checkValidRange()
194 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
197 for (int j = 0; j < sequence.length; j++)
199 if (!Comparison.isGap(sequence[j]))
218 * default constructor
222 sequenceFeatureStore = new SequenceFeatures();
226 * Creates a new Sequence object.
233 public Sequence(String name, String sequence)
235 this(name, sequence, 1, -1);
239 * Creates a new Sequence object with new AlignmentAnnotations but inherits
240 * any existing dataset sequence reference. If non exists, everything is
244 * if seq is a dataset sequence, behaves like a plain old copy
247 public Sequence(SequenceI seq)
249 this(seq, seq.getAnnotation());
253 * Create a new sequence object with new features, DBRefEntries, and PDBIds
254 * but inherits any existing dataset sequence reference, and duplicate of any
255 * annotation that is present in the given annotation array.
258 * the sequence to be copied
259 * @param alAnnotation
260 * an array of annotation including some associated with seq
262 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
265 initSeqFrom(seq, alAnnotation);
269 * does the heavy lifting when cloning a dataset sequence, or coping data from
270 * dataset to a new derived sequence.
273 * - source of attributes.
274 * @param alAnnotation
275 * - alignment annotation present on seq that should be copied onto
278 protected void initSeqFrom(SequenceI seq,
279 AlignmentAnnotation[] alAnnotation)
281 char[] oseq = seq.getSequence(); // returns a copy of the array
282 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
284 description = seq.getDescription();
285 if (seq != datasetSequence)
287 setDatasetSequence(seq.getDatasetSequence());
291 * only copy DBRefs and seqfeatures if we really are a dataset sequence
293 if (datasetSequence == null)
295 if (seq.getDBRefs() != null)
297 DBRefEntry[] dbr = seq.getDBRefs();
298 for (int i = 0; i < dbr.length; i++)
300 addDBRef(new DBRefEntry(dbr[i]));
305 * make copies of any sequence features
307 for (SequenceFeature sf : seq.getSequenceFeatures())
309 addSequenceFeature(new SequenceFeature(sf));
313 if (seq.getAnnotation() != null)
315 AlignmentAnnotation[] sqann = seq.getAnnotation();
316 for (int i = 0; i < sqann.length; i++)
318 if (sqann[i] == null)
322 boolean found = (alAnnotation == null);
325 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
327 found = (alAnnotation[apos] == sqann[i]);
332 // only copy the given annotation
333 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
334 addAlignmentAnnotation(newann);
338 if (seq.getAllPDBEntries() != null)
340 Vector<PDBEntry> ids = seq.getAllPDBEntries();
341 for (PDBEntry pdb : ids)
343 this.addPDBId(new PDBEntry(pdb));
346 if (seq.getHMM() != null)
348 this.hmm = new HiddenMarkovModel(seq.getHMM(), this);
354 public void setSequenceFeatures(List<SequenceFeature> features)
356 if (datasetSequence != null)
358 datasetSequence.setSequenceFeatures(features);
361 sequenceFeatureStore = new SequenceFeatures(features);
365 public synchronized boolean addSequenceFeature(SequenceFeature sf)
367 if (sf.getType() == null)
369 System.err.println("SequenceFeature type may not be null: "
374 if (datasetSequence != null)
376 return datasetSequence.addSequenceFeature(sf);
379 return sequenceFeatureStore.add(sf);
383 public void deleteFeature(SequenceFeature sf)
385 if (datasetSequence != null)
387 datasetSequence.deleteFeature(sf);
391 sequenceFeatureStore.delete(sf);
401 public List<SequenceFeature> getSequenceFeatures()
403 if (datasetSequence != null)
405 return datasetSequence.getSequenceFeatures();
407 return sequenceFeatureStore.getAllFeatures();
411 public SequenceFeaturesI getFeatures()
413 return datasetSequence != null ? datasetSequence.getFeatures()
414 : sequenceFeatureStore;
418 public boolean addPDBId(PDBEntry entry)
422 pdbIds = new Vector<>();
427 for (PDBEntry pdbe : pdbIds)
429 if (pdbe.updateFrom(entry))
434 pdbIds.addElement(entry);
445 public void setPDBId(Vector<PDBEntry> id)
453 * @return DOCUMENT ME!
456 public Vector<PDBEntry> getAllPDBEntries()
458 return pdbIds == null ? new Vector<>() : pdbIds;
464 * @return DOCUMENT ME!
467 public String getDisplayId(boolean jvsuffix)
469 StringBuffer result = new StringBuffer(name);
472 result.append("/" + start + "-" + end);
475 return result.toString();
479 * Sets the sequence name. If the name ends in /start-end, then the start-end
480 * values are parsed out and set, and the suffix is removed from the name.
485 public void setName(String theName)
494 * @return DOCUMENT ME!
497 public String getName()
509 public void setStart(int start)
517 * @return DOCUMENT ME!
520 public int getStart()
532 public void setEnd(int end)
540 * @return DOCUMENT ME!
551 * @return DOCUMENT ME!
554 public int getLength()
556 return this.sequence.length;
566 public void setSequence(String seq)
568 this.sequence = seq.toCharArray();
574 public String getSequenceAsString()
576 return new String(sequence);
580 public String getSequenceAsString(int start, int end)
582 return new String(getSequence(start, end));
586 public char[] getSequence()
589 return sequence == null ? null : Arrays.copyOf(sequence,
596 * @see jalview.datamodel.SequenceI#getSequence(int, int)
599 public char[] getSequence(int start, int end)
605 // JBPNote - left to user to pad the result here (TODO:Decide on this
607 if (start >= sequence.length)
612 if (end >= sequence.length)
614 end = sequence.length;
617 char[] reply = new char[end - start];
618 System.arraycopy(sequence, start, reply, 0, end - start);
624 public SequenceI getSubSequence(int start, int end)
630 char[] seq = getSequence(start, end);
635 int nstart = findPosition(start);
636 int nend = findPosition(end) - 1;
637 // JBPNote - this is an incomplete copy.
638 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
639 nseq.setDescription(description);
640 if (datasetSequence != null)
642 nseq.setDatasetSequence(datasetSequence);
646 nseq.setDatasetSequence(this);
652 * Returns the character of the aligned sequence at the given position (base
653 * zero), or space if the position is not within the sequence's bounds
658 public char getCharAt(int i)
660 if (i >= 0 && i < sequence.length)
671 * Sets the sequence description, and also parses out any special formats of
677 public void setDescription(String desc)
679 this.description = desc;
683 public void setGeneLoci(String speciesId, String assemblyId,
684 String chromosomeId, MapList map)
686 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
687 + ":" + chromosomeId, new Mapping(map)));
691 * Returns the gene loci mapping for the sequence (may be null)
696 public GeneLociI getGeneLoci()
698 DBRefEntry[] refs = getDBRefs();
701 for (final DBRefEntry ref : refs)
703 if (ref.isChromosome())
705 return new GeneLociI()
708 public String getSpeciesId()
710 return ref.getSource();
714 public String getAssemblyId()
716 return ref.getVersion();
720 public String getChromosomeId()
722 // strip off "chromosome:" prefix to chrId
723 return ref.getAccessionId().substring(
724 DBRefEntry.CHROMOSOME.length() + 1);
728 public MapList getMap()
730 return ref.getMap().getMap();
740 * Answers the description
745 public String getDescription()
747 return this.description;
754 public int findIndex(int pos)
757 * use a valid, hopefully nearby, cursor if available
759 if (isValidCursor(cursor))
761 return findIndex(pos, cursor);
769 * traverse sequence from the start counting gaps; make a note of
770 * the column of the first residue to save in the cursor
772 while ((i < sequence.length) && (j <= end) && (j <= pos))
774 if (!Comparison.isGap(sequence[i]))
785 if (j == end && j < pos)
790 updateCursor(pos, i, startColumn);
795 * Updates the cursor to the latest found residue and column position
802 * column position of the first sequence residue
804 protected void updateCursor(int residuePos, int column, int startColumn)
807 * preserve end residue column provided cursor was valid
809 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
810 if (residuePos == this.end)
815 cursor = new SequenceCursor(this, residuePos, column, startColumn,
816 endColumn, this.changeCount);
820 * Answers the aligned column position (1..) for the given residue position
821 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
822 * The hint may be left of, at, or to the right of the required position.
828 protected int findIndex(int pos, SequenceCursor curs)
830 if (!isValidCursor(curs))
833 * wrong or invalidated cursor, compute de novo
835 return findIndex(pos);
838 if (curs.residuePosition == pos)
840 return curs.columnPosition;
844 * move left or right to find pos from hint.position
846 int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
848 int newPos = curs.residuePosition;
849 int delta = newPos > pos ? -1 : 1;
851 while (newPos != pos)
853 col += delta; // shift one column left or right
854 if (col < 0 || col == sequence.length)
858 if (!Comparison.isGap(sequence[col]))
864 col++; // convert back to base 1
865 updateCursor(pos, col, curs.firstColumnPosition);
874 public int findPosition(final int column)
877 * use a valid, hopefully nearby, cursor if available
879 if (isValidCursor(cursor))
881 return findPosition(column + 1, cursor);
884 // TODO recode this more naturally i.e. count residues only
885 // as they are found, not 'in anticipation'
888 * traverse the sequence counting gaps; note the column position
889 * of the first residue, to save in the cursor
891 int firstResidueColumn = 0;
892 int lastPosFound = 0;
893 int lastPosFoundColumn = 0;
894 int seqlen = sequence.length;
896 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
898 lastPosFound = start;
899 lastPosFoundColumn = 0;
905 while (j < column && j < seqlen)
907 if (!Comparison.isGap(sequence[j]))
910 lastPosFoundColumn = j;
911 if (pos == this.start)
913 firstResidueColumn = j;
919 if (j < seqlen && !Comparison.isGap(sequence[j]))
922 lastPosFoundColumn = j;
923 if (pos == this.start)
925 firstResidueColumn = j;
930 * update the cursor to the last residue position found (if any)
931 * (converting column position to base 1)
933 if (lastPosFound != 0)
935 updateCursor(lastPosFound, lastPosFoundColumn + 1,
936 firstResidueColumn + 1);
943 * Answers true if the given cursor is not null, is for this sequence object,
944 * and has a token value that matches this object's changeCount, else false.
945 * This allows us to ignore a cursor as 'stale' if the sequence has been
946 * modified since the cursor was created.
951 protected boolean isValidCursor(SequenceCursor curs)
953 if (curs == null || curs.sequence != this || curs.token != changeCount)
958 * sanity check against range
960 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
964 if (curs.residuePosition < start || curs.residuePosition > end)
972 * Answers the sequence position (start..) for the given aligned column
973 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
974 * may lie left of, at, or to the right of the column position.
980 protected int findPosition(final int col, SequenceCursor curs)
982 if (!isValidCursor(curs))
985 * wrong or invalidated cursor, compute de novo
987 return findPosition(col - 1);// ugh back to base 0
990 if (curs.columnPosition == col)
992 cursor = curs; // in case this method becomes public
993 return curs.residuePosition; // easy case :-)
996 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
999 * sequence lies entirely to the left of col
1000 * - return last residue + 1
1005 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1008 * sequence lies entirely to the right of col
1009 * - return first residue
1014 // todo could choose closest to col out of column,
1015 // firstColumnPosition, lastColumnPosition as a start point
1018 * move left or right to find pos from cursor position
1020 int firstResidueColumn = curs.firstColumnPosition;
1021 int column = curs.columnPosition - 1; // to base 0
1022 int newPos = curs.residuePosition;
1023 int delta = curs.columnPosition > col ? -1 : 1;
1024 boolean gapped = false;
1025 int lastFoundPosition = curs.residuePosition;
1026 int lastFoundPositionColumn = curs.columnPosition;
1028 while (column != col - 1)
1030 column += delta; // shift one column left or right
1031 if (column < 0 || column == sequence.length)
1035 gapped = Comparison.isGap(sequence[column]);
1039 lastFoundPosition = newPos;
1040 lastFoundPositionColumn = column + 1;
1041 if (lastFoundPosition == this.start)
1043 firstResidueColumn = column + 1;
1048 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1050 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1051 firstResidueColumn);
1055 * hack to give position to the right if on a gap
1056 * or beyond the length of the sequence (see JAL-2562)
1058 if (delta > 0 && (gapped || column >= sequence.length))
1070 public Range findPositions(int fromColumn, int toColumn)
1072 if (toColumn < fromColumn || fromColumn < 1)
1078 * find the first non-gapped position, if any
1080 int firstPosition = 0;
1081 int col = fromColumn - 1;
1082 int length = sequence.length;
1083 while (col < length && col < toColumn)
1085 if (!Comparison.isGap(sequence[col]))
1087 firstPosition = findPosition(col++);
1093 if (firstPosition == 0)
1099 * find the last non-gapped position
1101 int lastPosition = firstPosition;
1102 while (col < length && col < toColumn)
1104 if (!Comparison.isGap(sequence[col++]))
1110 return new Range(firstPosition, lastPosition);
1114 * Returns an int array where indices correspond to each residue in the
1115 * sequence and the element value gives its position in the alignment
1117 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1118 * residues in SequenceI object
1121 public int[] gapMap()
1123 String seq = jalview.analysis.AlignSeq.extractGaps(
1124 jalview.util.Comparison.GapChars, new String(sequence));
1125 int[] map = new int[seq.length()];
1129 while (j < sequence.length)
1131 if (!jalview.util.Comparison.isGap(sequence[j]))
1143 * Build a bitset corresponding to sequence gaps
1145 * @return a BitSet where set values correspond to gaps in the sequence
1148 public BitSet gapBitset()
1150 BitSet gaps = new BitSet(sequence.length);
1152 while (j < sequence.length)
1154 if (jalview.util.Comparison.isGap(sequence[j]))
1164 public int[] findPositionMap()
1166 int map[] = new int[sequence.length];
1169 int seqlen = sequence.length;
1170 while ((j < seqlen))
1173 if (!jalview.util.Comparison.isGap(sequence[j]))
1184 public List<int[]> getInsertions()
1186 ArrayList<int[]> map = new ArrayList<>();
1187 int lastj = -1, j = 0;
1189 int seqlen = sequence.length;
1190 while ((j < seqlen))
1192 if (jalview.util.Comparison.isGap(sequence[j]))
1203 map.add(new int[] { lastj, j - 1 });
1211 map.add(new int[] { lastj, j - 1 });
1218 public BitSet getInsertionsAsBits()
1220 BitSet map = new BitSet();
1221 int lastj = -1, j = 0;
1223 int seqlen = sequence.length;
1224 while ((j < seqlen))
1226 if (jalview.util.Comparison.isGap(sequence[j]))
1252 public void deleteChars(final int i, final int j)
1254 int newstart = start, newend = end;
1255 if (i >= sequence.length || i < 0)
1260 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1261 boolean createNewDs = false;
1262 // TODO: take a (second look) at the dataset creation validation method for
1263 // the very large sequence case
1264 int startIndex = findIndex(start) - 1;
1265 int endIndex = findIndex(end) - 1;
1266 int startDeleteColumn = -1; // for dataset sequence deletions
1267 int deleteCount = 0;
1269 for (int s = i; s < j; s++)
1271 if (Comparison.isGap(sequence[s]))
1276 if (startDeleteColumn == -1)
1278 startDeleteColumn = findPosition(s) - start;
1286 if (startIndex == s)
1289 * deleting characters from start of sequence; new start is the
1290 * sequence position of the next column (position to the right
1291 * if the column position is gapped)
1293 newstart = findPosition(j);
1301 * deleting characters at end of sequence; new end is the sequence
1302 * position of the column before the deletion; subtract 1 if this is
1303 * gapped since findPosition returns the next sequence position
1305 newend = findPosition(i - 1);
1306 if (Comparison.isGap(sequence[i - 1]))
1321 if (createNewDs && this.datasetSequence != null)
1324 * if deletion occured in the middle of the sequence,
1325 * construct a new dataset sequence and delete the residues
1326 * that were deleted from the aligned sequence
1328 Sequence ds = new Sequence(datasetSequence);
1329 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1330 datasetSequence = ds;
1331 // TODO: remove any non-inheritable properties ?
1332 // TODO: create a sequence mapping (since there is a relation here ?)
1341 public void insertCharAt(int i, int length, char c)
1343 char[] tmp = new char[sequence.length + length];
1345 if (i >= sequence.length)
1347 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1348 i = sequence.length;
1352 System.arraycopy(sequence, 0, tmp, 0, i);
1362 if (i < sequence.length)
1364 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1372 public void insertCharAt(int i, char c)
1374 insertCharAt(i, 1, c);
1378 public String getVamsasId()
1384 public void setVamsasId(String id)
1390 public void setDBRefs(DBRefEntry[] dbref)
1392 if (dbrefs == null && datasetSequence != null
1393 && this != datasetSequence)
1395 datasetSequence.setDBRefs(dbref);
1401 DBRefUtils.ensurePrimaries(this);
1406 public DBRefEntry[] getDBRefs()
1408 if (dbrefs == null && datasetSequence != null
1409 && this != datasetSequence)
1411 return datasetSequence.getDBRefs();
1417 public void addDBRef(DBRefEntry entry)
1419 if (datasetSequence != null)
1421 datasetSequence.addDBRef(entry);
1427 dbrefs = new DBRefEntry[0];
1430 for (DBRefEntryI dbr : dbrefs)
1432 if (dbr.updateFrom(entry))
1435 * found a dbref that either matched, or could be
1436 * updated from, the new entry - no need to add it
1443 * extend the array to make room for one more
1445 // TODO use an ArrayList instead
1446 int j = dbrefs.length;
1447 DBRefEntry[] temp = new DBRefEntry[j + 1];
1448 System.arraycopy(dbrefs, 0, temp, 0, j);
1449 temp[temp.length - 1] = entry;
1453 DBRefUtils.ensurePrimaries(this);
1457 public void setDatasetSequence(SequenceI seq)
1461 throw new IllegalArgumentException(
1462 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1464 if (seq != null && seq.getDatasetSequence() != null)
1466 throw new IllegalArgumentException(
1467 "Implementation error: cascading dataset sequences are not allowed.");
1469 datasetSequence = seq;
1473 public SequenceI getDatasetSequence()
1475 return datasetSequence;
1479 public AlignmentAnnotation[] getAnnotation()
1481 return annotation == null ? null
1483 .toArray(new AlignmentAnnotation[annotation.size()]);
1487 public boolean hasAnnotation(AlignmentAnnotation ann)
1489 return annotation == null ? false : annotation.contains(ann);
1493 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1495 if (this.annotation == null)
1497 this.annotation = new Vector<>();
1499 if (!this.annotation.contains(annotation))
1501 this.annotation.addElement(annotation);
1503 annotation.setSequenceRef(this);
1507 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1509 if (this.annotation != null)
1511 this.annotation.removeElement(annotation);
1512 if (this.annotation.size() == 0)
1514 this.annotation = null;
1520 * test if this is a valid candidate for another sequence's dataset sequence.
1523 private boolean isValidDatasetSequence()
1525 if (datasetSequence != null)
1529 for (int i = 0; i < sequence.length; i++)
1531 if (jalview.util.Comparison.isGap(sequence[i]))
1540 public SequenceI deriveSequence()
1542 Sequence seq = null;
1543 if (datasetSequence == null)
1545 if (isValidDatasetSequence())
1547 // Use this as dataset sequence
1548 seq = new Sequence(getName(), "", 1, -1);
1549 seq.setDatasetSequence(this);
1550 seq.initSeqFrom(this, getAnnotation());
1555 // Create a new, valid dataset sequence
1556 createDatasetSequence();
1559 return new Sequence(this);
1562 private boolean _isNa;
1564 private int _seqhash = 0;
1567 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1571 public boolean isProtein()
1573 if (datasetSequence != null)
1575 return datasetSequence.isProtein();
1577 if (_seqhash != sequence.hashCode())
1579 _seqhash = sequence.hashCode();
1580 _isNa = Comparison.isNucleotide(this);
1588 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1591 public SequenceI createDatasetSequence()
1593 if (datasetSequence == null)
1595 Sequence dsseq = new Sequence(getName(),
1596 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1597 getSequenceAsString()),
1598 getStart(), getEnd());
1600 datasetSequence = dsseq;
1602 dsseq.setDescription(description);
1603 // move features and database references onto dataset sequence
1604 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1605 sequenceFeatureStore = null;
1606 dsseq.dbrefs = dbrefs;
1608 // TODO: search and replace any references to this sequence with
1609 // references to the dataset sequence in Mappings on dbref
1610 dsseq.pdbIds = pdbIds;
1612 datasetSequence.updatePDBIds();
1613 if (annotation != null)
1615 // annotation is cloned rather than moved, to preserve what's currently
1617 for (AlignmentAnnotation aa : annotation)
1619 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1620 _aa.sequenceRef = datasetSequence;
1621 _aa.adjustForAlignment(); // uses annotation's own record of
1622 // sequence-column mapping
1623 datasetSequence.addAlignmentAnnotation(_aa);
1627 return datasetSequence;
1634 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1638 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1640 if (annotation != null)
1642 annotation.removeAllElements();
1644 if (annotations != null)
1646 for (int i = 0; i < annotations.length; i++)
1648 if (annotations[i] != null)
1650 addAlignmentAnnotation(annotations[i]);
1657 public AlignmentAnnotation[] getAnnotation(String label)
1659 if (annotation == null || annotation.size() == 0)
1664 Vector<AlignmentAnnotation> subset = new Vector<>();
1665 Enumeration<AlignmentAnnotation> e = annotation.elements();
1666 while (e.hasMoreElements())
1668 AlignmentAnnotation ann = e.nextElement();
1669 if (ann.label != null && ann.label.equals(label))
1671 subset.addElement(ann);
1674 if (subset.size() == 0)
1678 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1680 e = subset.elements();
1681 while (e.hasMoreElements())
1683 anns[i++] = e.nextElement();
1685 subset.removeAllElements();
1690 public boolean updatePDBIds()
1692 if (datasetSequence != null)
1694 // TODO: could merge DBRefs
1695 return datasetSequence.updatePDBIds();
1697 if (dbrefs == null || dbrefs.length == 0)
1701 boolean added = false;
1702 for (DBRefEntry dbr : dbrefs)
1704 if (DBRefSource.PDB.equals(dbr.getSource()))
1707 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1708 * PDB id is not already present in a 'matching' PDBEntry
1709 * Constructor parses out a chain code if appended to the accession id
1710 * (a fudge used to 'store' the chain code in the DBRef)
1712 PDBEntry pdbe = new PDBEntry(dbr);
1713 added |= addPDBId(pdbe);
1720 public void transferAnnotation(SequenceI entry, Mapping mp)
1722 if (datasetSequence != null)
1724 datasetSequence.transferAnnotation(entry, mp);
1727 if (entry.getDatasetSequence() != null)
1729 transferAnnotation(entry.getDatasetSequence(), mp);
1732 // transfer any new features from entry onto sequence
1733 if (entry.getSequenceFeatures() != null)
1736 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1737 for (SequenceFeature feature : sfs)
1739 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1740 : new SequenceFeature[] { new SequenceFeature(feature) };
1743 for (int sfi = 0; sfi < sf.length; sfi++)
1745 addSequenceFeature(sf[sfi]);
1751 // transfer PDB entries
1752 if (entry.getAllPDBEntries() != null)
1754 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1755 while (e.hasMoreElements())
1757 PDBEntry pdb = e.nextElement();
1761 // transfer database references
1762 DBRefEntry[] entryRefs = entry.getDBRefs();
1763 if (entryRefs != null)
1765 for (int r = 0; r < entryRefs.length; r++)
1767 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1768 if (newref.getMap() != null && mp != null)
1770 // remap ref using our local mapping
1772 // we also assume all version string setting is done by dbSourceProxy
1774 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1775 * newref.setSource(dbSource); }
1783 public void setRNA(RNA r)
1795 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1798 List<AlignmentAnnotation> result = new ArrayList<>();
1799 if (this.annotation != null)
1801 for (AlignmentAnnotation ann : annotation)
1803 String id = ann.getCalcId();
1804 if (id != null && id.equals(calcId)
1805 && ann.label != null && ann.label.equals(label))
1815 public String toString()
1817 return getDisplayId(false);
1821 public PDBEntry getPDBEntry(String pdbIdStr)
1823 if (getDatasetSequence() != null)
1825 return getDatasetSequence().getPDBEntry(pdbIdStr);
1831 List<PDBEntry> entries = getAllPDBEntries();
1832 for (PDBEntry entry : entries)
1834 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1843 public List<DBRefEntry> getPrimaryDBRefs()
1845 if (datasetSequence != null)
1847 return datasetSequence.getPrimaryDBRefs();
1849 if (dbrefs == null || dbrefs.length == 0)
1851 return Collections.emptyList();
1853 synchronized (dbrefs)
1855 List<DBRefEntry> primaries = new ArrayList<>();
1856 DBRefEntry[] tmp = new DBRefEntry[1];
1857 for (DBRefEntry ref : dbrefs)
1859 if (!ref.isPrimaryCandidate())
1865 MapList mp = ref.getMap().getMap();
1866 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1868 // map only involves a subsequence, so cannot be primary
1872 // whilst it looks like it is a primary ref, we also sanity check type
1873 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1874 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1876 // PDB dbrefs imply there should be a PDBEntry associated
1877 // TODO: tighten PDB dbrefs
1878 // formally imply Jalview has actually downloaded and
1879 // parsed the pdb file. That means there should be a cached file
1880 // handle on the PDBEntry, and a real mapping between sequence and
1881 // extracted sequence from PDB file
1882 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1883 if (pdbentry != null && pdbentry.getFile() != null)
1889 // check standard protein or dna sources
1891 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1892 if (res != null && res[0] == tmp[0])
1903 public HiddenMarkovModel getHMM()
1909 public void setHMM(HiddenMarkovModel hmm)
1915 public boolean hasHMMAnnotation()
1917 if (this.annotation == null) {
1920 for (AlignmentAnnotation ann : annotation)
1922 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1934 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1937 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1938 int endPos = fromColumn == toColumn ? startPos
1939 : findPosition(toColumn - 1);
1941 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1945 * if end column is gapped, endPos may be to the right,
1946 * and we may have included adjacent or enclosing features;
1947 * remove any that are not enclosing, non-contact features
1949 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1950 && Comparison.isGap(sequence[toColumn - 1]);
1951 if (endPos > this.end || endColumnIsGapped)
1953 ListIterator<SequenceFeature> it = result.listIterator();
1954 while (it.hasNext())
1956 SequenceFeature sf = it.next();
1957 int sfBegin = sf.getBegin();
1958 int sfEnd = sf.getEnd();
1959 int featureStartColumn = findIndex(sfBegin);
1960 if (featureStartColumn > toColumn)
1964 else if (featureStartColumn < fromColumn)
1966 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1968 if (featureEndColumn < fromColumn)
1972 else if (featureEndColumn > toColumn && sf.isContactFeature())
1975 * remove an enclosing feature if it is a contact feature
1987 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1988 * token that has to match the one presented by the cursor
1991 public void sequenceChanged()
2000 public int replace(char c1, char c2)
2007 synchronized (sequence)
2009 for (int c = 0; c < sequence.length; c++)
2011 if (sequence[c] == c1)
2027 public String getSequenceStringFromIterator(Iterator<int[]> it)
2029 StringBuilder newSequence = new StringBuilder();
2030 while (it.hasNext())
2032 int[] block = it.next();
2035 newSequence.append(getSequence(block[0], block[1] + 1));
2039 newSequence.append(getSequence(block[0], block[1]));
2043 return newSequence.toString();
2047 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2051 if (!regions.hasNext())
2053 return findIndex(getStart()) - 1;
2056 // Simply walk along the sequence whilst watching for region
2058 int hideStart = getLength();
2060 boolean foundStart = false;
2062 // step through the non-gapped positions of the sequence
2063 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2065 // get alignment position of this residue in the sequence
2066 int p = findIndex(i) - 1;
2068 // update region start/end
2069 while (hideEnd < p && regions.hasNext())
2071 int[] region = regions.next();
2072 hideStart = region[0];
2073 hideEnd = region[1];
2077 hideStart = getLength();
2079 // update boundary for sequence
2091 // otherwise, sequence was completely hidden
2096 public boolean hasHMMProfile()