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.Enumeration;
29 import java.util.List;
30 import java.util.Vector;
32 import fr.orsay.lri.varna.models.rna.RNA;
36 * Implements the SequenceI interface for a char[] based sequence object.
41 public class Sequence extends ASequence implements SequenceI
43 SequenceI datasetSequence;
47 private char[] sequence;
55 Vector<PDBEntry> pdbIds;
59 DBRefEntryI sourceDBRef;
66 * This annotation is displayed below the alignment but the positions are tied
67 * to the residues of this sequence
69 * TODO: change to List<>
71 Vector<AlignmentAnnotation> annotation;
74 * The index of the sequence in a MSA
78 /** array of sequence features - may not be null for a valid sequence object */
79 public SequenceFeature[] sequenceFeatures;
82 * Creates a new Sequence object.
87 * string to form a possibly gapped sequence out of
89 * first position of non-gap residue in the sequence
91 * last position of ungapped residues (nearly always only used for
94 public Sequence(String name, String sequence, int start, int end)
96 initSeqAndName(name, sequence.toCharArray(), start, end);
99 public Sequence(String name, char[] sequence, int start, int end)
101 initSeqAndName(name, sequence, start, end);
105 * Stage 1 constructor - assign name, sequence, and set start and end fields.
106 * start and end are updated values from name2 if it ends with /start-end
113 protected void initSeqAndName(String name2, char[] sequence2, int start2,
117 this.sequence = sequence2;
124 com.stevesoft.pat.Regex limitrx = new com.stevesoft.pat.Regex(
125 "[/][0-9]{1,}[-][0-9]{1,}$");
127 com.stevesoft.pat.Regex endrx = new com.stevesoft.pat.Regex("[0-9]{1,}$");
134 .println("POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
137 // Does sequence have the /start-end signature?
138 if (limitrx.search(name))
140 name = limitrx.left();
141 endrx.search(limitrx.stringMatched());
142 setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
143 endrx.matchedFrom() - 1)));
144 setEnd(Integer.parseInt(endrx.stringMatched()));
148 void checkValidRange()
151 // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
154 for (int j = 0; j < sequence.length; j++)
156 if (!jalview.util.Comparison.isGap(sequence[j]))
175 * Creates a new Sequence object.
182 public Sequence(String name, String sequence)
184 this(name, sequence, 1, -1);
188 * Creates a new Sequence object with new features, DBRefEntries,
189 * AlignmentAnnotations, and PDBIds but inherits any existing dataset sequence
195 public Sequence(SequenceI seq)
197 this(seq, seq.getAnnotation());
201 * Create a new sequence object with new features, DBRefEntries, and PDBIds
202 * but inherits any existing dataset sequence reference, and duplicate of any
203 * annotation that is present in the given annotation array.
206 * the sequence to be copied
207 * @param alAnnotation
208 * an array of annotation including some associated with seq
210 public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
212 initSeqFrom(seq, alAnnotation);
216 protected void initSeqFrom(SequenceI seq,
217 AlignmentAnnotation[] alAnnotation)
219 initSeqAndName(seq.getName(), seq.getSequence(), seq.getStart(),
221 description = seq.getDescription();
222 sourceDBRef = seq.getSourceDBRef() == null ? null : new DBRefEntry(
223 seq.getSourceDBRef());
224 if (seq.getSequenceFeatures() != null)
226 SequenceFeature[] sf = seq.getSequenceFeatures();
227 for (int i = 0; i < sf.length; i++)
229 addSequenceFeature(new SequenceFeature(sf[i]));
232 setDatasetSequence(seq.getDatasetSequence());
233 if (datasetSequence == null && seq.getDBRefs() != null)
235 // only copy DBRefs if we really are a dataset sequence
236 DBRefEntry[] dbr = seq.getDBRefs();
237 for (int i = 0; i < dbr.length; i++)
239 addDBRef(new DBRefEntry(dbr[i]));
242 if (seq.getAnnotation() != null)
244 AlignmentAnnotation[] sqann = seq.getAnnotation();
245 for (int i = 0; i < sqann.length; i++)
247 if (sqann[i] == null)
251 boolean found = (alAnnotation == null);
254 for (int apos = 0; !found && apos < alAnnotation.length; apos++)
256 found = (alAnnotation[apos] == sqann[i]);
261 // only copy the given annotation
262 AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
263 addAlignmentAnnotation(newann);
267 if (seq.getAllPDBEntries() != null)
269 Vector<PDBEntry> ids = seq.getAllPDBEntries();
270 for (PDBEntry pdb : ids)
272 this.addPDBId(new PDBEntry(pdb));
284 public void setSequenceFeatures(SequenceFeature[] features)
286 sequenceFeatures = features;
290 public synchronized void addSequenceFeature(SequenceFeature sf)
292 // TODO add to dataset sequence instead if there is one?
293 if (sequenceFeatures == null)
295 sequenceFeatures = new SequenceFeature[0];
298 for (int i = 0; i < sequenceFeatures.length; i++)
300 if (sequenceFeatures[i].equals(sf))
306 SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
307 System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
308 temp[sequenceFeatures.length] = sf;
310 sequenceFeatures = temp;
314 public void deleteFeature(SequenceFeature sf)
316 if (sequenceFeatures == null)
322 for (index = 0; index < sequenceFeatures.length; index++)
324 if (sequenceFeatures[index].equals(sf))
330 if (index == sequenceFeatures.length)
335 int sfLength = sequenceFeatures.length;
338 sequenceFeatures = null;
342 SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
343 System.arraycopy(sequenceFeatures, 0, temp, 0, index);
345 if (index < sfLength)
347 System.arraycopy(sequenceFeatures, index + 1, temp, index,
348 sequenceFeatures.length - index - 1);
351 sequenceFeatures = temp;
356 * Returns the sequence features (if any), looking first on the sequence, then
357 * on its dataset sequence, and so on until a non-null value is found (or
358 * none). This supports retrieval of sequence features stored on the sequence
359 * (as in the applet) or on the dataset sequence (as in the Desktop version).
364 public SequenceFeature[] getSequenceFeatures()
366 SequenceFeature[] features = sequenceFeatures;
368 SequenceI seq = this;
369 int count = 0; // failsafe against loop in sequence.datasetsequence...
370 while (features == null && seq.getDatasetSequence() != null
373 seq = seq.getDatasetSequence();
374 features = ((Sequence) seq).sequenceFeatures;
380 public void addPDBId(PDBEntry entry)
384 pdbIds = new Vector<PDBEntry>();
386 if (pdbIds.contains(entry))
388 updatePDBEntry(pdbIds.get(pdbIds.indexOf(entry)), entry);
392 pdbIds.addElement(entry);
396 private static void updatePDBEntry(PDBEntry oldEntry, PDBEntry newEntry)
398 if (newEntry.getFile() != null)
400 oldEntry.setFile(newEntry.getFile());
411 public void setPDBId(Vector<PDBEntry> id)
419 * @return DOCUMENT ME!
422 public Vector<PDBEntry> getAllPDBEntries()
424 return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
430 * @return DOCUMENT ME!
433 public String getDisplayId(boolean jvsuffix)
435 StringBuffer result = new StringBuffer(name);
438 result.append("/" + start + "-" + end);
441 return result.toString();
451 public void setName(String name)
460 * @return DOCUMENT ME!
463 public String getName()
475 public void setStart(int start)
483 * @return DOCUMENT ME!
486 public int getStart()
498 public void setEnd(int end)
506 * @return DOCUMENT ME!
517 * @return DOCUMENT ME!
520 public int getLength()
522 return this.sequence.length;
532 public void setSequence(String seq)
534 this.sequence = seq.toCharArray();
539 public String getSequenceAsString()
541 return new String(sequence);
545 public String getSequenceAsString(int start, int end)
547 return new String(getSequence(start, end));
551 public char[] getSequence()
559 * @see jalview.datamodel.SequenceI#getSequence(int, int)
562 public char[] getSequence(int start, int end)
568 // JBPNote - left to user to pad the result here (TODO:Decide on this
570 if (start >= sequence.length)
575 if (end >= sequence.length)
577 end = sequence.length;
580 char[] reply = new char[end - start];
581 System.arraycopy(sequence, start, reply, 0, end - start);
587 public SequenceI getSubSequence(int start, int end)
593 char[] seq = getSequence(start, end);
598 int nstart = findPosition(start);
599 int nend = findPosition(end) - 1;
600 // JBPNote - this is an incomplete copy.
601 SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
602 nseq.setDescription(description);
603 if (datasetSequence != null)
605 nseq.setDatasetSequence(datasetSequence);
609 nseq.setDatasetSequence(this);
615 * Returns the character of the aligned sequence at the given position (base
616 * zero), or space if the position is not within the sequence's bounds
621 public char getCharAt(int i)
623 if (i >= 0 && i < sequence.length)
640 public void setDescription(String desc)
642 this.description = desc;
648 * @return DOCUMENT ME!
651 public String getDescription()
653 return this.description;
659 * @see jalview.datamodel.SequenceI#findIndex(int)
662 public int findIndex(int pos)
664 // returns the alignment position for a residue
667 // Rely on end being at least as long as the length of the sequence.
668 while ((i < sequence.length) && (j <= end) && (j <= pos))
670 if (!jalview.util.Comparison.isGap(sequence[i]))
678 if ((j == end) && (j < pos))
689 public int findPosition(int i)
693 int seqlen = sequence.length;
694 while ((j < i) && (j < seqlen))
696 if (!jalview.util.Comparison.isGap(sequence[j]))
708 * Returns an int array where indices correspond to each residue in the
709 * sequence and the element value gives its position in the alignment
711 * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
712 * residues in SequenceI object
715 public int[] gapMap()
717 String seq = jalview.analysis.AlignSeq.extractGaps(
718 jalview.util.Comparison.GapChars, new String(sequence));
719 int[] map = new int[seq.length()];
723 while (j < sequence.length)
725 if (!jalview.util.Comparison.isGap(sequence[j]))
737 public int[] findPositionMap()
739 int map[] = new int[sequence.length];
742 int seqlen = sequence.length;
746 if (!jalview.util.Comparison.isGap(sequence[j]))
757 public List<int[]> getInsertions()
759 ArrayList<int[]> map = new ArrayList<int[]>();
760 int lastj = -1, j = 0;
762 int seqlen = sequence.length;
765 if (jalview.util.Comparison.isGap(sequence[j]))
776 map.add(new int[] { lastj, j - 1 });
784 map.add(new int[] { lastj, j - 1 });
791 public void deleteChars(int i, int j)
793 int newstart = start, newend = end;
794 if (i >= sequence.length || i < 0)
799 char[] tmp = StringUtils.deleteChars(sequence, i, j);
800 boolean createNewDs = false;
801 // TODO: take a (second look) at the dataset creation validation method for
802 // the very large sequence case
803 int eindex = -1, sindex = -1;
804 boolean ecalc = false, scalc = false;
805 for (int s = i; s < j; s++)
807 if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
817 sindex = findIndex(start) - 1;
822 // delete characters including start of sequence
823 newstart = findPosition(j);
824 break; // don't need to search for any more residue characters.
828 // delete characters after start.
831 eindex = findIndex(end) - 1;
836 // delete characters at end of sequence
837 newend = findPosition(i - 1);
838 break; // don't need to search for any more residue characters.
843 newend--; // decrease end position by one for the deleted residue
844 // and search further
850 // deletion occured in the middle of the sequence
851 if (createNewDs && this.datasetSequence != null)
853 // construct a new sequence
854 Sequence ds = new Sequence(datasetSequence);
855 // TODO: remove any non-inheritable properties ?
856 // TODO: create a sequence mapping (since there is a relation here ?)
857 ds.deleteChars(i, j);
858 datasetSequence = ds;
866 public void insertCharAt(int i, int length, char c)
868 char[] tmp = new char[sequence.length + length];
870 if (i >= sequence.length)
872 System.arraycopy(sequence, 0, tmp, 0, sequence.length);
877 System.arraycopy(sequence, 0, tmp, 0, i);
887 if (i < sequence.length)
889 System.arraycopy(sequence, i, tmp, index, sequence.length - i);
896 public void insertCharAt(int i, char c)
898 insertCharAt(i, 1, c);
902 public String getVamsasId()
908 public void setVamsasId(String id)
914 public void setDBRefs(DBRefEntry[] dbref)
920 public DBRefEntry[] getDBRefs()
922 if (dbrefs == null && datasetSequence != null
923 && this != datasetSequence)
925 return datasetSequence.getDBRefs();
931 public void addDBRef(DBRefEntry entry)
933 // TODO add to dataset sequence instead if there is one?
936 dbrefs = new DBRefEntry[0];
939 int i, iSize = dbrefs.length;
941 for (i = 0; i < iSize; i++)
943 if (dbrefs[i].equalRef(entry))
945 if (entry.getMap() != null)
947 if (dbrefs[i].getMap() == null)
949 // overwrite with 'superior' entry that contains a mapping.
957 DBRefEntry[] temp = new DBRefEntry[iSize + 1];
958 System.arraycopy(dbrefs, 0, temp, 0, iSize);
959 temp[temp.length - 1] = entry;
965 public void setDatasetSequence(SequenceI seq)
967 // TODO check for circular reference before setting?
968 datasetSequence = seq;
972 public SequenceI getDatasetSequence()
974 return datasetSequence;
978 public AlignmentAnnotation[] getAnnotation()
980 return annotation == null ? null : annotation
981 .toArray(new AlignmentAnnotation[annotation.size()]);
985 public boolean hasAnnotation(AlignmentAnnotation ann)
987 return annotation == null ? false : annotation.contains(ann);
991 public void addAlignmentAnnotation(AlignmentAnnotation annotation)
993 if (this.annotation == null)
995 this.annotation = new Vector<AlignmentAnnotation>();
997 if (!this.annotation.contains(annotation))
999 this.annotation.addElement(annotation);
1001 annotation.setSequenceRef(this);
1005 public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1007 if (this.annotation != null)
1009 this.annotation.removeElement(annotation);
1010 if (this.annotation.size() == 0)
1012 this.annotation = null;
1018 * test if this is a valid candidate for another sequence's dataset sequence.
1021 private boolean isValidDatasetSequence()
1023 if (datasetSequence != null)
1027 for (int i = 0; i < sequence.length; i++)
1029 if (jalview.util.Comparison.isGap(sequence[i]))
1038 public SequenceI deriveSequence()
1040 SequenceI seq = new Sequence(this);
1041 if (datasetSequence != null)
1043 // duplicate current sequence with same dataset
1044 seq.setDatasetSequence(datasetSequence);
1048 if (isValidDatasetSequence())
1050 // Use this as dataset sequence
1051 seq.setDatasetSequence(this);
1055 // Create a new, valid dataset sequence
1057 ds.setSequence(AlignSeq.extractGaps(
1058 jalview.util.Comparison.GapChars, new String(sequence)));
1059 setDatasetSequence(ds);
1060 ds.setSequenceFeatures(getSequenceFeatures());
1061 seq = this; // and return this sequence as the derived sequence.
1070 * @see jalview.datamodel.SequenceI#createDatasetSequence()
1073 public SequenceI createDatasetSequence()
1075 if (datasetSequence == null)
1077 datasetSequence = new Sequence(getName(), AlignSeq.extractGaps(
1078 jalview.util.Comparison.GapChars, getSequenceAsString()),
1079 getStart(), getEnd());
1080 datasetSequence.setSequenceFeatures(getSequenceFeatures());
1081 datasetSequence.setDescription(getDescription());
1082 setSequenceFeatures(null);
1083 // move database references onto dataset sequence
1084 datasetSequence.setDBRefs(getDBRefs());
1086 datasetSequence.setPDBId(getAllPDBEntries());
1088 datasetSequence.updatePDBIds();
1089 if (annotation != null)
1091 for (AlignmentAnnotation aa : annotation)
1093 AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1094 _aa.sequenceRef = datasetSequence;
1095 _aa.adjustForAlignment(); // uses annotation's own record of
1096 // sequence-column mapping
1097 datasetSequence.addAlignmentAnnotation(_aa);
1101 return datasetSequence;
1108 * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1112 public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1114 if (annotation != null)
1116 annotation.removeAllElements();
1118 if (annotations != null)
1120 for (int i = 0; i < annotations.length; i++)
1122 if (annotations[i] != null)
1124 addAlignmentAnnotation(annotations[i]);
1131 public AlignmentAnnotation[] getAnnotation(String label)
1133 if (annotation == null || annotation.size() == 0)
1138 Vector subset = new Vector();
1139 Enumeration e = annotation.elements();
1140 while (e.hasMoreElements())
1142 AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1143 if (ann.label != null && ann.label.equals(label))
1145 subset.addElement(ann);
1148 if (subset.size() == 0)
1152 AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1154 e = subset.elements();
1155 while (e.hasMoreElements())
1157 anns[i++] = (AlignmentAnnotation) e.nextElement();
1159 subset.removeAllElements();
1164 public boolean updatePDBIds()
1166 if (datasetSequence != null)
1168 // TODO: could merge DBRefs
1169 return datasetSequence.updatePDBIds();
1171 if (dbrefs == null || dbrefs.length == 0)
1175 Vector newpdb = new Vector();
1176 for (int i = 0; i < dbrefs.length; i++)
1178 if (DBRefSource.PDB.equals(dbrefs[i].getSource()))
1180 PDBEntry pdbe = new PDBEntry();
1181 pdbe.setId(dbrefs[i].getAccessionId());
1182 if (pdbIds == null || pdbIds.size() == 0)
1184 newpdb.addElement(pdbe);
1188 Enumeration en = pdbIds.elements();
1189 boolean matched = false;
1190 while (!matched && en.hasMoreElements())
1192 PDBEntry anentry = (PDBEntry) en.nextElement();
1193 if (anentry.getId().equals(pdbe.getId()))
1200 newpdb.addElement(pdbe);
1205 if (newpdb.size() > 0)
1207 Enumeration en = newpdb.elements();
1208 while (en.hasMoreElements())
1210 addPDBId((PDBEntry) en.nextElement());
1218 public void transferAnnotation(SequenceI entry, Mapping mp)
1220 if (datasetSequence != null)
1222 datasetSequence.transferAnnotation(entry, mp);
1225 if (entry.getDatasetSequence() != null)
1227 transferAnnotation(entry.getDatasetSequence(), mp);
1230 // transfer any new features from entry onto sequence
1231 if (entry.getSequenceFeatures() != null)
1234 SequenceFeature[] sfs = entry.getSequenceFeatures();
1235 for (int si = 0; si < sfs.length; si++)
1237 SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1238 : new SequenceFeature[] { new SequenceFeature(sfs[si]) };
1239 if (sf != null && sf.length > 0)
1241 for (int sfi = 0; sfi < sf.length; sfi++)
1243 addSequenceFeature(sf[sfi]);
1249 // transfer PDB entries
1250 if (entry.getAllPDBEntries() != null)
1252 Enumeration e = entry.getAllPDBEntries().elements();
1253 while (e.hasMoreElements())
1255 PDBEntry pdb = (PDBEntry) e.nextElement();
1259 // transfer database references
1260 DBRefEntry[] entryRefs = entry.getDBRefs();
1261 if (entryRefs != null)
1263 for (int r = 0; r < entryRefs.length; r++)
1265 DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1266 if (newref.getMap() != null && mp != null)
1268 // remap ref using our local mapping
1270 // we also assume all version string setting is done by dbSourceProxy
1272 * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1273 * newref.setSource(dbSource); }
1281 * @return The index (zero-based) on this sequence in the MSA. It returns
1282 * {@code -1} if this information is not available.
1285 public int getIndex()
1291 * Defines the position of this sequence in the MSA. Use the value {@code -1}
1292 * if this information is undefined.
1295 * position for this sequence. This value is zero-based (zero for
1296 * this first sequence)
1299 public void setIndex(int value)
1305 public void setRNA(RNA r)
1317 public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1320 List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1321 if (this.annotation != null)
1323 for (AlignmentAnnotation ann : annotation)
1325 if (ann.calcId != null && ann.calcId.equals(calcId)
1326 && ann.label != null && ann.label.equals(label))
1336 public String toString()
1338 return getDisplayId(false);
1342 public PDBEntry getPDBEntry(String pdbIdStr)
1344 if (getDatasetSequence() == null
1345 || getDatasetSequence().getAllPDBEntries() == null)
1349 List<PDBEntry> entries = getDatasetSequence().getAllPDBEntries();
1350 for (PDBEntry entry : entries)
1352 if (entry.getId().equalsIgnoreCase(pdbIdStr))
1361 public void setSourceDBRef(DBRefEntryI dbRef)
1363 this.sourceDBRef = dbRef;
1367 public DBRefEntryI getSourceDBRef()
1369 return this.sourceDBRef;