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 DBRefEntry(speciesId, assemblyId,
700 DBRefEntry.CHROMOSOME + ":" + chromosomeId, new Mapping(map)));
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.isChromosome())
718 return new GeneLociI()
721 public String getSpeciesId()
723 return ref.getSource();
727 public String getAssemblyId()
729 // DEV NOTE: DBRefEntry is reused here to hold chromosomal locus
730 // of a gene sequence.
731 // source=species, version=assemblyId, accession=chromosome, map =
734 return ref.getVersion();
738 public String getChromosomeId()
740 // strip off "chromosome:" prefix to chrId
741 return ref.getAccessionId()
742 .substring(DBRefEntry.CHROMOSOME.length() + 1);
746 public MapList getMap()
748 return ref.getMap().getMap();
758 * Answers the description
763 public String getDescription()
765 return this.description;
772 public int findIndex(int pos)
775 * use a valid, hopefully nearby, cursor if available
777 if (isValidCursor(cursor))
779 return findIndex(pos, cursor);
787 * traverse sequence from the start counting gaps; make a note of
788 * the column of the first residue to save in the cursor
790 while ((i < sequence.length) && (j <= end) && (j <= pos))
792 if (!Comparison.isGap(sequence[i]))
803 if (j == end && j < pos)
808 updateCursor(pos, i, startColumn);
813 * Updates the cursor to the latest found residue and column position
820 * column position of the first sequence residue
822 protected void updateCursor(int residuePos, int column, int startColumn)
825 * preserve end residue column provided cursor was valid
827 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
829 if (residuePos == this.end)
834 cursor = new SequenceCursor(this, residuePos, column, startColumn,
835 endColumn, this.changeCount);
839 * Answers the aligned column position (1..) for the given residue position
840 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
841 * The hint may be left of, at, or to the right of the required position.
847 protected int findIndex(final int pos, SequenceCursor curs)
849 if (!isValidCursor(curs))
852 * wrong or invalidated cursor, compute de novo
854 return findIndex(pos);
857 if (curs.residuePosition == pos)
859 return curs.columnPosition;
863 * move left or right to find pos from hint.position
865 int col = curs.columnPosition - 1; // convert from base 1 to base 0
866 int newPos = curs.residuePosition;
867 int delta = newPos > pos ? -1 : 1;
869 while (newPos != pos)
871 col += delta; // shift one column left or right
876 if (col == sequence.length)
878 col--; // return last column if we failed to reach pos
881 if (!Comparison.isGap(sequence[col]))
887 col++; // convert back to base 1
890 * only update cursor if we found the target position
894 updateCursor(pos, col, curs.firstColumnPosition);
904 public int findPosition(final int column)
907 * use a valid, hopefully nearby, cursor if available
909 if (isValidCursor(cursor))
911 return findPosition(column + 1, cursor);
914 // TODO recode this more naturally i.e. count residues only
915 // as they are found, not 'in anticipation'
918 * traverse the sequence counting gaps; note the column position
919 * of the first residue, to save in the cursor
921 int firstResidueColumn = 0;
922 int lastPosFound = 0;
923 int lastPosFoundColumn = 0;
924 int seqlen = sequence.length;
926 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
928 lastPosFound = start;
929 lastPosFoundColumn = 0;
935 while (j < column && j < seqlen)
937 if (!Comparison.isGap(sequence[j]))
940 lastPosFoundColumn = j;
941 if (pos == this.start)
943 firstResidueColumn = j;
949 if (j < seqlen && !Comparison.isGap(sequence[j]))
952 lastPosFoundColumn = j;
953 if (pos == this.start)
955 firstResidueColumn = j;
960 * update the cursor to the last residue position found (if any)
961 * (converting column position to base 1)
963 if (lastPosFound != 0)
965 updateCursor(lastPosFound, lastPosFoundColumn + 1,
966 firstResidueColumn + 1);
973 * Answers true if the given cursor is not null, is for this sequence object,
974 * and has a token value that matches this object's changeCount, else false.
975 * This allows us to ignore a cursor as 'stale' if the sequence has been
976 * modified since the cursor was created.
981 protected boolean isValidCursor(SequenceCursor curs)
983 if (curs == null || curs.sequence != this || curs.token != changeCount)
988 * sanity check against range
990 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
994 if (curs.residuePosition < start || curs.residuePosition > end)
1002 * Answers the sequence position (start..) for the given aligned column
1003 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
1004 * may lie left of, at, or to the right of the column position.
1010 protected int findPosition(final int col, SequenceCursor curs)
1012 if (!isValidCursor(curs))
1015 * wrong or invalidated cursor, compute de novo
1017 return findPosition(col - 1);// ugh back to base 0
1020 if (curs.columnPosition == col)
1022 cursor = curs; // in case this method becomes public
1023 return curs.residuePosition; // easy case :-)
1026 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1029 * sequence lies entirely to the left of col
1030 * - return last residue + 1
1035 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1038 * sequence lies entirely to the right of col
1039 * - return first residue
1044 // todo could choose closest to col out of column,
1045 // firstColumnPosition, lastColumnPosition as a start point
1048 * move left or right to find pos from cursor position
1050 int firstResidueColumn = curs.firstColumnPosition;
1051 int column = curs.columnPosition - 1; // to base 0
1052 int newPos = curs.residuePosition;
1053 int delta = curs.columnPosition > col ? -1 : 1;
1054 boolean gapped = false;
1055 int lastFoundPosition = curs.residuePosition;
1056 int lastFoundPositionColumn = curs.columnPosition;
1058 while (column != col - 1)
1060 column += delta; // shift one column left or right
1061 if (column < 0 || column == sequence.length)
1065 gapped = Comparison.isGap(sequence[column]);
1069 lastFoundPosition = newPos;
1070 lastFoundPositionColumn = column + 1;
1071 if (lastFoundPosition == this.start)
1073 firstResidueColumn = column + 1;
1078 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1080 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1081 firstResidueColumn);
1085 * hack to give position to the right if on a gap
1086 * or beyond the length of the sequence (see JAL-2562)
1088 if (delta > 0 && (gapped || column >= sequence.length))
1100 public ContiguousI findPositions(int fromColumn, int toColumn)
1102 if (toColumn < fromColumn || fromColumn < 1)
1108 * find the first non-gapped position, if any
1110 int firstPosition = 0;
1111 int col = fromColumn - 1;
1112 int length = sequence.length;
1113 while (col < length && col < toColumn)
1115 if (!Comparison.isGap(sequence[col]))
1117 firstPosition = findPosition(col++);
1123 if (firstPosition == 0)
1129 * find the last non-gapped position
1131 int lastPosition = firstPosition;
1132 while (col < length && col < toColumn)
1134 if (!Comparison.isGap(sequence[col++]))
1140 return new Range(firstPosition, lastPosition);
1144 * Returns an int array where indices correspond to each residue in the
1145 * sequence and the element value gives its position in the alignment
1147 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1148 * residues in SequenceI object
1151 public int[] gapMap()
1153 String seq = jalview.analysis.AlignSeq.extractGaps(
1154 jalview.util.Comparison.GapChars, new String(sequence));
1155 int[] map = new int[seq.length()];
1159 while (j < sequence.length)
1161 if (!jalview.util.Comparison.isGap(sequence[j]))
1173 * Build a bitset corresponding to sequence gaps
1175 * @return a BitSet where set values correspond to gaps in the sequence
1178 public BitSet gapBitset()
1180 BitSet gaps = new BitSet(sequence.length);
1182 while (j < sequence.length)
1184 if (jalview.util.Comparison.isGap(sequence[j]))
1194 public int[] findPositionMap()
1196 int map[] = new int[sequence.length];
1199 int seqlen = sequence.length;
1200 while ((j < seqlen))
1203 if (!jalview.util.Comparison.isGap(sequence[j]))
1214 public List<int[]> getInsertions()
1216 ArrayList<int[]> map = new ArrayList<>();
1217 int lastj = -1, j = 0;
1219 int seqlen = sequence.length;
1220 while ((j < seqlen))
1222 if (jalview.util.Comparison.isGap(sequence[j]))
1233 map.add(new int[] { lastj, j - 1 });
1241 map.add(new int[] { lastj, j - 1 });
1248 public BitSet getInsertionsAsBits()
1250 BitSet map = new BitSet();
1251 int lastj = -1, j = 0;
1253 int seqlen = sequence.length;
1254 while ((j < seqlen))
1256 if (jalview.util.Comparison.isGap(sequence[j]))
1282 public void deleteChars(final int i, final int j)
1284 int newstart = start, newend = end;
1285 if (i >= sequence.length || i < 0)
1290 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1291 boolean createNewDs = false;
1292 // TODO: take a (second look) at the dataset creation validation method for
1293 // the very large sequence case
1295 int startIndex = findIndex(start) - 1;
1296 int endIndex = findIndex(end) - 1;
1297 int startDeleteColumn = -1; // for dataset sequence deletions
1298 int deleteCount = 0;
1300 for (int s = i; s < j && s < sequence.length; s++)
1302 if (Comparison.isGap(sequence[s]))
1307 if (startDeleteColumn == -1)
1309 startDeleteColumn = findPosition(s) - start;
1317 if (startIndex == s)
1320 * deleting characters from start of sequence; new start is the
1321 * sequence position of the next column (position to the right
1322 * if the column position is gapped)
1324 newstart = findPosition(j);
1332 * deleting characters at end of sequence; new end is the sequence
1333 * position of the column before the deletion; subtract 1 if this is
1334 * gapped since findPosition returns the next sequence position
1336 newend = findPosition(i - 1);
1337 if (Comparison.isGap(sequence[i - 1]))
1352 if (createNewDs && this.datasetSequence != null)
1355 * if deletion occured in the middle of the sequence,
1356 * construct a new dataset sequence and delete the residues
1357 * that were deleted from the aligned sequence
1359 Sequence ds = new Sequence(datasetSequence);
1360 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1361 datasetSequence = ds;
1362 // TODO: remove any non-inheritable properties ?
1363 // TODO: create a sequence mapping (since there is a relation here ?)
1372 public void insertCharAt(int i, int length, char c)
1374 char[] tmp = new char[sequence.length + length];
1376 if (i >= sequence.length)
1378 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1379 i = sequence.length;
1383 System.arraycopy(sequence, 0, tmp, 0, i);
1393 if (i < sequence.length)
1395 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1403 public void insertCharAt(int i, char c)
1405 insertCharAt(i, 1, c);
1409 public String getVamsasId()
1415 public void setVamsasId(String id)
1422 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1424 if (dbrefs == null && datasetSequence != null
1425 && this != datasetSequence)
1427 datasetSequence.setDBRefs(newDBrefs);
1435 public DBModList<DBRefEntry> getDBRefs()
1437 if (dbrefs == null && datasetSequence != null
1438 && this != datasetSequence)
1440 return datasetSequence.getDBRefs();
1446 public void addDBRef(DBRefEntry entry)
1448 if (datasetSequence != null)
1450 datasetSequence.addDBRef(entry);
1456 dbrefs = new DBModList<>();
1459 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1461 if (dbrefs.get(ib).updateFrom(entry))
1464 * found a dbref that either matched, or could be
1465 * updated from, the new entry - no need to add it
1473 // * extend the array to make room for one more
1475 // // TODO use an ArrayList instead
1476 // int j = dbrefs.length;
1477 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1478 // System.arraycopy(dbrefs, 0, temp, 0, j);
1479 // temp[temp.length - 1] = entry;
1487 public void setDatasetSequence(SequenceI seq)
1491 throw new IllegalArgumentException(
1492 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1494 if (seq != null && seq.getDatasetSequence() != null)
1496 throw new IllegalArgumentException(
1497 "Implementation error: cascading dataset sequences are not allowed.");
1499 datasetSequence = seq;
1503 public SequenceI getDatasetSequence()
1505 return datasetSequence;
1509 public AlignmentAnnotation[] getAnnotation()
1511 return annotation == null ? null
1513 .toArray(new AlignmentAnnotation[annotation.size()]);
1517 public boolean hasAnnotation(AlignmentAnnotation ann)
1519 return annotation == null ? false : annotation.contains(ann);
1523 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1525 if (this.annotation == null)
1527 this.annotation = new Vector<>();
1529 if (!this.annotation.contains(annotation))
1531 this.annotation.addElement(annotation);
1533 annotation.setSequenceRef(this);
1537 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1539 if (this.annotation != null)
1541 this.annotation.removeElement(annotation);
1542 if (this.annotation.size() == 0)
1544 this.annotation = null;
1550 * test if this is a valid candidate for another sequence's dataset sequence.
1553 private boolean isValidDatasetSequence()
1555 if (datasetSequence != null)
1559 for (int i = 0; i < sequence.length; i++)
1561 if (jalview.util.Comparison.isGap(sequence[i]))
1570 public SequenceI deriveSequence()
1572 Sequence seq = null;
1573 if (datasetSequence == null)
1575 if (isValidDatasetSequence())
1577 // Use this as dataset sequence
1578 seq = new Sequence(getName(), "", 1, -1);
1579 seq.setDatasetSequence(this);
1580 seq.initSeqFrom(this, getAnnotation());
1585 // Create a new, valid dataset sequence
1586 createDatasetSequence();
1589 return new Sequence(this);
1592 private boolean _isNa;
1594 private int _seqhash = 0;
1596 private List<DBRefEntry> primaryRefs;
1599 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1603 public boolean isProtein()
1605 if (datasetSequence != null)
1607 return datasetSequence.isProtein();
1609 if (_seqhash != sequence.hashCode())
1611 _seqhash = sequence.hashCode();
1612 _isNa = Comparison.isNucleotide(this);
1620 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1623 public SequenceI createDatasetSequence()
1625 if (datasetSequence == null)
1627 Sequence dsseq = new Sequence(getName(),
1628 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1629 getSequenceAsString()),
1630 getStart(), getEnd());
1632 datasetSequence = dsseq;
1634 dsseq.setDescription(description);
1635 // move features and database references onto dataset sequence
1636 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1637 sequenceFeatureStore = null;
1638 dsseq.dbrefs = dbrefs;
1640 // TODO: search and replace any references to this sequence with
1641 // references to the dataset sequence in Mappings on dbref
1642 dsseq.pdbIds = pdbIds;
1644 datasetSequence.updatePDBIds();
1645 if (annotation != null)
1647 // annotation is cloned rather than moved, to preserve what's currently
1649 for (AlignmentAnnotation aa : annotation)
1651 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1652 _aa.sequenceRef = datasetSequence;
1653 _aa.adjustForAlignment(); // uses annotation's own record of
1654 // sequence-column mapping
1655 datasetSequence.addAlignmentAnnotation(_aa);
1659 return datasetSequence;
1666 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1670 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1672 if (annotation != null)
1674 annotation.removeAllElements();
1676 if (annotations != null)
1678 for (int i = 0; i < annotations.length; i++)
1680 if (annotations[i] != null)
1682 addAlignmentAnnotation(annotations[i]);
1689 public AlignmentAnnotation[] getAnnotation(String label)
1691 if (annotation == null || annotation.size() == 0)
1696 Vector<AlignmentAnnotation> subset = new Vector<>();
1697 Enumeration<AlignmentAnnotation> e = annotation.elements();
1698 while (e.hasMoreElements())
1700 AlignmentAnnotation ann = e.nextElement();
1701 if (ann.label != null && ann.label.equals(label))
1703 subset.addElement(ann);
1706 if (subset.size() == 0)
1710 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1712 e = subset.elements();
1713 while (e.hasMoreElements())
1715 anns[i++] = e.nextElement();
1717 subset.removeAllElements();
1722 public boolean updatePDBIds()
1724 if (datasetSequence != null)
1726 // TODO: could merge DBRefs
1727 return datasetSequence.updatePDBIds();
1729 if (dbrefs == null || dbrefs.size() == 0)
1733 boolean added = false;
1734 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1736 DBRefEntry dbr = dbrefs.get(ib);
1737 if (DBRefSource.PDB.equals(dbr.getSource()))
1740 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1741 * PDB id is not already present in a 'matching' PDBEntry
1742 * Constructor parses out a chain code if appended to the accession id
1743 * (a fudge used to 'store' the chain code in the DBRef)
1745 PDBEntry pdbe = new PDBEntry(dbr);
1746 added |= addPDBId(pdbe);
1753 public void transferAnnotation(SequenceI entry, Mapping mp)
1755 if (datasetSequence != null)
1757 datasetSequence.transferAnnotation(entry, mp);
1760 if (entry.getDatasetSequence() != null)
1762 transferAnnotation(entry.getDatasetSequence(), mp);
1765 // transfer any new features from entry onto sequence
1766 if (entry.getSequenceFeatures() != null)
1769 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1770 for (SequenceFeature feature : sfs)
1772 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1773 : new SequenceFeature[]
1774 { new SequenceFeature(feature) };
1777 for (int sfi = 0; sfi < sf.length; sfi++)
1779 addSequenceFeature(sf[sfi]);
1785 // transfer PDB entries
1786 if (entry.getAllPDBEntries() != null)
1788 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1789 while (e.hasMoreElements())
1791 PDBEntry pdb = e.nextElement();
1795 // transfer database references
1796 List<DBRefEntry> entryRefs = entry.getDBRefs();
1797 if (entryRefs != null)
1799 for (int r = 0, n = entryRefs.size(); r < n; r++)
1801 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1802 if (newref.getMap() != null && mp != null)
1804 // remap ref using our local mapping
1806 // we also assume all version string setting is done by dbSourceProxy
1808 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1809 * newref.setSource(dbSource); }
1817 public void setRNA(RNA r)
1829 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1832 List<AlignmentAnnotation> result = new ArrayList<>();
1833 if (this.annotation != null)
1835 for (AlignmentAnnotation ann : annotation)
1837 if (ann.calcId != null && ann.calcId.equals(calcId)
1838 && ann.label != null && ann.label.equals(label))
1848 public String toString()
1850 return getDisplayId(false);
1854 public PDBEntry getPDBEntry(String pdbIdStr)
1856 if (getDatasetSequence() != null)
1858 return getDatasetSequence().getPDBEntry(pdbIdStr);
1864 List<PDBEntry> entries = getAllPDBEntries();
1865 for (PDBEntry entry : entries)
1867 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1875 private List<DBRefEntry> tmpList;
1878 public List<DBRefEntry> getPrimaryDBRefs()
1880 if (datasetSequence != null)
1882 return datasetSequence.getPrimaryDBRefs();
1884 if (dbrefs == null || dbrefs.size() == 0)
1886 return Collections.emptyList();
1888 synchronized (dbrefs)
1890 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1892 return primaryRefs; // no changes
1894 refModCount = dbrefs.getModCount();
1895 List<DBRefEntry> primaries = (primaryRefs == null
1896 ? (primaryRefs = new ArrayList<>())
1899 if (tmpList == null)
1901 tmpList = new ArrayList<>();
1902 tmpList.add(null); // for replacement
1904 for (int i = 0, n = dbrefs.size(); i < n; i++)
1906 DBRefEntry ref = dbrefs.get(i);
1907 if (!ref.isPrimaryCandidate())
1913 MapList mp = ref.getMap().getMap();
1914 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1916 // map only involves a subsequence, so cannot be primary
1920 // whilst it looks like it is a primary ref, we also sanity check type
1921 if (DBRefSource.PDB_CANONICAL_NAME
1922 .equals(ref.getCanonicalSourceName()))
1924 // PDB dbrefs imply there should be a PDBEntry associated
1925 // TODO: tighten PDB dbrefs
1926 // formally imply Jalview has actually downloaded and
1927 // parsed the pdb file. That means there should be a cached file
1928 // handle on the PDBEntry, and a real mapping between sequence and
1929 // extracted sequence from PDB file
1930 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1931 if (pdbentry == null || pdbentry.getFile() == null)
1938 // check standard protein or dna sources
1939 tmpList.set(0, ref);
1940 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1942 if (res == null || res.get(0) != tmpList.get(0))
1950 // version must be not null, as otherwise it will not be a candidate,
1952 DBRefUtils.ensurePrimaries(this, primaries);
1961 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1964 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1965 int endPos = fromColumn == toColumn ? startPos
1966 : findPosition(toColumn - 1);
1968 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1972 * if end column is gapped, endPos may be to the right,
1973 * and we may have included adjacent or enclosing features;
1974 * remove any that are not enclosing, non-contact features
1976 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1977 && Comparison.isGap(sequence[toColumn - 1]);
1978 if (endPos > this.end || endColumnIsGapped)
1980 ListIterator<SequenceFeature> it = result.listIterator();
1981 while (it.hasNext())
1983 SequenceFeature sf = it.next();
1984 int sfBegin = sf.getBegin();
1985 int sfEnd = sf.getEnd();
1986 int featureStartColumn = findIndex(sfBegin);
1987 if (featureStartColumn > toColumn)
1991 else if (featureStartColumn < fromColumn)
1993 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1995 if (featureEndColumn < fromColumn)
1999 else if (featureEndColumn > toColumn && sf.isContactFeature())
2002 * remove an enclosing feature if it is a contact feature
2014 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2015 * token that has to match the one presented by the cursor
2018 public void sequenceChanged()
2027 public int replace(char c1, char c2)
2034 synchronized (sequence)
2036 for (int c = 0; c < sequence.length; c++)
2038 if (sequence[c] == c1)
2054 public String getSequenceStringFromIterator(Iterator<int[]> it)
2056 StringBuilder newSequence = new StringBuilder();
2057 while (it.hasNext())
2059 int[] block = it.next();
2062 newSequence.append(getSequence(block[0], block[1] + 1));
2066 newSequence.append(getSequence(block[0], block[1]));
2070 return newSequence.toString();
2074 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2078 if (!regions.hasNext())
2080 return findIndex(getStart()) - 1;
2083 // Simply walk along the sequence whilst watching for region
2085 int hideStart = getLength();
2087 boolean foundStart = false;
2089 // step through the non-gapped positions of the sequence
2090 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2092 // get alignment position of this residue in the sequence
2093 int p = findIndex(i) - 1;
2095 // update region start/end
2096 while (hideEnd < p && regions.hasNext())
2098 int[] region = regions.next();
2099 hideStart = region[0];
2100 hideEnd = region[1];
2104 hideStart = getLength();
2106 // update boundary for sequence
2118 // otherwise, sequence was completely hidden
2123 * Answers a (possibly empty) list of features of the specified type that
2124 * overlap the specified column position. If parameter {@code result} is not
2125 * null, features are appended to it and the (possibly extended) list is
2129 public List<SequenceFeature> findFeatures(int column, String type,
2130 List<SequenceFeature> result)
2132 return getFeatures().findFeatures(findPosition(column - 1), type,
2137 public boolean hasFeatures(String type)
2139 return getFeatures().hasFeatures(type);