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.datamodel.features.SequenceFeatures;
25 import jalview.datamodel.features.SequenceFeaturesI;
26 import jalview.util.Comparison;
27 import jalview.util.DBRefUtils;
28 import jalview.util.MapList;
29 import jalview.util.StringUtils;
31 import java.awt.Color;
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
52 * A subclass that gives us access to modCount, which tracks whether there
53 * have been any changes. We use this to update
59 @SuppressWarnings("serial")
60 public class DBModList<T> extends ArrayList<DBRefEntry>
63 protected int getModCount()
70 SequenceI datasetSequence;
74 private char[] sequence;
76 private String description;
82 private Vector<PDBEntry> pdbIds;
84 private String vamsasId;
86 private DBModList<DBRefEntry> dbrefs; // controlled access
89 * a flag to let us know that elements have changed in dbrefs
93 private int refModCount = 0;
98 * This annotation is displayed below the alignment but the positions are tied
99 * to the residues of this sequence
101 * TODO: change to List<>
103 private Vector<AlignmentAnnotation> annotation;
105 private SequenceFeaturesI sequenceFeatureStore;
108 * A cursor holding the approximate current view position to the sequence,
109 * as determined by findIndex or findPosition or findPositions.
110 * Using a cursor as a hint allows these methods to be more performant for
113 private SequenceCursor cursor;
116 * A number that should be incremented whenever the sequence is edited.
117 * If the value matches the cursor token, then we can trust the cursor,
118 * if not then it should be recomputed.
120 private int changeCount;
123 * Creates a new Sequence object.
126 * display name string
128 * string to form a possibly gapped sequence out of
130 * first position of non-gap residue in the sequence
132 * last position of ungapped residues (nearly always only used for
135 public Sequence(String name, String sequence, int start, int end)
138 initSeqAndName(name, sequence.toCharArray(), start, end);
141 public Sequence(String name, char[] sequence, int start, int end)
144 initSeqAndName(name, sequence, start, end);
148 * Stage 1 constructor - assign name, sequence, and set start and end fields.
149 * start and end are updated values from name2 if it ends with /start-end
156 protected void initSeqAndName(String name2, char[] sequence2, int start2,
160 this.sequence = sequence2;
168 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
169 * start and end respectively and removes the suffix from the name
176 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
179 int slashPos = name.lastIndexOf('/');
180 if (slashPos > -1 && slashPos < name.length() - 1)
182 String suffix = name.substring(slashPos + 1);
183 String[] range = suffix.split("-");
184 if (range.length == 2)
188 int from = Integer.valueOf(range[0]);
189 int to = Integer.valueOf(range[1]);
190 if (from > 0 && to >= from)
192 name = name.substring(0, slashPos);
197 } catch (NumberFormatException e)
199 // leave name unchanged if suffix is invalid
206 * Ensures that 'end' is not before the end of the sequence, that is,
207 * (end-start+1) is at least as long as the count of ungapped positions. Note
208 * that end is permitted to be beyond the end of the sequence data.
210 void checkValidRange()
213 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
216 for (int j = 0; j < sequence.length; j++)
218 if (!Comparison.isGap(sequence[j]))
237 * default constructor
241 sequenceFeatureStore = new SequenceFeatures();
245 * Creates a new Sequence object.
252 public Sequence(String name, String sequence)
254 this(name, sequence, 1, -1);
258 * Creates a new Sequence object with new AlignmentAnnotations but inherits
259 * any existing dataset sequence reference. If non exists, everything is
263 * if seq is a dataset sequence, behaves like a plain old copy
266 public Sequence(SequenceI seq)
268 this(seq, seq.getAnnotation());
272 * Create a new sequence object with new features, DBRefEntries, and PDBIds
273 * but inherits any existing dataset sequence reference, and duplicate of any
274 * annotation that is present in the given annotation array.
277 * the sequence to be copied
278 * @param alAnnotation
279 * an array of annotation including some associated with seq
281 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
284 initSeqFrom(seq, alAnnotation);
288 * does the heavy lifting when cloning a dataset sequence, or coping data from
289 * dataset to a new derived sequence.
292 * - source of attributes.
293 * @param alAnnotation
294 * - alignment annotation present on seq that should be copied onto
297 protected void initSeqFrom(SequenceI seq,
298 AlignmentAnnotation[] alAnnotation)
300 char[] oseq = seq.getSequence(); // returns a copy of the array
301 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
303 description = seq.getDescription();
304 if (seq != datasetSequence)
306 setDatasetSequence(seq.getDatasetSequence());
310 * only copy DBRefs and seqfeatures if we really are a dataset sequence
312 if (datasetSequence == null)
314 List<DBRefEntry> dbr = seq.getDBRefs();
317 for (int i = 0, n = dbr.size(); i < n; i++)
319 addDBRef(new DBRefEntry(dbr.get(i)));
324 * make copies of any sequence features
326 for (SequenceFeature sf : seq.getSequenceFeatures())
328 addSequenceFeature(new SequenceFeature(sf));
332 if (seq.getAnnotation() != null)
334 AlignmentAnnotation[] sqann = seq.getAnnotation();
335 for (int i = 0; i < sqann.length; i++)
337 if (sqann[i] == null)
341 boolean found = (alAnnotation == null);
344 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
346 found = (alAnnotation[apos] == sqann[i]);
351 // only copy the given annotation
352 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
353 addAlignmentAnnotation(newann);
357 if (seq.getAllPDBEntries() != null)
359 Vector<PDBEntry> ids = seq.getAllPDBEntries();
360 for (PDBEntry pdb : ids)
362 this.addPDBId(new PDBEntry(pdb));
368 public void setSequenceFeatures(List<SequenceFeature> features)
370 if (datasetSequence != null)
372 datasetSequence.setSequenceFeatures(features);
375 sequenceFeatureStore = new SequenceFeatures(features);
379 public synchronized boolean addSequenceFeature(SequenceFeature sf)
381 if (sf.getType() == null)
384 "SequenceFeature type may not be null: " + sf.toString());
388 if (datasetSequence != null)
390 return datasetSequence.addSequenceFeature(sf);
393 return sequenceFeatureStore.add(sf);
397 public void deleteFeature(SequenceFeature sf)
399 if (datasetSequence != null)
401 datasetSequence.deleteFeature(sf);
405 sequenceFeatureStore.delete(sf);
415 public List<SequenceFeature> getSequenceFeatures()
417 if (datasetSequence != null)
419 return datasetSequence.getSequenceFeatures();
421 return sequenceFeatureStore.getAllFeatures();
425 public SequenceFeaturesI getFeatures()
427 return datasetSequence != null ? datasetSequence.getFeatures()
428 : sequenceFeatureStore;
432 public boolean addPDBId(PDBEntry entry)
436 pdbIds = new Vector<>();
441 for (PDBEntry pdbe : pdbIds)
443 if (pdbe.updateFrom(entry))
448 pdbIds.addElement(entry);
459 public void setPDBId(Vector<PDBEntry> id)
467 * @return DOCUMENT ME!
470 public Vector<PDBEntry> getAllPDBEntries()
472 return pdbIds == null ? new Vector<>() : pdbIds;
478 * @return DOCUMENT ME!
481 public String getDisplayId(boolean jvsuffix)
483 StringBuffer result = new StringBuffer(name);
486 result.append("/" + start + "-" + end);
489 return result.toString();
493 * Sets the sequence name. If the name ends in /start-end, then the start-end
494 * values are parsed out and set, and the suffix is removed from the name.
499 public void setName(String theName)
508 * @return DOCUMENT ME!
511 public String getName()
523 public void setStart(int start)
531 * @return DOCUMENT ME!
534 public int getStart()
546 public void setEnd(int end)
554 * @return DOCUMENT ME!
565 * @return DOCUMENT ME!
568 public int getLength()
570 return this.sequence.length;
580 public void setSequence(String seq)
582 this.sequence = seq.toCharArray();
588 public String getSequenceAsString()
590 return new String(sequence);
594 public String getSequenceAsString(int start, int end)
596 return new String(getSequence(start, end));
600 public char[] getSequence()
603 return sequence == null ? null
604 : Arrays.copyOf(sequence, sequence.length);
610 * @see jalview.datamodel.SequenceI#getSequence(int, int)
613 public char[] getSequence(int start, int end)
619 // JBPNote - left to user to pad the result here (TODO:Decide on this
621 if (start >= sequence.length)
626 if (end >= sequence.length)
628 end = sequence.length;
631 char[] reply = new char[end - start];
632 System.arraycopy(sequence, start, reply, 0, end - start);
638 public SequenceI getSubSequence(int start, int end)
644 char[] seq = getSequence(start, end);
649 int nstart = findPosition(start);
650 int nend = findPosition(end) - 1;
651 // JBPNote - this is an incomplete copy.
652 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
653 nseq.setDescription(description);
654 if (datasetSequence != null)
656 nseq.setDatasetSequence(datasetSequence);
660 nseq.setDatasetSequence(this);
666 * Returns the character of the aligned sequence at the given position (base
667 * zero), or space if the position is not within the sequence's bounds
672 public char getCharAt(int i)
674 if (i >= 0 && i < sequence.length)
685 * Sets the sequence description, and also parses out any special formats of
691 public void setDescription(String desc)
693 this.description = desc;
697 public void setGeneLoci(String speciesId, String assemblyId,
698 String chromosomeId, MapList map)
700 addDBRef(new DBRefEntry(speciesId, assemblyId,
701 DBRefEntry.CHROMOSOME + ":" + chromosomeId, new Mapping(map)));
705 * Returns the gene loci mapping for the sequence (may be null)
710 public GeneLociI getGeneLoci()
712 List<DBRefEntry> refs = getDBRefs();
715 for (final DBRefEntry ref : refs)
717 if (ref.isChromosome())
719 return new GeneLociI()
722 public String getSpeciesId()
724 return ref.getSource();
728 public String getAssemblyId()
730 // DEV NOTE: DBRefEntry is reused here to hold chromosomal locus
731 // of a gene sequence.
732 // source=species, version=assemblyId, accession=chromosome, map =
735 return ref.getVersion();
739 public String getChromosomeId()
741 // strip off "chromosome:" prefix to chrId
742 return ref.getAccessionId()
743 .substring(DBRefEntry.CHROMOSOME.length() + 1);
747 public MapList getMap()
749 return ref.getMap().getMap();
759 * Answers the description
764 public String getDescription()
766 return this.description;
773 public int findIndex(int pos)
776 * use a valid, hopefully nearby, cursor if available
778 if (isValidCursor(cursor))
780 return findIndex(pos, cursor);
788 * traverse sequence from the start counting gaps; make a note of
789 * the column of the first residue to save in the cursor
791 while ((i < sequence.length) && (j <= end) && (j <= pos))
793 if (!Comparison.isGap(sequence[i]))
804 if (j == end && j < pos)
809 updateCursor(pos, i, startColumn);
814 * Updates the cursor to the latest found residue and column position
821 * column position of the first sequence residue
823 protected void updateCursor(int residuePos, int column, int startColumn)
826 * preserve end residue column provided cursor was valid
828 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
830 if (residuePos == this.end)
835 cursor = new SequenceCursor(this, residuePos, column, startColumn,
836 endColumn, this.changeCount);
840 * Answers the aligned column position (1..) for the given residue position
841 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
842 * The hint may be left of, at, or to the right of the required position.
848 protected int findIndex(final int pos, SequenceCursor curs)
850 if (!isValidCursor(curs))
853 * wrong or invalidated cursor, compute de novo
855 return findIndex(pos);
858 if (curs.residuePosition == pos)
860 return curs.columnPosition;
864 * move left or right to find pos from hint.position
866 int col = curs.columnPosition - 1; // convert from base 1 to base 0
867 int newPos = curs.residuePosition;
868 int delta = newPos > pos ? -1 : 1;
870 while (newPos != pos)
872 col += delta; // shift one column left or right
877 if (col == sequence.length)
879 col--; // return last column if we failed to reach pos
882 if (!Comparison.isGap(sequence[col]))
888 col++; // convert back to base 1
891 * only update cursor if we found the target position
895 updateCursor(pos, col, curs.firstColumnPosition);
905 public int findPosition(final int column)
908 * use a valid, hopefully nearby, cursor if available
910 if (isValidCursor(cursor))
912 return findPosition(column + 1, cursor);
915 // TODO recode this more naturally i.e. count residues only
916 // as they are found, not 'in anticipation'
919 * traverse the sequence counting gaps; note the column position
920 * of the first residue, to save in the cursor
922 int firstResidueColumn = 0;
923 int lastPosFound = 0;
924 int lastPosFoundColumn = 0;
925 int seqlen = sequence.length;
927 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
929 lastPosFound = start;
930 lastPosFoundColumn = 0;
936 while (j < column && j < seqlen)
938 if (!Comparison.isGap(sequence[j]))
941 lastPosFoundColumn = j;
942 if (pos == this.start)
944 firstResidueColumn = j;
950 if (j < seqlen && !Comparison.isGap(sequence[j]))
953 lastPosFoundColumn = j;
954 if (pos == this.start)
956 firstResidueColumn = j;
961 * update the cursor to the last residue position found (if any)
962 * (converting column position to base 1)
964 if (lastPosFound != 0)
966 updateCursor(lastPosFound, lastPosFoundColumn + 1,
967 firstResidueColumn + 1);
974 * Answers true if the given cursor is not null, is for this sequence object,
975 * and has a token value that matches this object's changeCount, else false.
976 * This allows us to ignore a cursor as 'stale' if the sequence has been
977 * modified since the cursor was created.
982 protected boolean isValidCursor(SequenceCursor curs)
984 if (curs == null || curs.sequence != this || curs.token != changeCount)
989 * sanity check against range
991 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
995 if (curs.residuePosition < start || curs.residuePosition > end)
1003 * Answers the sequence position (start..) for the given aligned column
1004 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
1005 * may lie left of, at, or to the right of the column position.
1011 protected int findPosition(final int col, SequenceCursor curs)
1013 if (!isValidCursor(curs))
1016 * wrong or invalidated cursor, compute de novo
1018 return findPosition(col - 1);// ugh back to base 0
1021 if (curs.columnPosition == col)
1023 cursor = curs; // in case this method becomes public
1024 return curs.residuePosition; // easy case :-)
1027 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1030 * sequence lies entirely to the left of col
1031 * - return last residue + 1
1036 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1039 * sequence lies entirely to the right of col
1040 * - return first residue
1045 // todo could choose closest to col out of column,
1046 // firstColumnPosition, lastColumnPosition as a start point
1049 * move left or right to find pos from cursor position
1051 int firstResidueColumn = curs.firstColumnPosition;
1052 int column = curs.columnPosition - 1; // to base 0
1053 int newPos = curs.residuePosition;
1054 int delta = curs.columnPosition > col ? -1 : 1;
1055 boolean gapped = false;
1056 int lastFoundPosition = curs.residuePosition;
1057 int lastFoundPositionColumn = curs.columnPosition;
1059 while (column != col - 1)
1061 column += delta; // shift one column left or right
1062 if (column < 0 || column == sequence.length)
1066 gapped = Comparison.isGap(sequence[column]);
1070 lastFoundPosition = newPos;
1071 lastFoundPositionColumn = column + 1;
1072 if (lastFoundPosition == this.start)
1074 firstResidueColumn = column + 1;
1079 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1081 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1082 firstResidueColumn);
1086 * hack to give position to the right if on a gap
1087 * or beyond the length of the sequence (see JAL-2562)
1089 if (delta > 0 && (gapped || column >= sequence.length))
1101 public ContiguousI findPositions(int fromColumn, int toColumn)
1103 if (toColumn < fromColumn || fromColumn < 1)
1109 * find the first non-gapped position, if any
1111 int firstPosition = 0;
1112 int col = fromColumn - 1;
1113 int length = sequence.length;
1114 while (col < length && col < toColumn)
1116 if (!Comparison.isGap(sequence[col]))
1118 firstPosition = findPosition(col++);
1124 if (firstPosition == 0)
1130 * find the last non-gapped position
1132 int lastPosition = firstPosition;
1133 while (col < length && col < toColumn)
1135 if (!Comparison.isGap(sequence[col++]))
1141 return new Range(firstPosition, lastPosition);
1145 * Returns an int array where indices correspond to each residue in the
1146 * sequence and the element value gives its position in the alignment
1148 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1149 * residues in SequenceI object
1152 public int[] gapMap()
1154 String seq = jalview.analysis.AlignSeq.extractGaps(
1155 jalview.util.Comparison.GapChars, new String(sequence));
1156 int[] map = new int[seq.length()];
1160 while (j < sequence.length)
1162 if (!jalview.util.Comparison.isGap(sequence[j]))
1174 * Build a bitset corresponding to sequence gaps
1176 * @return a BitSet where set values correspond to gaps in the sequence
1179 public BitSet gapBitset()
1181 BitSet gaps = new BitSet(sequence.length);
1183 while (j < sequence.length)
1185 if (jalview.util.Comparison.isGap(sequence[j]))
1195 public int[] findPositionMap()
1197 int map[] = new int[sequence.length];
1200 int seqlen = sequence.length;
1201 while ((j < seqlen))
1204 if (!jalview.util.Comparison.isGap(sequence[j]))
1215 public List<int[]> getInsertions()
1217 ArrayList<int[]> map = new ArrayList<>();
1218 int lastj = -1, j = 0;
1220 int seqlen = sequence.length;
1221 while ((j < seqlen))
1223 if (jalview.util.Comparison.isGap(sequence[j]))
1234 map.add(new int[] { lastj, j - 1 });
1242 map.add(new int[] { lastj, j - 1 });
1249 public BitSet getInsertionsAsBits()
1251 BitSet map = new BitSet();
1252 int lastj = -1, j = 0;
1254 int seqlen = sequence.length;
1255 while ((j < seqlen))
1257 if (jalview.util.Comparison.isGap(sequence[j]))
1283 public void deleteChars(final int i, final int j)
1285 int newstart = start, newend = end;
1286 if (i >= sequence.length || i < 0)
1291 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1292 boolean createNewDs = false;
1293 // TODO: take a (second look) at the dataset creation validation method for
1294 // the very large sequence case
1296 int startIndex = findIndex(start) - 1;
1297 int endIndex = findIndex(end) - 1;
1298 int startDeleteColumn = -1; // for dataset sequence deletions
1299 int deleteCount = 0;
1301 for (int s = i; s < j && s < sequence.length; s++)
1303 if (Comparison.isGap(sequence[s]))
1308 if (startDeleteColumn == -1)
1310 startDeleteColumn = findPosition(s) - start;
1318 if (startIndex == s)
1321 * deleting characters from start of sequence; new start is the
1322 * sequence position of the next column (position to the right
1323 * if the column position is gapped)
1325 newstart = findPosition(j);
1333 * deleting characters at end of sequence; new end is the sequence
1334 * position of the column before the deletion; subtract 1 if this is
1335 * gapped since findPosition returns the next sequence position
1337 newend = findPosition(i - 1);
1338 if (Comparison.isGap(sequence[i - 1]))
1353 if (createNewDs && this.datasetSequence != null)
1356 * if deletion occured in the middle of the sequence,
1357 * construct a new dataset sequence and delete the residues
1358 * that were deleted from the aligned sequence
1360 Sequence ds = new Sequence(datasetSequence);
1361 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1362 datasetSequence = ds;
1363 // TODO: remove any non-inheritable properties ?
1364 // TODO: create a sequence mapping (since there is a relation here ?)
1373 public void insertCharAt(int i, int length, char c)
1375 char[] tmp = new char[sequence.length + length];
1377 if (i >= sequence.length)
1379 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1380 i = sequence.length;
1384 System.arraycopy(sequence, 0, tmp, 0, i);
1394 if (i < sequence.length)
1396 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1404 public void insertCharAt(int i, char c)
1406 insertCharAt(i, 1, c);
1410 public String getVamsasId()
1416 public void setVamsasId(String id)
1423 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1425 if (dbrefs == null && datasetSequence != null
1426 && this != datasetSequence)
1428 datasetSequence.setDBRefs(newDBrefs);
1436 public DBModList<DBRefEntry> getDBRefs()
1438 if (dbrefs == null && datasetSequence != null
1439 && this != datasetSequence)
1441 return datasetSequence.getDBRefs();
1447 public void addDBRef(DBRefEntry entry)
1449 if (datasetSequence != null)
1451 datasetSequence.addDBRef(entry);
1457 dbrefs = new DBModList<>();
1460 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1462 if (dbrefs.get(ib).updateFrom(entry))
1465 * found a dbref that either matched, or could be
1466 * updated from, the new entry - no need to add it
1474 // * extend the array to make room for one more
1476 // // TODO use an ArrayList instead
1477 // int j = dbrefs.length;
1478 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1479 // System.arraycopy(dbrefs, 0, temp, 0, j);
1480 // temp[temp.length - 1] = entry;
1488 public void setDatasetSequence(SequenceI seq)
1492 throw new IllegalArgumentException(
1493 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1495 if (seq != null && seq.getDatasetSequence() != null)
1497 throw new IllegalArgumentException(
1498 "Implementation error: cascading dataset sequences are not allowed.");
1500 datasetSequence = seq;
1504 public SequenceI getDatasetSequence()
1506 return datasetSequence;
1510 public AlignmentAnnotation[] getAnnotation()
1512 return annotation == null ? null
1514 .toArray(new AlignmentAnnotation[annotation.size()]);
1518 public boolean hasAnnotation(AlignmentAnnotation ann)
1520 return annotation == null ? false : annotation.contains(ann);
1524 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1526 if (this.annotation == null)
1528 this.annotation = new Vector<>();
1530 if (!this.annotation.contains(annotation))
1532 this.annotation.addElement(annotation);
1534 annotation.setSequenceRef(this);
1538 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1540 if (this.annotation != null)
1542 this.annotation.removeElement(annotation);
1543 if (this.annotation.size() == 0)
1545 this.annotation = null;
1551 * test if this is a valid candidate for another sequence's dataset sequence.
1554 private boolean isValidDatasetSequence()
1556 if (datasetSequence != null)
1560 for (int i = 0; i < sequence.length; i++)
1562 if (jalview.util.Comparison.isGap(sequence[i]))
1571 public SequenceI deriveSequence()
1573 Sequence seq = null;
1574 if (datasetSequence == null)
1576 if (isValidDatasetSequence())
1578 // Use this as dataset sequence
1579 seq = new Sequence(getName(), "", 1, -1);
1580 seq.setDatasetSequence(this);
1581 seq.initSeqFrom(this, getAnnotation());
1586 // Create a new, valid dataset sequence
1587 createDatasetSequence();
1590 return new Sequence(this);
1593 private boolean _isNa;
1595 private int _seqhash = 0;
1597 private List<DBRefEntry> primaryRefs;
1600 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1604 public boolean isProtein()
1606 if (datasetSequence != null)
1608 return datasetSequence.isProtein();
1610 if (_seqhash != sequence.hashCode())
1612 _seqhash = sequence.hashCode();
1613 _isNa = Comparison.isNucleotide(this);
1621 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1624 public SequenceI createDatasetSequence()
1626 if (datasetSequence == null)
1628 Sequence dsseq = new Sequence(getName(),
1629 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1630 getSequenceAsString()),
1631 getStart(), getEnd());
1633 datasetSequence = dsseq;
1635 dsseq.setDescription(description);
1636 // move features and database references onto dataset sequence
1637 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1638 sequenceFeatureStore = null;
1639 dsseq.dbrefs = dbrefs;
1641 // TODO: search and replace any references to this sequence with
1642 // references to the dataset sequence in Mappings on dbref
1643 dsseq.pdbIds = pdbIds;
1645 datasetSequence.updatePDBIds();
1646 if (annotation != null)
1648 // annotation is cloned rather than moved, to preserve what's currently
1650 for (AlignmentAnnotation aa : annotation)
1652 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1653 _aa.sequenceRef = datasetSequence;
1654 _aa.adjustForAlignment(); // uses annotation's own record of
1655 // sequence-column mapping
1656 datasetSequence.addAlignmentAnnotation(_aa);
1660 return datasetSequence;
1667 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1671 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1673 if (annotation != null)
1675 annotation.removeAllElements();
1677 if (annotations != null)
1679 for (int i = 0; i < annotations.length; i++)
1681 if (annotations[i] != null)
1683 addAlignmentAnnotation(annotations[i]);
1690 public AlignmentAnnotation[] getAnnotation(String label)
1692 if (annotation == null || annotation.size() == 0)
1697 Vector<AlignmentAnnotation> subset = new Vector<>();
1698 Enumeration<AlignmentAnnotation> e = annotation.elements();
1699 while (e.hasMoreElements())
1701 AlignmentAnnotation ann = e.nextElement();
1702 if (ann.label != null && ann.label.equals(label))
1704 subset.addElement(ann);
1707 if (subset.size() == 0)
1711 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1713 e = subset.elements();
1714 while (e.hasMoreElements())
1716 anns[i++] = e.nextElement();
1718 subset.removeAllElements();
1723 public boolean updatePDBIds()
1725 if (datasetSequence != null)
1727 // TODO: could merge DBRefs
1728 return datasetSequence.updatePDBIds();
1730 if (dbrefs == null || dbrefs.size() == 0)
1734 boolean added = false;
1735 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1737 DBRefEntry dbr = dbrefs.get(ib);
1738 if (DBRefSource.PDB.equals(dbr.getSource()))
1741 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1742 * PDB id is not already present in a 'matching' PDBEntry
1743 * Constructor parses out a chain code if appended to the accession id
1744 * (a fudge used to 'store' the chain code in the DBRef)
1746 PDBEntry pdbe = new PDBEntry(dbr);
1747 added |= addPDBId(pdbe);
1754 public void transferAnnotation(SequenceI entry, Mapping mp)
1756 if (datasetSequence != null)
1758 datasetSequence.transferAnnotation(entry, mp);
1761 if (entry.getDatasetSequence() != null)
1763 transferAnnotation(entry.getDatasetSequence(), mp);
1766 // transfer any new features from entry onto sequence
1767 if (entry.getSequenceFeatures() != null)
1770 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1771 for (SequenceFeature feature : sfs)
1773 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1774 : new SequenceFeature[]
1775 { new SequenceFeature(feature) };
1778 for (int sfi = 0; sfi < sf.length; sfi++)
1780 addSequenceFeature(sf[sfi]);
1786 // transfer PDB entries
1787 if (entry.getAllPDBEntries() != null)
1789 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1790 while (e.hasMoreElements())
1792 PDBEntry pdb = e.nextElement();
1796 // transfer database references
1797 List<DBRefEntry> entryRefs = entry.getDBRefs();
1798 if (entryRefs != null)
1800 for (int r = 0, n = entryRefs.size(); r < n; r++)
1802 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1803 if (newref.getMap() != null && mp != null)
1805 // remap ref using our local mapping
1807 // we also assume all version string setting is done by dbSourceProxy
1809 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1810 * newref.setSource(dbSource); }
1818 public void setRNA(RNA r)
1830 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1833 List<AlignmentAnnotation> result = new ArrayList<>();
1834 if (this.annotation != null)
1836 for (AlignmentAnnotation ann : annotation)
1838 if (ann.calcId != null && ann.calcId.equals(calcId)
1839 && ann.label != null && ann.label.equals(label))
1849 public String toString()
1851 return getDisplayId(false);
1855 public PDBEntry getPDBEntry(String pdbIdStr)
1857 if (getDatasetSequence() != null)
1859 return getDatasetSequence().getPDBEntry(pdbIdStr);
1865 List<PDBEntry> entries = getAllPDBEntries();
1866 for (PDBEntry entry : entries)
1868 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1876 private List<DBRefEntry> tmpList;
1879 public List<DBRefEntry> getPrimaryDBRefs()
1881 if (datasetSequence != null)
1883 return datasetSequence.getPrimaryDBRefs();
1885 if (dbrefs == null || dbrefs.size() == 0)
1887 return Collections.emptyList();
1889 synchronized (dbrefs)
1891 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1893 return primaryRefs; // no changes
1895 refModCount = dbrefs.getModCount();
1896 List<DBRefEntry> primaries = (primaryRefs == null
1897 ? (primaryRefs = new ArrayList<>())
1900 if (tmpList == null)
1902 tmpList = new ArrayList<>();
1903 tmpList.add(null); // for replacement
1905 for (int i = 0, n = dbrefs.size(); i < n; i++)
1907 DBRefEntry ref = dbrefs.get(i);
1908 if (!ref.isPrimaryCandidate())
1914 MapList mp = ref.getMap().getMap();
1915 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1917 // map only involves a subsequence, so cannot be primary
1921 // whilst it looks like it is a primary ref, we also sanity check type
1922 if (DBRefSource.PDB_CANONICAL_NAME
1923 .equals(ref.getCanonicalSourceName()))
1925 // PDB dbrefs imply there should be a PDBEntry associated
1926 // TODO: tighten PDB dbrefs
1927 // formally imply Jalview has actually downloaded and
1928 // parsed the pdb file. That means there should be a cached file
1929 // handle on the PDBEntry, and a real mapping between sequence and
1930 // extracted sequence from PDB file
1931 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1932 if (pdbentry == null || pdbentry.getFile() == null)
1939 // check standard protein or dna sources
1940 tmpList.set(0, ref);
1941 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1943 if (res == null || res.get(0) != tmpList.get(0))
1951 // version must be not null, as otherwise it will not be a candidate,
1953 DBRefUtils.ensurePrimaries(this, primaries);
1962 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1965 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1966 int endPos = fromColumn == toColumn ? startPos
1967 : findPosition(toColumn - 1);
1969 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1971 if (datasetSequence != null)
1973 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1978 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1982 * if end column is gapped, endPos may be to the right,
1983 * and we may have included adjacent or enclosing features;
1984 * remove any that are not enclosing, non-contact features
1986 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1987 && Comparison.isGap(sequence[toColumn - 1]);
1988 if (endPos > this.end || endColumnIsGapped)
1990 ListIterator<SequenceFeature> it = result.listIterator();
1991 while (it.hasNext())
1993 SequenceFeature sf = it.next();
1994 int sfBegin = sf.getBegin();
1995 int sfEnd = sf.getEnd();
1996 int featureStartColumn = findIndex(sfBegin);
1997 if (featureStartColumn > toColumn)
2001 else if (featureStartColumn < fromColumn)
2003 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2005 if (featureEndColumn < fromColumn)
2009 else if (featureEndColumn > toColumn && sf.isContactFeature())
2012 * remove an enclosing feature if it is a contact feature
2024 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2025 * token that has to match the one presented by the cursor
2028 public void sequenceChanged()
2037 public int replace(char c1, char c2)
2044 synchronized (sequence)
2046 for (int c = 0; c < sequence.length; c++)
2048 if (sequence[c] == c1)
2064 public String getSequenceStringFromIterator(Iterator<int[]> it)
2066 StringBuilder newSequence = new StringBuilder();
2067 while (it.hasNext())
2069 int[] block = it.next();
2072 newSequence.append(getSequence(block[0], block[1] + 1));
2076 newSequence.append(getSequence(block[0], block[1]));
2080 return newSequence.toString();
2084 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2088 if (!regions.hasNext())
2090 return findIndex(getStart()) - 1;
2093 // Simply walk along the sequence whilst watching for region
2095 int hideStart = getLength();
2097 boolean foundStart = false;
2099 // step through the non-gapped positions of the sequence
2100 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2102 // get alignment position of this residue in the sequence
2103 int p = findIndex(i) - 1;
2105 // update region start/end
2106 while (hideEnd < p && regions.hasNext())
2108 int[] region = regions.next();
2109 hideStart = region[0];
2110 hideEnd = region[1];
2114 hideStart = getLength();
2116 // update boundary for sequence
2128 // otherwise, sequence was completely hidden
2133 public Color getColor(int i)
2139 public Color setColor(int i, Color c)
2145 public void resetColors()