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 base class to support parsing of GenBank, EMBL or DDBJ flat file format
29 * data. Example files (rather than formal specifications) are provided at
32 * https://ena-docs.readthedocs.io/en/latest/submit/fileprep/flat-file-example.html
33 * https://www.ncbi.nlm.nih.gov/Sitemap/samplerecord.html
36 * or to compare the same entry, see
39 * https://www.ebi.ac.uk/ena/browser/api/embl/X81322.1
40 * https://www.ncbi.nlm.nih.gov/nuccore/X81322.1
43 * The feature table part of the file has a common definition, only the start of
44 * each line is formatted differently in GenBank and EMBL. See
45 * http://www.insdc.org/files/feature_table.html#7.1.
47 public abstract class FlatFile extends AlignFile
49 protected static final String LOCATION = "location";
51 protected static final String QUOTE = "\"";
53 protected static final String DOUBLED_QUOTE = QUOTE + QUOTE;
55 protected static final String WHITESPACE = "\\s+";
58 * Removes leading or trailing double quotes (") unless doubled, and changes
59 * any 'escaped' (doubled) double quotes to single characters. As per the
60 * Feature Table specification for Qualifiers, Free Text.
65 protected static String removeQuotes(String value)
71 if (value.startsWith(QUOTE) && !value.startsWith(DOUBLED_QUOTE))
73 value = value.substring(1);
75 if (value.endsWith(QUOTE) && !value.endsWith(DOUBLED_QUOTE))
77 value = value.substring(0, value.length() - 1);
79 value = value.replace(DOUBLED_QUOTE, QUOTE);
84 * Truncates (if necessary) the exon intervals to match 3 times the length of
85 * the protein; also accepts 3 bases longer (for stop codon not included in
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, or longer by the
105 * length of a stop codon (3 bases), then leave it unchanged
107 if (expectedCdsLength >= exonLength
108 || expectedCdsLength == exonLength - 3)
116 origxon = new int[exon.length];
117 System.arraycopy(exon, 0, origxon, 0, exon.length);
119 for (int x = 0; x < exon.length; x += 2)
121 cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
122 if (expectedCdsLength <= cdspos)
124 // advanced beyond last codon.
126 if (expectedCdsLength != cdspos)
129 // .println("Truncating final exon interval on region by "
130 // + (cdspos - cdslength));
134 * shrink the final exon - reduce end position if forward
135 * strand, increase it if reverse
137 if (exon[x + 1] >= exon[x])
139 endxon = exon[x + 1] - cdspos + expectedCdsLength;
143 endxon = exon[x + 1] + cdspos - expectedCdsLength;
151 // and trim the exon interval set if necessary
152 int[] nxon = new int[sxpos + 2];
153 System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
154 nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
162 * values parsed from the data file
164 protected String sourceDb;
166 protected String accession;
168 protected String version;
170 protected String description;
172 protected int length = 128;
174 protected List<DBRefEntry> dbrefs;
176 protected String sequenceString;
178 protected Map<String, CdsData> cds;
185 * @throws IOException
187 public FlatFile(FileParse fp, String sourceId) throws IOException
189 super(false, fp); // don't parse immediately
190 this.sourceDb = sourceId;
191 dbrefs = new ArrayList<>();
194 * using TreeMap gives CDS sequences in alphabetical, so readable, order
196 cds = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
202 * Parses one (GenBank or EMBL format) CDS feature, saves the parsed data, and
203 * returns the next line
207 * @throws IOException
209 protected String parseCDSFeature(String location) throws IOException
214 * parse location, which can be over >1 line e.g. EAW51554
216 CdsData data = new CdsData();
217 StringBuilder sb = new StringBuilder().append(location);
218 line = parseFeatureQualifier(sb, false);
219 data.cdsLocation = sb.toString();
223 if (!isFeatureContinuationLine(line))
225 // e.g. start of next feature "FT source..."
230 * extract qualifier, e.g. FT /protein_id="CAA37824.1"
231 * - the value may extend over more than one line
232 * - if the value has enclosing quotes, these are removed
233 * - escaped double quotes ("") are reduced to a single character
235 int slashPos = line.indexOf('/');
238 Cache.log.error("Unexpected EMBL line ignored: " + line);
242 int eqPos = line.indexOf('=', slashPos + 1);
245 // can happen, e.g. /ribosomal_slippage
249 String qualifier = line.substring(slashPos + 1, eqPos);
250 String value = line.substring(eqPos + 1);
251 value = removeQuotes(value);
252 sb = new StringBuilder().append(value);
253 boolean asText = !"translation".equals(qualifier);
254 line = parseFeatureQualifier(sb, asText);
255 String featureValue = sb.toString();
257 if ("protein_id".equals(qualifier))
259 data.proteinId = featureValue;
261 else if ("codon_start".equals(qualifier))
265 data.codonStart = Integer.parseInt(featureValue.trim());
266 } catch (NumberFormatException e)
268 Cache.log.error("Invalid codon_start in XML for " + this.accession
269 + ": " + e.getMessage());
272 else if ("db_xref".equals(qualifier))
274 String[] parts = featureValue.split(":");
275 if (parts.length == 2)
277 String db = parts[0].trim();
278 db = DBRefUtils.getCanonicalName(db);
279 DBRefEntry dbref = new DBRefEntry(db, "0", parts[1].trim());
280 data.xrefs.add(dbref);
283 else if ("product".equals(qualifier))
285 data.proteinName = featureValue;
287 else if ("translation".equals(qualifier))
289 data.translation = featureValue;
291 else if (!"".equals(featureValue))
293 // throw anything else into the additional properties hash
294 data.cdsProps.put(qualifier, featureValue);
298 if (data.proteinId != null)
300 this.cds.put(data.proteinId, data);
304 Cache.log.error("Ignoring CDS feature with no protein_id for "
305 + sourceDb + ":" + accession);
311 protected abstract boolean isFeatureContinuationLine(String line);
314 * Output (print) is not (yet) implemented for flat file format
317 public String print(SequenceI[] seqs, boolean jvsuffix)
323 * Constructs and saves the sequence from parsed components
325 protected void buildSequence()
327 if (this.accession == null || this.sequenceString == null)
329 Cache.log.error("Failed to parse data from EMBL");
333 String name = this.accession;
334 if (this.sourceDb != null)
336 name = this.sourceDb + "|" + name;
338 SequenceI seq = new Sequence(name, this.sequenceString);
339 seq.setDescription(this.description);
342 * add a DBRef to itself
344 DBRefEntry selfRef = new DBRefEntry(sourceDb, version, accession);
345 int[] startEnd = new int[] { 1, seq.getLength() };
346 selfRef.setMap(new Mapping(null, startEnd, startEnd, 1, 1));
347 seq.addDBRef(selfRef);
349 for (DBRefEntry dbref : this.dbrefs)
354 processCDSFeatures(seq);
356 seq.deriveSequence();
362 * Process the CDS features, including generation of cross-references and
363 * mappings to the protein products (translation)
367 protected void processCDSFeatures(SequenceI seq)
370 * record protein products found to avoid duplication i.e. >1 CDS with
371 * the same /protein_id [though not sure I can find an example of this]
373 Map<String, SequenceI> proteins = new HashMap<>();
374 for (CdsData data : cds.values())
376 processCDSFeature(seq, data, proteins);
381 * Processes data for one parsed CDS feature to
383 * <li>create a protein product sequence for the translation</li>
384 * <li>create a cross-reference to protein with mapping from dna</li>
385 * <li>add a CDS feature to the sequence for each CDS start-end range</li>
386 * <li>add any CDS dbrefs to the sequence and to the protein product</li>
392 * map of protein products so far derived from CDS data
394 void processCDSFeature(SequenceI dna, CdsData data,
395 Map<String, SequenceI> proteins)
398 * parse location into a list of [start, end, start, end] positions
400 int[] exons = getCdsRanges(this.accession, data.cdsLocation);
402 MapList maplist = buildMappingToProtein(dna, exons, data);
406 for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
408 int exonStart = exons[xint];
409 int exonEnd = exons[xint + 1];
410 int begin = Math.min(exonStart, exonEnd);
411 int end = Math.max(exonStart, exonEnd);
413 String desc = String.format("Exon %d for protein EMBLCDS:%s",
414 exonNumber, data.proteinId);
416 SequenceFeature sf = new SequenceFeature("CDS", desc, begin, end,
418 for (Entry<String, String> val : data.cdsProps.entrySet())
420 sf.setValue(val.getKey(), val.getValue());
423 sf.setEnaLocation(data.cdsLocation);
424 boolean forwardStrand = exonStart <= exonEnd;
425 sf.setStrand(forwardStrand ? "+" : "-");
426 sf.setPhase(String.valueOf(data.codonStart - 1));
427 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
428 sf.setValue(FeatureProperties.EXONPRODUCT, data.proteinName);
430 dna.addSequenceFeature(sf);
433 boolean hasUniprotDbref = false;
434 for (DBRefEntry xref : data.xrefs)
437 if (xref.getSource().equals(DBRefSource.UNIPROT))
440 * construct (or find) the sequence for (data.protein_id, data.translation)
442 SequenceI protein = buildProteinProduct(dna, xref, data, proteins);
443 Mapping map = new Mapping(protein, maplist);
444 map.setMappedFromId(data.proteinId);
448 * add DBRefs with mappings from dna to protein and the inverse
450 DBRefEntry db1 = new DBRefEntry(sourceDb, version, accession);
451 db1.setMap(new Mapping(dna, maplist.getInverse()));
452 protein.addDBRef(db1);
454 hasUniprotDbref = true;
459 * if we have a product (translation) but no explicit Uniprot dbref
460 * (example: EMBL M19487 protein_id AAB02592.1)
461 * then construct mappings to an assumed EMBLCDSPROTEIN accession
463 if (!hasUniprotDbref)
465 SequenceI protein = proteins.get(data.proteinId);
468 protein = new Sequence(data.proteinId, data.translation);
469 protein.setDescription(data.proteinName);
470 proteins.put(data.proteinId, protein);
472 // assuming CDSPROTEIN sequence version = dna version (?!)
473 DBRefEntry db1 = new DBRefEntry(DBRefSource.EMBLCDSProduct,
474 this.version, data.proteinId);
475 protein.addDBRef(db1);
477 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
478 DBRefSource.EMBLCDSProduct, this.version, data.proteinId);
479 Mapping map = new Mapping(protein, maplist);
480 map.setMappedFromId(data.proteinId);
481 dnaToEmblProteinRef.setMap(map);
482 dna.addDBRef(dnaToEmblProteinRef);
486 * comment brought forward from EmblXmlSource, lines 447-451:
487 * TODO: if retrieved from EMBLCDS, add a DBRef back to the parent EMBL
488 * sequence with the exon map; if given a dataset reference, search
489 * dataset for parent EMBL sequence if it exists and set its map;
490 * make a new feature annotating the coding contig
495 * Computes a mapping from CDS positions in DNA sequence to protein product
496 * positions, with allowance for stop codon or incomplete start codon
503 MapList buildMappingToProtein(final SequenceI dna, final int[] exons,
506 MapList dnaToProteinMapping = null;
507 int peptideLength = data.translation.length();
509 int[] proteinRange = new int[] { 1, peptideLength };
510 if (exons != null && exons.length > 0)
513 * We were able to parse 'location'; do a final
514 * product length truncation check
516 int[] cdsRanges = adjustForProteinLength(peptideLength, exons);
517 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
522 * workaround until we handle all 'location' formats fully
523 * e.g. X53828.1:60..1058 or <123..>289
525 Cache.log.error(String.format(
526 "Implementation Notice: EMBLCDS location '%s'not properly supported yet"
527 + " - Making up the CDNA region of (%s:%s)... may be incorrect",
528 data.cdsLocation, sourceDb, this.accession));
530 int completeCodonsLength = 1 - data.codonStart + dna.getLength();
531 int mappedDnaEnd = dna.getEnd();
532 if (peptideLength * 3 == completeCodonsLength)
534 // this might occur for CDS sequences where no features are marked
535 Cache.log.warn("Assuming no stop codon at end of cDNA fragment");
536 mappedDnaEnd = dna.getEnd();
538 else if ((peptideLength + 1) * 3 == completeCodonsLength)
540 Cache.log.warn("Assuming stop codon at end of cDNA fragment");
541 mappedDnaEnd = dna.getEnd() - 3;
544 if (mappedDnaEnd != -1)
546 int[] cdsRanges = new int[] {
547 dna.getStart() + (data.codonStart - 1), mappedDnaEnd };
548 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
552 return dnaToProteinMapping;
556 * Constructs a sequence for the protein product for the CDS data (if there is
557 * one), and dbrefs with mappings from CDS to protein and the reverse
565 SequenceI buildProteinProduct(SequenceI dna, DBRefEntry xref,
566 CdsData data, Map<String, SequenceI> proteins)
569 * check we have some data to work with
571 if (data.proteinId == null || data.translation == null)
577 * Construct the protein sequence (if not already seen)
579 String proteinSeqName = xref.getSource() + "|" + xref.getAccessionId();
580 SequenceI protein = proteins.get(proteinSeqName);
583 protein = new Sequence(proteinSeqName, data.translation, 1,
584 data.translation.length());
585 protein.setDescription(data.proteinName != null ? data.proteinName
586 : "Protein Product from " + sourceDb);
587 proteins.put(proteinSeqName, protein);
594 * Returns the CDS location as a single array of [start, end, start, end...]
595 * positions. If on the reverse strand, these will be in descending order.
601 protected int[] getCdsRanges(String accession, String location)
603 if (location == null)
610 List<int[]> ranges = DnaUtils.parseLocation(location);
611 return MappingUtils.listToArray(ranges);
612 } catch (ParseException e)
615 String.format("Not parsing inexact CDS location %s in ENA %s",
616 location, accession));
622 * Reads the value of a feature (FT) qualifier from one or more lines of the
623 * file, and returns the next line after that. Values are appended to the
624 * string buffer, which should be already primed with the value read from the
625 * first line for the qualifier (with any leading double quote removed).
626 * Enclosing double quotes are removed, and escaped (repeated) double quotes
627 * reduced to one only. For example for
630 * FT /note="gene_id=hCG28070.3
631 * FT ""foobar"" isoform=CRA_b"
632 * the returned value is
633 * gene_id=hCG28070.3 "foobar" isoform=CRA_b
636 * Note the side-effect of this method, to advance data reading to the next
637 * line after the feature qualifier (which could be another qualifier, a
638 * different feature, a non-feature line, or null at end of file).
641 * a string buffer primed with the first line of the value
644 * @throws IOException
646 String parseFeatureQualifier(StringBuilder sb, boolean asText)
650 while ((line = nextLine()) != null)
652 if (!isFeatureContinuationLine(line))
654 break; // reached next feature or other input line
656 String[] tokens = line.split(WHITESPACE);
657 if (tokens.length < 2)
659 Cache.log.error("Ignoring bad EMBL line for " + this.accession
663 if (tokens[1].startsWith("/"))
665 break; // next feature qualifier
669 * if text (e.g. /product), add a word separator for a new line,
670 * else (e.g. /translation) don't
678 * remove trailing " and unescape doubled ""
680 String data = removeQuotes(tokens[1]);
688 * Reads and saves the sequence, read from the lines following the ORIGIN
689 * (GenBank) or SQ (EMBL) line. Whitespace and position counters are
690 * discarded. Returns the next line following the sequence data (the next line
691 * that doesn't start with whitespace).
693 * @throws IOException
695 protected String parseSequence() throws IOException
697 StringBuilder sb = new StringBuilder(this.length);
698 String line = nextLine();
699 while (line != null && line.startsWith(" "))
702 String[] blocks = line.split(WHITESPACE);
705 * the first or last block on each line might be a position count - omit
707 for (int i = 0; i < blocks.length; i++)
711 Long.parseLong(blocks[i]);
712 // position counter - ignore it
713 } catch (NumberFormatException e)
715 // sequence data - append it
716 sb.append(blocks[i]);
721 this.sequenceString = sb.toString();
727 * Processes a feature line. If it declares a feature type of interest
728 * (currently, only CDS is processed), processes all of the associated lines
729 * (feature qualifiers), and returns the next line after that, otherwise
730 * simply returns the next line.
733 * the first line for the feature (with initial FT omitted for EMBL
736 * @throws IOException
738 protected String parseFeature(String line) throws IOException
740 String[] tokens = line.trim().split(WHITESPACE);
741 if (tokens.length < 2 || !"CDS".equals(tokens[0]))
746 return parseCDSFeature(tokens[1]);
751 * A data bean class to hold values parsed from one CDS Feature
755 String translation; // from /translation qualifier
757 String cdsLocation; // the raw value e.g. join(1..1234,2012..2837)
759 int codonStart = 1; // from /codon_start qualifier
761 String proteinName; // from /product qualifier; used for protein description
763 String proteinId; // from /protein_id qualifier
765 List<DBRefEntry> xrefs = new ArrayList<>(); // from /db_xref qualifiers
767 Map<String, String> cdsProps = new Hashtable<>(); // other qualifiers