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.bin.Cache;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.FeatureProperties;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32 import jalview.util.DBRefUtils;
33 import jalview.util.DnaUtils;
34 import jalview.util.MapList;
35 import jalview.util.MappingUtils;
36 import jalview.util.StringUtils;
38 import java.text.ParseException;
39 import java.util.Arrays;
40 import java.util.Hashtable;
41 import java.util.List;
43 import java.util.Map.Entry;
44 import java.util.Vector;
45 import java.util.regex.Pattern;
48 * Data model for one entry returned from an EMBL query, as marshalled by a
52 * http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=ena_sequence&id=J03321
55 * @see embl_mapping.xml
57 public class EmblEntry
59 private static final Pattern SPACE_PATTERN = Pattern.compile(" ");
65 String sequenceVersion;
73 String sequenceLength;
75 String taxonomicDivision;
79 String firstPublicDate;
81 String firstPublicRelease;
83 String lastUpdatedDate;
85 String lastUpdatedRelease;
87 Vector<String> keywords;
89 Vector<DBRefEntry> dbRefs;
91 Vector<EmblFeature> features;
93 EmblSequence sequence;
96 * @return the accession
98 public String getAccession()
105 * the accession to set
107 public void setAccession(String accession)
109 this.accession = accession;
115 public Vector<DBRefEntry> getDbRefs()
124 public void setDbRefs(Vector<DBRefEntry> dbRefs)
126 this.dbRefs = dbRefs;
130 * @return the features
132 public Vector<EmblFeature> getFeatures()
139 * the features to set
141 public void setFeatures(Vector<EmblFeature> features)
143 this.features = features;
147 * @return the keywords
149 public Vector<String> getKeywords()
156 * the keywords to set
158 public void setKeywords(Vector<String> keywords)
160 this.keywords = keywords;
164 * @return the sequence
166 public EmblSequence getSequence()
173 * the sequence to set
175 public void setSequence(EmblSequence sequence)
177 this.sequence = sequence;
181 * Recover annotated sequences from EMBL file
185 * a list of protein products found so far (to add to)
186 * @return dna dataset sequence with DBRefs and features
188 public SequenceI getSequence(String sourceDb, List<SequenceI> peptides)
190 SequenceI dna = new Sequence(sourceDb + "|" + accession,
191 sequence.getSequence());
192 dna.setDescription(description);
193 DBRefEntry retrievedref = new DBRefEntry(sourceDb,
194 getSequenceVersion(), accession);
195 dna.addDBRef(retrievedref);
196 // add map to indicate the sequence is a valid coordinate frame for the
198 retrievedref.setMap(new Mapping(null, new int[] { 1, dna.getLength() },
199 new int[] { 1, dna.getLength() }, 1, 1));
202 * transform EMBL Database refs to canonical form
206 for (DBRefEntry dbref : dbRefs)
208 dbref.setSource(DBRefUtils.getCanonicalName(dbref.getSource()));
213 SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
216 for (EmblFeature feature : features)
218 if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
220 parseCodingFeature(feature, sourceDb, dna, peptides, matcher);
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 * helper to match xrefs in already retrieved sequences
251 void parseCodingFeature(EmblFeature feature, String sourceDb,
252 SequenceI dna, List<SequenceI> peptides, SequenceIdMatcher matcher)
254 boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
256 int[] exon = getCdsRanges(feature);
261 Map<String, String> vals = new Hashtable<String, String>();
264 * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
265 * (phase is required for CDS features in GFF3 format)
270 * parse qualifiers, saving protein translation, protein id,
271 * codon start position, product (name), and 'other values'
273 if (feature.getQualifiers() != null)
275 for (Qualifier q : feature.getQualifiers())
277 String qname = q.getName();
278 if (qname.equals("translation"))
280 // remove all spaces (precompiled String.replaceAll(" ", ""))
281 prseq = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll("");
283 else if (qname.equals("protein_id"))
285 prid = q.getValues()[0];
287 else if (qname.equals("codon_start"))
291 codonStart = Integer.parseInt(q.getValues()[0]);
292 } catch (NumberFormatException e)
294 System.err.println("Invalid codon_start in XML for "
295 + accession + ": " + e.getMessage());
298 else if (qname.equals("product"))
300 // sometimes name is returned e.g. for V00488
301 prname = q.getValues()[0];
305 // throw anything else into the additional properties hash
306 String[] qvals = q.getValues();
309 String commaSeparated = StringUtils.arrayToSeparatorList(qvals,
311 vals.put(qname, commaSeparated);
317 DBRefEntry protEMBLCDS = null;
318 exon = MappingUtils.removeStartPositions(codonStart - 1, exon);
319 boolean noProteinDbref = true;
321 SequenceI product = null;
323 if (prseq != null && prname != null && prid != null)
326 * look for product in peptides list, if not found, add it
328 product = matcher.findIdMatch(prid);
331 product = new Sequence(prid, prseq, 1, prseq.length());
332 product.setDescription(((prname.length() == 0) ? "Protein Product from "
335 peptides.add(product);
336 matcher.add(product);
339 // we have everything - create the mapping and perhaps the protein
341 if (exon == null || exon.length == 0)
344 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
345 + sourceDb + ":" + getAccession() + ")");
346 if (prseq.length() * 3 == (1 - codonStart + dna.getSequence().length))
349 .println("Not allowing for additional stop codon at end of cDNA fragment... !");
350 // this might occur for CDS sequences where no features are
352 exon = new int[] { dna.getStart() + (codonStart - 1),
354 map = new Mapping(product, exon, new int[] { 1, prseq.length() },
357 if ((prseq.length() + 1) * 3 == (1 - codonStart + dna.getSequence().length))
360 .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
361 exon = new int[] { dna.getStart() + (codonStart - 1),
363 map = new Mapping(product, exon, new int[] { 1, prseq.length() },
369 // Trim the exon mapping if necessary - the given product may only be a
370 // fragment of a larger protein. (EMBL:AY043181 is an example)
374 // TODO: Add a DbRef back to the parent EMBL sequence with the exon
376 // if given a dataset reference, search dataset for parent EMBL
377 // sequence if it exists and set its map
378 // make a new feature annotating the coding contig
382 // final product length truncation check
383 // TODO should from range include stop codon even if not in protein
384 // in order to include stop codon in CDS sequence (as done for
386 int[] cdsRanges = adjustForProteinLength(prseq.length(), exon);
387 map = new Mapping(product, cdsRanges, new int[] { 1,
388 prseq.length() }, 3, 1);
389 // reconstruct the EMBLCDS entry
390 // TODO: this is only necessary when there codon annotation is
391 // complete (I think JBPNote)
392 DBRefEntry pcdnaref = new DBRefEntry();
393 pcdnaref.setAccessionId(prid);
394 pcdnaref.setSource(DBRefSource.EMBLCDS);
395 pcdnaref.setVersion(getSequenceVersion()); // same as parent EMBL
397 MapList mp = new MapList(new int[] { 1, prseq.length() },
398 new int[] { 1 + (codonStart - 1),
399 (codonStart - 1) + 3 * prseq.length() }, 1, 3);
400 pcdnaref.setMap(new Mapping(mp));
403 product.addDBRef(pcdnaref);
404 protEMBLCDS = new DBRefEntry(pcdnaref);
405 protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
406 product.addDBRef(protEMBLCDS);
410 // add cds feature to dna seq - this may include the stop codon
411 for (int xint = 0; exon != null && xint < exon.length; xint += 2)
413 SequenceFeature sf = makeCdsFeature(exon, xint, prname, prid, vals,
415 sf.setType(feature.getName()); // "CDS"
416 sf.setEnaLocation(feature.getLocation());
417 sf.setFeatureGroup(sourceDb);
418 dna.addSequenceFeature(sf);
423 * add dbRefs to sequence, and mappings for Uniprot xrefs
425 if (feature.dbRefs != null)
427 boolean mappingUsed = false;
428 for (DBRefEntry ref : feature.dbRefs)
431 * ensure UniProtKB/Swiss-Prot converted to UNIPROT
433 ref.setSource(DBRefUtils.getCanonicalName(ref.getSource()));
434 if (ref.getSource().equals(DBRefSource.UNIPROT))
436 String proteinSeqName = DBRefSource.UNIPROT + "|"
437 + ref.getAccessionId();
438 if (map != null && map.getTo() != null)
443 * two or more Uniprot xrefs for the same CDS -
444 * each needs a distinct Mapping (as to a different sequence)
446 map = new Mapping(map);
451 * try to locate the protein mapped to (possibly by a
452 * previous CDS feature)
454 SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
455 if (proteinSeq == null)
457 proteinSeq = new Sequence(proteinSeqName,
458 product.getSequenceAsString());
459 matcher.add(proteinSeq);
460 peptides.add(proteinSeq);
462 map.setTo(proteinSeq);
463 map.getTo().addDBRef(
464 new DBRefEntry(ref.getSource(), ref.getVersion(), ref
468 noProteinDbref = false;
472 DBRefEntry pref = new DBRefEntry(ref.getSource(),
473 ref.getVersion(), ref.getAccessionId());
474 pref.setMap(null); // reference is direct
475 product.addDBRef(pref);
476 // Add converse mapping reference
479 Mapping pmap = new Mapping(dna, map.getMap().getInverse());
480 pref = new DBRefEntry(sourceDb, getSequenceVersion(),
481 this.getAccession());
483 if (map.getTo() != null)
485 map.getTo().addDBRef(pref);
491 if (noProteinDbref && product != null)
493 // add protein coding reference to dna sequence so xref matches
494 if (protEMBLCDS == null)
496 protEMBLCDS = new DBRefEntry();
497 protEMBLCDS.setAccessionId(prid);
498 protEMBLCDS.setSource(DBRefSource.EMBLCDSProduct);
499 protEMBLCDS.setVersion(getSequenceVersion());
501 .setMap(new Mapping(product, map.getMap().getInverse()));
503 product.addDBRef(protEMBLCDS);
505 // Add converse mapping reference
508 Mapping pmap = new Mapping(product, protEMBLCDS.getMap().getMap()
510 DBRefEntry ncMap = new DBRefEntry(protEMBLCDS);
512 if (map.getTo() != null)
522 * Helper method to construct a SequenceFeature for one cds range
525 * array of cds [start, end, ...] positions
526 * @param exonStartIndex
527 * offset into the exons array
529 * @param proteinAccessionId
531 * map of 'miscellaneous values' for feature
533 * codon start position for CDS (1/2/3, normally 1)
536 protected SequenceFeature makeCdsFeature(int[] exons, int exonStartIndex,
537 String proteinName, String proteinAccessionId,
538 Map<String, String> vals, int codonStart)
540 int exonNumber = exonStartIndex / 2 + 1;
541 SequenceFeature sf = new SequenceFeature();
542 sf.setBegin(Math.min(exons[exonStartIndex], exons[exonStartIndex + 1]));
543 sf.setEnd(Math.max(exons[exonStartIndex], exons[exonStartIndex + 1]));
544 sf.setDescription(String.format("Exon %d for protein '%s' EMBLCDS:%s",
545 exonNumber, proteinName, proteinAccessionId));
546 sf.setPhase(String.valueOf(codonStart - 1));
547 sf.setStrand(exons[exonStartIndex] <= exons[exonStartIndex + 1] ? "+"
549 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
550 sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
553 StringBuilder sb = new StringBuilder();
554 boolean first = true;
555 for (Entry<String, String> val : vals.entrySet())
561 sb.append(val.getKey()).append("=").append(val.getValue());
563 sf.setValue(val.getKey(), val.getValue());
565 sf.setAttributes(sb.toString());
571 * Returns the CDS positions as a single array of [start, end, start, end...]
572 * positions. If on the reverse strand, these will be in descending order.
577 protected int[] getCdsRanges(EmblFeature feature)
579 if (feature.location == null)
586 List<int[]> ranges = DnaUtils.parseLocation(feature.location);
587 return listToArray(ranges);
588 } catch (ParseException e)
590 Cache.log.warn(String.format(
591 "Not parsing inexact CDS location %s in ENA %s",
592 feature.location, this.accession));
598 * Converts a list of [start, end] ranges to a single array of [start, end,
604 int[] listToArray(List<int[]> ranges)
606 int[] result = new int[ranges.size() * 2];
608 for (int[] range : ranges)
610 result[i++] = range[0];
611 result[i++] = range[1];
617 * truncate the last exon interval to the prlength'th codon
623 static int[] adjustForProteinLength(int prlength, int[] exon)
625 if (prlength <= 0 || exon == null)
629 int desiredCdsLength = prlength * 3;
630 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
633 * assuming here exon might include stop codon in addition to protein codons
635 if (desiredCdsLength == exonLength
636 || desiredCdsLength == exonLength - 3)
644 origxon = new int[exon.length];
645 System.arraycopy(exon, 0, origxon, 0, exon.length);
647 for (int x = 0; x < exon.length; x += 2)
649 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
650 if (desiredCdsLength <= cdspos)
652 // advanced beyond last codon.
654 if (desiredCdsLength != cdspos)
657 // .println("Truncating final exon interval on region by "
658 // + (cdspos - cdslength));
662 * shrink the final exon - reduce end position if forward
663 * strand, increase it if reverse
665 if (exon[x + 1] >= exon[x])
667 endxon = exon[x + 1] - cdspos + desiredCdsLength;
671 endxon = exon[x + 1] + cdspos - desiredCdsLength;
679 // and trim the exon interval set if necessary
680 int[] nxon = new int[sxpos + 2];
681 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
682 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
689 public String getSequenceVersion()
691 return sequenceVersion;
694 public void setSequenceVersion(String sequenceVersion)
696 this.sequenceVersion = sequenceVersion;
699 public String getSequenceLength()
701 return sequenceLength;
704 public void setSequenceLength(String sequenceLength)
706 this.sequenceLength = sequenceLength;
709 public String getEntryVersion()
714 public void setEntryVersion(String entryVersion)
716 this.entryVersion = entryVersion;
719 public String getMoleculeType()
724 public void setMoleculeType(String moleculeType)
726 this.moleculeType = moleculeType;
729 public String getTopology()
734 public void setTopology(String topology)
736 this.topology = topology;
739 public String getTaxonomicDivision()
741 return taxonomicDivision;
744 public void setTaxonomicDivision(String taxonomicDivision)
746 this.taxonomicDivision = taxonomicDivision;
749 public String getDescription()
754 public void setDescription(String description)
756 this.description = description;
759 public String getFirstPublicDate()
761 return firstPublicDate;
764 public void setFirstPublicDate(String firstPublicDate)
766 this.firstPublicDate = firstPublicDate;
769 public String getFirstPublicRelease()
771 return firstPublicRelease;
774 public void setFirstPublicRelease(String firstPublicRelease)
776 this.firstPublicRelease = firstPublicRelease;
779 public String getLastUpdatedDate()
781 return lastUpdatedDate;
784 public void setLastUpdatedDate(String lastUpdatedDate)
786 this.lastUpdatedDate = lastUpdatedDate;
789 public String getLastUpdatedRelease()
791 return lastUpdatedRelease;
794 public void setLastUpdatedRelease(String lastUpdatedRelease)
796 this.lastUpdatedRelease = lastUpdatedRelease;
799 public String getDataClass()
804 public void setDataClass(String dataClass)
806 this.dataClass = dataClass;