JAL-3692 refactor/complete parsing, more unit test coverage
[jalview.git] / src / jalview / io / EmblFlatFile.java
index 5be4364..f7a5161 100644 (file)
@@ -3,14 +3,17 @@ package jalview.io;
 import java.io.IOException;
 import java.text.ParseException;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Hashtable;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.TreeMap;
 
 import jalview.bin.Cache;
 import jalview.datamodel.DBRefEntry;
+import jalview.datamodel.DBRefSource;
 import jalview.datamodel.FeatureProperties;
 import jalview.datamodel.Mapping;
 import jalview.datamodel.Sequence;
@@ -18,6 +21,7 @@ import jalview.datamodel.SequenceFeature;
 import jalview.datamodel.SequenceI;
 import jalview.util.DBRefUtils;
 import jalview.util.DnaUtils;
+import jalview.util.MapList;
 import jalview.util.MappingUtils;
 
 /**
@@ -41,6 +45,8 @@ import jalview.util.MappingUtils;
  */
 public class EmblFlatFile extends AlignFile // FileParse
 {
+  private static final String QUOTE = "\"";
+
   /**
    * A data bean class to hold values parsed from one CDS Feature (FT)
    */
@@ -56,6 +62,8 @@ public class EmblFlatFile extends AlignFile // FileParse
 
     String proteinId; // from CDS /protein_id
 
+    List<DBRefEntry> xrefs = new ArrayList<>(); // from CDS /db_xref qualifiers
+
     Map<String, String> cdsProps = new Hashtable<>(); // CDS other qualifiers
   }
 
@@ -74,11 +82,14 @@ public class EmblFlatFile extends AlignFile // FileParse
 
   private int length = 128; // from ID (7th token), with usable default
 
-  private List<DBRefEntry> dbrefs; // from DR and also CDS /db_xref qualifiers
+  private List<DBRefEntry> dbrefs; // from DR
 
   private String sequenceString; // from SQ lines
 
-  private List<CdsData> cds;
+  /*
+   * parsed CDS data fields, keyed by protein_id
+   */
+  private Map<String, CdsData> cds;
 
   /**
    * Constructor
@@ -92,7 +103,11 @@ public class EmblFlatFile extends AlignFile // FileParse
     super(false, fp); // don't parse immediately
     this.sourceDb = sourceId;
     dbrefs = new ArrayList<>();
-    cds = new ArrayList<>();
+    
+    /*
+     * using TreeMap gives CDS sequences in alphabetical, so readable, order
+     */
+    cds = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
   }
 
   /**
@@ -131,7 +146,7 @@ public class EmblFlatFile extends AlignFile // FileParse
         line = nextLine();
       }
     }
-    assembleSequence();
+    buildSequence();
   }
 
   /**
@@ -329,12 +344,14 @@ public class EmblFlatFile extends AlignFile // FileParse
       int eqPos = line.indexOf('=', slashPos + 1);
       if (eqPos == -1)
       {
-        Cache.log.error("Unexpected EMBL line ignored: " + line);
+        // can happen, e.g. /ribosomal_slippage
+//        Cache.log.error("Unexpected EMBL line ignored: " + line);
+        line = nextLine();
         continue;
       }
       String qualifier = line.substring(slashPos + 1, eqPos);
       String value = line.substring(eqPos + 1);
-      if (value.startsWith("\"") && value.endsWith("\""))
+      if (value.startsWith(QUOTE) && value.endsWith(QUOTE))
       {
         value = value.substring(1, value.length() - 1);
       }
@@ -364,7 +381,7 @@ public class EmblFlatFile extends AlignFile // FileParse
           String db = parts[0].trim();
           db = DBRefUtils.getCanonicalName(db);
           DBRefEntry dbref = new DBRefEntry(db, "0", parts[1].trim());
-          this.dbrefs.add(dbref);
+          data.xrefs.add(dbref);
         }
         line = nextLine();
       }
@@ -376,7 +393,7 @@ public class EmblFlatFile extends AlignFile // FileParse
       }
       else if ("translation".equals(qualifier))
       {
-        line = readTranslation(value, data);
+        line = parseTranslation(value, data);
       }
       else if (!"".equals(value))
       {
@@ -386,7 +403,15 @@ public class EmblFlatFile extends AlignFile // FileParse
       }
     }
 
-    this.cds.add(data);
+    if (data.proteinId != null)
+    {
+      this.cds.put(data.proteinId, data);
+    }
+    else
+    {
+      Cache.log.error("Ignoring CDS feature with no protein_id for "
+              + sourceDb + ":" + accession);
+    }
 
     return line;
   }
@@ -401,10 +426,10 @@ public class EmblFlatFile extends AlignFile // FileParse
    * @return
    * @throws IOException
    */
