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.xdb.embl;
23 import jalview.analysis.SequenceIdMatcher;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.FeatureProperties;
27 import jalview.datamodel.Mapping;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.util.DBRefUtils;
32 import jalview.util.DnaUtils;
33 import jalview.util.MapList;
34 import jalview.util.MappingUtils;
35 import jalview.util.StringUtils;
37 import java.util.Arrays;
38 import java.util.Hashtable;
39 import java.util.List;
41 import java.util.Map.Entry;
42 import java.util.Vector;
43 import java.util.regex.Pattern;
46 * Data model for one entry returned from an EMBL query, as marshalled by a
50 * http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=ena_sequence&id=J03321
53 * @see embl_mapping.xml
55 public class EmblEntry
57 private static final Pattern SPACE_PATTERN = Pattern.compile(" ");
63 String sequenceVersion;
71 String sequenceLength;
73 String taxonomicDivision;
77 String firstPublicDate;
79 String firstPublicRelease;
81 String lastUpdatedDate;
83 String lastUpdatedRelease;
85 Vector<String> keywords;
87 Vector<DBRefEntry> dbRefs;
89 Vector<EmblFeature> features;
91 EmblSequence sequence;
94 * @return the accession
96 public String getAccession()
103 * the accession to set
105 public void setAccession(String accession)
107 this.accession = accession;
113 public Vector<DBRefEntry> getDbRefs()
122 public void setDbRefs(Vector<DBRefEntry> dbRefs)
124 this.dbRefs = dbRefs;
128 * @return the features
130 public Vector<EmblFeature> getFeatures()
137 * the features to set
139 public void setFeatures(Vector<EmblFeature> features)
141 this.features = features;
145 * @return the keywords
147 public Vector<String> getKeywords()
154 * the keywords to set
156 public void setKeywords(Vector<String> keywords)
158 this.keywords = keywords;
162 * @return the sequence
164 public EmblSequence getSequence()
171 * the sequence to set
173 public void setSequence(EmblSequence sequence)
175 this.sequence = sequence;
179 * Recover annotated sequences from EMBL file
183 * a list of protein products found so far (to add to)
184 * @return dna dataset sequence with DBRefs and features
186 public SequenceI getSequence(String sourceDb, List<SequenceI> peptides)
188 SequenceI dna = new Sequence(sourceDb + "|" + accession,
189 sequence.getSequence());
190 dna.setDescription(description);
191 DBRefEntry retrievedref = new DBRefEntry(sourceDb,
192 getSequenceVersion(), accession);
193 dna.addDBRef(retrievedref);
194 // add map to indicate the sequence is a valid coordinate frame for the
196 retrievedref.setMap(new Mapping(null, new int[] { 1, dna.getLength() },
197 new int[] { 1, dna.getLength() }, 1, 1));
198 // TODO: transform EMBL Database refs to canonical form
201 for (DBRefEntry dbref : dbRefs)
209 for (EmblFeature feature : features)
211 if (feature.dbRefs != null)
213 for (DBRefEntry dbref : feature.dbRefs)
218 if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
220 parseCodingFeature(feature, sourceDb, dna, peptides);
223 } catch (Exception e)
225 System.err.println("EMBL Record Features parsing error!");
227 .println("Please report the following to help@jalview.org :");
228 System.err.println("EMBL Record " + accession);
229 System.err.println("Resulted in exception: " + e.getMessage());
230 e.printStackTrace(System.err);
237 * Extracts coding region and product from a CDS feature and properly decorate
238 * it with annotations.
243 * source database for the EMBLXML
245 * parent dna sequence for this record
247 * list of protein product sequences for Embl entry
249 void parseCodingFeature(EmblFeature feature, String sourceDb,
250 SequenceI dna, List<SequenceI> peptides)
252 boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
254 int[] exon = getCdsRanges(feature);
259 Map<String, String> vals = new Hashtable<String, String>();
260 SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
263 * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
264 * (phase is required for CDS features in GFF3 format)
269 * parse qualifiers, saving protein translation, protein id,
270 * codon start position, product (name), and 'other values'
272 if (feature.getQualifiers() != null)
274 for (Qualifier q : feature.getQualifiers())
276 String qname = q.getName();
277 if (qname.equals("translation"))
279 // remove all spaces (precompiled String.replaceAll(" ", ""))
280 prseq = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll("");
282 else if (qname.equals("protein_id"))
284 prid = q.getValues()[0];
286 else if (qname.equals("codon_start"))
290 codonStart = Integer.parseInt(q.getValues()[0]);
291 } catch (NumberFormatException e)
293 System.err.println("Invalid codon_start in XML for "
294 + accession + ": " + e.getMessage());
297 else if (qname.equals("product"))
299 // sometimes name is returned e.g. for V00488
300 prname = q.getValues()[0];
304 // throw anything else into the additional properties hash
305 String[] qvals = q.getValues();
308 String commaSeparated = StringUtils.arrayToSeparatorList(qvals,
310 vals.put(qname, commaSeparated);
316 DBRefEntry protEMBLCDS = null;
317 exon = MappingUtils.removeStartPositions(codonStart - 1, exon);
318 boolean noProteinDbref = true;
320 SequenceI product = null;
322 if (prseq != null && prname != null && prid != null)
325 * look for product in peptides list, if not found, add it
327 product = matcher.findIdMatch(prid);
330 product = new Sequence(prid, prseq, 1, prseq.length());
331 product.setDescription(((prname.length() == 0) ? "Protein Product from "
334 peptides.add(product);
335 matcher.add(product);
338 // we have everything - create the mapping and perhaps the protein
340 if (exon == null || exon.length == 0)
343 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
344 + sourceDb + ":" + getAccession() + ")");
345 if (prseq.length() * 3 == (1 - codonStart + dna.getSequence().length))
348 .println("Not allowing for additional stop codon at end of cDNA fragment... !");
349 // this might occur for CDS sequences where no features are
351 exon = new int[] { dna.getStart() + (codonStart - 1),
353 map = new Mapping(product, exon, new int[] { 1, prseq.length() },
356 if ((prseq.length() + 1) * 3 == (1 - codonStart + dna.getSequence().length))
359 .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
360 exon = new int[] { dna.getStart() + (codonStart - 1),
362 map = new Mapping(product, exon, new int[] { 1, prseq.length() },
368 // Trim the exon mapping if necessary - the given product may only be a
369 // fragment of a larger protein. (EMBL:AY043181 is an example)
373 // TODO: Add a DbRef back to the parent EMBL sequence with the exon
375 // if given a dataset reference, search dataset for parent EMBL
376 // sequence if it exists and set its map
377 // make a new feature annotating the coding contig
381 // final product length truncation check
382 // TODO should from range include stop codon even if not in protein
383 // in order to include stop codon in CDS sequence (as done for
385 int[] cdsRanges = adjustForProteinLength(prseq.length(), exon);
386 map = new Mapping(product, cdsRanges, new int[] { 1,
387 prseq.length() }, 3, 1);
388 // reconstruct the EMBLCDS entry
389 // TODO: this is only necessary when there codon annotation is
390 // complete (I think JBPNote)
391 DBRefEntry pcdnaref = new DBRefEntry();
392 pcdnaref.setAccessionId(prid);
393 pcdnaref.setSource(DBRefSource.EMBLCDS);
394 pcdnaref.setVersion(getSequenceVersion()); // same as parent EMBL
396 MapList mp = new MapList(new int[] { 1, prseq.length() },
397 new int[] { 1 + (codonStart - 1),
398 (codonStart - 1) + 3 * prseq.length() }, 1, 3);
399 pcdnaref.setMap(new Mapping(mp));
402 product.addDBRef(pcdnaref);
403 protEMBLCDS = new DBRefEntry(pcdnaref);
404 protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
405 product.addDBRef(protEMBLCDS);
409 // add cds feature to dna seq - this may include the stop codon
410 for (int xint = 0; exon != null && xint < exon.length; xint += 2)
412 SequenceFeature sf = makeCdsFeature(exon, xint, prname, prid, vals,
414 sf.setType(feature.getName()); // "CDS"
415 sf.setEnaLocation(feature.getLocation());
416 sf.setFeatureGroup(sourceDb);
417 dna.addSequenceFeature(sf);
422 * add dbRefs to sequence, and mappings for Uniprot xrefs
424 if (feature.dbRefs != null)
426 boolean mappingUsed = false;
427 for (DBRefEntry ref : feature.dbRefs)
429 ref.setSource(DBRefUtils.getCanonicalName(ref.getSource()));
430 if (ref.getSource().equals(DBRefSource.UNIPROT))
432 String proteinSeqName = DBRefSource.UNIPROT + "|"
433 + ref.getAccessionId();
434 if (map != null && map.getTo() != null)
439 * two or more Uniprot xrefs for the same CDS -
440 * each needs a distinct Mapping (as to a different sequence)
442 map = new Mapping(map);
447 * try to locate the protein mapped to (possibly by a
448 * previous CDS feature)
450 SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
451 if (proteinSeq == null)
453 proteinSeq = new Sequence(proteinSeqName,
454 product.getSequenceAsString());
455 matcher.add(proteinSeq);
456 peptides.add(proteinSeq);
458 map.setTo(proteinSeq);
459 map.getTo().addDBRef(
460 new DBRefEntry(ref.getSource(), ref.getVersion(), ref
464 noProteinDbref = false;
468 DBRefEntry pref = new DBRefEntry(ref.getSource(),
469 ref.getVersion(), ref.getAccessionId());
470 pref.setMap(null); // reference is direct
471 product.addDBRef(pref);
472 // Add converse mapping reference
475 Mapping pmap = new Mapping(dna, map.getMap().getInverse());
476 pref = new DBRefEntry(sourceDb, getSequenceVersion(),
477 this.getAccession());
479 if (map.getTo() != null)
481 map.getTo().addDBRef(pref);
487 if (noProteinDbref && product != null)
489 // add protein coding reference to dna sequence so xref matches
490 if (protEMBLCDS == null)
492 protEMBLCDS = new DBRefEntry();
493 protEMBLCDS.setAccessionId(prid);
494 protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
495 protEMBLCDS.setVersion(getSequenceVersion());
497 .setMap(new Mapping(product, map.getMap().getInverse()));
499 product.addDBRef(protEMBLCDS);
501 // Add converse mapping reference
504 Mapping pmap = new Mapping(product, protEMBLCDS.getMap().getMap()
506 DBRefEntry ncMap = new DBRefEntry(protEMBLCDS);
508 if (map.getTo() != null)
518 * Helper method to construct a SequenceFeature for one cds range
521 * array of cds [start, end, ...] positions
522 * @param exonStartIndex
523 * offset into the exons array
525 * @param proteinAccessionId
527 * map of 'miscellaneous values' for feature
529 * codon start position for CDS (1/2/3, normally 1)
532 protected SequenceFeature makeCdsFeature(int[] exons, int exonStartIndex,
533 String proteinName, String proteinAccessionId,
534 Map<String, String> vals, int codonStart)
536 int exonNumber = exonStartIndex / 2 + 1;
537 SequenceFeature sf = new SequenceFeature();
538 sf.setBegin(Math.min(exons[exonStartIndex], exons[exonStartIndex + 1]));
539 sf.setEnd(Math.max(exons[exonStartIndex], exons[exonStartIndex + 1]));
540 sf.setDescription(String.format("Exon %d for protein '%s' EMBLCDS:%s",
541 exonNumber, proteinName, proteinAccessionId));
542 sf.setPhase(String.valueOf(codonStart - 1));
543 sf.setStrand(exons[exonStartIndex] <= exons[exonStartIndex + 1] ? "+"
545 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
546 sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
549 StringBuilder sb = new StringBuilder();
550 boolean first = true;
551 for (Entry<String, String> val : vals.entrySet())
557 sb.append(val.getKey()).append("=").append(val.getValue());
559 sf.setValue(val.getKey(), val.getValue());
561 sf.setAttributes(sb.toString());
567 * Returns the CDS positions as a list of [start, end, start, end...]
568 * positions. If on the reverse strand, these will be in descending order.
573 protected int[] getCdsRanges(EmblFeature feature)
575 if (feature.location == null)
579 List<int[]> ranges = DnaUtils.parseLocation(feature.location);
580 return ranges == null ? new int[] {} : listToArray(ranges);
584 * Converts a list of [start, end] ranges to a single array of [start, end,
590 int[] listToArray(List<int[]> ranges)
592 int[] result = new int[ranges.size() * 2];
594 for (int[] range : ranges)
596 result[i++] = range[0];
597 result[i++] = range[1];
603 * truncate the last exon interval to the prlength'th codon
609 static int[] adjustForProteinLength(int prlength, int[] exon)
611 if (prlength <= 0 || exon == null)
615 int desiredCdsLength = prlength * 3;
616 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
619 * assuming here exon might include stop codon in addition to protein codons
621 if (desiredCdsLength == exonLength
622 || desiredCdsLength == exonLength - 3)
630 origxon = new int[exon.length];
631 System.arraycopy(exon, 0, origxon, 0, exon.length);
633 for (int x = 0; x < exon.length; x += 2)
635 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
636 if (desiredCdsLength <= cdspos)
638 // advanced beyond last codon.
640 if (desiredCdsLength != cdspos)
643 // .println("Truncating final exon interval on region by "
644 // + (cdspos - cdslength));
648 * shrink the final exon - reduce end position if forward
649 * strand, increase it if reverse
651 if (exon[x + 1] >= exon[x])
653 endxon = exon[x + 1] - cdspos + desiredCdsLength;
657 endxon = exon[x + 1] + cdspos - desiredCdsLength;
665 // and trim the exon interval set if necessary
666 int[] nxon = new int[sxpos + 2];
667 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
668 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
675 public String getSequenceVersion()
677 return sequenceVersion;
680 public void setSequenceVersion(String sequenceVersion)
682 this.sequenceVersion = sequenceVersion;
685 public String getSequenceLength()
687 return sequenceLength;
690 public void setSequenceLength(String sequenceLength)
692 this.sequenceLength = sequenceLength;
695 public String getEntryVersion()
700 public void setEntryVersion(String entryVersion)
702 this.entryVersion = entryVersion;
705 public String getMoleculeType()
710 public void setMoleculeType(String moleculeType)
712 this.moleculeType = moleculeType;
715 public String getTopology()
720 public void setTopology(String topology)
722 this.topology = topology;
725 public String getTaxonomicDivision()
727 return taxonomicDivision;
730 public void setTaxonomicDivision(String taxonomicDivision)
732 this.taxonomicDivision = taxonomicDivision;
735 public String getDescription()
740 public void setDescription(String description)
742 this.description = description;
745 public String getFirstPublicDate()
747 return firstPublicDate;
750 public void setFirstPublicDate(String firstPublicDate)
752 this.firstPublicDate = firstPublicDate;
755 public String getFirstPublicRelease()
757 return firstPublicRelease;
760 public void setFirstPublicRelease(String firstPublicRelease)
762 this.firstPublicRelease = firstPublicRelease;
765 public String getLastUpdatedDate()
767 return lastUpdatedDate;
770 public void setLastUpdatedDate(String lastUpdatedDate)
772 this.lastUpdatedDate = lastUpdatedDate;
775 public String getLastUpdatedRelease()
777 return lastUpdatedRelease;
780 public void setLastUpdatedRelease(String lastUpdatedRelease)
782 this.lastUpdatedRelease = lastUpdatedRelease;
785 public String getDataClass()
790 public void setDataClass(String dataClass)
792 this.dataClass = dataClass;