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.
51 public class Sequence extends ASequence implements SequenceI
53 SequenceI datasetSequence;
57 private char[] sequence;
65 Vector<PDBEntry> pdbIds;
74 * This annotation is displayed below the alignment but the positions are tied
75 * to the residues of this sequence
77 * TODO: change to List<>
79 Vector<AlignmentAnnotation> annotation;
81 private SequenceFeaturesI sequenceFeatureStore;
84 * A cursor holding the approximate current view position to the sequence,
85 * as determined by findIndex or findPosition or findPositions.
86 * Using a cursor as a hint allows these methods to be more performant for
89 private SequenceCursor cursor;
92 * A number that should be incremented whenever the sequence is edited.
93 * If the value matches the cursor token, then we can trust the cursor,
94 * if not then it should be recomputed.
96 private int changeCount;
99 * Creates a new Sequence object.
102 * display name string
104 * string to form a possibly gapped sequence out of
106 * first position of non-gap residue in the sequence
108 * last position of ungapped residues (nearly always only used for
111 public Sequence(String name, String sequence, int start, int end)
114 initSeqAndName(name, sequence.toCharArray(), start, end);
117 public Sequence(String name, char[] sequence, int start, int end)
120 initSeqAndName(name, sequence, start, end);
124 * Stage 1 constructor - assign name, sequence, and set start and end fields.
125 * start and end are updated values from name2 if it ends with /start-end
132 protected void initSeqAndName(String name2, char[] sequence2, int start2,
136 this.sequence = sequence2;
144 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
145 * start and end respectively and removes the suffix from the name
152 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
155 int slashPos = name.lastIndexOf('/');
156 if (slashPos > -1 && slashPos < name.length() - 1)
158 String suffix = name.substring(slashPos + 1);
159 String[] range = suffix.split("-");
160 if (range.length == 2)
164 int from = Integer.valueOf(range[0]);
165 int to = Integer.valueOf(range[1]);
166 if (from > 0 && to >= from)
168 name = name.substring(0, slashPos);
173 } catch (NumberFormatException e)
175 // leave name unchanged if suffix is invalid
182 * Ensures that 'end' is not before the end of the sequence, that is,
183 * (end-start+1) is at least as long as the count of ungapped positions. Note
184 * that end is permitted to be beyond the end of the sequence data.
186 void checkValidRange()
189 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
192 for (int j = 0; j < sequence.length; j++)
194 if (!Comparison.isGap(sequence[j]))
213 * default constructor
217 sequenceFeatureStore = new SequenceFeatures();
221 * Creates a new Sequence object.
228 public Sequence(String name, String sequence)
230 this(name, sequence, 1, -1);
234 * Creates a new Sequence object with new AlignmentAnnotations but inherits
235 * any existing dataset sequence reference. If non exists, everything is
239 * if seq is a dataset sequence, behaves like a plain old copy
242 public Sequence(SequenceI seq)
244 this(seq, seq.getAnnotation());
248 * Create a new sequence object with new features, DBRefEntries, and PDBIds
249 * but inherits any existing dataset sequence reference, and duplicate of any
250 * annotation that is present in the given annotation array.
253 * the sequence to be copied
254 * @param alAnnotation
255 * an array of annotation including some associated with seq
257 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
260 initSeqFrom(seq, alAnnotation);
264 * does the heavy lifting when cloning a dataset sequence, or coping data from
265 * dataset to a new derived sequence.
268 * - source of attributes.
269 * @param alAnnotation
270 * - alignment annotation present on seq that should be copied onto
273 protected void initSeqFrom(SequenceI seq,
274 AlignmentAnnotation[] alAnnotation)
276 char[] oseq = seq.getSequence(); // returns a copy of the array
277 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
279 description = seq.getDescription();
280 if (seq != datasetSequence)
282 setDatasetSequence(seq.getDatasetSequence());
286 * only copy DBRefs and seqfeatures if we really are a dataset sequence
288 if (datasetSequence == null)
290 if (seq.getDBRefs() != null)
292 DBRefEntry[] dbr = seq.getDBRefs();
293 for (int i = 0; i < dbr.length; i++)
295 addDBRef(new DBRefEntry(dbr[i]));
300 * make copies of any sequence features
302 for (SequenceFeature sf : seq.getSequenceFeatures())
304 addSequenceFeature(new SequenceFeature(sf));
308 if (seq.getAnnotation() != null)
310 AlignmentAnnotation[] sqann = seq.getAnnotation();
311 for (int i = 0; i < sqann.length; i++)
313 if (sqann[i] == null)
317 boolean found = (alAnnotation == null);
320 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
322 found = (alAnnotation[apos] == sqann[i]);
327 // only copy the given annotation
328 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
329 addAlignmentAnnotation(newann);
333 if (seq.getAllPDBEntries() != null)
335 Vector<PDBEntry> ids = seq.getAllPDBEntries();
336 for (PDBEntry pdb : ids)
338 this.addPDBId(new PDBEntry(pdb));
344 public void setSequenceFeatures(List<SequenceFeature> features)
346 if (datasetSequence != null)
348 datasetSequence.setSequenceFeatures(features);
351 sequenceFeatureStore = new SequenceFeatures(features);
355 public synchronized boolean addSequenceFeature(SequenceFeature sf)
357 if (sf.getType() == null)
359 System.err.println("SequenceFeature type may not be null: "
364 if (datasetSequence != null)
366 return datasetSequence.addSequenceFeature(sf);
369 return sequenceFeatureStore.add(sf);
373 public void deleteFeature(SequenceFeature sf)
375 if (datasetSequence != null)
377 datasetSequence.deleteFeature(sf);
381 sequenceFeatureStore.delete(sf);
391 public List<SequenceFeature> getSequenceFeatures()
393 if (datasetSequence != null)
395 return datasetSequence.getSequenceFeatures();
397 return sequenceFeatureStore.getAllFeatures();
401 public SequenceFeaturesI getFeatures()
403 return datasetSequence != null ? datasetSequence.getFeatures()
404 : sequenceFeatureStore;
408 public boolean addPDBId(PDBEntry entry)
412 pdbIds = new Vector<>();
417 for (PDBEntry pdbe : pdbIds)
419 if (pdbe.updateFrom(entry))
424 pdbIds.addElement(entry);
435 public void setPDBId(Vector<PDBEntry> id)
443 * @return DOCUMENT ME!
446 public Vector<PDBEntry> getAllPDBEntries()
448 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
454 * @return DOCUMENT ME!
457 public String getDisplayId(boolean jvsuffix)
459 StringBuffer result = new StringBuffer(name);
462 result.append("/" + start + "-" + end);
465 return result.toString();
469 * Sets the sequence name. If the name ends in /start-end, then the start-end
470 * values are parsed out and set, and the suffix is removed from the name.
475 public void setName(String theName)
484 * @return DOCUMENT ME!
487 public String getName()
499 public void setStart(int start)
507 * @return DOCUMENT ME!
510 public int getStart()
522 public void setEnd(int end)
530 * @return DOCUMENT ME!
541 * @return DOCUMENT ME!
544 public int getLength()
546 return this.sequence.length;
556 public void setSequence(String seq)
558 this.sequence = seq.toCharArray();
564 public String getSequenceAsString()
566 return new String(sequence);
570 public String getSequenceAsString(int start, int end)
572 return new String(getSequence(start, end));
576 public char[] getSequence()
579 return sequence == null ? null : Arrays.copyOf(sequence,
586 * @see jalview.datamodel.SequenceI#getSequence(int, int)
589 public char[] getSequence(int start, int end)
595 // JBPNote - left to user to pad the result here (TODO:Decide on this
597 if (start >= sequence.length)
602 if (end >= sequence.length)
604 end = sequence.length;
607 char[] reply = new char[end - start];
608 System.arraycopy(sequence, start, reply, 0, end - start);
614 public SequenceI getSubSequence(int start, int end)
620 char[] seq = getSequence(start, end);
625 int nstart = findPosition(start);
626 int nend = findPosition(end) - 1;
627 // JBPNote - this is an incomplete copy.
628 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
629 nseq.setDescription(description);
630 if (datasetSequence != null)
632 nseq.setDatasetSequence(datasetSequence);
636 nseq.setDatasetSequence(this);
642 * Returns the character of the aligned sequence at the given position (base
643 * zero), or space if the position is not within the sequence's bounds
648 public char getCharAt(int i)
650 if (i >= 0 && i < sequence.length)
661 * Sets the sequence description, and also parses out any special formats of
667 public void setDescription(String desc)
669 this.description = desc;
673 public void setGeneLoci(String speciesId, String assemblyId,
674 String chromosomeId, MapList map)
676 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
677 + ":" + chromosomeId, new Mapping(map)));
681 * Returns the gene loci mapping for the sequence (may be null)
686 public GeneLociI getGeneLoci()
688 DBRefEntry[] refs = getDBRefs();
691 for (final DBRefEntry ref : refs)
693 if (ref.isChromosome())
695 return new GeneLociI()
698 public String getSpeciesId()
700 return ref.getSource();
704 public String getAssemblyId()
706 return ref.getVersion();
710 public String getChromosomeId()
712 // strip off "chromosome:" prefix to chrId
713 return ref.getAccessionId().substring(
714 DBRefEntry.CHROMOSOME.length() + 1);
718 public MapList getMap()
720 return ref.getMap().getMap();
730 * Answers the description
735 public String getDescription()
737 return this.description;
744 public int findIndex(int pos)
747 * use a valid, hopefully nearby, cursor if available
749 if (isValidCursor(cursor))
751 return findIndex(pos, cursor);
759 * traverse sequence from the start counting gaps; make a note of
760 * the column of the first residue to save in the cursor
762 while ((i < sequence.length) && (j <= end) && (j <= pos))
764 if (!Comparison.isGap(sequence[i]))
775 if (j == end && j < pos)
780 updateCursor(pos, i, startColumn);
785 * Updates the cursor to the latest found residue and column position
792 * column position of the first sequence residue
794 protected void updateCursor(int residuePos, int column, int startColumn)
797 * preserve end residue column provided cursor was valid
799 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
800 if (residuePos == this.end)
805 cursor = new SequenceCursor(this, residuePos, column, startColumn,
806 endColumn, this.changeCount);
810 * Answers the aligned column position (1..) for the given residue position
811 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
812 * The hint may be left of, at, or to the right of the required position.
818 protected int findIndex(int pos, SequenceCursor curs)
820 if (!isValidCursor(curs))
823 * wrong or invalidated cursor, compute de novo
825 return findIndex(pos);
828 if (curs.residuePosition == pos)
830 return curs.columnPosition;
834 * move left or right to find pos from hint.position
836 int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
838 int newPos = curs.residuePosition;
839 int delta = newPos > pos ? -1 : 1;
841 while (newPos != pos)
843 col += delta; // shift one column left or right
844 if (col < 0 || col == sequence.length)
848 if (!Comparison.isGap(sequence[col]))
854 col++; // convert back to base 1
855 updateCursor(pos, col, curs.firstColumnPosition);
864 public int findPosition(final int column)
867 * use a valid, hopefully nearby, cursor if available
869 if (isValidCursor(cursor))
871 return findPosition(column + 1, cursor);
874 // TODO recode this more naturally i.e. count residues only
875 // as they are found, not 'in anticipation'
878 * traverse the sequence counting gaps; note the column position
879 * of the first residue, to save in the cursor
881 int firstResidueColumn = 0;
882 int lastPosFound = 0;
883 int lastPosFoundColumn = 0;
884 int seqlen = sequence.length;
886 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
888 lastPosFound = start;
889 lastPosFoundColumn = 0;
895 while (j < column && j < seqlen)
897 if (!Comparison.isGap(sequence[j]))
900 lastPosFoundColumn = j;
901 if (pos == this.start)
903 firstResidueColumn = j;
909 if (j < seqlen && !Comparison.isGap(sequence[j]))
912 lastPosFoundColumn = j;
913 if (pos == this.start)
915 firstResidueColumn = j;
920 * update the cursor to the last residue position found (if any)
921 * (converting column position to base 1)
923 if (lastPosFound != 0)
925 updateCursor(lastPosFound, lastPosFoundColumn + 1,
926 firstResidueColumn + 1);
933 * Answers true if the given cursor is not null, is for this sequence object,
934 * and has a token value that matches this object's changeCount, else false.
935 * This allows us to ignore a cursor as 'stale' if the sequence has been
936 * modified since the cursor was created.
941 protected boolean isValidCursor(SequenceCursor curs)
943 if (curs == null || curs.sequence != this || curs.token != changeCount)
948 * sanity check against range
950 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
954 if (curs.residuePosition < start || curs.residuePosition > end)
962 * Answers the sequence position (start..) for the given aligned column
963 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
964 * may lie left of, at, or to the right of the column position.
970 protected int findPosition(final int col, SequenceCursor curs)
972 if (!isValidCursor(curs))
975 * wrong or invalidated cursor, compute de novo
977 return findPosition(col - 1);// ugh back to base 0
980 if (curs.columnPosition == col)
982 cursor = curs; // in case this method becomes public
983 return curs.residuePosition; // easy case :-)
986 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
989 * sequence lies entirely to the left of col
990 * - return last residue + 1
995 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
998 * sequence lies entirely to the right of col
999 * - return first residue
1004 // todo could choose closest to col out of column,
1005 // firstColumnPosition, lastColumnPosition as a start point
1008 * move left or right to find pos from cursor position
1010 int firstResidueColumn = curs.firstColumnPosition;
1011 int column = curs.columnPosition - 1; // to base 0
1012 int newPos = curs.residuePosition;
1013 int delta = curs.columnPosition > col ? -1 : 1;
1014 boolean gapped = false;
1015 int lastFoundPosition = curs.residuePosition;
1016 int lastFoundPositionColumn = curs.columnPosition;
1018 while (column != col - 1)
1020 column += delta; // shift one column left or right
1021 if (column < 0 || column == sequence.length)
1025 gapped = Comparison.isGap(sequence[column]);
1029 lastFoundPosition = newPos;
1030 lastFoundPositionColumn = column + 1;
1031 if (lastFoundPosition == this.start)
1033 firstResidueColumn = column + 1;
1038 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1040 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1041 firstResidueColumn);
1045 * hack to give position to the right if on a gap
1046 * or beyond the length of the sequence (see JAL-2562)
1048 if (delta > 0 && (gapped || column >= sequence.length))
1060 public Range findPositions(int fromColumn, int toColumn)
1062 if (toColumn < fromColumn || fromColumn < 1)
1068 * find the first non-gapped position, if any
1070 int firstPosition = 0;
1071 int col = fromColumn - 1;
1072 int length = sequence.length;
1073 while (col < length && col < toColumn)
1075 if (!Comparison.isGap(sequence[col]))
1077 firstPosition = findPosition(col++);
1083 if (firstPosition == 0)
1089 * find the last non-gapped position
1091 int lastPosition = firstPosition;
1092 while (col < length && col < toColumn)
1094 if (!Comparison.isGap(sequence[col++]))
1100 return new Range(firstPosition, lastPosition);
1104 * Returns an int array where indices correspond to each residue in the
1105 * sequence and the element value gives its position in the alignment
1107 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1108 * residues in SequenceI object
1111 public int[] gapMap()
1113 String seq = jalview.analysis.AlignSeq.extractGaps(
1114 jalview.util.Comparison.GapChars, new String(sequence));
1115 int[] map = new int[seq.length()];
1119 while (j < sequence.length)
1121 if (!jalview.util.Comparison.isGap(sequence[j]))
1133 * Build a bitset corresponding to sequence gaps
1135 * @return a BitSet where set values correspond to gaps in the sequence
1138 public BitSet gapBitset()
1140 BitSet gaps = new BitSet(sequence.length);
1142 while (j < sequence.length)
1144 if (jalview.util.Comparison.isGap(sequence[j]))
1154 public int[] findPositionMap()
1156 int map[] = new int[sequence.length];
1159 int seqlen = sequence.length;
1160 while ((j < seqlen))
1163 if (!jalview.util.Comparison.isGap(sequence[j]))
1174 public List<int[]> getInsertions()
1176 ArrayList<int[]> map = new ArrayList<>();
1177 int lastj = -1, j = 0;
1179 int seqlen = sequence.length;
1180 while ((j < seqlen))
1182 if (jalview.util.Comparison.isGap(sequence[j]))
1193 map.add(new int[] { lastj, j - 1 });
1201 map.add(new int[] { lastj, j - 1 });
1208 public BitSet getInsertionsAsBits()
1210 BitSet map = new BitSet();
1211 int lastj = -1, j = 0;
1213 int seqlen = sequence.length;
1214 while ((j < seqlen))
1216 if (jalview.util.Comparison.isGap(sequence[j]))
1242 public void deleteChars(final int i, final int j)
1244 int newstart = start, newend = end;
1245 if (i >= sequence.length || i < 0)
1250 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1251 boolean createNewDs = false;
1252 // TODO: take a (second look) at the dataset creation validation method for
1253 // the very large sequence case
1254 int startIndex = findIndex(start) - 1;
1255 int endIndex = findIndex(end) - 1;
1256 int startDeleteColumn = -1; // for dataset sequence deletions
1257 int deleteCount = 0;
1259 for (int s = i; s < j; s++)
1261 if (Comparison.isGap(sequence[s]))
1266 if (startDeleteColumn == -1)
1268 startDeleteColumn = findPosition(s) - start;
1276 if (startIndex == s)
1279 * deleting characters from start of sequence; new start is the
1280 * sequence position of the next column (position to the right
1281 * if the column position is gapped)
1283 newstart = findPosition(j);
1291 * deleting characters at end of sequence; new end is the sequence
1292 * position of the column before the deletion; subtract 1 if this is
1293 * gapped since findPosition returns the next sequence position
1295 newend = findPosition(i - 1);
1296 if (Comparison.isGap(sequence[i - 1]))
1311 if (createNewDs && this.datasetSequence != null)
1314 * if deletion occured in the middle of the sequence,
1315 * construct a new dataset sequence and delete the residues
1316 * that were deleted from the aligned sequence
1318 Sequence ds = new Sequence(datasetSequence);
1319 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1320 datasetSequence = ds;
1321 // TODO: remove any non-inheritable properties ?
1322 // TODO: create a sequence mapping (since there is a relation here ?)
1331 public void insertCharAt(int i, int length, char c)
1333 char[] tmp = new char[sequence.length + length];
1335 if (i >= sequence.length)
1337 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1338 i = sequence.length;
1342 System.arraycopy(sequence, 0, tmp, 0, i);
1352 if (i < sequence.length)
1354 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1362 public void insertCharAt(int i, char c)
1364 insertCharAt(i, 1, c);
1368 public String getVamsasId()
1374 public void setVamsasId(String id)
1380 public void setDBRefs(DBRefEntry[] dbref)
1382 if (dbrefs == null && datasetSequence != null
1383 && this != datasetSequence)
1385 datasetSequence.setDBRefs(dbref);
1391 DBRefUtils.ensurePrimaries(this);
1396 public DBRefEntry[] getDBRefs()
1398 if (dbrefs == null && datasetSequence != null
1399 && this != datasetSequence)
1401 return datasetSequence.getDBRefs();
1407 public void addDBRef(DBRefEntry entry)
1409 if (datasetSequence != null)
1411 datasetSequence.addDBRef(entry);
1417 dbrefs = new DBRefEntry[0];
1420 for (DBRefEntryI dbr : dbrefs)
1422 if (dbr.updateFrom(entry))
1425 * found a dbref that either matched, or could be
1426 * updated from, the new entry - no need to add it
1433 * extend the array to make room for one more
1435 // TODO use an ArrayList instead
1436 int j = dbrefs.length;
1437 DBRefEntry[] temp = new DBRefEntry[j + 1];
1438 System.arraycopy(dbrefs, 0, temp, 0, j);
1439 temp[temp.length - 1] = entry;
1443 DBRefUtils.ensurePrimaries(this);
1447 public void setDatasetSequence(SequenceI seq)
1451 throw new IllegalArgumentException(
1452 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1454 if (seq != null && seq.getDatasetSequence() != null)
1456 throw new IllegalArgumentException(
1457 "Implementation error: cascading dataset sequences are not allowed.");
1459 datasetSequence = seq;
1463 public SequenceI getDatasetSequence()
1465 return datasetSequence;
1469 public AlignmentAnnotation[] getAnnotation()
1471 return annotation == null ? null
1473 .toArray(new AlignmentAnnotation[annotation.size()]);
1477 public boolean hasAnnotation(AlignmentAnnotation ann)
1479 return annotation == null ? false : annotation.contains(ann);
1483 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1485 if (this.annotation == null)
1487 this.annotation = new Vector<>();
1489 if (!this.annotation.contains(annotation))
1491 this.annotation.addElement(annotation);
1493 annotation.setSequenceRef(this);
1497 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1499 if (this.annotation != null)
1501 this.annotation.removeElement(annotation);
1502 if (this.annotation.size() == 0)
1504 this.annotation = null;
1510 * test if this is a valid candidate for another sequence's dataset sequence.
1513 private boolean isValidDatasetSequence()
1515 if (datasetSequence != null)
1519 for (int i = 0; i < sequence.length; i++)
1521 if (jalview.util.Comparison.isGap(sequence[i]))
1530 public SequenceI deriveSequence()
1532 Sequence seq = null;
1533 if (datasetSequence == null)
1535 if (isValidDatasetSequence())
1537 // Use this as dataset sequence
1538 seq = new Sequence(getName(), "", 1, -1);
1539 seq.setDatasetSequence(this);
1540 seq.initSeqFrom(this, getAnnotation());
1545 // Create a new, valid dataset sequence
1546 createDatasetSequence();
1549 return new Sequence(this);
1552 private boolean _isNa;
1554 private int _seqhash = 0;
1557 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1561 public boolean isProtein()
1563 if (datasetSequence != null)
1565 return datasetSequence.isProtein();
1567 if (_seqhash != sequence.hashCode())
1569 _seqhash = sequence.hashCode();
1570 _isNa = Comparison.isNucleotide(this);
1578 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1581 public SequenceI createDatasetSequence()
1583 if (datasetSequence == null)
1585 Sequence dsseq = new Sequence(getName(),
1586 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1587 getSequenceAsString()),
1588 getStart(), getEnd());
1590 datasetSequence = dsseq;
1592 dsseq.setDescription(description);
1593 // move features and database references onto dataset sequence
1594 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1595 sequenceFeatureStore = null;
1596 dsseq.dbrefs = dbrefs;
1598 // TODO: search and replace any references to this sequence with
1599 // references to the dataset sequence in Mappings on dbref
1600 dsseq.pdbIds = pdbIds;
1602 datasetSequence.updatePDBIds();
1603 if (annotation != null)
1605 // annotation is cloned rather than moved, to preserve what's currently
1607 for (AlignmentAnnotation aa : annotation)
1609 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1610 _aa.sequenceRef = datasetSequence;
1611 _aa.adjustForAlignment(); // uses annotation's own record of
1612 // sequence-column mapping
1613 datasetSequence.addAlignmentAnnotation(_aa);
1617 return datasetSequence;
1624 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1628 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1630 if (annotation != null)
1632 annotation.removeAllElements();
1634 if (annotations != null)
1636 for (int i = 0; i < annotations.length; i++)
1638 if (annotations[i] != null)
1640 addAlignmentAnnotation(annotations[i]);
1647 public AlignmentAnnotation[] getAnnotation(String label)
1649 if (annotation == null || annotation.size() == 0)
1654 Vector<AlignmentAnnotation> subset = new Vector<>();
1655 Enumeration<AlignmentAnnotation> e = annotation.elements();
1656 while (e.hasMoreElements())
1658 AlignmentAnnotation ann = e.nextElement();
1659 if (ann.label != null && ann.label.equals(label))
1661 subset.addElement(ann);
1664 if (subset.size() == 0)
1668 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1670 e = subset.elements();
1671 while (e.hasMoreElements())
1673 anns[i++] = e.nextElement();
1675 subset.removeAllElements();
1680 public boolean updatePDBIds()
1682 if (datasetSequence != null)
1684 // TODO: could merge DBRefs
1685 return datasetSequence.updatePDBIds();
1687 if (dbrefs == null || dbrefs.length == 0)
1691 boolean added = false;
1692 for (DBRefEntry dbr : dbrefs)
1694 if (DBRefSource.PDB.equals(dbr.getSource()))
1697 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1698 * PDB id is not already present in a 'matching' PDBEntry
1699 * Constructor parses out a chain code if appended to the accession id
1700 * (a fudge used to 'store' the chain code in the DBRef)
1702 PDBEntry pdbe = new PDBEntry(dbr);
1703 added |= addPDBId(pdbe);
1710 public void transferAnnotation(SequenceI entry, Mapping mp)
1712 if (datasetSequence != null)
1714 datasetSequence.transferAnnotation(entry, mp);
1717 if (entry.getDatasetSequence() != null)
1719 transferAnnotation(entry.getDatasetSequence(), mp);
1722 // transfer any new features from entry onto sequence
1723 if (entry.getSequenceFeatures() != null)
1726 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1727 for (SequenceFeature feature : sfs)
1729 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1730 : new SequenceFeature[] { new SequenceFeature(feature) };
1733 for (int sfi = 0; sfi < sf.length; sfi++)
1735 addSequenceFeature(sf[sfi]);
1741 // transfer PDB entries
1742 if (entry.getAllPDBEntries() != null)
1744 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1745 while (e.hasMoreElements())
1747 PDBEntry pdb = e.nextElement();
1751 // transfer database references
1752 DBRefEntry[] entryRefs = entry.getDBRefs();
1753 if (entryRefs != null)
1755 for (int r = 0; r < entryRefs.length; r++)
1757 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1758 if (newref.getMap() != null && mp != null)
1760 // remap ref using our local mapping
1762 // we also assume all version string setting is done by dbSourceProxy
1764 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1765 * newref.setSource(dbSource); }
1773 public void setRNA(RNA r)
1785 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1788 List<AlignmentAnnotation> result = new ArrayList<>();
1789 if (this.annotation != null)
1791 for (AlignmentAnnotation ann : annotation)
1793 if (ann.calcId != null && ann.calcId.equals(calcId)
1794 && ann.label != null && ann.label.equals(label))
1804 public String toString()
1806 return getDisplayId(false);
1810 public PDBEntry getPDBEntry(String pdbIdStr)
1812 if (getDatasetSequence() != null)
1814 return getDatasetSequence().getPDBEntry(pdbIdStr);
1820 List<PDBEntry> entries = getAllPDBEntries();
1821 for (PDBEntry entry : entries)
1823 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1832 public List<DBRefEntry> getPrimaryDBRefs()
1834 if (datasetSequence != null)
1836 return datasetSequence.getPrimaryDBRefs();
1838 if (dbrefs == null || dbrefs.length == 0)
1840 return Collections.emptyList();
1842 synchronized (dbrefs)
1844 List<DBRefEntry> primaries = new ArrayList<>();
1845 DBRefEntry[] tmp = new DBRefEntry[1];
1846 for (DBRefEntry ref : dbrefs)
1848 if (!ref.isPrimaryCandidate())
1854 MapList mp = ref.getMap().getMap();
1855 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1857 // map only involves a subsequence, so cannot be primary
1861 // whilst it looks like it is a primary ref, we also sanity check type
1862 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1863 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1865 // PDB dbrefs imply there should be a PDBEntry associated
1866 // TODO: tighten PDB dbrefs
1867 // formally imply Jalview has actually downloaded and
1868 // parsed the pdb file. That means there should be a cached file
1869 // handle on the PDBEntry, and a real mapping between sequence and
1870 // extracted sequence from PDB file
1871 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1872 if (pdbentry != null && pdbentry.getFile() != null)
1878 // check standard protein or dna sources
1880 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1881 if (res != null && res[0] == tmp[0])
1895 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1898 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1899 int endPos = fromColumn == toColumn ? startPos
1900 : findPosition(toColumn - 1);
1902 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1906 * if end column is gapped, endPos may be to the right,
1907 * and we may have included adjacent or enclosing features;
1908 * remove any that are not enclosing, non-contact features
1910 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1911 && Comparison.isGap(sequence[toColumn - 1]);
1912 if (endPos > this.end || endColumnIsGapped)
1914 ListIterator<SequenceFeature> it = result.listIterator();
1915 while (it.hasNext())
1917 SequenceFeature sf = it.next();
1918 int sfBegin = sf.getBegin();
1919 int sfEnd = sf.getEnd();
1920 int featureStartColumn = findIndex(sfBegin);
1921 if (featureStartColumn > toColumn)
1925 else if (featureStartColumn < fromColumn)
1927 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1929 if (featureEndColumn < fromColumn)
1933 else if (featureEndColumn > toColumn && sf.isContactFeature())
1936 * remove an enclosing feature if it is a contact feature
1948 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1949 * token that has to match the one presented by the cursor
1952 public void sequenceChanged()
1961 public int replace(char c1, char c2)
1968 synchronized (sequence)
1970 for (int c = 0; c < sequence.length; c++)
1972 if (sequence[c] == c1)
1988 public String getSequenceStringFromIterator(Iterator<int[]> it)
1990 StringBuilder newSequence = new StringBuilder();
1991 while (it.hasNext())
1993 int[] block = it.next();
1996 newSequence.append(getSequence(block[0], block[1] + 1));
2000 newSequence.append(getSequence(block[0], block[1]));
2004 return newSequence.toString();
2008 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2012 if (!regions.hasNext())
2014 return findIndex(getStart()) - 1;
2017 // Simply walk along the sequence whilst watching for region
2019 int hideStart = getLength();
2021 boolean foundStart = false;
2023 // step through the non-gapped positions of the sequence
2024 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2026 // get alignment position of this residue in the sequence
2027 int p = findIndex(i) - 1;
2029 // update region start/end
2030 while (hideEnd < p && regions.hasNext())
2032 int[] region = regions.next();
2033 hideStart = region[0];
2034 hideEnd = region[1];
2038 hideStart = getLength();
2040 // update boundary for sequence
2052 // otherwise, sequence was completely hidden