-  String readTranslation(String value, CdsData data) throws IOException
+  String parseTranslation(String value, CdsData data) throws IOException
   {
     StringBuilder sb = new StringBuilder(this.length / 3 + 1);
-    sb.append(value.replace("\"", ""));
+    sb.append(value.replace(QUOTE, ""));
 
     String line;
     while ((line = nextLine()) != null)
@@ -423,7 +448,7 @@ public class EmblFlatFile extends AlignFile // FileParse
       {
         break; // next feature qualifier
       }
-      sb.append(tokens[1].replace("\"", ""));
+      sb.append(tokens[1].replace(QUOTE, ""));
     }
 
     data.translation = sb.toString();
@@ -434,7 +459,7 @@ public class EmblFlatFile extends AlignFile // FileParse
   /**
    * Constructs and saves the sequence from parsed components
    */
-  void assembleSequence()
+  void buildSequence()
   {
     String name = this.accession;
     if (this.sourceDb != null)
@@ -457,7 +482,7 @@ public class EmblFlatFile extends AlignFile // FileParse
       seq.addDBRef(dbref);
     }
 
-    processAllCDS(seq);
+    processCDSFeatures(seq);
 
     seq.deriveSequence();
 
@@ -470,25 +495,25 @@ public class EmblFlatFile extends AlignFile // FileParse
    * 
    * @param seq
    */
-  protected void processAllCDS(SequenceI seq)
+  protected void processCDSFeatures(SequenceI seq)
   {
     /*
      * record protein products found to avoid duplication i.e. >1 CDS with 
      * the same /protein_id [though not sure I can find an example of this]
      */
     Map<String, SequenceI> proteins = new HashMap<>();
-    for (CdsData data : cds)
+    for (CdsData data : cds.values())
     {
-      processOneCDS(seq, data, proteins);
+      processCDSFeature(seq, data, proteins);
     }
   }
 
   /**
-   * Processes the parsed CDS feature data to
+   * Processes data for one parsed CDS feature to
    * <ul>
-   * <li>add a CDS feature to the sequence for each CDS start-end range</li>
    * <li>create a protein product sequence for the translation</li>
    * <li>create a cross-reference to protein with mapping from dna</li>
+   * <li>add a CDS feature to the sequence for each CDS start-end range</li>
    * <li>add any CDS dbrefs to the sequence and to the protein product</li>
    * </ul>
    * 
@@ -497,13 +522,16 @@ public class EmblFlatFile extends AlignFile // FileParse
    * @param proteins
    *          map of protein products so far derived from CDS data
    */
