JAL-1191 cache isA (great-)grandparents as well for fast isA testing
[jalview.git] / src / jalview / io / gff / SequenceOntology.java
index c437f86..36ffaf8 100644 (file)
 package jalview.io.gff;
 
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import org.biojava.nbio.ontology.Ontology;
+import org.biojava.nbio.ontology.Term;
+import org.biojava.nbio.ontology.Term.Impl;
+import org.biojava.nbio.ontology.Triple;
+import org.biojava.nbio.ontology.io.OboParser;
+import org.biojava.nbio.ontology.utils.Annotation;
+
 /**
  * A wrapper class that parses the Sequence Ontology and exposes useful access
- * methods
+ * methods. This version uses the BioJava parser.
  */
 public class SequenceOntology
 {
-  private static SequenceOntology instance = new SequenceOntology();
+  private static SequenceOntology instance;
+
+  private Ontology ontology;
 
-  public static SequenceOntology getInstance()
+  private Term isA;
+
+  /*
+   * lookup of terms by user readable name (NB not guaranteed unique)
+   */
+  private Map<String, Term> termsByDescription;
+
+  /*
+   * Map where key is a Term and value is a (possibly empty) list of 
+   * all Terms to which the key has an 'isA' relationship, either
+   * directly or indirectly (A isA B isA C)
+   */
+  private Map<Term, List<Term>> termIsA;
+
+  /**
+   * Returns singleton instance
+   * 
+   * @return
+   */
+  public synchronized static SequenceOntology getInstance()
   {
+    if (instance == null)
+    {
+      instance = new SequenceOntology();
+    }
     return instance;
   }
 
   /**
-   * Private constructor to enforce use of singleton.
+   * Private constructor to enforce use of singleton. Parses and caches the SO
+   * OBO data file.
    */
   private SequenceOntology()
   {
-    // TODO: parse and cache so.obo data file e.g. using BioJava
+    termsByDescription = new HashMap<String, Term>();
+    termIsA = new HashMap<Term, List<Term>>();
+
+    loadOntologyZipFile("so-xp-simple.obo");
   }
 
   /**
-   * Test whether the given Sequence Ontology term is nucleotide_match (either
-   * directly or via is_a relationship)
+   * Loads the given ontology file from a zip file with ".zip" appended
    * 
-   * @param soTerm
+   * @param ontologyFile
+   */
+  protected void loadOntologyZipFile(String ontologyFile)
+  {
+    ZipInputStream zipStream = null;
+    try
+    {
+      InputStream inStream = this.getClass().getResourceAsStream(
+              "/" + ontologyFile + ".zip");
+      zipStream = new ZipInputStream(new BufferedInputStream(inStream));
+      ZipEntry entry;
+      while ((entry = zipStream.getNextEntry()) != null)
+      {
+        if (entry.getName().equals(ontologyFile))
+        {
+          loadOboFile(zipStream);
+        }
+      }
+    } catch (Exception e)
+    {
+      e.printStackTrace();
+    } finally
+    {
+      closeStream(zipStream);
+    }
+  }
+
+  /**
+   * Closes the input stream, swallowing all exceptions
+   * 
+   * @param is
+   */
+  protected void closeStream(InputStream is)
+  {
+    if (is != null)
+    {
+      try
+      {
+        is.close();
+      } catch (IOException e)
+      {
+        // ignore
+      }
+    }
+  }
+
+  /**
+   * Reads, parses and stores the OBO file data
+   * 
+   * @param is
+   * @throws ParseException
+   * @throws IOException
+   */
+  protected void loadOboFile(InputStream is) throws ParseException,
+          IOException
+  {
+    BufferedReader oboFile = new BufferedReader(new InputStreamReader(is));
+    OboParser parser = new OboParser();
+    ontology = parser.parseOBO(oboFile, "SO", "the SO ontology");
+    isA = ontology.getTerm("is_a");
+    storeTermNames();
+  }
+
+  /**
+   * Stores a lookup table of terms by description. Note that description is not
+   * guaranteed unique. Where duplicate descriptions are found, try to discard
+   * the term that is flagged as obsolete. However we do store obsolete terms
+   * where there is no duplication of description.
+   */
+  protected void storeTermNames()
+  {
+    for (Term term : ontology.getTerms())
+    {
+      if (term instanceof Impl)
+      {
+        String description = term.getDescription();
+        if (description != null)
+        {
+          Term replaced = termsByDescription.get(description);
+          if (replaced != null)
+          {
+            boolean newTermIsObsolete = isObsolete(term);
+            boolean oldTermIsObsolete = isObsolete(replaced);
+            if (newTermIsObsolete && !oldTermIsObsolete)
+            {
+              System.err.println("Ignoring " + term.getName()
+                      + " as obsolete and duplicated by "
+                      + replaced.getName());
+              term = replaced;
+            }
+            else if (!newTermIsObsolete && oldTermIsObsolete)
+            {
+              System.err.println("Ignoring " + replaced.getName()
+                      + " as obsolete and duplicated by " + term.getName());
+            }
+            else
+            {
+            System.err.println("Warning: " + term.getName()
+                    + " has replaced " + replaced.getName()
+                    + " for lookup of '" + description + "'");
+            }
+          }
+          termsByDescription.put(description, term);
+        }
+      }
+    }
+  }
+
+  /**
+   * Answers true if the term has property "is_obsolete" with value true, else
+   * false
+   * 
+   * @param term
    * @return
    */
-  public boolean isNucleotideMatch(String soTerm)
+  public static boolean isObsolete(Term term)
   {
-    // temporary until OBO parser is in place!
-    // (which should also match SO ids e.g. "SO:0000347")
-    String[] nucMatch = { "nucleotide_match", "primer_match",
-        "cross_genome_match", "expressed_sequence_match",
-        "translated_nucleotide_match", "UST_match", "RSF_match",
-        "cDNA_match", "EST_match" };
-    for (int i = 0; i < nucMatch.length; i++)
+    Annotation ann = term.getAnnotation();
+    if (ann != null)
     {
-      if (nucMatch[i].equals(soTerm))
+      try
       {
-        return true;
+      if (Boolean.TRUE.equals(ann.getProperty("is_obsolete")))
+      {
+          return true;
+        }
+      } catch (NoSuchElementException e)
+      {
+        // fall through to false
       }
     }
     return false;
   }
 
   /**
+   * Test whether the given Sequence Ontology term is nucleotide_match (either
+   * directly or via is_a relationship)
+   * 
+   * @param soTerm
+   *          SO name or description
+   * @return
+   */
+  public boolean isNucleotideMatch(String soTerm)
+  {
+    return isA(soTerm, "nucleotide_match");
+  }
+
+  /**
    * Test whether the given Sequence Ontology term is protein_match (either
    * directly or via is_a relationship)
    * 
    * @param soTerm
+   *          SO name or description
    * @return
    */
   public boolean isProteinMatch(String soTerm)
   {
-    // temporary until OBO parser is in place!
-    return "protein_match".equals(soTerm)
-            || "protein_hmm_match".equals(soTerm);
+    return isA(soTerm, "protein_match");
   }
 
+  /**
+   * Test whether the given Sequence Ontology term is polypeptide (either
+   * directly or via is_a relationship)
+   * 
+   * @param soTerm
+   *          SO name or description
+   * @return
+   */
   public boolean isPolypeptide(String soTerm)
   {
-    return "polypeptide".equals(soTerm);
+    return isA(soTerm, "polypeptide");
+  }
+
+  /**
+   * Returns true if the given term has a (direct or indirect) 'isA'
+   * relationship with the parent
+   * 
+   * @param child
+   * @param parent
+   * @return
+   */
+  public boolean isA(String child, String parent)
+  {
+    Term childTerm = getTerm(child);
+    Term parentTerm = getTerm(parent);
+
+    return termIsA(childTerm, parentTerm);
+  }
+
+  /**
+   * Returns true if the childTerm 'isA' parentTerm (directly or indirectly).
+   * 
+   * @param childTerm
+   * @param parentTerm
+   * @return
+   */
+  protected synchronized boolean termIsA(Term childTerm, Term parentTerm)
+  {
+    /*
+     * null term could arise from a misspelled SO description
+     */
+    if (childTerm == null || parentTerm == null)
+    {
+      return false;
+    }
+
+    /*
+     * recursive search endpoint:
+     */
+    if (childTerm == parentTerm)
+    {
+      return true;
+    }
+
+    /*
+     * lazy initialisation - find all of a term's parents (recursively) 
+     * the first time this is called, and save them in a map.
+     */
+    if (!termIsA.containsKey(childTerm))
+    {
+      findParents(childTerm);
+    }
+
+    List<Term> parents = termIsA.get(childTerm);
+    for (Term parent : parents)
+    {
+      if (termIsA(parent, parentTerm))
+      {
+        /*
+         * add (great-)grandparents to parents list as they are discovered,
+         * for faster lookup next time
+         */
+        if (!parents.contains(parentTerm))
+        {
+          parents.add(parentTerm);
+        }
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  /**
+   * Finds all the 'isA' parents of the childTerm and stores them as a (possibly
+   * empty) list.
+   * 
+   * @param childTerm
+   */
+  protected synchronized void findParents(Term childTerm)
+  {
+    List<Term> result = new ArrayList<Term>();
+    for (Triple triple : ontology.getTriples(childTerm, null, isA))
+    {
+      Term parent = triple.getObject();
+      result.add(parent);
+
+      /*
+       * and search for the parent's parents recursively
+       */
+      findParents(parent);
+    }
+    termIsA.put(childTerm, result);
+  }
+
+  /**
+   * Returns the Term for a given name (e.g. "SO:0000735") or description (e.g.
+   * "sequence_location"), or null if not found.
+   * 
+   * @param child
+   * @return
+   */
+  protected Term getTerm(String nameOrDescription)
+  {
+    Term t = termsByDescription.get(nameOrDescription);
+    if (t == null)
+    {
+      try
+      {
+        t = ontology.getTerm(nameOrDescription);
+      } catch (NoSuchElementException e)
+      {
+        // not found
+      }
+    }
+    return t;
   }
 }