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
51 * For example: http://www.ebi.ac.uk/ena/data/view/J03321&display=xml
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 = makeSequence(sourceDb);
193 dna.setDescription(description);
194 DBRefEntry retrievedref = new DBRefEntry(sourceDb,
195 getSequenceVersion(), accession);
196 dna.addDBRef(retrievedref);
197 // add map to indicate the sequence is a valid coordinate frame for the
199 retrievedref.setMap(new Mapping(null, new int[] { 1, dna.getLength() },
200 new int[] { 1, dna.getLength() }, 1, 1));
203 * transform EMBL Database refs to canonical form
207 for (DBRefEntry dbref : dbRefs)
209 dbref.setSource(DBRefUtils.getCanonicalName(dbref.getSource()));
214 SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
217 for (EmblFeature feature : features)
219 if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
221 parseCodingFeature(feature, sourceDb, dna, peptides, matcher);
224 } catch (Exception e)
226 System.err.println("EMBL Record Features parsing error!");
228 .println("Please report the following to help@jalview.org :");
229 System.err.println("EMBL Record " + accession);
230 System.err.println("Resulted in exception: " + e.getMessage());
231 e.printStackTrace(System.err);
241 SequenceI makeSequence(String sourceDb)
243 if (sequence == null)
245 System.err.println("No sequence was returned for ENA accession "
249 SequenceI dna = new Sequence(sourceDb + "|" + accession,
250 sequence.getSequence());
255 * Extracts coding region and product from a CDS feature and properly decorate
256 * it with annotations.
261 * source database for the EMBLXML
263 * parent dna sequence for this record
265 * list of protein product sequences for Embl entry
267 * helper to match xrefs in already retrieved sequences
269 void parseCodingFeature(EmblFeature feature, String sourceDb,
270 SequenceI dna, List<SequenceI> peptides, SequenceIdMatcher matcher)
272 boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
274 int[] exons = getCdsRanges(feature);
276 String translation = null;
277 String proteinName = "";
278 String proteinId = null;
279 Map<String, String> vals = new Hashtable<String, String>();
282 * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
283 * (phase is required for CDS features in GFF3 format)
288 * parse qualifiers, saving protein translation, protein id,
289 * codon start position, product (name), and 'other values'
291 if (feature.getQualifiers() != null)
293 for (Qualifier q : feature.getQualifiers())
295 String qname = q.getName();
296 if (qname.equals("translation"))
298 // remove all spaces (precompiled String.replaceAll(" ", ""))
299 translation = SPACE_PATTERN.matcher(q.getValues()[0]).replaceAll(
302 else if (qname.equals("protein_id"))
304 proteinId = q.getValues()[0].trim();
306 else if (qname.equals("codon_start"))
310 codonStart = Integer.parseInt(q.getValues()[0].trim());
311 } catch (NumberFormatException e)
313 System.err.println("Invalid codon_start in XML for "
314 + accession + ": " + e.getMessage());
317 else if (qname.equals("product"))
319 // sometimes name is returned e.g. for V00488
320 proteinName = q.getValues()[0].trim();
324 // throw anything else into the additional properties hash
325 String[] qvals = q.getValues();
328 String commaSeparated = StringUtils.arrayToSeparatorList(qvals,
330 vals.put(qname, commaSeparated);
336 DBRefEntry proteinToEmblProteinRef = null;
337 exons = MappingUtils.removeStartPositions(codonStart - 1, exons);
339 SequenceI product = null;
340 Mapping dnaToProteinMapping = null;
341 if (translation != null && proteinName != null && proteinId != null)
343 int translationLength = translation.length();
346 * look for product in peptides list, if not found, add it
348 product = matcher.findIdMatch(proteinId);
351 product = new Sequence(proteinId, translation, 1, translationLength);
352 product.setDescription(((proteinName.length() == 0) ? "Protein Product from "
355 peptides.add(product);
356 matcher.add(product);
359 // we have everything - create the mapping and perhaps the protein
361 if (exons == null || exons.length == 0)
364 * workaround until we handle dna location for CDS sequence
365 * e.g. location="X53828.1:60..1058" correctly
368 .println("Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
369 + sourceDb + ":" + getAccession() + ")");
370 if (translationLength * 3 == (1 - codonStart + dna.getSequence().length))
373 .println("Not allowing for additional stop codon at end of cDNA fragment... !");
374 // this might occur for CDS sequences where no features are marked
375 exons = new int[] { dna.getStart() + (codonStart - 1),
377 dnaToProteinMapping = new Mapping(product, exons, new int[] { 1,
378 translationLength }, 3, 1);
380 if ((translationLength + 1) * 3 == (1 - codonStart + dna
381 .getSequence().length))
384 .println("Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
385 exons = new int[] { dna.getStart() + (codonStart - 1),
387 dnaToProteinMapping = new Mapping(product, exons, new int[] { 1,
388 translationLength }, 3, 1);
393 // Trim the exon mapping if necessary - the given product may only be a
394 // fragment of a larger protein. (EMBL:AY043181 is an example)
398 // TODO: Add a DbRef back to the parent EMBL sequence with the exon
400 // if given a dataset reference, search dataset for parent EMBL
401 // sequence if it exists and set its map
402 // make a new feature annotating the coding contig
406 // final product length truncation check
407 int[] cdsRanges = adjustForProteinLength(translationLength, exons);
408 dnaToProteinMapping = new Mapping(product, cdsRanges, new int[] {
409 1, translationLength }, 3, 1);
413 * make xref with mapping from protein to EMBL dna
415 DBRefEntry proteinToEmblRef = new DBRefEntry(DBRefSource.EMBL,
416 getSequenceVersion(), proteinId, new Mapping(
417 dnaToProteinMapping.getMap().getInverse()));
418 product.addDBRef(proteinToEmblRef);
421 * make xref from protein to EMBLCDS; we assume here that the
422 * CDS sequence version is same as dna sequence (?!)
424 MapList proteinToCdsMapList = new MapList(new int[] { 1,
425 translationLength }, new int[] { 1 + (codonStart - 1),
426 (codonStart - 1) + 3 * translationLength }, 1, 3);
427 DBRefEntry proteinToEmblCdsRef = new DBRefEntry(
428 DBRefSource.EMBLCDS, getSequenceVersion(), proteinId,
429 new Mapping(proteinToCdsMapList));
430 product.addDBRef(proteinToEmblCdsRef);
433 * make 'direct' xref from protein to EMBLCDSPROTEIN
435 proteinToEmblProteinRef = new DBRefEntry(proteinToEmblCdsRef);
436 proteinToEmblProteinRef.setSource(DBRefSource.EMBLCDSProduct);
437 proteinToEmblProteinRef.setMap(null);
438 product.addDBRef(proteinToEmblProteinRef);
444 * add cds features to dna sequence
446 String cds = feature.getName(); // "CDS"
447 for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
449 int exonStart = exons[xint];
450 int exonEnd = exons[xint + 1];
451 int begin = Math.min(exonStart, exonEnd);
452 int end = Math.max(exonStart, exonEnd);
453 int exonNumber = xint / 2 + 1;
454 String desc = String.format("Exon %d for protein '%s' EMBLCDS:%s",
455 exonNumber, proteinName, proteinId);
457 SequenceFeature sf = makeCdsFeature(cds, desc, begin, end,
460 sf.setEnaLocation(feature.getLocation());
461 boolean forwardStrand = exonStart <= exonEnd;
462 sf.setStrand(forwardStrand ? "+" : "-");
463 sf.setPhase(String.valueOf(codonStart - 1));
464 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
465 sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
467 dna.addSequenceFeature(sf);
472 * add feature dbRefs to sequence, and mappings for Uniprot xrefs
474 boolean hasUniprotDbref = false;
475 if (feature.dbRefs != null)
477 boolean mappingUsed = false;
478 for (DBRefEntry ref : feature.dbRefs)
481 * ensure UniProtKB/Swiss-Prot converted to UNIPROT
483 String source = DBRefUtils.getCanonicalName(ref.getSource());
484 ref.setSource(source);
485 DBRefEntry proteinDbRef = new DBRefEntry(ref.getSource(),
486 ref.getVersion(), ref.getAccessionId());
487 if (source.equals(DBRefSource.UNIPROT))
489 String proteinSeqName = DBRefSource.UNIPROT + "|"
490 + ref.getAccessionId();
491 if (dnaToProteinMapping != null
492 && dnaToProteinMapping.getTo() != null)
497 * two or more Uniprot xrefs for the same CDS -
498 * each needs a distinct Mapping (as to a different sequence)
500 dnaToProteinMapping = new Mapping(dnaToProteinMapping);
505 * try to locate the protein mapped to (possibly by a
506 * previous CDS feature); if not found, construct it from
507 * the EMBL translation
509 SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
510 if (proteinSeq == null)
512 proteinSeq = new Sequence(proteinSeqName,
513 product.getSequenceAsString());
514 matcher.add(proteinSeq);
515 peptides.add(proteinSeq);
517 dnaToProteinMapping.setTo(proteinSeq);
518 dnaToProteinMapping.setMappedFromId(proteinId);
519 proteinSeq.addDBRef(proteinDbRef);
520 ref.setMap(dnaToProteinMapping);
522 hasUniprotDbref = true;
527 * copy feature dbref to our protein product
529 DBRefEntry pref = proteinDbRef;
530 pref.setMap(null); // reference is direct
531 product.addDBRef(pref);
532 // Add converse mapping reference
533 if (dnaToProteinMapping != null)
535 Mapping pmap = new Mapping(dna, dnaToProteinMapping.getMap()
537 pref = new DBRefEntry(sourceDb, getSequenceVersion(),
538 this.getAccession());
540 if (dnaToProteinMapping.getTo() != null)
542 dnaToProteinMapping.getTo().addDBRef(pref);
551 * if we have a product (translation) but no explicit Uniprot dbref
552 * (example: EMBL AAFI02000057 protein_id EAL65544.1)
553 * then construct mappings to an assumed EMBLCDSPROTEIN accession
555 if (!hasUniprotDbref && product != null)
557 if (proteinToEmblProteinRef == null)
559 // assuming CDSPROTEIN sequence version = dna version (?!)
560 proteinToEmblProteinRef = new DBRefEntry(
561 DBRefSource.EMBLCDSProduct, getSequenceVersion(), proteinId);
563 product.addDBRef(proteinToEmblProteinRef);
565 if (dnaToProteinMapping != null
566 && dnaToProteinMapping.getTo() != null)
568 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
569 DBRefSource.EMBLCDSProduct, getSequenceVersion(), proteinId);
570 dnaToEmblProteinRef.setMap(dnaToProteinMapping);
571 dnaToProteinMapping.setMappedFromId(proteinId);
572 dna.addDBRef(dnaToEmblProteinRef);
578 * Helper method to construct a SequenceFeature for one cds range
581 * feature type ("CDS")
591 * map of 'miscellaneous values' for feature
594 protected SequenceFeature makeCdsFeature(String type, String desc,
595 int begin, int end, String group, Map<String, String> vals)
597 SequenceFeature sf = new SequenceFeature(type, desc, begin, end,
602 StringBuilder sb = new StringBuilder();
603 boolean first = true;
604 for (Entry<String, String> val : vals.entrySet())
610 sb.append(val.getKey()).append("=").append(val.getValue());
612 sf.setValue(val.getKey(), val.getValue());
614 sf.setAttributes(sb.toString());
620 * Returns the CDS positions as a single array of [start, end, start, end...]
621 * positions. If on the reverse strand, these will be in descending order.
626 protected int[] getCdsRanges(EmblFeature feature)
628 if (feature.location == null)
635 List<int[]> ranges = DnaUtils.parseLocation(feature.location);
636 return listToArray(ranges);
637 } catch (ParseException e)
639 Cache.log.warn(String.format(
640 "Not parsing inexact CDS location %s in ENA %s",
641 feature.location, this.accession));
647 * Converts a list of [start, end] ranges to a single array of [start, end,
653 int[] listToArray(List<int[]> ranges)
655 int[] result = new int[ranges.size() * 2];
657 for (int[] range : ranges)
659 result[i++] = range[0];
660 result[i++] = range[1];
666 * Truncates (if necessary) the exon intervals to match 3 times the length of
667 * the protein; also accepts 3 bases longer (for stop codon not included in
670 * @param proteinLength
672 * an array of [start, end, start, end...] intervals
673 * @return the same array (if unchanged) or a truncated copy
675 static int[] adjustForProteinLength(int proteinLength, int[] exon)
677 if (proteinLength <= 0 || exon == null)
681 int expectedCdsLength = proteinLength * 3;
682 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
685 * if exon length matches protein, or is shorter, or longer by the
686 * length of a stop codon (3 bases), then leave it unchanged
688 if (expectedCdsLength >= exonLength
689 || expectedCdsLength == exonLength - 3)
697 origxon = new int[exon.length];
698 System.arraycopy(exon, 0, origxon, 0, exon.length);
700 for (int x = 0; x < exon.length; x += 2)
702 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
703 if (expectedCdsLength <= cdspos)
705 // advanced beyond last codon.
707 if (expectedCdsLength != cdspos)
710 // .println("Truncating final exon interval on region by "
711 // + (cdspos - cdslength));
715 * shrink the final exon - reduce end position if forward
716 * strand, increase it if reverse
718 if (exon[x + 1] >= exon[x])
720 endxon = exon[x + 1] - cdspos + expectedCdsLength;
724 endxon = exon[x + 1] + cdspos - expectedCdsLength;
732 // and trim the exon interval set if necessary
733 int[] nxon = new int[sxpos + 2];
734 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
735 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
742 public String getSequenceVersion()
744 return sequenceVersion;
747 public void setSequenceVersion(String sequenceVersion)
749 this.sequenceVersion = sequenceVersion;
752 public String getSequenceLength()
754 return sequenceLength;
757 public void setSequenceLength(String sequenceLength)
759 this.sequenceLength = sequenceLength;
762 public String getEntryVersion()
767 public void setEntryVersion(String entryVersion)
769 this.entryVersion = entryVersion;
772 public String getMoleculeType()
777 public void setMoleculeType(String moleculeType)
779 this.moleculeType = moleculeType;
782 public String getTopology()
787 public void setTopology(String topology)
789 this.topology = topology;
792 public String getTaxonomicDivision()
794 return taxonomicDivision;
797 public void setTaxonomicDivision(String taxonomicDivision)
799 this.taxonomicDivision = taxonomicDivision;
802 public String getDescription()
807 public void setDescription(String description)
809 this.description = description;
812 public String getFirstPublicDate()
814 return firstPublicDate;
817 public void setFirstPublicDate(String firstPublicDate)
819 this.firstPublicDate = firstPublicDate;
822 public String getFirstPublicRelease()
824 return firstPublicRelease;
827 public void setFirstPublicRelease(String firstPublicRelease)
829 this.firstPublicRelease = firstPublicRelease;
832 public String getLastUpdatedDate()
834 return lastUpdatedDate;
837 public void setLastUpdatedDate(String lastUpdatedDate)
839 this.lastUpdatedDate = lastUpdatedDate;
842 public String getLastUpdatedRelease()
844 return lastUpdatedRelease;
847 public void setLastUpdatedRelease(String lastUpdatedRelease)
849 this.lastUpdatedRelease = lastUpdatedRelease;
852 public String getDataClass()
857 public void setDataClass(String dataClass)
859 this.dataClass = dataClass;