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<>() : 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(final 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
848 if (col == sequence.length)
850 col--; // return last column if we failed to reach pos
853 if (!Comparison.isGap(sequence[col]))
859 col++; // convert back to base 1
862 * only update cursor if we found the target position
866 updateCursor(pos, col, curs.firstColumnPosition);
876 public int findPosition(final int column)
879 * use a valid, hopefully nearby, cursor if available
881 if (isValidCursor(cursor))
883 return findPosition(column + 1, cursor);
886 // TODO recode this more naturally i.e. count residues only
887 // as they are found, not 'in anticipation'
890 * traverse the sequence counting gaps; note the column position
891 * of the first residue, to save in the cursor
893 int firstResidueColumn = 0;
894 int lastPosFound = 0;
895 int lastPosFoundColumn = 0;
896 int seqlen = sequence.length;
898 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
900 lastPosFound = start;
901 lastPosFoundColumn = 0;
907 while (j < column && j < seqlen)
909 if (!Comparison.isGap(sequence[j]))
912 lastPosFoundColumn = j;
913 if (pos == this.start)
915 firstResidueColumn = j;
921 if (j < seqlen && !Comparison.isGap(sequence[j]))
924 lastPosFoundColumn = j;
925 if (pos == this.start)
927 firstResidueColumn = j;
932 * update the cursor to the last residue position found (if any)
933 * (converting column position to base 1)
935 if (lastPosFound != 0)
937 updateCursor(lastPosFound, lastPosFoundColumn + 1,
938 firstResidueColumn + 1);
945 * Answers true if the given cursor is not null, is for this sequence object,
946 * and has a token value that matches this object's changeCount, else false.
947 * This allows us to ignore a cursor as 'stale' if the sequence has been
948 * modified since the cursor was created.
953 protected boolean isValidCursor(SequenceCursor curs)
955 if (curs == null || curs.sequence != this || curs.token != changeCount)
960 * sanity check against range
962 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
966 if (curs.residuePosition < start || curs.residuePosition > end)
974 * Answers the sequence position (start..) for the given aligned column
975 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
976 * may lie left of, at, or to the right of the column position.
982 protected int findPosition(final int col, SequenceCursor curs)
984 if (!isValidCursor(curs))
987 * wrong or invalidated cursor, compute de novo
989 return findPosition(col - 1);// ugh back to base 0
992 if (curs.columnPosition == col)
994 cursor = curs; // in case this method becomes public
995 return curs.residuePosition; // easy case :-)
998 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1001 * sequence lies entirely to the left of col
1002 * - return last residue + 1
1007 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1010 * sequence lies entirely to the right of col
1011 * - return first residue
1016 // todo could choose closest to col out of column,
1017 // firstColumnPosition, lastColumnPosition as a start point
1020 * move left or right to find pos from cursor position
1022 int firstResidueColumn = curs.firstColumnPosition;
1023 int column = curs.columnPosition - 1; // to base 0
1024 int newPos = curs.residuePosition;
1025 int delta = curs.columnPosition > col ? -1 : 1;
1026 boolean gapped = false;
1027 int lastFoundPosition = curs.residuePosition;
1028 int lastFoundPositionColumn = curs.columnPosition;
1030 while (column != col - 1)
1032 column += delta; // shift one column left or right
1033 if (column < 0 || column == sequence.length)
1037 gapped = Comparison.isGap(sequence[column]);
1041 lastFoundPosition = newPos;
1042 lastFoundPositionColumn = column + 1;
1043 if (lastFoundPosition == this.start)
1045 firstResidueColumn = column + 1;
1050 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1052 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1053 firstResidueColumn);
1057 * hack to give position to the right if on a gap
1058 * or beyond the length of the sequence (see JAL-2562)
1060 if (delta > 0 && (gapped || column >= sequence.length))
1072 public Range findPositions(int fromColumn, int toColumn)
1074 if (toColumn < fromColumn || fromColumn < 1)
1080 * find the first non-gapped position, if any
1082 int firstPosition = 0;
1083 int col = fromColumn - 1;
1084 int length = sequence.length;
1085 while (col < length && col < toColumn)
1087 if (!Comparison.isGap(sequence[col]))
1089 firstPosition = findPosition(col++);
1095 if (firstPosition == 0)
1101 * find the last non-gapped position
1103 int lastPosition = firstPosition;
1104 while (col < length && col < toColumn)
1106 if (!Comparison.isGap(sequence[col++]))
1112 return new Range(firstPosition, lastPosition);
1116 * Returns an int array where indices correspond to each residue in the
1117 * sequence and the element value gives its position in the alignment
1119 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1120 * residues in SequenceI object
1123 public int[] gapMap()
1125 String seq = jalview.analysis.AlignSeq.extractGaps(
1126 jalview.util.Comparison.GapChars, new String(sequence));
1127 int[] map = new int[seq.length()];
1131 while (j < sequence.length)
1133 if (!jalview.util.Comparison.isGap(sequence[j]))
1145 * Build a bitset corresponding to sequence gaps
1147 * @return a BitSet where set values correspond to gaps in the sequence
1150 public BitSet gapBitset()
1152 BitSet gaps = new BitSet(sequence.length);
1154 while (j < sequence.length)
1156 if (jalview.util.Comparison.isGap(sequence[j]))
1166 public int[] findPositionMap()
1168 int map[] = new int[sequence.length];
1171 int seqlen = sequence.length;
1172 while ((j < seqlen))
1175 if (!jalview.util.Comparison.isGap(sequence[j]))
1186 public List<int[]> getInsertions()
1188 ArrayList<int[]> map = new ArrayList<>();
1189 int lastj = -1, j = 0;
1191 int seqlen = sequence.length;
1192 while ((j < seqlen))
1194 if (jalview.util.Comparison.isGap(sequence[j]))
1205 map.add(new int[] { lastj, j - 1 });
1213 map.add(new int[] { lastj, j - 1 });
1220 public BitSet getInsertionsAsBits()
1222 BitSet map = new BitSet();
1223 int lastj = -1, j = 0;
1225 int seqlen = sequence.length;
1226 while ((j < seqlen))
1228 if (jalview.util.Comparison.isGap(sequence[j]))
1254 public void deleteChars(final int i, final int j)
1256 int newstart = start, newend = end;
1257 if (i >= sequence.length || i < 0)
1262 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1263 boolean createNewDs = false;
1264 // TODO: take a (second look) at the dataset creation validation method for
1265 // the very large sequence case
1266 int startIndex = findIndex(start) - 1;
1267 int endIndex = findIndex(end) - 1;
1268 int startDeleteColumn = -1; // for dataset sequence deletions
1269 int deleteCount = 0;
1271 for (int s = i; s < j; s++)
1273 if (Comparison.isGap(sequence[s]))
1278 if (startDeleteColumn == -1)
1280 startDeleteColumn = findPosition(s) - start;
1288 if (startIndex == s)
1291 * deleting characters from start of sequence; new start is the
1292 * sequence position of the next column (position to the right
1293 * if the column position is gapped)
1295 newstart = findPosition(j);
1303 * deleting characters at end of sequence; new end is the sequence
1304 * position of the column before the deletion; subtract 1 if this is
1305 * gapped since findPosition returns the next sequence position
1307 newend = findPosition(i - 1);
1308 if (Comparison.isGap(sequence[i - 1]))
1323 if (createNewDs && this.datasetSequence != null)
1326 * if deletion occured in the middle of the sequence,
1327 * construct a new dataset sequence and delete the residues
1328 * that were deleted from the aligned sequence
1330 Sequence ds = new Sequence(datasetSequence);
1331 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1332 datasetSequence = ds;
1333 // TODO: remove any non-inheritable properties ?
1334 // TODO: create a sequence mapping (since there is a relation here ?)
1343 public void insertCharAt(int i, int length, char c)
1345 char[] tmp = new char[sequence.length + length];
1347 if (i >= sequence.length)
1349 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1350 i = sequence.length;
1354 System.arraycopy(sequence, 0, tmp, 0, i);
1364 if (i < sequence.length)
1366 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1374 public void insertCharAt(int i, char c)
1376 insertCharAt(i, 1, c);
1380 public String getVamsasId()
1386 public void setVamsasId(String id)
1392 public void setDBRefs(DBRefEntry[] dbref)
1394 if (dbrefs == null && datasetSequence != null
1395 && this != datasetSequence)
1397 datasetSequence.setDBRefs(dbref);
1403 DBRefUtils.ensurePrimaries(this);
1408 public DBRefEntry[] getDBRefs()
1410 if (dbrefs == null && datasetSequence != null
1411 && this != datasetSequence)
1413 return datasetSequence.getDBRefs();
1419 public void addDBRef(DBRefEntry entry)
1421 if (datasetSequence != null)
1423 datasetSequence.addDBRef(entry);
1429 dbrefs = new DBRefEntry[0];
1432 for (DBRefEntryI dbr : dbrefs)
1434 if (dbr.updateFrom(entry))
1437 * found a dbref that either matched, or could be
1438 * updated from, the new entry - no need to add it
1445 * extend the array to make room for one more
1447 // TODO use an ArrayList instead
1448 int j = dbrefs.length;
1449 DBRefEntry[] temp = new DBRefEntry[j + 1];
1450 System.arraycopy(dbrefs, 0, temp, 0, j);
1451 temp[temp.length - 1] = entry;
1455 DBRefUtils.ensurePrimaries(this);
1459 public void setDatasetSequence(SequenceI seq)
1463 throw new IllegalArgumentException(
1464 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1466 if (seq != null && seq.getDatasetSequence() != null)
1468 throw new IllegalArgumentException(
1469 "Implementation error: cascading dataset sequences are not allowed.");
1471 datasetSequence = seq;
1475 public SequenceI getDatasetSequence()
1477 return datasetSequence;
1481 public AlignmentAnnotation[] getAnnotation()
1483 return annotation == null ? null
1485 .toArray(new AlignmentAnnotation[annotation.size()]);
1489 public boolean hasAnnotation(AlignmentAnnotation ann)
1491 return annotation == null ? false : annotation.contains(ann);
1495 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1497 if (this.annotation == null)
1499 this.annotation = new Vector<>();
1501 if (!this.annotation.contains(annotation))
1503 this.annotation.addElement(annotation);
1505 annotation.setSequenceRef(this);
1509 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1511 if (this.annotation != null)
1513 this.annotation.removeElement(annotation);
1514 if (this.annotation.size() == 0)
1516 this.annotation = null;
1522 * test if this is a valid candidate for another sequence's dataset sequence.
1525 private boolean isValidDatasetSequence()
1527 if (datasetSequence != null)
1531 for (int i = 0; i < sequence.length; i++)
1533 if (jalview.util.Comparison.isGap(sequence[i]))
1542 public SequenceI deriveSequence()
1544 Sequence seq = null;
1545 if (datasetSequence == null)
1547 if (isValidDatasetSequence())
1549 // Use this as dataset sequence
1550 seq = new Sequence(getName(), "", 1, -1);
1551 seq.setDatasetSequence(this);
1552 seq.initSeqFrom(this, getAnnotation());
1557 // Create a new, valid dataset sequence
1558 createDatasetSequence();
1561 return new Sequence(this);
1564 private boolean _isNa;
1566 private int _seqhash = 0;
1569 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1573 public boolean isProtein()
1575 if (datasetSequence != null)
1577 return datasetSequence.isProtein();
1579 if (_seqhash != sequence.hashCode())
1581 _seqhash = sequence.hashCode();
1582 _isNa = Comparison.isNucleotide(this);
1590 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1593 public SequenceI createDatasetSequence()
1595 if (datasetSequence == null)
1597 Sequence dsseq = new Sequence(getName(),
1598 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1599 getSequenceAsString()),
1600 getStart(), getEnd());
1602 datasetSequence = dsseq;
1604 dsseq.setDescription(description);
1605 // move features and database references onto dataset sequence
1606 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1607 sequenceFeatureStore = null;
1608 dsseq.dbrefs = dbrefs;
1610 // TODO: search and replace any references to this sequence with
1611 // references to the dataset sequence in Mappings on dbref
1612 dsseq.pdbIds = pdbIds;
1614 datasetSequence.updatePDBIds();
1615 if (annotation != null)
1617 // annotation is cloned rather than moved, to preserve what's currently
1619 for (AlignmentAnnotation aa : annotation)
1621 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1622 _aa.sequenceRef = datasetSequence;
1623 _aa.adjustForAlignment(); // uses annotation's own record of
1624 // sequence-column mapping
1625 datasetSequence.addAlignmentAnnotation(_aa);
1629 return datasetSequence;
1636 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1640 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1642 if (annotation != null)
1644 annotation.removeAllElements();
1646 if (annotations != null)
1648 for (int i = 0; i < annotations.length; i++)
1650 if (annotations[i] != null)
1652 addAlignmentAnnotation(annotations[i]);
1659 public AlignmentAnnotation[] getAnnotation(String label)
1661 if (annotation == null || annotation.size() == 0)
1666 Vector<AlignmentAnnotation> subset = new Vector<>();
1667 Enumeration<AlignmentAnnotation> e = annotation.elements();
1668 while (e.hasMoreElements())
1670 AlignmentAnnotation ann = e.nextElement();
1671 if (ann.label != null && ann.label.equals(label))
1673 subset.addElement(ann);
1676 if (subset.size() == 0)
1680 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1682 e = subset.elements();
1683 while (e.hasMoreElements())
1685 anns[i++] = e.nextElement();
1687 subset.removeAllElements();
1692 public boolean updatePDBIds()
1694 if (datasetSequence != null)
1696 // TODO: could merge DBRefs
1697 return datasetSequence.updatePDBIds();
1699 if (dbrefs == null || dbrefs.length == 0)
1703 boolean added = false;
1704 for (DBRefEntry dbr : dbrefs)
1706 if (DBRefSource.PDB.equals(dbr.getSource()))
1709 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1710 * PDB id is not already present in a 'matching' PDBEntry
1711 * Constructor parses out a chain code if appended to the accession id
1712 * (a fudge used to 'store' the chain code in the DBRef)
1714 PDBEntry pdbe = new PDBEntry(dbr);
1715 added |= addPDBId(pdbe);
1722 public void transferAnnotation(SequenceI entry, Mapping mp)
1724 if (datasetSequence != null)
1726 datasetSequence.transferAnnotation(entry, mp);
1729 if (entry.getDatasetSequence() != null)
1731 transferAnnotation(entry.getDatasetSequence(), mp);
1734 // transfer any new features from entry onto sequence
1735 if (entry.getSequenceFeatures() != null)
1738 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1739 for (SequenceFeature feature : sfs)
1741 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1742 : new SequenceFeature[] { new SequenceFeature(feature) };
1745 for (int sfi = 0; sfi < sf.length; sfi++)
1747 addSequenceFeature(sf[sfi]);
1753 // transfer PDB entries
1754 if (entry.getAllPDBEntries() != null)
1756 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1757 while (e.hasMoreElements())
1759 PDBEntry pdb = e.nextElement();
1763 // transfer database references
1764 DBRefEntry[] entryRefs = entry.getDBRefs();
1765 if (entryRefs != null)
1767 for (int r = 0; r < entryRefs.length; r++)
1769 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1770 if (newref.getMap() != null && mp != null)
1772 // remap ref using our local mapping
1774 // we also assume all version string setting is done by dbSourceProxy
1776 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1777 * newref.setSource(dbSource); }
1785 public void setRNA(RNA r)
1797 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1800 List<AlignmentAnnotation> result = new ArrayList<>();
1801 if (this.annotation != null)
1803 for (AlignmentAnnotation ann : annotation)
1805 if (ann.calcId != null && ann.calcId.equals(calcId)
1806 && ann.label != null && ann.label.equals(label))
1816 public String toString()
1818 return getDisplayId(false);
1822 public PDBEntry getPDBEntry(String pdbIdStr)
1824 if (getDatasetSequence() != null)
1826 return getDatasetSequence().getPDBEntry(pdbIdStr);
1832 List<PDBEntry> entries = getAllPDBEntries();
1833 for (PDBEntry entry : entries)
1835 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1844 public List<DBRefEntry> getPrimaryDBRefs()
1846 if (datasetSequence != null)
1848 return datasetSequence.getPrimaryDBRefs();
1850 if (dbrefs == null || dbrefs.length == 0)
1852 return Collections.emptyList();
1854 synchronized (dbrefs)
1856 List<DBRefEntry> primaries = new ArrayList<>();
1857 DBRefEntry[] tmp = new DBRefEntry[1];
1858 for (DBRefEntry ref : dbrefs)
1860 if (!ref.isPrimaryCandidate())
1866 MapList mp = ref.getMap().getMap();
1867 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1869 // map only involves a subsequence, so cannot be primary
1873 // whilst it looks like it is a primary ref, we also sanity check type
1874 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1875 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1877 // PDB dbrefs imply there should be a PDBEntry associated
1878 // TODO: tighten PDB dbrefs
1879 // formally imply Jalview has actually downloaded and
1880 // parsed the pdb file. That means there should be a cached file
1881 // handle on the PDBEntry, and a real mapping between sequence and
1882 // extracted sequence from PDB file
1883 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1884 if (pdbentry != null && pdbentry.getFile() != null)
1890 // check standard protein or dna sources
1892 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1893 if (res != null && res[0] == tmp[0])
1907 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1910 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1911 int endPos = fromColumn == toColumn ? startPos
1912 : findPosition(toColumn - 1);
1914 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1918 * if end column is gapped, endPos may be to the right,
1919 * and we may have included adjacent or enclosing features;
1920 * remove any that are not enclosing, non-contact features
1922 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1923 && Comparison.isGap(sequence[toColumn - 1]);
1924 if (endPos > this.end || endColumnIsGapped)
1926 ListIterator<SequenceFeature> it = result.listIterator();
1927 while (it.hasNext())
1929 SequenceFeature sf = it.next();
1930 int sfBegin = sf.getBegin();
1931 int sfEnd = sf.getEnd();
1932 int featureStartColumn = findIndex(sfBegin);
1933 if (featureStartColumn > toColumn)
1937 else if (featureStartColumn < fromColumn)
1939 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1941 if (featureEndColumn < fromColumn)
1945 else if (featureEndColumn > toColumn && sf.isContactFeature())
1948 * remove an enclosing feature if it is a contact feature
1960 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1961 * token that has to match the one presented by the cursor
1964 public void sequenceChanged()
1973 public int replace(char c1, char c2)
1980 synchronized (sequence)
1982 for (int c = 0; c < sequence.length; c++)
1984 if (sequence[c] == c1)
2000 public String getSequenceStringFromIterator(Iterator<int[]> it)
2002 StringBuilder newSequence = new StringBuilder();
2003 while (it.hasNext())
2005 int[] block = it.next();
2008 newSequence.append(getSequence(block[0], block[1] + 1));
2012 newSequence.append(getSequence(block[0], block[1]));
2016 return newSequence.toString();
2020 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2024 if (!regions.hasNext())
2026 return findIndex(getStart()) - 1;
2029 // Simply walk along the sequence whilst watching for region
2031 int hideStart = getLength();
2033 boolean foundStart = false;
2035 // step through the non-gapped positions of the sequence
2036 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2038 // get alignment position of this residue in the sequence
2039 int p = findIndex(i) - 1;
2041 // update region start/end
2042 while (hideEnd < p && regions.hasNext())
2044 int[] region = regions.next();
2045 hideStart = region[0];
2046 hideEnd = region[1];
2050 hideStart = getLength();
2052 // update boundary for sequence
2064 // otherwise, sequence was completely hidden