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 AlignmentAnnotations but inherits
190 * any existing dataset sequence reference. If non exists, everything is
194 * if seq is a dataset sequence, behaves like a plain old copy
197 public Sequence(SequenceI seq)
199 this(seq, seq.getAnnotation());
203 * Create a new sequence object with new features, DBRefEntries, and PDBIds
204 * but inherits any existing dataset sequence reference, and duplicate of any
205 * annotation that is present in the given annotation array.
208 * the sequence to be copied
209 * @param alAnnotation
210 * an array of annotation including some associated with seq
212 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
214 initSeqFrom(seq, alAnnotation);
219 * does the heavy lifting when cloning a dataset sequence, or coping data from
220 * dataset to a new derived sequence.
223 * - source of attributes.
224 * @param alAnnotation
225 * - alignment annotation present on seq that should be copied onto
228 protected void initSeqFrom(SequenceI seq,
229 AlignmentAnnotation[] alAnnotation)
232 char[] oseq = seq.getSequence();
233 initSeqAndName(seq.getName(), Arrays.copyOf(oseq, oseq.length),
237 description = seq.getDescription();
238 sourceDBRef = seq.getSourceDBRef() == null ? null : new DBRefEntry(
239 seq.getSourceDBRef());
240 if (seq != datasetSequence)
242 setDatasetSequence(seq.getDatasetSequence());
244 if (datasetSequence == null && seq.getDBRefs() != null)
246 // only copy DBRefs and seqfeatures if we really are a dataset sequence
247 DBRefEntry[] dbr = seq.getDBRefs();
248 for (int i = 0; i < dbr.length; i++)
250 addDBRef(new DBRefEntry(dbr[i]));
252 if (seq.getSequenceFeatures() != null)
254 SequenceFeature[] sf = seq.getSequenceFeatures();
255 for (int i = 0; i < sf.length; i++)
257 addSequenceFeature(new SequenceFeature(sf[i]));
261 if (seq.getAnnotation() != null)
263 AlignmentAnnotation[] sqann = seq.getAnnotation();
264 for (int i = 0; i < sqann.length; i++)
266 if (sqann[i] == null)
270 boolean found = (alAnnotation == null);
273 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
275 found = (alAnnotation[apos] == sqann[i]);
280 // only copy the given annotation
281 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
282 addAlignmentAnnotation(newann);
286 if (seq.getAllPDBEntries() != null)
288 Vector<PDBEntry> ids = seq.getAllPDBEntries();
289 for (PDBEntry pdb : ids)
291 this.addPDBId(new PDBEntry(pdb));
298 public void setSequenceFeatures(SequenceFeature[] features)
300 if (datasetSequence == null)
302 sequenceFeatures = features;
306 if (datasetSequence.getSequenceFeatures() != features
307 && datasetSequence.getSequenceFeatures() != null
308 && datasetSequence.getSequenceFeatures().length > 0)
311 .println("Warning: JAL-2046 side effect ? Possible implementation error: overwriting dataset sequence features by setting sequence features on alignment");
313 datasetSequence.setSequenceFeatures(features);
318 public synchronized void addSequenceFeature(SequenceFeature sf)
320 if (sequenceFeatures==null && datasetSequence != null)
322 datasetSequence.addSequenceFeature(sf);
325 if (sequenceFeatures == null)
327 sequenceFeatures = new SequenceFeature[0];
330 for (int i = 0; i < sequenceFeatures.length; i++)
332 if (sequenceFeatures[i].equals(sf))
338 SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
339 System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
340 temp[sequenceFeatures.length] = sf;
342 sequenceFeatures = temp;
346 public void deleteFeature(SequenceFeature sf)
348 if (sequenceFeatures == null)
350 if (datasetSequence!=null) {
351 datasetSequence.deleteFeature(sf);
357 for (index = 0; index < sequenceFeatures.length; index++)
359 if (sequenceFeatures[index].equals(sf))
365 if (index == sequenceFeatures.length)
370 int sfLength = sequenceFeatures.length;
373 sequenceFeatures = null;
377 SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
378 System.arraycopy(sequenceFeatures, 0, temp, 0, index);
380 if (index < sfLength)
382 System.arraycopy(sequenceFeatures, index + 1, temp, index,
383 sequenceFeatures.length - index - 1);
386 sequenceFeatures = temp;
391 * Returns the sequence features (if any), looking first on the sequence, then
392 * on its dataset sequence, and so on until a non-null value is found (or
393 * none). This supports retrieval of sequence features stored on the sequence
394 * (as in the applet) or on the dataset sequence (as in the Desktop version).
399 public SequenceFeature[] getSequenceFeatures()
401 SequenceFeature[] features = sequenceFeatures;
403 SequenceI seq = this;
404 int count = 0; // failsafe against loop in sequence.datasetsequence...
405 while (features == null && seq.getDatasetSequence() != null
408 seq = seq.getDatasetSequence();
409 features = ((Sequence) seq).sequenceFeatures;
415 public void addPDBId(PDBEntry entry)
419 pdbIds = new Vector<PDBEntry>();
421 if (pdbIds.contains(entry))
423 updatePDBEntry(pdbIds.get(pdbIds.indexOf(entry)), entry);
427 pdbIds.addElement(entry);
431 private static void updatePDBEntry(PDBEntry oldEntry, PDBEntry newEntry)
433 if (newEntry.getFile() != null)
435 oldEntry.setFile(newEntry.getFile());
446 public void setPDBId(Vector<PDBEntry> id)
454 * @return DOCUMENT ME!
457 public Vector<PDBEntry> getAllPDBEntries()
459 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
465 * @return DOCUMENT ME!
468 public String getDisplayId(boolean jvsuffix)
470 StringBuffer result = new StringBuffer(name);
473 result.append("/" + start + "-" + end);
476 return result.toString();
486 public void setName(String name)
495 * @return DOCUMENT ME!
498 public String getName()
510 public void setStart(int start)
518 * @return DOCUMENT ME!
521 public int getStart()
533 public void setEnd(int end)
541 * @return DOCUMENT ME!
552 * @return DOCUMENT ME!
555 public int getLength()
557 return this.sequence.length;
567 public void setSequence(String seq)
569 this.sequence = seq.toCharArray();
574 public String getSequenceAsString()
576 return new String(sequence);
580 public String getSequenceAsString(int start, int end)
582 return new String(getSequence(start, end));
586 public char[] getSequence()
594 * @see jalview.datamodel.SequenceI#getSequence(int, int)
597 public char[] getSequence(int start, int end)
603 // JBPNote - left to user to pad the result here (TODO:Decide on this
605 if (start >= sequence.length)
610 if (end >= sequence.length)
612 end = sequence.length;
615 char[] reply = new char[end - start];
616 System.arraycopy(sequence, start, reply, 0, end - start);
622 public SequenceI getSubSequence(int start, int end)
628 char[] seq = getSequence(start, end);
633 int nstart = findPosition(start);
634 int nend = findPosition(end) - 1;
635 // JBPNote - this is an incomplete copy.
636 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
637 nseq.setDescription(description);
638 if (datasetSequence != null)
640 nseq.setDatasetSequence(datasetSequence);
644 nseq.setDatasetSequence(this);
650 * Returns the character of the aligned sequence at the given position (base
651 * zero), or space if the position is not within the sequence's bounds
656 public char getCharAt(int i)
658 if (i >= 0 && i < sequence.length)
675 public void setDescription(String desc)
677 this.description = desc;
683 * @return DOCUMENT ME!
686 public String getDescription()
688 return this.description;
694 * @see jalview.datamodel.SequenceI#findIndex(int)
697 public int findIndex(int pos)
699 // returns the alignment position for a residue
702 // Rely on end being at least as long as the length of the sequence.
703 while ((i < sequence.length) && (j <= end) && (j <= pos))
705 if (!jalview.util.Comparison.isGap(sequence[i]))
713 if ((j == end) && (j < pos))
724 public int findPosition(int i)
728 int seqlen = sequence.length;
729 while ((j < i) && (j < seqlen))
731 if (!jalview.util.Comparison.isGap(sequence[j]))
743 * Returns an int array where indices correspond to each residue in the
744 * sequence and the element value gives its position in the alignment
746 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
747 * residues in SequenceI object
750 public int[] gapMap()
752 String seq = jalview.analysis.AlignSeq.extractGaps(
753 jalview.util.Comparison.GapChars, new String(sequence));
754 int[] map = new int[seq.length()];
758 while (j < sequence.length)
760 if (!jalview.util.Comparison.isGap(sequence[j]))
772 public int[] findPositionMap()
774 int map[] = new int[sequence.length];
777 int seqlen = sequence.length;
781 if (!jalview.util.Comparison.isGap(sequence[j]))
792 public List<int[]> getInsertions()
794 ArrayList<int[]> map = new ArrayList<int[]>();
795 int lastj = -1, j = 0;
797 int seqlen = sequence.length;
800 if (jalview.util.Comparison.isGap(sequence[j]))
811 map.add(new int[] { lastj, j - 1 });
819 map.add(new int[] { lastj, j - 1 });
826 public void deleteChars(int i, int j)
828 int newstart = start, newend = end;
829 if (i >= sequence.length || i < 0)
834 char[] tmp = StringUtils.deleteChars(sequence, i, j);
835 boolean createNewDs = false;
836 // TODO: take a (second look) at the dataset creation validation method for
837 // the very large sequence case
838 int eindex = -1, sindex = -1;
839 boolean ecalc = false, scalc = false;
840 for (int s = i; s < j; s++)
842 if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
852 sindex = findIndex(start) - 1;
857 // delete characters including start of sequence
858 newstart = findPosition(j);
859 break; // don't need to search for any more residue characters.
863 // delete characters after start.
866 eindex = findIndex(end) - 1;
871 // delete characters at end of sequence
872 newend = findPosition(i - 1);
873 break; // don't need to search for any more residue characters.
878 newend--; // decrease end position by one for the deleted residue
879 // and search further
885 // deletion occured in the middle of the sequence
886 if (createNewDs && this.datasetSequence != null)
888 // construct a new sequence
889 Sequence ds = new Sequence(datasetSequence);
890 // TODO: remove any non-inheritable properties ?
891 // TODO: create a sequence mapping (since there is a relation here ?)
892 ds.deleteChars(i, j);
893 datasetSequence = ds;
901 public void insertCharAt(int i, int length, char c)
903 char[] tmp = new char[sequence.length + length];
905 if (i >= sequence.length)
907 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
912 System.arraycopy(sequence, 0, tmp, 0, i);
922 if (i < sequence.length)
924 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
931 public void insertCharAt(int i, char c)
933 insertCharAt(i, 1, c);
937 public String getVamsasId()
943 public void setVamsasId(String id)
949 public void setDBRefs(DBRefEntry[] dbref)
955 public DBRefEntry[] getDBRefs()
957 if (dbrefs == null && datasetSequence != null
958 && this != datasetSequence)
960 return datasetSequence.getDBRefs();
966 public void addDBRef(DBRefEntry entry)
968 // TODO add to dataset sequence instead if there is one?
971 dbrefs = new DBRefEntry[0];
974 for (DBRefEntryI dbr : dbrefs)
976 if (dbr.updateFrom(entry))
979 * found a dbref that either matched, or could be
980 * updated from, the new entry - no need to add it
987 * extend the array to make room for one more
989 // TODO use an ArrayList instead
990 int j = dbrefs.length;
991 DBRefEntry[] temp = new DBRefEntry[j + 1];
992 System.arraycopy(dbrefs, 0, temp, 0, j);
993 temp[temp.length - 1] = entry;
999 public void setDatasetSequence(SequenceI seq)
1001 // TODO check for circular reference before setting?
1002 datasetSequence = seq;
1006 public SequenceI getDatasetSequence()
1008 return datasetSequence;
1012 public AlignmentAnnotation[] getAnnotation()
1014 return annotation == null ? null : annotation
1015 .toArray(new AlignmentAnnotation[annotation.size()]);
1019 public boolean hasAnnotation(AlignmentAnnotation ann)
1021 return annotation == null ? false : annotation.contains(ann);
1025 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1027 if (this.annotation == null)
1029 this.annotation = new Vector<AlignmentAnnotation>();
1031 if (!this.annotation.contains(annotation))
1033 this.annotation.addElement(annotation);
1035 annotation.setSequenceRef(this);
1039 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1041 if (this.annotation != null)
1043 this.annotation.removeElement(annotation);
1044 if (this.annotation.size() == 0)
1046 this.annotation = null;
1052 * test if this is a valid candidate for another sequence's dataset sequence.
1055 private boolean isValidDatasetSequence()
1057 if (datasetSequence != null)
1061 for (int i = 0; i < sequence.length; i++)
1063 if (jalview.util.Comparison.isGap(sequence[i]))
1072 public SequenceI deriveSequence()
1075 if (datasetSequence == null)
1077 if (isValidDatasetSequence())
1079 // Use this as dataset sequence
1080 seq = new Sequence(getName(), "", 1, -1);
1081 seq.setDatasetSequence(this);
1082 seq.initSeqFrom(this, getAnnotation());
1087 // Create a new, valid dataset sequence
1088 createDatasetSequence();
1091 return new Sequence(this);
1094 private boolean _isNa;
1096 private long _seqhash = 0;
1099 public boolean isProtein()
1101 if (datasetSequence != null)
1103 return datasetSequence.isProtein();
1105 if (_seqhash != sequence.hashCode())
1107 _seqhash = sequence.hashCode();
1108 _isNa=jalview.util.Comparison.isNucleotide(new SequenceI[] { this });
1116 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1119 public SequenceI createDatasetSequence()
1121 if (datasetSequence == null)
1123 Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1124 jalview.util.Comparison.GapChars, getSequenceAsString()),
1125 getStart(), getEnd());
1127 datasetSequence = dsseq;
1129 dsseq.setDescription(description);
1130 // move features and database references onto dataset sequence
1131 dsseq.sequenceFeatures = sequenceFeatures;
1132 sequenceFeatures=null;
1133 dsseq.dbrefs = dbrefs;
1135 // TODO: search and replace any references to this sequence with
1136 // references to the dataset sequence in Mappings on dbref
1137 dsseq.pdbIds = pdbIds;
1139 datasetSequence.updatePDBIds();
1140 if (annotation != null)
1142 // annotation is cloned rather than moved, to preserve what's currently
1144 for (AlignmentAnnotation aa : annotation)
1146 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1147 _aa.sequenceRef = datasetSequence;
1148 _aa.adjustForAlignment(); // uses annotation's own record of
1149 // sequence-column mapping
1150 datasetSequence.addAlignmentAnnotation(_aa);
1154 return datasetSequence;
1161 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1165 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1167 if (annotation != null)
1169 annotation.removeAllElements();
1171 if (annotations != null)
1173 for (int i = 0; i < annotations.length; i++)
1175 if (annotations[i] != null)
1177 addAlignmentAnnotation(annotations[i]);
1184 public AlignmentAnnotation[] getAnnotation(String label)
1186 if (annotation == null || annotation.size() == 0)
1191 Vector subset = new Vector();
1192 Enumeration e = annotation.elements();
1193 while (e.hasMoreElements())
1195 AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1196 if (ann.label != null && ann.label.equals(label))
1198 subset.addElement(ann);
1201 if (subset.size() == 0)
1205 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1207 e = subset.elements();
1208 while (e.hasMoreElements())
1210 anns[i++] = (AlignmentAnnotation) e.nextElement();
1212 subset.removeAllElements();
1217 public boolean updatePDBIds()
1219 if (datasetSequence != null)
1221 // TODO: could merge DBRefs
1222 return datasetSequence.updatePDBIds();
1224 if (dbrefs == null || dbrefs.length == 0)
1228 Vector newpdb = new Vector();
1229 for (int i = 0; i < dbrefs.length; i++)
1231 if (DBRefSource.PDB.equals(dbrefs[i].getSource()))
1233 PDBEntry pdbe = new PDBEntry();
1234 pdbe.setId(dbrefs[i].getAccessionId());
1235 if (pdbIds == null || pdbIds.size() == 0)
1237 newpdb.addElement(pdbe);
1241 Enumeration en = pdbIds.elements();
1242 boolean matched = false;
1243 while (!matched && en.hasMoreElements())
1245 PDBEntry anentry = (PDBEntry) en.nextElement();
1246 if (anentry.getId().equals(pdbe.getId()))
1253 newpdb.addElement(pdbe);
1258 if (newpdb.size() > 0)
1260 Enumeration en = newpdb.elements();
1261 while (en.hasMoreElements())
1263 addPDBId((PDBEntry) en.nextElement());
1271 public void transferAnnotation(SequenceI entry, Mapping mp)
1273 if (datasetSequence != null)
1275 datasetSequence.transferAnnotation(entry, mp);
1278 if (entry.getDatasetSequence() != null)
1280 transferAnnotation(entry.getDatasetSequence(), mp);
1283 // transfer any new features from entry onto sequence
1284 if (entry.getSequenceFeatures() != null)
1287 SequenceFeature[] sfs = entry.getSequenceFeatures();
1288 for (int si = 0; si < sfs.length; si++)
1290 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1291 : new SequenceFeature[] { new SequenceFeature(sfs[si]) };
1292 if (sf != null && sf.length > 0)
1294 for (int sfi = 0; sfi < sf.length; sfi++)
1296 addSequenceFeature(sf[sfi]);
1302 // transfer PDB entries
1303 if (entry.getAllPDBEntries() != null)
1305 Enumeration e = entry.getAllPDBEntries().elements();
1306 while (e.hasMoreElements())
1308 PDBEntry pdb = (PDBEntry) e.nextElement();
1312 // transfer database references
1313 DBRefEntry[] entryRefs = entry.getDBRefs();
1314 if (entryRefs != null)
1316 for (int r = 0; r < entryRefs.length; r++)
1318 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1319 if (newref.getMap() != null && mp != null)
1321 // remap ref using our local mapping
1323 // we also assume all version string setting is done by dbSourceProxy
1325 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1326 * newref.setSource(dbSource); }
1334 * @return The index (zero-based) on this sequence in the MSA. It returns
1335 * {@code -1} if this information is not available.
1338 public int getIndex()
1344 * Defines the position of this sequence in the MSA. Use the value {@code -1}
1345 * if this information is undefined.
1348 * position for this sequence. This value is zero-based (zero for
1349 * this first sequence)
1352 public void setIndex(int value)
1358 public void setRNA(RNA r)
1370 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1373 List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1374 if (this.annotation != null)
1376 for (AlignmentAnnotation ann : annotation)
1378 if (ann.calcId != null && ann.calcId.equals(calcId)
1379 && ann.label != null && ann.label.equals(label))
1389 public String toString()
1391 return getDisplayId(false);
1395 public PDBEntry getPDBEntry(String pdbIdStr)
1397 if (getDatasetSequence() == null
1398 || getDatasetSequence().getAllPDBEntries() == null)
1402 List<PDBEntry> entries = getDatasetSequence().getAllPDBEntries();
1403 for (PDBEntry entry : entries)
1405 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1414 public void setSourceDBRef(DBRefEntryI dbRef)
1416 this.sourceDBRef = dbRef;
1420 public DBRefEntryI getSourceDBRef()
1422 return this.sourceDBRef;