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;
68 HiddenMarkovModel hmm;
70 boolean isHMMConsensusSequence = false;
72 Vector<PDBEntry> pdbIds;
81 * This annotation is displayed below the alignment but the positions are tied
82 * to the residues of this sequence
84 * TODO: change to List<>
86 Vector<AlignmentAnnotation> annotation;
88 private SequenceFeaturesI sequenceFeatureStore;
91 * A cursor holding the approximate current view position to the sequence,
92 * as determined by findIndex or findPosition or findPositions.
93 * Using a cursor as a hint allows these methods to be more performant for
96 private SequenceCursor cursor;
99 * A number that should be incremented whenever the sequence is edited.
100 * If the value matches the cursor token, then we can trust the cursor,
101 * if not then it should be recomputed.
103 private int changeCount;
106 * Creates a new Sequence object.
109 * display name string
111 * string to form a possibly gapped sequence out of
113 * first position of non-gap residue in the sequence
115 * last position of ungapped residues (nearly always only used for
118 public Sequence(String name, String sequence, int start, int end)
121 initSeqAndName(name, sequence.toCharArray(), start, end);
124 public Sequence(String name, char[] sequence, int start, int end)
127 initSeqAndName(name, sequence, start, end);
131 * Stage 1 constructor - assign name, sequence, and set start and end fields.
132 * start and end are updated values from name2 if it ends with /start-end
139 protected void initSeqAndName(String name2, char[] sequence2, int start2,
143 this.sequence = sequence2;
151 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
152 * start and end respectively and removes the suffix from the name
159 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
162 int slashPos = name.lastIndexOf('/');
163 if (slashPos > -1 && slashPos < name.length() - 1)
165 String suffix = name.substring(slashPos + 1);
166 String[] range = suffix.split("-");
167 if (range.length == 2)
171 int from = Integer.valueOf(range[0]);
172 int to = Integer.valueOf(range[1]);
173 if (from > 0 && to >= from)
175 name = name.substring(0, slashPos);
180 } catch (NumberFormatException e)
182 // leave name unchanged if suffix is invalid
189 * Ensures that 'end' is not before the end of the sequence, that is,
190 * (end-start+1) is at least as long as the count of ungapped positions. Note
191 * that end is permitted to be beyond the end of the sequence data.
193 void checkValidRange()
196 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
199 for (int j = 0; j < sequence.length; j++)
201 if (!Comparison.isGap(sequence[j]))
220 * default constructor
224 sequenceFeatureStore = new SequenceFeatures();
228 * Creates a new Sequence object.
235 public Sequence(String name, String sequence)
237 this(name, sequence, 1, -1);
241 * Creates a new Sequence object with new AlignmentAnnotations but inherits
242 * any existing dataset sequence reference. If non exists, everything is
246 * if seq is a dataset sequence, behaves like a plain old copy
249 public Sequence(SequenceI seq)
251 this(seq, seq.getAnnotation());
255 * Create a new sequence object with new features, DBRefEntries, and PDBIds
256 * but inherits any existing dataset sequence reference, and duplicate of any
257 * annotation that is present in the given annotation array.
260 * the sequence to be copied
261 * @param alAnnotation
262 * an array of annotation including some associated with seq
264 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
267 initSeqFrom(seq, alAnnotation);
271 * does the heavy lifting when cloning a dataset sequence, or coping data from
272 * dataset to a new derived sequence.
275 * - source of attributes.
276 * @param alAnnotation
277 * - alignment annotation present on seq that should be copied onto
280 protected void initSeqFrom(SequenceI seq,
281 AlignmentAnnotation[] alAnnotation)
283 char[] oseq = seq.getSequence(); // returns a copy of the array
284 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
286 description = seq.getDescription();
287 if (seq != datasetSequence)
289 setDatasetSequence(seq.getDatasetSequence());
293 * only copy DBRefs and seqfeatures if we really are a dataset sequence
295 if (datasetSequence == null)
297 if (seq.getDBRefs() != null)
299 DBRefEntry[] dbr = seq.getDBRefs();
300 for (int i = 0; i < dbr.length; i++)
302 addDBRef(new DBRefEntry(dbr[i]));
307 * make copies of any sequence features
309 for (SequenceFeature sf : seq.getSequenceFeatures())
311 addSequenceFeature(new SequenceFeature(sf));
315 if (seq.getAnnotation() != null)
317 AlignmentAnnotation[] sqann = seq.getAnnotation();
318 for (int i = 0; i < sqann.length; i++)
320 if (sqann[i] == null)
324 boolean found = (alAnnotation == null);
327 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
329 found = (alAnnotation[apos] == sqann[i]);
334 // only copy the given annotation
335 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
336 addAlignmentAnnotation(newann);
340 if (seq.getAllPDBEntries() != null)
342 Vector<PDBEntry> ids = seq.getAllPDBEntries();
343 for (PDBEntry pdb : ids)
345 this.addPDBId(new PDBEntry(pdb));
348 if (seq.isHMMConsensusSequence())
350 this.isHMMConsensusSequence = true;
352 if (seq.getHMM() != null)
354 this.hmm = new HiddenMarkovModel(seq.getHMM());
360 public void setSequenceFeatures(List<SequenceFeature> features)
362 if (datasetSequence != null)
364 datasetSequence.setSequenceFeatures(features);
367 sequenceFeatureStore = new SequenceFeatures(features);
371 public synchronized boolean addSequenceFeature(SequenceFeature sf)
373 if (sf.getType() == null)
375 System.err.println("SequenceFeature type may not be null: "
380 if (datasetSequence != null)
382 return datasetSequence.addSequenceFeature(sf);
385 return sequenceFeatureStore.add(sf);
389 public void deleteFeature(SequenceFeature sf)
391 if (datasetSequence != null)
393 datasetSequence.deleteFeature(sf);
397 sequenceFeatureStore.delete(sf);
407 public List<SequenceFeature> getSequenceFeatures()
409 if (datasetSequence != null)
411 return datasetSequence.getSequenceFeatures();
413 return sequenceFeatureStore.getAllFeatures();
417 public SequenceFeaturesI getFeatures()
419 return datasetSequence != null ? datasetSequence.getFeatures()
420 : sequenceFeatureStore;
424 public boolean addPDBId(PDBEntry entry)
428 pdbIds = new Vector<>();
433 for (PDBEntry pdbe : pdbIds)
435 if (pdbe.updateFrom(entry))
440 pdbIds.addElement(entry);
451 public void setPDBId(Vector<PDBEntry> id)
459 * @return DOCUMENT ME!
462 public Vector<PDBEntry> getAllPDBEntries()
464 return pdbIds == null ? new Vector<>() : pdbIds;
470 * @return DOCUMENT ME!
473 public String getDisplayId(boolean jvsuffix)
475 StringBuffer result = new StringBuffer(name);
478 result.append("/" + start + "-" + end);
481 return result.toString();
485 * Sets the sequence name. If the name ends in /start-end, then the start-end
486 * values are parsed out and set, and the suffix is removed from the name.
491 public void setName(String theName)
500 * @return DOCUMENT ME!
503 public String getName()
515 public void setStart(int start)
523 * @return DOCUMENT ME!
526 public int getStart()
538 public void setEnd(int end)
546 * @return DOCUMENT ME!
557 * @return DOCUMENT ME!
560 public int getLength()
562 return this.sequence.length;
572 public void setSequence(String seq)
574 this.sequence = seq.toCharArray();
580 public String getSequenceAsString()
582 return new String(sequence);
586 public String getSequenceAsString(int start, int end)
588 return new String(getSequence(start, end));
592 public char[] getSequence()
595 return sequence == null ? null : Arrays.copyOf(sequence,
602 * @see jalview.datamodel.SequenceI#getSequence(int, int)
605 public char[] getSequence(int start, int end)
611 // JBPNote - left to user to pad the result here (TODO:Decide on this
613 if (start >= sequence.length)
618 if (end >= sequence.length)
620 end = sequence.length;
623 char[] reply = new char[end - start];
624 System.arraycopy(sequence, start, reply, 0, end - start);
630 public SequenceI getSubSequence(int start, int end)
636 char[] seq = getSequence(start, end);
641 int nstart = findPosition(start);
642 int nend = findPosition(end) - 1;
643 // JBPNote - this is an incomplete copy.
644 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
645 nseq.setDescription(description);
646 if (datasetSequence != null)
648 nseq.setDatasetSequence(datasetSequence);
652 nseq.setDatasetSequence(this);
658 * Returns the character of the aligned sequence at the given position (base
659 * zero), or space if the position is not within the sequence's bounds
664 public char getCharAt(int i)
666 if (i >= 0 && i < sequence.length)
677 * Sets the sequence description, and also parses out any special formats of
683 public void setDescription(String desc)
685 this.description = desc;
689 public void setGeneLoci(String speciesId, String assemblyId,
690 String chromosomeId, MapList map)
692 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
693 + ":" + chromosomeId, new Mapping(map)));
697 * Returns the gene loci mapping for the sequence (may be null)
702 public GeneLociI getGeneLoci()
704 DBRefEntry[] refs = getDBRefs();
707 for (final DBRefEntry ref : refs)
709 if (ref.isChromosome())
711 return new GeneLociI()
714 public String getSpeciesId()
716 return ref.getSource();
720 public String getAssemblyId()
722 return ref.getVersion();
726 public String getChromosomeId()
728 // strip off "chromosome:" prefix to chrId
729 return ref.getAccessionId().substring(
730 DBRefEntry.CHROMOSOME.length() + 1);
734 public MapList getMap()
736 return ref.getMap().getMap();
746 * Answers the description
751 public String getDescription()
753 return this.description;
760 public int findIndex(int pos)
763 * use a valid, hopefully nearby, cursor if available
765 if (isValidCursor(cursor))
767 return findIndex(pos, cursor);
775 * traverse sequence from the start counting gaps; make a note of
776 * the column of the first residue to save in the cursor
778 while ((i < sequence.length) && (j <= end) && (j <= pos))
780 if (!Comparison.isGap(sequence[i]))
791 if (j == end && j < pos)
796 updateCursor(pos, i, startColumn);
801 * Updates the cursor to the latest found residue and column position
808 * column position of the first sequence residue
810 protected void updateCursor(int residuePos, int column, int startColumn)
813 * preserve end residue column provided cursor was valid
815 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
816 if (residuePos == this.end)
821 cursor = new SequenceCursor(this, residuePos, column, startColumn,
822 endColumn, this.changeCount);
826 * Answers the aligned column position (1..) for the given residue position
827 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
828 * The hint may be left of, at, or to the right of the required position.
834 protected int findIndex(int pos, SequenceCursor curs)
836 if (!isValidCursor(curs))
839 * wrong or invalidated cursor, compute de novo
841 return findIndex(pos);
844 if (curs.residuePosition == pos)
846 return curs.columnPosition;
850 * move left or right to find pos from hint.position
852 int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
854 int newPos = curs.residuePosition;
855 int delta = newPos > pos ? -1 : 1;
857 while (newPos != pos)
859 col += delta; // shift one column left or right
860 if (col < 0 || col == sequence.length)
864 if (!Comparison.isGap(sequence[col]))
870 col++; // convert back to base 1
871 updateCursor(pos, col, curs.firstColumnPosition);
880 public int findPosition(final int column)
883 * use a valid, hopefully nearby, cursor if available
885 if (isValidCursor(cursor))
887 return findPosition(column + 1, cursor);
890 // TODO recode this more naturally i.e. count residues only
891 // as they are found, not 'in anticipation'
894 * traverse the sequence counting gaps; note the column position
895 * of the first residue, to save in the cursor
897 int firstResidueColumn = 0;
898 int lastPosFound = 0;
899 int lastPosFoundColumn = 0;
900 int seqlen = sequence.length;
902 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
904 lastPosFound = start;
905 lastPosFoundColumn = 0;
911 while (j < column && j < seqlen)
913 if (!Comparison.isGap(sequence[j]))
916 lastPosFoundColumn = j;
917 if (pos == this.start)
919 firstResidueColumn = j;
925 if (j < seqlen && !Comparison.isGap(sequence[j]))
928 lastPosFoundColumn = j;
929 if (pos == this.start)
931 firstResidueColumn = j;
936 * update the cursor to the last residue position found (if any)
937 * (converting column position to base 1)
939 if (lastPosFound != 0)
941 updateCursor(lastPosFound, lastPosFoundColumn + 1,
942 firstResidueColumn + 1);
949 * Answers true if the given cursor is not null, is for this sequence object,
950 * and has a token value that matches this object's changeCount, else false.
951 * This allows us to ignore a cursor as 'stale' if the sequence has been
952 * modified since the cursor was created.
957 protected boolean isValidCursor(SequenceCursor curs)
959 if (curs == null || curs.sequence != this || curs.token != changeCount)
964 * sanity check against range
966 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
970 if (curs.residuePosition < start || curs.residuePosition > end)
978 * Answers the sequence position (start..) for the given aligned column
979 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
980 * may lie left of, at, or to the right of the column position.
986 protected int findPosition(final int col, SequenceCursor curs)
988 if (!isValidCursor(curs))
991 * wrong or invalidated cursor, compute de novo
993 return findPosition(col - 1);// ugh back to base 0
996 if (curs.columnPosition == col)
998 cursor = curs; // in case this method becomes public
999 return curs.residuePosition; // easy case :-)
1002 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1005 * sequence lies entirely to the left of col
1006 * - return last residue + 1
1011 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1014 * sequence lies entirely to the right of col
1015 * - return first residue
1020 // todo could choose closest to col out of column,
1021 // firstColumnPosition, lastColumnPosition as a start point
1024 * move left or right to find pos from cursor position
1026 int firstResidueColumn = curs.firstColumnPosition;
1027 int column = curs.columnPosition - 1; // to base 0
1028 int newPos = curs.residuePosition;
1029 int delta = curs.columnPosition > col ? -1 : 1;
1030 boolean gapped = false;
1031 int lastFoundPosition = curs.residuePosition;
1032 int lastFoundPositionColumn = curs.columnPosition;
1034 while (column != col - 1)
1036 column += delta; // shift one column left or right
1037 if (column < 0 || column == sequence.length)
1041 gapped = Comparison.isGap(sequence[column]);
1045 lastFoundPosition = newPos;
1046 lastFoundPositionColumn = column + 1;
1047 if (lastFoundPosition == this.start)
1049 firstResidueColumn = column + 1;
1054 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1056 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1057 firstResidueColumn);
1061 * hack to give position to the right if on a gap
1062 * or beyond the length of the sequence (see JAL-2562)
1064 if (delta > 0 && (gapped || column >= sequence.length))
1076 public Range findPositions(int fromColumn, int toColumn)
1078 if (toColumn < fromColumn || fromColumn < 1)
1084 * find the first non-gapped position, if any
1086 int firstPosition = 0;
1087 int col = fromColumn - 1;
1088 int length = sequence.length;
1089 while (col < length && col < toColumn)
1091 if (!Comparison.isGap(sequence[col]))
1093 firstPosition = findPosition(col++);
1099 if (firstPosition == 0)
1105 * find the last non-gapped position
1107 int lastPosition = firstPosition;
1108 while (col < length && col < toColumn)
1110 if (!Comparison.isGap(sequence[col++]))
1116 return new Range(firstPosition, lastPosition);
1120 * Returns an int array where indices correspond to each residue in the
1121 * sequence and the element value gives its position in the alignment
1123 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1124 * residues in SequenceI object
1127 public int[] gapMap()
1129 String seq = jalview.analysis.AlignSeq.extractGaps(
1130 jalview.util.Comparison.GapChars, new String(sequence));
1131 int[] map = new int[seq.length()];
1135 while (j < sequence.length)
1137 if (!jalview.util.Comparison.isGap(sequence[j]))
1149 public int[] findPositionMap()
1151 int map[] = new int[sequence.length];
1154 int seqlen = sequence.length;
1155 while ((j < seqlen))
1158 if (!jalview.util.Comparison.isGap(sequence[j]))
1169 public List<int[]> getInsertions()
1171 ArrayList<int[]> map = new ArrayList<>();
1172 int lastj = -1, j = 0;
1174 int seqlen = sequence.length;
1175 while ((j < seqlen))
1177 if (jalview.util.Comparison.isGap(sequence[j]))
1188 map.add(new int[] { lastj, j - 1 });
1196 map.add(new int[] { lastj, j - 1 });
1203 public BitSet getInsertionsAsBits()
1205 BitSet map = new BitSet();
1206 int lastj = -1, j = 0;
1208 int seqlen = sequence.length;
1209 while ((j < seqlen))
1211 if (jalview.util.Comparison.isGap(sequence[j]))
1237 public void deleteChars(final int i, final int j)
1239 int newstart = start, newend = end;
1240 if (i >= sequence.length || i < 0)
1245 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1246 boolean createNewDs = false;
1247 // TODO: take a (second look) at the dataset creation validation method for
1248 // the very large sequence case
1249 int startIndex = findIndex(start) - 1;
1250 int endIndex = findIndex(end) - 1;
1251 int startDeleteColumn = -1; // for dataset sequence deletions
1252 int deleteCount = 0;
1254 for (int s = i; s < j; s++)
1256 if (Comparison.isGap(sequence[s]))
1261 if (startDeleteColumn == -1)
1263 startDeleteColumn = findPosition(s) - start;
1271 if (startIndex == s)
1274 * deleting characters from start of sequence; new start is the
1275 * sequence position of the next column (position to the right
1276 * if the column position is gapped)
1278 newstart = findPosition(j);
1286 * deleting characters at end of sequence; new end is the sequence
1287 * position of the column before the deletion; subtract 1 if this is
1288 * gapped since findPosition returns the next sequence position
1290 newend = findPosition(i - 1);
1291 if (Comparison.isGap(sequence[i - 1]))
1306 if (createNewDs && this.datasetSequence != null)
1309 * if deletion occured in the middle of the sequence,
1310 * construct a new dataset sequence and delete the residues
1311 * that were deleted from the aligned sequence
1313 Sequence ds = new Sequence(datasetSequence);
1314 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1315 datasetSequence = ds;
1316 // TODO: remove any non-inheritable properties ?
1317 // TODO: create a sequence mapping (since there is a relation here ?)
1326 public void insertCharAt(int i, int length, char c)
1328 char[] tmp = new char[sequence.length + length];
1330 if (i >= sequence.length)
1332 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1333 i = sequence.length;
1337 System.arraycopy(sequence, 0, tmp, 0, i);
1347 if (i < sequence.length)
1349 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1357 public void insertCharAt(int i, char c)
1359 insertCharAt(i, 1, c);
1363 public String getVamsasId()
1369 public void setVamsasId(String id)
1375 public void setDBRefs(DBRefEntry[] dbref)
1377 if (dbrefs == null && datasetSequence != null
1378 && this != datasetSequence)
1380 datasetSequence.setDBRefs(dbref);
1386 DBRefUtils.ensurePrimaries(this);
1391 public DBRefEntry[] getDBRefs()
1393 if (dbrefs == null && datasetSequence != null
1394 && this != datasetSequence)
1396 return datasetSequence.getDBRefs();
1402 public void addDBRef(DBRefEntry entry)
1404 if (datasetSequence != null)
1406 datasetSequence.addDBRef(entry);
1412 dbrefs = new DBRefEntry[0];
1415 for (DBRefEntryI dbr : dbrefs)
1417 if (dbr.updateFrom(entry))
1420 * found a dbref that either matched, or could be
1421 * updated from, the new entry - no need to add it
1428 * extend the array to make room for one more
1430 // TODO use an ArrayList instead
1431 int j = dbrefs.length;
1432 DBRefEntry[] temp = new DBRefEntry[j + 1];
1433 System.arraycopy(dbrefs, 0, temp, 0, j);
1434 temp[temp.length - 1] = entry;
1438 DBRefUtils.ensurePrimaries(this);
1442 public void setDatasetSequence(SequenceI seq)
1446 throw new IllegalArgumentException(
1447 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1449 if (seq != null && seq.getDatasetSequence() != null)
1451 throw new IllegalArgumentException(
1452 "Implementation error: cascading dataset sequences are not allowed.");
1454 datasetSequence = seq;
1458 public SequenceI getDatasetSequence()
1460 return datasetSequence;
1464 public AlignmentAnnotation[] getAnnotation()
1466 return annotation == null ? null
1468 .toArray(new AlignmentAnnotation[annotation.size()]);
1472 public boolean hasAnnotation(AlignmentAnnotation ann)
1474 return annotation == null ? false : annotation.contains(ann);
1478 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1480 if (this.annotation == null)
1482 this.annotation = new Vector<>();
1484 if (!this.annotation.contains(annotation))
1486 this.annotation.addElement(annotation);
1488 annotation.setSequenceRef(this);
1492 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1494 if (this.annotation != null)
1496 this.annotation.removeElement(annotation);
1497 if (this.annotation.size() == 0)
1499 this.annotation = null;
1505 * test if this is a valid candidate for another sequence's dataset sequence.
1508 private boolean isValidDatasetSequence()
1510 if (datasetSequence != null)
1514 for (int i = 0; i < sequence.length; i++)
1516 if (jalview.util.Comparison.isGap(sequence[i]))
1525 public SequenceI deriveSequence()
1527 Sequence seq = null;
1528 if (datasetSequence == null)
1530 if (isValidDatasetSequence())
1532 // Use this as dataset sequence
1533 seq = new Sequence(getName(), "", 1, -1);
1534 seq.setDatasetSequence(this);
1535 seq.initSeqFrom(this, getAnnotation());
1540 // Create a new, valid dataset sequence
1541 createDatasetSequence();
1544 return new Sequence(this);
1547 private boolean _isNa;
1549 private int _seqhash = 0;
1552 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1556 public boolean isProtein()
1558 if (datasetSequence != null)
1560 return datasetSequence.isProtein();
1562 if (_seqhash != sequence.hashCode())
1564 _seqhash = sequence.hashCode();
1565 _isNa = Comparison.isNucleotide(this);
1573 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1576 public SequenceI createDatasetSequence()
1578 if (datasetSequence == null)
1580 Sequence dsseq = new Sequence(getName(),
1581 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1582 getSequenceAsString()),
1583 getStart(), getEnd());
1585 datasetSequence = dsseq;
1587 dsseq.setDescription(description);
1588 // move features and database references onto dataset sequence
1589 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1590 sequenceFeatureStore = null;
1591 dsseq.dbrefs = dbrefs;
1593 // TODO: search and replace any references to this sequence with
1594 // references to the dataset sequence in Mappings on dbref
1595 dsseq.pdbIds = pdbIds;
1597 datasetSequence.updatePDBIds();
1598 if (annotation != null)
1600 // annotation is cloned rather than moved, to preserve what's currently
1602 for (AlignmentAnnotation aa : annotation)
1604 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1605 _aa.sequenceRef = datasetSequence;
1606 _aa.adjustForAlignment(); // uses annotation's own record of
1607 // sequence-column mapping
1608 datasetSequence.addAlignmentAnnotation(_aa);
1612 return datasetSequence;
1619 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1623 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1625 if (annotation != null)
1627 annotation.removeAllElements();
1629 if (annotations != null)
1631 for (int i = 0; i < annotations.length; i++)
1633 if (annotations[i] != null)
1635 addAlignmentAnnotation(annotations[i]);
1642 public AlignmentAnnotation[] getAnnotation(String label)
1644 if (annotation == null || annotation.size() == 0)
1649 Vector<AlignmentAnnotation> subset = new Vector<>();
1650 Enumeration<AlignmentAnnotation> e = annotation.elements();
1651 while (e.hasMoreElements())
1653 AlignmentAnnotation ann = e.nextElement();
1654 if (ann.label != null && ann.label.equals(label))
1656 subset.addElement(ann);
1659 if (subset.size() == 0)
1663 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1665 e = subset.elements();
1666 while (e.hasMoreElements())
1668 anns[i++] = e.nextElement();
1670 subset.removeAllElements();
1675 public boolean updatePDBIds()
1677 if (datasetSequence != null)
1679 // TODO: could merge DBRefs
1680 return datasetSequence.updatePDBIds();
1682 if (dbrefs == null || dbrefs.length == 0)
1686 boolean added = false;
1687 for (DBRefEntry dbr : dbrefs)
1689 if (DBRefSource.PDB.equals(dbr.getSource()))
1692 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1693 * PDB id is not already present in a 'matching' PDBEntry
1694 * Constructor parses out a chain code if appended to the accession id
1695 * (a fudge used to 'store' the chain code in the DBRef)
1697 PDBEntry pdbe = new PDBEntry(dbr);
1698 added |= addPDBId(pdbe);
1705 public void transferAnnotation(SequenceI entry, Mapping mp)
1707 if (datasetSequence != null)
1709 datasetSequence.transferAnnotation(entry, mp);
1712 if (entry.getDatasetSequence() != null)
1714 transferAnnotation(entry.getDatasetSequence(), mp);
1717 // transfer any new features from entry onto sequence
1718 if (entry.getSequenceFeatures() != null)
1721 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1722 for (SequenceFeature feature : sfs)
1724 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1725 : new SequenceFeature[] { new SequenceFeature(feature) };
1728 for (int sfi = 0; sfi < sf.length; sfi++)
1730 addSequenceFeature(sf[sfi]);
1736 // transfer PDB entries
1737 if (entry.getAllPDBEntries() != null)
1739 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1740 while (e.hasMoreElements())
1742 PDBEntry pdb = e.nextElement();
1746 // transfer database references
1747 DBRefEntry[] entryRefs = entry.getDBRefs();
1748 if (entryRefs != null)
1750 for (int r = 0; r < entryRefs.length; r++)
1752 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1753 if (newref.getMap() != null && mp != null)
1755 // remap ref using our local mapping
1757 // we also assume all version string setting is done by dbSourceProxy
1759 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1760 * newref.setSource(dbSource); }
1768 public void setRNA(RNA r)
1780 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1783 List<AlignmentAnnotation> result = new ArrayList<>();
1784 if (this.annotation != null)
1786 for (AlignmentAnnotation ann : annotation)
1788 if (ann.calcId != null && ann.calcId.equals(calcId)
1789 && ann.label != null && ann.label.equals(label))
1799 public String toString()
1801 return getDisplayId(false);
1805 public PDBEntry getPDBEntry(String pdbIdStr)
1807 if (getDatasetSequence() != null)
1809 return getDatasetSequence().getPDBEntry(pdbIdStr);
1815 List<PDBEntry> entries = getAllPDBEntries();
1816 for (PDBEntry entry : entries)
1818 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1827 public List<DBRefEntry> getPrimaryDBRefs()
1829 if (datasetSequence != null)
1831 return datasetSequence.getPrimaryDBRefs();
1833 if (dbrefs == null || dbrefs.length == 0)
1835 return Collections.emptyList();
1837 synchronized (dbrefs)
1839 List<DBRefEntry> primaries = new ArrayList<>();
1840 DBRefEntry[] tmp = new DBRefEntry[1];
1841 for (DBRefEntry ref : dbrefs)
1843 if (!ref.isPrimaryCandidate())
1849 MapList mp = ref.getMap().getMap();
1850 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1852 // map only involves a subsequence, so cannot be primary
1856 // whilst it looks like it is a primary ref, we also sanity check type
1857 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1858 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1860 // PDB dbrefs imply there should be a PDBEntry associated
1861 // TODO: tighten PDB dbrefs
1862 // formally imply Jalview has actually downloaded and
1863 // parsed the pdb file. That means there should be a cached file
1864 // handle on the PDBEntry, and a real mapping between sequence and
1865 // extracted sequence from PDB file
1866 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1867 if (pdbentry != null && pdbentry.getFile() != null)
1873 // check standard protein or dna sources
1875 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1876 if (res != null && res[0] == tmp[0])
1887 public HiddenMarkovModel getHMM()
1893 public void setHMM(HiddenMarkovModel hmm)
1899 public void updateHMMMapping()
1903 hmm.emptyNodeLookup();
1904 for (char residue : sequence)
1906 if (!Comparison.isGap(residue))
1908 hmm.setAlignmentColumn(node, column);
1916 * Maps the HMM sequence to the reference annotation.
1921 public void mapToReference(AlignmentAnnotation rf)
1923 if (this.isHMMConsensusSequence)
1926 hmm.emptyNodeLookup();
1927 for (int i = 0; i < getLength(); i++)
1929 if (rf.annotations[i].displayCharacter.equals("x")
1930 || rf.annotations[i].displayCharacter.equals("X"))
1932 if (i < hmm.getNodeAlignmentColumn(node))
1934 this.deleteChars(i, hmm.getNodeAlignmentColumn(node));
1937 else if (i > hmm.getNodeAlignmentColumn(node))
1939 int length = i - hmm.getNodeAlignmentColumn(node);
1940 this.insertCharAt(hmm.getNodeAlignmentColumn(node), length,
1951 public boolean isHMMConsensusSequence()
1953 return isHMMConsensusSequence;
1957 public void setIsHMMConsensusSequence(boolean isHMMConsensusSequence)
1959 this.isHMMConsensusSequence = isHMMConsensusSequence;
1963 public boolean hasHMMAnnotation()
1969 public void setHasInfo(boolean status)
1975 public int getPreviousPosition()
1977 return previousPosition;
1981 public void setPreviousPosition(int previousPosition)
1983 this.previousPosition = previousPosition;
1990 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1993 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1994 int endPos = fromColumn == toColumn ? startPos
1995 : findPosition(toColumn - 1);
1997 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
2001 * if end column is gapped, endPos may be to the right,
2002 * and we may have included adjacent or enclosing features;
2003 * remove any that are not enclosing, non-contact features
2005 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
2006 && Comparison.isGap(sequence[toColumn - 1]);
2007 if (endPos > this.end || endColumnIsGapped)
2009 ListIterator<SequenceFeature> it = result.listIterator();
2010 while (it.hasNext())
2012 SequenceFeature sf = it.next();
2013 int sfBegin = sf.getBegin();
2014 int sfEnd = sf.getEnd();
2015 int featureStartColumn = findIndex(sfBegin);
2016 if (featureStartColumn > toColumn)
2020 else if (featureStartColumn < fromColumn)
2022 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2024 if (featureEndColumn < fromColumn)
2028 else if (featureEndColumn > toColumn && sf.isContactFeature())
2031 * remove an enclosing feature if it is a contact feature
2043 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2044 * token that has to match the one presented by the cursor
2047 public void sequenceChanged()
2056 public int replace(char c1, char c2)
2063 synchronized (sequence)
2065 for (int c = 0; c < sequence.length; c++)
2067 if (sequence[c] == c1)