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 * when true, interpret the mol_type 'source' feature attribute
54 * and generate an RNA sequence from the DNA record
56 private boolean produceRna=true;
58 * A data bean class to hold values parsed from one CDS Feature (FT)
62 String translation; // from CDS feature /translation
64 String cdsLocation; // CDS /location raw value
66 int codonStart = 1; // from CDS /codon_start
68 String proteinName; // from CDS /product; used for protein description
70 String proteinId; // from CDS /protein_id
72 List<DBRefEntry> xrefs = new ArrayList<>(); // from CDS /db_xref qualifiers
74 Map<String, String> cdsProps = new Hashtable<>(); // CDS other qualifiers
77 private static final String WHITESPACE = "\\s+";
79 private String sourceDb;
82 * values parsed from the EMBL flatfile record
84 private String accession; // from ID (first token)
86 private String version; // from ID (second token)
88 private String description; // from (first) DE line
90 private int length = 128; // from ID (7th token), with usable default
92 private List<DBRefEntry> dbrefs; // from DR
94 private boolean sequenceStringIsRNA=false;
95 private String sequenceString; // from SQ lines
98 * parsed CDS data fields, keyed by protein_id
100 private Map<String, CdsData> cds;
107 * @throws IOException
109 public EmblFlatFile(FileParse fp, String sourceId) throws IOException
111 super(false, fp); // don't parse immediately
112 this.sourceDb = sourceId;
113 dbrefs = new ArrayList<>();
116 * using TreeMap gives CDS sequences in alphabetical, so readable, order
118 cds = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
122 * Parses the flatfile, and if successful, saves as an annotated sequence
123 * which may be retrieved by calling {@code getSequence()}
125 * @throws IOException
128 public void parse() throws IOException
130 String line = nextLine();
133 if (line.startsWith("ID"))
135 line = parseID(line);
137 else if (line.startsWith("DE"))
139 line = parseDE(line);
141 else if (line.startsWith("DR"))
143 line = parseDR(line);
145 else if (line.startsWith("SQ"))
149 else if (line.startsWith("FT"))
151 line = parseFT(line);
162 * Extracts and saves the primary accession and version (SV value) from an ID
163 * line, or null if not found. Returns the next line after the one processed.
166 * @throws IOException
168 String parseID(String line) throws IOException
170 String[] tokens = line.substring(2).split(";");
173 * first is primary accession
175 String token = tokens[0].trim();
176 if (!token.isEmpty())
178 this.accession = token;
182 * second token is 'SV versionNo'
184 if (tokens.length > 1)
186 token = tokens[1].trim();
187 if (token.startsWith("SV"))
189 String[] bits = token.trim().split(WHITESPACE);
190 this.version = bits[bits.length - 1];
195 * seventh token is 'length BP'
197 if (tokens.length > 6)
199 token = tokens[6].trim();
200 String[] bits = token.trim().split(WHITESPACE);
203 this.length = Integer.valueOf(bits[0]);
204 } catch (NumberFormatException e)
206 Cache.log.error("bad length read in flatfile, line: " + line);
214 * Reads sequence description from the first DE line found. Any trailing
215 * period is discarded. If there are multiple DE lines, only the first (short
216 * description) is read, the rest are ignored.
220 * @throws IOException
222 String parseDE(String line) throws IOException
224 String desc = line.substring(2).trim();
225 if (desc.endsWith("."))
227 desc = desc.substring(0, desc.length() - 1);
229 this.description = desc;
232 * pass over any additional DE lines
234 while ((line = nextLine()) != null)
236 if (!line.startsWith("DE"))
246 * Processes one DR line and saves as a DBRefEntry cross-reference. Returns
247 * the line following the line processed.
250 * @throws IOException
252 String parseDR(String line) throws IOException
254 String[] tokens = line.substring(2).split(";");
255 if (tokens.length > 1)
258 * ensure UniProtKB/Swiss-Prot converted to UNIPROT
260 String db = tokens[0].trim();
261 db = DBRefUtils.getCanonicalName(db);
262 String acc = tokens[1].trim();
263 if (acc.endsWith("."))
265 acc = acc.substring(0, acc.length() - 1);
267 String version = "0";
268 if (tokens.length > 2)
270 String secondaryId = tokens[2].trim();
271 if (!secondaryId.isEmpty())
273 // todo: is this right? secondary id is not a version number
274 // version = secondaryId;
277 this.dbrefs.add(new DBRefEntry(db, version, acc));
284 * Reads and saves the sequence, read from the lines following the SQ line.
285 * Whitespace and position counters are discarded. Returns the next line
286 * following the sequence data (the next line that doesn't start with
289 * @throws IOException
291 String parseSQ() throws IOException
293 StringBuilder sb = new StringBuilder(this.length);
294 String line = nextLine();
295 while (line != null && line.startsWith(" "))
298 String[] blocks = line.split(WHITESPACE);
301 * omit the last block (position counter) on each line
303 for (int i = 0; i < blocks.length - 1; i++)
305 sb.append(blocks[i]);
309 this.sequenceString = sb.toString();
315 * Processes an FT line. If it declares a feature type of interest (currently,
316 * only CDS is processed), processes all of the associated lines (feature
317 * qualifiers), and returns the next line after that, otherwise simply returns
322 * @throws IOException
324 String parseFT(String line) throws IOException
326 String[] tokens = line.split(WHITESPACE);
327 if (tokens.length < 3 || (!"CDS".equals(tokens[1]) && !"source".equals(tokens[1])))
332 if (tokens[1].equals("source"))
334 return parseSourceQualifiers(tokens);
337 * parse location - which may be over more than one line e.g. EAW51554
339 CdsData data = new CdsData();
340 StringBuilder sb = new StringBuilder().append(tokens[2]);
341 line = parseFeatureQualifier(sb, "CDS");
342 data.cdsLocation = sb.toString();
346 if (!line.startsWith("FT ")) // 4 spaces
348 // e.g. start of next feature "FT source..."
353 * extract qualifier, e.g. FT /protein_id="CAA37824.1"
354 * - the value may extend over more than one line
355 * - if the value has enclosing quotes, these are removed
356 * - escaped double quotes ("") are reduced to a single character
358 int slashPos = line.indexOf('/');
361 Cache.log.error("Unexpected EMBL line ignored: " + line);
365 int eqPos = line.indexOf('=', slashPos + 1);
368 // can happen, e.g. /ribosomal_slippage
369 // Cache.log.error("Unexpected EMBL line ignored: " + line);
373 String qualifier = line.substring(slashPos + 1, eqPos);
374 String value = line.substring(eqPos + 1);
375 value = removeQuotes(value);
376 sb = new StringBuilder().append(value);
377 line = parseFeatureQualifier(sb, qualifier);
378 String featureValue = sb.toString();
380 if ("protein_id".equals(qualifier))
382 data.proteinId = featureValue;
384 else if ("codon_start".equals(qualifier))
388 data.codonStart = Integer.parseInt(featureValue.trim());
389 } catch (NumberFormatException e)
391 Cache.log.error("Invalid codon_start in XML for " + this.accession
392 + ": " + e.getMessage());
395 else if ("db_xref".equals(qualifier))
397 String[] parts = featureValue.split(":");
398 if (parts.length == 2)
400 String db = parts[0].trim();
401 db = DBRefUtils.getCanonicalName(db);
402 DBRefEntry dbref = new DBRefEntry(db, "0", parts[1].trim());
403 data.xrefs.add(dbref);
406 else if ("product".equals(qualifier))
408 data.proteinName = featureValue;
410 else if ("translation".equals(qualifier))
412 data.translation = featureValue;
414 else if (!"".equals(featureValue))
416 // throw anything else into the additional properties hash
417 data.cdsProps.put(qualifier, featureValue);
421 if (data.proteinId != null)
423 this.cds.put(data.proteinId, data);
427 Cache.log.error("Ignoring CDS feature with no protein_id for "
428 + sourceDb + ":" + accession);
435 * process attributes for 'source' until the next FT feature entry
436 * only interested in 'mol_type'
439 * @throws IOException
441 private String parseSourceQualifiers(String[] tokens) throws IOException
443 if (!"source".equals(tokens[1]))
445 throw (new RuntimeException("Not given a source qualifier"));
447 // search for mol_type attribute
449 StringBuilder sb = new StringBuilder().append(tokens[2]); // extent of
452 String line = parseFeatureQualifier(sb, "source");
455 if (!line.startsWith("FT ")) // four spaces, end of this feature table
461 int p = line.indexOf("\\mol_type");
462 int qs = line.indexOf("\"", p);
463 int qe = line.indexOf("\"", qs + 1);
464 String qualifier=line.substring(qs,qe).toLowerCase();
465 if (qualifier.indexOf("rna") > -1)
467 sequenceStringIsRNA = true;
469 if (qualifier.indexOf("dna") > -1)
471 sequenceStringIsRNA = false;
473 line=parseFeatureQualifier(sb, "source");
479 * Removes leading or trailing double quotes (") unless doubled, and changes
480 * any 'escaped' (doubled) double quotes to single characters. As per the
481 * Feature Table specification for Qualifiers, Free Text.
486 static String removeQuotes(String value)
492 if (value.startsWith(QUOTE) && !value.startsWith(DOUBLED_QUOTE))
494 value = value.substring(1);
496 if (value.endsWith(QUOTE) && !value.endsWith(DOUBLED_QUOTE))
498 value = value.substring(0, value.length() - 1);
500 value = value.replace(DOUBLED_QUOTE, QUOTE);
505 * Reads the value of a feature (FT) qualifier from one or more lines of the
506 * file, and returns the next line after that. Values are appended to the
507 * string buffer, which should be already primed with the value read from the
508 * first line for the qualifier (with any leading double quote removed).
509 * Enclosing double quotes are removed, and escaped (repeated) double quotes
510 * reduced to one only. For example for
513 * FT /note="gene_id=hCG28070.3
514 * FT ""foobar"" isoform=CRA_b"
515 * the returned value is
516 * gene_id=hCG28070.3 "foobar" isoform=CRA_b
519 * Note the side-effect of this method, to advance data reading to the next
520 * line after the feature qualifier.
523 * a string buffer primed with the first line of the value
524 * @param qualifierName
526 * @throws IOException
528 String parseFeatureQualifier(StringBuilder sb, String qualifierName)
532 while ((line = nextLine()) != null)
534 if (!line.startsWith("FT "))
536 break; // reached next feature or other input line
538 String[] tokens = line.split(WHITESPACE);
539 if (tokens.length < 2)
541 Cache.log.error("Ignoring bad EMBL line for " + this.accession
545 if (tokens[1].startsWith("/"))
547 break; // next feature qualifier
551 * heuristic rule: most multi-line value (e.g. /product) are text,
552 * so add a space for word boundary at a new line; not for translation
554 if (!"translation".equals(qualifierName)
555 && !"CDS".equals(qualifierName))
561 * remove trailing " and unescape doubled ""
563 String data = removeQuotes(tokens[1]);
571 * Constructs and saves the sequence from parsed components
575 if (this.accession == null || this.sequenceString == null)
577 Cache.log.error("Failed to parse data from EMBL");
581 String name = this.accession;
582 if (this.sourceDb != null)
584 name = this.sourceDb + "|" + name;
587 if (produceRna && sequenceStringIsRNA)
589 sequenceString = sequenceString.replace('T', 'U').replace('t', 'u');
592 SequenceI seq = new Sequence(name, this.sequenceString);
593 seq.setDescription(this.description);
596 * add a DBRef to itself
598 DBRefEntry selfRef = new DBRefEntry(sourceDb, version, accession);
599 int[] startEnd = new int[] { 1, seq.getLength() };
600 selfRef.setMap(new Mapping(null, startEnd, startEnd, 1, 1));
601 seq.addDBRef(selfRef);
603 for (DBRefEntry dbref : this.dbrefs)
608 processCDSFeatures(seq);
610 seq.deriveSequence();
616 * Process the CDS features, including generation of cross-references and
617 * mappings to the protein products (translation)
621 protected void processCDSFeatures(SequenceI seq)
624 * record protein products found to avoid duplication i.e. >1 CDS with
625 * the same /protein_id [though not sure I can find an example of this]
627 Map<String, SequenceI> proteins = new HashMap<>();
628 for (CdsData data : cds.values())
630 processCDSFeature(seq, data, proteins);
635 * Processes data for one parsed CDS feature to
637 * <li>create a protein product sequence for the translation</li>
638 * <li>create a cross-reference to protein with mapping from dna</li>
639 * <li>add a CDS feature to the sequence for each CDS start-end range</li>
640 * <li>add any CDS dbrefs to the sequence and to the protein product</li>
646 * map of protein products so far derived from CDS data
648 void processCDSFeature(SequenceI dna, CdsData data,
649 Map<String, SequenceI> proteins)
652 * parse location into a list of [start, end, start, end] positions
654 int[] exons = getCdsRanges(this.accession, data.cdsLocation);
656 MapList maplist = buildMappingToProtein(dna, exons, data);
660 for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
662 int exonStart = exons[xint];
663 int exonEnd = exons[xint + 1];
664 int begin = Math.min(exonStart, exonEnd);
665 int end = Math.max(exonStart, exonEnd);
667 String desc = String.format("Exon %d for protein EMBLCDS:%s",
668 exonNumber, data.proteinId);
670 SequenceFeature sf = new SequenceFeature("CDS", desc, begin, end,
672 for (Entry<String, String> val : data.cdsProps.entrySet())
674 sf.setValue(val.getKey(), val.getValue());
677 sf.setEnaLocation(data.cdsLocation);
678 boolean forwardStrand = exonStart <= exonEnd;
679 sf.setStrand(forwardStrand ? "+" : "-");
680 sf.setPhase(String.valueOf(data.codonStart - 1));
681 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
682 sf.setValue(FeatureProperties.EXONPRODUCT, data.proteinName);
684 dna.addSequenceFeature(sf);
687 boolean hasUniprotDbref = false;
688 for (DBRefEntry xref : data.xrefs)
691 if (xref.getSource().equals(DBRefSource.UNIPROT))
694 * construct (or find) the sequence for (data.protein_id, data.translation)
696 SequenceI protein = buildProteinProduct(dna, xref, data, proteins);
697 Mapping map = new Mapping(protein, maplist);
698 map.setMappedFromId(data.proteinId);
702 * add DBRefs with mappings from dna to protein and the inverse
704 DBRefEntry db1 = new DBRefEntry(sourceDb, version, accession);
705 db1.setMap(new Mapping(dna, maplist.getInverse()));
706 protein.addDBRef(db1);
708 hasUniprotDbref = true;
713 * if we have a product (translation) but no explicit Uniprot dbref
714 * (example: EMBL M19487 protein_id AAB02592.1)
715 * then construct mappings to an assumed EMBLCDSPROTEIN accession
717 if (!hasUniprotDbref)
719 SequenceI protein = proteins.get(data.proteinId);
722 protein = new Sequence(data.proteinId, data.translation);
723 protein.setDescription(data.proteinName);
724 proteins.put(data.proteinId, protein);
726 // assuming CDSPROTEIN sequence version = dna version (?!)
727 DBRefEntry db1 = new DBRefEntry(DBRefSource.EMBLCDSProduct,
728 this.version, data.proteinId);
729 protein.addDBRef(db1);
731 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
732 DBRefSource.EMBLCDSProduct, this.version, data.proteinId);
733 Mapping map = new Mapping(protein, maplist);
734 map.setMappedFromId(data.proteinId);
735 dnaToEmblProteinRef.setMap(map);
736 dna.addDBRef(dnaToEmblProteinRef);
740 * comment brought forward from EmblXmlSource, lines 447-451:
741 * TODO: if retrieved from EMBLCDS, add a DBRef back to the parent EMBL
742 * sequence with the exon map; if given a dataset reference, search
743 * dataset for parent EMBL sequence if it exists and set its map;
744 * make a new feature annotating the coding contig
749 * Computes a mapping from CDS positions in DNA sequence to protein product
750 * positions, with allowance for stop codon or incomplete start codon
757 MapList buildMappingToProtein(final SequenceI dna, final int[] exons,
760 MapList dnaToProteinMapping = null;
761 int peptideLength = data.translation.length();
763 int[] proteinRange = new int[] { 1, peptideLength };
764 if (exons != null && exons.length > 0)
767 * We were able to parse 'location'; do a final
768 * product length truncation check
770 int[] cdsRanges = adjustForProteinLength(peptideLength, exons);
771 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
776 * workaround until we handle all 'location' formats fully
777 * e.g. X53828.1:60..1058 or <123..>289
779 Cache.log.error(String.format(
780 "Implementation Notice: EMBLCDS location '%s'not properly supported yet"
781 + " - Making up the CDNA region of (%s:%s)... may be incorrect",
782 data.cdsLocation, sourceDb, this.accession));
784 int completeCodonsLength = 1 - data.codonStart + dna.getLength();
785 int mappedDnaEnd = dna.getEnd();
786 if (peptideLength * 3 == completeCodonsLength)
788 // this might occur for CDS sequences where no features are marked
789 Cache.log.warn("Assuming no stop codon at end of cDNA fragment");
790 mappedDnaEnd = dna.getEnd();
792 else if ((peptideLength + 1) * 3 == completeCodonsLength)
794 Cache.log.warn("Assuming stop codon at end of cDNA fragment");
795 mappedDnaEnd = dna.getEnd() - 3;
798 if (mappedDnaEnd != -1)
800 int[] cdsRanges = new int[] {
801 dna.getStart() + (data.codonStart - 1), mappedDnaEnd };
802 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
806 return dnaToProteinMapping;
810 * Constructs a sequence for the protein product for the CDS data (if there is
811 * one), and dbrefs with mappings from CDS to protein and the reverse
819 SequenceI buildProteinProduct(SequenceI dna, DBRefEntry xref,
820 CdsData data, Map<String, SequenceI> proteins)
823 * check we have some data to work with
825 if (data.proteinId == null || data.translation == null)
831 * Construct the protein sequence (if not already seen)
833 String proteinSeqName = xref.getSource() + "|" + xref.getAccessionId();
834 SequenceI protein = proteins.get(proteinSeqName);
837 protein = new Sequence(proteinSeqName, data.translation, 1,
838 data.translation.length());
839 protein.setDescription(data.proteinName != null ? data.proteinName
840 : "Protein Product from " + sourceDb);
841 proteins.put(proteinSeqName, protein);
848 * Returns the CDS location as a single array of [start, end, start, end...]
849 * positions. If on the reverse strand, these will be in descending order.
855 protected int[] getCdsRanges(String accession, String location)
857 if (location == null)
864 List<int[]> ranges = DnaUtils.parseLocation(location);
865 return MappingUtils.listToArray(ranges);
866 } catch (ParseException e)
869 String.format("Not parsing inexact CDS location %s in ENA %s",
870 location, accession));
876 * Output (print) is not implemented for EMBL flat file format
879 public String print(SequenceI[] seqs, boolean jvsuffix)
885 * Truncates (if necessary) the exon intervals to match 3 times the length of
886 * the protein; also accepts 3 bases longer (for stop codon not included in
889 * @param proteinLength
891 * an array of [start, end, start, end...] intervals
892 * @return the same array (if unchanged) or a truncated copy
894 static int[] adjustForProteinLength(int proteinLength, int[] exon)
896 if (proteinLength <= 0 || exon == null)
900 int expectedCdsLength = proteinLength * 3;
901 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
904 * if exon length matches protein, or is shorter, then leave it unchanged
906 if (expectedCdsLength >= exonLength)
914 origxon = new int[exon.length];
915 System.arraycopy(exon, 0, origxon, 0, exon.length);
917 for (int x = 0; x < exon.length; x += 2)
919 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
920 if (expectedCdsLength <= cdspos)
922 // advanced beyond last codon.
924 if (expectedCdsLength != cdspos)
927 // .println("Truncating final exon interval on region by "
928 // + (cdspos - cdslength));
932 * shrink the final exon - reduce end position if forward
933 * strand, increase it if reverse
935 if (exon[x + 1] >= exon[x])
937 endxon = exon[x + 1] - cdspos + expectedCdsLength;
941 endxon = exon[x + 1] + cdspos - expectedCdsLength;
949 // and trim the exon interval set if necessary
950 int[] nxon = new int[sxpos + 2];
951 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
952 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon