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, getSequenceVersion(),
196 dna.addDBRef(retrievedref);
197 // add map to indicate the sequence is a valid coordinate frame for the
200 .setMap(new Mapping(null, new int[]
201 { 1, dna.getLength() }, new int[] { 1, dna.getLength() }, 1,
205 * transform EMBL Database refs to canonical form
209 for (DBRefEntry dbref : dbRefs)
211 dbref.setSource(DBRefUtils.getCanonicalName(dbref.getSource()));
216 SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
219 for (EmblFeature feature : features)
221 if (FeatureProperties.isCodingFeature(sourceDb, feature.getName()))
223 parseCodingFeature(feature, sourceDb, dna, peptides, matcher);
226 } catch (Exception e)
228 System.err.println("EMBL Record Features parsing error!");
230 .println("Please report the following to help@jalview.org :");
231 System.err.println("EMBL Record " + accession);
232 System.err.println("Resulted in exception: " + e.getMessage());
233 e.printStackTrace(System.err);
243 SequenceI makeSequence(String sourceDb)
245 if (sequence == null)
248 "No sequence was returned for ENA accession " + accession);
251 SequenceI dna = new Sequence(sourceDb + "|" + accession,
252 sequence.getSequence());
257 * Extracts coding region and product from a CDS feature and properly decorate
258 * it with annotations.
263 * source database for the EMBLXML
265 * parent dna sequence for this record
267 * list of protein product sequences for Embl entry
269 * helper to match xrefs in already retrieved sequences
271 void parseCodingFeature(EmblFeature feature, String sourceDb,
272 SequenceI dna, List<SequenceI> peptides,
273 SequenceIdMatcher matcher)
275 boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
277 int[] exons = getCdsRanges(feature);
279 String translation = null;
280 String proteinName = "";
281 String proteinId = null;
282 Map<String, String> vals = new Hashtable<>();
285 * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
286 * (phase is required for CDS features in GFF3 format)
291 * parse qualifiers, saving protein translation, protein id,
292 * codon start position, product (name), and 'other values'
294 if (feature.getQualifiers() != null)
296 for (Qualifier q : feature.getQualifiers())
298 String qname = q.getName();
299 if (qname.equals("translation"))
301 // remove all spaces (precompiled String.replaceAll(" ", ""))
302 translation = SPACE_PATTERN.matcher(q.getValues()[0])
305 else if (qname.equals("protein_id"))
307 proteinId = q.getValues()[0].trim();
309 else if (qname.equals("codon_start"))
313 codonStart = Integer.parseInt(q.getValues()[0].trim());
314 } catch (NumberFormatException e)
316 System.err.println("Invalid codon_start in XML for " + accession
317 + ": " + e.getMessage());
320 else if (qname.equals("product"))
322 // sometimes name is returned e.g. for V00488
323 proteinName = q.getValues()[0].trim();
327 // throw anything else into the additional properties hash
328 String[] qvals = q.getValues();
331 String commaSeparated = StringUtils.arrayToSeparatorList(qvals,
333 vals.put(qname, commaSeparated);
339 DBRefEntry proteinToEmblProteinRef = null;
340 exons = MappingUtils.removeStartPositions(codonStart - 1, exons);
342 SequenceI product = null;
343 Mapping dnaToProteinMapping = null;
344 if (translation != null && proteinName != null && proteinId != null)
346 int translationLength = translation.length();
349 * look for product in peptides list, if not found, add it
351 product = matcher.findIdMatch(proteinId);
354 product = new Sequence(proteinId, translation, 1,
356 product.setDescription(((proteinName.length() == 0)
357 ? "Protein Product from " + sourceDb
359 peptides.add(product);
360 matcher.add(product);
363 // we have everything - create the mapping and perhaps the protein
365 if (exons == null || exons.length == 0)
368 * workaround until we handle dna location for CDS sequence
369 * e.g. location="X53828.1:60..1058" correctly
372 "Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
373 + sourceDb + ":" + getAccession() + ")");
374 int dnaLength = dna.getLength();
375 if (translationLength * 3 == (1 - codonStart + dnaLength))
378 "Not allowing for additional stop codon at end of cDNA fragment... !");
379 // this might occur for CDS sequences where no features are marked
380 exons = new int[] { dna.getStart() + (codonStart - 1),
382 dnaToProteinMapping = new Mapping(product, exons,
384 { 1, translationLength }, 3, 1);
386 if ((translationLength + 1) * 3 == (1 - codonStart + dnaLength))
389 "Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
390 exons = new int[] { dna.getStart() + (codonStart - 1),
392 dnaToProteinMapping = new Mapping(product, exons,
394 { 1, translationLength }, 3, 1);
399 // Trim the exon mapping if necessary - the given product may only be a
400 // fragment of a larger protein. (EMBL:AY043181 is an example)
404 // TODO: Add a DbRef back to the parent EMBL sequence with the exon
406 // if given a dataset reference, search dataset for parent EMBL
407 // sequence if it exists and set its map
408 // make a new feature annotating the coding contig
412 // final product length truncation check
413 int[] cdsRanges = adjustForProteinLength(translationLength,
415 dnaToProteinMapping = new Mapping(product, cdsRanges,
417 { 1, translationLength }, 3, 1);
421 * make xref with mapping from protein to EMBL dna
423 DBRefEntry proteinToEmblRef = new DBRefEntry(DBRefSource.EMBL,
424 getSequenceVersion(), proteinId,
425 new Mapping(dnaToProteinMapping.getMap().getInverse()));
426 product.addDBRef(proteinToEmblRef);
429 * make xref from protein to EMBLCDS; we assume here that the
430 * CDS sequence version is same as dna sequence (?!)
432 MapList proteinToCdsMapList = new MapList(
434 { 1, translationLength },
436 { 1 + (codonStart - 1),
437 (codonStart - 1) + 3 * translationLength },
439 DBRefEntry proteinToEmblCdsRef = new DBRefEntry(
440 DBRefSource.EMBLCDS, getSequenceVersion(), proteinId,
441 new Mapping(proteinToCdsMapList));
442 product.addDBRef(proteinToEmblCdsRef);
445 * make 'direct' xref from protein to EMBLCDSPROTEIN
447 proteinToEmblProteinRef = new DBRefEntry(proteinToEmblCdsRef);
448 proteinToEmblProteinRef.setSource(DBRefSource.EMBLCDSProduct);
449 proteinToEmblProteinRef.setMap(null);
450 product.addDBRef(proteinToEmblProteinRef);
456 * add cds features to dna sequence
458 String cds = feature.getName(); // "CDS"
459 for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
461 int exonStart = exons[xint];
462 int exonEnd = exons[xint + 1];
463 int begin = Math.min(exonStart, exonEnd);
464 int end = Math.max(exonStart, exonEnd);
465 int exonNumber = xint / 2 + 1;
466 String desc = String.format("Exon %d for protein '%s' EMBLCDS:%s",
467 exonNumber, proteinName, proteinId);
469 SequenceFeature sf = makeCdsFeature(cds, desc, begin, end,
472 sf.setEnaLocation(feature.getLocation());
473 boolean forwardStrand = exonStart <= exonEnd;
474 sf.setStrand(forwardStrand ? "+" : "-");
475 sf.setPhase(String.valueOf(codonStart - 1));
476 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
477 sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
479 dna.addSequenceFeature(sf);
484 * add feature dbRefs to sequence, and mappings for Uniprot xrefs
486 boolean hasUniprotDbref = false;
487 if (feature.dbRefs != null)
489 boolean mappingUsed = false;
490 for (DBRefEntry ref : feature.dbRefs)
493 * ensure UniProtKB/Swiss-Prot converted to UNIPROT
495 String source = DBRefUtils.getCanonicalName(ref.getSource());
496 ref.setSource(source);
497 DBRefEntry proteinDbRef = new DBRefEntry(ref.getSource(),
498 ref.getVersion(), ref.getAccessionId());
499 if (source.equals(DBRefSource.UNIPROT))
501 String proteinSeqName = DBRefSource.UNIPROT + "|"
502 + ref.getAccessionId();
503 if (dnaToProteinMapping != null
504 && dnaToProteinMapping.getTo() != null)
509 * two or more Uniprot xrefs for the same CDS -
510 * each needs a distinct Mapping (as to a different sequence)
512 dnaToProteinMapping = new Mapping(dnaToProteinMapping);
517 * try to locate the protein mapped to (possibly by a
518 * previous CDS feature); if not found, construct it from
519 * the EMBL translation
521 SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
522 if (proteinSeq == null)
524 proteinSeq = new Sequence(proteinSeqName,
525 product.getSequenceAsString());
526 matcher.add(proteinSeq);
527 peptides.add(proteinSeq);
529 dnaToProteinMapping.setTo(proteinSeq);
530 dnaToProteinMapping.setMappedFromId(proteinId);
531 proteinSeq.addDBRef(proteinDbRef);
532 ref.setMap(dnaToProteinMapping);
534 hasUniprotDbref = true;
539 * copy feature dbref to our protein product
541 DBRefEntry pref = proteinDbRef;
542 pref.setMap(null); // reference is direct
543 product.addDBRef(pref);
544 // Add converse mapping reference
545 if (dnaToProteinMapping != null)
547 Mapping pmap = new Mapping(dna,
548 dnaToProteinMapping.getMap().getInverse());
549 pref = new DBRefEntry(sourceDb, getSequenceVersion(),
550 this.getAccession());
552 if (dnaToProteinMapping.getTo() != null)
554 dnaToProteinMapping.getTo().addDBRef(pref);
563 * if we have a product (translation) but no explicit Uniprot dbref
564 * (example: EMBL AAFI02000057 protein_id EAL65544.1)
565 * then construct mappings to an assumed EMBLCDSPROTEIN accession
567 if (!hasUniprotDbref && product != null)
569 if (proteinToEmblProteinRef == null)
571 // assuming CDSPROTEIN sequence version = dna version (?!)
572 proteinToEmblProteinRef = new DBRefEntry(DBRefSource.EMBLCDSProduct,
573 getSequenceVersion(), proteinId);
575 product.addDBRef(proteinToEmblProteinRef);
577 if (dnaToProteinMapping != null
578 && dnaToProteinMapping.getTo() != null)
580 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
581 DBRefSource.EMBLCDSProduct, getSequenceVersion(),
583 dnaToEmblProteinRef.setMap(dnaToProteinMapping);
584 dnaToProteinMapping.setMappedFromId(proteinId);
585 dna.addDBRef(dnaToEmblProteinRef);
591 * Helper method to construct a SequenceFeature for one cds range
594 * feature type ("CDS")
604 * map of 'miscellaneous values' for feature
607 protected SequenceFeature makeCdsFeature(String type, String desc,
608 int begin, int end, String group, Map<String, String> vals)
610 SequenceFeature sf = new SequenceFeature(type, desc, begin, end, group);
613 StringBuilder sb = new StringBuilder();
614 boolean first = true;
615 for (Entry<String, String> val : vals.entrySet())
621 sb.append(val.getKey()).append("=").append(val.getValue());
623 sf.setValue(val.getKey(), val.getValue());
625 sf.setAttributes(sb.toString());
631 * Returns the CDS positions as a single array of [start, end, start, end...]
632 * positions. If on the reverse strand, these will be in descending order.
637 protected int[] getCdsRanges(EmblFeature feature)
639 if (feature.location == null)
646 List<int[]> ranges = DnaUtils.parseLocation(feature.location);
647 return listToArray(ranges);
648 } catch (ParseException e)
651 String.format("Not parsing inexact CDS location %s in ENA %s",
652 feature.location, this.accession));
658 * Converts a list of [start, end] ranges to a single array of [start, end,
664 int[] listToArray(List<int[]> ranges)
666 int[] result = new int[ranges.size() * 2];
668 for (int[] range : ranges)
670 result[i++] = range[0];
671 result[i++] = range[1];
677 * Truncates (if necessary) the exon intervals to match 3 times the length of
678 * the protein; also accepts 3 bases longer (for stop codon not included in
681 * @param proteinLength
683 * an array of [start, end, start, end...] intervals
684 * @return the same array (if unchanged) or a truncated copy
686 static int[] adjustForProteinLength(int proteinLength, int[] exon)
688 if (proteinLength <= 0 || exon == null)
692 int expectedCdsLength = proteinLength * 3;
693 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
696 * if exon length matches protein, or is shorter, or longer by the
697 * length of a stop codon (3 bases), then leave it unchanged
699 if (expectedCdsLength >= exonLength
700 || expectedCdsLength == exonLength - 3)
708 origxon = new int[exon.length];
709 System.arraycopy(exon, 0, origxon, 0, exon.length);
711 for (int x = 0; x < exon.length; x += 2)
713 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
714 if (expectedCdsLength <= cdspos)
716 // advanced beyond last codon.
718 if (expectedCdsLength != cdspos)
721 // .println("Truncating final exon interval on region by "
722 // + (cdspos - cdslength));
726 * shrink the final exon - reduce end position if forward
727 * strand, increase it if reverse
729 if (exon[x + 1] >= exon[x])
731 endxon = exon[x + 1] - cdspos + expectedCdsLength;
735 endxon = exon[x + 1] + cdspos - expectedCdsLength;
743 // and trim the exon interval set if necessary
744 int[] nxon = new int[sxpos + 2];
745 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
746 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
753 public String getSequenceVersion()
755 return sequenceVersion;
758 public void setSequenceVersion(String sequenceVersion)
760 this.sequenceVersion = sequenceVersion;
763 public String getSequenceLength()
765 return sequenceLength;
768 public void setSequenceLength(String sequenceLength)
770 this.sequenceLength = sequenceLength;
773 public String getEntryVersion()
778 public void setEntryVersion(String entryVersion)
780 this.entryVersion = entryVersion;
783 public String getMoleculeType()
788 public void setMoleculeType(String moleculeType)
790 this.moleculeType = moleculeType;
793 public String getTopology()
798 public void setTopology(String topology)
800 this.topology = topology;
803 public String getTaxonomicDivision()
805 return taxonomicDivision;
808 public void setTaxonomicDivision(String taxonomicDivision)
810 this.taxonomicDivision = taxonomicDivision;
813 public String getDescription()
818 public void setDescription(String description)
820 this.description = description;
823 public String getFirstPublicDate()
825 return firstPublicDate;
828 public void setFirstPublicDate(String firstPublicDate)
830 this.firstPublicDate = firstPublicDate;
833 public String getFirstPublicRelease()
835 return firstPublicRelease;
838 public void setFirstPublicRelease(String firstPublicRelease)
840 this.firstPublicRelease = firstPublicRelease;
843 public String getLastUpdatedDate()
845 return lastUpdatedDate;
848 public void setLastUpdatedDate(String lastUpdatedDate)
850 this.lastUpdatedDate = lastUpdatedDate;
853 public String getLastUpdatedRelease()
855 return lastUpdatedRelease;
858 public void setLastUpdatedRelease(String lastUpdatedRelease)
860 this.lastUpdatedRelease = lastUpdatedRelease;
863 public String getDataClass()
868 public void setDataClass(String dataClass)
870 this.dataClass = dataClass;