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;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.BitSet;
34 import java.util.Collections;
35 import java.util.Enumeration;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.ListIterator;
39 import java.util.Vector;
41 import fr.orsay.lri.varna.models.rna.RNA;
45 * Implements the SequenceI interface for a char[] based sequence object
47 public class Sequence extends ASequence implements SequenceI
51 * A subclass that gives us access to modCount, which tracks whether there
52 * have been any changes. We use this to update
58 @SuppressWarnings("serial")
59 public class DBModList<T> extends ArrayList<DBRefEntry>
62 protected int getModCount()
69 SequenceI datasetSequence;
73 private char[] sequence;
75 private String description;
81 private Vector<PDBEntry> pdbIds;
83 private String vamsasId;
85 private DBModList<DBRefEntry> dbrefs; // controlled access
88 * a flag to let us know that elements have changed in dbrefs
92 private int refModCount = 0;
97 * This annotation is displayed below the alignment but the positions are tied
98 * to the residues of this sequence
100 * TODO: change to List<>
102 private Vector<AlignmentAnnotation> annotation;
104 private SequenceFeaturesI sequenceFeatureStore;
107 * A cursor holding the approximate current view position to the sequence,
108 * as determined by findIndex or findPosition or findPositions.
109 * Using a cursor as a hint allows these methods to be more performant for
112 private SequenceCursor cursor;
115 * A number that should be incremented whenever the sequence is edited.
116 * If the value matches the cursor token, then we can trust the cursor,
117 * if not then it should be recomputed.
119 private int changeCount;
122 * Creates a new Sequence object.
125 * display name string
127 * string to form a possibly gapped sequence out of
129 * first position of non-gap residue in the sequence
131 * last position of ungapped residues (nearly always only used for
134 public Sequence(String name, String sequence, int start, int end)
137 initSeqAndName(name, sequence.toCharArray(), start, end);
140 public Sequence(String name, char[] sequence, int start, int end)
143 initSeqAndName(name, sequence, start, end);
147 * Stage 1 constructor - assign name, sequence, and set start and end fields.
148 * start and end are updated values from name2 if it ends with /start-end
155 protected void initSeqAndName(String name2, char[] sequence2, int start2,
159 this.sequence = sequence2;
167 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
168 * start and end respectively and removes the suffix from the name
175 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
178 int slashPos = name.lastIndexOf('/');
179 if (slashPos > -1 && slashPos < name.length() - 1)
181 String suffix = name.substring(slashPos + 1);
182 String[] range = suffix.split("-");
183 if (range.length == 2)
187 int from = Integer.valueOf(range[0]);
188 int to = Integer.valueOf(range[1]);
189 if (from > 0 && to >= from)
191 name = name.substring(0, slashPos);
196 } catch (NumberFormatException e)
198 // leave name unchanged if suffix is invalid
205 * Ensures that 'end' is not before the end of the sequence, that is,
206 * (end-start+1) is at least as long as the count of ungapped positions. Note
207 * that end is permitted to be beyond the end of the sequence data.
209 void checkValidRange()
212 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
215 for (int j = 0; j < sequence.length; j++)
217 if (!Comparison.isGap(sequence[j]))
236 * default constructor
240 sequenceFeatureStore = new SequenceFeatures();
244 * Creates a new Sequence object.
251 public Sequence(String name, String sequence)
253 this(name, sequence, 1, -1);
257 * Creates a new Sequence object with new AlignmentAnnotations but inherits
258 * any existing dataset sequence reference. If non exists, everything is
262 * if seq is a dataset sequence, behaves like a plain old copy
265 public Sequence(SequenceI seq)
267 this(seq, seq.getAnnotation());
271 * Create a new sequence object with new features, DBRefEntries, and PDBIds
272 * but inherits any existing dataset sequence reference, and duplicate of any
273 * annotation that is present in the given annotation array.
276 * the sequence to be copied
277 * @param alAnnotation
278 * an array of annotation including some associated with seq
280 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
283 initSeqFrom(seq, alAnnotation);
287 * does the heavy lifting when cloning a dataset sequence, or coping data from
288 * dataset to a new derived sequence.
291 * - source of attributes.
292 * @param alAnnotation
293 * - alignment annotation present on seq that should be copied onto
296 protected void initSeqFrom(SequenceI seq,
297 AlignmentAnnotation[] alAnnotation)
299 char[] oseq = seq.getSequence(); // returns a copy of the array
300 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
302 description = seq.getDescription();
303 if (seq != datasetSequence)
305 setDatasetSequence(seq.getDatasetSequence());
309 * only copy DBRefs and seqfeatures if we really are a dataset sequence
311 if (datasetSequence == null)
313 List<DBRefEntry> dbr = seq.getDBRefs();
316 for (int i = 0, n = dbr.size(); i < n; i++)
318 addDBRef(new DBRefEntry(dbr.get(i)));
323 * make copies of any sequence features
325 for (SequenceFeature sf : seq.getSequenceFeatures())
327 addSequenceFeature(new SequenceFeature(sf));
331 if (seq.getAnnotation() != null)
333 AlignmentAnnotation[] sqann = seq.getAnnotation();
334 for (int i = 0; i < sqann.length; i++)
336 if (sqann[i] == null)
340 boolean found = (alAnnotation == null);
343 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
345 found = (alAnnotation[apos] == sqann[i]);
350 // only copy the given annotation
351 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
352 addAlignmentAnnotation(newann);
356 if (seq.getAllPDBEntries() != null)
358 Vector<PDBEntry> ids = seq.getAllPDBEntries();
359 for (PDBEntry pdb : ids)
361 this.addPDBId(new PDBEntry(pdb));
367 public void setSequenceFeatures(List<SequenceFeature> features)
369 if (datasetSequence != null)
371 datasetSequence.setSequenceFeatures(features);
374 sequenceFeatureStore = new SequenceFeatures(features);
378 public synchronized boolean addSequenceFeature(SequenceFeature sf)
380 if (sf.getType() == null)
383 "SequenceFeature type may not be null: " + sf.toString());
387 if (datasetSequence != null)
389 return datasetSequence.addSequenceFeature(sf);
392 return sequenceFeatureStore.add(sf);
396 public void deleteFeature(SequenceFeature sf)
398 if (datasetSequence != null)
400 datasetSequence.deleteFeature(sf);
404 sequenceFeatureStore.delete(sf);
414 public List<SequenceFeature> getSequenceFeatures()
416 if (datasetSequence != null)
418 return datasetSequence.getSequenceFeatures();
420 return sequenceFeatureStore.getAllFeatures();
424 public SequenceFeaturesI getFeatures()
426 return datasetSequence != null ? datasetSequence.getFeatures()
427 : sequenceFeatureStore;
431 public boolean addPDBId(PDBEntry entry)
435 pdbIds = new Vector<>();
440 for (PDBEntry pdbe : pdbIds)
442 if (pdbe.updateFrom(entry))
447 pdbIds.addElement(entry);
458 public void setPDBId(Vector<PDBEntry> id)
466 * @return DOCUMENT ME!
469 public Vector<PDBEntry> getAllPDBEntries()
471 return pdbIds == null ? new Vector<>() : pdbIds;
477 * @return DOCUMENT ME!
480 public String getDisplayId(boolean jvsuffix)
482 StringBuffer result = new StringBuffer(name);
485 result.append("/" + start + "-" + end);
488 return result.toString();
492 * Sets the sequence name. If the name ends in /start-end, then the start-end
493 * values are parsed out and set, and the suffix is removed from the name.
498 public void setName(String theName)
507 * @return DOCUMENT ME!
510 public String getName()
522 public void setStart(int start)
530 * @return DOCUMENT ME!
533 public int getStart()
545 public void setEnd(int end)
553 * @return DOCUMENT ME!
564 * @return DOCUMENT ME!
567 public int getLength()
569 return this.sequence.length;
579 public void setSequence(String seq)
581 this.sequence = seq.toCharArray();
587 public String getSequenceAsString()
589 return new String(sequence);
593 public String getSequenceAsString(int start, int end)
595 return new String(getSequence(start, end));
599 public char[] getSequence()
602 return sequence == null ? null
603 : Arrays.copyOf(sequence, sequence.length);
609 * @see jalview.datamodel.SequenceI#getSequence(int, int)
612 public char[] getSequence(int start, int end)
618 // JBPNote - left to user to pad the result here (TODO:Decide on this
620 if (start >= sequence.length)
625 if (end >= sequence.length)
627 end = sequence.length;
630 char[] reply = new char[end - start];
631 System.arraycopy(sequence, start, reply, 0, end - start);
637 public SequenceI getSubSequence(int start, int end)
643 char[] seq = getSequence(start, end);
648 int nstart = findPosition(start);
649 int nend = findPosition(end) - 1;
650 // JBPNote - this is an incomplete copy.
651 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
652 nseq.setDescription(description);
653 if (datasetSequence != null)
655 nseq.setDatasetSequence(datasetSequence);
659 nseq.setDatasetSequence(this);
665 * Returns the character of the aligned sequence at the given position (base
666 * zero), or space if the position is not within the sequence's bounds
671 public char getCharAt(int i)
673 if (i >= 0 && i < sequence.length)
684 * Sets the sequence description, and also parses out any special formats of
690 public void setDescription(String desc)
692 this.description = desc;
696 public void setGeneLoci(String speciesId, String assemblyId,
697 String chromosomeId, MapList map)
699 addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
704 * Returns the gene loci mapping for the sequence (may be null)
709 public GeneLociI getGeneLoci()
711 List<DBRefEntry> refs = getDBRefs();
714 for (final DBRefEntry ref : refs)
716 if (ref instanceof GeneLociI)
718 return (GeneLociI) ref;
726 * Answers the description
731 public String getDescription()
733 return this.description;
740 public int findIndex(int pos)
743 * use a valid, hopefully nearby, cursor if available
745 if (isValidCursor(cursor))
747 return findIndex(pos, cursor);
755 * traverse sequence from the start counting gaps; make a note of
756 * the column of the first residue to save in the cursor
758 while ((i < sequence.length) && (j <= end) && (j <= pos))
760 if (!Comparison.isGap(sequence[i]))
771 if (j == end && j < pos)
776 updateCursor(pos, i, startColumn);
781 * Updates the cursor to the latest found residue and column position
788 * column position of the first sequence residue
790 protected void updateCursor(int residuePos, int column, int startColumn)
793 * preserve end residue column provided cursor was valid
795 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
797 if (residuePos == this.end)
802 cursor = new SequenceCursor(this, residuePos, column, startColumn,
803 endColumn, this.changeCount);
807 * Answers the aligned column position (1..) for the given residue position
808 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
809 * The hint may be left of, at, or to the right of the required position.
815 protected int findIndex(final int pos, SequenceCursor curs)
817 if (!isValidCursor(curs))
820 * wrong or invalidated cursor, compute de novo
822 return findIndex(pos);
825 if (curs.residuePosition == pos)
827 return curs.columnPosition;
831 * move left or right to find pos from hint.position
833 int col = curs.columnPosition - 1; // convert from base 1 to base 0
834 int newPos = curs.residuePosition;
835 int delta = newPos > pos ? -1 : 1;
837 while (newPos != pos)
839 col += delta; // shift one column left or right
844 if (col == sequence.length)
846 col--; // return last column if we failed to reach pos
849 if (!Comparison.isGap(sequence[col]))
855 col++; // convert back to base 1
858 * only update cursor if we found the target position
862 updateCursor(pos, col, curs.firstColumnPosition);
872 public int findPosition(final int column)
875 * use a valid, hopefully nearby, cursor if available
877 if (isValidCursor(cursor))
879 return findPosition(column + 1, cursor);
882 // TODO recode this more naturally i.e. count residues only
883 // as they are found, not 'in anticipation'
886 * traverse the sequence counting gaps; note the column position
887 * of the first residue, to save in the cursor
889 int firstResidueColumn = 0;
890 int lastPosFound = 0;
891 int lastPosFoundColumn = 0;
892 int seqlen = sequence.length;
894 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
896 lastPosFound = start;
897 lastPosFoundColumn = 0;
903 while (j < column && j < seqlen)
905 if (!Comparison.isGap(sequence[j]))
908 lastPosFoundColumn = j;
909 if (pos == this.start)
911 firstResidueColumn = j;
917 if (j < seqlen && !Comparison.isGap(sequence[j]))
920 lastPosFoundColumn = j;
921 if (pos == this.start)
923 firstResidueColumn = j;
928 * update the cursor to the last residue position found (if any)
929 * (converting column position to base 1)
931 if (lastPosFound != 0)
933 updateCursor(lastPosFound, lastPosFoundColumn + 1,
934 firstResidueColumn + 1);
941 * Answers true if the given cursor is not null, is for this sequence object,
942 * and has a token value that matches this object's changeCount, else false.
943 * This allows us to ignore a cursor as 'stale' if the sequence has been
944 * modified since the cursor was created.
949 protected boolean isValidCursor(SequenceCursor curs)
951 if (curs == null || curs.sequence != this || curs.token != changeCount)
956 * sanity check against range
958 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
962 if (curs.residuePosition < start || curs.residuePosition > end)
970 * Answers the sequence position (start..) for the given aligned column
971 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
972 * may lie left of, at, or to the right of the column position.
978 protected int findPosition(final int col, SequenceCursor curs)
980 if (!isValidCursor(curs))
983 * wrong or invalidated cursor, compute de novo
985 return findPosition(col - 1);// ugh back to base 0
988 if (curs.columnPosition == col)
990 cursor = curs; // in case this method becomes public
991 return curs.residuePosition; // easy case :-)
994 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
997 * sequence lies entirely to the left of col
998 * - return last residue + 1
1003 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1006 * sequence lies entirely to the right of col
1007 * - return first residue
1012 // todo could choose closest to col out of column,
1013 // firstColumnPosition, lastColumnPosition as a start point
1016 * move left or right to find pos from cursor position
1018 int firstResidueColumn = curs.firstColumnPosition;
1019 int column = curs.columnPosition - 1; // to base 0
1020 int newPos = curs.residuePosition;
1021 int delta = curs.columnPosition > col ? -1 : 1;
1022 boolean gapped = false;
1023 int lastFoundPosition = curs.residuePosition;
1024 int lastFoundPositionColumn = curs.columnPosition;
1026 while (column != col - 1)
1028 column += delta; // shift one column left or right
1029 if (column < 0 || column == sequence.length)
1033 gapped = Comparison.isGap(sequence[column]);
1037 lastFoundPosition = newPos;
1038 lastFoundPositionColumn = column + 1;
1039 if (lastFoundPosition == this.start)
1041 firstResidueColumn = column + 1;
1046 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1048 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1049 firstResidueColumn);
1053 * hack to give position to the right if on a gap
1054 * or beyond the length of the sequence (see JAL-2562)
1056 if (delta > 0 && (gapped || column >= sequence.length))
1068 public ContiguousI findPositions(int fromColumn, int toColumn)
1070 if (toColumn < fromColumn || fromColumn < 1)
1076 * find the first non-gapped position, if any
1078 int firstPosition = 0;
1079 int col = fromColumn - 1;
1080 int length = sequence.length;
1081 while (col < length && col < toColumn)
1083 if (!Comparison.isGap(sequence[col]))
1085 firstPosition = findPosition(col++);
1091 if (firstPosition == 0)
1097 * find the last non-gapped position
1099 int lastPosition = firstPosition;
1100 while (col < length && col < toColumn)
1102 if (!Comparison.isGap(sequence[col++]))
1108 return new Range(firstPosition, lastPosition);
1112 * Returns an int array where indices correspond to each residue in the
1113 * sequence and the element value gives its position in the alignment
1115 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1116 * residues in SequenceI object
1119 public int[] gapMap()
1121 String seq = jalview.analysis.AlignSeq.extractGaps(
1122 jalview.util.Comparison.GapChars, new String(sequence));
1123 int[] map = new int[seq.length()];
1127 while (j < sequence.length)
1129 if (!jalview.util.Comparison.isGap(sequence[j]))
1141 * Build a bitset corresponding to sequence gaps
1143 * @return a BitSet where set values correspond to gaps in the sequence
1146 public BitSet gapBitset()
1148 BitSet gaps = new BitSet(sequence.length);
1150 while (j < sequence.length)
1152 if (jalview.util.Comparison.isGap(sequence[j]))
1162 public int[] findPositionMap()
1164 int map[] = new int[sequence.length];
1167 int seqlen = sequence.length;
1168 while ((j < seqlen))
1171 if (!jalview.util.Comparison.isGap(sequence[j]))
1182 public List<int[]> getInsertions()
1184 ArrayList<int[]> map = new ArrayList<>();
1185 int lastj = -1, j = 0;
1187 int seqlen = sequence.length;
1188 while ((j < seqlen))
1190 if (jalview.util.Comparison.isGap(sequence[j]))
1201 map.add(new int[] { lastj, j - 1 });
1209 map.add(new int[] { lastj, j - 1 });
1216 public BitSet getInsertionsAsBits()
1218 BitSet map = new BitSet();
1219 int lastj = -1, j = 0;
1221 int seqlen = sequence.length;
1222 while ((j < seqlen))
1224 if (jalview.util.Comparison.isGap(sequence[j]))
1250 public void deleteChars(final int i, final int j)
1252 int newstart = start, newend = end;
1253 if (i >= sequence.length || i < 0)
1258 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1259 boolean createNewDs = false;
1260 // TODO: take a (second look) at the dataset creation validation method for
1261 // the very large sequence case
1263 int startIndex = findIndex(start) - 1;
1264 int endIndex = findIndex(end) - 1;
1265 int startDeleteColumn = -1; // for dataset sequence deletions
1266 int deleteCount = 0;
1268 for (int s = i; s < j && s < sequence.length; s++)
1270 if (Comparison.isGap(sequence[s]))
1275 if (startDeleteColumn == -1)
1277 startDeleteColumn = findPosition(s) - start;
1285 if (startIndex == s)
1288 * deleting characters from start of sequence; new start is the
1289 * sequence position of the next column (position to the right
1290 * if the column position is gapped)
1292 newstart = findPosition(j);
1300 * deleting characters at end of sequence; new end is the sequence
1301 * position of the column before the deletion; subtract 1 if this is
1302 * gapped since findPosition returns the next sequence position
1304 newend = findPosition(i - 1);
1305 if (Comparison.isGap(sequence[i - 1]))
1320 if (createNewDs && this.datasetSequence != null)
1323 * if deletion occured in the middle of the sequence,
1324 * construct a new dataset sequence and delete the residues
1325 * that were deleted from the aligned sequence
1327 Sequence ds = new Sequence(datasetSequence);
1328 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1329 datasetSequence = ds;
1330 // TODO: remove any non-inheritable properties ?
1331 // TODO: create a sequence mapping (since there is a relation here ?)
1340 public void insertCharAt(int i, int length, char c)
1342 char[] tmp = new char[sequence.length + length];
1344 if (i >= sequence.length)
1346 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1347 i = sequence.length;
1351 System.arraycopy(sequence, 0, tmp, 0, i);
1361 if (i < sequence.length)
1363 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1371 public void insertCharAt(int i, char c)
1373 insertCharAt(i, 1, c);
1377 public String getVamsasId()
1383 public void setVamsasId(String id)
1390 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1392 if (dbrefs == null && datasetSequence != null
1393 && this != datasetSequence)
1395 datasetSequence.setDBRefs(newDBrefs);
1403 public DBModList<DBRefEntry> getDBRefs()
1405 if (dbrefs == null && datasetSequence != null
1406 && this != datasetSequence)
1408 return datasetSequence.getDBRefs();
1414 public void addDBRef(DBRefEntry entry)
1416 if (datasetSequence != null)
1418 datasetSequence.addDBRef(entry);
1424 dbrefs = new DBModList<>();
1427 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1429 if (dbrefs.get(ib).updateFrom(entry))
1432 * found a dbref that either matched, or could be
1433 * updated from, the new entry - no need to add it
1441 // * extend the array to make room for one more
1443 // // TODO use an ArrayList instead
1444 // int j = dbrefs.length;
1445 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1446 // System.arraycopy(dbrefs, 0, temp, 0, j);
1447 // temp[temp.length - 1] = entry;
1455 public void setDatasetSequence(SequenceI seq)
1459 throw new IllegalArgumentException(
1460 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1462 if (seq != null && seq.getDatasetSequence() != null)
1464 throw new IllegalArgumentException(
1465 "Implementation error: cascading dataset sequences are not allowed.");
1467 datasetSequence = seq;
1471 public SequenceI getDatasetSequence()
1473 return datasetSequence;
1477 public AlignmentAnnotation[] getAnnotation()
1479 return annotation == null ? null
1481 .toArray(new AlignmentAnnotation[annotation.size()]);
1485 public boolean hasAnnotation(AlignmentAnnotation ann)
1487 return annotation == null ? false : annotation.contains(ann);
1491 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1493 if (this.annotation == null)
1495 this.annotation = new Vector<>();
1497 if (!this.annotation.contains(annotation))
1499 this.annotation.addElement(annotation);
1501 annotation.setSequenceRef(this);
1505 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1507 if (this.annotation != null)
1509 this.annotation.removeElement(annotation);
1510 if (this.annotation.size() == 0)
1512 this.annotation = null;
1518 * test if this is a valid candidate for another sequence's dataset sequence.
1521 private boolean isValidDatasetSequence()
1523 if (datasetSequence != null)
1527 for (int i = 0; i < sequence.length; i++)
1529 if (jalview.util.Comparison.isGap(sequence[i]))
1538 public SequenceI deriveSequence()
1540 Sequence seq = null;
1541 if (datasetSequence == null)
1543 if (isValidDatasetSequence())
1545 // Use this as dataset sequence
1546 seq = new Sequence(getName(), "", 1, -1);
1547 seq.setDatasetSequence(this);
1548 seq.initSeqFrom(this, getAnnotation());
1553 // Create a new, valid dataset sequence
1554 createDatasetSequence();
1557 return new Sequence(this);
1560 private boolean _isNa;
1562 private int _seqhash = 0;
1564 private List<DBRefEntry> primaryRefs;
1567 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1571 public boolean isProtein()
1573 if (datasetSequence != null)
1575 return datasetSequence.isProtein();
1577 if (_seqhash != sequence.hashCode())
1579 _seqhash = sequence.hashCode();
1580 _isNa = Comparison.isNucleotide(this);
1588 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1591 public SequenceI createDatasetSequence()
1593 if (datasetSequence == null)
1595 Sequence dsseq = new Sequence(getName(),
1596 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1597 getSequenceAsString()),
1598 getStart(), getEnd());
1600 datasetSequence = dsseq;
1602 dsseq.setDescription(description);
1603 // move features and database references onto dataset sequence
1604 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1605 sequenceFeatureStore = null;
1606 dsseq.dbrefs = dbrefs;
1608 // TODO: search and replace any references to this sequence with
1609 // references to the dataset sequence in Mappings on dbref
1610 dsseq.pdbIds = pdbIds;
1612 datasetSequence.updatePDBIds();
1613 if (annotation != null)
1615 // annotation is cloned rather than moved, to preserve what's currently
1617 for (AlignmentAnnotation aa : annotation)
1619 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1620 _aa.sequenceRef = datasetSequence;
1621 _aa.adjustForAlignment(); // uses annotation's own record of
1622 // sequence-column mapping
1623 datasetSequence.addAlignmentAnnotation(_aa);
1627 return datasetSequence;
1634 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1638 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1640 if (annotation != null)
1642 annotation.removeAllElements();
1644 if (annotations != null)
1646 for (int i = 0; i < annotations.length; i++)
1648 if (annotations[i] != null)
1650 addAlignmentAnnotation(annotations[i]);
1657 public AlignmentAnnotation[] getAnnotation(String label)
1659 if (annotation == null || annotation.size() == 0)
1664 Vector<AlignmentAnnotation> subset = new Vector<>();
1665 Enumeration<AlignmentAnnotation> e = annotation.elements();
1666 while (e.hasMoreElements())
1668 AlignmentAnnotation ann = e.nextElement();
1669 if (ann.label != null && ann.label.equals(label))
1671 subset.addElement(ann);
1674 if (subset.size() == 0)
1678 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1680 e = subset.elements();
1681 while (e.hasMoreElements())
1683 anns[i++] = e.nextElement();
1685 subset.removeAllElements();
1690 public boolean updatePDBIds()
1692 if (datasetSequence != null)
1694 // TODO: could merge DBRefs
1695 return datasetSequence.updatePDBIds();
1697 if (dbrefs == null || dbrefs.size() == 0)
1701 boolean added = false;
1702 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1704 DBRefEntry dbr = dbrefs.get(ib);
1705 if (DBRefSource.PDB.equals(dbr.getSource()))
1708 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1709 * PDB id is not already present in a 'matching' PDBEntry
1710 * Constructor parses out a chain code if appended to the accession id
1711 * (a fudge used to 'store' the chain code in the DBRef)
1713 PDBEntry pdbe = new PDBEntry(dbr);
1714 added |= addPDBId(pdbe);
1721 public void transferAnnotation(SequenceI entry, Mapping mp)
1723 if (datasetSequence != null)
1725 datasetSequence.transferAnnotation(entry, mp);
1728 if (entry.getDatasetSequence() != null)
1730 transferAnnotation(entry.getDatasetSequence(), mp);
1733 // transfer any new features from entry onto sequence
1734 if (entry.getSequenceFeatures() != null)
1737 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1738 for (SequenceFeature feature : sfs)
1740 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1741 : new SequenceFeature[]
1742 { new SequenceFeature(feature) };
1745 for (int sfi = 0; sfi < sf.length; sfi++)
1747 addSequenceFeature(sf[sfi]);
1753 // transfer PDB entries
1754 if (entry.getAllPDBEntries() != null)
1756 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1757 while (e.hasMoreElements())
1759 PDBEntry pdb = e.nextElement();
1763 // transfer database references
1764 List<DBRefEntry> entryRefs = entry.getDBRefs();
1765 if (entryRefs != null)
1767 for (int r = 0, n = entryRefs.size(); r < n; r++)
1769 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1770 if (newref.getMap() != null && mp != null)
1772 // remap ref using our local mapping
1774 // we also assume all version string setting is done by dbSourceProxy
1776 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1777 * newref.setSource(dbSource); }
1785 public void setRNA(RNA r)
1797 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1800 List<AlignmentAnnotation> result = new ArrayList<>();
1801 if (this.annotation != null)
1803 for (AlignmentAnnotation ann : annotation)
1805 if (ann.calcId != null && ann.calcId.equals(calcId)
1806 && ann.label != null && ann.label.equals(label))
1816 public String toString()
1818 return getDisplayId(false);
1822 public PDBEntry getPDBEntry(String pdbIdStr)
1824 if (getDatasetSequence() != null)
1826 return getDatasetSequence().getPDBEntry(pdbIdStr);
1832 List<PDBEntry> entries = getAllPDBEntries();
1833 for (PDBEntry entry : entries)
1835 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1843 private List<DBRefEntry> tmpList;
1846 public List<DBRefEntry> getPrimaryDBRefs()
1848 if (datasetSequence != null)
1850 return datasetSequence.getPrimaryDBRefs();
1852 if (dbrefs == null || dbrefs.size() == 0)
1854 return Collections.emptyList();
1856 synchronized (dbrefs)
1858 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1860 return primaryRefs; // no changes
1862 refModCount = dbrefs.getModCount();
1863 List<DBRefEntry> primaries = (primaryRefs == null
1864 ? (primaryRefs = new ArrayList<>())
1867 if (tmpList == null)
1869 tmpList = new ArrayList<>();
1870 tmpList.add(null); // for replacement
1872 for (int i = 0, n = dbrefs.size(); i < n; i++)
1874 DBRefEntry ref = dbrefs.get(i);
1875 if (!ref.isPrimaryCandidate())
1881 MapList mp = ref.getMap().getMap();
1882 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1884 // map only involves a subsequence, so cannot be primary
1888 // whilst it looks like it is a primary ref, we also sanity check type
1889 if (DBRefSource.PDB_CANONICAL_NAME
1890 .equals(ref.getCanonicalSourceName()))
1892 // PDB dbrefs imply there should be a PDBEntry associated
1893 // TODO: tighten PDB dbrefs
1894 // formally imply Jalview has actually downloaded and
1895 // parsed the pdb file. That means there should be a cached file
1896 // handle on the PDBEntry, and a real mapping between sequence and
1897 // extracted sequence from PDB file
1898 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1899 if (pdbentry == null || pdbentry.getFile() == null)
1906 // check standard protein or dna sources
1907 tmpList.set(0, ref);
1908 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1910 if (res == null || res.get(0) != tmpList.get(0))
1918 // version must be not null, as otherwise it will not be a candidate,
1920 DBRefUtils.ensurePrimaries(this, primaries);
1929 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1932 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1933 int endPos = fromColumn == toColumn ? startPos
1934 : findPosition(toColumn - 1);
1936 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1938 if (datasetSequence != null)
1940 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1945 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1949 * if end column is gapped, endPos may be to the right,
1950 * and we may have included adjacent or enclosing features;
1951 * remove any that are not enclosing, non-contact features
1953 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1954 && Comparison.isGap(sequence[toColumn - 1]);
1955 if (endPos > this.end || endColumnIsGapped)
1957 ListIterator<SequenceFeature> it = result.listIterator();
1958 while (it.hasNext())
1960 SequenceFeature sf = it.next();
1961 int sfBegin = sf.getBegin();
1962 int sfEnd = sf.getEnd();
1963 int featureStartColumn = findIndex(sfBegin);
1964 if (featureStartColumn > toColumn)
1968 else if (featureStartColumn < fromColumn)
1970 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1972 if (featureEndColumn < fromColumn)
1976 else if (featureEndColumn > toColumn && sf.isContactFeature())
1979 * remove an enclosing feature if it is a contact feature
1991 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1992 * token that has to match the one presented by the cursor
1995 public void sequenceChanged()
2004 public int replace(char c1, char c2)
2011 synchronized (sequence)
2013 for (int c = 0; c < sequence.length; c++)
2015 if (sequence[c] == c1)
2031 public String getSequenceStringFromIterator(Iterator<int[]> it)
2033 StringBuilder newSequence = new StringBuilder();
2034 while (it.hasNext())
2036 int[] block = it.next();
2039 newSequence.append(getSequence(block[0], block[1] + 1));
2043 newSequence.append(getSequence(block[0], block[1]));
2047 return newSequence.toString();
2051 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2055 if (!regions.hasNext())
2057 return findIndex(getStart()) - 1;
2060 // Simply walk along the sequence whilst watching for region
2062 int hideStart = getLength();
2064 boolean foundStart = false;
2066 // step through the non-gapped positions of the sequence
2067 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2069 // get alignment position of this residue in the sequence
2070 int p = findIndex(i) - 1;
2072 // update region start/end
2073 while (hideEnd < p && regions.hasNext())
2075 int[] region = regions.next();
2076 hideStart = region[0];
2077 hideEnd = region[1];
2081 hideStart = getLength();
2083 // update boundary for sequence
2095 // otherwise, sequence was completely hidden