-  void processOneCDS(SequenceI dna, CdsData data,
+  void processCDSFeature(SequenceI dna, CdsData data,
           Map<String, SequenceI> proteins)
   {
     /*
      * parse location into a list of [start, end, start, end] positions
      */
     int[] exons = getCdsRanges(this.accession, data.cdsLocation);
+
+    MapList maplist = buildMappingToProtein(dna, exons, data);
+
     int exonNumber = 0;
 
     for (int xint = 0; exons != null && xint < exons.length - 1; xint += 2)
@@ -531,9 +559,127 @@ public class EmblFlatFile extends AlignFile // FileParse
       sf.setValue(FeatureProperties.EXONPRODUCT, data.proteinName);
 
       dna.addSequenceFeature(sf);
+    }
 
-      linkProteinProduct(dna, data, proteins);
+    boolean hasUniprotDbref = false;
+    for (DBRefEntry xref : data.xrefs)
+    {
+      dna.addDBRef(xref);
+      if (xref.getSource().equals(DBRefSource.UNIPROT))
+      {
+        /*
+         * construct (or find) the sequence for (data.protein_id, data.translation)
+         */
+        SequenceI protein = buildProteinProduct(dna, xref, data, proteins);
+        Mapping map = new Mapping(protein, maplist);
+        map.setMappedFromId(data.proteinId);
+        xref.setMap(map);
+
+        /*
+         * add DBRefs with mappings from dna to protein and the inverse
+         */
+        DBRefEntry db1 = new DBRefEntry(sourceDb, version, accession);
+        db1.setMap(new Mapping(dna, maplist.getInverse()));
+        protein.addDBRef(db1);
+
+        hasUniprotDbref = true;
+      }
     }
+
+    /*
+     * if we have a product (translation) but no explicit Uniprot dbref
+     * (example: EMBL M19487 protein_id AAB02592.1)
+     * then construct mappings to an assumed EMBLCDSPROTEIN accession
+     */
+    if (!hasUniprotDbref)
+    {
+      SequenceI protein = proteins.get(data.proteinId);
+      if (protein == null)
+      {
+        protein = new Sequence(data.proteinId, data.translation);
+        proteins.put(data.proteinId, protein);
+      }
+      // assuming CDSPROTEIN sequence version = dna version (?!)
+      DBRefEntry db1 = new DBRefEntry(DBRefSource.EMBLCDSProduct,
+              this.version, data.proteinId);
+      protein.addDBRef(db1);
+
+      DBRefEntry dnaToEmblProteinRef = new DBRefEntry(
+              DBRefSource.EMBLCDSProduct, this.version, data.proteinId);
+      Mapping map = new Mapping(protein, maplist);
+      map.setMappedFromId(data.proteinId);
+      dnaToEmblProteinRef.setMap(map);
+      dna.addDBRef(dnaToEmblProteinRef);
+     }
+
+    /*
+     * comment brought forward from EmblXmlSource, lines 447-451:
+     * TODO: if retrieved from EMBLCDS, add a DBRef back to the parent EMBL
+     * sequence with the exon  map; if given a dataset reference, search
+     * dataset for parent EMBL sequence if it exists and set its map;
+     * make a new feature annotating the coding contig
+     */
+  }
+
+  /**
+   * Computes a mapping from CDS positions in DNA sequence to protein product
+   * positions, with allowance for stop codon or incomplete start codon
+   * 
+   * @param dna
+   * @param exons
+   * @param data
+   * @return
+   */
+  MapList buildMappingToProtein(final SequenceI dna, final int[] exons,
+          final CdsData data)
+  {
+    MapList dnaToProteinMapping = null;
+    int peptideLength = data.translation.length();
+
+    int[] proteinRange = new int[] { 1, peptideLength };
+    if (exons != null && exons.length > 0)
+    {
+      /*
+       * We were able to parse 'location'; do a final 
+       * product length truncation check
+       */
+      int[] cdsRanges = adjustForProteinLength(peptideLength, exons);
+      dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
+    }
+    else
+    {
+      /*
+       * workaround until we handle all 'location' formats fully
+       * e.g. X53828.1:60..1058 or <123..>289
+       */
+      Cache.log.error(String.format(
+              "Implementation Notice: EMBLCDS location '%s'not properly supported yet"
+                      + " - Making up the CDNA region of (%s:%s)... may be incorrect",
+              data.cdsLocation, sourceDb, this.accession));
+
+      int completeCodonsLength = 1 - data.codonStart + dna.getLength();
+      int mappedDnaEnd = dna.getEnd();
+      if (peptideLength * 3 == completeCodonsLength)
+      {
+        // this might occur for CDS sequences where no features are marked
+        Cache.log.warn("Assuming no stop codon at end of cDNA fragment");
+        mappedDnaEnd = dna.getEnd();
+      }
+      else if ((peptideLength + 1) * 3 == completeCodonsLength)
+      {
+        Cache.log.warn("Assuming stop codon at end of cDNA fragment");
+        mappedDnaEnd = dna.getEnd() - 3;
+      }
+
+      if (mappedDnaEnd != -1)
+      {
+        int[] cdsRanges = new int[] {
+            dna.getStart() + (data.codonStart - 1), mappedDnaEnd };
+        dnaToProteinMapping = new MapList(cdsRanges, proteinRange, 3, 1);
+      }
+    }
+
+    return dnaToProteinMapping;
   }
 
   /**
@@ -541,31 +687,37 @@ public class EmblFlatFile extends AlignFile // FileParse
    * one), and dbrefs with mappings from CDS to protein and the reverse
    * 
    * @param dna
+   * @param xref
    * @param data
    * @param proteins
+   * @return
    */
