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 java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.BitSet;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.Enumeration;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.ListIterator;
32 import java.util.Vector;
34 import fr.orsay.lri.varna.models.rna.RNA;
35 import jalview.analysis.AlignSeq;
36 import jalview.datamodel.features.SequenceFeatures;
37 import jalview.datamodel.features.SequenceFeaturesI;
38 import jalview.util.Comparison;
39 import jalview.util.DBRefUtils;
40 import jalview.util.MapList;
41 import jalview.util.StringUtils;
42 import jalview.ws.datamodel.alphafold.MappableContactMatrix;
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 private DBModList<DBRefEntry> dbrefs; // controlled access
89 * a flag to let us know that elements have changed in dbrefs
93 private int refModCount = 0;
98 * This annotation is displayed below the alignment but the positions are tied
99 * to the residues of this sequence
101 * TODO: change to List<>
103 private Vector<AlignmentAnnotation> annotation;
105 private SequenceFeaturesI sequenceFeatureStore;
108 * A cursor holding the approximate current view position to the sequence,
109 * as determined by findIndex or findPosition or findPositions.
110 * Using a cursor as a hint allows these methods to be more performant for
113 private SequenceCursor cursor;
116 * A number that should be incremented whenever the sequence is edited.
117 * If the value matches the cursor token, then we can trust the cursor,
118 * if not then it should be recomputed.
120 private int changeCount;
123 * Creates a new Sequence object.
126 * display name string
128 * string to form a possibly gapped sequence out of
130 * first position of non-gap residue in the sequence
132 * last position of ungapped residues (nearly always only used for
135 public Sequence(String name, String sequence, int start, int end)
138 initSeqAndName(name, sequence.toCharArray(), start, end);
141 public Sequence(String name, char[] sequence, int start, int end)
144 initSeqAndName(name, sequence, start, end);
148 * Stage 1 constructor - assign name, sequence, and set start and end fields.
149 * start and end are updated values from name2 if it ends with /start-end
156 protected void initSeqAndName(String name2, char[] sequence2, int start2,
160 this.sequence = sequence2;
168 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
169 * start and end respectively and removes the suffix from the name
176 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
179 int slashPos = name.lastIndexOf('/');
180 if (slashPos > -1 && slashPos < name.length() - 1)
182 String suffix = name.substring(slashPos + 1);
183 String[] range = suffix.split("-");
184 if (range.length == 2)
188 int from = Integer.valueOf(range[0]);
189 int to = Integer.valueOf(range[1]);
190 if (from > 0 && to >= from)
192 name = name.substring(0, slashPos);
197 } catch (NumberFormatException e)
199 // leave name unchanged if suffix is invalid
206 * Ensures that 'end' is not before the end of the sequence, that is,
207 * (end-start+1) is at least as long as the count of ungapped positions. Note
208 * that end is permitted to be beyond the end of the sequence data.
210 void checkValidRange()
213 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
216 for (int j = 0; j < sequence.length; j++)
218 if (!Comparison.isGap(sequence[j]))
237 * default constructor
241 sequenceFeatureStore = new SequenceFeatures();
245 * Creates a new Sequence object.
252 public Sequence(String name, String sequence)
254 this(name, sequence, 1, -1);
258 * Creates a new Sequence object with new AlignmentAnnotations but inherits
259 * any existing dataset sequence reference. If non exists, everything is
263 * if seq is a dataset sequence, behaves like a plain old copy
266 public Sequence(SequenceI seq)
268 this(seq, seq.getAnnotation());
272 * Create a new sequence object with new features, DBRefEntries, and PDBIds
273 * but inherits any existing dataset sequence reference, and duplicate of any
274 * annotation that is present in the given annotation array.
277 * the sequence to be copied
278 * @param alAnnotation
279 * an array of annotation including some associated with seq
281 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
284 initSeqFrom(seq, alAnnotation);
288 * does the heavy lifting when cloning a dataset sequence, or coping data from
289 * dataset to a new derived sequence.
292 * - source of attributes.
293 * @param alAnnotation
294 * - alignment annotation present on seq that should be copied onto
297 protected void initSeqFrom(SequenceI seq,
298 AlignmentAnnotation[] alAnnotation)
300 char[] oseq = seq.getSequence(); // returns a copy of the array
301 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
303 description = seq.getDescription();
304 if (seq != datasetSequence)
306 setDatasetSequence(seq.getDatasetSequence());
310 * only copy DBRefs and seqfeatures if we really are a dataset sequence
312 if (datasetSequence == null)
314 List<DBRefEntry> dbr = seq.getDBRefs();
317 for (int i = 0, n = dbr.size(); i < n; i++)
319 addDBRef(new DBRefEntry(dbr.get(i)));
324 * make copies of any sequence features
326 for (SequenceFeature sf : seq.getSequenceFeatures())
328 addSequenceFeature(new SequenceFeature(sf));
332 if (seq.getAnnotation() != null)
334 AlignmentAnnotation[] sqann = seq.getAnnotation();
335 for (int i = 0; i < sqann.length; i++)
337 if (sqann[i] == null)
341 boolean found = (alAnnotation == null);
344 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
346 found = (alAnnotation[apos] == sqann[i]);
351 // only copy the given annotation
352 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
353 addAlignmentAnnotation(newann);
357 if (seq.getAllPDBEntries() != null)
359 Vector<PDBEntry> ids = seq.getAllPDBEntries();
360 for (PDBEntry pdb : ids)
362 this.addPDBId(new PDBEntry(pdb));
368 public void setSequenceFeatures(List<SequenceFeature> features)
370 if (datasetSequence != null)
372 datasetSequence.setSequenceFeatures(features);
375 sequenceFeatureStore = new SequenceFeatures(features);
379 public synchronized boolean addSequenceFeature(SequenceFeature sf)
381 if (sf.getType() == null)
384 "SequenceFeature type may not be null: " + sf.toString());
388 if (datasetSequence != null)
390 return datasetSequence.addSequenceFeature(sf);
393 return sequenceFeatureStore.add(sf);
397 public void deleteFeature(SequenceFeature sf)
399 if (datasetSequence != null)
401 datasetSequence.deleteFeature(sf);
405 sequenceFeatureStore.delete(sf);
415 public List<SequenceFeature> getSequenceFeatures()
417 if (datasetSequence != null)
419 return datasetSequence.getSequenceFeatures();
421 return sequenceFeatureStore.getAllFeatures();
425 public SequenceFeaturesI getFeatures()
427 return datasetSequence != null ? datasetSequence.getFeatures()
428 : sequenceFeatureStore;
432 public boolean addPDBId(PDBEntry entry)
436 pdbIds = new Vector<>();
441 for (PDBEntry pdbe : pdbIds)
443 if (pdbe.updateFrom(entry))
448 pdbIds.addElement(entry);
459 public void setPDBId(Vector<PDBEntry> id)
467 * @return DOCUMENT ME!
470 public Vector<PDBEntry> getAllPDBEntries()
472 return pdbIds == null ? new Vector<>() : pdbIds;
476 * Answers the sequence name, with '/start-end' appended if jvsuffix is true
481 public String getDisplayId(boolean jvsuffix)
487 StringBuilder result = new StringBuilder(name);
488 result.append("/").append(start).append("-").append(end);
490 return result.toString();
494 * Sets the sequence name. If the name ends in /start-end, then the start-end
495 * values are parsed out and set, and the suffix is removed from the name.
500 public void setName(String theName)
509 * @return DOCUMENT ME!
512 public String getName()
524 public void setStart(int start)
533 * @return DOCUMENT ME!
536 public int getStart()
548 public void setEnd(int end)
556 * @return DOCUMENT ME!
567 * @return DOCUMENT ME!
570 public int getLength()
572 return this.sequence.length;
582 public void setSequence(String seq)
584 this.sequence = seq.toCharArray();
590 public String getSequenceAsString()
592 return new String(sequence);
596 public String getSequenceAsString(int start, int end)
598 return new String(getSequence(start, end));
602 public char[] getSequence()
605 return sequence == null ? null
606 : Arrays.copyOf(sequence, sequence.length);
612 * @see jalview.datamodel.SequenceI#getSequence(int, int)
615 public char[] getSequence(int start, int end)
621 // JBPNote - left to user to pad the result here (TODO:Decide on this
623 if (start >= sequence.length)
628 if (end >= sequence.length)
630 end = sequence.length;
633 char[] reply = new char[end - start];
634 System.arraycopy(sequence, start, reply, 0, end - start);
640 public SequenceI getSubSequence(int start, int end)
646 char[] seq = getSequence(start, end);
651 int nstart = findPosition(start);
652 int nend = findPosition(end) - 1;
653 // JBPNote - this is an incomplete copy.
654 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
655 nseq.setDescription(description);
656 if (datasetSequence != null)
658 nseq.setDatasetSequence(datasetSequence);
662 nseq.setDatasetSequence(this);
668 * Returns the character of the aligned sequence at the given position (base
669 * zero), or space if the position is not within the sequence's bounds
674 public char getCharAt(int i)
676 if (i >= 0 && i < sequence.length)
687 * Sets the sequence description, and also parses out any special formats of
693 public void setDescription(String desc)
695 this.description = desc;
699 public void setGeneLoci(String speciesId, String assemblyId,
700 String chromosomeId, MapList map)
702 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
707 * Returns the gene loci mapping for the sequence (may be null)
712 public GeneLociI getGeneLoci()
714 List<DBRefEntry> refs = getDBRefs();
717 for (final DBRefEntry ref : refs)
719 if (ref instanceof GeneLociI)
721 return (GeneLociI) ref;
729 * Answers the description
734 public String getDescription()
736 return this.description;
743 public int findIndex(int pos)
746 * use a valid, hopefully nearby, cursor if available
748 if (isValidCursor(cursor))
750 return findIndex(pos, cursor);
758 * traverse sequence from the start counting gaps; make a note of
759 * the column of the first residue to save in the cursor
761 while ((i < sequence.length) && (j <= end) && (j <= pos))
763 if (!Comparison.isGap(sequence[i]))
774 if (j == end && j < pos)
779 updateCursor(pos, i, startColumn);
784 * Updates the cursor to the latest found residue and column position
791 * column position of the first sequence residue
793 protected void updateCursor(int residuePos, int column, int startColumn)
796 * preserve end residue column provided cursor was valid
798 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
800 if (residuePos == this.end)
805 cursor = new SequenceCursor(this, residuePos, column, startColumn,
806 endColumn, this.changeCount);
810 * Answers the aligned column position (1..) for the given residue position
811 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
812 * The hint may be left of, at, or to the right of the required position.
818 protected int findIndex(final int pos, SequenceCursor curs)
820 if (!isValidCursor(curs))
823 * wrong or invalidated cursor, compute de novo
825 return findIndex(pos);
828 if (curs.residuePosition == pos)
830 return curs.columnPosition;
834 * move left or right to find pos from hint.position
836 int col = curs.columnPosition - 1; // convert from base 1 to base 0
837 int newPos = curs.residuePosition;
838 int delta = newPos > pos ? -1 : 1;
840 while (newPos != pos)
842 col += delta; // shift one column left or right
847 if (col == sequence.length)
849 col--; // return last column if we failed to reach pos
852 if (!Comparison.isGap(sequence[col]))
858 col++; // convert back to base 1
861 * only update cursor if we found the target position
865 updateCursor(pos, col, curs.firstColumnPosition);
875 public int findPosition(final int column)
878 * use a valid, hopefully nearby, cursor if available
880 if (isValidCursor(cursor))
882 return findPosition(column + 1, cursor);
885 // TODO recode this more naturally i.e. count residues only
886 // as they are found, not 'in anticipation'
889 * traverse the sequence counting gaps; note the column position
890 * of the first residue, to save in the cursor
892 int firstResidueColumn = 0;
893 int lastPosFound = 0;
894 int lastPosFoundColumn = 0;
895 int seqlen = sequence.length;
897 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
899 lastPosFound = start;
900 lastPosFoundColumn = 0;
906 while (j < column && j < seqlen)
908 if (!Comparison.isGap(sequence[j]))
911 lastPosFoundColumn = j;
912 if (pos == this.start)
914 firstResidueColumn = j;
920 if (j < seqlen && !Comparison.isGap(sequence[j]))
923 lastPosFoundColumn = j;
924 if (pos == this.start)
926 firstResidueColumn = j;
931 * update the cursor to the last residue position found (if any)
932 * (converting column position to base 1)
934 if (lastPosFound != 0)
936 updateCursor(lastPosFound, lastPosFoundColumn + 1,
937 firstResidueColumn + 1);
944 * Answers true if the given cursor is not null, is for this sequence object,
945 * and has a token value that matches this object's changeCount, else false.
946 * This allows us to ignore a cursor as 'stale' if the sequence has been
947 * modified since the cursor was created.
952 protected boolean isValidCursor(SequenceCursor curs)
954 if (curs == null || curs.sequence != this || curs.token != changeCount)
959 * sanity check against range
961 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
965 if (curs.residuePosition < start || curs.residuePosition > end)
973 * Answers the sequence position (start..) for the given aligned column
974 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
975 * may lie left of, at, or to the right of the column position.
981 protected int findPosition(final int col, SequenceCursor curs)
983 if (!isValidCursor(curs))
986 * wrong or invalidated cursor, compute de novo
988 return findPosition(col - 1);// ugh back to base 0
991 if (curs.columnPosition == col)
993 cursor = curs; // in case this method becomes public
994 return curs.residuePosition; // easy case :-)
997 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1000 * sequence lies entirely to the left of col
1001 * - return last residue + 1
1006 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1009 * sequence lies entirely to the right of col
1010 * - return first residue
1015 // todo could choose closest to col out of column,
1016 // firstColumnPosition, lastColumnPosition as a start point
1019 * move left or right to find pos from cursor position
1021 int firstResidueColumn = curs.firstColumnPosition;
1022 int column = curs.columnPosition - 1; // to base 0
1023 int newPos = curs.residuePosition;
1024 int delta = curs.columnPosition > col ? -1 : 1;
1025 boolean gapped = false;
1026 int lastFoundPosition = curs.residuePosition;
1027 int lastFoundPositionColumn = curs.columnPosition;
1029 while (column != col - 1)
1031 column += delta; // shift one column left or right
1032 if (column < 0 || column == sequence.length)
1036 gapped = Comparison.isGap(sequence[column]);
1040 lastFoundPosition = newPos;
1041 lastFoundPositionColumn = column + 1;
1042 if (lastFoundPosition == this.start)
1044 firstResidueColumn = column + 1;
1049 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1051 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1052 firstResidueColumn);
1056 * hack to give position to the right if on a gap
1057 * or beyond the length of the sequence (see JAL-2562)
1059 if (delta > 0 && (gapped || column >= sequence.length))
1071 public ContiguousI findPositions(int fromColumn, int toColumn)
1073 if (toColumn < fromColumn || fromColumn < 1)
1079 * find the first non-gapped position, if any
1081 int firstPosition = 0;
1082 int col = fromColumn - 1;
1083 int length = sequence.length;
1084 while (col < length && col < toColumn)
1086 if (!Comparison.isGap(sequence[col]))
1088 firstPosition = findPosition(col++);
1094 if (firstPosition == 0)
1100 * find the last non-gapped position
1102 int lastPosition = firstPosition;
1103 while (col < length && col < toColumn)
1105 if (!Comparison.isGap(sequence[col++]))
1111 return new Range(firstPosition, lastPosition);
1115 * Returns an int array where indices correspond to each residue in the
1116 * sequence and the element value gives its position in the alignment
1118 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1119 * residues in SequenceI object
1122 public int[] gapMap()
1124 String seq = jalview.analysis.AlignSeq.extractGaps(
1125 jalview.util.Comparison.GapChars, new String(sequence));
1126 int[] map = new int[seq.length()];
1130 while (j < sequence.length)
1132 if (!jalview.util.Comparison.isGap(sequence[j]))
1144 * Build a bitset corresponding to sequence gaps
1146 * @return a BitSet where set values correspond to gaps in the sequence
1149 public BitSet gapBitset()
1151 BitSet gaps = new BitSet(sequence.length);
1153 while (j < sequence.length)
1155 if (jalview.util.Comparison.isGap(sequence[j]))
1165 public int[] findPositionMap()
1167 int map[] = new int[sequence.length];
1170 int seqlen = sequence.length;
1171 while ((j < seqlen))
1174 if (!jalview.util.Comparison.isGap(sequence[j]))
1185 public List<int[]> getInsertions()
1187 ArrayList<int[]> map = new ArrayList<>();
1188 int lastj = -1, j = 0;
1190 int seqlen = sequence.length;
1191 while ((j < seqlen))
1193 if (jalview.util.Comparison.isGap(sequence[j]))
1204 map.add(new int[] { lastj, j - 1 });
1212 map.add(new int[] { lastj, j - 1 });
1219 public BitSet getInsertionsAsBits()
1221 BitSet map = new BitSet();
1222 int lastj = -1, j = 0;
1224 int seqlen = sequence.length;
1225 while ((j < seqlen))
1227 if (jalview.util.Comparison.isGap(sequence[j]))
1253 public void deleteChars(final int i, final int j)
1255 int newstart = start, newend = end;
1256 if (i >= sequence.length || i < 0)
1261 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1262 boolean createNewDs = false;
1263 // TODO: take a (second look) at the dataset creation validation method for
1264 // the very large sequence case
1266 int startIndex = findIndex(start) - 1;
1267 int endIndex = findIndex(end) - 1;
1268 int startDeleteColumn = -1; // for dataset sequence deletions
1269 int deleteCount = 0;
1271 for (int s = i; s < j && s < sequence.length; s++)
1273 if (Comparison.isGap(sequence[s]))
1278 if (startDeleteColumn == -1)
1280 startDeleteColumn = findPosition(s) - start;
1288 if (startIndex == s)
1291 * deleting characters from start of sequence; new start is the
1292 * sequence position of the next column (position to the right
1293 * if the column position is gapped)
1295 newstart = findPosition(j);
1303 * deleting characters at end of sequence; new end is the sequence
1304 * position of the column before the deletion; subtract 1 if this is
1305 * gapped since findPosition returns the next sequence position
1307 newend = findPosition(i - 1);
1308 if (Comparison.isGap(sequence[i - 1]))
1323 if (createNewDs && this.datasetSequence != null)
1326 * if deletion occured in the middle of the sequence,
1327 * construct a new dataset sequence and delete the residues
1328 * that were deleted from the aligned sequence
1330 Sequence ds = new Sequence(datasetSequence);
1331 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1332 datasetSequence = ds;
1333 // TODO: remove any non-inheritable properties ?
1334 // TODO: create a sequence mapping (since there is a relation here ?)
1343 public void insertCharAt(int i, int length, char c)
1345 char[] tmp = new char[sequence.length + length];
1347 if (i >= sequence.length)
1349 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1350 i = sequence.length;
1354 System.arraycopy(sequence, 0, tmp, 0, i);
1364 if (i < sequence.length)
1366 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1374 public void insertCharAt(int i, char c)
1376 insertCharAt(i, 1, c);
1380 public String getVamsasId()
1386 public void setVamsasId(String id)
1393 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1395 if (dbrefs == null && datasetSequence != null
1396 && this != datasetSequence)
1398 datasetSequence.setDBRefs(newDBrefs);
1406 public DBModList<DBRefEntry> getDBRefs()
1408 if (dbrefs == null && datasetSequence != null
1409 && this != datasetSequence)
1411 return datasetSequence.getDBRefs();
1417 public void addDBRef(DBRefEntry entry)
1419 // TODO JAL-3980 maintain as sorted list
1420 if (datasetSequence != null)
1422 datasetSequence.addDBRef(entry);
1428 dbrefs = new DBModList<>();
1430 // TODO JAL-3979 LOOK UP RATHER THAN SWEEP FOR EFFICIENCY
1432 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1434 if (dbrefs.get(ib).updateFrom(entry))
1437 * found a dbref that either matched, or could be
1438 * updated from, the new entry - no need to add it
1446 // * extend the array to make room for one more
1448 // // TODO use an ArrayList instead
1449 // int j = dbrefs.length;
1450 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1451 // System.arraycopy(dbrefs, 0, temp, 0, j);
1452 // temp[temp.length - 1] = entry;
1460 public void setDatasetSequence(SequenceI seq)
1464 throw new IllegalArgumentException(
1465 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1467 if (seq != null && seq.getDatasetSequence() != null)
1469 throw new IllegalArgumentException(
1470 "Implementation error: cascading dataset sequences are not allowed.");
1472 datasetSequence = seq;
1476 public SequenceI getDatasetSequence()
1478 return datasetSequence;
1482 public AlignmentAnnotation[] getAnnotation()
1484 return annotation == null ? null
1486 .toArray(new AlignmentAnnotation[annotation.size()]);
1490 public boolean hasAnnotation(AlignmentAnnotation ann)
1492 return annotation == null ? false : annotation.contains(ann);
1496 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1498 if (this.annotation == null)
1500 this.annotation = new Vector<>();
1502 if (!this.annotation.contains(annotation))
1504 this.annotation.addElement(annotation);
1506 annotation.setSequenceRef(this);
1510 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1512 if (this.annotation != null)
1514 this.annotation.removeElement(annotation);
1515 if (this.annotation.size() == 0)
1517 this.annotation = null;
1523 * test if this is a valid candidate for another sequence's dataset sequence.
1526 private boolean isValidDatasetSequence()
1528 if (datasetSequence != null)
1532 for (int i = 0; i < sequence.length; i++)
1534 if (jalview.util.Comparison.isGap(sequence[i]))
1543 public SequenceI deriveSequence()
1545 Sequence seq = null;
1546 if (datasetSequence == null)
1548 if (isValidDatasetSequence())
1550 // Use this as dataset sequence
1551 seq = new Sequence(getName(), "", 1, -1);
1552 seq.setDatasetSequence(this);
1553 seq.initSeqFrom(this, getAnnotation());
1558 // Create a new, valid dataset sequence
1559 createDatasetSequence();
1562 return new Sequence(this);
1565 private boolean _isNa;
1567 private int _seqhash = 0;
1569 private List<DBRefEntry> primaryRefs;
1572 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1576 public boolean isProtein()
1578 if (datasetSequence != null)
1580 return datasetSequence.isProtein();
1582 if (_seqhash != sequence.hashCode())
1584 _seqhash = sequence.hashCode();
1585 _isNa = Comparison.isNucleotide(this);
1593 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1596 public SequenceI createDatasetSequence()
1598 if (datasetSequence == null)
1600 Sequence dsseq = new Sequence(getName(),
1601 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1602 getSequenceAsString()),
1603 getStart(), getEnd());
1605 datasetSequence = dsseq;
1607 dsseq.setDescription(description);
1608 // move features and database references onto dataset sequence
1609 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1610 sequenceFeatureStore = null;
1611 dsseq.dbrefs = dbrefs;
1613 // TODO: search and replace any references to this sequence with
1614 // references to the dataset sequence in Mappings on dbref
1615 dsseq.pdbIds = pdbIds;
1617 datasetSequence.updatePDBIds();
1618 if (annotation != null)
1620 // annotation is cloned rather than moved, to preserve what's currently
1622 for (AlignmentAnnotation aa : annotation)
1624 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1625 _aa.sequenceRef = datasetSequence;
1626 _aa.adjustForAlignment(); // uses annotation's own record of
1627 // sequence-column mapping
1628 datasetSequence.addAlignmentAnnotation(_aa);
1630 // transfer contact matrices
1631 ContactMatrixI cm = getContactMatrixFor(aa);
1634 datasetSequence.addContactListFor(_aa, cm);
1639 return datasetSequence;
1646 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1650 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1652 if (annotation != null)
1654 annotation.removeAllElements();
1656 if (annotations != null)
1658 for (int i = 0; i < annotations.length; i++)
1660 if (annotations[i] != null)
1662 addAlignmentAnnotation(annotations[i]);
1669 public AlignmentAnnotation[] getAnnotation(String label)
1671 if (annotation == null || annotation.size() == 0)
1676 Vector<AlignmentAnnotation> subset = new Vector<>();
1677 Enumeration<AlignmentAnnotation> e = annotation.elements();
1678 while (e.hasMoreElements())
1680 AlignmentAnnotation ann = e.nextElement();
1681 if (ann.label != null && ann.label.equals(label))
1683 subset.addElement(ann);
1686 if (subset.size() == 0)
1690 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1692 e = subset.elements();
1693 while (e.hasMoreElements())
1695 anns[i++] = e.nextElement();
1697 subset.removeAllElements();
1702 public boolean updatePDBIds()
1704 if (datasetSequence != null)
1706 // TODO: could merge DBRefs
1707 return datasetSequence.updatePDBIds();
1709 if (dbrefs == null || dbrefs.size() == 0)
1713 boolean added = false;
1714 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1716 DBRefEntry dbr = dbrefs.get(ib);
1717 if (DBRefSource.PDB.equals(dbr.getSource()))
1720 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1721 * PDB id is not already present in a 'matching' PDBEntry
1722 * Constructor parses out a chain code if appended to the accession id
1723 * (a fudge used to 'store' the chain code in the DBRef)
1725 PDBEntry pdbe = new PDBEntry(dbr);
1726 added |= addPDBId(pdbe);
1733 public void transferAnnotation(SequenceI entry, Mapping mp)
1735 if (datasetSequence != null)
1737 datasetSequence.transferAnnotation(entry, mp);
1740 if (entry.getDatasetSequence() != null)
1742 transferAnnotation(entry.getDatasetSequence(), mp);
1745 // transfer any new features from entry onto sequence
1746 if (entry.getSequenceFeatures() != null)
1749 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1750 for (SequenceFeature feature : sfs)
1752 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1753 : new SequenceFeature[]
1754 { new SequenceFeature(feature) };
1757 for (int sfi = 0; sfi < sf.length; sfi++)
1759 addSequenceFeature(sf[sfi]);
1765 // transfer PDB entries
1766 if (entry.getAllPDBEntries() != null)
1768 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1769 while (e.hasMoreElements())
1771 PDBEntry pdb = e.nextElement();
1775 // transfer database references
1776 List<DBRefEntry> entryRefs = entry.getDBRefs();
1777 if (entryRefs != null)
1779 for (int r = 0, n = entryRefs.size(); r < n; r++)
1781 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1782 if (newref.getMap() != null && mp != null)
1784 // remap ref using our local mapping
1786 // we also assume all version string setting is done by dbSourceProxy
1788 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1789 * newref.setSource(dbSource); }
1797 public void setRNA(RNA r)
1809 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1812 return getAlignmentAnnotations(calcId, label, null, true);
1816 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1817 String label, String description)
1819 return getAlignmentAnnotations(calcId, label, description, false);
1822 private List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1823 String label, String description, boolean ignoreDescription)
1825 List<AlignmentAnnotation> result = new ArrayList<>();
1826 if (this.annotation != null)
1828 for (AlignmentAnnotation ann : annotation)
1830 if ((ann.calcId != null && ann.calcId.equals(calcId))
1831 && (ann.label != null && ann.label.equals(label))
1832 && ((ignoreDescription && description == null)
1833 || (ann.description != null
1834 && ann.description.equals(description))))
1845 public String toString()
1847 return getDisplayId(false);
1851 public PDBEntry getPDBEntry(String pdbIdStr)
1853 if (getDatasetSequence() != null)
1855 return getDatasetSequence().getPDBEntry(pdbIdStr);
1861 List<PDBEntry> entries = getAllPDBEntries();
1862 for (PDBEntry entry : entries)
1864 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1872 private List<DBRefEntry> tmpList;
1875 public List<DBRefEntry> getPrimaryDBRefs()
1877 if (datasetSequence != null)
1879 return datasetSequence.getPrimaryDBRefs();
1881 if (dbrefs == null || dbrefs.size() == 0)
1883 return Collections.emptyList();
1885 synchronized (dbrefs)
1887 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1889 return primaryRefs; // no changes
1891 refModCount = dbrefs.getModCount();
1892 List<DBRefEntry> primaries = (primaryRefs == null
1893 ? (primaryRefs = new ArrayList<>())
1896 if (tmpList == null)
1898 tmpList = new ArrayList<>();
1899 tmpList.add(null); // for replacement
1901 for (int i = 0, n = dbrefs.size(); i < n; i++)
1903 DBRefEntry ref = dbrefs.get(i);
1904 if (!ref.isPrimaryCandidate())
1910 MapList mp = ref.getMap().getMap();
1911 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1913 // map only involves a subsequence, so cannot be primary
1917 // whilst it looks like it is a primary ref, we also sanity check type
1918 if (DBRefSource.PDB_CANONICAL_NAME
1919 .equals(ref.getCanonicalSourceName()))
1921 // PDB dbrefs imply there should be a PDBEntry associated
1922 // TODO: tighten PDB dbrefs
1923 // formally imply Jalview has actually downloaded and
1924 // parsed the pdb file. That means there should be a cached file
1925 // handle on the PDBEntry, and a real mapping between sequence and
1926 // extracted sequence from PDB file
1927 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1928 if (pdbentry == null || pdbentry.getFile() == null)
1935 // check standard protein or dna sources
1936 tmpList.set(0, ref);
1937 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1939 if (res == null || res.get(0) != tmpList.get(0))
1947 // version must be not null, as otherwise it will not be a candidate,
1949 DBRefUtils.ensurePrimaries(this, primaries);
1958 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1961 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1962 int endPos = fromColumn == toColumn ? startPos
1963 : findPosition(toColumn - 1);
1965 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1969 * if end column is gapped, endPos may be to the right,
1970 * and we may have included adjacent or enclosing features;
1971 * remove any that are not enclosing, non-contact features
1973 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1974 && Comparison.isGap(sequence[toColumn - 1]);
1975 if (endPos > this.end || endColumnIsGapped)
1977 ListIterator<SequenceFeature> it = result.listIterator();
1978 while (it.hasNext())
1980 SequenceFeature sf = it.next();
1981 int sfBegin = sf.getBegin();
1982 int sfEnd = sf.getEnd();
1983 int featureStartColumn = findIndex(sfBegin);
1984 if (featureStartColumn > toColumn)
1988 else if (featureStartColumn < fromColumn)
1990 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1992 if (featureEndColumn < fromColumn)
1996 else if (featureEndColumn > toColumn && sf.isContactFeature())
1999 * remove an enclosing feature if it is a contact feature
2011 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2012 * token that has to match the one presented by the cursor
2015 public void sequenceChanged()
2024 public int replace(char c1, char c2)
2031 synchronized (sequence)
2033 for (int c = 0; c < sequence.length; c++)
2035 if (sequence[c] == c1)
2051 public String getSequenceStringFromIterator(Iterator<int[]> it)
2053 StringBuilder newSequence = new StringBuilder();
2054 while (it.hasNext())
2056 int[] block = it.next();
2059 newSequence.append(getSequence(block[0], block[1] + 1));
2063 newSequence.append(getSequence(block[0], block[1]));
2067 return newSequence.toString();
2071 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2075 if (!regions.hasNext())
2077 return findIndex(getStart()) - 1;
2080 // Simply walk along the sequence whilst watching for region
2082 int hideStart = getLength();
2084 boolean foundStart = false;
2086 // step through the non-gapped positions of the sequence
2087 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2089 // get alignment position of this residue in the sequence
2090 int p = findIndex(i) - 1;
2092 // update region start/end
2093 while (hideEnd < p && regions.hasNext())
2095 int[] region = regions.next();
2096 hideStart = region[0];
2097 hideEnd = region[1];
2101 hideStart = getLength();
2103 // update boundary for sequence
2115 // otherwise, sequence was completely hidden
2120 //// Contact Matrix Holder Boilerplate
2122 ContactMapHolderI cmholder = new ContactMapHolder();
2125 public Collection<ContactMatrixI> getContactMaps()
2127 return cmholder.getContactMaps();
2131 public ContactMatrixI getContactMatrixFor(AlignmentAnnotation ann)
2133 return cmholder.getContactMatrixFor(ann);
2137 public ContactListI getContactListFor(AlignmentAnnotation _aa, int column)
2139 return cmholder.getContactListFor(_aa, column);
2143 public AlignmentAnnotation addContactList(ContactMatrixI cm)
2145 AlignmentAnnotation aa = cmholder.addContactList(cm);
2147 Annotation _aa[] = new Annotation[getLength()];
2148 Annotation dummy = new Annotation(0.0f);
2149 for (int i = 0; i < _aa.length; _aa[i++] = dummy)
2153 aa.annotations = _aa;
2154 aa.setSequenceRef(this);
2155 if (cm instanceof MappableContactMatrix && !((MappableContactMatrix) cm).hasReferenceSeq())
2157 ((MappableContactMatrix) cm).setRefSeq(this);
2159 aa.createSequenceMapping(this, getStart(), false);
2160 addAlignmentAnnotation(aa);
2165 public void addContactListFor(AlignmentAnnotation annotation,
2168 cmholder.addContactListFor(annotation, cm);