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.Iterator;
38 import java.util.List;
39 import java.util.ListIterator;
40 import java.util.Vector;
42 import fr.orsay.lri.varna.models.rna.RNA;
46 * Implements the SequenceI interface for a char[] based sequence object
48 public class Sequence extends ASequence implements SequenceI
50 SequenceI datasetSequence;
54 private char[] sequence;
62 Vector<PDBEntry> pdbIds;
71 * This annotation is displayed below the alignment but the positions are tied
72 * to the residues of this sequence
74 * TODO: change to List<>
76 Vector<AlignmentAnnotation> annotation;
78 private SequenceFeaturesI sequenceFeatureStore;
81 * A cursor holding the approximate current view position to the sequence,
82 * as determined by findIndex or findPosition or findPositions.
83 * Using a cursor as a hint allows these methods to be more performant for
86 private SequenceCursor cursor;
89 * A number that should be incremented whenever the sequence is edited.
90 * If the value matches the cursor token, then we can trust the cursor,
91 * if not then it should be recomputed.
93 private int changeCount;
96 * Creates a new Sequence object.
101 * string to form a possibly gapped sequence out of
103 * first position of non-gap residue in the sequence
105 * last position of ungapped residues (nearly always only used for
108 public Sequence(String name, String sequence, int start, int end)
111 initSeqAndName(name, sequence.toCharArray(), start, end);
114 public Sequence(String name, char[] sequence, int start, int end)
117 initSeqAndName(name, sequence, start, end);
121 * Stage 1 constructor - assign name, sequence, and set start and end fields.
122 * start and end are updated values from name2 if it ends with /start-end
129 protected void initSeqAndName(String name2, char[] sequence2, int start2,
133 this.sequence = sequence2;
141 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
142 * start and end respectively and removes the suffix from the name
149 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
152 int slashPos = name.lastIndexOf('/');
153 if (slashPos > -1 && slashPos < name.length() - 1)
155 String suffix = name.substring(slashPos + 1);
156 String[] range = suffix.split("-");
157 if (range.length == 2)
161 int from = Integer.valueOf(range[0]);
162 int to = Integer.valueOf(range[1]);
163 if (from > 0 && to >= from)
165 name = name.substring(0, slashPos);
170 } catch (NumberFormatException e)
172 // leave name unchanged if suffix is invalid
179 * Ensures that 'end' is not before the end of the sequence, that is,
180 * (end-start+1) is at least as long as the count of ungapped positions. Note
181 * that end is permitted to be beyond the end of the sequence data.
183 void checkValidRange()
186 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
189 for (int j = 0; j < sequence.length; j++)
191 if (!Comparison.isGap(sequence[j]))
210 * default constructor
214 sequenceFeatureStore = new SequenceFeatures();
218 * Creates a new Sequence object.
225 public Sequence(String name, String sequence)
227 this(name, sequence, 1, -1);
231 * Creates a new Sequence object with new AlignmentAnnotations but inherits
232 * any existing dataset sequence reference. If non exists, everything is
236 * if seq is a dataset sequence, behaves like a plain old copy
239 public Sequence(SequenceI seq)
241 this(seq, seq.getAnnotation());
245 * Create a new sequence object with new features, DBRefEntries, and PDBIds
246 * but inherits any existing dataset sequence reference, and duplicate of any
247 * annotation that is present in the given annotation array.
250 * the sequence to be copied
251 * @param alAnnotation
252 * an array of annotation including some associated with seq
254 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
257 initSeqFrom(seq, alAnnotation);
261 * does the heavy lifting when cloning a dataset sequence, or coping data from
262 * dataset to a new derived sequence.
265 * - source of attributes.
266 * @param alAnnotation
267 * - alignment annotation present on seq that should be copied onto
270 protected void initSeqFrom(SequenceI seq,
271 AlignmentAnnotation[] alAnnotation)
273 char[] oseq = seq.getSequence(); // returns a copy of the array
274 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
276 description = seq.getDescription();
277 if (seq != datasetSequence)
279 setDatasetSequence(seq.getDatasetSequence());
283 * only copy DBRefs and seqfeatures if we really are a dataset sequence
285 if (datasetSequence == null)
287 if (seq.getDBRefs() != null)
289 DBRefEntry[] dbr = seq.getDBRefs();
290 for (int i = 0; i < dbr.length; i++)
292 addDBRef(new DBRefEntry(dbr[i]));
297 * make copies of any sequence features
299 for (SequenceFeature sf : seq.getSequenceFeatures())
301 addSequenceFeature(new SequenceFeature(sf));
305 if (seq.getAnnotation() != null)
307 AlignmentAnnotation[] sqann = seq.getAnnotation();
308 for (int i = 0; i < sqann.length; i++)
310 if (sqann[i] == null)
314 boolean found = (alAnnotation == null);
317 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
319 found = (alAnnotation[apos] == sqann[i]);
324 // only copy the given annotation
325 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
326 addAlignmentAnnotation(newann);
330 if (seq.getAllPDBEntries() != null)
332 Vector<PDBEntry> ids = seq.getAllPDBEntries();
333 for (PDBEntry pdb : ids)
335 this.addPDBId(new PDBEntry(pdb));
341 public void setSequenceFeatures(List<SequenceFeature> features)
343 if (datasetSequence != null)
345 datasetSequence.setSequenceFeatures(features);
348 sequenceFeatureStore = new SequenceFeatures(features);
352 public synchronized boolean addSequenceFeature(SequenceFeature sf)
354 if (sf.getType() == null)
356 System.err.println("SequenceFeature type may not be null: "
361 if (datasetSequence != null)
363 return datasetSequence.addSequenceFeature(sf);
366 return sequenceFeatureStore.add(sf);
370 public void deleteFeature(SequenceFeature sf)
372 if (datasetSequence != null)
374 datasetSequence.deleteFeature(sf);
378 sequenceFeatureStore.delete(sf);
388 public List<SequenceFeature> getSequenceFeatures()
390 if (datasetSequence != null)
392 return datasetSequence.getSequenceFeatures();
394 return sequenceFeatureStore.getAllFeatures();
398 public SequenceFeaturesI getFeatures()
400 return datasetSequence != null ? datasetSequence.getFeatures()
401 : sequenceFeatureStore;
405 public boolean addPDBId(PDBEntry entry)
409 pdbIds = new Vector<>();
414 for (PDBEntry pdbe : pdbIds)
416 if (pdbe.updateFrom(entry))
421 pdbIds.addElement(entry);
432 public void setPDBId(Vector<PDBEntry> id)
440 * @return DOCUMENT ME!
443 public Vector<PDBEntry> getAllPDBEntries()
445 return pdbIds == null ? new Vector<>() : pdbIds;
451 * @return DOCUMENT ME!
454 public String getDisplayId(boolean jvsuffix)
456 StringBuffer result = new StringBuffer(name);
459 result.append("/" + start + "-" + end);
462 return result.toString();
466 * Sets the sequence name. If the name ends in /start-end, then the start-end
467 * values are parsed out and set, and the suffix is removed from the name.
472 public void setName(String theName)
481 * @return DOCUMENT ME!
484 public String getName()
496 public void setStart(int start)
504 * @return DOCUMENT ME!
507 public int getStart()
519 public void setEnd(int end)
527 * @return DOCUMENT ME!
538 * @return DOCUMENT ME!
541 public int getLength()
543 return this.sequence.length;
553 public void setSequence(String seq)
555 this.sequence = seq.toCharArray();
561 public String getSequenceAsString()
563 return new String(sequence);
567 public String getSequenceAsString(int start, int end)
569 return new String(getSequence(start, end));
573 public char[] getSequence()
576 return sequence == null ? null : Arrays.copyOf(sequence,
583 * @see jalview.datamodel.SequenceI#getSequence(int, int)
586 public char[] getSequence(int start, int end)
592 // JBPNote - left to user to pad the result here (TODO:Decide on this
594 if (start >= sequence.length)
599 if (end >= sequence.length)
601 end = sequence.length;
604 char[] reply = new char[end - start];
605 System.arraycopy(sequence, start, reply, 0, end - start);
611 public SequenceI getSubSequence(int start, int end)
617 char[] seq = getSequence(start, end);
622 int nstart = findPosition(start);
623 int nend = findPosition(end) - 1;
624 // JBPNote - this is an incomplete copy.
625 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
626 nseq.setDescription(description);
627 if (datasetSequence != null)
629 nseq.setDatasetSequence(datasetSequence);
633 nseq.setDatasetSequence(this);
639 * Returns the character of the aligned sequence at the given position (base
640 * zero), or space if the position is not within the sequence's bounds
645 public char getCharAt(int i)
647 if (i >= 0 && i < sequence.length)
658 * Sets the sequence description, and also parses out any special formats of
664 public void setDescription(String desc)
666 this.description = desc;
670 public void setGeneLoci(String speciesId, String assemblyId,
671 String chromosomeId, MapList map)
673 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
674 + ":" + chromosomeId, new Mapping(map)));
678 * Returns the gene loci mapping for the sequence (may be null)
683 public GeneLociI getGeneLoci()
685 DBRefEntry[] refs = getDBRefs();
688 for (final DBRefEntry ref : refs)
690 if (ref.isChromosome())
692 return new GeneLociI()
695 public String getSpeciesId()
697 return ref.getSource();
701 public String getAssemblyId()
703 return ref.getVersion();
707 public String getChromosomeId()
709 // strip off "chromosome:" prefix to chrId
710 return ref.getAccessionId().substring(
711 DBRefEntry.CHROMOSOME.length() + 1);
715 public MapList getMap()
717 return ref.getMap().getMap();
727 * Answers the description
732 public String getDescription()
734 return this.description;
741 public int findIndex(int pos)
744 * use a valid, hopefully nearby, cursor if available
746 if (isValidCursor(cursor))
748 return findIndex(pos, cursor);
756 * traverse sequence from the start counting gaps; make a note of
757 * the column of the first residue to save in the cursor
759 while ((i < sequence.length) && (j <= end) && (j <= pos))
761 if (!Comparison.isGap(sequence[i]))
772 if (j == end && j < pos)
777 updateCursor(pos, i, startColumn);
782 * Updates the cursor to the latest found residue and column position
789 * column position of the first sequence residue
791 protected void updateCursor(int residuePos, int column, int startColumn)
794 * preserve end residue column provided cursor was valid
796 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
798 if (residuePos == this.end)
803 cursor = new SequenceCursor(this, residuePos, column, startColumn,
804 endColumn, this.changeCount);
808 * Answers the aligned column position (1..) for the given residue position
809 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
810 * The hint may be left of, at, or to the right of the required position.
816 protected int findIndex(final int pos, SequenceCursor curs)
818 if (!isValidCursor(curs))
821 * wrong or invalidated cursor, compute de novo
823 return findIndex(pos);
826 if (curs.residuePosition == pos)
828 return curs.columnPosition;
832 * move left or right to find pos from hint.position
834 int col = curs.columnPosition - 1; // convert from base 1 to base 0
835 int newPos = curs.residuePosition;
836 int delta = newPos > pos ? -1 : 1;
838 while (newPos != pos)
840 col += delta; // shift one column left or right
845 if (col == sequence.length)
847 col--; // return last column if we failed to reach pos
850 if (!Comparison.isGap(sequence[col]))
856 col++; // convert back to base 1
859 * only update cursor if we found the target position
863 updateCursor(pos, col, curs.firstColumnPosition);
873 public int findPosition(final int column)
876 * use a valid, hopefully nearby, cursor if available
878 if (isValidCursor(cursor))
880 return findPosition(column + 1, cursor);
883 // TODO recode this more naturally i.e. count residues only
884 // as they are found, not 'in anticipation'
887 * traverse the sequence counting gaps; note the column position
888 * of the first residue, to save in the cursor
890 int firstResidueColumn = 0;
891 int lastPosFound = 0;
892 int lastPosFoundColumn = 0;
893 int seqlen = sequence.length;
895 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
897 lastPosFound = start;
898 lastPosFoundColumn = 0;
904 while (j < column && j < seqlen)
906 if (!Comparison.isGap(sequence[j]))
909 lastPosFoundColumn = j;
910 if (pos == this.start)
912 firstResidueColumn = j;
918 if (j < seqlen && !Comparison.isGap(sequence[j]))
921 lastPosFoundColumn = j;
922 if (pos == this.start)
924 firstResidueColumn = j;
929 * update the cursor to the last residue position found (if any)
930 * (converting column position to base 1)
932 if (lastPosFound != 0)
934 updateCursor(lastPosFound, lastPosFoundColumn + 1,
935 firstResidueColumn + 1);
942 * Answers true if the given cursor is not null, is for this sequence object,
943 * and has a token value that matches this object's changeCount, else false.
944 * This allows us to ignore a cursor as 'stale' if the sequence has been
945 * modified since the cursor was created.
950 protected boolean isValidCursor(SequenceCursor curs)
952 if (curs == null || curs.sequence != this || curs.token != changeCount)
957 * sanity check against range
959 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
963 if (curs.residuePosition < start || curs.residuePosition > end)
971 * Answers the sequence position (start..) for the given aligned column
972 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
973 * may lie left of, at, or to the right of the column position.
979 protected int findPosition(final int col, SequenceCursor curs)
981 if (!isValidCursor(curs))
984 * wrong or invalidated cursor, compute de novo
986 return findPosition(col - 1);// ugh back to base 0
989 if (curs.columnPosition == col)
991 cursor = curs; // in case this method becomes public
992 return curs.residuePosition; // easy case :-)
995 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
998 * sequence lies entirely to the left of col
999 * - return last residue + 1
1004 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1007 * sequence lies entirely to the right of col
1008 * - return first residue
1013 // todo could choose closest to col out of column,
1014 // firstColumnPosition, lastColumnPosition as a start point
1017 * move left or right to find pos from cursor position
1019 int firstResidueColumn = curs.firstColumnPosition;
1020 int column = curs.columnPosition - 1; // to base 0
1021 int newPos = curs.residuePosition;
1022 int delta = curs.columnPosition > col ? -1 : 1;
1023 boolean gapped = false;
1024 int lastFoundPosition = curs.residuePosition;
1025 int lastFoundPositionColumn = curs.columnPosition;
1027 while (column != col - 1)
1029 column += delta; // shift one column left or right
1030 if (column < 0 || column == sequence.length)
1034 gapped = Comparison.isGap(sequence[column]);
1038 lastFoundPosition = newPos;
1039 lastFoundPositionColumn = column + 1;
1040 if (lastFoundPosition == this.start)
1042 firstResidueColumn = column + 1;
1047 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1049 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1050 firstResidueColumn);
1054 * hack to give position to the right if on a gap
1055 * or beyond the length of the sequence (see JAL-2562)
1057 if (delta > 0 && (gapped || column >= sequence.length))
1069 public Range findPositions(int fromColumn, int toColumn)
1071 if (toColumn < fromColumn || fromColumn < 1)
1077 * find the first non-gapped position, if any
1079 int firstPosition = 0;
1080 int col = fromColumn - 1;
1081 int length = sequence.length;
1082 while (col < length && col < toColumn)
1084 if (!Comparison.isGap(sequence[col]))
1086 firstPosition = findPosition(col++);
1092 if (firstPosition == 0)
1098 * find the last non-gapped position
1100 int lastPosition = firstPosition;
1101 while (col < length && col < toColumn)
1103 if (!Comparison.isGap(sequence[col++]))
1109 return new Range(firstPosition, lastPosition);
1113 * Returns an int array where indices correspond to each residue in the
1114 * sequence and the element value gives its position in the alignment
1116 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1117 * residues in SequenceI object
1120 public int[] gapMap()
1122 String seq = jalview.analysis.AlignSeq.extractGaps(
1123 jalview.util.Comparison.GapChars, new String(sequence));
1124 int[] map = new int[seq.length()];
1128 while (j < sequence.length)
1130 if (!jalview.util.Comparison.isGap(sequence[j]))
1142 * Build a bitset corresponding to sequence gaps
1144 * @return a BitSet where set values correspond to gaps in the sequence
1147 public BitSet gapBitset()
1149 BitSet gaps = new BitSet(sequence.length);
1151 while (j < sequence.length)
1153 if (jalview.util.Comparison.isGap(sequence[j]))
1163 public int[] findPositionMap()
1165 int map[] = new int[sequence.length];
1168 int seqlen = sequence.length;
1169 while ((j < seqlen))
1172 if (!jalview.util.Comparison.isGap(sequence[j]))
1183 public List<int[]> getInsertions()
1185 ArrayList<int[]> map = new ArrayList<>();
1186 int lastj = -1, j = 0;
1188 int seqlen = sequence.length;
1189 while ((j < seqlen))
1191 if (jalview.util.Comparison.isGap(sequence[j]))
1202 map.add(new int[] { lastj, j - 1 });
1210 map.add(new int[] { lastj, j - 1 });
1217 public BitSet getInsertionsAsBits()
1219 BitSet map = new BitSet();
1220 int lastj = -1, j = 0;
1222 int seqlen = sequence.length;
1223 while ((j < seqlen))
1225 if (jalview.util.Comparison.isGap(sequence[j]))
1251 public void deleteChars(final int i, final int j)
1253 int newstart = start, newend = end;
1254 if (i >= sequence.length || i < 0)
1259 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1260 boolean createNewDs = false;
1261 // TODO: take a (second look) at the dataset creation validation method for
1262 // the very large sequence case
1264 int startIndex = findIndex(start) - 1;
1265 int endIndex = findIndex(end) - 1;
1266 int startDeleteColumn = -1; // for dataset sequence deletions
1267 int deleteCount = 0;
1269 for (int s = i; s < j && s < sequence.length; s++)
1271 if (Comparison.isGap(sequence[s]))
1276 if (startDeleteColumn == -1)
1278 startDeleteColumn = findPosition(s) - start;
1286 if (startIndex == s)
1289 * deleting characters from start of sequence; new start is the
1290 * sequence position of the next column (position to the right
1291 * if the column position is gapped)
1293 newstart = findPosition(j);
1301 * deleting characters at end of sequence; new end is the sequence
1302 * position of the column before the deletion; subtract 1 if this is
1303 * gapped since findPosition returns the next sequence position
1305 newend = findPosition(i - 1);
1306 if (Comparison.isGap(sequence[i - 1]))
1321 if (createNewDs && this.datasetSequence != null)
1324 * if deletion occured in the middle of the sequence,
1325 * construct a new dataset sequence and delete the residues
1326 * that were deleted from the aligned sequence
1328 Sequence ds = new Sequence(datasetSequence);
1329 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1330 datasetSequence = ds;
1331 // TODO: remove any non-inheritable properties ?
1332 // TODO: create a sequence mapping (since there is a relation here ?)
1341 public void insertCharAt(int i, int length, char c)
1343 char[] tmp = new char[sequence.length + length];
1345 if (i >= sequence.length)
1347 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1348 i = sequence.length;
1352 System.arraycopy(sequence, 0, tmp, 0, i);
1362 if (i < sequence.length)
1364 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1372 public void insertCharAt(int i, char c)
1374 insertCharAt(i, 1, c);
1378 public String getVamsasId()
1384 public void setVamsasId(String id)
1390 public void setDBRefs(DBRefEntry[] dbref)
1392 if (dbrefs == null && datasetSequence != null
1393 && this != datasetSequence)
1395 datasetSequence.setDBRefs(dbref);
1401 DBRefUtils.ensurePrimaries(this);
1406 public DBRefEntry[] getDBRefs()
1408 if (dbrefs == null && datasetSequence != null
1409 && this != datasetSequence)
1411 return datasetSequence.getDBRefs();
1417 public void addDBRef(DBRefEntry entry)
1419 if (datasetSequence != null)
1421 datasetSequence.addDBRef(entry);
1427 dbrefs = new DBRefEntry[0];
1430 for (DBRefEntryI dbr : dbrefs)
1432 if (dbr.updateFrom(entry))
1435 * found a dbref that either matched, or could be
1436 * updated from, the new entry - no need to add it
1443 * extend the array to make room for one more
1445 // TODO use an ArrayList instead
1446 int j = dbrefs.length;
1447 DBRefEntry[] temp = new DBRefEntry[j + 1];
1448 System.arraycopy(dbrefs, 0, temp, 0, j);
1449 temp[temp.length - 1] = entry;
1453 DBRefUtils.ensurePrimaries(this);
1457 public void setDatasetSequence(SequenceI seq)
1461 throw new IllegalArgumentException(
1462 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1464 if (seq != null && seq.getDatasetSequence() != null)
1466 throw new IllegalArgumentException(
1467 "Implementation error: cascading dataset sequences are not allowed.");
1469 datasetSequence = seq;
1473 public SequenceI getDatasetSequence()
1475 return datasetSequence;
1479 public AlignmentAnnotation[] getAnnotation()
1481 return annotation == null ? null
1483 .toArray(new AlignmentAnnotation[annotation.size()]);
1487 public boolean hasAnnotation(AlignmentAnnotation ann)
1489 return annotation == null ? false : annotation.contains(ann);
1493 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1495 if (this.annotation == null)
1497 this.annotation = new Vector<>();
1499 if (!this.annotation.contains(annotation))
1501 this.annotation.addElement(annotation);
1503 annotation.setSequenceRef(this);
1507 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1509 if (this.annotation != null)
1511 this.annotation.removeElement(annotation);
1512 if (this.annotation.size() == 0)
1514 this.annotation = null;
1520 * test if this is a valid candidate for another sequence's dataset sequence.
1523 private boolean isValidDatasetSequence()
1525 if (datasetSequence != null)
1529 for (int i = 0; i < sequence.length; i++)
1531 if (jalview.util.Comparison.isGap(sequence[i]))
1540 public SequenceI deriveSequence()
1542 Sequence seq = null;
1543 if (datasetSequence == null)
1545 if (isValidDatasetSequence())
1547 // Use this as dataset sequence
1548 seq = new Sequence(getName(), "", 1, -1);
1549 seq.setDatasetSequence(this);
1550 seq.initSeqFrom(this, getAnnotation());
1555 // Create a new, valid dataset sequence
1556 createDatasetSequence();
1559 return new Sequence(this);
1562 private boolean _isNa;
1564 private int _seqhash = 0;
1567 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1571 public boolean isProtein()
1573 if (datasetSequence != null)
1575 return datasetSequence.isProtein();
1577 if (_seqhash != sequence.hashCode())
1579 _seqhash = sequence.hashCode();
1580 _isNa = Comparison.isNucleotide(this);
1588 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1591 public SequenceI createDatasetSequence()
1593 if (datasetSequence == null)
1595 Sequence dsseq = new Sequence(getName(),
1596 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1597 getSequenceAsString()),
1598 getStart(), getEnd());
1600 datasetSequence = dsseq;
1602 dsseq.setDescription(description);
1603 // move features and database references onto dataset sequence
1604 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1605 sequenceFeatureStore = null;
1606 dsseq.dbrefs = dbrefs;
1608 // TODO: search and replace any references to this sequence with
1609 // references to the dataset sequence in Mappings on dbref
1610 dsseq.pdbIds = pdbIds;
1612 datasetSequence.updatePDBIds();
1613 if (annotation != null)
1615 // annotation is cloned rather than moved, to preserve what's currently
1617 for (AlignmentAnnotation aa : annotation)
1619 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1620 _aa.sequenceRef = datasetSequence;
1621 _aa.adjustForAlignment(); // uses annotation's own record of
1622 // sequence-column mapping
1623 datasetSequence.addAlignmentAnnotation(_aa);
1627 return datasetSequence;
1634 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1638 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1640 if (annotation != null)
1642 annotation.removeAllElements();
1644 if (annotations != null)
1646 for (int i = 0; i < annotations.length; i++)
1648 if (annotations[i] != null)
1650 addAlignmentAnnotation(annotations[i]);
1657 public AlignmentAnnotation[] getAnnotation(String label)
1659 if (annotation == null || annotation.size() == 0)
1664 Vector<AlignmentAnnotation> subset = new Vector<>();
1665 Enumeration<AlignmentAnnotation> e = annotation.elements();
1666 while (e.hasMoreElements())
1668 AlignmentAnnotation ann = e.nextElement();
1669 if (ann.label != null && ann.label.equals(label))
1671 subset.addElement(ann);
1674 if (subset.size() == 0)
1678 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1680 e = subset.elements();
1681 while (e.hasMoreElements())
1683 anns[i++] = e.nextElement();
1685 subset.removeAllElements();
1690 public boolean updatePDBIds()
1692 if (datasetSequence != null)
1694 // TODO: could merge DBRefs
1695 return datasetSequence.updatePDBIds();
1697 if (dbrefs == null || dbrefs.length == 0)
1701 boolean added = false;
1702 for (DBRefEntry dbr : dbrefs)
1704 if (DBRefSource.PDB.equals(dbr.getSource()))
1707 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1708 * PDB id is not already present in a 'matching' PDBEntry
1709 * Constructor parses out a chain code if appended to the accession id
1710 * (a fudge used to 'store' the chain code in the DBRef)
1712 PDBEntry pdbe = new PDBEntry(dbr);
1713 added |= addPDBId(pdbe);
1720 public void transferAnnotation(SequenceI entry, Mapping mp)
1722 if (datasetSequence != null)
1724 datasetSequence.transferAnnotation(entry, mp);
1727 if (entry.getDatasetSequence() != null)
1729 transferAnnotation(entry.getDatasetSequence(), mp);
1732 // transfer any new features from entry onto sequence
1733 if (entry.getSequenceFeatures() != null)
1736 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1737 for (SequenceFeature feature : sfs)
1739 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1740 : new SequenceFeature[] { new SequenceFeature(feature) };
1743 for (int sfi = 0; sfi < sf.length; sfi++)
1745 addSequenceFeature(sf[sfi]);
1751 // transfer PDB entries
1752 if (entry.getAllPDBEntries() != null)
1754 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1755 while (e.hasMoreElements())
1757 PDBEntry pdb = e.nextElement();
1761 // transfer database references
1762 DBRefEntry[] entryRefs = entry.getDBRefs();
1763 if (entryRefs != null)
1765 for (int r = 0; r < entryRefs.length; r++)
1767 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1768 if (newref.getMap() != null && mp != null)
1770 // remap ref using our local mapping
1772 // we also assume all version string setting is done by dbSourceProxy
1774 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1775 * newref.setSource(dbSource); }
1783 public void setRNA(RNA r)
1795 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1798 List<AlignmentAnnotation> result = new ArrayList<>();
1799 if (this.annotation != null)
1801 for (AlignmentAnnotation ann : annotation)
1803 if (ann.calcId != null && ann.calcId.equals(calcId)
1804 && ann.label != null && ann.label.equals(label))
1814 public String toString()
1816 return getDisplayId(false);
1820 public PDBEntry getPDBEntry(String pdbIdStr)
1822 if (getDatasetSequence() != null)
1824 return getDatasetSequence().getPDBEntry(pdbIdStr);
1830 List<PDBEntry> entries = getAllPDBEntries();
1831 for (PDBEntry entry : entries)
1833 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1842 public List<DBRefEntry> getPrimaryDBRefs()
1844 if (datasetSequence != null)
1846 return datasetSequence.getPrimaryDBRefs();
1848 if (dbrefs == null || dbrefs.length == 0)
1850 return Collections.emptyList();
1852 synchronized (dbrefs)
1854 List<DBRefEntry> primaries = new ArrayList<>();
1855 DBRefEntry[] tmp = new DBRefEntry[1];
1856 for (DBRefEntry ref : dbrefs)
1858 if (!ref.isPrimaryCandidate())
1864 MapList mp = ref.getMap().getMap();
1865 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1867 // map only involves a subsequence, so cannot be primary
1871 // whilst it looks like it is a primary ref, we also sanity check type
1872 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1873 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1875 // PDB dbrefs imply there should be a PDBEntry associated
1876 // TODO: tighten PDB dbrefs
1877 // formally imply Jalview has actually downloaded and
1878 // parsed the pdb file. That means there should be a cached file
1879 // handle on the PDBEntry, and a real mapping between sequence and
1880 // extracted sequence from PDB file
1881 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1882 if (pdbentry != null && pdbentry.getFile() != null)
1888 // check standard protein or dna sources
1890 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1891 if (res != null && res[0] == tmp[0])
1905 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1908 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1909 int endPos = fromColumn == toColumn ? startPos
1910 : findPosition(toColumn - 1);
1912 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1914 if (datasetSequence != null)
1916 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1921 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1925 * if end column is gapped, endPos may be to the right,
1926 * and we may have included adjacent or enclosing features;
1927 * remove any that are not enclosing, non-contact features
1929 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1930 && Comparison.isGap(sequence[toColumn - 1]);
1931 if (endPos > this.end || endColumnIsGapped)
1933 ListIterator<SequenceFeature> it = result.listIterator();
1934 while (it.hasNext())
1936 SequenceFeature sf = it.next();
1937 int sfBegin = sf.getBegin();
1938 int sfEnd = sf.getEnd();
1939 int featureStartColumn = findIndex(sfBegin);
1940 if (featureStartColumn > toColumn)
1944 else if (featureStartColumn < fromColumn)
1946 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1948 if (featureEndColumn < fromColumn)
1952 else if (featureEndColumn > toColumn && sf.isContactFeature())
1955 * remove an enclosing feature if it is a contact feature
1967 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1968 * token that has to match the one presented by the cursor
1971 public void sequenceChanged()
1980 public int replace(char c1, char c2)
1987 synchronized (sequence)
1989 for (int c = 0; c < sequence.length; c++)
1991 if (sequence[c] == c1)
2007 public String getSequenceStringFromIterator(Iterator<int[]> it)
2009 StringBuilder newSequence = new StringBuilder();
2010 while (it.hasNext())
2012 int[] block = it.next();
2015 newSequence.append(getSequence(block[0], block[1] + 1));
2019 newSequence.append(getSequence(block[0], block[1]));
2023 return newSequence.toString();
2027 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2031 if (!regions.hasNext())
2033 return findIndex(getStart()) - 1;
2036 // Simply walk along the sequence whilst watching for region
2038 int hideStart = getLength();
2040 boolean foundStart = false;
2042 // step through the non-gapped positions of the sequence
2043 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2045 // get alignment position of this residue in the sequence
2046 int p = findIndex(i) - 1;
2048 // update region start/end
2049 while (hideEnd < p && regions.hasNext())
2051 int[] region = regions.next();
2052 hideStart = region[0];
2053 hideEnd = region[1];
2057 hideStart = getLength();
2059 // update boundary for sequence
2071 // otherwise, sequence was completely hidden