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;
604 public void setSequence(String seq)
606 this.sequence = seq.toCharArray();
612 public String getSequenceAsString()
614 return new String(sequence);
618 public String getSequenceAsString(int start, int end)
620 return new String(getSequence(start, end));
624 public char[] getSequence()
627 return sequence == null ? null
628 : Arrays.copyOf(sequence, sequence.length);
634 * @see jalview.datamodel.SequenceI#getSequence(int, int)
637 public char[] getSequence(int start, int end)
643 // JBPNote - left to user to pad the result here (TODO:Decide on this
645 if (start >= sequence.length)
650 if (end >= sequence.length)
652 end = sequence.length;
655 char[] reply = new char[end - start];
656 System.arraycopy(sequence, start, reply, 0, end - start);
662 public SequenceI getSubSequence(int start, int end)
668 char[] seq = getSequence(start, end);
673 int nstart = findPosition(start);
674 int nend = findPosition(end) - 1;
675 // JBPNote - this is an incomplete copy.
676 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
677 nseq.setDescription(description);
678 if (datasetSequence != null)
680 nseq.setDatasetSequence(datasetSequence);
684 nseq.setDatasetSequence(this);
690 * Returns the character of the aligned sequence at the given position (base
691 * zero), or space if the position is not within the sequence's bounds
696 public char getCharAt(int i)
698 if (i >= 0 && i < sequence.length)
709 * Sets the sequence description, and also parses out any special formats of
715 public void setDescription(String desc)
717 this.description = desc;
721 public void setGeneLoci(String speciesId, String assemblyId,
722 String chromosomeId, MapList map)
724 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
729 * Returns the gene loci mapping for the sequence (may be null)
734 public GeneLociI getGeneLoci()
736 List<DBRefEntry> refs = getDBRefs();
739 for (final DBRefEntry ref : refs)
741 if (ref instanceof GeneLociI)
743 return (GeneLociI) ref;
751 * Answers the description
756 public String getDescription()
758 return this.description;
765 public int findIndex(int pos)
768 * use a valid, hopefully nearby, cursor if available
770 if (isValidCursor(cursor))
772 return findIndex(pos, cursor);
780 * traverse sequence from the start counting gaps; make a note of
781 * the column of the first residue to save in the cursor
783 while ((i < sequence.length) && (j <= end) && (j <= pos))
785 if (!Comparison.isGap(sequence[i]))
796 if (j == end && j < pos)
801 updateCursor(pos, i, startColumn);
806 * Updates the cursor to the latest found residue and column position
813 * column position of the first sequence residue
815 protected void updateCursor(int residuePos, int column, int startColumn)
818 * preserve end residue column provided cursor was valid
820 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
822 if (residuePos == this.end)
827 cursor = new SequenceCursor(this, residuePos, column, startColumn,
828 endColumn, this.changeCount);
832 * Answers the aligned column position (1..) for the given residue position
833 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
834 * The hint may be left of, at, or to the right of the required position.
840 protected int findIndex(final int pos, SequenceCursor curs)
842 if (!isValidCursor(curs))
845 * wrong or invalidated cursor, compute de novo
847 return findIndex(pos);
850 if (curs.residuePosition == pos)
852 return curs.columnPosition;
856 * move left or right to find pos from hint.position
858 int col = curs.columnPosition - 1; // convert from base 1 to base 0
859 int newPos = curs.residuePosition;
860 int delta = newPos > pos ? -1 : 1;
862 while (newPos != pos)
864 col += delta; // shift one column left or right
869 if (col == sequence.length)
871 col--; // return last column if we failed to reach pos
874 if (!Comparison.isGap(sequence[col]))
880 col++; // convert back to base 1
883 * only update cursor if we found the target position
887 updateCursor(pos, col, curs.firstColumnPosition);
897 public int findPosition(final int column)
900 * use a valid, hopefully nearby, cursor if available
902 if (isValidCursor(cursor))
904 return findPosition(column + 1, cursor);
907 // TODO recode this more naturally i.e. count residues only
908 // as they are found, not 'in anticipation'
911 * traverse the sequence counting gaps; note the column position
912 * of the first residue, to save in the cursor
914 int firstResidueColumn = 0;
915 int lastPosFound = 0;
916 int lastPosFoundColumn = 0;
917 int seqlen = sequence.length;
919 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
921 lastPosFound = start;
922 lastPosFoundColumn = 0;
928 while (j < column && j < seqlen)
930 if (!Comparison.isGap(sequence[j]))
933 lastPosFoundColumn = j;
934 if (pos == this.start)
936 firstResidueColumn = j;
942 if (j < seqlen && !Comparison.isGap(sequence[j]))
945 lastPosFoundColumn = j;
946 if (pos == this.start)
948 firstResidueColumn = j;
953 * update the cursor to the last residue position found (if any)
954 * (converting column position to base 1)
956 if (lastPosFound != 0)
958 updateCursor(lastPosFound, lastPosFoundColumn + 1,
959 firstResidueColumn + 1);
966 * Answers true if the given cursor is not null, is for this sequence object,
967 * and has a token value that matches this object's changeCount, else false.
968 * This allows us to ignore a cursor as 'stale' if the sequence has been
969 * modified since the cursor was created.
974 protected boolean isValidCursor(SequenceCursor curs)
976 if (curs == null || curs.sequence != this || curs.token != changeCount)
981 * sanity check against range
983 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
987 if (curs.residuePosition < start || curs.residuePosition > end)
995 * Answers the sequence position (start..) for the given aligned column
996 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
997 * may lie left of, at, or to the right of the column position.
1003 protected int findPosition(final int col, SequenceCursor curs)
1005 if (!isValidCursor(curs))
1008 * wrong or invalidated cursor, compute de novo
1010 return findPosition(col - 1);// ugh back to base 0
1013 if (curs.columnPosition == col)
1015 cursor = curs; // in case this method becomes public
1016 return curs.residuePosition; // easy case :-)
1019 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1022 * sequence lies entirely to the left of col
1023 * - return last residue + 1
1028 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1031 * sequence lies entirely to the right of col
1032 * - return first residue
1037 // todo could choose closest to col out of column,
1038 // firstColumnPosition, lastColumnPosition as a start point
1041 * move left or right to find pos from cursor position
1043 int firstResidueColumn = curs.firstColumnPosition;
1044 int column = curs.columnPosition - 1; // to base 0
1045 int newPos = curs.residuePosition;
1046 int delta = curs.columnPosition > col ? -1 : 1;
1047 boolean gapped = false;
1048 int lastFoundPosition = curs.residuePosition;
1049 int lastFoundPositionColumn = curs.columnPosition;
1051 while (column != col - 1)
1053 column += delta; // shift one column left or right
1054 if (column < 0 || column == sequence.length)
1058 gapped = Comparison.isGap(sequence[column]);
1062 lastFoundPosition = newPos;
1063 lastFoundPositionColumn = column + 1;
1064 if (lastFoundPosition == this.start)
1066 firstResidueColumn = column + 1;
1071 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1073 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1074 firstResidueColumn);
1078 * hack to give position to the right if on a gap
1079 * or beyond the length of the sequence (see JAL-2562)
1081 if (delta > 0 && (gapped || column >= sequence.length))
1093 public ContiguousI findPositions(int fromColumn, int toColumn)
1095 fromColumn = Math.max(fromColumn, 1);
1096 if (toColumn < fromColumn)
1102 * find the first non-gapped position, if any
1104 int firstPosition = 0;
1105 int col = fromColumn - 1;
1106 int length = sequence.length;
1107 while (col < length && col < toColumn)
1109 if (!Comparison.isGap(sequence[col]))
1111 firstPosition = findPosition(col++);
1117 if (firstPosition == 0)
1123 * find the last non-gapped position
1125 int lastPosition = firstPosition;
1126 while (col < length && col < toColumn)
1128 if (!Comparison.isGap(sequence[col++]))
1134 return new Range(firstPosition, lastPosition);
1138 * Returns an int array where indices correspond to each residue in the
1139 * sequence and the element value gives its position in the alignment
1141 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1142 * residues in SequenceI object
1145 public int[] gapMap()
1147 String seq = jalview.analysis.AlignSeq.extractGaps(
1148 jalview.util.Comparison.GapChars, new String(sequence));
1149 int[] map = new int[seq.length()];
1153 while (j < sequence.length)
1155 if (!jalview.util.Comparison.isGap(sequence[j]))
1167 * Build a bitset corresponding to sequence gaps
1169 * @return a BitSet where set values correspond to gaps in the sequence
1172 public BitSet gapBitset()
1174 BitSet gaps = new BitSet(sequence.length);
1176 while (j < sequence.length)
1178 if (jalview.util.Comparison.isGap(sequence[j]))
1188 public int[] findPositionMap()
1190 int map[] = new int[sequence.length];
1193 int seqlen = sequence.length;
1194 while ((j < seqlen))
1197 if (!jalview.util.Comparison.isGap(sequence[j]))
1208 public List<int[]> getInsertions()
1210 ArrayList<int[]> map = new ArrayList<>();
1211 int lastj = -1, j = 0;
1213 int seqlen = sequence.length;
1214 while ((j < seqlen))
1216 if (jalview.util.Comparison.isGap(sequence[j]))
1227 map.add(new int[] { lastj, j - 1 });
1235 map.add(new int[] { lastj, j - 1 });
1242 public BitSet getInsertionsAsBits()
1244 BitSet map = new BitSet();
1245 int lastj = -1, j = 0;
1247 int seqlen = sequence.length;
1248 while ((j < seqlen))
1250 if (jalview.util.Comparison.isGap(sequence[j]))
1276 public void deleteChars(final int i, final int j)
1278 int newstart = start, newend = end;
1279 if (i >= sequence.length || i < 0)
1284 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1285 boolean createNewDs = false;
1286 // TODO: take a (second look) at the dataset creation validation method for
1287 // the very large sequence case
1289 int startIndex = findIndex(start) - 1;
1290 int endIndex = findIndex(end) - 1;
1291 int startDeleteColumn = -1; // for dataset sequence deletions
1292 int deleteCount = 0;
1294 for (int s = i; s < j && s < sequence.length; s++)
1296 if (Comparison.isGap(sequence[s]))
1301 if (startDeleteColumn == -1)
1303 startDeleteColumn = findPosition(s) - start;
1311 if (startIndex == s)
1314 * deleting characters from start of sequence; new start is the
1315 * sequence position of the next column (position to the right
1316 * if the column position is gapped)
1318 newstart = findPosition(j);
1326 * deleting characters at end of sequence; new end is the sequence
1327 * position of the column before the deletion; subtract 1 if this is
1328 * gapped since findPosition returns the next sequence position
1330 newend = findPosition(i - 1);
1331 if (Comparison.isGap(sequence[i - 1]))
1346 if (createNewDs && this.datasetSequence != null)
1349 * if deletion occured in the middle of the sequence,
1350 * construct a new dataset sequence and delete the residues
1351 * that were deleted from the aligned sequence
1353 Sequence ds = new Sequence(datasetSequence);
1354 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1355 datasetSequence = ds;
1356 // TODO: remove any non-inheritable properties ?
1357 // TODO: create a sequence mapping (since there is a relation here ?)
1366 public void insertCharAt(int i, int length, char c)
1368 char[] tmp = new char[sequence.length + length];
1370 if (i >= sequence.length)
1372 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1373 i = sequence.length;
1377 System.arraycopy(sequence, 0, tmp, 0, i);
1387 if (i < sequence.length)
1389 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1397 public void insertCharAt(int i, char c)
1399 insertCharAt(i, 1, c);
1403 public String getVamsasId()
1409 public void setVamsasId(String id)
1416 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1418 if (dbrefs == null && datasetSequence != null
1419 && this != datasetSequence)
1421 datasetSequence.setDBRefs(newDBrefs);
1429 public DBModList<DBRefEntry> getDBRefs()
1431 if (dbrefs == null && datasetSequence != null
1432 && this != datasetSequence)
1434 return datasetSequence.getDBRefs();
1440 public void addDBRef(DBRefEntry entry)
1442 // TODO JAL-3980 maintain as sorted list
1443 if (datasetSequence != null)
1445 datasetSequence.addDBRef(entry);
1451 dbrefs = new DBModList<>();
1453 // TODO JAL-3979 LOOK UP RATHER THAN SWEEP FOR EFFICIENCY
1455 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1457 if (dbrefs.get(ib).updateFrom(entry))
1460 * found a dbref that either matched, or could be
1461 * updated from, the new entry - no need to add it
1469 // * extend the array to make room for one more
1471 // // TODO use an ArrayList instead
1472 // int j = dbrefs.length;
1473 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1474 // System.arraycopy(dbrefs, 0, temp, 0, j);
1475 // temp[temp.length - 1] = entry;
1483 public void setDatasetSequence(SequenceI seq)
1487 throw new IllegalArgumentException(
1488 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1490 if (seq != null && seq.getDatasetSequence() != null)
1492 throw new IllegalArgumentException(
1493 "Implementation error: cascading dataset sequences are not allowed.");
1495 datasetSequence = seq;
1499 public SequenceI getDatasetSequence()
1501 return datasetSequence;
1505 public AlignmentAnnotation[] getAnnotation()
1507 return annotation == null ? null
1509 .toArray(new AlignmentAnnotation[annotation.size()]);
1513 public boolean hasAnnotation(AlignmentAnnotation ann)
1515 return annotation == null ? false : annotation.contains(ann);
1519 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1521 if (this.annotation == null)
1523 this.annotation = new Vector<>();
1525 if (!this.annotation.contains(annotation))
1527 this.annotation.addElement(annotation);
1529 annotation.setSequenceRef(this);
1533 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1535 if (this.annotation != null)
1537 this.annotation.removeElement(annotation);
1538 if (this.annotation.size() == 0)
1540 this.annotation = null;
1546 * test if this is a valid candidate for another sequence's dataset sequence.
1549 private boolean isValidDatasetSequence()
1551 if (datasetSequence != null)
1555 for (int i = 0; i < sequence.length; i++)
1557 if (jalview.util.Comparison.isGap(sequence[i]))
1566 public SequenceI deriveSequence()
1568 Sequence seq = null;
1569 if (datasetSequence == null)
1571 if (isValidDatasetSequence())
1573 // Use this as dataset sequence
1574 seq = new Sequence(getName(), "", 1, -1);
1575 seq.setDatasetSequence(this);
1576 seq.initSeqFrom(this, getAnnotation());
1581 // Create a new, valid dataset sequence
1582 createDatasetSequence();
1585 return new Sequence(this);
1588 private boolean _isNa;
1590 private int _seqhash = 0;
1592 private List<DBRefEntry> primaryRefs;
1595 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1599 public boolean isProtein()
1601 if (datasetSequence != null)
1603 return datasetSequence.isProtein();
1605 if (_seqhash != sequence.hashCode())
1607 _seqhash = sequence.hashCode();
1608 _isNa = Comparison.isNucleotide(this);
1616 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1619 public SequenceI createDatasetSequence()
1621 if (datasetSequence == null)
1623 Sequence dsseq = new Sequence(getName(),
1624 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1625 getSequenceAsString()),
1626 getStart(), getEnd());
1628 datasetSequence = dsseq;
1630 dsseq.setDescription(description);
1631 // move features and database references onto dataset sequence
1632 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1633 sequenceFeatureStore = null;
1634 dsseq.dbrefs = dbrefs;
1636 // TODO: search and replace any references to this sequence with
1637 // references to the dataset sequence in Mappings on dbref
1638 dsseq.pdbIds = pdbIds;
1640 datasetSequence.updatePDBIds();
1641 if (annotation != null)
1643 // annotation is cloned rather than moved, to preserve what's currently
1645 for (AlignmentAnnotation aa : annotation)
1647 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1648 _aa.sequenceRef = datasetSequence;
1649 _aa.adjustForAlignment(); // uses annotation's own record of
1650 // sequence-column mapping
1651 datasetSequence.addAlignmentAnnotation(_aa);
1655 return datasetSequence;
1662 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1666 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1668 if (annotation != null)
1670 annotation.removeAllElements();
1672 if (annotations != null)
1674 for (int i = 0; i < annotations.length; i++)
1676 if (annotations[i] != null)
1678 addAlignmentAnnotation(annotations[i]);
1685 public AlignmentAnnotation[] getAnnotation(String label)
1687 if (annotation == null || annotation.size() == 0)
1692 Vector<AlignmentAnnotation> subset = new Vector<>();
1693 Enumeration<AlignmentAnnotation> e = annotation.elements();
1694 while (e.hasMoreElements())
1696 AlignmentAnnotation ann = e.nextElement();
1697 if (ann.label != null && ann.label.equals(label))
1699 subset.addElement(ann);
1702 if (subset.size() == 0)
1706 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1708 e = subset.elements();
1709 while (e.hasMoreElements())
1711 anns[i++] = e.nextElement();
1713 subset.removeAllElements();
1718 public boolean updatePDBIds()
1720 if (datasetSequence != null)
1722 // TODO: could merge DBRefs
1723 return datasetSequence.updatePDBIds();
1725 if (dbrefs == null || dbrefs.size() == 0)
1729 boolean added = false;
1730 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1732 DBRefEntry dbr = dbrefs.get(ib);
1733 if (DBRefSource.PDB.equals(dbr.getSource()))
1736 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1737 * PDB id is not already present in a 'matching' PDBEntry
1738 * Constructor parses out a chain code if appended to the accession id
1739 * (a fudge used to 'store' the chain code in the DBRef)
1741 PDBEntry pdbe = new PDBEntry(dbr);
1742 added |= addPDBId(pdbe);
1749 public void transferAnnotation(SequenceI entry, Mapping mp)
1751 if (datasetSequence != null)
1753 datasetSequence.transferAnnotation(entry, mp);
1756 if (entry.getDatasetSequence() != null)
1758 transferAnnotation(entry.getDatasetSequence(), mp);
1761 // transfer any new features from entry onto sequence
1762 if (entry.getSequenceFeatures() != null)
1765 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1766 for (SequenceFeature feature : sfs)
1768 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1769 : new SequenceFeature[]
1770 { new SequenceFeature(feature) };
1773 for (int sfi = 0; sfi < sf.length; sfi++)
1775 addSequenceFeature(sf[sfi]);
1781 // transfer PDB entries
1782 if (entry.getAllPDBEntries() != null)
1784 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1785 while (e.hasMoreElements())
1787 PDBEntry pdb = e.nextElement();
1791 // transfer database references
1792 List<DBRefEntry> entryRefs = entry.getDBRefs();
1793 if (entryRefs != null)
1795 for (int r = 0, n = entryRefs.size(); r < n; r++)
1797 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1798 if (newref.getMap() != null && mp != null)
1800 // remap ref using our local mapping
1802 // we also assume all version string setting is done by dbSourceProxy
1804 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1805 * newref.setSource(dbSource); }
1813 public void setRNA(RNA r)
1825 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1828 return getAlignmentAnnotations(calcId, label, null, true);
1832 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1833 String label, String description)
1835 return getAlignmentAnnotations(calcId, label, description, false);
1838 private List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1839 String label, String description, boolean ignoreDescription)
1841 List<AlignmentAnnotation> result = new ArrayList<>();
1842 if (this.annotation != null)
1844 for (AlignmentAnnotation ann : annotation)
1846 String id = ann.getCalcId();
1847 if ((id != null && id.equals(calcId))
1848 && (ann.label != null && ann.label.equals(label))
1849 && ((ignoreDescription && description == null)
1850 || (ann.description != null
1851 && ann.description.equals(description))))
1861 public String toString()
1863 return getDisplayId(false);
1867 public PDBEntry getPDBEntry(String pdbIdStr)
1869 if (getDatasetSequence() != null)
1871 return getDatasetSequence().getPDBEntry(pdbIdStr);
1877 List<PDBEntry> entries = getAllPDBEntries();
1878 for (PDBEntry entry : entries)
1880 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1888 private List<DBRefEntry> tmpList;
1891 public List<DBRefEntry> getPrimaryDBRefs()
1893 if (datasetSequence != null)
1895 return datasetSequence.getPrimaryDBRefs();
1897 if (dbrefs == null || dbrefs.size() == 0)
1899 return Collections.emptyList();
1901 synchronized (dbrefs)
1903 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1905 return primaryRefs; // no changes
1907 refModCount = dbrefs.getModCount();
1908 List<DBRefEntry> primaries = (primaryRefs == null
1909 ? (primaryRefs = new ArrayList<>())
1912 if (tmpList == null)
1914 tmpList = new ArrayList<>();
1915 tmpList.add(null); // for replacement
1917 for (int i = 0, n = dbrefs.size(); i < n; i++)
1919 DBRefEntry ref = dbrefs.get(i);
1920 if (!ref.isPrimaryCandidate())
1926 MapList mp = ref.getMap().getMap();
1927 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1929 // map only involves a subsequence, so cannot be primary
1933 // whilst it looks like it is a primary ref, we also sanity check type
1934 if (DBRefSource.PDB_CANONICAL_NAME
1935 .equals(ref.getCanonicalSourceName()))
1937 // PDB dbrefs imply there should be a PDBEntry associated
1938 // TODO: tighten PDB dbrefs
1939 // formally imply Jalview has actually downloaded and
1940 // parsed the pdb file. That means there should be a cached file
1941 // handle on the PDBEntry, and a real mapping between sequence and
1942 // extracted sequence from PDB file
1943 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1944 if (pdbentry == null || pdbentry.getFile() == null)
1951 // check standard protein or dna sources
1952 tmpList.set(0, ref);
1953 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1955 if (res == null || res.get(0) != tmpList.get(0))
1963 // version must be not null, as otherwise it will not be a candidate,
1965 DBRefUtils.ensurePrimaries(this, primaries);
1971 public HiddenMarkovModel getHMM()
1977 public void setHMM(HiddenMarkovModel hmm)
1983 public boolean hasHMMAnnotation()
1985 if (this.annotation == null) {
1988 for (AlignmentAnnotation ann : annotation)
1990 if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
2001 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
2004 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
2005 int endPos = fromColumn == toColumn ? startPos
2006 : findPosition(toColumn - 1);
2008 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
2012 * if end column is gapped, endPos may be to the right,
2013 * and we may have included adjacent or enclosing features;
2014 * remove any that are not enclosing, non-contact features
2016 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
2017 && Comparison.isGap(sequence[toColumn - 1]);
2018 if (endPos > this.end || endColumnIsGapped)
2020 ListIterator<SequenceFeature> it = result.listIterator();
2021 while (it.hasNext())
2023 SequenceFeature sf = it.next();
2024 int sfBegin = sf.getBegin();
2025 int sfEnd = sf.getEnd();
2026 int featureStartColumn = findIndex(sfBegin);
2027 if (featureStartColumn > toColumn)
2031 else if (featureStartColumn < fromColumn)
2033 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2035 if (featureEndColumn < fromColumn)
2039 else if (featureEndColumn > toColumn && sf.isContactFeature())
2042 * remove an enclosing feature if it is a contact feature
2054 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2055 * token that has to match the one presented by the cursor
2058 public void sequenceChanged()
2067 public int replace(char c1, char c2)
2074 synchronized (sequence)
2076 for (int c = 0; c < sequence.length; c++)
2078 if (sequence[c] == c1)
2094 public String getSequenceStringFromIterator(Iterator<int[]> it)
2096 StringBuilder newSequence = new StringBuilder();
2097 while (it.hasNext())
2099 int[] block = it.next();
2102 newSequence.append(getSequence(block[0], block[1] + 1));
2106 newSequence.append(getSequence(block[0], block[1]));
2110 return newSequence.toString();
2114 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2118 if (!regions.hasNext())
2120 return findIndex(getStart()) - 1;
2123 // Simply walk along the sequence whilst watching for region
2125 int hideStart = getLength();
2127 boolean foundStart = false;
2129 // step through the non-gapped positions of the sequence
2130 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2132 // get alignment position of this residue in the sequence
2133 int p = findIndex(i) - 1;
2135 // update region start/end
2136 while (hideEnd < p && regions.hasNext())
2138 int[] region = regions.next();
2139 hideStart = region[0];
2140 hideEnd = region[1];
2144 hideStart = getLength();
2146 // update boundary for sequence
2158 // otherwise, sequence was completely hidden
2163 public boolean hasHMMProfile()