3 import java.io.IOException;
4 import java.text.ParseException;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.HashMap;
8 import java.util.Hashtable;
11 import java.util.Map.Entry;
12 import java.util.TreeMap;
14 import jalview.bin.Cache;
15 import jalview.datamodel.DBRefEntry;
16 import jalview.datamodel.DBRefSource;
17 import jalview.datamodel.FeatureProperties;
18 import jalview.datamodel.Mapping;
19 import jalview.datamodel.Sequence;
20 import jalview.datamodel.SequenceFeature;
21 import jalview.datamodel.SequenceI;
22 import jalview.util.DBRefUtils;
23 import jalview.util.DnaUtils;
24 import jalview.util.MapList;
25 import jalview.util.MappingUtils;
28 * A class that provides selective parsing of the EMBL flatfile format.
30 * The initial implementation is limited to extracting fields used by Jalview
31 * after fetching an EMBL or EMBLCDS entry:
34 * accession, version, sequence, xref
35 * and (for CDS feature) location, protein_id, product, codon_start, translation
38 * For a complete parser, it may be best to adopt that provided in
39 * https://github.com/enasequence/sequencetools/tree/master/src/main/java/uk/ac/ebi/embl/flatfile
40 * (but note this has a dependency on the Apache Commons library)
43 * @see ftp://ftp.ebi.ac.uk/pub/databases/ena/sequence/release/doc/usrman.txt
44 * @see ftp://ftp.ebi.ac.uk/pub/databases/embl/doc/FT_current.html
46 public class EmblFlatFile extends AlignFile // FileParse
48 private static final String QUOTE = "\"";
50 private static final String DOUBLED_QUOTE = QUOTE + QUOTE;
53 * A data bean class to hold values parsed from one CDS Feature (FT)
57 String translation; // from CDS feature /translation
59 String cdsLocation; // CDS /location raw value
61 int codonStart = 1; // from CDS /codon_start
63 String proteinName; // from CDS /product; used for protein description
65 String proteinId; // from CDS /protein_id
67 List<DBRefEntry> xrefs = new ArrayList<>(); // from CDS /db_xref qualifiers
69 Map<String, String> cdsProps = new Hashtable<>(); // CDS other qualifiers
72 private static final String WHITESPACE = "\\s+";
74 private String sourceDb;
77 * values parsed from the EMBL flatfile record
79 private String accession; // from ID (first token)
81 private String version; // from ID (second token)
83 private String description; // from (first) DE line
85 private int length = 128; // from ID (7th token), with usable default
87 private List<DBRefEntry> dbrefs; // from DR
89 private String sequenceString; // from SQ lines
92 * parsed CDS data fields, keyed by protein_id
94 private Map<String, CdsData> cds;
101 * @throws IOException
103 public EmblFlatFile(FileParse fp, String sourceId) throws IOException
105 super(false, fp); // don't parse immediately
106 this.sourceDb = sourceId;
107 dbrefs = new ArrayList<>();
110 * using TreeMap gives CDS sequences in alphabetical, so readable, order
112 cds = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
116 * Parses the flatfile, and if successful, saves as an annotated sequence
117 * which may be retrieved by calling {@code getSequence()}
119 * @throws IOException
121 public void parse() throws IOException
123 String line = nextLine();
126 if (line.startsWith("ID"))
128 line = parseID(line);
130 else if (line.startsWith("DE"))
132 line = parseDE(line);
134 else if (line.startsWith("DR"))
136 line = parseDR(line);
138 else if (line.startsWith("SQ"))
142 else if (line.startsWith("FT"))
144 line = parseFT(line);
155 * Extracts and saves the primary accession and version (SV value) from an ID
156 * line, or null if not found. Returns the next line after the one processed.
159 * @throws IOException
161 String parseID(String line) throws IOException
163 String[] tokens = line.substring(2).split(";");
166 * first is primary accession
168 String token = tokens[0].trim();
169 if (!token.isEmpty())
171 this.accession = token;
175 * second token is 'SV versionNo'
177 if (tokens.length > 1)
179 token = tokens[1].trim();
180 if (token.startsWith("SV"))
182 String[] bits = token.trim().split(WHITESPACE);
183 this.version = bits[bits.length - 1];
188 * seventh token is 'length BP'
190 if (tokens.length > 6)
192 token = tokens[6].trim();
193 String[] bits = token.trim().split(WHITESPACE);
196 this.length = Integer.valueOf(bits[0]);
197 } catch (NumberFormatException e)
199 Cache.log.error("bad length read in flatfile, line: " + line);
207 * Reads sequence description from the first DE line found. Any trailing
208 * period is discarded. If there are multiple DE lines, only the first (short
209 * description) is read, the rest are ignored.
213 * @throws IOException
215 String parseDE(String line) throws IOException
217 String desc = line.substring(2).trim();
218 if (desc.endsWith("."))
220 desc = desc.substring(0, desc.length() - 1);
222 this.description = desc;
225 * pass over any additional DE lines
227 while ((line = nextLine()) != null)
229 if (!line.startsWith("DE"))
239 * Processes one DR line and saves as a DBRefEntry cross-reference. Returns
240 * the line following the line processed.
243 * @throws IOException
245 String parseDR(String line) throws IOException
247 String[] tokens = line.substring(2).split(";");
248 if (tokens.length > 1)
251 * ensure UniProtKB/Swiss-Prot converted to UNIPROT
253 String db = tokens[0].trim();
254 db = DBRefUtils.getCanonicalName(db);
255 String acc = tokens[1].trim();
256 if (acc.endsWith("."))
258 acc = acc.substring(0, acc.length() - 1);
260 String version = "0";
261 if (tokens.length > 2)
263 String secondaryId = tokens[2].trim();
264 if (!secondaryId.isEmpty())
266 // todo: is this right? secondary id is not a version number
267 // version = secondaryId;
270 this.dbrefs.add(new DBRefEntry(db, version, acc));
277 * Reads and saves the sequence, read from the lines following the SQ line.
278 * Whitespace and position counters are discarded. Returns the next line
279 * following the sequence data (the next line that doesn't start with
282 * @throws IOException
284 String parseSQ() throws IOException
286 StringBuilder sb = new StringBuilder(this.length);
287 String line = nextLine();
288 while (line != null && line.startsWith(" "))
291 String[] blocks = line.split(WHITESPACE);
294 * omit the last block (position counter) on each line
296 for (int i = 0; i < blocks.length - 1; i++)
298 sb.append(blocks[i]);
302 this.sequenceString = sb.toString();
308 * Processes an FT line. If it declares a feature type of interest (currently,
309 * only CDS is processed), processes all of the associated lines (feature
310 * qualifiers), and returns the next line after that, otherwise simply returns
315 * @throws IOException
317 String parseFT(String line) throws IOException
319 String[] tokens = line.split(WHITESPACE);
320 if (tokens.length < 3 || !"CDS".equals(tokens[1]))
325 CdsData data = new CdsData();
326 data.cdsLocation = tokens[2];
327 // TODO location can be over >1 line e.g. EAW51554
332 if (!line.startsWith("FT ")) // 4 spaces
334 // e.g. start of next feature "FT source..."
339 * extract qualifier, e.g. FT /protein_id="CAA37824.1"
340 * - the value may extend over more than one line
341 * - if the value has enclosing quotes, these are removed
342 * - escaped double quotes ("") are reduced to a single character
344 int slashPos = line.indexOf('/');
347 Cache.log.error("Unexpected EMBL line ignored: " + line);
351 int eqPos = line.indexOf('=', slashPos + 1);
354 // can happen, e.g. /ribosomal_slippage
355 // Cache.log.error("Unexpected EMBL line ignored: " + line);
359 String qualifier = line.substring(slashPos + 1, eqPos);
360 String value = line.substring(eqPos + 1);
361 value = removeQuotes(value);
362 StringBuilder sb = new StringBuilder().append(value);
363 line = parseFeatureQualifier(sb, qualifier);
364 String featureValue = sb.toString();
366 if ("protein_id".equals(qualifier))
368 data.proteinId = featureValue;
370 else if ("codon_start".equals(qualifier))
374 data.codonStart = Integer.parseInt(featureValue.trim());
375 } catch (NumberFormatException e)
377 Cache.log.error("Invalid codon_start in XML for " + this.accession
378 + ": " + e.getMessage());
381 else if ("db_xref".equals(qualifier))
383 String[] parts = featureValue.split(":");
384 if (parts.length == 2)
386 String db = parts[0].trim();
387 db = DBRefUtils.getCanonicalName(db);
388 DBRefEntry dbref = new DBRefEntry(db, "0", parts[1].trim());
389 data.xrefs.add(dbref);
392 else if ("product".equals(qualifier))
394 data.proteinName = featureValue;
396 else if ("translation".equals(qualifier))
398 data.translation = featureValue;
400 else if (!"".equals(featureValue))
402 // throw anything else into the additional properties hash
403 data.cdsProps.put(qualifier, featureValue);
407 if (data.proteinId != null)
409 this.cds.put(data.proteinId, data);
413 Cache.log.error("Ignoring CDS feature with no protein_id for "
414 + sourceDb + ":" + accession);
421 * Removes leading or trailing double quotes (") unless doubled, and changes
422 * any 'escaped' (doubled) double quotes to single characters. As per the
423 * Feature Table specification for Qualifiers, Free Text.
428 static String removeQuotes(String value)
434 if (value.startsWith(QUOTE) && !value.startsWith(DOUBLED_QUOTE))
436 value = value.substring(1);
438 if (value.endsWith(QUOTE) && !value.endsWith(DOUBLED_QUOTE))
440 value = value.substring(0, value.length() - 1);
442 value = value.replace(DOUBLED_QUOTE, QUOTE);
447 * Reads the value of a feature (FT) qualifier from one or more lines of the
448 * file, and returns the next line after that. Values are appended to the
449 * string buffer, which should be already primed with the value read from the
450 * first line for the qualifier (with any leading double quote removed).
451 * Enclosing double quotes are removed, and escaped (repeated) double quotes
452 * reduced to one only. For example for
455 * FT /note="gene_id=hCG28070.3
456 * FT ""foobar"" isoform=CRA_b"
457 * the returned value is
458 * gene_id=hCG28070.3 "foobar" isoform=CRA_b
461 * Note the side-effect of this method, to advance data reading to the next
462 * line after the feature qualifier.
465 * a string buffer primed with the first line of the value
466 * @param qualifierName
468 * @throws IOException
470 String parseFeatureQualifier(StringBuilder sb, String qualifierName)
474 while ((line = nextLine()) != null)
476 if (!line.startsWith("FT "))
478 break; // reached next feature or other input line
480 String[] tokens = line.split(WHITESPACE);
481 if (tokens.length < 2)
483 Cache.log.error("Ignoring bad EMBL line for " + this.accession
487 if (tokens[1].startsWith("/"))
489 break; // next feature qualifier
493 * heuristic rule: most multi-line value (e.g. /product) are text,
494 * so add a space for word boundary at a new line; not for translation
496 if (!"translation".equals(qualifierName))
502 * remove trailing " and unescape doubled ""
504 String data = removeQuotes(tokens[1]);
512 * Constructs and saves the sequence from parsed components
516 if (this.accession == null || this.sequenceString == null)
518 Cache.log.error("Failed to parse data from EMBL");
522 String name = this.accession;
523 if (this.sourceDb != null)
525 name = this.sourceDb + "|" + name;
527 SequenceI seq = new Sequence(name, this.sequenceString);
528 seq.setDescription(this.description);
531 * add a DBRef to itself
533 DBRefEntry selfRef = new DBRefEntry(sourceDb, version, accession);
534 int[] startEnd = new int[] { 1, seq.getLength() };
535 selfRef.setMap(new Mapping(null, startEnd, startEnd, 1, 1));
536 seq.addDBRef(selfRef);
538 for (DBRefEntry dbref : this.dbrefs)
543 processCDSFeatures(seq);
545 seq.deriveSequence();
551 * Process the CDS features, including generation of cross-references and
552 * mappings to the protein products (translation)
556 protected void processCDSFeatures(SequenceI seq)
559 * record protein products found to avoid duplication i.e. >1 CDS with
560 * the same /protein_id [though not sure I can find an example of this]
562 Map<String, SequenceI> proteins = new HashMap<>();
563 for (CdsData data : cds.values())
565 processCDSFeature(seq, data, proteins);
570 * Processes data for one parsed CDS feature to
572 * <li>create a protein product sequence for the translation</li>
573 * <li>create a cross-reference to protein with mapping from dna</li>
574 * <li>add a CDS feature to the sequence for each CDS start-end range</li>
575 * <li>add any CDS dbrefs to the sequence and to the protein product</li>
581 * map of protein products so far derived from CDS data
583 void processCDSFeature(SequenceI dna, CdsData data,
584 Map<String, SequenceI> proteins)
587 * parse location into a list of [start, end, start, end] positions
589 int[] exons = getCdsRanges(this.accession, data.cdsLocation);
591 MapList maplist = buildMappingToProtein(dna, exons, data);
595 for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
597 int exonStart = exons[xint];
598 int exonEnd = exons[xint + 1];
599 int begin = Math.min(exonStart, exonEnd);
600 int end = Math.max(exonStart, exonEnd);
602 String desc = String.format("Exon %d for protein EMBLCDS:%s",
603 exonNumber, data.proteinId);
605 SequenceFeature sf = new SequenceFeature("CDS", desc, begin, end,
607 for (Entry<String, String> val : data.cdsProps.entrySet())
609 sf.setValue(val.getKey(), val.getValue());
612 sf.setEnaLocation(data.cdsLocation);
613 boolean forwardStrand = exonStart <= exonEnd;
614 sf.setStrand(forwardStrand ? "+" : "-");
615 sf.setPhase(String.valueOf(data.codonStart - 1));
616 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
617 sf.setValue(FeatureProperties.EXONPRODUCT, data.proteinName);
619 dna.addSequenceFeature(sf);
622 boolean hasUniprotDbref = false;
623 for (DBRefEntry xref : data.xrefs)
626 if (xref.getSource().equals(DBRefSource.UNIPROT))
629 * construct (or find) the sequence for (data.protein_id, data.translation)
631 SequenceI protein = buildProteinProduct(dna, xref, data, proteins);
632 Mapping map = new Mapping(protein, maplist);
633 map.setMappedFromId(data.proteinId);
637 * add DBRefs with mappings from dna to protein and the inverse
639 DBRefEntry db1 = new DBRefEntry(sourceDb, version, accession);
640 db1.setMap(new Mapping(dna, maplist.getInverse()));
641 protein.addDBRef(db1);
643 hasUniprotDbref = true;
648 * if we have a product (translation) but no explicit Uniprot dbref
649 * (example: EMBL M19487 protein_id AAB02592.1)
650 * then construct mappings to an assumed EMBLCDSPROTEIN accession
652 if (!hasUniprotDbref)
654 SequenceI protein = proteins.get(data.proteinId);
657 protein = new Sequence(data.proteinId, data.translation);
658 protein.setDescription(data.proteinName);
659 proteins.put(data.proteinId, protein);
661 // assuming CDSPROTEIN sequence version = dna version (?!)
662 DBRefEntry db1 = new DBRefEntry(DBRefSource.EMBLCDSProduct,
663 this.version, data.proteinId);
664 protein.addDBRef(db1);
666 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
667 DBRefSource.EMBLCDSProduct, this.version, data.proteinId);
668 Mapping map = new Mapping(protein, maplist);
669 map.setMappedFromId(data.proteinId);
670 dnaToEmblProteinRef.setMap(map);
671 dna.addDBRef(dnaToEmblProteinRef);
675 * comment brought forward from EmblXmlSource, lines 447-451:
676 * TODO: if retrieved from EMBLCDS, add a DBRef back to the parent EMBL
677 * sequence with the exon map; if given a dataset reference, search
678 * dataset for parent EMBL sequence if it exists and set its map;
679 * make a new feature annotating the coding contig
684 * Computes a mapping from CDS positions in DNA sequence to protein product
685 * positions, with allowance for stop codon or incomplete start codon
692 MapList buildMappingToProtein(final SequenceI dna, final int[] exons,
695 MapList dnaToProteinMapping = null;
696 int peptideLength = data.translation.length();
698 int[] proteinRange = new int[] { 1, peptideLength };
699 if (exons != null && exons.length > 0)
702 * We were able to parse 'location'; do a final
703 * product length truncation check
705 int[] cdsRanges = adjustForProteinLength(peptideLength, exons);
706 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
711 * workaround until we handle all 'location' formats fully
712 * e.g. X53828.1:60..1058 or <123..>289
714 Cache.log.error(String.format(
715 "Implementation Notice: EMBLCDS location '%s'not properly supported yet"
716 + " - Making up the CDNA region of (%s:%s)... may be incorrect",
717 data.cdsLocation, sourceDb, this.accession));
719 int completeCodonsLength = 1 - data.codonStart + dna.getLength();
720 int mappedDnaEnd = dna.getEnd();
721 if (peptideLength * 3 == completeCodonsLength)
723 // this might occur for CDS sequences where no features are marked
724 Cache.log.warn("Assuming no stop codon at end of cDNA fragment");
725 mappedDnaEnd = dna.getEnd();
727 else if ((peptideLength + 1) * 3 == completeCodonsLength)
729 Cache.log.warn("Assuming stop codon at end of cDNA fragment");
730 mappedDnaEnd = dna.getEnd() - 3;
733 if (mappedDnaEnd != -1)
735 int[] cdsRanges = new int[] {
736 dna.getStart() + (data.codonStart - 1), mappedDnaEnd };
737 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
741 return dnaToProteinMapping;
745 * Constructs a sequence for the protein product for the CDS data (if there is
746 * one), and dbrefs with mappings from CDS to protein and the reverse
754 SequenceI buildProteinProduct(SequenceI dna, DBRefEntry xref,
755 CdsData data, Map<String, SequenceI> proteins)
758 * check we have some data to work with
760 if (data.proteinId == null || data.translation == null)
766 * Construct the protein sequence (if not already seen)
768 String proteinSeqName = xref.getSource() + "|" + xref.getAccessionId();
769 SequenceI protein = proteins.get(proteinSeqName);
772 protein = new Sequence(proteinSeqName, data.translation, 1,
773 data.translation.length());
774 protein.setDescription(data.proteinName != null ? data.proteinName
775 : "Protein Product from " + sourceDb);
776 proteins.put(proteinSeqName, protein);
783 * Returns the CDS location as a single array of [start, end, start, end...]
784 * positions. If on the reverse strand, these will be in descending order.
790 protected int[] getCdsRanges(String accession, String location)
792 if (location == null)
799 List<int[]> ranges = DnaUtils.parseLocation(location);
800 return MappingUtils.listToArray(ranges);
801 } catch (ParseException e)
804 String.format("Not parsing inexact CDS location %s in ENA %s",
805 location, accession));
811 * Output (print) is not implemented for EMBL flat file format
814 public String print(SequenceI[] seqs, boolean jvsuffix)
820 * Truncates (if necessary) the exon intervals to match 3 times the length of
821 * the protein; also accepts 3 bases longer (for stop codon not included in
824 * @param proteinLength
826 * an array of [start, end, start, end...] intervals
827 * @return the same array (if unchanged) or a truncated copy
829 static int[] adjustForProteinLength(int proteinLength, int[] exon)
831 if (proteinLength <= 0 || exon == null)
835 int expectedCdsLength = proteinLength * 3;
836 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
839 * if exon length matches protein, or is shorter, or longer by the
840 * length of a stop codon (3 bases), then leave it unchanged
842 if (expectedCdsLength >= exonLength
843 || expectedCdsLength == exonLength - 3)
851 origxon = new int[exon.length];
852 System.arraycopy(exon, 0, origxon, 0, exon.length);
854 for (int x = 0; x < exon.length; x += 2)
856 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
857 if (expectedCdsLength <= cdspos)
859 // advanced beyond last codon.
861 if (expectedCdsLength != cdspos)
864 // .println("Truncating final exon interval on region by "
865 // + (cdspos - cdslength));
869 * shrink the final exon - reduce end position if forward
870 * strand, increase it if reverse
872 if (exon[x + 1] >= exon[x])
874 endxon = exon[x + 1] - cdspos + expectedCdsLength;
878 endxon = exon[x + 1] + cdspos - expectedCdsLength;
886 // and trim the exon interval set if necessary
887 int[] nxon = new int[sxpos + 2];
888 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
889 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon