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.util.StringUtils;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Enumeration;
30 import java.util.List;
31 import java.util.Vector;
33 import fr.orsay.lri.varna.models.rna.RNA;
37 * Implements the SequenceI interface for a char[] based sequence object.
42 public class Sequence extends ASequence implements SequenceI
44 SequenceI datasetSequence;
48 private char[] sequence;
56 Vector<PDBEntry> pdbIds;
60 DBRefEntryI sourceDBRef;
67 * This annotation is displayed below the alignment but the positions are tied
68 * to the residues of this sequence
70 * TODO: change to List<>
72 Vector<AlignmentAnnotation> annotation;
75 * The index of the sequence in a MSA
79 /** array of sequence features - may not be null for a valid sequence object */
80 public SequenceFeature[] sequenceFeatures;
83 * Creates a new Sequence object.
88 * string to form a possibly gapped sequence out of
90 * first position of non-gap residue in the sequence
92 * last position of ungapped residues (nearly always only used for
95 public Sequence(String name, String sequence, int start, int end)
97 initSeqAndName(name, sequence.toCharArray(), start, end);
100 public Sequence(String name, char[] sequence, int start, int end)
102 initSeqAndName(name, sequence, start, end);
106 * Stage 1 constructor - assign name, sequence, and set start and end fields.
107 * start and end are updated values from name2 if it ends with /start-end
114 protected void initSeqAndName(String name2, char[] sequence2, int start2,
118 this.sequence = sequence2;
125 com.stevesoft.pat.Regex limitrx = new com.stevesoft.pat.Regex(
126 "[/][0-9]{1,}[-][0-9]{1,}$");
128 com.stevesoft.pat.Regex endrx = new com.stevesoft.pat.Regex("[0-9]{1,}$");
135 .println("POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
138 // Does sequence have the /start-end signature?
139 if (limitrx.search(name))
141 name = limitrx.left();
142 endrx.search(limitrx.stringMatched());
143 setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
144 endrx.matchedFrom() - 1)));
145 setEnd(Integer.parseInt(endrx.stringMatched()));
149 void checkValidRange()
152 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
155 for (int j = 0; j < sequence.length; j++)
157 if (!jalview.util.Comparison.isGap(sequence[j]))
176 * Creates a new Sequence object.
183 public Sequence(String name, String sequence)
185 this(name, sequence, 1, -1);
189 * Creates a new Sequence object with new features, DBRefEntries,
190 * AlignmentAnnotations, and PDBIds but inherits any existing dataset sequence
196 public Sequence(SequenceI seq)
198 this(seq, seq.getAnnotation());
202 * Create a new sequence object with new features, DBRefEntries, and PDBIds
203 * but inherits any existing dataset sequence reference, and duplicate of any
204 * annotation that is present in the given annotation array.
207 * the sequence to be copied
208 * @param alAnnotation
209 * an array of annotation including some associated with seq
211 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
213 initSeqFrom(seq, alAnnotation);
217 protected void initSeqFrom(SequenceI seq,
218 AlignmentAnnotation[] alAnnotation)
221 char[] oseq = seq.getSequence();
222 initSeqAndName(seq.getName(), Arrays.copyOf(oseq, oseq.length),
226 description = seq.getDescription();
227 sourceDBRef = seq.getSourceDBRef() == null ? null : new DBRefEntry(
228 seq.getSourceDBRef());
229 if (seq.getSequenceFeatures() != null)
231 SequenceFeature[] sf = seq.getSequenceFeatures();
232 for (int i = 0; i < sf.length; i++)
234 addSequenceFeature(new SequenceFeature(sf[i]));
237 setDatasetSequence(seq.getDatasetSequence());
238 if (datasetSequence == null && seq.getDBRefs() != null)
240 // only copy DBRefs if we really are a dataset sequence
241 DBRefEntry[] dbr = seq.getDBRefs();
242 for (int i = 0; i < dbr.length; i++)
244 addDBRef(new DBRefEntry(dbr[i]));
247 if (seq.getAnnotation() != null)
249 AlignmentAnnotation[] sqann = seq.getAnnotation();
250 for (int i = 0; i < sqann.length; i++)
252 if (sqann[i] == null)
256 boolean found = (alAnnotation == null);
259 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
261 found = (alAnnotation[apos] == sqann[i]);
266 // only copy the given annotation
267 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
268 addAlignmentAnnotation(newann);
272 if (seq.getAllPDBEntries() != null)
274 Vector<PDBEntry> ids = seq.getAllPDBEntries();
275 for (PDBEntry pdb : ids)
277 this.addPDBId(new PDBEntry(pdb));
289 public void setSequenceFeatures(SequenceFeature[] features)
291 sequenceFeatures = features;
295 public synchronized void addSequenceFeature(SequenceFeature sf)
297 // TODO add to dataset sequence instead if there is one?
298 if (sequenceFeatures == null)
300 sequenceFeatures = new SequenceFeature[0];
303 for (int i = 0; i < sequenceFeatures.length; i++)
305 if (sequenceFeatures[i].equals(sf))
311 SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
312 System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
313 temp[sequenceFeatures.length] = sf;
315 sequenceFeatures = temp;
319 public void deleteFeature(SequenceFeature sf)
321 if (sequenceFeatures == null)
327 for (index = 0; index < sequenceFeatures.length; index++)
329 if (sequenceFeatures[index].equals(sf))
335 if (index == sequenceFeatures.length)
340 int sfLength = sequenceFeatures.length;
343 sequenceFeatures = null;
347 SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
348 System.arraycopy(sequenceFeatures, 0, temp, 0, index);
350 if (index < sfLength)
352 System.arraycopy(sequenceFeatures, index + 1, temp, index,
353 sequenceFeatures.length - index - 1);
356 sequenceFeatures = temp;
361 * Returns the sequence features (if any), looking first on the sequence, then
362 * on its dataset sequence, and so on until a non-null value is found (or
363 * none). This supports retrieval of sequence features stored on the sequence
364 * (as in the applet) or on the dataset sequence (as in the Desktop version).
369 public SequenceFeature[] getSequenceFeatures()
371 SequenceFeature[] features = sequenceFeatures;
373 SequenceI seq = this;
374 int count = 0; // failsafe against loop in sequence.datasetsequence...
375 while (features == null && seq.getDatasetSequence() != null
378 seq = seq.getDatasetSequence();
379 features = ((Sequence) seq).sequenceFeatures;
385 public void addPDBId(PDBEntry entry)
389 pdbIds = new Vector<PDBEntry>();
391 if (pdbIds.contains(entry))
393 updatePDBEntry(pdbIds.get(pdbIds.indexOf(entry)), entry);
397 pdbIds.addElement(entry);
401 private static void updatePDBEntry(PDBEntry oldEntry, PDBEntry newEntry)
403 if (newEntry.getFile() != null)
405 oldEntry.setFile(newEntry.getFile());
416 public void setPDBId(Vector<PDBEntry> id)
424 * @return DOCUMENT ME!
427 public Vector<PDBEntry> getAllPDBEntries()
429 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
435 * @return DOCUMENT ME!
438 public String getDisplayId(boolean jvsuffix)
440 StringBuffer result = new StringBuffer(name);
443 result.append("/" + start + "-" + end);
446 return result.toString();
456 public void setName(String name)
465 * @return DOCUMENT ME!
468 public String getName()
480 public void setStart(int start)
488 * @return DOCUMENT ME!
491 public int getStart()
503 public void setEnd(int end)
511 * @return DOCUMENT ME!
522 * @return DOCUMENT ME!
525 public int getLength()
527 return this.sequence.length;
537 public void setSequence(String seq)
539 this.sequence = seq.toCharArray();
544 public String getSequenceAsString()
546 return new String(sequence);
550 public String getSequenceAsString(int start, int end)
552 return new String(getSequence(start, end));
556 public char[] getSequence()
564 * @see jalview.datamodel.SequenceI#getSequence(int, int)
567 public char[] getSequence(int start, int end)
573 // JBPNote - left to user to pad the result here (TODO:Decide on this
575 if (start >= sequence.length)
580 if (end >= sequence.length)
582 end = sequence.length;
585 char[] reply = new char[end - start];
586 System.arraycopy(sequence, start, reply, 0, end - start);
592 public SequenceI getSubSequence(int start, int end)
598 char[] seq = getSequence(start, end);
603 int nstart = findPosition(start);
604 int nend = findPosition(end) - 1;
605 // JBPNote - this is an incomplete copy.
606 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
607 nseq.setDescription(description);
608 if (datasetSequence != null)
610 nseq.setDatasetSequence(datasetSequence);
614 nseq.setDatasetSequence(this);
620 * Returns the character of the aligned sequence at the given position (base
621 * zero), or space if the position is not within the sequence's bounds
626 public char getCharAt(int i)
628 if (i >= 0 && i < sequence.length)
645 public void setDescription(String desc)
647 this.description = desc;
653 * @return DOCUMENT ME!
656 public String getDescription()
658 return this.description;
664 * @see jalview.datamodel.SequenceI#findIndex(int)
667 public int findIndex(int pos)
669 // returns the alignment position for a residue
672 // Rely on end being at least as long as the length of the sequence.
673 while ((i < sequence.length) && (j <= end) && (j <= pos))
675 if (!jalview.util.Comparison.isGap(sequence[i]))
683 if ((j == end) && (j < pos))
694 public int findPosition(int i)
698 int seqlen = sequence.length;
699 while ((j < i) && (j < seqlen))
701 if (!jalview.util.Comparison.isGap(sequence[j]))
713 * Returns an int array where indices correspond to each residue in the
714 * sequence and the element value gives its position in the alignment
716 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
717 * residues in SequenceI object
720 public int[] gapMap()
722 String seq = jalview.analysis.AlignSeq.extractGaps(
723 jalview.util.Comparison.GapChars, new String(sequence));
724 int[] map = new int[seq.length()];
728 while (j < sequence.length)
730 if (!jalview.util.Comparison.isGap(sequence[j]))
742 public int[] findPositionMap()
744 int map[] = new int[sequence.length];
747 int seqlen = sequence.length;
751 if (!jalview.util.Comparison.isGap(sequence[j]))
762 public List<int[]> getInsertions()
764 ArrayList<int[]> map = new ArrayList<int[]>();
765 int lastj = -1, j = 0;
767 int seqlen = sequence.length;
770 if (jalview.util.Comparison.isGap(sequence[j]))
781 map.add(new int[] { lastj, j - 1 });
789 map.add(new int[] { lastj, j - 1 });
796 public void deleteChars(int i, int j)
798 int newstart = start, newend = end;
799 if (i >= sequence.length || i < 0)
804 char[] tmp = StringUtils.deleteChars(sequence, i, j);
805 boolean createNewDs = false;
806 // TODO: take a (second look) at the dataset creation validation method for
807 // the very large sequence case
808 int eindex = -1, sindex = -1;
809 boolean ecalc = false, scalc = false;
810 for (int s = i; s < j; s++)
812 if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
822 sindex = findIndex(start) - 1;
827 // delete characters including start of sequence
828 newstart = findPosition(j);
829 break; // don't need to search for any more residue characters.
833 // delete characters after start.
836 eindex = findIndex(end) - 1;
841 // delete characters at end of sequence
842 newend = findPosition(i - 1);
843 break; // don't need to search for any more residue characters.
848 newend--; // decrease end position by one for the deleted residue
849 // and search further
855 // deletion occured in the middle of the sequence
856 if (createNewDs && this.datasetSequence != null)
858 // construct a new sequence
859 Sequence ds = new Sequence(datasetSequence);
860 // TODO: remove any non-inheritable properties ?
861 // TODO: create a sequence mapping (since there is a relation here ?)
862 ds.deleteChars(i, j);
863 datasetSequence = ds;
871 public void insertCharAt(int i, int length, char c)
873 char[] tmp = new char[sequence.length + length];
875 if (i >= sequence.length)
877 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
882 System.arraycopy(sequence, 0, tmp, 0, i);
892 if (i < sequence.length)
894 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
901 public void insertCharAt(int i, char c)
903 insertCharAt(i, 1, c);
907 public String getVamsasId()
913 public void setVamsasId(String id)
919 public void setDBRefs(DBRefEntry[] dbref)
925 public DBRefEntry[] getDBRefs()
927 if (dbrefs == null && datasetSequence != null
928 && this != datasetSequence)
930 return datasetSequence.getDBRefs();
936 public void addDBRef(DBRefEntry entry)
938 // TODO add to dataset sequence instead if there is one?
941 dbrefs = new DBRefEntry[0];
944 int i, iSize = dbrefs.length;
946 for (i = 0; i < iSize; i++)
948 if (dbrefs[i].equalRef(entry))
950 if (entry.getMap() != null)
952 if (dbrefs[i].getMap() == null)
954 // overwrite with 'superior' entry that contains a mapping.
962 DBRefEntry[] temp = new DBRefEntry[iSize + 1];
963 System.arraycopy(dbrefs, 0, temp, 0, iSize);
964 temp[temp.length - 1] = entry;
970 public void setDatasetSequence(SequenceI seq)
972 // TODO check for circular reference before setting?
973 datasetSequence = seq;
977 public SequenceI getDatasetSequence()
979 return datasetSequence;
983 public AlignmentAnnotation[] getAnnotation()
985 return annotation == null ? null : annotation
986 .toArray(new AlignmentAnnotation[annotation.size()]);
990 public boolean hasAnnotation(AlignmentAnnotation ann)
992 return annotation == null ? false : annotation.contains(ann);
996 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
998 if (this.annotation == null)
1000 this.annotation = new Vector<AlignmentAnnotation>();
1002 if (!this.annotation.contains(annotation))
1004 this.annotation.addElement(annotation);
1006 annotation.setSequenceRef(this);
1010 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1012 if (this.annotation != null)
1014 this.annotation.removeElement(annotation);
1015 if (this.annotation.size() == 0)
1017 this.annotation = null;
1023 * test if this is a valid candidate for another sequence's dataset sequence.
1026 private boolean isValidDatasetSequence()
1028 if (datasetSequence != null)
1032 for (int i = 0; i < sequence.length; i++)
1034 if (jalview.util.Comparison.isGap(sequence[i]))
1043 public SequenceI deriveSequence()
1045 SequenceI seq = new Sequence(this);
1046 if (datasetSequence != null)
1048 // duplicate current sequence with same dataset
1049 seq.setDatasetSequence(datasetSequence);
1053 if (isValidDatasetSequence())
1055 // Use this as dataset sequence
1056 seq.setDatasetSequence(this);
1060 // Create a new, valid dataset sequence
1062 ds.setSequence(AlignSeq.extractGaps(
1063 jalview.util.Comparison.GapChars, new String(sequence)));
1064 setDatasetSequence(ds);
1065 ds.setSequenceFeatures(getSequenceFeatures());
1066 seq = this; // and return this sequence as the derived sequence.
1075 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1078 public SequenceI createDatasetSequence()
1080 if (datasetSequence == null)
1082 Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1083 jalview.util.Comparison.GapChars, getSequenceAsString()),
1084 getStart(), getEnd());
1086 datasetSequence = dsseq;
1088 dsseq.setDescription(description);
1089 // move features and database references onto dataset sequence
1090 dsseq.sequenceFeatures = sequenceFeatures;
1091 sequenceFeatures=null;
1092 dsseq.dbrefs = dbrefs;
1094 // TODO: search and replace any references to this sequence with
1095 // references to the dataset sequence in Mappings on dbref
1096 dsseq.pdbIds = pdbIds;
1098 datasetSequence.updatePDBIds();
1099 if (annotation != null)
1101 // annotation is cloned rather than moved, to preserve what's currently
1103 for (AlignmentAnnotation aa : annotation)
1105 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1106 _aa.sequenceRef = datasetSequence;
1107 _aa.adjustForAlignment(); // uses annotation's own record of
1108 // sequence-column mapping
1109 datasetSequence.addAlignmentAnnotation(_aa);
1113 return datasetSequence;
1120 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1124 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1126 if (annotation != null)
1128 annotation.removeAllElements();
1130 if (annotations != null)
1132 for (int i = 0; i < annotations.length; i++)
1134 if (annotations[i] != null)
1136 addAlignmentAnnotation(annotations[i]);
1143 public AlignmentAnnotation[] getAnnotation(String label)
1145 if (annotation == null || annotation.size() == 0)
1150 Vector subset = new Vector();
1151 Enumeration e = annotation.elements();
1152 while (e.hasMoreElements())
1154 AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1155 if (ann.label != null && ann.label.equals(label))
1157 subset.addElement(ann);
1160 if (subset.size() == 0)
1164 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1166 e = subset.elements();
1167 while (e.hasMoreElements())
1169 anns[i++] = (AlignmentAnnotation) e.nextElement();
1171 subset.removeAllElements();
1176 public boolean updatePDBIds()
1178 if (datasetSequence != null)
1180 // TODO: could merge DBRefs
1181 return datasetSequence.updatePDBIds();
1183 if (dbrefs == null || dbrefs.length == 0)
1187 Vector newpdb = new Vector();
1188 for (int i = 0; i < dbrefs.length; i++)
1190 if (DBRefSource.PDB.equals(dbrefs[i].getSource()))
1192 PDBEntry pdbe = new PDBEntry();
1193 pdbe.setId(dbrefs[i].getAccessionId());
1194 if (pdbIds == null || pdbIds.size() == 0)
1196 newpdb.addElement(pdbe);
1200 Enumeration en = pdbIds.elements();
1201 boolean matched = false;
1202 while (!matched && en.hasMoreElements())
1204 PDBEntry anentry = (PDBEntry) en.nextElement();
1205 if (anentry.getId().equals(pdbe.getId()))
1212 newpdb.addElement(pdbe);
1217 if (newpdb.size() > 0)
1219 Enumeration en = newpdb.elements();
1220 while (en.hasMoreElements())
1222 addPDBId((PDBEntry) en.nextElement());
1230 public void transferAnnotation(SequenceI entry, Mapping mp)
1232 if (datasetSequence != null)
1234 datasetSequence.transferAnnotation(entry, mp);
1237 if (entry.getDatasetSequence() != null)
1239 transferAnnotation(entry.getDatasetSequence(), mp);
1242 // transfer any new features from entry onto sequence
1243 if (entry.getSequenceFeatures() != null)
1246 SequenceFeature[] sfs = entry.getSequenceFeatures();
1247 for (int si = 0; si < sfs.length; si++)
1249 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1250 : new SequenceFeature[] { new SequenceFeature(sfs[si]) };
1251 if (sf != null && sf.length > 0)
1253 for (int sfi = 0; sfi < sf.length; sfi++)
1255 addSequenceFeature(sf[sfi]);
1261 // transfer PDB entries
1262 if (entry.getAllPDBEntries() != null)
1264 Enumeration e = entry.getAllPDBEntries().elements();
1265 while (e.hasMoreElements())
1267 PDBEntry pdb = (PDBEntry) e.nextElement();
1271 // transfer database references
1272 DBRefEntry[] entryRefs = entry.getDBRefs();
1273 if (entryRefs != null)
1275 for (int r = 0; r < entryRefs.length; r++)
1277 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1278 if (newref.getMap() != null && mp != null)
1280 // remap ref using our local mapping
1282 // we also assume all version string setting is done by dbSourceProxy
1284 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1285 * newref.setSource(dbSource); }
1293 * @return The index (zero-based) on this sequence in the MSA. It returns
1294 * {@code -1} if this information is not available.
1297 public int getIndex()
1303 * Defines the position of this sequence in the MSA. Use the value {@code -1}
1304 * if this information is undefined.
1307 * position for this sequence. This value is zero-based (zero for
1308 * this first sequence)
1311 public void setIndex(int value)
1317 public void setRNA(RNA r)
1329 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1332 List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1333 if (this.annotation != null)
1335 for (AlignmentAnnotation ann : annotation)
1337 if (ann.calcId != null && ann.calcId.equals(calcId)
1338 && ann.label != null && ann.label.equals(label))
1348 public String toString()
1350 return getDisplayId(false);
1354 public PDBEntry getPDBEntry(String pdbIdStr)
1356 if (getDatasetSequence() == null
1357 || getDatasetSequence().getAllPDBEntries() == null)
1361 List<PDBEntry> entries = getDatasetSequence().getAllPDBEntries();
1362 for (PDBEntry entry : entries)
1364 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1373 public void setSourceDBRef(DBRefEntryI dbRef)
1375 this.sourceDBRef = dbRef;
1379 public DBRefEntryI getSourceDBRef()
1381 return this.sourceDBRef;