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;
30 import jalview.ws.params.InvalidArgumentException;
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
53 * whether there have been any changes. We use this to update
58 @SuppressWarnings("serial")
59 protected class DBModList<T> extends ArrayList<DBRefEntry> {
61 protected int getModCount() {
67 SequenceI datasetSequence;
71 private char[] sequence;
79 Vector<PDBEntry> pdbIds;
83 private DBModList<DBRefEntry> dbrefs; // controlled acces
86 * a flag to let us know that elements have changed in dbrefs
90 private int refModCount = 0;
95 * This annotation is displayed below the alignment but the positions are tied
96 * to the residues of this sequence
98 * TODO: change to List<>
100 Vector<AlignmentAnnotation> annotation;
102 private SequenceFeaturesI sequenceFeatureStore;
105 * A cursor holding the approximate current view position to the sequence,
106 * as determined by findIndex or findPosition or findPositions.
107 * Using a cursor as a hint allows these methods to be more performant for
110 private SequenceCursor cursor;
113 * A number that should be incremented whenever the sequence is edited.
114 * If the value matches the cursor token, then we can trust the cursor,
115 * if not then it should be recomputed.
117 private int changeCount;
120 * Creates a new Sequence object.
123 * display name string
125 * string to form a possibly gapped sequence out of
127 * first position of non-gap residue in the sequence
129 * last position of ungapped residues (nearly always only used for
132 public Sequence(String name, String sequence, int start, int end)
135 initSeqAndName(name, sequence.toCharArray(), start, end);
138 public Sequence(String name, char[] sequence, int start, int end)
141 initSeqAndName(name, sequence, start, end);
145 * Stage 1 constructor - assign name, sequence, and set start and end fields.
146 * start and end are updated values from name2 if it ends with /start-end
153 protected void initSeqAndName(String name2, char[] sequence2, int start2,
157 this.sequence = sequence2;
165 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
166 * start and end respectively and removes the suffix from the name
173 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
176 int slashPos = name.lastIndexOf('/');
177 if (slashPos > -1 && slashPos < name.length() - 1)
179 String suffix = name.substring(slashPos + 1);
180 String[] range = suffix.split("-");
181 if (range.length == 2)
185 int from = Integer.valueOf(range[0]);
186 int to = Integer.valueOf(range[1]);
187 if (from > 0 && to >= from)
189 name = name.substring(0, slashPos);
194 } catch (NumberFormatException e)
196 // leave name unchanged if suffix is invalid
203 * Ensures that 'end' is not before the end of the sequence, that is,
204 * (end-start+1) is at least as long as the count of ungapped positions. Note
205 * that end is permitted to be beyond the end of the sequence data.
207 void checkValidRange()
210 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
213 for (int j = 0; j < sequence.length; j++)
215 if (!Comparison.isGap(sequence[j]))
234 * default constructor
238 sequenceFeatureStore = new SequenceFeatures();
242 * Creates a new Sequence object.
249 public Sequence(String name, String sequence)
251 this(name, sequence, 1, -1);
255 * Creates a new Sequence object with new AlignmentAnnotations but inherits
256 * any existing dataset sequence reference. If non exists, everything is
260 * if seq is a dataset sequence, behaves like a plain old copy
263 public Sequence(SequenceI seq)
265 this(seq, seq.getAnnotation());
269 * Create a new sequence object with new features, DBRefEntries, and PDBIds
270 * but inherits any existing dataset sequence reference, and duplicate of any
271 * annotation that is present in the given annotation array.
274 * the sequence to be copied
275 * @param alAnnotation
276 * an array of annotation including some associated with seq
278 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
281 initSeqFrom(seq, alAnnotation);
285 * does the heavy lifting when cloning a dataset sequence, or coping data from
286 * dataset to a new derived sequence.
289 * - source of attributes.
290 * @param alAnnotation
291 * - alignment annotation present on seq that should be copied onto
294 protected void initSeqFrom(SequenceI seq,
295 AlignmentAnnotation[] alAnnotation)
297 char[] oseq = seq.getSequence(); // returns a copy of the array
298 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
300 description = seq.getDescription();
301 if (seq != datasetSequence)
303 setDatasetSequence(seq.getDatasetSequence());
307 * only copy DBRefs and seqfeatures if we really are a dataset sequence
309 if (datasetSequence == null)
311 List<DBRefEntry> dbr = seq.getDBRefs();
314 for (int i = 0, n = dbr.size(); i < n; i++)
316 addDBRef(new DBRefEntry(dbr.get(i)));
321 * make copies of any sequence features
323 for (SequenceFeature sf : seq.getSequenceFeatures())
325 addSequenceFeature(new SequenceFeature(sf));
329 if (seq.getAnnotation() != null)
331 AlignmentAnnotation[] sqann = seq.getAnnotation();
332 for (int i = 0; i < sqann.length; i++)
334 if (sqann[i] == null)
338 boolean found = (alAnnotation == null);
341 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
343 found = (alAnnotation[apos] == sqann[i]);
348 // only copy the given annotation
349 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
350 addAlignmentAnnotation(newann);
354 if (seq.getAllPDBEntries() != null)
356 Vector<PDBEntry> ids = seq.getAllPDBEntries();
357 for (PDBEntry pdb : ids)
359 this.addPDBId(new PDBEntry(pdb));
365 public void setSequenceFeatures(List<SequenceFeature> features)
367 if (datasetSequence != null)
369 datasetSequence.setSequenceFeatures(features);
372 sequenceFeatureStore = new SequenceFeatures(features);
376 public synchronized boolean addSequenceFeature(SequenceFeature sf)
378 if (sf.getType() == null)
380 System.err.println("SequenceFeature type may not be null: "
385 if (datasetSequence != null)
387 return datasetSequence.addSequenceFeature(sf);
390 return sequenceFeatureStore.add(sf);
394 public void deleteFeature(SequenceFeature sf)
396 if (datasetSequence != null)
398 datasetSequence.deleteFeature(sf);
402 sequenceFeatureStore.delete(sf);
412 public List<SequenceFeature> getSequenceFeatures()
414 if (datasetSequence != null)
416 return datasetSequence.getSequenceFeatures();
418 return sequenceFeatureStore.getAllFeatures();
422 public SequenceFeaturesI getFeatures()
424 return datasetSequence != null ? datasetSequence.getFeatures()
425 : sequenceFeatureStore;
429 public boolean addPDBId(PDBEntry entry)
433 pdbIds = new Vector<>();
438 for (PDBEntry pdbe : pdbIds)
440 if (pdbe.updateFrom(entry))
445 pdbIds.addElement(entry);
456 public void setPDBId(Vector<PDBEntry> id)
464 * @return DOCUMENT ME!
467 public Vector<PDBEntry> getAllPDBEntries()
469 return pdbIds == null ? new Vector<>() : pdbIds;
475 * @return DOCUMENT ME!
478 public String getDisplayId(boolean jvsuffix)
480 StringBuffer result = new StringBuffer(name);
483 result.append("/" + start + "-" + end);
486 return result.toString();
490 * Sets the sequence name. If the name ends in /start-end, then the start-end
491 * values are parsed out and set, and the suffix is removed from the name.
496 public void setName(String theName)
505 * @return DOCUMENT ME!
508 public String getName()
520 public void setStart(int start)
528 * @return DOCUMENT ME!
531 public int getStart()
543 public void setEnd(int end)
551 * @return DOCUMENT ME!
562 * @return DOCUMENT ME!
565 public int getLength()
567 return this.sequence.length;
577 public void setSequence(String seq)
579 this.sequence = seq.toCharArray();
585 public String getSequenceAsString()
587 return new String(sequence);
591 public String getSequenceAsString(int start, int end)
593 return new String(getSequence(start, end));
597 public char[] getSequence()
600 return sequence == null ? null : Arrays.copyOf(sequence,
607 * @see jalview.datamodel.SequenceI#getSequence(int, int)
610 public char[] getSequence(int start, int end)
616 // JBPNote - left to user to pad the result here (TODO:Decide on this
618 if (start >= sequence.length)
623 if (end >= sequence.length)
625 end = sequence.length;
628 char[] reply = new char[end - start];
629 System.arraycopy(sequence, start, reply, 0, end - start);
635 public SequenceI getSubSequence(int start, int end)
641 char[] seq = getSequence(start, end);
646 int nstart = findPosition(start);
647 int nend = findPosition(end) - 1;
648 // JBPNote - this is an incomplete copy.
649 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
650 nseq.setDescription(description);
651 if (datasetSequence != null)
653 nseq.setDatasetSequence(datasetSequence);
657 nseq.setDatasetSequence(this);
663 * Returns the character of the aligned sequence at the given position (base
664 * zero), or space if the position is not within the sequence's bounds
669 public char getCharAt(int i)
671 if (i >= 0 && i < sequence.length)
682 * Sets the sequence description, and also parses out any special formats of
688 public void setDescription(String desc)
690 this.description = desc;
694 public void setGeneLoci(String speciesId, String assemblyId,
695 String chromosomeId, MapList map)
697 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
698 + ":" + chromosomeId, new Mapping(map)));
702 * Returns the gene loci mapping for the sequence (may be null)
707 public GeneLociI getGeneLoci()
709 List<DBRefEntry> refs = getDBRefs();
712 for (final DBRefEntry ref : refs)
714 if (ref.isChromosome())
716 return new GeneLociI()
719 public String getSpeciesId()
721 return ref.getSource();
725 public String getAssemblyId()
727 return ref.getVersion();
731 public String getChromosomeId()
733 // strip off "chromosome:" prefix to chrId
734 return ref.getAccessionId().substring(
735 DBRefEntry.CHROMOSOME.length() + 1);
739 public MapList getMap()
741 return ref.getMap().getMap();
751 * Answers the description
756 public String getDescription()
758 return this.description;
765 public int findIndex(int pos)
768 * use a valid, hopefully nearby, cursor if available
770 if (isValidCursor(cursor))
772 return findIndex(pos, cursor);
780 * traverse sequence from the start counting gaps; make a note of
781 * the column of the first residue to save in the cursor
783 while ((i < sequence.length) && (j <= end) && (j <= pos))
785 if (!Comparison.isGap(sequence[i]))
796 if (j == end && j < pos)
801 updateCursor(pos, i, startColumn);
806 * Updates the cursor to the latest found residue and column position
813 * column position of the first sequence residue
815 protected void updateCursor(int residuePos, int column, int startColumn)
818 * preserve end residue column provided cursor was valid
820 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
822 if (residuePos == this.end)
827 cursor = new SequenceCursor(this, residuePos, column, startColumn,
828 endColumn, this.changeCount);
832 * Answers the aligned column position (1..) for the given residue position
833 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
834 * The hint may be left of, at, or to the right of the required position.
840 protected int findIndex(final int pos, SequenceCursor curs)
842 if (!isValidCursor(curs))
845 * wrong or invalidated cursor, compute de novo
847 return findIndex(pos);
850 if (curs.residuePosition == pos)
852 return curs.columnPosition;
856 * move left or right to find pos from hint.position
858 int col = curs.columnPosition - 1; // convert from base 1 to base 0
859 int newPos = curs.residuePosition;
860 int delta = newPos > pos ? -1 : 1;
862 while (newPos != pos)
864 col += delta; // shift one column left or right
869 if (col == sequence.length)
871 col--; // return last column if we failed to reach pos
874 if (!Comparison.isGap(sequence[col]))
880 col++; // convert back to base 1
883 * only update cursor if we found the target position
887 updateCursor(pos, col, curs.firstColumnPosition);
897 public int findPosition(final int column)
900 * use a valid, hopefully nearby, cursor if available
902 if (isValidCursor(cursor))
904 return findPosition(column + 1, cursor);
907 // TODO recode this more naturally i.e. count residues only
908 // as they are found, not 'in anticipation'
911 * traverse the sequence counting gaps; note the column position
912 * of the first residue, to save in the cursor
914 int firstResidueColumn = 0;
915 int lastPosFound = 0;
916 int lastPosFoundColumn = 0;
917 int seqlen = sequence.length;
919 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
921 lastPosFound = start;
922 lastPosFoundColumn = 0;
928 while (j < column && j < seqlen)
930 if (!Comparison.isGap(sequence[j]))
933 lastPosFoundColumn = j;
934 if (pos == this.start)
936 firstResidueColumn = j;
942 if (j < seqlen && !Comparison.isGap(sequence[j]))
945 lastPosFoundColumn = j;
946 if (pos == this.start)
948 firstResidueColumn = j;
953 * update the cursor to the last residue position found (if any)
954 * (converting column position to base 1)
956 if (lastPosFound != 0)
958 updateCursor(lastPosFound, lastPosFoundColumn + 1,
959 firstResidueColumn + 1);
966 * Answers true if the given cursor is not null, is for this sequence object,
967 * and has a token value that matches this object's changeCount, else false.
968 * This allows us to ignore a cursor as 'stale' if the sequence has been
969 * modified since the cursor was created.
974 protected boolean isValidCursor(SequenceCursor curs)
976 if (curs == null || curs.sequence != this || curs.token != changeCount)
981 * sanity check against range
983 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
987 if (curs.residuePosition < start || curs.residuePosition > end)
995 * Answers the sequence position (start..) for the given aligned column
996 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
997 * may lie left of, at, or to the right of the column position.
1003 protected int findPosition(final int col, SequenceCursor curs)
1005 if (!isValidCursor(curs))
1008 * wrong or invalidated cursor, compute de novo
1010 return findPosition(col - 1);// ugh back to base 0
1013 if (curs.columnPosition == col)
1015 cursor = curs; // in case this method becomes public
1016 return curs.residuePosition; // easy case :-)
1019 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1022 * sequence lies entirely to the left of col
1023 * - return last residue + 1
1028 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1031 * sequence lies entirely to the right of col
1032 * - return first residue
1037 // todo could choose closest to col out of column,
1038 // firstColumnPosition, lastColumnPosition as a start point
1041 * move left or right to find pos from cursor position
1043 int firstResidueColumn = curs.firstColumnPosition;
1044 int column = curs.columnPosition - 1; // to base 0
1045 int newPos = curs.residuePosition;
1046 int delta = curs.columnPosition > col ? -1 : 1;
1047 boolean gapped = false;
1048 int lastFoundPosition = curs.residuePosition;
1049 int lastFoundPositionColumn = curs.columnPosition;
1051 while (column != col - 1)
1053 column += delta; // shift one column left or right
1054 if (column < 0 || column == sequence.length)
1058 gapped = Comparison.isGap(sequence[column]);
1062 lastFoundPosition = newPos;
1063 lastFoundPositionColumn = column + 1;
1064 if (lastFoundPosition == this.start)
1066 firstResidueColumn = column + 1;
1071 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1073 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1074 firstResidueColumn);
1078 * hack to give position to the right if on a gap
1079 * or beyond the length of the sequence (see JAL-2562)
1081 if (delta > 0 && (gapped || column >= sequence.length))
1093 public Range findPositions(int fromColumn, int toColumn)
1095 if (toColumn < fromColumn || fromColumn < 1)
1101 * find the first non-gapped position, if any
1103 int firstPosition = 0;
1104 int col = fromColumn - 1;
1105 int length = sequence.length;
1106 while (col < length && col < toColumn)
1108 if (!Comparison.isGap(sequence[col]))
1110 firstPosition = findPosition(col++);
1116 if (firstPosition == 0)
1122 * find the last non-gapped position
1124 int lastPosition = firstPosition;
1125 while (col < length && col < toColumn)
1127 if (!Comparison.isGap(sequence[col++]))
1133 return new Range(firstPosition, lastPosition);
1137 * Returns an int array where indices correspond to each residue in the
1138 * sequence and the element value gives its position in the alignment
1140 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1141 * residues in SequenceI object
1144 public int[] gapMap()
1146 String seq = jalview.analysis.AlignSeq.extractGaps(
1147 jalview.util.Comparison.GapChars, new String(sequence));
1148 int[] map = new int[seq.length()];
1152 while (j < sequence.length)
1154 if (!jalview.util.Comparison.isGap(sequence[j]))
1166 * Build a bitset corresponding to sequence gaps
1168 * @return a BitSet where set values correspond to gaps in the sequence
1171 public BitSet gapBitset()
1173 BitSet gaps = new BitSet(sequence.length);
1175 while (j < sequence.length)
1177 if (jalview.util.Comparison.isGap(sequence[j]))
1187 public int[] findPositionMap()
1189 int map[] = new int[sequence.length];
1192 int seqlen = sequence.length;
1193 while ((j < seqlen))
1196 if (!jalview.util.Comparison.isGap(sequence[j]))
1207 public List<int[]> getInsertions()
1209 ArrayList<int[]> map = new ArrayList<>();
1210 int lastj = -1, j = 0;
1212 int seqlen = sequence.length;
1213 while ((j < seqlen))
1215 if (jalview.util.Comparison.isGap(sequence[j]))
1226 map.add(new int[] { lastj, j - 1 });
1234 map.add(new int[] { lastj, j - 1 });
1241 public BitSet getInsertionsAsBits()
1243 BitSet map = new BitSet();
1244 int lastj = -1, j = 0;
1246 int seqlen = sequence.length;
1247 while ((j < seqlen))
1249 if (jalview.util.Comparison.isGap(sequence[j]))
1275 public void deleteChars(final int i, final int j)
1277 int newstart = start, newend = end;
1278 if (i >= sequence.length || i < 0)
1283 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1284 boolean createNewDs = false;
1285 // TODO: take a (second look) at the dataset creation validation method for
1286 // the very large sequence case
1288 int startIndex = findIndex(start) - 1;
1289 int endIndex = findIndex(end) - 1;
1290 int startDeleteColumn = -1; // for dataset sequence deletions
1291 int deleteCount = 0;
1293 for (int s = i; s < j && s < sequence.length; s++)
1295 if (Comparison.isGap(sequence[s]))
1300 if (startDeleteColumn == -1)
1302 startDeleteColumn = findPosition(s) - start;
1310 if (startIndex == s)
1313 * deleting characters from start of sequence; new start is the
1314 * sequence position of the next column (position to the right
1315 * if the column position is gapped)
1317 newstart = findPosition(j);
1325 * deleting characters at end of sequence; new end is the sequence
1326 * position of the column before the deletion; subtract 1 if this is
1327 * gapped since findPosition returns the next sequence position
1329 newend = findPosition(i - 1);
1330 if (Comparison.isGap(sequence[i - 1]))
1345 if (createNewDs && this.datasetSequence != null)
1348 * if deletion occured in the middle of the sequence,
1349 * construct a new dataset sequence and delete the residues
1350 * that were deleted from the aligned sequence
1352 Sequence ds = new Sequence(datasetSequence);
1353 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1354 datasetSequence = ds;
1355 // TODO: remove any non-inheritable properties ?
1356 // TODO: create a sequence mapping (since there is a relation here ?)
1365 public void insertCharAt(int i, int length, char c)
1367 char[] tmp = new char[sequence.length + length];
1369 if (i >= sequence.length)
1371 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1372 i = sequence.length;
1376 System.arraycopy(sequence, 0, tmp, 0, i);
1386 if (i < sequence.length)
1388 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1396 public void insertCharAt(int i, char c)
1398 insertCharAt(i, 1, c);
1402 public String getVamsasId()
1408 public void setVamsasId(String id)
1413 @SuppressWarnings("deprecation")
1415 public void setDBRefs(List<DBRefEntry> newDBrefs) throws InvalidArgumentException
1417 if (dbrefs == null && datasetSequence != null
1418 && this != datasetSequence)
1420 datasetSequence.setDBRefs((DBModList<DBRefEntry>)newDBrefs);
1423 if (newDBrefs != null && !(newDBrefs instanceof DBModList<?>))
1424 throw new InvalidArgumentException("DBrefs must have DBModList class");
1426 dbrefs = (DBModList<DBRefEntry>)newDBrefs;
1431 public void getDBRefsFrom(SequenceI seq) {
1433 setDBRefs(seq.getDBRefs());
1434 } catch (InvalidArgumentException e) {
1435 // TODO Auto-generated catch block
1436 e.printStackTrace();
1441 public List<DBRefEntry> getDBRefs()
1443 if (dbrefs == null && datasetSequence != null
1444 && this != datasetSequence)
1446 return datasetSequence.getDBRefs();
1453 public void addDBRef(DBRefEntry entry)
1455 if (datasetSequence != null)
1457 datasetSequence.addDBRef(entry);
1463 dbrefs = new DBModList<DBRefEntry>();
1466 for (int ib = 0, nb= dbrefs.size(); ib < nb; ib++)
1468 if (dbrefs.get(ib).updateFrom(entry))
1471 * found a dbref that either matched, or could be
1472 * updated from, the new entry - no need to add it
1481 // * extend the array to make room for one more
1483 // // TODO use an ArrayList instead
1484 // int j = dbrefs.length;
1485 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1486 // System.arraycopy(dbrefs, 0, temp, 0, j);
1487 // temp[temp.length - 1] = entry;
1495 public void setDatasetSequence(SequenceI seq)
1499 throw new IllegalArgumentException(
1500 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1502 if (seq != null && seq.getDatasetSequence() != null)
1504 throw new IllegalArgumentException(
1505 "Implementation error: cascading dataset sequences are not allowed.");
1507 datasetSequence = seq;
1511 public SequenceI getDatasetSequence()
1513 return datasetSequence;
1517 public AlignmentAnnotation[] getAnnotation()
1519 return annotation == null ? null
1521 .toArray(new AlignmentAnnotation[annotation.size()]);
1525 public boolean hasAnnotation(AlignmentAnnotation ann)
1527 return annotation == null ? false : annotation.contains(ann);
1531 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1533 if (this.annotation == null)
1535 this.annotation = new Vector<>();
1537 if (!this.annotation.contains(annotation))
1539 this.annotation.addElement(annotation);
1541 annotation.setSequenceRef(this);
1545 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1547 if (this.annotation != null)
1549 this.annotation.removeElement(annotation);
1550 if (this.annotation.size() == 0)
1552 this.annotation = null;
1558 * test if this is a valid candidate for another sequence's dataset sequence.
1561 private boolean isValidDatasetSequence()
1563 if (datasetSequence != null)
1567 for (int i = 0; i < sequence.length; i++)
1569 if (jalview.util.Comparison.isGap(sequence[i]))
1578 public SequenceI deriveSequence()
1580 Sequence seq = null;
1581 if (datasetSequence == null)
1583 if (isValidDatasetSequence())
1585 // Use this as dataset sequence
1586 seq = new Sequence(getName(), "", 1, -1);
1587 seq.setDatasetSequence(this);
1588 seq.initSeqFrom(this, getAnnotation());
1593 // Create a new, valid dataset sequence
1594 createDatasetSequence();
1597 return new Sequence(this);
1600 private boolean _isNa;
1602 private int _seqhash = 0;
1604 private List<DBRefEntry> primaryRefs;
1607 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1611 public boolean isProtein()
1613 if (datasetSequence != null)
1615 return datasetSequence.isProtein();
1617 if (_seqhash != sequence.hashCode())
1619 _seqhash = sequence.hashCode();
1620 _isNa = Comparison.isNucleotide(this);
1628 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1631 public SequenceI createDatasetSequence()
1633 if (datasetSequence == null)
1635 Sequence dsseq = new Sequence(getName(),
1636 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1637 getSequenceAsString()),
1638 getStart(), getEnd());
1640 datasetSequence = dsseq;
1642 dsseq.setDescription(description);
1643 // move features and database references onto dataset sequence
1644 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1645 sequenceFeatureStore = null;
1646 dsseq.dbrefs = dbrefs;
1648 // TODO: search and replace any references to this sequence with
1649 // references to the dataset sequence in Mappings on dbref
1650 dsseq.pdbIds = pdbIds;
1652 datasetSequence.updatePDBIds();
1653 if (annotation != null)
1655 // annotation is cloned rather than moved, to preserve what's currently
1657 for (AlignmentAnnotation aa : annotation)
1659 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1660 _aa.sequenceRef = datasetSequence;
1661 _aa.adjustForAlignment(); // uses annotation's own record of
1662 // sequence-column mapping
1663 datasetSequence.addAlignmentAnnotation(_aa);
1667 return datasetSequence;
1674 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1678 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1680 if (annotation != null)
1682 annotation.removeAllElements();
1684 if (annotations != null)
1686 for (int i = 0; i < annotations.length; i++)
1688 if (annotations[i] != null)
1690 addAlignmentAnnotation(annotations[i]);
1697 public AlignmentAnnotation[] getAnnotation(String label)
1699 if (annotation == null || annotation.size() == 0)
1704 Vector<AlignmentAnnotation> subset = new Vector<>();
1705 Enumeration<AlignmentAnnotation> e = annotation.elements();
1706 while (e.hasMoreElements())
1708 AlignmentAnnotation ann = e.nextElement();
1709 if (ann.label != null && ann.label.equals(label))
1711 subset.addElement(ann);
1714 if (subset.size() == 0)
1718 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1720 e = subset.elements();
1721 while (e.hasMoreElements())
1723 anns[i++] = e.nextElement();
1725 subset.removeAllElements();
1730 public boolean updatePDBIds()
1732 if (datasetSequence != null)
1734 // TODO: could merge DBRefs
1735 return datasetSequence.updatePDBIds();
1737 if (dbrefs == null || dbrefs.size() == 0)
1741 boolean added = false;
1742 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1744 DBRefEntry dbr = dbrefs.get(ib);
1745 if (DBRefSource.PDB.equals(dbr.getSource()))
1748 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1749 * PDB id is not already present in a 'matching' PDBEntry
1750 * Constructor parses out a chain code if appended to the accession id
1751 * (a fudge used to 'store' the chain code in the DBRef)
1753 PDBEntry pdbe = new PDBEntry(dbr);
1754 added |= addPDBId(pdbe);
1761 public void transferAnnotation(SequenceI entry, Mapping mp)
1763 if (datasetSequence != null)
1765 datasetSequence.transferAnnotation(entry, mp);
1768 if (entry.getDatasetSequence() != null)
1770 transferAnnotation(entry.getDatasetSequence(), mp);
1773 // transfer any new features from entry onto sequence
1774 if (entry.getSequenceFeatures() != null)
1777 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1778 for (SequenceFeature feature : sfs)
1780 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1781 : new SequenceFeature[] { new SequenceFeature(feature) };
1784 for (int sfi = 0; sfi < sf.length; sfi++)
1786 addSequenceFeature(sf[sfi]);
1792 // transfer PDB entries
1793 if (entry.getAllPDBEntries() != null)
1795 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1796 while (e.hasMoreElements())
1798 PDBEntry pdb = e.nextElement();
1802 // transfer database references
1803 List<DBRefEntry> entryRefs = entry.getDBRefs();
1804 if (entryRefs != null)
1806 for (int r = 0, n = entryRefs.size(); r < n; r++)
1808 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1809 if (newref.getMap() != null && mp != null)
1811 // remap ref using our local mapping
1813 // we also assume all version string setting is done by dbSourceProxy
1815 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1816 * newref.setSource(dbSource); }
1824 public void setRNA(RNA r)
1836 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1839 List<AlignmentAnnotation> result = new ArrayList<>();
1840 if (this.annotation != null)
1842 for (AlignmentAnnotation ann : annotation)
1844 if (ann.calcId != null && ann.calcId.equals(calcId)
1845 && ann.label != null && ann.label.equals(label))
1855 public String toString()
1857 return getDisplayId(false);
1861 public PDBEntry getPDBEntry(String pdbIdStr)
1863 if (getDatasetSequence() != null)
1865 return getDatasetSequence().getPDBEntry(pdbIdStr);
1871 List<PDBEntry> entries = getAllPDBEntries();
1872 for (PDBEntry entry : entries)
1874 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1882 private List<DBRefEntry> tmpList;
1885 public List<DBRefEntry> getPrimaryDBRefs()
1887 if (datasetSequence != null)
1889 return datasetSequence.getPrimaryDBRefs();
1891 if (dbrefs == null || dbrefs.size() == 0)
1893 return Collections.emptyList();
1895 synchronized (dbrefs)
1897 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1898 return primaryRefs; // no changes
1899 refModCount = dbrefs.getModCount();
1900 List<DBRefEntry> primaries = (primaryRefs == null ? (primaryRefs = new ArrayList<>()) : primaryRefs);
1902 if (tmpList == null) {
1903 tmpList = new ArrayList<>();
1904 tmpList.add(null); // for replacement
1906 for (int i = 0, n = dbrefs.size(); i < n; i++)
1908 DBRefEntry ref = dbrefs.get(i);
1909 if (!ref.isPrimaryCandidate())
1915 MapList mp = ref.getMap().getMap();
1916 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1918 // map only involves a subsequence, so cannot be primary
1922 // whilst it looks like it is a primary ref, we also sanity check type
1923 if (DBRefSource.PDB_CANONICAL_NAME.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)
1937 // check standard protein or dna sources
1938 tmpList.set(0, ref);
1939 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(), tmpList);
1940 if (res == null || res.get(0) != tmpList.get(0))
1948 DBRefUtils.ensurePrimaries(this, primaries);
1957 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1960 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1961 int endPos = fromColumn == toColumn ? startPos
1962 : findPosition(toColumn - 1);
1964 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1966 if (datasetSequence != null)
1968 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1973 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1977 * if end column is gapped, endPos may be to the right,
1978 * and we may have included adjacent or enclosing features;
1979 * remove any that are not enclosing, non-contact features
1981 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1982 && Comparison.isGap(sequence[toColumn - 1]);
1983 if (endPos > this.end || endColumnIsGapped)
1985 ListIterator<SequenceFeature> it = result.listIterator();
1986 while (it.hasNext())
1988 SequenceFeature sf = it.next();
1989 int sfBegin = sf.getBegin();
1990 int sfEnd = sf.getEnd();
1991 int featureStartColumn = findIndex(sfBegin);
1992 if (featureStartColumn > toColumn)
1996 else if (featureStartColumn < fromColumn)
1998 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2000 if (featureEndColumn < fromColumn)
2004 else if (featureEndColumn > toColumn && sf.isContactFeature())
2007 * remove an enclosing feature if it is a contact feature
2019 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2020 * token that has to match the one presented by the cursor
2023 public void sequenceChanged()
2032 public int replace(char c1, char c2)
2039 synchronized (sequence)
2041 for (int c = 0; c < sequence.length; c++)
2043 if (sequence[c] == c1)
2059 public String getSequenceStringFromIterator(Iterator<int[]> it)
2061 StringBuilder newSequence = new StringBuilder();
2062 while (it.hasNext())
2064 int[] block = it.next();
2067 newSequence.append(getSequence(block[0], block[1] + 1));
2071 newSequence.append(getSequence(block[0], block[1]));
2075 return newSequence.toString();
2079 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2083 if (!regions.hasNext())
2085 return findIndex(getStart()) - 1;
2088 // Simply walk along the sequence whilst watching for region
2090 int hideStart = getLength();
2092 boolean foundStart = false;
2094 // step through the non-gapped positions of the sequence
2095 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2097 // get alignment position of this residue in the sequence
2098 int p = findIndex(i) - 1;
2100 // update region start/end
2101 while (hideEnd < p && regions.hasNext())
2103 int[] region = regions.next();
2104 hideStart = region[0];
2105 hideEnd = region[1];
2109 hideStart = getLength();
2111 // update boundary for sequence
2123 // otherwise, sequence was completely hidden