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;
10 import java.util.Locale;
12 import java.util.Map.Entry;
13 import java.util.TreeMap;
15 import jalview.bin.Console;
16 import jalview.datamodel.DBRefEntry;
17 import jalview.datamodel.DBRefSource;
18 import jalview.datamodel.FeatureProperties;
19 import jalview.datamodel.Mapping;
20 import jalview.datamodel.Sequence;
21 import jalview.datamodel.SequenceFeature;
22 import jalview.datamodel.SequenceI;
23 import jalview.util.DBRefUtils;
24 import jalview.util.DnaUtils;
25 import jalview.util.MapList;
26 import jalview.util.MappingUtils;
29 * A base class to support parsing of GenBank, EMBL or DDBJ flat file format
30 * data. Example files (rather than formal specifications) are provided at
33 * https://ena-docs.readthedocs.io/en/latest/submit/fileprep/flat-file-example.html
34 * https://www.ncbi.nlm.nih.gov/Sitemap/samplerecord.html
37 * or to compare the same entry, see
40 * https://www.ebi.ac.uk/ena/browser/api/embl/X81322.1
41 * https://www.ncbi.nlm.nih.gov/nuccore/X81322.1
44 * The feature table part of the file has a common definition, only the start of
45 * each line is formatted differently in GenBank and EMBL. See
46 * http://www.insdc.org/files/feature_table.html#7.1.
48 public abstract class EMBLLikeFlatFile extends AlignFile
50 protected static final String LOCATION = "location";
52 protected static final String QUOTE = "\"";
54 protected static final String DOUBLED_QUOTE = QUOTE + QUOTE;
56 protected static final String WHITESPACE = "\\s+";
59 * Removes leading or trailing double quotes (") unless doubled, and changes
60 * any 'escaped' (doubled) double quotes to single characters. As per the
61 * Feature Table specification for Qualifiers, Free Text.
66 protected static String removeQuotes(String value)
72 if (value.startsWith(QUOTE) && !value.startsWith(DOUBLED_QUOTE))
74 value = value.substring(1);
76 if (value.endsWith(QUOTE) && !value.endsWith(DOUBLED_QUOTE))
78 value = value.substring(0, value.length() - 1);
80 value = value.replace(DOUBLED_QUOTE, QUOTE);
85 * Truncates (if necessary) the exon intervals to match 3 times the length of
86 * the protein(including truncation for stop codon included in exon)
88 * @param proteinLength
90 * an array of [start, end, start, end...] intervals
91 * @return the same array (if unchanged) or a truncated copy
93 protected static int[] adjustForProteinLength(int proteinLength,
96 if (proteinLength <= 0 || exon == null)
100 int expectedCdsLength = proteinLength * 3;
101 int exonLength = MappingUtils.getLength(Arrays.asList(exon));
104 * if exon length matches protein, or is shorter, then leave it unchanged
106 if (expectedCdsLength >= exonLength)
114 origxon = new int[exon.length];
115 System.arraycopy(exon, 0, origxon, 0, exon.length);
117 for (int x = 0; x < exon.length; x += 2)
119 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
120 if (expectedCdsLength <= cdspos)
122 // advanced beyond last codon.
124 if (expectedCdsLength != cdspos)
127 // .println("Truncating final exon interval on region by "
128 // + (cdspos - cdslength));
132 * shrink the final exon - reduce end position if forward
133 * strand, increase it if reverse
135 if (exon[x + 1] >= exon[x])
137 endxon = exon[x + 1] - cdspos + expectedCdsLength;
141 endxon = exon[x + 1] + cdspos - expectedCdsLength;
149 // and trim the exon interval set if necessary
150 int[] nxon = new int[sxpos + 2];
151 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
152 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
160 * when true, interpret the mol_type 'source' feature attribute
161 * and generate an RNA sequence from the DNA record
163 protected boolean produceRna = true;
166 * values parsed from the data file
168 protected String sourceDb;
170 protected String accession;
172 protected String version;
174 protected String description;
176 protected int length = 128;
178 protected List<DBRefEntry> dbrefs;
180 protected boolean sequenceStringIsRNA = false;
182 protected String sequenceString;
184 protected Map<String, CdsData> cds;
191 * @throws IOException
193 public EMBLLikeFlatFile(FileParse fp, String sourceId) throws IOException
195 super(false, fp); // don't parse immediately
196 this.sourceDb = sourceId;
197 dbrefs = new ArrayList<>();
200 * using TreeMap gives CDS sequences in alphabetical, so readable, order
202 cds = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
208 * process attributes for 'source' until the next FT feature entry only
209 * interested in 'mol_type'
213 * @throws IOException
215 private String parseSourceQualifiers(String[] tokens) throws IOException
217 if (!"source".equals(tokens[0]))
219 throw (new RuntimeException("Not given a 'source' qualifier line"));
221 // search for mol_type attribute
223 StringBuilder sb = new StringBuilder().append(tokens[1]); // extent of
226 String line = parseFeatureQualifier(sb, false);
229 if (!line.startsWith("FT ")) // four spaces, end of this feature table
236 int p = line.indexOf("\\mol_type");
237 int qs = line.indexOf("\"", p);
238 int qe = line.indexOf("\"", qs + 1);
239 String qualifier = line.substring(qs, qe).toLowerCase(Locale.ROOT);
240 if (qualifier.indexOf("rna") > -1)
242 sequenceStringIsRNA = true;
244 if (qualifier.indexOf("dna") > -1)
246 sequenceStringIsRNA = false;
248 line = parseFeatureQualifier(sb, false);
254 * Parses one (GenBank or EMBL format) CDS feature, saves the parsed data, and
255 * returns the next line
259 * @throws IOException
261 protected String parseCDSFeature(String location) throws IOException
266 * parse location, which can be over >1 line e.g. EAW51554
268 CdsData data = new CdsData();
269 StringBuilder sb = new StringBuilder().append(location);
270 line = parseFeatureQualifier(sb, false);
271 data.cdsLocation = sb.toString();
275 if (!isFeatureContinuationLine(line))
277 // e.g. start of next feature "FT source..."
282 * extract qualifier, e.g. FT /protein_id="CAA37824.1"
283 * - the value may extend over more than one line
284 * - if the value has enclosing quotes, these are removed
285 * - escaped double quotes ("") are reduced to a single character
287 int slashPos = line.indexOf('/');
290 Console.error("Unexpected EMBL line ignored: " + line);
294 int eqPos = line.indexOf('=', slashPos + 1);
297 // can happen, e.g. /ribosomal_slippage
301 String qualifier = line.substring(slashPos + 1, eqPos);
302 String value = line.substring(eqPos + 1);
303 value = removeQuotes(value);
304 sb = new StringBuilder().append(value);
305 boolean asText = !"translation".equals(qualifier);
306 line = parseFeatureQualifier(sb, asText);
307 String featureValue = sb.toString();
309 if ("protein_id".equals(qualifier))
311 data.proteinId = featureValue;
313 else if ("codon_start".equals(qualifier))
317 data.codonStart = Integer.parseInt(featureValue.trim());
318 } catch (NumberFormatException e)
320 Console.error("Invalid codon_start in XML for " + this.accession
321 + ": " + e.getMessage());
324 else if ("db_xref".equals(qualifier))
326 String[] parts = featureValue.split(":");
327 if (parts.length == 2)
329 String db = parts[0].trim();
330 db = DBRefUtils.getCanonicalName(db);
331 DBRefEntry dbref = new DBRefEntry(db, "0", parts[1].trim());
332 data.xrefs.add(dbref);
335 else if ("product".equals(qualifier))
337 data.proteinName = featureValue;
339 else if ("translation".equals(qualifier))
341 data.translation = featureValue;
343 else if (!"".equals(featureValue))
345 // throw anything else into the additional properties hash
346 data.cdsProps.put(qualifier, featureValue);
350 if (data.proteinId != null)
352 this.cds.put(data.proteinId, data);
356 Console.error("Ignoring CDS feature with no protein_id for "
357 + sourceDb + ":" + accession);
363 protected abstract boolean isFeatureContinuationLine(String line);
366 * Output (print) is not (yet) implemented for flat file format
369 public String print(SequenceI[] seqs, boolean jvsuffix)
375 * Constructs and saves the sequence from parsed components
377 protected void buildSequence()
379 if (this.accession == null || this.sequenceString == null)
381 Console.error("Failed to parse data from EMBL");
385 String name = this.accession;
386 if (this.sourceDb != null)
388 name = this.sourceDb + "|" + name;
391 if (produceRna && sequenceStringIsRNA)
393 sequenceString = sequenceString.replace('T', 'U').replace('t', 'u');
396 SequenceI seq = new Sequence(name, this.sequenceString);
397 seq.setDescription(this.description);
400 * add a DBRef to itself
402 DBRefEntry selfRef = new DBRefEntry(sourceDb, version, accession);
403 int[] startEnd = new int[] { 1, seq.getLength() };
404 selfRef.setMap(new Mapping(null, startEnd, startEnd, 1, 1));
405 seq.addDBRef(selfRef);
407 for (DBRefEntry dbref : this.dbrefs)
412 processCDSFeatures(seq);
414 seq.deriveSequence();
420 * Process the CDS features, including generation of cross-references and
421 * mappings to the protein products (translation)
425 protected void processCDSFeatures(SequenceI seq)
428 * record protein products found to avoid duplication i.e. >1 CDS with
429 * the same /protein_id [though not sure I can find an example of this]
431 Map<String, SequenceI> proteins = new HashMap<>();
432 for (CdsData data : cds.values())
434 processCDSFeature(seq, data, proteins);
439 * Processes data for one parsed CDS feature to
441 * <li>create a protein product sequence for the translation</li>
442 * <li>create a cross-reference to protein with mapping from dna</li>
443 * <li>add a CDS feature to the sequence for each CDS start-end range</li>
444 * <li>add any CDS dbrefs to the sequence and to the protein product</li>
450 * map of protein products so far derived from CDS data
452 void processCDSFeature(SequenceI dna, CdsData data,
453 Map<String, SequenceI> proteins)
456 * parse location into a list of [start, end, start, end] positions
458 int[] exons = getCdsRanges(this.accession, data.cdsLocation);
460 MapList maplist = buildMappingToProtein(dna, exons, data);
464 for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
466 int exonStart = exons[xint];
467 int exonEnd = exons[xint + 1];
468 int begin = Math.min(exonStart, exonEnd);
469 int end = Math.max(exonStart, exonEnd);
471 String desc = String.format("Exon %d for protein EMBLCDS:%s",
472 exonNumber, data.proteinId);
474 SequenceFeature sf = new SequenceFeature("CDS", desc, begin, end,
476 for (Entry<String, String> val : data.cdsProps.entrySet())
478 sf.setValue(val.getKey(), val.getValue());
481 sf.setEnaLocation(data.cdsLocation);
482 boolean forwardStrand = exonStart <= exonEnd;
483 sf.setStrand(forwardStrand ? "+" : "-");
484 sf.setPhase(String.valueOf(data.codonStart - 1));
485 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
486 sf.setValue(FeatureProperties.EXONPRODUCT, data.proteinName);
488 dna.addSequenceFeature(sf);
491 boolean hasUniprotDbref = false;
492 for (DBRefEntry xref : data.xrefs)
495 if (xref.getSource().equals(DBRefSource.UNIPROT))
498 * construct (or find) the sequence for (data.protein_id, data.translation)
500 SequenceI protein = buildProteinProduct(dna, xref, data, proteins);
501 Mapping map = new Mapping(protein, maplist);
502 map.setMappedFromId(data.proteinId);
506 * add DBRefs with mappings from dna to protein and the inverse
508 DBRefEntry db1 = new DBRefEntry(sourceDb, version, accession);
509 db1.setMap(new Mapping(dna, maplist.getInverse()));
510 protein.addDBRef(db1);
512 hasUniprotDbref = true;
517 * if we have a product (translation) but no explicit Uniprot dbref
518 * (example: EMBL M19487 protein_id AAB02592.1)
519 * then construct mappings to an assumed EMBLCDSPROTEIN accession
521 if (!hasUniprotDbref)
523 SequenceI protein = proteins.get(data.proteinId);
526 protein = new Sequence(data.proteinId, data.translation);
527 protein.setDescription(data.proteinName);
528 proteins.put(data.proteinId, protein);
530 // assuming CDSPROTEIN sequence version = dna version (?!)
531 DBRefEntry db1 = new DBRefEntry(DBRefSource.EMBLCDSProduct,
532 this.version, data.proteinId);
533 protein.addDBRef(db1);
535 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
536 DBRefSource.EMBLCDSProduct, this.version, data.proteinId);
537 Mapping map = new Mapping(protein, maplist);
538 map.setMappedFromId(data.proteinId);
539 dnaToEmblProteinRef.setMap(map);
540 dna.addDBRef(dnaToEmblProteinRef);
544 * comment brought forward from EmblXmlSource, lines 447-451:
545 * TODO: if retrieved from EMBLCDS, add a DBRef back to the parent EMBL
546 * sequence with the exon map; if given a dataset reference, search
547 * dataset for parent EMBL sequence if it exists and set its map;
548 * make a new feature annotating the coding contig
553 * Computes a mapping from CDS positions in DNA sequence to protein product
554 * positions, with allowance for stop codon or incomplete start codon
561 MapList buildMappingToProtein(final SequenceI dna, final int[] exons,
564 MapList dnaToProteinMapping = null;
565 int peptideLength = data.translation.length();
567 int[] proteinRange = new int[] { 1, peptideLength };
568 if (exons != null && exons.length > 0)
571 * We were able to parse 'location'; do a final
572 * product length truncation check
574 int[] cdsRanges = adjustForProteinLength(peptideLength, exons);
575 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
580 * workaround until we handle all 'location' formats fully
581 * e.g. X53828.1:60..1058 or <123..>289
583 Console.error(String.format(
584 "Implementation Notice: EMBLCDS location '%s'not properly supported yet"
585 + " - Making up the CDNA region of (%s:%s)... may be incorrect",
586 data.cdsLocation, sourceDb, this.accession));
588 int completeCodonsLength = 1 - data.codonStart + dna.getLength();
589 int mappedDnaEnd = dna.getEnd();
590 if (peptideLength * 3 == completeCodonsLength)
592 // this might occur for CDS sequences where no features are marked
593 Console.warn("Assuming no stop codon at end of cDNA fragment");
594 mappedDnaEnd = dna.getEnd();
596 else if ((peptideLength + 1) * 3 == completeCodonsLength)
598 Console.warn("Assuming stop codon at end of cDNA fragment");
599 mappedDnaEnd = dna.getEnd() - 3;
602 if (mappedDnaEnd != -1)
604 int[] cdsRanges = new int[] {
605 dna.getStart() + (data.codonStart - 1), mappedDnaEnd };
606 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
610 return dnaToProteinMapping;
614 * Constructs a sequence for the protein product for the CDS data (if there is
615 * one), and dbrefs with mappings from CDS to protein and the reverse
623 SequenceI buildProteinProduct(SequenceI dna, DBRefEntry xref,
624 CdsData data, Map<String, SequenceI> proteins)
627 * check we have some data to work with
629 if (data.proteinId == null || data.translation == null)
635 * Construct the protein sequence (if not already seen)
637 String proteinSeqName = xref.getSource() + "|" + xref.getAccessionId();
638 SequenceI protein = proteins.get(proteinSeqName);
641 protein = new Sequence(proteinSeqName, data.translation, 1,
642 data.translation.length());
643 protein.setDescription(data.proteinName != null ? data.proteinName
644 : "Protein Product from " + sourceDb);
645 proteins.put(proteinSeqName, protein);
652 * Returns the CDS location as a single array of [start, end, start, end...]
653 * positions. If on the reverse strand, these will be in descending order.
659 protected int[] getCdsRanges(String accession, String location)
661 if (location == null)
668 List<int[]> ranges = DnaUtils.parseLocation(location);
669 return MappingUtils.rangeListToArray(ranges);
670 } catch (ParseException e)
673 String.format("Not parsing inexact CDS location %s in ENA %s",
674 location, accession));
680 * Reads the value of a feature (FT) qualifier from one or more lines of the
681 * file, and returns the next line after that. Values are appended to the
682 * string buffer, which should be already primed with the value read from the
683 * first line for the qualifier (with any leading double quote removed).
684 * Enclosing double quotes are removed, and escaped (repeated) double quotes
685 * reduced to one only. For example for
688 * FT /note="gene_id=hCG28070.3
689 * FT ""foobar"" isoform=CRA_b"
690 * the returned value is
691 * gene_id=hCG28070.3 "foobar" isoform=CRA_b
694 * Note the side-effect of this method, to advance data reading to the next
695 * line after the feature qualifier (which could be another qualifier, a
696 * different feature, a non-feature line, or null at end of file).
699 * a string buffer primed with the first line of the value
702 * @throws IOException
704 String parseFeatureQualifier(StringBuilder sb, boolean asText)
708 while ((line = nextLine()) != null)
710 if (!isFeatureContinuationLine(line))
712 break; // reached next feature or other input line
714 String[] tokens = line.split(WHITESPACE);
715 if (tokens.length < 2)
717 Console.error("Ignoring bad EMBL line for " + this.accession + ": "
721 if (tokens[1].startsWith("/"))
723 break; // next feature qualifier
727 * if text (e.g. /product), add a word separator for a new line,
728 * else (e.g. /translation) don't
736 * remove trailing " and unescape doubled ""
738 String data = removeQuotes(tokens[1]);
746 * Reads and saves the sequence, read from the lines following the ORIGIN
747 * (GenBank) or SQ (EMBL) line. Whitespace and position counters are
748 * discarded. Returns the next line following the sequence data (the next line
749 * that doesn't start with whitespace).
751 * @throws IOException
753 protected String parseSequence() throws IOException
755 StringBuilder sb = new StringBuilder(this.length);
756 String line = nextLine();
757 while (line != null && line.startsWith(" "))
760 String[] blocks = line.split(WHITESPACE);
763 * the first or last block on each line might be a position count - omit
765 for (int i = 0; i < blocks.length; i++)
769 Long.parseLong(blocks[i]);
770 // position counter - ignore it
771 } catch (NumberFormatException e)
773 // sequence data - append it
774 sb.append(blocks[i]);
779 this.sequenceString = sb.toString();
785 * Processes a feature line. If it declares a feature type of interest
786 * (currently, only CDS is processed), processes all of the associated lines
787 * (feature qualifiers), and returns the next line after that, otherwise
788 * simply returns the next line.
791 * the first line for the feature (with initial FT omitted for EMBL
794 * @throws IOException
796 protected String parseFeature(String line) throws IOException
798 String[] tokens = line.trim().split(WHITESPACE);
799 if (tokens.length < 2
800 || (!"CDS".equals(tokens[0]) && (!"source".equals(tokens[0]))))
804 if (tokens[0].equals("source"))
806 return parseSourceQualifiers(tokens);
808 return parseCDSFeature(tokens[1]);
813 * A data bean class to hold values parsed from one CDS Feature
817 String translation; // from /translation qualifier
819 String cdsLocation; // the raw value e.g. join(1..1234,2012..2837)
821 int codonStart = 1; // from /codon_start qualifier
823 String proteinName; // from /product qualifier; used for protein description
825 String proteinId; // from /protein_id qualifier
827 List<DBRefEntry> xrefs = new ArrayList<>(); // from /db_xref qualifiers
829 Map<String, String> cdsProps = new Hashtable<>(); // other qualifiers