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.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.BitSet;
34 import java.util.Collections;
35 import java.util.Enumeration;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.ListIterator;
39 import java.util.Vector;
41 import fr.orsay.lri.varna.models.rna.RNA;
45 * Implements the SequenceI interface for a char[] based sequence object
47 public class Sequence extends ASequence implements SequenceI
51 * A subclass that gives us access to modCount, which tracks
52 * whether there have been any changes. We use this to update
57 @SuppressWarnings("serial")
58 public class DBModList<T> extends ArrayList<DBRefEntry> {
60 protected int getModCount() {
66 SequenceI datasetSequence;
70 private char[] sequence;
72 private String description;
78 private Vector<PDBEntry> pdbIds;
80 private String vamsasId;
82 private DBModList<DBRefEntry> dbrefs; // controlled access
85 * a flag to let us know that elements have changed in dbrefs
89 private int refModCount = 0;
94 * This annotation is displayed below the alignment but the positions are tied
95 * to the residues of this sequence
97 * TODO: change to List<>
99 private Vector<AlignmentAnnotation> annotation;
101 private SequenceFeaturesI sequenceFeatureStore;
104 * A cursor holding the approximate current view position to the sequence,
105 * as determined by findIndex or findPosition or findPositions.
106 * Using a cursor as a hint allows these methods to be more performant for
109 private SequenceCursor cursor;
112 * A number that should be incremented whenever the sequence is edited.
113 * If the value matches the cursor token, then we can trust the cursor,
114 * if not then it should be recomputed.
116 private int changeCount;
119 * Creates a new Sequence object.
122 * display name string
124 * string to form a possibly gapped sequence out of
126 * first position of non-gap residue in the sequence
128 * last position of ungapped residues (nearly always only used for
131 public Sequence(String name, String sequence, int start, int end)
134 initSeqAndName(name, sequence.toCharArray(), start, end);
137 public Sequence(String name, char[] sequence, int start, int end)
140 initSeqAndName(name, sequence, start, end);
144 * Stage 1 constructor - assign name, sequence, and set start and end fields.
145 * start and end are updated values from name2 if it ends with /start-end
152 protected void initSeqAndName(String name2, char[] sequence2, int start2,
156 this.sequence = sequence2;
164 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
165 * start and end respectively and removes the suffix from the name
172 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
175 int slashPos = name.lastIndexOf('/');
176 if (slashPos > -1 && slashPos < name.length() - 1)
178 String suffix = name.substring(slashPos + 1);
179 String[] range = suffix.split("-");
180 if (range.length == 2)
184 int from = Integer.valueOf(range[0]);
185 int to = Integer.valueOf(range[1]);
186 if (from > 0 && to >= from)
188 name = name.substring(0, slashPos);
193 } catch (NumberFormatException e)
195 // leave name unchanged if suffix is invalid
202 * Ensures that 'end' is not before the end of the sequence, that is,
203 * (end-start+1) is at least as long as the count of ungapped positions. Note
204 * that end is permitted to be beyond the end of the sequence data.
206 void checkValidRange()
209 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
212 for (int j = 0; j < sequence.length; j++)
214 if (!Comparison.isGap(sequence[j]))
233 * default constructor
237 sequenceFeatureStore = new SequenceFeatures();
241 * Creates a new Sequence object.
248 public Sequence(String name, String sequence)
250 this(name, sequence, 1, -1);
254 * Creates a new Sequence object with new AlignmentAnnotations but inherits
255 * any existing dataset sequence reference. If non exists, everything is
259 * if seq is a dataset sequence, behaves like a plain old copy
262 public Sequence(SequenceI seq)
264 this(seq, seq.getAnnotation());
268 * Create a new sequence object with new features, DBRefEntries, and PDBIds
269 * but inherits any existing dataset sequence reference, and duplicate of any
270 * annotation that is present in the given annotation array.
273 * the sequence to be copied
274 * @param alAnnotation
275 * an array of annotation including some associated with seq
277 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
280 initSeqFrom(seq, alAnnotation);
284 * does the heavy lifting when cloning a dataset sequence, or coping data from
285 * dataset to a new derived sequence.
288 * - source of attributes.
289 * @param alAnnotation
290 * - alignment annotation present on seq that should be copied onto
293 protected void initSeqFrom(SequenceI seq,
294 AlignmentAnnotation[] alAnnotation)
296 char[] oseq = seq.getSequence(); // returns a copy of the array
297 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
299 description = seq.getDescription();
300 if (seq != datasetSequence)
302 setDatasetSequence(seq.getDatasetSequence());
306 * only copy DBRefs and seqfeatures if we really are a dataset sequence
308 if (datasetSequence == null)
310 List<DBRefEntry> dbr = seq.getDBRefs();
313 for (int i = 0, n = dbr.size(); i < n; i++)
315 addDBRef(new DBRefEntry(dbr.get(i)));
320 * make copies of any sequence features
322 for (SequenceFeature sf : seq.getSequenceFeatures())
324 addSequenceFeature(new SequenceFeature(sf));
328 if (seq.getAnnotation() != null)
330 AlignmentAnnotation[] sqann = seq.getAnnotation();
331 for (int i = 0; i < sqann.length; i++)
333 if (sqann[i] == null)
337 boolean found = (alAnnotation == null);
340 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
342 found = (alAnnotation[apos] == sqann[i]);
347 // only copy the given annotation
348 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
349 addAlignmentAnnotation(newann);
353 if (seq.getAllPDBEntries() != null)
355 Vector<PDBEntry> ids = seq.getAllPDBEntries();
356 for (PDBEntry pdb : ids)
358 this.addPDBId(new PDBEntry(pdb));
364 public void setSequenceFeatures(List<SequenceFeature> features)
366 if (datasetSequence != null)
368 datasetSequence.setSequenceFeatures(features);
371 sequenceFeatureStore = new SequenceFeatures(features);
375 public synchronized boolean addSequenceFeature(SequenceFeature sf)
377 if (sf.getType() == null)
379 System.err.println("SequenceFeature type may not be null: "
384 if (datasetSequence != null)
386 return datasetSequence.addSequenceFeature(sf);
389 return sequenceFeatureStore.add(sf);
393 public void deleteFeature(SequenceFeature sf)
395 if (datasetSequence != null)
397 datasetSequence.deleteFeature(sf);
401 sequenceFeatureStore.delete(sf);
411 public List<SequenceFeature> getSequenceFeatures()
413 if (datasetSequence != null)
415 return datasetSequence.getSequenceFeatures();
417 return sequenceFeatureStore.getAllFeatures();
421 public SequenceFeaturesI getFeatures()
423 return datasetSequence != null ? datasetSequence.getFeatures()
424 : sequenceFeatureStore;
428 public boolean addPDBId(PDBEntry entry)
432 pdbIds = new Vector<>();
437 for (PDBEntry pdbe : pdbIds)
439 if (pdbe.updateFrom(entry))
444 pdbIds.addElement(entry);
455 public void setPDBId(Vector<PDBEntry> id)
463 * @return DOCUMENT ME!
466 public Vector<PDBEntry> getAllPDBEntries()
468 return pdbIds == null ? new Vector<>() : pdbIds;
474 * @return DOCUMENT ME!
477 public String getDisplayId(boolean jvsuffix)
479 StringBuffer result = new StringBuffer(name);
482 result.append("/" + start + "-" + end);
485 return result.toString();
489 * Sets the sequence name. If the name ends in /start-end, then the start-end
490 * values are parsed out and set, and the suffix is removed from the name.
495 public void setName(String theName)
504 * @return DOCUMENT ME!
507 public String getName()
519 public void setStart(int start)
527 * @return DOCUMENT ME!
530 public int getStart()
542 public void setEnd(int end)
550 * @return DOCUMENT ME!
561 * @return DOCUMENT ME!
564 public int getLength()
566 return this.sequence.length;
576 public void setSequence(String seq)
578 this.sequence = seq.toCharArray();
584 public String getSequenceAsString()
586 return new String(sequence);
590 public String getSequenceAsString(int start, int end)
592 return new String(getSequence(start, end));
596 public char[] getSequence()
599 return sequence == null ? null : Arrays.copyOf(sequence,
606 * @see jalview.datamodel.SequenceI#getSequence(int, int)
609 public char[] getSequence(int start, int end)
615 // JBPNote - left to user to pad the result here (TODO:Decide on this
617 if (start >= sequence.length)
622 if (end >= sequence.length)
624 end = sequence.length;
627 char[] reply = new char[end - start];
628 System.arraycopy(sequence, start, reply, 0, end - start);
634 public SequenceI getSubSequence(int start, int end)
640 char[] seq = getSequence(start, end);
645 int nstart = findPosition(start);
646 int nend = findPosition(end) - 1;
647 // JBPNote - this is an incomplete copy.
648 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
649 nseq.setDescription(description);
650 if (datasetSequence != null)
652 nseq.setDatasetSequence(datasetSequence);
656 nseq.setDatasetSequence(this);
662 * Returns the character of the aligned sequence at the given position (base
663 * zero), or space if the position is not within the sequence's bounds
668 public char getCharAt(int i)
670 if (i >= 0 && i < sequence.length)
681 * Sets the sequence description, and also parses out any special formats of
687 public void setDescription(String desc)
689 this.description = desc;
693 public void setGeneLoci(String speciesId, String assemblyId,
694 String chromosomeId, MapList map)
696 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
697 + ":" + chromosomeId, new Mapping(map)));
701 * Returns the gene loci mapping for the sequence (may be null)
706 public GeneLociI getGeneLoci()
708 List<DBRefEntry> refs = getDBRefs();
711 for (final DBRefEntry ref : refs)
713 if (ref.isChromosome())
715 return new GeneLociI()
718 public String getSpeciesId()
720 return ref.getSource();
724 public String getAssemblyId()
726 // DEV NOTE: DBRefEntry is reused here to hold chromosomal locus of a gene sequence.
727 // source=species, version=assemblyId, accession=chromosome, map = positions.
729 return ref.getVersion();
733 public String getChromosomeId()
735 // strip off "chromosome:" prefix to chrId
736 return ref.getAccessionId().substring(
737 DBRefEntry.CHROMOSOME.length() + 1);
741 public MapList getMap()
743 return ref.getMap().getMap();
753 * Answers the description
758 public String getDescription()
760 return this.description;
767 public int findIndex(int pos)
770 * use a valid, hopefully nearby, cursor if available
772 if (isValidCursor(cursor))
774 return findIndex(pos, cursor);
782 * traverse sequence from the start counting gaps; make a note of
783 * the column of the first residue to save in the cursor
785 while ((i < sequence.length) && (j <= end) && (j <= pos))
787 if (!Comparison.isGap(sequence[i]))
798 if (j == end && j < pos)
803 updateCursor(pos, i, startColumn);
808 * Updates the cursor to the latest found residue and column position
815 * column position of the first sequence residue
817 protected void updateCursor(int residuePos, int column, int startColumn)
820 * preserve end residue column provided cursor was valid
822 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
824 if (residuePos == this.end)
829 cursor = new SequenceCursor(this, residuePos, column, startColumn,
830 endColumn, this.changeCount);
834 * Answers the aligned column position (1..) for the given residue position
835 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
836 * The hint may be left of, at, or to the right of the required position.
842 protected int findIndex(final int pos, SequenceCursor curs)
844 if (!isValidCursor(curs))
847 * wrong or invalidated cursor, compute de novo
849 return findIndex(pos);
852 if (curs.residuePosition == pos)
854 return curs.columnPosition;
858 * move left or right to find pos from hint.position
860 int col = curs.columnPosition - 1; // convert from base 1 to base 0
861 int newPos = curs.residuePosition;
862 int delta = newPos > pos ? -1 : 1;
864 while (newPos != pos)
866 col += delta; // shift one column left or right
871 if (col == sequence.length)
873 col--; // return last column if we failed to reach pos
876 if (!Comparison.isGap(sequence[col]))
882 col++; // convert back to base 1
885 * only update cursor if we found the target position
889 updateCursor(pos, col, curs.firstColumnPosition);
899 public int findPosition(final int column)
902 * use a valid, hopefully nearby, cursor if available
904 if (isValidCursor(cursor))
906 return findPosition(column + 1, cursor);
909 // TODO recode this more naturally i.e. count residues only
910 // as they are found, not 'in anticipation'
913 * traverse the sequence counting gaps; note the column position
914 * of the first residue, to save in the cursor
916 int firstResidueColumn = 0;
917 int lastPosFound = 0;
918 int lastPosFoundColumn = 0;
919 int seqlen = sequence.length;
921 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
923 lastPosFound = start;
924 lastPosFoundColumn = 0;
930 while (j < column && j < seqlen)
932 if (!Comparison.isGap(sequence[j]))
935 lastPosFoundColumn = j;
936 if (pos == this.start)
938 firstResidueColumn = j;
944 if (j < seqlen && !Comparison.isGap(sequence[j]))
947 lastPosFoundColumn = j;
948 if (pos == this.start)
950 firstResidueColumn = j;
955 * update the cursor to the last residue position found (if any)
956 * (converting column position to base 1)
958 if (lastPosFound != 0)
960 updateCursor(lastPosFound, lastPosFoundColumn + 1,
961 firstResidueColumn + 1);
968 * Answers true if the given cursor is not null, is for this sequence object,
969 * and has a token value that matches this object's changeCount, else false.
970 * This allows us to ignore a cursor as 'stale' if the sequence has been
971 * modified since the cursor was created.
976 protected boolean isValidCursor(SequenceCursor curs)
978 if (curs == null || curs.sequence != this || curs.token != changeCount)
983 * sanity check against range
985 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
989 if (curs.residuePosition < start || curs.residuePosition > end)
997 * Answers the sequence position (start..) for the given aligned column
998 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
999 * may lie left of, at, or to the right of the column position.
1005 protected int findPosition(final int col, SequenceCursor curs)
1007 if (!isValidCursor(curs))
1010 * wrong or invalidated cursor, compute de novo
1012 return findPosition(col - 1);// ugh back to base 0
1015 if (curs.columnPosition == col)
1017 cursor = curs; // in case this method becomes public
1018 return curs.residuePosition; // easy case :-)
1021 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1024 * sequence lies entirely to the left of col
1025 * - return last residue + 1
1030 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1033 * sequence lies entirely to the right of col
1034 * - return first residue
1039 // todo could choose closest to col out of column,
1040 // firstColumnPosition, lastColumnPosition as a start point
1043 * move left or right to find pos from cursor position
1045 int firstResidueColumn = curs.firstColumnPosition;
1046 int column = curs.columnPosition - 1; // to base 0
1047 int newPos = curs.residuePosition;
1048 int delta = curs.columnPosition > col ? -1 : 1;
1049 boolean gapped = false;
1050 int lastFoundPosition = curs.residuePosition;
1051 int lastFoundPositionColumn = curs.columnPosition;
1053 while (column != col - 1)
1055 column += delta; // shift one column left or right
1056 if (column < 0 || column == sequence.length)
1060 gapped = Comparison.isGap(sequence[column]);
1064 lastFoundPosition = newPos;
1065 lastFoundPositionColumn = column + 1;
1066 if (lastFoundPosition == this.start)
1068 firstResidueColumn = column + 1;
1073 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1075 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1076 firstResidueColumn);
1080 * hack to give position to the right if on a gap
1081 * or beyond the length of the sequence (see JAL-2562)
1083 if (delta > 0 && (gapped || column >= sequence.length))
1095 public Range findPositions(int fromColumn, int toColumn)
1097 if (toColumn < fromColumn || fromColumn < 1)
1103 * find the first non-gapped position, if any
1105 int firstPosition = 0;
1106 int col = fromColumn - 1;
1107 int length = sequence.length;
1108 while (col < length && col < toColumn)
1110 if (!Comparison.isGap(sequence[col]))
1112 firstPosition = findPosition(col++);
1118 if (firstPosition == 0)
1124 * find the last non-gapped position
1126 int lastPosition = firstPosition;
1127 while (col < length && col < toColumn)
1129 if (!Comparison.isGap(sequence[col++]))
1135 return new Range(firstPosition, lastPosition);
1139 * Returns an int array where indices correspond to each residue in the
1140 * sequence and the element value gives its position in the alignment
1142 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1143 * residues in SequenceI object
1146 public int[] gapMap()
1148 String seq = jalview.analysis.AlignSeq.extractGaps(
1149 jalview.util.Comparison.GapChars, new String(sequence));
1150 int[] map = new int[seq.length()];
1154 while (j < sequence.length)
1156 if (!jalview.util.Comparison.isGap(sequence[j]))
1168 * Build a bitset corresponding to sequence gaps
1170 * @return a BitSet where set values correspond to gaps in the sequence
1173 public BitSet gapBitset()
1175 BitSet gaps = new BitSet(sequence.length);
1177 while (j < sequence.length)
1179 if (jalview.util.Comparison.isGap(sequence[j]))
1189 public int[] findPositionMap()
1191 int map[] = new int[sequence.length];
1194 int seqlen = sequence.length;
1195 while ((j < seqlen))
1198 if (!jalview.util.Comparison.isGap(sequence[j]))
1209 public List<int[]> getInsertions()
1211 ArrayList<int[]> map = new ArrayList<>();
1212 int lastj = -1, j = 0;
1214 int seqlen = sequence.length;
1215 while ((j < seqlen))
1217 if (jalview.util.Comparison.isGap(sequence[j]))
1228 map.add(new int[] { lastj, j - 1 });
1236 map.add(new int[] { lastj, j - 1 });
1243 public BitSet getInsertionsAsBits()
1245 BitSet map = new BitSet();
1246 int lastj = -1, j = 0;
1248 int seqlen = sequence.length;
1249 while ((j < seqlen))
1251 if (jalview.util.Comparison.isGap(sequence[j]))
1277 public void deleteChars(final int i, final int j)
1279 int newstart = start, newend = end;
1280 if (i >= sequence.length || i < 0)
1285 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1286 boolean createNewDs = false;
1287 // TODO: take a (second look) at the dataset creation validation method for
1288 // the very large sequence case
1290 int startIndex = findIndex(start) - 1;
1291 int endIndex = findIndex(end) - 1;
1292 int startDeleteColumn = -1; // for dataset sequence deletions
1293 int deleteCount = 0;
1295 for (int s = i; s < j && s < sequence.length; s++)
1297 if (Comparison.isGap(sequence[s]))
1302 if (startDeleteColumn == -1)
1304 startDeleteColumn = findPosition(s) - start;
1312 if (startIndex == s)
1315 * deleting characters from start of sequence; new start is the
1316 * sequence position of the next column (position to the right
1317 * if the column position is gapped)
1319 newstart = findPosition(j);
1327 * deleting characters at end of sequence; new end is the sequence
1328 * position of the column before the deletion; subtract 1 if this is
1329 * gapped since findPosition returns the next sequence position
1331 newend = findPosition(i - 1);
1332 if (Comparison.isGap(sequence[i - 1]))
1347 if (createNewDs && this.datasetSequence != null)
1350 * if deletion occured in the middle of the sequence,
1351 * construct a new dataset sequence and delete the residues
1352 * that were deleted from the aligned sequence
1354 Sequence ds = new Sequence(datasetSequence);
1355 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1356 datasetSequence = ds;
1357 // TODO: remove any non-inheritable properties ?
1358 // TODO: create a sequence mapping (since there is a relation here ?)
1367 public void insertCharAt(int i, int length, char c)
1369 char[] tmp = new char[sequence.length + length];
1371 if (i >= sequence.length)
1373 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1374 i = sequence.length;
1378 System.arraycopy(sequence, 0, tmp, 0, i);
1388 if (i < sequence.length)
1390 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1398 public void insertCharAt(int i, char c)
1400 insertCharAt(i, 1, c);
1404 public String getVamsasId()
1410 public void setVamsasId(String id)
1417 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1419 if (dbrefs == null && datasetSequence != null
1420 && this != datasetSequence)
1422 datasetSequence.setDBRefs(newDBrefs);
1430 public DBModList<DBRefEntry> getDBRefs()
1432 if (dbrefs == null && datasetSequence != null
1433 && this != datasetSequence)
1435 return datasetSequence.getDBRefs();
1442 public void addDBRef(DBRefEntry entry)
1444 if (datasetSequence != null)
1446 datasetSequence.addDBRef(entry);
1452 dbrefs = new DBModList<DBRefEntry>();
1455 for (int ib = 0, nb= dbrefs.size(); ib < nb; ib++)
1457 if (dbrefs.get(ib).updateFrom(entry))
1460 * found a dbref that either matched, or could be
1461 * updated from, the new entry - no need to add it
1470 // * extend the array to make room for one more
1472 // // TODO use an ArrayList instead
1473 // int j = dbrefs.length;
1474 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1475 // System.arraycopy(dbrefs, 0, temp, 0, j);
1476 // temp[temp.length - 1] = entry;
1484 public void setDatasetSequence(SequenceI seq)
1488 throw new IllegalArgumentException(
1489 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1491 if (seq != null && seq.getDatasetSequence() != null)
1493 throw new IllegalArgumentException(
1494 "Implementation error: cascading dataset sequences are not allowed.");
1496 datasetSequence = seq;
1500 public SequenceI getDatasetSequence()
1502 return datasetSequence;
1506 public AlignmentAnnotation[] getAnnotation()
1508 return annotation == null ? null
1510 .toArray(new AlignmentAnnotation[annotation.size()]);
1514 public boolean hasAnnotation(AlignmentAnnotation ann)
1516 return annotation == null ? false : annotation.contains(ann);
1520 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1522 if (this.annotation == null)
1524 this.annotation = new Vector<>();
1526 if (!this.annotation.contains(annotation))
1528 this.annotation.addElement(annotation);
1530 annotation.setSequenceRef(this);
1534 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1536 if (this.annotation != null)
1538 this.annotation.removeElement(annotation);
1539 if (this.annotation.size() == 0)
1541 this.annotation = null;
1547 * test if this is a valid candidate for another sequence's dataset sequence.
1550 private boolean isValidDatasetSequence()
1552 if (datasetSequence != null)
1556 for (int i = 0; i < sequence.length; i++)
1558 if (jalview.util.Comparison.isGap(sequence[i]))
1567 public SequenceI deriveSequence()
1569 Sequence seq = null;
1570 if (datasetSequence == null)
1572 if (isValidDatasetSequence())
1574 // Use this as dataset sequence
1575 seq = new Sequence(getName(), "", 1, -1);
1576 seq.setDatasetSequence(this);
1577 seq.initSeqFrom(this, getAnnotation());
1582 // Create a new, valid dataset sequence
1583 createDatasetSequence();
1586 return new Sequence(this);
1589 private boolean _isNa;
1591 private int _seqhash = 0;
1593 private List<DBRefEntry> primaryRefs;
1596 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1600 public boolean isProtein()
1602 if (datasetSequence != null)
1604 return datasetSequence.isProtein();
1606 if (_seqhash != sequence.hashCode())
1608 _seqhash = sequence.hashCode();
1609 _isNa = Comparison.isNucleotide(this);
1617 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1620 public SequenceI createDatasetSequence()
1622 if (datasetSequence == null)
1624 Sequence dsseq = new Sequence(getName(),
1625 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1626 getSequenceAsString()),
1627 getStart(), getEnd());
1629 datasetSequence = dsseq;
1631 dsseq.setDescription(description);
1632 // move features and database references onto dataset sequence
1633 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1634 sequenceFeatureStore = null;
1635 dsseq.dbrefs = dbrefs;
1637 // TODO: search and replace any references to this sequence with
1638 // references to the dataset sequence in Mappings on dbref
1639 dsseq.pdbIds = pdbIds;
1641 datasetSequence.updatePDBIds();
1642 if (annotation != null)
1644 // annotation is cloned rather than moved, to preserve what's currently
1646 for (AlignmentAnnotation aa : annotation)
1648 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1649 _aa.sequenceRef = datasetSequence;
1650 _aa.adjustForAlignment(); // uses annotation's own record of
1651 // sequence-column mapping
1652 datasetSequence.addAlignmentAnnotation(_aa);
1656 return datasetSequence;
1663 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1667 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1669 if (annotation != null)
1671 annotation.removeAllElements();
1673 if (annotations != null)
1675 for (int i = 0; i < annotations.length; i++)
1677 if (annotations[i] != null)
1679 addAlignmentAnnotation(annotations[i]);
1686 public AlignmentAnnotation[] getAnnotation(String label)
1688 if (annotation == null || annotation.size() == 0)
1693 Vector<AlignmentAnnotation> subset = new Vector<>();
1694 Enumeration<AlignmentAnnotation> e = annotation.elements();
1695 while (e.hasMoreElements())
1697 AlignmentAnnotation ann = e.nextElement();
1698 if (ann.label != null && ann.label.equals(label))
1700 subset.addElement(ann);
1703 if (subset.size() == 0)
1707 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1709 e = subset.elements();
1710 while (e.hasMoreElements())
1712 anns[i++] = e.nextElement();
1714 subset.removeAllElements();
1719 public boolean updatePDBIds()
1721 if (datasetSequence != null)
1723 // TODO: could merge DBRefs
1724 return datasetSequence.updatePDBIds();
1726 if (dbrefs == null || dbrefs.size() == 0)
1730 boolean added = false;
1731 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1733 DBRefEntry dbr = dbrefs.get(ib);
1734 if (DBRefSource.PDB.equals(dbr.getSource()))
1737 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1738 * PDB id is not already present in a 'matching' PDBEntry
1739 * Constructor parses out a chain code if appended to the accession id
1740 * (a fudge used to 'store' the chain code in the DBRef)
1742 PDBEntry pdbe = new PDBEntry(dbr);
1743 added |= addPDBId(pdbe);
1750 public void transferAnnotation(SequenceI entry, Mapping mp)
1752 if (datasetSequence != null)
1754 datasetSequence.transferAnnotation(entry, mp);
1757 if (entry.getDatasetSequence() != null)
1759 transferAnnotation(entry.getDatasetSequence(), mp);
1762 // transfer any new features from entry onto sequence
1763 if (entry.getSequenceFeatures() != null)
1766 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1767 for (SequenceFeature feature : sfs)
1769 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1770 : new SequenceFeature[] { new SequenceFeature(feature) };
1773 for (int sfi = 0; sfi < sf.length; sfi++)
1775 addSequenceFeature(sf[sfi]);
1781 // transfer PDB entries
1782 if (entry.getAllPDBEntries() != null)
1784 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1785 while (e.hasMoreElements())
1787 PDBEntry pdb = e.nextElement();
1791 // transfer database references
1792 List<DBRefEntry> entryRefs = entry.getDBRefs();
1793 if (entryRefs != null)
1795 for (int r = 0, n = entryRefs.size(); r < n; r++)
1797 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1798 if (newref.getMap() != null && mp != null)
1800 // remap ref using our local mapping
1802 // we also assume all version string setting is done by dbSourceProxy
1804 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1805 * newref.setSource(dbSource); }
1813 public void setRNA(RNA r)
1825 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1828 List<AlignmentAnnotation> result = new ArrayList<>();
1829 if (this.annotation != null)
1831 for (AlignmentAnnotation ann : annotation)
1833 if (ann.calcId != null && ann.calcId.equals(calcId)
1834 && ann.label != null && ann.label.equals(label))
1844 public String toString()
1846 return getDisplayId(false);
1850 public PDBEntry getPDBEntry(String pdbIdStr)
1852 if (getDatasetSequence() != null)
1854 return getDatasetSequence().getPDBEntry(pdbIdStr);
1860 List<PDBEntry> entries = getAllPDBEntries();
1861 for (PDBEntry entry : entries)
1863 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1871 private List<DBRefEntry> tmpList;
1874 public List<DBRefEntry> getPrimaryDBRefs()
1876 if (datasetSequence != null)
1878 return datasetSequence.getPrimaryDBRefs();
1880 if (dbrefs == null || dbrefs.size() == 0)
1882 return Collections.emptyList();
1884 synchronized (dbrefs)
1886 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1887 return primaryRefs; // no changes
1888 refModCount = dbrefs.getModCount();
1889 List<DBRefEntry> primaries = (primaryRefs == null ? (primaryRefs = new ArrayList<>()) : primaryRefs);
1891 if (tmpList == null) {
1892 tmpList = new ArrayList<>();
1893 tmpList.add(null); // for replacement
1895 for (int i = 0, n = dbrefs.size(); i < n; i++)
1897 DBRefEntry ref = dbrefs.get(i);
1898 if (!ref.isPrimaryCandidate())
1904 MapList mp = ref.getMap().getMap();
1905 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1907 // map only involves a subsequence, so cannot be primary
1911 // whilst it looks like it is a primary ref, we also sanity check type
1912 if (DBRefSource.PDB_CANONICAL_NAME.equals(ref.getCanonicalSourceName()))
1914 // PDB dbrefs imply there should be a PDBEntry associated
1915 // TODO: tighten PDB dbrefs
1916 // formally imply Jalview has actually downloaded and
1917 // parsed the pdb file. That means there should be a cached file
1918 // handle on the PDBEntry, and a real mapping between sequence and
1919 // extracted sequence from PDB file
1920 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1921 if (pdbentry == null || pdbentry.getFile() == null)
1926 // check standard protein or dna sources
1927 tmpList.set(0, ref);
1928 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(), tmpList);
1929 if (res == null || res.get(0) != tmpList.get(0))
1937 // version must be not null, as otherwise it will not be a candidate, above
1938 DBRefUtils.ensurePrimaries(this, primaries);
1947 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1950 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1951 int endPos = fromColumn == toColumn ? startPos
1952 : findPosition(toColumn - 1);
1954 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1956 if (datasetSequence != null)
1958 result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1963 result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1967 * if end column is gapped, endPos may be to the right,
1968 * and we may have included adjacent or enclosing features;
1969 * remove any that are not enclosing, non-contact features
1971 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1972 && Comparison.isGap(sequence[toColumn - 1]);
1973 if (endPos > this.end || endColumnIsGapped)
1975 ListIterator<SequenceFeature> it = result.listIterator();
1976 while (it.hasNext())
1978 SequenceFeature sf = it.next();
1979 int sfBegin = sf.getBegin();
1980 int sfEnd = sf.getEnd();
1981 int featureStartColumn = findIndex(sfBegin);
1982 if (featureStartColumn > toColumn)
1986 else if (featureStartColumn < fromColumn)
1988 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1990 if (featureEndColumn < fromColumn)
1994 else if (featureEndColumn > toColumn && sf.isContactFeature())
1997 * remove an enclosing feature if it is a contact feature
2009 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2010 * token that has to match the one presented by the cursor
2013 public void sequenceChanged()
2022 public int replace(char c1, char c2)
2029 synchronized (sequence)
2031 for (int c = 0; c < sequence.length; c++)
2033 if (sequence[c] == c1)
2049 public String getSequenceStringFromIterator(Iterator<int[]> it)
2051 StringBuilder newSequence = new StringBuilder();
2052 while (it.hasNext())
2054 int[] block = it.next();
2057 newSequence.append(getSequence(block[0], block[1] + 1));
2061 newSequence.append(getSequence(block[0], block[1]));
2065 return newSequence.toString();
2069 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2073 if (!regions.hasNext())
2075 return findIndex(getStart()) - 1;
2078 // Simply walk along the sequence whilst watching for region
2080 int hideStart = getLength();
2082 boolean foundStart = false;
2084 // step through the non-gapped positions of the sequence
2085 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2087 // get alignment position of this residue in the sequence
2088 int p = findIndex(i) - 1;
2090 // update region start/end
2091 while (hideEnd < p && regions.hasNext())
2093 int[] region = regions.next();
2094 hideStart = region[0];
2095 hideEnd = region[1];
2099 hideStart = getLength();
2101 // update boundary for sequence
2113 // otherwise, sequence was completely hidden