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.
50 public class Sequence extends ASequence implements SequenceI
52 SequenceI datasetSequence;
56 private char[] sequence;
64 Vector<PDBEntry> pdbIds;
73 * This annotation is displayed below the alignment but the positions are tied
74 * to the residues of this sequence
76 * TODO: change to List<>
78 Vector<AlignmentAnnotation> annotation;
81 * The index of the sequence in a MSA
85 private SequenceFeaturesI sequenceFeatureStore;
88 * A cursor holding the approximate current view position to the sequence,
89 * as determined by findIndex or findPosition or findPositions.
90 * Using a cursor as a hint allows these methods to be more performant for
93 private SequenceCursor cursor;
96 * A number that should be incremented whenever the sequence is edited.
97 * If the value matches the cursor token, then we can trust the cursor,
98 * if not then it should be recomputed.
100 private int changeCount;
103 * Creates a new Sequence object.
106 * display name string
108 * string to form a possibly gapped sequence out of
110 * first position of non-gap residue in the sequence
112 * last position of ungapped residues (nearly always only used for
115 public Sequence(String name, String sequence, int start, int end)
118 initSeqAndName(name, sequence.toCharArray(), start, end);
121 public Sequence(String name, char[] sequence, int start, int end)
124 initSeqAndName(name, sequence, start, end);
128 * Stage 1 constructor - assign name, sequence, and set start and end fields.
129 * start and end are updated values from name2 if it ends with /start-end
136 protected void initSeqAndName(String name2, char[] sequence2, int start2,
140 this.sequence = sequence2;
148 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
149 * start and end respectively and removes the suffix from the name
156 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
159 int slashPos = name.lastIndexOf('/');
160 if (slashPos > -1 && slashPos < name.length() - 1)
162 String suffix = name.substring(slashPos + 1);
163 String[] range = suffix.split("-");
164 if (range.length == 2)
168 int from = Integer.valueOf(range[0]);
169 int to = Integer.valueOf(range[1]);
170 if (from > 0 && to >= from)
172 name = name.substring(0, slashPos);
177 } catch (NumberFormatException e)
179 // leave name unchanged if suffix is invalid
186 * Ensures that 'end' is not before the end of the sequence, that is,
187 * (end-start+1) is at least as long as the count of ungapped positions. Note
188 * that end is permitted to be beyond the end of the sequence data.
190 void checkValidRange()
193 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
196 for (int j = 0; j < sequence.length; j++)
198 if (!Comparison.isGap(sequence[j]))
217 * default constructor
221 sequenceFeatureStore = new SequenceFeatures();
225 * Creates a new Sequence object.
232 public Sequence(String name, String sequence)
234 this(name, sequence, 1, -1);
238 * Creates a new Sequence object with new AlignmentAnnotations but inherits
239 * any existing dataset sequence reference. If non exists, everything is
243 * if seq is a dataset sequence, behaves like a plain old copy
246 public Sequence(SequenceI seq)
248 this(seq, seq.getAnnotation());
252 * Create a new sequence object with new features, DBRefEntries, and PDBIds
253 * but inherits any existing dataset sequence reference, and duplicate of any
254 * annotation that is present in the given annotation array.
257 * the sequence to be copied
258 * @param alAnnotation
259 * an array of annotation including some associated with seq
261 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
264 initSeqFrom(seq, alAnnotation);
268 * does the heavy lifting when cloning a dataset sequence, or coping data from
269 * dataset to a new derived sequence.
272 * - source of attributes.
273 * @param alAnnotation
274 * - alignment annotation present on seq that should be copied onto
277 protected void initSeqFrom(SequenceI seq,
278 AlignmentAnnotation[] alAnnotation)
280 char[] oseq = seq.getSequence(); // returns a copy of the array
281 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
283 description = seq.getDescription();
284 if (seq != datasetSequence)
286 setDatasetSequence(seq.getDatasetSequence());
290 * only copy DBRefs and seqfeatures if we really are a dataset sequence
292 if (datasetSequence == null)
294 if (seq.getDBRefs() != null)
296 DBRefEntry[] dbr = seq.getDBRefs();
297 for (int i = 0; i < dbr.length; i++)
299 addDBRef(new DBRefEntry(dbr[i]));
304 * make copies of any sequence features
306 for (SequenceFeature sf : seq.getSequenceFeatures())
308 addSequenceFeature(new SequenceFeature(sf));
312 if (seq.getAnnotation() != null)
314 AlignmentAnnotation[] sqann = seq.getAnnotation();
315 for (int i = 0; i < sqann.length; i++)
317 if (sqann[i] == null)
321 boolean found = (alAnnotation == null);
324 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
326 found = (alAnnotation[apos] == sqann[i]);
331 // only copy the given annotation
332 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
333 addAlignmentAnnotation(newann);
337 if (seq.getAllPDBEntries() != null)
339 Vector<PDBEntry> ids = seq.getAllPDBEntries();
340 for (PDBEntry pdb : ids)
342 this.addPDBId(new PDBEntry(pdb));
348 public void setSequenceFeatures(List<SequenceFeature> features)
350 if (datasetSequence != null)
352 datasetSequence.setSequenceFeatures(features);
355 sequenceFeatureStore = new SequenceFeatures(features);
359 public synchronized boolean addSequenceFeature(SequenceFeature sf)
361 if (sf.getType() == null)
363 System.err.println("SequenceFeature type may not be null: "
368 if (datasetSequence != null)
370 return datasetSequence.addSequenceFeature(sf);
373 return sequenceFeatureStore.add(sf);
377 public void deleteFeature(SequenceFeature sf)
379 if (datasetSequence != null)
381 datasetSequence.deleteFeature(sf);
385 sequenceFeatureStore.delete(sf);
395 public List<SequenceFeature> getSequenceFeatures()
397 if (datasetSequence != null)
399 return datasetSequence.getSequenceFeatures();
401 return sequenceFeatureStore.getAllFeatures();
405 public SequenceFeaturesI getFeatures()
407 return datasetSequence != null ? datasetSequence.getFeatures()
408 : sequenceFeatureStore;
412 public boolean addPDBId(PDBEntry entry)
416 pdbIds = new Vector<>();
421 for (PDBEntry pdbe : pdbIds)
423 if (pdbe.updateFrom(entry))
428 pdbIds.addElement(entry);
439 public void setPDBId(Vector<PDBEntry> id)
447 * @return DOCUMENT ME!
450 public Vector<PDBEntry> getAllPDBEntries()
452 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
458 * @return DOCUMENT ME!
461 public String getDisplayId(boolean jvsuffix)
463 StringBuffer result = new StringBuffer(name);
466 result.append("/" + start + "-" + end);
469 return result.toString();
473 * Sets the sequence name. If the name ends in /start-end, then the start-end
474 * values are parsed out and set, and the suffix is removed from the name.
479 public void setName(String theName)
488 * @return DOCUMENT ME!
491 public String getName()
503 public void setStart(int start)
511 * @return DOCUMENT ME!
514 public int getStart()
526 public void setEnd(int end)
534 * @return DOCUMENT ME!
545 * @return DOCUMENT ME!
548 public int getLength()
550 return this.sequence.length;
560 public void setSequence(String seq)
562 this.sequence = seq.toCharArray();
568 public String getSequenceAsString()
570 return new String(sequence);
574 public String getSequenceAsString(int start, int end)
576 return new String(getSequence(start, end));
580 public char[] getSequence()
583 return sequence == null ? null : Arrays.copyOf(sequence,
590 * @see jalview.datamodel.SequenceI#getSequence(int, int)
593 public char[] getSequence(int start, int end)
599 // JBPNote - left to user to pad the result here (TODO:Decide on this
601 if (start >= sequence.length)
606 if (end >= sequence.length)
608 end = sequence.length;
611 char[] reply = new char[end - start];
612 System.arraycopy(sequence, start, reply, 0, end - start);
618 public SequenceI getSubSequence(int start, int end)
624 char[] seq = getSequence(start, end);
629 int nstart = findPosition(start);
630 int nend = findPosition(end) - 1;
631 // JBPNote - this is an incomplete copy.
632 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
633 nseq.setDescription(description);
634 if (datasetSequence != null)
636 nseq.setDatasetSequence(datasetSequence);
640 nseq.setDatasetSequence(this);
646 * Returns the character of the aligned sequence at the given position (base
647 * zero), or space if the position is not within the sequence's bounds
652 public char getCharAt(int i)
654 if (i >= 0 && i < sequence.length)
671 public void setDescription(String desc)
673 this.description = desc;
679 * @return DOCUMENT ME!
682 public String getDescription()
684 return this.description;
691 public int findIndex(int pos)
694 * use a valid, hopefully nearby, cursor if available
696 if (isValidCursor(cursor))
698 return findIndex(pos, cursor);
706 * traverse sequence from the start counting gaps; make a note of
707 * the column of the first residue to save in the cursor
709 while ((i < sequence.length) && (j <= end) && (j <= pos))
711 if (!Comparison.isGap(sequence[i]))
722 if (j == end && j < pos)
727 updateCursor(pos, i, startColumn);
732 * Updates the cursor to the latest found residue and column position
739 * column position of the first sequence residue
741 protected void updateCursor(int residuePos, int column, int startColumn)
744 * preserve end residue column provided cursor was valid
746 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
747 if (residuePos == this.end)
752 cursor = new SequenceCursor(this, residuePos, column, startColumn,
753 endColumn, this.changeCount);
757 * Answers the aligned column position (1..) for the given residue position
758 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
759 * The hint may be left of, at, or to the right of the required position.
765 protected int findIndex(int pos, SequenceCursor curs)
767 if (!isValidCursor(curs))
770 * wrong or invalidated cursor, compute de novo
772 return findIndex(pos);
775 if (curs.residuePosition == pos)
777 return curs.columnPosition;
781 * move left or right to find pos from hint.position
783 int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
785 int newPos = curs.residuePosition;
786 int delta = newPos > pos ? -1 : 1;
788 while (newPos != pos)
790 col += delta; // shift one column left or right
791 if (col < 0 || col == sequence.length)
795 if (!Comparison.isGap(sequence[col]))
801 col++; // convert back to base 1
802 updateCursor(pos, col, curs.firstColumnPosition);
811 public int findPosition(final int column)
814 * use a valid, hopefully nearby, cursor if available
816 if (isValidCursor(cursor))
818 return findPosition(column + 1, cursor);
821 // TODO recode this more naturally i.e. count residues only
822 // as they are found, not 'in anticipation'
825 * traverse the sequence counting gaps; note the column position
826 * of the first residue, to save in the cursor
828 int firstResidueColumn = 0;
829 int lastPosFound = 0;
830 int lastPosFoundColumn = 0;
831 int seqlen = sequence.length;
833 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
835 lastPosFound = start;
836 lastPosFoundColumn = 0;
842 while (j < column && j < seqlen)
844 if (!Comparison.isGap(sequence[j]))
847 lastPosFoundColumn = j;
848 if (pos == this.start)
850 firstResidueColumn = j;
856 if (j < seqlen && !Comparison.isGap(sequence[j]))
859 lastPosFoundColumn = j;
860 if (pos == this.start)
862 firstResidueColumn = j;
867 * update the cursor to the last residue position found (if any)
868 * (converting column position to base 1)
870 if (lastPosFound != 0)
872 updateCursor(lastPosFound, lastPosFoundColumn + 1,
873 firstResidueColumn + 1);
880 * Answers true if the given cursor is not null, is for this sequence object,
881 * and has a token value that matches this object's changeCount, else false.
882 * This allows us to ignore a cursor as 'stale' if the sequence has been
883 * modified since the cursor was created.
888 protected boolean isValidCursor(SequenceCursor curs)
890 if (curs == null || curs.sequence != this || curs.token != changeCount)
895 * sanity check against range
897 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
901 if (curs.residuePosition < start || curs.residuePosition > end)
909 * Answers the sequence position (start..) for the given aligned column
910 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
911 * may lie left of, at, or to the right of the column position.
917 protected int findPosition(final int col, SequenceCursor curs)
919 if (!isValidCursor(curs))
922 * wrong or invalidated cursor, compute de novo
924 return findPosition(col - 1);// ugh back to base 0
927 if (curs.columnPosition == col)
929 cursor = curs; // in case this method becomes public
930 return curs.residuePosition; // easy case :-)
933 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
936 * sequence lies entirely to the left of col
937 * - return last residue + 1
942 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
945 * sequence lies entirely to the right of col
946 * - return first residue
951 // todo could choose closest to col out of column,
952 // firstColumnPosition, lastColumnPosition as a start point
955 * move left or right to find pos from cursor position
957 int firstResidueColumn = curs.firstColumnPosition;
958 int column = curs.columnPosition - 1; // to base 0
959 int newPos = curs.residuePosition;
960 int delta = curs.columnPosition > col ? -1 : 1;
961 boolean gapped = false;
962 int lastFoundPosition = curs.residuePosition;
963 int lastFoundPositionColumn = curs.columnPosition;
965 while (column != col - 1)
967 column += delta; // shift one column left or right
968 if (column < 0 || column == sequence.length)
972 gapped = Comparison.isGap(sequence[column]);
976 lastFoundPosition = newPos;
977 lastFoundPositionColumn = column + 1;
978 if (lastFoundPosition == this.start)
980 firstResidueColumn = column + 1;
985 if (cursor == null || lastFoundPosition != cursor.residuePosition)
987 updateCursor(lastFoundPosition, lastFoundPositionColumn,
992 * hack to give position to the right if on a gap
993 * or beyond the length of the sequence (see JAL-2562)
995 if (delta > 0 && (gapped || column >= sequence.length))
1007 public Range findPositions(int fromColumn, int toColumn)
1009 if (toColumn < fromColumn || fromColumn < 1)
1015 * find the first non-gapped position, if any
1017 int firstPosition = 0;
1018 int col = fromColumn - 1;
1019 int length = sequence.length;
1020 while (col < length && col < toColumn)
1022 if (!Comparison.isGap(sequence[col]))
1024 firstPosition = findPosition(col++);
1030 if (firstPosition == 0)
1036 * find the last non-gapped position
1038 int lastPosition = firstPosition;
1039 while (col < length && col < toColumn)
1041 if (!Comparison.isGap(sequence[col++]))
1047 return new Range(firstPosition, lastPosition);
1051 * Returns an int array where indices correspond to each residue in the
1052 * sequence and the element value gives its position in the alignment
1054 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1055 * residues in SequenceI object
1058 public int[] gapMap()
1060 String seq = jalview.analysis.AlignSeq.extractGaps(
1061 jalview.util.Comparison.GapChars, new String(sequence));
1062 int[] map = new int[seq.length()];
1066 while (j < sequence.length)
1068 if (!jalview.util.Comparison.isGap(sequence[j]))
1080 * Build a bitset corresponding to sequence gaps
1082 * @return a BitSet where set values correspond to gaps in the sequence
1085 public BitSet gapBitset()
1087 BitSet gaps = new BitSet(sequence.length);
1089 while (j < sequence.length)
1091 if (jalview.util.Comparison.isGap(sequence[j]))
1101 public int[] findPositionMap()
1103 int map[] = new int[sequence.length];
1106 int seqlen = sequence.length;
1107 while ((j < seqlen))
1110 if (!jalview.util.Comparison.isGap(sequence[j]))
1121 public List<int[]> getInsertions()
1123 ArrayList<int[]> map = new ArrayList<>();
1124 int lastj = -1, j = 0;
1126 int seqlen = sequence.length;
1127 while ((j < seqlen))
1129 if (jalview.util.Comparison.isGap(sequence[j]))
1140 map.add(new int[] { lastj, j - 1 });
1148 map.add(new int[] { lastj, j - 1 });
1155 public BitSet getInsertionsAsBits()
1157 BitSet map = new BitSet();
1158 int lastj = -1, j = 0;
1160 int seqlen = sequence.length;
1161 while ((j < seqlen))
1163 if (jalview.util.Comparison.isGap(sequence[j]))
1189 public void deleteChars(int i, int j)
1191 int newstart = start, newend = end;
1192 if (i >= sequence.length || i < 0)
1197 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1198 boolean createNewDs = false;
1199 // TODO: take a (second look) at the dataset creation validation method for
1200 // the very large sequence case
1201 int eindex = -1, sindex = -1;
1202 boolean ecalc = false, scalc = false;
1203 for (int s = i; s < j; s++)
1205 if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
1215 sindex = findIndex(start) - 1;
1220 // delete characters including start of sequence
1221 newstart = findPosition(j);
1222 break; // don't need to search for any more residue characters.
1226 // delete characters after start.
1229 eindex = findIndex(end) - 1;
1234 // delete characters at end of sequence
1235 newend = findPosition(i - 1);
1236 break; // don't need to search for any more residue characters.
1241 newend--; // decrease end position by one for the deleted residue
1242 // and search further
1248 // deletion occured in the middle of the sequence
1249 if (createNewDs && this.datasetSequence != null)
1251 // construct a new sequence
1252 Sequence ds = new Sequence(datasetSequence);
1253 // TODO: remove any non-inheritable properties ?
1254 // TODO: create a sequence mapping (since there is a relation here ?)
1255 ds.deleteChars(i, j);
1256 datasetSequence = ds;
1265 public void insertCharAt(int i, int length, char c)
1267 char[] tmp = new char[sequence.length + length];
1269 if (i >= sequence.length)
1271 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1272 i = sequence.length;
1276 System.arraycopy(sequence, 0, tmp, 0, i);
1286 if (i < sequence.length)
1288 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1296 public void insertCharAt(int i, char c)
1298 insertCharAt(i, 1, c);
1302 public String getVamsasId()
1308 public void setVamsasId(String id)
1314 public void setDBRefs(DBRefEntry[] dbref)
1316 if (dbrefs == null && datasetSequence != null
1317 && this != datasetSequence)
1319 datasetSequence.setDBRefs(dbref);
1325 DBRefUtils.ensurePrimaries(this);
1330 public DBRefEntry[] getDBRefs()
1332 if (dbrefs == null && datasetSequence != null
1333 && this != datasetSequence)
1335 return datasetSequence.getDBRefs();
1341 public void addDBRef(DBRefEntry entry)
1343 if (datasetSequence != null)
1345 datasetSequence.addDBRef(entry);
1351 dbrefs = new DBRefEntry[0];
1354 for (DBRefEntryI dbr : dbrefs)
1356 if (dbr.updateFrom(entry))
1359 * found a dbref that either matched, or could be
1360 * updated from, the new entry - no need to add it
1367 * extend the array to make room for one more
1369 // TODO use an ArrayList instead
1370 int j = dbrefs.length;
1371 DBRefEntry[] temp = new DBRefEntry[j + 1];
1372 System.arraycopy(dbrefs, 0, temp, 0, j);
1373 temp[temp.length - 1] = entry;
1377 DBRefUtils.ensurePrimaries(this);
1381 public void setDatasetSequence(SequenceI seq)
1385 throw new IllegalArgumentException(
1386 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1388 if (seq != null && seq.getDatasetSequence() != null)
1390 throw new IllegalArgumentException(
1391 "Implementation error: cascading dataset sequences are not allowed.");
1393 datasetSequence = seq;
1397 public SequenceI getDatasetSequence()
1399 return datasetSequence;
1403 public AlignmentAnnotation[] getAnnotation()
1405 return annotation == null ? null
1407 .toArray(new AlignmentAnnotation[annotation.size()]);
1411 public boolean hasAnnotation(AlignmentAnnotation ann)
1413 return annotation == null ? false : annotation.contains(ann);
1417 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1419 if (this.annotation == null)
1421 this.annotation = new Vector<>();
1423 if (!this.annotation.contains(annotation))
1425 this.annotation.addElement(annotation);
1427 annotation.setSequenceRef(this);
1431 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1433 if (this.annotation != null)
1435 this.annotation.removeElement(annotation);
1436 if (this.annotation.size() == 0)
1438 this.annotation = null;
1444 * test if this is a valid candidate for another sequence's dataset sequence.
1447 private boolean isValidDatasetSequence()
1449 if (datasetSequence != null)
1453 for (int i = 0; i < sequence.length; i++)
1455 if (jalview.util.Comparison.isGap(sequence[i]))
1464 public SequenceI deriveSequence()
1466 Sequence seq = null;
1467 if (datasetSequence == null)
1469 if (isValidDatasetSequence())
1471 // Use this as dataset sequence
1472 seq = new Sequence(getName(), "", 1, -1);
1473 seq.setDatasetSequence(this);
1474 seq.initSeqFrom(this, getAnnotation());
1479 // Create a new, valid dataset sequence
1480 createDatasetSequence();
1483 return new Sequence(this);
1486 private boolean _isNa;
1488 private int _seqhash = 0;
1491 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1495 public boolean isProtein()
1497 if (datasetSequence != null)
1499 return datasetSequence.isProtein();
1501 if (_seqhash != sequence.hashCode())
1503 _seqhash = sequence.hashCode();
1504 _isNa = Comparison.isNucleotide(this);
1512 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1515 public SequenceI createDatasetSequence()
1517 if (datasetSequence == null)
1519 Sequence dsseq = new Sequence(getName(),
1520 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1521 getSequenceAsString()),
1522 getStart(), getEnd());
1524 datasetSequence = dsseq;
1526 dsseq.setDescription(description);
1527 // move features and database references onto dataset sequence
1528 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1529 sequenceFeatureStore = null;
1530 dsseq.dbrefs = dbrefs;
1532 // TODO: search and replace any references to this sequence with
1533 // references to the dataset sequence in Mappings on dbref
1534 dsseq.pdbIds = pdbIds;
1536 datasetSequence.updatePDBIds();
1537 if (annotation != null)
1539 // annotation is cloned rather than moved, to preserve what's currently
1541 for (AlignmentAnnotation aa : annotation)
1543 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1544 _aa.sequenceRef = datasetSequence;
1545 _aa.adjustForAlignment(); // uses annotation's own record of
1546 // sequence-column mapping
1547 datasetSequence.addAlignmentAnnotation(_aa);
1551 return datasetSequence;
1558 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1562 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1564 if (annotation != null)
1566 annotation.removeAllElements();
1568 if (annotations != null)
1570 for (int i = 0; i < annotations.length; i++)
1572 if (annotations[i] != null)
1574 addAlignmentAnnotation(annotations[i]);
1581 public AlignmentAnnotation[] getAnnotation(String label)
1583 if (annotation == null || annotation.size() == 0)
1588 Vector<AlignmentAnnotation> subset = new Vector<>();
1589 Enumeration<AlignmentAnnotation> e = annotation.elements();
1590 while (e.hasMoreElements())
1592 AlignmentAnnotation ann = e.nextElement();
1593 if (ann.label != null && ann.label.equals(label))
1595 subset.addElement(ann);
1598 if (subset.size() == 0)
1602 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1604 e = subset.elements();
1605 while (e.hasMoreElements())
1607 anns[i++] = e.nextElement();
1609 subset.removeAllElements();
1614 public boolean updatePDBIds()
1616 if (datasetSequence != null)
1618 // TODO: could merge DBRefs
1619 return datasetSequence.updatePDBIds();
1621 if (dbrefs == null || dbrefs.length == 0)
1625 boolean added = false;
1626 for (DBRefEntry dbr : dbrefs)
1628 if (DBRefSource.PDB.equals(dbr.getSource()))
1631 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1632 * PDB id is not already present in a 'matching' PDBEntry
1633 * Constructor parses out a chain code if appended to the accession id
1634 * (a fudge used to 'store' the chain code in the DBRef)
1636 PDBEntry pdbe = new PDBEntry(dbr);
1637 added |= addPDBId(pdbe);
1644 public void transferAnnotation(SequenceI entry, Mapping mp)
1646 if (datasetSequence != null)
1648 datasetSequence.transferAnnotation(entry, mp);
1651 if (entry.getDatasetSequence() != null)
1653 transferAnnotation(entry.getDatasetSequence(), mp);
1656 // transfer any new features from entry onto sequence
1657 if (entry.getSequenceFeatures() != null)
1660 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1661 for (SequenceFeature feature : sfs)
1663 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1664 : new SequenceFeature[] { new SequenceFeature(feature) };
1667 for (int sfi = 0; sfi < sf.length; sfi++)
1669 addSequenceFeature(sf[sfi]);
1675 // transfer PDB entries
1676 if (entry.getAllPDBEntries() != null)
1678 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1679 while (e.hasMoreElements())
1681 PDBEntry pdb = e.nextElement();
1685 // transfer database references
1686 DBRefEntry[] entryRefs = entry.getDBRefs();
1687 if (entryRefs != null)
1689 for (int r = 0; r < entryRefs.length; r++)
1691 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1692 if (newref.getMap() != null && mp != null)
1694 // remap ref using our local mapping
1696 // we also assume all version string setting is done by dbSourceProxy
1698 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1699 * newref.setSource(dbSource); }
1707 * @return The index (zero-based) on this sequence in the MSA. It returns
1708 * {@code -1} if this information is not available.
1711 public int getIndex()
1717 * Defines the position of this sequence in the MSA. Use the value {@code -1}
1718 * if this information is undefined.
1721 * position for this sequence. This value is zero-based (zero for
1722 * this first sequence)
1725 public void setIndex(int value)
1731 public void setRNA(RNA r)
1743 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1746 List<AlignmentAnnotation> result = new ArrayList<>();
1747 if (this.annotation != null)
1749 for (AlignmentAnnotation ann : annotation)
1751 if (ann.calcId != null && ann.calcId.equals(calcId)
1752 && ann.label != null && ann.label.equals(label))
1762 public String toString()
1764 return getDisplayId(false);
1768 public PDBEntry getPDBEntry(String pdbIdStr)
1770 if (getDatasetSequence() != null)
1772 return getDatasetSequence().getPDBEntry(pdbIdStr);
1778 List<PDBEntry> entries = getAllPDBEntries();
1779 for (PDBEntry entry : entries)
1781 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1790 public List<DBRefEntry> getPrimaryDBRefs()
1792 if (datasetSequence != null)
1794 return datasetSequence.getPrimaryDBRefs();
1796 if (dbrefs == null || dbrefs.length == 0)
1798 return Collections.emptyList();
1800 synchronized (dbrefs)
1802 List<DBRefEntry> primaries = new ArrayList<>();
1803 DBRefEntry[] tmp = new DBRefEntry[1];
1804 for (DBRefEntry ref : dbrefs)
1806 if (!ref.isPrimaryCandidate())
1812 MapList mp = ref.getMap().getMap();
1813 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1815 // map only involves a subsequence, so cannot be primary
1819 // whilst it looks like it is a primary ref, we also sanity check type
1820 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1821 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1823 // PDB dbrefs imply there should be a PDBEntry associated
1824 // TODO: tighten PDB dbrefs
1825 // formally imply Jalview has actually downloaded and
1826 // parsed the pdb file. That means there should be a cached file
1827 // handle on the PDBEntry, and a real mapping between sequence and
1828 // extracted sequence from PDB file
1829 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1830 if (pdbentry != null && pdbentry.getFile() != null)
1836 // check standard protein or dna sources
1838 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1839 if (res != null && res[0] == tmp[0])
1853 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1856 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1857 int endPos = fromColumn == toColumn ? startPos
1858 : findPosition(toColumn - 1);
1860 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1864 * if end column is gapped, endPos may be to the right,
1865 * and we may have included adjacent or enclosing features;
1866 * remove any that are not enclosing, non-contact features
1868 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1869 && Comparison.isGap(sequence[toColumn - 1]);
1870 if (endPos > this.end || endColumnIsGapped)
1872 ListIterator<SequenceFeature> it = result.listIterator();
1873 while (it.hasNext())
1875 SequenceFeature sf = it.next();
1876 int sfBegin = sf.getBegin();
1877 int sfEnd = sf.getEnd();
1878 int featureStartColumn = findIndex(sfBegin);
1879 if (featureStartColumn > toColumn)
1883 else if (featureStartColumn < fromColumn)
1885 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1887 if (featureEndColumn < fromColumn)
1891 else if (featureEndColumn > toColumn && sf.isContactFeature())
1894 * remove an enclosing feature if it is a contact feature
1906 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1907 * token that has to match the one presented by the cursor
1910 public void sequenceChanged()
1919 public int replace(char c1, char c2)
1926 synchronized (sequence)
1928 for (int c = 0; c < sequence.length; c++)
1930 if (sequence[c] == c1)