From: <jen...@us...> - 2008-03-03 12:46:25
|
Revision: 675 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=675&view=rev Author: jenslehmann Date: 2008-03-03 04:46:23 -0800 (Mon, 03 Mar 2008) Log Message: ----------- continued refinement operator implementation Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/core/Reasoner.java trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java trunk/src/dl-learner/org/dllearner/core/ReasoningService.java trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java trunk/src/dl-learner/org/dllearner/refinementoperators/MathOperations.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java Modified: trunk/src/dl-learner/org/dllearner/core/Reasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/Reasoner.java 2008-03-03 07:45:57 UTC (rev 674) +++ trunk/src/dl-learner/org/dllearner/core/Reasoner.java 2008-03-03 12:46:23 UTC (rev 675) @@ -112,13 +112,13 @@ // currently, we do not require that datatype properties can be returned; // the main reason is that DIG does not distinguish between datatype and // object properties (of course one could implement it but it is not easy) - public Set<DatatypeProperty> getDatatypeProperties() throws ReasoningMethodUnsupportedException; + public SortedSet<DatatypeProperty> getDatatypeProperties() throws ReasoningMethodUnsupportedException; - public Set<DatatypeProperty> getBooleanDatatypeProperties() throws ReasoningMethodUnsupportedException; + public SortedSet<DatatypeProperty> getBooleanDatatypeProperties() throws ReasoningMethodUnsupportedException; - public Set<DatatypeProperty> getDoubleDatatypeProperties() throws ReasoningMethodUnsupportedException; + public SortedSet<DatatypeProperty> getDoubleDatatypeProperties() throws ReasoningMethodUnsupportedException; - public Set<DatatypeProperty> getIntDatatypeProperties() throws ReasoningMethodUnsupportedException; + public SortedSet<DatatypeProperty> getIntDatatypeProperties() throws ReasoningMethodUnsupportedException; public SortedSet<Individual> getIndividuals(); Modified: trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java 2008-03-03 07:45:57 UTC (rev 674) +++ trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java 2008-03-03 12:46:23 UTC (rev 675) @@ -219,19 +219,19 @@ throw new ReasoningMethodUnsupportedException(); } - public Set<DatatypeProperty> getDatatypeProperties() throws ReasoningMethodUnsupportedException { + public SortedSet<DatatypeProperty> getDatatypeProperties() throws ReasoningMethodUnsupportedException { throw new ReasoningMethodUnsupportedException(); } - public Set<DatatypeProperty> getBooleanDatatypeProperties() throws ReasoningMethodUnsupportedException { + public SortedSet<DatatypeProperty> getBooleanDatatypeProperties() throws ReasoningMethodUnsupportedException { throw new ReasoningMethodUnsupportedException(); } - public Set<DatatypeProperty> getDoubleDatatypeProperties() throws ReasoningMethodUnsupportedException { + public SortedSet<DatatypeProperty> getDoubleDatatypeProperties() throws ReasoningMethodUnsupportedException { throw new ReasoningMethodUnsupportedException(); } - public Set<DatatypeProperty> getIntDatatypeProperties() throws ReasoningMethodUnsupportedException { + public SortedSet<DatatypeProperty> getIntDatatypeProperties() throws ReasoningMethodUnsupportedException { throw new ReasoningMethodUnsupportedException(); } Modified: trunk/src/dl-learner/org/dllearner/core/ReasoningService.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ReasoningService.java 2008-03-03 07:45:57 UTC (rev 674) +++ trunk/src/dl-learner/org/dllearner/core/ReasoningService.java 2008-03-03 12:46:23 UTC (rev 675) @@ -467,7 +467,7 @@ return reasoner.getAtomicRoles(); } - public Set<DatatypeProperty> getDatatypeProperties() { + public SortedSet<DatatypeProperty> getDatatypeProperties() { try { return reasoner.getDatatypeProperties(); } catch (ReasoningMethodUnsupportedException e) { @@ -476,7 +476,7 @@ } } - public Set<DatatypeProperty> getBooleanDatatypeProperties() { + public SortedSet<DatatypeProperty> getBooleanDatatypeProperties() { try { return reasoner.getBooleanDatatypeProperties(); } catch (ReasoningMethodUnsupportedException e) { @@ -485,7 +485,7 @@ } } - public Set<DatatypeProperty> getIntDatatypeProperties() { + public SortedSet<DatatypeProperty> getIntDatatypeProperties() { try { return reasoner.getIntDatatypeProperties(); } catch (ReasoningMethodUnsupportedException e) { @@ -494,7 +494,7 @@ } } - public Set<DatatypeProperty> getDoubleDatatypeProperties() { + public SortedSet<DatatypeProperty> getDoubleDatatypeProperties() { try { return reasoner.getDoubleDatatypeProperties(); } catch (ReasoningMethodUnsupportedException e) { Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-03 07:45:57 UTC (rev 674) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-03 12:46:23 UTC (rev 675) @@ -78,10 +78,10 @@ private Set<NamedClass> atomicConcepts; private Set<ObjectProperty> atomicRoles; - private Set<DatatypeProperty> datatypeProperties; - private Set<DatatypeProperty> booleanDatatypeProperties = new TreeSet<DatatypeProperty>(); - private Set<DatatypeProperty> doubleDatatypeProperties = new TreeSet<DatatypeProperty>(); - private Set<DatatypeProperty> intDatatypeProperties = new TreeSet<DatatypeProperty>(); + private SortedSet<DatatypeProperty> datatypeProperties; + private SortedSet<DatatypeProperty> booleanDatatypeProperties = new TreeSet<DatatypeProperty>(); + private SortedSet<DatatypeProperty> doubleDatatypeProperties = new TreeSet<DatatypeProperty>(); + private SortedSet<DatatypeProperty> intDatatypeProperties = new TreeSet<DatatypeProperty>(); private SortedSet<Individual> individuals; private ReasoningService rs; @@ -298,22 +298,22 @@ } @Override - public Set<DatatypeProperty> getDatatypeProperties() { + public SortedSet<DatatypeProperty> getDatatypeProperties() { return datatypeProperties; } @Override - public Set<DatatypeProperty> getBooleanDatatypeProperties() { + public SortedSet<DatatypeProperty> getBooleanDatatypeProperties() { return booleanDatatypeProperties; } @Override - public Set<DatatypeProperty> getDoubleDatatypeProperties() { + public SortedSet<DatatypeProperty> getDoubleDatatypeProperties() { return doubleDatatypeProperties; } @Override - public Set<DatatypeProperty> getIntDatatypeProperties() { + public SortedSet<DatatypeProperty> getIntDatatypeProperties() { return intDatatypeProperties; } Modified: trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-03 07:45:57 UTC (rev 674) +++ trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-03 12:46:23 UTC (rev 675) @@ -136,10 +136,10 @@ // primitives Set<NamedClass> atomicConcepts = new TreeSet<NamedClass>(conceptComparator); Set<ObjectProperty> atomicRoles = new TreeSet<ObjectProperty>(roleComparator); - Set<DatatypeProperty> datatypeProperties = new TreeSet<DatatypeProperty>(); - Set<DatatypeProperty> booleanDatatypeProperties = new TreeSet<DatatypeProperty>(); - Set<DatatypeProperty> doubleDatatypeProperties = new TreeSet<DatatypeProperty>(); - Set<DatatypeProperty> intDatatypeProperties = new TreeSet<DatatypeProperty>(); + SortedSet<DatatypeProperty> datatypeProperties = new TreeSet<DatatypeProperty>(); + SortedSet<DatatypeProperty> booleanDatatypeProperties = new TreeSet<DatatypeProperty>(); + SortedSet<DatatypeProperty> doubleDatatypeProperties = new TreeSet<DatatypeProperty>(); + SortedSet<DatatypeProperty> intDatatypeProperties = new TreeSet<DatatypeProperty>(); SortedSet<Individual> individuals = new TreeSet<Individual>(); // namespaces @@ -334,7 +334,7 @@ } @Override - public Set<DatatypeProperty> getDatatypeProperties() { + public SortedSet<DatatypeProperty> getDatatypeProperties() { return datatypeProperties; } @@ -960,7 +960,7 @@ * @return the booleanDatatypeProperties */ @Override - public Set<DatatypeProperty> getBooleanDatatypeProperties() { + public SortedSet<DatatypeProperty> getBooleanDatatypeProperties() { return booleanDatatypeProperties; } @@ -968,7 +968,7 @@ * @return the doubleDatatypeProperties */ @Override - public Set<DatatypeProperty> getDoubleDatatypeProperties() { + public SortedSet<DatatypeProperty> getDoubleDatatypeProperties() { return doubleDatatypeProperties; } @@ -976,7 +976,7 @@ * @return the intDatatypeProperties */ @Override - public Set<DatatypeProperty> getIntDatatypeProperties() { + public SortedSet<DatatypeProperty> getIntDatatypeProperties() { return intDatatypeProperties; } Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/MathOperations.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/MathOperations.java 2008-03-03 07:45:57 UTC (rev 674) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/MathOperations.java 2008-03-03 12:46:23 UTC (rev 675) @@ -23,9 +23,13 @@ import java.util.LinkedList; import java.util.List; import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.ObjectSomeRestriction; import org.dllearner.core.owl.Union; +import org.dllearner.utilities.ConceptComparator; /** * Math operations related to refinement operators. @@ -114,20 +118,44 @@ return combosTmp; } + /** + * @see #getCombos(int) + * @param length Length of construct. + * @param maxValue Maximum value which can occur in sum. + * @return + */ + public static List<List<Integer>> getCombos(int length, int maxValue) { + LinkedList<List<Integer>> combosTmp = new LinkedList<List<Integer>>(); + decompose(length, maxValue, new LinkedList<Integer>(), combosTmp); + return combosTmp; + } + @SuppressWarnings("unchecked") private static LinkedList<Integer> cloneList(LinkedList<Integer> list) { return (LinkedList<Integer>) list.clone(); - } - - public static void main(String args[]) { - System.out.println(getCombos(7)); } - // neue Implementierung, die nicht mehr zur incompleteness führen soll, - // da die Konzepte in einer MultiDisjunction als Liste gespeichert werden - public static Set<Union> incCrossProduct(Set<Union> baseSet, Set<Description> newSet) { - Set<Union> retSet = new HashSet<Union>(); - + /** + * Implements a cross product in the sense that each union description in the + * base set is extended by each description in the new set. + * + * Example: + * baseSet = {A1 OR A2, A1 or A3} + * newSet = {A1, EXISTS r.A3} + * + * Returns: + * {A1 OR A2 OR A1, A1 OR A2 OR EXISTS r.A3, A1 OR A3 OR A1, A1 OR A3 OR EXISTS r.A3} + * + * If the base set is empty, then the return value are union class descriptions + * for each value in newSet (a union with only one concept). + * + * @param baseSet A set of union class descriptions. + * @param newSet The descriptions to add to each union class descriptions. + * @return The "cross product" of baseSet and newSet. + */ + public static SortedSet<Union> incCrossProduct(Set<Union> baseSet, Set<Description> newSet) { + SortedSet<Union> retSet = new TreeSet<Union>(new ConceptComparator()); + if(baseSet.isEmpty()) { for(Description c : newSet) { Union md = new Union(); @@ -148,4 +176,26 @@ return retSet; } + /** + * Returns true if the same property is used twice in an object some + * restriction, e.g. (EXISTS r.A1 AND A2 AND EXISTS r.A3) returns true, + * while (A1 OR A2) and (EXISTS r.A1 AND A2 AND EXISTS s.A3) return false. + * Note that the method does not work recursively, e.g. it return false + * for EXISTS r.(EXISTS r.A1 AND A2 AND EXISTS r.A3). + * + * @param d Description to test. + * @return See description. + */ + public static boolean containsDoubleObjectSomeRestriction(Description d) { + Set<String> roles = new TreeSet<String>(); + for(Description c : d.getChildren()) { + if(c instanceof ObjectSomeRestriction) { + String role = ((ObjectSomeRestriction)c).getRole().getName(); + boolean roleExists = !roles.add(role); + if(roleExists) + return true; + } + } + return false; + } } Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-03 07:45:57 UTC (rev 674) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-03 12:46:23 UTC (rev 675) @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; @@ -45,6 +46,7 @@ import org.dllearner.core.owl.Union; import org.dllearner.utilities.ConceptComparator; import org.dllearner.utilities.ConceptTransformation; +import org.dllearner.utilities.Helper; /** * A downward refinement operator, which makes use of domains @@ -81,17 +83,19 @@ // for refinements of \rho_\top(\top), the second one for \rho_A(\top) private int topRefinementsLength = 0; private Map<NamedClass, Integer> topARefinementsLength = new TreeMap<NamedClass, Integer>(); + // M is finite and this value is the maximum length of any value in M + private static int mMaxLength = 3; // the sets M_\top and M_A - private Map<Integer,Set<Description>> m = new TreeMap<Integer,Set<Description>>(); - private Map<NamedClass,Map<Integer,Set<Description>>> mA = new TreeMap<NamedClass,Map<Integer,Set<Description>>>(); + private Map<Integer,SortedSet<Description>> m = new TreeMap<Integer,SortedSet<Description>>(); + private Map<NamedClass,Map<Integer,SortedSet<Description>>> mA = new TreeMap<NamedClass,Map<Integer,SortedSet<Description>>>(); // @see MathOperations.getCombos private Map<Integer, List<List<Integer>>> combos = new HashMap<Integer, List<List<Integer>>>(); // refinements of the top concept ordered by length - private Map<Integer, TreeSet<Description>> topRefinements = new TreeMap<Integer, TreeSet<Description>>(); - private Map<NamedClass,Map<Integer, TreeSet<Description>>> topARefinements = new TreeMap<NamedClass,Map<Integer, TreeSet<Description>>>(); + private Map<Integer, SortedSet<? extends Description>> topRefinements = new TreeMap<Integer, SortedSet<? extends Description>>(); + private Map<NamedClass,Map<Integer, SortedSet<? extends Description>>> topARefinements = new TreeMap<NamedClass,Map<Integer, SortedSet<? extends Description>>>(); // cumulated refinements of top (all from length one to the specified length) private Map<Integer, TreeSet<Description>> topRefinementsCumulative = new HashMap<Integer, TreeSet<Description>>(); @@ -105,6 +109,8 @@ // most general applicable properties private Map<NamedClass,Set<ObjectProperty>> mgr = new TreeMap<NamedClass,Set<ObjectProperty>>(); + private Map<NamedClass,Set<DatatypeProperty>> mgbd = new TreeMap<NamedClass,Set<DatatypeProperty>>(); + private Map<NamedClass,Set<DatatypeProperty>> mgdd = new TreeMap<NamedClass,Set<DatatypeProperty>>(); // comparator für Konzepte private ConceptComparator conceptComparator = new ConceptComparator(); @@ -154,7 +160,7 @@ */ public Set<Description> refine(Description description, int maxLength, List<Description> knownRefinements) { - return refine(description, maxLength, knownRefinements, new Thing()); + return refine(description, maxLength, knownRefinements, startClass); } @SuppressWarnings({"unchecked"}) @@ -198,89 +204,84 @@ private void computeTopRefinements(int maxLength, NamedClass domain) { long topComputationTimeStartNs = System.nanoTime(); - // M erweiteren - computeM(maxLength); + if(domain == null && m.size() == 0) + computeM(); - // berechnen aller möglichen Kombinationen für Disjunktion, - for(int i = topRefinementsLength+1; i <= maxLength; i++) { - combos.put(i,MathOperations.getCombos(i)); - topRefinements.put(i, new TreeSet<Description>(conceptComparator)); - // topRefinements.put(i, new HashSet<Concept>()); + if(domain != null && !mA.containsKey(domain)) + computeM(domain); + + // compute all possible combinations of the disjunction + int refinementsLength = (domain == null) ? topRefinementsLength : topARefinementsLength.get(domain); + for(int i = refinementsLength+1; i <= maxLength; i++) { + combos.put(i,MathOperations.getCombos(i, mMaxLength)); +// topRefinements.put(i, new TreeSet<Description>(conceptComparator)); for(List<Integer> combo : combos.get(i)) { - // Kombination besteht aus nur einer Zahl => einfach M benutzen - // if(combo.getNumbers().size()==1) { + // combination is a single number => try to use M if(combo.size()==1) { - topRefinements.get(i).addAll(m.get(i)); - // Kombination besteht aus mehreren Zahlen => Disjunktion erzeugen + if(domain == null) + topRefinements.put(i,m.get(i)); + else + topARefinements.get(domain).put(i,mA.get(domain).get(i)); + // combinations has several numbers => generate disjunct } else { - Set<Union> baseSet = new HashSet<Union>(); - for(Integer j : combo) { // combo.getNumbers()) { + SortedSet<Union> baseSet = new TreeSet<Union>(conceptComparator); + for(Integer j : combo) { baseSet = MathOperations.incCrossProduct(baseSet, m.get(j)); } - // Umwandlung aller Konzepte in Negationsnormalform + // convert all concepts in ordered negation normal form for(Description concept : baseSet) { ConceptTransformation.transformToOrderedNegationNormalForm(concept, conceptComparator); } + // apply the exists filter (throwing out all refinements with + // double \exists r for any r) + // TODO: similar filtering can be done for boolean datatype + // properties if(applyExistsFilter) { - Iterator<Union> it = baseSet.iterator(); - while(it.hasNext()) { - Union md = it.next(); - boolean remove = false; - // falls Exists r für gleiche Rolle zweimal vorkommt, - // dann rausschmeißen - // Map<AtomicRole,Boolean> roleOccured = new HashMap<AtomicRole,Boolean>(); - Set<String> roles = new TreeSet<String>(); - for(Description c : md.getChildren()) { - if(c instanceof ObjectSomeRestriction) { - String role = ((ObjectSomeRestriction)c).getRole().getName(); - boolean roleExists = !roles.add(role); - // falls Rolle schon vorkommt, dann kann ganzes - // Refinement ignoriert werden (man könnte dann auch - // gleich abbrechen, aber das hat nur minimalste - // Auswirkungen auf Effizienz) - if(roleExists) - remove = true; - } + Iterator<Union> it = baseSet.iterator(); + while(it.hasNext()) { + if(MathOperations.containsDoubleObjectSomeRestriction(it.next())) + it.remove(); } - if(remove) - it.remove(); + } - } - } - - topRefinements.get(i).addAll(baseSet); + // add computed refinements + if(domain == null) + topRefinements.put(new Integer(i), baseSet); + else + topARefinements.get(domain).put(new Integer(i), baseSet); } } - // neu berechnete Refinements kumulieren, damit sie schneller abgefragt werden können - // computeCumulativeTopRefinements(i); + // create cumulative versions of refinements such that they can + // be accessed easily TreeSet<Description> cumulativeRefinements = new TreeSet<Description>(conceptComparator); - // Set<Concept> cumulativeRefinements = new HashSet<Concept>(); for(int j=1; j<=i; j++) { - cumulativeRefinements.addAll(topRefinements.get(j)); + if(domain == null) + cumulativeRefinements.addAll(topRefinements.get(j)); + else + cumulativeRefinements.addAll(topARefinements.get(domain).get(j)); } - topRefinementsCumulative.put(i, cumulativeRefinements); + if(domain == null) + topRefinementsCumulative.put(i, cumulativeRefinements); + else + topARefinementsCumulative.get(domain).put(i, cumulativeRefinements); } - // neue Maximallänge eintragen - topRefinementsLength = maxLength; + // register new top refinements length + if(domain == null) + topRefinementsLength = maxLength; + else + topARefinementsLength.put(domain,maxLength); topComputationTimeNs += System.nanoTime() - topComputationTimeStartNs; } // compute M_\top - private void computeM(int maxLength) { - computeM(maxLength, null); - } - - // computation of the set M_A - // a major difference compared to the ILP 2007 \rho operator is that - // M is finite and contains elements of length (currently) at most 3 - private void computeM(int maxLength, NamedClass domain) { + private void computeM() { long mComputationTimeStartNs = System.nanoTime(); // initialise all possible lengths (1 to 3) @@ -288,19 +289,19 @@ m.put(i, new TreeSet<Description>(conceptComparator)); } - Set<Description> m1 = rs.getMoreSpecialConcepts(new Thing()); + SortedSet<Description> m1 = rs.getMoreSpecialConcepts(new Thing()); m.put(1,m1); if(useNegation) { Set<Description> m2tmp = rs.getMoreGeneralConcepts(new Nothing()); - Set<Description> m2 = new TreeSet<Description>(conceptComparator); + SortedSet<Description> m2 = new TreeSet<Description>(conceptComparator); for(Description c : m2tmp) { m2.add(new Negation(c)); } m.put(2,m2); } - Set<Description> m3 = new TreeSet<Description>(conceptComparator); + SortedSet<Description> m3 = new TreeSet<Description>(conceptComparator); if(useExistsConstructor) { // only uses most general roles for(ObjectProperty r : rs.getMostGeneralRoles()) { @@ -330,13 +331,89 @@ mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; } + + // computation of the set M_A + // a major difference compared to the ILP 2007 \rho operator is that + // M is finite and contains elements of length (currently) at most 3 + private void computeM(NamedClass nc) { + long mComputationTimeStartNs = System.nanoTime(); + + mA.put(nc, new TreeMap<Integer,SortedSet<Description>>()); + // initialise all possible lengths (1 to 3) + for(int i=1; i<=3; i++) { + mA.get(nc).put(i, new TreeSet<Description>(conceptComparator)); + } - private void computeMgr(NamedClass domain) { + SortedSet<Description> m1 = rs.getMoreSpecialConcepts(nc); + m.put(1,m1); + + if(useNegation) { + // the definition in the paper is more complex, but acutally + // we only have to insert the most specific concepts satisfying + // the mentioned restrictions; there is no need to implement a + // recursive method because for A subClassOf A' we have not A' + // subClassOf A and thus: if A and B are disjoint then also A' + // and B; if not A AND B = B then also not A' AND B = B + SortedSet<Description> m2tmp = rs.getMoreGeneralConcepts(new Nothing()); + SortedSet<Description> m2 = new TreeSet<Description>(conceptComparator); + for(Description c : m2tmp) { + if(c instanceof Thing) + m2.add(c); + else { + NamedClass a = (NamedClass) c; + if(!isNotADisjoint(a, nc) && !isNotAMeaningFul(a, nc)) + m2.add(new Negation(a)); + } + } + m.put(2,m2); + } + + // compute applicable properties + computeMg(nc); + + SortedSet<Description> m3 = new TreeSet<Description>(conceptComparator); + if(useExistsConstructor) { + for(ObjectProperty r : mgr.get(nc)) { + m3.add(new ObjectSomeRestriction(r, new Thing())); + } + } + + if(useAllConstructor) { + // we allow \forall r.\top here because otherwise the operator + // becomes too difficult to manage due to dependencies between + // M_A and M_A' where A'=ran(r) + for(ObjectProperty r : mgr.get(nc)) { + m3.add(new ObjectAllRestriction(r, new Thing())); + } + } + + // boolean datatypes, e.g. testPositive = true + if(useBooleanDatatypes) { + Set<DatatypeProperty> booleanDPs = mgbd.get(nc); + for(DatatypeProperty dp : booleanDPs) { + m3.add(new BooleanValueRestriction(dp,true)); + m3.add(new BooleanValueRestriction(dp,false)); + } + } + + m.put(3,m3); + + mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; + } + + private void computeMg(NamedClass domain) { // compute the applicable properties if this has not been done yet if(appOP.get(domain) == null) - computeApp(domain); - Set<ObjectProperty> mostGeneral = rs.getMostGeneralRoles(); + computeApp(domain); + SortedSet<ObjectProperty> mostGeneral = rs.getMostGeneralRoles(); computeMgrRecursive(domain, mostGeneral, mgr.get(domain)); + SortedSet<DatatypeProperty> mostGeneralDP = rs.getMostGeneralDatatypeProperties(); + // we make the (reasonable) assumption here that all sub and super + // datatype properties have the same type (e.g. boolean, integer, double) + Set<DatatypeProperty> mostGeneralBDP = Helper.intersection(mostGeneralDP, rs.getBooleanDatatypeProperties()); + Set<DatatypeProperty> mostGeneralDDP = Helper.intersection(mostGeneralDP, rs.getDoubleDatatypeProperties()); + computeMgbdRecursive(domain, mostGeneralBDP, mgbd.get(domain)); + computeMgddRecursive(domain, mostGeneralDDP, mgdd.get(domain)); } private void computeMgrRecursive(NamedClass domain, Set<ObjectProperty> currProperties, Set<ObjectProperty> mgrTmp) { @@ -348,9 +425,27 @@ } } + private void computeMgbdRecursive(NamedClass domain, Set<DatatypeProperty> currProperties, Set<DatatypeProperty> mgbdTmp) { + for(DatatypeProperty prop : currProperties) { + if(appBD.get(domain).contains(prop)) + mgbdTmp.add(prop); + else + computeMgbdRecursive(domain, rs.getMoreSpecialDatatypeProperties(prop), mgbdTmp); + } + } + + private void computeMgddRecursive(NamedClass domain, Set<DatatypeProperty> currProperties, Set<DatatypeProperty> mgddTmp) { + for(DatatypeProperty prop : currProperties) { + if(appDD.get(domain).contains(prop)) + mgddTmp.add(prop); + else + computeMgddRecursive(domain, rs.getMoreSpecialDatatypeProperties(prop), mgddTmp); + } + } + // computes the set of applicable properties for a given class private void computeApp(NamedClass domain) { - // TODO: also implement this for boolean/double datatype properties + // object properties Set<ObjectProperty> mostGeneral = rs.getAtomicRoles(); Set<ObjectProperty> applicableRoles = new TreeSet<ObjectProperty>(); for(ObjectProperty role : mostGeneral) { @@ -361,14 +456,52 @@ applicableRoles.add(role); } appOP.put(domain, applicableRoles); + + // boolean datatype properties + Set<DatatypeProperty> mostGeneralBDPs = rs.getBooleanDatatypeProperties(); + Set<DatatypeProperty> applicableBDPs = new TreeSet<DatatypeProperty>(); + for(DatatypeProperty role : mostGeneralBDPs) { + NamedClass nc = (NamedClass) rs.getDomain(role); + if(!isDisjoint(domain,nc)) + applicableBDPs.add(role); + } + appBD.put(domain, applicableBDPs); + + // double datatype properties + Set<DatatypeProperty> mostGeneralDDPs = rs.getBooleanDatatypeProperties(); + Set<DatatypeProperty> applicableDDPs = new TreeSet<DatatypeProperty>(); + for(DatatypeProperty role : mostGeneralDDPs) { + NamedClass nc = (NamedClass) rs.getDomain(role); + if(!isDisjoint(domain,nc)) + applicableDDPs.add(role); + } + appDD.put(domain, applicableDDPs); } // computes whether two classes are disjoint; this should be computed // by the reasoner only ones and otherwise taken from a matrix - private boolean isDisjoint(NamedClass class1, NamedClass class2) { + // => this has low importance in the long run, because M is cached anyway, + // but avoids many duplicate queries when computing M + private boolean isDisjoint(NamedClass a, NamedClass b) { // we need to test whether A AND B is equivalent to BOTTOM - Description d = new Intersection(class1, class2); + Description d = new Intersection(a, b); return rs.subsumes(new Nothing(), d); } + // we need to test whether NOT A AND B is equivalent to BOTTOM + private boolean isNotADisjoint(NamedClass a, NamedClass b) { + Description notA = new Negation(a); + Description d = new Intersection(notA, b); + return rs.subsumes(new Nothing(), d); + } + + // we need to test whether NOT A AND B = B + // (if not then NOT A is not meaningful in the sense that it does + // not semantically add anything to B) + private boolean isNotAMeaningFul(NamedClass a, NamedClass b) { + Description notA = new Negation(a); + Description d = new Intersection(notA, b); + return !rs.subsumes(b, d); + } + } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-04 08:17:55
|
Revision: 681 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=681&view=rev Author: jenslehmann Date: 2008-03-04 00:17:44 -0800 (Tue, 04 Mar 2008) Log Message: ----------- TreeModel for search tree GUI Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/gui/EBNodeTreeModel.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-03-04 03:54:48 UTC (rev 680) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-03-04 08:17:44 UTC (rev 681) @@ -344,4 +344,8 @@ algorithm.stop(); } + public ExampleBasedNode getStartNode() { + return algorithm.getStartNode(); + } + } Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-04 03:54:48 UTC (rev 680) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-04 08:17:44 UTC (rev 681) @@ -103,6 +103,9 @@ // setting to true gracefully stops the algorithm private boolean stop = false; + // node from which algorithm has started + private ExampleBasedNode startNode; + // solution protocol private boolean solutionFound = false; private List<Description> solutions = new LinkedList<Description>(); @@ -220,7 +223,6 @@ allowedMisclassifications = (int) Math.round(noise * nrOfExamples); // start search with start class - ExampleBasedNode startNode; if(startDescription == null) { Thing top = new Thing(); startNode = new ExampleBasedNode(top); @@ -748,6 +750,8 @@ return learningProblem.computeScore(getBestSolution()); } - + public ExampleBasedNode getStartNode() { + return startNode; + } } Added: trunk/src/dl-learner/org/dllearner/gui/EBNodeTreeModel.java =================================================================== --- trunk/src/dl-learner/org/dllearner/gui/EBNodeTreeModel.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/gui/EBNodeTreeModel.java 2008-03-04 08:17:44 UTC (rev 681) @@ -0,0 +1,116 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +package org.dllearner.gui; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.swing.event.TreeModelEvent; +import javax.swing.event.TreeModelListener; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; + +import org.dllearner.algorithms.refexamples.ExampleBasedNode; +import org.dllearner.algorithms.refexamples.NodeComparatorStable; + +/** + * A tree model used for displaying example based nodes. A search tree + * can become very large, so lazy loading should be used, i.e. never + * load the full search tree but only the nodes selected by the user. + * Note that the search tree changes over time. + * + * @author Jens Lehmann + * + */ +public class EBNodeTreeModel implements TreeModel { + + // root of the search tree + private ExampleBasedNode rootNode; + + // a mapping from nodes to their children; + // the main problem is that example based nodes use sets instead + // of lists, so we need to convert these sets to lists and store + // them here + private Map<ExampleBasedNode,List<ExampleBasedNode>> childrenMap = new TreeMap<ExampleBasedNode,List<ExampleBasedNode>>(new NodeComparatorStable()); + + // listeners for this model + private List<TreeModelListener> treeModelListeners = + new LinkedList<TreeModelListener>(); + + public EBNodeTreeModel(ExampleBasedNode rootNode) { + this.rootNode = rootNode; + } + + public void addTreeModelListener(TreeModelListener l) { + treeModelListeners.add(l); + } + + public Object getChild(Object parent, int index) { + return getChildren((ExampleBasedNode)parent).get(index); + } + + public int getChildCount(Object parent) { + return ((ExampleBasedNode)parent).getChildren().size(); + } + + public int getIndexOfChild(Object parent, Object child) { + return getChildren((ExampleBasedNode)parent).indexOf(child); + } + + public Object getRoot() { + return rootNode; + } + + public boolean isLeaf(Object node) { + return (getChildCount(node)==0); + } + + public void removeTreeModelListener(TreeModelListener l) { + treeModelListeners.remove(l); + } + + public void valueForPathChanged(TreePath path, Object newValue) { + + } + + private void fireTreeStructureChanged(ExampleBasedNode node) { + TreeModelEvent e = new TreeModelEvent(this, + new Object[] {node}); + for (TreeModelListener tml : treeModelListeners) { + tml.treeStructureChanged(e); + } + } + + // convert the set of children to a list and store it in this model + private List<ExampleBasedNode> getChildren(ExampleBasedNode node) { + List<ExampleBasedNode> children = childrenMap.get(node); + // if the children have not been cached or the list is outdated + // (node has more children now) we do an update + if(children == null || children.size() != node.getChildren().size()) { + children = new LinkedList<ExampleBasedNode>(node.getChildren()); + childrenMap.put(node, children); + fireTreeStructureChanged(node); + } + return children; + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-05 12:07:36
|
Revision: 688 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=688&view=rev Author: jenslehmann Date: 2008-03-05 04:07:28 -0800 (Wed, 05 Mar 2008) Log Message: ----------- implemented a new heuristic Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java trunk/src/dl-learner/org/dllearner/core/owl/Thing.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java 2008-03-04 19:10:55 UTC (rev 687) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java 2008-03-05 12:07:28 UTC (rev 688) @@ -39,16 +39,15 @@ */ public class ExampleBasedNode { - // example based variables here + // example based variables private Set<Individual> coveredPositives; private Set<Individual> coveredNegatives; - // TOP ist einfach das TOP-Konzept, also das einzige welches nicht evaluiert wird + // the method by which quality was evaluated in this node public enum QualityEvaluationMethod { TOP, REASONER, TOO_WEAK_LIST, OVERLY_GENERAL_LIST }; - private QualityEvaluationMethod qualityEvaluationMethod = QualityEvaluationMethod.TOP; - // alle Eigenschaften eines Knotens im Suchbaum + // all properties of a node in the search tree private Description concept; private int horizontalExpansion; private int coveredNegativeExamples; @@ -59,28 +58,17 @@ private static ConceptComparator conceptComparator = new ConceptComparator(); private static NodeComparatorStable nodeComparator = new NodeComparatorStable(); - // Einbettung in Suchbaum + // link to parent in search tree private ExampleBasedNode parent = null; - // private Set<Node> children = new HashSet<Node>(); private Set<ExampleBasedNode> children = new TreeSet<ExampleBasedNode>(nodeComparator); - // es wird auch eine Liste von Kindern gehalten + // apart from the child nodes, we also keep child concepts private Set<Description> childConcepts = new TreeSet<Description>(conceptComparator); - // verwendeter Operator für Expansion des Knotens - // private RefinementOperator operator; - public ExampleBasedNode(Description concept) { this.concept = concept; horizontalExpansion = 0; isQualityEvaluated = false; } - - public void setCoveredNegativeExamples(int coveredNegativeExamples) { - if(isQualityEvaluated) - throw new RuntimeException("Cannot set quality of a node more than once."); - this.coveredNegativeExamples = coveredNegativeExamples; - isQualityEvaluated = true; - } public void setHorizontalExpansion(int horizontalExpansion) { this.horizontalExpansion = horizontalExpansion; @@ -104,25 +92,16 @@ return children.add(child); } - public Description getConcept() { - return concept; + public void setQualityEvaluationMethod(QualityEvaluationMethod qualityEvaluationMethod) { + this.qualityEvaluationMethod = qualityEvaluationMethod; } - public int getCoveredNegativeExamples() { - return coveredNegativeExamples; + + public void setCoveredExamples(Set<Individual> coveredPositives, Set<Individual> coveredNegatives) { + this.coveredPositives = coveredPositives; + this.coveredNegatives = coveredNegatives; + isQualityEvaluated = true; } - public int getHorizontalExpansion() { - return horizontalExpansion; - } - public boolean isQualityEvaluated() { - return isQualityEvaluated; - } - public boolean isRedundant() { - return isRedundant; - } - public boolean isTooWeak() { - return isTooWeak; - } - + @Override public String toString() { String ret = concept.toString() + " [q:"; @@ -134,7 +113,7 @@ return ret; } - // gibt die Refinement-Chain zurück, die zu dem Knoten geführt hat + // returns the refinement chain leading to this node as string public String getRefinementChainString() { if(parent!=null) { String ret = parent.getRefinementChainString(); @@ -143,8 +122,8 @@ } else { return concept.toString(); } - } - + } + public String getTreeString() { return getTreeString(0).toString(); } @@ -173,6 +152,14 @@ ret += " ("+qualityEvaluationMethod+"), he:" + horizontalExpansion + "]"; return ret; + } + + public Set<Individual> getCoveredPositives() { + return coveredPositives; + } + + public Set<Individual> getCoveredNegatives() { + return coveredNegatives; } public Set<ExampleBasedNode> getChildren() { @@ -183,28 +170,35 @@ return childConcepts; } + public Description getConcept() { + return concept; + } + public QualityEvaluationMethod getQualityEvaluationMethod() { return qualityEvaluationMethod; + } + + public int getCoveredNegativeExamples() { + return coveredNegativeExamples; } - - public void setQualityEvaluationMethod(QualityEvaluationMethod qualityEvaluationMethod) { - this.qualityEvaluationMethod = qualityEvaluationMethod; + public int getHorizontalExpansion() { + return horizontalExpansion; } - - public Set<Individual> getCoveredPositives() { - return coveredPositives; + public boolean isQualityEvaluated() { + return isQualityEvaluated; } - - public void setCoveredPositives(Set<Individual> coveredPositives) { - this.coveredPositives = coveredPositives; + public boolean isRedundant() { + return isRedundant; } - - public Set<Individual> getCoveredNegatives() { - return coveredNegatives; + public boolean isTooWeak() { + return isTooWeak; } - public void setCoveredNegatives(Set<Individual> coveredNegatives) { - this.coveredNegatives = coveredNegatives; - } - -} + /** + * @return the parent + */ + public ExampleBasedNode getParent() { + return parent; + } + +} \ No newline at end of file Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-04 19:10:55 UTC (rev 687) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-05 12:07:28 UTC (rev 688) @@ -217,37 +217,25 @@ } public void start() { - - // calculate quality threshold required for a solution allowedMisclassifications = (int) Math.round(noise * nrOfExamples); // start search with start class if(startDescription == null) { - Thing top = new Thing(); - startNode = new ExampleBasedNode(top); - // top covers all negatives - int coveredNegativeExamples = getNumberOfNegatives(); - startNode.setCoveredNegativeExamples(coveredNegativeExamples); - startNode.setCoveredPositives(learningProblem.getPositiveExamples()); - startNode.setCoveredNegatives(learningProblem.getNegativeExamples()); + startNode = new ExampleBasedNode(Thing.instance); + startNode.setCoveredExamples(learningProblem.getPositiveExamples(), learningProblem.getNegativeExamples()); } else { startNode = new ExampleBasedNode(startDescription); Set<Individual> coveredNegatives = rs.instanceCheck(startDescription, learningProblem.getNegativeExamples()); - startNode.setCoveredPositives(rs.instanceCheck(startDescription, learningProblem.getPositiveExamples())); - startNode.setCoveredNegatives(coveredNegatives); - startNode.setCoveredNegativeExamples(coveredNegatives.size()); + Set<Individual> coveredPositives = rs.instanceCheck(startDescription, learningProblem.getPositiveExamples()); + startNode.setCoveredExamples(coveredPositives, coveredNegatives); } candidates.add(startNode); candidatesStable.add(startNode); - // note that TOP may already be a solution + ExampleBasedNode bestNode = startNode; -// solutionFound = (coveredNegativeExamples == 0); -// solutions = new LinkedList<Concept>(); -// if(solutionFound) -// solutions.add(top); - + int loop = 0; algorithmStartTime = System.nanoTime(); @@ -571,8 +559,7 @@ // quality is the number of misclassifications (if it is not too weak) quality = (nrOfPositiveExamples - newlyCoveredPositives.size()) + newlyCoveredNegatives.size(); - newNode.setCoveredNegatives(newlyCoveredNegatives); - newNode.setCoveredPositives(newlyCoveredPositives); + newNode.setCoveredExamples(newlyCoveredPositives, newlyCoveredNegatives); } } @@ -588,7 +575,7 @@ solutions.add(refinement); } - newNode.setCoveredNegativeExamples(quality); +// newNode.setCoveredNegativeExamples(quality); newCandidates.add(newNode); // candidates.add(newNode); // candidatesStable.add(newNode); Added: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-05 12:07:28 UTC (rev 688) @@ -0,0 +1,114 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +package org.dllearner.algorithms.refexamples; + +import org.dllearner.utilities.ConceptComparator; + +/** + * This heuristic combines the following criteria to assign a + * double score value to a node: + * <ul> + * <li>quality/accuracy of a concept (based on the full training set, not + * the negative example coverage as the flexible heuristic)</li> + * <li>horizontal expansion</li> + * <li>accuracy gain: The heuristic takes into account the accuracy + * difference between a node and its parent. If there is no gain (even + * though we know that the refinement is proper) it is unlikely (although + * not excluded) that the refinement is a necessary path to take towards a + * solution.</li> + * </ul> + * + * The heuristic has two parameters: + * <ul> + * <li>expansion penalty factor: describes how much accuracy gain is worth + * an increase of horizontal expansion by one (typical value: 0.01)</li> + * <li>gain bonus factor: describes how accuracy gain should be weighted + * versus accuracy itself (typical value: 1.00)</li> + * </ul> + * + * The value of a node is calculated as follows: + * + * <p><code>value = accuracy + gain bonus factor * accuracy gain - expansion penalty + * factor * horizontal expansion</code></p> + * + * <p><code>accuracy = (TP + TN)/(P + N)</code></p> + * + * <p><code> + * TP = number of true positives (= covered positives)<br /> + * TN = number of true negatives (= nr of negatives examples - covered negatives)<br /> + * P = number of positive examples<br /> + * N = number of negative examples<br /> + * </code></p> + * + * @author Jens Lehmann + * + */ +public class MultiHeuristic implements ExampleBasedHeuristic { + + private ConceptComparator conceptComparator = new ConceptComparator(); + + // heuristic parameters + private double expansionPenaltyFactor = 0.01; + private double gainBonusFactor = 1.00; + + // examples + private int nrOfNegativeExamples; + private int nrOfExamples; + + public MultiHeuristic(int nrOfPositiveExamples, int nrOfNegativeExamples, double expansionPenaltyFactor, double gainBonusFactor) { + this.nrOfNegativeExamples = nrOfNegativeExamples; + nrOfExamples = nrOfPositiveExamples + nrOfNegativeExamples; + this.expansionPenaltyFactor = expansionPenaltyFactor; + this.gainBonusFactor = gainBonusFactor; + } + + /* (non-Javadoc) + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + public int compare(ExampleBasedNode node1, ExampleBasedNode node2) { + double score1 = getNodeScore(node1); + double score2 = getNodeScore(node2); + double diff = score1 - score2; + if(diff>0) + return 1; + else if(diff<0) + return -1; + else + // TODO: would it be OK to simply return 0 here (?) + // could improve performance a bit + return conceptComparator.compare(node1.getConcept(), node2.getConcept()); + } + + public double getNodeScore(ExampleBasedNode node) { + double accuracy = getAccuracy(node.getCoveredPositives().size(),node.getCoveredNegatives().size()); + ExampleBasedNode parent = node.getParent(); + double gain = 0; + if(parent != null) { + double parentAccuracy = getAccuracy(parent.getCoveredPositives().size(),parent.getCoveredNegatives().size()); + gain = accuracy - parentAccuracy; + } + return accuracy + gainBonusFactor * gain - expansionPenaltyFactor * node.getHorizontalExpansion(); + } + + private double getAccuracy(int coveredPositives, int coveredNegatives) { + return (coveredPositives + nrOfNegativeExamples - coveredNegatives)/(double)nrOfExamples; + + } +} Modified: trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java 2008-03-04 19:10:55 UTC (rev 687) +++ trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java 2008-03-05 12:07:28 UTC (rev 688) @@ -1,3 +1,22 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ package org.dllearner.core.owl; import java.util.Map; @@ -2,13 +21,11 @@ - - +/** + * Implementation of owl:nothing/BOTTOM. + * + * @author Jens Lehmann + * + */ public class Nothing extends Description { - /* - @Override - protected void calculateSets(FlatABox abox, SortedSet<String> adcPosSet, SortedSet<String> adcNegSet) { - posSet = abox.bottom; - negSet = abox.top; - } - */ + public static final Nothing instance = new Nothing(); @@ -48,5 +65,4 @@ visitor.visit(this); } - } Modified: trunk/src/dl-learner/org/dllearner/core/owl/Thing.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Thing.java 2008-03-04 19:10:55 UTC (rev 687) +++ trunk/src/dl-learner/org/dllearner/core/owl/Thing.java 2008-03-05 12:07:28 UTC (rev 688) @@ -1,3 +1,22 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ package org.dllearner.core.owl; import java.util.Map; @@ -2,12 +21,19 @@ +/** + * Implementation of owl:thing/TOP. + * + * TODO: According to the OWL 1.1 spec, owl:thing is special instance of + * class, so it might be better to put a method there for retrieving + * a/the instance of owl:thing. However, some algorithms require parent + * links e.g. in EXISTS r.TOP we may need to know where TOP belongs + * (especially for genetic operators). This is instance dependant, i.e. + * two different instances of TOP can have different parent links. + * + * @author Jens Lehmann + * + */ public class Thing extends Description { - /* - @Override - protected void calculateSets(FlatABox abox, SortedSet<String> adcPosSet, SortedSet<String> adcNegSet) { - posSet = abox.top; - negSet = abox.bottom; - } - */ - + public static final Thing instance = new Thing(); + public String toString(String baseURI, Map<String,String> prefixes) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-07 08:44:26
|
Revision: 692 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=692&view=rev Author: jenslehmann Date: 2008-03-07 00:44:10 -0800 (Fri, 07 Mar 2008) Log Message: ----------- added ORE tool package Added Paths: ----------- trunk/src/dl-learner/org/dllearner/tools/ trunk/src/dl-learner/org/dllearner/tools/ore/ trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java Added: trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java =================================================================== --- trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java 2008-03-07 08:44:10 UTC (rev 692) @@ -0,0 +1,30 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +package org.dllearner.tools.ore; + +/** + * Start class for the ontology repair and enrichment tool. + * + * @author Lorenz Bühmann. + * + */ +public class ORE { + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-09 11:49:31
|
Revision: 697 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=697&view=rev Author: jenslehmann Date: 2008-03-09 04:49:21 -0700 (Sun, 09 Mar 2008) Log Message: ----------- - added disjointness test (including result cache) to further reduce refinements in new operator - bug fix for deactivated negation Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-09 02:16:01 UTC (rev 696) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-09 11:49:21 UTC (rev 697) @@ -260,7 +260,8 @@ bestNode = candidates.last(); // extend best node newCandidates.clear(); - // TODO: why is the best node tempoariliy removed from the candidates set? + // best node is removed temporarily, because extending it can + // change its evaluation candidates.remove(bestNode); extendNodeProper(bestNode, bestNode.getHorizontalExpansion()+1); candidates.add(bestNode); Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-09 02:16:01 UTC (rev 696) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-09 11:49:21 UTC (rev 697) @@ -302,6 +302,11 @@ @Override public SortedSet<Individual> retrieval(Description concept) throws ReasoningMethodUnsupportedException { + if(concept instanceof NamedClass) + return classInstancesPos.get((NamedClass)concept); + else if(concept instanceof Negation && concept.getChild(0) instanceof NamedClass) + return classInstancesNeg.get((NamedClass)concept.getChild(0)); + // return rs.retrieval(concept); SortedSet<Individual> inds = new TreeSet<Individual>(); for(Individual i : individuals) { Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-09 02:16:01 UTC (rev 696) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-09 11:49:21 UTC (rev 697) @@ -35,6 +35,7 @@ import org.dllearner.core.owl.BooleanValueRestriction; import org.dllearner.core.owl.DatatypeProperty; import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.Individual; import org.dllearner.core.owl.Intersection; import org.dllearner.core.owl.NamedClass; import org.dllearner.core.owl.Negation; @@ -127,11 +128,14 @@ private boolean useAllConstructor = true; private boolean useExistsConstructor = true; private boolean useNegation = true; - private boolean useBooleanDatatypes = true; + private boolean useBooleanDatatypes = true; + private boolean instanceBasedDisjoints = true; // caches for reasoner queries + private Map<Description,Map<Description,Boolean>> cachedDisjoints = new TreeMap<Description,Map<Description,Boolean>>(conceptComparator); + // private Map<NamedClass,Map<NamedClass,Boolean>> abDisjoint = new TreeMap<NamedClass,Map<NamedClass,Boolean>>(); - private Map<NamedClass,Map<NamedClass,Boolean>> notABDisjoint = new TreeMap<NamedClass,Map<NamedClass,Boolean>>(); +// private Map<NamedClass,Map<NamedClass,Boolean>> notABDisjoint = new TreeMap<NamedClass,Map<NamedClass,Boolean>>(); // private Map<NamedClass,Map<NamedClass,Boolean>> notABMeaningful = new TreeMap<NamedClass,Map<NamedClass,Boolean>>(); public RhoDRDown(ReasoningService reasoningService) { @@ -160,6 +164,18 @@ dpDomains.put(dp, rs.getDomain(dp)); } + +// NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Structure"); +// computeTopRefinements(3,struc); +// for(Description d : topARefinements.get(struc).get(1)) { + // bei 3 ist noch alles OK, bei 4 seltsamer Fehler mit Union +// for(Description d : refine(Thing.instance,3,null,struc)) { +// if(d instanceof Union) +// System.out.println(d); +// } +// System.out.println(refine(Thing.instance,7,null,struc).size()); +// System.exit(0); + if(startClass != null) this.startClass = startClass; } @@ -245,8 +261,7 @@ // (non-recursive variant because only depth 1 was modified) ConceptTransformation.cleanConceptNonRecursive(mc); ConceptTransformation.transformToOrderedNegationNormalFormNonRecursive(mc, conceptComparator); - - refinements.add(mc); + } } @@ -318,8 +333,9 @@ } - // if a refinement is neither Bottom nor Top a refinement of top can be appended - if(!(description instanceof Thing) && !(description instanceof Nothing)) { + // if a refinement is not Bottom, Top, ALL r.Bottom a refinement of top can be appended + if(!(description instanceof Thing) && !(description instanceof Nothing) + && !(description instanceof ObjectAllRestriction && description.getChild(0) instanceof Nothing)) { // -1 because of the AND symbol which is appended int topRefLength = maxLength - description.getLength() - 1; @@ -357,6 +373,14 @@ } } + // perform a disjointness check when named classes are added; + // this can avoid a lot of superfluous computation in the algorithm e.g. + // when A1 looks good, so many refinements of the form (A1 OR (A2 AND A3)) + // are generated which are all equal to A1 due to disjointness of A2 and A3 + if(c instanceof NamedClass && isDisjoint(description, c)) + // refinements.add(mc); + skip = true; + if(!skip) { Intersection mc = new Intersection(); mc.addChild(description); @@ -365,13 +389,20 @@ // clean and transform to ordered negation normal form ConceptTransformation.cleanConceptNonRecursive(mc); ConceptTransformation.transformToOrderedNegationNormalFormNonRecursive(mc, conceptComparator); - + refinements.add(mc); } } } } +// for(Description refinement : refinements) { +// if((refinement instanceof Intersection || refinement instanceof Union) && refinement.getChildren().size()<2) { +// System.out.println(description + " " + refinement + " " + currDomain + " " + maxLength); +// System.exit(0); +// } +// } + return refinements; } @@ -424,36 +455,52 @@ topARefinements.get(domain).get(i).addAll(mA.get(domain).get(i)); // combinations has several numbers => generate disjunct } else { - SortedSet<Union> baseSet = new TreeSet<Union>(conceptComparator); + + // check whether the combination makes sense, i.e. whether + // all lengths mentioned in it have corresponding elements + // e.g. when negation is deactivated there won't be elements of + // length 2 in M + boolean validCombo = true; for(Integer j : combo) { - if(domain == null) - baseSet = MathOperations.incCrossProduct(baseSet, m.get(j)); - else - baseSet = MathOperations.incCrossProduct(baseSet, mA.get(domain).get(j)); + if((domain == null && m.get(j).size()==0) || + (domain != null && mA.get(domain).get(j).size()==0)) + validCombo = false; } - // convert all concepts in ordered negation normal form - for(Description concept : baseSet) { - ConceptTransformation.transformToOrderedNegationNormalForm(concept, conceptComparator); - } - - // apply the exists filter (throwing out all refinements with - // double \exists r for any r) - // TODO: similar filtering can be done for boolean datatype - // properties - if(applyExistsFilter) { - Iterator<Union> it = baseSet.iterator(); - while(it.hasNext()) { - if(MathOperations.containsDoubleObjectSomeRestriction(it.next())) - it.remove(); + if(validCombo) { + + SortedSet<Union> baseSet = new TreeSet<Union>(conceptComparator); + for(Integer j : combo) { + if(domain == null) + baseSet = MathOperations.incCrossProduct(baseSet, m.get(j)); + else + baseSet = MathOperations.incCrossProduct(baseSet, mA.get(domain).get(j)); } + + // convert all concepts in ordered negation normal form + for(Description concept : baseSet) { + ConceptTransformation.transformToOrderedNegationNormalForm(concept, conceptComparator); + } + + // apply the exists filter (throwing out all refinements with + // double \exists r for any r) + // TODO: similar filtering can be done for boolean datatype + // properties + if(applyExistsFilter) { + Iterator<Union> it = baseSet.iterator(); + while(it.hasNext()) { + if(MathOperations.containsDoubleObjectSomeRestriction(it.next())) + it.remove(); + } + } + + // add computed refinements + if(domain == null) + topRefinements.get(i).addAll(baseSet); + else + topARefinements.get(domain).get(i).addAll(baseSet); + } - - // add computed refinements - if(domain == null) - topRefinements.get(i).addAll(baseSet); - else - topARefinements.get(domain).get(i).addAll(baseSet); } } @@ -690,31 +737,99 @@ appDD.put(domain, applicableDDPs); } + // returns true of the intersection contains elements disjoint + // to the given description (if true adding the description to + // the intersection results in a description equivalent to bottom) + // e.g. OldPerson AND YoungPerson; Nitrogen-34 AND Tin-113 + // Note: currently we only check named classes in the intersection, + // it would be interesting to see whether it makes sense to extend this + // (advantage: less refinements, drawback: operator will need infinitely many + // reasoner queries in the long run) + @SuppressWarnings({"unused"}) + private boolean containsDisjoints(Intersection intersection, Description d) { + List<Description> children = intersection.getChildren(); + for(Description child : children) { + if(d instanceof Nothing) + return true; + else if(child instanceof NamedClass) { + if(isDisjoint((NamedClass)child, d)) + return true; + } + } + return false; + } + + private boolean isDisjoint(Description d1, Description d2) { + // equal concepts are not disjoint (unless equivalent to bottom) +// if(conceptComparator.compare(d1, d2)==0) +// return false; + + // check whether we have cached this query + Map<Description,Boolean> tmp = cachedDisjoints.get(d1); + Boolean tmp2 = null; + if(tmp != null) + tmp2 = tmp.get(d2); + + if(tmp2==null) { + Boolean result; + if(instanceBasedDisjoints) { + result = isDisjointInstanceBased(d1,d2); + } else { + Description d = new Intersection(d1, d2); + result = rs.subsumes(new Nothing(), d); + } + // add the result to the cache (we add it twice such that + // the order of access does not matter) + + // create new entries if necessary + Map<Description,Boolean> map = new TreeMap<Description,Boolean>(conceptComparator); + if(tmp == null) + cachedDisjoints.put(d1, map); + if(!cachedDisjoints.containsKey(d2)) + cachedDisjoints.put(d2, map); + + // add result symmetrically in the description matrix + cachedDisjoints.get(d1).put(d2, result); + cachedDisjoints.get(d2).put(d1, result); + return result; + } else + return tmp2; + } + + private boolean isDisjointInstanceBased(Description d1, Description d2) { + Set<Individual> d1Instances = rs.retrieval(d1); + Set<Individual> d2Instances = rs.retrieval(d2); + for(Individual d1Instance : d1Instances) { + if(d2Instances.contains(d1Instance)) + return false; + } + return true; + } + + /* // computes whether two classes are disjoint; this should be computed // by the reasoner only ones and otherwise taken from a matrix - // => this has low importance in the long run, because M is cached anyway, - // but avoids many duplicate queries when computing M private boolean isDisjoint(NamedClass a, Description d) { // we need to test whether A AND B is equivalent to BOTTOM Description d2 = new Intersection(a, d); return rs.subsumes(new Nothing(), d2); - } + }*/ // we need to test whether NOT A AND B is equivalent to BOTTOM private boolean isNotADisjoint(NamedClass a, NamedClass b) { - Map<NamedClass,Boolean> tmp = notABDisjoint.get(a); - Boolean tmp2 = null; - if(tmp != null) - tmp2 = tmp.get(b); - - if(tmp2==null) { +// Map<NamedClass,Boolean> tmp = notABDisjoint.get(a); +// Boolean tmp2 = null; +// if(tmp != null) +// tmp2 = tmp.get(b); +// +// if(tmp2==null) { Description notA = new Negation(a); Description d = new Intersection(notA, b); Boolean result = rs.subsumes(new Nothing(), d); // ... add to cache ... return result; - } else - return tmp2; +// } else +// return tmp2; } // we need to test whether NOT A AND B = B This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-09 19:26:51
|
Revision: 699 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=699&view=rev Author: jenslehmann Date: 2008-03-09 12:25:46 -0700 (Sun, 09 Mar 2008) Log Message: ----------- small algorithm bug fixes and reasoning improvements Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java 2008-03-09 17:49:11 UTC (rev 698) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java 2008-03-09 19:25:46 UTC (rev 699) @@ -47,8 +47,8 @@ private Set<Individual> coveredNegatives; // the method by which quality was evaluated in this node - public enum QualityEvaluationMethod { TOP, REASONER, TOO_WEAK_LIST, OVERLY_GENERAL_LIST }; - private QualityEvaluationMethod qualityEvaluationMethod = QualityEvaluationMethod.TOP; + public enum QualityEvaluationMethod { START, REASONER, TOO_WEAK_LIST, OVERLY_GENERAL_LIST }; + private QualityEvaluationMethod qualityEvaluationMethod = QualityEvaluationMethod.START; // all properties of a node in the search tree private Description concept; Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-09 17:49:11 UTC (rev 698) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-09 19:25:46 UTC (rev 699) @@ -599,6 +599,7 @@ // + nrOfNegativeExamples - bestNode.getCoveredNegatives().size())/(double)nrOfExamples); // Refinementoperator auf Konzept anwenden // String bestNodeString = "currently best node: " + bestNode + " accuracy: " + df.format(accuracy) + "%"; + System.out.println("start node: " + startNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); String bestNodeString = "currently best node: " + bestNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI); // searchTree += bestNodeString + "\n"; System.out.println(bestNodeString); @@ -612,6 +613,7 @@ // System.out.println("max. number of children of a node: " + maxNrOfChildren); System.out.println("subsumption time: " + Helper.prettyPrintNanoSeconds(rs.getSubsumptionReasoningTimeNs())); System.out.println("instance check time: " + Helper.prettyPrintNanoSeconds(rs.getInstanceCheckReasoningTimeNs())); + System.out.println("retrieval time: " + Helper.prettyPrintNanoSeconds(rs.getRetrievalReasoningTimeNs())); } if(computeBenchmarkInformation) { Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-09 17:49:11 UTC (rev 698) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-09 19:25:46 UTC (rev 699) @@ -19,6 +19,10 @@ */ package org.dllearner.algorithms.refexamples; +import java.util.List; + +import org.dllearner.core.owl.BooleanValueRestriction; +import org.dllearner.core.owl.Description; import org.dllearner.utilities.ConceptComparator; /** @@ -73,13 +77,14 @@ private double expansionPenaltyFactor; private double gainBonusFactor; private double nodeChildPenalty = 0.0001; + private double startNodeBonus = 0.8; // examples private int nrOfNegativeExamples; private int nrOfExamples; public MultiHeuristic(int nrOfPositiveExamples, int nrOfNegativeExamples) { - this(nrOfPositiveExamples, nrOfNegativeExamples, 0.03, 0.5); + this(nrOfPositiveExamples, nrOfNegativeExamples, 0.02, 0.5); } public MultiHeuristic(int nrOfPositiveExamples, int nrOfNegativeExamples, double expansionPenaltyFactor, double gainBonusFactor) { @@ -113,8 +118,11 @@ if(parent != null) { double parentAccuracy = getAccuracy(parent.getCoveredPositives().size(),parent.getCoveredNegatives().size()); gain = accuracy - parentAccuracy; + } else { + accuracy += startNodeBonus; } - return accuracy + gainBonusFactor * gain - expansionPenaltyFactor * node.getHorizontalExpansion() - nodeChildPenalty * node.getChildren().size(); + int he = node.getHorizontalExpansion() - getHeuristicLengthBonus(node.getConcept()); + return accuracy + gainBonusFactor * gain - expansionPenaltyFactor * he - nodeChildPenalty * node.getChildren().size(); } private double getAccuracy(int coveredPositives, int coveredNegatives) { @@ -127,4 +135,18 @@ return multi.getNodeScore(node); } + // this function can be used to give some constructs a length bonus + // compared to their syntactic length + private static int getHeuristicLengthBonus(Description description) { + int bonus = 0; + + if(description instanceof BooleanValueRestriction) + bonus = 1; + + List<Description> children = description.getChildren(); + for(Description child : children) { + bonus += getHeuristicLengthBonus(child); + } + return bonus; + } } Modified: trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java 2008-03-09 17:49:11 UTC (rev 698) +++ trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java 2008-03-09 19:25:46 UTC (rev 699) @@ -50,5 +50,12 @@ public boolean getBooleanValue() { return booleanValue; } - + + /** + * Boolean value restrictions have length 2, because they encode two + * pieces of information: the property and the boolean value. + */ + public int getLength() { + return 2; + } } Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java 2008-03-09 17:49:11 UTC (rev 698) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java 2008-03-09 19:25:46 UTC (rev 699) @@ -29,7 +29,7 @@ * @author Jens Lehmann * */ -public class DatatypeValueRestriction extends ValueRestriction { +public abstract class DatatypeValueRestriction extends ValueRestriction { public DatatypeValueRestriction(DatatypeProperty restrictedPropertyExpression, Constant value) { super(restrictedPropertyExpression, value); @@ -55,9 +55,12 @@ /* (non-Javadoc) * @see org.dllearner.core.owl.KBElement#getLength() */ - public int getLength() { - return 1 + restrictedPropertyExpression.getLength() + value.getLength(); - } + // we do not add the + 1 here because e.g. for boolean values we + // probably do not want to add it while for double value we may + // add it (because "<=" ">=" are possible while boolean has only "=") +// public int getLength() { +// return 1 + restrictedPropertyExpression.getLength() + value.getLength(); +// } /* (non-Javadoc) * @see org.dllearner.core.owl.KBElement#toString(java.lang.String, java.util.Map) Modified: trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-09 17:49:11 UTC (rev 698) +++ trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-09 19:25:46 UTC (rev 699) @@ -659,6 +659,31 @@ return map; } + public Map<Individual, SortedSet<Double>> getDoubleValues(DatatypeProperty datatypeProperty) { + OWLDataProperty prop = getOWLAPIDescription(datatypeProperty); + Map<Individual, SortedSet<Double>> map = new TreeMap<Individual, SortedSet<Double>>(); + for(Individual i : individuals) { + OWLIndividual ind = factory.getOWLIndividual(URI.create(i.getName())); + + // get all related individuals via OWL API + Set<OWLConstant> inds = null; + try { + inds = reasoner.getRelatedValues(ind, prop); + } catch (OWLReasonerException e) { + e.printStackTrace(); + } + + // convert data back to DL-Learner structures + SortedSet<Double> is = new TreeSet<Double>(); + for(OWLConstant oi : inds) { + Double d = Double.parseDouble(oi.getLiteral()); + is.add(d); + } + map.put(i, is); + } + return map; + } + @Override public Map<Individual, SortedSet<Constant>> getDatatypeMembers(DatatypeProperty datatypeProperty) { OWLDataProperty prop = getOWLAPIDescription(datatypeProperty); Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-09 17:49:11 UTC (rev 698) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-09 19:25:46 UTC (rev 699) @@ -129,6 +129,7 @@ private boolean useExistsConstructor = true; private boolean useNegation = true; private boolean useBooleanDatatypes = true; + private boolean disjointChecks = true; private boolean instanceBasedDisjoints = true; // caches for reasoner queries @@ -164,18 +165,38 @@ dpDomains.put(dp, rs.getDomain(dp)); } - -// NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Structure"); + /* + NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Compound"); + ObjectProperty op = new ObjectProperty("http://dl-learner.org/carcinogenesis#hasAtom"); + ObjectAllRestriction oar = new ObjectAllRestriction(op,struc); + String str = "((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS FALSE) OR ALL \"http://dl-learner.org/carcinogenesis#hasAtom\".TOP)"; + Description desc = null; + try { + desc = KBParser.parseConcept(str); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } +// System.out.println(oar.getLength()); // computeTopRefinements(3,struc); // for(Description d : topARefinements.get(struc).get(1)) { // bei 3 ist noch alles OK, bei 4 seltsamer Fehler mit Union -// for(Description d : refine(Thing.instance,3,null,struc)) { + Set<Description> ds = refine(struc,10,null,struc); + Set<Description> improper = new HashSet<Description>(); + for(Description d : ds) { // if(d instanceof Union) -// System.out.println(d); -// } + if(rs.subsumes(d, struc)) { + improper.add(d); + System.out.println(d); + } + } // System.out.println(refine(Thing.instance,7,null,struc).size()); -// System.exit(0); + System.out.println(ds.size()); + System.out.println(improper.size()); + System.exit(0); + */ + if(startClass != null) this.startClass = startClass; } @@ -199,15 +220,16 @@ public Set<Description> refine(Description description, int maxLength, List<Description> knownRefinements, Description currDomain) { -// System.out.println(description + " " + currDomain); +// System.out.println(description + " " + currDomain + " " + maxLength); // actions needing to be performed if this is the first time the // current domain is used if(!(currDomain instanceof Thing) && !topARefinementsLength.containsKey(currDomain)) topARefinementsLength.put((NamedClass)currDomain, 0); - // TODO: check whether using list or set makes more sense + // check whether using list or set makes more sense // here; and whether HashSet or TreeSet should be used + // => TreeSet because duplicates are possible Set<Description> refinements = new TreeSet<Description>(conceptComparator); // used as temporary variable @@ -261,7 +283,8 @@ // (non-recursive variant because only depth 1 was modified) ConceptTransformation.cleanConceptNonRecursive(mc); ConceptTransformation.transformToOrderedNegationNormalFormNonRecursive(mc, conceptComparator); - + + refinements.add(mc); } } @@ -270,6 +293,8 @@ // refine one of the elements for(Description child : description.getChildren()) { +// System.out.println("union child: " + child + " " + maxLength + " " + description.getLength() + " " + child.getLength()); + // refine child tmp = refine(child, maxLength - description.getLength()+child.getLength(),null,currDomain); @@ -377,9 +402,10 @@ // this can avoid a lot of superfluous computation in the algorithm e.g. // when A1 looks good, so many refinements of the form (A1 OR (A2 AND A3)) // are generated which are all equal to A1 due to disjointness of A2 and A3 - if(c instanceof NamedClass && isDisjoint(description, c)) - // refinements.add(mc); + if(disjointChecks && c instanceof NamedClass && description instanceof NamedClass && isDisjoint(description, c)) { skip = true; +// System.out.println(c + " ignored when refining " + description); + } if(!skip) { Intersection mc = new Intersection(); @@ -545,14 +571,23 @@ SortedSet<Description> m1 = rs.getMoreSpecialConcepts(new Thing()); m.put(1,m1); + SortedSet<Description> m2 = new TreeSet<Description>(conceptComparator); if(useNegation) { Set<Description> m2tmp = rs.getMoreGeneralConcepts(new Nothing()); - SortedSet<Description> m2 = new TreeSet<Description>(conceptComparator); for(Description c : m2tmp) { m2.add(new Negation(c)); } - m.put(2,m2); } + + // boolean datatypes, e.g. testPositive = true + if(useBooleanDatatypes) { + Set<DatatypeProperty> booleanDPs = rs.getBooleanDatatypeProperties(); + for(DatatypeProperty dp : booleanDPs) { + m2.add(new BooleanValueRestriction(dp,true)); + m2.add(new BooleanValueRestriction(dp,false)); + } + } + m.put(2,m2); SortedSet<Description> m3 = new TreeSet<Description>(conceptComparator); if(useExistsConstructor) { @@ -571,15 +606,6 @@ } } - // boolean datatypes, e.g. testPositive = true - if(useBooleanDatatypes) { - Set<DatatypeProperty> booleanDPs = rs.getBooleanDatatypeProperties(); - for(DatatypeProperty dp : booleanDPs) { - m3.add(new BooleanValueRestriction(dp,true)); - m3.add(new BooleanValueRestriction(dp,false)); - } - } - m.put(3,m3); mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; @@ -600,6 +626,7 @@ SortedSet<Description> m1 = rs.getMoreSpecialConcepts(nc); mA.get(nc).put(1,m1); + SortedSet<Description> m2 = new TreeSet<Description>(conceptComparator); if(useNegation) { // the definition in the paper is more complex, but acutally // we only have to insert the most specific concepts satisfying @@ -608,7 +635,7 @@ // subClassOf A and thus: if A and B are disjoint then also A' // and B; if not A AND B = B then also not A' AND B = B SortedSet<Description> m2tmp = rs.getMoreGeneralConcepts(new Nothing()); - SortedSet<Description> m2 = new TreeSet<Description>(conceptComparator); + for(Description c : m2tmp) { if(c instanceof Thing) m2.add(c); @@ -617,13 +644,23 @@ if(!isNotADisjoint(a, nc) && isNotAMeaningful(a, nc)) m2.add(new Negation(a)); } + } + } + + // compute applicable properties + computeMg(nc); + + // boolean datatypes, e.g. testPositive = true + if(useBooleanDatatypes) { + Set<DatatypeProperty> booleanDPs = mgbd.get(nc); + for(DatatypeProperty dp : booleanDPs) { + m2.add(new BooleanValueRestriction(dp,true)); + m2.add(new BooleanValueRestriction(dp,false)); } - mA.get(nc).put(2,m2); } + + mA.get(nc).put(2,m2); - // compute applicable properties - computeMg(nc); - SortedSet<Description> m3 = new TreeSet<Description>(conceptComparator); if(useExistsConstructor) { for(ObjectProperty r : mgr.get(nc)) { @@ -640,15 +677,6 @@ } } - // boolean datatypes, e.g. testPositive = true - if(useBooleanDatatypes) { - Set<DatatypeProperty> booleanDPs = mgbd.get(nc); - for(DatatypeProperty dp : booleanDPs) { - m3.add(new BooleanValueRestriction(dp,true)); - m3.add(new BooleanValueRestriction(dp,false)); - } - } - mA.get(nc).put(3,m3); mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-10 17:54:15
|
Revision: 700 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=700&view=rev Author: jenslehmann Date: 2008-03-10 10:53:52 -0700 (Mon, 10 Mar 2008) Log Message: ----------- double datatype learning support Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java trunk/src/dl-learner/org/dllearner/core/Reasoner.java trunk/src/dl-learner/org/dllearner/core/ReasoningService.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIDescriptionConvertVisitor.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/core/owl/SimpleDoubleDataRange.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-10 17:53:52 UTC (rev 700) @@ -100,6 +100,12 @@ private boolean useOverlyGeneralList = true; private boolean useShortConceptConstruction = true; + // if set to false we do not test properness; this may seem wrong + // but the disadvantage of properness testing are additional reasoner + // queries and a search bias towards ALL r.something because + // ALL r.TOP is improper and automatically expanded further + private boolean testProperness = false; + // setting to true gracefully stops the algorithm private boolean stop = false; @@ -431,11 +437,13 @@ Set<Description> improperConcepts = null; if(toEvaluateConcepts.size()>0) { // Test aller Konzepte auf properness (mit DIG in nur einer Anfrage) - long propCalcReasoningStart = System.nanoTime(); - improperConcepts = rs.subsumes(toEvaluateConcepts, concept); - propernessTestsReasoner+=toEvaluateConcepts.size(); - // boolean isProper = !learningProblem.getReasoningService().subsumes(refinement, concept); - propernessCalcReasoningTimeNs += System.nanoTime() - propCalcReasoningStart; + if(testProperness) { + long propCalcReasoningStart = System.nanoTime(); + improperConcepts = rs.subsumes(toEvaluateConcepts, concept); + propernessTestsReasoner+=toEvaluateConcepts.size(); + // boolean isProper = !learningProblem.getReasoningService().subsumes(refinement, concept); + propernessCalcReasoningTimeNs += System.nanoTime() - propCalcReasoningStart; + } } long improperConceptsRemovalTimeNsStart = System.nanoTime(); Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-10 17:53:52 UTC (rev 700) @@ -77,7 +77,7 @@ private double expansionPenaltyFactor; private double gainBonusFactor; private double nodeChildPenalty = 0.0001; - private double startNodeBonus = 0.8; + private double startNodeBonus = 0.1; // examples private int nrOfNegativeExamples; Modified: trunk/src/dl-learner/org/dllearner/core/Reasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/Reasoner.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/core/Reasoner.java 2008-03-10 17:53:52 UTC (rev 700) @@ -79,6 +79,12 @@ public Map<Individual, SortedSet<Constant>> getDatatypeMembers(DatatypeProperty datatypeProperty) throws ReasoningMethodUnsupportedException; + // some convenience methods + public Map<Individual, SortedSet<Double>> getDoubleDatatypeMembers(DatatypeProperty datatypeProperty) throws ReasoningMethodUnsupportedException; + public Map<Individual, SortedSet<Boolean>> getBooleanDatatypeMembers(DatatypeProperty datatypeProperty) throws ReasoningMethodUnsupportedException; + public SortedSet<Individual> getTrueDatatypeMembers(DatatypeProperty datatypeProperty) throws ReasoningMethodUnsupportedException; + public SortedSet<Individual> getFalseDatatypeMembers(DatatypeProperty datatypeProperty) throws ReasoningMethodUnsupportedException; + public boolean instanceCheck(Description concept, Individual individual) throws ReasoningMethodUnsupportedException; // mehrere instance checks für ein Konzept - spart bei DIG Anfragen Modified: trunk/src/dl-learner/org/dllearner/core/ReasoningService.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ReasoningService.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/core/ReasoningService.java 2008-03-10 17:53:52 UTC (rev 700) @@ -459,6 +459,42 @@ return result; } + public Map<Individual, SortedSet<Double>> getDoubleDatatypeMembers(DatatypeProperty datatypeProperty) { + try { + return reasoner.getDoubleDatatypeMembers(datatypeProperty); + } catch (ReasoningMethodUnsupportedException e) { + handleExceptions(e); + return null; + } + } + + public Map<Individual, SortedSet<Double>> getIntDatatypeMembers(DatatypeProperty datatypeProperty) { + try { + return reasoner.getDoubleDatatypeMembers(datatypeProperty); + } catch (ReasoningMethodUnsupportedException e) { + handleExceptions(e); + return null; + } + } + + public Map<Individual, SortedSet<Double>> getTrueDatatypeMembers(DatatypeProperty datatypeProperty) { + try { + return reasoner.getDoubleDatatypeMembers(datatypeProperty); + } catch (ReasoningMethodUnsupportedException e) { + handleExceptions(e); + return null; + } + } + + public Map<Individual, SortedSet<Double>> getFalseDatatypeMembers(DatatypeProperty datatypeProperty) { + try { + return reasoner.getDoubleDatatypeMembers(datatypeProperty); + } catch (ReasoningMethodUnsupportedException e) { + handleExceptions(e); + return null; + } + } + public Set<NamedClass> getAtomicConcepts() { return reasoner.getAtomicConcepts(); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java 2008-03-10 17:53:52 UTC (rev 700) @@ -32,11 +32,14 @@ */ public class DatatypeSomeRestriction extends DatatypeQuantorRestriction { + DataRange dataRange; + /** * @param datatypeProperty */ - public DatatypeSomeRestriction(DatatypeProperty datatypeProperty) { + public DatatypeSomeRestriction(DatatypeProperty datatypeProperty, DataRange dataRange) { super(datatypeProperty); + this.dataRange = dataRange; } /* (non-Javadoc) @@ -44,7 +47,6 @@ */ @Override public int getArity() { - // TODO Auto-generated method stub return 0; } @@ -52,16 +54,14 @@ * @see org.dllearner.core.owl.KBElement#getLength() */ public int getLength() { - // TODO Auto-generated method stub - return 0; + return 1 + dataRange.getLength(); } /* (non-Javadoc) * @see org.dllearner.core.owl.KBElement#toString(java.lang.String, java.util.Map) */ public String toString(String baseURI, Map<String, String> prefixes) { - // TODO Auto-generated method stub - return null; + return restrictedPropertyExpression.toString(baseURI, prefixes) + dataRange.toString(baseURI, prefixes); } /* (non-Javadoc) @@ -83,5 +83,12 @@ public String toManchesterSyntaxString(String baseURI, Map<String,String> prefixes) { // TODO Auto-generated method stub return null; + } + + /** + * @return the dataRange + */ + public DataRange getDataRange() { + return dataRange; } } Modified: trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java 2008-03-10 17:53:52 UTC (rev 700) @@ -28,7 +28,7 @@ * @author Jens Lehmann * */ -public class DoubleMaxValue implements DoubleDataRange { +public class DoubleMaxValue implements SimpleDoubleDataRange { private double value; @@ -54,8 +54,7 @@ * @see org.dllearner.core.owl.KBElement#toString(java.lang.String, java.util.Map) */ public String toString(String baseURI, Map<String, String> prefixes) { - // TODO Auto-generated method stub - return null; + return " <= " + value; } public void accept(KBElementVisitor visitor) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java 2008-03-10 17:53:52 UTC (rev 700) @@ -22,13 +22,13 @@ import java.util.Map; /** - * Double data range restricted by a maximum value, e.g. + * Double data range restricted by a minimum value, e.g. * hasAge >= 18. * * @author Jens Lehmann * */ -public class DoubleMinValue implements DoubleDataRange { +public class DoubleMinValue implements SimpleDoubleDataRange { private double value; @@ -54,8 +54,7 @@ * @see org.dllearner.core.owl.KBElement#toString(java.lang.String, java.util.Map) */ public String toString(String baseURI, Map<String, String> prefixes) { - // TODO Auto-generated method stub - return null; + return " >= " + value; } public void accept(KBElementVisitor visitor) { Added: trunk/src/dl-learner/org/dllearner/core/owl/SimpleDoubleDataRange.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/SimpleDoubleDataRange.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/core/owl/SimpleDoubleDataRange.java 2008-03-10 17:53:52 UTC (rev 700) @@ -0,0 +1,33 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +package org.dllearner.core.owl; + +/** + * A double data range with a single value used for restrictions, + * e.g. hasAge >= 18 (but not 65 >= hasAge >= 18). + * + * @author Jens Lehmann + * + */ +public interface SimpleDoubleDataRange extends DoubleDataRange { + + public double getValue(); + +} Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-10 17:53:52 UTC (rev 700) @@ -37,9 +37,13 @@ import org.dllearner.core.config.ConfigEntry; import org.dllearner.core.config.InvalidConfigOptionValueException; import org.dllearner.core.owl.BooleanValueRestriction; +import org.dllearner.core.owl.DataRange; import org.dllearner.core.owl.DatatypeProperty; import org.dllearner.core.owl.DatatypePropertyHierarchy; +import org.dllearner.core.owl.DatatypeSomeRestriction; import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.DoubleMaxValue; +import org.dllearner.core.owl.DoubleMinValue; import org.dllearner.core.owl.Individual; import org.dllearner.core.owl.Intersection; import org.dllearner.core.owl.NamedClass; @@ -206,6 +210,9 @@ @Override public boolean instanceCheck(Description description, Individual individual) throws ReasoningMethodUnsupportedException { + +// System.out.println(description + " " + individual); + if (description instanceof NamedClass) { return classInstancesPos.get((NamedClass) description).contains(individual); } else if (description instanceof Negation) { @@ -294,6 +301,28 @@ } else { return bdNeg.get(dp).contains(individual); } + } else if (description instanceof DatatypeSomeRestriction) { + DatatypeSomeRestriction dsr = (DatatypeSomeRestriction) description; + DatatypeProperty dp = (DatatypeProperty) dsr.getRestrictedPropertyExpression(); + DataRange dr = dsr.getDataRange(); + SortedSet<Double> values = dd.get(dp).get(individual); + + // if there is no filler for this individual and property we + // need to return false + if(values == null) + return false; + + if(dr instanceof DoubleMaxValue) { + if(values.first() <= ((DoubleMaxValue)dr).getValue()) + return true; + else + return false; + } else if(dr instanceof DoubleMinValue) { + if(values.last() >= ((DoubleMinValue)dr).getValue()) + return true; + else + return false; + } } throw new ReasoningMethodUnsupportedException("Instance check for description " @@ -325,6 +354,11 @@ return atomicConcepts; } + @Override + public Map<Individual, SortedSet<Double>> getDoubleDatatypeMembers(DatatypeProperty datatypeProperty) throws ReasoningMethodUnsupportedException { + return rc.getDoubleDatatypeMembers(datatypeProperty); + } + /* * (non-Javadoc) * Modified: trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIDescriptionConvertVisitor.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIDescriptionConvertVisitor.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIDescriptionConvertVisitor.java 2008-03-10 17:53:52 UTC (rev 700) @@ -35,6 +35,7 @@ import org.dllearner.core.owl.DatatypeValueRestriction; import org.dllearner.core.owl.Description; import org.dllearner.core.owl.DescriptionVisitor; +import org.dllearner.core.owl.DoubleMinValue; import org.dllearner.core.owl.Intersection; import org.dllearner.core.owl.NamedClass; import org.dllearner.core.owl.Negation; @@ -45,6 +46,7 @@ import org.dllearner.core.owl.ObjectMinCardinalityRestriction; import org.dllearner.core.owl.ObjectSomeRestriction; import org.dllearner.core.owl.ObjectValueRestriction; +import org.dllearner.core.owl.SimpleDoubleDataRange; import org.dllearner.core.owl.Thing; import org.dllearner.core.owl.TypedConstant; import org.dllearner.core.owl.Union; @@ -55,9 +57,13 @@ import org.semanticweb.owl.model.OWLConstant; import org.semanticweb.owl.model.OWLDataFactory; import org.semanticweb.owl.model.OWLDataProperty; +import org.semanticweb.owl.model.OWLDataRange; import org.semanticweb.owl.model.OWLDataType; import org.semanticweb.owl.model.OWLDescription; import org.semanticweb.owl.model.OWLObjectProperty; +import org.semanticweb.owl.model.OWLTypedConstant; +import org.semanticweb.owl.vocab.OWLRestrictedDataRangeFacetVocabulary; +import org.semanticweb.owl.vocab.XSDVocabulary; /** * Converter from DL-Learner descriptions to OWL API descriptions based @@ -212,7 +218,8 @@ public void visit(DatatypeValueRestriction description) { // convert OWL constant to OWL API constant Constant c = description.getValue(); - OWLConstant constant; + OWLConstant constant = convertConstant(c); + /* if(c instanceof TypedConstant) { Datatype dt = ((TypedConstant)c).getDatatype(); OWLDataType odt = convertDatatype(dt); @@ -225,6 +232,7 @@ constant = factory.getOWLUntypedConstant(uc.getLiteral()); } } + */ // get datatype property DatatypeProperty dtp = description.getRestrictedPropertyExpresssion(); @@ -276,8 +284,28 @@ * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.DatatypeSomeRestriction) */ public void visit(DatatypeSomeRestriction description) { - // TODO Auto-generated method stub - throw new Error("OWLAPIDescriptionConverter: not implemented"); + + // TODO: currently works only for double min/max + + DatatypeProperty dp = (DatatypeProperty) description.getRestrictedPropertyExpression(); + // currently only double restrictions implemented + SimpleDoubleDataRange dr = (SimpleDoubleDataRange) description.getDataRange(); + Double value = dr.getValue(); + + OWLDataType doubleDataType = factory.getOWLDataType(XSDVocabulary.DOUBLE.getURI()); + OWLTypedConstant constant = factory.getOWLTypedConstant(value.toString(), doubleDataType); + + OWLRestrictedDataRangeFacetVocabulary facet; + if(dr instanceof DoubleMinValue) + facet = OWLRestrictedDataRangeFacetVocabulary.MIN_INCLUSIVE; + else + facet = OWLRestrictedDataRangeFacetVocabulary.MAX_INCLUSIVE; + + OWLDataRange owlDataRange = factory.getOWLDataRangeRestriction(doubleDataType, facet, constant); + OWLDataProperty odp = factory.getOWLDataProperty(URI.create(dp.getName())); + OWLDescription d = factory.getOWLDataSomeRestriction(odp, owlDataRange); + + stack.push(d); } public OWLDataType convertDatatype(Datatype datatype) { @@ -291,4 +319,20 @@ throw new Error("OWLAPIDescriptionConverter: datatype not implemented"); } + private OWLConstant convertConstant(Constant constant) { + OWLConstant owlConstant; + if(constant instanceof TypedConstant) { + Datatype dt = ((TypedConstant)constant).getDatatype(); + OWLDataType odt = convertDatatype(dt); + owlConstant = factory.getOWLTypedConstant(constant.getLiteral(), odt); + } else { + UntypedConstant uc = (UntypedConstant) constant; + if(uc.hasLang()) { + owlConstant = factory.getOWLUntypedConstant(uc.getLiteral(), uc.getLang()); + } else { + owlConstant = factory.getOWLUntypedConstant(uc.getLiteral()); + } + } + return owlConstant; + } } Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-10 17:53:52 UTC (rev 700) @@ -19,6 +19,7 @@ */ package org.dllearner.refinementoperators; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -29,12 +30,17 @@ import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; +import java.util.Map.Entry; import org.dllearner.algorithms.refinement.RefinementOperator; import org.dllearner.core.ReasoningService; import org.dllearner.core.owl.BooleanValueRestriction; +import org.dllearner.core.owl.DataRange; import org.dllearner.core.owl.DatatypeProperty; +import org.dllearner.core.owl.DatatypeSomeRestriction; import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.DoubleMaxValue; +import org.dllearner.core.owl.DoubleMinValue; import org.dllearner.core.owl.Individual; import org.dllearner.core.owl.Intersection; import org.dllearner.core.owl.NamedClass; @@ -119,7 +125,11 @@ // concept comparator private ConceptComparator conceptComparator = new ConceptComparator(); - // Statistik + // splits for double datatype properties in ascening order + private Map<DatatypeProperty,List<Double>> splits = new TreeMap<DatatypeProperty,List<Double>>(); + private int maxNrOfSplits = 20; + + // staistics public long mComputationTimeNs = 0; public long topComputationTimeNs = 0; @@ -129,6 +139,7 @@ private boolean useExistsConstructor = true; private boolean useNegation = true; private boolean useBooleanDatatypes = true; + private boolean useDoubleDatatypes = true; private boolean disjointChecks = true; private boolean instanceBasedDisjoints = true; @@ -165,38 +176,29 @@ dpDomains.put(dp, rs.getDomain(dp)); } + // compute splits for double datatype properties + for(DatatypeProperty dp : rs.getDoubleDatatypeProperties()) { + computeSplits(dp); + } + /* - NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Compound"); + NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Atom"); ObjectProperty op = new ObjectProperty("http://dl-learner.org/carcinogenesis#hasAtom"); - ObjectAllRestriction oar = new ObjectAllRestriction(op,struc); - String str = "((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS FALSE) OR ALL \"http://dl-learner.org/carcinogenesis#hasAtom\".TOP)"; - Description desc = null; - try { - desc = KBParser.parseConcept(str); - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// System.out.println(oar.getLength()); -// computeTopRefinements(3,struc); -// for(Description d : topARefinements.get(struc).get(1)) { - // bei 3 ist noch alles OK, bei 4 seltsamer Fehler mit Union - Set<Description> ds = refine(struc,10,null,struc); - Set<Description> improper = new HashSet<Description>(); + ObjectSomeRestriction oar = new ObjectSomeRestriction(op,Thing.instance); + + Set<Description> ds = refine(Thing.instance,3,null,struc); +// Set<Description> improper = new HashSet<Description>(); for(Description d : ds) { -// if(d instanceof Union) - if(rs.subsumes(d, struc)) { - improper.add(d); +// if(rs.subsumes(d, struc)) { +// improper.add(d); System.out.println(d); - } +// } } -// System.out.println(refine(Thing.instance,7,null,struc).size()); System.out.println(ds.size()); - System.out.println(improper.size()); +// System.out.println(improper.size()); System.exit(0); */ - - + if(startClass != null) this.startClass = startClass; } @@ -356,6 +358,36 @@ refinements.add(new ObjectAllRestriction(moreSpecialRole, description.getChild(0))); } + } else if (description instanceof DatatypeSomeRestriction) { + DatatypeSomeRestriction dsr = (DatatypeSomeRestriction) description; + DatatypeProperty dp = (DatatypeProperty) dsr.getRestrictedPropertyExpression(); + DataRange dr = dsr.getDataRange(); + if(dr instanceof DoubleMaxValue) { + double value = ((DoubleMaxValue)dr).getValue(); + // find out which split value was used + int splitIndex = splits.get(dp).lastIndexOf(value); + if(splitIndex == -1) + throw new Error("split error"); + int newSplitIndex = splitIndex - 1; + if(newSplitIndex >= 0) { + DoubleMaxValue max = new DoubleMaxValue(splits.get(dp).get(newSplitIndex)); + DatatypeSomeRestriction newDSR = new DatatypeSomeRestriction(dp,max); + refinements.add(newDSR); +// System.out.println(description + " => " + newDSR); + } + } else if(dr instanceof DoubleMinValue) { + double value = ((DoubleMinValue)dr).getValue(); + // find out which split value was used + int splitIndex = splits.get(dp).lastIndexOf(value); + if(splitIndex == -1) + throw new Error("split error"); + int newSplitIndex = splitIndex + 1; + if(newSplitIndex < splits.get(dp).size()) { + DoubleMinValue min = new DoubleMinValue(splits.get(dp).get(newSplitIndex)); + DatatypeSomeRestriction newDSR = new DatatypeSomeRestriction(dp,min); + refinements.add(newDSR); + } + } } // if a refinement is not Bottom, Top, ALL r.Bottom a refinement of top can be appended @@ -606,6 +638,16 @@ } } + if(useDoubleDatatypes) { + Set<DatatypeProperty> doubleDPs = rs.getDoubleDatatypeProperties(); + for(DatatypeProperty dp : doubleDPs) { + DoubleMaxValue max = new DoubleMaxValue(splits.get(dp).get(splits.get(dp).size()-1)); + DoubleMinValue min = new DoubleMinValue(splits.get(dp).get(0)); + m3.add(new DatatypeSomeRestriction(dp,max)); + m3.add(new DatatypeSomeRestriction(dp,min)); + } + } + m.put(3,m3); mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; @@ -677,6 +719,24 @@ } } + if(useDoubleDatatypes) { + Set<DatatypeProperty> doubleDPs = mgdd.get(nc); +// System.out.println("cached disjoints " + cachedDisjoints); +// System.out.println("appOP " + appOP); +// System.out.println("appBD " + appBD); +// System.out.println("appDD " + appDD); +// System.out.println("mgr " + mgr); +// System.out.println("mgbd " + mgbd); +// System.out.println("mgdd " + mgdd); + + for(DatatypeProperty dp : doubleDPs) { + DoubleMaxValue max = new DoubleMaxValue(splits.get(dp).get(splits.get(dp).size()-1)); + DoubleMinValue min = new DoubleMinValue(splits.get(dp).get(0)); + m3.add(new DatatypeSomeRestriction(dp,max)); + m3.add(new DatatypeSomeRestriction(dp,min)); + } + } + mA.get(nc).put(3,m3); mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; @@ -755,10 +815,11 @@ appBD.put(domain, applicableBDPs); // double datatype properties - Set<DatatypeProperty> mostGeneralDDPs = rs.getBooleanDatatypeProperties(); + Set<DatatypeProperty> mostGeneralDDPs = rs.getDoubleDatatypeProperties(); Set<DatatypeProperty> applicableDDPs = new TreeSet<DatatypeProperty>(); for(DatatypeProperty role : mostGeneralDDPs) { Description d = (NamedClass) rs.getDomain(role); +// System.out.println("domain: " + d); if(!isDisjoint(domain,d)) applicableDDPs.add(role); } @@ -788,16 +849,18 @@ } private boolean isDisjoint(Description d1, Description d2) { - // equal concepts are not disjoint (unless equivalent to bottom) -// if(conceptComparator.compare(d1, d2)==0) -// return false; +// System.out.println("| " + d1 + " " + d2); +// System.out.println("| " + cachedDisjoints); + // check whether we have cached this query Map<Description,Boolean> tmp = cachedDisjoints.get(d1); Boolean tmp2 = null; if(tmp != null) tmp2 = tmp.get(d2); +// System.out.println("| " + tmp + " " + tmp2); + if(tmp2==null) { Boolean result; if(instanceBasedDisjoints) { @@ -809,24 +872,33 @@ // add the result to the cache (we add it twice such that // the order of access does not matter) +// System.out.println("| result: " + result); + // create new entries if necessary - Map<Description,Boolean> map = new TreeMap<Description,Boolean>(conceptComparator); + Map<Description,Boolean> map1 = new TreeMap<Description,Boolean>(conceptComparator); + Map<Description,Boolean> map2 = new TreeMap<Description,Boolean>(conceptComparator); if(tmp == null) - cachedDisjoints.put(d1, map); + cachedDisjoints.put(d1, map1); if(!cachedDisjoints.containsKey(d2)) - cachedDisjoints.put(d2, map); + cachedDisjoints.put(d2, map2); // add result symmetrically in the description matrix cachedDisjoints.get(d1).put(d2, result); cachedDisjoints.get(d2).put(d1, result); +// System.out.println("---"); return result; - } else + } else { +// System.out.println("==="); return tmp2; + } } private boolean isDisjointInstanceBased(Description d1, Description d2) { - Set<Individual> d1Instances = rs.retrieval(d1); - Set<Individual> d2Instances = rs.retrieval(d2); + SortedSet<Individual> d1Instances = rs.retrieval(d1); + SortedSet<Individual> d2Instances = rs.retrieval(d2); +// System.out.println(d1 + " " + d2); +// System.out.println(d1 + " " + d1Instances); +// System.out.println(d2 + " " + d2Instances); for(Individual d1Instance : d1Instances) { if(d2Instances.contains(d1Instance)) return false; @@ -870,4 +942,34 @@ return !rs.subsumes(d, b); } + private void computeSplits(DatatypeProperty dp) { + Set<Double> valuesSet = new TreeSet<Double>(); +// Set<Individual> individuals = rs.getIndividuals(); + Map<Individual,SortedSet<Double>> valueMap = rs.getDoubleDatatypeMembers(dp); + // add all values to the set (duplicates will be remove automatically) + for(Entry<Individual,SortedSet<Double>> e : valueMap.entrySet()) + valuesSet.addAll(e.getValue()); + // convert set to a list where values are sorted + List<Double> values = new LinkedList<Double>(valuesSet); + Collections.sort(values); + + int nrOfValues = values.size(); + // create split set + List<Double> splitsDP = new LinkedList<Double>(); + for(int splitNr=0; splitNr < maxNrOfSplits; splitNr++) { + int index; + if(nrOfValues<=maxNrOfSplits) + index = splitNr; + else + index = (int) Math.floor(splitNr * (double)nrOfValues/(maxNrOfSplits+1)); + + double value = 0.5*(values.get(index)+values.get(index+1)); + splitsDP.add(value); + } + splits.put(dp, splitsDP); + +// System.out.println(values); +// System.out.println(splits); +// System.exit(0); + } } \ No newline at end of file Modified: trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java 2008-03-09 19:25:46 UTC (rev 699) +++ trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java 2008-03-10 17:53:52 UTC (rev 700) @@ -4,12 +4,17 @@ import java.util.Set; import org.dllearner.core.owl.BooleanValueRestriction; +import org.dllearner.core.owl.DatatypeProperty; +import org.dllearner.core.owl.DatatypeSomeRestriction; +import org.dllearner.core.owl.DoubleMaxValue; +import org.dllearner.core.owl.DoubleMinValue; import org.dllearner.core.owl.ObjectAllRestriction; import org.dllearner.core.owl.NamedClass; import org.dllearner.core.owl.Nothing; import org.dllearner.core.owl.Description; import org.dllearner.core.owl.ObjectSomeRestriction; import org.dllearner.core.owl.Intersection; +import org.dllearner.core.owl.SimpleDoubleDataRange; import org.dllearner.core.owl.Union; import org.dllearner.core.owl.Negation; import org.dllearner.core.owl.ObjectQuantorRestriction; @@ -94,8 +99,44 @@ return cmp; } else return -1; + } else if(concept1 instanceof DatatypeSomeRestriction) { + if(concept2 instanceof Nothing || concept2 instanceof NamedClass || concept2 instanceof BooleanValueRestriction) { + return 1; + } else if(concept2 instanceof DatatypeSomeRestriction) { + DatatypeSomeRestriction dsr = (DatatypeSomeRestriction) concept1; + DatatypeProperty dp = (DatatypeProperty) dsr.getRestrictedPropertyExpression(); + DatatypeSomeRestriction dsr2 = (DatatypeSomeRestriction) concept2; + DatatypeProperty dp2 = (DatatypeProperty) dsr2.getRestrictedPropertyExpression(); + + // first criterion: name of the properties + int cmp = rc.compare(dp, dp2); + + if(cmp == 0) { + SimpleDoubleDataRange dr = (SimpleDoubleDataRange) dsr.getDataRange(); + SimpleDoubleDataRange dr2 = (SimpleDoubleDataRange) dsr2.getDataRange(); + + // equal classes + if((dr instanceof DoubleMaxValue && dr2 instanceof DoubleMaxValue) + || (dr instanceof DoubleMinValue && dr2 instanceof DoubleMinValue)) { + double val1 = dr.getValue(); + double val2 = dr2.getValue(); + if(val1 > val2) + return 1; + else if(val1 == val2) + return 0; + else + return -1; + + } else if(dr instanceof DoubleMaxValue) + return 1; + else + return -1; + } else + return cmp; + } else + return -1; } else if(concept1 instanceof Thing) { - if(concept2 instanceof Nothing || concept2 instanceof NamedClass || concept2 instanceof BooleanValueRestriction) + if(concept2 instanceof Nothing || concept2 instanceof NamedClass || concept2 instanceof BooleanValueRestriction || concept2 instanceof DatatypeSomeRestriction) return 1; else if(concept2 instanceof Thing) return 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ton...@us...> - 2008-03-12 01:48:15
|
Revision: 702 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=702&view=rev Author: tonytacker Date: 2008-03-11 18:48:07 -0700 (Tue, 11 Mar 2008) Log Message: ----------- We can now start to show a search tree. It was not possible, without some changes. - add abstract class getStartNode() to LearningAlgorithm.java - implement this method in all classes which are using it ATTENTION: I had to change getStartNode() in ROLearner.java, hope it will not produce errors. Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java 2008-03-11 17:55:22 UTC (rev 701) +++ trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java 2008-03-12 01:48:07 UTC (rev 702) @@ -26,6 +26,7 @@ import java.util.List; import java.util.Map; +import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -286,4 +287,8 @@ stop = true; } + @Override + public ExampleBasedNode getStartNode() { + return null; + } } Modified: trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java 2008-03-11 17:55:22 UTC (rev 701) +++ trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java 2008-03-12 01:48:07 UTC (rev 702) @@ -25,6 +25,7 @@ import org.apache.log4j.Logger; import org.dllearner.algorithms.gp.Program; import org.dllearner.algorithms.gp.GPUtilities; +import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -127,5 +128,9 @@ } + @Override + public ExampleBasedNode getStartNode() { + return null; + } } Modified: trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2008-03-11 17:55:22 UTC (rev 701) +++ trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2008-03-12 01:48:07 UTC (rev 702) @@ -30,6 +30,7 @@ import java.util.Map.Entry; import org.dllearner.algorithms.hybridgp.Psi; +import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -1003,4 +1004,9 @@ //public void setAlgorithmType(AlgorithmType algorithmType) { // this.algorithmType = algorithmType; //} + + @Override + public ExampleBasedNode getStartNode() { + return null; + } } Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-03-11 17:55:22 UTC (rev 701) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-03-12 01:48:07 UTC (rev 702) @@ -349,6 +349,7 @@ algorithm.stop(); } + @Override public ExampleBasedNode getStartNode() { return algorithm.getStartNode(); } Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-03-11 17:55:22 UTC (rev 701) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-03-12 01:48:07 UTC (rev 702) @@ -12,6 +12,7 @@ import java.util.TreeSet; import org.apache.log4j.Logger; +import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -1003,8 +1004,12 @@ /** * @return the startNode */ - public Node getStartNode() { + public Node getStartNode_original() { return startNode; } + @Override + public ExampleBasedNode getStartNode() { + return null; + } } Modified: trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java 2008-03-11 17:55:22 UTC (rev 701) +++ trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java 2008-03-12 01:48:07 UTC (rev 702) @@ -23,6 +23,7 @@ import java.util.LinkedList; import java.util.List; +import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.owl.Description; /** @@ -70,4 +71,9 @@ return new LinkedList<Class<? extends LearningProblem>>(); } + /** + * Root for search tree. + * @return + */ + public abstract ExampleBasedNode getStartNode(); } Modified: trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java =================================================================== --- trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java 2008-03-11 17:55:22 UTC (rev 701) +++ trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java 2008-03-12 01:48:07 UTC (rev 702) @@ -22,6 +22,7 @@ import javax.swing.*; import javax.swing.tree.*; +import org.dllearner.algorithms.refexamples.*; /** * TreeWindow @@ -45,21 +46,29 @@ // set icon setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("icon.gif"))); - + // tree - DefaultMutableTreeNode root = new DefaultMutableTreeNode( "root" ); - for ( int knot = 0; knot < 4; knot++ ) - { - DefaultMutableTreeNode node = new DefaultMutableTreeNode( "knot " + knot ); - root.add( node ); - for ( int leaf = 1; leaf < 4; leaf++ ) - node.add( new DefaultMutableTreeNode("leaf " + (knot*3+leaf )) ); - } - JTree tree = new JTree( root ); - this.add( new JScrollPane( tree ) ); + DefaultMutableTreeNode exampleRoot = new DefaultMutableTreeNode("root"); + for (int knot = 0; knot < 4; knot++) { + DefaultMutableTreeNode node = new DefaultMutableTreeNode("knot " + knot); + exampleRoot.add(node); + for (int leaf = 1; leaf < 4; leaf++) + node.add(new DefaultMutableTreeNode("leaf " + (knot * 3 + leaf))); + } + ExampleBasedNode rootNode = config.getLearningAlgorithm().getStartNode(); + EBNodeTreeModel root = new EBNodeTreeModel(rootNode); + + // show tree + if (root != null) { + JTree tree = new JTree(root); + this.add(new JScrollPane(tree)); + } + else { + JTree tree = new JTree(exampleRoot); + this.add(new JScrollPane(tree)); + } this.setVisible(true); } - - + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ton...@us...> - 2008-03-12 16:22:27
|
Revision: 704 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=704&view=rev Author: tonytacker Date: 2008-03-12 09:22:24 -0700 (Wed, 12 Mar 2008) Log Message: ----------- removed changes Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java 2008-03-12 02:45:28 UTC (rev 703) +++ trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java 2008-03-12 16:22:24 UTC (rev 704) @@ -26,7 +26,6 @@ import java.util.List; import java.util.Map; -import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -287,8 +286,4 @@ stop = true; } - @Override - public ExampleBasedNode getStartNode() { - return null; - } } Modified: trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java 2008-03-12 02:45:28 UTC (rev 703) +++ trunk/src/dl-learner/org/dllearner/algorithms/RandomGuesser.java 2008-03-12 16:22:24 UTC (rev 704) @@ -25,7 +25,6 @@ import org.apache.log4j.Logger; import org.dllearner.algorithms.gp.Program; import org.dllearner.algorithms.gp.GPUtilities; -import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -128,9 +127,4 @@ } - @Override - public ExampleBasedNode getStartNode() { - return null; - } - } Modified: trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2008-03-12 02:45:28 UTC (rev 703) +++ trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2008-03-12 16:22:24 UTC (rev 704) @@ -30,7 +30,6 @@ import java.util.Map.Entry; import org.dllearner.algorithms.hybridgp.Psi; -import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -1005,8 +1004,4 @@ // this.algorithmType = algorithmType; //} - @Override - public ExampleBasedNode getStartNode() { - return null; - } } Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-03-12 02:45:28 UTC (rev 703) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-03-12 16:22:24 UTC (rev 704) @@ -349,7 +349,6 @@ algorithm.stop(); } - @Override public ExampleBasedNode getStartNode() { return algorithm.getStartNode(); } Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-03-12 02:45:28 UTC (rev 703) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-03-12 16:22:24 UTC (rev 704) @@ -12,7 +12,6 @@ import java.util.TreeSet; import org.apache.log4j.Logger; -import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasoningService; @@ -1004,12 +1003,8 @@ /** * @return the startNode */ - public Node getStartNode_original() { + public Node getStartNode() { return startNode; } - @Override - public ExampleBasedNode getStartNode() { - return null; - } } Modified: trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java 2008-03-12 02:45:28 UTC (rev 703) +++ trunk/src/dl-learner/org/dllearner/core/LearningAlgorithm.java 2008-03-12 16:22:24 UTC (rev 704) @@ -23,7 +23,6 @@ import java.util.LinkedList; import java.util.List; -import org.dllearner.algorithms.refexamples.ExampleBasedNode; import org.dllearner.core.owl.Description; /** @@ -70,10 +69,5 @@ public static Collection<Class<? extends LearningProblem>> supportedLearningProblems() { return new LinkedList<Class<? extends LearningProblem>>(); } - - /** - * Root for search tree. - * @return - */ - public abstract ExampleBasedNode getStartNode(); + } Modified: trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java =================================================================== --- trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java 2008-03-12 02:45:28 UTC (rev 703) +++ trunk/src/dl-learner/org/dllearner/gui/TreeWindow.java 2008-03-12 16:22:24 UTC (rev 704) @@ -22,7 +22,6 @@ import javax.swing.*; import javax.swing.tree.*; -import org.dllearner.algorithms.refexamples.*; /** * TreeWindow @@ -59,14 +58,14 @@ // tree model EBNodeTreeModel root = null; if (config.getLearningAlgorithm() != null) { - ExampleBasedNode rootNode = config.getLearningAlgorithm().getStartNode(); - root = new EBNodeTreeModel(rootNode); + //ExampleBasedNode rootNode = config.getLearningAlgorithm().getStartNode(); + //root = new EBNodeTreeModel(rootNode); } // show tree if (root != null) { - JTree tree = new JTree(root); - this.add(new JScrollPane(tree)); + //JTree tree = new JTree(root); + //this.add(new JScrollPane(tree)); } else { JTree tree = new JTree(exampleRoot); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-13 06:55:17
|
Revision: 707 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=707&view=rev Author: jenslehmann Date: 2008-03-12 23:55:13 -0700 (Wed, 12 Mar 2008) Log Message: ----------- - wrote script for training on one and testing on another conf file - small algorithm improvements Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/utilities/TestValidation.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-12 23:15:31 UTC (rev 706) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-13 06:55:13 UTC (rev 707) @@ -267,7 +267,7 @@ long lastReductionTime = System.nanoTime(); // try a traversal after 100 seconds long traversalInterval = 1000l * 1000000000l; - long reductionInterval = 100l * 1000000000l; + long reductionInterval = 300l * 1000000000l; long currentTime; while(!solutionFound && !stop) { Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-12 23:15:31 UTC (rev 706) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-13 06:55:13 UTC (rev 707) @@ -21,7 +21,8 @@ import java.util.List; -import org.dllearner.core.owl.DatatypeValueRestriction; +import org.dllearner.core.owl.BooleanValueRestriction; +import org.dllearner.core.owl.DatatypeSomeRestriction; import org.dllearner.core.owl.Description; import org.dllearner.core.owl.Thing; import org.dllearner.utilities.ConceptComparator; @@ -78,7 +79,7 @@ private double expansionPenaltyFactor; private double gainBonusFactor; private double nodeChildPenalty = 0.0001; - private double startNodeBonus = 0.8; + private double startNodeBonus = 1.0; // examples private int nrOfNegativeExamples; @@ -144,11 +145,16 @@ // do not count TOP symbols (in particular in ALL r.TOP and EXISTS r.TOP) // as they provide no extra information if(description instanceof Thing) - bonus = 1; + bonus = 2; + if(description instanceof BooleanValueRestriction) + bonus = -1; + // some bonus for doubles because they are already penalised by length 3 - if(description instanceof DatatypeValueRestriction) - bonus = 1; + if(description instanceof DatatypeSomeRestriction) { +// System.out.println(description); + bonus = 3; + } List<Description> children = description.getChildren(); for(Description child : children) { Modified: trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java 2008-03-12 23:15:31 UTC (rev 706) +++ trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java 2008-03-13 06:55:13 UTC (rev 707) @@ -112,6 +112,16 @@ // list of all "hasProperty" test private static Set<String> tests = new TreeSet<String>(); + // we ignore the ames test since its distribution in PTE-2 is so + // different from the training substances that a different testing + // strategy was probably in use + private static boolean ignoreAmes = false; + private static boolean ignoreSalmonella = false;; + private static boolean ignoreCytogenCa = false; + // if true we learn carcinogenic, if false we learn non-carcinogenic + private static boolean learnCarcinogenic = true; + private static boolean useNewGroups = true; + /** * @param args * No arguments supported. @@ -168,8 +178,10 @@ // define properties including domain and range String kbString = "DPDOMAIN(" + getURI2("charge") + ") = " + getURI2("Atom") + ".\n"; kbString += "DPRANGE(" + getURI2("charge") + ") = DOUBLE.\n"; - kbString += "DPDOMAIN(" + getURI2("amesTestPositive") + ") = " + getURI2("Compound") + ".\n"; - kbString += "DPRANGE(" + getURI2("amesTestPositive") + ") = BOOLEAN.\n"; + if(!ignoreAmes) { + kbString += "DPDOMAIN(" + getURI2("amesTestPositive") + ") = " + getURI2("Compound") + ".\n"; + kbString += "DPRANGE(" + getURI2("amesTestPositive") + ") = BOOLEAN.\n"; + } kbString += "OPDOMAIN(" + getURI2("hasAtom") + ") = " + getURI2("Compound") + ".\n"; kbString += "OPRANGE(" + getURI2("hasAtom") + ") = " + getURI2("Atom") + ".\n"; kbString += "OPDOMAIN(" + getURI2("hasBond") + ") = " + getURI2("Compound") + ".\n"; @@ -177,7 +189,10 @@ kbString += "OPDOMAIN(" + getURI2("inBond") + ") = " + getURI2("Bond") + ".\n"; kbString += "OPRANGE(" + getURI2("inBond") + ") = " + getURI2("Atom") + ".\n"; kbString += "OPDOMAIN(" + getURI2("hasStructure") + ") = " + getURI2("Compound") + ".\n"; - kbString += "OPRANGE(" + getURI2("hasStructure") + ") = " + getURI2("Structure") + ".\n"; + kbString += "OPRANGE(" + getURI2("hasStructure") + ") = " + getURI2("Structure") + ".\n"; + kbString += getURI2("Di") + " SUB " + getURI2("Structure") + ".\n"; + kbString += getURI2("Halide") + " SUB " + getURI2("Structure") + ".\n"; + kbString += getURI2("Ring") + " SUB " + getURI2("Structure") + ".\n"; KB kb2 = KBParser.parseKBFile(kbString); kb.addKB(kb2); @@ -195,7 +210,7 @@ // are in ames.pl [the rest is negative in Prolog by CWA], so // we add negative test results here) for(String compound : compounds) { - if(!compoundsAmes.contains(compound)) { + if(!ignoreAmes && !compoundsAmes.contains(compound)) { BooleanDatatypePropertyAssertion ames = getBooleanDatatypePropertyAssertion(compound, "amesTestPositive", false); kb.addAxiom(ames); } @@ -255,15 +270,19 @@ // generating test examples for PTE-1 // => put all in one file, because they were used as training for PTE-2 - // File confPTE1File = new File("examples/carcinogenesis/testpte1.conf"); - // Files.clearFile(confPTE1File); + File confPTE1File = new File("examples/carcinogenesis/testpte1.conf"); + Files.clearFile(confPTE1File); File testPTE1Positives = new File(prologDirectory + "pte1.f"); File testPTE1Negatives = new File(prologDirectory + "pte1.n"); List<Individual> posPTE1Examples = getExamples(testPTE1Positives); List<Individual> negPTE1Examples = getExamples(testPTE1Negatives); appendPosExamples(confTrainFile, posPTE1Examples); - appendNegExamples(confTrainFile, negPTE1Examples); + appendNegExamples(confTrainFile, negPTE1Examples); + Files.clearFile(confPTE1File); + Files.appendFile(confPTE1File, "import(\"pte.owl\");\nreasoner=fastInstanceChecker;\n\n"); + appendPosExamples(confPTE1File, posPTE1Examples); + appendNegExamples(confPTE1File, negPTE1Examples); // create a PTE-2 test file File confPTE2File = new File("examples/carcinogenesis/testpte2.conf"); @@ -288,10 +307,12 @@ // remaining stuff or use closed world assumption in the // TBox dematerialisation later on if(headName.equals("ames")) { + if(!ignoreAmes) { String compoundName = head.getArgument(0).toPLString(); BooleanDatatypePropertyAssertion ames = getBooleanDatatypePropertyAssertion(compoundName, "amesTestPositive", true); axioms.add(ames); compoundsAmes.add(compoundName); + } } else if (headName.equals("atm")) { String compoundName = head.getArgument(0).toPLString(); String atomName = head.getArgument(1).toPLString(); @@ -350,48 +371,67 @@ } else if (headName.equals("has_property")) { String compoundName = head.getArgument(0).toPLString(); String testName = head.getArgument(1).toPLString(); - String resultStr = head.getArgument(2).toPLString(); - boolean testResult = (resultStr.equals("p")) ? true : false; - - // create a new datatype property if it does not exist already - if(!tests.contains(testName)) { - String axiom1 = "DPDOMAIN(" + getURI2(testName) + ") = " + getURI2("Compound") + ".\n"; - String axiom2 = "DPRANGE(" + getURI2(testName) + ") = BOOLEAN.\n"; - KB kb = KBParser.parseKBFile(axiom1 + axiom2); - axioms.addAll(kb.getAxioms()); + if(!(ignoreSalmonella && testName.equals("salmonella")) + && !(ignoreCytogenCa && testName.equals("cytogen_ca"))) { + String resultStr = head.getArgument(2).toPLString(); + boolean testResult = (resultStr.equals("p")) ? true : false; + + // create a new datatype property if it does not exist already + if(!tests.contains(testName)) { + String axiom1 = "DPDOMAIN(" + getURI2(testName) + ") = " + getURI2("Compound") + ".\n"; + String axiom2 = "DPRANGE(" + getURI2(testName) + ") = BOOLEAN.\n"; + KB kb = KBParser.parseKBFile(axiom1 + axiom2); + axioms.addAll(kb.getAxioms()); + } + // create an axiom with the test result + DatatypePropertyAssertion dpa = getBooleanDatatypePropertyAssertion(compoundName, testName, + testResult); + axioms.add(dpa); } - // create an axiom with the test result - DatatypePropertyAssertion dpa = getBooleanDatatypePropertyAssertion(compoundName, testName, - testResult); - axioms.add(dpa); // either parse this or ashby_alert - not both - ashby_alert contains // all information in ind already } else if (headName.equals("ind") || headName.equals("ring_no")) { + // parse this only if the new groups are not parsed +// if(!useNewGroups) { String compoundName = head.getArgument(0).toPLString(); String structureName = head.getArgument(1).toPLString(); - int count = Integer.parseInt(head.getArgument(2).toPLString()); +// int count = Integer.parseInt(head.getArgument(2).toPLString()); // upper case first letter String structureClass = structureName.substring(0,1).toUpperCase() + structureName.substring(1);; String structureInstance = structureName + "-" + structureNr; - if (!bondTypes.contains(structureClass)) { - NamedClass subClass = getAtomicConcept(structureClass); - SubClassAxiom sc = new SubClassAxiom(subClass, getAtomicConcept("Structure")); - axioms.add(sc); - structureTypes.add(structureClass); - } + addStructureSubclass(axioms, structureClass); - for(int i=0; i<count; i++) { +// for(int i=0; i<count; i++) { ObjectPropertyAssertion op = getRoleAssertion("hasStructure", compoundName, structureInstance); axioms.add(op); // make e.g. halide10-382 instance of Bond-3 ClassAssertionAxiom ca = getConceptAssertion(structureClass, structureInstance); axioms.add(ca); structureNr++; - } +// } +// } } else if (headName.equals("ashby_alert")) { // ... currently ignored ... } else if (newGroups.contains(headName)) { + if(useNewGroups) { + String compoundName = head.getArgument(0).toPLString(); + String structureName = headName; +// int count = Integer.parseInt(head.getArgument(2).toPLString()); + // upper case first letter + String structureClass = structureName.substring(0,1).toUpperCase() + structureName.substring(1);; + String structureInstance = structureName + "-" + structureNr; + + addStructureSubclass(axioms, structureClass); + +// for(int i=0; i<count; i++) { + ObjectPropertyAssertion op = getRoleAssertion("hasStructure", compoundName, structureInstance); + axioms.add(op); + ClassAssertionAxiom ca = getConceptAssertion(structureClass, structureInstance); + axioms.add(ca); + structureNr++; +// } + } } else { // print clauses which are not supported yet System.out.println("unsupported clause"); @@ -402,6 +442,23 @@ return axioms; } + private static void addStructureSubclass(List<Axiom> axioms, String structureClass) { + // build in more fine-grained subclasses e.g. Di+number is subclass of Di + if (!structureTypes.contains(structureClass)) { + NamedClass nc = getAtomicConcept("Structure"); + if(structureClass.contains("Di")) + nc = getAtomicConcept("Di"); + else if(structureClass.contains("ring") || structureClass.contains("Ring")) + nc = getAtomicConcept("Ring"); + else if(structureClass.contains("halide") || structureClass.contains("Halide")) + nc = getAtomicConcept("Halide"); + NamedClass subClass = getAtomicConcept(structureClass); + SubClassAxiom sc = new SubClassAxiom(subClass, nc); + axioms.add(sc); + structureTypes.add(structureClass); + } + } + // takes a *.f or *.n file as input and returns the // contained examples private static List<Individual> getExamples(File file) throws FileNotFoundException, IOException, ParseException { @@ -419,7 +476,10 @@ private static void appendPosExamples(File file, List<Individual> examples) { StringBuffer content = new StringBuffer(); for(Individual example : examples) { - content.append("+\""+example.toString()+"\"\n"); + if(learnCarcinogenic) + content.append("+\""+example.toString()+"\"\n"); + else + content.append("-\""+example.toString()+"\"\n"); } Files.appendFile(file, content.toString()); } @@ -427,7 +487,10 @@ private static void appendNegExamples(File file, List<Individual> examples) { StringBuffer content = new StringBuffer(); for(Individual example : examples) { - content.append("-\""+example.toString()+"\"\n"); + if(learnCarcinogenic) + content.append("-\""+example.toString()+"\"\n"); + else + content.append("+\""+example.toString()+"\"\n"); } Files.appendFile(file, content.toString()); } @@ -582,6 +645,7 @@ * <p>Positives (19): <br /> * <ul> * <li>t3 (SE+3NE): http://ntp.niehs.nih.gov/index.cfm?objectid=BCACAFD4-123F-7908-7B521E4F665EFBD9</li> + * <li>t4 (3CE+NE) - contradicts IJCAI-97 paper and should probably be case 75-52-5 instead of 75-52-8: http://ntp.niehs.nih.gov/index.cfm?objectid=BCE49084-123F-7908-7BE127F7AF1FFBB5</li> * <li>t5: paper</li> * <li>t7: paper</li> * <li>t8: paper</li> @@ -607,7 +671,7 @@ * <ul> * <li>t1 (4NE): http://ntp.niehs.nih.gov/index.cfm?objectid=BD9FF53C-123F-7908-7B123DAE0A25B122 </li> * <li>t2 (4NE): http://ntp.niehs.nih.gov/index.cfm?objectid=BCF8651E-123F-7908-7B21DD5ED83CD0FF </li> - * <li>t4: paper</li> + * <li><strike>t4: paper</strike></li> * <li>t6: paper</li> * <li>t11: paper</li> * <li>t13 (4NE): http://ntp.niehs.nih.gov/index.cfm?objectid=BD136ED6-123F-7908-7B619EE79F2FD062</li> @@ -623,21 +687,47 @@ * <li>t29: probably a negative (see http://ntp.niehs.nih.gov/index.cfm?objectid=BD855EA1-123F-7908-7B573FC3C08188DC) but * no tests directly for this substance</li> * </ul> + * + * <p>The following examples are probably not part of the IJCAI PTE-2 challenge + * (reports younger than 1998): + * <ul> + * <li>pos: t21 (5/99), t25 (9/04), t30(10/01)</li> + * <li>neg: t26 (5/99), t27 (05/01), t28 (05/00), t29 (09/02)</li> + * </ul> * </p> + * </p> * @return A string for all examples as used in the conf file. */ public static String getPTE2Examples() { - String[] pos = new String[] {"t3","t5","t7","t8","t9","t10","t12", - "t14","t15","t16","t18","t19","t20","t21","t22","t23","t24", - "t25","t30"}; - String[] neg = new String[] {"t1", "t2", "t4", "t6", "t11", "t13", - "t17","t26","t27","t28"}; + String[] pos = new String[] {"t3","t4","t5","t7","t8", + "t9", + "t10","t12", + "t14","t15","t16","t18","t19","t20", + "t21", + "t22", + "t23", + "t24", + "t25", + "t30"}; + String[] neg = new String[] {"t1", "t2", + "t6", "t11", "t13", + "t17","t26","t27", + "t28","t29" + }; String ret = ""; - for(String posEx : pos) - ret += "+" + getURI2(posEx) + "\n"; - for(String negEx : neg) - ret += "-" + getURI2(negEx) + "\n"; + for(String posEx : pos) { + if(learnCarcinogenic) + ret += "+" + getURI2(posEx) + "\n"; + else + ret += "-" + getURI2(posEx) + "\n"; + } + for(String negEx : neg) { + if(learnCarcinogenic) + ret += "-" + getURI2(negEx) + "\n"; + else + ret += "+" + getURI2(negEx) + "\n"; + } return ret; } Modified: trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java 2008-03-12 23:15:31 UTC (rev 706) +++ trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java 2008-03-13 06:55:13 UTC (rev 707) @@ -54,9 +54,9 @@ String str = ""; str += "score: " + score + "\n"; str += "accuracy: " + (1 + classificationScore) + "\n"; - str += "posAsPos: " + posAsPos + "\n"; - str += "positive examples classified as negative: " + posAsNeg + "\n"; - str += "negative examples classified as positive: " + negAsPos + "\n"; + str += "posAsPos (" + posAsPos.size() + "): " + posAsPos + "\n"; + str += "positive examples classified as negative (" + posAsNeg.size() + "): " + posAsNeg + "\n"; + str += "negative examples classified as positive (" + negAsPos.size() + "): " + negAsPos + "\n"; return str; } Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-12 23:15:31 UTC (rev 706) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-13 06:55:13 UTC (rev 707) @@ -286,7 +286,9 @@ ConceptTransformation.cleanConceptNonRecursive(mc); ConceptTransformation.transformToOrderedNegationNormalFormNonRecursive(mc, conceptComparator); - refinements.add(mc); + // check whether the intersection is OK (sanity checks), then add it + if(checkIntersection(mc)) + refinements.add(mc); } } @@ -431,6 +433,17 @@ } } + // check for double datatype properties + if(c instanceof DatatypeSomeRestriction && + description instanceof DatatypeSomeRestriction) { + DataRange dr = ((DatatypeSomeRestriction)c).getDataRange(); + DataRange dr2 = ((DatatypeSomeRestriction)description).getDataRange(); + // it does not make sense to have statements like height >= 1.8 AND height >= 1.7 + if((dr instanceof DoubleMaxValue && dr2 instanceof DoubleMaxValue) + ||(dr instanceof DoubleMinValue && dr2 instanceof DoubleMinValue)) + skip = true; + } + // perform a disjointness check when named classes are added; // this can avoid a lot of superfluous computation in the algorithm e.g. // when A1 looks good, so many refinements of the form (A1 OR (A2 AND A3)) @@ -465,6 +478,33 @@ return refinements; } + // when a child of an intersection is refined and reintegrated into the + // intersection, we can perform some sanity checks; + // method returns true if everything is OK and false otherwise + private boolean checkIntersection(Intersection intersection) { + // rule 1: max. restrictions at most once + boolean maxDoubleOccurence = false; + // rule 2: min restrictions at most once + boolean minDoubleOccurence = false; + for(Description child : intersection.getChildren()) { + if(child instanceof DatatypeSomeRestriction) { + DataRange dr = ((DatatypeSomeRestriction)child).getDataRange(); + if(dr instanceof DoubleMaxValue) { + if(maxDoubleOccurence) + return false; + else + maxDoubleOccurence = true; + } else if(dr instanceof DoubleMinValue) { + if(minDoubleOccurence) + return false; + else + minDoubleOccurence = true; + } + } + } + return true; + } + private void computeTopRefinements(int maxLength) { computeTopRefinements(maxLength, null); } Added: trunk/src/dl-learner/org/dllearner/utilities/TestValidation.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/TestValidation.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/utilities/TestValidation.java 2008-03-13 06:55:13 UTC (rev 707) @@ -0,0 +1,75 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +package org.dllearner.utilities; + +import java.io.File; +import java.util.Set; + +import org.apache.log4j.ConsoleAppender; +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.apache.log4j.SimpleLayout; +import org.dllearner.cli.Start; +import org.dllearner.core.ComponentInitException; +import org.dllearner.core.LearningProblem; +import org.dllearner.core.ReasoningService; +import org.dllearner.core.Score; +import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.Individual; + +/** + * @author Jens Lehmann + * + */ +public class TestValidation { + + private static Logger logger = Logger.getRootLogger(); + + public static void main(String args[]) throws ComponentInitException { + + // create logger (a simple logger which outputs + // its messages to the console) + SimpleLayout layout = new SimpleLayout(); + ConsoleAppender consoleAppender = new ConsoleAppender(layout); + logger.removeAllAppenders(); + logger.addAppender(consoleAppender); + logger.setLevel(Level.DEBUG); + + String filenameTrain = args[0]; + String filenameTest = args[1]; + + Start start = new Start(new File(filenameTrain)); + start.start(false); + Description solution = start.getLearningAlgorithm().getBestSolution(); + + logger.setLevel(Level.WARN); + + Start startTest = new Start(new File(filenameTest)); + ReasoningService rs = startTest.getReasoningService(); + LearningProblem lp = startTest.getLearningProblem(); + + Set<Individual> result = rs.retrieval(solution); + System.out.println("retrieval result: " + result); + + Score score = lp.computeScore(solution); + System.out.println(score); + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-16 19:03:58
|
Revision: 713 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=713&view=rev Author: jenslehmann Date: 2008-03-16 12:03:46 -0700 (Sun, 16 Mar 2008) Log Message: ----------- partial cardinality restriction learning support Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/Info.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java trunk/src/dl-learner/org/dllearner/core/ComponentManager.java trunk/src/dl-learner/org/dllearner/core/ComponentPool.java trunk/src/dl-learner/org/dllearner/core/Reasoner.java trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java trunk/src/dl-learner/org/dllearner/core/ReasoningService.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java trunk/src/dl-learner/org/dllearner/utilities/CrossValidation.java Modified: trunk/src/dl-learner/org/dllearner/Info.java =================================================================== --- trunk/src/dl-learner/org/dllearner/Info.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/Info.java 2008-03-16 19:03:46 UTC (rev 713) @@ -3,6 +3,6 @@ package org.dllearner; public class Info { - public static final String build = "2008-02-18"; + public static final String build = "2008-03-16"; } \ No newline at end of file Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-16 19:03:46 UTC (rev 713) @@ -30,7 +30,6 @@ import java.util.SortedSet; import java.util.TreeSet; -import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.dllearner.algorithms.refinement.RefinementOperator; import org.dllearner.core.LearningProblem; @@ -39,8 +38,8 @@ import org.dllearner.core.owl.Description; import org.dllearner.core.owl.Individual; import org.dllearner.core.owl.Intersection; +import org.dllearner.core.owl.Thing; import org.dllearner.core.owl.Union; -import org.dllearner.core.owl.Thing; import org.dllearner.learningproblems.PosNegLP; import org.dllearner.learningproblems.PosOnlyDefinitionLP; import org.dllearner.refinementoperators.RhoDRDown; @@ -116,7 +115,7 @@ // the divide&conquer approach in many ILP programs using a // clause by clause search; after a period of time the candidate // set is reduced to focus CPU time on the most promising concepts - private boolean useCandidateReduction = true; + private boolean useCandidateReduction = false; private int candidatePostReductionSize = 30; // setting to true gracefully stops the algorithm @@ -214,6 +213,11 @@ posOnly = false; nrOfPositiveExamples = lp.getPositiveExamples().size(); nrOfNegativeExamples = lp.getNegativeExamples().size(); + +// System.out.println(nrOfPositiveExamples); +// System.out.println(nrOfNegativeExamples); +// System.exit(0); + } else if(learningProblem instanceof PosOnlyDefinitionLP) { PosOnlyDefinitionLP lp = (PosOnlyDefinitionLP) learningProblem; this.posOnlyLearningProblem = lp; @@ -236,10 +240,40 @@ this.useShortConceptConstruction = useShortConceptConstruction; baseURI = rs.getBaseURI(); - logger.setLevel(Level.DEBUG); +// logger.setLevel(Level.DEBUG); } public void start() { + /* +// String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND (>= 2 \"http://dl-learner.org/carcinogenesis#hasStructure\".\"http://dl-learner.org/carcinogenesis#Ar_halide\" OR ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND >= 5 \"http://dl-learner.org/carcinogenesis#hasBond\". TOP)))"; + String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND (\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE)))"; + try { + NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Compound"); + Description d = KBParser.parseConcept(conceptStr); +// SortedSet<Description> ds = (SortedSet<Description>) operator.refine(d,15,null,struc); +// System.out.println(ds); + + System.out.println(RhoDRDown.checkIntersection((Intersection)d)); + + + Set<Individual> coveredNegatives = rs.instanceCheck(d, learningProblem.getNegativeExamples()); + Set<Individual> coveredPositives = rs.instanceCheck(d, learningProblem.getPositiveExamples()); + ExampleBasedNode ebn = new ExampleBasedNode(d); + ebn.setCoveredExamples(coveredPositives, coveredNegatives); + extendNodeProper(ebn,15); + + // Individual i = new Individual("http://dl-learner.org/carcinogenesis#d101"); +// for(Individual i : learningProblem.getPositiveExamples()) +// rs.instanceCheck(ds.last(), i); + + System.out.println("finished"); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.exit(0); + */ + // calculate quality threshold required for a solution allowedMisclassifications = (int) Math.round(noise * nrOfExamples); @@ -290,8 +324,10 @@ if(useCandidateReduction && (currentTime - lastReductionTime > reductionInterval)) { reduceCandidates(); lastReductionTime = System.nanoTime(); +// Logger.getRootLogger().setLevel(Level.TRACE); } + System.out.println("next expanded: " + candidates.last().getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); // chose best node according to heuristics bestNode = candidates.last(); // extend best node @@ -304,7 +340,8 @@ // newCandidates has been filled during node expansion candidates.addAll(newCandidates); candidatesStable.addAll(newCandidates); - +// System.out.println("done"); + if(writeSearchTree) { // String treeString = ""; String treeString = "best node: " + bestNode+ "\n"; @@ -338,13 +375,13 @@ logger.info(" " + c + " (length " + c.getLength() +", depth " + c.getDepth() + ")"); } } - System.out.println("size of candidate set: " + candidates.size()); + logger.debug("size of candidate set: " + candidates.size()); printStatistics(true); if(stop) - System.out.println("Algorithm stopped."); + logger.info("Algorithm stopped."); else - System.out.println("Algorithm terminated succesfully."); + logger.info("Algorithm terminated succesfully."); } // we apply the operator recursively until all proper refinements up @@ -397,14 +434,18 @@ childConceptsDeletionTimeNs += System.nanoTime() - childConceptsDeletionTimeNsStart; +// if(refinements.size()<30) +// System.out.println("refinements: " + refinements); + long evaluateSetCreationTimeNsStart = System.nanoTime(); // alle Konzepte, die länger als horizontal expansion sind, müssen ausgewertet // werden - Set<Description> toEvaluateConcepts = new TreeSet<Description>(conceptComparator); + TreeSet<Description> toEvaluateConcepts = new TreeSet<Description>(conceptComparator); Iterator<Description> it = refinements.iterator(); // for(Concept refinement : refinements) { - while(it.hasNext()) { + while(it.hasNext()) { + Description refinement = it.next(); if(refinement.getLength()>node.getHorizontalExpansion()) { // sagt aus, ob festgestellt wurde, ob refinement proper ist @@ -413,7 +454,6 @@ // 1. short concept construction if(useShortConceptConstruction) { - // kurzes Konzept konstruieren Description shortConcept = ConceptTransformation.getShortConcept(refinement, conceptComparator); int n = conceptComparator.compare(shortConcept, concept); @@ -422,11 +462,14 @@ if(n==0) { propernessTestsAvoidedByShortConceptConstruction++; propernessDetected = true; + + System.out.println("refinement " + refinement + " can be shortened"); +// System.exit(0); } } // 2. too weak test - if(!propernessDetected && useTooWeakList) { + if(!propernessDetected && useTooWeakList) { if(refinement instanceof Intersection) { boolean tooWeakElement = containsTooWeakElement((Intersection)refinement); if(tooWeakElement) { @@ -454,14 +497,28 @@ } // properness konnte nicht vorher ermittelt werden - if(!propernessDetected) + if(!propernessDetected) { toEvaluateConcepts.add(refinement); +// if(!res) { +// System.out.println("already in: " + refinement); +// Comparator comp = toEvaluateConcepts.comparator(); +// for(Description d : toEvaluateConcepts) { +// if(comp.compare(d,refinement)==0) +// System.out.println("see: " + d); +// } +// } + } } + +// System.out.println("handled " + refinement + " length: " + refinement.getLength() + " (new size: " + toEvaluateConcepts.size() + ")"); + } evaluateSetCreationTimeNs += System.nanoTime() - evaluateSetCreationTimeNsStart; +// System.out.println("intermediate 1"); + // System.out.println(toEvaluateConcepts.size()); Set<Description> improperConcepts = null; @@ -476,6 +533,11 @@ } } +// if(toEvaluateConcepts.size()<10) +// System.out.println("to evaluate: " + toEvaluateConcepts); +// else +// System.out.println("to evaluate: more than 10"); + long improperConceptsRemovalTimeNsStart = System.nanoTime(); // die improper Konzepte werden von den auszuwertenden gelöscht, d.h. // alle proper concepts bleiben übrig (einfache Umbenennung) @@ -486,6 +548,13 @@ refinements.removeAll(properConcepts); improperConceptsRemovalTimeNs += System.nanoTime() - improperConceptsRemovalTimeNsStart; +// if(refinements.size()<10) +// System.out.println("refinements: " + refinements); +// else +// System.out.println("refinements: more than 10"); +// +// System.out.println("improper concepts: " + improperConcepts); + for(Description refinement : properConcepts) { long redundancyCheckTimeNsStart = System.nanoTime(); boolean nonRedundant = properRefinements.add(refinement); @@ -603,18 +672,18 @@ } } - // es sind jetzt noch alle Konzepte übrig, die improper refinements sind // auf jedem dieser Konzepte wird die Funktion erneut aufgerufen, da sich // proper refinements ergeben könnten for(Description refinement : refinements) { // for(int i=0; i<=recDepth; i++) // System.out.print(" "); - // System.out.println("call: " + refinement + " [maxLength " + maxLength + "]"); +// System.out.println("call: " + refinement + " [maxLength " + maxLength + "]"); extendNodeProper(node, refinement, maxLength, recDepth+1); // for(int i=0; i<=recDepth; i++) // System.out.print(" "); - // System.out.println("finished: " + refinement + " [maxLength " + maxLength + "]"); + // System.out.println("finished: " + refinement + " [maxLength " + maxLength + "]"); +// System.exit(0); } } @@ -637,26 +706,25 @@ // + nrOfNegativeExamples - bestNode.getCoveredNegatives().size())/(double)nrOfExamples); // Refinementoperator auf Konzept anwenden // String bestNodeString = "currently best node: " + bestNode + " accuracy: " + df.format(accuracy) + "%"; - System.out.println("start node: " + startNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); + logger.debug("start node: " + startNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); String bestNodeString = "currently best node: " + bestNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI); // searchTree += bestNodeString + "\n"; - System.out.println(bestNodeString); + logger.debug(bestNodeString); String expandedNodeString = "next expanded node: " + candidates.last().getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI); // searchTree += expandedNodeString + "\n"; - System.out.println(expandedNodeString); - System.out.println("algorithm runtime " + Helper.prettyPrintNanoSeconds(algorithmRuntime)); - System.out.println("size of candidate set: " + candidates.size()); + logger.debug(expandedNodeString); + logger.debug("algorithm runtime " + Helper.prettyPrintNanoSeconds(algorithmRuntime)); + logger.debug("size of candidate set: " + candidates.size()); // System.out.println("properness max recursion depth: " + maxRecDepth); // System.out.println("max. number of one-step refinements: " + maxNrOfRefinements); // System.out.println("max. number of children of a node: " + maxNrOfChildren); - System.out.println("subsumption time: " + Helper.prettyPrintNanoSeconds(rs.getSubsumptionReasoningTimeNs())); - System.out.println("instance check time: " + Helper.prettyPrintNanoSeconds(rs.getInstanceCheckReasoningTimeNs())); - System.out.println("retrieval time: " + Helper.prettyPrintNanoSeconds(rs.getRetrievalReasoningTimeNs())); + logger.debug("subsumption time: " + Helper.prettyPrintNanoSeconds(rs.getSubsumptionReasoningTimeNs())); + logger.debug("instance check time: " + Helper.prettyPrintNanoSeconds(rs.getInstanceCheckReasoningTimeNs())); + logger.debug("retrieval time: " + Helper.prettyPrintNanoSeconds(rs.getRetrievalReasoningTimeNs())); } if(computeBenchmarkInformation) { - long reasoningTime = rs.getOverallReasoningTimeNs(); double reasoningPercentage = 100 * reasoningTime/(double)algorithmRuntime; long propWithoutReasoning = propernessCalcTimeNs-propernessCalcReasoningTimeNs; @@ -674,24 +742,24 @@ double onnfTimePercentage = 100 * ConceptTransformation.onnfTimeNs/(double)algorithmRuntime; double shorteningTimePercentage = 100 * ConceptTransformation.shorteningTimeNs/(double)algorithmRuntime; - System.out.println("reasoning percentage: " + df.format(reasoningPercentage) + "%"); - System.out.println(" subsumption check time: " + df.format(subPercentage) + "%"); - System.out.println("proper calculation percentage (wo. reasoning): " + df.format(propPercentage) + "%"); - System.out.println(" deletion time percentage: " + df.format(deletionPercentage) + "%"); - System.out.println(" refinement calculation percentage: " + df.format(refinementPercentage) + "%"); - System.out.println(" m calculation percentage: " + df.format(mComputationTimePercentage) + "%"); - System.out.println(" top calculation percentage: " + df.format(topComputationTimePercentage) + "%"); - System.out.println(" redundancy check percentage: " + df.format(redundancyCheckPercentage) + "%"); - System.out.println(" evaluate set creation time percentage: " + df.format(evaluateSetCreationTimePercentage) + "%"); - System.out.println(" improper concepts removal time percentage: " + df.format(improperConceptsRemovalTimePercentage) + "%"); - System.out.println("clean time percentage: " + df.format(cleanTimePercentage) + "%"); - System.out.println("onnf time percentage: " + df.format(onnfTimePercentage) + "%"); - System.out.println("shortening time percentage: " + df.format(shorteningTimePercentage) + "%"); + logger.debug("reasoning percentage: " + df.format(reasoningPercentage) + "%"); + logger.debug(" subsumption check time: " + df.format(subPercentage) + "%"); + logger.debug("proper calculation percentage (wo. reasoning): " + df.format(propPercentage) + "%"); + logger.debug(" deletion time percentage: " + df.format(deletionPercentage) + "%"); + logger.debug(" refinement calculation percentage: " + df.format(refinementPercentage) + "%"); + logger.debug(" m calculation percentage: " + df.format(mComputationTimePercentage) + "%"); + logger.debug(" top calculation percentage: " + df.format(topComputationTimePercentage) + "%"); + logger.debug(" redundancy check percentage: " + df.format(redundancyCheckPercentage) + "%"); + logger.debug(" evaluate set creation time percentage: " + df.format(evaluateSetCreationTimePercentage) + "%"); + logger.debug(" improper concepts removal time percentage: " + df.format(improperConceptsRemovalTimePercentage) + "%"); + logger.debug("clean time percentage: " + df.format(cleanTimePercentage) + "%"); + logger.debug("onnf time percentage: " + df.format(onnfTimePercentage) + "%"); + logger.debug("shortening time percentage: " + df.format(shorteningTimePercentage) + "%"); } - System.out.println("properness tests (reasoner/short concept/too weak list): " + propernessTestsReasoner + "/" + propernessTestsAvoidedByShortConceptConstruction + logger.debug("properness tests (reasoner/short concept/too weak list): " + propernessTestsReasoner + "/" + propernessTestsAvoidedByShortConceptConstruction + "/" + propernessTestsAvoidedByTooWeakList); - System.out.println("concept tests (reasoner/too weak list/overly general list/redundant concepts): " + conceptTestsReasoner + "/" + logger.debug("concept tests (reasoner/too weak list/overly general list/redundant concepts): " + conceptTestsReasoner + "/" + conceptTestsTooWeakList + "/" + conceptTestsOverlyGeneralList + "/" + redundantConcepts); } @@ -737,8 +805,8 @@ Set<Individual> currentCoveredNeg = startNode.getCoveredNegatives(); double currentAccuracy = startNode.getAccuracy(nrOfPositiveExamples, nrOfNegativeExamples); int currentMisclassifications = nrOfPositiveExamples - currentCoveredPos.size() + currentCoveredNeg.size(); - System.out.println("tree traversal start node " + startNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); - System.out.println("tree traversal start accuracy: " + currentAccuracy); + logger.debug("tree traversal start node " + startNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); + logger.debug("tree traversal start accuracy: " + currentAccuracy); int i=0; // start from the most promising nodes NavigableSet<ExampleBasedNode> reverseView = candidatesStable.descendingSet(); @@ -775,9 +843,9 @@ ConceptTransformation.transformToOrderedNegationNormalFormNonRecursive(mc, conceptComparator); // System.out.println("extended concept to: " + mc); - System.out.println("misclassifications: " + misclassifications); - System.out.println("misclassified positives: " + misclassifiedPositives); - System.out.println("accuracy: " + accuracy); + logger.debug("misclassifications: " + misclassifications); + logger.debug("misclassified positives: " + misclassifiedPositives); + logger.debug("accuracy: " + accuracy); // update variables currentDescription = mc; @@ -787,8 +855,8 @@ currentAccuracy = accuracy; if(accuracy > 1 - noise) { - System.out.println("traversal found " + mc); - System.out.println("accuracy: " + accuracy); + logger.info("traversal found " + mc); + logger.info("accuracy: " + accuracy); System.exit(0); } } @@ -844,9 +912,9 @@ i++; } candidates.retainAll(promisingNodes); - System.out.println("searched " + i + " nodes and picked the following promising descriptions:"); + logger.debug("searched " + i + " nodes and picked the following promising descriptions:"); for(ExampleBasedNode node : promisingNodes) - System.out.println(node.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); + logger.debug(node.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); } /* Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-16 19:03:46 UTC (rev 713) @@ -21,7 +21,6 @@ import java.util.List; -import org.dllearner.core.owl.BooleanValueRestriction; import org.dllearner.core.owl.DatatypeSomeRestriction; import org.dllearner.core.owl.Description; import org.dllearner.core.owl.Thing; @@ -145,10 +144,10 @@ // do not count TOP symbols (in particular in ALL r.TOP and EXISTS r.TOP) // as they provide no extra information if(description instanceof Thing) - bonus = 2; + bonus = 1; - if(description instanceof BooleanValueRestriction) - bonus = -1; +// if(description instanceof BooleanValueRestriction) +// bonus = -1; // some bonus for doubles because they are already penalised by length 3 if(description instanceof DatatypeSomeRestriction) { Modified: trunk/src/dl-learner/org/dllearner/core/ComponentManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-03-16 19:03:46 UTC (rev 713) @@ -355,6 +355,10 @@ pool.unregisterComponent(component); } + public void freeAllComponents() { + pool.clearComponents(); + } + public <T> T getConfigOptionValue(Component component, ConfigOption<T> option) { T object = pool.getLastValidConfigValue(component, option); if(object==null) Modified: trunk/src/dl-learner/org/dllearner/core/ComponentPool.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ComponentPool.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/core/ComponentPool.java 2008-03-16 19:03:46 UTC (rev 713) @@ -70,4 +70,11 @@ lastValidConfigValue.get(component).put(entry.getOption(), entry.getValue()); } + // unregisters all components + public void clearComponents() { + components = new LinkedList<Component>(); + lastValidConfigValue = new HashMap<Component,Map<ConfigOption<?>,Object>>(); + configEntryHistory = new HashMap<Component,List<ConfigEntry<?>>>(); + } + } Modified: trunk/src/dl-learner/org/dllearner/core/Reasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/Reasoner.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/core/Reasoner.java 2008-03-16 19:03:46 UTC (rev 713) @@ -128,4 +128,5 @@ public SortedSet<Individual> getIndividuals(); + public void releaseKB(); } Modified: trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/core/ReasonerComponent.java 2008-03-16 19:03:46 UTC (rev 713) @@ -251,4 +251,6 @@ throw new ReasoningMethodUnsupportedException(); } + public abstract void releaseKB(); + } Modified: trunk/src/dl-learner/org/dllearner/core/ReasoningService.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ReasoningService.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/core/ReasoningService.java 2008-03-16 19:03:46 UTC (rev 713) @@ -603,6 +603,10 @@ return reasoner.getPrefixes(); } + public void releaseKB() { + reasoner.releaseKB(); + } + public long getInstanceCheckReasoningTimeNs() { return instanceCheckReasoningTimeNs; } Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectCardinalityRestriction.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectCardinalityRestriction.java 2008-03-16 19:03:46 UTC (rev 713) @@ -13,7 +13,7 @@ } public int getLength() { - return 1 + role.getLength() + getChild(0).getLength(); + return 2 + role.getLength() + getChild(0).getLength(); } public int getNumber() { Modified: trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java 2008-03-16 19:03:46 UTC (rev 713) @@ -118,6 +118,7 @@ private static boolean ignoreAmes = false; private static boolean ignoreSalmonella = false;; private static boolean ignoreCytogenCa = false; + private static boolean includeMutagenesis = true; // if true we learn carcinogenic, if false we learn non-carcinogenic private static boolean learnCarcinogenic = true; private static boolean useNewGroups = true; @@ -134,10 +135,11 @@ // TODO: newgroups are not mapped currently String[] files = new String[] { "newgroups.pl", "ames.pl", "atoms.pl", "bonds.pl", "gentoxprops.pl", - "ind_nos.pl", "ind_pos.pl", "pte2/canc_nos.pl", "pte2/pte2ames.pl", "pte2/pte2atoms.pl", - "pte2/pte2bonds.pl", "pte2/pte2gentox.pl", "pte2/pte2ind_nos.pl", "pte2/pte2newgroups.pl" + "ind_nos.pl", "ind_pos.pl"}; + // "pte2/canc_nos.pl", "pte2/pte2ames.pl", "pte2/pte2atoms.pl", + // "pte2/pte2bonds.pl", "pte2/pte2gentox.pl", "pte2/pte2ind_nos.pl", "pte2/pte2newgroups.pl" // "train.b" => not a pure Prolog file but Progol/Aleph specific - }; + // }; File owlFile = new File("examples/carcinogenesis/pte.owl"); Program program = null; @@ -182,6 +184,10 @@ kbString += "DPDOMAIN(" + getURI2("amesTestPositive") + ") = " + getURI2("Compound") + ".\n"; kbString += "DPRANGE(" + getURI2("amesTestPositive") + ") = BOOLEAN.\n"; } + if(includeMutagenesis) { + kbString += "DPDOMAIN(" + getURI2("isMutagenic") + ") = " + getURI2("Compound") + ".\n"; + kbString += "DPRANGE(" + getURI2("isMutagenic") + ") = BOOLEAN.\n"; + } kbString += "OPDOMAIN(" + getURI2("hasAtom") + ") = " + getURI2("Compound") + ".\n"; kbString += "OPRANGE(" + getURI2("hasAtom") + ") = " + getURI2("Atom") + ".\n"; kbString += "OPDOMAIN(" + getURI2("hasBond") + ") = " + getURI2("Compound") + ".\n"; @@ -205,6 +211,10 @@ for (Axiom axiom : axioms) kb.addAxiom(axiom); } + + if(includeMutagenesis) + addMutagenesis(kb); + // special handling for ames test (we assume the ames test // was performed on all compounds but only the positive ones // are in ames.pl [the rest is negative in Prolog by CWA], so @@ -395,42 +405,39 @@ // if(!useNewGroups) { String compoundName = head.getArgument(0).toPLString(); String structureName = head.getArgument(1).toPLString(); -// int count = Integer.parseInt(head.getArgument(2).toPLString()); + int count = Integer.parseInt(head.getArgument(2).toPLString()); // upper case first letter String structureClass = structureName.substring(0,1).toUpperCase() + structureName.substring(1);; String structureInstance = structureName + "-" + structureNr; addStructureSubclass(axioms, structureClass); -// for(int i=0; i<count; i++) { + for(int i=0; i<count; i++) { ObjectPropertyAssertion op = getRoleAssertion("hasStructure", compoundName, structureInstance); axioms.add(op); // make e.g. halide10-382 instance of Bond-3 ClassAssertionAxiom ca = getConceptAssertion(structureClass, structureInstance); axioms.add(ca); structureNr++; + } // } -// } } else if (headName.equals("ashby_alert")) { // ... currently ignored ... } else if (newGroups.contains(headName)) { if(useNewGroups) { String compoundName = head.getArgument(0).toPLString(); String structureName = headName; -// int count = Integer.parseInt(head.getArgument(2).toPLString()); // upper case first letter String structureClass = structureName.substring(0,1).toUpperCase() + structureName.substring(1);; String structureInstance = structureName + "-" + structureNr; addStructureSubclass(axioms, structureClass); -// for(int i=0; i<count; i++) { ObjectPropertyAssertion op = getRoleAssertion("hasStructure", compoundName, structureInstance); axioms.add(op); ClassAssertionAxiom ca = getConceptAssertion(structureClass, structureInstance); axioms.add(ca); structureNr++; -// } } } else { // print clauses which are not supported yet @@ -732,4 +739,36 @@ return ret; } + private static void addMutagenesis(KB kb) { + String[] mutagenicCompounds = new String[] { + "d101", "d104", "d106", "d107", "d112", "d113", "d117", + "d121", "d123", "d126", "d128", "d13", "d135", "d137", + "d139", "d140", "d143", "d144", "d145", "d146", "d147", + "d152", "d153", "d154", "d155", "d156", "d159", "d160", + "d161", "d163", "d164", "d166", "d168", "d171", "d173", + "d174", "d177", "d179", "d18", "d180", "d182", "d183", + "d185", "d186", "d187", "d188", "d189", "d19", "d191", + "d192", "d193", "d195", "d197", "d2", "d201", "d202", + "d205", "d206", "d207", "d211", "d214", "d215", "d216", + "d224", "d225", "d227", "d228", "d229", "d231", "d235", + "d237", "d239", "d242", "d245", "d246", "d249", "d251", + "d254", "d257", "d258", "d261", "d264", "d266", "d269", + "d27", "d270", "d271", "d28", "d288", "d292", "d297", + "d300", "d308", "d309", "d311", "d313", "d314", "d322", + "d323", "d324", "d329", "d330", "d332", "d334", "d35", + "d36", "d37", "d38", "d41", "d42", "d48", "d50", "d51", + "d54", "d58", "d61", "d62", "d63", "d66", "d69", "d72", + "d76", "d77", "d78", "d84", "d86", "d89", "d92", "d96"}; + TreeSet<String> mutagenic = new TreeSet<String>(Arrays.asList(mutagenicCompounds)); + + for(String compound : compounds) { + if(mutagenic.contains(compound)) { + BooleanDatatypePropertyAssertion muta = getBooleanDatatypePropertyAssertion(compound, "isMutagenic", true); + kb.addAxiom(muta); + } else { + BooleanDatatypePropertyAssertion muta = getBooleanDatatypePropertyAssertion(compound, "isMutagenic", false); + kb.addAxiom(muta); + } + } + } } Modified: trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java 2008-03-16 19:03:46 UTC (rev 713) @@ -760,6 +760,7 @@ return identifier; } + @Override public void releaseKB() { connector.releaseKB(kbURI); } Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-16 19:03:46 UTC (rev 713) @@ -50,6 +50,9 @@ import org.dllearner.core.owl.Negation; import org.dllearner.core.owl.Nothing; import org.dllearner.core.owl.ObjectAllRestriction; +import org.dllearner.core.owl.ObjectCardinalityRestriction; +import org.dllearner.core.owl.ObjectMaxCardinalityRestriction; +import org.dllearner.core.owl.ObjectMinCardinalityRestriction; import org.dllearner.core.owl.ObjectProperty; import org.dllearner.core.owl.ObjectPropertyExpression; import org.dllearner.core.owl.ObjectPropertyHierarchy; @@ -290,6 +293,82 @@ return false; } return true; + } else if (description instanceof ObjectMinCardinalityRestriction) { + ObjectPropertyExpression ope = ((ObjectCardinalityRestriction) description).getRole(); + if (!(ope instanceof ObjectProperty)) + throw new ReasoningMethodUnsupportedException("Instance check for description " + + description + " unsupported. Inverse object properties not supported."); + ObjectProperty op = (ObjectProperty) ope; + Description child = description.getChild(0); + Map<Individual, SortedSet<Individual>> mapping = opPos.get(op); + + if (mapping == null) { + logger.warn("Instance check of a description with an undefinied property (" + op + + ")."); + return true; + } + + int number = ((ObjectCardinalityRestriction) description).getNumber(); + int nrOfFillers = 0; + + SortedSet<Individual> roleFillers = opPos.get(op).get(individual); + // return false if there are none or not enough role fillers + if (roleFillers == null || roleFillers.size() < number) + return false; + + int index = 0; + for (Individual roleFiller : roleFillers) { + index++; + if (instanceCheck(child, roleFiller)) { + nrOfFillers++; + if(nrOfFillers == number) + return true; + // earyl abort: e.g. >= 10 hasStructure.Methyl; + // if there are 11 fillers and 2 are not Methyl, the result is false + } /* else { + if(roleFillers.size() - index < number) + return false; + }*/ + } + return false; + } else if (description instanceof ObjectMaxCardinalityRestriction) { + ObjectPropertyExpression ope = ((ObjectCardinalityRestriction) description).getRole(); + if (!(ope instanceof ObjectProperty)) + throw new ReasoningMethodUnsupportedException("Instance check for description " + + description + " unsupported. Inverse object properties not supported."); + ObjectProperty op = (ObjectProperty) ope; + Description child = description.getChild(0); + Map<Individual, SortedSet<Individual>> mapping = opPos.get(op); + + if (mapping == null) { + logger.warn("Instance check of a description with an undefinied property (" + op + + ")."); + return true; + } + + int number = ((ObjectCardinalityRestriction) description).getNumber(); + int nrOfFillers = 0; + + SortedSet<Individual> roleFillers = opPos.get(op).get(individual); + // return false if there are none or not enough role fillers + if (roleFillers == null || roleFillers.size() > number) + return true; + + int index = 0; + for (Individual roleFiller : roleFillers) { + index++; + if (instanceCheck(child, roleFiller)) { + nrOfFillers++; + if(nrOfFillers == number) + return false; + // earyl abort: e.g. <= 5 hasStructure.Methyl; + // if there are 6 fillers and 2 are not Methyl, the result is true + } /* else { + if(roleFillers.size() - index <= number) + return true; + } */ + } + return true; } else if (description instanceof BooleanValueRestriction) { DatatypeProperty dp = ((BooleanValueRestriction)description).getRestrictedPropertyExpresssion(); boolean value = ((BooleanValueRestriction)description).getBooleanValue(); @@ -503,6 +582,19 @@ @Override public Description getRange(ObjectProperty objectProperty) { return rc.getRange(objectProperty); + } + + @Override + public Map<Individual, SortedSet<Individual>> getRoleMembers(ObjectProperty atomicRole) { + return opPos.get(atomicRole); + } + + /* (non-Javadoc) + * @see org.dllearner.core.ReasonerComponent#releaseKB() + */ + @Override + public void releaseKB() { + rc.releaseKB(); } } Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java 2008-03-16 19:03:46 UTC (rev 713) @@ -182,5 +182,13 @@ */ public Map<String, String> getPrefixes() { return rc.getPrefixes(); - } + } + + /* (non-Javadoc) + * @see org.dllearner.core.ReasonerComponent#releaseKB() + */ + @Override + public void releaseKB() { + rc.releaseKB(); + } } Modified: trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-16 19:03:46 UTC (rev 713) @@ -1021,4 +1021,18 @@ return prefixes; } + /* (non-Javadoc) + * @see org.dllearner.core.ReasonerComponent#releaseKB() + */ + @Override + public void releaseKB() { + try { + reasoner.clearOntologies(); + reasoner.dispose(); + } catch (OWLReasonerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-16 19:03:46 UTC (rev 713) @@ -32,6 +32,7 @@ import java.util.TreeSet; import java.util.Map.Entry; +import org.apache.log4j.Logger; import org.dllearner.algorithms.refinement.RefinementOperator; import org.dllearner.core.ReasoningService; import org.dllearner.core.owl.BooleanValueRestriction; @@ -47,6 +48,9 @@ import org.dllearner.core.owl.Negation; import org.dllearner.core.owl.Nothing; import org.dllearner.core.owl.ObjectAllRestriction; +import org.dllearner.core.owl.ObjectCardinalityRestriction; +import org.dllearner.core.owl.ObjectMaxCardinalityRestriction; +import org.dllearner.core.owl.ObjectMinCardinalityRestriction; import org.dllearner.core.owl.ObjectProperty; import org.dllearner.core.owl.ObjectPropertyExpression; import org.dllearner.core.owl.ObjectQuantorRestriction; @@ -72,6 +76,10 @@ */ public class RhoDRDown implements RefinementOperator { + @SuppressWarnings({"unused"}) + private static Logger logger = Logger + .getLogger(RhoDRDown.class); + private ReasoningService rs; // hierarchies @@ -82,6 +90,9 @@ private Map<DatatypeProperty,Description> dpDomains = new TreeMap<DatatypeProperty,Description>(); private Map<ObjectProperty,Description> opRanges = new TreeMap<ObjectProperty,Description>(); + // maximum number of fillers for eeach role + private Map<ObjectProperty,Integer> maxNrOfFillers = new TreeMap<ObjectProperty,Integer>(); + // start concept (can be used to start from an arbitrary concept, needs // to be Thing or NamedClass), note that when you use e.g. Compound as // start class, then the algorithm should start the search with class @@ -137,6 +148,7 @@ private boolean applyExistsFilter = true; private boolean useAllConstructor = true; private boolean useExistsConstructor = true; + private boolean useCardinalityRestrictions = true; private boolean useNegation = true; private boolean useBooleanDatatypes = true; private boolean useDoubleDatatypes = true; @@ -181,7 +193,36 @@ computeSplits(dp); } + // determine the maximum number of fillers for each role + for(ObjectProperty op : rs.getAtomicRoles()) { + int maxFillers = 0; + Map<Individual,SortedSet<Individual>> opMembers = rs.getRoleMembers(op); + for(SortedSet<Individual> inds : opMembers.values()) { + if(inds.size()>maxFillers) + maxFillers = inds.size(); + } + maxNrOfFillers.put(op, maxFillers); + } + /* + String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND (>= 2 \"http://dl-learner.org/carcinogenesis#hasStructure\".\"http://dl-learner.org/carcinogenesis#Ar_halide\" OR ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND >= 5 \"http://dl-learner.org/carcinogenesis#hasBond\". TOP)))"; + try { + NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Compound"); + Description d = KBParser.parseConcept(conceptStr); + SortedSet<Description> ds = (SortedSet<Description>) refine(d,15,null,struc); + System.out.println(ds); + + Individual i = new Individual("http://dl-learner.org/carcinogenesis#d101"); + rs.instanceCheck(ds.first(), i); + + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.exit(0); + */ + + /* NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Atom"); ObjectProperty op = new ObjectProperty("http://dl-learner.org/carcinogenesis#hasAtom"); ObjectSomeRestriction oar = new ObjectSomeRestriction(op,Thing.instance); @@ -222,7 +263,7 @@ public Set<Description> refine(Description description, int maxLength, List<Description> knownRefinements, Description currDomain) { -// System.out.println(description + " " + currDomain + " " + maxLength); +// logger.trace(description + " " + currDomain + " " + maxLength); // actions needing to be performed if this is the first time the // current domain is used @@ -336,6 +377,15 @@ for(ObjectProperty moreSpecialRole : moreSpecialRoles) refinements.add(new ObjectSomeRestriction(moreSpecialRole, description.getChild(0))); + // rule 3: EXISTS r.D => >= 2 r.D + // (length increases by 1 so we have to check whether max length is sufficient) + if(useCardinalityRestrictions) { + if(maxLength > description.getLength() && maxNrOfFillers.get(ar)>1) { + ObjectMinCardinalityRestriction min = new ObjectMinCardinalityRestriction(2,role,description.getChild(0)); + refinements.add(min); + } + } + } else if (description instanceof ObjectAllRestriction) { ObjectPropertyExpression role = ((ObjectQuantorRestriction)description).getRole(); Description range = opRanges.get(role); @@ -360,6 +410,28 @@ refinements.add(new ObjectAllRestriction(moreSpecialRole, description.getChild(0))); } + // rule 4: ALL r.D => <= (maxFillers-1) r.D + // (length increases by 1 so we have to check whether max length is sufficient) + if(useCardinalityRestrictions) { + if(maxLength > description.getLength() && maxNrOfFillers.get(ar)>1) { + ObjectMaxCardinalityRestriction max = new ObjectMaxCardinalityRestriction(maxNrOfFillers.get(ar)-1,role,description.getChild(0)); + refinements.add(max); + } + } + } else if (description instanceof ObjectCardinalityRestriction) { + if(description instanceof ObjectMaxCardinalityRestriction) { + // <= x r.C => <= (x-1) r.C + ObjectMaxCardinalityRestriction max = (ObjectMaxCardinalityRestriction) description; + int number = max.getNumber(); + if(number > 0) + refinements.add(new ObjectMaxCardinalityRestriction(number-1,max.getRole(),max.getChild(0))); + } else if(description instanceof ObjectMinCardinalityRestriction) { + // >= x r.C => >= (x+1) r.C + ObjectMinCardinalityRestriction min = (ObjectMinCardinalityRestriction) description; + int number = min.getNumber(); + if(number < maxNrOfFillers.get(min.getRole())) + refinements.add(new ObjectMinCardinalityRestriction(number+1,min.getRole(),min.getChild(0))); + } } else if (description instanceof DatatypeSomeRestriction) { DatatypeSomeRestriction dsr = (DatatypeSomeRestriction) description; @@ -434,6 +506,7 @@ } // check for double datatype properties + /* if(c instanceof DatatypeSomeRestriction && description instanceof DatatypeSomeRestriction) { DataRange dr = ((DatatypeSomeRestriction)c).getDataRange(); @@ -442,7 +515,7 @@ if((dr instanceof DoubleMaxValue && dr2 instanceof DoubleMaxValue) ||(dr instanceof DoubleMinValue && dr2 instanceof DoubleMinValue)) skip = true; - } + }*/ // perform a disjointness check when named classes are added; // this can avoid a lot of superfluous computation in the algorithm e.g. @@ -462,7 +535,9 @@ ConceptTransformation.cleanConceptNonRecursive(mc); ConceptTransformation.transformToOrderedNegationNormalFormNonRecursive(mc, conceptComparator); - refinements.add(mc); + // last check before intersection is added + if(checkIntersection(mc)) + refinements.add(mc); } } } @@ -481,11 +556,15 @@ // when a child of an intersection is refined and reintegrated into the // intersection, we can perform some sanity checks; // method returns true if everything is OK and false otherwise - private boolean checkIntersection(Intersection intersection) { + // TODO: can be implemented more efficiently if the newly added child + // is given as parameter + public static boolean checkIntersection(Intersection intersection) { // rule 1: max. restrictions at most once boolean maxDoubleOccurence = false; // rule 2: min restrictions at most once boolean minDoubleOccurence = false; + // rule 3: no double boolean datatypes + TreeSet<DatatypeProperty> occuredDP = new TreeSet<DatatypeProperty>(); for(Description child : intersection.getChildren()) { if(child instanceof DatatypeSomeRestriction) { DataRange dr = ((DatatypeSomeRestriction)child).getDataRange(); @@ -500,7 +579,14 @@ else minDoubleOccurence = true; } + } else if(child instanceof BooleanValueRestriction) { + DatatypeProperty dp = (DatatypeProperty) ((BooleanValueRestriction)child).getRestrictedPropertyExpression(); +// System.out.println("dp: " + dp); + // return false if the boolean property exists already + if(!occuredDP.add(dp)) + return false; } +// System.out.println(child.getClass()); } return true; } Modified: trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/utilities/ConceptComparator.java 2008-03-16 19:03:46 UTC (rev 713) @@ -12,6 +12,9 @@ import org.dllearner.core.owl.NamedClass; import org.dllearner.core.owl.Nothing; import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.ObjectCardinalityRestriction; +import org.dllearner.core.owl.ObjectMaxCardinalityRestriction; +import org.dllearner.core.owl.ObjectMinCardinalityRestriction; import org.dllearner.core.owl.ObjectSomeRestriction; import org.dllearner.core.owl.Intersection; import org.dllearner.core.owl.SimpleDoubleDataRange; @@ -172,6 +175,46 @@ return roleCompare; } else return -1; + } else if(concept1 instanceof ObjectMinCardinalityRestriction) { + if(concept2.getChildren().size()<1 || concept2 instanceof Negation || concept2 instanceof ObjectQuantorRestriction) + return 1; + // first criterion: object property + // second criterion: number + // third criterion: children + else if(concept2 instanceof ObjectMinCardinalityRestriction) { + int roleCompare = rc.compare(((ObjectCardinalityRestriction)concept1).getRole(), ((ObjectCardinalityRestriction)concept2).getRole()); + if(roleCompare == 0) { + Integer number1 = ((ObjectCardinalityRestriction)concept1).getNumber(); + Integer number2 = ((ObjectCardinalityRestriction)concept2).getNumber(); + int numberCompare = number1.compareTo(number2); + if(numberCompare == 0) + return compare(concept1.getChild(0), concept2.getChild(0)); + else + return numberCompare; + } else + return roleCompare; + } else + return -1; + } else if(concept1 instanceof ObjectMaxCardinalityRestriction) { + if(concept2.getChildren().size()<1 || concept2 instanceof Negation || concept2 instanceof ObjectQuantorRestriction || concept2 instanceof ObjectMinCardinalityRestriction) + return 1; + // first criterion: object property + // second criterion: number + // third criterion: children + else if(concept2 instanceof ObjectMaxCardinalityRestriction) { + int roleCompare = rc.compare(((ObjectCardinalityRestriction)concept1).getRole(), ((ObjectCardinalityRestriction)concept2).getRole()); + if(roleCompare == 0) { + Integer number1 = ((ObjectCardinalityRestriction)concept1).getNumber(); + Integer number2 = ((ObjectCardinalityRestriction)concept2).getNumber(); + int numberCompare = number1.compareTo(number2); + if(numberCompare == 0) + return compare(concept1.getChild(0), concept2.getChild(0)); + else + return numberCompare; + } else + return roleCompare; + } else + return -1; } else if(concept1 instanceof Intersection) { if(concept2.getChildren().size()<2) return 1; Modified: trunk/src/dl-learner/org/dllearner/utilities/CrossValidation.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/CrossValidation.java 2008-03-14 22:58:35 UTC (rev 712) +++ trunk/src/dl-learner/org/dllearner/utilities/CrossValidation.java 2008-03-16 19:03:46 UTC (rev 713) @@ -21,9 +21,11 @@ import java.io.File; import java.text.DecimalFormat; +import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; +import java.util.Random; import java.util.Set; import org.apache.log4j.ConsoleAppender; @@ -65,20 +67,27 @@ else leaveOneOut = true; + if(folds < 2) { + System.out.println("At least 2 fold needed."); + System.exit(0); + } + // create logger (a simple logger which outputs // its messages to the console) SimpleLayout layout = new SimpleLayout(); ConsoleAppender consoleAppender = new ConsoleAppender(layout); logger.removeAllAppenders(); logger.addAppender(consoleAppender); - logger.setLevel(Level.WARN); + logger.setLevel(Level.WARN); + // disable OWL API info output + java.util.logging.Logger.getLogger("").setLevel(java.util.logging.Level.WARNING); new CrossValidation(file, folds, leaveOneOut); } public CrossValidation(File file, int folds, boolean leaveOneOut) { - + DecimalFormat df = new DecimalFormat(); ComponentManager cm = ComponentManager.getInstance(); @@ -104,10 +113,13 @@ if(lp instanceof PosNegLP) { + // get examples and shuffle them to Set<Individual> posExamples = ((PosNegLP)lp).getPositiveExamples(); List<Individual> posExamplesList = new LinkedList<Individual>(posExamples); + Collections.shuffle(posExamplesList, new Random(1)); Set<Individual> negExamples = ((PosNegLP)lp).getNegativeExamples(); List<Individual> negExamplesList = new LinkedList<Individual>(negExamples); + Collections.shuffle(negExamplesList, new Random(2)); // sanity check whether nr. of folds makes sense for this benchmark if(!leaveOneOut && (posExamples.size()<folds && negExamples.size()<folds)) { @@ -138,6 +150,9 @@ int[] splitsPos = calculateSplits(posExamples.size(),folds); int[] splitsNeg = calculateSplits(negExamples.size(),folds); +// System.out.println(splitsPos[0]); +// System.out.println(splitsNeg[0]); + // calculating training and test sets for(int i=0; i<folds; i++) { Set<Individual> testPos = getTestingSet(posExamplesList, splitsPos, i); @@ -180,16 +195,45 @@ Set<String> neg = Datastructures.individualSetToStringSet(trainingSetsNeg.get(currFold)); cm.applyConfigEntry(lp, "positiveExamples", pos); cm.applyConfigEntry(lp, "negativeExamples", neg); +// System.out.println("pos: " + pos.size()); +// System.out.println("neg: " + neg.size()); +// System.exit(0); + // es fehlt init zwischendurch + LearningAlgorithm la = start.getLearningAlgorithm(); + // init again, because examples have changed + try { + la.init(); + } catch (ComponentInitException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } long algorithmStartTime = System.nanoTime(); la.start(); long algorithmDuration = System.nanoTime() - algorithmStartTime; runtime.addNumber(algorithmDuration/(double)1000000000); Description concept = la.getBestSolution(); - int correctExamples = getCorrectPosClassified(rs, concept, testSetsPos.get(currFold)) - + getCorrectNegClassified(rs, concept, testSetsNeg.get(currFold)); + + Set<Individual> tmp = rs.instanceCheck(concept, testSetsPos.get(currFold)); + Set<Individual> tmp2 = Helper.difference(testSetsPos.get(currFold), tmp); + Set<Individual> tmp3 = rs.instanceCheck(concept, testSetsNeg.get(currFold)); + + System.out.println("test set errors pos: " + tmp2); + System.out.println("test set errors neg: " + tmp3); + + // calculate training accuracies + int trainingCorrectPosClassified = getCorrectPosClassified(rs, concept, trainingSetsPos.get(currFold)); + int trainingCorrectNegClassified = getCorrectNegClassified(rs, concept, trainingSetsNeg.get(currFold)); + int trainingCorrectExamples = trainingCorrectPosClassified + trainingCorrectNegClassified; + double trainingAccuracy = 100*((double)trainingCorrectExamples/(trainingSetsPos.get(currFold).size()+ + trainingSetsNeg.get(currFold).size())); + + // calculate test accuracies + int correctPosClassified = getCorrectPosClassified(rs, concept, testSetsPos.get(currFold)); + int correctNegClassified = getCorrectNegClassified(rs, concept, testSetsNeg.get(currFold)); + int correctExamples = correctPosClassified + correctNegClassified; double currAccuracy = 100*((double)correctExamples/(testSetsPos.get(currFold).size()+ testSetsNeg.get(currFold).size())); accuracy.addNumber(currAccuracy); @@ -197,10 +241,17 @@ length.addNumber(concept.getLength()); System.out.println("fold " + currFold + " (" + file + "):"); + System.out.println(" training: " + pos.size() + " positive and " + neg.size() + " negative examples"); + System.out.println(" testing: " + correctPosClassified + "/" + testSetsPos.get(currFold).size() + " correct positives, " + + correctNegClassified + "/" + testSetsNeg.get(currFold).size() + " correct negatives"); System.out.println(" concept: " + concept); - System.out.println(" accuracy: " + df.format(currAccuracy) + "%"); + System.out.println(" accuracy: " + df.format(currAccuracy) + "% (" + df.format(trainingAccuracy) + "% on training set)"); System.out.println(" length: " + df.format(concept.getLength())); System.out.println(" runtime: " + df.format(algorithmDuration/(double)1000000000) + "s"); + + // free all resources + start.getReasoningService().releaseKB(); + cm.freeAllComponents(); } System.out.println(); @@ -211,12 +262,12 @@ } - private int getCorrectPosClassified(ReasoningService rs, Description concept, Set<Individual> posClassified) { - return rs.instanceCheck(concept, posClassified).size(); + private int getCorrectPosClassified(ReasoningService rs, Description concept, Set<Individual> testSetPos) { + return rs.instanceCheck(concept, testSetPos).size(); } - private int getCorrectNegClassified(ReasoningService rs, Description concept, Set<Individual> negClassified) { - return negClassified.size() - rs.instanceCheck(concept, negClassified).size(); + private int getCorrectNegClassified(ReasoningService rs, Description concept, Set<Individual> testSetNeg) { + return testSetNeg.size() - rs.instanceCheck(concept, testSetNeg).size(); } private Set<Individual> getTestingSet(List<Individual> examples, int[] splits, int fold) { @@ -229,6 +280,8 @@ // the split corresponds to the ends of the folds int toIndex = splits[fold]; +// System.out.println("from " + fromIndex + " to " + toIndex); + Set<Individual> testingSet = new HashSet<Individual>(); // +1 because 2nd element is exclusive in subList method testingSet.addAll(examples.subList(fromIndex, toIndex)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-19 08:11:25
|
Revision: 715 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=715&view=rev Author: jenslehmann Date: 2008-03-19 01:11:19 -0700 (Wed, 19 Mar 2008) Log Message: ----------- redundancy check bug fixes changes in heuristic Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-17 10:21:51 UTC (rev 714) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-03-19 08:11:19 UTC (rev 715) @@ -115,7 +115,7 @@ // the divide&conquer approach in many ILP programs using a // clause by clause search; after a period of time the candidate // set is reduced to focus CPU time on the most promising concepts - private boolean useCandidateReduction = false; + private boolean useCandidateReduction = true; private int candidatePostReductionSize = 30; // setting to true gracefully stops the algorithm @@ -244,24 +244,36 @@ } public void start() { + + // TODO: write a JUnit test for this problem (long-lasting or infinite loops because + // redundant children of a node are called recursively after when the node is extended + // twice) /* // String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND (>= 2 \"http://dl-learner.org/carcinogenesis#hasStructure\".\"http://dl-learner.org/carcinogenesis#Ar_halide\" OR ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND >= 5 \"http://dl-learner.org/carcinogenesis#hasBond\". TOP)))"; - String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND (\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE)))"; +// String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND (\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE)))"; + String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND (>= 3 \"http://dl-learner.org/carcinogenesis#hasStructure\".\"http://dl-learner.org/carcinogenesis#Halide\" OR ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND ALL \"http://dl-learner.org/carcinogenesis#hasAtom\".TOP)))"; + String conceptStr2 = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND (>= 4 \"http://dl-learner.org/carcinogenesis#hasStructure\".\"http://dl-learner.org/carcinogenesis#Halide\" OR ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND ALL \"http://dl-learner.org/carcinogenesis#hasAtom\".TOP)))"; try { NamedClass struc = new NamedClass("http://dl-learner.org/carcinogenesis#Compound"); Description d = KBParser.parseConcept(conceptStr); + Description d2 = KBParser.parseConcept(conceptStr2); // SortedSet<Description> ds = (SortedSet<Description>) operator.refine(d,15,null,struc); // System.out.println(ds); - System.out.println(RhoDRDown.checkIntersection((Intersection)d)); +// System.out.println(RhoDRDown.checkIntersection((Intersection)d)); Set<Individual> coveredNegatives = rs.instanceCheck(d, learningProblem.getNegativeExamples()); Set<Individual> coveredPositives = rs.instanceCheck(d, learningProblem.getPositiveExamples()); ExampleBasedNode ebn = new ExampleBasedNode(d); ebn.setCoveredExamples(coveredPositives, coveredNegatives); - extendNodeProper(ebn,15); + properRefinements.add(d2); + extendNodeProper(ebn,13); + extendNodeProper(ebn,14); + for(Description refinement: ebn.getChildConcepts()) + System.out.println("refinement: " + refinement); + // Individual i = new Individual("http://dl-learner.org/carcinogenesis#d101"); // for(Individual i : learningProblem.getPositiveExamples()) // rs.instanceCheck(ds.last(), i); @@ -308,7 +320,7 @@ // print statistics at most once a second currentTime = System.nanoTime(); - if(currentTime - lastPrintTime > 1000000000) { + if(currentTime - lastPrintTime > 3000000000l) { printStatistics(false); lastPrintTime = currentTime; logger.debug("--- loop " + loop + " started ---"); @@ -327,7 +339,7 @@ // Logger.getRootLogger().setLevel(Level.TRACE); } - System.out.println("next expanded: " + candidates.last().getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); +// System.out.println("next expanded: " + candidates.last().getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); // chose best node according to heuristics bestNode = candidates.last(); // extend best node @@ -434,8 +446,11 @@ childConceptsDeletionTimeNs += System.nanoTime() - childConceptsDeletionTimeNsStart; -// if(refinements.size()<30) -// System.out.println("refinements: " + refinements); +// if(refinements.size()<30) { +//// System.out.println("refinements: " + refinements); +// for(Description refinement: refinements) +// System.out.println("refinement: " + refinement); +// } long evaluateSetCreationTimeNsStart = System.nanoTime(); @@ -463,7 +478,7 @@ propernessTestsAvoidedByShortConceptConstruction++; propernessDetected = true; - System.out.println("refinement " + refinement + " can be shortened"); +// System.out.println("refinement " + refinement + " can be shortened"); // System.exit(0); } } @@ -517,7 +532,7 @@ } evaluateSetCreationTimeNs += System.nanoTime() - evaluateSetCreationTimeNsStart; -// System.out.println("intermediate 1"); +// System.out.println("intermediate 1 " + node.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); // System.out.println(toEvaluateConcepts.size()); @@ -678,8 +693,17 @@ for(Description refinement : refinements) { // for(int i=0; i<=recDepth; i++) // System.out.print(" "); -// System.out.println("call: " + refinement + " [maxLength " + maxLength + "]"); - extendNodeProper(node, refinement, maxLength, recDepth+1); +// System.out.println("call: " + refinement + " [maxLength " + maxLength + ", rec depth " + recDepth + "]"); + + // check for redundancy (otherwise we may run into very time-intensive loops, + // see planned JUnit test case $x) + + long redundancyCheckTimeNsStart = System.nanoTime(); + boolean redundant = properRefinements.contains(refinement); + redundancyCheckTimeNs += System.nanoTime() - redundancyCheckTimeNsStart; + + if(!redundant) + extendNodeProper(node, refinement, maxLength, recDepth+1); // for(int i=0; i<=recDepth; i++) // System.out.print(" "); // System.out.println("finished: " + refinement + " [maxLength " + maxLength + "]"); Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-17 10:21:51 UTC (rev 714) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-03-19 08:11:19 UTC (rev 715) @@ -79,6 +79,9 @@ private double gainBonusFactor; private double nodeChildPenalty = 0.0001; private double startNodeBonus = 1.0; + // penalise errors on positive examples harder than on negative examples + // (positive weight = 1) + private double negativeWeight = 0.8; // examples private int nrOfNegativeExamples; @@ -113,11 +116,11 @@ } public double getNodeScore(ExampleBasedNode node) { - double accuracy = getAccuracy(node.getCoveredPositives().size(),node.getCoveredNegatives().size()); + double accuracy = getWeightedAccuracy(node.getCoveredPositives().size(),node.getCoveredNegatives().size()); ExampleBasedNode parent = node.getParent(); double gain = 0; if(parent != null) { - double parentAccuracy = getAccuracy(parent.getCoveredPositives().size(),parent.getCoveredNegatives().size()); + double parentAccuracy = getWeightedAccuracy(parent.getCoveredPositives().size(),parent.getCoveredNegatives().size()); gain = accuracy - parentAccuracy; } else { accuracy += startNodeBonus; @@ -126,9 +129,8 @@ return accuracy + gainBonusFactor * gain - expansionPenaltyFactor * he - nodeChildPenalty * node.getChildren().size(); } - private double getAccuracy(int coveredPositives, int coveredNegatives) { - return (coveredPositives + nrOfNegativeExamples - coveredNegatives)/(double)nrOfExamples; - + private double getWeightedAccuracy(int coveredPositives, int coveredNegatives) { + return (coveredPositives + negativeWeight * (nrOfNegativeExamples - coveredNegatives))/(double)nrOfExamples; } public static double getNodeScore(ExampleBasedNode node, int nrOfPositiveExamples, int nrOfNegativeExamples) { Modified: trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java 2008-03-17 10:21:51 UTC (rev 714) +++ trunk/src/dl-learner/org/dllearner/examples/Carcinogenesis.java 2008-03-19 08:11:19 UTC (rev 715) @@ -123,6 +123,9 @@ private static boolean learnCarcinogenic = true; private static boolean useNewGroups = true; + private static boolean createPTE1Conf = false; + private static boolean createPTE2Conf = false; + /** * @param args * No arguments supported. @@ -133,14 +136,13 @@ public static void main(String[] args) throws FileNotFoundException, IOException, ParseException { - // TODO: newgroups are not mapped currently String[] files = new String[] { "newgroups.pl", "ames.pl", "atoms.pl", "bonds.pl", "gentoxprops.pl", "ind_nos.pl", "ind_pos.pl"}; // "pte2/canc_nos.pl", "pte2/pte2ames.pl", "pte2/pte2atoms.pl", // "pte2/pte2bonds.pl", "pte2/pte2gentox.pl", "pte2/pte2ind_nos.pl", "pte2/pte2newgroups.pl" // "train.b" => not a pure Prolog file but Progol/Aleph specific // }; - File owlFile = new File("examples/carcinogenesis/pte.owl"); + File owlFile = new File("examples/carcinogenesis/carcinogenesis.owl"); Program program = null; long startTime, duration; @@ -281,7 +283,6 @@ // generating test examples for PTE-1 // => put all in one file, because they were used as training for PTE-2 File confPTE1File = new File("examples/carcinogenesis/testpte1.conf"); - Files.clearFile(confPTE1File); File testPTE1Positives = new File(prologDirectory + "pte1.f"); File testPTE1Negatives = new File(prologDirectory + "pte1.n"); @@ -289,16 +290,20 @@ List<Individual> negPTE1Examples = getExamples(testPTE1Negatives); appendPosExamples(confTrainFile, posPTE1Examples); appendNegExamples(confTrainFile, negPTE1Examples); - Files.clearFile(confPTE1File); - Files.appendFile(confPTE1File, "import(\"pte.owl\");\nreasoner=fastInstanceChecker;\n\n"); - appendPosExamples(confPTE1File, posPTE1Examples); - appendNegExamples(confPTE1File, negPTE1Examples); + if(createPTE1Conf) { + Files.clearFile(confPTE1File); + Files.appendFile(confPTE1File, "import(\"pte.owl\");\nreasoner=fastInstanceChecker;\n\n"); + appendPosExamples(confPTE1File, posPTE1Examples); + appendNegExamples(confPTE1File, negPTE1Examples); + } // create a PTE-2 test file - File confPTE2File = new File("examples/carcinogenesis/testpte2.conf"); - Files.clearFile(confPTE2File); - Files.appendFile(confPTE2File, "import(\"pte.owl\");\nreasoner=fastInstanceChecker;\n\n"); - Files.appendFile(confPTE2File, getPTE2Examples()); + if(createPTE2Conf) { + File confPTE2File = new File("examples/carcinogenesis/testpte2.conf"); + Files.clearFile(confPTE2File); + Files.appendFile(confPTE2File, "import(\"pte.owl\");\nreasoner=fastInstanceChecker;\n\n"); + Files.appendFile(confPTE2File, getPTE2Examples()); + } } Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-17 10:21:51 UTC (rev 714) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-19 08:11:19 UTC (rev 715) @@ -325,10 +325,10 @@ return true; // earyl abort: e.g. >= 10 hasStructure.Methyl; // if there are 11 fillers and 2 are not Methyl, the result is false - } /* else { + } else { if(roleFillers.size() - index < number) return false; - }*/ + } } return false; } else if (description instanceof ObjectMaxCardinalityRestriction) { @@ -363,10 +363,10 @@ return false; // earyl abort: e.g. <= 5 hasStructure.Methyl; // if there are 6 fillers and 2 are not Methyl, the result is true - } /* else { + } else { if(roleFillers.size() - index <= number) return true; - } */ + } } return true; } else if (description instanceof BooleanValueRestriction) { Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-17 10:21:51 UTC (rev 714) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-03-19 08:11:19 UTC (rev 715) @@ -92,6 +92,10 @@ // maximum number of fillers for eeach role private Map<ObjectProperty,Integer> maxNrOfFillers = new TreeMap<ObjectProperty,Integer>(); + // limit for cardinality restrictions (this makes sense if we e.g. have compounds with up to + // more than 200 atoms but we are only interested in atoms with certain characteristics and do + // not want something like e.g. >= 204 hasAtom.NOT Carbon-87; which blows up the search space + private int cardinalityLimit = 5; // start concept (can be used to start from an arbitrary concept, needs // to be Thing or NamedClass), note that when you use e.g. Compound as @@ -105,7 +109,7 @@ private int topRefinementsLength = 0; private Map<NamedClass, Integer> topARefinementsLength = new TreeMap<NamedClass, Integer>(); // M is finite and this value is the maximum length of any value in M - private static int mMaxLength = 3; + private static int mMaxLength = 4; // the sets M_\top and M_A private Map<Integer,SortedSet<Description>> m = new TreeMap<Integer,SortedSet<Description>>(); @@ -194,15 +198,22 @@ } // determine the maximum number of fillers for each role + // (up to a specified cardinality maximum) + if(useCardinalityRestrictions) { for(ObjectProperty op : rs.getAtomicRoles()) { int maxFillers = 0; Map<Individual,SortedSet<Individual>> opMembers = rs.getRoleMembers(op); for(SortedSet<Individual> inds : opMembers.values()) { if(inds.size()>maxFillers) maxFillers = inds.size(); + if(maxFillers >= cardinalityLimit) { + maxFillers = cardinalityLimit; + break; + } } maxNrOfFillers.put(op, maxFillers); } + } /* String conceptStr = "(\"http://dl-learner.org/carcinogenesis#Compound\" AND (>= 2 \"http://dl-learner.org/carcinogenesis#hasStructure\".\"http://dl-learner.org/carcinogenesis#Ar_halide\" OR ((\"http://dl-learner.org/carcinogenesis#amesTestPositive\" IS TRUE) AND >= 5 \"http://dl-learner.org/carcinogenesis#hasBond\". TOP)))"; @@ -412,23 +423,41 @@ // rule 4: ALL r.D => <= (maxFillers-1) r.D // (length increases by 1 so we have to check whether max length is sufficient) - if(useCardinalityRestrictions) { - if(maxLength > description.getLength() && maxNrOfFillers.get(ar)>1) { - ObjectMaxCardinalityRestriction max = new ObjectMaxCardinalityRestriction(maxNrOfFillers.get(ar)-1,role,description.getChild(0)); - refinements.add(max); - } - } + // => commented out because this is acutally not a downward refinement +// if(useCardinalityRestrictions) { +// if(maxLength > description.getLength() && maxNrOfFillers.get(ar)>1) { +// ObjectMaxCardinalityRestriction max = new ObjectMaxCardinalityRestriction(maxNrOfFillers.get(ar)-1,role,description.getChild(0)); +// refinements.add(max); +// } +// } } else if (description instanceof ObjectCardinalityRestriction) { + ObjectPropertyExpression role = ((ObjectCardinalityRestriction)description).getRole(); + Description range = opRanges.get(role); + int number = ((ObjectCardinalityRestriction)description).getCardinality(); if(description instanceof ObjectMaxCardinalityRestriction) { - // <= x r.C => <= (x-1) r.C + // rule 1: <= x r.C => <= x r.D + tmp = refine(description.getChild(0), maxLength-3, null, range); + + for(Description d : tmp) { + refinements.add(new ObjectMaxCardinalityRestriction(number,role,d)); + } + + // rule 2: <= x r.C => <= (x-1) r.C ObjectMaxCardinalityRestriction max = (ObjectMaxCardinalityRestriction) description; - int number = max.getNumber(); - if(number > 0) +// int number = max.getNumber(); + if(number > 1) refinements.add(new ObjectMaxCardinalityRestriction(number-1,max.getRole(),max.getChild(0))); + } else if(description instanceof ObjectMinCardinalityRestriction) { + tmp = refine(description.getChild(0), maxLength-3, null, range); + + for(Description d : tmp) { + refinements.add(new ObjectMinCardinalityRestriction(number,role,d)); + } + // >= x r.C => >= (x+1) r.C ObjectMinCardinalityRestriction min = (ObjectMinCardinalityRestriction) description; - int number = min.getNumber(); +// int number = min.getNumber(); if(number < maxNrOfFillers.get(min.getRole())) refinements.add(new ObjectMinCardinalityRestriction(number+1,min.getRole(),min.getChild(0))); } @@ -723,7 +752,7 @@ long mComputationTimeStartNs = System.nanoTime(); // initialise all possible lengths (1 to 3) - for(int i=1; i<=3; i++) { + for(int i=1; i<=mMaxLength; i++) { m.put(i, new TreeSet<Description>(conceptComparator)); } @@ -777,6 +806,15 @@ m.put(3,m3); + SortedSet<Description> m4 = new TreeSet<Description>(conceptComparator); + if(useCardinalityRestrictions) { + for(ObjectProperty r : rs.getMostGeneralRoles()) { + int maxFillers = maxNrOfFillers.get(r); + m4.add(new ObjectMaxCardinalityRestriction(maxFillers-1, r, new Thing())); + } + } + m.put(4,m4); + mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; } @@ -866,6 +904,15 @@ mA.get(nc).put(3,m3); + SortedSet<Description> m4 = new TreeSet<Description>(conceptComparator); + if(useCardinalityRestrictions) { + for(ObjectProperty r : mgr.get(nc)) { + int maxFillers = maxNrOfFillers.get(r); + m4.add(new ObjectMaxCardinalityRestriction(maxFillers-1, r, new Thing())); + } + } + mA.get(nc).put(4,m4); + mComputationTimeNs += System.nanoTime() - mComputationTimeStartNs; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-19 16:15:56
|
Revision: 717 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=717&view=rev Author: jenslehmann Date: 2008-03-19 09:15:18 -0700 (Wed, 19 Mar 2008) Log Message: ----------- added template for DBpedia navigation link suggestor Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/algorithms/DBpediaNavigationSuggestor.java Added: trunk/src/dl-learner/org/dllearner/algorithms/DBpediaNavigationSuggestor.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/DBpediaNavigationSuggestor.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/algorithms/DBpediaNavigationSuggestor.java 2008-03-19 16:15:18 UTC (rev 717) @@ -0,0 +1,85 @@ +/** + * Copyright (C) 2007-2008, Jens Lehmann + * + * This file is part of DL-Learner. + * + * DL-Learner is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * DL-Learner is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +package org.dllearner.algorithms; + +import org.dllearner.core.ComponentInitException; +import org.dllearner.core.LearningAlgorithm; +import org.dllearner.core.ReasoningService; +import org.dllearner.core.Score; +import org.dllearner.core.config.ConfigEntry; +import org.dllearner.core.config.InvalidConfigOptionValueException; +import org.dllearner.core.owl.Description; +import org.dllearner.learningproblems.PosNegLP; +import org.dllearner.learningproblems.PosOnlyDefinitionLP; + +/** + * The DBpedia Navigation suggestor takes a knowledge fragment extracted + * from DBpedia, performs some preprocessing steps, invokes a learning + * algorithm, and then performs postprocessing steps. It does not + * implement a completely new learning algorithm itself, but uses the + * example based refinement operator learning algorithm. + * + * @author Jens Lehmann + * + */ +public class DBpediaNavigationSuggestor extends LearningAlgorithm { + + public DBpediaNavigationSuggestor(PosNegLP learningProblem, ReasoningService rs) { + + } + + public DBpediaNavigationSuggestor(PosOnlyDefinitionLP learningProblem, ReasoningService rs) { + + } + + @Override + public <T> void applyConfigEntry(ConfigEntry<T> entry) throws InvalidConfigOptionValueException { + // TODO Auto-generated method stub + } + + @Override + public void init() throws ComponentInitException { + // TODO Auto-generated method stub + } + + @Override + public void start() { + // TODO Auto-generated method stub + } + + @Override + public void stop() { + // TODO Auto-generated method stub + + } + + @Override + public Description getBestSolution() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Score getSolutionScore() { + // TODO Auto-generated method stub + return null; + } + +} Modified: trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java =================================================================== --- trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java 2008-03-19 14:29:21 UTC (rev 716) +++ trunk/src/dl-learner/org/dllearner/tools/ore/ORE.java 2008-03-19 16:15:18 UTC (rev 717) @@ -519,6 +519,7 @@ Thread laThread = new Thread() { + @Override public void run(){ la.start(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2008-03-26 13:41:27
|
Revision: 726 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=726&view=rev Author: sknappe Date: 2008-03-26 06:41:24 -0700 (Wed, 26 Mar 2008) Log Message: ----------- a sparql query is created, that gets all individuals to a given concept Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/core/owl/Description.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java Modified: trunk/src/dl-learner/org/dllearner/core/owl/Description.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Description.java 2008-03-25 19:11:32 UTC (rev 725) +++ trunk/src/dl-learner/org/dllearner/core/owl/Description.java 2008-03-26 13:41:24 UTC (rev 726) @@ -33,6 +33,7 @@ protected Description parent = null; protected List<Description> children = new LinkedList<Description>(); + protected String sparqlVar = "subject"; public abstract int getArity(); @@ -200,4 +201,12 @@ public abstract String toManchesterSyntaxString(String baseURI, Map<String,String> prefixes); public abstract void accept(DescriptionVisitor visitor); + + public String getSparqlVar() { + return sparqlVar; + } + + public void setSparqlVar(String sparqlVar) { + this.sparqlVar = sparqlVar; + } } Added: trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java 2008-03-26 13:41:24 UTC (rev 726) @@ -0,0 +1,213 @@ +package org.dllearner.kb.sparql; + + +import org.dllearner.algorithms.gp.ADC; +import org.dllearner.core.owl.DatatypeExactCardinalityRestriction; +import org.dllearner.core.owl.DatatypeMaxCardinalityRestriction; +import org.dllearner.core.owl.DatatypeMinCardinalityRestriction; +import org.dllearner.core.owl.DatatypeSomeRestriction; +import org.dllearner.core.owl.DatatypeValueRestriction; +import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.DescriptionVisitor; +import org.dllearner.core.owl.Intersection; +import org.dllearner.core.owl.NamedClass; +import org.dllearner.core.owl.Negation; +import org.dllearner.core.owl.Nothing; +import org.dllearner.core.owl.ObjectAllRestriction; +import org.dllearner.core.owl.ObjectExactCardinalityRestriction; +import org.dllearner.core.owl.ObjectMaxCardinalityRestriction; +import org.dllearner.core.owl.ObjectMinCardinalityRestriction; +import org.dllearner.core.owl.ObjectSomeRestriction; +import org.dllearner.core.owl.ObjectValueRestriction; +import org.dllearner.core.owl.Thing; +import org.dllearner.core.owl.Union; +import org.dllearner.parser.KBParser; +import org.dllearner.parser.ParseException; + +/** + * Converter from DL-Learner descriptions to a corresponding SPARQL query + * to get all instances that are described by this description. + * @author Sebastian Knappe + * + */ +public class SparqlQueryDescriptionConvertVisitor implements DescriptionVisitor{ + + private String query=""; + + private int currentObject=0; + + public String getSparqlQuery() + { + query="SELECT ?subject\nWHERE {"+query; + query+="}\n"; + query+="LIMIT 5"; + return query; + } + + public static String getSparqlQuery(Description description) + { + SparqlQueryDescriptionConvertVisitor visitor=new SparqlQueryDescriptionConvertVisitor(); + description.accept(visitor); + return visitor.getSparqlQuery(); + } + + /** + * Used for testing the Sparql Query converter. + * + * @param args + */ + public static void main(String[] args) { + try { + Description d = KBParser.parseConcept("EXISTS \"http://dbpedia.org/property/disambiguates\".TOP"); + String query = SparqlQueryDescriptionConvertVisitor.getSparqlQuery(d); + System.out.println(d); + System.out.println(query); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.Negation) + */ + public void visit(Negation description) { + System.out.println("Negation"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.ObjectAllRestriction) + */ + public void visit(ObjectAllRestriction description) { + System.out.println("ObjectAllRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.ObjectSomeRestriction) + */ + public void visit(ObjectSomeRestriction description) { + System.out.println("ObjectSomeRestriction"); + query+="?"+description.getSparqlVar()+" <"+description.getRole()+"> ?object"+currentObject+"."; + description.getChild(0).setSparqlVar("object"+currentObject); + currentObject++; + description.getChild(0).accept(this); + System.out.println(description.getRole()); + System.out.println(description.getChild(0)); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.Nothing) + */ + public void visit(Nothing description) { + System.out.println("Nothing"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.Thing) + */ + public void visit(Thing description) { + System.out.println("Thing"); + + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.Intersection) + */ + public void visit(Intersection description) { + System.out.println("Intersection"); + description.getChild(0).accept(this); + query+="."; + description.getChild(1).accept(this); + query+="."; + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.Union) + */ + public void visit(Union description) { + System.out.println("Union"); + query+="{"; + description.getChild(0).accept(this); + query+="} UNION {"; + description.getChild(1).accept(this); + query+="}"; + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.ObjectMinCardinalityRestriction) + */ + public void visit(ObjectMinCardinalityRestriction description) { + System.out.println("ObjectMinCardinalityRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.ObjectExactCardinalityRestriction) + */ + public void visit(ObjectExactCardinalityRestriction description) { + System.out.println("ObjectExactCardinalityRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.ObjectMaxCardinalityRestriction) + */ + public void visit(ObjectMaxCardinalityRestriction description) { + System.out.println("ObjectMaxCardinalityRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.ObjectValueRestriction) + */ + public void visit(ObjectValueRestriction description) { + System.out.println("ObjectValueRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.DatatypeValueRestriction) + */ + public void visit(DatatypeValueRestriction description) { + System.out.println("DatatypeValueRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.NamedClass) + */ + public void visit(NamedClass description) { + System.out.println("NamedClass"); + query+="?"+description.getSparqlVar()+" a <"+description.getName()+">"; + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.algorithms.gp.ADC) + */ + public void visit(ADC description) { + System.out.println("ADC"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.DatatypeMinCardinalityRestriction) + */ + public void visit(DatatypeMinCardinalityRestriction description) { + System.out.println("DatatypeMinCardinalityRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.DatatypeExactCardinalityRestriction) + */ + public void visit(DatatypeExactCardinalityRestriction description) { + System.out.println("DatatypeExactCardinalityRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.DatatypeMaxCardinalityRestriction) + */ + public void visit(DatatypeMaxCardinalityRestriction description) { + System.out.println("DatatypeMaxCardinalityRestriction"); + } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.DescriptionVisitor#visit(org.dllearner.core.owl.DatatypeSomeRestriction) + */ + public void visit(DatatypeSomeRestriction description) { + System.out.println("DatatypeSomeRestriction"); + } +} Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java 2008-03-25 19:11:32 UTC (rev 725) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java 2008-03-26 13:41:24 UTC (rev 726) @@ -56,6 +56,7 @@ import org.dllearner.kb.OWLFile; import org.dllearner.kb.sparql.SparqlKnowledgeSource; import org.dllearner.kb.sparql.SparqlQuery; +import org.dllearner.kb.sparql.SparqlQueryDescriptionConvertVisitor; import org.dllearner.kb.sparql.SparqlQueryException; import org.dllearner.kb.sparql.SparqlQueryThreaded; import org.dllearner.learningproblems.PosNegDefinitionLP; @@ -590,6 +591,13 @@ } @WebMethod + public String getSparqlForConcept(int id) throws ClientNotKnownException { + ClientState state = getState(id); + Description solution=state.getLearningAlgorithm().getBestSolution(); + return SparqlQueryDescriptionConvertVisitor.getSparqlQuery(solution); + } + + @WebMethod public void debug(String deb) { System.out.println(deb); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2008-03-27 13:26:17
|
Revision: 732 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=732&view=rev Author: sknappe Date: 2008-03-27 06:26:15 -0700 (Thu, 27 Mar 2008) Log Message: ----------- deleted variable in Description a web service method now exists to get instances to a certain concept Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/core/owl/Description.java trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java Modified: trunk/src/dl-learner/org/dllearner/core/owl/Description.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Description.java 2008-03-27 08:26:58 UTC (rev 731) +++ trunk/src/dl-learner/org/dllearner/core/owl/Description.java 2008-03-27 13:26:15 UTC (rev 732) @@ -33,8 +33,7 @@ protected Description parent = null; protected List<Description> children = new LinkedList<Description>(); - protected String sparqlVar = "subject"; - + public abstract int getArity(); /** @@ -202,11 +201,4 @@ public abstract void accept(DescriptionVisitor visitor); - public String getSparqlVar() { - return sparqlVar; - } - - public void setSparqlVar(String sparqlVar) { - this.sparqlVar = sparqlVar; - } } Modified: trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java 2008-03-27 08:26:58 UTC (rev 731) +++ trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlQueryDescriptionConvertVisitor.java 2008-03-27 13:26:15 UTC (rev 732) @@ -1,6 +1,8 @@ package org.dllearner.kb.sparql; +import java.util.Stack; + import org.dllearner.algorithms.gp.ADC; import org.dllearner.core.owl.DatatypeExactCardinalityRestriction; import org.dllearner.core.owl.DatatypeMaxCardinalityRestriction; @@ -32,10 +34,17 @@ */ public class SparqlQueryDescriptionConvertVisitor implements DescriptionVisitor{ + private Stack<String> stack = new Stack<String>(); + private String query=""; private int currentObject=0; + public SparqlQueryDescriptionConvertVisitor() + { + stack.push("subject"); + } + public String getSparqlQuery() { query="SELECT ?subject\nWHERE {"+query; @@ -44,6 +53,14 @@ return query; } + public static String getSparqlQuery(String description) throws ParseException + { + Description d = KBParser.parseConcept(description); + SparqlQueryDescriptionConvertVisitor visitor=new SparqlQueryDescriptionConvertVisitor(); + d.accept(visitor); + return visitor.getSparqlQuery(); + } + public static String getSparqlQuery(Description description) { SparqlQueryDescriptionConvertVisitor visitor=new SparqlQueryDescriptionConvertVisitor(); @@ -58,7 +75,7 @@ */ public static void main(String[] args) { try { - Description d = KBParser.parseConcept("EXISTS \"http://dbpedia.org/property/disambiguates\".TOP"); + String d = "EXISTS \"http://dbpedia.org/property/disambiguates\".TOP"; String query = SparqlQueryDescriptionConvertVisitor.getSparqlQuery(d); System.out.println(d); System.out.println(query); @@ -87,10 +104,11 @@ */ public void visit(ObjectSomeRestriction description) { System.out.println("ObjectSomeRestriction"); - query+="?"+description.getSparqlVar()+" <"+description.getRole()+"> ?object"+currentObject+"."; - description.getChild(0).setSparqlVar("object"+currentObject); + query+="?"+stack.peek()+" <"+description.getRole()+"> ?object"+currentObject+"."; + stack.push("object"+currentObject); currentObject++; description.getChild(0).accept(this); + stack.pop(); System.out.println(description.getRole()); System.out.println(description.getChild(0)); } @@ -173,7 +191,7 @@ */ public void visit(NamedClass description) { System.out.println("NamedClass"); - query+="?"+description.getSparqlVar()+" a <"+description.getName()+">"; + query+="?"+stack.peek()+" a <"+description.getName()+">"; } /* (non-Javadoc) Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java 2008-03-27 08:26:58 UTC (rev 731) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java 2008-03-27 13:26:15 UTC (rev 732) @@ -522,10 +522,10 @@ } @WebMethod - public int sparqlQueryThreaded(int sessionID, int componentID, final String query) throws ClientNotKnownException + public int sparqlQueryThreaded(int sessionID, int componentID, String query) throws ClientNotKnownException { final ClientState state = getState(sessionID); - final Component component = state.getComponent(componentID); + Component component = state.getComponent(componentID); final int id=state.addQuery(((SparqlKnowledgeSource)component).sparqlQueryThreaded(query)); Thread sparqlThread = new Thread() { @Override @@ -591,10 +591,11 @@ } @WebMethod - public String getSparqlForConcept(int id) throws ClientNotKnownException { + public void SparqlRetrievalThreaded(int id, int componentID, String conceptString) throws ClientNotKnownException, ParseException { ClientState state = getState(id); - Description solution=state.getLearningAlgorithm().getBestSolution(); - return SparqlQueryDescriptionConvertVisitor.getSparqlQuery(solution); + // call parser to parse concept + String sparqlQuery = SparqlQueryDescriptionConvertVisitor.getSparqlQuery(conceptString); + sparqlQueryThreaded(id, componentID,sparqlQuery); } @WebMethod This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2008-03-31 14:36:15
|
Revision: 744 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=744&view=rev Author: jenslehmann Date: 2008-03-31 07:36:13 -0700 (Mon, 31 Mar 2008) Log Message: ----------- fix for #1928052 Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/core/ComponentManager.java trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java Modified: trunk/src/dl-learner/org/dllearner/core/ComponentManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-03-31 14:30:50 UTC (rev 743) +++ trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-03-31 14:36:13 UTC (rev 744) @@ -71,7 +71,7 @@ // you can either use the components.ini file or directly specify the classes to use private static String componentsFile = "lib/components.ini"; private static String[] componentClasses = new String[]{}; - private static ComponentManager cm = new ComponentManager(); + private static ComponentManager cm = null; // list of all configuration options of all components private static Map<Class<? extends Component>, String> componentNames; Modified: trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-31 14:30:50 UTC (rev 743) +++ trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-31 14:36:13 UTC (rev 744) @@ -27,6 +27,7 @@ import java.util.Comparator; import java.util.HashSet; import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; @@ -146,6 +147,9 @@ private Map<String, String> prefixes = new TreeMap<String,String>(); private String baseURI; + // references to OWL API ontologies + private List<OWLOntology> owlAPIOntologies = new LinkedList<OWLOntology>(); + public OWLAPIReasoner(Set<KnowledgeSource> sources) { this.sources = sources; } @@ -201,6 +205,7 @@ try { OWLOntology ontology = manager.loadOntologyFromPhysicalURI(url.toURI()); + owlAPIOntologies.add(ontology); allImports.addAll(manager.getImportsClosure(ontology)); classes.addAll(ontology.getReferencedClasses()); owlObjectProperties.addAll(ontology.getReferencedObjectProperties()); @@ -234,6 +239,7 @@ e.printStackTrace(); } OWLAPIAxiomConvertVisitor.fillOWLOntology(manager, ontology, kb); + owlAPIOntologies.add(ontology); allImports.add(ontology); atomicConcepts.addAll(kb.findAllAtomicConcepts()); atomicRoles.addAll(kb.findAllAtomicRoles()); @@ -1035,4 +1041,8 @@ } } + public List<OWLOntology> getOWLAPIOntologies() { + return owlAPIOntologies; + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-01 10:23:37
|
Revision: 745 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=745&view=rev Author: kurzum Date: 2008-04-01 03:23:30 -0700 (Tue, 01 Apr 2008) Log Message: ----------- added function getUsage() to components for writing a better doc file. implemented it in some component, where I was sure. added some output to ConfigOptionScriptGenerator, respectively to ComponentManager Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/ComponentManager.java trunk/src/dl-learner/org/dllearner/kb/KBFile.java trunk/src/dl-learner/org/dllearner/kb/OWLFile.java trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-04-01 10:23:30 UTC (rev 745) @@ -324,6 +324,10 @@ return "example driven refinement operator based learning algorithm"; } + public static String getUsage() { + return "algorithm = refexamples;"; + } + @Override public void start() { algorithm.start(); Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-04-01 10:23:30 UTC (rev 745) @@ -327,6 +327,10 @@ return "refinement operator based learning algorithm"; } + public static String getUsage() { + return "algorithm = refinement;"; + } + private int coveredNegativesOrTooWeak(Description concept) { if(posOnly) return posOnlyLearningProblem.coveredPseudoNegativeExamplesOrTooWeak(concept); Modified: trunk/src/dl-learner/org/dllearner/core/ComponentManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-04-01 10:23:30 UTC (rev 745) @@ -421,10 +421,24 @@ private String getComponentConfigString(Class<? extends Component> component) { String componentDescription = "component: " + invokeStaticMethod(component,"getName") + " (" + component.getName() + ")"; String str = componentDescription + "\n"; + String usage =""; + + usage = invokeStaticMethod(component,"getUsage")+""; + + + if(usage.equals("null")) { + System.out.println("Component "+component.getName()+" needs Usage definition"); + } + else { + System.out.println(usage +" |in| "+ component.getName()); + } + for(int i=0; i<componentDescription.length(); i++) str += "="; str += "\n\n"; + str += "Usage:\n"+usage+"\n\n"; + for(ConfigOption<?> option : componentOptions.get(component)) { str += option.toString() + "\n"; } Modified: trunk/src/dl-learner/org/dllearner/kb/KBFile.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/KBFile.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/kb/KBFile.java 2008-04-01 10:23:30 UTC (rev 745) @@ -82,6 +82,10 @@ public static String getName() { return "KB file"; } + + public static String getUsage() { + return "import(\"kbFileName.kb\");"; + } public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); Modified: trunk/src/dl-learner/org/dllearner/kb/OWLFile.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/OWLFile.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/kb/OWLFile.java 2008-04-01 10:23:30 UTC (rev 745) @@ -47,6 +47,11 @@ public static String getName() { return "OWL file"; } + + public static String getUsage() { + return "import(\"owlFileName.owl\");"; + } + public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); Modified: trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java 2008-04-01 10:23:30 UTC (rev 745) @@ -104,6 +104,9 @@ public static String getName() { return "SPARQL Endpoint"; } + public static String getUsage() { + return "Example: import(\"http://dbpedia.openlinksw.com:8890/sparql\",\"SPARQL\");"; + } private static Logger logger = Logger .getLogger(SparqlKnowledgeSource.class); Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java 2008-04-01 10:23:30 UTC (rev 745) @@ -64,6 +64,10 @@ public static String getName() { return "two valued definition learning problem"; } + + public static String getUsage() { + return "problem = XXX DEFAULT"; + } public static Collection<ConfigOption<?>> createConfigOptions() { return PosNegLP.createConfigOptions(); Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2008-04-01 10:23:30 UTC (rev 745) @@ -76,6 +76,11 @@ return "inclusion learning problem"; } + public static String getUsage() { + return "problem = posNegInclusion;"; + } + + /* * (non-Javadoc) * Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java 2008-04-01 10:23:30 UTC (rev 745) @@ -46,6 +46,10 @@ public static String getName() { return "positive only definition learning problem"; } + + public static String getUsage() { + return "problem = posOnlyDefinition;"; + } /* (non-Javadoc) * @see org.dllearner.core.Component#init() Modified: trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java 2008-04-01 10:23:30 UTC (rev 745) @@ -173,6 +173,10 @@ public static String getName() { return "DIG reasoner"; } + + public static String getUsage() { + return "reasoner = dig;"; + } public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-04-01 10:23:30 UTC (rev 745) @@ -133,6 +133,10 @@ return "fast instance checker"; } + public static String getUsage() { + return "reasoner = fastInstanceChecker;"; + } + /* * (non-Javadoc) * Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java 2008-04-01 10:23:30 UTC (rev 745) @@ -150,8 +150,12 @@ public static String getName() { return "fast retrieval reasoner"; - } + } + public static String getUsage() { + return "reasoner = XXX;"; + } + /* (non-Javadoc) * @see org.dllearner.core.Component#applyConfigEntry(org.dllearner.core.ConfigEntry) */ Modified: trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-03-31 14:36:13 UTC (rev 744) +++ trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-04-01 10:23:30 UTC (rev 745) @@ -158,6 +158,10 @@ return "OWL API reasoner"; } + public static String getUsage() { + return "reasoner = owlAPI;"; + } + public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); StringConfigOption type = new StringConfigOption("reasonerType", "FaCT++ or Pellet", "pellet"); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-01 10:46:17
|
Revision: 747 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=747&view=rev Author: kurzum Date: 2008-04-01 03:46:11 -0700 (Tue, 01 Apr 2008) Log Message: ----------- rollback Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/core/ComponentManager.java trunk/src/dl-learner/org/dllearner/kb/KBFile.java trunk/src/dl-learner/org/dllearner/kb/OWLFile.java trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java Modified: trunk/src/dl-learner/org/dllearner/core/ComponentManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-04-01 10:46:11 UTC (rev 747) @@ -423,21 +423,22 @@ String str = componentDescription + "\n"; String usage =""; - usage = invokeStaticMethod(component,"getUsage")+""; + //usage = invokeStaticMethod(component,"getUsage")+""; - if(usage.equals("null")) { + /*if(usage.equals("null")) { System.out.println("Component "+component.getName()+" needs Usage definition"); } else { System.out.println(usage +" |in| "+ component.getName()); } + */ for(int i=0; i<componentDescription.length(); i++) str += "="; str += "\n\n"; - str += "Usage:\n"+usage+"\n\n"; + //str += "Usage:\n"+usage+"\n\n"; for(ConfigOption<?> option : componentOptions.get(component)) { str += option.toString() + "\n"; Modified: trunk/src/dl-learner/org/dllearner/kb/KBFile.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/KBFile.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/kb/KBFile.java 2008-04-01 10:46:11 UTC (rev 747) @@ -83,9 +83,6 @@ return "KB file"; } - public static String getUsage() { - return "import(\"kbFileName.kb\");"; - } public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); Modified: trunk/src/dl-learner/org/dllearner/kb/OWLFile.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/OWLFile.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/kb/OWLFile.java 2008-04-01 10:46:11 UTC (rev 747) @@ -48,9 +48,6 @@ return "OWL file"; } - public static String getUsage() { - return "import(\"owlFileName.owl\");"; - } public static Collection<ConfigOption<?>> createConfigOptions() { Modified: trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/kb/sparql/SparqlKnowledgeSource.java 2008-04-01 10:46:11 UTC (rev 747) @@ -104,9 +104,7 @@ public static String getName() { return "SPARQL Endpoint"; } - public static String getUsage() { - return "Example: import(\"http://dbpedia.openlinksw.com:8890/sparql\",\"SPARQL\");"; - } + private static Logger logger = Logger .getLogger(SparqlKnowledgeSource.class); Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java 2008-04-01 10:46:11 UTC (rev 747) @@ -65,9 +65,6 @@ return "two valued definition learning problem"; } - public static String getUsage() { - return "problem = XXX DEFAULT"; - } public static Collection<ConfigOption<?>> createConfigOptions() { return PosNegLP.createConfigOptions(); Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2008-04-01 10:46:11 UTC (rev 747) @@ -76,11 +76,7 @@ return "inclusion learning problem"; } - public static String getUsage() { - return "problem = posNegInclusion;"; - } - - + /* * (non-Javadoc) * Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java 2008-04-01 10:46:11 UTC (rev 747) @@ -46,10 +46,7 @@ public static String getName() { return "positive only definition learning problem"; } - - public static String getUsage() { - return "problem = posOnlyDefinition;"; - } + /* (non-Javadoc) * @see org.dllearner.core.Component#init() Modified: trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/reasoning/DIGReasoner.java 2008-04-01 10:46:11 UTC (rev 747) @@ -174,9 +174,6 @@ return "DIG reasoner"; } - public static String getUsage() { - return "reasoner = dig;"; - } public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastInstanceChecker.java 2008-04-01 10:46:11 UTC (rev 747) @@ -133,10 +133,7 @@ return "fast instance checker"; } - public static String getUsage() { - return "reasoner = fastInstanceChecker;"; - } - + /* * (non-Javadoc) * Modified: trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/reasoning/FastRetrievalReasoner.java 2008-04-01 10:46:11 UTC (rev 747) @@ -152,10 +152,8 @@ return "fast retrieval reasoner"; } - public static String getUsage() { - return "reasoner = XXX;"; - } + /* (non-Javadoc) * @see org.dllearner.core.Component#applyConfigEntry(org.dllearner.core.ConfigEntry) */ Modified: trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-04-01 10:24:36 UTC (rev 746) +++ trunk/src/dl-learner/org/dllearner/reasoning/OWLAPIReasoner.java 2008-04-01 10:46:11 UTC (rev 747) @@ -158,9 +158,6 @@ return "OWL API reasoner"; } - public static String getUsage() { - return "reasoner = owlAPI;"; - } public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-02 10:31:33
|
Revision: 750 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=750&view=rev Author: kurzum Date: 2008-04-02 03:31:31 -0700 (Wed, 02 Apr 2008) Log Message: ----------- some more changes to the option doc generator, still not perfect Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/cli/Start.java trunk/src/dl-learner/org/dllearner/core/ComponentManager.java trunk/src/dl-learner/org/dllearner/core/config/ConfigOption.java Modified: trunk/src/dl-learner/org/dllearner/cli/Start.java =================================================================== --- trunk/src/dl-learner/org/dllearner/cli/Start.java 2008-04-01 11:48:39 UTC (rev 749) +++ trunk/src/dl-learner/org/dllearner/cli/Start.java 2008-04-02 10:31:31 UTC (rev 750) @@ -224,9 +224,12 @@ componentPrefixMapping.put(SparqlKnowledgeSource.class, "sparql"); // reasoners componentPrefixMapping.put(DIGReasoner.class, "digReasoner"); + componentPrefixMapping.put(FastInstanceChecker.class, "fastInstanceChecker"); componentPrefixMapping.put(OWLAPIReasoner.class, "owlAPIReasoner"); // learning problems - configured via + and - flags for examples componentPrefixMapping.put(PosNegDefinitionLP.class, "posNegDefinitionLP"); + componentPrefixMapping.put(PosNegInclusionLP.class, "posNegInclusionLP"); + componentPrefixMapping.put(PosOnlyDefinitionLP.class, "posOnlyDefinitionLP"); // learning algorithms componentPrefixMapping.put(ROLearner.class, "refinement"); componentPrefixMapping.put(ExampleBasedROLComponent.class, "refexamples"); Modified: trunk/src/dl-learner/org/dllearner/core/ComponentManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-04-01 11:48:39 UTC (rev 749) +++ trunk/src/dl-learner/org/dllearner/core/ComponentManager.java 2008-04-02 10:31:31 UTC (rev 750) @@ -40,6 +40,7 @@ import java.util.TreeMap; import java.util.TreeSet; +import org.dllearner.cli.Start; import org.dllearner.core.config.ConfigEntry; import org.dllearner.core.config.ConfigOption; import org.dllearner.core.config.InvalidConfigOptionValueException; @@ -421,31 +422,43 @@ private String getComponentConfigString(Class<? extends Component> component) { String componentDescription = "component: " + invokeStaticMethod(component,"getName") + " (" + component.getName() + ")"; String str = componentDescription + "\n"; + String CLI = getCLIMapping(component.getSuperclass().getSimpleName()+""); String usage =""; - //usage = invokeStaticMethod(component,"getUsage")+""; - - - /*if(usage.equals("null")) { - System.out.println("Component "+component.getName()+" needs Usage definition"); + Map<Class<? extends Component>, String> m=Start.createComponentPrefixMapping(); + for (Class<? extends Component> c : m.keySet()) { + if(c.getCanonicalName().equals(component.getCanonicalName())) + { usage=m.get(c); + } } - else { - System.out.println(usage +" |in| "+ component.getName()); + + for(int i=0; i<componentDescription.length(); i++) { + str += "="; } - */ - - for(int i=0; i<componentDescription.length(); i++) - str += "="; str += "\n\n"; + str += "CLI usage: "+CLI+" = "+usage+";\n\n"; - //str += "Usage:\n"+usage+"\n\n"; for(ConfigOption<?> option : componentOptions.get(component)) { - str += option.toString() + "\n"; + str += option.toString() + + "CLI usage: "+usage+"."+ + option.getName()+" = "+option.getDefaultValue()+ + ";\n\n"; } - return str; + return str+"\n"; } + public static String getCLIMapping(String componentSuperClass){ + HashMap<String, String> m = new HashMap<String, String>(); + m.put("KnowledgeSource", "import"); + m.put("ReasonerComponent", "reasoner"); + m.put("PosNegLP", "problem"); + m.put("PosOnlyLP", "problem"); + m.put("LearningAlgorithm", "algorithm"); + return m.get(componentSuperClass); + } + + private Object invokeStaticMethod(Class<?> clazz, String methodName, Object... args) { // unfortunately Java does not seem to offer a way to call // a static method given a class object directly, so we have Modified: trunk/src/dl-learner/org/dllearner/core/config/ConfigOption.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/config/ConfigOption.java 2008-04-01 11:48:39 UTC (rev 749) +++ trunk/src/dl-learner/org/dllearner/core/config/ConfigOption.java 2008-04-02 10:31:31 UTC (rev 750) @@ -77,10 +77,12 @@ public abstract boolean isValidValue(T value); + //TODO maybe change the function getClass in the options to get simpleName public String getAllowedValuesDescription() { return getClass().toString(); } + @Override public String toString() { return "option name: " + name + "\ndescription: " + description + "\nvalues: " This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-03 14:03:33
|
Revision: 764 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=764&view=rev Author: kurzum Date: 2008-04-03 07:03:19 -0700 (Thu, 03 Apr 2008) Log Message: ----------- some minor changes, verification works now with kb parse, but still yields strange results Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/Info.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java trunk/src/dl-learner/org/dllearner/core/owl/Thing.java trunk/src/dl-learner/org/dllearner/examples/KRK.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java Removed Paths: ------------- trunk/src/dl-learner/org/dllearner/examples/OntologyCloser.java Modified: trunk/src/dl-learner/org/dllearner/Info.java =================================================================== --- trunk/src/dl-learner/org/dllearner/Info.java 2008-04-03 11:57:35 UTC (rev 763) +++ trunk/src/dl-learner/org/dllearner/Info.java 2008-04-03 14:03:19 UTC (rev 764) @@ -3,6 +3,6 @@ package org.dllearner; public class Info { - public static final String build = "2008-03-16"; + public static final String build = "2008-03-31"; } \ No newline at end of file Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-03 11:57:35 UTC (rev 763) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-03 14:03:19 UTC (rev 764) @@ -386,8 +386,11 @@ logger.info("\nsolutions:"); for(Description c : solutions) { logger.info(" " + c + " (length " + c.getLength() +", depth " + c.getDepth() + ")"); - //TODO remove this line - logger.info(" MANCHESTER: " + c.toManchesterSyntaxString(baseURI, new HashMap<String,String>()) ); + //TODO remove this line maybe + // watch for String.replace Quick hack + logger.info(" MANCHESTER: " + + c.toManchesterSyntaxString(baseURI, new HashMap<String,String>()). + replace("\"", "")); } } logger.debug("size of candidate set: " + candidates.size()); Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-04-03 11:57:35 UTC (rev 763) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-04-03 14:03:19 UTC (rev 764) @@ -513,7 +513,11 @@ logger.info("\nsolutions:"); for(Description c : solutions) { logger.info(" " + c + " (length " + c.getLength() +", depth " + c.getDepth() + ")"); - logger.info(" MANCHESTER: " + c.toManchesterSyntaxString(baseURI, new HashMap<String,String>()) ); + //TODO remove this line maybe + // watch for String.replace Quick hack + logger.info(" MANCHESTER: " + + c.toManchesterSyntaxString(baseURI, new HashMap<String,String>()). + replace("\"", "")); } } logger.info(" horizontal expansion: " + minimumHorizontalExpansion + " to " + maximumHorizontalExpansion); Modified: trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java 2008-04-03 11:57:35 UTC (rev 763) +++ trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java 2008-04-03 14:03:19 UTC (rev 764) @@ -40,8 +40,10 @@ */ @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { - // TODO: check whether this is correct - return "owl:Nothing"; + // in Protege 3.3 owl:Nothing + // in Protege 4.0 only Nothing + //return "owl:Nothing"; + return "Nothing"; } public int getLength() { Modified: trunk/src/dl-learner/org/dllearner/core/owl/Thing.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Thing.java 2008-04-03 11:57:35 UTC (rev 763) +++ trunk/src/dl-learner/org/dllearner/core/owl/Thing.java 2008-04-03 14:03:19 UTC (rev 764) @@ -44,7 +44,11 @@ @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { - return "owl:Thing"; + // in Protege 3.3 owl:Thing + // in Protege 4.0 only Thing + //return "owl:Thing"; + return "Thing"; + } public int getLength() { Modified: trunk/src/dl-learner/org/dllearner/examples/KRK.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-03 11:57:35 UTC (rev 763) +++ trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-03 14:03:19 UTC (rev 764) @@ -30,6 +30,7 @@ import org.dllearner.core.owl.SymmetricObjectPropertyAxiom; import org.dllearner.core.owl.TransitiveObjectPropertyAxiom; import org.dllearner.reasoning.OWLAPIReasoner; +import org.dllearner.utilities.OntologyCloser; /* * Structure @@ -223,14 +224,37 @@ writeOWLFile("test.owl"); } if(writeClosedOWL) { + OntologyCloser oc = new OntologyCloser(kb); + oc.applyNumberRestrictions(); + + String conceptStr = "ALL \"http://www.test.de/test#hasPiece\".(EXISTS \"http://www.test.de/test#fileDistanceLessThan6\".((NOT \"http://www.test.de/test#WKing\") AND ALL \"http://www.test.de/test#rankDistance1\".(\"http://www.test.de/test#WKing\" AND ALL \"http://www.test.de/test#fileDistanceLessThan2\".\"http://www.test.de/test#BKing\" AND ALL \"http://www.test.de/test#hasLowerFileThan\".\"http://www.test.de/test#WKing\")) AND ALL \"http://www.test.de/test#fileDistance1\".\"http://www.test.de/test#WRook\")"; //conceptStr = "ALL http://www.test.de/test#hasPiece.(EXISTS http://www.test.de/test#fileDistanceLessThan6.((NOT http://www.test.de/test#WKing) AND ALL http://www.test.de/test#rankDistance1.(http://www.test.de/test#WKing AND ALL http://www.test.de/test#fileDistanceLessThan2.http://www.test.de/test#WKing AND ALL http://www.test.de/test#hasLowerFileThan.http://www.test.de/test#WKing)) AND ALL http://www.test.de/test#fileDistance1.http://www.test.de/test#WRook)"; //conceptStr = "ALL hasPiece.(EXISTS fileDistanceLessThan6.((NOT WKing) AND ALL rankDistance1.(WKing AND ALL fileDistanceLessThan2.WKing AND ALL hasLowerFileThan.WKing)) AND ALL fileDistance1.WRook)"; - conceptStr = "ALL \"http://www.test.de/test#hasPiece\".\"http://www.test.de/test#WKing\""; - OntologyCloser oc = new OntologyCloser(kb); - oc.applyNumberRestrictions(); + //conceptStr = "ALL \"http://www.test.de/test#hasPiece\".\"http://www.test.de/test#WKing\""; + //conceptStr = "EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#hasLowerRankThan\".(\"http://www.test.de/test#WRook\" AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\")"; + + + conceptStr = "\"http://www.test.de/test#WRook\""; + oc.verifyConcept(conceptStr); - writeOWLFile("test_Closed.owl"); + conceptStr = "ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + + "\"http://www.test.de/test#WKing\" "; + + oc.verifyConcept(conceptStr); + conceptStr = "(\"http://www.test.de/test#WRook\" "+ + " AND " + + " ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + + "\"http://www.test.de/test#WKing\") "; + + oc.verifyConcept(conceptStr); + conceptStr = "EXISTS \"http://www.test.de/test#hasLowerRankThan\"."+ + "(\"http://www.test.de/test#WRook\""+ + "AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\") "; + + + oc.verifyConcept(conceptStr); + //writeOWLFile("test_Closed.owl"); } } catch (Exception e) { Deleted: trunk/src/dl-learner/org/dllearner/examples/OntologyCloser.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/OntologyCloser.java 2008-04-03 11:57:35 UTC (rev 763) +++ trunk/src/dl-learner/org/dllearner/examples/OntologyCloser.java 2008-04-03 14:03:19 UTC (rev 764) @@ -1,102 +0,0 @@ -package org.dllearner.examples; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; - -import org.dllearner.core.KnowledgeSource; -import org.dllearner.core.ReasoningService; -import org.dllearner.core.owl.ClassAssertionAxiom; -import org.dllearner.core.owl.Description; -import org.dllearner.core.owl.Individual; -import org.dllearner.core.owl.KB; -import org.dllearner.core.owl.ObjectExactCardinalityRestriction; -import org.dllearner.core.owl.ObjectProperty; -import org.dllearner.core.owl.PropertyAxiom; -import org.dllearner.core.owl.Thing; -import org.dllearner.kb.KBFile; -import org.dllearner.parser.KBParser; -import org.dllearner.reasoning.OWLAPIReasoner; - -public class OntologyCloser { - KB kb; - KBFile kbFile; - Set<KnowledgeSource> ks; - ReasoningService rs; - - public OntologyCloser(KB kb) { - super(); - this.kb = kb; - this.kbFile = new KBFile(this.kb); - this.ks = new HashSet<KnowledgeSource>(); - this.ks.add(this.kbFile); - OWLAPIReasoner owlapi = new OWLAPIReasoner(ks); - owlapi.init(); - - this.rs = new ReasoningService(owlapi); - - } - - /** - * counts the number of roles used by each individual and assigns - * ExactCardinalityRestriction - */ - public void applyNumberRestrictions() { - Set<ObjectProperty> allRoles = this.rs.getAtomicRoles(); - // Set<Individual> allind = this.rs.getIndividuals(); - Set<PropertyAxiom> ax = kb.getRbox(); - for (PropertyAxiom propertyAxiom : ax) { - if (propertyAxiom.getClass().getSimpleName().equals( - "TransitiveObjectPropertyAxiom")) { - - System.out - .println("WARNING transitive object property can't be used in cardinality restriction\n" - + propertyAxiom.toString()); - } - } - - for (ObjectProperty oneRole : allRoles) { - - // System.out.println(oneRole.getClass()); - Map<Individual, SortedSet<Individual>> allRoleMembers = this.rs - .getRoleMembers(oneRole); - for (Individual oneInd : allRoleMembers.keySet()) { - SortedSet<Individual> fillers = allRoleMembers.get(oneInd); - if (fillers.size() > 0) { - ObjectExactCardinalityRestriction oecr = new ObjectExactCardinalityRestriction( - fillers.size(), oneRole, new Thing()); - kb.addABoxAxiom(new ClassAssertionAxiom(oecr, oneInd)); - } - } - - } - // System.out.println("good ontology? " + rs.isSatisfiable()); - - } - - public static void closeKB(KB kb) { - new OntologyCloser(kb).applyNumberRestrictions(); - } - - public void verifyConcept(String conceptStr) { - Description d; - StringBuffer sb = new StringBuffer(); - sb.append(conceptStr); - conceptStr = sb.toString(); - try { - d = KBParser.parseConcept(conceptStr); - System.out.println("Starting retrieval"); - SortedSet<Individual> ind = this.rs.retrieval(d); - System.out.println("retrieved: " + ind.size() + " instances"); - - for (Individual individual : ind) { - System.out.println(individual + ""); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} Copied: trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java (from rev 760, trunk/src/dl-learner/org/dllearner/examples/OntologyCloser.java) =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java 2008-04-03 14:03:19 UTC (rev 764) @@ -0,0 +1,105 @@ +package org.dllearner.utilities; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; + +import org.dllearner.core.KnowledgeSource; +import org.dllearner.core.ReasoningService; +import org.dllearner.core.owl.ClassAssertionAxiom; +import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.Individual; +import org.dllearner.core.owl.KB; +import org.dllearner.core.owl.ObjectExactCardinalityRestriction; +import org.dllearner.core.owl.ObjectProperty; +import org.dllearner.core.owl.PropertyAxiom; +import org.dllearner.core.owl.Thing; +import org.dllearner.kb.KBFile; +import org.dllearner.parser.KBParser; +import org.dllearner.reasoning.OWLAPIReasoner; + +public class OntologyCloser { + KB kb; + KBFile kbFile; + Set<KnowledgeSource> ks; + ReasoningService rs; + + public OntologyCloser(KB kb) { + super(); + this.kb = kb; + this.kbFile = new KBFile(this.kb); + this.ks = new HashSet<KnowledgeSource>(); + this.ks.add(this.kbFile); + OWLAPIReasoner owlapi = new OWLAPIReasoner(ks); + owlapi.init(); + + this.rs = new ReasoningService(owlapi); + + } + + /** + * counts the number of roles used by each individual and assigns + * ExactCardinalityRestriction + */ + public void applyNumberRestrictions() { + Set<ObjectProperty> allRoles = this.rs.getAtomicRoles(); + // Set<Individual> allind = this.rs.getIndividuals(); + Set<PropertyAxiom> ax = kb.getRbox(); + for (PropertyAxiom propertyAxiom : ax) { + if (propertyAxiom.getClass().getSimpleName().equals( + "TransitiveObjectPropertyAxiom")) { + + System.out + .println("WARNING transitive object property can't be used in cardinality restriction\n" + + propertyAxiom.toString()); + } + } + + for (ObjectProperty oneRole : allRoles) { + + // System.out.println(oneRole.getClass()); + Map<Individual, SortedSet<Individual>> allRoleMembers = this.rs + .getRoleMembers(oneRole); + for (Individual oneInd : allRoleMembers.keySet()) { + SortedSet<Individual> fillers = allRoleMembers.get(oneInd); + if (fillers.size() > 0) { + ObjectExactCardinalityRestriction oecr = new ObjectExactCardinalityRestriction( + fillers.size(), oneRole, new Thing()); + kb.addABoxAxiom(new ClassAssertionAxiom(oecr, oneInd)); + } + } + + } + // System.out.println("good ontology? " + rs.isSatisfiable()); + + } + + public static void closeKB(KB kb) { + new OntologyCloser(kb).applyNumberRestrictions(); + } + + public void verifyConcept(String conceptStr) { + Description d; + StringBuffer sb = new StringBuffer(); + sb.append(conceptStr); + conceptStr = sb.toString(); + try { + d = KBParser.parseConcept(conceptStr); + System.out.println(d.toManchesterSyntaxString("", new HashMap<String,String>())); + System.out.println(d.toString()); + System.out.println("Starting retrieval"); + SortedSet<Individual> ind = this.rs.retrieval(d); + System.out.println("retrieved: " + ind.size() + " instances"); + + //for (Individual individual : ind) { + //System.out.println(individual + ""); + //} + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-07 07:48:13
|
Revision: 769 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=769&view=rev Author: kurzum Date: 2008-04-07 00:48:07 -0700 (Mon, 07 Apr 2008) Log Message: ----------- script and classes for closing ontologies Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/examples/KRK.java trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/utilities/CloseOntology.java trunk/src/dl-learner/org/dllearner/utilities/OntologyCloserOWLAPI.java trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java Modified: trunk/src/dl-learner/org/dllearner/examples/KRK.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-07 07:46:21 UTC (rev 768) +++ trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-07 07:48:07 UTC (rev 769) @@ -7,6 +7,7 @@ import java.io.FileReader; import java.io.IOException; import java.net.URI; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.SortedSet; @@ -50,9 +51,16 @@ // // turn off to not write the owl, needs about 30 seconds or more static boolean writeOWL = true; - static boolean writeClosedOWL = true ; static boolean useTransitivity = false; + static boolean writeExampleSets = true; + static boolean writeConciseOWLAllDifferent = false; + + static boolean closeKB=true; + static boolean closeConcise= true && closeKB; + static boolean writeClosedOWL = true && closeKB; + static boolean verifySomeConcepts = false && closeKB; + static boolean useInverse = false; // dependent, love and marriage, horse and carriage @@ -216,53 +224,116 @@ finishBackgroundForRoles(); System.out.println("Finished Background"); // WRITE - writeExampleSets(); - writeConciseOWLAllDifferent(); + if(writeExampleSets)writeExampleSets(); + if(writeConciseOWLAllDifferent)writeConciseOWLAllDifferent(); + if (writeOWL)writeOWLFile("test.owl"); - - if (writeOWL) { - writeOWLFile("test.owl"); + OntologyCloser oc = new OntologyCloser(kb); + String kbaddition= "_Closed"; + if(closeKB) { + + if(closeConcise) { + oc.applyNumberRestrictionsNamed(); + kbaddition = "_CloseConcise"; + } + else oc.applyNumberRestrictions(); } - if(writeClosedOWL) { - OntologyCloser oc = new OntologyCloser(kb); - oc.applyNumberRestrictions(); - - String conceptStr = "ALL \"http://www.test.de/test#hasPiece\".(EXISTS \"http://www.test.de/test#fileDistanceLessThan6\".((NOT \"http://www.test.de/test#WKing\") AND ALL \"http://www.test.de/test#rankDistance1\".(\"http://www.test.de/test#WKing\" AND ALL \"http://www.test.de/test#fileDistanceLessThan2\".\"http://www.test.de/test#BKing\" AND ALL \"http://www.test.de/test#hasLowerFileThan\".\"http://www.test.de/test#WKing\")) AND ALL \"http://www.test.de/test#fileDistance1\".\"http://www.test.de/test#WRook\")"; - //conceptStr = "ALL http://www.test.de/test#hasPiece.(EXISTS http://www.test.de/test#fileDistanceLessThan6.((NOT http://www.test.de/test#WKing) AND ALL http://www.test.de/test#rankDistance1.(http://www.test.de/test#WKing AND ALL http://www.test.de/test#fileDistanceLessThan2.http://www.test.de/test#WKing AND ALL http://www.test.de/test#hasLowerFileThan.http://www.test.de/test#WKing)) AND ALL http://www.test.de/test#fileDistance1.http://www.test.de/test#WRook)"; - //conceptStr = "ALL hasPiece.(EXISTS fileDistanceLessThan6.((NOT WKing) AND ALL rankDistance1.(WKing AND ALL fileDistanceLessThan2.WKing AND ALL hasLowerFileThan.WKing)) AND ALL fileDistance1.WRook)"; - //conceptStr = "ALL \"http://www.test.de/test#hasPiece\".\"http://www.test.de/test#WKing\""; - //conceptStr = "EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#hasLowerRankThan\".(\"http://www.test.de/test#WRook\" AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\")"; - - conceptStr = "\"http://www.test.de/test#WRook\""; + if (verifySomeConcepts) verifySomeConcepts(oc); + if (writeClosedOWL) writeOWLFile("test"+kbaddition+".owl"); - oc.verifyConcept(conceptStr); - conceptStr = "ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + - "\"http://www.test.de/test#WKing\" "; - - oc.verifyConcept(conceptStr); - conceptStr = "(\"http://www.test.de/test#WRook\" "+ - " AND " + - " ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + - "\"http://www.test.de/test#WKing\") "; - - oc.verifyConcept(conceptStr); - conceptStr = "EXISTS \"http://www.test.de/test#hasLowerRankThan\"."+ - "(\"http://www.test.de/test#WRook\""+ - "AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\") "; - - - oc.verifyConcept(conceptStr); - //writeOWLFile("test_Closed.owl"); - } - } catch (Exception e) { e.printStackTrace(); } System.out.println("Done"); }// end main + + protected static void verifySomeConcepts(OntologyCloser oc) { + + ArrayList<String> test=new ArrayList<String>(); + + //String conceptStr = "ALL \"http://www.test.de/test#hasPiece\".(EXISTS \"http://www.test.de/test#fileDistanceLessThan6\".((NOT \"http://www.test.de/test#WKing\") AND ALL \"http://www.test.de/test#rankDistance1\".(\"http://www.test.de/test#WKing\" AND ALL \"http://www.test.de/test#fileDistanceLessThan2\".\"http://www.test.de/test#BKing\" AND ALL \"http://www.test.de/test#hasLowerFileThan\".\"http://www.test.de/test#WKing\")) AND ALL \"http://www.test.de/test#fileDistance1\".\"http://www.test.de/test#WRook\")"; + //conceptStr = "ALL http://www.test.de/test#hasPiece.(EXISTS http://www.test.de/test#fileDistanceLessThan6.((NOT http://www.test.de/test#WKing) AND ALL http://www.test.de/test#rankDistance1.(http://www.test.de/test#WKing AND ALL http://www.test.de/test#fileDistanceLessThan2.http://www.test.de/test#WKing AND ALL http://www.test.de/test#hasLowerFileThan.http://www.test.de/test#WKing)) AND ALL http://www.test.de/test#fileDistance1.http://www.test.de/test#WRook)"; + //conceptStr = "ALL hasPiece.(EXISTS fileDistanceLessThan6.((NOT WKing) AND ALL rankDistance1.(WKing AND ALL fileDistanceLessThan2.WKing AND ALL hasLowerFileThan.WKing)) AND ALL fileDistance1.WRook)"; + //conceptStr = "ALL \"http://www.test.de/test#hasPiece\".\"http://www.test.de/test#WKing\""; + //conceptStr = "EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#hasLowerRankThan\".(\"http://www.test.de/test#WRook\" AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\")"; + + + test.add("\"http://www.test.de/test#WRook\""); + /*test.add("ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + + "\"http://www.test.de/test#WKing\""); + /*test.add("(\"http://www.test.de/test#WRook\" "+ + " AND " + + " ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + + "\"http://www.test.de/test#WKing\") ");*/ + /*test.add("(\"http://www.test.de/test#Piece\" "+ + " AND " + + " ALL \"http://www.test.de/test#fileDistanceLessThan8\"." + + "\"http://www.test.de/test#Piece\") "); + test.add("(\"http://www.test.de/test#Piece\" "+ + " AND ( " + + " ALL \"http://www.test.de/test#fileDistanceLessThan8\"." + + "\"http://www.test.de/test#Piece\" " + + " AND " + + " EXISTS \"http://www.test.de/test#fileDistanceLessThan8\"." + + "\"http://www.test.de/test#Piece\"))") ; + test.add("(\"http://www.test.de/test#Piece\" "+ + " AND ( " + + " ALL \"http://www.test.de/test#fileDistanceLessThan7\"." + + "\"http://www.test.de/test#Piece\" " + + " AND " + + " EXISTS \"http://www.test.de/test#fileDistanceLessThan7\"." + + "\"http://www.test.de/test#Piece\"))") ; + test.add("(\"http://www.test.de/test#Piece\" "+ + " AND ( " + + " ALL \"http://www.test.de/test#fileDistanceLessThan5\"." + + "\"http://www.test.de/test#Piece\" " + + " AND " + + " EXISTS \"http://www.test.de/test#fileDistanceLessThan5\"." + + "\"http://www.test.de/test#Piece\"))") ;*/ + test.add("(\"http://www.test.de/test#Piece\" "+ + " AND ( " + + " ALL \"http://www.test.de/test#fileDistanceLessThan3\"." + + "\"http://www.test.de/test#Piece\" " + + " AND " + + " EXISTS \"http://www.test.de/test#fileDistanceLessThan3\"." + + "\"http://www.test.de/test#Piece\"))") ; + test.add("(\"http://www.test.de/test#BKing\" "+ + " AND ( " + + " ALL \"http://www.test.de/test#fileDistanceLessThan3\"." + + "\"http://www.test.de/test#Piece\" " + + " AND " + + " EXISTS \"http://www.test.de/test#fileDistanceLessThan3\"." + + "\"http://www.test.de/test#Piece\"))") ; + test.add("(\"http://www.test.de/test#BKing\" "+ + " AND ( " + + " ALL \"http://www.test.de/test#fileDistanceLessThan2\"." + + "\"http://www.test.de/test#Piece\" " + + " AND " + + " EXISTS \"http://www.test.de/test#fileDistanceLessThan2\"." + + "\"http://www.test.de/test#Piece\"))") ; + + /*test.add("(\"http://www.test.de/test#Piece\" "+ + " AND " + + " ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + + "\"http://www.test.de/test#WKing\") ");*/ + + for (int i = 0; i < test.size(); i++) { + String conceptStr = test.get(i); + oc.verifyConcept(conceptStr); + } + + + /*conceptStr = "EXISTS \"http://www.test.de/test#hasLowerRankThan\"."+ + "(\"http://www.test.de/test#WRook\""+ + "AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\") "; + + */ + System.out.println(); + } + static void makeDistanceRoles(KRKPiece A, KRKPiece B) { int Fdist = A.getFileDistance(B); int Rdist = A.getRankDistance(B); Added: trunk/src/dl-learner/org/dllearner/utilities/CloseOntology.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/CloseOntology.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/utilities/CloseOntology.java 2008-04-07 07:48:07 UTC (rev 769) @@ -0,0 +1,69 @@ +package org.dllearner.utilities; + +import java.io.File; +import java.net.URI; +import java.util.HashSet; +import java.util.Set; + +import org.dllearner.core.KnowledgeSource; +import org.dllearner.kb.OWLFile; +import org.dllearner.reasoning.OWLAPIReasoner; + +public class CloseOntology { + + /** + * @param args + */ + public static void main(String[] args) { + String ontopath="examples/krkworking/test.owl"; + ontopath = args[0]; + File file = new File(ontopath); + + //System.out.println(file.getAbsolutePath()); + System.out.println(file.toURI()); + + + try{ + URI inputURI = file.toURI(); + URI outputURI; + OWLFile owlFile=new OWLFile(); + owlFile.setURL(inputURI.toURL()); + + Set<KnowledgeSource> ks = new HashSet<KnowledgeSource>(); + ks.add(owlFile); + OWLAPIReasoner owlapireasoner = new OWLAPIReasoner(ks); + owlapireasoner.init(); + OntologyCloserOWLAPI oc= new OntologyCloserOWLAPI(owlapireasoner); + oc.testForTransitiveProperties(true); + String ending = ontopath.substring(ontopath.lastIndexOf(".") + 1); + /*ontopath=ontopath.replace("."+ending, "_test."+ending); + file=new File(ontopath); + URI outputURI = file.toURI(); + oc.writeOWLFile(outputURI);*/ + System.out.println("Attempting to close"); + oc.applyNumberRestrictionsConcise(); + System.out.println("Finished, preparing output"); + //String ending = ontopath.substring(ontopath.lastIndexOf(".") + 1); + ontopath=ontopath.replace("."+ending, "_closedConcise."+ending); + file=new File(ontopath); + outputURI = file.toURI(); + oc.writeOWLFile(outputURI); + + //ontopath=ontopath.replace("_closed."+ending, "_ClosedConcise."+ending); + //file=new File(ontopath); + //outputURI = file.toURI(); + //oc.writeOWLFile(outputURI); + + + //System.out.println(ontopath); + + /*manager.saveOntology(ontology, new OWLXMLOntologyFormat(), + physicalURI2); + + manager.removeOntology(ontology.getURI()); + */ + + }catch (Exception e) {e.printStackTrace();} + } + +} Modified: trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java 2008-04-07 07:46:21 UTC (rev 768) +++ trunk/src/dl-learner/org/dllearner/utilities/OntologyCloser.java 2008-04-07 07:48:07 UTC (rev 769) @@ -2,16 +2,21 @@ import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.SortedSet; +import java.util.TreeSet; import org.dllearner.core.KnowledgeSource; import org.dllearner.core.ReasoningService; import org.dllearner.core.owl.ClassAssertionAxiom; import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.EquivalentClassesAxiom; import org.dllearner.core.owl.Individual; +import org.dllearner.core.owl.Intersection; import org.dllearner.core.owl.KB; +import org.dllearner.core.owl.NamedClass; import org.dllearner.core.owl.ObjectExactCardinalityRestriction; import org.dllearner.core.owl.ObjectProperty; import org.dllearner.core.owl.PropertyAxiom; @@ -19,22 +24,31 @@ import org.dllearner.kb.KBFile; import org.dllearner.parser.KBParser; import org.dllearner.reasoning.OWLAPIReasoner; +import org.semanticweb.owl.model.OWLOntology; public class OntologyCloser { KB kb; KBFile kbFile; - Set<KnowledgeSource> ks; + OWLOntology onto; + OWLAPIReasoner reasoner; + boolean isKB = true; + + // Set<KnowledgeSource> ks; ReasoningService rs; + HashMap<Individual, Set<ObjectExactCardinalityRestriction>> indToRestr; + HashMap<Individual, Set<Description>> indToNamedClass; + HashSet<Description> classes; public OntologyCloser(KB kb) { super(); this.kb = kb; this.kbFile = new KBFile(this.kb); - this.ks = new HashSet<KnowledgeSource>(); - this.ks.add(this.kbFile); + Set<KnowledgeSource> ks = new HashSet<KnowledgeSource>(); + ks.add(this.kbFile); OWLAPIReasoner owlapi = new OWLAPIReasoner(ks); owlapi.init(); - + this.indToRestr = new HashMap<Individual, Set<ObjectExactCardinalityRestriction>>(); + this.classes = new HashSet<Description>(); this.rs = new ReasoningService(owlapi); } @@ -46,17 +60,38 @@ public void applyNumberRestrictions() { Set<ObjectProperty> allRoles = this.rs.getAtomicRoles(); // Set<Individual> allind = this.rs.getIndividuals(); - Set<PropertyAxiom> ax = kb.getRbox(); - for (PropertyAxiom propertyAxiom : ax) { - if (propertyAxiom.getClass().getSimpleName().equals( - "TransitiveObjectPropertyAxiom")) { + testForTransitiveProperties(true); - System.out - .println("WARNING transitive object property can't be used in cardinality restriction\n" - + propertyAxiom.toString()); + for (ObjectProperty oneRole : allRoles) { + + // System.out.println(oneRole.getClass()); + Map<Individual, SortedSet<Individual>> allRoleMembers = this.rs + .getRoleMembers(oneRole); + for (Individual oneInd : allRoleMembers.keySet()) { + SortedSet<Individual> fillers = allRoleMembers.get(oneInd); + if (fillers.size() > 0) { + ObjectExactCardinalityRestriction oecr = new ObjectExactCardinalityRestriction( + fillers.size(), oneRole, new Thing()); + kb.addABoxAxiom(new ClassAssertionAxiom(oecr, oneInd)); + } } + } + // System.out.println("good ontology? " + rs.isSatisfiable()); + } + + + + /** + * counts the number of roles used by each individual and assigns + * ExactCardinalityRestriction + */ + public void applyNumberRestrictionsConcise() { + Set<ObjectProperty> allRoles = this.rs.getAtomicRoles(); + // Set<Individual> allind = this.rs.getIndividuals(); + testForTransitiveProperties(true); + for (ObjectProperty oneRole : allRoles) { // System.out.println(oneRole.getClass()); @@ -67,39 +102,165 @@ if (fillers.size() > 0) { ObjectExactCardinalityRestriction oecr = new ObjectExactCardinalityRestriction( fillers.size(), oneRole, new Thing()); - kb.addABoxAxiom(new ClassAssertionAxiom(oecr, oneInd)); + // indToRestr.put(oneInd,) + collectExObjRestrForInd(oneInd, oecr); } } + // + + }// end for + + // Intersection intersection = null; + LinkedList<Description> ll = new LinkedList<Description>(); + Set<ObjectExactCardinalityRestriction> s = null; + + for (Individual oneInd : indToRestr.keySet()) { + s = indToRestr.get(oneInd); + for (ObjectExactCardinalityRestriction oecr : s) { + ll.add(oecr); + } + kb.addABoxAxiom(new ClassAssertionAxiom(new Intersection(ll), + oneInd)); + s = null; + ll = new LinkedList<Description>(); } + + // + // System.out.println("good ontology? " + rs.isSatisfiable()); } + + + /** + * counts the number of roles used by each individual and assigns + * ExactCardinalityRestriction + */ + public void applyNumberRestrictionsNamed() { + Set<ObjectProperty> allRoles = this.rs.getAtomicRoles(); + // Set<Individual> allind = this.rs.getIndividuals(); + testForTransitiveProperties(true); + + for (ObjectProperty oneRole : allRoles) { + + // System.out.println(oneRole.getClass()); + Map<Individual, SortedSet<Individual>> allRoleMembers = this.rs + .getRoleMembers(oneRole); + for (Individual oneInd : allRoleMembers.keySet()) { + SortedSet<Individual> fillers = allRoleMembers.get(oneInd); + //if (fillers.size() > 0) { + ObjectExactCardinalityRestriction oecr = new ObjectExactCardinalityRestriction( + fillers.size(), oneRole, new Thing()); + // indToRestr.put(oneInd,) + //make Description + Description d = new NamedClass(oneRole+"Exact"+fillers.size()+"gen"); + d.addChild(oecr); + kb.addTBoxAxiom(new EquivalentClassesAxiom(d,oecr)); + //System.out.println(d.toManchesterSyntaxString("", new HashMap<String, String>())); + kb.addABoxAxiom(new ClassAssertionAxiom(d,oneInd)); + //collectExObjRestrForInd(oneInd, oecr); + + } + + // + + }// end for + + // Intersection intersection = null; + /* + LinkedList<Description> ll = new LinkedList<Description>(); + Set<ObjectExactCardinalityRestriction> s = null; + + for (Individual oneInd : indToRestr.keySet()) { + s = indToRestr.get(oneInd); + for (ObjectExactCardinalityRestriction oecr : s) { + ll.add(oecr); + } + kb.addABoxAxiom(new ClassAssertionAxiom(new Intersection(ll), + oneInd)); + s = null; + ll = new LinkedList<Description>(); + }*/ + + // + + // System.out.println("good ontology? " + rs.isSatisfiable()); + + } + + public boolean testForTransitiveProperties(boolean printflag) { + boolean retval = false; + Set<PropertyAxiom> ax = kb.getRbox(); + for (PropertyAxiom propertyAxiom : ax) { + if (propertyAxiom.getClass().getSimpleName().equals( + "TransitiveObjectPropertyAxiom")) { + retval = true; + if (printflag) { + System.out + .println("WARNING transitive object property can't be used in cardinality restriction\n" + + propertyAxiom.toString()); + } + } + } + + return retval; + } + public static void closeKB(KB kb) { new OntologyCloser(kb).applyNumberRestrictions(); } - public void verifyConcept(String conceptStr) { + public SortedSet<Individual> verifyConcept(String conceptStr) { Description d; + SimpleClock sc = new SimpleClock(); StringBuffer sb = new StringBuffer(); sb.append(conceptStr); conceptStr = sb.toString(); + SortedSet<Individual> ind = new TreeSet<Individual>(); try { d = KBParser.parseConcept(conceptStr); - System.out.println(d.toManchesterSyntaxString("", new HashMap<String,String>())); - System.out.println(d.toString()); - System.out.println("Starting retrieval"); - SortedSet<Individual> ind = this.rs.retrieval(d); + System.out.println("\n*******************\nStarting retrieval"); + System.out.println(d.toManchesterSyntaxString("", + new HashMap<String, String>())); + // System.out.println(d.toString()); + sc.setTime(); + this.rs.retrieval(d); + System.out.println("retrieved: " + ind.size() + " instances"); + sc.printAndSet(); + for (Individual individual : ind) { + System.out.print(individual + "|"); + } - //for (Individual individual : ind) { - //System.out.println(individual + ""); - //} - } catch (Exception e) { e.printStackTrace(); } + return ind; } + private boolean collectExObjRestrForInd(Individual ind, + ObjectExactCardinalityRestriction oecr) { + Set<ObjectExactCardinalityRestriction> s = indToRestr.get(ind); + if (s == null) { + indToRestr.put(ind, + new HashSet<ObjectExactCardinalityRestriction>()); + s = indToRestr.get(ind); + } + return s.add(oecr); + } + + @SuppressWarnings("unused") + private boolean collectDescriptionForInd(Individual ind, + Description d) { + Set<Description> s = indToNamedClass.get(ind); + if (s == null) { + indToNamedClass.put(ind, + new HashSet<Description>()); + s = indToNamedClass.get(ind); + } + return s.add(d); + } + } Added: trunk/src/dl-learner/org/dllearner/utilities/OntologyCloserOWLAPI.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/OntologyCloserOWLAPI.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/utilities/OntologyCloserOWLAPI.java 2008-04-07 07:48:07 UTC (rev 769) @@ -0,0 +1,264 @@ +package org.dllearner.utilities; + +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.dllearner.core.ReasoningService; +import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.Individual; +import org.dllearner.core.owl.ObjectProperty; +import org.dllearner.parser.KBParser; +import org.dllearner.reasoning.OWLAPIReasoner; +import org.semanticweb.owl.apibinding.OWLManager; +import org.semanticweb.owl.io.OWLXMLOntologyFormat; +import org.semanticweb.owl.model.AddAxiom; +import org.semanticweb.owl.model.OWLAxiom; +import org.semanticweb.owl.model.OWLDataFactory; +import org.semanticweb.owl.model.OWLDescription; +import org.semanticweb.owl.model.OWLOntology; +import org.semanticweb.owl.model.OWLOntologyManager; +import org.semanticweb.owl.model.OWLPropertyAxiom; + +import uk.ac.manchester.cs.owl.OWLObjectExactCardinalityRestrictionImpl; +import uk.ac.manchester.cs.owl.OWLObjectIntersectionOfImpl; + +public class OntologyCloserOWLAPI { + + OWLOntology onto; + OWLAPIReasoner reasoner; + //Set<KnowledgeSource> ks; + ReasoningService rs; + HashMap<Individual,Set<OWLObjectExactCardinalityRestrictionImpl>> indToRestr; + OWLDataFactory factory; + OWLOntologyManager manager; + public int numberOfStatementsChanged = 0; + + public OntologyCloserOWLAPI(OWLAPIReasoner reasoner) { + //this.onto = reasoner.getOWLAPIOntologies().get(0); + this.reasoner = reasoner; + this.indToRestr = new HashMap<Individual,Set<OWLObjectExactCardinalityRestrictionImpl>> (); + this.rs = new ReasoningService(reasoner); + this.manager = OWLManager.createOWLOntologyManager(); + this.factory = manager.getOWLDataFactory(); + + this.onto = reasoner.getOWLAPIOntologies().get(0); + //URI ontologyURI = URI.create(reasoner.getBaseURI()); + //URI physicalURI = URI.create(owlFile); + //SimpleURIMapper mapper = new SimpleURIMapper(ontologyURI, physicalURI); + //manager.addURIMapper(mapper); + /*try{ + this.onto = manager.loadOntologyFromPhysicalURI(physicalURI); + }catch (Exception e) {e.printStackTrace();} + //manager.getOntologies().add(this.onto); + System.out.println(manager.getOntologies()); + System.out.println(this.onto);*/ + //reasoner = new org.mindswap.pellet.owlapi.Reasoner(manager); + //System.out.println(this.rs.getAtomicConcepts()); + + } + + + /** + * counts the number of roles used by each individual and assigns + * ExactCardinalityRestriction + */ + public void applyNumberRestrictions() { + System.out.println("applyNRES"); + Set<ObjectProperty> allRoles = this.rs.getAtomicRoles(); + System.out.println("found: "+allRoles.size()+" roles"); + // Set<Individual> allind = this.rs.getIndividuals(); + //testForTransitiveProperties(true); + + + + for (ObjectProperty oneRole : allRoles) { + + // System.out.println(oneRole.getClass()); + Map<Individual, SortedSet<Individual>> allRoleMembers = this.rs + .getRoleMembers(oneRole); + for (Individual oneInd : allRoleMembers.keySet()) { + SortedSet<Individual> fillers = allRoleMembers.get(oneInd); + if (fillers.size() > 0) { + OWLObjectExactCardinalityRestrictionImpl oecr = + new OWLObjectExactCardinalityRestrictionImpl( + factory, + factory.getOWLObjectProperty(URI.create(oneRole.getName())), + fillers.size(), + factory.getOWLThing() + ); + //System.out.println(oneRole.getName()+"||"+fillers.size()+"||"+oneInd); + /*ObjectExactCardinalityRestriction oecr = new ObjectExactCardinalityRestriction( + fillers.size(), oneRole, new Thing());*/ + //kb.addABoxAxiom(new ClassAssertionAxiom(oecr, oneInd)); + OWLAxiom axiom = factory.getOWLClassAssertionAxiom( + factory.getOWLIndividual(URI.create(oneInd.getName())) + , oecr); + AddAxiom addAxiom = new AddAxiom(this.onto, axiom); + try{ + manager.applyChange(addAxiom); + }catch (Exception e) {e.printStackTrace();} + } + } + + } + // System.out.println("good ontology? " + rs.isSatisfiable()); + + } + + /** + * counts the number of roles used by each individual and assigns + * ExactCardinalityRestriction + */ + public void applyNumberRestrictionsConcise() { + + Set<ObjectProperty> allRoles = this.rs.getAtomicRoles(); + // Set<Individual> allind = this.rs.getIndividuals(); + // testForTransitiveProperties(true); + + for (ObjectProperty oneRole : allRoles) { + + // System.out.println(oneRole.getClass()); + Map<Individual, SortedSet<Individual>> allRoleMembers = this.rs + .getRoleMembers(oneRole); + for (Individual oneInd : allRoleMembers.keySet()) { + SortedSet<Individual> fillers = allRoleMembers.get(oneInd); + if (fillers.size() > 0) { + OWLObjectExactCardinalityRestrictionImpl oecr = + new OWLObjectExactCardinalityRestrictionImpl( + factory, + factory.getOWLObjectProperty(URI.create(oneRole.getName())), + fillers.size(), + factory.getOWLThing() + ); + //indToRestr.put(oneInd,) + + collectExObjRestrForInd(oneInd, oecr); + } + } + + // + + }//end for + + //Intersection intersection = null; + Set<OWLDescription> target = new HashSet<OWLDescription>(); + Set<OWLObjectExactCardinalityRestrictionImpl> s = null; + + for (Individual oneInd : indToRestr.keySet()) { + s = indToRestr.get(oneInd); + for (OWLObjectExactCardinalityRestrictionImpl oecr : s) { + target.add(oecr); + } + OWLObjectIntersectionOfImpl intersection = + new OWLObjectIntersectionOfImpl(this.factory,target); + //kb.addABoxAxiom(new ClassAssertionAxiom(new OWLIntersection(ll), oneInd)); + + + s = null; + target = new HashSet<OWLDescription>(); + + OWLAxiom axiom = factory.getOWLClassAssertionAxiom( + factory.getOWLIndividual(URI.create(oneInd.getName())) + , intersection); + AddAxiom addAxiom = new AddAxiom(this.onto, axiom); + try{ + manager.applyChange(addAxiom); + numberOfStatementsChanged++; + }catch (Exception e) {e.printStackTrace();} + + }//end for + + + + // + + // System.out.println("good ontology? " + rs.isSatisfiable()); + + } + + + public boolean testForTransitiveProperties(boolean printflag) { + + boolean retval = false; + + Set<OWLPropertyAxiom> ax = onto.getObjectPropertyAxioms(); + for (OWLPropertyAxiom propertyAxiom : ax) { + //System.out.println(propertyAxiom.getClass().getSimpleName()); + if (propertyAxiom.getClass().getSimpleName().equals( + "OWLTransitiveObjectPropertyAxiomImpl")) { + retval = true; + if(printflag) { + System.out.println( + "WARNING transitive object property can't be used in cardinality restriction\n" + + propertyAxiom.toString()+"but I'm ignoring it"); + } + } + } + if(printflag) { + System.out.println( + "No transitive Properties found"); + } + return retval; + } + +/* + public static void closeKB(KB kb) { + new OntologyCloserOWLAPI(kb).applyNumberRestrictions(); + } +*/ + + public SortedSet<Individual> verifyConcept(String conceptStr) { + + Description d; + SimpleClock sc=new SimpleClock(); + StringBuffer sb = new StringBuffer(); + sb.append(conceptStr); + conceptStr = sb.toString(); + SortedSet<Individual> ind = new TreeSet<Individual>(); + try { + d = KBParser.parseConcept(conceptStr); + System.out.println("\n*******************\nStarting retrieval"); + System.out.println(d.toManchesterSyntaxString("", new HashMap<String,String>())); + //System.out.println(d.toString()); + sc.setTime(); + this.rs.retrieval(d); + + System.out.println("retrieved: " + ind.size() + " instances"); + sc.printAndSet(); + for (Individual individual : ind) { + System.out.print(individual + "|"); + } + + + + } catch (Exception e) { + e.printStackTrace(); + } + return ind; + } + + public void writeOWLFile(URI filename){ + try{ + manager.saveOntology(this.onto, new OWLXMLOntologyFormat(), + filename); + }catch (Exception e) {e.printStackTrace();} + } + + + private boolean collectExObjRestrForInd(Individual ind, OWLObjectExactCardinalityRestrictionImpl oecr){ + Set<OWLObjectExactCardinalityRestrictionImpl> s = indToRestr.get(ind); + + if(s==null){ + + indToRestr.put(ind, new HashSet<OWLObjectExactCardinalityRestrictionImpl>()); + s = indToRestr.get(ind); + } + return s.add(oecr); + } + +} Added: trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java 2008-04-07 07:48:07 UTC (rev 769) @@ -0,0 +1,20 @@ +package org.dllearner.utilities; + +public class SimpleClock { + private long time; + + public SimpleClock() { + time=System.currentTimeMillis(); + } + + public void printAndSet() { + long now=System.currentTimeMillis(); + System.out.println("needed "+(now-time)+" ms"); + time=now; + } + + public void setTime() { + time=System.currentTimeMillis(); + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-07 15:05:57
|
Revision: 775 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=775&view=rev Author: kurzum Date: 2008-04-07 08:05:51 -0700 (Mon, 07 Apr 2008) Log Message: ----------- added toKBSyntaxString method Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java trunk/src/dl-learner/org/dllearner/core/owl/BooleanDataRange.java trunk/src/dl-learner/org/dllearner/core/owl/BooleanDatatypePropertyAssertion.java trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ClassAssertionAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/Datatype.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeExactCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMaxCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMinCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeProperty.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyDomainAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyRangeAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/DifferentIndividualsAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/DisjointClassesAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/DoubleDatatypePropertyAssertion.java trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java trunk/src/dl-learner/org/dllearner/core/owl/EquivalentClassesAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/FunctionalObjectPropertyAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/Individual.java trunk/src/dl-learner/org/dllearner/core/owl/Intersection.java trunk/src/dl-learner/org/dllearner/core/owl/InverseObjectPropertyAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/KB.java trunk/src/dl-learner/org/dllearner/core/owl/KBElement.java trunk/src/dl-learner/org/dllearner/core/owl/NamedClass.java trunk/src/dl-learner/org/dllearner/core/owl/Negation.java trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectAllRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectProperty.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyAssertion.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyDomainAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyInverse.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyRangeAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectSomeRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectValueRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/SubClassAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/SubObjectPropertyAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/SymmetricObjectPropertyAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/Thing.java trunk/src/dl-learner/org/dllearner/core/owl/TransitiveObjectPropertyAxiom.java trunk/src/dl-learner/org/dllearner/core/owl/TypedConstant.java trunk/src/dl-learner/org/dllearner/core/owl/Union.java trunk/src/dl-learner/org/dllearner/core/owl/UntypedConstant.java trunk/src/dl-learner/org/dllearner/examples/KRK.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java 2008-04-07 15:05:51 UTC (rev 775) @@ -37,6 +37,12 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "ADC"; } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "ADC"; + } + + /* (non-Javadoc) * @see org.dllearner.core.owl.Description#toManchesterSyntaxString() Modified: trunk/src/dl-learner/org/dllearner/core/owl/BooleanDataRange.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/BooleanDataRange.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/BooleanDataRange.java 2008-04-07 15:05:51 UTC (rev 775) @@ -58,6 +58,13 @@ // TODO Auto-generated method stub return null; } + + + public String toKBSyntaxString (String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } + public void accept(KBElementVisitor visitor) { visitor.visit(this); Modified: trunk/src/dl-learner/org/dllearner/core/owl/BooleanDatatypePropertyAssertion.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/BooleanDatatypePropertyAssertion.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/BooleanDatatypePropertyAssertion.java 2008-04-07 15:05:51 UTC (rev 775) @@ -37,6 +37,11 @@ public String toString(String baseURI, Map<String, String> prefixes) { return datatypeProperty.toString(baseURI, prefixes) + "(" + individual.toString(baseURI, prefixes) + "," + value +")"; } + + @Override + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return datatypeProperty.toKBSyntaxString(baseURI,prefixes) + "(" + individual.toKBSyntaxString( baseURI, prefixes) + "," + value +")"; + } public boolean getValue() { return value; Modified: trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/BooleanValueRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -19,6 +19,7 @@ */ package org.dllearner.core.owl; + /** * Convenience class for boolean value restrictions. * @@ -58,4 +59,10 @@ public int getLength() { return 2; } + + /*@Override + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + throw new Error("BooleanValueRestriction: not implemented"); + + }*/ } Modified: trunk/src/dl-learner/org/dllearner/core/owl/ClassAssertionAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ClassAssertionAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ClassAssertionAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -51,9 +51,18 @@ } public String toString(String baseURI, Map<String,String> prefixes) { - return concept.toString(baseURI, prefixes) + "(" + individual + ")"; + return concept.toString(baseURI, prefixes) + "(" + individual.toString(baseURI, prefixes) + ")"; } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return concept.toKBSyntaxString(baseURI, prefixes) + "(" + individual.toKBSyntaxString(baseURI, prefixes) + ")"; + } + + /*@Override + public String toKBSyntaxString() { + return concept.toKBSyntaxString() + "(" + individual + ")"; + }*/ + @Override public void accept(AxiomVisitor visitor) { visitor.visit(this); Modified: trunk/src/dl-learner/org/dllearner/core/owl/Datatype.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Datatype.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/Datatype.java 2008-04-07 15:05:51 UTC (rev 775) @@ -55,6 +55,10 @@ return uri.toString(); } + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return uri.toString(); + } + public void accept(KBElementVisitor visitor) { visitor.visit(this); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeExactCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeExactCardinalityRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeExactCardinalityRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -63,6 +63,11 @@ return null; } + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } + /* (non-Javadoc) * @see org.dllearner.core.owl.Description#toManchesterSyntaxString() */ Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMaxCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMaxCardinalityRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMaxCardinalityRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -62,6 +62,11 @@ // TODO Auto-generated method stub return null; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } @Override public void accept(DescriptionVisitor visitor) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMinCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMinCardinalityRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeMinCardinalityRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -62,6 +62,11 @@ // TODO Auto-generated method stub return null; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } /* (non-Javadoc) * @see org.dllearner.core.owl.Description#accept(org.dllearner.core.owl.DescriptionVisitor) Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeProperty.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeProperty.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeProperty.java 2008-04-07 15:05:51 UTC (rev 775) @@ -52,6 +52,10 @@ } public String toString(String baseURI, Map<String, String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes); + } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { return "\"" + Helper.getAbbreviatedString(name, baseURI, prefixes) + "\""; } Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyDomainAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyDomainAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyDomainAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -52,6 +52,15 @@ } /* (non-Javadoc) + * @see org.dllearner.core.owl.KBElement#toKBSyntaxString(java.lang.String, java.util.Map) + */ + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } + + + /* (non-Javadoc) * @see org.dllearner.core.owl.Axiom#accept(org.dllearner.core.owl.AxiomVisitor) */ @Override Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyRangeAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyRangeAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypePropertyRangeAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -50,6 +50,11 @@ // TODO Auto-generated method stub return null; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } /* (non-Javadoc) * @see org.dllearner.core.owl.Axiom#accept(org.dllearner.core.owl.AxiomVisitor) Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeSomeRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -63,6 +63,13 @@ public String toString(String baseURI, Map<String, String> prefixes) { return restrictedPropertyExpression.toString(baseURI, prefixes) + dataRange.toString(baseURI, prefixes); } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.KBElement#toKBSyntaxString(java.lang.String, java.util.Map) + */ + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return restrictedPropertyExpression.toKBSyntaxString(baseURI, prefixes) + dataRange.toKBSyntaxString(baseURI, prefixes); + } /* (non-Javadoc) * @see org.dllearner.core.owl.Description#accept(org.dllearner.core.owl.DescriptionVisitor) Modified: trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DatatypeValueRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -68,6 +68,10 @@ public String toString(String baseURI, Map<String, String> prefixes) { return restrictedPropertyExpression.toString(baseURI, prefixes) + " = " + value.toString(baseURI, prefixes); } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return restrictedPropertyExpression.toKBSyntaxString(baseURI, prefixes) + " = " + value.toKBSyntaxString(baseURI, prefixes); + } public DatatypeProperty getRestrictedPropertyExpresssion() { return (DatatypeProperty) restrictedPropertyExpression; Modified: trunk/src/dl-learner/org/dllearner/core/owl/DifferentIndividualsAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DifferentIndividualsAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DifferentIndividualsAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -48,6 +48,11 @@ // TODO Auto-generated method stub return null; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + throw new Error("DifferentIndividualsAxiom: Not implemented"); + } public Set<Individual> getIndividuals() { return individuals; Modified: trunk/src/dl-learner/org/dllearner/core/owl/DisjointClassesAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DisjointClassesAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DisjointClassesAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -51,6 +51,13 @@ // TODO Auto-generated method stub return null; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + throw new Error("DisjointClassesAxiom: Not implemented"); + } + + @Override public void accept(AxiomVisitor visitor) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/DoubleDatatypePropertyAssertion.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DoubleDatatypePropertyAssertion.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DoubleDatatypePropertyAssertion.java 2008-04-07 15:05:51 UTC (rev 775) @@ -40,6 +40,13 @@ public String toString(String baseURI, Map<String, String> prefixes) { return datatypeProperty.toString(baseURI, prefixes) + "(" + individual.toString(baseURI, prefixes) + "," + value +")"; } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.KBElement#toKBSyntaxString(java.lang.String, java.util.Map) + */ + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return datatypeProperty.toKBSyntaxString(baseURI, prefixes) + "(" + individual.toKBSyntaxString(baseURI, prefixes) + "," + value +")"; + } public double getValue() { return value; Modified: trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DoubleMaxValue.java 2008-04-07 15:05:51 UTC (rev 775) @@ -57,6 +57,10 @@ return " <= " + value; } + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return " <= " + value; + } + public void accept(KBElementVisitor visitor) { visitor.visit(this); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/DoubleMinValue.java 2008-04-07 15:05:51 UTC (rev 775) @@ -57,6 +57,10 @@ return " >= " + value; } + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return " >= " + value; + } + public void accept(KBElementVisitor visitor) { visitor.visit(this); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/EquivalentClassesAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/EquivalentClassesAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/EquivalentClassesAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -27,6 +27,10 @@ public String toString(String baseURI, Map<String,String> prefixes) { return concept1.toString(baseURI, prefixes) + " = " + concept2.toString(baseURI, prefixes); } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return concept1.toKBSyntaxString(baseURI, prefixes) + " = " + concept2.toKBSyntaxString(baseURI, prefixes); + } @Override public void accept(AxiomVisitor visitor) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/FunctionalObjectPropertyAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/FunctionalObjectPropertyAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/FunctionalObjectPropertyAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -18,9 +18,19 @@ return 1 + role.getLength(); } + /* (non-Javadoc) + * @see org.dllearner.core.owl.KBElement#toString(java.lang.String, java.util.Map) + */ public String toString(String baseURI, Map<String,String> prefixes) { return "Functional(" + role.toString(baseURI, prefixes) + ")"; } + + /* (non-Javadoc) + * @see org.dllearner.core.owl.KBElement#toKBSyntaxString(java.lang.String, java.util.Map) + */ + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "Functional(" + role.toKBSyntaxString(baseURI, prefixes) + ")"; + } @Override public void accept(AxiomVisitor visitor) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/Individual.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Individual.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/Individual.java 2008-04-07 15:05:51 UTC (rev 775) @@ -60,6 +60,10 @@ } public String toString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes); + } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { return "\"" + Helper.getAbbreviatedString(name, baseURI, prefixes) + "\""; } Modified: trunk/src/dl-learner/org/dllearner/core/owl/Intersection.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Intersection.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/Intersection.java 2008-04-07 15:05:51 UTC (rev 775) @@ -39,16 +39,28 @@ return "EMPTY_AND"; String ret = "("; + for(int i=0; i<children.size()-1; i++) { + ret += children.get(i).toString(baseURI, prefixes) + " AND "; + } + ret += children.get(children.size()-1).toString(baseURI, prefixes) + ")"; + return ret; + } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + if(children.size()==0) + return "EMPTY_AND"; + + String ret = "("; String bracketCollect = ""; for(int i=0; i<children.size()-1; i++) { - ret += children.get(i).toString(baseURI, prefixes) + " AND "; + ret += children.get(i).toKBSyntaxString(baseURI, prefixes) + " AND "; if( i != (children.size()-2) ) { ret += "("; bracketCollect += ")"; } } - ret += children.get(children.size()-1).toString(baseURI, prefixes) + ")"; + ret += children.get(children.size()-1).toKBSyntaxString(baseURI, prefixes) + ")"; ret += bracketCollect; return ret; } Modified: trunk/src/dl-learner/org/dllearner/core/owl/InverseObjectPropertyAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/InverseObjectPropertyAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/InverseObjectPropertyAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -26,6 +26,10 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "Inverse(" + inverseRole + "," + role.toString(baseURI, prefixes) + ")"; + } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "Inverse(" + inverseRole.toKBSyntaxString(baseURI, prefixes) + "," + role.toKBSyntaxString(baseURI, prefixes) + ")"; } @Override Modified: trunk/src/dl-learner/org/dllearner/core/owl/KB.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/KB.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/KB.java 2008-04-07 15:05:51 UTC (rev 775) @@ -203,6 +203,19 @@ return str; } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + String str = "TBox["+tbox.size()+"]:\n"; + for(Axiom a : tbox) + str += " " + a.toString(baseURI, prefixes)+"\n"; + str += "RBox["+rbox.size()+"]:\n"; + for(Axiom a : rbox) + str += " " + a.toString(baseURI, prefixes)+"\n"; + str += "ABox["+abox.size()+"]:\n"; + for(Axiom a : abox) + str += " " + a.toString(baseURI, prefixes)+"\n"; + return str; + } + public Set<Individual> findRelatedIndividuals(Individual individual) { return findRelatedIndividuals(individual, new TreeSet<Individual>()); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/KBElement.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/KBElement.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/KBElement.java 2008-04-07 15:05:51 UTC (rev 775) @@ -14,5 +14,7 @@ public String toString(String baseURI, Map<String,String> prefixes); + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes); + public void accept(KBElementVisitor visitor); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/NamedClass.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/NamedClass.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/NamedClass.java 2008-04-07 15:05:51 UTC (rev 775) @@ -52,6 +52,10 @@ } public String toString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes); + } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { return "\"" + Helper.getAbbreviatedString(name, baseURI, prefixes) + "\""; } Modified: trunk/src/dl-learner/org/dllearner/core/owl/Negation.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Negation.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/Negation.java 2008-04-07 15:05:51 UTC (rev 775) @@ -21,6 +21,11 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "(NOT " +children.get(0).toString(baseURI, prefixes) + ")"; } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + //TODO brackets removed, but they maybe have to be here + return "NOT " +children.get(0).toKBSyntaxString(baseURI, prefixes) + ""; + } public int getLength() { return 1 + children.get(0).getLength(); Modified: trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/Nothing.java 2008-04-07 15:05:51 UTC (rev 775) @@ -34,6 +34,10 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "BOTTOM"; } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "BOTTOM"; + } /* (non-Javadoc) * @see org.dllearner.core.owl.Description#toManchesterSyntaxString(java.lang.String, java.util.Map) Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectAllRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectAllRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectAllRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -37,6 +37,10 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "ALL " + restrictedPropertyExpression.toString(baseURI, prefixes) + "." + children.get(0).toString(baseURI, prefixes); } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "ALL " + restrictedPropertyExpression.toKBSyntaxString(baseURI, prefixes) + "." + children.get(0).toKBSyntaxString(baseURI, prefixes); + } @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -39,6 +39,10 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + " " + getChild(0).toKBSyntaxString(baseURI, prefixes); + } @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -15,8 +15,12 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "<= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); - } + } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "<= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + " " + getChild(0).toKBSyntaxString(baseURI, prefixes); + } + @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { return role.toString(baseURI, prefixes) + " max " + number + " " + getChild(0).toManchesterSyntaxString(baseURI, prefixes); Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -17,6 +17,10 @@ return ">= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return ">= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + " " + getChild(0).toKBSyntaxString(baseURI, prefixes); + } + @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { return role.toString(baseURI, prefixes) + " min " + number + " " + getChild(0).toManchesterSyntaxString(baseURI, prefixes); Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectProperty.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectProperty.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectProperty.java 2008-04-07 15:05:51 UTC (rev 775) @@ -46,8 +46,12 @@ } public String toString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes) ; + } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { return "\"" + Helper.getAbbreviatedString(name, baseURI, prefixes) + "\""; - } + } public void accept(KBElementVisitor visitor) { visitor.visit(this); Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyAssertion.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyAssertion.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyAssertion.java 2008-04-07 15:05:51 UTC (rev 775) @@ -65,6 +65,10 @@ return role.toString(baseURI, prefixes) + "(" + individual1.toString(baseURI, prefixes) + "," + individual2.toString(baseURI, prefixes) +")"; } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return role.toKBSyntaxString(baseURI, prefixes) + "(" + individual1.toKBSyntaxString(baseURI, prefixes) + "," + individual2.toKBSyntaxString(baseURI, prefixes) +")"; + } + public void accept(KBElementVisitor visitor) { visitor.visit(this); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyDomainAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyDomainAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyDomainAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -52,6 +52,12 @@ // TODO Auto-generated method stub return null; } + + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } @Override public void accept(AxiomVisitor visitor) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyInverse.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyInverse.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyInverse.java 2008-04-07 15:05:51 UTC (rev 775) @@ -50,6 +50,10 @@ return Helper.getAbbreviatedString(name, baseURI, prefixes) + "-"; } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes) + "-"; + } + public void accept(KBElementVisitor visitor) { visitor.visit(this); } Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyRangeAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyRangeAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectPropertyRangeAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -46,6 +46,11 @@ // TODO Auto-generated method stub return null; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } @Override public Description getRange() { Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectSomeRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectSomeRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectSomeRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -36,6 +36,10 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "EXISTS " + restrictedPropertyExpression.toString(baseURI, prefixes) + "." + children.get(0).toString(baseURI, prefixes); } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "EXISTS " + restrictedPropertyExpression.toKBSyntaxString(baseURI, prefixes) + "." + children.get(0).toKBSyntaxString(baseURI, prefixes); + } @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectValueRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectValueRestriction.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectValueRestriction.java 2008-04-07 15:05:51 UTC (rev 775) @@ -71,6 +71,11 @@ return null; } + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + // TODO Auto-generated method stub + return null; + } + public Individual getIndividual() { return (Individual) value; } Modified: trunk/src/dl-learner/org/dllearner/core/owl/SubClassAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/SubClassAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/SubClassAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -28,6 +28,10 @@ return subConcept.toString(baseURI, prefixes) + " SUBCONCEPTOF " + superConcept.toString(baseURI, prefixes); } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return subConcept.toKBSyntaxString(baseURI, prefixes) + " SUBCONCEPTOF " + superConcept.toKBSyntaxString(baseURI, prefixes); + } + @Override public void accept(AxiomVisitor visitor) { visitor.visit(this); Modified: trunk/src/dl-learner/org/dllearner/core/owl/SubObjectPropertyAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/SubObjectPropertyAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/SubObjectPropertyAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -26,8 +26,12 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "Subrole(" + subRole.toString(baseURI, prefixes) + "," + role.toString(baseURI, prefixes) + ")"; - } + } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "Subrole(" + subRole.toKBSyntaxString(baseURI, prefixes) + "," + role.toKBSyntaxString(baseURI, prefixes) + ")"; + } + @Override public void accept(AxiomVisitor visitor) { visitor.visit(this); Modified: trunk/src/dl-learner/org/dllearner/core/owl/SymmetricObjectPropertyAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/SymmetricObjectPropertyAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/SymmetricObjectPropertyAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -22,6 +22,10 @@ return "Symmetric(" + role.toString(baseURI, prefixes) + ")"; } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "Symmetric(" + role.toKBSyntaxString(baseURI, prefixes) + ")"; + } + @Override public void accept(AxiomVisitor visitor) { visitor.visit(this); Modified: trunk/src/dl-learner/org/dllearner/core/owl/Thing.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Thing.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/Thing.java 2008-04-07 15:05:51 UTC (rev 775) @@ -41,6 +41,10 @@ public String toString(String baseURI, Map<String,String> prefixes) { return "TOP"; } + + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "TOP"; + } @Override public String toManchesterSyntaxString(String baseURI, Map<String, String> prefixes) { Modified: trunk/src/dl-learner/org/dllearner/core/owl/TransitiveObjectPropertyAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/TransitiveObjectPropertyAxiom.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/TransitiveObjectPropertyAxiom.java 2008-04-07 15:05:51 UTC (rev 775) @@ -22,6 +22,10 @@ return "Transitive(" + role.toString(baseURI, prefixes) + ")"; } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + return "Transitive(" + role.toKBSyntaxString(baseURI, prefixes) + ")"; + } + @Override public void accept(AxiomVisitor visitor) { visitor.visit(this); Modified: trunk/src/dl-learner/org/dllearner/core/owl/TypedConstant.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/TypedConstant.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/TypedConstant.java 2008-04-07 15:05:51 UTC (rev 775) @@ -50,6 +50,11 @@ return literal; // return literal + "^^" + datatype; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + return literal; +// return literal + "^^" + datatype; + } /** * @return the datatype Modified: trunk/src/dl-learner/org/dllearner/core/owl/Union.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Union.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/Union.java 2008-04-07 15:05:51 UTC (rev 775) @@ -48,6 +48,25 @@ return ret; } + public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { + + if(children.size()==0) + return "EMPTY_OR"; + + String ret = "("; + String bracketCollect = ""; + for(int i=0; i<children.size()-1; i++) { + ret += children.get(i).toKBSyntaxString(baseURI, prefixes) + " OR "; + if( i != (children.size()-2) ) { + ret += "("; + bracketCollect += ")"; + } + } + ret += children.get(children.size()-1).toKBSyntaxString(baseURI, prefixes) + ")"; + ret += bracketCollect; + return ret; + } + @Override public String toManchesterSyntaxString(String baseURI, Map<String,String> prefixes) { if(children.size()==0) Modified: trunk/src/dl-learner/org/dllearner/core/owl/UntypedConstant.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/UntypedConstant.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/core/owl/UntypedConstant.java 2008-04-07 15:05:51 UTC (rev 775) @@ -61,6 +61,13 @@ else return literal; } + + public String toKBSyntaxString(String baseURI, Map<String, String> prefixes) { + if(hasLang) + return literal + "@" + lang; + else + return literal; + } /** * @return the lang Modified: trunk/src/dl-learner/org/dllearner/examples/KRK.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-07 12:18:57 UTC (rev 774) +++ trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-07 15:05:51 UTC (rev 775) @@ -233,14 +233,17 @@ if(closeKB) { if(closeConcise) { - oc.applyNumberRestrictionsNamed(); + oc.applyNumberRestrictionsConcise(); kbaddition = "_CloseConcise"; } else oc.applyNumberRestrictions(); } - - if (verifySomeConcepts) verifySomeConcepts(oc); + + if (verifySomeConcepts) { + oc.updateReasoner(); + verifySomeConcepts(oc); + } if (writeClosedOWL) writeOWLFile("test"+kbaddition+".owl"); } catch (Exception e) { @@ -319,6 +322,9 @@ " ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + "\"http://www.test.de/test#WKing\") ");*/ + + test.add("EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#hasLowerRankThan\".(\"http://www.test.de/test#WRook\" AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\")") ; + for (int i = 0; i < test.size(); i++) { String conceptStr = test.get(i); oc.verifyConcept(conceptStr); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-07 15:18:05
|
Revision: 776 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=776&view=rev Author: kurzum Date: 2008-04-07 08:17:58 -0700 (Mon, 07 Apr 2008) Log Message: ----------- changed output of learning algorithms ROL and REF, now has simple, Manchester, KBSyntax output Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/cli/Start.java trunk/src/dl-learner/org/dllearner/core/owl/Description.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-07 15:05:51 UTC (rev 775) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-07 15:17:58 UTC (rev 776) @@ -385,12 +385,13 @@ logger.info("best node " + candidatesStable.last().getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); logger.info("\nsolutions:"); for(Description c : solutions) { - logger.info(" " + c + " (length " + c.getLength() +", depth " + c.getDepth() + ")"); + logger.info(" " + c.toString(baseURI,null) + " (length " + c.getLength() +", depth " + c.getDepth() + ")"); //TODO remove this line maybe // watch for String.replace Quick hack logger.info(" MANCHESTER: " + c.toManchesterSyntaxString(baseURI, new HashMap<String,String>()). replace("\"", "")); + logger.info(" KBSyntax: " + c.toKBSyntaxString()); } } logger.debug("size of candidate set: " + candidates.size()); Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-04-07 15:05:51 UTC (rev 775) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2008-04-07 15:17:58 UTC (rev 776) @@ -512,12 +512,13 @@ if(solutionFound) { logger.info("\nsolutions:"); for(Description c : solutions) { - logger.info(" " + c + " (length " + c.getLength() +", depth " + c.getDepth() + ")"); + logger.info(" " + c.toString(baseURI,null) + " (length " + c.getLength() +", depth " + c.getDepth() + ")"); //TODO remove this line maybe // watch for String.replace Quick hack logger.info(" MANCHESTER: " + c.toManchesterSyntaxString(baseURI, new HashMap<String,String>()). replace("\"", "")); + logger.info(" KBSyntax: " + c.toKBSyntaxString()); } } logger.info(" horizontal expansion: " + minimumHorizontalExpansion + " to " + maximumHorizontalExpansion); Modified: trunk/src/dl-learner/org/dllearner/cli/Start.java =================================================================== --- trunk/src/dl-learner/org/dllearner/cli/Start.java 2008-04-07 15:05:51 UTC (rev 775) +++ trunk/src/dl-learner/org/dllearner/cli/Start.java 2008-04-07 15:17:58 UTC (rev 776) @@ -711,7 +711,7 @@ Set<Individual> result = null; result = rs.retrieval(concept); - System.out.println("retrieval result: " + result); + System.out.println("retrieval result ("+result.size()+"): " + result); Score score = lp.computeScore(concept); System.out.println(score); Modified: trunk/src/dl-learner/org/dllearner/core/owl/Description.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/Description.java 2008-04-07 15:05:51 UTC (rev 775) +++ trunk/src/dl-learner/org/dllearner/core/owl/Description.java 2008-04-07 15:17:58 UTC (rev 776) @@ -190,6 +190,11 @@ return toString(null, null); } + + public String toKBSyntaxString() { + return toKBSyntaxString(null, null); + } + /** * Returns a manchester syntax string of this description. For a * reference, see This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-10 13:20:23
|
Revision: 785 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=785&view=rev Author: kurzum Date: 2008-04-10 06:20:09 -0700 (Thu, 10 Apr 2008) Log Message: ----------- some kbsyntax manchester fixes, added option useCardinalityRestrictions Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java trunk/src/dl-learner/org/dllearner/core/config/CommonConfigOptions.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java trunk/src/dl-learner/org/dllearner/examples/KRK.java trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLComponent.java 2008-04-10 13:20:09 UTC (rev 785) @@ -101,6 +101,7 @@ private boolean improveSubsumptionHierarchy = true; private boolean useAllConstructor = true; private boolean useExistsConstructor = true; + private boolean useCardinalityRestrictions = true; private boolean useNegation = true; private boolean useBooleanDatatypes = true; private double noisePercentage = 0.0; @@ -160,8 +161,10 @@ options.add(CommonConfigOptions.ignoredRoles()); options.add(CommonConfigOptions.useAllConstructor()); options.add(CommonConfigOptions.useExistsConstructor()); + options.add(CommonConfigOptions.useCardinalityRestrictions()); options.add(CommonConfigOptions.useNegation()); options.add(CommonConfigOptions.useBooleanDatatypes()); + DoubleConfigOption noisePercentage = new DoubleConfigOption("noisePercentage", "the (approximated) percentage of noise within the examples"); noisePercentage.setLowerLimit(0); noisePercentage.setUpperLimit(100); @@ -213,6 +216,8 @@ useAllConstructor = (Boolean) entry.getValue(); } else if(name.equals("useExistsConstructor")) { useExistsConstructor = (Boolean) entry.getValue(); + } else if(name.equals("useCardinalityRestrictions")) { + useCardinalityRestrictions = (Boolean) entry.getValue(); } else if(name.equals("useNegation")) { useNegation = (Boolean) entry.getValue(); } else if(name.equals("noisePercentage")) { @@ -292,6 +297,7 @@ applyExistsFilter, useAllConstructor, useExistsConstructor, + useCardinalityRestrictions, useNegation, useBooleanDatatypes, startClass Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-10 13:20:09 UTC (rev 785) @@ -739,8 +739,11 @@ // String bestNodeString = "currently best node: " + bestNode + " accuracy: " + df.format(accuracy) + "%"; logger.debug("start node: " + startNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI)); String bestNodeString = "currently best node: " + bestNode.getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI); + String bestNodeStringKBSyntax = "currently best node KBSyntax: " + bestNode.getConcept().toKBSyntaxString(); + // searchTree += bestNodeString + "\n"; logger.debug(bestNodeString); + logger.debug(bestNodeStringKBSyntax); String expandedNodeString = "next expanded node: " + candidates.last().getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI); // searchTree += expandedNodeString + "\n"; logger.debug(expandedNodeString); Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/MultiHeuristic.java 2008-04-10 13:20:09 UTC (rev 785) @@ -78,7 +78,7 @@ private double expansionPenaltyFactor; private double gainBonusFactor; private double nodeChildPenalty = 0.0001; - private double startNodeBonus = 2.0; + private double startNodeBonus = 0.1; //was 2.0 // penalise errors on positive examples harder than on negative examples // (positive weight = 1) private double negativeWeight = 0.8; Modified: trunk/src/dl-learner/org/dllearner/core/config/CommonConfigOptions.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/config/CommonConfigOptions.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/core/config/CommonConfigOptions.java 2008-04-10 13:20:09 UTC (rev 785) @@ -28,6 +28,21 @@ * */ public final class CommonConfigOptions { + + //public static boolean applyAllFilterDefault = true; + //public static boolean applyExistsFilterDefault = true; + //public static boolean useTooWeakListDefault = true; + //public static boolean useOverlyGeneralListDefault = true; + //public static boolean useShortConceptConstructionDefault = true; + //public static boolean improveSubsumptionHierarchyDefault = true; + public static boolean useAllConstructorDefault = true; + public static boolean useExistsConstructorDefault = true; + public static boolean useCardinalityRestrictionsDefault = true; + public static boolean useNegationDefault = true; + public static boolean useBooleanDatatypesDefault = true; + //public static double noisePercentageDefault = 0.0; + + public static StringConfigOption getVerbosityOption() { StringConfigOption verbosityOption = new StringConfigOption("verbosity", "control verbosity of output for this component", "warning"); @@ -72,18 +87,22 @@ } public static BooleanConfigOption useAllConstructor() { - return new BooleanConfigOption("useAllConstructor", "specifies whether to universal concept constructor is used in the learning algorothm"); + return new BooleanConfigOption("useAllConstructor", "specifies whether the universal concept constructor is used in the learning algorithm",useAllConstructorDefault); } public static BooleanConfigOption useExistsConstructor() { - return new BooleanConfigOption("useExistsConstructor", "specifies whether to existential concept constructor is used in the learning algorothm"); + return new BooleanConfigOption("useExistsConstructor", "specifies whether the existential concept constructor is used in the learning algorithm",useExistsConstructorDefault); } + public static BooleanConfigOption useCardinalityRestrictions() { + return new BooleanConfigOption("useCardinalityRestrictions", "specifies whether CardinalityRestrictions is used in the learning algorithm",useCardinalityRestrictionsDefault); + } + public static BooleanConfigOption useNegation() { - return new BooleanConfigOption("useNegation", "specifies whether negation is used in the learning algorothm"); + return new BooleanConfigOption("useNegation", "specifies whether negation is used in the learning algorothm",useNegationDefault); } public static BooleanConfigOption useBooleanDatatypes() { - return new BooleanConfigOption("useBooleanDatatypes", "specifies whether boolean datatypes are used in the learning algorothm"); + return new BooleanConfigOption("useBooleanDatatypes", "specifies whether boolean datatypes are used in the learning algorothm",useBooleanDatatypesDefault); } } Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectExactCardinalityRestriction.java 2008-04-10 13:20:09 UTC (rev 785) @@ -37,11 +37,11 @@ } public String toString(String baseURI, Map<String,String> prefixes) { - return "= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); + return "= " + number + " " + role.toString(baseURI, prefixes) + "." + getChild(0).toString(baseURI, prefixes); } public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { - return "= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + " " + getChild(0).toKBSyntaxString(baseURI, prefixes); + return "= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + "." + getChild(0).toKBSyntaxString(baseURI, prefixes); } @Override Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectMaxCardinalityRestriction.java 2008-04-10 13:20:09 UTC (rev 785) @@ -14,11 +14,11 @@ } public String toString(String baseURI, Map<String,String> prefixes) { - return "<= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); + return "<= " + number + " " + role.toString(baseURI, prefixes) + "." + getChild(0).toString(baseURI, prefixes); } public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { - return "<= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + " " + getChild(0).toKBSyntaxString(baseURI, prefixes); + return "<= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + "." + getChild(0).toKBSyntaxString(baseURI, prefixes); } @Override Modified: trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/core/owl/ObjectMinCardinalityRestriction.java 2008-04-10 13:20:09 UTC (rev 785) @@ -14,11 +14,11 @@ } public String toString(String baseURI, Map<String,String> prefixes) { - return ">= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); + return ">= " + number + " " + role.toString(baseURI, prefixes) + "." + getChild(0).toString(baseURI, prefixes); } public String toKBSyntaxString(String baseURI, Map<String,String> prefixes) { - return ">= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + " " + getChild(0).toKBSyntaxString(baseURI, prefixes); + return ">= " + number + " " + role.toKBSyntaxString(baseURI, prefixes) + "." + getChild(0).toKBSyntaxString(baseURI, prefixes); } @Override Modified: trunk/src/dl-learner/org/dllearner/examples/KRK.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-10 13:20:09 UTC (rev 785) @@ -56,7 +56,7 @@ static boolean writeConciseOWLAllDifferent = false; - static boolean closeKB=true; + static boolean closeKB=false; static boolean closeConcise= true && closeKB; static boolean writeClosedOWL = true && closeKB; static boolean verifySomeConcepts = false && closeKB; Modified: trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-04-10 13:01:21 UTC (rev 784) +++ trunk/src/dl-learner/org/dllearner/refinementoperators/RhoDRDown.java 2008-04-10 13:20:09 UTC (rev 785) @@ -167,16 +167,17 @@ // private Map<NamedClass,Map<NamedClass,Boolean>> notABMeaningful = new TreeMap<NamedClass,Map<NamedClass,Boolean>>(); public RhoDRDown(ReasoningService reasoningService) { - this(reasoningService, true, true, true, true, true, true, null); + this(reasoningService, true, true, true, true, true, true, true, null); } public RhoDRDown(ReasoningService reasoningService, boolean applyAllFilter, boolean applyExistsFilter, boolean useAllConstructor, - boolean useExistsConstructor, boolean useNegation, boolean useBooleanDatatypes, NamedClass startClass) { + boolean useExistsConstructor,boolean useCardinalityRestrictions,boolean useNegation, boolean useBooleanDatatypes, NamedClass startClass) { this.rs = reasoningService; this.applyAllFilter = applyAllFilter; this.applyExistsFilter = applyExistsFilter; this.useAllConstructor = useAllConstructor; this.useExistsConstructor = useExistsConstructor; + this.useCardinalityRestrictions = useCardinalityRestrictions; this.useNegation = useNegation; this.useBooleanDatatypes = useBooleanDatatypes; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2008-04-15 10:20:25
|
Revision: 788 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=788&view=rev Author: kurzum Date: 2008-04-15 03:20:23 -0700 (Tue, 15 Apr 2008) Log Message: ----------- added some functions at some places nothing big new approach to KRK Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java trunk/src/dl-learner/org/dllearner/examples/KRK.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java trunk/src/dl-learner/org/dllearner/parser/KBParser.java trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/examples/KRKModular.java trunk/src/dl-learner/org/dllearner/examples/KRKOntologyTBox.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java 2008-04-14 22:45:16 UTC (rev 787) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedNode.java 2008-04-15 10:20:23 UTC (rev 788) @@ -174,6 +174,30 @@ return ret; } + //TODO integrate this method with the one above + public String getStats(int nrOfPositiveExamples, int nrOfNegativeExamples) { + String ret = " ["; + + if(isTooWeak) + ret += "q:tw"; + else { + double accuracy = 100 * (coveredPositives.size() + nrOfNegativeExamples - coveredNegatives.size())/(double)(nrOfPositiveExamples+nrOfNegativeExamples); + ret += "acc:" + df.format(accuracy) + "% "; + + // comment this out to display the heuristic score with default parameters + double heuristicScore = MultiHeuristic.getNodeScore(this, nrOfPositiveExamples, nrOfNegativeExamples); + ret += "h:" +df.format(heuristicScore) + " "; + + int wrongPositives = nrOfPositiveExamples - coveredPositives.size(); + ret += "q:" + wrongPositives + "p-" + coveredNegatives.size() + "n"; + } + + ret += " ("+qualityEvaluationMethod+"), he:" + horizontalExpansion; + ret += " c:" + children.size() + "]"; + + return ret; + } + public double getAccuracy(int nrOfPositiveExamples, int nrOfNegativeExamples) { return (coveredPositives.size() + nrOfNegativeExamples - coveredNegatives.size())/(double)(nrOfPositiveExamples+nrOfNegativeExamples); } Modified: trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-14 22:45:16 UTC (rev 787) +++ trunk/src/dl-learner/org/dllearner/algorithms/refexamples/ExampleBasedROLearner.java 2008-04-15 10:20:23 UTC (rev 788) @@ -743,6 +743,7 @@ // searchTree += bestNodeString + "\n"; logger.debug(bestNodeString); + logger.debug(startNode.getStats(nrOfPositiveExamples, nrOfNegativeExamples)); logger.debug(bestNodeStringKBSyntax); String expandedNodeString = "next expanded node: " + candidates.last().getShortDescription(nrOfPositiveExamples, nrOfNegativeExamples, baseURI); // searchTree += expandedNodeString + "\n"; Modified: trunk/src/dl-learner/org/dllearner/examples/KRK.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-14 22:45:16 UTC (rev 787) +++ trunk/src/dl-learner/org/dllearner/examples/KRK.java 2008-04-15 10:20:23 UTC (rev 788) @@ -5,6 +5,7 @@ import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; +import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.util.ArrayList; @@ -17,7 +18,6 @@ import org.dllearner.core.owl.ClassAssertionAxiom; import org.dllearner.core.owl.DatatypeProperty; import org.dllearner.core.owl.Description; -import org.dllearner.core.owl.DisjointClassesAxiom; import org.dllearner.core.owl.Individual; import org.dllearner.core.owl.InverseObjectPropertyAxiom; import org.dllearner.core.owl.KB; @@ -51,7 +51,9 @@ // // turn off to not write the owl, needs about 30 seconds or more static boolean writeOWL = true; + static boolean writeKB = false; static boolean useTransitivity = false; + static boolean useHigherThan = false; static boolean writeExampleSets = true; static boolean writeConciseOWLAllDifferent = false; @@ -103,6 +105,9 @@ static ObjectProperty rankLessThan = getRole("hasLowerRankThan"); static ObjectProperty fileLessThan = getRole("hasLowerFileThan"); + + static ObjectProperty rankHigherThan = getRole("hasHigherRankThan"); + static ObjectProperty fileHigherThan = getRole("hasHigherFileThan"); // static ObjectProperty lessThan = getRole("strictLessThan"); @@ -142,10 +147,13 @@ + + try { String line = ""; String[] ar = new String[6]; + String currentclass=""; int x = 0; while ((line = in.readLine()) != null) { @@ -154,11 +162,15 @@ System.out.println("Currently at line" + x); ar = tokenize(line); + currentclass = ar[6]; + gameind = getIndividual("game" + x); wkingind = getIndividual("wking_" + ar[0] + ar[1] + "_" + x); wrookind = getIndividual("wrook_" + ar[2] + ar[3] + "_" + x); bkingind = getIndividual("bking_" + ar[4] + ar[5] + "_" + x); + + allInstances.add(gameind+""); allInstances.add(wkingind+""); allInstances.add(wrookind+""); @@ -180,6 +192,34 @@ kb.addABoxAxiom(new ClassAssertionAxiom(WRook, wrookind)); kb.addABoxAxiom(new ClassAssertionAxiom(BKing, bkingind)); + + /**Files and Ranks***/ + // FILES are letters + // RANKS are numbers + + //WKing + NamedClass tmp=getAtomicConcept(ar[0].toUpperCase()); + kb.addABoxAxiom(new ClassAssertionAxiom(tmp, wkingind)); + + tmp=getAtomicConcept("F"+ar[1]); + kb.addABoxAxiom(new ClassAssertionAxiom(tmp , wkingind)); + + //WRook + tmp=getAtomicConcept(ar[2].toUpperCase()); + kb.addABoxAxiom(new ClassAssertionAxiom(tmp, wrookind)); + + tmp=getAtomicConcept("F"+ar[3]); + kb.addABoxAxiom(new ClassAssertionAxiom(tmp , wrookind)); + + //BKing + tmp=getAtomicConcept(ar[4].toUpperCase()); + kb.addABoxAxiom(new ClassAssertionAxiom(tmp, bkingind)); + + tmp=getAtomicConcept("F"+ar[5]); + kb.addABoxAxiom(new ClassAssertionAxiom(tmp, bkingind)); + + + // PROPERTIES kb.addABoxAxiom(new ObjectPropertyAssertion(hasPiece, gameind, wkingind)); @@ -227,11 +267,12 @@ if(writeExampleSets)writeExampleSets(); if(writeConciseOWLAllDifferent)writeConciseOWLAllDifferent(); if (writeOWL)writeOWLFile("test.owl"); - - OntologyCloser oc = new OntologyCloser(kb); + if(writeKB)writeKBFile("test.kb"); + + OntologyCloser oc = null; String kbaddition= "_Closed"; if(closeKB) { - + oc= new OntologyCloser(kb); if(closeConcise) { oc.applyNumberRestrictionsConcise(); kbaddition = "_CloseConcise"; @@ -241,6 +282,7 @@ if (verifySomeConcepts) { + oc.updateReasoner(); verifySomeConcepts(oc); } @@ -252,79 +294,25 @@ System.out.println("Done"); }// end main + + + static void makeOntology(){ + + + + } + + protected static void verifySomeConcepts(OntologyCloser oc) { ArrayList<String> test=new ArrayList<String>(); - //String conceptStr = "ALL \"http://www.test.de/test#hasPiece\".(EXISTS \"http://www.test.de/test#fileDistanceLessThan6\".((NOT \"http://www.test.de/test#WKing\") AND ALL \"http://www.test.de/test#rankDistance1\".(\"http://www.test.de/test#WKing\" AND ALL \"http://www.test.de/test#fileDistanceLessThan2\".\"http://www.test.de/test#BKing\" AND ALL \"http://www.test.de/test#hasLowerFileThan\".\"http://www.test.de/test#WKing\")) AND ALL \"http://www.test.de/test#fileDistance1\".\"http://www.test.de/test#WRook\")"; - //conceptStr = "ALL http://www.test.de/test#hasPiece.(EXISTS http://www.test.de/test#fileDistanceLessThan6.((NOT http://www.test.de/test#WKing) AND ALL http://www.test.de/test#rankDistance1.(http://www.test.de/test#WKing AND ALL http://www.test.de/test#fileDistanceLessThan2.http://www.test.de/test#WKing AND ALL http://www.test.de/test#hasLowerFileThan.http://www.test.de/test#WKing)) AND ALL http://www.test.de/test#fileDistance1.http://www.test.de/test#WRook)"; - //conceptStr = "ALL hasPiece.(EXISTS fileDistanceLessThan6.((NOT WKing) AND ALL rankDistance1.(WKing AND ALL fileDistanceLessThan2.WKing AND ALL hasLowerFileThan.WKing)) AND ALL fileDistance1.WRook)"; - //conceptStr = "ALL \"http://www.test.de/test#hasPiece\".\"http://www.test.de/test#WKing\""; - //conceptStr = "EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#hasLowerRankThan\".(\"http://www.test.de/test#WRook\" AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\")"; - - test.add("\"http://www.test.de/test#WRook\""); - /*test.add("ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + - "\"http://www.test.de/test#WKing\""); - /*test.add("(\"http://www.test.de/test#WRook\" "+ - " AND " + - " ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + - "\"http://www.test.de/test#WKing\") ");*/ - /*test.add("(\"http://www.test.de/test#Piece\" "+ - " AND " + - " ALL \"http://www.test.de/test#fileDistanceLessThan8\"." + - "\"http://www.test.de/test#Piece\") "); - test.add("(\"http://www.test.de/test#Piece\" "+ - " AND ( " + - " ALL \"http://www.test.de/test#fileDistanceLessThan8\"." + - "\"http://www.test.de/test#Piece\" " + - " AND " + - " EXISTS \"http://www.test.de/test#fileDistanceLessThan8\"." + - "\"http://www.test.de/test#Piece\"))") ; - test.add("(\"http://www.test.de/test#Piece\" "+ - " AND ( " + - " ALL \"http://www.test.de/test#fileDistanceLessThan7\"." + - "\"http://www.test.de/test#Piece\" " + - " AND " + - " EXISTS \"http://www.test.de/test#fileDistanceLessThan7\"." + - "\"http://www.test.de/test#Piece\"))") ; - test.add("(\"http://www.test.de/test#Piece\" "+ - " AND ( " + - " ALL \"http://www.test.de/test#fileDistanceLessThan5\"." + - "\"http://www.test.de/test#Piece\" " + - " AND " + - " EXISTS \"http://www.test.de/test#fileDistanceLessThan5\"." + - "\"http://www.test.de/test#Piece\"))") ;*/ - test.add("(\"http://www.test.de/test#Piece\" "+ - " AND ( " + - " ALL \"http://www.test.de/test#fileDistanceLessThan3\"." + - "\"http://www.test.de/test#Piece\" " + - " AND " + - " EXISTS \"http://www.test.de/test#fileDistanceLessThan3\"." + - "\"http://www.test.de/test#Piece\"))") ; - test.add("(\"http://www.test.de/test#BKing\" "+ - " AND ( " + - " ALL \"http://www.test.de/test#fileDistanceLessThan3\"." + - "\"http://www.test.de/test#Piece\" " + - " AND " + - " EXISTS \"http://www.test.de/test#fileDistanceLessThan3\"." + - "\"http://www.test.de/test#Piece\"))") ; - test.add("(\"http://www.test.de/test#BKing\" "+ - " AND ( " + - " ALL \"http://www.test.de/test#fileDistanceLessThan2\"." + - "\"http://www.test.de/test#Piece\" " + - " AND " + - " EXISTS \"http://www.test.de/test#fileDistanceLessThan2\"." + - "\"http://www.test.de/test#Piece\"))") ; + test.add("(EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#rankDistanceLessThan2\".(\"http://www.test.de/test#BKing\" AND EXISTS \"http://www.test.de/test#fileDistanceLessThan1\".(\"http://www.test.de/test#A\" OR \"http://www.test.de/test#WKing\")) AND EXISTS \"http://www.test.de/test#hasPiece\".(\"http://www.test.de/test#WKing\" AND ((\"http://www.test.de/test#C\" AND EXISTS \"http://www.test.de/test#hasLowerRankThan\".\"http://www.test.de/test#A\") OR (\"http://www.test.de/test#F3\" AND EXISTS \"http://www.test.de/test#rankDistance2\".\"http://www.test.de/test#WRook\"))))"); - /*test.add("(\"http://www.test.de/test#Piece\" "+ - " AND " + - " ALL \"http://www.test.de/test#fileDistanceLessThan1\"." + - "\"http://www.test.de/test#WKing\") ");*/ + - test.add("EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#hasLowerRankThan\".(\"http://www.test.de/test#WRook\" AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\")") ; - for (int i = 0; i < test.size(); i++) { String conceptStr = test.get(i); oc.verifyConcept(conceptStr); @@ -352,21 +340,37 @@ kb.addABoxAxiom(new ObjectPropertyAssertion(getRole(fdistance + Fdist), A.id, B.id)); symmetricRoleSet.add(fdistance + Fdist); + + - if (A.meHasLowerFileThan(B)) + if (A.meHasLowerFileThan(B)){ kb.addABoxAxiom(new ObjectPropertyAssertion(fileLessThan, A.id, B.id)); + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(fileHigherThan, B.id, + A.id)); + + } // 18:00 - else if (B.meHasLowerFileThan(A)) + else if (B.meHasLowerFileThan(A)){ kb.addABoxAxiom(new ObjectPropertyAssertion(fileLessThan, B.id, A.id)); + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(fileHigherThan, A.id, + B.id)); + } - if (A.meHasLowerRankThan(B)) + if (A.meHasLowerRankThan(B)){ kb.addABoxAxiom(new ObjectPropertyAssertion(rankLessThan, A.id, B.id)); - else if (B.meHasLowerRankThan(A)) + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(rankHigherThan, B.id, + A.id)); + } + else if (B.meHasLowerRankThan(A)){ kb.addABoxAxiom(new ObjectPropertyAssertion(rankLessThan, B.id, A.id)); + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(rankHigherThan, A.id, + B.id)); + + } } public static void init() { @@ -384,7 +388,7 @@ // DisJointClasses1.add(Rank); // DisJointClasses1.add(File); DisJointClasses1.add(Game); - kb.addTBoxAxiom(new DisjointClassesAxiom(DisJointClasses1)); + //kb.addTBoxAxiom(new DisjointClassesAxiom(DisJointClasses1)); SortedSet<Description> DisJointClasses2 = new TreeSet<Description>(); DisJointClasses2 = new TreeSet<Description>(); @@ -395,7 +399,7 @@ // DisJointClasses2.add(File); // DisJointClasses2.add(Game); - kb.addTBoxAxiom(new DisjointClassesAxiom(DisJointClasses2)); + //kb.addTBoxAxiom(new DisjointClassesAxiom(DisJointClasses2)); } public static void initClassHierarchy() { @@ -404,6 +408,19 @@ kb.addTBoxAxiom(new SubClassAxiom(WKing, Piece)); kb.addTBoxAxiom(new SubClassAxiom(WRook, Piece)); kb.addTBoxAxiom(new SubClassAxiom(BKing, Piece)); + + String[] letters=new String[]{"A","B","C","D","E","F","G","H"}; + String[] numbers=new String[8]; + for (int i = 0; i < numbers.length; i++) { + numbers[i]="F"+i; + } + //System.out.println(numbers); + + for (int i = 0; i < numbers.length; i++) { + kb.addTBoxAxiom(new SubClassAxiom(getAtomicConcept(letters[i]),Piece)); + kb.addTBoxAxiom(new SubClassAxiom(getAtomicConcept(letters[i]),Piece)); + } + } static void initClassesForRankAndFile() { @@ -458,10 +475,15 @@ kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(rankLessThan, Piece)); kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(rankLessThan, Piece)); - kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(fileLessThan, Piece)); kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(fileLessThan, Piece)); - + + if(useHigherThan) { + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(rankHigherThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(rankHigherThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(fileHigherThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(fileHigherThan, Piece)); + } } static void finishBackgroundForRoles() { @@ -469,6 +491,11 @@ if (useTransitivity) { kb.addRBoxAxiom(new TransitiveObjectPropertyAxiom(rankLessThan)); kb.addRBoxAxiom(new TransitiveObjectPropertyAxiom(fileLessThan)); + if(useHigherThan) { + kb.addRBoxAxiom(new TransitiveObjectPropertyAxiom(rankHigherThan)); + kb.addRBoxAxiom(new TransitiveObjectPropertyAxiom(fileHigherThan)); + } + } if (useInverse) // INVERSE @@ -677,7 +704,20 @@ OWLAPIReasoner.exportKBToOWL(owlfile, kb, ontologyURI); } + + protected static void writeKBFile(String filename) { + System.out.println("Writing kb"); + try{ + FileWriter fw = new FileWriter(workingDir+"/" + filename,false); + fw.write(kb.toKBSyntaxString(ontologyURI.toString(), null)); + fw.flush(); + }catch (Exception e) {e.printStackTrace();} + System.out.println("done writing kb"); + + + } + protected static Individual getIndividual(String name) { return new Individual(ontologyURI + "#" + name); } Added: trunk/src/dl-learner/org/dllearner/examples/KRKModular.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/KRKModular.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/examples/KRKModular.java 2008-04-15 10:20:23 UTC (rev 788) @@ -0,0 +1,775 @@ +package org.dllearner.examples; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; +import java.util.SortedSet; +import java.util.StringTokenizer; +import java.util.TreeSet; + +import org.dllearner.algorithms.refexamples.ExampleBasedROLComponent; +import org.dllearner.core.ComponentManager; +import org.dllearner.core.KnowledgeSource; +import org.dllearner.core.LearningAlgorithm; +import org.dllearner.core.LearningProblem; +import org.dllearner.core.ReasonerComponent; +import org.dllearner.core.ReasoningService; +import org.dllearner.core.owl.ClassAssertionAxiom; +import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.Individual; +import org.dllearner.core.owl.KB; +import org.dllearner.core.owl.NamedClass; +import org.dllearner.core.owl.ObjectProperty; +import org.dllearner.core.owl.ObjectPropertyAssertion; +import org.dllearner.kb.KBFile; +import org.dllearner.learningproblems.PosNegDefinitionLP; +import org.dllearner.learningproblems.PosNegLP; +import org.dllearner.parser.KBParser; +import org.dllearner.reasoning.FastInstanceChecker; +import org.dllearner.reasoning.OWLAPIReasoner; +import org.dllearner.utilities.SimpleClock; + +/* + * Structure + * + * + * + * + * */ + +public class KRKModular { + + // REMEMBER + // FILES are letters + // RANKS are numbers + + // FLAGS + // + // turn off to not write the owl, needs about 30 seconds or more + /*static boolean writeOWL = true; + static boolean writeKB = false; + static boolean useTransitivity = false; + + static boolean writeExampleSets = true; + static boolean writeConciseOWLAllDifferent = false; + */ + boolean useHigherThan = KRKOntologyTBox.useHigherThan; + + + + //static boolean useInverse = false; + // dependent, love and marriage, horse and carriage + //static boolean useTripleSubProps = useInverse && false; + + + static String workingDir = "examples/krk/"; + static String allData = workingDir+"krkopt_no_draw.data"; + + static URI ontologyURI = KRKOntologyTBox.ontologyURI; + + // static SortedSet<String> fileSet = new TreeSet<String>(); + //static SortedSet<String> allInstances = new TreeSet<String>(); + //static SortedSet<String> classSet = new TreeSet<String>(); + //static SortedSet<String> symmetricRoleSet = new TreeSet<String>(); + + static HashMap<String, SortedSet<Individual>> classToInd = new HashMap<String, SortedSet<Individual>>(); + static HashMap<Individual, String> indToClass = new HashMap<Individual, String>(); + + static Set<ReasonerComponent> allReasoners = new HashSet<ReasonerComponent>(); + static int negativeExamplesAdded = 300; + + // static LinkedList<String> words; + public KB kb; + public ReasonerComponent reasoner; + + + //public FastInstanceChecker fic; + // static HashMap<String,SortedSet<String>> classToInd; + + + public static void init(){ + if (!new File(workingDir).exists()) { + System.out.println("Created directory: " + workingDir + + " : " + new File(workingDir).mkdir()+ "."); + } + } + /** + * @param args + */ + public static void main(String[] args) { + init(); + initAllInstancesAndReasoners(); + System.out.println("initializing finished"); + String currentClass = "ZERO"; + SortedSet<Individual> allPos = classToInd.get(currentClass); + //if(allPos.size()<400)negativeExamplesAdded = allPos.size(); + //else negativeExamplesAdded = 400; + SortedSet<Individual> tmp = new TreeSet<Individual>(); + for (Individual individual : indToClass.keySet()) { + tmp.add(individual); + } + + SortedSet<Individual> neg = getNegativeExamples(currentClass, tmp, negativeExamplesAdded); + SortedSet<Integer> lines = getLines(allPos, neg); + KB kb = getKB(lines); + + + while (true){ + + /*for (String set : classToInd.keySet()) { + for (Individual individual : classToInd.get(set)) { + if(indToClass.get(individual)==null)System.out.println(indToClass.get(individual)); + }}*/ + + + + Description d= learn(kb, allPos, neg); + SortedSet<Individual> result = retrieveAll(d); + System.out.println("still left: " + (result.size()-allPos.size())); + if(verify(currentClass, result)) { + System.out.println("Correct solution: "+ d.toKBSyntaxString(ontologyURI+"#", null)); + break;} + neg.addAll(getNegativeExamples(currentClass, result, negativeExamplesAdded)); + lines = getLines(allPos, neg); + kb = getKB(lines); + + + } + //System.out.println(allPos); + //System.out.println(neg); + + //cm. + + + /*Map<Class<? extends Component>, String> componentPrefixMapping = Start.createComponentPrefixMapping(); + ComponentManager cm = ComponentManager.getInstance(); + + Set<KnowledgeSource> sources = new HashSet<KnowledgeSource>(); + KnowledgeSource ks = cm.knowledgeSource(KBFile.class); + sources.add(ks); + cm.applyConfigEntry(ks, "url", null); + ks.init(); + */ + + + + + + + //verifyConcept("EXISTS hasPiece.EXISTS fileDistance0.TOP"); + //verifyConcept("(EXISTS \"http://dl-learner.org/krk#hasPiece\".EXISTS \"http://dl-learner.org/krk#rankDistanceLessThan2\".(\"http://dl-learner.org/krk#BKing\" AND EXISTS \"http://dl-learner.org/krk#fileDistanceLessThan1\".(\"http://dl-learner.org/krk#A\" OR \"http://dl-learner.org/krk#F3\")) AND EXISTS \"http://dl-learner.org/krk#hasPiece\".(\"http://dl-learner.org/krk#WKing\" AND ((\"http://dl-learner.org/krk#C\" AND EXISTS \"http://dl-learner.org/krk#hasLowerRankThan\".\"http://dl-learner.org/krk#A\") OR (\"http://dl-learner.org/krk#F3\" AND EXISTS \"http://dl-learner.org/krk#rankDistance2\".\"http://dl-learner.org/krk#WRook\"))))"); + //verifyConcept("EXISTS hasPiece.TOP"); + + //.writeOWLFile("test.owl"); + + } + + static Description learn(KB kb, SortedSet<Individual> pos,SortedSet<Individual> neg){ + + System.out.println(pos); + System.out.println(neg); + + ComponentManager cm = ComponentManager.getInstance(); + LearningAlgorithm la = null; + try { + Set<KnowledgeSource> sources = new HashSet<KnowledgeSource>(); + sources.add(new KBFile(kb)); + ReasonerComponent r = new FastInstanceChecker(sources); + r.init(); + ReasoningService rs = new ReasoningService(r); + + LearningProblem lp = new PosNegDefinitionLP(rs); + ((PosNegLP)lp).setPositiveExamples(pos); + ((PosNegLP)lp).setNegativeExamples(neg); + lp.init(); + + la = cm.learningAlgorithm(ExampleBasedROLComponent.class, lp, rs); + SortedSet<String> ignoredConcepts = getIgnoredConcepts(pos, neg); + + cm.applyConfigEntry(la,"useAllConstructor",false); + cm.applyConfigEntry(la,"useExistsConstructor",true); + cm.applyConfigEntry(la,"useCardinalityRestrictions",false); + cm.applyConfigEntry(la,"useNegation",false); + //cm.applyConfigEntry(la,"quiet",false); + cm.applyConfigEntry(la,"ignoredConcepts",ignoredConcepts); + + + la.init(); + + System.out.println("start learning"); + + la.start(); + //System.out.println("best"+la.getBestSolution()); + + }catch (Exception e) {e.printStackTrace();} + return la.getBestSolution(); + } + + static KB getKB(SortedSet<Integer> lines){ + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(allData)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + KRKModular km = new KRKModular(); + try { + String line = ""; + int x = 0; + while ((line = in.readLine()) != null) { + Integer tmp = new Integer(x); + if(lines.contains(tmp)) + km.addOneLineToKB(x, line); + x++; + }// endWhile + }catch (Exception e) {e.printStackTrace();} + return km.kb; + + } + + + static SortedSet<Integer> getLines(SortedSet<Individual> pos,SortedSet<Individual> neg){ + SortedSet<Integer> ret = new TreeSet<Integer>(); + + for (Individual individual : pos) { + int a = Integer.parseInt(individual.getName().substring((ontologyURI+"#g").length())); + ret.add(new Integer(a)); + } + for (Individual individual : neg) { + int a = Integer.parseInt(individual.getName().substring((ontologyURI+"#g").length())); + ret.add(new Integer(a)); + } + return ret; + + } + + static SortedSet<String> getIgnoredConcepts(SortedSet<Individual> pos,SortedSet<Individual> neg){ + SortedSet<String> ret = new TreeSet<String>(); + + for (Individual individual : pos) { + String tmp = indToClass.get(individual); + //System.out.println("pos"+tmp+individual); + ret.add(ontologyURI+"#"+tmp); + } + for (Individual individual : neg) { + //String tmp = indToClass.get((Individual)individual); + //System.out.println("neg"+tmp+individual); + for (Individual string : indToClass.keySet()) { + if(string.toString().equals(individual.getName())){ + ret.add(ontologyURI+"#"+indToClass.get(string)); + //System.out.println("aaaaaaaa"+individual.getName()); + } + + } + + } + + //System.out.println(indToClass); + return ret; + + } + + public KRKModular() { + this.kb = makeOntologyTBox(); + } + + public KRKModular(String concept) { + this.kb = makeOntologyTBox(concept); + } + + public static void initAllInstancesAndReasoners(){ + // Datei \xF6ffnen + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(allData)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + SimpleClock sc= new SimpleClock(); + KRKModular km =null; + km = new KRKModular(); + try { + String line = ""; + int x = 0; + while ((line = in.readLine()) != null) { + if (x % 10000 == 0) + {sc.print("Currently at line " + x+" : ");} + km.addOneLineToKBinit(x, line); + if(x%1000==0 && x!=0){ + km.initReasonerFact(); + allReasoners.add(km.reasoner); + km = new KRKModular(); + } + if(x==26000)break; + x++; + }// endWhile + + km.initReasonerFact(); + allReasoners.add(km.reasoner); + km = null; + + + sc.printAndSet("initialization finished"); + + //sc.printAndSet("nach Retrieval"); + //km.writeOWLFile(); + /*SortedSet<Individual> s = new TreeSet<Individual>(); + for (int i = 0; i < x; i++) { + s.add(getIndividual("g"+i)); + //if(km.check2(i))howmany++; + }*/ + //writeExampleSet(s); + + + //sc.printAndSet("before "); + //km.initReasonerFact(); + //sc.printAndSet("after initfact"); + + //SortedSet<Individual> ret = km.checkAllOWLAPI(concept, s); + //sc.print("totalfic ("+ret.size()+") for 1000: "); + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + public static SortedSet<Individual> retrieveAll(String concept){ + Description d = null; + try{ + d = KBParser.parseConcept(concept); + }catch (Exception e) {e.printStackTrace();} + return retrieveAll(d); + } + + public static SortedSet<Individual> retrieveAll(Description d){ + SortedSet<Individual> ret = new TreeSet<Individual>(); + try{ + + for (ReasonerComponent onereasoner : allReasoners) { + ret.addAll(onereasoner.retrieval(d)); + } + + }catch (Exception e) {e.printStackTrace();} + return ret; + } + + + + + + public void initReasonerFact(){ + KBFile kbFile = new KBFile(this.kb); + Set<KnowledgeSource> ks = new HashSet<KnowledgeSource>(); + ks.add(kbFile); + reasoner = new OWLAPIReasoner(ks); + ((OWLAPIReasoner)reasoner).setReasonerType("fact"); + try{ + reasoner.init(); + }catch (Exception e) {e.printStackTrace();} + } + + + + public void initFIC(){ + KBFile kbFile = new KBFile(this.kb); + Set<KnowledgeSource> ks = new HashSet<KnowledgeSource>(); + ks.add(kbFile); + //System.out.println("blabla"); + reasoner = new FastInstanceChecker(ks); + //fic.setReasonerType("fact"); + try{ + reasoner.init(); + }catch (Exception e) {e.printStackTrace();} + } + + public KB makeOntologyTBox(){ + + KRKOntologyTBox tbox = new KRKOntologyTBox(); + return tbox.getKb(); + + } + + public KB makeOntologyTBox(String concept){ + + KRKOntologyTBox tbox = new KRKOntologyTBox(); + tbox.addConcept(concept); + return tbox.getKb(); + + } + + + public void addOneLineToKBinit(int x, String line){ + + String[] ar = new String[6]; + Individual gameind = KRKOntologyTBox.getIndividual("g" + x); + ar = tokenize(line); + addToHM(ar[6], gameind); + addOneLineToKB( x, line); + + + } + + public void addOneLineToKB(int x, String line){ + + Individual gameind; + Individual wkingind; + Individual wrookind; + Individual bkingind; + + String[] ar = new String[6]; + + ar = tokenize(line); + + //String currentclass = ar[6]; + + gameind = KRKOntologyTBox.getIndividual("g" + x); + wkingind = KRKOntologyTBox.getIndividual("wking_" + ar[0] + ar[1] + "_" + x); + wrookind = KRKOntologyTBox.getIndividual("wrook_" + ar[2] + ar[3] + "_" + x); + bkingind = KRKOntologyTBox.getIndividual("bking_" + ar[4] + ar[5] + "_" + x); + + + + //allInstances.add(gameind+""); + //allInstances.add(wkingind+""); + //allInstances.add(wrookind+""); + //allInstances.add(bkingind+""); + + // save it for examplegeneration + + // .add(gameind.getName()); + //classSet.add(ar[6]); + + // CLASSES + kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.Game, gameind)); + kb.addABoxAxiom(new ClassAssertionAxiom( + getAtomicConcept(ar[6]), gameind)); + kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.WKing, wkingind)); + kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.WRook, wrookind)); + kb.addABoxAxiom(new ClassAssertionAxiom(KRKOntologyTBox.BKing, bkingind)); + + + /**Files and Ranks***/ + // FILES are letters + // RANKS are numbers + + //WKing + kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept(ar[0].toUpperCase()), wkingind)); + kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("F"+ar[1]) , wkingind)); + + //WRook + kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept(ar[2].toUpperCase()), wrookind)); + kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("F"+ar[3]) , wrookind)); + + //BKing + kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept(ar[4].toUpperCase()), bkingind)); + kb.addABoxAxiom(new ClassAssertionAxiom(getAtomicConcept("F"+ar[5]), bkingind)); + + + + // PROPERTIES + kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.hasPiece, gameind, + wkingind)); + kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.hasPiece, gameind, + wrookind)); + kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.hasPiece, gameind, + bkingind)); + + // labels + + KRKPiece WKingPiece = new KRKPiece(wkingind, ar[0], Integer + .parseInt(ar[1])); + KRKPiece WRookPiece = new KRKPiece(wrookind, ar[2], Integer + .parseInt(ar[3])); + KRKPiece BKingPiece = new KRKPiece(bkingind, ar[4], Integer + .parseInt(ar[5])); + + makeDistanceRoles(WKingPiece, WRookPiece); + makeDistanceRoles(WKingPiece, BKingPiece); + makeDistanceRoles(WRookPiece, BKingPiece); + + } + + + /*protected static void verifySomeConcepts(OntologyCloser oc) { + + ArrayList<String> test=new ArrayList<String>(); + test.add("(EXISTS \"http://www.test.de/test#hasPiece\".EXISTS \"http://www.test.de/test#rankDistanceLessThan2\".(\"http://www.test.de/test#BKing\" AND EXISTS \"http://www.test.de/test#fileDistanceLessThan1\".(\"http://www.test.de/test#A\" OR \"http://www.test.de/test#WKing\")) AND EXISTS \"http://www.test.de/test#hasPiece\".(\"http://www.test.de/test#WKing\" AND ((\"http://www.test.de/test#C\" AND EXISTS \"http://www.test.de/test#hasLowerRankThan\".\"http://www.test.de/test#A\") OR (\"http://www.test.de/test#F3\" AND EXISTS \"http://www.test.de/test#rankDistance2\".\"http://www.test.de/test#WRook\"))))"); + for (int i = 0; i < test.size(); i++) { + String conceptStr = test.get(i); + oc.verifyConcept(conceptStr); + } + /*conceptStr = "EXISTS \"http://www.test.de/test#hasLowerRankThan\"."+ + "(\"http://www.test.de/test#WRook\""+ + "AND ALL \"http://www.test.de/test#fileDistanceLessThan1\".\"http://www.test.de/test#WKing\") "; + + System.out.println(); + }*/ + + public void makeDistanceRoles(KRKPiece A, KRKPiece B) { + int Fdist = A.getFileDistance(B); + int Rdist = A.getRankDistance(B); + String rdistance = "rankDistance"; + String fdistance = "fileDistance"; + + kb.addABoxAxiom(new ObjectPropertyAssertion(getRole(rdistance + Rdist), + A.id, B.id)); + kb.addABoxAxiom(new ObjectPropertyAssertion(getRole(fdistance + Fdist), + A.id, B.id)); + + if (A.meHasLowerFileThan(B)){ + kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileLessThan, A.id, + B.id)); + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileHigherThan, B.id, + A.id)); + } + else if (B.meHasLowerFileThan(A)){ + kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileLessThan, B.id, + A.id)); + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.fileHigherThan, A.id, + B.id)); + } + + if (A.meHasLowerRankThan(B)){ + kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankLessThan, A.id, + B.id)); + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankHigherThan, B.id, + A.id)); + } + else if (B.meHasLowerRankThan(A)){ + kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankLessThan, B.id, + A.id)); + if(useHigherThan)kb.addABoxAxiom(new ObjectPropertyAssertion(KRKOntologyTBox.rankHigherThan, A.id, + B.id)); + + } + } + + + + + protected static void writeExampleSet(Set<Individual> s) { + for (Individual individual : s) { + writeToFile(workingDir+"example.txt", "+\""+individual.getName()+"\"\n"); + } + + } + + + + + + /*protected static void writeExampleSets() { + StringBuffer collect1 = new StringBuffer(); + StringBuffer collect2 = new StringBuffer(); + System.out.println("start writing sets"); + + for (String keys : classToInd.keySet()) { + System.out.println(keys); + SortedSet<String> tmpset = classToInd.get(keys); + for (String individuals : tmpset) { + collect1.append("+\"" + individuals + "\"\n"); + collect2.append("-\"" + individuals + "\"\n"); + } + + writeToFile(workingDir+"/examples_for_" + keys + ".txt", collect1 + + "\n\n" + collect2 + "\n"); + collect1 = new StringBuffer(); + collect2 = new StringBuffer(); + } + // System.out.println("Sets written"); + collect1 = new StringBuffer(); + collect2 = new StringBuffer(); + for (String key : classToInd.keySet()) { + + SortedSet<String> tmpset = classToInd.get(key); + + if (key.equals("ZERO")) {*/ + // collect1.append("/**" + key + "**/\n"); + /* for (String individuals : tmpset) { + collect1.append("+\"" + individuals + "\"\n"); + } + + continue; + } else { */ + // collect2.append("/**" + key + "**/\n"); + /* for (String individuals : tmpset) { + collect2.append("-\"" + individuals + "\"\n"); + } + } + + } + writeToFile(workingDir+"/examples_for_ZERO_and_Rest.txt", collect1 + + "\n\n" + collect2 + "\n"); + System.out.println("Example sets written"); + } + */ + + + + + + + /*protected void writeOWLFile(String filename) { + + Iterator<String> it = classSet.iterator(); + System.out.println("import(\"" + filename + "\");"); + String collect = "refinement.ignoredConcepts={"; + while (it.hasNext()) { + String tmp = (String) it.next(); + collect += "\n\"" + getAtomicConcept(tmp).getName() + "\","; + } + collect = collect.substring(0, collect.length() - 1); + System.out.println(collect + "};"); + + System.out.println("Writing owl"); + File owlfile = new File(workingDir+"/" + filename); + // System.out.println(kb.toString("http://www.test.de/test", new + // HashMap<String, String>())); + OWLAPIReasoner.exportKBToOWL(owlfile, kb, ontologyURI); + + }*/ + + protected void writeOWLFile() { + writeOWLFile("test.owl"); + } + + protected void writeOWLFile(String filename) { + + System.out.println("Writing owl"); + File owlfile = new File(workingDir+"/" + filename); + OWLAPIReasoner.exportKBToOWL(owlfile, this.kb, ontologyURI); + + } + + + + protected static void writeToFile(String filename, String content) { + // create the file we want to use + File file = new File(filename); + + try { + file.createNewFile(); + FileOutputStream fos = new FileOutputStream(filename, true); + // ObjectOutputStream o = new ObjectOutputStream(fos); + fos.write(content.getBytes()); + fos.flush(); + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + protected static void addToHM(String className, Individual ind) { + if (classToInd.get(className) == null) + classToInd.put(className, new TreeSet<Individual>()); + + classToInd.get(className).add(ind); + indToClass.put(ind, className); + + } + + + protected static Individual getIndividual(String name) { + return new Individual(ontologyURI + "#" + name); + } + + protected static ObjectProperty getRole(String name) { + return new ObjectProperty(ontologyURI + "#" + name); + } + + protected static NamedClass getAtomicConcept(String name) { + return new NamedClass(ontologyURI + "#" + name); + } + + public static String[] tokenize(String s) { + StringTokenizer st = new StringTokenizer(s, ","); + + String tmp = ""; + String[] ret = new String[7]; + int x = 0; + while (st.hasMoreTokens()) { + tmp = st.nextToken(); + if (x == 6) + tmp = tmp.toUpperCase(); + ret[x] = tmp; + x++; + } + return ret; + + } + + static SortedSet<Individual> getNegativeExamples(String currentClass, SortedSet<Individual> allRetrieved, int howmany) { + SortedSet<Individual> ret = new TreeSet<Individual>(); + + //clean + SortedSet<Individual> allPos = classToInd.get(currentClass); + for (Individual individual : allPos) { + if(!allRetrieved.remove(individual))System.out.println("WARNING, not all positives covered");; + } + + Random r = new Random(); + double treshold = ((double)howmany)/allRetrieved.size(); + //System.out.println("treshold"+howmany); + //System.out.println("treshold"+allRetrieved.size()); + //System.out.println("treshold"+treshold); + int added=0; + for (Individual oneInd : allRetrieved) { + if(r.nextDouble()<treshold) { + ret.add(oneInd); + added++; + } + } + System.out.println(added+" new negs added"); + return ret; + } + static boolean verify(String currentClass, SortedSet<Individual> allRetrieved) { + //clean + SortedSet<Individual> allPos = classToInd.get(currentClass); + boolean hasAll=true; + for (Individual individual : allPos) { + if(!allRetrieved.contains(individual))hasAll=false; + } + if(hasAll && allRetrieved.size()==allPos.size()){return true;} + else return false; + + } + + /*public SortedSet<Individual> checkAll(String concept, SortedSet<Individual> s){ + try{ + Description d = KBParser.parseConcept(concept,ontologyURI.toString()+"#"); + + return reasoner.instanceCheck(d, s); + }catch (Exception e) {e.printStackTrace();} + return null; +} + +public SortedSet<Individual> checkAllOWLAPI(String concept,SortedSet<Individual> s){ + try{ + Description d = KBParser.parseConcept(concept,ontologyURI.toString()+"#"); + return reasoner.instanceCheck(d, s); + }catch (Exception e) {e.printStackTrace();} + return null; +} + +/*public SortedSet<Individual> retrieveAllowlAPI(String concept){ + try{ + Description d = KBParser.parseConcept(concept,ontologyURI.toString()+"#"); + return reasoner.retrieval(d); + }catch (Exception e) {e.printStackTrace();} + return null; +}*/ + +} Added: trunk/src/dl-learner/org/dllearner/examples/KRKOntologyTBox.java =================================================================== --- trunk/src/dl-learner/org/dllearner/examples/KRKOntologyTBox.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/examples/KRKOntologyTBox.java 2008-04-15 10:20:23 UTC (rev 788) @@ -0,0 +1,251 @@ +package org.dllearner.examples; + +import java.net.URI; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.dllearner.core.owl.ClassAssertionAxiom; +import org.dllearner.core.owl.DatatypeProperty; +import org.dllearner.core.owl.Description; +import org.dllearner.core.owl.DisjointClassesAxiom; +import org.dllearner.core.owl.EquivalentClassesAxiom; +import org.dllearner.core.owl.Individual; +import org.dllearner.core.owl.KB; +import org.dllearner.core.owl.NamedClass; +import org.dllearner.core.owl.ObjectProperty; +import org.dllearner.core.owl.ObjectPropertyAssertion; +import org.dllearner.core.owl.ObjectPropertyDomainAxiom; +import org.dllearner.core.owl.ObjectPropertyRangeAxiom; +import org.dllearner.core.owl.SubClassAxiom; +import org.dllearner.core.owl.SubObjectPropertyAxiom; +import org.dllearner.core.owl.SymmetricObjectPropertyAxiom; +import org.dllearner.parser.KBParser; + +public class KRKOntologyTBox { + + private KB kb; + static URI ontologyURI = URI.create("http://dl-learner.org/krk"); + + static boolean useHigherThan=false; + static boolean useInverse = false; + + static NamedClass Game = getAtomicConcept("Game"); + static NamedClass WKing = getAtomicConcept("WKing"); + static NamedClass WRook = getAtomicConcept("WRook"); + static NamedClass BKing = getAtomicConcept("BKing"); + // had to rename, too much similarity to java.io.File + static NamedClass FileData = getAtomicConcept("File"); + static NamedClass Rank = getAtomicConcept("Rank"); + static NamedClass Piece = getAtomicConcept("Piece"); + + static ObjectProperty hasPiece = getRole("hasPiece"); + static ObjectProperty hasWKing = getRole("hasWKing"); + static ObjectProperty hasWRook = getRole("hasWRook"); + static ObjectProperty hasBKing = getRole("hasBKing"); + + static ObjectProperty hasPieceInv = getRole("hasGame"); + static ObjectProperty hasWKingInv = getRole("hasWKingInv"); + static ObjectProperty hasWRookInv = getRole("hasWRookInv"); + static ObjectProperty hasBKingInv = getRole("hasBKingInv"); + + static ObjectProperty rankLessThan = getRole("hasLowerRankThan"); + static ObjectProperty fileLessThan = getRole("hasLowerFileThan"); + + static ObjectProperty rankHigherThan = getRole("hasHigherRankThan"); + static ObjectProperty fileHigherThan = getRole("hasHigherFileThan"); + + + /*public KRKOntologyTBox(KB kbin){ + this.kb=kbin; + + }*/ + + public KRKOntologyTBox(){ + this.kb=new KB(); + initOntologyTBox(); + + + } + + public void addConcept(String concept){ + try{ + //make Description + Description d = KBParser.parseConcept(concept,ontologyURI.toString()+"#"); + //d.addChild(oecr); + kb.addTBoxAxiom(new EquivalentClassesAxiom(getAtomicConcept("test"),d)); + + }catch (Exception e) {e.printStackTrace();} + } + + public void initOntologyTBox(){ + + //DISJOINTCLASSES + SortedSet<Description> DisJointClasses1 = new TreeSet<Description>(); + DisJointClasses1.add(Piece); + DisJointClasses1.add(Game); + kb.addTBoxAxiom(new DisjointClassesAxiom(DisJointClasses1)); + + SortedSet<Description> DisJointClasses2 = new TreeSet<Description>(); + DisJointClasses2 = new TreeSet<Description>(); + DisJointClasses2.add(WKing); + DisJointClasses2.add(WRook); + DisJointClasses2.add(BKing); + // DisJointClasses2.add(Rank); + // DisJointClasses2.add(File); + // DisJointClasses2.add(Game); + kb.addTBoxAxiom(new DisjointClassesAxiom(DisJointClasses2)); + + /**CLASSES***/ + // all sub of piece + kb.addTBoxAxiom(new SubClassAxiom(WKing, Piece)); + kb.addTBoxAxiom(new SubClassAxiom(WRook, Piece)); + kb.addTBoxAxiom(new SubClassAxiom(BKing, Piece)); + + String[] letters=new String[]{"A","B","C","D","E","F","G","H"}; + String[] numbers=new String[8]; + for (int i = 0; i < numbers.length; i++) { + numbers[i]="F"+(i+1); + } + //System.out.println(numbers); + + for (int i = 0; i < numbers.length; i++) { + kb.addTBoxAxiom(new SubClassAxiom(getAtomicConcept(letters[i]),Piece)); + kb.addTBoxAxiom(new SubClassAxiom(getAtomicConcept(numbers[i]),Piece)); + } + + + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(hasPiece, Game)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(hasPiece, Piece)); + + + if (useInverse) { + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(hasPieceInv, Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(hasPieceInv, Game)); + + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(hasWKingInv, WKing)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(hasWKingInv, Game)); + + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(hasWRookInv, WRook)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(hasWRookInv, Game)); + + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(hasBKingInv, BKing)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(hasBKingInv, Game)); + } + + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(rankLessThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(rankLessThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(fileLessThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(fileLessThan, Piece)); + + if(useHigherThan) { + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(rankHigherThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(rankHigherThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(fileHigherThan, Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(fileHigherThan, Piece)); + } + + finishBackgroundForRoles(); + + //return this.kb; + + } + + + public void finishBackgroundForRoles() { + + for (int i = 8; i > 0; i--) { + + + ObjectProperty rankDistance = getRole("rankDistance"+(i-1)); + ObjectProperty fileDistance = getRole("fileDistance"+(i-1)); + kb.addRBoxAxiom(new SymmetricObjectPropertyAxiom(rankDistance)); + kb.addRBoxAxiom(new SymmetricObjectPropertyAxiom(fileDistance)); + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(rankDistance, + KRKOntologyTBox.Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(rankDistance, + KRKOntologyTBox.Piece)); + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom(fileDistance, + KRKOntologyTBox.Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom(fileDistance, + KRKOntologyTBox.Piece)); + + + + kb.addRBoxAxiom(new SubObjectPropertyAxiom( + getRole("rankDistance" + (i - 1)), + getRole("rankDistanceLessThan" + i))); + kb.addRBoxAxiom(new SubObjectPropertyAxiom( + getRole("fileDistance" + (i - 1)), + getRole("fileDistanceLessThan" + i))); + + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom( + getRole("rankDistanceLessThan" + i), KRKOntologyTBox.Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom( + getRole("rankDistanceLessThan" + i), KRKOntologyTBox.Piece)); + + kb.addRBoxAxiom(new ObjectPropertyDomainAxiom( + getRole("fileDistanceLessThan" + i), KRKOntologyTBox.Piece)); + kb.addRBoxAxiom(new ObjectPropertyRangeAxiom( + getRole("fileDistanceLessThan" + i), KRKOntologyTBox.Piece)); + + + if(i==1) continue; + + kb.addRBoxAxiom(new SubObjectPropertyAxiom( + getRole("rankDistanceLessThan" + (i - 1)), + getRole("rankDistanceLessThan" + i))); + kb.addRBoxAxiom(new SubObjectPropertyAxiom( + getRole("fileDistanceLessThan" + (i - 1)), + getRole("fileDistanceLessThan" + i))); + + + } + + + } + + + protected static Individual getIndividual(String name) { + return new Individual(ontologyURI + "#" + name); + } + + protected static ObjectProperty getRole(String name) { + return new ObjectProperty(ontologyURI + "#" + name); + } + + @SuppressWarnings("unused") + protected static DatatypeProperty getDatatypeProperty(String name) { + return new DatatypeProperty(ontologyURI + "#" + name); + } + + protected static NamedClass getAtomicConcept(String name) { + return new NamedClass(ontologyURI + "#" + name); + } + + @SuppressWarnings("unused") + protected static String getURI(String name) { + return ontologyURI + "#" + name; + } + + @SuppressWarnings("unused") + protected static ClassAssertionAxiom getConceptAssertion(String concept, + String instance) { + Individual ind = getIndividual(instance); + NamedClass c = getAtomicConcept(concept); + return new ClassAssertionAxiom(c, ind); + } + + @SuppressWarnings("unused") + protected static ObjectPropertyAssertion getRoleAssertion(String role, + String i1, String i2) { + Individual ind1 = getIndividual(i1); + Individual ind2 = getIndividual(i2); + ObjectProperty ar = getRole(role); + return new ObjectPropertyAssertion(ar, ind1, ind2); + } + + public KB getKb() { + return kb; + } + +} Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java 2008-04-14 22:45:16 UTC (rev 787) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java 2008-04-15 10:20:23 UTC (rev 788) @@ -145,6 +145,14 @@ return positiveExamples; } + public void setNegativeExamples(SortedSet<Individual> set) { + this.negativeExamples=set; + } + + public void setPositiveExamples(SortedSet<Individual> set) { + this.positiveExamples=set; + } + public abstract int coveredNegativeExamplesOrTooWeak(Description concept); public double getPercentPerLengthUnit() { Modified: trunk/src/dl-learner/org/dllearner/parser/KBParser.java =================================================================== --- trunk/src/dl-learner/org/dllearner/parser/KBParser.java 2008-04-14 22:45:16 UTC (rev 787) +++ trunk/src/dl-learner/org/dllearner/parser/KBParser.java 2008-04-15 10:20:23 UTC (rev 788) @@ -18,6 +18,12 @@ return internalNamespace + name; } + //TODO beware of this function it is evil + public static Description parseConcept(String string, String namespace) throws ParseException { + internalNamespace = namespace; + return parseConcept(string); + } + public static Description parseConcept(String string) throws ParseException { // when just parsing the string as concept, we have no guarantee // that the parser uses all symbols, e.g. a AND b returns just a Modified: trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java 2008-04-14 22:45:16 UTC (rev 787) +++ trunk/src/dl-learner/org/dllearner/utilities/SimpleClock.java 2008-04-15 10:20:23 UTC (rev 788) @@ -11,6 +11,10 @@ time=System.currentTimeMillis(); } + + + + /** * prints time needed * and resets the clock @@ -33,6 +37,18 @@ time=now; } + + /** + * prints time needed + * + * @param s String for printing + */ + public void print(String s) { + long now=System.currentTimeMillis(); + System.out.println(s+" needed "+(now-time)+" ms"); + + } + public void setTime() { time=System.currentTimeMillis(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |