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.List;
39 import java.util.ListIterator;
40 import java.util.Vector;
42 import fr.orsay.lri.varna.models.rna.RNA;
46 * Implements the SequenceI interface for a char[] based sequence object.
51 public class Sequence extends ASequence implements SequenceI
53 SequenceI datasetSequence;
57 private char[] sequence;
65 HiddenMarkovModel hmm;
67 boolean isHMMConsensusSequence = false;
69 Vector<PDBEntry> pdbIds;
78 * This annotation is displayed below the alignment but the positions are tied
79 * to the residues of this sequence
81 * TODO: change to List<>
83 Vector<AlignmentAnnotation> annotation;
85 private SequenceFeaturesI sequenceFeatureStore;
88 * A cursor holding the approximate current view position to the sequence,
89 * as determined by findIndex or findPosition or findPositions.
90 * Using a cursor as a hint allows these methods to be more performant for
93 private SequenceCursor cursor;
96 * A number that should be incremented whenever the sequence is edited.
97 * If the value matches the cursor token, then we can trust the cursor,
98 * if not then it should be recomputed.
100 private int changeCount;
103 * Creates a new Sequence object.
106 * display name string
108 * string to form a possibly gapped sequence out of
110 * first position of non-gap residue in the sequence
112 * last position of ungapped residues (nearly always only used for
115 public Sequence(String name, String sequence, int start, int end)
118 initSeqAndName(name, sequence.toCharArray(), start, end);
121 public Sequence(String name, char[] sequence, int start, int end)
124 initSeqAndName(name, sequence, start, end);
128 * Stage 1 constructor - assign name, sequence, and set start and end fields.
129 * start and end are updated values from name2 if it ends with /start-end
136 protected void initSeqAndName(String name2, char[] sequence2, int start2,
140 this.sequence = sequence2;
148 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
149 * start and end respectively and removes the suffix from the name
156 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
159 int slashPos = name.lastIndexOf('/');
160 if (slashPos > -1 && slashPos < name.length() - 1)
162 String suffix = name.substring(slashPos + 1);
163 String[] range = suffix.split("-");
164 if (range.length == 2)
168 int from = Integer.valueOf(range[0]);
169 int to = Integer.valueOf(range[1]);
170 if (from > 0 && to >= from)
172 name = name.substring(0, slashPos);
177 } catch (NumberFormatException e)
179 // leave name unchanged if suffix is invalid
186 * Ensures that 'end' is not before the end of the sequence, that is,
187 * (end-start+1) is at least as long as the count of ungapped positions. Note
188 * that end is permitted to be beyond the end of the sequence data.
190 void checkValidRange()
193 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
196 for (int j = 0; j < sequence.length; j++)
198 if (!Comparison.isGap(sequence[j]))
217 * default constructor
221 sequenceFeatureStore = new SequenceFeatures();
225 * Creates a new Sequence object.
232 public Sequence(String name, String sequence)
234 this(name, sequence, 1, -1);
238 * Creates a new Sequence object with new AlignmentAnnotations but inherits
239 * any existing dataset sequence reference. If non exists, everything is
243 * if seq is a dataset sequence, behaves like a plain old copy
246 public Sequence(SequenceI seq)
248 this(seq, seq.getAnnotation());
252 * Create a new sequence object with new features, DBRefEntries, and PDBIds
253 * but inherits any existing dataset sequence reference, and duplicate of any
254 * annotation that is present in the given annotation array.
257 * the sequence to be copied
258 * @param alAnnotation
259 * an array of annotation including some associated with seq
261 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
264 initSeqFrom(seq, alAnnotation);
268 * does the heavy lifting when cloning a dataset sequence, or coping data from
269 * dataset to a new derived sequence.
272 * - source of attributes.
273 * @param alAnnotation
274 * - alignment annotation present on seq that should be copied onto
277 protected void initSeqFrom(SequenceI seq,
278 AlignmentAnnotation[] alAnnotation)
280 char[] oseq = seq.getSequence(); // returns a copy of the array
281 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
283 description = seq.getDescription();
284 if (seq != datasetSequence)
286 setDatasetSequence(seq.getDatasetSequence());
290 * only copy DBRefs and seqfeatures if we really are a dataset sequence
292 if (datasetSequence == null)
294 if (seq.getDBRefs() != null)
296 DBRefEntry[] dbr = seq.getDBRefs();
297 for (int i = 0; i < dbr.length; i++)
299 addDBRef(new DBRefEntry(dbr[i]));
304 * make copies of any sequence features
306 for (SequenceFeature sf : seq.getSequenceFeatures())
308 addSequenceFeature(new SequenceFeature(sf));
312 if (seq.getAnnotation() != null)
314 AlignmentAnnotation[] sqann = seq.getAnnotation();
315 for (int i = 0; i < sqann.length; i++)
317 if (sqann[i] == null)
321 boolean found = (alAnnotation == null);
324 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
326 found = (alAnnotation[apos] == sqann[i]);
331 // only copy the given annotation
332 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
333 addAlignmentAnnotation(newann);
337 if (seq.getAllPDBEntries() != null)
339 Vector<PDBEntry> ids = seq.getAllPDBEntries();
340 for (PDBEntry pdb : ids)
342 this.addPDBId(new PDBEntry(pdb));
345 if (seq.isHMMConsensusSequence())
347 this.isHMMConsensusSequence = true;
349 if (seq.getHMM() != null)
351 this.hmm = new HiddenMarkovModel(seq.getHMM());
357 public void setSequenceFeatures(List<SequenceFeature> features)
359 if (datasetSequence != null)
361 datasetSequence.setSequenceFeatures(features);
364 sequenceFeatureStore = new SequenceFeatures(features);
368 public synchronized boolean addSequenceFeature(SequenceFeature sf)
370 if (sf.getType() == null)
372 System.err.println("SequenceFeature type may not be null: "
377 if (datasetSequence != null)
379 return datasetSequence.addSequenceFeature(sf);
382 return sequenceFeatureStore.add(sf);
386 public void deleteFeature(SequenceFeature sf)
388 if (datasetSequence != null)
390 datasetSequence.deleteFeature(sf);
394 sequenceFeatureStore.delete(sf);
404 public List<SequenceFeature> getSequenceFeatures()
406 if (datasetSequence != null)
408 return datasetSequence.getSequenceFeatures();
410 return sequenceFeatureStore.getAllFeatures();
414 public SequenceFeaturesI getFeatures()
416 return datasetSequence != null ? datasetSequence.getFeatures()
417 : sequenceFeatureStore;
421 public boolean addPDBId(PDBEntry entry)
425 pdbIds = new Vector<>();
430 for (PDBEntry pdbe : pdbIds)
432 if (pdbe.updateFrom(entry))
437 pdbIds.addElement(entry);
448 public void setPDBId(Vector<PDBEntry> id)
456 * @return DOCUMENT ME!
459 public Vector<PDBEntry> getAllPDBEntries()
461 return pdbIds == null ? new Vector<>() : pdbIds;
467 * @return DOCUMENT ME!
470 public String getDisplayId(boolean jvsuffix)
472 StringBuffer result = new StringBuffer(name);
475 result.append("/" + start + "-" + end);
478 return result.toString();
482 * Sets the sequence name. If the name ends in /start-end, then the start-end
483 * values are parsed out and set, and the suffix is removed from the name.
488 public void setName(String theName)
497 * @return DOCUMENT ME!
500 public String getName()
512 public void setStart(int start)
520 * @return DOCUMENT ME!
523 public int getStart()
535 public void setEnd(int end)
543 * @return DOCUMENT ME!
554 * @return DOCUMENT ME!
557 public int getLength()
559 return this.sequence.length;
569 public void setSequence(String seq)
571 this.sequence = seq.toCharArray();
577 public String getSequenceAsString()
579 return new String(sequence);
583 public String getSequenceAsString(int start, int end)
585 return new String(getSequence(start, end));
589 public char[] getSequence()
592 return sequence == null ? null : Arrays.copyOf(sequence,
599 * @see jalview.datamodel.SequenceI#getSequence(int, int)
602 public char[] getSequence(int start, int end)
608 // JBPNote - left to user to pad the result here (TODO:Decide on this
610 if (start >= sequence.length)
615 if (end >= sequence.length)
617 end = sequence.length;
620 char[] reply = new char[end - start];
621 System.arraycopy(sequence, start, reply, 0, end - start);
627 public SequenceI getSubSequence(int start, int end)
633 char[] seq = getSequence(start, end);
638 int nstart = findPosition(start);
639 int nend = findPosition(end) - 1;
640 // JBPNote - this is an incomplete copy.
641 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
642 nseq.setDescription(description);
643 if (datasetSequence != null)
645 nseq.setDatasetSequence(datasetSequence);
649 nseq.setDatasetSequence(this);
655 * Returns the character of the aligned sequence at the given position (base
656 * zero), or space if the position is not within the sequence's bounds
661 public char getCharAt(int i)
663 if (i >= 0 && i < sequence.length)
674 * Sets the sequence description, and also parses out any special formats of
680 public void setDescription(String desc)
682 this.description = desc;
686 public void setGeneLoci(String speciesId, String assemblyId,
687 String chromosomeId, MapList map)
689 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
690 + ":" + chromosomeId, new Mapping(map)));
694 * Returns the gene loci mapping for the sequence (may be null)
699 public GeneLociI getGeneLoci()
701 DBRefEntry[] refs = getDBRefs();
704 for (final DBRefEntry ref : refs)
706 if (ref.isChromosome())
708 return new GeneLociI()
711 public String getSpeciesId()
713 return ref.getSource();
717 public String getAssemblyId()
719 return ref.getVersion();
723 public String getChromosomeId()
725 // strip off "chromosome:" prefix to chrId
726 return ref.getAccessionId().substring(
727 DBRefEntry.CHROMOSOME.length() + 1);
731 public MapList getMap()
733 return ref.getMap().getMap();
743 * Answers the description
748 public String getDescription()
750 return this.description;
757 public int findIndex(int pos)
760 * use a valid, hopefully nearby, cursor if available
762 if (isValidCursor(cursor))
764 return findIndex(pos, cursor);
772 * traverse sequence from the start counting gaps; make a note of
773 * the column of the first residue to save in the cursor
775 while ((i < sequence.length) && (j <= end) && (j <= pos))
777 if (!Comparison.isGap(sequence[i]))
788 if (j == end && j < pos)
793 updateCursor(pos, i, startColumn);
798 * Updates the cursor to the latest found residue and column position
805 * column position of the first sequence residue
807 protected void updateCursor(int residuePos, int column, int startColumn)
810 * preserve end residue column provided cursor was valid
812 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
813 if (residuePos == this.end)
818 cursor = new SequenceCursor(this, residuePos, column, startColumn,
819 endColumn, this.changeCount);
823 * Answers the aligned column position (1..) for the given residue position
824 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
825 * The hint may be left of, at, or to the right of the required position.
831 protected int findIndex(int pos, SequenceCursor curs)
833 if (!isValidCursor(curs))
836 * wrong or invalidated cursor, compute de novo
838 return findIndex(pos);
841 if (curs.residuePosition == pos)
843 return curs.columnPosition;
847 * move left or right to find pos from hint.position
849 int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
851 int newPos = curs.residuePosition;
852 int delta = newPos > pos ? -1 : 1;
854 while (newPos != pos)
856 col += delta; // shift one column left or right
857 if (col < 0 || col == sequence.length)
861 if (!Comparison.isGap(sequence[col]))
867 col++; // convert back to base 1
868 updateCursor(pos, col, curs.firstColumnPosition);
877 public int findPosition(final int column)
880 * use a valid, hopefully nearby, cursor if available
882 if (isValidCursor(cursor))
884 return findPosition(column + 1, cursor);
887 // TODO recode this more naturally i.e. count residues only
888 // as they are found, not 'in anticipation'
891 * traverse the sequence counting gaps; note the column position
892 * of the first residue, to save in the cursor
894 int firstResidueColumn = 0;
895 int lastPosFound = 0;
896 int lastPosFoundColumn = 0;
897 int seqlen = sequence.length;
899 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
901 lastPosFound = start;
902 lastPosFoundColumn = 0;
908 while (j < column && j < seqlen)
910 if (!Comparison.isGap(sequence[j]))
913 lastPosFoundColumn = j;
914 if (pos == this.start)
916 firstResidueColumn = j;
922 if (j < seqlen && !Comparison.isGap(sequence[j]))
925 lastPosFoundColumn = j;
926 if (pos == this.start)
928 firstResidueColumn = j;
933 * update the cursor to the last residue position found (if any)
934 * (converting column position to base 1)
936 if (lastPosFound != 0)
938 updateCursor(lastPosFound, lastPosFoundColumn + 1,
939 firstResidueColumn + 1);
946 * Answers true if the given cursor is not null, is for this sequence object,
947 * and has a token value that matches this object's changeCount, else false.
948 * This allows us to ignore a cursor as 'stale' if the sequence has been
949 * modified since the cursor was created.
954 protected boolean isValidCursor(SequenceCursor curs)
956 if (curs == null || curs.sequence != this || curs.token != changeCount)
961 * sanity check against range
963 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
967 if (curs.residuePosition < start || curs.residuePosition > end)
975 * Answers the sequence position (start..) for the given aligned column
976 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
977 * may lie left of, at, or to the right of the column position.
983 protected int findPosition(final int col, SequenceCursor curs)
985 if (!isValidCursor(curs))
988 * wrong or invalidated cursor, compute de novo
990 return findPosition(col - 1);// ugh back to base 0
993 if (curs.columnPosition == col)
995 cursor = curs; // in case this method becomes public
996 return curs.residuePosition; // easy case :-)
999 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1002 * sequence lies entirely to the left of col
1003 * - return last residue + 1
1008 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1011 * sequence lies entirely to the right of col
1012 * - return first residue
1017 // todo could choose closest to col out of column,
1018 // firstColumnPosition, lastColumnPosition as a start point
1021 * move left or right to find pos from cursor position
1023 int firstResidueColumn = curs.firstColumnPosition;
1024 int column = curs.columnPosition - 1; // to base 0
1025 int newPos = curs.residuePosition;
1026 int delta = curs.columnPosition > col ? -1 : 1;
1027 boolean gapped = false;
1028 int lastFoundPosition = curs.residuePosition;
1029 int lastFoundPositionColumn = curs.columnPosition;
1031 while (column != col - 1)
1033 column += delta; // shift one column left or right
1034 if (column < 0 || column == sequence.length)
1038 gapped = Comparison.isGap(sequence[column]);
1042 lastFoundPosition = newPos;
1043 lastFoundPositionColumn = column + 1;
1044 if (lastFoundPosition == this.start)
1046 firstResidueColumn = column + 1;
1051 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1053 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1054 firstResidueColumn);
1058 * hack to give position to the right if on a gap
1059 * or beyond the length of the sequence (see JAL-2562)
1061 if (delta > 0 && (gapped || column >= sequence.length))
1073 public Range findPositions(int fromColumn, int toColumn)
1075 if (toColumn < fromColumn || fromColumn < 1)
1081 * find the first non-gapped position, if any
1083 int firstPosition = 0;
1084 int col = fromColumn - 1;
1085 int length = sequence.length;
1086 while (col < length && col < toColumn)
1088 if (!Comparison.isGap(sequence[col]))
1090 firstPosition = findPosition(col++);
1096 if (firstPosition == 0)
1102 * find the last non-gapped position
1104 int lastPosition = firstPosition;
1105 while (col < length && col < toColumn)
1107 if (!Comparison.isGap(sequence[col++]))
1113 return new Range(firstPosition, lastPosition);
1117 * Returns an int array where indices correspond to each residue in the
1118 * sequence and the element value gives its position in the alignment
1120 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1121 * residues in SequenceI object
1124 public int[] gapMap()
1126 String seq = jalview.analysis.AlignSeq.extractGaps(
1127 jalview.util.Comparison.GapChars, new String(sequence));
1128 int[] map = new int[seq.length()];
1132 while (j < sequence.length)
1134 if (!jalview.util.Comparison.isGap(sequence[j]))
1146 public int[] findPositionMap()
1148 int map[] = new int[sequence.length];
1151 int seqlen = sequence.length;
1152 while ((j < seqlen))
1155 if (!jalview.util.Comparison.isGap(sequence[j]))
1166 public List<int[]> getInsertions()
1168 ArrayList<int[]> map = new ArrayList<>();
1169 int lastj = -1, j = 0;
1171 int seqlen = sequence.length;
1172 while ((j < seqlen))
1174 if (jalview.util.Comparison.isGap(sequence[j]))
1185 map.add(new int[] { lastj, j - 1 });
1193 map.add(new int[] { lastj, j - 1 });
1200 public BitSet getInsertionsAsBits()
1202 BitSet map = new BitSet();
1203 int lastj = -1, j = 0;
1205 int seqlen = sequence.length;
1206 while ((j < seqlen))
1208 if (jalview.util.Comparison.isGap(sequence[j]))
1234 public void deleteChars(final int i, final int j)
1236 int newstart = start, newend = end;
1237 if (i >= sequence.length || i < 0)
1242 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1243 boolean createNewDs = false;
1244 // TODO: take a (second look) at the dataset creation validation method for
1245 // the very large sequence case
1246 int startIndex = findIndex(start) - 1;
1247 int endIndex = findIndex(end) - 1;
1248 int startDeleteColumn = -1; // for dataset sequence deletions
1249 int deleteCount = 0;
1251 for (int s = i; s < j; s++)
1253 if (Comparison.isGap(sequence[s]))
1258 if (startDeleteColumn == -1)
1260 startDeleteColumn = findPosition(s) - start;
1268 if (startIndex == s)
1271 * deleting characters from start of sequence; new start is the
1272 * sequence position of the next column (position to the right
1273 * if the column position is gapped)
1275 newstart = findPosition(j);
1283 * deleting characters at end of sequence; new end is the sequence
1284 * position of the column before the deletion; subtract 1 if this is
1285 * gapped since findPosition returns the next sequence position
1287 newend = findPosition(i - 1);
1288 if (Comparison.isGap(sequence[i - 1]))
1303 if (createNewDs && this.datasetSequence != null)
1306 * if deletion occured in the middle of the sequence,
1307 * construct a new dataset sequence and delete the residues
1308 * that were deleted from the aligned sequence
1310 Sequence ds = new Sequence(datasetSequence);
1311 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1312 datasetSequence = ds;
1313 // TODO: remove any non-inheritable properties ?
1314 // TODO: create a sequence mapping (since there is a relation here ?)
1323 public void insertCharAt(int i, int length, char c)
1325 char[] tmp = new char[sequence.length + length];
1327 if (i >= sequence.length)
1329 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1330 i = sequence.length;
1334 System.arraycopy(sequence, 0, tmp, 0, i);
1344 if (i < sequence.length)
1346 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1354 public void insertCharAt(int i, char c)
1356 insertCharAt(i, 1, c);
1360 public String getVamsasId()
1366 public void setVamsasId(String id)
1372 public void setDBRefs(DBRefEntry[] dbref)
1374 if (dbrefs == null && datasetSequence != null
1375 && this != datasetSequence)
1377 datasetSequence.setDBRefs(dbref);
1383 DBRefUtils.ensurePrimaries(this);
1388 public DBRefEntry[] getDBRefs()
1390 if (dbrefs == null && datasetSequence != null
1391 && this != datasetSequence)
1393 return datasetSequence.getDBRefs();
1399 public void addDBRef(DBRefEntry entry)
1401 if (datasetSequence != null)
1403 datasetSequence.addDBRef(entry);
1409 dbrefs = new DBRefEntry[0];
1412 for (DBRefEntryI dbr : dbrefs)
1414 if (dbr.updateFrom(entry))
1417 * found a dbref that either matched, or could be
1418 * updated from, the new entry - no need to add it
1425 * extend the array to make room for one more
1427 // TODO use an ArrayList instead
1428 int j = dbrefs.length;
1429 DBRefEntry[] temp = new DBRefEntry[j + 1];
1430 System.arraycopy(dbrefs, 0, temp, 0, j);
1431 temp[temp.length - 1] = entry;
1435 DBRefUtils.ensurePrimaries(this);
1439 public void setDatasetSequence(SequenceI seq)
1443 throw new IllegalArgumentException(
1444 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1446 if (seq != null && seq.getDatasetSequence() != null)
1448 throw new IllegalArgumentException(
1449 "Implementation error: cascading dataset sequences are not allowed.");
1451 datasetSequence = seq;
1455 public SequenceI getDatasetSequence()
1457 return datasetSequence;
1461 public AlignmentAnnotation[] getAnnotation()
1463 return annotation == null ? null
1465 .toArray(new AlignmentAnnotation[annotation.size()]);
1469 public boolean hasAnnotation(AlignmentAnnotation ann)
1471 return annotation == null ? false : annotation.contains(ann);
1475 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1477 if (this.annotation == null)
1479 this.annotation = new Vector<>();
1481 if (!this.annotation.contains(annotation))
1483 this.annotation.addElement(annotation);
1485 annotation.setSequenceRef(this);
1489 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1491 if (this.annotation != null)
1493 this.annotation.removeElement(annotation);
1494 if (this.annotation.size() == 0)
1496 this.annotation = null;
1502 * test if this is a valid candidate for another sequence's dataset sequence.
1505 private boolean isValidDatasetSequence()
1507 if (datasetSequence != null)
1511 for (int i = 0; i < sequence.length; i++)
1513 if (jalview.util.Comparison.isGap(sequence[i]))
1522 public SequenceI deriveSequence()
1524 Sequence seq = null;
1525 if (datasetSequence == null)
1527 if (isValidDatasetSequence())
1529 // Use this as dataset sequence
1530 seq = new Sequence(getName(), "", 1, -1);
1531 seq.setDatasetSequence(this);
1532 seq.initSeqFrom(this, getAnnotation());
1537 // Create a new, valid dataset sequence
1538 createDatasetSequence();
1541 return new Sequence(this);
1544 private boolean _isNa;
1546 private int _seqhash = 0;
1549 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1553 public boolean isProtein()
1555 if (datasetSequence != null)
1557 return datasetSequence.isProtein();
1559 if (_seqhash != sequence.hashCode())
1561 _seqhash = sequence.hashCode();
1562 _isNa = Comparison.isNucleotide(this);
1570 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1573 public SequenceI createDatasetSequence()
1575 if (datasetSequence == null)
1577 Sequence dsseq = new Sequence(getName(),
1578 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1579 getSequenceAsString()),
1580 getStart(), getEnd());
1582 datasetSequence = dsseq;
1584 dsseq.setDescription(description);
1585 // move features and database references onto dataset sequence
1586 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1587 sequenceFeatureStore = null;
1588 dsseq.dbrefs = dbrefs;
1590 // TODO: search and replace any references to this sequence with
1591 // references to the dataset sequence in Mappings on dbref
1592 dsseq.pdbIds = pdbIds;
1594 datasetSequence.updatePDBIds();
1595 if (annotation != null)
1597 // annotation is cloned rather than moved, to preserve what's currently
1599 for (AlignmentAnnotation aa : annotation)
1601 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1602 _aa.sequenceRef = datasetSequence;
1603 _aa.adjustForAlignment(); // uses annotation's own record of
1604 // sequence-column mapping
1605 datasetSequence.addAlignmentAnnotation(_aa);
1609 return datasetSequence;
1616 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1620 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1622 if (annotation != null)
1624 annotation.removeAllElements();
1626 if (annotations != null)
1628 for (int i = 0; i < annotations.length; i++)
1630 if (annotations[i] != null)
1632 addAlignmentAnnotation(annotations[i]);
1639 public AlignmentAnnotation[] getAnnotation(String label)
1641 if (annotation == null || annotation.size() == 0)
1646 Vector<AlignmentAnnotation> subset = new Vector<>();
1647 Enumeration<AlignmentAnnotation> e = annotation.elements();
1648 while (e.hasMoreElements())
1650 AlignmentAnnotation ann = e.nextElement();
1651 if (ann.label != null && ann.label.equals(label))
1653 subset.addElement(ann);
1656 if (subset.size() == 0)
1660 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1662 e = subset.elements();
1663 while (e.hasMoreElements())
1665 anns[i++] = e.nextElement();
1667 subset.removeAllElements();
1672 public boolean updatePDBIds()
1674 if (datasetSequence != null)
1676 // TODO: could merge DBRefs
1677 return datasetSequence.updatePDBIds();
1679 if (dbrefs == null || dbrefs.length == 0)
1683 boolean added = false;
1684 for (DBRefEntry dbr : dbrefs)
1686 if (DBRefSource.PDB.equals(dbr.getSource()))
1689 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1690 * PDB id is not already present in a 'matching' PDBEntry
1691 * Constructor parses out a chain code if appended to the accession id
1692 * (a fudge used to 'store' the chain code in the DBRef)
1694 PDBEntry pdbe = new PDBEntry(dbr);
1695 added |= addPDBId(pdbe);
1702 public void transferAnnotation(SequenceI entry, Mapping mp)
1704 if (datasetSequence != null)
1706 datasetSequence.transferAnnotation(entry, mp);
1709 if (entry.getDatasetSequence() != null)
1711 transferAnnotation(entry.getDatasetSequence(), mp);
1714 // transfer any new features from entry onto sequence
1715 if (entry.getSequenceFeatures() != null)
1718 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1719 for (SequenceFeature feature : sfs)
1721 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1722 : new SequenceFeature[] { new SequenceFeature(feature) };
1725 for (int sfi = 0; sfi < sf.length; sfi++)
1727 addSequenceFeature(sf[sfi]);
1733 // transfer PDB entries
1734 if (entry.getAllPDBEntries() != null)
1736 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1737 while (e.hasMoreElements())
1739 PDBEntry pdb = e.nextElement();
1743 // transfer database references
1744 DBRefEntry[] entryRefs = entry.getDBRefs();
1745 if (entryRefs != null)
1747 for (int r = 0; r < entryRefs.length; r++)
1749 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1750 if (newref.getMap() != null && mp != null)
1752 // remap ref using our local mapping
1754 // we also assume all version string setting is done by dbSourceProxy
1756 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1757 * newref.setSource(dbSource); }
1765 public void setRNA(RNA r)
1777 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1780 List<AlignmentAnnotation> result = new ArrayList<>();
1781 if (this.annotation != null)
1783 for (AlignmentAnnotation ann : annotation)
1785 String id = ann.getCalcId();
1786 if (id != null && id.equals(calcId)
1787 && ann.label != null && ann.label.equals(label))
1797 public String toString()
1799 return getDisplayId(false);
1803 public PDBEntry getPDBEntry(String pdbIdStr)
1805 if (getDatasetSequence() != null)
1807 return getDatasetSequence().getPDBEntry(pdbIdStr);
1813 List<PDBEntry> entries = getAllPDBEntries();
1814 for (PDBEntry entry : entries)
1816 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1825 public List<DBRefEntry> getPrimaryDBRefs()
1827 if (datasetSequence != null)
1829 return datasetSequence.getPrimaryDBRefs();
1831 if (dbrefs == null || dbrefs.length == 0)
1833 return Collections.emptyList();
1835 synchronized (dbrefs)
1837 List<DBRefEntry> primaries = new ArrayList<>();
1838 DBRefEntry[] tmp = new DBRefEntry[1];
1839 for (DBRefEntry ref : dbrefs)
1841 if (!ref.isPrimaryCandidate())
1847 MapList mp = ref.getMap().getMap();
1848 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1850 // map only involves a subsequence, so cannot be primary
1854 // whilst it looks like it is a primary ref, we also sanity check type
1855 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1856 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1858 // PDB dbrefs imply there should be a PDBEntry associated
1859 // TODO: tighten PDB dbrefs
1860 // formally imply Jalview has actually downloaded and
1861 // parsed the pdb file. That means there should be a cached file
1862 // handle on the PDBEntry, and a real mapping between sequence and
1863 // extracted sequence from PDB file
1864 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1865 if (pdbentry != null && pdbentry.getFile() != null)
1871 // check standard protein or dna sources
1873 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1874 if (res != null && res[0] == tmp[0])
1885 public HiddenMarkovModel getHMM()
1891 public void setHMM(HiddenMarkovModel hmm)
1897 public void updateHMMMapping()
1903 hmm.updateMapping(sequence);
1907 * Maps the HMM sequence to the reference annotation.
1912 public void mapToReference(AlignmentAnnotation rf)
1914 if (this.isHMMConsensusSequence)
1917 hmm.clearNodeLookup();
1918 for (int i = 0; i < getLength(); i++)
1920 if (rf.annotations[i].displayCharacter.equalsIgnoreCase("x"))
1922 if (i < hmm.getNodeAlignmentColumn(node))
1924 this.deleteChars(i, hmm.getNodeAlignmentColumn(node));
1927 else if (i > hmm.getNodeAlignmentColumn(node))
1929 int length = i - hmm.getNodeAlignmentColumn(node);
1930 this.insertCharAt(hmm.getNodeAlignmentColumn(node), length,
1941 public boolean isHMMConsensusSequence()
1943 return isHMMConsensusSequence;
1947 public void setIsHMMConsensusSequence(boolean value)
1949 this.isHMMConsensusSequence = value;
1953 public boolean hasHMMAnnotation()
1955 if (this.annotation == null) {
1958 for (AlignmentAnnotation ann : annotation)
1960 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1972 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1975 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1976 int endPos = fromColumn == toColumn ? startPos
1977 : findPosition(toColumn - 1);
1979 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1983 * if end column is gapped, endPos may be to the right,
1984 * and we may have included adjacent or enclosing features;
1985 * remove any that are not enclosing, non-contact features
1987 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1988 && Comparison.isGap(sequence[toColumn - 1]);
1989 if (endPos > this.end || endColumnIsGapped)
1991 ListIterator<SequenceFeature> it = result.listIterator();
1992 while (it.hasNext())
1994 SequenceFeature sf = it.next();
1995 int sfBegin = sf.getBegin();
1996 int sfEnd = sf.getEnd();
1997 int featureStartColumn = findIndex(sfBegin);
1998 if (featureStartColumn > toColumn)
2002 else if (featureStartColumn < fromColumn)
2004 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2006 if (featureEndColumn < fromColumn)
2010 else if (featureEndColumn > toColumn && sf.isContactFeature())
2013 * remove an enclosing feature if it is a contact feature
2025 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2026 * token that has to match the one presented by the cursor
2029 public void sequenceChanged()
2038 public int replace(char c1, char c2)
2045 synchronized (sequence)
2047 for (int c = 0; c < sequence.length; c++)
2049 if (sequence[c] == c1)