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.Cache;
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;
167 * values parsed from the data file
169 protected String sourceDb;
171 protected String accession;
173 protected String version;
175 protected String description;
177 protected int length = 128;
179 protected List<DBRefEntry> dbrefs;
181 protected boolean sequenceStringIsRNA=false;
183 protected String sequenceString;
185 protected Map<String, CdsData> cds;
192 * @throws IOException
194 public EMBLLikeFlatFile(FileParse fp, String sourceId) throws IOException
196 super(false, fp); // don't parse immediately
197 this.sourceDb = sourceId;
198 dbrefs = new ArrayList<>();
201 * using TreeMap gives CDS sequences in alphabetical, so readable, order
203 cds = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
209 * process attributes for 'source' until the next FT feature entry
210 * only 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);
255 * Parses one (GenBank or EMBL format) CDS feature, saves the parsed data, and
256 * returns the next line
260 * @throws IOException
262 protected String parseCDSFeature(String location) throws IOException
267 * parse location, which can be over >1 line e.g. EAW51554
269 CdsData data = new CdsData();
270 StringBuilder sb = new StringBuilder().append(location);
271 line = parseFeatureQualifier(sb, false);
272 data.cdsLocation = sb.toString();
276 if (!isFeatureContinuationLine(line))
278 // e.g. start of next feature "FT source..."
283 * extract qualifier, e.g. FT /protein_id="CAA37824.1"
284 * - the value may extend over more than one line
285 * - if the value has enclosing quotes, these are removed
286 * - escaped double quotes ("") are reduced to a single character
288 int slashPos = line.indexOf('/');
291 Cache.log.error("Unexpected EMBL line ignored: " + line);
295 int eqPos = line.indexOf('=', slashPos + 1);
298 // can happen, e.g. /ribosomal_slippage
302 String qualifier = line.substring(slashPos + 1, eqPos);
303 String value = line.substring(eqPos + 1);
304 value = removeQuotes(value);
305 sb = new StringBuilder().append(value);
306 boolean asText = !"translation".equals(qualifier);
307 line = parseFeatureQualifier(sb, asText);
308 String featureValue = sb.toString();
310 if ("protein_id".equals(qualifier))
312 data.proteinId = featureValue;
314 else if ("codon_start".equals(qualifier))
318 data.codonStart = Integer.parseInt(featureValue.trim());
319 } catch (NumberFormatException e)
321 Cache.log.error("Invalid codon_start in XML for " + this.accession
322 + ": " + e.getMessage());
325 else if ("db_xref".equals(qualifier))
327 String[] parts = featureValue.split(":");
328 if (parts.length == 2)
330 String db = parts[0].trim();
331 db = DBRefUtils.getCanonicalName(db);
332 DBRefEntry dbref = new DBRefEntry(db, "0", parts[1].trim());
333 data.xrefs.add(dbref);
336 else if ("product".equals(qualifier))
338 data.proteinName = featureValue;
340 else if ("translation".equals(qualifier))
342 data.translation = featureValue;
344 else if (!"".equals(featureValue))
346 // throw anything else into the additional properties hash
347 data.cdsProps.put(qualifier, featureValue);
351 if (data.proteinId != null)
353 this.cds.put(data.proteinId, data);
357 Cache.log.error("Ignoring CDS feature with no protein_id for "
358 + sourceDb + ":" + accession);
364 protected abstract boolean isFeatureContinuationLine(String line);
367 * Output (print) is not (yet) implemented for flat file format
370 public String print(SequenceI[] seqs, boolean jvsuffix)
376 * Constructs and saves the sequence from parsed components
378 protected void buildSequence()
380 if (this.accession == null || this.sequenceString == null)
382 Cache.log.error("Failed to parse data from EMBL");
386 String name = this.accession;
387 if (this.sourceDb != null)
389 name = this.sourceDb + "|" + name;
392 if (produceRna && sequenceStringIsRNA)
394 sequenceString = sequenceString.replace('T', 'U').replace('t', 'u');
397 SequenceI seq = new Sequence(name, this.sequenceString);
398 seq.setDescription(this.description);
401 * add a DBRef to itself
403 DBRefEntry selfRef = new DBRefEntry(sourceDb, version, accession);
404 int[] startEnd = new int[] { 1, seq.getLength() };
405 selfRef.setMap(new Mapping(null, startEnd, startEnd, 1, 1));
406 seq.addDBRef(selfRef);
408 for (DBRefEntry dbref : this.dbrefs)
413 processCDSFeatures(seq);
415 seq.deriveSequence();
421 * Process the CDS features, including generation of cross-references and
422 * mappings to the protein products (translation)
426 protected void processCDSFeatures(SequenceI seq)
429 * record protein products found to avoid duplication i.e. >1 CDS with
430 * the same /protein_id [though not sure I can find an example of this]
432 Map<String, SequenceI> proteins = new HashMap<>();
433 for (CdsData data : cds.values())
435 processCDSFeature(seq, data, proteins);
440 * Processes data for one parsed CDS feature to
442 * <li>create a protein product sequence for the translation</li>
443 * <li>create a cross-reference to protein with mapping from dna</li>
444 * <li>add a CDS feature to the sequence for each CDS start-end range</li>
445 * <li>add any CDS dbrefs to the sequence and to the protein product</li>
451 * map of protein products so far derived from CDS data
453 void processCDSFeature(SequenceI dna, CdsData data,
454 Map<String, SequenceI> proteins)
457 * parse location into a list of [start, end, start, end] positions
459 int[] exons = getCdsRanges(this.accession, data.cdsLocation);
461 MapList maplist = buildMappingToProtein(dna, exons, data);
465 for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
467 int exonStart = exons[xint];
468 int exonEnd = exons[xint + 1];
469 int begin = Math.min(exonStart, exonEnd);
470 int end = Math.max(exonStart, exonEnd);
472 String desc = String.format("Exon %d for protein EMBLCDS:%s",
473 exonNumber, data.proteinId);
475 SequenceFeature sf = new SequenceFeature("CDS", desc, begin, end,
477 for (Entry<String, String> val : data.cdsProps.entrySet())
479 sf.setValue(val.getKey(), val.getValue());
482 sf.setEnaLocation(data.cdsLocation);
483 boolean forwardStrand = exonStart <= exonEnd;
484 sf.setStrand(forwardStrand ? "+" : "-");
485 sf.setPhase(String.valueOf(data.codonStart - 1));
486 sf.setValue(FeatureProperties.EXONPOS, exonNumber);
487 sf.setValue(FeatureProperties.EXONPRODUCT, data.proteinName);
489 dna.addSequenceFeature(sf);
492 boolean hasUniprotDbref = false;
493 for (DBRefEntry xref : data.xrefs)
496 if (xref.getSource().equals(DBRefSource.UNIPROT))
499 * construct (or find) the sequence for (data.protein_id, data.translation)
501 SequenceI protein = buildProteinProduct(dna, xref, data, proteins);
502 Mapping map = new Mapping(protein, maplist);
503 map.setMappedFromId(data.proteinId);
507 * add DBRefs with mappings from dna to protein and the inverse
509 DBRefEntry db1 = new DBRefEntry(sourceDb, version, accession);
510 db1.setMap(new Mapping(dna, maplist.getInverse()));
511 protein.addDBRef(db1);
513 hasUniprotDbref = true;
518 * if we have a product (translation) but no explicit Uniprot dbref
519 * (example: EMBL M19487 protein_id AAB02592.1)
520 * then construct mappings to an assumed EMBLCDSPROTEIN accession
522 if (!hasUniprotDbref)
524 SequenceI protein = proteins.get(data.proteinId);
527 protein = new Sequence(data.proteinId, data.translation);
528 protein.setDescription(data.proteinName);
529 proteins.put(data.proteinId, protein);
531 // assuming CDSPROTEIN sequence version = dna version (?!)
532 DBRefEntry db1 = new DBRefEntry(DBRefSource.EMBLCDSProduct,
533 this.version, data.proteinId);
534 protein.addDBRef(db1);
536 DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
537 DBRefSource.EMBLCDSProduct, this.version, data.proteinId);
538 Mapping map = new Mapping(protein, maplist);
539 map.setMappedFromId(data.proteinId);
540 dnaToEmblProteinRef.setMap(map);
541 dna.addDBRef(dnaToEmblProteinRef);
545 * comment brought forward from EmblXmlSource, lines 447-451:
546 * TODO: if retrieved from EMBLCDS, add a DBRef back to the parent EMBL
547 * sequence with the exon map; if given a dataset reference, search
548 * dataset for parent EMBL sequence if it exists and set its map;
549 * make a new feature annotating the coding contig
554 * Computes a mapping from CDS positions in DNA sequence to protein product
555 * positions, with allowance for stop codon or incomplete start codon
562 MapList buildMappingToProtein(final SequenceI dna, final int[] exons,
565 MapList dnaToProteinMapping = null;
566 int peptideLength = data.translation.length();
568 int[] proteinRange = new int[] { 1, peptideLength };
569 if (exons != null && exons.length > 0)
572 * We were able to parse 'location'; do a final
573 * product length truncation check
575 int[] cdsRanges = adjustForProteinLength(peptideLength, exons);
576 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
581 * workaround until we handle all 'location' formats fully
582 * e.g. X53828.1:60..1058 or <123..>289
584 Cache.log.error(String.format(
585 "Implementation Notice: EMBLCDS location '%s'not properly supported yet"
586 + " - Making up the CDNA region of (%s:%s)... may be incorrect",
587 data.cdsLocation, sourceDb, this.accession));
589 int completeCodonsLength = 1 - data.codonStart + dna.getLength();
590 int mappedDnaEnd = dna.getEnd();
591 if (peptideLength * 3 == completeCodonsLength)
593 // this might occur for CDS sequences where no features are marked
594 Cache.log.warn("Assuming no stop codon at end of cDNA fragment");
595 mappedDnaEnd = dna.getEnd();
597 else if ((peptideLength + 1) * 3 == completeCodonsLength)
599 Cache.log.warn("Assuming stop codon at end of cDNA fragment");
600 mappedDnaEnd = dna.getEnd() - 3;
603 if (mappedDnaEnd != -1)
605 int[] cdsRanges = new int[] {
606 dna.getStart() + (data.codonStart - 1), mappedDnaEnd };
607 dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
611 return dnaToProteinMapping;
615 * Constructs a sequence for the protein product for the CDS data (if there is
616 * one), and dbrefs with mappings from CDS to protein and the reverse
624 SequenceI buildProteinProduct(SequenceI dna, DBRefEntry xref,
625 CdsData data, Map<String, SequenceI> proteins)
628 * check we have some data to work with
630 if (data.proteinId == null || data.translation == null)
636 * Construct the protein sequence (if not already seen)
638 String proteinSeqName = xref.getSource() + "|" + xref.getAccessionId();
639 SequenceI protein = proteins.get(proteinSeqName);
642 protein = new Sequence(proteinSeqName, data.translation, 1,
643 data.translation.length());
644 protein.setDescription(data.proteinName != null ? data.proteinName
645 : "Protein Product from " + sourceDb);
646 proteins.put(proteinSeqName, protein);
653 * Returns the CDS location as a single array of [start, end, start, end...]
654 * positions. If on the reverse strand, these will be in descending order.
660 protected int[] getCdsRanges(String accession, String location)
662 if (location == null)
669 List<int[]> ranges = DnaUtils.parseLocation(location);
670 return MappingUtils.rangeListToArray(ranges);
671 } catch (ParseException e)
674 String.format("Not parsing inexact CDS location %s in ENA %s",
675 location, accession));
681 * Reads the value of a feature (FT) qualifier from one or more lines of the
682 * file, and returns the next line after that. Values are appended to the
683 * string buffer, which should be already primed with the value read from the
684 * first line for the qualifier (with any leading double quote removed).
685 * Enclosing double quotes are removed, and escaped (repeated) double quotes
686 * reduced to one only. For example for
689 * FT /note="gene_id=hCG28070.3
690 * FT ""foobar"" isoform=CRA_b"
691 * the returned value is
692 * gene_id=hCG28070.3 "foobar" isoform=CRA_b
695 * Note the side-effect of this method, to advance data reading to the next
696 * line after the feature qualifier (which could be another qualifier, a
697 * different feature, a non-feature line, or null at end of file).
700 * a string buffer primed with the first line of the value
703 * @throws IOException
705 String parseFeatureQualifier(StringBuilder sb, boolean asText)
709 while ((line = nextLine()) != null)
711 if (!isFeatureContinuationLine(line))
713 break; // reached next feature or other input line
715 String[] tokens = line.split(WHITESPACE);
716 if (tokens.length < 2)
718 Cache.log.error("Ignoring bad EMBL line for " + this.accession
722 if (tokens[1].startsWith("/"))
724 break; // next feature qualifier
728 * if text (e.g. /product), add a word separator for a new line,
729 * else (e.g. /translation) don't
737 * remove trailing " and unescape doubled ""
739 String data = removeQuotes(tokens[1]);
747 * Reads and saves the sequence, read from the lines following the ORIGIN
748 * (GenBank) or SQ (EMBL) line. Whitespace and position counters are
749 * discarded. Returns the next line following the sequence data (the next line
750 * that doesn't start with whitespace).
752 * @throws IOException
754 protected String parseSequence() throws IOException
756 StringBuilder sb = new StringBuilder(this.length);
757 String line = nextLine();
758 while (line != null && line.startsWith(" "))
761 String[] blocks = line.split(WHITESPACE);
764 * the first or last block on each line might be a position count - omit
766 for (int i = 0; i < blocks.length; i++)
770 Long.parseLong(blocks[i]);
771 // position counter - ignore it
772 } catch (NumberFormatException e)
774 // sequence data - append it
775 sb.append(blocks[i]);
780 this.sequenceString = sb.toString();
786 * Processes a feature line. If it declares a feature type of interest
787 * (currently, only CDS is processed), processes all of the associated lines
788 * (feature qualifiers), and returns the next line after that, otherwise
789 * simply returns the next line.
792 * the first line for the feature (with initial FT omitted for EMBL
795 * @throws IOException
797 protected String parseFeature(String line) throws IOException
799 String[] tokens = line.trim().split(WHITESPACE);
800 if (tokens.length < 2 || (!"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