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.datamodel.features.SequenceFeatures;
25 import jalview.datamodel.features.SequenceFeaturesI;
26 import jalview.util.Comparison;
27 import jalview.util.DBRefUtils;
28 import jalview.util.MapList;
29 import jalview.util.StringUtils;
30 import jalview.workers.InformationThread;
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.Iterator;
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
48 public class Sequence extends ASequence implements SequenceI
52 * A subclass that gives us access to modCount, which tracks whether there
53 * have been any changes. We use this to update
59 @SuppressWarnings("serial")
60 public class DBModList<T> extends ArrayList<DBRefEntry>
63 protected int getModCount()
70 SequenceI datasetSequence;
74 private char[] sequence;
76 private String description;
82 private Vector<PDBEntry> pdbIds;
84 private String vamsasId;
86 HiddenMarkovModel hmm;
88 boolean isHMMConsensusSequence = false;
89 private DBModList<DBRefEntry> dbrefs; // controlled access
92 * a flag to let us know that elements have changed in dbrefs
96 private int refModCount = 0;
101 * This annotation is displayed below the alignment but the positions are tied
102 * to the residues of this sequence
104 * TODO: change to List<>
106 private Vector<AlignmentAnnotation> annotation;
108 private SequenceFeaturesI sequenceFeatureStore;
111 * A cursor holding the approximate current view position to the sequence,
112 * as determined by findIndex or findPosition or findPositions.
113 * Using a cursor as a hint allows these methods to be more performant for
116 private SequenceCursor cursor;
119 * A number that should be incremented whenever the sequence is edited.
120 * If the value matches the cursor token, then we can trust the cursor,
121 * if not then it should be recomputed.
123 private int changeCount;
126 * Creates a new Sequence object.
129 * display name string
131 * string to form a possibly gapped sequence out of
133 * first position of non-gap residue in the sequence
135 * last position of ungapped residues (nearly always only used for
138 public Sequence(String name, String sequence, int start, int end)
141 initSeqAndName(name, sequence.toCharArray(), start, end);
144 public Sequence(String name, char[] sequence, int start, int end)
147 initSeqAndName(name, sequence, start, end);
151 * Stage 1 constructor - assign name, sequence, and set start and end fields.
152 * start and end are updated values from name2 if it ends with /start-end
159 protected void initSeqAndName(String name2, char[] sequence2, int start2,
163 this.sequence = sequence2;
171 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
172 * start and end respectively and removes the suffix from the name
179 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
182 int slashPos = name.lastIndexOf('/');
183 if (slashPos > -1 && slashPos < name.length() - 1)
185 String suffix = name.substring(slashPos + 1);
186 String[] range = suffix.split("-");
187 if (range.length == 2)
191 int from = Integer.valueOf(range[0]);
192 int to = Integer.valueOf(range[1]);
193 if (from > 0 && to >= from)
195 name = name.substring(0, slashPos);
200 } catch (NumberFormatException e)
202 // leave name unchanged if suffix is invalid
209 * Ensures that 'end' is not before the end of the sequence, that is,
210 * (end-start+1) is at least as long as the count of ungapped positions. Note
211 * that end is permitted to be beyond the end of the sequence data.
213 void checkValidRange()
216 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
219 for (int j = 0; j < sequence.length; j++)
221 if (!Comparison.isGap(sequence[j]))
240 * default constructor
244 sequenceFeatureStore = new SequenceFeatures();
248 * Creates a new Sequence object.
255 public Sequence(String name, String sequence)
257 this(name, sequence, 1, -1);
261 * Create a new sequence object from a characters array using default values
262 * of 1 and -1 for start and end. The array used to create the sequence is
263 * copied and is not stored internally.
270 public Sequence(String name, char[] sequence)
272 this(name, Arrays.copyOf(sequence, sequence.length), 1, -1);
276 * Creates a new Sequence object with new AlignmentAnnotations but inherits
277 * any existing dataset sequence reference. If non exists, everything is
281 * if seq is a dataset sequence, behaves like a plain old copy
284 public Sequence(SequenceI seq)
286 this(seq, seq.getAnnotation());
290 * Create a new sequence object with new features, DBRefEntries, and PDBIds
291 * but inherits any existing dataset sequence reference, and duplicate of any
292 * annotation that is present in the given annotation array.
295 * the sequence to be copied
296 * @param alAnnotation
297 * an array of annotation including some associated with seq
299 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
302 initSeqFrom(seq, alAnnotation);
306 * does the heavy lifting when cloning a dataset sequence, or coping data from
307 * dataset to a new derived sequence.
310 * - source of attributes.
311 * @param alAnnotation
312 * - alignment annotation present on seq that should be copied onto
315 protected void initSeqFrom(SequenceI seq,
316 AlignmentAnnotation[] alAnnotation)
318 char[] oseq = seq.getSequence(); // returns a copy of the array
319 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
321 description = seq.getDescription();
322 if (seq != datasetSequence)
324 setDatasetSequence(seq.getDatasetSequence());
328 * only copy DBRefs and seqfeatures if we really are a dataset sequence
330 if (datasetSequence == null)
332 List<DBRefEntry> dbr = seq.getDBRefs();
335 for (int i = 0, n = dbr.size(); i < n; i++)
337 addDBRef(new DBRefEntry(dbr.get(i)));
342 * make copies of any sequence features
344 for (SequenceFeature sf : seq.getSequenceFeatures())
346 addSequenceFeature(new SequenceFeature(sf));
350 if (seq.getAnnotation() != null)
352 AlignmentAnnotation[] sqann = seq.getAnnotation();
353 for (int i = 0; i < sqann.length; i++)
355 if (sqann[i] == null)
359 boolean found = (alAnnotation == null);
362 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
364 found = (alAnnotation[apos] == sqann[i]);
369 // only copy the given annotation
370 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
371 addAlignmentAnnotation(newann);
375 if (seq.getAllPDBEntries() != null)
377 Vector<PDBEntry> ids = seq.getAllPDBEntries();
378 for (PDBEntry pdb : ids)
380 this.addPDBId(new PDBEntry(pdb));
383 if (seq.getHMM() != null)
385 this.hmm = new HiddenMarkovModel(seq.getHMM(), this);
390 public void setSequenceFeatures(List<SequenceFeature> features)
392 if (datasetSequence != null)
394 datasetSequence.setSequenceFeatures(features);
397 sequenceFeatureStore = new SequenceFeatures(features);
401 public synchronized boolean addSequenceFeature(SequenceFeature sf)
403 if (sf.getType() == null)
406 "SequenceFeature type may not be null: " + sf.toString());
410 if (datasetSequence != null)
412 return datasetSequence.addSequenceFeature(sf);
415 return sequenceFeatureStore.add(sf);
419 public void deleteFeature(SequenceFeature sf)
421 if (datasetSequence != null)
423 datasetSequence.deleteFeature(sf);
427 sequenceFeatureStore.delete(sf);
437 public List<SequenceFeature> getSequenceFeatures()
439 if (datasetSequence != null)
441 return datasetSequence.getSequenceFeatures();
443 return sequenceFeatureStore.getAllFeatures();
447 public SequenceFeaturesI getFeatures()
449 return datasetSequence != null ? datasetSequence.getFeatures()
450 : sequenceFeatureStore;
454 public boolean addPDBId(PDBEntry entry)
458 pdbIds = new Vector<>();
463 for (PDBEntry pdbe : pdbIds)
465 if (pdbe.updateFrom(entry))
470 pdbIds.addElement(entry);
481 public void setPDBId(Vector<PDBEntry> id)
489 * @return DOCUMENT ME!
492 public Vector<PDBEntry> getAllPDBEntries()
494 return pdbIds == null ? new Vector<>() : pdbIds;
498 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
503 public String getDisplayId(boolean jvsuffix)
509 StringBuilder result = new StringBuilder(name);
510 result.append("/").append(start).append("-").append(end);
512 return result.toString();
516 * Sets the sequence name. If the name ends in /start-end, then the start-end
517 * values are parsed out and set, and the suffix is removed from the name.
522 public void setName(String theName)
531 * @return DOCUMENT ME!
534 public String getName()
546 public void setStart(int start)
555 * @return DOCUMENT ME!
558 public int getStart()
570 public void setEnd(int end)
578 * @return DOCUMENT ME!
589 * @return DOCUMENT ME!
592 public int getLength()
594 return this.sequence.length;
598 public void setSequence(char[] seq)
600 this.sequence = Arrays.copyOf(seq, seq.length);
612 public void setSequence(String seq)
614 this.sequence = seq.toCharArray();
620 public String getSequenceAsString()
622 return new String(sequence);
626 public String getSequenceAsString(int start, int end)
628 return new String(getSequence(start, end));
632 public char[] getSequence()
635 return sequence == null ? null
636 : Arrays.copyOf(sequence, sequence.length);
642 * @see jalview.datamodel.SequenceI#getSequence(int, int)
645 public char[] getSequence(int start, int end)
651 // JBPNote - left to user to pad the result here (TODO:Decide on this
653 if (start >= sequence.length)
658 if (end >= sequence.length)
660 end = sequence.length;
663 char[] reply = new char[end - start];
664 System.arraycopy(sequence, start, reply, 0, end - start);
670 public SequenceI getSubSequence(int start, int end)
676 char[] seq = getSequence(start, end);
681 int nstart = findPosition(start);
682 int nend = findPosition(end) - 1;
683 // JBPNote - this is an incomplete copy.
684 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
685 nseq.setDescription(description);
686 if (datasetSequence != null)
688 nseq.setDatasetSequence(datasetSequence);
692 nseq.setDatasetSequence(this);
698 * Returns the character of the aligned sequence at the given position (base
699 * zero), or space if the position is not within the sequence's bounds
704 public char getCharAt(int i)
706 if (i >= 0 && i < sequence.length)
717 * Sets the sequence description, and also parses out any special formats of
723 public void setDescription(String desc)
725 this.description = desc;
729 public void setGeneLoci(String speciesId, String assemblyId,
730 String chromosomeId, MapList map)
732 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
737 * Returns the gene loci mapping for the sequence (may be null)
742 public GeneLociI getGeneLoci()
744 List<DBRefEntry> refs = getDBRefs();
747 for (final DBRefEntry ref : refs)
749 if (ref instanceof GeneLociI)
751 return (GeneLociI) ref;
759 * Answers the description
764 public String getDescription()
766 return this.description;
773 public int findIndex(int pos)
776 * use a valid, hopefully nearby, cursor if available
778 if (isValidCursor(cursor))
780 return findIndex(pos, cursor);
788 * traverse sequence from the start counting gaps; make a note of
789 * the column of the first residue to save in the cursor
791 while ((i < sequence.length) && (j <= end) && (j <= pos))
793 if (!Comparison.isGap(sequence[i]))
804 if (j == end && j < pos)
809 updateCursor(pos, i, startColumn);
814 * Updates the cursor to the latest found residue and column position
821 * column position of the first sequence residue
823 protected void updateCursor(int residuePos, int column, int startColumn)
826 * preserve end residue column provided cursor was valid
828 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
830 if (residuePos == this.end)
835 cursor = new SequenceCursor(this, residuePos, column, startColumn,
836 endColumn, this.changeCount);
840 * Answers the aligned column position (1..) for the given residue position
841 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
842 * The hint may be left of, at, or to the right of the required position.
848 protected int findIndex(final int pos, SequenceCursor curs)
850 if (!isValidCursor(curs))
853 * wrong or invalidated cursor, compute de novo
855 return findIndex(pos);
858 if (curs.residuePosition == pos)
860 return curs.columnPosition;
864 * move left or right to find pos from hint.position
866 int col = curs.columnPosition - 1; // convert from base 1 to base 0
867 int newPos = curs.residuePosition;
868 int delta = newPos > pos ? -1 : 1;
870 while (newPos != pos)
872 col += delta; // shift one column left or right
877 if (col == sequence.length)
879 col--; // return last column if we failed to reach pos
882 if (!Comparison.isGap(sequence[col]))
888 col++; // convert back to base 1
891 * only update cursor if we found the target position
895 updateCursor(pos, col, curs.firstColumnPosition);
905 public int findPosition(final int column)
908 * use a valid, hopefully nearby, cursor if available
910 if (isValidCursor(cursor))
912 return findPosition(column + 1, cursor);
915 // TODO recode this more naturally i.e. count residues only
916 // as they are found, not 'in anticipation'
919 * traverse the sequence counting gaps; note the column position
920 * of the first residue, to save in the cursor
922 int firstResidueColumn = 0;
923 int lastPosFound = 0;
924 int lastPosFoundColumn = 0;
925 int seqlen = sequence.length;
927 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
929 lastPosFound = start;
930 lastPosFoundColumn = 0;
936 while (j < column && j < seqlen)
938 if (!Comparison.isGap(sequence[j]))
941 lastPosFoundColumn = j;
942 if (pos == this.start)
944 firstResidueColumn = j;
950 if (j < seqlen && !Comparison.isGap(sequence[j]))
953 lastPosFoundColumn = j;
954 if (pos == this.start)
956 firstResidueColumn = j;
961 * update the cursor to the last residue position found (if any)
962 * (converting column position to base 1)
964 if (lastPosFound != 0)
966 updateCursor(lastPosFound, lastPosFoundColumn + 1,
967 firstResidueColumn + 1);
974 * Answers true if the given cursor is not null, is for this sequence object,
975 * and has a token value that matches this object's changeCount, else false.
976 * This allows us to ignore a cursor as 'stale' if the sequence has been
977 * modified since the cursor was created.
982 protected boolean isValidCursor(SequenceCursor curs)
984 if (curs == null || curs.sequence != this || curs.token != changeCount)
989 * sanity check against range
991 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
995 if (curs.residuePosition < start || curs.residuePosition > end)
1003 * Answers the sequence position (start..) for the given aligned column
1004 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
1005 * may lie left of, at, or to the right of the column position.
1011 protected int findPosition(final int col, SequenceCursor curs)
1013 if (!isValidCursor(curs))
1016 * wrong or invalidated cursor, compute de novo
1018 return findPosition(col - 1);// ugh back to base 0
1021 if (curs.columnPosition == col)
1023 cursor = curs; // in case this method becomes public
1024 return curs.residuePosition; // easy case :-)
1027 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1030 * sequence lies entirely to the left of col
1031 * - return last residue + 1
1036 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1039 * sequence lies entirely to the right of col
1040 * - return first residue
1045 // todo could choose closest to col out of column,
1046 // firstColumnPosition, lastColumnPosition as a start point
1049 * move left or right to find pos from cursor position
1051 int firstResidueColumn = curs.firstColumnPosition;
1052 int column = curs.columnPosition - 1; // to base 0
1053 int newPos = curs.residuePosition;
1054 int delta = curs.columnPosition > col ? -1 : 1;
1055 boolean gapped = false;
1056 int lastFoundPosition = curs.residuePosition;
1057 int lastFoundPositionColumn = curs.columnPosition;
1059 while (column != col - 1)
1061 column += delta; // shift one column left or right
1062 if (column < 0 || column == sequence.length)
1066 gapped = Comparison.isGap(sequence[column]);
1070 lastFoundPosition = newPos;
1071 lastFoundPositionColumn = column + 1;
1072 if (lastFoundPosition == this.start)
1074 firstResidueColumn = column + 1;
1079 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1081 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1082 firstResidueColumn);
1086 * hack to give position to the right if on a gap
1087 * or beyond the length of the sequence (see JAL-2562)
1089 if (delta > 0 && (gapped || column >= sequence.length))
1101 public ContiguousI findPositions(int fromColumn, int toColumn)
1103 fromColumn = Math.max(fromColumn, 1);
1104 if (toColumn < fromColumn)
1110 * find the first non-gapped position, if any
1112 int firstPosition = 0;
1113 int col = fromColumn - 1;
1114 int length = sequence.length;
1115 while (col < length && col < toColumn)
1117 if (!Comparison.isGap(sequence[col]))
1119 firstPosition = findPosition(col++);
1125 if (firstPosition == 0)
1131 * find the last non-gapped position
1133 int lastPosition = firstPosition;
1134 while (col < length && col < toColumn)
1136 if (!Comparison.isGap(sequence[col++]))
1142 return new Range(firstPosition, lastPosition);
1146 * Returns an int array where indices correspond to each residue in the
1147 * sequence and the element value gives its position in the alignment
1149 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1150 * residues in SequenceI object
1153 public int[] gapMap()
1155 String seq = jalview.analysis.AlignSeq.extractGaps(
1156 jalview.util.Comparison.GapChars, new String(sequence));
1157 int[] map = new int[seq.length()];
1161 while (j < sequence.length)
1163 if (!jalview.util.Comparison.isGap(sequence[j]))
1175 * Build a bitset corresponding to sequence gaps
1177 * @return a BitSet where set values correspond to gaps in the sequence
1180 public BitSet gapBitset()
1182 BitSet gaps = new BitSet(sequence.length);
1184 while (j < sequence.length)
1186 if (jalview.util.Comparison.isGap(sequence[j]))
1196 public int[] findPositionMap()
1198 int map[] = new int[sequence.length];
1201 int seqlen = sequence.length;
1202 while ((j < seqlen))
1205 if (!jalview.util.Comparison.isGap(sequence[j]))
1216 public List<int[]> getInsertions()
1218 ArrayList<int[]> map = new ArrayList<>();
1219 int lastj = -1, j = 0;
1221 int seqlen = sequence.length;
1222 while ((j < seqlen))
1224 if (jalview.util.Comparison.isGap(sequence[j]))
1235 map.add(new int[] { lastj, j - 1 });
1243 map.add(new int[] { lastj, j - 1 });
1250 public BitSet getInsertionsAsBits()
1252 BitSet map = new BitSet();
1253 int lastj = -1, j = 0;
1255 int seqlen = sequence.length;
1256 while ((j < seqlen))
1258 if (jalview.util.Comparison.isGap(sequence[j]))
1284 public void deleteChars(final int i, final int j)
1286 int newstart = start, newend = end;
1287 if (i >= sequence.length || i < 0)
1292 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1293 boolean createNewDs = false;
1294 // TODO: take a (second look) at the dataset creation validation method for
1295 // the very large sequence case
1297 int startIndex = findIndex(start) - 1;
1298 int endIndex = findIndex(end) - 1;
1299 int startDeleteColumn = -1; // for dataset sequence deletions
1300 int deleteCount = 0;
1302 for (int s = i; s < j && s < sequence.length; s++)
1304 if (Comparison.isGap(sequence[s]))
1309 if (startDeleteColumn == -1)
1311 startDeleteColumn = findPosition(s) - start;
1319 if (startIndex == s)
1322 * deleting characters from start of sequence; new start is the
1323 * sequence position of the next column (position to the right
1324 * if the column position is gapped)
1326 newstart = findPosition(j);
1334 * deleting characters at end of sequence; new end is the sequence
1335 * position of the column before the deletion; subtract 1 if this is
1336 * gapped since findPosition returns the next sequence position
1338 newend = findPosition(i - 1);
1339 if (Comparison.isGap(sequence[i - 1]))
1354 if (createNewDs && this.datasetSequence != null)
1357 * if deletion occured in the middle of the sequence,
1358 * construct a new dataset sequence and delete the residues
1359 * that were deleted from the aligned sequence
1361 Sequence ds = new Sequence(datasetSequence);
1362 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1363 datasetSequence = ds;
1364 // TODO: remove any non-inheritable properties ?
1365 // TODO: create a sequence mapping (since there is a relation here ?)
1374 public void insertCharAt(int i, int length, char c)
1376 char[] tmp = new char[sequence.length + length];
1378 if (i >= sequence.length)
1380 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1381 i = sequence.length;
1385 System.arraycopy(sequence, 0, tmp, 0, i);
1395 if (i < sequence.length)
1397 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1405 public void insertCharAt(int i, char c)
1407 insertCharAt(i, 1, c);
1411 public String getVamsasId()
1417 public void setVamsasId(String id)
1424 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1426 if (dbrefs == null && datasetSequence != null
1427 && this != datasetSequence)
1429 datasetSequence.setDBRefs(newDBrefs);
1437 public DBModList<DBRefEntry> getDBRefs()
1439 if (dbrefs == null && datasetSequence != null
1440 && this != datasetSequence)
1442 return datasetSequence.getDBRefs();
1448 public void addDBRef(DBRefEntry entry)
1450 // TODO JAL-3980 maintain as sorted list
1451 if (datasetSequence != null)
1453 datasetSequence.addDBRef(entry);
1459 dbrefs = new DBModList<>();
1461 // TODO JAL-3979 LOOK UP RATHER THAN SWEEP FOR EFFICIENCY
1463 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1465 if (dbrefs.get(ib).updateFrom(entry))
1468 * found a dbref that either matched, or could be
1469 * updated from, the new entry - no need to add it
1477 // * extend the array to make room for one more
1479 // // TODO use an ArrayList instead
1480 // int j = dbrefs.length;
1481 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1482 // System.arraycopy(dbrefs, 0, temp, 0, j);
1483 // temp[temp.length - 1] = entry;
1491 public void setDatasetSequence(SequenceI seq)
1495 throw new IllegalArgumentException(
1496 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1498 if (seq != null && seq.getDatasetSequence() != null)
1500 throw new IllegalArgumentException(
1501 "Implementation error: cascading dataset sequences are not allowed.");
1503 datasetSequence = seq;
1507 public SequenceI getDatasetSequence()
1509 return datasetSequence;
1513 public AlignmentAnnotation[] getAnnotation()
1515 return annotation == null ? null
1517 .toArray(new AlignmentAnnotation[annotation.size()]);
1521 public boolean hasAnnotation(AlignmentAnnotation ann)
1523 return annotation == null ? false : annotation.contains(ann);
1527 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1529 if (this.annotation == null)
1531 this.annotation = new Vector<>();
1533 if (!this.annotation.contains(annotation))
1535 this.annotation.addElement(annotation);
1537 annotation.setSequenceRef(this);
1541 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1543 if (this.annotation != null)
1545 this.annotation.removeElement(annotation);
1546 if (this.annotation.size() == 0)
1548 this.annotation = null;
1554 * test if this is a valid candidate for another sequence's dataset sequence.
1557 private boolean isValidDatasetSequence()
1559 if (datasetSequence != null)
1563 for (int i = 0; i < sequence.length; i++)
1565 if (jalview.util.Comparison.isGap(sequence[i]))
1574 public SequenceI deriveSequence()
1576 Sequence seq = null;
1577 if (datasetSequence == null)
1579 if (isValidDatasetSequence())
1581 // Use this as dataset sequence
1582 seq = new Sequence(getName(), "", 1, -1);
1583 seq.setDatasetSequence(this);
1584 seq.initSeqFrom(this, getAnnotation());
1589 // Create a new, valid dataset sequence
1590 createDatasetSequence();
1593 return new Sequence(this);
1596 private boolean _isNa;
1598 private int _seqhash = 0;
1600 private List<DBRefEntry> primaryRefs;
1603 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1607 public boolean isProtein()
1609 if (datasetSequence != null)
1611 return datasetSequence.isProtein();
1613 if (_seqhash != sequence.hashCode())
1615 _seqhash = sequence.hashCode();
1616 _isNa = Comparison.isNucleotide(this);
1624 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1627 public SequenceI createDatasetSequence()
1629 if (datasetSequence == null)
1631 Sequence dsseq = new Sequence(getName(),
1632 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1633 getSequenceAsString()),
1634 getStart(), getEnd());
1636 datasetSequence = dsseq;
1638 dsseq.setDescription(description);
1639 // move features and database references onto dataset sequence
1640 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1641 sequenceFeatureStore = null;
1642 dsseq.dbrefs = dbrefs;
1644 // TODO: search and replace any references to this sequence with
1645 // references to the dataset sequence in Mappings on dbref
1646 dsseq.pdbIds = pdbIds;
1648 datasetSequence.updatePDBIds();
1649 if (annotation != null)
1651 // annotation is cloned rather than moved, to preserve what's currently
1653 for (AlignmentAnnotation aa : annotation)
1655 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1656 _aa.sequenceRef = datasetSequence;
1657 _aa.adjustForAlignment(); // uses annotation's own record of
1658 // sequence-column mapping
1659 datasetSequence.addAlignmentAnnotation(_aa);
1663 return datasetSequence;
1670 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1674 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1676 if (annotation != null)
1678 annotation.removeAllElements();
1680 if (annotations != null)
1682 for (int i = 0; i < annotations.length; i++)
1684 if (annotations[i] != null)
1686 addAlignmentAnnotation(annotations[i]);
1693 public AlignmentAnnotation[] getAnnotation(String label)
1695 if (annotation == null || annotation.size() == 0)
1700 Vector<AlignmentAnnotation> subset = new Vector<>();
1701 Enumeration<AlignmentAnnotation> e = annotation.elements();
1702 while (e.hasMoreElements())
1704 AlignmentAnnotation ann = e.nextElement();
1705 if (ann.label != null && ann.label.equals(label))
1707 subset.addElement(ann);
1710 if (subset.size() == 0)
1714 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1716 e = subset.elements();
1717 while (e.hasMoreElements())
1719 anns[i++] = e.nextElement();
1721 subset.removeAllElements();
1726 public boolean updatePDBIds()
1728 if (datasetSequence != null)
1730 // TODO: could merge DBRefs
1731 return datasetSequence.updatePDBIds();
1733 if (dbrefs == null || dbrefs.size() == 0)
1737 boolean added = false;
1738 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1740 DBRefEntry dbr = dbrefs.get(ib);
1741 if (DBRefSource.PDB.equals(dbr.getSource()))
1744 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1745 * PDB id is not already present in a 'matching' PDBEntry
1746 * Constructor parses out a chain code if appended to the accession id
1747 * (a fudge used to 'store' the chain code in the DBRef)
1749 PDBEntry pdbe = new PDBEntry(dbr);
1750 added |= addPDBId(pdbe);
1757 public void transferAnnotation(SequenceI entry, Mapping mp)
1759 if (datasetSequence != null)
1761 datasetSequence.transferAnnotation(entry, mp);
1764 if (entry.getDatasetSequence() != null)
1766 transferAnnotation(entry.getDatasetSequence(), mp);
1769 // transfer any new features from entry onto sequence
1770 if (entry.getSequenceFeatures() != null)
1773 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1774 for (SequenceFeature feature : sfs)
1776 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1777 : new SequenceFeature[]
1778 { new SequenceFeature(feature) };
1781 for (int sfi = 0; sfi < sf.length; sfi++)
1783 addSequenceFeature(sf[sfi]);
1789 // transfer PDB entries
1790 if (entry.getAllPDBEntries() != null)
1792 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1793 while (e.hasMoreElements())
1795 PDBEntry pdb = e.nextElement();
1799 // transfer database references
1800 List<DBRefEntry> entryRefs = entry.getDBRefs();
1801 if (entryRefs != null)
1803 for (int r = 0, n = entryRefs.size(); r < n; r++)
1805 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1806 if (newref.getMap() != null && mp != null)
1808 // remap ref using our local mapping
1810 // we also assume all version string setting is done by dbSourceProxy
1812 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1813 * newref.setSource(dbSource); }
1821 public void setRNA(RNA r)
1833 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1836 return getAlignmentAnnotations(calcId, label, null, true);
1840 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1841 String label, String description)
1843 return getAlignmentAnnotations(calcId, label, description, false);
1846 private List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1847 String label, String description, boolean ignoreDescription)
1849 List<AlignmentAnnotation> result = new ArrayList<>();
1850 if (this.annotation != null)
1852 for (AlignmentAnnotation ann : annotation)
1854 String id = ann.getCalcId();
1855 if ((id != null && id.equals(calcId))
1856 && (ann.label != null && ann.label.equals(label))
1857 && ((ignoreDescription && description == null)
1858 || (ann.description != null
1859 && ann.description.equals(description))))
1869 public String toString()
1871 return getDisplayId(false);
1875 public PDBEntry getPDBEntry(String pdbIdStr)
1877 if (getDatasetSequence() != null)
1879 return getDatasetSequence().getPDBEntry(pdbIdStr);
1885 List<PDBEntry> entries = getAllPDBEntries();
1886 for (PDBEntry entry : entries)
1888 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1896 private List<DBRefEntry> tmpList;
1899 public List<DBRefEntry> getPrimaryDBRefs()
1901 if (datasetSequence != null)
1903 return datasetSequence.getPrimaryDBRefs();
1905 if (dbrefs == null || dbrefs.size() == 0)
1907 return Collections.emptyList();
1909 synchronized (dbrefs)
1911 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1913 return primaryRefs; // no changes
1915 refModCount = dbrefs.getModCount();
1916 List<DBRefEntry> primaries = (primaryRefs == null
1917 ? (primaryRefs = new ArrayList<>())
1920 if (tmpList == null)
1922 tmpList = new ArrayList<>();
1923 tmpList.add(null); // for replacement
1925 for (int i = 0, n = dbrefs.size(); i < n; i++)
1927 DBRefEntry ref = dbrefs.get(i);
1928 if (!ref.isPrimaryCandidate())
1934 MapList mp = ref.getMap().getMap();
1935 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1937 // map only involves a subsequence, so cannot be primary
1941 // whilst it looks like it is a primary ref, we also sanity check type
1942 if (DBRefSource.PDB_CANONICAL_NAME
1943 .equals(ref.getCanonicalSourceName()))
1945 // PDB dbrefs imply there should be a PDBEntry associated
1946 // TODO: tighten PDB dbrefs
1947 // formally imply Jalview has actually downloaded and
1948 // parsed the pdb file. That means there should be a cached file
1949 // handle on the PDBEntry, and a real mapping between sequence and
1950 // extracted sequence from PDB file
1951 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1952 if (pdbentry == null || pdbentry.getFile() == null)
1959 // check standard protein or dna sources
1960 tmpList.set(0, ref);
1961 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1963 if (res == null || res.get(0) != tmpList.get(0))
1971 // version must be not null, as otherwise it will not be a candidate,
1973 DBRefUtils.ensurePrimaries(this, primaries);
1979 public HiddenMarkovModel getHMM()
1985 public void setHMM(HiddenMarkovModel hmm)
1991 public boolean hasHMMAnnotation()
1993 if (this.annotation == null) {
1996 for (AlignmentAnnotation ann : annotation)
1998 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
2009 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
2012 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
2013 int endPos = fromColumn == toColumn ? startPos
2014 : findPosition(toColumn - 1);
2016 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
2020 * if end column is gapped, endPos may be to the right,
2021 * and we may have included adjacent or enclosing features;
2022 * remove any that are not enclosing, non-contact features
2024 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
2025 && Comparison.isGap(sequence[toColumn - 1]);
2026 if (endPos > this.end || endColumnIsGapped)
2028 ListIterator<SequenceFeature> it = result.listIterator();
2029 while (it.hasNext())
2031 SequenceFeature sf = it.next();
2032 int sfBegin = sf.getBegin();
2033 int sfEnd = sf.getEnd();
2034 int featureStartColumn = findIndex(sfBegin);
2035 if (featureStartColumn > toColumn)
2039 else if (featureStartColumn < fromColumn)
2041 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2043 if (featureEndColumn < fromColumn)
2047 else if (featureEndColumn > toColumn && sf.isContactFeature())
2050 * remove an enclosing feature if it is a contact feature
2062 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2063 * token that has to match the one presented by the cursor
2066 public void sequenceChanged()
2075 public int replace(char c1, char c2)
2082 synchronized (sequence)
2084 for (int c = 0; c < sequence.length; c++)
2086 if (sequence[c] == c1)
2102 public String getSequenceStringFromIterator(Iterator<int[]> it)
2104 StringBuilder newSequence = new StringBuilder();
2105 while (it.hasNext())
2107 int[] block = it.next();
2110 newSequence.append(getSequence(block[0], block[1] + 1));
2114 newSequence.append(getSequence(block[0], block[1]));
2118 return newSequence.toString();
2122 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2126 if (!regions.hasNext())
2128 return findIndex(getStart()) - 1;
2131 // Simply walk along the sequence whilst watching for region
2133 int hideStart = getLength();
2135 boolean foundStart = false;
2137 // step through the non-gapped positions of the sequence
2138 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2140 // get alignment position of this residue in the sequence
2141 int p = findIndex(i) - 1;
2143 // update region start/end
2144 while (hideEnd < p && regions.hasNext())
2146 int[] region = regions.next();
2147 hideStart = region[0];
2148 hideEnd = region[1];
2152 hideStart = getLength();
2154 // update boundary for sequence
2166 // otherwise, sequence was completely hidden
2171 public boolean hasHMMProfile()