2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.datamodel;
23 import jalview.analysis.AlignSeq;
24 import jalview.api.DBRefEntryI;
25 import jalview.datamodel.features.SequenceFeatures;
26 import jalview.datamodel.features.SequenceFeaturesI;
27 import jalview.util.Comparison;
28 import jalview.util.DBRefUtils;
29 import jalview.util.MapList;
30 import jalview.util.StringUtils;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.BitSet;
35 import java.util.Collections;
36 import java.util.Enumeration;
37 import java.util.List;
38 import java.util.ListIterator;
39 import java.util.Vector;
41 import fr.orsay.lri.varna.models.rna.RNA;
45 * Implements the SequenceI interface for a char[] based sequence object.
50 public class Sequence extends ASequence implements SequenceI
52 SequenceI datasetSequence;
56 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.isHMMConsensusSequence())
348 this.isHMMConsensusSequence = true;
350 if (seq.getHMM() != null)
352 this.hmm = new HiddenMarkovModel(seq.getHMM());
358 public void setSequenceFeatures(List<SequenceFeature> features)
360 if (datasetSequence != null)
362 datasetSequence.setSequenceFeatures(features);
365 sequenceFeatureStore = new SequenceFeatures(features);
369 public synchronized boolean addSequenceFeature(SequenceFeature sf)
371 if (sf.getType() == null)
373 System.err.println("SequenceFeature type may not be null: "
378 if (datasetSequence != null)
380 return datasetSequence.addSequenceFeature(sf);
383 return sequenceFeatureStore.add(sf);
387 public void deleteFeature(SequenceFeature sf)
389 if (datasetSequence != null)
391 datasetSequence.deleteFeature(sf);
395 sequenceFeatureStore.delete(sf);
405 public List<SequenceFeature> getSequenceFeatures()
407 if (datasetSequence != null)
409 return datasetSequence.getSequenceFeatures();
411 return sequenceFeatureStore.getAllFeatures();
415 public SequenceFeaturesI getFeatures()
417 return datasetSequence != null ? datasetSequence.getFeatures()
418 : sequenceFeatureStore;
422 public boolean addPDBId(PDBEntry entry)
426 pdbIds = new Vector<>();
431 for (PDBEntry pdbe : pdbIds)
433 if (pdbe.updateFrom(entry))
438 pdbIds.addElement(entry);
449 public void setPDBId(Vector<PDBEntry> id)
457 * @return DOCUMENT ME!
460 public Vector<PDBEntry> getAllPDBEntries()
462 return pdbIds == null ? new Vector<>() : pdbIds;
468 * @return DOCUMENT ME!
471 public String getDisplayId(boolean jvsuffix)
473 StringBuffer result = new StringBuffer(name);
476 result.append("/" + start + "-" + end);
479 return result.toString();
483 * Sets the sequence name. If the name ends in /start-end, then the start-end
484 * values are parsed out and set, and the suffix is removed from the name.
489 public void setName(String theName)
498 * @return DOCUMENT ME!
501 public String getName()
513 public void setStart(int start)
521 * @return DOCUMENT ME!
524 public int getStart()
536 public void setEnd(int end)
544 * @return DOCUMENT ME!
555 * @return DOCUMENT ME!
558 public int getLength()
560 return this.sequence.length;
570 public void setSequence(String seq)
572 this.sequence = seq.toCharArray();
578 public String getSequenceAsString()
580 return new String(sequence);
584 public String getSequenceAsString(int start, int end)
586 return new String(getSequence(start, end));
590 public char[] getSequence()
593 return sequence == null ? null : Arrays.copyOf(sequence,
600 * @see jalview.datamodel.SequenceI#getSequence(int, int)
603 public char[] getSequence(int start, int end)
609 // JBPNote - left to user to pad the result here (TODO:Decide on this
611 if (start >= sequence.length)
616 if (end >= sequence.length)
618 end = sequence.length;
621 char[] reply = new char[end - start];
622 System.arraycopy(sequence, start, reply, 0, end - start);
628 public SequenceI getSubSequence(int start, int end)
634 char[] seq = getSequence(start, end);
639 int nstart = findPosition(start);
640 int nend = findPosition(end) - 1;
641 // JBPNote - this is an incomplete copy.
642 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
643 nseq.setDescription(description);
644 if (datasetSequence != null)
646 nseq.setDatasetSequence(datasetSequence);
650 nseq.setDatasetSequence(this);
656 * Returns the character of the aligned sequence at the given position (base
657 * zero), or space if the position is not within the sequence's bounds
662 public char getCharAt(int i)
664 if (i >= 0 && i < sequence.length)
675 * Sets the sequence description, and also parses out any special formats of
681 public void setDescription(String desc)
683 this.description = desc;
687 public void setGeneLoci(String speciesId, String assemblyId,
688 String chromosomeId, MapList map)
690 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
691 + ":" + chromosomeId, new Mapping(map)));
695 * Returns the gene loci mapping for the sequence (may be null)
700 public GeneLociI getGeneLoci()
702 DBRefEntry[] refs = getDBRefs();
705 for (final DBRefEntry ref : refs)
707 if (ref.isChromosome())
709 return new GeneLociI()
712 public String getSpeciesId()
714 return ref.getSource();
718 public String getAssemblyId()
720 return ref.getVersion();
724 public String getChromosomeId()
726 // strip off "chromosome:" prefix to chrId
727 return ref.getAccessionId().substring(
728 DBRefEntry.CHROMOSOME.length() + 1);
732 public MapList getMap()
734 return ref.getMap().getMap();
744 * Answers the description
749 public String getDescription()
751 return this.description;
758 public int findIndex(int pos)
761 * use a valid, hopefully nearby, cursor if available
763 if (isValidCursor(cursor))
765 return findIndex(pos, cursor);
773 * traverse sequence from the start counting gaps; make a note of
774 * the column of the first residue to save in the cursor
776 while ((i < sequence.length) && (j <= end) && (j <= pos))
778 if (!Comparison.isGap(sequence[i]))
789 if (j == end && j < pos)
794 updateCursor(pos, i, startColumn);
799 * Updates the cursor to the latest found residue and column position
806 * column position of the first sequence residue
808 protected void updateCursor(int residuePos, int column, int startColumn)
811 * preserve end residue column provided cursor was valid
813 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
814 if (residuePos == this.end)
819 cursor = new SequenceCursor(this, residuePos, column, startColumn,
820 endColumn, this.changeCount);
824 * Answers the aligned column position (1..) for the given residue position
825 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
826 * The hint may be left of, at, or to the right of the required position.
832 protected int findIndex(int pos, SequenceCursor curs)
834 if (!isValidCursor(curs))
837 * wrong or invalidated cursor, compute de novo
839 return findIndex(pos);
842 if (curs.residuePosition == pos)
844 return curs.columnPosition;
848 * move left or right to find pos from hint.position
850 int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
852 int newPos = curs.residuePosition;
853 int delta = newPos > pos ? -1 : 1;
855 while (newPos != pos)
857 col += delta; // shift one column left or right
858 if (col < 0 || col == sequence.length)
862 if (!Comparison.isGap(sequence[col]))
868 col++; // convert back to base 1
869 updateCursor(pos, col, curs.firstColumnPosition);
878 public int findPosition(final int column)
881 * use a valid, hopefully nearby, cursor if available
883 if (isValidCursor(cursor))
885 return findPosition(column + 1, cursor);
888 // TODO recode this more naturally i.e. count residues only
889 // as they are found, not 'in anticipation'
892 * traverse the sequence counting gaps; note the column position
893 * of the first residue, to save in the cursor
895 int firstResidueColumn = 0;
896 int lastPosFound = 0;
897 int lastPosFoundColumn = 0;
898 int seqlen = sequence.length;
900 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
902 lastPosFound = start;
903 lastPosFoundColumn = 0;
909 while (j < column && j < seqlen)
911 if (!Comparison.isGap(sequence[j]))
914 lastPosFoundColumn = j;
915 if (pos == this.start)
917 firstResidueColumn = j;
923 if (j < seqlen && !Comparison.isGap(sequence[j]))
926 lastPosFoundColumn = j;
927 if (pos == this.start)
929 firstResidueColumn = j;
934 * update the cursor to the last residue position found (if any)
935 * (converting column position to base 1)
937 if (lastPosFound != 0)
939 updateCursor(lastPosFound, lastPosFoundColumn + 1,
940 firstResidueColumn + 1);
947 * Answers true if the given cursor is not null, is for this sequence object,
948 * and has a token value that matches this object's changeCount, else false.
949 * This allows us to ignore a cursor as 'stale' if the sequence has been
950 * modified since the cursor was created.
955 protected boolean isValidCursor(SequenceCursor curs)
957 if (curs == null || curs.sequence != this || curs.token != changeCount)
962 * sanity check against range
964 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
968 if (curs.residuePosition < start || curs.residuePosition > end)
976 * Answers the sequence position (start..) for the given aligned column
977 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
978 * may lie left of, at, or to the right of the column position.
984 protected int findPosition(final int col, SequenceCursor curs)
986 if (!isValidCursor(curs))
989 * wrong or invalidated cursor, compute de novo
991 return findPosition(col - 1);// ugh back to base 0
994 if (curs.columnPosition == col)
996 cursor = curs; // in case this method becomes public
997 return curs.residuePosition; // easy case :-)
1000 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1003 * sequence lies entirely to the left of col
1004 * - return last residue + 1
1009 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1012 * sequence lies entirely to the right of col
1013 * - return first residue
1018 // todo could choose closest to col out of column,
1019 // firstColumnPosition, lastColumnPosition as a start point
1022 * move left or right to find pos from cursor position
1024 int firstResidueColumn = curs.firstColumnPosition;
1025 int column = curs.columnPosition - 1; // to base 0
1026 int newPos = curs.residuePosition;
1027 int delta = curs.columnPosition > col ? -1 : 1;
1028 boolean gapped = false;
1029 int lastFoundPosition = curs.residuePosition;
1030 int lastFoundPositionColumn = curs.columnPosition;
1032 while (column != col - 1)
1034 column += delta; // shift one column left or right
1035 if (column < 0 || column == sequence.length)
1039 gapped = Comparison.isGap(sequence[column]);
1043 lastFoundPosition = newPos;
1044 lastFoundPositionColumn = column + 1;
1045 if (lastFoundPosition == this.start)
1047 firstResidueColumn = column + 1;
1052 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1054 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1055 firstResidueColumn);
1059 * hack to give position to the right if on a gap
1060 * or beyond the length of the sequence (see JAL-2562)
1062 if (delta > 0 && (gapped || column >= sequence.length))
1074 public Range findPositions(int fromColumn, int toColumn)
1076 if (toColumn < fromColumn || fromColumn < 1)
1082 * find the first non-gapped position, if any
1084 int firstPosition = 0;
1085 int col = fromColumn - 1;
1086 int length = sequence.length;
1087 while (col < length && col < toColumn)
1089 if (!Comparison.isGap(sequence[col]))
1091 firstPosition = findPosition(col++);
1097 if (firstPosition == 0)
1103 * find the last non-gapped position
1105 int lastPosition = firstPosition;
1106 while (col < length && col < toColumn)
1108 if (!Comparison.isGap(sequence[col++]))
1114 return new Range(firstPosition, lastPosition);
1118 * Returns an int array where indices correspond to each residue in the
1119 * sequence and the element value gives its position in the alignment
1121 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1122 * residues in SequenceI object
1125 public int[] gapMap()
1127 String seq = jalview.analysis.AlignSeq.extractGaps(
1128 jalview.util.Comparison.GapChars, new String(sequence));
1129 int[] map = new int[seq.length()];
1133 while (j < sequence.length)
1135 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
1247 int startIndex = findIndex(start) - 1;
1248 int endIndex = findIndex(end) - 1;
1249 int startDeleteColumn = -1; // for dataset sequence deletions
1250 int deleteCount = 0;
1252 for (int s = i; s < j; s++)
1254 if (Comparison.isGap(sequence[s]))
1259 if (startDeleteColumn == -1)
1261 startDeleteColumn = findPosition(s) - start;
1269 if (startIndex == s)
1272 * deleting characters from start of sequence; new start is the
1273 * sequence position of the next column (position to the right
1274 * if the column position is gapped)
1276 newstart = findPosition(j);
1284 * deleting characters at end of sequence; new end is the sequence
1285 * position of the column before the deletion; subtract 1 if this is
1286 * gapped since findPosition returns the next sequence position
1288 newend = findPosition(i - 1);
1289 if (Comparison.isGap(sequence[i - 1]))
1304 if (createNewDs && this.datasetSequence != null)
1307 * if deletion occured in the middle of the sequence,
1308 * construct a new dataset sequence and delete the residues
1309 * that were deleted from the aligned sequence
1311 Sequence ds = new Sequence(datasetSequence);
1312 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1313 datasetSequence = ds;
1314 // TODO: remove any non-inheritable properties ?
1315 // TODO: create a sequence mapping (since there is a relation here ?)
1324 public void insertCharAt(int i, int length, char c)
1326 char[] tmp = new char[sequence.length + length];
1328 if (i >= sequence.length)
1330 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1331 i = sequence.length;
1335 System.arraycopy(sequence, 0, tmp, 0, i);
1345 if (i < sequence.length)
1347 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1355 public void insertCharAt(int i, char c)
1357 insertCharAt(i, 1, c);
1361 public String getVamsasId()
1367 public void setVamsasId(String id)
1373 public void setDBRefs(DBRefEntry[] dbref)
1375 if (dbrefs == null && datasetSequence != null
1376 && this != datasetSequence)
1378 datasetSequence.setDBRefs(dbref);
1384 DBRefUtils.ensurePrimaries(this);
1389 public DBRefEntry[] getDBRefs()
1391 if (dbrefs == null && datasetSequence != null
1392 && this != datasetSequence)
1394 return datasetSequence.getDBRefs();
1400 public void addDBRef(DBRefEntry entry)
1402 if (datasetSequence != null)
1404 datasetSequence.addDBRef(entry);
1410 dbrefs = new DBRefEntry[0];
1413 for (DBRefEntryI dbr : dbrefs)
1415 if (dbr.updateFrom(entry))
1418 * found a dbref that either matched, or could be
1419 * updated from, the new entry - no need to add it
1426 * extend the array to make room for one more
1428 // TODO use an ArrayList instead
1429 int j = dbrefs.length;
1430 DBRefEntry[] temp = new DBRefEntry[j + 1];
1431 System.arraycopy(dbrefs, 0, temp, 0, j);
1432 temp[temp.length - 1] = entry;
1436 DBRefUtils.ensurePrimaries(this);
1440 public void setDatasetSequence(SequenceI seq)
1444 throw new IllegalArgumentException(
1445 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1447 if (seq != null && seq.getDatasetSequence() != null)
1449 throw new IllegalArgumentException(
1450 "Implementation error: cascading dataset sequences are not allowed.");
1452 datasetSequence = seq;
1456 public SequenceI getDatasetSequence()
1458 return datasetSequence;
1462 public AlignmentAnnotation[] getAnnotation()
1464 return annotation == null ? null
1466 .toArray(new AlignmentAnnotation[annotation.size()]);
1470 public boolean hasAnnotation(AlignmentAnnotation ann)
1472 return annotation == null ? false : annotation.contains(ann);
1476 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1478 if (this.annotation == null)
1480 this.annotation = new Vector<>();
1482 if (!this.annotation.contains(annotation))
1484 this.annotation.addElement(annotation);
1486 annotation.setSequenceRef(this);
1490 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1492 if (this.annotation != null)
1494 this.annotation.removeElement(annotation);
1495 if (this.annotation.size() == 0)
1497 this.annotation = null;
1503 * test if this is a valid candidate for another sequence's dataset sequence.
1506 private boolean isValidDatasetSequence()
1508 if (datasetSequence != null)
1512 for (int i = 0; i < sequence.length; i++)
1514 if (jalview.util.Comparison.isGap(sequence[i]))
1523 public SequenceI deriveSequence()
1525 Sequence seq = null;
1526 if (datasetSequence == null)
1528 if (isValidDatasetSequence())
1530 // Use this as dataset sequence
1531 seq = new Sequence(getName(), "", 1, -1);
1532 seq.setDatasetSequence(this);
1533 seq.initSeqFrom(this, getAnnotation());
1538 // Create a new, valid dataset sequence
1539 createDatasetSequence();
1542 return new Sequence(this);
1545 private boolean _isNa;
1547 private int _seqhash = 0;
1550 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1554 public boolean isProtein()
1556 if (datasetSequence != null)
1558 return datasetSequence.isProtein();
1560 if (_seqhash != sequence.hashCode())
1562 _seqhash = sequence.hashCode();
1563 _isNa = Comparison.isNucleotide(this);
1571 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1574 public SequenceI createDatasetSequence()
1576 if (datasetSequence == null)
1578 Sequence dsseq = new Sequence(getName(),
1579 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1580 getSequenceAsString()),
1581 getStart(), getEnd());
1583 datasetSequence = dsseq;
1585 dsseq.setDescription(description);
1586 // move features and database references onto dataset sequence
1587 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1588 sequenceFeatureStore = null;
1589 dsseq.dbrefs = dbrefs;
1591 // TODO: search and replace any references to this sequence with
1592 // references to the dataset sequence in Mappings on dbref
1593 dsseq.pdbIds = pdbIds;
1595 datasetSequence.updatePDBIds();
1596 if (annotation != null)
1598 // annotation is cloned rather than moved, to preserve what's currently
1600 for (AlignmentAnnotation aa : annotation)
1602 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1603 _aa.sequenceRef = datasetSequence;
1604 _aa.adjustForAlignment(); // uses annotation's own record of
1605 // sequence-column mapping
1606 datasetSequence.addAlignmentAnnotation(_aa);
1610 return datasetSequence;
1617 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1621 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1623 if (annotation != null)
1625 annotation.removeAllElements();
1627 if (annotations != null)
1629 for (int i = 0; i < annotations.length; i++)
1631 if (annotations[i] != null)
1633 addAlignmentAnnotation(annotations[i]);
1640 public AlignmentAnnotation[] getAnnotation(String label)
1642 if (annotation == null || annotation.size() == 0)
1647 Vector<AlignmentAnnotation> subset = new Vector<>();
1648 Enumeration<AlignmentAnnotation> e = annotation.elements();
1649 while (e.hasMoreElements())
1651 AlignmentAnnotation ann = e.nextElement();
1652 if (ann.label != null && ann.label.equals(label))
1654 subset.addElement(ann);
1657 if (subset.size() == 0)
1661 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1663 e = subset.elements();
1664 while (e.hasMoreElements())
1666 anns[i++] = e.nextElement();
1668 subset.removeAllElements();
1673 public boolean updatePDBIds()
1675 if (datasetSequence != null)
1677 // TODO: could merge DBRefs
1678 return datasetSequence.updatePDBIds();
1680 if (dbrefs == null || dbrefs.length == 0)
1684 boolean added = false;
1685 for (DBRefEntry dbr : dbrefs)
1687 if (DBRefSource.PDB.equals(dbr.getSource()))
1690 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1691 * PDB id is not already present in a 'matching' PDBEntry
1692 * Constructor parses out a chain code if appended to the accession id
1693 * (a fudge used to 'store' the chain code in the DBRef)
1695 PDBEntry pdbe = new PDBEntry(dbr);
1696 added |= addPDBId(pdbe);
1703 public void transferAnnotation(SequenceI entry, Mapping mp)
1705 if (datasetSequence != null)
1707 datasetSequence.transferAnnotation(entry, mp);
1710 if (entry.getDatasetSequence() != null)
1712 transferAnnotation(entry.getDatasetSequence(), mp);
1715 // transfer any new features from entry onto sequence
1716 if (entry.getSequenceFeatures() != null)
1719 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1720 for (SequenceFeature feature : sfs)
1722 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1723 : new SequenceFeature[] { new SequenceFeature(feature) };
1726 for (int sfi = 0; sfi < sf.length; sfi++)
1728 addSequenceFeature(sf[sfi]);
1734 // transfer PDB entries
1735 if (entry.getAllPDBEntries() != null)
1737 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1738 while (e.hasMoreElements())
1740 PDBEntry pdb = e.nextElement();
1744 // transfer database references
1745 DBRefEntry[] entryRefs = entry.getDBRefs();
1746 if (entryRefs != null)
1748 for (int r = 0; r < entryRefs.length; r++)
1750 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1751 if (newref.getMap() != null && mp != null)
1753 // remap ref using our local mapping
1755 // we also assume all version string setting is done by dbSourceProxy
1757 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1758 * newref.setSource(dbSource); }
1766 public void setRNA(RNA r)
1778 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1781 List<AlignmentAnnotation> result = new ArrayList<>();
1782 if (this.annotation != null)
1784 for (AlignmentAnnotation ann : annotation)
1786 String id = ann.getCalcId();
1787 if (id != null && id.equals(calcId)
1788 && ann.label != null && ann.label.equals(label))
1798 public String toString()
1800 return getDisplayId(false);
1804 public PDBEntry getPDBEntry(String pdbIdStr)
1806 if (getDatasetSequence() != null)
1808 return getDatasetSequence().getPDBEntry(pdbIdStr);
1814 List<PDBEntry> entries = getAllPDBEntries();
1815 for (PDBEntry entry : entries)
1817 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1826 public List<DBRefEntry> getPrimaryDBRefs()
1828 if (datasetSequence != null)
1830 return datasetSequence.getPrimaryDBRefs();
1832 if (dbrefs == null || dbrefs.length == 0)
1834 return Collections.emptyList();
1836 synchronized (dbrefs)
1838 List<DBRefEntry> primaries = new ArrayList<>();
1839 DBRefEntry[] tmp = new DBRefEntry[1];
1840 for (DBRefEntry ref : dbrefs)
1842 if (!ref.isPrimaryCandidate())
1848 MapList mp = ref.getMap().getMap();
1849 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1851 // map only involves a subsequence, so cannot be primary
1855 // whilst it looks like it is a primary ref, we also sanity check type
1856 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1857 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1859 // PDB dbrefs imply there should be a PDBEntry associated
1860 // TODO: tighten PDB dbrefs
1861 // formally imply Jalview has actually downloaded and
1862 // parsed the pdb file. That means there should be a cached file
1863 // handle on the PDBEntry, and a real mapping between sequence and
1864 // extracted sequence from PDB file
1865 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1866 if (pdbentry != null && pdbentry.getFile() != null)
1872 // check standard protein or dna sources
1874 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1875 if (res != null && res[0] == tmp[0])
1886 public HiddenMarkovModel getHMM()
1892 public void setHMM(HiddenMarkovModel hmm)
1898 public void updateHMMMapping()
1904 hmm.updateMapping(sequence);
1908 * Maps the HMM sequence to the reference annotation.
1913 public void mapToReference(AlignmentAnnotation rf)
1915 if (this.isHMMConsensusSequence)
1918 hmm.clearNodeLookup();
1919 for (int i = 0; i < getLength(); i++)
1921 if (rf.annotations[i].displayCharacter.equalsIgnoreCase("x"))
1923 if (i < hmm.getNodeAlignmentColumn(node))
1925 this.deleteChars(i, hmm.getNodeAlignmentColumn(node));
1928 else if (i > hmm.getNodeAlignmentColumn(node))
1930 int length = i - hmm.getNodeAlignmentColumn(node);
1931 this.insertCharAt(hmm.getNodeAlignmentColumn(node), length,
1942 public boolean isHMMConsensusSequence()
1944 return isHMMConsensusSequence;
1948 public void setIsHMMConsensusSequence(boolean isHMMConsensusSequence)
1950 this.isHMMConsensusSequence = isHMMConsensusSequence;
1954 public boolean hasHMMAnnotation()
1960 public void setHasInfo(boolean status)
1969 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1972 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1973 int endPos = fromColumn == toColumn ? startPos
1974 : findPosition(toColumn - 1);
1976 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1980 * if end column is gapped, endPos may be to the right,
1981 * and we may have included adjacent or enclosing features;
1982 * remove any that are not enclosing, non-contact features
1984 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1985 && Comparison.isGap(sequence[toColumn - 1]);
1986 if (endPos > this.end || endColumnIsGapped)
1988 ListIterator<SequenceFeature> it = result.listIterator();
1989 while (it.hasNext())
1991 SequenceFeature sf = it.next();
1992 int sfBegin = sf.getBegin();
1993 int sfEnd = sf.getEnd();
1994 int featureStartColumn = findIndex(sfBegin);
1995 if (featureStartColumn > toColumn)
1999 else if (featureStartColumn < fromColumn)
2001 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2003 if (featureEndColumn < fromColumn)
2007 else if (featureEndColumn > toColumn && sf.isContactFeature())
2010 * remove an enclosing feature if it is a contact feature
2022 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2023 * token that has to match the one presented by the cursor
2026 public void sequenceChanged()
2035 public int replace(char c1, char c2)
2042 synchronized (sequence)
2044 for (int c = 0; c < sequence.length; c++)
2046 if (sequence[c] == c1)