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.api.DBRefEntryI;
25 import jalview.datamodel.features.SequenceFeatures;
26 import jalview.datamodel.features.SequenceFeaturesI;
27 import jalview.util.Comparison;
28 import jalview.util.DBRefUtils;
29 import jalview.util.MapList;
30 import jalview.util.StringUtils;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.BitSet;
35 import java.util.Collections;
36 import java.util.Enumeration;
37 import java.util.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
49 SequenceI datasetSequence;
53 private char[] sequence;
61 Vector<PDBEntry> pdbIds;
70 * This annotation is displayed below the alignment but the positions are tied
71 * to the residues of this sequence
73 * TODO: change to List<>
75 Vector<AlignmentAnnotation> annotation;
77 private SequenceFeaturesI sequenceFeatureStore;
80 * A cursor holding the approximate current view position to the sequence,
81 * as determined by findIndex or findPosition or findPositions.
82 * Using a cursor as a hint allows these methods to be more performant for
85 private SequenceCursor cursor;
88 * A number that should be incremented whenever the sequence is edited.
89 * If the value matches the cursor token, then we can trust the cursor,
90 * if not then it should be recomputed.
92 private int changeCount;
95 * Creates a new Sequence object.
100 * string to form a possibly gapped sequence out of
102 * first position of non-gap residue in the sequence
104 * last position of ungapped residues (nearly always only used for
107 public Sequence(String name, String sequence, int start, int end)
110 initSeqAndName(name, sequence.toCharArray(), start, end);
113 public Sequence(String name, char[] sequence, int start, int end)
116 initSeqAndName(name, sequence, start, end);
120 * Stage 1 constructor - assign name, sequence, and set start and end fields.
121 * start and end are updated values from name2 if it ends with /start-end
128 protected void initSeqAndName(String name2, char[] sequence2, int start2,
132 this.sequence = sequence2;
140 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
141 * start and end respectively and removes the suffix from the name
148 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
151 int slashPos = name.lastIndexOf('/');
152 if (slashPos > -1 && slashPos < name.length() - 1)
154 String suffix = name.substring(slashPos + 1);
155 String[] range = suffix.split("-");
156 if (range.length == 2)
160 int from = Integer.valueOf(range[0]);
161 int to = Integer.valueOf(range[1]);
162 if (from > 0 && to >= from)
164 name = name.substring(0, slashPos);
169 } catch (NumberFormatException e)
171 // leave name unchanged if suffix is invalid
178 * Ensures that 'end' is not before the end of the sequence, that is,
179 * (end-start+1) is at least as long as the count of ungapped positions. Note
180 * that end is permitted to be beyond the end of the sequence data.
182 void checkValidRange()
185 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
188 for (int j = 0; j < sequence.length; j++)
190 if (!Comparison.isGap(sequence[j]))
209 * default constructor
213 sequenceFeatureStore = new SequenceFeatures();
217 * Creates a new Sequence object.
224 public Sequence(String name, String sequence)
226 this(name, sequence, 1, -1);
230 * Creates a new Sequence object with new AlignmentAnnotations but inherits
231 * any existing dataset sequence reference. If non exists, everything is
235 * if seq is a dataset sequence, behaves like a plain old copy
238 public Sequence(SequenceI seq)
240 this(seq, seq.getAnnotation());
244 * Create a new sequence object with new features, DBRefEntries, and PDBIds
245 * but inherits any existing dataset sequence reference, and duplicate of any
246 * annotation that is present in the given annotation array.
249 * the sequence to be copied
250 * @param alAnnotation
251 * an array of annotation including some associated with seq
253 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
256 initSeqFrom(seq, alAnnotation);
260 * does the heavy lifting when cloning a dataset sequence, or coping data from
261 * dataset to a new derived sequence.
264 * - source of attributes.
265 * @param alAnnotation
266 * - alignment annotation present on seq that should be copied onto
269 protected void initSeqFrom(SequenceI seq,
270 AlignmentAnnotation[] alAnnotation)
272 char[] oseq = seq.getSequence(); // returns a copy of the array
273 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
275 description = seq.getDescription();
276 if (seq != datasetSequence)
278 setDatasetSequence(seq.getDatasetSequence());
282 * only copy DBRefs and seqfeatures if we really are a dataset sequence
284 if (datasetSequence == null)
286 if (seq.getDBRefs() != null)
288 DBRefEntry[] dbr = seq.getDBRefs();
289 for (int i = 0; i < dbr.length; i++)
291 addDBRef(new DBRefEntry(dbr[i]));
296 * make copies of any sequence features
298 for (SequenceFeature sf : seq.getSequenceFeatures())
300 addSequenceFeature(new SequenceFeature(sf));
304 if (seq.getAnnotation() != null)
306 AlignmentAnnotation[] sqann = seq.getAnnotation();
307 for (int i = 0; i < sqann.length; i++)
309 if (sqann[i] == null)
313 boolean found = (alAnnotation == null);
316 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
318 found = (alAnnotation[apos] == sqann[i]);
323 // only copy the given annotation
324 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
325 addAlignmentAnnotation(newann);
329 if (seq.getAllPDBEntries() != null)
331 Vector<PDBEntry> ids = seq.getAllPDBEntries();
332 for (PDBEntry pdb : ids)
334 this.addPDBId(new PDBEntry(pdb));
340 public void setSequenceFeatures(List<SequenceFeature> features)
342 if (datasetSequence != null)
344 datasetSequence.setSequenceFeatures(features);
347 sequenceFeatureStore = new SequenceFeatures(features);
351 public synchronized boolean addSequenceFeature(SequenceFeature sf)
353 if (sf.getType() == null)
355 System.err.println("SequenceFeature type may not be null: "
360 if (datasetSequence != null)
362 return datasetSequence.addSequenceFeature(sf);
365 return sequenceFeatureStore.add(sf);
369 public void deleteFeature(SequenceFeature sf)
371 if (datasetSequence != null)
373 datasetSequence.deleteFeature(sf);
377 sequenceFeatureStore.delete(sf);
387 public List<SequenceFeature> getSequenceFeatures()
389 if (datasetSequence != null)
391 return datasetSequence.getSequenceFeatures();
393 return sequenceFeatureStore.getAllFeatures();
397 public SequenceFeaturesI getFeatures()
399 return datasetSequence != null ? datasetSequence.getFeatures()
400 : sequenceFeatureStore;
404 public boolean addPDBId(PDBEntry entry)
408 pdbIds = new Vector<PDBEntry>();
413 for (PDBEntry pdbe : pdbIds)
415 if (pdbe.updateFrom(entry))
420 pdbIds.addElement(entry);
431 public void setPDBId(Vector<PDBEntry> id)
439 * @return DOCUMENT ME!
442 public Vector<PDBEntry> getAllPDBEntries()
444 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
450 * @return DOCUMENT ME!
453 public String getDisplayId(boolean jvsuffix)
455 StringBuffer result = new StringBuffer(name);
458 result.append("/" + start + "-" + end);
461 return result.toString();
465 * Sets the sequence name. If the name ends in /start-end, then the start-end
466 * values are parsed out and set, and the suffix is removed from the name.
471 public void setName(String theName)
480 * @return DOCUMENT ME!
483 public String getName()
495 public void setStart(int start)
503 * @return DOCUMENT ME!
506 public int getStart()
518 public void setEnd(int end)
526 * @return DOCUMENT ME!
537 * @return DOCUMENT ME!
540 public int getLength()
542 return this.sequence.length;
552 public void setSequence(String seq)
554 this.sequence = seq.toCharArray();
560 public String getSequenceAsString()
562 return new String(sequence);
566 public String getSequenceAsString(int start, int end)
568 return new String(getSequence(start, end));
572 public char[] getSequence()
575 return sequence == null ? null : Arrays.copyOf(sequence,
582 * @see jalview.datamodel.SequenceI#getSequence(int, int)
585 public char[] getSequence(int start, int end)
591 // JBPNote - left to user to pad the result here (TODO:Decide on this
593 if (start >= sequence.length)
598 if (end >= sequence.length)
600 end = sequence.length;
603 char[] reply = new char[end - start];
604 System.arraycopy(sequence, start, reply, 0, end - start);
610 public SequenceI getSubSequence(int start, int end)
616 char[] seq = getSequence(start, end);
621 int nstart = findPosition(start);
622 int nend = findPosition(end) - 1;
623 // JBPNote - this is an incomplete copy.
624 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
625 nseq.setDescription(description);
626 if (datasetSequence != null)
628 nseq.setDatasetSequence(datasetSequence);
632 nseq.setDatasetSequence(this);
638 * Returns the character of the aligned sequence at the given position (base
639 * zero), or space if the position is not within the sequence's bounds
644 public char getCharAt(int i)
646 if (i >= 0 && i < sequence.length)
663 public void setDescription(String desc)
665 this.description = desc;
671 * @return DOCUMENT ME!
674 public String getDescription()
676 return this.description;
683 public int findIndex(int pos)
686 * use a valid, hopefully nearby, cursor if available
688 if (isValidCursor(cursor))
690 return findIndex(pos, cursor);
698 * traverse sequence from the start counting gaps; make a note of
699 * the column of the first residue to save in the cursor
701 while ((i < sequence.length) && (j <= end) && (j <= pos))
703 if (!Comparison.isGap(sequence[i]))
714 if (j == end && j < pos)
719 updateCursor(pos, i, startColumn);
724 * Updates the cursor to the latest found residue and column position
731 * column position of the first sequence residue
733 protected void updateCursor(int residuePos, int column, int startColumn)
736 * preserve end residue column provided cursor was valid
738 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
740 if (residuePos == this.end)
745 cursor = new SequenceCursor(this, residuePos, column, startColumn,
746 endColumn, this.changeCount);
750 * Answers the aligned column position (1..) for the given residue position
751 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
752 * The hint may be left of, at, or to the right of the required position.
758 protected int findIndex(int pos, SequenceCursor curs)
760 if (!isValidCursor(curs))
763 * wrong or invalidated cursor, compute de novo
765 return findIndex(pos);
768 if (curs.residuePosition == pos)
770 return curs.columnPosition;
774 * move left or right to find pos from hint.position
776 int col = curs.columnPosition - 1; // convert from base 1 to base 0
777 int newPos = curs.residuePosition;
778 int delta = newPos > pos ? -1 : 1;
780 while (newPos != pos)
782 col += delta; // shift one column left or right
783 if (col < 0 || col == sequence.length)
787 if (!Comparison.isGap(sequence[col]))
793 col++; // convert back to base 1
794 updateCursor(pos, col, curs.firstColumnPosition);
803 public int findPosition(final int column)
806 * use a valid, hopefully nearby, cursor if available
808 if (isValidCursor(cursor))
810 return findPosition(column + 1, cursor);
813 // TODO recode this more naturally i.e. count residues only
814 // as they are found, not 'in anticipation'
817 * traverse the sequence counting gaps; note the column position
818 * of the first residue, to save in the cursor
820 int firstResidueColumn = 0;
821 int lastPosFound = 0;
822 int lastPosFoundColumn = 0;
823 int seqlen = sequence.length;
825 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
827 lastPosFound = start;
828 lastPosFoundColumn = 0;
834 while (j < column && j < seqlen)
836 if (!Comparison.isGap(sequence[j]))
839 lastPosFoundColumn = j;
840 if (pos == this.start)
842 firstResidueColumn = j;
848 if (j < seqlen && !Comparison.isGap(sequence[j]))
851 lastPosFoundColumn = j;
852 if (pos == this.start)
854 firstResidueColumn = j;
859 * update the cursor to the last residue position found (if any)
860 * (converting column position to base 1)
862 if (lastPosFound != 0)
864 updateCursor(lastPosFound, lastPosFoundColumn + 1,
865 firstResidueColumn + 1);
872 * Answers true if the given cursor is not null, is for this sequence object,
873 * and has a token value that matches this object's changeCount, else false.
874 * This allows us to ignore a cursor as 'stale' if the sequence has been
875 * modified since the cursor was created.
880 protected boolean isValidCursor(SequenceCursor curs)
882 if (curs == null || curs.sequence != this || curs.token != changeCount)
887 * sanity check against range
889 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
893 if (curs.residuePosition < start || curs.residuePosition > end)
901 * Answers the sequence position (start..) for the given aligned column
902 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
903 * may lie left of, at, or to the right of the column position.
909 protected int findPosition(final int col, SequenceCursor curs)
911 if (!isValidCursor(curs))
914 * wrong or invalidated cursor, compute de novo
916 return findPosition(col - 1);// ugh back to base 0
919 if (curs.columnPosition == col)
921 cursor = curs; // in case this method becomes public
922 return curs.residuePosition; // easy case :-)
925 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
928 * sequence lies entirely to the left of col
929 * - return last residue + 1
934 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
937 * sequence lies entirely to the right of col
938 * - return first residue
943 // todo could choose closest to col out of column,
944 // firstColumnPosition, lastColumnPosition as a start point
947 * move left or right to find pos from cursor position
949 int firstResidueColumn = curs.firstColumnPosition;
950 int column = curs.columnPosition - 1; // to base 0
951 int newPos = curs.residuePosition;
952 int delta = curs.columnPosition > col ? -1 : 1;
953 boolean gapped = false;
954 int lastFoundPosition = curs.residuePosition;
955 int lastFoundPositionColumn = curs.columnPosition;
957 while (column != col - 1)
959 column += delta; // shift one column left or right
960 if (column < 0 || column == sequence.length)
964 gapped = Comparison.isGap(sequence[column]);
968 lastFoundPosition = newPos;
969 lastFoundPositionColumn = column + 1;
970 if (lastFoundPosition == this.start)
972 firstResidueColumn = column + 1;
977 if (cursor == null || lastFoundPosition != cursor.residuePosition)
979 updateCursor(lastFoundPosition, lastFoundPositionColumn,
984 * hack to give position to the right if on a gap
985 * or beyond the length of the sequence (see JAL-2562)
987 if (delta > 0 && (gapped || column >= sequence.length))
999 public Range findPositions(int fromColumn, int toColumn)
1001 if (toColumn < fromColumn || fromColumn < 1)
1007 * find the first non-gapped position, if any
1009 int firstPosition = 0;
1010 int col = fromColumn - 1;
1011 int length = sequence.length;
1012 while (col < length && col < toColumn)
1014 if (!Comparison.isGap(sequence[col]))
1016 firstPosition = findPosition(col++);
1022 if (firstPosition == 0)
1028 * find the last non-gapped position
1030 int lastPosition = firstPosition;
1031 while (col < length && col < toColumn)
1033 if (!Comparison.isGap(sequence[col++]))
1039 return new Range(firstPosition, lastPosition);
1043 * Returns an int array where indices correspond to each residue in the
1044 * sequence and the element value gives its position in the alignment
1046 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1047 * residues in SequenceI object
1050 public int[] gapMap()
1052 String seq = jalview.analysis.AlignSeq.extractGaps(
1053 jalview.util.Comparison.GapChars, new String(sequence));
1054 int[] map = new int[seq.length()];
1058 while (j < sequence.length)
1060 if (!jalview.util.Comparison.isGap(sequence[j]))
1072 public int[] findPositionMap()
1074 int map[] = new int[sequence.length];
1077 int seqlen = sequence.length;
1078 while ((j < seqlen))
1081 if (!jalview.util.Comparison.isGap(sequence[j]))
1092 public List<int[]> getInsertions()
1094 ArrayList<int[]> map = new ArrayList<int[]>();
1095 int lastj = -1, j = 0;
1097 int seqlen = sequence.length;
1098 while ((j < seqlen))
1100 if (jalview.util.Comparison.isGap(sequence[j]))
1111 map.add(new int[] { lastj, j - 1 });
1119 map.add(new int[] { lastj, j - 1 });
1126 public BitSet getInsertionsAsBits()
1128 BitSet map = new BitSet();
1129 int lastj = -1, j = 0;
1131 int seqlen = sequence.length;
1132 while ((j < seqlen))
1134 if (jalview.util.Comparison.isGap(sequence[j]))
1160 public void deleteChars(final int i, final int j)
1162 int newstart = start, newend = end;
1163 if (i >= sequence.length || i < 0)
1168 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1169 boolean createNewDs = false;
1170 // TODO: take a (second look) at the dataset creation validation method for
1171 // the very large sequence case
1173 int startIndex = findIndex(start) - 1;
1174 int endIndex = findIndex(end) - 1;
1175 int startDeleteColumn = -1; // for dataset sequence deletions
1176 int deleteCount = 0;
1178 for (int s = i; s < j && s < sequence.length; s++)
1180 if (Comparison.isGap(sequence[s]))
1185 if (startDeleteColumn == -1)
1187 startDeleteColumn = findPosition(s) - start;
1195 if (startIndex == s)
1198 * deleting characters from start of sequence; new start is the
1199 * sequence position of the next column (position to the right
1200 * if the column position is gapped)
1202 newstart = findPosition(j);
1210 * deleting characters at end of sequence; new end is the sequence
1211 * position of the column before the deletion; subtract 1 if this is
1212 * gapped since findPosition returns the next sequence position
1214 newend = findPosition(i - 1);
1215 if (Comparison.isGap(sequence[i - 1]))
1230 if (createNewDs && this.datasetSequence != null)
1233 * if deletion occured in the middle of the sequence,
1234 * construct a new dataset sequence and delete the residues
1235 * that were deleted from the aligned sequence
1237 Sequence ds = new Sequence(datasetSequence);
1238 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1239 datasetSequence = ds;
1240 // TODO: remove any non-inheritable properties ?
1241 // TODO: create a sequence mapping (since there is a relation here ?)
1250 public void insertCharAt(int i, int length, char c)
1252 char[] tmp = new char[sequence.length + length];
1254 if (i >= sequence.length)
1256 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1257 i = sequence.length;
1261 System.arraycopy(sequence, 0, tmp, 0, i);
1271 if (i < sequence.length)
1273 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1281 public void insertCharAt(int i, char c)
1283 insertCharAt(i, 1, c);
1287 public String getVamsasId()
1293 public void setVamsasId(String id)
1299 public void setDBRefs(DBRefEntry[] dbref)
1301 if (dbrefs == null && datasetSequence != null
1302 && this != datasetSequence)
1304 datasetSequence.setDBRefs(dbref);
1310 DBRefUtils.ensurePrimaries(this);
1315 public DBRefEntry[] getDBRefs()
1317 if (dbrefs == null && datasetSequence != null
1318 && this != datasetSequence)
1320 return datasetSequence.getDBRefs();
1326 public void addDBRef(DBRefEntry entry)
1328 if (datasetSequence != null)
1330 datasetSequence.addDBRef(entry);
1336 dbrefs = new DBRefEntry[0];
1339 for (DBRefEntryI dbr : dbrefs)
1341 if (dbr.updateFrom(entry))
1344 * found a dbref that either matched, or could be
1345 * updated from, the new entry - no need to add it
1352 * extend the array to make room for one more
1354 // TODO use an ArrayList instead
1355 int j = dbrefs.length;
1356 DBRefEntry[] temp = new DBRefEntry[j + 1];
1357 System.arraycopy(dbrefs, 0, temp, 0, j);
1358 temp[temp.length - 1] = entry;
1362 DBRefUtils.ensurePrimaries(this);
1366 public void setDatasetSequence(SequenceI seq)
1370 throw new IllegalArgumentException(
1371 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1373 if (seq != null && seq.getDatasetSequence() != null)
1375 throw new IllegalArgumentException(
1376 "Implementation error: cascading dataset sequences are not allowed.");
1378 datasetSequence = seq;
1382 public SequenceI getDatasetSequence()
1384 return datasetSequence;
1388 public AlignmentAnnotation[] getAnnotation()
1390 return annotation == null ? null
1392 .toArray(new AlignmentAnnotation[annotation.size()]);
1396 public boolean hasAnnotation(AlignmentAnnotation ann)
1398 return annotation == null ? false : annotation.contains(ann);
1402 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1404 if (this.annotation == null)
1406 this.annotation = new Vector<AlignmentAnnotation>();
1408 if (!this.annotation.contains(annotation))
1410 this.annotation.addElement(annotation);
1412 annotation.setSequenceRef(this);
1416 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1418 if (this.annotation != null)
1420 this.annotation.removeElement(annotation);
1421 if (this.annotation.size() == 0)
1423 this.annotation = null;
1429 * test if this is a valid candidate for another sequence's dataset sequence.
1432 private boolean isValidDatasetSequence()
1434 if (datasetSequence != null)
1438 for (int i = 0; i < sequence.length; i++)
1440 if (jalview.util.Comparison.isGap(sequence[i]))
1449 public SequenceI deriveSequence()
1451 Sequence seq = null;
1452 if (datasetSequence == null)
1454 if (isValidDatasetSequence())
1456 // Use this as dataset sequence
1457 seq = new Sequence(getName(), "", 1, -1);
1458 seq.setDatasetSequence(this);
1459 seq.initSeqFrom(this, getAnnotation());
1464 // Create a new, valid dataset sequence
1465 createDatasetSequence();
1468 return new Sequence(this);
1471 private boolean _isNa;
1473 private int _seqhash = 0;
1476 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1480 public boolean isProtein()
1482 if (datasetSequence != null)
1484 return datasetSequence.isProtein();
1486 if (_seqhash != sequence.hashCode())
1488 _seqhash = sequence.hashCode();
1489 _isNa = Comparison.isNucleotide(this);
1497 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1500 public SequenceI createDatasetSequence()
1502 if (datasetSequence == null)
1504 Sequence dsseq = new Sequence(getName(),
1505 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1506 getSequenceAsString()),
1507 getStart(), getEnd());
1509 datasetSequence = dsseq;
1511 dsseq.setDescription(description);
1512 // move features and database references onto dataset sequence
1513 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1514 sequenceFeatureStore = null;
1515 dsseq.dbrefs = dbrefs;
1517 // TODO: search and replace any references to this sequence with
1518 // references to the dataset sequence in Mappings on dbref
1519 dsseq.pdbIds = pdbIds;
1521 datasetSequence.updatePDBIds();
1522 if (annotation != null)
1524 // annotation is cloned rather than moved, to preserve what's currently
1526 for (AlignmentAnnotation aa : annotation)
1528 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1529 _aa.sequenceRef = datasetSequence;
1530 _aa.adjustForAlignment(); // uses annotation's own record of
1531 // sequence-column mapping
1532 datasetSequence.addAlignmentAnnotation(_aa);
1536 return datasetSequence;
1543 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1547 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1549 if (annotation != null)
1551 annotation.removeAllElements();
1553 if (annotations != null)
1555 for (int i = 0; i < annotations.length; i++)
1557 if (annotations[i] != null)
1559 addAlignmentAnnotation(annotations[i]);
1566 public AlignmentAnnotation[] getAnnotation(String label)
1568 if (annotation == null || annotation.size() == 0)
1573 Vector<AlignmentAnnotation> subset = new Vector<AlignmentAnnotation>();
1574 Enumeration<AlignmentAnnotation> e = annotation.elements();
1575 while (e.hasMoreElements())
1577 AlignmentAnnotation ann = e.nextElement();
1578 if (ann.label != null && ann.label.equals(label))
1580 subset.addElement(ann);
1583 if (subset.size() == 0)
1587 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1589 e = subset.elements();
1590 while (e.hasMoreElements())
1592 anns[i++] = e.nextElement();
1594 subset.removeAllElements();
1599 public boolean updatePDBIds()
1601 if (datasetSequence != null)
1603 // TODO: could merge DBRefs
1604 return datasetSequence.updatePDBIds();
1606 if (dbrefs == null || dbrefs.length == 0)
1610 boolean added = false;
1611 for (DBRefEntry dbr : dbrefs)
1613 if (DBRefSource.PDB.equals(dbr.getSource()))
1616 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1617 * PDB id is not already present in a 'matching' PDBEntry
1618 * Constructor parses out a chain code if appended to the accession id
1619 * (a fudge used to 'store' the chain code in the DBRef)
1621 PDBEntry pdbe = new PDBEntry(dbr);
1622 added |= addPDBId(pdbe);
1629 public void transferAnnotation(SequenceI entry, Mapping mp)
1631 if (datasetSequence != null)
1633 datasetSequence.transferAnnotation(entry, mp);
1636 if (entry.getDatasetSequence() != null)
1638 transferAnnotation(entry.getDatasetSequence(), mp);
1641 // transfer any new features from entry onto sequence
1642 if (entry.getSequenceFeatures() != null)
1645 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1646 for (SequenceFeature feature : sfs)
1648 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1649 : new SequenceFeature[] { new SequenceFeature(feature) };
1652 for (int sfi = 0; sfi < sf.length; sfi++)
1654 addSequenceFeature(sf[sfi]);
1660 // transfer PDB entries
1661 if (entry.getAllPDBEntries() != null)
1663 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1664 while (e.hasMoreElements())
1666 PDBEntry pdb = e.nextElement();
1670 // transfer database references
1671 DBRefEntry[] entryRefs = entry.getDBRefs();
1672 if (entryRefs != null)
1674 for (int r = 0; r < entryRefs.length; r++)
1676 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1677 if (newref.getMap() != null && mp != null)
1679 // remap ref using our local mapping
1681 // we also assume all version string setting is done by dbSourceProxy
1683 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1684 * newref.setSource(dbSource); }
1692 public void setRNA(RNA r)
1704 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1707 List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1708 if (this.annotation != null)
1710 for (AlignmentAnnotation ann : annotation)
1712 if (ann.calcId != null && ann.calcId.equals(calcId)
1713 && ann.label != null && ann.label.equals(label))
1723 public String toString()
1725 return getDisplayId(false);
1729 public PDBEntry getPDBEntry(String pdbIdStr)
1731 if (getDatasetSequence() != null)
1733 return getDatasetSequence().getPDBEntry(pdbIdStr);
1739 List<PDBEntry> entries = getAllPDBEntries();
1740 for (PDBEntry entry : entries)
1742 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1751 public List<DBRefEntry> getPrimaryDBRefs()
1753 if (datasetSequence != null)
1755 return datasetSequence.getPrimaryDBRefs();
1757 if (dbrefs == null || dbrefs.length == 0)
1759 return Collections.emptyList();
1761 synchronized (dbrefs)
1763 List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1764 DBRefEntry[] tmp = new DBRefEntry[1];
1765 for (DBRefEntry ref : dbrefs)
1767 if (!ref.isPrimaryCandidate())
1773 MapList mp = ref.getMap().getMap();
1774 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1776 // map only involves a subsequence, so cannot be primary
1780 // whilst it looks like it is a primary ref, we also sanity check type
1781 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1782 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1784 // PDB dbrefs imply there should be a PDBEntry associated
1785 // TODO: tighten PDB dbrefs
1786 // formally imply Jalview has actually downloaded and
1787 // parsed the pdb file. That means there should be a cached file
1788 // handle on the PDBEntry, and a real mapping between sequence and
1789 // extracted sequence from PDB file
1790 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1791 if (pdbentry != null && pdbentry.getFile() != null)
1797 // check standard protein or dna sources
1799 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1800 if (res != null && res[0] == tmp[0])
1814 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1817 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1818 int endPos = fromColumn == toColumn ? startPos
1819 : findPosition(toColumn - 1);
1821 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1823 if (datasetSequence != null)
1825 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1830 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1834 * if end column is gapped, endPos may be to the right,
1835 * and we may have included adjacent or enclosing features;
1836 * remove any that are not enclosing, non-contact features
1838 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1839 && Comparison.isGap(sequence[toColumn - 1]);
1840 if (endPos > this.end || endColumnIsGapped)
1842 ListIterator<SequenceFeature> it = result.listIterator();
1843 while (it.hasNext())
1845 SequenceFeature sf = it.next();
1846 int sfBegin = sf.getBegin();
1847 int sfEnd = sf.getEnd();
1848 int featureStartColumn = findIndex(sfBegin);
1849 if (featureStartColumn > toColumn)
1853 else if (featureStartColumn < fromColumn)
1855 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1857 if (featureEndColumn < fromColumn)
1861 else if (featureEndColumn > toColumn && sf.isContactFeature())
1864 * remove an enclosing feature if it is a contact feature
1876 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1877 * token that has to match the one presented by the cursor
1880 public void sequenceChanged()
1889 public int replace(char c1, char c2)
1896 synchronized (sequence)
1898 for (int c = 0; c < sequence.length; c++)
1900 if (sequence[c] == c1)