JAL-3010 discover root parent SO terms at runtime
[jalview.git] / src / jalview / datamodel / ontology / OntologyBase.java
1 package jalview.datamodel.ontology;
2
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.HashSet;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.Set;
9
10 /**
11  * A base class for models of Sequence Ontology and others
12  * 
13  * @author gmcarstairs
14  *
15  */
16 public abstract class OntologyBase implements OntologyI
17 {
18   protected Map<String, List<String>> rootParents = new HashMap<>();
19
20   @Override
21   public Set<String> getParentTerms(Set<String> terms)
22   {
23     Set<String> parents = new HashSet<>(terms);
24
25     boolean childRemoved = true;
26     while (childRemoved)
27     {
28       childRemoved = removeChild(parents);
29     }
30     return parents;
31   }
32
33   /**
34    * Removes the first term in the given set found which is a child of another
35    * term in the set. Answers true if a child was found and removed, else false.
36    * 
37    * @param terms
38    * @return
39    */
40   boolean removeChild(Set<String> terms)
41   {
42     for (String t1 : terms)
43     {
44       for (String t2 : terms)
45       {
46         if (t1 != t2)
47         {
48           if (isA(t1, t2))
49           {
50             terms.remove(t1);
51             return true;
52           }
53           if (isA(t2, t1))
54           {
55             terms.remove(t2);
56             return true;
57           }
58         }
59       }
60     }
61     return false;
62   }
63
64   @Override
65   public List<String> getChildTerms(String parent, List<String> terms)
66   {
67     List<String> children = new ArrayList<>();
68     for (String term : terms)
69     {
70       if (!term.equals(parent) && isA(term, parent))
71       {
72         children.add(term);
73       }
74     }
75     return children;
76   }
77 }