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;
24 import java.io.FileInputStream;
25 import java.io.InputStream;
26 import java.text.ParseException;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Hashtable;
30 import java.util.List;
31 import java.util.Locale;
33 import java.util.Map.Entry;
35 import javax.xml.bind.JAXBContext;
36 import javax.xml.bind.JAXBElement;
37 import javax.xml.bind.JAXBException;
38 import javax.xml.stream.FactoryConfigurationError;
39 import javax.xml.stream.XMLInputFactory;
40 import javax.xml.stream.XMLStreamException;
41 import javax.xml.stream.XMLStreamReader;
43 import com.stevesoft.pat.Regex;
45 import jalview.analysis.SequenceIdMatcher;
46 import jalview.bin.Console;
47 import jalview.datamodel.Alignment;
48 import jalview.datamodel.AlignmentI;
49 import jalview.datamodel.DBRefEntry;
50 import jalview.datamodel.DBRefSource;
51 import jalview.datamodel.FeatureProperties;
52 import jalview.datamodel.Mapping;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceFeature;
55 import jalview.datamodel.SequenceI;
56 import jalview.util.DBRefUtils;
57 import jalview.util.DnaUtils;
58 import jalview.util.MapList;
59 import jalview.util.MappingUtils;
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;
67 public abstract class EmblXmlSource extends EbiFileRetrievedProxy
69 private static final Regex ACCESSION_REGEX = new Regex("^[A-Z]+[0-9]+");
72 * JAL-1856 Embl returns this text for query not found
74 private static final String EMBL_NOT_FOUND_REPLY = "ERROR 12 No entries found.";
76 public EmblXmlSource()
82 * Retrieves and parses an emblxml file, and returns an alignment containing
83 * the parsed sequences, or null if none were found
86 * "EMBL" or "EMBLCDS" - anything else will not retrieve emblxml
91 protected AlignmentI getEmblSequenceRecords(String emprefx, String query)
95 EBIFetchClient dbFetch = new EBIFetchClient();
99 reply = dbFetch.fetchDataAsFile(
100 emprefx.toLowerCase(Locale.ROOT) + ":" + query.trim(),
101 "display=xml", "xml");
102 } catch (Exception e)
106 String.format("EBI EMBL XML retrieval failed for %s:%s",
107 emprefx.toLowerCase(Locale.ROOT), query.trim()),
110 return getEmblSequenceRecords(emprefx, query, reply);
114 * parse an emblxml file stored locally
117 * either EMBL or EMBLCDS strings are allowed - anything else will
118 * not retrieve emblxml
121 * the EMBL XML file containing the results of a query
125 protected AlignmentI getEmblSequenceRecords(String emprefx, String query,
126 File reply) throws Exception
128 List<EntryType> entries = null;
129 if (reply != null && reply.exists())
131 file = reply.getAbsolutePath();
132 if (reply.length() > EMBL_NOT_FOUND_REPLY.length())
134 InputStream is = new FileInputStream(reply);
135 entries = getEmblEntries(is);
140 * invalid accession gets a reply with no <entry> elements, text content of
141 * EmbFile reads something like (e.g.) this ungrammatical phrase
142 * Entry: <acc> display type is either not supported or entry is not found.
144 AlignmentI al = null;
145 List<SequenceI> seqs = new ArrayList<>();
146 List<SequenceI> peptides = new ArrayList<>();
149 for (EntryType entry : entries)
151 SequenceI seq = getSequence(emprefx, entry, peptides);
154 seqs.add(seq.deriveSequence());
155 // place DBReferences on dataset and refer
160 al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
164 jalview.bin.Console.outPrintln(
165 "No record found for '" + emprefx + ":" + query + "'");
174 * Reads the XML reply from file and unmarshals it to Java objects. Answers a
175 * (possibly empty) list of <code>EntryType</code> objects.
181 List<EntryType> getEmblEntries(InputStream is)
183 List<EntryType> entries = new ArrayList<>();
186 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.embl");
187 XMLStreamReader streamReader = XMLInputFactory.newInstance()
188 .createXMLStreamReader(is);
189 javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
190 JAXBElement<ROOT> rootElement = um.unmarshal(streamReader,
192 ROOT root = rootElement.getValue();
195 * document root contains either "entry" or "entrySet"
201 if (root.getEntrySet() != null)
203 entries = root.getEntrySet().getEntry();
205 else if (root.getEntry() != null)
207 entries.add(root.getEntry());
209 } catch (JAXBException | XMLStreamException
210 | FactoryConfigurationError e)
218 * A helper method to parse XML data and construct a sequence, with any
219 * available database references and features
226 SequenceI getSequence(String sourceDb, EntryType entry,
227 List<SequenceI> peptides)
229 String seqString = entry.getSequence();
230 if (seqString == null)
234 seqString = seqString.replace(" ", "").replace("\n", "").replace("\t",
236 String accession = entry.getAccession();
237 SequenceI dna = new Sequence(sourceDb + "|" + accession, seqString);
239 dna.setDescription(entry.getDescription());
240 String sequenceVersion = String.valueOf(entry.getVersion().intValue());
241 DBRefEntry selfRref = new DBRefEntry(sourceDb, sequenceVersion,
243 dna.addDBRef(selfRref);
245 new Mapping(null, new int[]
246 { 1, dna.getLength() }, new int[] { 1, dna.getLength() }, 1,
252 List<XrefType> xrefs = entry.getXref();
255 for (XrefType xref : xrefs)
257 String acc = xref.getId();
258 String source = DBRefUtils.getCanonicalName(xref.getDb());
259 String version = xref.getSecondaryId();
260 if (version == null || "".equals(version))
264 dna.addDBRef(new DBRefEntry(source, version, acc));
268 SequenceIdMatcher matcher = new SequenceIdMatcher(peptides);
271 List<Feature> features = entry.getFeature();
272 if (features != null)
274 for (Feature feature : features)
276 if (FeatureProperties.isCodingFeature(sourceDb,
279 parseCodingFeature(entry, feature, sourceDb, dna, peptides,
284 } catch (Exception e)
286 jalview.bin.Console.errPrintln("EMBL Record Features parsing error!");
288 .println("Please report the following to help@jalview.org :");
289 jalview.bin.Console.errPrintln("EMBL Record " + accession);
290 jalview.bin.Console.errPrintln("Resulted in exception: " + e.getMessage());
291 e.printStackTrace(System.err);
298 * Extracts coding region and product from a CDS feature and decorates it with
308 void parseCodingFeature(EntryType entry, Feature feature, String sourceDb,
309 SequenceI dna, List<SequenceI> peptides,
310 SequenceIdMatcher matcher)
312 final boolean isEmblCdna = sourceDb.equals(DBRefSource.EMBLCDS);
313 final String accession = entry.getAccession();
314 final String sequenceVersion = entry.getVersion().toString();
316 int[] exons = getCdsRanges(entry.getAccession(), feature);
318 String translation = null;
319 String proteinName = "";
320 String proteinId = null;
321 Map<String, String> vals = new Hashtable<>();
324 * codon_start 1/2/3 in EMBL corresponds to phase 0/1/2 in CDS
325 * (phase is required for CDS features in GFF3 format)
330 * parse qualifiers, saving protein translation, protein id,
331 * codon start position, product (name), and 'other values'
333 if (feature.getQualifier() != null)
335 for (Qualifier q : feature.getQualifier())
337 String qname = q.getName();
338 String value = q.getValue();
339 value = value == null ? ""
340 : value.trim().replace(" ", "").replace("\n", "")
342 if (qname.equals("translation"))
346 else if (qname.equals("protein_id"))
350 else if (qname.equals("codon_start"))
354 codonStart = Integer.parseInt(value.trim());
355 } catch (NumberFormatException e)
357 jalview.bin.Console.errPrintln("Invalid codon_start in XML for "
358 + entry.getAccession() + ": " + e.getMessage());
361 else if (qname.equals("product"))
363 // sometimes name is returned e.g. for V00488
368 // throw anything else into the additional properties hash
369 if (!"".equals(value))
371 vals.put(qname, value);
377 DBRefEntry proteinToEmblProteinRef = null;
378 exons = MappingUtils.removeStartPositions(codonStart - 1, exons);
380 SequenceI product = null;
381 Mapping dnaToProteinMapping = null;
382 if (translation != null && proteinName != null && proteinId != null)
384 int translationLength = translation.length();
387 * look for product in peptides list, if not found, add it
389 product = matcher.findIdMatch(proteinId);
392 product = new Sequence(proteinId, translation, 1,
394 product.setDescription(((proteinName.length() == 0)
395 ? "Protein Product from " + sourceDb
397 peptides.add(product);
398 matcher.add(product);
401 // we have everything - create the mapping and perhaps the protein
403 if (exons == null || exons.length == 0)
406 * workaround until we handle dna location for CDS sequence
407 * e.g. location="X53828.1:60..1058" correctly
409 jalview.bin.Console.errPrintln(
410 "Implementation Notice: EMBLCDS records not properly supported yet - Making up the CDNA region of this sequence... may be incorrect ("
411 + sourceDb + ":" + entry.getAccession() + ")");
412 int dnaLength = dna.getLength();
413 if (translationLength * 3 == (1 - codonStart + dnaLength))
415 jalview.bin.Console.errPrintln(
416 "Not allowing for additional stop codon at end of cDNA fragment... !");
417 // this might occur for CDS sequences where no features are marked
418 exons = new int[] { dna.getStart() + (codonStart - 1),
420 dnaToProteinMapping = new Mapping(product, exons,
422 { 1, translationLength }, 3, 1);
424 if ((translationLength + 1) * 3 == (1 - codonStart + dnaLength))
426 jalview.bin.Console.errPrintln(
427 "Allowing for additional stop codon at end of cDNA fragment... will probably cause an error in VAMSAs!");
428 exons = new int[] { dna.getStart() + (codonStart - 1),
430 dnaToProteinMapping = new Mapping(product, exons,
432 { 1, translationLength }, 3, 1);
437 // Trim the exon mapping if necessary - the given product may only be a
438 // fragment of a larger protein. (EMBL:AY043181 is an example)
442 // TODO: Add a DbRef back to the parent EMBL sequence with the exon
444 // if given a dataset reference, search dataset for parent EMBL
445 // sequence if it exists and set its map
446 // make a new feature annotating the coding contig
450 // final product length truncation check
451 int[] exons2 = adjustForProteinLength(translationLength, exons);
452 dnaToProteinMapping = new Mapping(product, exons2,
454 { 1, translationLength }, 3, 1);
458 * make xref with mapping from protein to EMBL dna
460 DBRefEntry proteinToEmblRef = new DBRefEntry(DBRefSource.EMBL,
461 sequenceVersion, proteinId,
462 new Mapping(dnaToProteinMapping.getMap().getInverse()));
463 product.addDBRef(proteinToEmblRef);
466 * make xref from protein to EMBLCDS; we assume here that the
467 * CDS sequence version is same as dna sequence (?!)
469 MapList proteinToCdsMapList = new MapList(
471 { 1, translationLength },
473 { 1 + (codonStart - 1),
474 (codonStart - 1) + 3 * translationLength },
476 DBRefEntry proteinToEmblCdsRef = new DBRefEntry(
477 DBRefSource.EMBLCDS, sequenceVersion, proteinId,
478 new Mapping(proteinToCdsMapList));
479 product.addDBRef(proteinToEmblCdsRef);
482 * make 'direct' xref from protein to EMBLCDSPROTEIN
484 proteinToEmblProteinRef = new DBRefEntry(proteinToEmblCdsRef);
485 proteinToEmblProteinRef.setSource(DBRefSource.EMBLCDSProduct);
486 proteinToEmblProteinRef.setMap(null);
487 product.addDBRef(proteinToEmblProteinRef);
493 * add cds features to dna sequence
495 String cds = feature.getName(); // "CDS"
496 for (int xint = 0; exons != null
497 && xint < exons.length - 1; xint += 2)
499 int exonStart = exons[xint];
500 int exonEnd = exons[xint + 1];
501 int begin = Math.min(exonStart, exonEnd);
502 int end = Math.max(exonStart, exonEnd);
503 int exonNumber = xint / 2 + 1;
504 String desc = String.format("Exon %d for protein '%s' EMBLCDS:%s",
505 exonNumber, proteinName, proteinId);
507 SequenceFeature sf = makeCdsFeature(cds, desc, begin, end, sourceDb,
510 sf.setEnaLocation(feature.getLocation());
511 boolean forwardStrand = exonStart <= exonEnd;
512 sf.setStrand(forwardStrand ? "+" : "-");
513 sf.setPhase(String.valueOf(codonStart - 1));
514 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
515 sf.setValue(FeatureProperties.EXONPRODUCT, proteinName);
517 dna.addSequenceFeature(sf);
522 * add feature dbRefs to sequence, and mappings for Uniprot xrefs
524 boolean hasUniprotDbref = false;
525 List<XrefType> xrefs = feature.getXref();
528 boolean mappingUsed = false;
529 for (XrefType xref : xrefs)
532 * ensure UniProtKB/Swiss-Prot converted to UNIPROT
534 String source = DBRefUtils.getCanonicalName(xref.getDb());
535 String version = xref.getSecondaryId();
536 if (version == null || "".equals(version))
540 DBRefEntry dbref = new DBRefEntry(source, version, xref.getId());
541 DBRefEntry proteinDbRef = new DBRefEntry(source, version,
542 dbref.getAccessionId());
543 if (source.equals(DBRefSource.UNIPROT))
545 String proteinSeqName = DBRefSource.UNIPROT + "|"
546 + dbref.getAccessionId();
547 if (dnaToProteinMapping != null
548 && dnaToProteinMapping.getTo() != null)
553 * two or more Uniprot xrefs for the same CDS -
554 * each needs a distinct Mapping (as to a different sequence)
556 dnaToProteinMapping = new Mapping(dnaToProteinMapping);
561 * try to locate the protein mapped to (possibly by a
562 * previous CDS feature); if not found, construct it from
563 * the EMBL translation
565 SequenceI proteinSeq = matcher.findIdMatch(proteinSeqName);
566 if (proteinSeq == null)
568 proteinSeq = new Sequence(proteinSeqName,
569 product.getSequenceAsString());
570 matcher.add(proteinSeq);
571 proteinSeq.setDescription(product.getDescription());
572 peptides.add(proteinSeq);
574 dnaToProteinMapping.setTo(proteinSeq);
575 dnaToProteinMapping.setMappedFromId(proteinId);
576 proteinSeq.addDBRef(proteinDbRef);
577 dbref.setMap(dnaToProteinMapping);
579 hasUniprotDbref = true;
584 * copy feature dbref to our protein product
586 DBRefEntry pref = proteinDbRef;
587 pref.setMap(null); // reference is direct
588 product.addDBRef(pref);
589 // Add converse mapping reference
590 if (dnaToProteinMapping != null)
592 Mapping pmap = new Mapping(dna,
593 dnaToProteinMapping.getMap().getInverse());
594 pref = new DBRefEntry(sourceDb, sequenceVersion, accession);
596 if (dnaToProteinMapping.getTo() != null)
598 dnaToProteinMapping.getTo().addDBRef(pref);
607 * if we have a product (translation) but no explicit Uniprot dbref
608 * (example: EMBL AAFI02000057 protein_id EAL65544.1)
609 * then construct mappings to an assumed EMBLCDSPROTEIN accession
611 if (!hasUniprotDbref && product != null)
613 if (proteinToEmblProteinRef == null)
615 // assuming CDSPROTEIN sequence version = dna version (?!)
616 proteinToEmblProteinRef = new DBRefEntry(DBRefSource.EMBLCDSProduct,
617 sequenceVersion, proteinId);
619 product.addDBRef(proteinToEmblProteinRef);
621 if (dnaToProteinMapping != null
622 && dnaToProteinMapping.getTo() != null)
624 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
625 DBRefSource.EMBLCDSProduct, sequenceVersion, proteinId);
626 dnaToEmblProteinRef.setMap(dnaToProteinMapping);
627 dnaToProteinMapping.setMappedFromId(proteinId);
628 dna.addDBRef(dnaToEmblProteinRef);
634 public boolean isDnaCoding()
640 * Returns the CDS positions as a single array of [start, end, start, end...]
641 * positions. If on the reverse strand, these will be in descending order.
647 protected int[] getCdsRanges(String accession, Feature feature)
649 String location = feature.getLocation();
650 if (location == null)
657 List<int[]> ranges = DnaUtils.parseLocation(location);
658 return listToArray(ranges);
659 } catch (ParseException e)
662 String.format("Not parsing inexact CDS location %s in ENA %s",
663 location, accession));
669 * Converts a list of [start, end] ranges to a single array of [start, end,
675 int[] listToArray(List<int[]> ranges)
677 int[] result = new int[ranges.size() * 2];
679 for (int[] range : ranges)
681 result[i++] = range[0];
682 result[i++] = range[1];
688 * Helper method to construct a SequenceFeature for one cds range
691 * feature type ("CDS")
701 * map of 'miscellaneous values' for feature
704 protected SequenceFeature makeCdsFeature(String type, String desc,
705 int begin, int end, String group, Map<String, String> vals)
707 SequenceFeature sf = new SequenceFeature(type, desc, begin, end, group);
710 for (Entry<String, String> val : vals.entrySet())
712 sf.setValue(val.getKey(), val.getValue());
719 public String getAccessionSeparator()
725 public Regex getAccessionValidator()
727 return ACCESSION_REGEX;
731 public String getDbVersion()
743 public boolean isValidReference(String accession)
745 if (accession == null || accession.length() < 2)
749 return getAccessionValidator().search(accession);
753 * Truncates (if necessary) the exon intervals to match 3 times the length of
754 * the protein (including truncation for stop codon included in exon)
756 * @param proteinLength
758 * an array of [start, end, start, end...] intervals
759 * @return the same array (if unchanged) or a truncated copy
761 static int[] adjustForProteinLength(int proteinLength, int[] exon)
763 if (proteinLength <= 0 || exon == null)
767 int expectedCdsLength = proteinLength * 3;
768 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
771 * if exon length matches protein, or is shorter, then leave it unchanged
773 if (expectedCdsLength >= exonLength)
781 origxon = new int[exon.length];
782 System.arraycopy(exon, 0, origxon, 0, exon.length);
784 for (int x = 0; x < exon.length; x += 2)
786 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
787 if (expectedCdsLength <= cdspos)
789 // advanced beyond last codon.
791 if (expectedCdsLength != cdspos)
794 // .println("Truncating final exon interval on region by "
795 // + (cdspos - cdslength));
799 * shrink the final exon - reduce end position if forward
800 * strand, increase it if reverse
802 if (exon[x + 1] >= exon[x])
804 endxon = exon[x + 1] - cdspos + expectedCdsLength;
808 endxon = exon[x + 1] + cdspos - expectedCdsLength;
816 // and trim the exon interval set if necessary
817 int[] nxon = new int[sxpos + 2];
818 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
819 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon