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.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 * Build a bitset corresponding to sequence gaps
1149 * @return a BitSet where set values correspond to gaps in the sequence
1152 public BitSet gapBitset()
1154 BitSet gaps = new BitSet(sequence.length);
1156 while (j < sequence.length)
1158 if (jalview.util.Comparison.isGap(sequence[j]))
1168 public int[] findPositionMap()
1170 int map[] = new int[sequence.length];
1173 int seqlen = sequence.length;
1174 while ((j < seqlen))
1177 if (!jalview.util.Comparison.isGap(sequence[j]))
1188 public List<int[]> getInsertions()
1190 ArrayList<int[]> map = new ArrayList<>();
1191 int lastj = -1, j = 0;
1193 int seqlen = sequence.length;
1194 while ((j < seqlen))
1196 if (jalview.util.Comparison.isGap(sequence[j]))
1207 map.add(new int[] { lastj, j - 1 });
1215 map.add(new int[] { lastj, j - 1 });
1222 public BitSet getInsertionsAsBits()
1224 BitSet map = new BitSet();
1225 int lastj = -1, j = 0;
1227 int seqlen = sequence.length;
1228 while ((j < seqlen))
1230 if (jalview.util.Comparison.isGap(sequence[j]))
1256 public void deleteChars(final int i, final int j)
1258 int newstart = start, newend = end;
1259 if (i >= sequence.length || i < 0)
1264 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1265 boolean createNewDs = false;
1266 // TODO: take a (second look) at the dataset creation validation method for
1267 // the very large sequence case
1268 int startIndex = findIndex(start) - 1;
1269 int endIndex = findIndex(end) - 1;
1270 int startDeleteColumn = -1; // for dataset sequence deletions
1271 int deleteCount = 0;
1273 for (int s = i; s < j; s++)
1275 if (Comparison.isGap(sequence[s]))
1280 if (startDeleteColumn == -1)
1282 startDeleteColumn = findPosition(s) - start;
1290 if (startIndex == s)
1293 * deleting characters from start of sequence; new start is the
1294 * sequence position of the next column (position to the right
1295 * if the column position is gapped)
1297 newstart = findPosition(j);
1305 * deleting characters at end of sequence; new end is the sequence
1306 * position of the column before the deletion; subtract 1 if this is
1307 * gapped since findPosition returns the next sequence position
1309 newend = findPosition(i - 1);
1310 if (Comparison.isGap(sequence[i - 1]))
1325 if (createNewDs && this.datasetSequence != null)
1328 * if deletion occured in the middle of the sequence,
1329 * construct a new dataset sequence and delete the residues
1330 * that were deleted from the aligned sequence
1332 Sequence ds = new Sequence(datasetSequence);
1333 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1334 datasetSequence = ds;
1335 // TODO: remove any non-inheritable properties ?
1336 // TODO: create a sequence mapping (since there is a relation here ?)
1345 public void insertCharAt(int i, int length, char c)
1347 char[] tmp = new char[sequence.length + length];
1349 if (i >= sequence.length)
1351 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1352 i = sequence.length;
1356 System.arraycopy(sequence, 0, tmp, 0, i);
1366 if (i < sequence.length)
1368 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1376 public void insertCharAt(int i, char c)
1378 insertCharAt(i, 1, c);
1382 public String getVamsasId()
1388 public void setVamsasId(String id)
1394 public void setDBRefs(DBRefEntry[] dbref)
1396 if (dbrefs == null && datasetSequence != null
1397 && this != datasetSequence)
1399 datasetSequence.setDBRefs(dbref);
1405 DBRefUtils.ensurePrimaries(this);
1410 public DBRefEntry[] getDBRefs()
1412 if (dbrefs == null && datasetSequence != null
1413 && this != datasetSequence)
1415 return datasetSequence.getDBRefs();
1421 public void addDBRef(DBRefEntry entry)
1423 if (datasetSequence != null)
1425 datasetSequence.addDBRef(entry);
1431 dbrefs = new DBRefEntry[0];
1434 for (DBRefEntryI dbr : dbrefs)
1436 if (dbr.updateFrom(entry))
1439 * found a dbref that either matched, or could be
1440 * updated from, the new entry - no need to add it
1447 * extend the array to make room for one more
1449 // TODO use an ArrayList instead
1450 int j = dbrefs.length;
1451 DBRefEntry[] temp = new DBRefEntry[j + 1];
1452 System.arraycopy(dbrefs, 0, temp, 0, j);
1453 temp[temp.length - 1] = entry;
1457 DBRefUtils.ensurePrimaries(this);
1461 public void setDatasetSequence(SequenceI seq)
1465 throw new IllegalArgumentException(
1466 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1468 if (seq != null && seq.getDatasetSequence() != null)
1470 throw new IllegalArgumentException(
1471 "Implementation error: cascading dataset sequences are not allowed.");
1473 datasetSequence = seq;
1477 public SequenceI getDatasetSequence()
1479 return datasetSequence;
1483 public AlignmentAnnotation[] getAnnotation()
1485 return annotation == null ? null
1487 .toArray(new AlignmentAnnotation[annotation.size()]);
1491 public boolean hasAnnotation(AlignmentAnnotation ann)
1493 return annotation == null ? false : annotation.contains(ann);
1497 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1499 if (this.annotation == null)
1501 this.annotation = new Vector<>();
1503 if (!this.annotation.contains(annotation))
1505 this.annotation.addElement(annotation);
1507 annotation.setSequenceRef(this);
1511 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1513 if (this.annotation != null)
1515 this.annotation.removeElement(annotation);
1516 if (this.annotation.size() == 0)
1518 this.annotation = null;
1524 * test if this is a valid candidate for another sequence's dataset sequence.
1527 private boolean isValidDatasetSequence()
1529 if (datasetSequence != null)
1533 for (int i = 0; i < sequence.length; i++)
1535 if (jalview.util.Comparison.isGap(sequence[i]))
1544 public SequenceI deriveSequence()
1546 Sequence seq = null;
1547 if (datasetSequence == null)
1549 if (isValidDatasetSequence())
1551 // Use this as dataset sequence
1552 seq = new Sequence(getName(), "", 1, -1);
1553 seq.setDatasetSequence(this);
1554 seq.initSeqFrom(this, getAnnotation());
1559 // Create a new, valid dataset sequence
1560 createDatasetSequence();
1563 return new Sequence(this);
1566 private boolean _isNa;
1568 private int _seqhash = 0;
1571 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1575 public boolean isProtein()
1577 if (datasetSequence != null)
1579 return datasetSequence.isProtein();
1581 if (_seqhash != sequence.hashCode())
1583 _seqhash = sequence.hashCode();
1584 _isNa = Comparison.isNucleotide(this);
1592 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1595 public SequenceI createDatasetSequence()
1597 if (datasetSequence == null)
1599 Sequence dsseq = new Sequence(getName(),
1600 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1601 getSequenceAsString()),
1602 getStart(), getEnd());
1604 datasetSequence = dsseq;
1606 dsseq.setDescription(description);
1607 // move features and database references onto dataset sequence
1608 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1609 sequenceFeatureStore = null;
1610 dsseq.dbrefs = dbrefs;
1612 // TODO: search and replace any references to this sequence with
1613 // references to the dataset sequence in Mappings on dbref
1614 dsseq.pdbIds = pdbIds;
1616 datasetSequence.updatePDBIds();
1617 if (annotation != null)
1619 // annotation is cloned rather than moved, to preserve what's currently
1621 for (AlignmentAnnotation aa : annotation)
1623 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1624 _aa.sequenceRef = datasetSequence;
1625 _aa.adjustForAlignment(); // uses annotation's own record of
1626 // sequence-column mapping
1627 datasetSequence.addAlignmentAnnotation(_aa);
1631 return datasetSequence;
1638 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1642 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1644 if (annotation != null)
1646 annotation.removeAllElements();
1648 if (annotations != null)
1650 for (int i = 0; i < annotations.length; i++)
1652 if (annotations[i] != null)
1654 addAlignmentAnnotation(annotations[i]);
1661 public AlignmentAnnotation[] getAnnotation(String label)
1663 if (annotation == null || annotation.size() == 0)
1668 Vector<AlignmentAnnotation> subset = new Vector<>();
1669 Enumeration<AlignmentAnnotation> e = annotation.elements();
1670 while (e.hasMoreElements())
1672 AlignmentAnnotation ann = e.nextElement();
1673 if (ann.label != null && ann.label.equals(label))
1675 subset.addElement(ann);
1678 if (subset.size() == 0)
1682 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1684 e = subset.elements();
1685 while (e.hasMoreElements())
1687 anns[i++] = e.nextElement();
1689 subset.removeAllElements();
1694 public boolean updatePDBIds()
1696 if (datasetSequence != null)
1698 // TODO: could merge DBRefs
1699 return datasetSequence.updatePDBIds();
1701 if (dbrefs == null || dbrefs.length == 0)
1705 boolean added = false;
1706 for (DBRefEntry dbr : dbrefs)
1708 if (DBRefSource.PDB.equals(dbr.getSource()))
1711 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1712 * PDB id is not already present in a 'matching' PDBEntry
1713 * Constructor parses out a chain code if appended to the accession id
1714 * (a fudge used to 'store' the chain code in the DBRef)
1716 PDBEntry pdbe = new PDBEntry(dbr);
1717 added |= addPDBId(pdbe);
1724 public void transferAnnotation(SequenceI entry, Mapping mp)
1726 if (datasetSequence != null)
1728 datasetSequence.transferAnnotation(entry, mp);
1731 if (entry.getDatasetSequence() != null)
1733 transferAnnotation(entry.getDatasetSequence(), mp);
1736 // transfer any new features from entry onto sequence
1737 if (entry.getSequenceFeatures() != null)
1740 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1741 for (SequenceFeature feature : sfs)
1743 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1744 : new SequenceFeature[] { new SequenceFeature(feature) };
1747 for (int sfi = 0; sfi < sf.length; sfi++)
1749 addSequenceFeature(sf[sfi]);
1755 // transfer PDB entries
1756 if (entry.getAllPDBEntries() != null)
1758 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1759 while (e.hasMoreElements())
1761 PDBEntry pdb = e.nextElement();
1765 // transfer database references
1766 DBRefEntry[] entryRefs = entry.getDBRefs();
1767 if (entryRefs != null)
1769 for (int r = 0; r < entryRefs.length; r++)
1771 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1772 if (newref.getMap() != null && mp != null)
1774 // remap ref using our local mapping
1776 // we also assume all version string setting is done by dbSourceProxy
1778 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1779 * newref.setSource(dbSource); }
1787 public void setRNA(RNA r)
1799 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1802 List<AlignmentAnnotation> result = new ArrayList<>();
1803 if (this.annotation != null)
1805 for (AlignmentAnnotation ann : annotation)
1807 String id = ann.getCalcId();
1808 if (id != null && id.equals(calcId)
1809 && ann.label != null && ann.label.equals(label))
1819 public String toString()
1821 return getDisplayId(false);
1825 public PDBEntry getPDBEntry(String pdbIdStr)
1827 if (getDatasetSequence() != null)
1829 return getDatasetSequence().getPDBEntry(pdbIdStr);
1835 List<PDBEntry> entries = getAllPDBEntries();
1836 for (PDBEntry entry : entries)
1838 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1847 public List<DBRefEntry> getPrimaryDBRefs()
1849 if (datasetSequence != null)
1851 return datasetSequence.getPrimaryDBRefs();
1853 if (dbrefs == null || dbrefs.length == 0)
1855 return Collections.emptyList();
1857 synchronized (dbrefs)
1859 List<DBRefEntry> primaries = new ArrayList<>();
1860 DBRefEntry[] tmp = new DBRefEntry[1];
1861 for (DBRefEntry ref : dbrefs)
1863 if (!ref.isPrimaryCandidate())
1869 MapList mp = ref.getMap().getMap();
1870 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1872 // map only involves a subsequence, so cannot be primary
1876 // whilst it looks like it is a primary ref, we also sanity check type
1877 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1878 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1880 // PDB dbrefs imply there should be a PDBEntry associated
1881 // TODO: tighten PDB dbrefs
1882 // formally imply Jalview has actually downloaded and
1883 // parsed the pdb file. That means there should be a cached file
1884 // handle on the PDBEntry, and a real mapping between sequence and
1885 // extracted sequence from PDB file
1886 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1887 if (pdbentry != null && pdbentry.getFile() != null)
1893 // check standard protein or dna sources
1895 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1896 if (res != null && res[0] == tmp[0])
1907 public HiddenMarkovModel getHMM()
1913 public void setHMM(HiddenMarkovModel hmm)
1919 public void updateHMMMapping()
1925 hmm.updateMapping(sequence);
1929 * Maps the HMM sequence to the reference annotation.
1934 public void mapToReference(AlignmentAnnotation rf)
1936 if (this.isHMMConsensusSequence)
1939 hmm.clearNodeLookup();
1940 for (int i = 0; i < getLength(); i++)
1942 if (rf.annotations[i].displayCharacter.equalsIgnoreCase("x"))
1944 if (i < hmm.getNodeAlignmentColumn(node))
1946 this.deleteChars(i, hmm.getNodeAlignmentColumn(node));
1949 else if (i > hmm.getNodeAlignmentColumn(node))
1951 int length = i - hmm.getNodeAlignmentColumn(node);
1952 this.insertCharAt(hmm.getNodeAlignmentColumn(node), length,
1963 public boolean isHMMConsensusSequence()
1965 return isHMMConsensusSequence;
1969 public void setIsHMMConsensusSequence(boolean value)
1971 this.isHMMConsensusSequence = value;
1975 public boolean hasHMMAnnotation()
1977 if (this.annotation == null) {
1980 for (AlignmentAnnotation ann : annotation)
1982 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1994 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1997 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1998 int endPos = fromColumn == toColumn ? startPos
1999 : findPosition(toColumn - 1);
2001 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
2005 * if end column is gapped, endPos may be to the right,
2006 * and we may have included adjacent or enclosing features;
2007 * remove any that are not enclosing, non-contact features
2009 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
2010 && Comparison.isGap(sequence[toColumn - 1]);
2011 if (endPos > this.end || endColumnIsGapped)
2013 ListIterator<SequenceFeature> it = result.listIterator();
2014 while (it.hasNext())
2016 SequenceFeature sf = it.next();
2017 int sfBegin = sf.getBegin();
2018 int sfEnd = sf.getEnd();
2019 int featureStartColumn = findIndex(sfBegin);
2020 if (featureStartColumn > toColumn)
2024 else if (featureStartColumn < fromColumn)
2026 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2028 if (featureEndColumn < fromColumn)
2032 else if (featureEndColumn > toColumn && sf.isContactFeature())
2035 * remove an enclosing feature if it is a contact feature
2047 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2048 * token that has to match the one presented by the cursor
2051 public void sequenceChanged()
2060 public int replace(char c1, char c2)
2067 synchronized (sequence)
2069 for (int c = 0; c < sequence.length; c++)
2071 if (sequence[c] == c1)
2087 public String getSequenceStringFromIterator(Iterator<int[]> it)
2089 StringBuilder newSequence = new StringBuilder();
2090 while (it.hasNext())
2092 int[] block = it.next();
2095 newSequence.append(getSequence(block[0], block[1] + 1));
2099 newSequence.append(getSequence(block[0], block[1]));
2103 return newSequence.toString();
2107 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2111 if (!regions.hasNext())
2113 return findIndex(getStart()) - 1;
2116 // Simply walk along the sequence whilst watching for region
2118 int hideStart = getLength();
2120 boolean foundStart = false;
2122 // step through the non-gapped positions of the sequence
2123 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2125 // get alignment position of this residue in the sequence
2126 int p = findIndex(i) - 1;
2128 // update region start/end
2129 while (hideEnd < p && regions.hasNext())
2131 int[] region = regions.next();
2132 hideStart = region[0];
2133 hideEnd = region[1];
2137 hideStart = getLength();
2139 // update boundary for sequence
2151 // otherwise, sequence was completely hidden