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 * cached rgb colours for each position of the aligned sequence (column)
127 * Creates a new Sequence object.
130 * display name string
132 * string to form a possibly gapped sequence out of
134 * first position of non-gap residue in the sequence
136 * last position of ungapped residues (nearly always only used for
139 public Sequence(String name, String sequence, int start, int end)
142 initSeqAndName(name, sequence.toCharArray(), start, end);
145 public Sequence(String name, char[] sequence, int start, int end)
148 initSeqAndName(name, sequence, start, end);
152 * Stage 1 constructor - assign name, sequence, and set start and end fields.
153 * start and end are updated values from name2 if it ends with /start-end
160 protected void initSeqAndName(String name2, char[] sequence2, int start2,
164 this.sequence = sequence2;
172 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
173 * start and end respectively and removes the suffix from the name
180 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
183 int slashPos = name.lastIndexOf('/');
184 if (slashPos > -1 && slashPos < name.length() - 1)
186 String suffix = name.substring(slashPos + 1);
187 String[] range = suffix.split("-");
188 if (range.length == 2)
192 int from = Integer.valueOf(range[0]);
193 int to = Integer.valueOf(range[1]);
194 if (from > 0 && to >= from)
196 name = name.substring(0, slashPos);
201 } catch (NumberFormatException e)
203 // leave name unchanged if suffix is invalid
210 * Ensures that 'end' is not before the end of the sequence, that is,
211 * (end-start+1) is at least as long as the count of ungapped positions. Note
212 * that end is permitted to be beyond the end of the sequence data.
214 void checkValidRange()
217 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
220 for (int j = 0; j < sequence.length; j++)
222 if (!Comparison.isGap(sequence[j]))
241 * default constructor
245 sequenceFeatureStore = new SequenceFeatures();
249 * Creates a new Sequence object.
256 public Sequence(String name, String sequence)
258 this(name, sequence, 1, -1);
262 * Creates a new Sequence object with new AlignmentAnnotations but inherits
263 * any existing dataset sequence reference. If non exists, everything is
267 * if seq is a dataset sequence, behaves like a plain old copy
270 public Sequence(SequenceI seq)
272 this(seq, seq.getAnnotation());
276 * Create a new sequence object with new features, DBRefEntries, and PDBIds
277 * but inherits any existing dataset sequence reference, and duplicate of any
278 * annotation that is present in the given annotation array.
281 * the sequence to be copied
282 * @param alAnnotation
283 * an array of annotation including some associated with seq
285 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
288 initSeqFrom(seq, alAnnotation);
292 * does the heavy lifting when cloning a dataset sequence, or coping data from
293 * dataset to a new derived sequence.
296 * - source of attributes.
297 * @param alAnnotation
298 * - alignment annotation present on seq that should be copied onto
301 protected void initSeqFrom(SequenceI seq,
302 AlignmentAnnotation[] alAnnotation)
304 char[] oseq = seq.getSequence(); // returns a copy of the array
305 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
307 description = seq.getDescription();
308 if (seq != datasetSequence)
310 setDatasetSequence(seq.getDatasetSequence());
314 * only copy DBRefs and seqfeatures if we really are a dataset sequence
316 if (datasetSequence == null)
318 List<DBRefEntry> dbr = seq.getDBRefs();
321 for (int i = 0, n = dbr.size(); i < n; i++)
323 addDBRef(new DBRefEntry(dbr.get(i)));
328 * make copies of any sequence features
330 for (SequenceFeature sf : seq.getSequenceFeatures())
332 addSequenceFeature(new SequenceFeature(sf));
336 if (seq.getAnnotation() != null)
338 AlignmentAnnotation[] sqann = seq.getAnnotation();
339 for (int i = 0; i < sqann.length; i++)
341 if (sqann[i] == null)
345 boolean found = (alAnnotation == null);
348 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
350 found = (alAnnotation[apos] == sqann[i]);
355 // only copy the given annotation
356 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
357 addAlignmentAnnotation(newann);
361 if (seq.getAllPDBEntries() != null)
363 Vector<PDBEntry> ids = seq.getAllPDBEntries();
364 for (PDBEntry pdb : ids)
366 this.addPDBId(new PDBEntry(pdb));
372 public void setSequenceFeatures(List<SequenceFeature> features)
374 if (datasetSequence != null)
376 datasetSequence.setSequenceFeatures(features);
379 sequenceFeatureStore = new SequenceFeatures(features);
383 public synchronized boolean addSequenceFeature(SequenceFeature sf)
385 if (sf.getType() == null)
388 "SequenceFeature type may not be null: " + sf.toString());
392 if (datasetSequence != null)
394 return datasetSequence.addSequenceFeature(sf);
397 return sequenceFeatureStore.add(sf);
401 public void deleteFeature(SequenceFeature sf)
403 if (datasetSequence != null)
405 datasetSequence.deleteFeature(sf);
409 sequenceFeatureStore.delete(sf);
419 public List<SequenceFeature> getSequenceFeatures()
421 if (datasetSequence != null)
423 return datasetSequence.getSequenceFeatures();
425 return sequenceFeatureStore.getAllFeatures();
429 public SequenceFeaturesI getFeatures()
431 return datasetSequence != null ? datasetSequence.getFeatures()
432 : sequenceFeatureStore;
436 public boolean addPDBId(PDBEntry entry)
440 pdbIds = new Vector<>();
445 for (PDBEntry pdbe : pdbIds)
447 if (pdbe.updateFrom(entry))
452 pdbIds.addElement(entry);
463 public void setPDBId(Vector<PDBEntry> id)
471 * @return DOCUMENT ME!
474 public Vector<PDBEntry> getAllPDBEntries()
476 return pdbIds == null ? new Vector<>() : pdbIds;
482 * @return DOCUMENT ME!
485 public String getDisplayId(boolean jvsuffix)
487 StringBuffer result = new StringBuffer(name);
490 result.append("/" + start + "-" + end);
493 return result.toString();
497 * Sets the sequence name. If the name ends in /start-end, then the start-end
498 * values are parsed out and set, and the suffix is removed from the name.
503 public void setName(String theName)
512 * @return DOCUMENT ME!
515 public String getName()
527 public void setStart(int start)
535 * @return DOCUMENT ME!
538 public int getStart()
550 public void setEnd(int end)
558 * @return DOCUMENT ME!
569 * @return DOCUMENT ME!
572 public int getLength()
574 return this.sequence.length;
584 public void setSequence(String seq)
586 this.sequence = seq.toCharArray();
592 public String getSequenceAsString()
594 return new String(sequence);
598 public String getSequenceAsString(int start, int end)
600 return new String(getSequence(start, end));
604 public char[] getSequence()
607 return sequence == null ? null
608 : Arrays.copyOf(sequence, sequence.length);
614 * @see jalview.datamodel.SequenceI#getSequence(int, int)
617 public char[] getSequence(int start, int end)
623 // JBPNote - left to user to pad the result here (TODO:Decide on this
625 if (start >= sequence.length)
630 if (end >= sequence.length)
632 end = sequence.length;
635 char[] reply = new char[end - start];
636 System.arraycopy(sequence, start, reply, 0, end - start);
642 public SequenceI getSubSequence(int start, int end)
648 char[] seq = getSequence(start, end);
653 int nstart = findPosition(start);
654 int nend = findPosition(end) - 1;
655 // JBPNote - this is an incomplete copy.
656 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
657 nseq.setDescription(description);
658 if (datasetSequence != null)
660 nseq.setDatasetSequence(datasetSequence);
664 nseq.setDatasetSequence(this);
670 * Returns the character of the aligned sequence at the given position (base
671 * zero), or space if the position is not within the sequence's bounds
676 public char getCharAt(int i)
678 if (i >= 0 && i < sequence.length)
689 * Sets the sequence description, and also parses out any special formats of
695 public void setDescription(String desc)
697 this.description = desc;
701 public void setGeneLoci(String speciesId, String assemblyId,
702 String chromosomeId, MapList map)
704 addDBRef(new DBRefEntry(speciesId, assemblyId,
705 DBRefEntry.CHROMOSOME + ":" + chromosomeId, new Mapping(map)));
709 * Returns the gene loci mapping for the sequence (may be null)
714 public GeneLociI getGeneLoci()
716 List<DBRefEntry> refs = getDBRefs();
719 for (final DBRefEntry ref : refs)
721 if (ref.isChromosome())
723 return new GeneLociI()
726 public String getSpeciesId()
728 return ref.getSource();
732 public String getAssemblyId()
734 // DEV NOTE: DBRefEntry is reused here to hold chromosomal locus
735 // of a gene sequence.
736 // source=species, version=assemblyId, accession=chromosome, map =
739 return ref.getVersion();
743 public String getChromosomeId()
745 // strip off "chromosome:" prefix to chrId
746 return ref.getAccessionId()
747 .substring(DBRefEntry.CHROMOSOME.length() + 1);
751 public MapList getMap()
753 return ref.getMap().getMap();
763 * Answers the description
768 public String getDescription()
770 return this.description;
777 public int findIndex(int pos)
780 * use a valid, hopefully nearby, cursor if available
782 if (isValidCursor(cursor))
784 return findIndex(pos, cursor);
792 * traverse sequence from the start counting gaps; make a note of
793 * the column of the first residue to save in the cursor
795 while ((i < sequence.length) && (j <= end) && (j <= pos))
797 if (!Comparison.isGap(sequence[i]))
808 if (j == end && j < pos)
813 updateCursor(pos, i, startColumn);
818 * Updates the cursor to the latest found residue and column position
825 * column position of the first sequence residue
827 protected void updateCursor(int residuePos, int column, int startColumn)
830 * preserve end residue column provided cursor was valid
832 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
834 if (residuePos == this.end)
839 cursor = new SequenceCursor(this, residuePos, column, startColumn,
840 endColumn, this.changeCount);
844 * Answers the aligned column position (1..) for the given residue position
845 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
846 * The hint may be left of, at, or to the right of the required position.
852 protected int findIndex(final int pos, SequenceCursor curs)
854 if (!isValidCursor(curs))
857 * wrong or invalidated cursor, compute de novo
859 return findIndex(pos);
862 if (curs.residuePosition == pos)
864 return curs.columnPosition;
868 * move left or right to find pos from hint.position
870 int col = curs.columnPosition - 1; // convert from base 1 to base 0
871 int newPos = curs.residuePosition;
872 int delta = newPos > pos ? -1 : 1;
874 while (newPos != pos)
876 col += delta; // shift one column left or right
881 if (col == sequence.length)
883 col--; // return last column if we failed to reach pos
886 if (!Comparison.isGap(sequence[col]))
892 col++; // convert back to base 1
895 * only update cursor if we found the target position
899 updateCursor(pos, col, curs.firstColumnPosition);
909 public int findPosition(final int column)
912 * use a valid, hopefully nearby, cursor if available
914 if (isValidCursor(cursor))
916 return findPosition(column + 1, cursor);
919 // TODO recode this more naturally i.e. count residues only
920 // as they are found, not 'in anticipation'
923 * traverse the sequence counting gaps; note the column position
924 * of the first residue, to save in the cursor
926 int firstResidueColumn = 0;
927 int lastPosFound = 0;
928 int lastPosFoundColumn = 0;
929 int seqlen = sequence.length;
931 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
933 lastPosFound = start;
934 lastPosFoundColumn = 0;
940 while (j < column && j < seqlen)
942 if (!Comparison.isGap(sequence[j]))
945 lastPosFoundColumn = j;
946 if (pos == this.start)
948 firstResidueColumn = j;
954 if (j < seqlen && !Comparison.isGap(sequence[j]))
957 lastPosFoundColumn = j;
958 if (pos == this.start)
960 firstResidueColumn = j;
965 * update the cursor to the last residue position found (if any)
966 * (converting column position to base 1)
968 if (lastPosFound != 0)
970 updateCursor(lastPosFound, lastPosFoundColumn + 1,
971 firstResidueColumn + 1);
978 * Answers true if the given cursor is not null, is for this sequence object,
979 * and has a token value that matches this object's changeCount, else false.
980 * This allows us to ignore a cursor as 'stale' if the sequence has been
981 * modified since the cursor was created.
986 protected boolean isValidCursor(SequenceCursor curs)
988 if (curs == null || curs.sequence != this || curs.token != changeCount)
993 * sanity check against range
995 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
999 if (curs.residuePosition < start || curs.residuePosition > end)
1007 * Answers the sequence position (start..) for the given aligned column
1008 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
1009 * may lie left of, at, or to the right of the column position.
1015 protected int findPosition(final int col, SequenceCursor curs)
1017 if (!isValidCursor(curs))
1020 * wrong or invalidated cursor, compute de novo
1022 return findPosition(col - 1);// ugh back to base 0
1025 if (curs.columnPosition == col)
1027 cursor = curs; // in case this method becomes public
1028 return curs.residuePosition; // easy case :-)
1031 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
1034 * sequence lies entirely to the left of col
1035 * - return last residue + 1
1040 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
1043 * sequence lies entirely to the right of col
1044 * - return first residue
1049 // todo could choose closest to col out of column,
1050 // firstColumnPosition, lastColumnPosition as a start point
1053 * move left or right to find pos from cursor position
1055 int firstResidueColumn = curs.firstColumnPosition;
1056 int column = curs.columnPosition - 1; // to base 0
1057 int newPos = curs.residuePosition;
1058 int delta = curs.columnPosition > col ? -1 : 1;
1059 boolean gapped = false;
1060 int lastFoundPosition = curs.residuePosition;
1061 int lastFoundPositionColumn = curs.columnPosition;
1063 while (column != col - 1)
1065 column += delta; // shift one column left or right
1066 if (column < 0 || column == sequence.length)
1070 gapped = Comparison.isGap(sequence[column]);
1074 lastFoundPosition = newPos;
1075 lastFoundPositionColumn = column + 1;
1076 if (lastFoundPosition == this.start)
1078 firstResidueColumn = column + 1;
1083 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1085 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1086 firstResidueColumn);
1090 * hack to give position to the right if on a gap
1091 * or beyond the length of the sequence (see JAL-2562)
1093 if (delta > 0 && (gapped || column >= sequence.length))
1105 public ContiguousI findPositions(int fromColumn, int toColumn)
1107 if (toColumn < fromColumn || fromColumn < 1)
1113 * find the first non-gapped position, if any
1115 int firstPosition = 0;
1116 int col = fromColumn - 1;
1117 int length = sequence.length;
1118 while (col < length && col < toColumn)
1120 if (!Comparison.isGap(sequence[col]))
1122 firstPosition = findPosition(col++);
1128 if (firstPosition == 0)
1134 * find the last non-gapped position
1136 int lastPosition = firstPosition;
1137 while (col < length && col < toColumn)
1139 if (!Comparison.isGap(sequence[col++]))
1145 return new Range(firstPosition, lastPosition);
1149 * Returns an int array where indices correspond to each residue in the
1150 * sequence and the element value gives its position in the alignment
1152 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1153 * residues in SequenceI object
1156 public int[] gapMap()
1158 String seq = jalview.analysis.AlignSeq.extractGaps(
1159 jalview.util.Comparison.GapChars, new String(sequence));
1160 int[] map = new int[seq.length()];
1164 while (j < sequence.length)
1166 if (!jalview.util.Comparison.isGap(sequence[j]))
1178 * Build a bitset corresponding to sequence gaps
1180 * @return a BitSet where set values correspond to gaps in the sequence
1183 public BitSet gapBitset()
1185 BitSet gaps = new BitSet(sequence.length);
1187 while (j < sequence.length)
1189 if (jalview.util.Comparison.isGap(sequence[j]))
1199 public int[] findPositionMap()
1201 int map[] = new int[sequence.length];
1204 int seqlen = sequence.length;
1205 while ((j < seqlen))
1208 if (!jalview.util.Comparison.isGap(sequence[j]))
1219 public List<int[]> getInsertions()
1221 ArrayList<int[]> map = new ArrayList<>();
1222 int lastj = -1, j = 0;
1224 int seqlen = sequence.length;
1225 while ((j < seqlen))
1227 if (jalview.util.Comparison.isGap(sequence[j]))
1238 map.add(new int[] { lastj, j - 1 });
1246 map.add(new int[] { lastj, j - 1 });
1253 public BitSet getInsertionsAsBits()
1255 BitSet map = new BitSet();
1256 int lastj = -1, j = 0;
1258 int seqlen = sequence.length;
1259 while ((j < seqlen))
1261 if (jalview.util.Comparison.isGap(sequence[j]))
1287 public void deleteChars(final int i, final int j)
1289 int newstart = start, newend = end;
1290 if (i >= sequence.length || i < 0)
1295 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1296 boolean createNewDs = false;
1297 // TODO: take a (second look) at the dataset creation validation method for
1298 // the very large sequence case
1300 int startIndex = findIndex(start) - 1;
1301 int endIndex = findIndex(end) - 1;
1302 int startDeleteColumn = -1; // for dataset sequence deletions
1303 int deleteCount = 0;
1305 for (int s = i; s < j && s < sequence.length; s++)
1307 if (Comparison.isGap(sequence[s]))
1312 if (startDeleteColumn == -1)
1314 startDeleteColumn = findPosition(s) - start;
1322 if (startIndex == s)
1325 * deleting characters from start of sequence; new start is the
1326 * sequence position of the next column (position to the right
1327 * if the column position is gapped)
1329 newstart = findPosition(j);
1337 * deleting characters at end of sequence; new end is the sequence
1338 * position of the column before the deletion; subtract 1 if this is
1339 * gapped since findPosition returns the next sequence position
1341 newend = findPosition(i - 1);
1342 if (Comparison.isGap(sequence[i - 1]))
1357 if (createNewDs && this.datasetSequence != null)
1360 * if deletion occured in the middle of the sequence,
1361 * construct a new dataset sequence and delete the residues
1362 * that were deleted from the aligned sequence
1364 Sequence ds = new Sequence(datasetSequence);
1365 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1366 datasetSequence = ds;
1367 // TODO: remove any non-inheritable properties ?
1368 // TODO: create a sequence mapping (since there is a relation here ?)
1377 public void insertCharAt(int i, int length, char c)
1379 char[] tmp = new char[sequence.length + length];
1381 if (i >= sequence.length)
1383 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1384 i = sequence.length;
1388 System.arraycopy(sequence, 0, tmp, 0, i);
1398 if (i < sequence.length)
1400 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1408 public void insertCharAt(int i, char c)
1410 insertCharAt(i, 1, c);
1414 public String getVamsasId()
1420 public void setVamsasId(String id)
1427 public void setDBRefs(DBModList<DBRefEntry> newDBrefs)
1429 if (dbrefs == null && datasetSequence != null
1430 && this != datasetSequence)
1432 datasetSequence.setDBRefs(newDBrefs);
1440 public DBModList<DBRefEntry> getDBRefs()
1442 if (dbrefs == null && datasetSequence != null
1443 && this != datasetSequence)
1445 return datasetSequence.getDBRefs();
1451 public void addDBRef(DBRefEntry entry)
1453 if (datasetSequence != null)
1455 datasetSequence.addDBRef(entry);
1461 dbrefs = new DBModList<>();
1464 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1466 if (dbrefs.get(ib).updateFrom(entry))
1469 * found a dbref that either matched, or could be
1470 * updated from, the new entry - no need to add it
1478 // * extend the array to make room for one more
1480 // // TODO use an ArrayList instead
1481 // int j = dbrefs.length;
1482 // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1483 // System.arraycopy(dbrefs, 0, temp, 0, j);
1484 // temp[temp.length - 1] = entry;
1492 public void setDatasetSequence(SequenceI seq)
1496 throw new IllegalArgumentException(
1497 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1499 if (seq != null && seq.getDatasetSequence() != null)
1501 throw new IllegalArgumentException(
1502 "Implementation error: cascading dataset sequences are not allowed.");
1504 datasetSequence = seq;
1508 public SequenceI getDatasetSequence()
1510 return datasetSequence;
1514 public AlignmentAnnotation[] getAnnotation()
1516 return annotation == null ? null
1518 .toArray(new AlignmentAnnotation[annotation.size()]);
1522 public boolean hasAnnotation(AlignmentAnnotation ann)
1524 return annotation == null ? false : annotation.contains(ann);
1528 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1530 if (this.annotation == null)
1532 this.annotation = new Vector<>();
1534 if (!this.annotation.contains(annotation))
1536 this.annotation.addElement(annotation);
1538 annotation.setSequenceRef(this);
1542 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1544 if (this.annotation != null)
1546 this.annotation.removeElement(annotation);
1547 if (this.annotation.size() == 0)
1549 this.annotation = null;
1555 * test if this is a valid candidate for another sequence's dataset sequence.
1558 private boolean isValidDatasetSequence()
1560 if (datasetSequence != null)
1564 for (int i = 0; i < sequence.length; i++)
1566 if (jalview.util.Comparison.isGap(sequence[i]))
1575 public SequenceI deriveSequence()
1577 Sequence seq = null;
1578 if (datasetSequence == null)
1580 if (isValidDatasetSequence())
1582 // Use this as dataset sequence
1583 seq = new Sequence(getName(), "", 1, -1);
1584 seq.setDatasetSequence(this);
1585 seq.initSeqFrom(this, getAnnotation());
1590 // Create a new, valid dataset sequence
1591 createDatasetSequence();
1594 return new Sequence(this);
1597 private boolean _isNa;
1599 private int _seqhash = 0;
1601 private List<DBRefEntry> primaryRefs;
1604 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1608 public boolean isProtein()
1610 if (datasetSequence != null)
1612 return datasetSequence.isProtein();
1614 if (_seqhash != sequence.hashCode())
1616 _seqhash = sequence.hashCode();
1617 _isNa = Comparison.isNucleotide(this);
1625 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1628 public SequenceI createDatasetSequence()
1630 if (datasetSequence == null)
1632 Sequence dsseq = new Sequence(getName(),
1633 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1634 getSequenceAsString()),
1635 getStart(), getEnd());
1637 datasetSequence = dsseq;
1639 dsseq.setDescription(description);
1640 // move features and database references onto dataset sequence
1641 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1642 sequenceFeatureStore = null;
1643 dsseq.dbrefs = dbrefs;
1645 // TODO: search and replace any references to this sequence with
1646 // references to the dataset sequence in Mappings on dbref
1647 dsseq.pdbIds = pdbIds;
1649 datasetSequence.updatePDBIds();
1650 if (annotation != null)
1652 // annotation is cloned rather than moved, to preserve what's currently
1654 for (AlignmentAnnotation aa : annotation)
1656 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1657 _aa.sequenceRef = datasetSequence;
1658 _aa.adjustForAlignment(); // uses annotation's own record of
1659 // sequence-column mapping
1660 datasetSequence.addAlignmentAnnotation(_aa);
1664 return datasetSequence;
1671 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1675 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1677 if (annotation != null)
1679 annotation.removeAllElements();
1681 if (annotations != null)
1683 for (int i = 0; i < annotations.length; i++)
1685 if (annotations[i] != null)
1687 addAlignmentAnnotation(annotations[i]);
1694 public AlignmentAnnotation[] getAnnotation(String label)
1696 if (annotation == null || annotation.size() == 0)
1701 Vector<AlignmentAnnotation> subset = new Vector<>();
1702 Enumeration<AlignmentAnnotation> e = annotation.elements();
1703 while (e.hasMoreElements())
1705 AlignmentAnnotation ann = e.nextElement();
1706 if (ann.label != null && ann.label.equals(label))
1708 subset.addElement(ann);
1711 if (subset.size() == 0)
1715 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1717 e = subset.elements();
1718 while (e.hasMoreElements())
1720 anns[i++] = e.nextElement();
1722 subset.removeAllElements();
1727 public boolean updatePDBIds()
1729 if (datasetSequence != null)
1731 // TODO: could merge DBRefs
1732 return datasetSequence.updatePDBIds();
1734 if (dbrefs == null || dbrefs.size() == 0)
1738 boolean added = false;
1739 for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1741 DBRefEntry dbr = dbrefs.get(ib);
1742 if (DBRefSource.PDB.equals(dbr.getSource()))
1745 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1746 * PDB id is not already present in a 'matching' PDBEntry
1747 * Constructor parses out a chain code if appended to the accession id
1748 * (a fudge used to 'store' the chain code in the DBRef)
1750 PDBEntry pdbe = new PDBEntry(dbr);
1751 added |= addPDBId(pdbe);
1758 public void transferAnnotation(SequenceI entry, Mapping mp)
1760 if (datasetSequence != null)
1762 datasetSequence.transferAnnotation(entry, mp);
1765 if (entry.getDatasetSequence() != null)
1767 transferAnnotation(entry.getDatasetSequence(), mp);
1770 // transfer any new features from entry onto sequence
1771 if (entry.getSequenceFeatures() != null)
1774 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1775 for (SequenceFeature feature : sfs)
1777 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1778 : new SequenceFeature[]
1779 { new SequenceFeature(feature) };
1782 for (int sfi = 0; sfi < sf.length; sfi++)
1784 addSequenceFeature(sf[sfi]);
1790 // transfer PDB entries
1791 if (entry.getAllPDBEntries() != null)
1793 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1794 while (e.hasMoreElements())
1796 PDBEntry pdb = e.nextElement();
1800 // transfer database references
1801 List<DBRefEntry> entryRefs = entry.getDBRefs();
1802 if (entryRefs != null)
1804 for (int r = 0, n = entryRefs.size(); r < n; r++)
1806 DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1807 if (newref.getMap() != null && mp != null)
1809 // remap ref using our local mapping
1811 // we also assume all version string setting is done by dbSourceProxy
1813 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1814 * newref.setSource(dbSource); }
1822 public void setRNA(RNA r)
1834 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1837 List<AlignmentAnnotation> result = new ArrayList<>();
1838 if (this.annotation != null)
1840 for (AlignmentAnnotation ann : annotation)
1842 if (ann.calcId != null && ann.calcId.equals(calcId)
1843 && ann.label != null && ann.label.equals(label))
1853 public String toString()
1855 return getDisplayId(false);
1859 public PDBEntry getPDBEntry(String pdbIdStr)
1861 if (getDatasetSequence() != null)
1863 return getDatasetSequence().getPDBEntry(pdbIdStr);
1869 List<PDBEntry> entries = getAllPDBEntries();
1870 for (PDBEntry entry : entries)
1872 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1880 private List<DBRefEntry> tmpList;
1883 public List<DBRefEntry> getPrimaryDBRefs()
1885 if (datasetSequence != null)
1887 return datasetSequence.getPrimaryDBRefs();
1889 if (dbrefs == null || dbrefs.size() == 0)
1891 return Collections.emptyList();
1893 synchronized (dbrefs)
1895 if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1897 return primaryRefs; // no changes
1899 refModCount = dbrefs.getModCount();
1900 List<DBRefEntry> primaries = (primaryRefs == null
1901 ? (primaryRefs = new ArrayList<>())
1904 if (tmpList == null)
1906 tmpList = new ArrayList<>();
1907 tmpList.add(null); // for replacement
1909 for (int i = 0, n = dbrefs.size(); i < n; i++)
1911 DBRefEntry ref = dbrefs.get(i);
1912 if (!ref.isPrimaryCandidate())
1918 MapList mp = ref.getMap().getMap();
1919 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1921 // map only involves a subsequence, so cannot be primary
1925 // whilst it looks like it is a primary ref, we also sanity check type
1926 if (DBRefSource.PDB_CANONICAL_NAME
1927 .equals(ref.getCanonicalSourceName()))
1929 // PDB dbrefs imply there should be a PDBEntry associated
1930 // TODO: tighten PDB dbrefs
1931 // formally imply Jalview has actually downloaded and
1932 // parsed the pdb file. That means there should be a cached file
1933 // handle on the PDBEntry, and a real mapping between sequence and
1934 // extracted sequence from PDB file
1935 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1936 if (pdbentry == null || pdbentry.getFile() == null)
1943 // check standard protein or dna sources
1944 tmpList.set(0, ref);
1945 List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1947 if (res == null || res.get(0) != tmpList.get(0))
1955 // version must be not null, as otherwise it will not be a candidate,
1957 DBRefUtils.ensurePrimaries(this, primaries);
1966 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1969 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1970 int endPos = fromColumn == toColumn ? startPos
1971 : findPosition(toColumn - 1);
1973 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
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()
2033 public int replace(char c1, char c2)
2040 synchronized (sequence)
2042 for (int c = 0; c < sequence.length; c++)
2044 if (sequence[c] == c1)
2060 public String getSequenceStringFromIterator(Iterator<int[]> it)
2062 StringBuilder newSequence = new StringBuilder();
2063 while (it.hasNext())
2065 int[] block = it.next();
2068 newSequence.append(getSequence(block[0], block[1] + 1));
2072 newSequence.append(getSequence(block[0], block[1]));
2076 return newSequence.toString();
2080 public int firstResidueOutsideIterator(Iterator<int[]> regions)
2084 if (!regions.hasNext())
2086 return findIndex(getStart()) - 1;
2089 // Simply walk along the sequence whilst watching for region
2091 int hideStart = getLength();
2093 boolean foundStart = false;
2095 // step through the non-gapped positions of the sequence
2096 for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2098 // get alignment position of this residue in the sequence
2099 int p = findIndex(i) - 1;
2101 // update region start/end
2102 while (hideEnd < p && regions.hasNext())
2104 int[] region = regions.next();
2105 hideStart = region[0];
2106 hideEnd = region[1];
2110 hideStart = getLength();
2112 // update boundary for sequence
2124 // otherwise, sequence was completely hidden
2129 public int getColor(int i)
2131 return argb == null ? 0 : argb[i];
2135 public int setColor(int i, int rgb)
2139 argb = new int[this.sequence.length];
2141 return (argb[i] = rgb);
2145 public void resetColors()
2151 * Answers a (possibly empty) list of features of the specified type that
2152 * overlap the specified column position. If parameter {@code result} is not
2153 * null, features are appended to it and the (possibly extended) list is
2157 public List<SequenceFeature> findFeatures(int column, String type,
2158 List<SequenceFeature> result)
2160 return getFeatures().findFeatures(findPosition(column - 1), type,
2165 public boolean hasFeatures(String type)
2167 return getFeatures().hasFeatures(type);