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 whether there
52 * have been any changes. We use this to update
58 @SuppressWarnings("serial")
59 public class DBModList<T> extends ArrayList<DBRefEntry>
62 protected int getModCount()
69 SequenceI datasetSequence;
73 private char[] sequence;
75 private String description;
81 private Vector<PDBEntry> pdbIds;
83 private String vamsasId;
85 private DBModList<DBRefEntry> dbrefs; // controlled access
88 * a flag to let us know that elements have changed in dbrefs
92 private int refModCount = 0;
97 * This annotation is displayed below the alignment but the positions are tied
98 * to the residues of this sequence
100 * TODO: change to List<>
102 private Vector<AlignmentAnnotation> annotation;
104 private SequenceFeaturesI sequenceFeatureStore;
107 * A cursor holding the approximate current view position to the sequence,
108 * as determined by findIndex or findPosition or findPositions.
109 * Using a cursor as a hint allows these methods to be more performant for
112 private SequenceCursor cursor;
115 * A number that should be incremented whenever the sequence is edited.
116 * If the value matches the cursor token, then we can trust the cursor,
117 * if not then it should be recomputed.
119 private int changeCount;
122 * Creates a new Sequence object.
125 * display name string
127 * string to form a possibly gapped sequence out of
129 * first position of non-gap residue in the sequence
131 * last position of ungapped residues (nearly always only used for
134 public Sequence(String name, String sequence, int start, int end)
137 initSeqAndName(name, sequence.toCharArray(), start, end);
140 public Sequence(String name, char[] sequence, int start, int end)
143 initSeqAndName(name, sequence, start, end);
147 * Stage 1 constructor - assign name, sequence, and set start and end fields.
148 * start and end are updated values from name2 if it ends with /start-end
155 protected void initSeqAndName(String name2, char[] sequence2, int start2,
159 this.sequence = sequence2;
167 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
168 * start and end respectively and removes the suffix from the name
175 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
178 int slashPos = name.lastIndexOf('/');
179 if (slashPos > -1 && slashPos < name.length() - 1)
181 String suffix = name.substring(slashPos + 1);
182 String[] range = suffix.split("-");
183 if (range.length == 2)
187 int from = Integer.valueOf(range[0]);
188 int to = Integer.valueOf(range[1]);
189 if (from > 0 && to >= from)
191 name = name.substring(0, slashPos);
196 } catch (NumberFormatException e)
198 // leave name unchanged if suffix is invalid
205 * Ensures that 'end' is not before the end of the sequence, that is,
206 * (end-start+1) is at least as long as the count of ungapped positions. Note
207 * that end is permitted to be beyond the end of the sequence data.
209 void checkValidRange()
212 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
215 for (int j = 0; j < sequence.length; j++)
217 if (!Comparison.isGap(sequence[j]))
236 * default constructor
240 sequenceFeatureStore = new SequenceFeatures();
244 * Creates a new Sequence object.
251 public Sequence(String name, String sequence)
253 this(name, sequence, 1, -1);
257 * Creates a new Sequence object with new AlignmentAnnotations but inherits
258 * any existing dataset sequence reference. If non exists, everything is
262 * if seq is a dataset sequence, behaves like a plain old copy
265 public Sequence(SequenceI seq)
267 this(seq, seq.getAnnotation());
271 * Create a new sequence object with new features, DBRefEntries, and PDBIds
272 * but inherits any existing dataset sequence reference, and duplicate of any
273 * annotation that is present in the given annotation array.
276 * the sequence to be copied
277 * @param alAnnotation
278 * an array of annotation including some associated with seq
280 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
283 initSeqFrom(seq, alAnnotation);
287 * does the heavy lifting when cloning a dataset sequence, or coping data from
288 * dataset to a new derived sequence.
291 * - source of attributes.
292 * @param alAnnotation
293 * - alignment annotation present on seq that should be copied onto
296 protected void initSeqFrom(SequenceI seq,
297 AlignmentAnnotation[] alAnnotation)
299 char[] oseq = seq.getSequence(); // returns a copy of the array
300 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
302 description = seq.getDescription();
303 if (seq != datasetSequence)
305 setDatasetSequence(seq.getDatasetSequence());
309 * only copy DBRefs and seqfeatures if we really are a dataset sequence
311 if (datasetSequence == null)
313 List<DBRefEntry> dbr = seq.getDBRefs();
316 for (int i = 0, n = dbr.size(); i < n; i++)
318 addDBRef(new DBRefEntry(dbr.get(i)));
323 * make copies of any sequence features
325 for (SequenceFeature sf : seq.getSequenceFeatures())
327 addSequenceFeature(new SequenceFeature(sf));
331 if (seq.getAnnotation() != null)
333 AlignmentAnnotation[] sqann = seq.getAnnotation();
334 for (int i = 0; i < sqann.length; i++)
336 if (sqann[i] == null)
340 boolean found = (alAnnotation == null);
343 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
345 found = (alAnnotation[apos] == sqann[i]);
350 // only copy the given annotation
351 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
352 addAlignmentAnnotation(newann);
356 if (seq.getAllPDBEntries() != null)
358 Vector<PDBEntry> ids = seq.getAllPDBEntries();
359 for (PDBEntry pdb : ids)
361 this.addPDBId(new PDBEntry(pdb));
367 public void setSequenceFeatures(List<SequenceFeature> features)
369 if (datasetSequence != null)
371 datasetSequence.setSequenceFeatures(features);
374 sequenceFeatureStore = new SequenceFeatures(features);
378 public synchronized boolean addSequenceFeature(SequenceFeature sf)
380 if (sf.getType() == null)
383 "SequenceFeature type may not be null: " + sf.toString());
387 if (datasetSequence != null)
389 return datasetSequence.addSequenceFeature(sf);
392 return sequenceFeatureStore.add(sf);
397 * A known feature of this featureStore
400 public void deleteFeature(SequenceFeature sf)
402 if (datasetSequence != null)
404 datasetSequence.deleteFeature(sf);
408 sequenceFeatureStore.delete(sf);
418 public List<SequenceFeature> getSequenceFeatures()
420 if (datasetSequence != null)
422 return datasetSequence.getSequenceFeatures();
424 return sequenceFeatureStore.getAllFeatures();
428 public SequenceFeaturesI getFeatures()
430 return datasetSequence != null ? datasetSequence.getFeatures()
431 : sequenceFeatureStore;
435 public boolean addPDBId(PDBEntry entry)
439 pdbIds = new Vector<>();
444 for (PDBEntry pdbe : pdbIds)
446 if (pdbe.updateFrom(entry))
451 pdbIds.addElement(entry);
462 public void setPDBId(Vector<PDBEntry> id)
470 * @return DOCUMENT ME!
473 public Vector<PDBEntry> getAllPDBEntries()
475 return pdbIds == null ? new Vector<>() : pdbIds;
481 * @return DOCUMENT ME!
484 public String getDisplayId(boolean jvsuffix)
486 StringBuffer result = new StringBuffer(name);
489 result.append("/" + start + "-" + end);
492 return result.toString();
496 * Sets the sequence name. If the name ends in /start-end, then the start-end
497 * values are parsed out and set, and the suffix is removed from the name.
502 public void setName(String theName)
511 * @return DOCUMENT ME!
514 public String getName()
526 public void setStart(int start)
534 * @return DOCUMENT ME!
537 public int getStart()
549 public void setEnd(int end)
557 * @return DOCUMENT ME!
568 * @return DOCUMENT ME!
571 public int getLength()
573 return this.sequence.length;
583 public void setSequence(String seq)
585 this.sequence = seq.toCharArray();
591 public String getSequenceAsString()
593 return new String(sequence);
597 public String getSequenceAsString(int start, int end)
599 return new String(getSequence(start, end));
603 public char[] getSequence()
606 return sequence == null ? null
607 : Arrays.copyOf(sequence, sequence.length);
613 * @see jalview.datamodel.SequenceI#getSequence(int, int)
616 public char[] getSequence(int start, int end)
622 // JBPNote - left to user to pad the result here (TODO:Decide on this
624 if (start >= sequence.length)
629 if (end >= sequence.length)
631 end = sequence.length;
634 char[] reply = new char[end - start];
635 System.arraycopy(sequence, start, reply, 0, end - start);
641 public SequenceI getSubSequence(int start, int end)
647 char[] seq = getSequence(start, end);
652 int nstart = findPosition(start);
653 int nend = findPosition(end) - 1;
654 // JBPNote - this is an incomplete copy.
655 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
656 nseq.setDescription(description);
657 if (datasetSequence != null)
659 nseq.setDatasetSequence(datasetSequence);
663 nseq.setDatasetSequence(this);
669 * Returns the character of the aligned sequence at the given position (base
670 * zero), or space if the position is not within the sequence's bounds
675 public char getCharAt(int i)
677 if (i >= 0 && i < sequence.length)
688 * Sets the sequence description, and also parses out any special formats of
694 public void setDescription(String desc)
696 this.description = desc;
700 public void setGeneLoci(String speciesId, String assemblyId,
701 String chromosomeId, MapList map)
703 addDBRef(new DBRefEntry(speciesId, assemblyId,
704 DBRefEntry.CHROMOSOME + ":" + chromosomeId, new Mapping(map)));
708 * Returns the gene loci mapping for the sequence (may be null)
713 public GeneLociI getGeneLoci()
715 List<DBRefEntry> refs = getDBRefs();
718 for (final DBRefEntry ref : refs)
720 if (ref.isChromosome())
722 return new GeneLociI()
725 public String getSpeciesId()
727 return ref.getSource();
731 public String getAssemblyId()
733 // DEV NOTE: DBRefEntry is reused here to hold chromosomal locus
734 // of a gene sequence.
735 // source=species, version=assemblyId, accession=chromosome, map =
738 return ref.getVersion();
742 public String getChromosomeId()
744 // strip off "chromosome:" prefix to chrId
745 return ref.getAccessionId()
746 .substring(DBRefEntry.CHROMOSOME.length() + 1);
750 public MapList getMap()
752 return ref.getMap().getMap();
762 * Answers the description
767 public String getDescription()
769 return this.description;
776 public int findIndex(int pos)
779 * use a valid, hopefully nearby, cursor if available
781 if (isValidCursor(cursor))
783 return findIndex(pos, cursor);
791 * traverse sequence from the start counting gaps; make a note of
792 * the column of the first residue to save in the cursor
794 while ((i < sequence.length) && (j <= end) && (j <= pos))
796 if (!Comparison.isGap(sequence[i]))
807 if (j == end && j < pos)
812 updateCursor(pos, i, startColumn);
817 * Updates the cursor to the latest found residue and column position
824 * column position of the first sequence residue
826 protected void updateCursor(int residuePos, int column, int startColumn)
829 * preserve end residue column provided cursor was valid
831 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
833 if (residuePos == this.end)
838 cursor = new SequenceCursor(this, residuePos, column, startColumn,
839 endColumn, this.changeCount);
843 * Answers the aligned column position (1..) for the given residue position
844 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
845 * The hint may be left of, at, or to the right of the required position.
851 protected int findIndex(final int pos, SequenceCursor curs)
853 if (!isValidCursor(curs))
856 * wrong or invalidated cursor, compute de novo
858 return findIndex(pos);
861 if (curs.residuePosition == pos)
863 return curs.columnPosition;
867 * move left or right to find pos from hint.position
869 int col = curs.columnPosition - 1; // convert from base 1 to base 0
870 int newPos = curs.residuePosition;
871 int delta = newPos > pos ? -1 : 1;
873 while (newPos != pos)
875 col += delta; // shift one column left or right
880 if (col == sequence.length)
882 col--; // return last column if we failed to reach pos
885 if (!Comparison.isGap(sequence[col]))
891 col++; // convert back to base 1
894 * only update cursor if we found the target position
898 updateCursor(pos, col, curs.firstColumnPosition);
908 public int findPosition(final int column)
911 * use a valid, hopefully nearby, cursor if available
913 if (isValidCursor(cursor))
915 return findPosition(column + 1, cursor);
918 // TODO recode this more naturally i.e. count residues only
919 // as they are found, not 'in anticipation'
922 * traverse the sequence counting gaps; note the column position
923 * of the first residue, to save in the cursor
925 int firstResidueColumn = 0;
926 int lastPosFound = 0;
927 int lastPosFoundColumn = 0;
928 int seqlen = sequence.length;
930 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
932 lastPosFound = start;
933 lastPosFoundColumn = 0;
939 while (j < column && j < seqlen)
941 if (!Comparison.isGap(sequence[j]))
944 lastPosFoundColumn = j;
945 if (pos == this.start)
947 firstResidueColumn = j;
953 if (j < seqlen && !Comparison.isGap(sequence[j]))
956 lastPosFoundColumn = j;
957 if (pos == this.start)
959 firstResidueColumn = j;
964 * update the cursor to the last residue position found (if any)
965 * (converting column position to base 1)
967 if (lastPosFound != 0)
969 updateCursor(lastPosFound, lastPosFoundColumn + 1,
970 firstResidueColumn + 1);
977 * Answers true if the given cursor is not null, is for this sequence object,
978 * and has a token value that matches this object's changeCount, else false.
979 * This allows us to ignore a cursor as 'stale' if the sequence has been
980 * modified since the cursor was created.
985 protected boolean isValidCursor(SequenceCursor curs)
987 if (curs == null || curs.sequence != this || curs.token != changeCount)
992 * sanity check against range
994 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
998 if (curs.residuePosition < start || curs.residuePosition > end)
1006 * Answers the sequence position (start..) for the given aligned column
1007 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
1008 * may lie left of, at, or to the right of the column position.
1014 protected int findPosition(final int col, SequenceCursor curs)
1016 if (!isValidCursor(curs))
1019 * wrong or invalidated cursor, compute de novo
1021 return findPosition(col - 1);// ugh back to base 0
1024 if (curs.columnPosition == col)
1026 cursor = curs; // in case this method becomes public
1027 return curs.residuePosition; // easy case :-)
1030 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1033 * sequence lies entirely to the left of col
1034 * - return last residue + 1
1039 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1042 * sequence lies entirely to the right of col
1043 * - return first residue
1048 // todo could choose closest to col out of column,
1049 // firstColumnPosition, lastColumnPosition as a start point
1052 * move left or right to find pos from cursor position
1054 int firstResidueColumn = curs.firstColumnPosition;
1055 int column = curs.columnPosition - 1; // to base 0
1056 int newPos = curs.residuePosition;
1057 int delta = curs.columnPosition > col ? -1 : 1;
1058 boolean gapped = false;
1059 int lastFoundPosition = curs.residuePosition;
1060 int lastFoundPositionColumn = curs.columnPosition;
1062 while (column != col - 1)
1064 column += delta; // shift one column left or right
1065 if (column < 0 || column == sequence.length)
1069 gapped = Comparison.isGap(sequence[column]);
1073 lastFoundPosition = newPos;
1074 lastFoundPositionColumn = column + 1;
1075 if (lastFoundPosition == this.start)
1077 firstResidueColumn = column + 1;
1082 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1084 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1085 firstResidueColumn);
1089 * hack to give position to the right if on a gap
1090 * or beyond the length of the sequence (see JAL-2562)
1092 if (delta > 0 && (gapped || column >= sequence.length))
1104 public ContiguousI findPositions(int fromColumn, int toColumn)
1106 if (toColumn < fromColumn || fromColumn < 1)
1112 * find the first non-gapped position, if any
1114 int firstPosition = 0;
1115 int col = fromColumn - 1;
1116 int length = sequence.length;
1117 while (col < length && col < toColumn)
1119 if (!Comparison.isGap(sequence[col]))
1121 firstPosition = findPosition(col++);
1127 if (firstPosition == 0)
1133 * find the last non-gapped position
1135 int lastPosition = firstPosition;
1136 while (col < length && col < toColumn)
1138 if (!Comparison.isGap(sequence[col++]))
1144 return new Range(firstPosition, lastPosition);
1148 * Returns an int array where indices correspond to each residue in the
1149 * sequence and the element value gives its position in the alignment
1151 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1152 * residues in SequenceI object
1155 public int[] gapMap()
1157 String seq = jalview.analysis.AlignSeq.extractGaps(
1158 jalview.util.Comparison.GapChars, new String(sequence));
1159 int[] map = new int[seq.length()];
1163 while (j < sequence.length)
1165 if (!jalview.util.Comparison.isGap(sequence[j]))
1177 * Build a bitset corresponding to sequence gaps
1179 * @return a BitSet where set values correspond to gaps in the sequence
1182 public BitSet gapBitset()
1184 BitSet gaps = new BitSet(sequence.length);
1186 while (j < sequence.length)
1188 if (jalview.util.Comparison.isGap(sequence[j]))
1198 public int[] findPositionMap()
1200 int map[] = new int[sequence.length];
1203 int seqlen = sequence.length;
1204 while ((j < seqlen))
1207 if (!jalview.util.Comparison.isGap(sequence[j]))
1218 public List<int[]> getInsertions()
1220 ArrayList<int[]> map = new ArrayList<>();
1221 int lastj = -1, j = 0;
1223 int seqlen = sequence.length;
1224 while ((j < seqlen))
1226 if (jalview.util.Comparison.isGap(sequence[j]))
1237 map.add(new int[] { lastj, j - 1 });
1245 map.add(new int[] { lastj, j - 1 });
1252 public BitSet getInsertionsAsBits()
1254 BitSet map = new BitSet();
1255 int lastj = -1, j = 0;
1257 int seqlen = sequence.length;
1258 while ((j < seqlen))
1260 if (jalview.util.Comparison.isGap(sequence[j]))
1286 public void deleteChars(final int i, final int j)
1288 int newstart = start, newend = end;
1289 if (i >= sequence.length || i < 0)
1294 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1295 boolean createNewDs = false;
1296 // TODO: take a (second look) at the dataset creation validation method for
1297 // the very large sequence case
1299 int startIndex = findIndex(start) - 1;
1300 int endIndex = findIndex(end) - 1;
1301 int startDeleteColumn = -1; // for dataset sequence deletions
1302 int deleteCount = 0;
1304 for (int s = i; s < j && s < sequence.length; s++)
1306 if (Comparison.isGap(sequence[s]))
1311 if (startDeleteColumn == -1)
1313 startDeleteColumn = findPosition(s) - start;
1321 if (startIndex == s)
1324 * deleting characters from start of sequence; new start is the
1325 * sequence position of the next column (position to the right
1326 * if the column position is gapped)
1328 newstart = findPosition(j);
1336 * deleting characters at end of sequence; new end is the sequence
1337 * position of the column before the deletion; subtract 1 if this is
1338 * gapped since findPosition returns the next sequence position
1340 newend = findPosition(i - 1);
1341 if (Comparison.isGap(sequence[i - 1]))
1356 if (createNewDs && this.datasetSequence != null)
1359 * if deletion occured in the middle of the sequence,
1360 * construct a new dataset sequence and delete the residues
1361 * that were deleted from the aligned sequence
1363 Sequence ds = new Sequence(datasetSequence);
1364 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1365 datasetSequence = ds;
1366 // TODO: remove any non-inheritable properties ?
1367 // TODO: create a sequence mapping (since there is a relation here ?)
1376 public void insertCharAt(int i, int length, char c)
1378 char[] tmp = new char[sequence.length + length];
1380 if (i >= sequence.length)
1382 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1383 i = sequence.length;
1387 System.arraycopy(sequence, 0, tmp, 0, i);
1397 if (i < sequence.length)
1399 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1407 public void insertCharAt(int i, char c)
1409 insertCharAt(i, 1, c);
1413 public String getVamsasId()
1419 public void setVamsasId(String id)
1426 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1428 if (dbrefs == null && datasetSequence != null
1429 && this != datasetSequence)
1431 datasetSequence.setDBRefs(newDBrefs);
1439 public DBModList<DBRefEntry> getDBRefs()
1441 if (dbrefs == null && datasetSequence != null
1442 && this != datasetSequence)
1444 return datasetSequence.getDBRefs();
1450 public void addDBRef(DBRefEntry entry)
1452 if (datasetSequence != null)
1454 datasetSequence.addDBRef(entry);
1460 dbrefs = new DBModList<>();
1463 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1465 if (dbrefs.get(ib).updateFrom(entry))
1468 * found a dbref that either matched, or could be
1469 * updated from, the new entry - no need to add it
1477 // * extend the array to make room for one more
1479 // // TODO use an ArrayList instead
1480 // int j = dbrefs.length;
1481 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1482 // System.arraycopy(dbrefs, 0, temp, 0, j);
1483 // temp[temp.length - 1] = entry;
1491 public void setDatasetSequence(SequenceI seq)
1495 throw new IllegalArgumentException(
1496 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1498 if (seq != null && seq.getDatasetSequence() != null)
1500 throw new IllegalArgumentException(
1501 "Implementation error: cascading dataset sequences are not allowed.");
1503 datasetSequence = seq;
1507 public SequenceI getDatasetSequence()
1509 return datasetSequence;
1513 public AlignmentAnnotation[] getAnnotation()
1515 return annotation == null ? null
1517 .toArray(new AlignmentAnnotation[annotation.size()]);
1521 public boolean hasAnnotation(AlignmentAnnotation ann)
1523 return annotation == null ? false : annotation.contains(ann);
1527 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1529 if (this.annotation == null)
1531 this.annotation = new Vector<>();
1533 if (!this.annotation.contains(annotation))
1535 this.annotation.addElement(annotation);
1537 annotation.setSequenceRef(this);
1541 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1543 if (this.annotation != null)
1545 this.annotation.removeElement(annotation);
1546 if (this.annotation.size() == 0)
1548 this.annotation = null;
1554 * test if this is a valid candidate for another sequence's dataset sequence.
1557 private boolean isValidDatasetSequence()
1559 if (datasetSequence != null)
1563 for (int i = 0; i < sequence.length; i++)
1565 if (jalview.util.Comparison.isGap(sequence[i]))
1574 public SequenceI deriveSequence()
1576 Sequence seq = null;
1577 if (datasetSequence == null)
1579 if (isValidDatasetSequence())
1581 // Use this as dataset sequence
1582 seq = new Sequence(getName(), "", 1, -1);
1583 seq.setDatasetSequence(this);
1584 seq.initSeqFrom(this, getAnnotation());
1589 // Create a new, valid dataset sequence
1590 createDatasetSequence();
1593 return new Sequence(this);
1596 private boolean _isNa;
1598 private int _seqhash = 0;
1600 private List<DBRefEntry> primaryRefs;
1603 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1607 public boolean isProtein()
1609 if (datasetSequence != null)
1611 return datasetSequence.isProtein();
1613 if (_seqhash != sequence.hashCode())
1615 _seqhash = sequence.hashCode();
1616 _isNa = Comparison.isNucleotide(this);
1624 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1627 public SequenceI createDatasetSequence()
1629 if (datasetSequence == null)
1631 Sequence dsseq = new Sequence(getName(),
1632 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1633 getSequenceAsString()),
1634 getStart(), getEnd());
1636 datasetSequence = dsseq;
1638 dsseq.setDescription(description);
1639 // move features and database references onto dataset sequence
1640 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1641 sequenceFeatureStore = null;
1642 dsseq.dbrefs = dbrefs;
1644 // TODO: search and replace any references to this sequence with
1645 // references to the dataset sequence in Mappings on dbref
1646 dsseq.pdbIds = pdbIds;
1648 datasetSequence.updatePDBIds();
1649 if (annotation != null)
1651 // annotation is cloned rather than moved, to preserve what's currently
1653 for (AlignmentAnnotation aa : annotation)
1655 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1656 _aa.sequenceRef = datasetSequence;
1657 _aa.adjustForAlignment(); // uses annotation's own record of
1658 // sequence-column mapping
1659 datasetSequence.addAlignmentAnnotation(_aa);
1663 return datasetSequence;
1670 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1674 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1676 if (annotation != null)
1678 annotation.removeAllElements();
1680 if (annotations != null)
1682 for (int i = 0; i < annotations.length; i++)
1684 if (annotations[i] != null)
1686 addAlignmentAnnotation(annotations[i]);
1693 public AlignmentAnnotation[] getAnnotation(String label)
1695 if (annotation == null || annotation.size() == 0)
1700 Vector<AlignmentAnnotation> subset = new Vector<>();
1701 Enumeration<AlignmentAnnotation> e = annotation.elements();
1702 while (e.hasMoreElements())
1704 AlignmentAnnotation ann = e.nextElement();
1705 if (ann.label != null && ann.label.equals(label))
1707 subset.addElement(ann);
1710 if (subset.size() == 0)
1714 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1716 e = subset.elements();
1717 while (e.hasMoreElements())
1719 anns[i++] = e.nextElement();
1721 subset.removeAllElements();
1726 public boolean updatePDBIds()
1728 if (datasetSequence != null)
1730 // TODO: could merge DBRefs
1731 return datasetSequence.updatePDBIds();
1733 if (dbrefs == null || dbrefs.size() == 0)
1737 boolean added = false;
1738 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1740 DBRefEntry dbr = dbrefs.get(ib);
1741 if (DBRefSource.PDB.equals(dbr.getSource()))
1744 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1745 * PDB id is not already present in a 'matching' PDBEntry
1746 * Constructor parses out a chain code if appended to the accession id
1747 * (a fudge used to 'store' the chain code in the DBRef)
1749 PDBEntry pdbe = new PDBEntry(dbr);
1750 added |= addPDBId(pdbe);
1757 public void transferAnnotation(SequenceI entry, Mapping mp)
1759 if (datasetSequence != null)
1761 datasetSequence.transferAnnotation(entry, mp);
1764 if (entry.getDatasetSequence() != null)
1766 transferAnnotation(entry.getDatasetSequence(), mp);
1769 // transfer any new features from entry onto sequence
1770 if (entry.getSequenceFeatures() != null)
1773 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1774 for (SequenceFeature feature : sfs)
1776 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1777 : new SequenceFeature[]
1778 { new SequenceFeature(feature) };
1781 for (int sfi = 0; sfi < sf.length; sfi++)
1783 addSequenceFeature(sf[sfi]);
1789 // transfer PDB entries
1790 if (entry.getAllPDBEntries() != null)
1792 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1793 while (e.hasMoreElements())
1795 PDBEntry pdb = e.nextElement();
1799 // transfer database references
1800 List<DBRefEntry> entryRefs = entry.getDBRefs();
1801 if (entryRefs != null)
1803 for (int r = 0, n = entryRefs.size(); r < n; r++)
1805 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1806 if (newref.getMap() != null && mp != null)
1808 // remap ref using our local mapping
1810 // we also assume all version string setting is done by dbSourceProxy
1812 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1813 * newref.setSource(dbSource); }
1821 public void setRNA(RNA r)
1833 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1836 List<AlignmentAnnotation> result = new ArrayList<>();
1837 if (this.annotation != null)
1839 for (AlignmentAnnotation ann : annotation)
1841 if (ann.calcId != null && ann.calcId.equals(calcId)
1842 && ann.label != null && ann.label.equals(label))
1852 public String toString()
1854 return getDisplayId(false);
1858 public PDBEntry getPDBEntry(String pdbIdStr)
1860 if (getDatasetSequence() != null)
1862 return getDatasetSequence().getPDBEntry(pdbIdStr);
1868 List<PDBEntry> entries = getAllPDBEntries();
1869 for (PDBEntry entry : entries)
1871 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1879 private List<DBRefEntry> tmpList;
1882 public List<DBRefEntry> getPrimaryDBRefs()
1884 if (datasetSequence != null)
1886 return datasetSequence.getPrimaryDBRefs();
1888 if (dbrefs == null || dbrefs.size() == 0)
1890 return Collections.emptyList();
1892 synchronized (dbrefs)
1894 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1896 return primaryRefs; // no changes
1898 refModCount = dbrefs.getModCount();
1899 List<DBRefEntry> primaries = (primaryRefs == null
1900 ? (primaryRefs = new ArrayList<>())
1903 if (tmpList == null)
1905 tmpList = new ArrayList<>();
1906 tmpList.add(null); // for replacement
1908 for (int i = 0, n = dbrefs.size(); i < n; i++)
1910 DBRefEntry ref = dbrefs.get(i);
1911 if (!ref.isPrimaryCandidate())
1917 MapList mp = ref.getMap().getMap();
1918 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1920 // map only involves a subsequence, so cannot be primary
1924 // whilst it looks like it is a primary ref, we also sanity check type
1925 if (DBRefSource.PDB_CANONICAL_NAME
1926 .equals(ref.getCanonicalSourceName()))
1928 // PDB dbrefs imply there should be a PDBEntry associated
1929 // TODO: tighten PDB dbrefs
1930 // formally imply Jalview has actually downloaded and
1931 // parsed the pdb file. That means there should be a cached file
1932 // handle on the PDBEntry, and a real mapping between sequence and
1933 // extracted sequence from PDB file
1934 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1935 if (pdbentry == null || pdbentry.getFile() == null)
1942 // check standard protein or dna sources
1943 tmpList.set(0, ref);
1944 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1946 if (res == null || res.get(0) != tmpList.get(0))
1954 // version must be not null, as otherwise it will not be a candidate,
1956 DBRefUtils.ensurePrimaries(this, primaries);
1965 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1968 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1969 int endPos = fromColumn == toColumn ? startPos
1970 : findPosition(toColumn - 1);
1972 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1974 // if (datasetSequence != null)
1976 // result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1981 // result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1985 * if end column is gapped, endPos may be to the right,
1986 * and we may have included adjacent or enclosing features;
1987 * remove any that are not enclosing, non-contact features
1989 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1990 && Comparison.isGap(sequence[toColumn - 1]);
1991 if (endPos > this.end || endColumnIsGapped)
1993 ListIterator<SequenceFeature> it = result.listIterator();
1994 while (it.hasNext())
1996 SequenceFeature sf = it.next();
1997 int sfBegin = sf.getBegin();
1998 int sfEnd = sf.getEnd();
1999 int featureStartColumn = findIndex(sfBegin);
2000 if (featureStartColumn > toColumn)
2004 else if (featureStartColumn < fromColumn)
2006 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
2008 if (featureEndColumn < fromColumn)
2012 else if (featureEndColumn > toColumn && sf.isContactFeature())
2015 * remove an enclosing feature if it is a contact feature
2027 * Invalidates any stale cursors (forcing recalculation) by incrementing the
2028 * token that has to match the one presented by the cursor
2031 public void sequenceChanged()
2041 public int replace(char c1, char c2)
2048 synchronized (sequence)
2050 for (int c = 0; c < sequence.length; c++)
2052 if (sequence[c] == c1)
2068 public String getSequenceStringFromIterator(Iterator<int[]> it)
2070 StringBuilder newSequence = new StringBuilder();
2071 while (it.hasNext())
2073 int[] block = it.next();
2076 newSequence.append(getSequence(block[0], block[1] + 1));
2080 newSequence.append(getSequence(block[0], block[1]));
2084 return newSequence.toString();
2088 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2092 if (!regions.hasNext())
2094 return findIndex(getStart()) - 1;
2097 // Simply walk along the sequence whilst watching for region
2099 int hideStart = getLength();
2101 boolean foundStart = false;
2103 // step through the non-gapped positions of the sequence
2104 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2106 // get alignment position of this residue in the sequence
2107 int p = findIndex(i) - 1;
2109 // update region start/end
2110 while (hideEnd < p && regions.hasNext())
2112 int[] region = regions.next();
2113 hideStart = region[0];
2114 hideEnd = region[1];
2118 hideStart = getLength();
2120 // update boundary for sequence
2132 // otherwise, sequence was completely hidden
2139 public int getColor(int i)
2141 return argb == null ? 0 : argb[i];
2145 public int setColor(int i, int rgb)
2149 argb = new int[this.sequence.length];
2151 return (argb[i] = rgb);
2155 public void resetColors()
2161 * @author Bob Hanson 2019.07.30
2163 * allows passing the result ArrayList as a parameter to avoid
2164 * unnecessary construction
2165 * @return result (JavaScript) or new ArrayList (Java -- see FeatureRender)
2169 public List<SequenceFeature> findFeatures(int column, String type,
2170 List<SequenceFeature> result)
2172 return getFeatures().findFeatures(findPosition(column - 1), type,
2177 * allows early intervention for renderer if this returns false
2180 public boolean hasFeatures(String type)
2182 return getFeatures().hasFeatures(type);