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(final 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
858 if (col == sequence.length)
860 col--; // return last column if we failed to reach pos
863 if (!Comparison.isGap(sequence[col]))
869 col++; // convert back to base 1
872 * only update cursor if we found the target position
876 updateCursor(pos, col, curs.firstColumnPosition);
886 public int findPosition(final int column)
889 * use a valid, hopefully nearby, cursor if available
891 if (isValidCursor(cursor))
893 return findPosition(column + 1, cursor);
896 // TODO recode this more naturally i.e. count residues only
897 // as they are found, not 'in anticipation'
900 * traverse the sequence counting gaps; note the column position
901 * of the first residue, to save in the cursor
903 int firstResidueColumn = 0;
904 int lastPosFound = 0;
905 int lastPosFoundColumn = 0;
906 int seqlen = sequence.length;
908 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
910 lastPosFound = start;
911 lastPosFoundColumn = 0;
917 while (j < column && j < seqlen)
919 if (!Comparison.isGap(sequence[j]))
922 lastPosFoundColumn = j;
923 if (pos == this.start)
925 firstResidueColumn = j;
931 if (j < seqlen && !Comparison.isGap(sequence[j]))
934 lastPosFoundColumn = j;
935 if (pos == this.start)
937 firstResidueColumn = j;
942 * update the cursor to the last residue position found (if any)
943 * (converting column position to base 1)
945 if (lastPosFound != 0)
947 updateCursor(lastPosFound, lastPosFoundColumn + 1,
948 firstResidueColumn + 1);
955 * Answers true if the given cursor is not null, is for this sequence object,
956 * and has a token value that matches this object's changeCount, else false.
957 * This allows us to ignore a cursor as 'stale' if the sequence has been
958 * modified since the cursor was created.
963 protected boolean isValidCursor(SequenceCursor curs)
965 if (curs == null || curs.sequence != this || curs.token != changeCount)
970 * sanity check against range
972 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
976 if (curs.residuePosition < start || curs.residuePosition > end)
984 * Answers the sequence position (start..) for the given aligned column
985 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
986 * may lie left of, at, or to the right of the column position.
992 protected int findPosition(final int col, SequenceCursor curs)
994 if (!isValidCursor(curs))
997 * wrong or invalidated cursor, compute de novo
999 return findPosition(col - 1);// ugh back to base 0
1002 if (curs.columnPosition == col)
1004 cursor = curs; // in case this method becomes public
1005 return curs.residuePosition; // easy case :-)
1008 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1011 * sequence lies entirely to the left of col
1012 * - return last residue + 1
1017 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1020 * sequence lies entirely to the right of col
1021 * - return first residue
1026 // todo could choose closest to col out of column,
1027 // firstColumnPosition, lastColumnPosition as a start point
1030 * move left or right to find pos from cursor position
1032 int firstResidueColumn = curs.firstColumnPosition;
1033 int column = curs.columnPosition - 1; // to base 0
1034 int newPos = curs.residuePosition;
1035 int delta = curs.columnPosition > col ? -1 : 1;
1036 boolean gapped = false;
1037 int lastFoundPosition = curs.residuePosition;
1038 int lastFoundPositionColumn = curs.columnPosition;
1040 while (column != col - 1)
1042 column += delta; // shift one column left or right
1043 if (column < 0 || column == sequence.length)
1047 gapped = Comparison.isGap(sequence[column]);
1051 lastFoundPosition = newPos;
1052 lastFoundPositionColumn = column + 1;
1053 if (lastFoundPosition == this.start)
1055 firstResidueColumn = column + 1;
1060 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1062 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1063 firstResidueColumn);
1067 * hack to give position to the right if on a gap
1068 * or beyond the length of the sequence (see JAL-2562)
1070 if (delta > 0 && (gapped || column >= sequence.length))
1082 public Range findPositions(int fromColumn, int toColumn)
1084 if (toColumn < fromColumn || fromColumn < 1)
1090 * find the first non-gapped position, if any
1092 int firstPosition = 0;
1093 int col = fromColumn - 1;
1094 int length = sequence.length;
1095 while (col < length && col < toColumn)
1097 if (!Comparison.isGap(sequence[col]))
1099 firstPosition = findPosition(col++);
1105 if (firstPosition == 0)
1111 * find the last non-gapped position
1113 int lastPosition = firstPosition;
1114 while (col < length && col < toColumn)
1116 if (!Comparison.isGap(sequence[col++]))
1122 return new Range(firstPosition, lastPosition);
1126 * Returns an int array where indices correspond to each residue in the
1127 * sequence and the element value gives its position in the alignment
1129 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1130 * residues in SequenceI object
1133 public int[] gapMap()
1135 String seq = jalview.analysis.AlignSeq.extractGaps(
1136 jalview.util.Comparison.GapChars, new String(sequence));
1137 int[] map = new int[seq.length()];
1141 while (j < sequence.length)
1143 if (!jalview.util.Comparison.isGap(sequence[j]))
1155 * Build a bitset corresponding to sequence gaps
1157 * @return a BitSet where set values correspond to gaps in the sequence
1160 public BitSet gapBitset()
1162 BitSet gaps = new BitSet(sequence.length);
1164 while (j < sequence.length)
1166 if (jalview.util.Comparison.isGap(sequence[j]))
1176 public int[] findPositionMap()
1178 int map[] = new int[sequence.length];
1181 int seqlen = sequence.length;
1182 while ((j < seqlen))
1185 if (!jalview.util.Comparison.isGap(sequence[j]))
1196 public List<int[]> getInsertions()
1198 ArrayList<int[]> map = new ArrayList<>();
1199 int lastj = -1, j = 0;
1201 int seqlen = sequence.length;
1202 while ((j < seqlen))
1204 if (jalview.util.Comparison.isGap(sequence[j]))
1215 map.add(new int[] { lastj, j - 1 });
1223 map.add(new int[] { lastj, j - 1 });
1230 public BitSet getInsertionsAsBits()
1232 BitSet map = new BitSet();
1233 int lastj = -1, j = 0;
1235 int seqlen = sequence.length;
1236 while ((j < seqlen))
1238 if (jalview.util.Comparison.isGap(sequence[j]))
1264 public void deleteChars(final int i, final int j)
1266 int newstart = start, newend = end;
1267 if (i >= sequence.length || i < 0)
1272 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1273 boolean createNewDs = false;
1274 // TODO: take a (second look) at the dataset creation validation method for
1275 // the very large sequence case
1276 int startIndex = findIndex(start) - 1;
1277 int endIndex = findIndex(end) - 1;
1278 int startDeleteColumn = -1; // for dataset sequence deletions
1279 int deleteCount = 0;
1281 for (int s = i; s < j; s++)
1283 if (Comparison.isGap(sequence[s]))
1288 if (startDeleteColumn == -1)
1290 startDeleteColumn = findPosition(s) - start;
1298 if (startIndex == s)
1301 * deleting characters from start of sequence; new start is the
1302 * sequence position of the next column (position to the right
1303 * if the column position is gapped)
1305 newstart = findPosition(j);
1313 * deleting characters at end of sequence; new end is the sequence
1314 * position of the column before the deletion; subtract 1 if this is
1315 * gapped since findPosition returns the next sequence position
1317 newend = findPosition(i - 1);
1318 if (Comparison.isGap(sequence[i - 1]))
1333 if (createNewDs && this.datasetSequence != null)
1336 * if deletion occured in the middle of the sequence,
1337 * construct a new dataset sequence and delete the residues
1338 * that were deleted from the aligned sequence
1340 Sequence ds = new Sequence(datasetSequence);
1341 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1342 datasetSequence = ds;
1343 // TODO: remove any non-inheritable properties ?
1344 // TODO: create a sequence mapping (since there is a relation here ?)
1353 public void insertCharAt(int i, int length, char c)
1355 char[] tmp = new char[sequence.length + length];
1357 if (i >= sequence.length)
1359 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1360 i = sequence.length;
1364 System.arraycopy(sequence, 0, tmp, 0, i);
1374 if (i < sequence.length)
1376 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1384 public void insertCharAt(int i, char c)
1386 insertCharAt(i, 1, c);
1390 public String getVamsasId()
1396 public void setVamsasId(String id)
1402 public void setDBRefs(DBRefEntry[] dbref)
1404 if (dbrefs == null && datasetSequence != null
1405 && this != datasetSequence)
1407 datasetSequence.setDBRefs(dbref);
1413 DBRefUtils.ensurePrimaries(this);
1418 public DBRefEntry[] getDBRefs()
1420 if (dbrefs == null && datasetSequence != null
1421 && this != datasetSequence)
1423 return datasetSequence.getDBRefs();
1429 public void addDBRef(DBRefEntry entry)
1431 if (datasetSequence != null)
1433 datasetSequence.addDBRef(entry);
1439 dbrefs = new DBRefEntry[0];
1442 for (DBRefEntryI dbr : dbrefs)
1444 if (dbr.updateFrom(entry))
1447 * found a dbref that either matched, or could be
1448 * updated from, the new entry - no need to add it
1455 * extend the array to make room for one more
1457 // TODO use an ArrayList instead
1458 int j = dbrefs.length;
1459 DBRefEntry[] temp = new DBRefEntry[j + 1];
1460 System.arraycopy(dbrefs, 0, temp, 0, j);
1461 temp[temp.length - 1] = entry;
1465 DBRefUtils.ensurePrimaries(this);
1469 public void setDatasetSequence(SequenceI seq)
1473 throw new IllegalArgumentException(
1474 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1476 if (seq != null && seq.getDatasetSequence() != null)
1478 throw new IllegalArgumentException(
1479 "Implementation error: cascading dataset sequences are not allowed.");
1481 datasetSequence = seq;
1485 public SequenceI getDatasetSequence()
1487 return datasetSequence;
1491 public AlignmentAnnotation[] getAnnotation()
1493 return annotation == null ? null
1495 .toArray(new AlignmentAnnotation[annotation.size()]);
1499 public boolean hasAnnotation(AlignmentAnnotation ann)
1501 return annotation == null ? false : annotation.contains(ann);
1505 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1507 if (this.annotation == null)
1509 this.annotation = new Vector<>();
1511 if (!this.annotation.contains(annotation))
1513 this.annotation.addElement(annotation);
1515 annotation.setSequenceRef(this);
1519 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1521 if (this.annotation != null)
1523 this.annotation.removeElement(annotation);
1524 if (this.annotation.size() == 0)
1526 this.annotation = null;
1532 * test if this is a valid candidate for another sequence's dataset sequence.
1535 private boolean isValidDatasetSequence()
1537 if (datasetSequence != null)
1541 for (int i = 0; i < sequence.length; i++)
1543 if (jalview.util.Comparison.isGap(sequence[i]))
1552 public SequenceI deriveSequence()
1554 Sequence seq = null;
1555 if (datasetSequence == null)
1557 if (isValidDatasetSequence())
1559 // Use this as dataset sequence
1560 seq = new Sequence(getName(), "", 1, -1);
1561 seq.setDatasetSequence(this);
1562 seq.initSeqFrom(this, getAnnotation());
1567 // Create a new, valid dataset sequence
1568 createDatasetSequence();
1571 return new Sequence(this);
1574 private boolean _isNa;
1576 private int _seqhash = 0;
1579 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1583 public boolean isProtein()
1585 if (datasetSequence != null)
1587 return datasetSequence.isProtein();
1589 if (_seqhash != sequence.hashCode())
1591 _seqhash = sequence.hashCode();
1592 _isNa = Comparison.isNucleotide(this);
1600 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1603 public SequenceI createDatasetSequence()
1605 if (datasetSequence == null)
1607 Sequence dsseq = new Sequence(getName(),
1608 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1609 getSequenceAsString()),
1610 getStart(), getEnd());
1612 datasetSequence = dsseq;
1614 dsseq.setDescription(description);
1615 // move features and database references onto dataset sequence
1616 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1617 sequenceFeatureStore = null;
1618 dsseq.dbrefs = dbrefs;
1620 // TODO: search and replace any references to this sequence with
1621 // references to the dataset sequence in Mappings on dbref
1622 dsseq.pdbIds = pdbIds;
1624 datasetSequence.updatePDBIds();
1625 if (annotation != null)
1627 // annotation is cloned rather than moved, to preserve what's currently
1629 for (AlignmentAnnotation aa : annotation)
1631 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1632 _aa.sequenceRef = datasetSequence;
1633 _aa.adjustForAlignment(); // uses annotation's own record of
1634 // sequence-column mapping
1635 datasetSequence.addAlignmentAnnotation(_aa);
1639 return datasetSequence;
1646 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1650 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1652 if (annotation != null)
1654 annotation.removeAllElements();
1656 if (annotations != null)
1658 for (int i = 0; i < annotations.length; i++)
1660 if (annotations[i] != null)
1662 addAlignmentAnnotation(annotations[i]);
1669 public AlignmentAnnotation[] getAnnotation(String label)
1671 if (annotation == null || annotation.size() == 0)
1676 Vector<AlignmentAnnotation> subset = new Vector<>();
1677 Enumeration<AlignmentAnnotation> e = annotation.elements();
1678 while (e.hasMoreElements())
1680 AlignmentAnnotation ann = e.nextElement();
1681 if (ann.label != null && ann.label.equals(label))
1683 subset.addElement(ann);
1686 if (subset.size() == 0)
1690 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1692 e = subset.elements();
1693 while (e.hasMoreElements())
1695 anns[i++] = e.nextElement();
1697 subset.removeAllElements();
1702 public boolean updatePDBIds()
1704 if (datasetSequence != null)
1706 // TODO: could merge DBRefs
1707 return datasetSequence.updatePDBIds();
1709 if (dbrefs == null || dbrefs.length == 0)
1713 boolean added = false;
1714 for (DBRefEntry dbr : dbrefs)
1716 if (DBRefSource.PDB.equals(dbr.getSource()))
1719 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1720 * PDB id is not already present in a 'matching' PDBEntry
1721 * Constructor parses out a chain code if appended to the accession id
1722 * (a fudge used to 'store' the chain code in the DBRef)
1724 PDBEntry pdbe = new PDBEntry(dbr);
1725 added |= addPDBId(pdbe);
1732 public void transferAnnotation(SequenceI entry, Mapping mp)
1734 if (datasetSequence != null)
1736 datasetSequence.transferAnnotation(entry, mp);
1739 if (entry.getDatasetSequence() != null)
1741 transferAnnotation(entry.getDatasetSequence(), mp);
1744 // transfer any new features from entry onto sequence
1745 if (entry.getSequenceFeatures() != null)
1748 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1749 for (SequenceFeature feature : sfs)
1751 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1752 : new SequenceFeature[] { new SequenceFeature(feature) };
1755 for (int sfi = 0; sfi < sf.length; sfi++)
1757 addSequenceFeature(sf[sfi]);
1763 // transfer PDB entries
1764 if (entry.getAllPDBEntries() != null)
1766 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1767 while (e.hasMoreElements())
1769 PDBEntry pdb = e.nextElement();
1773 // transfer database references
1774 DBRefEntry[] entryRefs = entry.getDBRefs();
1775 if (entryRefs != null)
1777 for (int r = 0; r < entryRefs.length; r++)
1779 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1780 if (newref.getMap() != null && mp != null)
1782 // remap ref using our local mapping
1784 // we also assume all version string setting is done by dbSourceProxy
1786 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1787 * newref.setSource(dbSource); }
1795 public void setRNA(RNA r)
1807 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1810 List<AlignmentAnnotation> result = new ArrayList<>();
1811 if (this.annotation != null)
1813 for (AlignmentAnnotation ann : annotation)
1815 String id = ann.getCalcId();
1816 if (id != null && id.equals(calcId)
1817 && ann.label != null && ann.label.equals(label))
1827 public String toString()
1829 return getDisplayId(false);
1833 public PDBEntry getPDBEntry(String pdbIdStr)
1835 if (getDatasetSequence() != null)
1837 return getDatasetSequence().getPDBEntry(pdbIdStr);
1843 List<PDBEntry> entries = getAllPDBEntries();
1844 for (PDBEntry entry : entries)
1846 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1855 public List<DBRefEntry> getPrimaryDBRefs()
1857 if (datasetSequence != null)
1859 return datasetSequence.getPrimaryDBRefs();
1861 if (dbrefs == null || dbrefs.length == 0)
1863 return Collections.emptyList();
1865 synchronized (dbrefs)
1867 List<DBRefEntry> primaries = new ArrayList<>();
1868 DBRefEntry[] tmp = new DBRefEntry[1];
1869 for (DBRefEntry ref : dbrefs)
1871 if (!ref.isPrimaryCandidate())
1877 MapList mp = ref.getMap().getMap();
1878 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1880 // map only involves a subsequence, so cannot be primary
1884 // whilst it looks like it is a primary ref, we also sanity check type
1885 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1886 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1888 // PDB dbrefs imply there should be a PDBEntry associated
1889 // TODO: tighten PDB dbrefs
1890 // formally imply Jalview has actually downloaded and
1891 // parsed the pdb file. That means there should be a cached file
1892 // handle on the PDBEntry, and a real mapping between sequence and
1893 // extracted sequence from PDB file
1894 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1895 if (pdbentry != null && pdbentry.getFile() != null)
1901 // check standard protein or dna sources
1903 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1904 if (res != null && res[0] == tmp[0])
1915 public HiddenMarkovModel getHMM()
1921 public void setHMM(HiddenMarkovModel hmm)
1927 public boolean hasHMMAnnotation()
1929 if (this.annotation == null) {
1932 for (AlignmentAnnotation ann : annotation)
1934 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1946 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1949 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1950 int endPos = fromColumn == toColumn ? startPos
1951 : findPosition(toColumn - 1);
1953 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1957 * if end column is gapped, endPos may be to the right,
1958 * and we may have included adjacent or enclosing features;
1959 * remove any that are not enclosing, non-contact features
1961 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1962 && Comparison.isGap(sequence[toColumn - 1]);
1963 if (endPos > this.end || endColumnIsGapped)
1965 ListIterator<SequenceFeature> it = result.listIterator();
1966 while (it.hasNext())
1968 SequenceFeature sf = it.next();
1969 int sfBegin = sf.getBegin();
1970 int sfEnd = sf.getEnd();
1971 int featureStartColumn = findIndex(sfBegin);
1972 if (featureStartColumn > toColumn)
1976 else if (featureStartColumn < fromColumn)
1978 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1980 if (featureEndColumn < fromColumn)
1984 else if (featureEndColumn > toColumn && sf.isContactFeature())
1987 * remove an enclosing feature if it is a contact feature
1999 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2000 * token that has to match the one presented by the cursor
2003 public void sequenceChanged()
2012 public int replace(char c1, char c2)
2019 synchronized (sequence)
2021 for (int c = 0; c < sequence.length; c++)
2023 if (sequence[c] == c1)
2039 public String getSequenceStringFromIterator(Iterator<int[]> it)
2041 StringBuilder newSequence = new StringBuilder();
2042 while (it.hasNext())
2044 int[] block = it.next();
2047 newSequence.append(getSequence(block[0], block[1] + 1));
2051 newSequence.append(getSequence(block[0], block[1]));
2055 return newSequence.toString();
2059 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2063 if (!regions.hasNext())
2065 return findIndex(getStart()) - 1;
2068 // Simply walk along the sequence whilst watching for region
2070 int hideStart = getLength();
2072 boolean foundStart = false;
2074 // step through the non-gapped positions of the sequence
2075 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2077 // get alignment position of this residue in the sequence
2078 int p = findIndex(i) - 1;
2080 // update region start/end
2081 while (hideEnd < p && regions.hasNext())
2083 int[] region = regions.next();
2084 hideStart = region[0];
2085 hideEnd = region[1];
2089 hideStart = getLength();
2091 // update boundary for sequence
2103 // otherwise, sequence was completely hidden
2108 public boolean hasHMMProfile()