-  void linkProteinProduct(SequenceI dna, CdsData data, Map<String, SequenceI> proteins)
+  SequenceI buildProteinProduct(SequenceI dna, DBRefEntry xref,
+          CdsData data, Map<String, SequenceI> proteins)
   {
     /*
      * check we have some data to work with
      */
     if (data.proteinId == null || data.translation == null)
     {
-      return;
+      return null;
     }
-    
+
     /*
      * Construct the protein sequence (if not already seen)
      */
-    SequenceI protein = proteins.get(data.proteinId);
+    String proteinSeqName = xref.getSource() + "|" + xref.getAccessionId();
+    SequenceI protein = proteins.get(proteinSeqName);
     if (protein == null)
     {
-      protein = new Sequence(data.proteinId, data.translation, 1,
+      protein = new Sequence(proteinSeqName, data.translation, 1,
               data.translation.length());
       protein.setDescription(data.proteinName != null ? data.proteinName
               : "Protein Product from " + sourceDb);
-      proteins.put(data.proteinId, protein);
+      proteins.put(proteinSeqName, protein);
     }
+
+    return protein;
   }
 
   /**
@@ -604,4 +756,81 @@ public class EmblFlatFile extends AlignFile // FileParse
   {
     return null;
   }
+
+  /**
+   * Truncates (if necessary) the exon intervals to match 3 times the length of
+   * the protein; also accepts 3 bases longer (for stop codon not included in
+   * protein)
+   * 
+   * @param proteinLength
+   * @param exon
+   *          an array of [start, end, start, end...] intervals
+   * @return the same array (if unchanged) or a truncated copy
+   */
+  static int[] adjustForProteinLength(int proteinLength, int[] exon)
+  {
+    if (proteinLength <= 0 || exon == null)
+    {
+      return exon;
+    }
+    int expectedCdsLength = proteinLength * 3;
+    int exonLength = MappingUtils.getLength(Arrays.asList(exon));
+
+    /*
+     * if exon length matches protein, or is shorter, or longer by the 
+     * length of a stop codon (3 bases), then leave it unchanged
+     */
+    if (expectedCdsLength >= exonLength
+            || expectedCdsLength == exonLength - 3)
+    {
+      return exon;
+    }
+
+    int origxon[];
+    int sxpos = -1;
+    int endxon = 0;
+    origxon = new int[exon.length];
+    System.arraycopy(exon, 0, origxon, 0, exon.length);
+    int cdspos = 0;
+    for (int x = 0; x < exon.length; x += 2)
+    {
+      cdspos += Math.abs(exon[x + 1] - exon[x]) + 1;
+      if (expectedCdsLength <= cdspos)
+      {
+        // advanced beyond last codon.
+        sxpos = x;
+        if (expectedCdsLength != cdspos)
+        {
+          // System.err
+          // .println("Truncating final exon interval on region by "
+          // + (cdspos - cdslength));
+        }
+
+        /*
+         * shrink the final exon - reduce end position if forward
+         * strand, increase it if reverse
+         */
+        if (exon[x + 1] >= exon[x])
+        {
+          endxon = exon[x + 1] - cdspos + expectedCdsLength;
+        }
+        else
+        {
+          endxon = exon[x + 1] + cdspos - expectedCdsLength;
+        }
+        break;
+      }
+    }
+
+    if (sxpos != -1)
+    {
+      // and trim the exon interval set if necessary
+      int[] nxon = new int[sxpos + 2];
+      System.arraycopy(exon, 0, nxon, 0, sxpos + 2);
+      nxon[sxpos + 1] = endxon; // update the end boundary for the new exon
+                                // set
+      exon = nxon;
+    }
+    return exon;
+  }
 }