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.api.DBRefEntryI;
25 import jalview.datamodel.features.SequenceFeatures;
26 import jalview.datamodel.features.SequenceFeaturesI;
27 import jalview.util.Comparison;
28 import jalview.util.DBRefUtils;
29 import jalview.util.MapList;
30 import jalview.util.StringUtils;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.BitSet;
35 import java.util.Collections;
36 import java.util.Enumeration;
37 import java.util.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.
50 public class Sequence extends ASequence implements SequenceI
52 SequenceI datasetSequence;
56 private char[] sequence;
64 Vector<PDBEntry> pdbIds;
73 * This annotation is displayed below the alignment but the positions are tied
74 * to the residues of this sequence
76 * TODO: change to List<>
78 Vector<AlignmentAnnotation> annotation;
80 private SequenceFeaturesI sequenceFeatureStore;
83 * A cursor holding the approximate current view position to the sequence,
84 * as determined by findIndex or findPosition or findPositions.
85 * Using a cursor as a hint allows these methods to be more performant for
88 private SequenceCursor cursor;
91 * A number that should be incremented whenever the sequence is edited.
92 * If the value matches the cursor token, then we can trust the cursor,
93 * if not then it should be recomputed.
95 private int changeCount;
98 * Creates a new Sequence object.
101 * display name string
103 * string to form a possibly gapped sequence out of
105 * first position of non-gap residue in the sequence
107 * last position of ungapped residues (nearly always only used for
110 public Sequence(String name, String sequence, int start, int end)
113 initSeqAndName(name, sequence.toCharArray(), start, end);
116 public Sequence(String name, char[] sequence, int start, int end)
119 initSeqAndName(name, sequence, start, end);
123 * Stage 1 constructor - assign name, sequence, and set start and end fields.
124 * start and end are updated values from name2 if it ends with /start-end
131 protected void initSeqAndName(String name2, char[] sequence2, int start2,
135 this.sequence = sequence2;
143 * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
144 * start and end respectively and removes the suffix from the name
151 "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
154 int slashPos = name.lastIndexOf('/');
155 if (slashPos > -1 && slashPos < name.length() - 1)
157 String suffix = name.substring(slashPos + 1);
158 String[] range = suffix.split("-");
159 if (range.length == 2)
163 int from = Integer.valueOf(range[0]);
164 int to = Integer.valueOf(range[1]);
165 if (from > 0 && to >= from)
167 name = name.substring(0, slashPos);
172 } catch (NumberFormatException e)
174 // leave name unchanged if suffix is invalid
181 * Ensures that 'end' is not before the end of the sequence, that is,
182 * (end-start+1) is at least as long as the count of ungapped positions. Note
183 * that end is permitted to be beyond the end of the sequence data.
185 void checkValidRange()
188 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
191 for (int j = 0; j < sequence.length; j++)
193 if (!Comparison.isGap(sequence[j]))
212 * default constructor
216 sequenceFeatureStore = new SequenceFeatures();
220 * Creates a new Sequence object.
227 public Sequence(String name, String sequence)
229 this(name, sequence, 1, -1);
233 * Creates a new Sequence object with new AlignmentAnnotations but inherits
234 * any existing dataset sequence reference. If non exists, everything is
238 * if seq is a dataset sequence, behaves like a plain old copy
241 public Sequence(SequenceI seq)
243 this(seq, seq.getAnnotation());
247 * Create a new sequence object with new features, DBRefEntries, and PDBIds
248 * but inherits any existing dataset sequence reference, and duplicate of any
249 * annotation that is present in the given annotation array.
252 * the sequence to be copied
253 * @param alAnnotation
254 * an array of annotation including some associated with seq
256 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
259 initSeqFrom(seq, alAnnotation);
263 * does the heavy lifting when cloning a dataset sequence, or coping data from
264 * dataset to a new derived sequence.
267 * - source of attributes.
268 * @param alAnnotation
269 * - alignment annotation present on seq that should be copied onto
272 protected void initSeqFrom(SequenceI seq,
273 AlignmentAnnotation[] alAnnotation)
275 char[] oseq = seq.getSequence(); // returns a copy of the array
276 initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
278 description = seq.getDescription();
279 if (seq != datasetSequence)
281 setDatasetSequence(seq.getDatasetSequence());
285 * only copy DBRefs and seqfeatures if we really are a dataset sequence
287 if (datasetSequence == null)
289 if (seq.getDBRefs() != null)
291 DBRefEntry[] dbr = seq.getDBRefs();
292 for (int i = 0; i < dbr.length; i++)
294 addDBRef(new DBRefEntry(dbr[i]));
299 * make copies of any sequence features
301 for (SequenceFeature sf : seq.getSequenceFeatures())
303 addSequenceFeature(new SequenceFeature(sf));
307 if (seq.getAnnotation() != null)
309 AlignmentAnnotation[] sqann = seq.getAnnotation();
310 for (int i = 0; i < sqann.length; i++)
312 if (sqann[i] == null)
316 boolean found = (alAnnotation == null);
319 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
321 found = (alAnnotation[apos] == sqann[i]);
326 // only copy the given annotation
327 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
328 addAlignmentAnnotation(newann);
332 if (seq.getAllPDBEntries() != null)
334 Vector<PDBEntry> ids = seq.getAllPDBEntries();
335 for (PDBEntry pdb : ids)
337 this.addPDBId(new PDBEntry(pdb));
343 public void setSequenceFeatures(List<SequenceFeature> features)
345 if (datasetSequence != null)
347 datasetSequence.setSequenceFeatures(features);
350 sequenceFeatureStore = new SequenceFeatures(features);
354 public synchronized boolean addSequenceFeature(SequenceFeature sf)
356 if (sf.getType() == null)
358 System.err.println("SequenceFeature type may not be null: "
363 if (datasetSequence != null)
365 return datasetSequence.addSequenceFeature(sf);
368 return sequenceFeatureStore.add(sf);
372 public void deleteFeature(SequenceFeature sf)
374 if (datasetSequence != null)
376 datasetSequence.deleteFeature(sf);
380 sequenceFeatureStore.delete(sf);
390 public List<SequenceFeature> getSequenceFeatures()
392 if (datasetSequence != null)
394 return datasetSequence.getSequenceFeatures();
396 return sequenceFeatureStore.getAllFeatures();
400 public SequenceFeaturesI getFeatures()
402 return datasetSequence != null ? datasetSequence.getFeatures()
403 : sequenceFeatureStore;
407 public boolean addPDBId(PDBEntry entry)
411 pdbIds = new Vector<PDBEntry>();
416 for (PDBEntry pdbe : pdbIds)
418 if (pdbe.updateFrom(entry))
423 pdbIds.addElement(entry);
434 public void setPDBId(Vector<PDBEntry> id)
442 * @return DOCUMENT ME!
445 public Vector<PDBEntry> getAllPDBEntries()
447 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
453 * @return DOCUMENT ME!
456 public String getDisplayId(boolean jvsuffix)
458 StringBuffer result = new StringBuffer(name);
461 result.append("/" + start + "-" + end);
464 return result.toString();
468 * Sets the sequence name. If the name ends in /start-end, then the start-end
469 * values are parsed out and set, and the suffix is removed from the name.
474 public void setName(String theName)
483 * @return DOCUMENT ME!
486 public String getName()
498 public void setStart(int start)
506 * @return DOCUMENT ME!
509 public int getStart()
521 public void setEnd(int end)
529 * @return DOCUMENT ME!
540 * @return DOCUMENT ME!
543 public int getLength()
545 return this.sequence.length;
555 public void setSequence(String seq)
557 this.sequence = seq.toCharArray();
563 public String getSequenceAsString()
565 return new String(sequence);
569 public String getSequenceAsString(int start, int end)
571 return new String(getSequence(start, end));
575 public char[] getSequence()
578 return sequence == null ? null : Arrays.copyOf(sequence,
585 * @see jalview.datamodel.SequenceI#getSequence(int, int)
588 public char[] getSequence(int start, int end)
594 // JBPNote - left to user to pad the result here (TODO:Decide on this
596 if (start >= sequence.length)
601 if (end >= sequence.length)
603 end = sequence.length;
606 char[] reply = new char[end - start];
607 System.arraycopy(sequence, start, reply, 0, end - start);
613 public SequenceI getSubSequence(int start, int end)
619 char[] seq = getSequence(start, end);
624 int nstart = findPosition(start);
625 int nend = findPosition(end) - 1;
626 // JBPNote - this is an incomplete copy.
627 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
628 nseq.setDescription(description);
629 if (datasetSequence != null)
631 nseq.setDatasetSequence(datasetSequence);
635 nseq.setDatasetSequence(this);
641 * Returns the character of the aligned sequence at the given position (base
642 * zero), or space if the position is not within the sequence's bounds
647 public char getCharAt(int i)
649 if (i >= 0 && i < sequence.length)
660 * Sets the sequence description, and also parses out any special formats of
666 public void setDescription(String desc)
668 this.description = desc;
672 public void setGeneLoci(String speciesId, String assemblyId,
673 String chromosomeId, MapList map)
675 addDBRef(new DBRefEntry(speciesId, assemblyId, DBRefEntry.CHROMOSOME
676 + ":" + chromosomeId, new Mapping(map)));
680 * Returns the gene loci mapping for the sequence (may be null)
685 public GeneLociI getGeneLoci()
687 DBRefEntry[] refs = getDBRefs();
690 for (final DBRefEntry ref : refs)
692 if (ref.isChromosome())
694 return new GeneLociI()
697 public String getSpeciesId()
699 return ref.getSource();
703 public String getAssemblyId()
705 return ref.getVersion();
709 public String getChromosomeId()
711 // strip off "chromosome:" prefix to chrId
712 return ref.getAccessionId().substring(
713 DBRefEntry.CHROMOSOME.length() + 1);
717 public MapList getMap()
719 return ref.getMap().getMap();
729 * Answers the description
734 public String getDescription()
736 return this.description;
743 public int findIndex(int pos)
746 * use a valid, hopefully nearby, cursor if available
748 if (isValidCursor(cursor))
750 return findIndex(pos, cursor);
758 * traverse sequence from the start counting gaps; make a note of
759 * the column of the first residue to save in the cursor
761 while ((i < sequence.length) && (j <= end) && (j <= pos))
763 if (!Comparison.isGap(sequence[i]))
774 if (j == end && j < pos)
779 updateCursor(pos, i, startColumn);
784 * Updates the cursor to the latest found residue and column position
791 * column position of the first sequence residue
793 protected void updateCursor(int residuePos, int column, int startColumn)
796 * preserve end residue column provided cursor was valid
798 int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
799 if (residuePos == this.end)
804 cursor = new SequenceCursor(this, residuePos, column, startColumn,
805 endColumn, this.changeCount);
809 * Answers the aligned column position (1..) for the given residue position
810 * (start..) given a 'hint' of a residue/column location in the neighbourhood.
811 * The hint may be left of, at, or to the right of the required position.
817 protected int findIndex(int pos, SequenceCursor curs)
819 if (!isValidCursor(curs))
822 * wrong or invalidated cursor, compute de novo
824 return findIndex(pos);
827 if (curs.residuePosition == pos)
829 return curs.columnPosition;
833 * move left or right to find pos from hint.position
835 int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
837 int newPos = curs.residuePosition;
838 int delta = newPos > pos ? -1 : 1;
840 while (newPos != pos)
842 col += delta; // shift one column left or right
843 if (col < 0 || col == sequence.length)
847 if (!Comparison.isGap(sequence[col]))
853 col++; // convert back to base 1
854 updateCursor(pos, col, curs.firstColumnPosition);
863 public int findPosition(final int column)
866 * use a valid, hopefully nearby, cursor if available
868 if (isValidCursor(cursor))
870 return findPosition(column + 1, cursor);
873 // TODO recode this more naturally i.e. count residues only
874 // as they are found, not 'in anticipation'
877 * traverse the sequence counting gaps; note the column position
878 * of the first residue, to save in the cursor
880 int firstResidueColumn = 0;
881 int lastPosFound = 0;
882 int lastPosFoundColumn = 0;
883 int seqlen = sequence.length;
885 if (seqlen > 0 && !Comparison.isGap(sequence[0]))
887 lastPosFound = start;
888 lastPosFoundColumn = 0;
894 while (j < column && j < seqlen)
896 if (!Comparison.isGap(sequence[j]))
899 lastPosFoundColumn = j;
900 if (pos == this.start)
902 firstResidueColumn = j;
908 if (j < seqlen && !Comparison.isGap(sequence[j]))
911 lastPosFoundColumn = j;
912 if (pos == this.start)
914 firstResidueColumn = j;
919 * update the cursor to the last residue position found (if any)
920 * (converting column position to base 1)
922 if (lastPosFound != 0)
924 updateCursor(lastPosFound, lastPosFoundColumn + 1,
925 firstResidueColumn + 1);
932 * Answers true if the given cursor is not null, is for this sequence object,
933 * and has a token value that matches this object's changeCount, else false.
934 * This allows us to ignore a cursor as 'stale' if the sequence has been
935 * modified since the cursor was created.
940 protected boolean isValidCursor(SequenceCursor curs)
942 if (curs == null || curs.sequence != this || curs.token != changeCount)
947 * sanity check against range
949 if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
953 if (curs.residuePosition < start || curs.residuePosition > end)
961 * Answers the sequence position (start..) for the given aligned column
962 * position (1..), given a hint of a cursor in the neighbourhood. The cursor
963 * may lie left of, at, or to the right of the column position.
969 protected int findPosition(final int col, SequenceCursor curs)
971 if (!isValidCursor(curs))
974 * wrong or invalidated cursor, compute de novo
976 return findPosition(col - 1);// ugh back to base 0
979 if (curs.columnPosition == col)
981 cursor = curs; // in case this method becomes public
982 return curs.residuePosition; // easy case :-)
985 if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
988 * sequence lies entirely to the left of col
989 * - return last residue + 1
994 if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
997 * sequence lies entirely to the right of col
998 * - return first residue
1003 // todo could choose closest to col out of column,
1004 // firstColumnPosition, lastColumnPosition as a start point
1007 * move left or right to find pos from cursor position
1009 int firstResidueColumn = curs.firstColumnPosition;
1010 int column = curs.columnPosition - 1; // to base 0
1011 int newPos = curs.residuePosition;
1012 int delta = curs.columnPosition > col ? -1 : 1;
1013 boolean gapped = false;
1014 int lastFoundPosition = curs.residuePosition;
1015 int lastFoundPositionColumn = curs.columnPosition;
1017 while (column != col - 1)
1019 column += delta; // shift one column left or right
1020 if (column < 0 || column == sequence.length)
1024 gapped = Comparison.isGap(sequence[column]);
1028 lastFoundPosition = newPos;
1029 lastFoundPositionColumn = column + 1;
1030 if (lastFoundPosition == this.start)
1032 firstResidueColumn = column + 1;
1037 if (cursor == null || lastFoundPosition != cursor.residuePosition)
1039 updateCursor(lastFoundPosition, lastFoundPositionColumn,
1040 firstResidueColumn);
1044 * hack to give position to the right if on a gap
1045 * or beyond the length of the sequence (see JAL-2562)
1047 if (delta > 0 && (gapped || column >= sequence.length))
1059 public Range findPositions(int fromColumn, int toColumn)
1061 if (toColumn < fromColumn || fromColumn < 1)
1067 * find the first non-gapped position, if any
1069 int firstPosition = 0;
1070 int col = fromColumn - 1;
1071 int length = sequence.length;
1072 while (col < length && col < toColumn)
1074 if (!Comparison.isGap(sequence[col]))
1076 firstPosition = findPosition(col++);
1082 if (firstPosition == 0)
1088 * find the last non-gapped position
1090 int lastPosition = firstPosition;
1091 while (col < length && col < toColumn)
1093 if (!Comparison.isGap(sequence[col++]))
1099 return new Range(firstPosition, lastPosition);
1103 * Returns an int array where indices correspond to each residue in the
1104 * sequence and the element value gives its position in the alignment
1106 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1107 * residues in SequenceI object
1110 public int[] gapMap()
1112 String seq = jalview.analysis.AlignSeq.extractGaps(
1113 jalview.util.Comparison.GapChars, new String(sequence));
1114 int[] map = new int[seq.length()];
1118 while (j < sequence.length)
1120 if (!jalview.util.Comparison.isGap(sequence[j]))
1132 public int[] findPositionMap()
1134 int map[] = new int[sequence.length];
1137 int seqlen = sequence.length;
1138 while ((j < seqlen))
1141 if (!jalview.util.Comparison.isGap(sequence[j]))
1152 public List<int[]> getInsertions()
1154 ArrayList<int[]> map = new ArrayList<int[]>();
1155 int lastj = -1, j = 0;
1157 int seqlen = sequence.length;
1158 while ((j < seqlen))
1160 if (jalview.util.Comparison.isGap(sequence[j]))
1171 map.add(new int[] { lastj, j - 1 });
1179 map.add(new int[] { lastj, j - 1 });
1186 public BitSet getInsertionsAsBits()
1188 BitSet map = new BitSet();
1189 int lastj = -1, j = 0;
1191 int seqlen = sequence.length;
1192 while ((j < seqlen))
1194 if (jalview.util.Comparison.isGap(sequence[j]))
1220 public void deleteChars(final int i, final int j)
1222 int newstart = start, newend = end;
1223 if (i >= sequence.length || i < 0)
1228 char[] tmp = StringUtils.deleteChars(sequence, i, j);
1229 boolean createNewDs = false;
1230 // TODO: take a (second look) at the dataset creation validation method for
1231 // the very large sequence case
1232 int startIndex = findIndex(start) - 1;
1233 int endIndex = findIndex(end) - 1;
1234 int startDeleteColumn = -1; // for dataset sequence deletions
1235 int deleteCount = 0;
1237 for (int s = i; s < j; s++)
1239 if (Comparison.isGap(sequence[s]))
1244 if (startDeleteColumn == -1)
1246 startDeleteColumn = findPosition(s) - start;
1254 if (startIndex == s)
1257 * deleting characters from start of sequence; new start is the
1258 * sequence position of the next column (position to the right
1259 * if the column position is gapped)
1261 newstart = findPosition(j);
1269 * deleting characters at end of sequence; new end is the sequence
1270 * position of the column before the deletion; subtract 1 if this is
1271 * gapped since findPosition returns the next sequence position
1273 newend = findPosition(i - 1);
1274 if (Comparison.isGap(sequence[i - 1]))
1289 if (createNewDs && this.datasetSequence != null)
1292 * if deletion occured in the middle of the sequence,
1293 * construct a new dataset sequence and delete the residues
1294 * that were deleted from the aligned sequence
1296 Sequence ds = new Sequence(datasetSequence);
1297 ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1298 datasetSequence = ds;
1299 // TODO: remove any non-inheritable properties ?
1300 // TODO: create a sequence mapping (since there is a relation here ?)
1309 public void insertCharAt(int i, int length, char c)
1311 char[] tmp = new char[sequence.length + length];
1313 if (i >= sequence.length)
1315 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1316 i = sequence.length;
1320 System.arraycopy(sequence, 0, tmp, 0, i);
1330 if (i < sequence.length)
1332 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1340 public void insertCharAt(int i, char c)
1342 insertCharAt(i, 1, c);
1346 public String getVamsasId()
1352 public void setVamsasId(String id)
1358 public void setDBRefs(DBRefEntry[] dbref)
1360 if (dbrefs == null && datasetSequence != null
1361 && this != datasetSequence)
1363 datasetSequence.setDBRefs(dbref);
1369 DBRefUtils.ensurePrimaries(this);
1374 public DBRefEntry[] getDBRefs()
1376 if (dbrefs == null && datasetSequence != null
1377 && this != datasetSequence)
1379 return datasetSequence.getDBRefs();
1385 public void addDBRef(DBRefEntry entry)
1387 if (datasetSequence != null)
1389 datasetSequence.addDBRef(entry);
1395 dbrefs = new DBRefEntry[0];
1398 for (DBRefEntryI dbr : dbrefs)
1400 if (dbr.updateFrom(entry))
1403 * found a dbref that either matched, or could be
1404 * updated from, the new entry - no need to add it
1411 * extend the array to make room for one more
1413 // TODO use an ArrayList instead
1414 int j = dbrefs.length;
1415 DBRefEntry[] temp = new DBRefEntry[j + 1];
1416 System.arraycopy(dbrefs, 0, temp, 0, j);
1417 temp[temp.length - 1] = entry;
1421 DBRefUtils.ensurePrimaries(this);
1425 public void setDatasetSequence(SequenceI seq)
1429 throw new IllegalArgumentException(
1430 "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1432 if (seq != null && seq.getDatasetSequence() != null)
1434 throw new IllegalArgumentException(
1435 "Implementation error: cascading dataset sequences are not allowed.");
1437 datasetSequence = seq;
1441 public SequenceI getDatasetSequence()
1443 return datasetSequence;
1447 public AlignmentAnnotation[] getAnnotation()
1449 return annotation == null ? null
1451 .toArray(new AlignmentAnnotation[annotation.size()]);
1455 public boolean hasAnnotation(AlignmentAnnotation ann)
1457 return annotation == null ? false : annotation.contains(ann);
1461 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1463 if (this.annotation == null)
1465 this.annotation = new Vector<AlignmentAnnotation>();
1467 if (!this.annotation.contains(annotation))
1469 this.annotation.addElement(annotation);
1471 annotation.setSequenceRef(this);
1475 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1477 if (this.annotation != null)
1479 this.annotation.removeElement(annotation);
1480 if (this.annotation.size() == 0)
1482 this.annotation = null;
1488 * test if this is a valid candidate for another sequence's dataset sequence.
1491 private boolean isValidDatasetSequence()
1493 if (datasetSequence != null)
1497 for (int i = 0; i < sequence.length; i++)
1499 if (jalview.util.Comparison.isGap(sequence[i]))
1508 public SequenceI deriveSequence()
1510 Sequence seq = null;
1511 if (datasetSequence == null)
1513 if (isValidDatasetSequence())
1515 // Use this as dataset sequence
1516 seq = new Sequence(getName(), "", 1, -1);
1517 seq.setDatasetSequence(this);
1518 seq.initSeqFrom(this, getAnnotation());
1523 // Create a new, valid dataset sequence
1524 createDatasetSequence();
1527 return new Sequence(this);
1530 private boolean _isNa;
1532 private int _seqhash = 0;
1535 * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1539 public boolean isProtein()
1541 if (datasetSequence != null)
1543 return datasetSequence.isProtein();
1545 if (_seqhash != sequence.hashCode())
1547 _seqhash = sequence.hashCode();
1548 _isNa = Comparison.isNucleotide(this);
1556 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1559 public SequenceI createDatasetSequence()
1561 if (datasetSequence == null)
1563 Sequence dsseq = new Sequence(getName(),
1564 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1565 getSequenceAsString()),
1566 getStart(), getEnd());
1568 datasetSequence = dsseq;
1570 dsseq.setDescription(description);
1571 // move features and database references onto dataset sequence
1572 dsseq.sequenceFeatureStore = sequenceFeatureStore;
1573 sequenceFeatureStore = null;
1574 dsseq.dbrefs = dbrefs;
1576 // TODO: search and replace any references to this sequence with
1577 // references to the dataset sequence in Mappings on dbref
1578 dsseq.pdbIds = pdbIds;
1580 datasetSequence.updatePDBIds();
1581 if (annotation != null)
1583 // annotation is cloned rather than moved, to preserve what's currently
1585 for (AlignmentAnnotation aa : annotation)
1587 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1588 _aa.sequenceRef = datasetSequence;
1589 _aa.adjustForAlignment(); // uses annotation's own record of
1590 // sequence-column mapping
1591 datasetSequence.addAlignmentAnnotation(_aa);
1595 return datasetSequence;
1602 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1606 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1608 if (annotation != null)
1610 annotation.removeAllElements();
1612 if (annotations != null)
1614 for (int i = 0; i < annotations.length; i++)
1616 if (annotations[i] != null)
1618 addAlignmentAnnotation(annotations[i]);
1625 public AlignmentAnnotation[] getAnnotation(String label)
1627 if (annotation == null || annotation.size() == 0)
1632 Vector<AlignmentAnnotation> subset = new Vector<AlignmentAnnotation>();
1633 Enumeration<AlignmentAnnotation> e = annotation.elements();
1634 while (e.hasMoreElements())
1636 AlignmentAnnotation ann = e.nextElement();
1637 if (ann.label != null && ann.label.equals(label))
1639 subset.addElement(ann);
1642 if (subset.size() == 0)
1646 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1648 e = subset.elements();
1649 while (e.hasMoreElements())
1651 anns[i++] = e.nextElement();
1653 subset.removeAllElements();
1658 public boolean updatePDBIds()
1660 if (datasetSequence != null)
1662 // TODO: could merge DBRefs
1663 return datasetSequence.updatePDBIds();
1665 if (dbrefs == null || dbrefs.length == 0)
1669 boolean added = false;
1670 for (DBRefEntry dbr : dbrefs)
1672 if (DBRefSource.PDB.equals(dbr.getSource()))
1675 * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1676 * PDB id is not already present in a 'matching' PDBEntry
1677 * Constructor parses out a chain code if appended to the accession id
1678 * (a fudge used to 'store' the chain code in the DBRef)
1680 PDBEntry pdbe = new PDBEntry(dbr);
1681 added |= addPDBId(pdbe);
1688 public void transferAnnotation(SequenceI entry, Mapping mp)
1690 if (datasetSequence != null)
1692 datasetSequence.transferAnnotation(entry, mp);
1695 if (entry.getDatasetSequence() != null)
1697 transferAnnotation(entry.getDatasetSequence(), mp);
1700 // transfer any new features from entry onto sequence
1701 if (entry.getSequenceFeatures() != null)
1704 List<SequenceFeature> sfs = entry.getSequenceFeatures();
1705 for (SequenceFeature feature : sfs)
1707 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1708 : new SequenceFeature[] { new SequenceFeature(feature) };
1711 for (int sfi = 0; sfi < sf.length; sfi++)
1713 addSequenceFeature(sf[sfi]);
1719 // transfer PDB entries
1720 if (entry.getAllPDBEntries() != null)
1722 Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1723 while (e.hasMoreElements())
1725 PDBEntry pdb = e.nextElement();
1729 // transfer database references
1730 DBRefEntry[] entryRefs = entry.getDBRefs();
1731 if (entryRefs != null)
1733 for (int r = 0; r < entryRefs.length; r++)
1735 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1736 if (newref.getMap() != null && mp != null)
1738 // remap ref using our local mapping
1740 // we also assume all version string setting is done by dbSourceProxy
1742 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1743 * newref.setSource(dbSource); }
1751 public void setRNA(RNA r)
1763 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1766 List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1767 if (this.annotation != null)
1769 for (AlignmentAnnotation ann : annotation)
1771 if (ann.calcId != null && ann.calcId.equals(calcId)
1772 && ann.label != null && ann.label.equals(label))
1782 public String toString()
1784 return getDisplayId(false);
1788 public PDBEntry getPDBEntry(String pdbIdStr)
1790 if (getDatasetSequence() != null)
1792 return getDatasetSequence().getPDBEntry(pdbIdStr);
1798 List<PDBEntry> entries = getAllPDBEntries();
1799 for (PDBEntry entry : entries)
1801 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1810 public List<DBRefEntry> getPrimaryDBRefs()
1812 if (datasetSequence != null)
1814 return datasetSequence.getPrimaryDBRefs();
1816 if (dbrefs == null || dbrefs.length == 0)
1818 return Collections.emptyList();
1820 synchronized (dbrefs)
1822 List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1823 DBRefEntry[] tmp = new DBRefEntry[1];
1824 for (DBRefEntry ref : dbrefs)
1826 if (!ref.isPrimaryCandidate())
1832 MapList mp = ref.getMap().getMap();
1833 if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1835 // map only involves a subsequence, so cannot be primary
1839 // whilst it looks like it is a primary ref, we also sanity check type
1840 if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1841 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1843 // PDB dbrefs imply there should be a PDBEntry associated
1844 // TODO: tighten PDB dbrefs
1845 // formally imply Jalview has actually downloaded and
1846 // parsed the pdb file. That means there should be a cached file
1847 // handle on the PDBEntry, and a real mapping between sequence and
1848 // extracted sequence from PDB file
1849 PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1850 if (pdbentry != null && pdbentry.getFile() != null)
1856 // check standard protein or dna sources
1858 DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1859 if (res != null && res[0] == tmp[0])
1873 public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1876 int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1877 int endPos = fromColumn == toColumn ? startPos
1878 : findPosition(toColumn - 1);
1880 List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1884 * if end column is gapped, endPos may be to the right,
1885 * and we may have included adjacent or enclosing features;
1886 * remove any that are not enclosing, non-contact features
1888 boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1889 && Comparison.isGap(sequence[toColumn - 1]);
1890 if (endPos > this.end || endColumnIsGapped)
1892 ListIterator<SequenceFeature> it = result.listIterator();
1893 while (it.hasNext())
1895 SequenceFeature sf = it.next();
1896 int sfBegin = sf.getBegin();
1897 int sfEnd = sf.getEnd();
1898 int featureStartColumn = findIndex(sfBegin);
1899 if (featureStartColumn > toColumn)
1903 else if (featureStartColumn < fromColumn)
1905 int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1907 if (featureEndColumn < fromColumn)
1911 else if (featureEndColumn > toColumn && sf.isContactFeature())
1914 * remove an enclosing feature if it is a contact feature
1926 * Invalidates any stale cursors (forcing recalculation) by incrementing the
1927 * token that has to match the one presented by the cursor
1930 public void sequenceChanged()
1939 public int replace(char c1, char c2)
1946 synchronized (sequence)
1948 for (int c = 0; c < sequence.length; c++)
1950 if (sequence[c] == c1)