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 "Warning: JAL-2046 side effect ? Possible implementation error: overwriting dataset sequence features by setting sequence features on alignment")
314 datasetSequence.setSequenceFeatures(features);
319 public synchronized void addSequenceFeature(SequenceFeature sf)
321 if (sequenceFeatures==null && datasetSequence != null)
323 datasetSequence.addSequenceFeature(sf);
326 if (sequenceFeatures == null)
328 sequenceFeatures = new SequenceFeature[0];
331 for (int i = 0; i < sequenceFeatures.length; i++)
333 if (sequenceFeatures[i].equals(sf))
339 SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
340 System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
341 temp[sequenceFeatures.length] = sf;
343 sequenceFeatures = temp;
347 public void deleteFeature(SequenceFeature sf)
349 if (sequenceFeatures == null)
351 if (datasetSequence!=null) {
352 datasetSequence.deleteFeature(sf);
358 for (index = 0; index < sequenceFeatures.length; index++)
360 if (sequenceFeatures[index].equals(sf))
366 if (index == sequenceFeatures.length)
371 int sfLength = sequenceFeatures.length;
374 sequenceFeatures = null;
378 SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
379 System.arraycopy(sequenceFeatures, 0, temp, 0, index);
381 if (index < sfLength)
383 System.arraycopy(sequenceFeatures, index + 1, temp, index,
384 sequenceFeatures.length - index - 1);
387 sequenceFeatures = temp;
392 * Returns the sequence features (if any), looking first on the sequence, then
393 * on its dataset sequence, and so on until a non-null value is found (or
394 * none). This supports retrieval of sequence features stored on the sequence
395 * (as in the applet) or on the dataset sequence (as in the Desktop version).
400 public SequenceFeature[] getSequenceFeatures()
402 SequenceFeature[] features = sequenceFeatures;
404 SequenceI seq = this;
405 int count = 0; // failsafe against loop in sequence.datasetsequence...
406 while (features == null && seq.getDatasetSequence() != null
409 seq = seq.getDatasetSequence();
410 features = ((Sequence) seq).sequenceFeatures;
416 public void addPDBId(PDBEntry entry)
420 pdbIds = new Vector<PDBEntry>();
422 if (pdbIds.contains(entry))
424 updatePDBEntry(pdbIds.get(pdbIds.indexOf(entry)), entry);
428 pdbIds.addElement(entry);
432 private static void updatePDBEntry(PDBEntry oldEntry, PDBEntry newEntry)
434 if (newEntry.getFile() != null)
436 oldEntry.setFile(newEntry.getFile());
447 public void setPDBId(Vector<PDBEntry> id)
455 * @return DOCUMENT ME!
458 public Vector<PDBEntry> getAllPDBEntries()
460 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
466 * @return DOCUMENT ME!
469 public String getDisplayId(boolean jvsuffix)
471 StringBuffer result = new StringBuffer(name);
474 result.append("/" + start + "-" + end);
477 return result.toString();
487 public void setName(String name)
496 * @return DOCUMENT ME!
499 public String getName()
511 public void setStart(int start)
519 * @return DOCUMENT ME!
522 public int getStart()
534 public void setEnd(int end)
542 * @return DOCUMENT ME!
553 * @return DOCUMENT ME!
556 public int getLength()
558 return this.sequence.length;
568 public void setSequence(String seq)
570 this.sequence = seq.toCharArray();
575 public String getSequenceAsString()
577 return new String(sequence);
581 public String getSequenceAsString(int start, int end)
583 return new String(getSequence(start, end));
587 public char[] getSequence()
595 * @see jalview.datamodel.SequenceI#getSequence(int, int)
598 public char[] getSequence(int start, int end)
604 // JBPNote - left to user to pad the result here (TODO:Decide on this
606 if (start >= sequence.length)
611 if (end >= sequence.length)
613 end = sequence.length;
616 char[] reply = new char[end - start];
617 System.arraycopy(sequence, start, reply, 0, end - start);
623 public SequenceI getSubSequence(int start, int end)
629 char[] seq = getSequence(start, end);
634 int nstart = findPosition(start);
635 int nend = findPosition(end) - 1;
636 // JBPNote - this is an incomplete copy.
637 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
638 nseq.setDescription(description);
639 if (datasetSequence != null)
641 nseq.setDatasetSequence(datasetSequence);
645 nseq.setDatasetSequence(this);
651 * Returns the character of the aligned sequence at the given position (base
652 * zero), or space if the position is not within the sequence's bounds
657 public char getCharAt(int i)
659 if (i >= 0 && i < sequence.length)
676 public void setDescription(String desc)
678 this.description = desc;
684 * @return DOCUMENT ME!
687 public String getDescription()
689 return this.description;
695 * @see jalview.datamodel.SequenceI#findIndex(int)
698 public int findIndex(int pos)
700 // returns the alignment position for a residue
703 // Rely on end being at least as long as the length of the sequence.
704 while ((i < sequence.length) && (j <= end) && (j <= pos))
706 if (!jalview.util.Comparison.isGap(sequence[i]))
714 if ((j == end) && (j < pos))
725 public int findPosition(int i)
729 int seqlen = sequence.length;
730 while ((j < i) && (j < seqlen))
732 if (!jalview.util.Comparison.isGap(sequence[j]))
744 * Returns an int array where indices correspond to each residue in the
745 * sequence and the element value gives its position in the alignment
747 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
748 * residues in SequenceI object
751 public int[] gapMap()
753 String seq = jalview.analysis.AlignSeq.extractGaps(
754 jalview.util.Comparison.GapChars, new String(sequence));
755 int[] map = new int[seq.length()];
759 while (j < sequence.length)
761 if (!jalview.util.Comparison.isGap(sequence[j]))
773 public int[] findPositionMap()
775 int map[] = new int[sequence.length];
778 int seqlen = sequence.length;
782 if (!jalview.util.Comparison.isGap(sequence[j]))
793 public List<int[]> getInsertions()
795 ArrayList<int[]> map = new ArrayList<int[]>();
796 int lastj = -1, j = 0;
798 int seqlen = sequence.length;
801 if (jalview.util.Comparison.isGap(sequence[j]))
812 map.add(new int[] { lastj, j - 1 });
820 map.add(new int[] { lastj, j - 1 });
827 public void deleteChars(int i, int j)
829 int newstart = start, newend = end;
830 if (i >= sequence.length || i < 0)
835 char[] tmp = StringUtils.deleteChars(sequence, i, j);
836 boolean createNewDs = false;
837 // TODO: take a (second look) at the dataset creation validation method for
838 // the very large sequence case
839 int eindex = -1, sindex = -1;
840 boolean ecalc = false, scalc = false;
841 for (int s = i; s < j; s++)
843 if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
853 sindex = findIndex(start) - 1;
858 // delete characters including start of sequence
859 newstart = findPosition(j);
860 break; // don't need to search for any more residue characters.
864 // delete characters after start.
867 eindex = findIndex(end) - 1;
872 // delete characters at end of sequence
873 newend = findPosition(i - 1);
874 break; // don't need to search for any more residue characters.
879 newend--; // decrease end position by one for the deleted residue
880 // and search further
886 // deletion occured in the middle of the sequence
887 if (createNewDs && this.datasetSequence != null)
889 // construct a new sequence
890 Sequence ds = new Sequence(datasetSequence);
891 // TODO: remove any non-inheritable properties ?
892 // TODO: create a sequence mapping (since there is a relation here ?)
893 ds.deleteChars(i, j);
894 datasetSequence = ds;
902 public void insertCharAt(int i, int length, char c)
904 char[] tmp = new char[sequence.length + length];
906 if (i >= sequence.length)
908 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
913 System.arraycopy(sequence, 0, tmp, 0, i);
923 if (i < sequence.length)
925 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
932 public void insertCharAt(int i, char c)
934 insertCharAt(i, 1, c);
938 public String getVamsasId()
944 public void setVamsasId(String id)
950 public void setDBRefs(DBRefEntry[] dbref)
956 public DBRefEntry[] getDBRefs()
958 if (dbrefs == null && datasetSequence != null
959 && this != datasetSequence)
961 return datasetSequence.getDBRefs();
967 public void addDBRef(DBRefEntry entry)
969 // TODO add to dataset sequence instead if there is one?
972 dbrefs = new DBRefEntry[0];
975 for (DBRefEntryI dbr : dbrefs)
977 if (dbr.updateFrom(entry))
980 * found a dbref that either matched, or could be
981 * updated from, the new entry - no need to add it
988 * extend the array to make room for one more
990 // TODO use an ArrayList instead
991 int j = dbrefs.length;
992 DBRefEntry[] temp = new DBRefEntry[j + 1];
993 System.arraycopy(dbrefs, 0, temp, 0, j);
994 temp[temp.length - 1] = entry;
1000 public void setDatasetSequence(SequenceI seq)
1002 // TODO check for circular reference before setting?
1003 datasetSequence = seq;
1007 public SequenceI getDatasetSequence()
1009 return datasetSequence;
1013 public AlignmentAnnotation[] getAnnotation()
1015 return annotation == null ? null : annotation
1016 .toArray(new AlignmentAnnotation[annotation.size()]);
1020 public boolean hasAnnotation(AlignmentAnnotation ann)
1022 return annotation == null ? false : annotation.contains(ann);
1026 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1028 if (this.annotation == null)
1030 this.annotation = new Vector<AlignmentAnnotation>();
1032 if (!this.annotation.contains(annotation))
1034 this.annotation.addElement(annotation);
1036 annotation.setSequenceRef(this);
1040 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1042 if (this.annotation != null)
1044 this.annotation.removeElement(annotation);
1045 if (this.annotation.size() == 0)
1047 this.annotation = null;
1053 * test if this is a valid candidate for another sequence's dataset sequence.
1056 private boolean isValidDatasetSequence()
1058 if (datasetSequence != null)
1062 for (int i = 0; i < sequence.length; i++)
1064 if (jalview.util.Comparison.isGap(sequence[i]))
1073 public SequenceI deriveSequence()
1076 if (datasetSequence == null)
1078 if (isValidDatasetSequence())
1080 // Use this as dataset sequence
1081 seq = new Sequence(getName(), "", 1, -1);
1082 seq.setDatasetSequence(this);
1083 seq.initSeqFrom(this, getAnnotation());
1088 // Create a new, valid dataset sequence
1089 createDatasetSequence();
1092 return new Sequence(this);
1095 private boolean _isNa;
1097 private long _seqhash = 0;
1100 public boolean isProtein()
1102 if (datasetSequence != null)
1104 return datasetSequence.isProtein();
1106 if (_seqhash != sequence.hashCode())
1108 _seqhash = sequence.hashCode();
1109 _isNa=jalview.util.Comparison.isNucleotide(new SequenceI[] { this });
1117 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1120 public SequenceI createDatasetSequence()
1122 if (datasetSequence == null)
1124 Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1125 jalview.util.Comparison.GapChars, getSequenceAsString()),
1126 getStart(), getEnd());
1128 datasetSequence = dsseq;
1130 dsseq.setDescription(description);
1131 // move features and database references onto dataset sequence
1132 dsseq.sequenceFeatures = sequenceFeatures;
1133 sequenceFeatures=null;
1134 dsseq.dbrefs = dbrefs;
1136 // TODO: search and replace any references to this sequence with
1137 // references to the dataset sequence in Mappings on dbref
1138 dsseq.pdbIds = pdbIds;
1140 datasetSequence.updatePDBIds();
1141 if (annotation != null)
1143 // annotation is cloned rather than moved, to preserve what's currently
1145 for (AlignmentAnnotation aa : annotation)
1147 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1148 _aa.sequenceRef = datasetSequence;
1149 _aa.adjustForAlignment(); // uses annotation's own record of
1150 // sequence-column mapping
1151 datasetSequence.addAlignmentAnnotation(_aa);
1155 return datasetSequence;
1162 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1166 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1168 if (annotation != null)
1170 annotation.removeAllElements();
1172 if (annotations != null)
1174 for (int i = 0; i < annotations.length; i++)
1176 if (annotations[i] != null)
1178 addAlignmentAnnotation(annotations[i]);
1185 public AlignmentAnnotation[] getAnnotation(String label)
1187 if (annotation == null || annotation.size() == 0)
1192 Vector subset = new Vector();
1193 Enumeration e = annotation.elements();
1194 while (e.hasMoreElements())
1196 AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1197 if (ann.label != null && ann.label.equals(label))
1199 subset.addElement(ann);
1202 if (subset.size() == 0)
1206 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1208 e = subset.elements();
1209 while (e.hasMoreElements())
1211 anns[i++] = (AlignmentAnnotation) e.nextElement();
1213 subset.removeAllElements();
1218 public boolean updatePDBIds()
1220 if (datasetSequence != null)
1222 // TODO: could merge DBRefs
1223 return datasetSequence.updatePDBIds();
1225 if (dbrefs == null || dbrefs.length == 0)
1229 Vector newpdb = new Vector();
1230 for (int i = 0; i < dbrefs.length; i++)
1232 if (DBRefSource.PDB.equals(dbrefs[i].getSource()))
1234 PDBEntry pdbe = new PDBEntry();
1235 pdbe.setId(dbrefs[i].getAccessionId());
1236 if (pdbIds == null || pdbIds.size() == 0)
1238 newpdb.addElement(pdbe);
1242 Enumeration en = pdbIds.elements();
1243 boolean matched = false;
1244 while (!matched && en.hasMoreElements())
1246 PDBEntry anentry = (PDBEntry) en.nextElement();
1247 if (anentry.getId().equals(pdbe.getId()))
1254 newpdb.addElement(pdbe);
1259 if (newpdb.size() > 0)
1261 Enumeration en = newpdb.elements();
1262 while (en.hasMoreElements())
1264 addPDBId((PDBEntry) en.nextElement());
1272 public void transferAnnotation(SequenceI entry, Mapping mp)
1274 if (datasetSequence != null)
1276 datasetSequence.transferAnnotation(entry, mp);
1279 if (entry.getDatasetSequence() != null)
1281 transferAnnotation(entry.getDatasetSequence(), mp);
1284 // transfer any new features from entry onto sequence
1285 if (entry.getSequenceFeatures() != null)
1288 SequenceFeature[] sfs = entry.getSequenceFeatures();
1289 for (int si = 0; si < sfs.length; si++)
1291 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1292 : new SequenceFeature[] { new SequenceFeature(sfs[si]) };
1293 if (sf != null && sf.length > 0)
1295 for (int sfi = 0; sfi < sf.length; sfi++)
1297 addSequenceFeature(sf[sfi]);
1303 // transfer PDB entries
1304 if (entry.getAllPDBEntries() != null)
1306 Enumeration e = entry.getAllPDBEntries().elements();
1307 while (e.hasMoreElements())
1309 PDBEntry pdb = (PDBEntry) e.nextElement();
1313 // transfer database references
1314 DBRefEntry[] entryRefs = entry.getDBRefs();
1315 if (entryRefs != null)
1317 for (int r = 0; r < entryRefs.length; r++)
1319 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1320 if (newref.getMap() != null && mp != null)
1322 // remap ref using our local mapping
1324 // we also assume all version string setting is done by dbSourceProxy
1326 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1327 * newref.setSource(dbSource); }
1335 * @return The index (zero-based) on this sequence in the MSA. It returns
1336 * {@code -1} if this information is not available.
1339 public int getIndex()
1345 * Defines the position of this sequence in the MSA. Use the value {@code -1}
1346 * if this information is undefined.
1349 * position for this sequence. This value is zero-based (zero for
1350 * this first sequence)
1353 public void setIndex(int value)
1359 public void setRNA(RNA r)
1371 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1374 List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1375 if (this.annotation != null)
1377 for (AlignmentAnnotation ann : annotation)
1379 if (ann.calcId != null && ann.calcId.equals(calcId)
1380 && ann.label != null && ann.label.equals(label))
1390 public String toString()
1392 return getDisplayId(false);
1396 public PDBEntry getPDBEntry(String pdbIdStr)
1398 if (getDatasetSequence() == null
1399 || getDatasetSequence().getAllPDBEntries() == null)
1403 List<PDBEntry> entries = getDatasetSequence().getAllPDBEntries();
1404 for (PDBEntry entry : entries)
1406 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1415 public void setSourceDBRef(DBRefEntryI dbRef)
1417 this.sourceDBRef = dbRef;
1421 public DBRefEntryI getSourceDBRef()
1423 return this.sourceDBRef;