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.ws.dbsources;
23 import java.util.Locale;
26 import java.io.FileInputStream;
27 import java.io.InputStream;
28 import java.text.ParseException;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Hashtable;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import javax.xml.bind.JAXBContext;
37 import javax.xml.bind.JAXBElement;
38 import javax.xml.bind.JAXBException;
39 import javax.xml.stream.FactoryConfigurationError;
40 import javax.xml.stream.XMLInputFactory;
41 import javax.xml.stream.XMLStreamException;
42 import javax.xml.stream.XMLStreamReader;
44 import jalview.analysis.SequenceIdMatcher;
45 import jalview.bin.Cache;
46 import jalview.datamodel.Alignment;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.DBRefEntry;
49 import jalview.datamodel.DBRefSource;
50 import jalview.datamodel.FeatureProperties;
51 import jalview.datamodel.Mapping;
52 import jalview.datamodel.Sequence;
53 import jalview.datamodel.SequenceFeature;
54 import jalview.datamodel.SequenceI;
55 import jalview.util.DBRefUtils;
56 import jalview.util.DnaUtils;
57 import jalview.util.MapList;
58 import jalview.util.MappingUtils;
59 import jalview.util.MessageManager;
60 import jalview.ws.ebi.EBIFetchClient;
61 import jalview.xml.binding.embl.EntryType;
62 import jalview.xml.binding.embl.EntryType.Feature;
63 import jalview.xml.binding.embl.EntryType.Feature.Qualifier;
64 import jalview.xml.binding.embl.ROOT;
65 import jalview.xml.binding.embl.XrefType;
68 * Provides XML binding and parsing of EMBL or EMBLCDS records retrieved from
69 * (e.g.) {@code https://www.ebi.ac.uk/ena/data/view/x53828&display=xml}.
71 * @deprecated endpoint withdrawn August 2020 (JAL-3692), use EmblFlatfileSource
74 public abstract class EmblXmlSource extends EbiFileRetrievedProxy
76 // TODO: delete class or update tyhis validator for 2.12 style Platform.regex
77 private static final Regex ACCESSION_REGEX = new Regex("^[A-Z]+[0-9]+");
79 * JAL-1856 Embl returns this text for query not found
81 private static final String EMBL_NOT_FOUND_REPLY = "ERROR 12 No entries found.";
83 public EmblXmlSource()
89 * Retrieves and parses an emblxml file, and returns an alignment containing
90 * the parsed sequences, or null if none were found
93 * "EMBL" or "EMBLCDS" - anything else will not retrieve emblxml
98 protected AlignmentI getEmblSequenceRecords(String emprefx, String query)
102 EBIFetchClient dbFetch = new EBIFetchClient();
106 reply = dbFetch.fetchDataAsFile(
107 emprefx.toLowerCase(Locale.ROOT) + ":" + query.trim(), "display=xml",
109 } catch (Exception e)
113 String.format("EBI EMBL XML retrieval failed for %s:%s",
114 emprefx.toLowerCase(Locale.ROOT), query.trim()),
117 return getEmblSequenceRecords(emprefx, query, reply);
121 * parse an emblxml file stored locally
124 * either EMBL or EMBLCDS strings are allowed - anything else will
125 * not retrieve emblxml
128 * the EMBL XML file containing the results of a query
132 protected AlignmentI getEmblSequenceRecords(String emprefx, String query,
133 File reply) throws Exception
135 List<EntryType> entries = null;
136 if (reply != null && reply.exists())
138 file = reply.getAbsolutePath();
139 if (reply.length() > EMBL_NOT_FOUND_REPLY.length())
141 InputStream is = new FileInputStream(reply);
142 entries = getEmblEntries(is);
147 * invalid accession gets a reply with no <entry> elements, text content of
148 * EmbFile reads something like (e.g.) this ungrammatical phrase
149 * Entry: <acc> display type is either not supported or entry is not found.
151 AlignmentI al = null;
152 List<SequenceI> seqs = new ArrayList<>();
153 List<SequenceI> peptides = new ArrayList<>();
156 for (EntryType entry : entries)
158 SequenceI seq = getSequence(emprefx, entry, peptides);
161 seqs.add(seq.deriveSequence());
162 // place DBReferences on dataset and refer
167 al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
172 "No record found for '" + emprefx + ":" + query + "'");
181 * Reads the XML reply from file and unmarshals it to Java objects. Answers a
182 * (possibly empty) list of <code>EntryType</code> objects.
188 List<EntryType> getEmblEntries(InputStream is)
190 List<EntryType> entries = new ArrayList<>();
193 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.embl");
194 XMLStreamReader streamReader = XMLInputFactory.newInstance()
195 .createXMLStreamReader(is);
196 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
197 JAXBElement<ROOT> rootElement = um.unmarshal(streamReader,
199 ROOT root = rootElement.getValue();
202 * document root contains either "entry" or "entrySet"
208 if (root.getEntrySet() != null)
210 entries = root.getEntrySet().getEntry();
212 else if (root.getEntry() != null)
214 entries.add(root.getEntry());
216 } catch (JAXBException | XMLStreamException
217 | FactoryConfigurationError e)
225 * A helper method to parse XML data and construct a sequence, with any
226 * available database references and features
233 SequenceI getSequence(String sourceDb, EntryType entry,
234 List<SequenceI> peptides)
236 String seqString = entry.getSequence();
237 if (seqString == null)
241 seqString = seqString.replace(" ", "").replace("\n", "").replace("\t",
243 String accession = entry.getAccession();
244 SequenceI dna = new Sequence(sourceDb + "|" + accession, seqString);
246 dna.setDescription(entry.getDescription());
247 String sequenceVersion = String.valueOf(entry.getVersion().intValue());
248 DBRefEntry selfRref = new DBRefEntry(sourceDb, sequenceVersion,
250 dna.addDBRef(selfRref);
252 new Mapping(null, new int[]
253 { 1, dna.getLength() }, new int[] { 1, dna.getLength() }, 1,
259 List<XrefType> xrefs = entry.getXref();
262 for (XrefType xref : xrefs)
264 String acc = xref.getId();
265 String source = DBRefUtils.getCanonicalName(xref.getDb());
266 String version = xref.getSecondaryId();
267 if (version == null || "".equals(version))
271 dna.addDBRef(new DBRefEntry(source, version, acc));
275 SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
278 List<Feature> features = entry.getFeature();
279 if (features != null)
281 for (Feature feature : features)
283 if (FeatureProperties.isCodingFeature(sourceDb,
286 parseCodingFeature(entry, feature, sourceDb, dna, peptides,
291 } catch (Exception e)
293 System.err.println("EMBL Record Features parsing error!");
295 .println("Please report the following to help@jalview.org :");
296 System.err.println("EMBL Record " + accession);
297 System.err.println("Resulted in exception: " + e.getMessage());
298 e.printStackTrace(System.err);
305 * Extracts coding region and product from a CDS feature and decorates it with
315 void parseCodingFeature(EntryType entry, Feature feature, String sourceDb,
316 SequenceI dna, List<SequenceI> peptides,
317 SequenceIdMatcher matcher)
319 final boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
320 final String accession = entry.getAccession();
321 final String sequenceVersion = entry.getVersion().toString();
323 int[] exons = getCdsRanges(entry.getAccession(), feature);
325 String translation = null;
326 String proteinName = "";
327 String proteinId = null;
328 Map<String, String> vals = new Hashtable<>();
331 * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
332 * (phase is required for CDS features in GFF3 format)
337 * parse qualifiers, saving protein translation, protein id,
338 * codon start position, product (name), and 'other values'
340 if (feature.getQualifier() != null)
342 for (Qualifier q : feature.getQualifier())
344 String qname = q.getName();
345 String value = q.getValue();
346 value = value == null ? ""
347 : value.trim().replace(" ", "").replace("\n", "")
349 if (qname.equals("translation"))
353 else if (qname.equals("protein_id"))
357 else if (qname.equals("codon_start"))
361 codonStart = Integer.parseInt(value.trim());
362 } catch (NumberFormatException e)
364 System.err.println("Invalid codon_start in XML for "
365 + entry.getAccession() + ": " + e.getMessage());
368 else if (qname.equals("product"))
370 // sometimes name is returned e.g. for V00488
375 // throw anything else into the additional properties hash
376 if (!"".equals(value))
378 vals.put(qname, value);
384 DBRefEntry proteinToEmblProteinRef = null;
385 exons = MappingUtils.removeStartPositions(codonStart - 1, exons);
387 SequenceI product = null;
388 Mapping dnaToProteinMapping = null;
389 if (translation != null && proteinName != null && proteinId != null)
391 int translationLength = translation.length();
394 * look for product in peptides list, if not found, add it
396 product = matcher.findIdMatch(proteinId);
399 product = new Sequence(proteinId, translation, 1,
401 product.setDescription(((proteinName.length() == 0)
402 ? "Protein Product from " + sourceDb
404 peptides.add(product);
405 matcher.add(product);
408 // we have everything - create the mapping and perhaps the protein
410 if (exons == null || exons.length == 0)
413 * workaround until we handle dna location for CDS sequence
414 * e.g. location="X53828.1:60..1058" correctly
417 "Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
418 + sourceDb + ":" + entry.getAccession() + ")");
419 int dnaLength = dna.getLength();
420 if (translationLength * 3 == (1 - codonStart + dnaLength))
423 "Not allowing for additional stop codon at end of cDNA fragment... !");
424 // this might occur for CDS sequences where no features are marked
425 exons = new int[] { dna.getStart() + (codonStart - 1),
427 dnaToProteinMapping = new Mapping(product, exons,
429 { 1, translationLength }, 3, 1);
431 if ((translationLength + 1) * 3 == (1 - codonStart + dnaLength))
434 "Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
435 exons = new int[] { dna.getStart() + (codonStart - 1),
437 dnaToProteinMapping = new Mapping(product, exons,
439 { 1, translationLength }, 3, 1);
444 // Trim the exon mapping if necessary - the given product may only be a
445 // fragment of a larger protein. (EMBL:AY043181 is an example)
449 // TODO: Add a DbRef back to the parent EMBL sequence with the exon
451 // if given a dataset reference, search dataset for parent EMBL
452 // sequence if it exists and set its map
453 // make a new feature annotating the coding contig
457 // final product length truncation check
458 int[] cdsRanges = adjustForProteinLength(translationLength,
460 dnaToProteinMapping = new Mapping(product, cdsRanges,
462 { 1, translationLength }, 3, 1);
466 * make xref with mapping from protein to EMBL dna
468 DBRefEntry proteinToEmblRef = new DBRefEntry(DBRefSource.EMBL,
469 sequenceVersion, proteinId,
470 new Mapping(dnaToProteinMapping.getMap().getInverse()));
471 product.addDBRef(proteinToEmblRef);
474 * make xref from protein to EMBLCDS; we assume here that the
475 * CDS sequence version is same as dna sequence (?!)
477 MapList proteinToCdsMapList = new MapList(
479 { 1, translationLength },
481 { 1 + (codonStart - 1),
482 (codonStart - 1) + 3 * translationLength },
484 DBRefEntry proteinToEmblCdsRef = new DBRefEntry(
485 DBRefSource.EMBLCDS, sequenceVersion, proteinId,
486 new Mapping(proteinToCdsMapList));
487 product.addDBRef(proteinToEmblCdsRef);
490 * make 'direct' xref from protein to EMBLCDSPROTEIN
492 proteinToEmblProteinRef = new DBRefEntry(proteinToEmblCdsRef);
493 proteinToEmblProteinRef.setSource(DBRefSource.EMBLCDSProduct);
494 proteinToEmblProteinRef.setMap(null);
495 product.addDBRef(proteinToEmblProteinRef);
501 * add cds features to dna sequence
503 String cds = feature.getName(); // "CDS"
504 for (int xint = 0; exons != null
505 && xint < exons.length - 1; xint += 2)
507 int exonStart = exons[xint];
508 int exonEnd = exons[xint + 1];
509 int begin = Math.min(exonStart, exonEnd);
510 int end = Math.max(exonStart, exonEnd);
511 int exonNumber = xint / 2 + 1;
512 String desc = String.format("Exon %d for protein '%s' EMBLCDS:%s",
513 exonNumber, proteinName, proteinId);
515 SequenceFeature sf = makeCdsFeature(cds, desc, begin, end, sourceDb,
518 sf.setEnaLocation(feature.getLocation());
519 boolean forwardStrand = exonStart <= exonEnd;
520 sf.setStrand(forwardStrand ? "+" : "-");
521 sf.setPhase(String.valueOf(codonStart - 1));
522 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
523 sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
525 dna.addSequenceFeature(sf);
530 * add feature dbRefs to sequence, and mappings for Uniprot xrefs
532 boolean hasUniprotDbref = false;
533 List<XrefType> xrefs = feature.getXref();
536 boolean mappingUsed = false;
537 for (XrefType xref : xrefs)
540 * ensure UniProtKB/Swiss-Prot converted to UNIPROT
542 String source = DBRefUtils.getCanonicalName(xref.getDb());
543 String version = xref.getSecondaryId();
544 if (version == null || "".equals(version))
548 DBRefEntry dbref = new DBRefEntry(source, version, xref.getId());
549 DBRefEntry proteinDbRef = new DBRefEntry(source, version,
550 dbref.getAccessionId());
551 if (source.equals(DBRefSource.UNIPROT))
553 String proteinSeqName = DBRefSource.UNIPROT + "|"
554 + dbref.getAccessionId();
555 if (dnaToProteinMapping != null
556 && dnaToProteinMapping.getTo() != null)
561 * two or more Uniprot xrefs for the same CDS -
562 * each needs a distinct Mapping (as to a different sequence)
564 dnaToProteinMapping = new Mapping(dnaToProteinMapping);
569 * try to locate the protein mapped to (possibly by a
570 * previous CDS feature); if not found, construct it from
571 * the EMBL translation
573 SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
574 if (proteinSeq == null)
576 proteinSeq = new Sequence(proteinSeqName,
577 product.getSequenceAsString());
578 matcher.add(proteinSeq);
579 proteinSeq.setDescription(product.getDescription());
580 peptides.add(proteinSeq);
582 dnaToProteinMapping.setTo(proteinSeq);
583 dnaToProteinMapping.setMappedFromId(proteinId);
584 proteinSeq.addDBRef(proteinDbRef);
585 dbref.setMap(dnaToProteinMapping);
587 hasUniprotDbref = true;
592 * copy feature dbref to our protein product
594 DBRefEntry pref = proteinDbRef;
595 pref.setMap(null); // reference is direct
596 product.addDBRef(pref);
597 // Add converse mapping reference
598 if (dnaToProteinMapping != null)
600 Mapping pmap = new Mapping(dna,
601 dnaToProteinMapping.getMap().getInverse());
602 pref = new DBRefEntry(sourceDb, sequenceVersion, accession);
604 if (dnaToProteinMapping.getTo() != null)
606 dnaToProteinMapping.getTo().addDBRef(pref);
615 * if we have a product (translation) but no explicit Uniprot dbref
616 * (example: EMBL AAFI02000057 protein_id EAL65544.1)
617 * then construct mappings to an assumed EMBLCDSPROTEIN accession
619 if (!hasUniprotDbref && product != null)
621 if (proteinToEmblProteinRef == null)
623 // assuming CDSPROTEIN sequence version = dna version (?!)
624 proteinToEmblProteinRef = new DBRefEntry(DBRefSource.EMBLCDSProduct,
625 sequenceVersion, proteinId);
627 product.addDBRef(proteinToEmblProteinRef);
629 if (dnaToProteinMapping != null
630 && dnaToProteinMapping.getTo() != null)
632 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
633 DBRefSource.EMBLCDSProduct, sequenceVersion, proteinId);
634 dnaToEmblProteinRef.setMap(dnaToProteinMapping);
635 dnaToProteinMapping.setMappedFromId(proteinId);
636 dna.addDBRef(dnaToEmblProteinRef);
642 public boolean isDnaCoding()
648 * Returns the CDS positions as a single array of [start, end, start, end...]
649 * positions. If on the reverse strand, these will be in descending order.
655 protected int[] getCdsRanges(String accession, Feature feature)
657 String location = feature.getLocation();
658 if (location == null)
664 List<int[]> ranges = DnaUtils.parseLocation(location);
665 return listToArray(ranges);
666 } catch (ParseException e)
669 String.format("Not parsing inexact CDS location %s in ENA %s",
670 location, accession));
676 * Converts a list of [start, end] ranges to a single array of [start, end,
682 int[] listToArray(List<int[]> ranges)
684 int[] result = new int[ranges.size() * 2];
686 for (int[] range : ranges)
688 result[i++] = range[0];
689 result[i++] = range[1];
695 * Helper method to construct a SequenceFeature for one cds range
698 * feature type ("CDS")
708 * map of 'miscellaneous values' for feature
711 protected SequenceFeature makeCdsFeature(String type, String desc,
712 int begin, int end, String group, Map<String, String> vals)
714 SequenceFeature sf = new SequenceFeature(type, desc, begin, end, group);
717 for (Entry<String, String> val : vals.entrySet())
719 sf.setValue(val.getKey(), val.getValue());
726 public String getAccessionSeparator()
732 public Regex getAccessionValidator()
734 return ACCESSION_REGEX;
738 public String getDbVersion()
750 public boolean isValidReference(String accession)
752 if (accession == null || accession.length() < 2)
756 return getAccessionValidator().search(accession);
759 * Truncates (if necessary) the exon intervals to match 3 times the length of
760 * the protein; also accepts 3 bases longer (for stop codon not included in
763 * @param proteinLength
765 * an array of [start, end, start, end...] intervals
766 * @return the same array (if unchanged) or a truncated copy
768 static int[] adjustForProteinLength(int proteinLength, int[] exon)
770 if (proteinLength <= 0 || exon == null)
774 int expectedCdsLength = proteinLength * 3;
775 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
777 * if exon length matches protein, or is shorter, or longer by the
778 * length of a stop codon (3 bases), then leave it unchanged
780 if (expectedCdsLength >= exonLength
781 || expectedCdsLength == exonLength - 3)
788 origxon = new int[exon.length];
789 System.arraycopy(exon, 0, origxon, 0, exon.length);
791 for (int x = 0; x < exon.length; x += 2)
793 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
794 if (expectedCdsLength <= cdspos)
796 // advanced beyond last codon.
798 if (expectedCdsLength != cdspos)
801 // .println("Truncating final exon interval on region by "
802 // + (cdspos - cdslength));
805 * shrink the final exon - reduce end position if forward
806 * strand, increase it if reverse
808 if (exon[x + 1] >= exon[x])
810 endxon = exon[x + 1] - cdspos + expectedCdsLength;
814 endxon = exon[x + 1] + cdspos - expectedCdsLength;
821 // and trim the exon interval set if necessary
822 int[] nxon = new int[sxpos + 2];
823 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
824 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon