You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(120) |
Sep
(36) |
Oct
(116) |
Nov
(17) |
Dec
(44) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(143) |
Feb
(192) |
Mar
(74) |
Apr
(84) |
May
(105) |
Jun
(64) |
Jul
(49) |
Aug
(120) |
Sep
(159) |
Oct
(156) |
Nov
(51) |
Dec
(28) |
2009 |
Jan
(17) |
Feb
(55) |
Mar
(33) |
Apr
(57) |
May
(54) |
Jun
(28) |
Jul
(6) |
Aug
(16) |
Sep
(38) |
Oct
(30) |
Nov
(26) |
Dec
(52) |
2010 |
Jan
(7) |
Feb
(91) |
Mar
(65) |
Apr
(2) |
May
(14) |
Jun
(25) |
Jul
(38) |
Aug
(48) |
Sep
(80) |
Oct
(70) |
Nov
(75) |
Dec
(77) |
2011 |
Jan
(68) |
Feb
(53) |
Mar
(51) |
Apr
(35) |
May
(65) |
Jun
(101) |
Jul
(29) |
Aug
(230) |
Sep
(95) |
Oct
(49) |
Nov
(110) |
Dec
(63) |
2012 |
Jan
(41) |
Feb
(42) |
Mar
(25) |
Apr
(46) |
May
(51) |
Jun
(44) |
Jul
(45) |
Aug
(29) |
Sep
(12) |
Oct
(9) |
Nov
(17) |
Dec
(2) |
2013 |
Jan
(12) |
Feb
(14) |
Mar
(7) |
Apr
(16) |
May
(54) |
Jun
(27) |
Jul
(11) |
Aug
(5) |
Sep
(85) |
Oct
(27) |
Nov
(37) |
Dec
(32) |
2014 |
Jan
(8) |
Feb
(29) |
Mar
(5) |
Apr
(3) |
May
(22) |
Jun
(3) |
Jul
(4) |
Aug
(3) |
Sep
|
Oct
|
Nov
|
Dec
|
From: <jen...@us...> - 2007-10-16 09:32:14
|
Revision: 227 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=227&view=rev Author: jenslehmann Date: 2007-10-16 02:32:08 -0700 (Tue, 16 Oct 2007) Log Message: ----------- refactored web service classes, added some documentation, adjusted build script Modified Paths: -------------- trunk/build.xml trunk/src/dl-learner/org/dllearner/server/DLLearnerWSStart.java trunk/src/dl-learner/org/dllearner/server/package.html Added Paths: ----------- trunk/src/dl-learner/org/dllearner/server/ClientState.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java trunk/src/dl-learner/org/dllearner/server/jaxws/package.html Removed Paths: ------------- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java trunk/src/dl-learner/org/dllearner/server/State.java Modified: trunk/build.xml =================================================================== --- trunk/build.xml 2007-10-16 09:27:26 UTC (rev 226) +++ trunk/build.xml 2007-10-16 09:32:08 UTC (rev 227) @@ -164,8 +164,7 @@ <arg value="-verbose"/> <arg value="-cp"/> <arg value="${wsgenpath}"/> - <!--<arg value=".;../../classes;../../library/dig1.1-xmlbeans.jar;../../library/kaon2.jar;../../library/xbean.jar;../../library/owlapi/;../../library/owlapi/antlr-runtime-3.0.jar;../../library/owlapi/commons-lang-2.2.jar;../../library/owlapi/owlapi-api.jar;../../library/owlapi/owlapi-apibinding.jar;../../library/owlapi/owlapi-change.jar;../../library/owlapi/owlapi-debugging.jar;../../library/owlapi/owlapi-dig1_1.jar;../../library/owlapi/owlapi-functionalparser.jar;../../library/owlapi/owlapi-functionalrenderer.jar;../../library/owlapi/owlapi-impl.jar;../../library/owlapi/owlapi-krssparser.jar;../../library/owlapi/owlapi-mansyntaxparser.jar;../../library/owlapi/owlapi-mansyntaxrenderer.jar;../../library/owlapi/owlapi-metrics.jar;../../library/owlapi/owlapi-oboparser.jar;../../library/owlapi/owlapi-owlxmlparser.jar;../../library/owlapi/owlapi-owlxmlrenderer.jar;../../library/owlapi/owlapi-rdfapi.jar;../../library/owlapi/owlapi-rdfxmlparser.jar;../../library/owlapi/owlapi-rdfxmlrenderer.jar;../../library/owlapi/owlapi-util.jar"/>--> - <arg value="org.dllearner.server.DLLearnerWSNew"/> + <arg value="org.dllearner.server.DLLearnerWS"/> </exec> </target> Copied: trunk/src/dl-learner/org/dllearner/server/ClientState.java (from rev 218, trunk/src/dl-learner/org/dllearner/server/State.java) =================================================================== --- trunk/src/dl-learner/org/dllearner/server/ClientState.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/server/ClientState.java 2007-10-16 09:32:08 UTC (rev 227) @@ -0,0 +1,209 @@ +/** + * Copyright (C) 2007, 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.server; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +import org.dllearner.core.Component; +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.kb.OWLFile; +import org.dllearner.kb.SparqlEndpoint; + +/** + * Stores the state of a DL-Learner client session. + * + * @author Jens Lehmann + * + */ +public class ClientState { + + // stores the mapping between component IDs and component + // (note that this allows us to keep all references to components even + // if they are note used anymore e.g. a deleted knowledge source) + private Map<Integer,Component> componentIDs = new HashMap<Integer,Component>(); + + private Set<KnowledgeSource> knowledgeSources = new HashSet<KnowledgeSource>(); + + private LearningProblem learningProblem; + + private ReasonerComponent reasonerComponent; + private ReasoningService reasoningService; + + private LearningAlgorithm learningAlgorithm; + + private Random rand=new Random(); + + private boolean isAlgorithmRunning = false; + + private int generateComponentID(Component component) { + int id; + do { + id = rand.nextInt(); + } while(componentIDs.keySet().contains(id)); + componentIDs.put(id, component); + return id; + } + + /** + * @return the isAlgorithmRunning + */ + public boolean isAlgorithmRunning() { + return isAlgorithmRunning; + } + + /** + * @param isAlgorithmRunning the isAlgorithmRunning to set + */ + public void setAlgorithmRunning(boolean isAlgorithmRunning) { + this.isAlgorithmRunning = isAlgorithmRunning; + } + +// public Component getComponent(Class<? extends Component> componentClass) throws UnknownComponentException { +// if(learningProblem.getClass().equals(componentClass)) +// return learningProblem; +// else if(learningAlgorithm.getClass().equals(componentClass)) +// return learningAlgorithm; +// else if(reasonerComponent.getClass().equals(componentClass)) +// return reasonerComponent; +// else if(KnowledgeSource.class.isAssignableFrom(componentClass)) { +// +// +// for(KnowledgeSource ks : knowledgeSources) { +// if(ks.getClass().equals(componentClass)) +// return ks; +// } +// throw new UnknownComponentException(componentClass.getName()); +// } else +// throw new UnknownComponentException(componentClass.getName()); +// } + + /** + * Removes a knowledge source with the given URL (independant of its type). + * @param url URL of the OWL file or SPARQL Endpoint. + * @return True if a knowledge source was deleted, false otherwise. + */ + public boolean removeKnowledgeSource(String url) { + Iterator<KnowledgeSource> it = knowledgeSources.iterator(); + while(it.hasNext()) { + KnowledgeSource source = it.next(); + if((source instanceof OWLFile && ((OWLFile)source).getURL().toString().equals(url)) + || (source instanceof SparqlEndpoint && ((SparqlEndpoint)source).getURL().toString().equals(url)) ) { + it.remove(); + return true; + } + } + return false; + } + + /** + * @return the learningProblem + */ + public LearningProblem getLearningProblem() { + return learningProblem; + } + + /** + * @param learningProblem the learningProblem to set + */ + public int setLearningProblem(LearningProblem learningProblem) { + this.learningProblem = learningProblem; + return generateComponentID(learningProblem); + } + + /** + * @return the reasonerComponent + */ + public ReasonerComponent getReasonerComponent() { + return reasonerComponent; + } + + /** + * Sets the reasoner component and creates the corresponding + * <code>ReasoningService</code> instance. + * + * @param reasonerComponent the reasonerComponent to set + */ + public int setReasonerComponent(ReasonerComponent reasonerComponent) { + this.reasonerComponent = reasonerComponent; + reasoningService = new ReasoningService(reasonerComponent); + return generateComponentID(reasonerComponent); + } + + /** + * @return the learningAlgorithm + */ + public LearningAlgorithm getLearningAlgorithm() { + return learningAlgorithm; + } + + /** + * @param learningAlgorithm the learningAlgorithm to set + */ + public int setLearningAlgorithm(LearningAlgorithm learningAlgorithm) { + this.learningAlgorithm = learningAlgorithm; + return generateComponentID(learningAlgorithm); + } + + /** + * @return the reasoningService + */ + public ReasoningService getReasoningService() { + return reasoningService; + } + + /** + * @param key + * @return + * @see java.util.Map#get(java.lang.Object) + */ + public Component getComponent(int id) { + return componentIDs.get(id); + } + + /** + * @param e + * @return + */ + public int addKnowledgeSource(KnowledgeSource ks) { + knowledgeSources.add(ks); + return generateComponentID(ks); + + } + + public boolean removeKnowledgeSource(int componentID) { + return knowledgeSources.remove(componentIDs.get(componentID)); + } + + /** + * @return the knowledgeSources + */ + public Set<KnowledgeSource> getKnowledgeSources() { + return knowledgeSources; + } +} Copied: trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java (from rev 225, trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java) =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java 2007-10-16 09:32:08 UTC (rev 227) @@ -0,0 +1,350 @@ +/** + * Copyright (C) 2007, 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.server; + +import java.util.Arrays; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; + +import javax.jws.WebMethod; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; + +import org.dllearner.algorithms.refinement.ROLearner; +import org.dllearner.core.Component; +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.dl.AtomicConcept; +import org.dllearner.core.dl.AtomicRole; +import org.dllearner.core.dl.Concept; +import org.dllearner.core.dl.Individual; +import org.dllearner.kb.OWLFile; +import org.dllearner.kb.SparqlEndpoint; +import org.dllearner.learningproblems.PosNegDefinitionLP; +import org.dllearner.learningproblems.PosNegInclusionLP; +import org.dllearner.parser.KBParser; +import org.dllearner.parser.ParseException; +import org.dllearner.reasoning.DIGReasoner; +import org.dllearner.utilities.Datastructures; + +/** + * DL-Learner web service interface. + * + * @author Jens Lehmann + * @author Sebastian Hellmann + * + */ +@WebService(name = "DLLearnerWebService") +@SOAPBinding(style = SOAPBinding.Style.RPC) +public class DLLearnerWS { + + private Map<Integer, ClientState> clients = new TreeMap<Integer,ClientState>(); + private Random rand=new Random(); + private static ComponentManager cm = ComponentManager.getInstance(); + + // defines the components, which are accessible for the web service + private static Map<String,Class<? extends KnowledgeSource>> knowledgeSourceMapping = new TreeMap<String,Class<? extends KnowledgeSource>>(); + private static Map<String,Class<? extends ReasonerComponent>> reasonerMapping = new TreeMap<String,Class<? extends ReasonerComponent>>(); + private static Map<String,Class<? extends LearningProblem>> learningProblemMapping = new TreeMap<String,Class<? extends LearningProblem>>(); + private static Map<String,Class<? extends LearningAlgorithm>> learningAlgorithmMapping = new TreeMap<String,Class<? extends LearningAlgorithm>>(); + + public DLLearnerWS() { + knowledgeSourceMapping.put("owlfile", OWLFile.class); + knowledgeSourceMapping.put("sparql", SparqlEndpoint.class); + reasonerMapping.put("dig", DIGReasoner.class); + learningProblemMapping.put("posNegDefinition", PosNegDefinitionLP.class); + learningProblemMapping.put("posNegInclusion", PosNegInclusionLP.class); + learningAlgorithmMapping.put("refinement", ROLearner.class); + } + + /** + * Generates a unique ID for the client and initialises a session. + * Using the ID the client can call the other web service methods. + * Two calls to this method are guaranteed to return different results. + * + * @return A session ID. + */ + @WebMethod + public int generateID() { + int id; + do { + id = rand.nextInt(); + } while(clients.containsKey(id)); + clients.put(id, new ClientState()); + return id; + } + + // returns session state or throws client not known exception + private ClientState getState(int id) throws ClientNotKnownException { + ClientState state = clients.get(id); + if(state==null) + throw new ClientNotKnownException(id); + return state; + } + + // returns the class which is referred to by the string + @SuppressWarnings({"unused"}) + private Class<? extends Component> getComponent(String component) throws UnknownComponentException { + if(knowledgeSourceMapping.containsKey(component)) + return knowledgeSourceMapping.get(component); + else if(reasonerMapping.containsKey(component)) + return reasonerMapping.get(component); + else if(learningProblemMapping.containsKey(component)) + return learningProblemMapping.get(component); + else if(learningAlgorithmMapping.containsKey(component)) + return learningAlgorithmMapping.get(component); + else + throw new UnknownComponentException(component); + } + + /////////////////////////////////////// + // methods for basic component setup // + /////////////////////////////////////// + + /** + * Adds a knowledge source. + * + * @return An identifier for the component. + */ + @WebMethod + public int addKnowledgeSource(int id, String component, String url) throws ClientNotKnownException, UnknownComponentException { + ClientState state = getState(id); + Class<? extends KnowledgeSource> ksClass = knowledgeSourceMapping.get(component); + if(ksClass == null) + throw new UnknownComponentException(component); + KnowledgeSource ks = cm.knowledgeSource(ksClass); + cm.applyConfigEntry(ks, "url", url); + return state.addKnowledgeSource(ks); + } + + @WebMethod + public void removeKnowledgeSource(int id, int componentID) throws ClientNotKnownException { + getState(id).removeKnowledgeSource(componentID); + } + + @WebMethod + public int setReasoner(int id, String component) throws ClientNotKnownException, UnknownComponentException { + ClientState state = getState(id); + Class<? extends ReasonerComponent> rcClass = reasonerMapping.get(component); + if(rcClass == null) + throw new UnknownComponentException(component); + + ReasonerComponent rc = cm.reasoner(rcClass, state.getKnowledgeSources()); + return state.setReasonerComponent(rc); + } + + @WebMethod + public int setLearningProblem(int id, String component) throws ClientNotKnownException, UnknownComponentException { + ClientState state = getState(id); + Class<? extends LearningProblem> lpClass = learningProblemMapping.get(component); + if(lpClass == null) + throw new UnknownComponentException(component); + + LearningProblem lp = cm.learningProblem(lpClass, state.getReasoningService()); + return state.setLearningProblem(lp); + } + + @WebMethod + public int setLearningAlgorithm(int id, String component) throws ClientNotKnownException, UnknownComponentException { + ClientState state = getState(id); + Class<? extends LearningAlgorithm> laClass = learningAlgorithmMapping.get(component); + if(laClass == null) + throw new UnknownComponentException(component); + + LearningAlgorithm la = cm.learningAlgorithm(laClass, state.getLearningProblem(), state.getReasoningService()); + return state.setLearningAlgorithm(la); + } + + /** + * Initialise all components. + * @param id Session ID. + */ + @WebMethod + public void init(int id) throws ClientNotKnownException { + ClientState state = getState(id); + for(KnowledgeSource ks : state.getKnowledgeSources()) + ks.init(); + state.getReasonerComponent().init(); + state.getLearningProblem().init(); + state.getLearningAlgorithm().init(); + } + + /** + * Starts the learning algorithm and returns the best concept found. This + * method will block until learning is completed. + * + * @param id Session ID. + * @return The best solution found. + * @throws ClientNotKnownException + */ + @WebMethod + public String learn(int id) throws ClientNotKnownException { + ClientState state = getState(id); + state.getLearningAlgorithm().start(); + return state.getLearningAlgorithm().getBestSolution().toString(); + } + + /** + * Starts the learning algorithm and returns immediately. The learning + * algorithm is executed in its own thread and can be queried and + * controlled using other Web Service methods. + * + * @param id Session ID. + * @throws ClientNotKnownException + */ + @WebMethod + public void learnThreaded(int id) throws ClientNotKnownException { + final ClientState state = getState(id); + Thread learningThread = new Thread() { + @Override + public void run() { + state.setAlgorithmRunning(true); + state.getLearningAlgorithm().start(); + state.setAlgorithmRunning(false); + } + }; + learningThread.start(); + } + + @WebMethod + public String getCurrentlyBestConcept(int id) throws ClientNotKnownException { + ClientState state = getState(id); + return state.getLearningAlgorithm().getBestSolution().toString(); + } + + @WebMethod + public boolean isAlgorithmRunning(int id) throws ClientNotKnownException { + return getState(id).isAlgorithmRunning(); + } + + /** + * Stops the learning algorithm smoothly. + * @param id + * @throws ClientNotKnownException + */ + @WebMethod + public void stop(int id) throws ClientNotKnownException { + getState(id).getLearningAlgorithm().stop(); + } + + ///////////////////////////////////////// + // methods for component configuration // + ///////////////////////////////////////// + + @WebMethod + public void setPositiveExamples(int id, String[] positiveExamples) throws ClientNotKnownException { + ClientState state = getState(id); + Set<String> posExamples = new TreeSet<String>(Arrays.asList(positiveExamples)); + cm.applyConfigEntry(state.getLearningProblem(), "positiveExamples", posExamples); + } + + @WebMethod + public void setNegativeExamples(int id, String[] negativeExamples) throws ClientNotKnownException { + ClientState state = getState(id); + Set<String> negExamples = new TreeSet<String>(Arrays.asList(negativeExamples)); + cm.applyConfigEntry(state.getLearningProblem(), "negativeExamples", negExamples); + } + + @WebMethod + public void applyConfigEntryInt(int sessionID, int componentID, String optionName, Integer value) throws ClientNotKnownException, UnknownComponentException { + applyConfigEntry(sessionID, componentID,optionName,value); + } + + @WebMethod + public void applyConfigEntryString(int sessionID, int componentID, String optionName, String value) throws ClientNotKnownException, UnknownComponentException { + applyConfigEntry(sessionID, componentID,optionName,value); + } + + @WebMethod + public void applyConfigEntryStringArray(int sessionID, int componentID, String optionName, String[] value) throws ClientNotKnownException, UnknownComponentException { + Set<String> stringSet = new TreeSet<String>(Arrays.asList(value)); + applyConfigEntry(sessionID, componentID,optionName,stringSet); + } + + @WebMethod + public void applyConfigEntryBoolean(int sessionID, int componentID, String optionName, Boolean value) throws ClientNotKnownException, UnknownComponentException { + applyConfigEntry(sessionID, componentID,optionName,value); + } + + private void applyConfigEntry(int sessionID, int componentID, String optionName, Object value) throws ClientNotKnownException, UnknownComponentException { + ClientState state = getState(sessionID); + Component component = state.getComponent(componentID); + cm.applyConfigEntry(component, optionName, value); + } + + //////////////////////////////////// + // reasoning and querying methods // + //////////////////////////////////// + + @WebMethod + public String[] getAtomicConcepts(int id) throws ClientNotKnownException { + Set<AtomicConcept> atomicConcepts = getState(id).getReasoningService().getAtomicConcepts(); + return Datastructures.sortedSet2StringListConcepts(atomicConcepts); + } + + @WebMethod + public String getSubsumptionHierarchy(int id) throws ClientNotKnownException { + return getState(id).getReasoningService().toString(); + } + + @WebMethod + public String[] retrieval(int id, String conceptString) throws ClientNotKnownException { + ClientState state = getState(id); + // call parser to parse atomic concept + Concept concept = null; + try { + concept = KBParser.parseConcept(conceptString); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Set<Individual> individuals = state.getReasoningService().retrieval(concept); + return Datastructures.sortedSet2StringListIndividuals(individuals); + } + + @WebMethod + public String[] getAtomicRoles(int id) throws ClientNotKnownException { + ClientState state = getState(id); + Set<AtomicRole> roles = state.getReasoningService().getAtomicRoles(); + return Datastructures.sortedSet2StringListRoles(roles); + } + + @WebMethod + public String[] getInstances(int id) throws ClientNotKnownException { + ClientState state = getState(id); + Set<Individual> individuals = state.getReasoningService().getIndividuals(); + return Datastructures.sortedSet2StringListIndividuals(individuals); + } + + @WebMethod + public String[] getIndividualsForARole(int id, String role) throws ClientNotKnownException { + ClientState state = getState(id); + Map<Individual,SortedSet<Individual>> m = state.getReasoningService().getRoleMembers(new AtomicRole(role)); + Set<Individual> individuals = m.keySet(); + return Datastructures.sortedSet2StringListIndividuals(individuals); + } +} Deleted: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-16 09:27:26 UTC (rev 226) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-16 09:32:08 UTC (rev 227) @@ -1,350 +0,0 @@ -/** - * Copyright (C) 2007, 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.server; - -import java.util.Arrays; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -import javax.jws.WebMethod; -import javax.jws.WebService; -import javax.jws.soap.SOAPBinding; - -import org.dllearner.algorithms.refinement.ROLearner; -import org.dllearner.core.Component; -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.dl.AtomicConcept; -import org.dllearner.core.dl.AtomicRole; -import org.dllearner.core.dl.Concept; -import org.dllearner.core.dl.Individual; -import org.dllearner.kb.OWLFile; -import org.dllearner.kb.SparqlEndpoint; -import org.dllearner.learningproblems.PosNegDefinitionLP; -import org.dllearner.learningproblems.PosNegInclusionLP; -import org.dllearner.parser.KBParser; -import org.dllearner.parser.ParseException; -import org.dllearner.reasoning.DIGReasoner; -import org.dllearner.utilities.Datastructures; - -/** - * DL-Learner web service interface. - * - * @author Jens Lehmann - * @author Sebastian Hellmann - * - */ -@WebService(name = "DLLearnerWebService") -@SOAPBinding(style = SOAPBinding.Style.RPC) -public class DLLearnerWSNew { - - private Map<Integer, State> clients = new TreeMap<Integer,State>(); - private Random rand=new Random(); - private static ComponentManager cm = ComponentManager.getInstance(); - - // defines the components, which are accessible for the web service - private static Map<String,Class<? extends KnowledgeSource>> knowledgeSourceMapping = new TreeMap<String,Class<? extends KnowledgeSource>>(); - private static Map<String,Class<? extends ReasonerComponent>> reasonerMapping = new TreeMap<String,Class<? extends ReasonerComponent>>(); - private static Map<String,Class<? extends LearningProblem>> learningProblemMapping = new TreeMap<String,Class<? extends LearningProblem>>(); - private static Map<String,Class<? extends LearningAlgorithm>> learningAlgorithmMapping = new TreeMap<String,Class<? extends LearningAlgorithm>>(); - - public DLLearnerWSNew() { - knowledgeSourceMapping.put("owlfile", OWLFile.class); - knowledgeSourceMapping.put("sparql", SparqlEndpoint.class); - reasonerMapping.put("dig", DIGReasoner.class); - learningProblemMapping.put("posNegDefinition", PosNegDefinitionLP.class); - learningProblemMapping.put("posNegInclusion", PosNegInclusionLP.class); - learningAlgorithmMapping.put("refinement", ROLearner.class); - } - - /** - * Generates a unique ID for the client and initialises a session. - * Using the ID the client can call the other web service methods. - * Two calls to this method are guaranteed to return different results. - * - * @return A session ID. - */ - @WebMethod - public int generateID() { - int id; - do { - id = rand.nextInt(); - } while(clients.containsKey(id)); - clients.put(id, new State()); - return id; - } - - // returns session state or throws client not known exception - private State getState(int id) throws ClientNotKnownException { - State state = clients.get(id); - if(state==null) - throw new ClientNotKnownException(id); - return state; - } - - // returns the class which is referred to by the string - @SuppressWarnings({"unused"}) - private Class<? extends Component> getComponent(String component) throws UnknownComponentException { - if(knowledgeSourceMapping.containsKey(component)) - return knowledgeSourceMapping.get(component); - else if(reasonerMapping.containsKey(component)) - return reasonerMapping.get(component); - else if(learningProblemMapping.containsKey(component)) - return learningProblemMapping.get(component); - else if(learningAlgorithmMapping.containsKey(component)) - return learningAlgorithmMapping.get(component); - else - throw new UnknownComponentException(component); - } - - /////////////////////////////////////// - // methods for basic component setup // - /////////////////////////////////////// - - /** - * Adds a knowledge source. - * - * @return An identifier for the component. - */ - @WebMethod - public int addKnowledgeSource(int id, String component, String url) throws ClientNotKnownException, UnknownComponentException { - State state = getState(id); - Class<? extends KnowledgeSource> ksClass = knowledgeSourceMapping.get(component); - if(ksClass == null) - throw new UnknownComponentException(component); - KnowledgeSource ks = cm.knowledgeSource(ksClass); - cm.applyConfigEntry(ks, "url", url); - return state.addKnowledgeSource(ks); - } - - @WebMethod - public void removeKnowledgeSource(int id, int componentID) throws ClientNotKnownException { - getState(id).removeKnowledgeSource(componentID); - } - - @WebMethod - public int setReasoner(int id, String component) throws ClientNotKnownException, UnknownComponentException { - State state = getState(id); - Class<? extends ReasonerComponent> rcClass = reasonerMapping.get(component); - if(rcClass == null) - throw new UnknownComponentException(component); - - ReasonerComponent rc = cm.reasoner(rcClass, state.getKnowledgeSources()); - return state.setReasonerComponent(rc); - } - - @WebMethod - public int setLearningProblem(int id, String component) throws ClientNotKnownException, UnknownComponentException { - State state = getState(id); - Class<? extends LearningProblem> lpClass = learningProblemMapping.get(component); - if(lpClass == null) - throw new UnknownComponentException(component); - - LearningProblem lp = cm.learningProblem(lpClass, state.getReasoningService()); - return state.setLearningProblem(lp); - } - - @WebMethod - public int setLearningAlgorithm(int id, String component) throws ClientNotKnownException, UnknownComponentException { - State state = getState(id); - Class<? extends LearningAlgorithm> laClass = learningAlgorithmMapping.get(component); - if(laClass == null) - throw new UnknownComponentException(component); - - LearningAlgorithm la = cm.learningAlgorithm(laClass, state.getLearningProblem(), state.getReasoningService()); - return state.setLearningAlgorithm(la); - } - - /** - * Initialise all components. - * @param id Session ID. - */ - @WebMethod - public void init(int id) throws ClientNotKnownException { - State state = getState(id); - for(KnowledgeSource ks : state.getKnowledgeSources()) - ks.init(); - state.getReasonerComponent().init(); - state.getLearningProblem().init(); - state.getLearningAlgorithm().init(); - } - - /** - * Starts the learning algorithm and returns the best concept found. This - * method will block until learning is completed. - * - * @param id Session ID. - * @return The best solution found. - * @throws ClientNotKnownException - */ - @WebMethod - public String learn(int id) throws ClientNotKnownException { - State state = getState(id); - state.getLearningAlgorithm().start(); - return state.getLearningAlgorithm().getBestSolution().toString(); - } - - /** - * Starts the learning algorithm and returns immediately. The learning - * algorithm is executed in its own thread and can be queried and - * controlled using other Web Service methods. - * - * @param id Session ID. - * @throws ClientNotKnownException - */ - @WebMethod - public void learnThreaded(int id) throws ClientNotKnownException { - final State state = getState(id); - Thread learningThread = new Thread() { - @Override - public void run() { - state.setAlgorithmRunning(true); - state.getLearningAlgorithm().start(); - state.setAlgorithmRunning(false); - } - }; - learningThread.start(); - } - - @WebMethod - public String getCurrentlyBestConcept(int id) throws ClientNotKnownException { - State state = getState(id); - return state.getLearningAlgorithm().getBestSolution().toString(); - } - - @WebMethod - public boolean isAlgorithmRunning(int id) throws ClientNotKnownException { - return getState(id).isAlgorithmRunning(); - } - - /** - * Stops the learning algorithm smoothly. - * @param id - * @throws ClientNotKnownException - */ - @WebMethod - public void stop(int id) throws ClientNotKnownException { - getState(id).getLearningAlgorithm().stop(); - } - - ///////////////////////////////////////// - // methods for component configuration // - ///////////////////////////////////////// - - @WebMethod - public void setPositiveExamples(int id, String[] positiveExamples) throws ClientNotKnownException { - State state = getState(id); - Set<String> posExamples = new TreeSet<String>(Arrays.asList(positiveExamples)); - cm.applyConfigEntry(state.getLearningProblem(), "positiveExamples", posExamples); - } - - @WebMethod - public void setNegativeExamples(int id, String[] negativeExamples) throws ClientNotKnownException { - State state = getState(id); - Set<String> negExamples = new TreeSet<String>(Arrays.asList(negativeExamples)); - cm.applyConfigEntry(state.getLearningProblem(), "negativeExamples", negExamples); - } - - @WebMethod - public void applyConfigEntryInt(int sessionID, int componentID, String optionName, Integer value) throws ClientNotKnownException, UnknownComponentException { - applyConfigEntry(sessionID, componentID,optionName,value); - } - - @WebMethod - public void applyConfigEntryString(int sessionID, int componentID, String optionName, String value) throws ClientNotKnownException, UnknownComponentException { - applyConfigEntry(sessionID, componentID,optionName,value); - } - - @WebMethod - public void applyConfigEntryStringArray(int sessionID, int componentID, String optionName, String[] value) throws ClientNotKnownException, UnknownComponentException { - Set<String> stringSet = new TreeSet<String>(Arrays.asList(value)); - applyConfigEntry(sessionID, componentID,optionName,stringSet); - } - - @WebMethod - public void applyConfigEntryBoolean(int sessionID, int componentID, String optionName, Boolean value) throws ClientNotKnownException, UnknownComponentException { - applyConfigEntry(sessionID, componentID,optionName,value); - } - - private void applyConfigEntry(int sessionID, int componentID, String optionName, Object value) throws ClientNotKnownException, UnknownComponentException { - State state = getState(sessionID); - Component component = state.getComponent(componentID); - cm.applyConfigEntry(component, optionName, value); - } - - //////////////////////////////////// - // reasoning and querying methods // - //////////////////////////////////// - - @WebMethod - public String[] getAtomicConcepts(int id) throws ClientNotKnownException { - Set<AtomicConcept> atomicConcepts = getState(id).getReasoningService().getAtomicConcepts(); - return Datastructures.sortedSet2StringListConcepts(atomicConcepts); - } - - @WebMethod - public String getSubsumptionHierarchy(int id) throws ClientNotKnownException { - return getState(id).getReasoningService().toString(); - } - - @WebMethod - public String[] retrieval(int id, String conceptString) throws ClientNotKnownException { - State state = getState(id); - // call parser to parse atomic concept - Concept concept = null; - try { - concept = KBParser.parseConcept(conceptString); - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Set<Individual> individuals = state.getReasoningService().retrieval(concept); - return Datastructures.sortedSet2StringListIndividuals(individuals); - } - - @WebMethod - public String[] getAtomicRoles(int id) throws ClientNotKnownException { - State state = getState(id); - Set<AtomicRole> roles = state.getReasoningService().getAtomicRoles(); - return Datastructures.sortedSet2StringListRoles(roles); - } - - @WebMethod - public String[] getInstances(int id) throws ClientNotKnownException { - State state = getState(id); - Set<Individual> individuals = state.getReasoningService().getIndividuals(); - return Datastructures.sortedSet2StringListIndividuals(individuals); - } - - @WebMethod - public String[] getIndividualsForARole(int id, String role) throws ClientNotKnownException { - State state = getState(id); - Map<Individual,SortedSet<Individual>> m = state.getReasoningService().getRoleMembers(new AtomicRole(role)); - Set<Individual> individuals = m.keySet(); - return Datastructures.sortedSet2StringListIndividuals(individuals); - } -} Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSStart.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSStart.java 2007-10-16 09:27:26 UTC (rev 226) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSStart.java 2007-10-16 09:32:08 UTC (rev 227) @@ -32,7 +32,7 @@ System.out.print("Starting DL-Learner web service at http://" + isa.getHostName()+":"+isa.getPort()+ "/services ... "); - Endpoint endpoint = Endpoint.create(new DLLearnerWSNew()); + Endpoint endpoint = Endpoint.create(new DLLearnerWS()); //Endpoint endpoint = Endpoint.create(new CustomDataClass()); HttpContext context = server.createContext("/services"); endpoint.publish(context); Deleted: trunk/src/dl-learner/org/dllearner/server/State.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-16 09:27:26 UTC (rev 226) +++ trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-16 09:32:08 UTC (rev 227) @@ -1,209 +0,0 @@ -/** - * Copyright (C) 2007, 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.server; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import org.dllearner.core.Component; -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.kb.OWLFile; -import org.dllearner.kb.SparqlEndpoint; - -/** - * Stores the state of a DL-Learner client session. - * - * @author Jens Lehmann - * - */ -public class State { - - // stores the mapping between component IDs and component - // (note that this allows us to keep all references to components even - // if they are note used anymore e.g. a deleted knowledge source) - private Map<Integer,Component> componentIDs = new HashMap<Integer,Component>(); - - private Set<KnowledgeSource> knowledgeSources = new HashSet<KnowledgeSource>(); - - private LearningProblem learningProblem; - - private ReasonerComponent reasonerComponent; - private ReasoningService reasoningService; - - private LearningAlgorithm learningAlgorithm; - - private Random rand=new Random(); - - private boolean isAlgorithmRunning = false; - - private int generateComponentID(Component component) { - int id; - do { - id = rand.nextInt(); - } while(componentIDs.keySet().contains(id)); - componentIDs.put(id, component); - return id; - } - - /** - * @return the isAlgorithmRunning - */ - public boolean isAlgorithmRunning() { - return isAlgorithmRunning; - } - - /** - * @param isAlgorithmRunning the isAlgorithmRunning to set - */ - public void setAlgorithmRunning(boolean isAlgorithmRunning) { - this.isAlgorithmRunning = isAlgorithmRunning; - } - -// public Component getComponent(Class<? extends Component> componentClass) throws UnknownComponentException { -// if(learningProblem.getClass().equals(componentClass)) -// return learningProblem; -// else if(learningAlgorithm.getClass().equals(componentClass)) -// return learningAlgorithm; -// else if(reasonerComponent.getClass().equals(componentClass)) -// return reasonerComponent; -// else if(KnowledgeSource.class.isAssignableFrom(componentClass)) { -// -// -// for(KnowledgeSource ks : knowledgeSources) { -// if(ks.getClass().equals(componentClass)) -// return ks; -// } -// throw new UnknownComponentException(componentClass.getName()); -// } else -// throw new UnknownComponentException(componentClass.getName()); -// } - - /** - * Removes a knowledge source with the given URL (independant of its type). - * @param url URL of the OWL file or SPARQL Endpoint. - * @return True if a knowledge source was deleted, false otherwise. - */ - public boolean removeKnowledgeSource(String url) { - Iterator<KnowledgeSource> it = knowledgeSources.iterator(); - while(it.hasNext()) { - KnowledgeSource source = it.next(); - if((source instanceof OWLFile && ((OWLFile)source).getURL().toString().equals(url)) - || (source instanceof SparqlEndpoint && ((SparqlEndpoint)source).getURL().toString().equals(url)) ) { - it.remove(); - return true; - } - } - return false; - } - - /** - * @return the learningProblem - */ - public LearningProblem getLearningProblem() { - return learningProblem; - } - - /** - * @param learningProblem the learningProblem to set - */ - public int setLearningProblem(LearningProblem learningProblem) { - this.learningProblem = learningProblem; - return generateComponentID(learningProblem); - } - - /** - * @return the reasonerComponent - */ - public ReasonerComponent getReasonerComponent() { - return reasonerComponent; - } - - /** - * Sets the reasoner component and creates the corresponding - * <code>ReasoningService</code> instance. - * - * @param reasonerComponent the reasonerComponent to set - */ - public int setReasonerComponent(ReasonerComponent reasonerComponent) { - this.reasonerComponent = reasonerComponent; - reasoningService = new ReasoningService(reasonerComponent); - return generateComponentID(reasonerComponent); - } - - /** - * @return the learningAlgorithm - */ - public LearningAlgorithm getLearningAlgorithm() { - return learningAlgorithm; - } - - /** - * @param learningAlgorithm the learningAlgorithm to set - */ - public int setLearningAlgorithm(LearningAlgorithm learningAlgorithm) { - this.learningAlgorithm = learningAlgorithm; - return generateComponentID(learningAlgorithm); - } - - /** - * @return the reasoningService - */ - public ReasoningService getReasoningService() { - return reasoningService; - } - - /** - * @param key - * @return - * @see java.util.Map#get(java.lang.Object) - */ - public Component getComponent(int id) { - return componentIDs.get(id); - } - - /** - * @param e - * @return - */ - public int addKnowledgeSource(KnowledgeSource ks) { - knowledgeSources.add(ks); - return generateComponentID(ks); - - } - - public boolean removeKnowledgeSource(int componentID) { - return knowledgeSources.remove(componentIDs.get(componentID)); - } - - /** - * @return the knowledgeSources - */ - public Set<KnowledgeSource> getKnowledgeSources() { - return knowledgeSources; - } -} Added: trunk/src/dl-learner/org/dllearner/server/jaxws/package.html =================================================================== --- trunk/src/dl-learner/org/dllearner/server/jaxws/package.html (rev 0) +++ trunk/src/dl-learner/org/dllearner/server/jaxws/package.html 2007-10-16 09:32:08 UTC (rev 227) @@ -0,0 +1,7 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> +<html> +<head></head> +<body bgcolor="white"> +<p>Classes generated by JAXWS.</p> +</body> +</html> \ No newline at end of file Modified: trunk/src/dl-learner/org/dllearner/server/package.html =================================================================== --- trunk/src/dl-learner/org/dllearner/server/package.html 2007-10-16 09:27:26 UTC (rev 226) +++ trunk/src/dl-learner/org/dllearner/server/package.html 2007-10-16 09:32:08 UTC (rev 227) @@ -2,8 +2,6 @@ <html> <head></head> <body bgcolor="white"> -<p>This package implements the DL-Learner server, which handles learning problems according to the "Ontology Class Learning Interface". - -TODO: So ein Interface muss natürlich erst spezifiziert werden ...</p> +<p>This package implements the DL-Learner web service.</p> </body> </html> \ 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...> - 2007-10-16 09:27:30
|
Revision: 226 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=226&view=rev Author: jenslehmann Date: 2007-10-16 02:27:26 -0700 (Tue, 16 Oct 2007) Log Message: ----------- deleted deprecated classes Removed Paths: ------------- trunk/src/dl-learner/org/dllearner/server/ClientState.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java trunk/src/dl-learner/org/dllearner/server/LearnMonitor.java trunk/src/dl-learner/org/dllearner/server/NoOntologySelectedException.java trunk/src/dl-learner/org/dllearner/server/OntologyURLNotValid.java trunk/src/dl-learner/org/dllearner/server/jaxws/NoOntologySelectedExceptionBean.java trunk/src/dl-learner/org/dllearner/server/jaxws/OntologyURLNotValidBean.java Deleted: trunk/src/dl-learner/org/dllearner/server/ClientState.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/ClientState.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/ClientState.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,571 +0,0 @@ - -package org.dllearner.server; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.dllearner.Config; -import org.dllearner.ConfigurationManager; -import org.dllearner.algorithms.refinement.ROLearner; -import org.dllearner.cli.ConfFileOption; -import org.dllearner.core.Reasoner; -import org.dllearner.core.ReasoningMethodUnsupportedException; -import org.dllearner.core.ReasoningService; -import org.dllearner.core.dl.AtomicConcept; -import org.dllearner.core.dl.AtomicRole; -import org.dllearner.core.dl.Individual; -import org.dllearner.kb.OntologyFileFormat; -import org.dllearner.utilities.Helper; - -public class ClientState { - - // private String reasonerURL="http://localhost:8081"; - //private String reasonerURL="http://localhost:3490"; - - private SortedSet<Individual> positiveExamples = new TreeSet<Individual>(); - public SortedSet<Individual> getPosExamples() { return this.positiveExamples;} - - private SortedSet<Individual> negativeExamples = new TreeSet<Individual>(); - public SortedSet<Individual> getNegExamples() { return this.negativeExamples;} - - private SortedSet<String> ignoredConcept = new TreeSet<String>(); - - - private Reasoner reasoner; - public Reasoner getReasoner() { return reasoner;} - - private ReasoningService rs; - public ReasoningService getRs() { return rs; } - - private String currentOntologyURL=null; - private boolean debug_flag=true; - private LearnMonitor lm=null; - - private String lastResult=""; - public String getLastResult(){ - try{ - return ROL.getBestSolution().toString(); - }catch (Exception e) {} - return this.lastResult; } - public void setLastResult(String lastResult) {this.lastResult = lastResult;} - - private String status="maiden-like"; - public void setStatus(String status) {this.status = status;} - - ConfigurationManager confMgr; - public void addOption(ConfFileOption c){confMgr.applyConfigurationOption(c);} - ROLearner ROL; - - public ClientState() { - - - TreeSet<ConfFileOption> s=new TreeSet<ConfFileOption>(); - //s.add(new ConfigurationOption("refinement","quiet","true")); - /*s.add(new ConfigurationOption()); - s.add(new ConfigurationOption()); - s.add(new ConfigurationOption()); - s.add(new ConfigurationOption()); - s.add(new ConfigurationOption()); - s.add(new ConfigurationOption());*/ - - confMgr = new ConfigurationManager(s); - addOption(new ConfFileOption("refinement","quiet","true")); - //confMgr.applyOptions(); - - } - - - - - public void addPositiveExample(String posExample) { - positiveExamples.add(new Individual(posExample)); - p("added pos: "+posExample); - } - - - public void addNegativeExample(String negExample) { - negativeExamples.add(new Individual(negExample)); - p("added neg: "+negExample); - } - - public void addIgnoredConcept(String concept) { - ignoredConcept.add(concept); - p("added ignoredConcepts: "+concept); - } - - public String[] selectInstancesForAConcept(String Concept)throws NoOntologySelectedException{ - if(Concept.endsWith("#Thing"))return new String[]{}; - AtomicConcept SelectedConcept=new AtomicConcept(Concept); - ArrayList<String> al=new ArrayList<String>(); - Individual indtmp=null; - //Set<AtomicConcept> ConceptSet=null; - AtomicConcept ac=null; - - - System.out.println("selectInstancesForAConcept: "+Concept); - // add all positives - Set<Individual> positives=rs.retrieval(SelectedConcept); - Iterator<Individual> i = positives.iterator(); - while(i.hasNext()){ - indtmp=i.next(); - p("added "+indtmp.getName()+" to positives"); - al.add("added "+indtmp.getName()+" to positives"); - positiveExamples.add(indtmp); - } - - //find more general concepts - ArrayList<AtomicConcept> superConcepts=new ArrayList<AtomicConcept>(); - try{ - //ConceptSet = rs.getSubsumptionHierarchy().getMoreGeneralConcepts(new AtomicConcept(Concept)); - //System.out.println(ConceptSet); - //Concept c=new AtomicConcept(Concept); - /*Set<AtomicConcept> s=rs.getAtomicConcepts(); - Set<Concept> sc=new TreeSet<Concept>(); - Iterator a=s.iterator(); - while (a.hasNext()) { - sc.add((Concept) a.next()); - } - sc=rs.subsumes(sc,new AtomicConcept(Concept));*/ - superConcepts=subsumesAll(SelectedConcept); - - //System.out.println("sizebefore: "+"size after:"+sc); - }catch (Exception e) {e.printStackTrace();} - - -// remove top - for (int j = 0; j < superConcepts.size(); ) { - //TODO no unique name assumption? - if(superConcepts.get(j).getName().equals(SelectedConcept.getName())){ - superConcepts.remove(j); - j=0; - continue; - } - if(superConcepts.get(j).getName().equals("TOP")){ - superConcepts.remove(j); - j=0; - continue; - } - j++; - } - - System.out.println("Found all those:"+ superConcepts); - - ac=null; - - if(superConcepts.size()==0){return al2s(al); }//TODO - else - { // add all negatives of all superclasses; - - //Iterator it=ConceptSet.iterator(); - for (int jj = 0; jj < superConcepts.size(); jj++) - { - ac=superConcepts.get(jj); - p("next this: "+ac.getName()); - Set<Individual> negatives=rs.retrieval(ac); - Iterator<Individual> i2 = negatives.iterator(); - indtmp=null; - while(i2.hasNext()){ - - indtmp=(Individual)i2.next(); - - if(!positives.contains(indtmp)){ - - p("added "+indtmp.getName()+" to NEGATIVES"); - al.add("added "+indtmp.getName()+" to NEGATIVES"); - negativeExamples.add(indtmp); - } - else{ - p("skipped "+indtmp.getName()); - al.add("skipped "+indtmp.getName()); - } - - } - }//endfor - return al2s(al); - } - - - } - - - - public String[] selectAConcept(String Concept, int Percentage)throws NoOntologySelectedException{ - if(Concept.endsWith("#Thing"))return new String[]{}; - AtomicConcept SelectedConcept=new AtomicConcept(Concept); - ArrayList<String> ret=new ArrayList<String>(); - Individual indtmp=null; - //Set<AtomicConcept> ConceptSet=null; - //AtomicConcept ac=null; - Random r=new Random(); - - - System.out.println("selectAConcept: "+Concept); - // add all positives - Set<Individual> positives=rs.retrieval(SelectedConcept); - Iterator<Individual> i = positives.iterator(); - while(i.hasNext()){ - indtmp=(Individual)i.next(); - p("added "+indtmp.getName()+" to positives"); - ret.add("added "+indtmp.getName()+" to positives"); - positiveExamples.add(indtmp); - } - - //find All other Instances concepts - Set<Individual> otherInstances=rs.getIndividuals(); - Iterator<Individual> it=otherInstances.iterator(); - while(it.hasNext()){ - indtmp=(Individual)it.next(); - - if(!positives.contains(indtmp) && (r.nextDouble()*100)<=Percentage){ - - p("added "+indtmp.getName()+" to NEGATIVES"); - ret.add("added "+indtmp.getName()+" to NEGATIVES"); - negativeExamples.add(indtmp); - } - }//while - - return al2s(ret); - - } - - - public ArrayList<AtomicConcept> subsumesAll(AtomicConcept c){ - Set<AtomicConcept> s=rs.getAtomicConcepts(); - ArrayList<AtomicConcept> ret=new ArrayList<AtomicConcept>(); - Iterator<AtomicConcept> i=s.iterator(); - while (i.hasNext()) { - AtomicConcept element = (AtomicConcept) i.next(); - if(rs.subsumes(element, c)) - { - ret.add(element); - } - - } - return ret; - } - public String[] getPositiveExamples(){ - String[] ret=new String[positiveExamples.size()]; - Iterator<Individual> i=positiveExamples.iterator(); - int a=0; - while (i.hasNext()){ - ret[a++]=((Individual)i.next()).getName(); - } - //p("getPositiveEx"); - return ret; - } - public String[] getNegativeExamples(){ - String[] ret=new String[negativeExamples.size()]; - Iterator<Individual> i=negativeExamples.iterator(); - int a=0; - while (i.hasNext()){ - ret[a++]=((Individual)i.next()).getName(); - } - //p("getNegativeEx"); - return ret; - } - - public String[] getIgnoredConcepts() { - String[] ret=new String[ignoredConcept.size()]; - Iterator<String> i=ignoredConcept.iterator(); - int a=0; - while (i.hasNext()){ - ret[a++]=((String)i.next()); - } - //p("getNegativeEx"); - return ret; - } - - public String getSubsumptionHierarchy() throws NoOntologySelectedException { - try{ - return this.rs.getSubsumptionHierarchy().toString(); - }catch (Exception e) {throw new NoOntologySelectedException("Subsumptionhierarchy",e.getMessage());} - - } - - - - public boolean removeNegativeExample(String NegExample){ - p("removed from neg: "+NegExample); - return negativeExamples.remove(new Individual(NegExample)); - } - public boolean removePositiveExample(String PosExample){ - p("removed from pos: "+PosExample); - return positiveExamples.remove(new Individual(PosExample)); - } - - public boolean removeAllPositiveExamples(){ - positiveExamples = new TreeSet<Individual>(); - p("removing all positive examples"); - return true; - } - public boolean removeAllNegativeExamples(){ - negativeExamples = new TreeSet<Individual>(); - p("removing all negative examples"); - return true; - } - - public boolean removeAllExamples(){ - positiveExamples = new TreeSet<Individual>(); - negativeExamples = new TreeSet<Individual>(); - p("removing all examples"); - return true; - } - - public void removeIgnoredConcept(String concept) { - //ignoredConcept.add(concept); - this.ignoredConcept.remove(concept); - p("removed ignoredConcepts: "+concept); - } - - public String[] getInstances()throws NoOntologySelectedException{ - try{ - SortedSet<Individual> s=rs.getIndividuals(); - //System.out.println(s); - String[] ret=new String[s.size()]; - Iterator<Individual> i=s.iterator(); - int a=0; - while (i.hasNext()){ - ret[a++]=((Individual)i.next()).getName(); - } - Arrays.sort(ret); - //p("getInstances"); - return ret; - }catch (Exception e) {throw new NoOntologySelectedException("Failed to get instances, no ontology selected","");} - } - - public String getCurrentOntologyURL()throws NoOntologySelectedException{ - p("getCurrentOntology: "+currentOntologyURL); - if(currentOntologyURL==null)throw new NoOntologySelectedException("Select Ontology First","quatsch"); - else return currentOntologyURL; - } - - public String getAlgorithmStatus(){ - return this.status; - } - - /** - * Specifies the URI of the ontology containing the background - * knowledge. Reads the ontology and sends it to the reasoner. - * - * @param ontologyURI The URI of the ontology to use. - */ - // gleiche Methoden mit verschiedenen Parametern sind offenbar problematisch - /* - @WebMethod - public void readOntology(String ontologyURI) { - readOntology(ontologyURI, "RDF/XML"); - } - */ - - - public void removeOntology() { - this.currentOntologyURL=null; - this.reasoner=null; - this.rs=null; - this.positiveExamples = new TreeSet<Individual>(); - this.negativeExamples = new TreeSet<Individual>(); - this.ignoredConcept=new TreeSet<String>(); - p("removing Ontology"); - - } - - /** - * Specifies the URI of the ontology containing the background - * knowledge and its format. Reads the ontology and sends it to - * the reasoner. - * - * @param ontologyURI The URI of the ontology to use. - * @param format "RDF/XML" or "N-TRIPLES". - */ - - - public void readOntology(String ontologyURL, String format) throws OntologyURLNotValid{ - this.currentOntologyURL=ontologyURL; - p("trying to read: "+ontologyURL+" ::"+format); - try{ - // this.ontologyURL = ontologyURL; - // this.ontologyFormat = format; - - // TODO: potentielles Sicherheitsrisiko, da man damit derzeit auch lokale Dateien - // laden könnte (Fix: nur http:// zulassen, kein file://) - URL ontology = null; - try { - ontology = new URL(ontologyURL); - } catch (MalformedURLException e1) { - this.removeOntology(); - throw new OntologyURLNotValid("The URL of the Ontology is not correct<br>\nCheck settings and URL","OntologyURLNotValid"); - - } - - OntologyFileFormat ofFormat; - if (format.equals("RDF/XML")) - ofFormat = OntologyFileFormat.RDF_XML; - else - ofFormat = OntologyFileFormat.N_TRIPLES; - - Map<URL, OntologyFileFormat> m = new HashMap<URL, OntologyFileFormat>(); - m.put(ontology, ofFormat); - - // Default-URI für DIG-Reasoner setzen - -// try { -// Config.digReasonerURL = new URL(reasonerURL); -// } catch (MalformedURLException e) { -// // Exception tritt nie auf, da URL korrekt -// e.printStackTrace(); -// } - - // reasoner = Main.createReasoner(new KB(), m); - System.err.println("TODO: rewrite webservice code"); - rs = new ReasoningService(reasoner); - - Helper.autoDetectConceptsAndRoles(rs); - reasoner.prepareSubsumptionHierarchy(); - if (Config.Refinement.improveSubsumptionHierarchy) { - try { - reasoner.prepareRoleHierarchy(); - reasoner.getSubsumptionHierarchy().improveSubsumptionHierarchy(); - } catch (ReasoningMethodUnsupportedException e) { - // solange DIG-Reasoner eingestellt ist, schlägt diese Operation nie fehl - e.printStackTrace(); - } - } - p(rs.getSubsumptionHierarchy().toString()); - //rs.getRoleMembers(arg0) - } - catch (Exception e) { //TODO - this.removeOntology(); - throw new OntologyURLNotValid("The URL of the Ontology is not correct<br>\nCheck settings and URL","OntologyURLNotValid"); - } - /*catch (JenaException e) { - e.printStackTrace();} - */ - - /*catch(Exception e2) { - - //p("exception:"+e.getMessage()); - e2.printStackTrace(); - }*/ - p("Ontology read: "+currentOntologyURL); - } - - - public void learnMonitored(){ - addOption(new ConfFileOption("refinement","ignoredConcepts",ignoredConcept)); - this.lm=new LearnMonitor(this); - this.lm.start(); - //this.lm.learn(this); - } - - /*public void relearn(){ - //TreeSet<String> s=new TreeSet<String>(); - //new ConfigurationOption(); - this.lm=new LearnMonitor(this); - this.lm.start(); - //this.lm.learn(this); - }*/ - - - public String[] getAtomicConcepts()throws NoOntologySelectedException{ - try{ - return SortedSet2StringListConcepts( rs.getAtomicConcepts()); - }catch (Exception e) {throw new NoOntologySelectedException("Select Ontology First","ddddd");} - } - - public String[] retrieval(String Concept)throws NoOntologySelectedException{ - return SortedSet2StringListIndividuals(rs.retrieval(new AtomicConcept(Concept))); - } - - public String[] getAtomicRoles()throws NoOntologySelectedException{ - return SortedSet2StringListRoles( rs.getAtomicRoles()); - } - - public String[] getIndividualsForARole(String Role)throws NoOntologySelectedException{ - Map<Individual,SortedSet<Individual>> m=rs.getRoleMembers(new AtomicRole(Role)); - Set<Individual> s=m.keySet(); - return SortedSet2StringListIndividuals(s); - } - - public synchronized void stop(){ - System.out.println("ROL"+this.ROL); - - System.out.println("lm"+lm); - System.out.println("lmstate"+lm.getState()); - System.out.println("lmalive"+lm.isAlive()); - System.out.println("lminterrupt"+lm.isInterrupted()); - this.ROL.stop(); - //lm.end(); - /*try{ - synchronized (this.lm) { - //this.lm.yield(); - } - }catch (Exception e) {e.printStackTrace();}*/ - System.out.println("lmstate"+lm.getState()); - System.out.println("lmalive"+lm.isAlive()); - System.out.println("lminterrupt"+lm.isInterrupted()); - - //this.ROL.stop(); - //this.lm.interrupt(); - - //this.lm.end(); - //this.lm.notify(); - } - - public String[] SortedSet2StringListIndividuals(Set<Individual> s){ - - String[] ret=new String[s.size()]; - Iterator<Individual> i=s.iterator(); - int a=0; - while (i.hasNext()){ - ret[a++]=((Individual)i.next()).getName(); - } - Arrays.sort(ret); - return ret; - } - - public String[] SortedSet2StringListConcepts(Set<AtomicConcept> s){ - - String[] ret=new String[s.size()]; - Iterator<AtomicConcept> i=s.iterator(); - int a=0; - while (i.hasNext()){ - ret[a++]=((AtomicConcept)i.next()).getName(); - } - Arrays.sort(ret); - return ret; - } - public String[] SortedSet2StringListRoles(Set<AtomicRole> s){ - - String[] ret=new String[s.size()]; - Iterator<AtomicRole> i=s.iterator(); - int a=0; - while (i.hasNext()){ - ret[a++]=((AtomicRole)i.next()).getName(); - } - Arrays.sort(ret); - return ret; - } - - public String[] al2s(ArrayList<String> al){ - String[] ret=new String[al.size()]; - for (int i = 0; i < al.size(); i++) { - ret[i]=al.get(i); - } - return ret; - } - public void p(String s){ - if(debug_flag){ - System.out.println("\t"+s); - } - - } -} Deleted: trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWS.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,225 +0,0 @@ -package org.dllearner.server; - -import java.util.HashMap; -import java.util.Random; - -import javax.jws.WebMethod; -import javax.jws.WebService; -import javax.jws.soap.SOAPBinding; - - -/** - * Offene Fragen: - * - * Welche Rückgabetypen sind erlaubt? - * Wie behandelt man Exceptions (z.B. aus angegebener URI kann keine Ontologie - * gelesen werden)? - * - * @author Jens Lehmann - * - */ -@WebService(name = "DLLearnerWebService") -@SOAPBinding(style = SOAPBinding.Style.RPC) -public class DLLearnerWS { - Random rand=new Random(); - private HashMap<Integer, ClientState> clients; - - // private String ontologyURL; - // private String ontologyFormat; - - - - public DLLearnerWS(){ - this.clients=new HashMap<Integer, ClientState>(); - - } - - /** - * - * - * - */ - @WebMethod - public int getID(){ - int id=rand.nextInt(); - while (id<=0){ - id=rand.nextInt(); - } - - // dont change to local function get, cause of exception - ClientState c=this.clients.get(new Long(id)); - if(c!=null){ - return getID(); - } - else { - this.clients.put(new Integer(id), new ClientState()); - System.out.println("new Client with id: "+id); - return id; - } - - } - - @WebMethod - public void addPositiveExample(int id,String posExample) throws ClientNotKnownException{ - ClientState c=getClientState(id); - c.addPositiveExample(posExample); - //positiveExamples.add(new Individual(posExample)); - } - @WebMethod - public void addNegativeExample(int id,String negExample) throws ClientNotKnownException { - ClientState c=getClientState(id); - c.addNegativeExample(negExample); - } - @WebMethod - public void addIgnoredConcept(int id,String concept)throws ClientNotKnownException { - getClientState(id).addIgnoredConcept(concept); - } - - @WebMethod - public String[] selectInstancesForAConcept(int id,String Concept)throws ClientNotKnownException,NoOntologySelectedException{ - return getClientState(id).selectInstancesForAConcept(Concept); - } - - @WebMethod - public String[] selectAConcept(int id,String Concept,int Percentage)throws ClientNotKnownException,NoOntologySelectedException{ - return getClientState(id).selectAConcept(Concept, Percentage); - } - - @WebMethod - public String[] getPositiveExamples(int id)throws ClientNotKnownException{ - ClientState c=getClientState(id); - return c.getPositiveExamples(); - } - @WebMethod - public String[] getNegativeExamples(int id)throws ClientNotKnownException{ - ClientState c=getClientState(id); - return c.getNegativeExamples(); - } - @WebMethod - public String[] getIgnoredConcepts(int id)throws ClientNotKnownException{ - return getClientState(id).getIgnoredConcepts(); - } - - @WebMethod - public boolean removePositiveExample(int id, String pos)throws ClientNotKnownException{ - return getClientState(id).removePositiveExample(pos); - } - - @WebMethod - public boolean removeNegativeExample(int id, String neg)throws ClientNotKnownException{ - return getClientState(id).removeNegativeExample(neg); - } - @WebMethod - public boolean removeAllExamples(int id)throws ClientNotKnownException{ - return getClientState(id).removeAllExamples(); - } - @WebMethod - public boolean removeAllPositiveExamples(int id)throws ClientNotKnownException{ - return getClientState(id).removeAllPositiveExamples(); - } - @WebMethod - public boolean removeAllNegativeExamples(int id)throws ClientNotKnownException{ - return getClientState(id).removeAllNegativeExamples(); - } - @WebMethod - public void removeIgnoredConcept(int id,String concept)throws ClientNotKnownException{ - getClientState(id).removeIgnoredConcept(concept); - } - - @WebMethod - public String getCurrentOntologyURL(int id)throws ClientNotKnownException,NoOntologySelectedException{ - return getClientState(id).getCurrentOntologyURL(); - - } - - @WebMethod - public String[] getInstances(int id)throws ClientNotKnownException,NoOntologySelectedException{ - return getClientState(id).getInstances(); - } - - @WebMethod - public String[] getAtomicConcepts(int id)throws ClientNotKnownException,NoOntologySelectedException{ - return getClientState(id).getAtomicConcepts(); - } - - @WebMethod - public String[] getAtomicRoles(int id)throws ClientNotKnownException,NoOntologySelectedException{ - return getClientState(id).getAtomicRoles(); - } - @WebMethod - public String[] getIndividualsForARole(int id,String Role)throws ClientNotKnownException, NoOntologySelectedException{ - return getClientState(id).getIndividualsForARole(Role); - } - @WebMethod - public String getSubsumptionHierarchy(int id)throws ClientNotKnownException, NoOntologySelectedException{ - return getClientState(id).getSubsumptionHierarchy(); - } - - @WebMethod - public String[] retrieval(int id,String Concept)throws ClientNotKnownException,NoOntologySelectedException{ - return getClientState(id).retrieval(Concept); - } - - @WebMethod - public void readOntology(int id,String ontologyURL, String format)throws ClientNotKnownException,OntologyURLNotValid{ - getClientState(id).readOntology(ontologyURL, format); - - } - - @WebMethod - public void removeOntology(int id)throws ClientNotKnownException{ - getClientState(id).removeOntology(); - } - - @WebMethod - public String learnConcept(int id)throws ClientNotKnownException{ - return "Deprecated method"; - - } - - - @WebMethod - public String getAlgorithmStatus(int id ) throws ClientNotKnownException{ - - return getClientState(id).getAlgorithmStatus(); - } - - - @WebMethod - public void learnMonitored(int id )throws ClientNotKnownException{ - getClientState(id).learnMonitored(); - } - /*@WebMethod - public void relearn(int id,String Concept )throws ClientNotKnownException{ - getClientState(id).relearn(Concept); - }*/ - - @WebMethod - public String getLastResult(int id)throws ClientNotKnownException{ - return getClientState(id).getLastResult(); - } - - @WebMethod - public void stop(int id)throws ClientNotKnownException{ - getClientState(id).stop(); - } - - - //*************************USER MANAGEMENT - - public ClientState getClientState(int id)throws ClientNotKnownException{ - System.out.println("Request from "+id); - ClientState c=this.clients.get(new Integer(id)); - if(c==null){ - //System.out.println(clients.keySet().toString()); - // throw new ClientNotKnownException("Client with id: "+id+" is not known","ClientNotKnownException"); - }; - return c; - - } - - - - - -} \ No newline at end of file Deleted: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,166 +0,0 @@ -package org.dllearner.server; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.jws.WebMethod; -import javax.jws.WebService; -import javax.jws.soap.SOAPBinding; - -import org.dllearner.Config; -import org.dllearner.algorithms.refinement.ROLearner; -import org.dllearner.core.Reasoner; -import org.dllearner.core.ReasoningMethodUnsupportedException; -import org.dllearner.core.ReasoningService; -import org.dllearner.core.dl.Individual; -import org.dllearner.kb.OntologyFileFormat; -import org.dllearner.learningproblems.PosNegLP; -import org.dllearner.utilities.Helper; - -/** - * Offene Fragen: - * - * Welche Rückgabetypen sind erlaubt? - * Wie behandelt man Exceptions (z.B. aus angegebener URI kann keine Ontologie - * gelesen werden)? - * - * @author Jens Lehmann - * - */ -@WebService(name = "DLLearnerWebService") -@SOAPBinding(style = SOAPBinding.Style.RPC) -public class DLLearnerWSoriginal { - - // private String ontologyURL; - // private String ontologyFormat; - private Reasoner reasoner; - private ReasoningService rs; - private SortedSet<Individual> positiveExamples = new TreeSet<Individual>(); - private SortedSet<Individual> negativeExamples = new TreeSet<Individual>(); - - /** - * Specifies the URI of the ontology containing the background - * knowledge. Reads the ontology and sends it to the reasoner. - * - * @param ontologyURI The URI of the ontology to use. - */ - // gleiche Methoden mit verschiedenen Parametern sind offenbar problematisch - /* - @WebMethod - public void readOntology(String ontologyURI) { - readOntology(ontologyURI, "RDF/XML"); - } - */ - - /** - * Specifies the URI of the ontology containing the background - * knowledge and its format. Reads the ontology and sends it to - * the reasoner. - * - * @param ontologyURI The URI of the ontology to use. - * @param format "RDF/XML" or "N-TRIPLES". - */ - @WebMethod - public void readOntology(String ontologyURL, String format) { - // this.ontologyURL = ontologyURL; - // this.ontologyFormat = format; - - // TODO: potentielles Sicherheitsrisiko, da man damit derzeit auch lokale Dateien - // laden könnte (Fix: nur http:// zulassen, kein file://) - URL ontology = null; - try { - ontology = new URL(ontologyURL); - } catch (MalformedURLException e1) { - e1.printStackTrace(); - } - - OntologyFileFormat ofFormat; - if (format.equals("RDF/XML")) - ofFormat = OntologyFileFormat.RDF_XML; - else - ofFormat = OntologyFileFormat.N_TRIPLES; - - Map<URL, OntologyFileFormat> m = new HashMap<URL, OntologyFileFormat>(); - m.put(ontology, ofFormat); - - // Default-URI für DIG-Reasoner setzen -// try { -// Config.digReasonerURL = new URL("http://localhost:8081"); -// } catch (MalformedURLException e) { -// // Exception tritt nie auf, da URL korrekt -// e.printStackTrace(); -// } - - // reasoner = Main.createReasoner(new KB(), m); - - rs = new ReasoningService(reasoner); - - } - - - @WebMethod - public String[] testString(String c) { - - return new String[]{"a","b"}; - } - - // String[] funktioniert leider noch nicht - @WebMethod - public void addPositiveExamples(String[] posExamples) { - for(String example : posExamples) - positiveExamples.add(new Individual(example)); - } - - @WebMethod - public void addNegativeExamples(String[] negExamples) { - for(String example : negExamples) - negativeExamples.add(new Individual(example)); - } - - - @WebMethod - public void addPositiveExample(String posExample) { - positiveExamples.add(new Individual(posExample)); - } - - @WebMethod - public void addNegativeExample(String negExample) { - negativeExamples.add(new Individual(negExample)); - } - - @WebMethod - public String learnConcept() { - // notwendige Vorverarbeitungsschritte für den Lernalgorithmus - // - es müssen ein paar Konzepte, die ev. von Jena generiert wurden ignoriert - // werden - // - die Subsumptionhierarchie muss erstellt werden - // - die Subsumptionhierarchie wird verbessert um das Lernen effizienter zu machen - Helper.autoDetectConceptsAndRoles(rs); - reasoner.prepareSubsumptionHierarchy(); - if (Config.Refinement.improveSubsumptionHierarchy) { - try { - reasoner.getSubsumptionHierarchy().improveSubsumptionHierarchy(); - } catch (ReasoningMethodUnsupportedException e) { - // solange DIG-Reasoner eingestellt ist, schlägt diese Operation nie fehl - e.printStackTrace(); - } - } - - // LearningProblem learningProblem = new LearningProblem(rs, positiveExamples, negativeExamples); - PosNegLP learningProblem = null; - // erstmal wird nur der Refinement-Learner als Web-Service angeboten - ROLearner learner = new ROLearner(learningProblem, null); - return learner.getBestSolution().toString(); - } - - // Testmethode - @WebMethod - public String hello(String name) { - return "Hello " + name + "!"; - } - -} \ No newline at end of file Deleted: trunk/src/dl-learner/org/dllearner/server/LearnMonitor.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/LearnMonitor.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/LearnMonitor.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,84 +0,0 @@ -package org.dllearner.server; - -import org.dllearner.Config; -import org.dllearner.core.ReasoningMethodUnsupportedException; -import org.dllearner.utilities.Helper; - -public class LearnMonitor extends Thread { - - - private ClientState c; - private boolean active = false; - - //private ROLearner ROL; - - public LearnMonitor(ClientState c){ - this.c=c; - } - - - public void end(){ - - System.out.println("trying to end"); - System.out.println("ROL2"+c.ROL); - this.c.ROL.stop(); - c.setLastResult(c.ROL.getBestSolution().toString()); - c.setStatus("stopped"); - } - - public void learn(){ - - this.start(); - - } - - /** - * @override - */ - @Override - public void run(){ - try{ - c.setStatus("still running"); - if(active); - active=true; - c.setStatus("running"); - - // notwendige Vorverarbeitungsschritte für den Lernalgorithmus - // - es müssen ein paar Konzepte, die ev. von Jena generiert wurden ignoriert - // werden - // - die Subsumptionhierarchie muss erstellt werden - // - die Subsumptionhierarchie wird verbessert um das Lernen effizienter zu machen - Helper.autoDetectConceptsAndRoles(c.getRs()); - c.getReasoner().prepareSubsumptionHierarchy(); - if (Config.Refinement.improveSubsumptionHierarchy) { - try { - c.getReasoner().getSubsumptionHierarchy().improveSubsumptionHierarchy(); - } catch (ReasoningMethodUnsupportedException e) { - // solange DIG-Reasoner eingestellt ist, schlägt diese Operation nie fehl - e.printStackTrace(); - } - } - c.p("learning started"); - // LearningProblem learningProblem = new LearningProblem(c.getRs(), c.getPosExamples(), c.getNegExamples()); - // erstmal wird nur der Refinement-Learner als Web-Service angeboten - //System.out.println("aaaa"); - // c.ROL = new ROLearner(learningProblem); - - c.ROL.start(); - //new ROLearner(); - //c.p(("ROL1"+ROL)); - - - - - - - //c.setLastResult(c.ROL.getBestSolution().toString()); - c.setLastResult(c.ROL.getBestSolution().toString()); - c.setStatus("finished"); - - }catch (Exception e) {e.printStackTrace();} - finally{active=false;}; - } - -} Deleted: trunk/src/dl-learner/org/dllearner/server/NoOntologySelectedException.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/NoOntologySelectedException.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/NoOntologySelectedException.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,15 +0,0 @@ -package org.dllearner.server; - -public class NoOntologySelectedException extends Exception { - static final long serialVersionUID=101; - String detail; - - public NoOntologySelectedException (String message, String detail) { - super (message); - this.detail = detail; - } - - public String getDetail () { - return detail; - } -} Deleted: trunk/src/dl-learner/org/dllearner/server/OntologyURLNotValid.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/OntologyURLNotValid.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/OntologyURLNotValid.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,15 +0,0 @@ -package org.dllearner.server; - -public class OntologyURLNotValid extends Exception { - static final long serialVersionUID=102; - String detail; - - public OntologyURLNotValid (String message, String detail) { - super (message); - this.detail = detail; - } - - public String getDetail () { - return detail; - } -} Deleted: trunk/src/dl-learner/org/dllearner/server/jaxws/NoOntologySelectedExceptionBean.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/jaxws/NoOntologySelectedExceptionBean.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/jaxws/NoOntologySelectedExceptionBean.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,63 +0,0 @@ - -package org.dllearner.server.jaxws; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - * This class was generated by the JAXWS SI. - * JAX-WS RI 2.0_02-b08-fcs - * Generated source version: 2.0_02 - * - */ -@XmlRootElement(name = "NoOntologySelectedException", namespace = "http://server.dllearner.org/") -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "NoOntologySelectedException", namespace = "http://server.dllearner.org/", propOrder = { - "detail", - "message" -}) -public class NoOntologySelectedExceptionBean { - - private String detail; - private String message; - - /** - * - * @return - * returns String - */ - public String getDetail() { - return this.detail; - } - - /** - * - * @param detail - * the value for the detail property - */ - public void setDetail(String detail) { - this.detail = detail; - } - - /** - * - * @return - * returns String - */ - public String getMessage() { - return this.message; - } - - /** - * - * @param message - * the value for the message property - */ - public void setMessage(String message) { - this.message = message; - } - -} Deleted: trunk/src/dl-learner/org/dllearner/server/jaxws/OntologyURLNotValidBean.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/jaxws/OntologyURLNotValidBean.java 2007-10-16 09:19:34 UTC (rev 225) +++ trunk/src/dl-learner/org/dllearner/server/jaxws/OntologyURLNotValidBean.java 2007-10-16 09:27:26 UTC (rev 226) @@ -1,63 +0,0 @@ - -package org.dllearner.server.jaxws; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - * This class was generated by the JAXWS SI. - * JAX-WS RI 2.0_02-b08-fcs - * Generated source version: 2.0_02 - * - */ -@XmlRootElement(name = "OntologyURLNotValid", namespace = "http://server.dllearner.org/") -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "OntologyURLNotValid", namespace = "http://server.dllearner.org/", propOrder = { - "detail", - "message" -}) -public class OntologyURLNotValidBean { - - private String detail; - private String message; - - /** - * - * @return - * returns String - */ - public String getDetail() { - return this.detail; - } - - /** - * - * @param detail - * the value for the detail property - */ - public void setDetail(String detail) { - this.detail = detail; - } - - /** - * - * @return - * returns String - */ - public String getMessage() { - return this.message; - } - - /** - * - * @param message - * the value for the message property - */ - public void setMessage(String message) { - this.message = message; - } - -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-16 09:19:38
|
Revision: 225 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=225&view=rev Author: jenslehmann Date: 2007-10-16 02:19:34 -0700 (Tue, 16 Oct 2007) Log Message: ----------- - extended web service interface by reasoning methods - continued evaluation cache Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java trunk/src/dl-learner/org/dllearner/utilities/Datastructures.java trunk/src/dl-learner/org/dllearner/utilities/SortedSetTuple.java Modified: trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java 2007-10-15 16:37:22 UTC (rev 224) +++ trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java 2007-10-16 09:19:34 UTC (rev 225) @@ -22,15 +22,14 @@ import java.util.Map; import java.util.SortedSet; import java.util.TreeMap; -import java.util.TreeSet; -import org.dllearner.core.dl.AtomicConcept; import org.dllearner.core.dl.Concept; import org.dllearner.core.dl.Individual; import org.dllearner.core.dl.MultiConjunction; import org.dllearner.core.dl.MultiDisjunction; import org.dllearner.utilities.ConceptComparator; import org.dllearner.utilities.Helper; +import org.dllearner.utilities.SortedSetTuple; /** * Caches results of previous concept evaluation to speed up @@ -46,6 +45,7 @@ // maps a concept to a list of individuals it covers private Map<Concept,SortedSet<Individual>> cache; + private boolean checkForEqualConcepts = false; // concept comparator for concept indexing // (so only logarithmic time complexity is needed to access a cached object) @@ -66,44 +66,49 @@ /** * Determines which examples are instances of a concept. * @param concept - * @return Set of inferred individuals or null if none were infered. + * @return A tuple of two sets, where the first element is the + * set of individuals belonging to the class and the second element + * is the set of individuals not belonging to the class. For all + * elements, which are in neither of the sets, the cache cannot + * safely determine whether they are concept instances or not. */ - public SortedSet<Individual> inferMember(Concept concept) { - // return examples for atomic concepts if it is in the cache - if(concept instanceof AtomicConcept) - return cache.get(concept); - // for a negation NOT C we can only say which concepts are not in it - // (those in C), but we cannot say which ones are in NOT C -// else if(concept instanceof Negation) -// return Helper.difference(examples, inferPos(concept.getChild(0))); - // for a conjunction we know that the intersection of instances - // of all children belongs to the concept - else if(concept instanceof MultiConjunction) { - SortedSet<Individual> ret = inferMember(concept.getChild(0)); - for(int i=1; i<concept.getChildren().size(); i++) { - ret = Helper.intersection(ret, inferMember(concept.getChild(i))); + public SortedSetTuple<Individual> infer(Concept concept) { + if(checkForEqualConcepts) { + SortedSet<Individual> pos = cache.get(concept); + SortedSet<Individual> neg = Helper.difference(examples, pos); + return new SortedSetTuple<Individual>(pos,neg); + } else { + // for a negation NOT C we can only say which concepts are not in it + // (those in C), but we cannot say which ones are in NOT C + + // for a conjunction we know that the intersection of instances + // of all children belongs to the concept + if(concept instanceof MultiConjunction) { + handleMultiConjunction((MultiConjunction)concept); + // disjunctions are similar to conjunctions but we use union here; + // note that there can be instances which are neither in a concept + // C nor in a concept D, but in (C OR D) + } else if(concept instanceof MultiDisjunction) { + SortedSet<Individual> ret = cache.get(concept.getChild(0)); + for(int i=1; i<concept.getChildren().size(); i++) { + ret = Helper.union(ret, cache.get(concept.getChild(i))); + } + // in all other cases we cannot infer anything, so we return an + // empty tuple + } else { + return new SortedSetTuple<Individual>(); } - return ret; - // disjunctions are similar to conjunctions but we use union here; - // note that there can be instances which are neither in a concept - // C nor in a concept D, but in (C OR D) - } else if(concept instanceof MultiDisjunction) { - SortedSet<Individual> ret = inferMember(concept.getChild(0)); - for(int i=1; i<concept.getChildren().size(); i++) { - ret = Helper.union(ret, inferMember(concept.getChild(i))); - } - return ret; } - return new TreeSet<Individual>(); + return null; } - /** - * Determines which examples are not instance of a concept. - * @param concept - * @return - */ - public SortedSet<Individual> inferNonMember(Concept concept) { + private SortedSetTuple<Individual> handleMultiConjunction(MultiConjunction mc) { + SortedSet<Individual> pos = cache.get(mc.getChild(0)); + for(int i=1; i<mc.getChildren().size(); i++) { + pos = Helper.intersection(pos, cache.get(mc.getChild(i))); + } + // TODO: handle the case that some children may not be in cache return null; } } Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-15 16:37:22 UTC (rev 224) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-16 09:19:34 UTC (rev 225) @@ -23,6 +23,7 @@ import java.util.Map; import java.util.Random; import java.util.Set; +import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; @@ -38,11 +39,17 @@ import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasonerComponent; import org.dllearner.core.dl.AtomicConcept; +import org.dllearner.core.dl.AtomicRole; +import org.dllearner.core.dl.Concept; +import org.dllearner.core.dl.Individual; import org.dllearner.kb.OWLFile; import org.dllearner.kb.SparqlEndpoint; import org.dllearner.learningproblems.PosNegDefinitionLP; import org.dllearner.learningproblems.PosNegInclusionLP; +import org.dllearner.parser.KBParser; +import org.dllearner.parser.ParseException; import org.dllearner.reasoning.DIGReasoner; +import org.dllearner.utilities.Datastructures; /** * DL-Learner web service interface. @@ -140,36 +147,36 @@ } @WebMethod - public void setReasoner(int id, String component) throws ClientNotKnownException, UnknownComponentException { + public int setReasoner(int id, String component) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); Class<? extends ReasonerComponent> rcClass = reasonerMapping.get(component); if(rcClass == null) throw new UnknownComponentException(component); ReasonerComponent rc = cm.reasoner(rcClass, state.getKnowledgeSources()); - state.setReasonerComponent(rc); + return state.setReasonerComponent(rc); } @WebMethod - public void setLearningProblem(int id, String component) throws ClientNotKnownException, UnknownComponentException { + public int setLearningProblem(int id, String component) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); Class<? extends LearningProblem> lpClass = learningProblemMapping.get(component); if(lpClass == null) throw new UnknownComponentException(component); LearningProblem lp = cm.learningProblem(lpClass, state.getReasoningService()); - state.setLearningProblem(lp); + return state.setLearningProblem(lp); } @WebMethod - public void setLearningAlgorithm(int id, String component) throws ClientNotKnownException, UnknownComponentException { + public int setLearningAlgorithm(int id, String component) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); Class<? extends LearningAlgorithm> laClass = learningAlgorithmMapping.get(component); if(laClass == null) throw new UnknownComponentException(component); LearningAlgorithm la = cm.learningAlgorithm(laClass, state.getLearningProblem(), state.getReasoningService()); - state.setLearningAlgorithm(la); + return state.setLearningAlgorithm(la); } /** @@ -263,27 +270,23 @@ } @WebMethod - public void applyConfigEntryInt(int sessionID, int componentID, String optionName, Integer value) throws ClientNotKnownException, UnknownComponentException - { + public void applyConfigEntryInt(int sessionID, int componentID, String optionName, Integer value) throws ClientNotKnownException, UnknownComponentException { applyConfigEntry(sessionID, componentID,optionName,value); } @WebMethod - public void applyConfigEntryString(int sessionID, int componentID, String optionName, String value) throws ClientNotKnownException, UnknownComponentException - { + public void applyConfigEntryString(int sessionID, int componentID, String optionName, String value) throws ClientNotKnownException, UnknownComponentException { applyConfigEntry(sessionID, componentID,optionName,value); } @WebMethod - public void applyConfigEntryStringArray(int sessionID, int componentID, String optionName, String[] value) throws ClientNotKnownException, UnknownComponentException - { + public void applyConfigEntryStringArray(int sessionID, int componentID, String optionName, String[] value) throws ClientNotKnownException, UnknownComponentException { Set<String> stringSet = new TreeSet<String>(Arrays.asList(value)); applyConfigEntry(sessionID, componentID,optionName,stringSet); } @WebMethod - public void applyConfigEntryBoolean(int sessionID, int componentID, String optionName, Boolean value) throws ClientNotKnownException, UnknownComponentException - { + public void applyConfigEntryBoolean(int sessionID, int componentID, String optionName, Boolean value) throws ClientNotKnownException, UnknownComponentException { applyConfigEntry(sessionID, componentID,optionName,value); } @@ -300,14 +303,48 @@ @WebMethod public String[] getAtomicConcepts(int id) throws ClientNotKnownException { Set<AtomicConcept> atomicConcepts = getState(id).getReasoningService().getAtomicConcepts(); - // convert to String-Array - String[] result = new String[atomicConcepts.size()]; - int i=0; - for(AtomicConcept ac : atomicConcepts) { - result[i] = ac.getName(); - i++; + return Datastructures.sortedSet2StringListConcepts(atomicConcepts); + } + + @WebMethod + public String getSubsumptionHierarchy(int id) throws ClientNotKnownException { + return getState(id).getReasoningService().toString(); + } + + @WebMethod + public String[] retrieval(int id, String conceptString) throws ClientNotKnownException { + State state = getState(id); + // call parser to parse atomic concept + Concept concept = null; + try { + concept = KBParser.parseConcept(conceptString); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - return result; + Set<Individual> individuals = state.getReasoningService().retrieval(concept); + return Datastructures.sortedSet2StringListIndividuals(individuals); } + @WebMethod + public String[] getAtomicRoles(int id) throws ClientNotKnownException { + State state = getState(id); + Set<AtomicRole> roles = state.getReasoningService().getAtomicRoles(); + return Datastructures.sortedSet2StringListRoles(roles); + } + + @WebMethod + public String[] getInstances(int id) throws ClientNotKnownException { + State state = getState(id); + Set<Individual> individuals = state.getReasoningService().getIndividuals(); + return Datastructures.sortedSet2StringListIndividuals(individuals); + } + + @WebMethod + public String[] getIndividualsForARole(int id, String role) throws ClientNotKnownException { + State state = getState(id); + Map<Individual,SortedSet<Individual>> m = state.getReasoningService().getRoleMembers(new AtomicRole(role)); + Set<Individual> individuals = m.keySet(); + return Datastructures.sortedSet2StringListIndividuals(individuals); + } } Modified: trunk/src/dl-learner/org/dllearner/utilities/Datastructures.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/Datastructures.java 2007-10-15 16:37:22 UTC (rev 224) +++ trunk/src/dl-learner/org/dllearner/utilities/Datastructures.java 2007-10-16 09:19:34 UTC (rev 225) @@ -19,10 +19,17 @@ */ package org.dllearner.utilities; +import java.util.Arrays; import java.util.Iterator; import java.util.Set; +import org.dllearner.core.dl.AtomicConcept; +import org.dllearner.core.dl.AtomicRole; +import org.dllearner.core.dl.Individual; + /** + * Conversion between different data structures. + * * @author Jens Lehmann * @author Sebastian Hellmann * @@ -44,7 +51,7 @@ * @param s * @return */ - public static String[] setToArray(Set<String> s){ + public static String[] setToArray(Set<String> s) { if(s==null)return null; String[] ret=new String[s.size()]; int i=0; @@ -57,4 +64,39 @@ } + public static String[] sortedSet2StringListIndividuals(Set<Individual> individuals){ + + String[] ret=new String[individuals.size()]; + Iterator<Individual> i=individuals.iterator(); + int a=0; + while (i.hasNext()){ + ret[a++]=((Individual)i.next()).getName(); + } + Arrays.sort(ret); + return ret; + } + + public static String[] sortedSet2StringListRoles(Set<AtomicRole> s){ + + String[] ret=new String[s.size()]; + Iterator<AtomicRole> i=s.iterator(); + int a=0; + while (i.hasNext()){ + ret[a++]=((AtomicRole)i.next()).getName(); + } + Arrays.sort(ret); + return ret; + } + + public static String[] sortedSet2StringListConcepts(Set<AtomicConcept> s){ + + String[] ret=new String[s.size()]; + Iterator<AtomicConcept> i=s.iterator(); + int a=0; + while (i.hasNext()){ + ret[a++]=((AtomicConcept)i.next()).getName(); + } + Arrays.sort(ret); + return ret; + } } Modified: trunk/src/dl-learner/org/dllearner/utilities/SortedSetTuple.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/SortedSetTuple.java 2007-10-15 16:37:22 UTC (rev 224) +++ trunk/src/dl-learner/org/dllearner/utilities/SortedSetTuple.java 2007-10-16 09:19:34 UTC (rev 225) @@ -1,12 +1,18 @@ package org.dllearner.utilities; import java.util.SortedSet; +import java.util.TreeSet; public class SortedSetTuple<T> { private SortedSet<T> posSet; private SortedSet<T> negSet; + public SortedSetTuple() { + posSet = new TreeSet<T>(); + negSet = new TreeSet<T>(); + } + public SortedSetTuple(SortedSet<T> posSet, SortedSet<T> negSet) { this.posSet = posSet; this.negSet = negSet; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-15 16:37:29
|
Revision: 224 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=224&view=rev Author: jenslehmann Date: 2007-10-15 09:37:22 -0700 (Mon, 15 Oct 2007) Log Message: ----------- - positive only definition learning problem partly implemented - refinement operator based approach adapted for positive only learning - CLI extended to handle positive only problem (use "problem = posOnlyDefinition;" in conf file) Modified Paths: -------------- trunk/examples/father.conf trunk/lib/components.ini trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/RhoDown.java trunk/src/dl-learner/org/dllearner/cli/Start.java trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java Modified: trunk/examples/father.conf =================================================================== --- trunk/examples/father.conf 2007-10-15 15:04:57 UTC (rev 223) +++ trunk/examples/father.conf 2007-10-15 16:37:22 UTC (rev 224) @@ -17,7 +17,7 @@ // algorithm settings algorithm = refinement; -// problem = posNegInclusion; +// problem = posOnlyDefinition; // search tree protocol refinement.writeSearchTree = false; Modified: trunk/lib/components.ini =================================================================== --- trunk/lib/components.ini 2007-10-15 15:04:57 UTC (rev 223) +++ trunk/lib/components.ini 2007-10-15 16:37:22 UTC (rev 224) @@ -11,6 +11,7 @@ # learning problems org.dllearner.learningproblems.PosNegDefinitionLP org.dllearner.learningproblems.PosNegInclusionLP +org.dllearner.learningproblems.PosOnlyDefinitionLP # learning algorithms org.dllearner.algorithms.RandomGuesser org.dllearner.algorithms.BruteForceLearner Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-15 15:04:57 UTC (rev 223) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-15 16:37:22 UTC (rev 224) @@ -28,6 +28,7 @@ import org.dllearner.core.dl.MultiDisjunction; import org.dllearner.core.dl.Top; import org.dllearner.learningproblems.PosNegLP; +import org.dllearner.learningproblems.PosOnlyDefinitionLP; import org.dllearner.utilities.ConceptComparator; import org.dllearner.utilities.ConceptTransformation; import org.dllearner.utilities.Files; @@ -53,7 +54,8 @@ DecimalFormat df = new DecimalFormat(); private PosNegLP learningProblem; - // private LearningProblem learningProblem2; + private PosOnlyDefinitionLP posOnlyLearningProblem; + private boolean posOnly = false; // Menge von Kandidaten für Refinement // (wird für Direktzugriff auf Baumknoten verwendet) @@ -127,13 +129,19 @@ public ROLearner(PosNegLP learningProblem, ReasoningService rs) { this.learningProblem = learningProblem; this.rs = rs; - - + posOnly=false; } + public ROLearner(PosOnlyDefinitionLP learningProblem, ReasoningService rs) { + this.posOnlyLearningProblem = learningProblem; + this.rs = rs; + posOnly=true; + } + public static Collection<Class<? extends LearningProblem>> supportedLearningProblems() { Collection<Class<? extends LearningProblem>> problems = new LinkedList<Class<? extends LearningProblem>>(); problems.add(PosNegLP.class); + problems.add(PosOnlyDefinitionLP.class); return problems; } @@ -196,11 +204,15 @@ // adjust heuristic if(heuristic == Heuristic.LEXICOGRAPHIC) nodeComparator = new NodeComparator(); - else - nodeComparator = new NodeComparator2(learningProblem.getNegativeExamples().size(), learningProblem.getPercentPerLengthUnit()); + else { + if(posOnly) { + throw new RuntimeException("does not work with positive examples only yet"); + } + nodeComparator = new NodeComparator2(learningProblem.getNegativeExamples().size(), learningProblem.getPercentPerLengthUnit()); + } // this.learningProblem2 = learningProblem2; - operator = new RhoDown(learningProblem); + operator = new RhoDown(rs); // candidate sets entsprechend der gewählten Heuristik initialisieren candidates = new TreeSet<Node>(nodeComparator); @@ -219,6 +231,20 @@ return "refinement operator based learning algorithm"; } + private int coveredNegativesOrTooWeak(Concept concept) { + if(posOnly) + return posOnlyLearningProblem.coveredPseudoNegativeExamplesOrTooWeak(concept); + else + return learningProblem.coveredNegativeExamplesOrTooWeak(concept); + } + + private int getNumberOfNegatives() { + if(posOnly) + return posOnlyLearningProblem.getPseudoNegatives().size(); + else + return learningProblem.getNegativeExamples().size(); + } + // Kernalgorithmus @Override @SuppressWarnings("unchecked") @@ -230,7 +256,7 @@ // int coveredNegativeExamples = learningProblem.coveredNegativeExamplesOrTooWeak(top); // aus Top folgen immer alle negativen Beispiele, d.h. es ist nur eine Lösung, wenn // es keine negativen Beispiele gibt - int coveredNegativeExamples = learningProblem.getNegativeExamples().size(); + int coveredNegativeExamples = getNumberOfNegatives(); topNode.setCoveredNegativeExamples(coveredNegativeExamples); // topNode.setHorizontalExpansion(1); // die 0 ist eigentlich richtig, da keine Refinements // der Länge 1 untersucht wurden @@ -553,7 +579,7 @@ if(toEvaluateConcepts.size()>0) { // Test aller Konzepte auf properness (mit DIG in nur einer Anfrage) long propCalcReasoningStart = System.nanoTime(); - improperConcepts = learningProblem.getReasoningService().subsumes(toEvaluateConcepts, concept); + improperConcepts = rs.subsumes(toEvaluateConcepts, concept); propernessTestsReasoner+=toEvaluateConcepts.size(); // boolean isProper = !learningProblem.getReasoningService().subsumes(refinement, concept); propernessCalcReasoningTimeNs += System.nanoTime() - propCalcReasoningStart; @@ -622,7 +648,7 @@ if(Config.Refinement.useOverlyGeneralList && refinement instanceof MultiDisjunction) { if(containsOverlyGeneralElement((MultiDisjunction)refinement)) { conceptTestsOverlyGeneralList++; - quality = learningProblem.getNegativeExamples().size(); + quality = getNumberOfNegatives(); qualityKnown = true; newNode.setQualityEvaluationMethod(Node.QualityEvaluationMethod.OVERLY_GENERAL_LIST); } @@ -632,7 +658,7 @@ if(!qualityKnown) { long propCalcReasoningStart2 = System.nanoTime(); conceptTestsReasoner++; - quality = learningProblem.coveredNegativeExamplesOrTooWeak(refinement); + quality = coveredNegativesOrTooWeak(refinement); propernessCalcReasoningTimeNs += System.nanoTime() - propCalcReasoningStart2; newNode.setQualityEvaluationMethod(Node.QualityEvaluationMethod.REASONER); } @@ -654,7 +680,7 @@ // candidatesStable.add(newNode); - if(quality == learningProblem.getNegativeExamples().size()) + if(quality == getNumberOfNegatives()) overlyGeneralList.add(refinement); // System.out.print("."); @@ -773,12 +799,12 @@ if(showBenchmarkInformation) { - long reasoningTime = learningProblem.getReasoningService().getOverallReasoningTimeNs(); + long reasoningTime = rs.getOverallReasoningTimeNs(); double reasoningPercentage = 100 * reasoningTime/(double)algorithmRuntime; long propWithoutReasoning = propernessCalcTimeNs-propernessCalcReasoningTimeNs; double propPercentage = 100 * propWithoutReasoning/(double)algorithmRuntime; double deletionPercentage = 100 * childConceptsDeletionTimeNs/(double)algorithmRuntime; - long subTime = learningProblem.getReasoningService().getSubsumptionReasoningTimeNs(); + long subTime = rs.getSubsumptionReasoningTimeNs(); double subPercentage = 100 * subTime/(double)algorithmRuntime; double refinementPercentage = 100 * refinementCalcTimeNs/(double)algorithmRuntime; double redundancyCheckPercentage = 100 * redundancyCheckTimeNs/(double)algorithmRuntime; @@ -837,7 +863,10 @@ @Override public Score getSolutionScore() { - return learningProblem.computeScore(getBestSolution()); + if(posOnly) + return posOnlyLearningProblem.computeScore(getBestSolution()); + else + return learningProblem.computeScore(getBestSolution()); } @Override Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/RhoDown.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/RhoDown.java 2007-10-15 15:04:57 UTC (rev 223) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/RhoDown.java 2007-10-15 16:37:22 UTC (rev 224) @@ -45,7 +45,6 @@ import org.dllearner.core.dl.Quantification; import org.dllearner.core.dl.Role; import org.dllearner.core.dl.Top; -import org.dllearner.learningproblems.PosNegLP; import org.dllearner.utilities.ConceptComparator; import org.dllearner.utilities.ConceptTransformation; @@ -62,7 +61,7 @@ */ public class RhoDown implements RefinementOperator { - private PosNegLP learningProblem; +// private PosNegLP learningProblem; private ReasoningService rs; // gibt die Gr��e an bis zu der die Refinements des Top-Konzepts @@ -91,9 +90,10 @@ // braucht man wirklich das learningProblem oder reicht der Reasoning-Service? // TODO: conceptComparator könnte auch noch Parameter sein - public RhoDown(PosNegLP learningProblem) { - this.learningProblem = learningProblem; - rs = learningProblem.getReasoningService(); + public RhoDown(ReasoningService reasoningService) { + this.rs = reasoningService; +// this.learningProblem = learningProblem; +// rs = learningProblem.getReasoningService(); } public Set<Concept> refine(Concept concept) { @@ -141,7 +141,7 @@ // beachte: die Funktion gibt bereits nur nicht-äquivalente Konzepte zurück // TODO: der Cast auf SortedSet ist nur ein Hack und muss später geeignet // behandelt werden - refinements = learningProblem.getReasoningService().getMoreSpecialConcepts(concept); + refinements = rs.getMoreSpecialConcepts(concept); // refinements.addAll(learningProblem.getReasoningService().getMoreSpecialConcepts(concept)); // Bottom rausschmeißen (nicht im Operator vorgesehen) @@ -506,14 +506,14 @@ // TODO: Spezialfälle, dass zwischen Top und Bottom nichts liegt behandeln if(topRefinementsLength==0 && maxLength>0) { // Konzepte der Länge 1 = alle Konzepte, die in der Subsumptionhierarchie unter Top liegen - Set<Concept> m1 = learningProblem.getReasoningService().getMoreSpecialConcepts(new Top()); + Set<Concept> m1 = rs.getMoreSpecialConcepts(new Top()); m.put(1,m1); } if(topRefinementsLength<2 && maxLength>1) { // Konzepte der Länge 2 = Negation aller Konzepte, die über Bottom liegen if(Config.Refinement.useNegation) { - Set<Concept> m2tmp = learningProblem.getReasoningService().getMoreGeneralConcepts(new Bottom()); + Set<Concept> m2tmp = rs.getMoreGeneralConcepts(new Bottom()); Set<Concept> m2 = new TreeSet<Concept>(conceptComparator); for(Concept c : m2tmp) { m2.add(new Negation(c)); Modified: trunk/src/dl-learner/org/dllearner/cli/Start.java =================================================================== --- trunk/src/dl-learner/org/dllearner/cli/Start.java 2007-10-15 15:04:57 UTC (rev 223) +++ trunk/src/dl-learner/org/dllearner/cli/Start.java 2007-10-15 16:37:22 UTC (rev 224) @@ -62,6 +62,7 @@ import org.dllearner.kb.SparqlEndpoint; import org.dllearner.learningproblems.PosNegDefinitionLP; import org.dllearner.learningproblems.PosNegInclusionLP; +import org.dllearner.learningproblems.PosOnlyDefinitionLP; import org.dllearner.parser.ConfParser; import org.dllearner.parser.KBParser; import org.dllearner.parser.ParseException; @@ -143,6 +144,8 @@ lpClass = PosNegDefinitionLP.class; else if (problemOption.getStringValue().equals("posNegInclusion")) lpClass = PosNegInclusionLP.class; + else if (problemOption.getStringValue().equals("posOnlyDefinition")) + lpClass = PosOnlyDefinitionLP.class; else handleError("Unknown value " + problemOption.getValue() + " for option \"problem\"."); @@ -150,7 +153,8 @@ SortedSet<String> posExamples = parser.getPositiveExamples(); SortedSet<String> negExamples = parser.getNegativeExamples(); cm.applyConfigEntry(lp, "positiveExamples", posExamples); - cm.applyConfigEntry(lp, "negativeExamples", negExamples); + if(lpClass != PosOnlyDefinitionLP.class) + cm.applyConfigEntry(lp, "negativeExamples", negExamples); // step 4: detect learning algorithm ConfFileOption algorithmOption = parser.getConfOptionsByName("algorithm"); Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java 2007-10-15 15:04:57 UTC (rev 223) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosOnlyDefinitionLP.java 2007-10-15 16:37:22 UTC (rev 224) @@ -19,38 +19,81 @@ */ package org.dllearner.learningproblems; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Set; +import java.util.SortedSet; + +import org.dllearner.core.CommonConfigMappings; import org.dllearner.core.ConfigEntry; +import org.dllearner.core.ConfigOption; import org.dllearner.core.InvalidConfigOptionValueException; import org.dllearner.core.ReasoningService; import org.dllearner.core.Score; +import org.dllearner.core.StringSetConfigOption; import org.dllearner.core.dl.Concept; +import org.dllearner.core.dl.Individual; +import org.dllearner.utilities.Helper; /** + * Definition learning problem from only positive examples. + * * @author Jens Lehmann * */ public class PosOnlyDefinitionLP extends PosOnlyLP implements DefinitionLP { + protected SortedSet<Individual> positiveExamples; + protected SortedSet<Individual> pseudoNegatives; + + private PosNegDefinitionLP definitionLP; + public PosOnlyDefinitionLP(ReasoningService reasoningService) { super(reasoningService); } - /* (non-Javadoc) - * @see org.dllearner.core.LearningProblemNew#computeScore(org.dllearner.core.dl.Concept) + /* + * (non-Javadoc) + * + * @see org.dllearner.core.Component#applyConfigEntry(org.dllearner.core.ConfigEntry) */ @Override - public Score computeScore(Concept concept) { - // TODO Auto-generated method stub - return null; + @SuppressWarnings( { "unchecked" }) + public <T> void applyConfigEntry(ConfigEntry<T> entry) throws InvalidConfigOptionValueException { + String name = entry.getOptionName(); + if (name.equals("positiveExamples")) + positiveExamples = CommonConfigMappings + .getIndividualSet((Set<String>) entry.getValue()); } + + public static Collection<ConfigOption<?>> createConfigOptions() { + Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); + options.add(new StringSetConfigOption("positiveExamples", + "positive examples")); + return options; + } + + /* + * (non-Javadoc) + * + * @see org.dllearner.core.Component#getName() + */ + public static String getName() { + return "positive only definition learning problem"; + } + + /** + * @return the positiveExamples + */ + public SortedSet<Individual> getPositiveExamples() { + return positiveExamples; + } - /* (non-Javadoc) - * @see org.dllearner.core.Component#applyConfigEntry(org.dllearner.core.ConfigEntry) + /** + * @return the pseudoNegatives */ - @Override - public <T> void applyConfigEntry(ConfigEntry<T> entry) throws InvalidConfigOptionValueException { - // TODO Auto-generated method stub - + public SortedSet<Individual> getPseudoNegatives() { + return pseudoNegatives; } /* (non-Javadoc) @@ -58,8 +101,33 @@ */ @Override public void init() { - // TODO Auto-generated method stub - + // by default we test all other instances of the knowledge base + pseudoNegatives = Helper.difference(reasoningService.getIndividuals(), positiveExamples); + + // create an instance of a standard definition learning problem + // instanciated with pseudo-negatives + definitionLP = new PosNegDefinitionLP(reasoningService, positiveExamples, pseudoNegatives); + // TODO: we must make sure that the problem also gets the same + // reasoning options (i.e. options are the same up to reversed example sets) + definitionLP.init(); } - + + /* (non-Javadoc) + * @see org.dllearner.core.LearningProblemNew#computeScore(org.dllearner.core.dl.Concept) + */ + @Override + public Score computeScore(Concept concept) { + // TODO need to implement class <code>ScoreOneValued</code> + return null; + } + + /** + * + * @param concept + * @return -1 for too weak, otherwise the number of pseudo-negatives (more is usually worse). + */ + public int coveredPseudoNegativeExamplesOrTooWeak(Concept concept) { + return definitionLP.coveredNegativeExamplesOrTooWeak(concept); + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-15 15:04:59
|
Revision: 223 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=223&view=rev Author: jenslehmann Date: 2007-10-15 08:04:57 -0700 (Mon, 15 Oct 2007) Log Message: ----------- start of evaluation cache (not working yet) Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java Added: trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/learningproblems/EvaluationCache.java 2007-10-15 15:04:57 UTC (rev 223) @@ -0,0 +1,109 @@ +/** + * Copyright (C) 2007, 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.learningproblems; + +import java.util.Map; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.dllearner.core.dl.AtomicConcept; +import org.dllearner.core.dl.Concept; +import org.dllearner.core.dl.Individual; +import org.dllearner.core.dl.MultiConjunction; +import org.dllearner.core.dl.MultiDisjunction; +import org.dllearner.utilities.ConceptComparator; +import org.dllearner.utilities.Helper; + +/** + * Caches results of previous concept evaluation to speed up + * further evaluations. Implements a fast evaluation approach, + * which tries to infer the covered examples of a given concept + * from previous results. + * + * @todo Under construction. + * @author Jens Lehmann + * + */ +public class EvaluationCache { + + // maps a concept to a list of individuals it covers + private Map<Concept,SortedSet<Individual>> cache; + + // concept comparator for concept indexing + // (so only logarithmic time complexity is needed to access a cached object) + private ConceptComparator conceptComparator; + + private SortedSet<Individual> examples; + + public EvaluationCache(SortedSet<Individual> examples) { + this.examples = examples; + conceptComparator = new ConceptComparator(); + cache = new TreeMap<Concept,SortedSet<Individual>>(conceptComparator); + } + + public void put(Concept concept, SortedSet<Individual> individuals) { + cache.put(concept, individuals); + } + + /** + * Determines which examples are instances of a concept. + * @param concept + * @return Set of inferred individuals or null if none were infered. + */ + public SortedSet<Individual> inferMember(Concept concept) { + // return examples for atomic concepts if it is in the cache + if(concept instanceof AtomicConcept) + return cache.get(concept); + // for a negation NOT C we can only say which concepts are not in it + // (those in C), but we cannot say which ones are in NOT C +// else if(concept instanceof Negation) +// return Helper.difference(examples, inferPos(concept.getChild(0))); + // for a conjunction we know that the intersection of instances + // of all children belongs to the concept + else if(concept instanceof MultiConjunction) { + SortedSet<Individual> ret = inferMember(concept.getChild(0)); + for(int i=1; i<concept.getChildren().size(); i++) { + ret = Helper.intersection(ret, inferMember(concept.getChild(i))); + } + return ret; + // disjunctions are similar to conjunctions but we use union here; + // note that there can be instances which are neither in a concept + // C nor in a concept D, but in (C OR D) + } else if(concept instanceof MultiDisjunction) { + SortedSet<Individual> ret = inferMember(concept.getChild(0)); + for(int i=1; i<concept.getChildren().size(); i++) { + ret = Helper.union(ret, inferMember(concept.getChild(i))); + } + return ret; + } + + return new TreeSet<Individual>(); + } + + /** + * Determines which examples are not instance of a concept. + * @param concept + * @return + */ + public SortedSet<Individual> inferNonMember(Concept concept) { + return null; + } +} Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2007-10-14 15:49:31 UTC (rev 222) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2007-10-15 15:04:57 UTC (rev 223) @@ -19,21 +19,14 @@ */ package org.dllearner.learningproblems; -import java.util.Collection; -import java.util.LinkedList; import java.util.Set; import java.util.SortedSet; -import java.util.TreeSet; -import org.dllearner.core.BooleanConfigOption; -import org.dllearner.core.ConfigOption; import org.dllearner.core.ReasoningService; import org.dllearner.core.Score; -import org.dllearner.core.StringSetConfigOption; import org.dllearner.core.dl.Concept; import org.dllearner.core.dl.Individual; import org.dllearner.core.dl.Negation; -import org.dllearner.learningproblems.PosNegLP.UseMultiInstanceChecks; import org.dllearner.utilities.Helper; /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-14 15:49:39
|
Revision: 222 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=222&view=rev Author: jenslehmann Date: 2007-10-14 08:49:31 -0700 (Sun, 14 Oct 2007) Log Message: ----------- - implemented evaluation for inclusion learning problem => inclusion learning should now work - note that it can happen that no 100% accuracy solution for the inclusion problem exists, although the standard definition problem has a solution (see provided father example) - further note that if a concept is a solution of the standard definition learning problem and the inclusion problem, then it is also a solution of the strict definition learning problem Modified Paths: -------------- trunk/examples/father.conf trunk/examples/uncle.conf trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java Added Paths: ----------- trunk/examples/father_incl.kb Modified: trunk/examples/father.conf =================================================================== --- trunk/examples/father.conf 2007-10-12 13:20:01 UTC (rev 221) +++ trunk/examples/father.conf 2007-10-14 15:49:31 UTC (rev 222) @@ -16,12 +16,12 @@ // algorithm settings algorithm = refinement; -//refinement.horizontalExpansionFactor = 0.5; -//refinement.quiet = false; +// problem = posNegInclusion; + // search tree protocol -// refinement.writeSearchTree = false; -// refinement.searchTreeFile = "log/searchTree.txt"; +refinement.writeSearchTree = false; +refinement.searchTreeFile = "log/searchFather.txt"; // control output cli.checkSatisfiability = true; @@ -31,6 +31,7 @@ cli.showSubsumptionHierarchy = false; import("father.kb"); +// import("father_incl.kb"); /** examples **/ +stefan Added: trunk/examples/father_incl.kb =================================================================== --- trunk/examples/father_incl.kb (rev 0) +++ trunk/examples/father_incl.kb 2007-10-14 15:49:31 UTC (rev 222) @@ -0,0 +1,20 @@ +BOTTOM = (male AND female). + +// persons +male(markus). +male(stefan). +male(heinz). +male(bernd). +female(anna). +female(gabi). +female(michelle). + +// children +hasChild(stefan,markus). +hasChild(markus,anna). +hasChild(bernd,gabi). +hasChild(anna,heinz). + +// to learn the inclusion axiom father SUBCLASS OF male AND EXISTS hasChild.TOP +// properly, we have to specifiy explicity that heinz does not have children +NOT EXISTS hasChild.TOP(heinz). Modified: trunk/examples/uncle.conf =================================================================== --- trunk/examples/uncle.conf 2007-10-12 13:20:01 UTC (rev 221) +++ trunk/examples/uncle.conf 2007-10-14 15:49:31 UTC (rev 222) @@ -14,9 +14,10 @@ * Copyright (C) 2007, Jens Lehmann */ -problem = posNegDefinition; +refinement.writeSearchTree = false; +refinement.searchTreeFile = "log/search_uncle.txt"; -digReasoner.writeDIGProtocol = true; +digReasoner.writeDIGProtocol = false; digReasoner.digProtocolFile = "log/dig_uncle.txt"; import("uncle.kb"); Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2007-10-12 13:20:01 UTC (rev 221) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegInclusionLP.java 2007-10-14 15:49:31 UTC (rev 222) @@ -21,6 +21,9 @@ import java.util.Collection; import java.util.LinkedList; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import org.dllearner.core.BooleanConfigOption; import org.dllearner.core.ConfigOption; @@ -28,7 +31,10 @@ import org.dllearner.core.Score; import org.dllearner.core.StringSetConfigOption; import org.dllearner.core.dl.Concept; +import org.dllearner.core.dl.Individual; import org.dllearner.core.dl.Negation; +import org.dllearner.learningproblems.PosNegLP.UseMultiInstanceChecks; +import org.dllearner.utilities.Helper; /** * The aim of this learning problem is to find an appropriate inclusion axiom @@ -56,7 +62,7 @@ public PosNegInclusionLP(ReasoningService reasoningService) { super(reasoningService); } - +/* public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); options.add(new StringSetConfigOption("positiveExamples", @@ -67,7 +73,7 @@ "Specifies whether to use retrieval or instance checks for testing a concept.")); return options; } - +*/ /* * (non-Javadoc) * @@ -86,19 +92,89 @@ public void init() { super.init(); definitionLP = new PosNegDefinitionLP(reasoningService, negativeExamples, positiveExamples); + // TODO: we must make sure that the problem also gets the same + // reasoning options (i.e. options are the same up to reversed example sets) + definitionLP.init(); } /** - * Calls the same method on the standard definition learning problem, but - * negates the concept before and permutes positive and negative examples. + * See the documentation of <code>coveredNegativeExamplesOrTooWeak</code> in + * the definition learning problem case. This method works differently: + * First, it tests whether none of the positive examples is covered by the + * negation of the given concept. Should this be the case, it returns + * too weak. If this is not the case, the method returns the number of + * negative examples, which do not follow from the negation of the input + * concept. Thus, this methods uses a different notion of coverage than + * the one for the standard definition learning problem. * - * @see org.dllearner.learningproblems.PosNegLP#coveredNegativeExamplesOrTooWeak(org.dllearner.core.dl.Concept) + * @see org.dllearner.learningproblems.DefinitionLP.MultiInstanceChecks + * @param concept + * The concept to test. + * @return -1 if concept is too weak and the number of covered negative + * examples otherwise. */ @Override public int coveredNegativeExamplesOrTooWeak(Concept concept) { - return definitionLP.coveredNegativeExamplesOrTooWeak(new Negation(concept)); + + if (useRetrievalForClassification) { + SortedSet<Individual> inNegatedConcept = reasoningService.retrieval(new Negation(concept)); + + for (Individual posExample : positiveExamples) { + // if any positive example follows from the negation, then + // the concept is "too weak" + if (inNegatedConcept.contains(posExample)) + return -1; + } + + // number of covered negatives + // cover = neg. example does not belong to the negated concept + SortedSet<Individual> negExInNegatedConcept = Helper.intersection(negativeExamples, inNegatedConcept); + return (negativeExamples.size() - negExInNegatedConcept.size()); + } else { + if (useDIGMultiInstanceChecks != UseMultiInstanceChecks.NEVER) { + // two checks + if (useDIGMultiInstanceChecks == UseMultiInstanceChecks.TWOCHECKS) { + Set<Individual> posExInNegatedConcept = reasoningService.instanceCheck(new Negation(concept), positiveExamples); + + if(posExInNegatedConcept.size()>0) { + return -1; + } else { + Set<Individual> negExInNegatedConcept = reasoningService.instanceCheck(new Negation(concept), negativeExamples); + return (negativeExamples.size() - negExInNegatedConcept.size()); + } + + // one check + } else { + Set<Individual> inNegatedConcept = reasoningService.instanceCheck(new Negation(concept), allExamples); + + for(Individual i : positiveExamples) { + if(inNegatedConcept.contains(i)) + return -1; + } + + // we can now be sure that inNegatedConcept contains only + // negative examples + return (negativeExamples.size() - inNegatedConcept.size()); + + } + // single instance checks + } else { + int coverCount = negativeExamples.size(); + + for (Individual example : positiveExamples) { + if (reasoningService.instanceCheck(new Negation(concept), example)) + return -1; + } + for (Individual example : negativeExamples) { + if (!reasoningService.instanceCheck(new Negation(concept), example)) + coverCount--; + } + + return coverCount; + } + } } - + /** * Calls the same method on the standard definition learning problem, but * negates the concept before and permutes positive and negative examples. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-12 13:20:12
|
Revision: 221 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=221&view=rev Author: jenslehmann Date: 2007-10-12 06:20:01 -0700 (Fri, 12 Oct 2007) Log Message: ----------- started to readd the genetic programming based learning configuration options Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java Modified: trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2007-10-12 12:56:15 UTC (rev 220) +++ trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2007-10-12 13:20:01 UTC (rev 221) @@ -47,12 +47,16 @@ import org.dllearner.Config; import org.dllearner.algorithms.hybridgp.Psi; +import org.dllearner.core.BooleanConfigOption; import org.dllearner.core.ConfigEntry; import org.dllearner.core.ConfigOption; +import org.dllearner.core.DoubleConfigOption; +import org.dllearner.core.IntegerConfigOption; import org.dllearner.core.InvalidConfigOptionValueException; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.Score; +import org.dllearner.core.StringConfigOption; import org.dllearner.core.dl.Concept; import org.dllearner.core.dl.Top; import org.dllearner.learningproblems.PosNegLP; @@ -138,6 +142,56 @@ public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); + StringConfigOption selectionType = new StringConfigOption("selectionType", "selection type", "rankSelection"); + selectionType.setAllowedValues(new String[] {"rankSelection", "fps", "tournament"}); + options.add(selectionType); + IntegerConfigOption tournamentSize = new IntegerConfigOption("tournamentSize", "tournament size (applies only to tournament selection)", 3); + tournamentSize.setLowerLimit(2); + tournamentSize.setUpperLimit(20); + options.add(tournamentSize); + options.add(new BooleanConfigOption("elitism", "specifies whether to use elitism in selection", true)); + StringConfigOption algorithmType = new StringConfigOption("algorithmType", "algorithm type", "steadyState"); + algorithmType.setAllowedValues(new String[] {"generational", "steadyState"}); + DoubleConfigOption mutationProb = new DoubleConfigOption("mutationProbablitiy", "mutation probability", 0.03); + mutationProb.setLowerLimit(0.0); + mutationProb.setUpperLimit(1.0); + options.add(mutationProb); + DoubleConfigOption crossoverProb = new DoubleConfigOption("crossoverProbablitiy", "crossover probability", 0.95); + crossoverProb.setLowerLimit(0.0); + crossoverProb.setUpperLimit(1.0); + options.add(crossoverProb); + DoubleConfigOption hillClimbingProb = new DoubleConfigOption("hillClimbingProbablitiy", "hill climbing probability", 0.0); + hillClimbingProb.setLowerLimit(0.0); + hillClimbingProb.setUpperLimit(1.0); + options.add(hillClimbingProb); + DoubleConfigOption refinementProb = new DoubleConfigOption("refinementProbablitiy", "refinement operator probability (values higher than 0 turn this into a hybrid GP algorithm - see publication)", 0.00); + refinementProb.setLowerLimit(0.0); + refinementProb.setUpperLimit(1.0); + options.add(refinementProb); + IntegerConfigOption numberOfInd = new IntegerConfigOption("numberOfIndividuals", "number of individuals", 100); + numberOfInd.setLowerLimit(1); + options.add(numberOfInd); + IntegerConfigOption numberOfSelInd = new IntegerConfigOption("numberOfSelectedIndividuals", "number of selected individuals", 92); + numberOfSelInd.setLowerLimit(1); + options.add(numberOfSelInd); + options.add(new BooleanConfigOption("useFixedNumberOfGenerations", "specifies whether to use a fixed number of generations", false)); + IntegerConfigOption gen = new IntegerConfigOption("generations", "number of generations (only valid if a fixed number of generations is used)", 20); + gen.setLowerLimit(1); + options.add(gen); + IntegerConfigOption post = new IntegerConfigOption("postConvergenceGenerations", "number of generations after which to stop if no improvement wrt. the best solution has been achieved", 50); + post.setLowerLimit(1); + options.add(post); + options.add(new BooleanConfigOption("adc", "whether to use automatically defined concept (this invents new helper concepts, but enlarges the search space", false)); + IntegerConfigOption initMin = new IntegerConfigOption("initMinDepth", "minimum depth to use when creating the initial population", 4); + initMin.setLowerLimit(1); + options.add(initMin); + IntegerConfigOption initMax = new IntegerConfigOption("initMaxDepth", "maximum depth to use when creating the initial population", 6); + initMax.setLowerLimit(1); + options.add(initMax); + IntegerConfigOption max = new IntegerConfigOption("maxConceptLength", "maximum concept length (higher length means lowest possible fitness)", 75); + max.setLowerLimit(1); + options.add(max); + options.add(new BooleanConfigOption("useMultiStructures", "specifies whether to use e.g. (a AND b AND c) instead of ((A and b) and c) - there is no apparent reason to set this to false", true)); return options; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-12 12:56:21
|
Revision: 220 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=220&view=rev Author: jenslehmann Date: 2007-10-12 05:56:15 -0700 (Fri, 12 Oct 2007) Log Message: ----------- started to readd the refinement based learning configuration options Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/Config.java trunk/src/dl-learner/org/dllearner/ConfigurationManager.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java Modified: trunk/src/dl-learner/org/dllearner/Config.java =================================================================== --- trunk/src/dl-learner/org/dllearner/Config.java 2007-10-12 09:20:39 UTC (rev 219) +++ trunk/src/dl-learner/org/dllearner/Config.java 2007-10-12 12:56:15 UTC (rev 220) @@ -7,7 +7,6 @@ import org.dllearner.algorithms.gp.GP.SelectionType; import org.dllearner.core.dl.AtomicConcept; import org.dllearner.core.dl.AtomicRole; -import org.dllearner.learningproblems.PosNegLP.UseMultiInstanceChecks; public class Config { // standardmäßig wird bis Tiefe 7 gesucht @@ -98,13 +97,13 @@ // Informationen (Rollen, Konzepte, Individuen, Anzahl Axiome) über // Wissensbasis anzeigen => alles konfigurierbar um Output in Grenzen // zu halten - public static boolean showRoles = false; - public static boolean showConcepts = false; - public static boolean showIndividuals = false; - public static boolean showSubsumptionHierarchy = false; +// public static boolean showRoles = false; +// public static boolean showConcepts = false; +// public static boolean showIndividuals = false; +// public static boolean showSubsumptionHierarchy = false; // zeigt die interne Wissensbasis an (d.h. keine externen OWL-Dateien) - public static boolean showInternalKB = false; - public static int maxLineLength = 100; +// public static boolean showInternalKB = false; +// public static int maxLineLength = 100; // public static boolean writeDIGProtocol = false; // public static File digProtocolFile = new File("log/digProtocol.txt"); @@ -145,7 +144,7 @@ // ausgeführt // werden, bevor too weak festgestellt werden kann // TODO: not implemented - public static UseMultiInstanceChecks useDIGMultiInstanceChecks = UseMultiInstanceChecks.TWOCHECKS; +// public static UseMultiInstanceChecks useDIGMultiInstanceChecks = UseMultiInstanceChecks.TWOCHECKS; // geplante Optionen um den Suchraum einzuschränken @@ -185,7 +184,7 @@ // Domain und Range beim Verschachteln von Rollen beachten // nicht implementiert // TODO: Wie soll man das in DIG machen? - public static boolean useDomainRange = false; +// public static boolean useDomainRange = false; // bereits vorher allgemeinere Konzepte festlegen (Default: keine) // nicht implementiert Modified: trunk/src/dl-learner/org/dllearner/ConfigurationManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-12 09:20:39 UTC (rev 219) +++ trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-12 12:56:15 UTC (rev 220) @@ -454,15 +454,15 @@ else if(option.equals("hidePrefix")) { // Config.hidePrefixes.add(value); } else if (option.equals("showIndividuals")) { - Config.showIndividuals = Datastructures.strToBool(value); +// Config.showIndividuals = Datastructures.strToBool(value); } else if (option.equals("showConcepts")) { - Config.showConcepts = Datastructures.strToBool(value); +// Config.showConcepts = Datastructures.strToBool(value); } else if (option.equals("showRoles")) { - Config.showRoles = Datastructures.strToBool(value); +// Config.showRoles = Datastructures.strToBool(value); } else if (option.equals("showInternalKB")) { - Config.showInternalKB = Datastructures.strToBool(value); +// Config.showInternalKB = Datastructures.strToBool(value); } else if (option.equals("showSubsumptionHierarchy")) { - Config.showSubsumptionHierarchy = Datastructures.strToBool(value); +// Config.showSubsumptionHierarchy = Datastructures.strToBool(value); } else if (option.equals("writeDIGProtocol")) { // Config.writeDIGProtocol = Datastructures.strToBool(value); } else if (option.equals("digProtocolFile")) { Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-12 09:20:39 UTC (rev 219) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-12 12:56:15 UTC (rev 220) @@ -13,8 +13,10 @@ import org.dllearner.Config; import org.dllearner.core.BooleanConfigOption; +import org.dllearner.core.CommonConfigOptions; import org.dllearner.core.ConfigEntry; import org.dllearner.core.ConfigOption; +import org.dllearner.core.DoubleConfigOption; import org.dllearner.core.InvalidConfigOptionValueException; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; @@ -142,6 +144,25 @@ StringConfigOption heuristicOption = new StringConfigOption("heuristic", "specifiy the heuristic to use", "lexicographic"); heuristicOption.setAllowedValues(new String[] {"lexicographic", "flexible"}); options.add(heuristicOption); + options.add(new BooleanConfigOption("applyAllFilter", "usage of equivalence ALL R.C AND ALL R.D = ALL R.(C AND D)", true)); + options.add(new BooleanConfigOption("applyExistsFilter", "usage of equivalence EXISTS R.C OR EXISTS R.D = EXISTS R.(C OR D)", true)); + options.add(new BooleanConfigOption("useTooWeakList", "try to filter out too weak concepts without sending them to the reasoner", true)); + options.add(new BooleanConfigOption("useOverlyGeneralList", "try to find overly general concept without sending them to the reasoner", true)); + options.add(new BooleanConfigOption("useShortConceptConstruction", "shorten concept to see whether they already exist", true)); + DoubleConfigOption horizExp = new DoubleConfigOption("horizontalExpansionFactor", "horizontal expansion factor (see publication for description)", 0.6); + horizExp.setLowerLimit(0.0); + horizExp.setUpperLimit(1.0); + options.add(horizExp); + options.add(new BooleanConfigOption("improveSubsumptionHierarchy", "simplify subsumption hierarchy to reduce search space (see publication for description)", true)); + // TODO: replace by a general verbosity option for all components + options.add(new BooleanConfigOption("quiet", "may be deprecated soon", false)); + options.add(CommonConfigOptions.allowedConcepts()); + options.add(CommonConfigOptions.ignoredConcepts()); + options.add(CommonConfigOptions.allowedRoles()); + options.add(CommonConfigOptions.ignoredRoles()); + options.add(CommonConfigOptions.useAllConstructor()); + options.add(CommonConfigOptions.useExistsConstructor()); + options.add(CommonConfigOptions.useNegation()); return options; } Modified: trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-12 09:20:39 UTC (rev 219) +++ trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-12 12:56:15 UTC (rev 220) @@ -49,4 +49,32 @@ public static BooleanConfigOption getOWA() { return new BooleanConfigOption("owa", "open world assumption (if set to false, we try to close the world", true); } + + public static StringSetConfigOption allowedConcepts() { + return new StringSetConfigOption("allowedConcepts", "concepts the algorithm is allowed to use"); + } + + public static StringSetConfigOption allowedRoles() { + return new StringSetConfigOption("allowedRoles", "roles the algorithm is allowed to use"); + } + + public static StringSetConfigOption ignoredConcepts() { + return new StringSetConfigOption("ignoredConcepts", "concepts the algorithm must ignore"); + } + + public static StringSetConfigOption ignoredRoles() { + return new StringSetConfigOption("ignoredRoles", "roles the algorithm must ignore"); + } + + public static BooleanConfigOption useAllConstructor() { + return new BooleanConfigOption("useAllConstructor", "specifies whether to universal concept constructor is used in the learning algorothm"); + } + + public static BooleanConfigOption useExistsConstructor() { + return new BooleanConfigOption("useExistsConstructor", "specifies whether to existential concept constructor is used in the learning algorothm"); + } + + public static BooleanConfigOption useNegation() { + return new BooleanConfigOption("useNegation", "specifies whether negation is used in the learning algorothm"); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-12 09:20:41
|
Revision: 219 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=219&view=rev Author: jenslehmann Date: 2007-10-12 02:20:39 -0700 (Fri, 12 Oct 2007) Log Message: ----------- Added ConfigDocumentationGenerator class, which contains a main method. Calling this class will automatically query all the components (specified in components.ini) for the configuration options they support. A documentation file is created and written to doc/configOptions.txt. This way the config option documentation is always in sync with the source code and does not need to be written manually. Modified Paths: -------------- trunk/doc/configOptions.txt trunk/lib/components.ini trunk/src/dl-learner/org/dllearner/core/dl/Role.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/core/ConfigDocumentationGenerator.java Modified: trunk/doc/configOptions.txt =================================================================== --- trunk/doc/configOptions.txt 2007-10-12 08:44:21 UTC (rev 218) +++ trunk/doc/configOptions.txt 2007-10-12 09:20:39 UTC (rev 219) @@ -4,6 +4,19 @@ * Knowledge Sources * ********************* +component: KB file (org.dllearner.kb.KBFile) +============================================ + +option name: filename +description: pointer to the KB file on local file system +values: none +default value: null + +option name: url +description: URL pointer to the KB file +values: none +default value: null + component: OWL file (org.dllearner.kb.OWLFile) ============================================== @@ -12,24 +25,93 @@ values: none default value: null +component: SPARQL Endpoint (org.dllearner.kb.SparqlEndpoint) +============================================================ + +option name: url +description: URL of SPARQL Endpoint +values: none +default value: null + +option name: instances +description: relevant instances e.g. positive and negative examples in a learning problem +values: none +default value: null + +option name: numberOfRecursions +description: number of Recursions, the Sparql-Endpoint is asked +values: none +default value: null + +option name: filterMode +description: the mode of the SPARQL Filter +values: none +default value: null + +option name: predList +description: a predicate list +values: none +default value: null + +option name: objList +description: an object list +values: none +default value: null + +option name: classList +description: a class list +values: none +default value: null + +option name: format +description: N-TRIPLES or KB format +values: none +default value: null + +option name: dumpToFile +description: wether Ontology from DBPedia is written to a file or not +values: none +default value: null + ************* * Reasoners * ************* -component: DIG reasoner (org.dllearner.reasoning.DIGReasonerNew) -================================================================ +component: DIG reasoner (org.dllearner.reasoning.DIGReasoner) +============================================================= option name: reasonerUrl description: URL of the DIG reasoner values: none default value: null +option name: writeDIGProtocol +description: specifies whether or not to write a protocoll of send and received DIG requests +values: none +default value: false + +option name: digProtocolFile +description: the file to store the DIG protocol +values: none +default value: log/digProtocol.txt + +component: unnamed component (org.dllearner.reasoning.FastRetrievalReasoner) +============================================================================ + +component: unnamed component (org.dllearner.reasoning.KAON2Reasoner) +==================================================================== + +option name: una +description: unique names assumption +values: none +default value: false + ********************* * Learning Problems * ********************* -component: two valued definition learning problem (org.dllearner.learningproblems.DefinitionLPTwoValued) -======================================================================================================== +component: two valued definition learning problem (org.dllearner.learningproblems.PosNegDefinitionLP) +===================================================================================================== option name: positiveExamples description: positive examples @@ -46,10 +128,46 @@ values: none default value: null +option name: percentPerLenghtUnit +description: describes the reduction in classification accuracy in percent one is willing to accept for reducing the length of the concept by one +values: none +default value: 0.05 + +component: inclusion learning problem (org.dllearner.learningproblems.PosNegInclusionLP) +======================================================================================== + +option name: positiveExamples +description: positive examples +values: none +default value: null + +option name: negativeExamples +description: negative examples +values: none +default value: null + +option name: useRetrievalForClassficiation +description: Specifies whether to use retrieval or instance checks for testing a concept. +values: none +default value: null + *********************** * Learning Algorithms * *********************** +component: unnamed component (org.dllearner.algorithms.BruteForceLearner) +========================================================================= + +option name: maxLength +description: maximum length of generated concepts +values: none +default value: null + +option name: returnType +description: Specifies the type which the solution has to belong to (if already) known. This means we inform the learning algorithm that the solution is a subclass of this type. +values: none +default value: null + component: unnamed component (org.dllearner.algorithms.RandomGuesser) ===================================================================== @@ -63,3 +181,24 @@ values: none default value: null +component: unnamed component (org.dllearner.algorithms.gp.GP) +============================================================= + +component: refinement operator based learning algorithm (org.dllearner.algorithms.refinement.ROLearner) +======================================================================================================= + +option name: writeSearchTree +description: specifies whether to write a search tree +values: none +default value: false + +option name: searchTreeFile +description: file to use for the search tree +values: none +default value: log/searchTree.txt + +option name: heuristic +description: specifiy the heuristic to use +values: none +default value: lexicographic + Modified: trunk/lib/components.ini =================================================================== --- trunk/lib/components.ini 2007-10-12 08:44:21 UTC (rev 218) +++ trunk/lib/components.ini 2007-10-12 09:20:39 UTC (rev 219) @@ -6,10 +6,13 @@ org.dllearner.kb.SparqlEndpoint # reasoners org.dllearner.reasoning.DIGReasoner +org.dllearner.reasoning.FastRetrievalReasoner +org.dllearner.reasoning.KAON2Reasoner # learning problems org.dllearner.learningproblems.PosNegDefinitionLP org.dllearner.learningproblems.PosNegInclusionLP # learning algorithms org.dllearner.algorithms.RandomGuesser +org.dllearner.algorithms.BruteForceLearner org.dllearner.algorithms.refinement.ROLearner org.dllearner.algorithms.gp.GP Added: trunk/src/dl-learner/org/dllearner/core/ConfigDocumentationGenerator.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/ConfigDocumentationGenerator.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/core/ConfigDocumentationGenerator.java 2007-10-12 09:20:39 UTC (rev 219) @@ -0,0 +1,43 @@ +/** + * Copyright (C) 2007, 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; + +import java.io.File; + +/** + * Collects information about all used configuration options and + * writes them into a file. This way the documentation is always + * in sync with the source code. + * + * @author Jens Lehmann + * + */ +public class ConfigDocumentationGenerator { + + /** + * @param args + */ + public static void main(String[] args) { + File file = new File("doc/configOptions.txt"); + ComponentManager cm = ComponentManager.getInstance(); + cm.writeConfigDocumentation(file); + } + +} Modified: trunk/src/dl-learner/org/dllearner/core/dl/Role.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Role.java 2007-10-12 08:44:21 UTC (rev 218) +++ trunk/src/dl-learner/org/dllearner/core/dl/Role.java 2007-10-12 09:20:39 UTC (rev 219) @@ -1,7 +1,5 @@ package org.dllearner.core.dl; -import java.util.Map; - public abstract class Role implements KBElement { protected String name; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-12 08:44:26
|
Revision: 218 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=218&view=rev Author: jenslehmann Date: 2007-10-12 01:44:21 -0700 (Fri, 12 Oct 2007) Log Message: ----------- - made another couple of options thread safe - implemented support for printing any KBElement with a base URI and prefixes Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/Config.java trunk/src/dl-learner/org/dllearner/ConfigurationManager.java trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java trunk/src/dl-learner/org/dllearner/core/dl/All.java trunk/src/dl-learner/org/dllearner/core/dl/AssertionalAxiom.java trunk/src/dl-learner/org/dllearner/core/dl/AtomicConcept.java trunk/src/dl-learner/org/dllearner/core/dl/AtomicRole.java trunk/src/dl-learner/org/dllearner/core/dl/Axiom.java trunk/src/dl-learner/org/dllearner/core/dl/Bottom.java trunk/src/dl-learner/org/dllearner/core/dl/Concept.java trunk/src/dl-learner/org/dllearner/core/dl/ConceptAssertion.java trunk/src/dl-learner/org/dllearner/core/dl/Conjunction.java trunk/src/dl-learner/org/dllearner/core/dl/Disjunction.java trunk/src/dl-learner/org/dllearner/core/dl/Equality.java trunk/src/dl-learner/org/dllearner/core/dl/Exists.java trunk/src/dl-learner/org/dllearner/core/dl/FunctionalRoleAxiom.java trunk/src/dl-learner/org/dllearner/core/dl/GreaterEqual.java trunk/src/dl-learner/org/dllearner/core/dl/Inclusion.java trunk/src/dl-learner/org/dllearner/core/dl/Individual.java trunk/src/dl-learner/org/dllearner/core/dl/InverseRole.java trunk/src/dl-learner/org/dllearner/core/dl/InverseRoleAxiom.java trunk/src/dl-learner/org/dllearner/core/dl/KB.java trunk/src/dl-learner/org/dllearner/core/dl/KBElement.java trunk/src/dl-learner/org/dllearner/core/dl/LessEqual.java trunk/src/dl-learner/org/dllearner/core/dl/MultiConjunction.java trunk/src/dl-learner/org/dllearner/core/dl/MultiDisjunction.java trunk/src/dl-learner/org/dllearner/core/dl/Negation.java trunk/src/dl-learner/org/dllearner/core/dl/Quantification.java trunk/src/dl-learner/org/dllearner/core/dl/RBoxAxiom.java trunk/src/dl-learner/org/dllearner/core/dl/Role.java trunk/src/dl-learner/org/dllearner/core/dl/RoleAssertion.java trunk/src/dl-learner/org/dllearner/core/dl/SubRoleAxiom.java trunk/src/dl-learner/org/dllearner/core/dl/SymmetricRoleAxiom.java trunk/src/dl-learner/org/dllearner/core/dl/TerminologicalAxiom.java trunk/src/dl-learner/org/dllearner/core/dl/Top.java trunk/src/dl-learner/org/dllearner/core/dl/TransitiveRoleAxiom.java trunk/src/dl-learner/org/dllearner/reasoning/KAON2Reasoner.java trunk/src/dl-learner/org/dllearner/utilities/Helper.java Modified: trunk/src/dl-learner/org/dllearner/Config.java =================================================================== --- trunk/src/dl-learner/org/dllearner/Config.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/Config.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,8 +1,6 @@ package org.dllearner; import java.lang.reflect.Field; -import java.util.LinkedList; -import java.util.List; import java.util.Set; import org.dllearner.algorithms.gp.GP.AlgorithmType; @@ -80,22 +78,22 @@ // public static URL digReasonerURL = null; // unique names assumption - public static boolean una = false; + // public static boolean una = false; // open world assumption; momentan wird closed world assumption nur // fuer Rollen unterstuetzt - public static boolean owa = true; + // public static boolean owa = true; // an-/abschalten von System.nanoTime()-Aufrufen außerhalb des // Reasoningservice - public static boolean useNonReasonerBenchmarks = false; + // public static boolean useNonReasonerBenchmarks = false; // erlaubt das abschalten von Benchmarks bei der Subsumptionhierarchie, // da diese ohnehin gecacht wird, also die System.nanoTime()-Aufrufe nur // Zeit kosten // public static boolean useHierarchyReasonerBenchmarks = false; - public static List<String> hidePrefixes = new LinkedList<String>(); + // public static List<String> hidePrefixes = new LinkedList<String>(); // Informationen (Rollen, Konzepte, Individuen, Anzahl Axiome) über // Wissensbasis anzeigen => alles konfigurierbar um Output in Grenzen Modified: trunk/src/dl-learner/org/dllearner/ConfigurationManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-12 08:44:21 UTC (rev 218) @@ -86,7 +86,7 @@ // } // der parserinterne Namespace wird immer ausgeblendet - Config.hidePrefixes.add(KBParser.internalNamespace); + ; // Config.hidePrefixes.add(KBParser.internalNamespace); } @@ -422,9 +422,9 @@ else if (option.equals("statMode")) ; // Config.statisticMode = Datastructures.strToBool(value); else if (option.equals("una")) - Config.una = Datastructures.strToBool(value); + ; // Config.una = Datastructures.strToBool(value); else if (option.equals("owa")) - Config.owa = Datastructures.strToBool(value); + ; // Config.owa = Datastructures.strToBool(value); else if (option.equals("gp.useFixedNumberOfGenerations")) Config.GP.useFixedNumberOfGenerations = Datastructures.strToBool(value); // else if (option.equals("scoreMethod")) { @@ -452,7 +452,7 @@ // Config.GP.mutationProbability = 0.0d; // } else if(option.equals("hidePrefix")) { - Config.hidePrefixes.add(value); +// Config.hidePrefixes.add(value); } else if (option.equals("showIndividuals")) { Config.showIndividuals = Datastructures.strToBool(value); } else if (option.equals("showConcepts")) { Modified: trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/algorithms/gp/ADC.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,7 @@ package org.dllearner.algorithms.gp; +import java.util.Map; + import org.dllearner.core.dl.Concept; public class ADC extends Concept { @@ -19,8 +21,7 @@ return 1; } - @Override - public String toString() { + public String toString(String baseURI, Map<String,String> prefixes) { return "ADC"; } Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-12 08:44:21 UTC (rev 218) @@ -126,12 +126,7 @@ this.learningProblem = learningProblem; this.rs = rs; - // this.learningProblem2 = learningProblem2; - operator = new RhoDown(learningProblem); - - // candidate sets entsprechend der gewählten Heuristik initialisieren - candidates = new TreeSet<Node>(nodeComparator); - // newCandidates = new TreeSet<Node>(nodeComparator); + } public static Collection<Class<? extends LearningProblem>> supportedLearningProblems() { @@ -183,6 +178,13 @@ else nodeComparator = new NodeComparator2(learningProblem.getNegativeExamples().size(), learningProblem.getPercentPerLengthUnit()); + // this.learningProblem2 = learningProblem2; + operator = new RhoDown(learningProblem); + + // candidate sets entsprechend der gewählten Heuristik initialisieren + candidates = new TreeSet<Node>(nodeComparator); + // newCandidates = new TreeSet<Node>(nodeComparator); + // TODO: this needs to be changed Helper.autoDetectConceptsAndRoles(rs); // prepare subsumption and role hierarchies, because they are needed Modified: trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-12 08:44:21 UTC (rev 218) @@ -41,4 +41,12 @@ public static StringConfigOption getReturnType() { return new StringConfigOption("returnType", "Specifies the type which the solution has to belong to (if already) known. This means we inform the learning algorithm that the solution is a subclass of this type."); } + + public static BooleanConfigOption getUNA() { + return new BooleanConfigOption("una", "unique names assumption", false); + } + + public static BooleanConfigOption getOWA() { + return new BooleanConfigOption("owa", "open world assumption (if set to false, we try to close the world", true); + } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/All.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/All.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/All.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,8 @@ package org.dllearner.core.dl; +import java.util.Map; + public class All extends Quantification { public All(Role role, Concept c) { @@ -83,10 +85,9 @@ return true; } */ - - @Override - public String toString() { - return "ALL " + role + "." + children.get(0).toString(); + + public String toString(String baseURI, Map<String,String> prefixes) { + return "ALL " + role + "." + children.get(0).toString(baseURI, prefixes); } /* Modified: trunk/src/dl-learner/org/dllearner/core/dl/AssertionalAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/AssertionalAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/AssertionalAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,5 @@ package org.dllearner.core.dl; -public interface AssertionalAxiom extends Axiom { +public abstract class AssertionalAxiom extends Axiom { } Modified: trunk/src/dl-learner/org/dllearner/core/dl/AtomicConcept.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/AtomicConcept.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/AtomicConcept.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,7 @@ package org.dllearner.core.dl; +import java.util.Map; + import org.dllearner.utilities.Helper; @@ -34,11 +36,11 @@ public String toString() { // es soll ein Prefix ausgeblendet werden um Konzepte // lesbarer zu machen (z.B. http://blabla.org/bla/bla#eigentlicher Name - String prefixToHide = Helper.findPrefixToHide(name); - - if(prefixToHide != null) - return name.substring(prefixToHide.length()); - else +// String prefixToHide = Helper.findPrefixToHide(name); +// +// if(prefixToHide != null) +// return name.substring(prefixToHide.length()); +// else return name; } @@ -51,4 +53,8 @@ return 0; } + public String toString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes); + } + } Modified: trunk/src/dl-learner/org/dllearner/core/dl/AtomicRole.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/AtomicRole.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/AtomicRole.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,7 @@ package org.dllearner.core.dl; +import java.util.Map; + import org.dllearner.utilities.Helper; public class AtomicRole extends Role { @@ -15,12 +17,16 @@ @Override public String toString() { - String name = getName(); - String prefixToHide = Helper.findPrefixToHide(name); - - if(prefixToHide != null) - return name.substring(prefixToHide.length()); - else +// String name = getName(); +// String prefixToHide = Helper.findPrefixToHide(name); +// +// if(prefixToHide != null) +// return name.substring(prefixToHide.length()); +// else return name; } + + public String toString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes); + } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Axiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Axiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Axiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,10 @@ package org.dllearner.core.dl; -public interface Axiom extends KBElement { +public abstract class Axiom implements KBElement { + @Override + public String toString() { + return toString(null, null); + } + } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Bottom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Bottom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Bottom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; +import java.util.Map; + public class Bottom extends Concept { /* @@ -11,8 +13,8 @@ negSet = abox.top; } */ - @Override - public String toString() { + + public String toString(String baseURI, Map<String,String> prefixes) { return "BOTTOM"; } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Concept.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Concept.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Concept.java 2007-10-12 08:44:21 UTC (rev 218) @@ -269,4 +269,10 @@ public Concept getChild(int i) { return children.get(i); } + + @Override + public String toString() { + return toString(null, null); + } + } Modified: trunk/src/dl-learner/org/dllearner/core/dl/ConceptAssertion.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/ConceptAssertion.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/ConceptAssertion.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,8 @@ package org.dllearner.core.dl; -public class ConceptAssertion implements AssertionalAxiom { +import java.util.Map; + +public class ConceptAssertion extends AssertionalAxiom { private Concept concept; private Individual individual; @@ -21,9 +23,8 @@ public int getLength() { return 1 + concept.getLength(); } - - @Override - public String toString() { - return concept.toString() + "(" + individual + ")"; + + public String toString(String baseURI, Map<String,String> prefixes) { + return concept.toString(baseURI, prefixes) + "(" + individual + ")"; } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Conjunction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Conjunction.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Conjunction.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; +import java.util.Map; + public class Conjunction extends Concept { /* @@ -20,9 +22,8 @@ addChild(c2); } - @Override - public String toString() { - return "(" + children.get(0).toString() + " AND " + children.get(1).toString() + ")"; + public String toString(String baseURI, Map<String,String> prefixes) { + return "(" + children.get(0).toString(baseURI, prefixes) + " AND " + children.get(1).toString(baseURI, prefixes) + ")"; } public int getLength() { Modified: trunk/src/dl-learner/org/dllearner/core/dl/Disjunction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Disjunction.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Disjunction.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,8 @@ package org.dllearner.core.dl; +import java.util.Map; + public class Disjunction extends Concept { /* @@ -19,9 +21,8 @@ addChild(c2); } - @Override - public String toString() { - return "(" + children.get(0).toString() + " OR " + children.get(1).toString() + ")"; + public String toString(String baseURI, Map<String,String> prefixes) { + return "(" + children.get(0).toString(baseURI, prefixes) + " OR " + children.get(1).toString(baseURI, prefixes) + ")"; } public int getLength() { Modified: trunk/src/dl-learner/org/dllearner/core/dl/Equality.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Equality.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Equality.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,8 @@ package org.dllearner.core.dl; -public class Equality implements TerminologicalAxiom { +import java.util.Map; + +public class Equality extends TerminologicalAxiom { private Concept concept1; private Concept concept2; @@ -21,9 +23,8 @@ public int getLength() { return 1 + concept1.getLength() + concept2.getLength(); } - - @Override - public String toString() { - return concept1.toString() + " = " + concept2.toString(); + + public String toString(String baseURI, Map<String,String> prefixes) { + return concept1.toString(baseURI, prefixes) + " = " + concept2.toString(baseURI, prefixes); } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Exists.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Exists.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Exists.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,8 @@ package org.dllearner.core.dl; +import java.util.Map; + public class Exists extends Quantification { public Exists(Role role, Concept c) { @@ -85,9 +87,8 @@ } */ - @Override - public String toString() { - return "EXISTS " + role + "." + children.get(0).toString(); + public String toString(String baseURI, Map<String,String> prefixes) { + return "EXISTS " + role.toString(baseURI, prefixes) + "." + children.get(0).toString(baseURI, prefixes); } /* Modified: trunk/src/dl-learner/org/dllearner/core/dl/FunctionalRoleAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/FunctionalRoleAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/FunctionalRoleAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; -public class FunctionalRoleAxiom implements RBoxAxiom { +import java.util.Map; +public class FunctionalRoleAxiom extends RBoxAxiom { + private AtomicRole role; public FunctionalRoleAxiom(AtomicRole role) { @@ -15,9 +17,8 @@ public int getLength() { return 1 + role.getLength(); } - - @Override - public String toString() { - return "Functional(" + role.toString() + ")"; + + public String toString(String baseURI, Map<String,String> prefixes) { + return "Functional(" + role.toString(baseURI, prefixes) + ")"; } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/GreaterEqual.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/GreaterEqual.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/GreaterEqual.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,7 @@ package org.dllearner.core.dl; +import java.util.Map; + public class GreaterEqual extends NumberRestriction { public GreaterEqual(int number, Role role, Concept c) { @@ -11,8 +13,7 @@ return 1; } - @Override - public String toString() { - return ">= " + number + " " + role + " " + getChild(0); + public String toString(String baseURI, Map<String,String> prefixes) { + return ">= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Inclusion.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Inclusion.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Inclusion.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,8 @@ package org.dllearner.core.dl; -public class Inclusion implements TerminologicalAxiom { +import java.util.Map; + +public class Inclusion extends TerminologicalAxiom { private Concept subConcept; private Concept superConcept; @@ -22,8 +24,7 @@ return 1 + subConcept.getLength() + superConcept.getLength(); } - @Override - public String toString() { - return subConcept.toString() + " SUBCONCEPTOF " + superConcept.toString(); + public String toString(String baseURI, Map<String,String> prefixes) { + return subConcept.toString(baseURI, prefixes) + " SUBCONCEPTOF " + superConcept.toString(baseURI, prefixes); } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Individual.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Individual.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Individual.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,7 @@ package org.dllearner.core.dl; +import java.util.Map; + import org.dllearner.utilities.Helper; /** @@ -40,11 +42,11 @@ @Override public String toString() { - String prefixToHide = Helper.findPrefixToHide(name); - - if(prefixToHide != null) - return name.substring(prefixToHide.length()); - else +// String prefixToHide = Helper.findPrefixToHide(name); +// +// if(prefixToHide != null) +// return name.substring(prefixToHide.length()); +// else return name; } @@ -56,6 +58,9 @@ public boolean equals(Object o) { return (compareTo((Individual)o)==0); } + + public String toString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes); + } - } Modified: trunk/src/dl-learner/org/dllearner/core/dl/InverseRole.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/InverseRole.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/InverseRole.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,14 +1,33 @@ +/** + * Copyright (C) 2007, 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.dl; +import java.util.Map; + +import org.dllearner.utilities.Helper; + /** - * TODO: nochmal ueberlegen, ob es sinnvoll ist, dass InverseRole von - * Role erbt; ev. besser trennen oder ein eine gemeinsame Oberklasse - * von beiden; genau wie Concept alle Konzeptkonstruktoren zusammenfasst, - * koennte Role alle Rollenkonstruktoren zusammenfassen + * An inverse role. * - * Role => Unterklassen: AtomicRole, InverseRole - * - * @author jl + * @author Jens Lehmann * */ public class InverseRole extends Role { @@ -18,12 +37,10 @@ } public int getLength() { - // TODO Auto-generated method stub return 2; } - - @Override - public String toString() { - return getName() + "-"; + + public String toString(String baseURI, Map<String,String> prefixes) { + return Helper.getAbbreviatedString(name, baseURI, prefixes) + "-"; } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/InverseRoleAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/InverseRoleAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/InverseRoleAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; -public class InverseRoleAxiom implements RBoxAxiom { +import java.util.Map; +public class InverseRoleAxiom extends RBoxAxiom { + private AtomicRole inverseRole; private AtomicRole role; @@ -22,8 +24,7 @@ return 1 + role.getLength() + inverseRole.getLength(); } - @Override - public String toString() { - return "Inverse(" + inverseRole + "," + role.toString() + ")"; + public String toString(String baseURI, Map<String,String> prefixes) { + return "Inverse(" + inverseRole + "," + role.toString(baseURI, prefixes) + ")"; } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/KB.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/KB.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/KB.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,7 @@ package org.dllearner.core.dl; import java.util.HashSet; +import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; @@ -155,22 +156,20 @@ length += a.getLength(); return length; } - - @Override - public String toString() { + + public String toString(String baseURI, Map<String,String> prefixes) { String str = "TBox["+tbox.size()+"]:\n"; for(Axiom a : tbox) - str += " " + a.toString()+"\n"; + str += " " + a.toString(baseURI, prefixes)+"\n"; str += "RBox["+rbox.size()+"]:\n"; for(Axiom a : rbox) - str += " " + a.toString()+"\n"; + str += " " + a.toString(baseURI, prefixes)+"\n"; str += "ABox["+abox.size()+"]:\n"; for(Axiom a : abox) - str += " " + a.toString()+"\n"; + 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/dl/KBElement.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/KBElement.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/KBElement.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,10 +1,16 @@ package org.dllearner.core.dl; +import java.util.Map; + /** - * Interface fuer alle Elemente der Wissensbasis. - * @author jl + * Interface for all elements of the knowledge base. + * + * @author Jens Lehmann * */ public interface KBElement { + public int getLength(); + + public String toString(String baseURI, Map<String,String> prefixes); } Modified: trunk/src/dl-learner/org/dllearner/core/dl/LessEqual.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/LessEqual.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/LessEqual.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,7 @@ package org.dllearner.core.dl; +import java.util.Map; + public class LessEqual extends NumberRestriction { public LessEqual(int number, Role role, Concept c) { @@ -11,8 +13,7 @@ return 1; } - @Override - public String toString() { - return "<= " + number + " " + role + " " + getChild(0); + public String toString(String baseURI, Map<String,String> prefixes) { + return "<= " + number + " " + role.toString(baseURI, prefixes) + " " + getChild(0).toString(baseURI, prefixes); } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/MultiConjunction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/MultiConjunction.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/MultiConjunction.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,7 @@ package org.dllearner.core.dl; import java.util.List; +import java.util.Map; public class MultiConjunction extends Concept { @@ -33,16 +34,15 @@ return length + children.size() - 1; } - @Override - public String toString() { + public String toString(String baseURI, Map<String,String> prefixes) { if(children.size()==0) return "EMPTY_AND"; String ret = "("; for(int i=0; i<children.size()-1; i++) { - ret += children.get(i).toString() + " AND "; + ret += children.get(i).toString(baseURI, prefixes) + " AND "; } - ret += children.get(children.size()-1).toString() + ")"; + ret += children.get(children.size()-1).toString(baseURI, prefixes) + ")"; return ret; } Modified: trunk/src/dl-learner/org/dllearner/core/dl/MultiDisjunction.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/MultiDisjunction.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/MultiDisjunction.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,7 @@ package org.dllearner.core.dl; import java.util.List; +import java.util.Map; public class MultiDisjunction extends Concept { @@ -34,17 +35,16 @@ } return length + children.size() - 1; } - - @Override - public String toString() { + + public String toString(String baseURI, Map<String,String> prefixes) { if(children.size()==0) return "EMPTY_OR"; String ret = "("; for(int i=0; i<children.size()-1; i++) { - ret += children.get(i).toString() + " OR "; + ret += children.get(i).toString(baseURI, prefixes) + " OR "; } - ret += children.get(children.size()-1).toString() + ")"; + ret += children.get(children.size()-1).toString(baseURI, prefixes) + ")"; return ret; } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Negation.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Negation.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Negation.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,8 @@ package org.dllearner.core.dl; +import java.util.Map; + public class Negation extends Concept { /* @@ -16,9 +18,8 @@ addChild(c); } - @Override - public String toString() { - return "(NOT " +children.get(0).toString() + ")"; + public String toString(String baseURI, Map<String,String> prefixes) { + return "(NOT " +children.get(0).toString(baseURI, prefixes) + ")"; } public int getLength() { Modified: trunk/src/dl-learner/org/dllearner/core/dl/Quantification.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Quantification.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Quantification.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,6 +1,6 @@ package org.dllearner.core.dl; -public class Quantification extends Concept { +public abstract class Quantification extends Concept { Role role; Modified: trunk/src/dl-learner/org/dllearner/core/dl/RBoxAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/RBoxAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/RBoxAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,5 @@ package org.dllearner.core.dl; -public interface RBoxAxiom extends Axiom { +public abstract class RBoxAxiom extends Axiom { } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Role.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Role.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Role.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,8 +1,10 @@ package org.dllearner.core.dl; +import java.util.Map; + public abstract class Role implements KBElement { - private String name; + protected String name; public Role(String name) { this.name = name; @@ -11,4 +13,5 @@ public String getName() { return name; } + } Modified: trunk/src/dl-learner/org/dllearner/core/dl/RoleAssertion.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/RoleAssertion.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/RoleAssertion.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; -public class RoleAssertion implements AssertionalAxiom { +import java.util.Map; +public class RoleAssertion extends AssertionalAxiom { + private AtomicRole role; private Individual individual1; private Individual individual2; @@ -28,8 +30,7 @@ return 2 + role.getLength(); } - @Override - public String toString() { - return role.toString() + "(" + individual1 + "," + individual2 +")"; + public String toString(String baseURI, Map<String,String> prefixes) { + return role.toString(baseURI, prefixes) + "(" + individual1.toString(baseURI, prefixes) + "," + individual2.toString(baseURI, prefixes) +")"; } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/SubRoleAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/SubRoleAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/SubRoleAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; -public class SubRoleAxiom implements RBoxAxiom { +import java.util.Map; +public class SubRoleAxiom extends RBoxAxiom { + private AtomicRole role; private AtomicRole subRole; @@ -21,9 +23,8 @@ public int getLength() { return 1 + role.getLength() + subRole.getLength(); } - - @Override - public String toString() { - return "Subrole(" + subRole + "," + role.toString() + ")"; + + public String toString(String baseURI, Map<String,String> prefixes) { + return "Subrole(" + subRole.toString(baseURI, prefixes) + "," + role.toString(baseURI, prefixes) + ")"; } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/SymmetricRoleAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/SymmetricRoleAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/SymmetricRoleAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; -public class SymmetricRoleAxiom implements RBoxAxiom { +import java.util.Map; +public class SymmetricRoleAxiom extends RBoxAxiom { + private AtomicRole role; public SymmetricRoleAxiom(AtomicRole role) { @@ -16,8 +18,7 @@ return 1 + role.getLength(); } - @Override - public String toString() { - return "Symmetric(" + role.toString() + ")"; + public String toString(String baseURI, Map<String,String> prefixes) { + return "Symmetric(" + role.toString(baseURI, prefixes) + ")"; } } Modified: trunk/src/dl-learner/org/dllearner/core/dl/TerminologicalAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/TerminologicalAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/TerminologicalAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,5 +1,5 @@ package org.dllearner.core.dl; -public interface TerminologicalAxiom extends Axiom { +public abstract class TerminologicalAxiom extends Axiom { } Modified: trunk/src/dl-learner/org/dllearner/core/dl/Top.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/Top.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/Top.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,7 @@ package org.dllearner.core.dl; +import java.util.Map; - public class Top extends Concept { /* @@ -12,8 +12,7 @@ } */ - @Override - public String toString() { + public String toString(String baseURI, Map<String,String> prefixes) { return "TOP"; } Modified: trunk/src/dl-learner/org/dllearner/core/dl/TransitiveRoleAxiom.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/dl/TransitiveRoleAxiom.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/core/dl/TransitiveRoleAxiom.java 2007-10-12 08:44:21 UTC (rev 218) @@ -1,7 +1,9 @@ package org.dllearner.core.dl; -public class TransitiveRoleAxiom implements RBoxAxiom { +import java.util.Map; +public class TransitiveRoleAxiom extends RBoxAxiom { + private Role role; public TransitiveRoleAxiom(Role role) { @@ -16,8 +18,7 @@ return role; } - @Override - public String toString() { - return "Transitive(" + role.toString() + ")"; - } + public String toString(String baseURI, Map<String,String> prefixes) { + return "Transitive(" + role.toString(baseURI, prefixes) + ")"; + } } Modified: trunk/src/dl-learner/org/dllearner/reasoning/KAON2Reasoner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/reasoning/KAON2Reasoner.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/reasoning/KAON2Reasoner.java 2007-10-12 08:44:21 UTC (rev 218) @@ -3,6 +3,7 @@ import java.io.File; import java.io.IOException; import java.net.URL; +import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -14,8 +15,9 @@ import java.util.TreeMap; import java.util.TreeSet; -import org.dllearner.Config; +import org.dllearner.core.CommonConfigOptions; import org.dllearner.core.ConfigEntry; +import org.dllearner.core.ConfigOption; import org.dllearner.core.InvalidConfigOptionValueException; import org.dllearner.core.ReasonerComponent; import org.dllearner.core.dl.All; @@ -75,6 +77,9 @@ */ public class KAON2Reasoner extends ReasonerComponent { + // configuration options + private boolean una = false; + ConceptComparator conceptComparator = new ConceptComparator(); Set<AtomicConcept> atomicConcepts; @@ -198,7 +203,7 @@ // je nachdem, ob unique names assumption aktiviert ist, muss // man jetzt noch hinzuf�gen, dass die Individuen verschieden sind - if (Config.una) { + if (una) { Set<org.semanticweb.kaon2.api.owl.elements.Individual> individualsSet = new HashSet<org.semanticweb.kaon2.api.owl.elements.Individual>(); for (Individual individual : individuals) individualsSet.add(KAON2Manager.factory().individual(individual.getName())); @@ -699,15 +704,15 @@ Formula f = null; // falls closed world assumption, dann reicht default negation - if (Config.owa) +// if (Config.owa) // wegen BUG IN KAON2 momentan auskommentiert // f = KAON2Manager.factory().classicalNegation(l); - ; - else +// ; +// else f = KAON2Manager.factory().defaultNegation(l); // if-Teil entf�llt, sobald Bug in KAON2 gefixt wurde - if (!Config.owa) { +// if (!Config.owa) { // ClassicalNegation cn = // KAON2Manager.factory().classicalNegation(l); try { @@ -736,7 +741,7 @@ // TODO Auto-generated catch block e.printStackTrace(); } - } +// } return returnMap; } @@ -766,13 +771,20 @@ return individuals; } + public static Collection<ConfigOption<?>> createConfigOptions() { + Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); + options.add(CommonConfigOptions.getUNA()); + return options; + } + /* (non-Javadoc) * @see org.dllearner.core.Component#applyConfigEntry(org.dllearner.core.ConfigEntry) */ @Override public <T> void applyConfigEntry(ConfigEntry<T> entry) throws InvalidConfigOptionValueException { - // TODO Auto-generated method stub - + String name = entry.getOptionName(); + if(name.equals("una")) + una = (Boolean) entry.getValue(); } /* (non-Javadoc) Modified: trunk/src/dl-learner/org/dllearner/utilities/Helper.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/Helper.java 2007-10-12 08:17:02 UTC (rev 217) +++ trunk/src/dl-learner/org/dllearner/utilities/Helper.java 2007-10-12 08:44:21 UTC (rev 218) @@ -9,6 +9,7 @@ import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; +import java.util.Map.Entry; import org.dllearner.Config; import org.dllearner.core.ReasoningMethodUnsupportedException; @@ -69,12 +70,40 @@ // sucht, ob der übergebene String mit einem Prefix beginnt der // versteckt werden soll und gibt diesen zurück, ansonsten wird // null zurück gegeben - public static String findPrefixToHide(String name) { - for(String prefix : Config.hidePrefixes) { - if(name.startsWith(prefix)) - return prefix; - } - return null; +// public static String findPrefixToHide(String name) { +// for(String prefix : Config.hidePrefixes) { +// if(name.startsWith(prefix)) +// return prefix; +// } +// return null; +// } + + /** + * + * Transforms an URI to an abbreviated version, e.g. if the base URI is + * "http://example.com/" and the uri is "http://example.com/test", then + * "test" is returned. If the the uri is "http://anotherexample.com/test2" + * and a prefix "ns1" is given for "http://anotherexample.com", then + * "ns1:test2" is returned. If there is no match, uri is returned. + * + * @param uri The full uri, which should be transformed to an abbreviated version. + * @param baseURI The base uri (ignored if null). + * @param prefixes A prefix map (ignored if null), where each entry contains a short string e.g. ns1 + * as key and the corresponding uri as value. + * @return Abbreviated version of the parameter uri. + */ + public static String getAbbreviatedString(String uri, String baseURI, Map<String,String> prefixes) { + if(baseURI != null && uri.startsWith(baseURI)) { + return uri.substring(baseURI.length()); + } else { + if(prefixes != null) { + for(Entry<String,String> prefix : prefixes.entrySet()) { + if(uri.startsWith(prefix.getValue())) + return prefix.getKey() + ":" + uri.substring(prefix.getValue().length()); + } + } + return uri; + } } public static String prettyPrintNanoSeconds(long nanoSeconds) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ku...@us...> - 2007-10-12 08:17:05
|
Revision: 217 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=217&view=rev Author: kurzum Date: 2007-10-12 01:17:02 -0700 (Fri, 12 Oct 2007) Log Message: ----------- simple daimler example Added Paths: ----------- trunk/examples/daimler/ trunk/examples/daimler/daimler.conf Added: trunk/examples/daimler/daimler.conf =================================================================== --- trunk/examples/daimler/daimler.conf (rev 0) +++ trunk/examples/daimler/daimler.conf 2007-10-12 08:17:02 UTC (rev 217) @@ -0,0 +1,102 @@ + + +/** settings **/ + // reasoner settings + reasoner = dig; + digReasonerURL = "http://localhost:8081"; + useRetrievalForClassification = true; + refinement.useDIGMultiInstanceChecks = twoChecks; + + // algorithm settings + algorithm = refinement; + refinement.horizontalExpansionFactor = 0.6; + refinement.quiet = false; + refinement.useTooWeakList = true; + + // search tree protocol + refinement.writeSearchTree = false; + refinement.searchTreeFile = "searchTree.txt"; + + // control output + showIndividuals = false; + showConcepts = true; + showRoles = true; + showInternalKB = false; +showSubsumptionHierarchy = true; +//export("moral_complete_fixed_test.owl"); + +refinement.ignoredConcepts = {"getriebe"}; + +/**backgound knowledge**/ + +//BOTTOM = (coupe AND (limousine AND (t-Modell AND (cabrio AND gelaendewagen )))). + +sportcoupe SUB coupe. + +/*Stoff SUB Polsterung. +Leder SUB Polsterung. +Ledernachbildung_ARTICO SUB Polsterung. +Schwarzes_Polster SUB Polsterfarben. +Alpakagraues_Polster SUB Polsterfarben. + +/*Iridiumsilber SUB Metalliclackierungen. +Cubanitsilber SUB Metalliclackierungen. +Jaspisblau SUB Metalliclackierungen. +Cameolrot SUB Metalliclackierungen.*/ + + +/* +// disjunct concepts +(male AND female) SUB BOTTOM. + +Symmetric(married). +Functional(married). + +// persons +male(m1). +male(m2). +*/ + + +/*car_c220cdi_001 +engine_c220cdi_001 +getriebe_autotronic_001 +getriebe_manuell_5G_001 +getriebe_manuell_6G_001 +getriebe_7G-TRONIC_001*/ + +negative(n). +car(car_c220cdi_001). +c_klasse(car_c220cdi_001). +sportcoupe(car_c220cdi_001). +engine(engine_c220cdi_001). + +gang_6(getriebe_autotronic_001). +autotronic(getriebe_autotronic_001). +automatikgetriebe(getriebe_autotronic_001). +getriebe(getriebe_autotronic_001). + +gang_7(getriebe_7g_tronic_001). +automatikgetriebe(getriebe_7g_tronic_001). +getriebe(getriebe_7g_tronic_001). + +gang_5(getriebe_manuell_5g_001). +mechanikgetriebe(getriebe_manuell_5g_001). +getriebe(getriebe_manuell_5g_001). + +gang_6(getriebe_manuell_6g_001). +mechanikgetriebe(getriebe_manuell_6g_001). +getriebe(getriebe_manuell_6g_001). + + +//positive + ++getriebe(getriebe_autotronic_001). ++getriebe(getriebe_manuell_5g_001). ++getriebe(getriebe_manuell_6g_001). ++getriebe(getriebe_7g_tronic_001). + +-getriebe(n). + + + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-11 18:35:13
|
Revision: 216 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=216&view=rev Author: jenslehmann Date: 2007-10-11 11:35:03 -0700 (Thu, 11 Oct 2007) Log Message: ----------- - enabled another couple of options (tedious work) - code beautifications Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/Config.java trunk/src/dl-learner/org/dllearner/ConfigurationManager.java trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java trunk/src/dl-learner/org/dllearner/algorithms/gp/GPUtilities.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator2.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java trunk/src/dl-learner/org/dllearner/core/LearningProblem.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLPStrict.java trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java trunk/src/dl-learner/org/dllearner/learningproblems/ScoreThreeValued.java trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java trunk/src/dl-learner/org/dllearner/server/ClientState.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java trunk/src/dl-learner/org/dllearner/utilities/PaperStatistics.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/algorithms/refinement/Heuristic.java Modified: trunk/src/dl-learner/org/dllearner/Config.java =================================================================== --- trunk/src/dl-learner/org/dllearner/Config.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/Config.java 2007-10-11 18:35:03 UTC (rev 216) @@ -1,7 +1,6 @@ package org.dllearner; import java.lang.reflect.Field; -import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -11,7 +10,6 @@ import org.dllearner.core.dl.AtomicConcept; import org.dllearner.core.dl.AtomicRole; import org.dllearner.learningproblems.PosNegLP.UseMultiInstanceChecks; -import org.dllearner.reasoning.ReasonerType; public class Config { // standardmäßig wird bis Tiefe 7 gesucht @@ -52,34 +50,34 @@ // 0.05) // angebracht // public static double percentPerLengthUnit = 0.0025; - public static double percentPerLengthUnit = 0.05; + // public static double percentPerLengthUnit = 0.05; - public enum Algorithm { - GP, BRUTE_FORCE, RANDOM_GUESSER, REFINEMENT, HYBRID_GP - }; +// public enum Algorithm { +// GP, BRUTE_FORCE, RANDOM_GUESSER, REFINEMENT, HYBRID_GP +// }; +// +// public static Algorithm algorithm = Algorithm.REFINEMENT; - public static Algorithm algorithm = Algorithm.REFINEMENT; - // Rückgabetyp des gelernten Konzepts - public static String returnType = ""; + // public static String returnType = ""; - public static boolean statisticMode = false; + // public static boolean statisticMode = false; // if set to true a retrieval algorithm is used for classification // instead of single instance checks (default is now false, because // we can send all instance checks in a single request), for KAON2 // as reasoner it should in many cases be set to true - public static boolean useRetrievalForClassification = false; + // public static boolean useRetrievalForClassification = false; // welche Art von Reasoning wird benutzt (eigener Algorithmus, // KAON2-API, DIG-Interface) - public static ReasonerType reasonerType = ReasonerType.DIG; + // public static ReasonerType reasonerType = ReasonerType.DIG; // bei fast retrieval muss trotzdem irgendein Reasoner gesetzt // werden um die flat ABox zu erzeugen - public static ReasonerType startUpReasoningType = ReasonerType.KAON2; + // public static ReasonerType startUpReasoningType = ReasonerType.KAON2; - public static URL digReasonerURL = null; + // public static URL digReasonerURL = null; // unique names assumption public static boolean una = false; Modified: trunk/src/dl-learner/org/dllearner/ConfigurationManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-11 18:35:03 UTC (rev 216) @@ -1,7 +1,5 @@ package org.dllearner; -import java.net.MalformedURLException; -import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; @@ -11,14 +9,12 @@ import java.util.Set; import java.util.TreeSet; -import org.dllearner.Config.Algorithm; import org.dllearner.algorithms.gp.GP.AlgorithmType; import org.dllearner.algorithms.gp.GP.SelectionType; import org.dllearner.cli.ConfFileOption; import org.dllearner.core.dl.AtomicConcept; import org.dllearner.core.dl.AtomicRole; import org.dllearner.parser.KBParser; -import org.dllearner.reasoning.ReasonerType; import org.dllearner.utilities.ConceptComparator; import org.dllearner.utilities.Datastructures; import org.dllearner.utilities.RoleComparator; @@ -80,14 +76,14 @@ // DIG-Reasoner-URL setzen, falls nicht schon geschehen (kann wegen Exception // nicht in Config gesetzt werden) - if(Config.digReasonerURL == null) { - try { - Config.digReasonerURL = new URL("http://localhost:8081"); - } catch (MalformedURLException e) { - // Exception tritt nie auf, da URL korrekt - e.printStackTrace(); - } - } +// if(Config.digReasonerURL == null) { +// try { +// Config.digReasonerURL = new URL("http://localhost:8081"); +// } catch (MalformedURLException e) { +// // Exception tritt nie auf, da URL korrekt +// e.printStackTrace(); +// } +// } // der parserinterne Namespace wird immer ausgeblendet Config.hidePrefixes.add(KBParser.internalNamespace); @@ -424,38 +420,38 @@ else if (option.equals("showCorrectClassifications")) ; // Config.showCorrectClassifications = Datastructures.strToBool(value); else if (option.equals("statMode")) - Config.statisticMode = Datastructures.strToBool(value); + ; // Config.statisticMode = Datastructures.strToBool(value); else if (option.equals("una")) Config.una = Datastructures.strToBool(value); else if (option.equals("owa")) Config.owa = Datastructures.strToBool(value); else if (option.equals("gp.useFixedNumberOfGenerations")) Config.GP.useFixedNumberOfGenerations = Datastructures.strToBool(value); - else if (option.equals("scoreMethod")) { +// else if (option.equals("scoreMethod")) { // if (value.equals("full")) // Config.scoreMethod = ScoreMethod.FULL; // else // Config.scoreMethod = ScoreMethod.POSITIVE; - } else if (option.equals("returnType")) - Config.returnType = value; - else if (option.equals("algorithm")) { - if (value.equals("gp")) - Config.algorithm = Algorithm.GP; - else if (value.equals("random")) - Config.algorithm = Algorithm.RANDOM_GUESSER; - else if(value.equals("bruteForce")) - Config.algorithm = Algorithm.BRUTE_FORCE; - else if(value.equals("refinement")) - Config.algorithm = Algorithm.REFINEMENT; - // hybrid GP = Menge von Konfigurationsoptionen - else { - Config.algorithm = Algorithm.HYBRID_GP; - Config.GP.refinementProbability = 1.0d; - Config.GP.crossoverProbability = 0.0d; - Config.GP.hillClimbingProbability = 0.0d; - Config.GP.mutationProbability = 0.0d; - } - } else if(option.equals("hidePrefix")) { +// } else if (option.equals("returnType")) +// Config.returnType = value; +// else if (option.equals("algorithm")) { +// if (value.equals("gp")) +// Config.algorithm = Algorithm.GP; +// else if (value.equals("random")) +// Config.algorithm = Algorithm.RANDOM_GUESSER; +// else if(value.equals("bruteForce")) +// Config.algorithm = Algorithm.BRUTE_FORCE; +// else if(value.equals("refinement")) +// Config.algorithm = Algorithm.REFINEMENT; +// // hybrid GP = Menge von Konfigurationsoptionen +// else { +// Config.algorithm = Algorithm.HYBRID_GP; +// Config.GP.refinementProbability = 1.0d; +// Config.GP.crossoverProbability = 0.0d; +// Config.GP.hillClimbingProbability = 0.0d; +// Config.GP.mutationProbability = 0.0d; +// } + else if(option.equals("hidePrefix")) { Config.hidePrefixes.add(value); } else if (option.equals("showIndividuals")) { Config.showIndividuals = Datastructures.strToBool(value); @@ -514,23 +510,24 @@ Config.Refinement.useExistsConstructor = Datastructures.strToBool(value); else if (option.equals("refinement.useNegation")) Config.Refinement.useNegation = Datastructures.strToBool(value); - else if (option.equals("reasoner")) { - if(value.equals("dig")) - Config.reasonerType = ReasonerType.DIG; - else if(value.equals("kaon2")) - Config.reasonerType = ReasonerType.KAON2; - else if(value.equals("fastRetrieval")) - Config.reasonerType = ReasonerType.FAST_RETRIEVAL; - } else if (option.equals("digReasonerURL")) { - try { - Config.digReasonerURL = new URL(value); - } catch (MalformedURLException e) { - e.printStackTrace(); - System.err.println("Malformed URL for DIG reasoner was given."); - System.exit(0); - } - } else if (option.equals("useRetrievalForClassification")) - Config.useRetrievalForClassification = Datastructures.strToBool(value); +// else if (option.equals("reasoner")) { +// if(value.equals("dig")) +// Config.reasonerType = ReasonerType.DIG; +// else if(value.equals("kaon2")) +// Config.reasonerType = ReasonerType.KAON2; +// else if(value.equals("fastRetrieval")) +// Config.reasonerType = ReasonerType.FAST_RETRIEVAL; + else if (option.equals("digReasonerURL")) { +// try { +// Config.digReasonerURL = new URL(value); +// } catch (MalformedURLException e) { +// e.printStackTrace(); +// System.err.println("Malformed URL for DIG reasoner was given."); +// System.exit(0); +// } + } +// } else if (option.equals("useRetrievalForClassification")) +// Config.useRetrievalForClassification = Datastructures.strToBool(value); // else if (option.equals("refinement.useDIGMultiInstanceChecks")) { // if(value.equals("never")) // Config.Refinement.useDIGMultiInstanceChecks = Config.Refinement.UseDIGMultiInstanceChecks.NEVER; Modified: trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/algorithms/BruteForceLearner.java 2007-10-11 18:35:03 UTC (rev 216) @@ -26,7 +26,7 @@ import java.util.List; import java.util.Map; -import org.dllearner.Config; +import org.dllearner.core.CommonConfigOptions; import org.dllearner.core.ConfigEntry; import org.dllearner.core.ConfigOption; import org.dllearner.core.IntegerConfigOption; @@ -63,6 +63,7 @@ private Score bestScore; private int maxLength = 7; + private String returnType; // list of all generated concepts sorted by length private Map<Integer,List<Concept>> generatedDefinitions = new HashMap<Integer,List<Concept>>(); @@ -80,6 +81,7 @@ public static Collection<ConfigOption<?>> createConfigOptions() { Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); options.add(new IntegerConfigOption("maxLength", "maximum length of generated concepts")); + options.add(CommonConfigOptions.getReturnType()); return options; } @@ -91,6 +93,8 @@ String name = entry.getOptionName(); if(name.equals("maxLength")) maxLength = (Integer) entry.getValue(); + else if(name.equals("returnType")) + returnType = (String) returnType; } /* (non-Javadoc) @@ -148,8 +152,8 @@ // if a return type is already given an appropriate tree is // generated here Concept newRoot; - if(!Config.returnType.equals("")) { - newRoot = new Conjunction(new AtomicConcept(Config.returnType),program); + if(returnType != null) { + newRoot = new Conjunction(new AtomicConcept(returnType),program); } else newRoot = program; Modified: trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/algorithms/gp/GP.java 2007-10-11 18:35:03 UTC (rev 216) @@ -414,8 +414,9 @@ // nachschauen, ob ev. noch bessere Konzepte im Psi-Cache sind boolean betterValueFoundInPsiCache = false; - double bestValue = bestScore.getScore(); - if(Config.algorithm == Config.Algorithm.HYBRID_GP) { + double bestValue = bestScore.getScore(); + + if(Config.GP.refinementProbability > 0) { // das Problem ist hier, dass die gecachte Score nicht unbedingt // der echten Score entsprechen muss, d.h. hier muss die // Konzeptlänge mit einberechnet werden => deswegen werden @@ -445,7 +446,7 @@ System.out.println("runtime in ms: " + Helper.prettyPrintNanoSeconds(endTime - startTime)); System.out.println("fitness evaluations: " + GPUtilities.fitnessEvaluations); - if(Config.algorithm == Config.Algorithm.HYBRID_GP) { + if(refinementProbability > 0) { System.out.println("operator applications: " + psi.getNrOfRequests() + " psi, " + GPUtilities.crossover + " crossover, " + GPUtilities.mutation + " mutation, " + GPUtilities.hillClimbing + " hillClimbing"); } @@ -735,7 +736,7 @@ // System.out.println(); System.out.println("best definition found: " + n); - if(Config.algorithm == Config.Algorithm.HYBRID_GP) { + if(refinementProbability > 0) { double cacheHitRate=0; double pdCacheHitRate=0, puCacheHitRate=0; if(psi.getNrOfRequests()>0) { Modified: trunk/src/dl-learner/org/dllearner/algorithms/gp/GPUtilities.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/gp/GPUtilities.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/algorithms/gp/GPUtilities.java 2007-10-11 18:35:03 UTC (rev 216) @@ -68,22 +68,25 @@ private static Score calculateFitness(LearningProblem learningProblem, Concept hypothesis, Concept adc) { Concept extendedHypothesis; - if (!Config.returnType.equals("")) { - System.out.println("return type"); - - // newRoot.addChild(new AtomicConcept(Config.returnType)); - // newRoot.addChild(hypothesis); - Concept newRoot; - if(Config.GP.useMultiStructures) - newRoot = new MultiConjunction(new AtomicConcept(Config.returnType),hypothesis); - else - newRoot = new Conjunction(new AtomicConcept(Config.returnType),hypothesis); - // parent wieder auf null setzen, damit es nicht inkonsistent wird - // TODO: ist nicht wirklich elegant und auch inkompatibel mit - // dem Hill-Climbing-Operator - hypothesis.setParent(null); - extendedHypothesis = newRoot; - } else + // return type temporarily disabled + // => it is probably more appropriate to have the + // number of superclasses of a target concept + // as parameter of the learning problem +// +// if (!Config.returnType.equals("")) { +// System.out.println("return type"); +// +// Concept newRoot; +// if(Config.GP.useMultiStructures) +// newRoot = new MultiConjunction(new AtomicConcept(Config.returnType),hypothesis); +// else +// newRoot = new Conjunction(new AtomicConcept(Config.returnType),hypothesis); +// // parent wieder auf null setzen, damit es nicht inkonsistent wird +// // TODO: ist nicht wirklich elegant und auch inkompatibel mit +// // dem Hill-Climbing-Operator +// hypothesis.setParent(null); +// extendedHypothesis = newRoot; +// } else extendedHypothesis = hypothesis; Score score; @@ -459,7 +462,7 @@ // neutClassified.retainAll(posClassified); neutClassified.retainAll(negClassified); PosNegDefinitionLPStrict lp = (PosNegDefinitionLPStrict)learningProblem; - return new ScoreThreeValued(conceptLength, lp.getAccuracyPenalty(), lp.getErrorPenalty(), lp.isPenaliseNeutralExamples(), posClassified, neutClassified, negClassified, lp.getPositiveExamples(),lp.getNeutralExamples(),lp.getNegativeExamples()); + return new ScoreThreeValued(conceptLength, lp.getAccuracyPenalty(), lp.getErrorPenalty(), lp.isPenaliseNeutralExamples(), lp.getPercentPerLengthUnit(), posClassified, neutClassified, negClassified, lp.getPositiveExamples(),lp.getNeutralExamples(),lp.getNegativeExamples()); } // aktualisiert die besten Knoten Added: trunk/src/dl-learner/org/dllearner/algorithms/refinement/Heuristic.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/Heuristic.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/Heuristic.java 2007-10-11 18:35:03 UTC (rev 216) @@ -0,0 +1,35 @@ +/** + * Copyright (C) 2007, 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.refinement; + +import java.util.Comparator; + +/** + * Marker interface for heuristics in the refinement operator + * based learning approach. A heuristic implements a method + * to decide which one of two given nodes seems to be more + * promising with respect to the learning problem we consider. + * + * @author Jens Lehmann + * + */ +public interface Heuristic extends Comparator<Node>{ + +} Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator.java 2007-10-11 18:35:03 UTC (rev 216) @@ -1,10 +1,8 @@ package org.dllearner.algorithms.refinement; -import java.util.Comparator; - import org.dllearner.utilities.ConceptComparator; -public class NodeComparator implements Comparator<Node> { +public class NodeComparator implements Heuristic { // Vergleich von Konzepten, falls alle anderen Kriterien fehlschlagen ConceptComparator conceptComparator = new ConceptComparator(); Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator2.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator2.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/NodeComparator2.java 2007-10-11 18:35:03 UTC (rev 216) @@ -1,30 +1,62 @@ +/** + * Copyright (C) 2007, 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.refinement; -import java.util.Comparator; - -import org.dllearner.Config; import org.dllearner.utilities.ConceptComparator; /** + * This heuristic compares two nodes by computing a score + * using the number of covered negatives and the horizontal + * expansion factor of a node as input. Using this score + * it decides which one of the nodes seems to be more promising. + * The heuristic is flexible, because it offers a tradeoff + * between accurary and horizontal expansion (concept length). + * In contrast to the lexicographic heuristic this means that + * it sometimes prefers worse classifiers with low horizontal + * expansion over a better classifier with high horizontal + * expansion. * - * Die zweite Heuristik ist flexibel, das sie einen Tradeoff zwischen - * prozentualer Richtigkeit und horizontal expansion bietet (die - * Standardheuristik ist lexikographisch, d.h. ein schlecht klassifizierendes - * Konzept wird nie vorgezogen). + * It can be configured by using the "percentPerLenghtUnit" + * constructor argument. A higher + * value means that the algorithm is more likely to search in + * unexplored areas (= low horizontal expansion) of the search + * space vs. looking in promising but already explored (= high + * horizontal expansion) areas of the search space. * - * @author jl + * @author Jens Lehmann * */ -public class NodeComparator2 implements Comparator<Node> { +public class NodeComparator2 implements Heuristic { // Vergleich von Konzepten, falls alle anderen Kriterien fehlschlagen - ConceptComparator conceptComparator = new ConceptComparator(); - int nrOfNegativeExamples; + private ConceptComparator conceptComparator = new ConceptComparator(); + private int nrOfNegativeExamples; + private double percentPerLengthUnit; + // 5% sind eine Verlängerung um 1 wert // double percentPerLengthUnit = 0.05; - public NodeComparator2(int nrOfNegativeExamples) { + public NodeComparator2(int nrOfNegativeExamples, double percentPerLengthUnit) { this.nrOfNegativeExamples = nrOfNegativeExamples; + this.percentPerLengthUnit = percentPerLengthUnit; } // implementiert einfach die Definition in der Diplomarbeit @@ -35,10 +67,10 @@ // alle scores sind negativ, größere scores sind besser double score1 = -n1.getCoveredNegativeExamples()/(double)nrOfNegativeExamples; - score1 -= Config.percentPerLengthUnit * n1.getConcept().getLength(); + score1 -= percentPerLengthUnit * n1.getConcept().getLength(); double score2 = -n2.getCoveredNegativeExamples()/(double)nrOfNegativeExamples; - score2 -= Config.percentPerLengthUnit * n2.getConcept().getLength(); + score2 -= percentPerLengthUnit * n2.getConcept().getLength(); double diff = score1 - score2; Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-11 18:35:03 UTC (rev 216) @@ -39,7 +39,7 @@ private boolean writeSearchTree; private File searchTreeFile; private static String defaultSearchTreeFile = "log/searchTree.txt"; - private Heuristic heuristic = Heuristic.LEXICOGRAPHIC; + private Heuristic heuristic = Heuristic.LEXICOGRAPHIC; private boolean stop = false; @@ -166,7 +166,7 @@ heuristic = Heuristic.LEXICOGRAPHIC; else heuristic = Heuristic.FLEXIBLE; - } + } } /* (non-Javadoc) @@ -181,7 +181,7 @@ if(heuristic == Heuristic.LEXICOGRAPHIC) nodeComparator = new NodeComparator(); else - nodeComparator = new NodeComparator2(learningProblem.getNegativeExamples().size()); + nodeComparator = new NodeComparator2(learningProblem.getNegativeExamples().size(), learningProblem.getPercentPerLengthUnit()); // TODO: this needs to be changed Helper.autoDetectConceptsAndRoles(rs); Modified: trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-11 18:35:03 UTC (rev 216) @@ -38,4 +38,7 @@ return option; } + public static StringConfigOption getReturnType() { + return new StringConfigOption("returnType", "Specifies the type which the solution has to belong to (if already) known. This means we inform the learning algorithm that the solution is a subclass of this type."); + } } Modified: trunk/src/dl-learner/org/dllearner/core/LearningProblem.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/LearningProblem.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/core/LearningProblem.java 2007-10-11 18:35:03 UTC (rev 216) @@ -24,6 +24,18 @@ /** * Base class for all learning problems. * + * @todo The current learning problem implementations + * assume that we learn a concept, which does not exist + * in the knowledge base so far. However, often we want + * to learn a complex definition for a concept which + * is already integrated in a subsumption hierarchy. This + * means it would make sense to specifiy the list of these + * superclasses as an additional argument of the learning + * problem. The learning algorithms could then make use of + * this to optimise their search for a solution. (More + * generally, one could specify the name of the concept, which + * should be improved.) + * * @author Jens Lehmann * */ Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLP.java 2007-10-11 18:35:03 UTC (rev 216) @@ -170,7 +170,7 @@ if (!posClassified.contains(negExample)) negAsNeg.add(negExample); } - return new ScoreTwoValued(concept.getLength(), posAsPos, posAsNeg, negAsPos, negAsNeg); + return new ScoreTwoValued(concept.getLength(), percentPerLengthUnit, posAsPos, posAsNeg, negAsPos, negAsNeg); // instance checks for classification } else { SortedSet<Individual> posAsPos = new TreeSet<Individual>(); @@ -187,7 +187,7 @@ posAsNeg = Helper.intersection(positiveExamples, negClassified); negAsPos = Helper.intersection(negativeExamples, posClassified); negAsNeg = Helper.intersection(negativeExamples, negClassified); - return new ScoreTwoValued(concept.getLength(), posAsPos, posAsNeg, negAsPos, + return new ScoreTwoValued(concept.getLength(), percentPerLengthUnit, posAsPos, posAsNeg, negAsPos, negAsNeg); } else { @@ -203,7 +203,7 @@ else negAsNeg.add(example); } - return new ScoreTwoValued(concept.getLength(), posAsPos, posAsNeg, negAsPos, + return new ScoreTwoValued(concept.getLength(), percentPerLengthUnit, posAsPos, posAsNeg, negAsPos, negAsNeg); } } Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLPStrict.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLPStrict.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegDefinitionLPStrict.java 2007-10-11 18:35:03 UTC (rev 216) @@ -112,13 +112,13 @@ // this.defPosSet = tuple.getPosSet(); // this.defNegSet = tuple.getNegSet(); SortedSet<Individual> neutClassified = Helper.intersectionTuple(reasoningService.getIndividuals(),tuple); - return new ScoreThreeValued(concept.getLength(),accuracyPenalty, errorPenalty, penaliseNeutralExamples, tuple.getPosSet(),neutClassified,tuple.getNegSet(),positiveExamples,neutralExamples,negativeExamples); + return new ScoreThreeValued(concept.getLength(),accuracyPenalty, errorPenalty, penaliseNeutralExamples, percentPerLengthUnit, tuple.getPosSet(),neutClassified,tuple.getNegSet(),positiveExamples,neutralExamples,negativeExamples); } else if(reasoningService.getReasonerType() == ReasonerType.KAON2) { SortedSet<Individual> posClassified = reasoningService.retrieval(concept); SortedSet<Individual> negClassified = reasoningService.retrieval(new Negation(concept)); SortedSet<Individual> neutClassified = Helper.intersection(reasoningService.getIndividuals(),posClassified); neutClassified.retainAll(negClassified); - return new ScoreThreeValued(concept.getLength(), accuracyPenalty, errorPenalty, penaliseNeutralExamples, posClassified,neutClassified,negClassified,positiveExamples,neutralExamples,negativeExamples); + return new ScoreThreeValued(concept.getLength(), accuracyPenalty, errorPenalty, penaliseNeutralExamples, percentPerLengthUnit, posClassified,neutClassified,negClassified,positiveExamples,neutralExamples,negativeExamples); } else throw new Error("score cannot be computed in this configuration"); } else { @@ -158,7 +158,7 @@ SortedSet<Individual> neutClassified = Helper.intersection(reasoningService.getIndividuals(),posClassified); neutClassified.retainAll(negClassified); - return new ScoreThreeValued(concept.getLength(), accuracyPenalty, errorPenalty, penaliseNeutralExamples, posClassified,neutClassified,negClassified,positiveExamples,neutralExamples,negativeExamples); + return new ScoreThreeValued(concept.getLength(), accuracyPenalty, errorPenalty, penaliseNeutralExamples, percentPerLengthUnit, posClassified,neutClassified,negClassified,positiveExamples,neutralExamples,negativeExamples); } else throw new Error("score cannot be computed in this configuration"); } Modified: trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/learningproblems/PosNegLP.java 2007-10-11 18:35:03 UTC (rev 216) @@ -26,6 +26,7 @@ import org.dllearner.core.BooleanConfigOption; import org.dllearner.core.CommonConfigMappings; +import org.dllearner.core.CommonConfigOptions; import org.dllearner.core.ConfigEntry; import org.dllearner.core.ConfigOption; import org.dllearner.core.InvalidConfigOptionValueException; @@ -48,6 +49,7 @@ protected boolean useRetrievalForClassification = false; protected UseMultiInstanceChecks useDIGMultiInstanceChecks = UseMultiInstanceChecks.TWOCHECKS; + protected double percentPerLengthUnit = 0.05; /** * If instance checks are used for testing concepts (e.g. no retrieval), then @@ -87,6 +89,7 @@ "negative examples")); options.add(new BooleanConfigOption("useRetrievalForClassficiation", "Specifies whether to use retrieval or instance checks for testing a concept.")); + options.add(CommonConfigOptions.getPercentPerLenghtUnitOption(0.05)); return options; } @@ -107,6 +110,8 @@ .getIndividualSet((Set<String>) entry.getValue()); else if (name.equals("useRetrievalForClassification")) useRetrievalForClassification = (Boolean) entry.getValue(); + else if (name.equals("percentPerLengthUnit")) + percentPerLengthUnit = (Double) entry.getValue(); } /* @@ -128,5 +133,9 @@ } public abstract int coveredNegativeExamplesOrTooWeak(Concept concept); + + public double getPercentPerLengthUnit() { + return percentPerLengthUnit; + } } Modified: trunk/src/dl-learner/org/dllearner/learningproblems/ScoreThreeValued.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/ScoreThreeValued.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/learningproblems/ScoreThreeValued.java 2007-10-11 18:35:03 UTC (rev 216) @@ -24,7 +24,6 @@ import java.util.Set; import java.util.SortedSet; -import org.dllearner.Config; import org.dllearner.core.Score; import org.dllearner.core.dl.Individual; import org.dllearner.utilities.Helper; @@ -49,6 +48,7 @@ private double accuracyPenalty; private double errorPenalty; private boolean penaliseNeutralExamples; + private double percentPerLengthUnit; // potential configuration options (not implemented as such, but one // could so) @@ -85,6 +85,7 @@ double accuracyPenalty, double errorPenalty, boolean penaliseNeutralExamples, + double percentPerLengthUnit, SortedSet<Individual> posClassified, SortedSet<Individual> neutClassified, SortedSet<Individual> negClassified, @@ -94,6 +95,8 @@ this.conceptLength = conceptLength; this.accuracyPenalty = accuracyPenalty; this.errorPenalty = errorPenalty; + this.penaliseNeutralExamples = penaliseNeutralExamples; + this.percentPerLengthUnit = percentPerLengthUnit; this.posClassified = posClassified; this.neutClassified = neutClassified; this.negClassified = negClassified; @@ -136,7 +139,7 @@ double worstValue = nrOfExamples * errorPenalty; // ergibt Zahl zwischen -1 und 0 score = score / worstValue; - score -= Config.percentPerLengthUnit * conceptLength; + score -= percentPerLengthUnit * conceptLength; // die folgenden Berechnungen k�nnten aus Performancegr�nden auch // ausgegliedert werden @@ -229,7 +232,7 @@ @Override public Score getModifiedLengthScore(int newLength) { - return new ScoreThreeValued(newLength, accuracyPenalty, errorPenalty, penaliseNeutralExamples, posClassified, neutClassified, negClassified, posExamples, neutExamples, negExamples); + return new ScoreThreeValued(newLength, accuracyPenalty, errorPenalty, penaliseNeutralExamples, percentPerLengthUnit, posClassified, neutClassified, negClassified, posExamples, neutExamples, negExamples); } } Modified: trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java =================================================================== --- trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/learningproblems/ScoreTwoValued.java 2007-10-11 18:35:03 UTC (rev 216) @@ -2,7 +2,6 @@ import java.util.Set; -import org.dllearner.Config; import org.dllearner.core.Score; import org.dllearner.core.dl.Individual; @@ -23,9 +22,11 @@ private double classificationScore; private int nrOfExamples; private int conceptLength; + private double percentPerLengthUnit; - public ScoreTwoValued(int conceptLength, Set<Individual> posAsPos, Set<Individual> posAsNeg, Set<Individual> negAsPos, Set<Individual> negAsNeg) { - this.conceptLength = conceptLength; + public ScoreTwoValued(int conceptLength, double percentPerLengthUnit, Set<Individual> posAsPos, Set<Individual> posAsNeg, Set<Individual> negAsPos, Set<Individual> negAsNeg) { + this.conceptLength = conceptLength; + this.percentPerLengthUnit = percentPerLengthUnit; this.posAsPos = posAsPos; this.posAsNeg = posAsNeg; this.negAsPos = negAsPos; @@ -40,7 +41,7 @@ // Anteil falscher Klassifikationen (Zahl zwischen -1 und 0) classificationScore = classificationScore / (double) nrOfExamples; // Berücksichtigung des Längenfaktors - score = classificationScore - Config.percentPerLengthUnit * conceptLength; + score = classificationScore - percentPerLengthUnit * conceptLength; } @Override @@ -82,6 +83,6 @@ @Override public Score getModifiedLengthScore(int newLength) { - return new ScoreTwoValued(newLength, posAsPos, posAsNeg, negAsPos, negAsNeg); + return new ScoreTwoValued(newLength, percentPerLengthUnit, posAsPos, posAsNeg, negAsPos, negAsNeg); } } Modified: trunk/src/dl-learner/org/dllearner/server/ClientState.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/ClientState.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/server/ClientState.java 2007-10-11 18:35:03 UTC (rev 216) @@ -28,7 +28,7 @@ public class ClientState { - private String reasonerURL="http://localhost:8081"; + // private String reasonerURL="http://localhost:8081"; //private String reasonerURL="http://localhost:3490"; private SortedSet<Individual> positiveExamples = new TreeSet<Individual>(); @@ -417,12 +417,12 @@ // Default-URI für DIG-Reasoner setzen - try { - Config.digReasonerURL = new URL(reasonerURL); - } catch (MalformedURLException e) { - // Exception tritt nie auf, da URL korrekt - e.printStackTrace(); - } +// try { +// Config.digReasonerURL = new URL(reasonerURL); +// } catch (MalformedURLException e) { +// // Exception tritt nie auf, da URL korrekt +// e.printStackTrace(); +// } // reasoner = Main.createReasoner(new KB(), m); System.err.println("TODO: rewrite webservice code"); Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-11 18:35:03 UTC (rev 216) @@ -100,6 +100,7 @@ } // returns the class which is referred to by the string + @SuppressWarnings({"unused"}) private Class<? extends Component> getComponent(String component) throws UnknownComponentException { if(knowledgeSourceMapping.containsKey(component)) return knowledgeSourceMapping.get(component); Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSoriginal.java 2007-10-11 18:35:03 UTC (rev 216) @@ -88,12 +88,12 @@ m.put(ontology, ofFormat); // Default-URI für DIG-Reasoner setzen - try { - Config.digReasonerURL = new URL("http://localhost:8081"); - } catch (MalformedURLException e) { - // Exception tritt nie auf, da URL korrekt - e.printStackTrace(); - } +// try { +// Config.digReasonerURL = new URL("http://localhost:8081"); +// } catch (MalformedURLException e) { +// // Exception tritt nie auf, da URL korrekt +// e.printStackTrace(); +// } // reasoner = Main.createReasoner(new KB(), m); Modified: trunk/src/dl-learner/org/dllearner/utilities/PaperStatistics.java =================================================================== --- trunk/src/dl-learner/org/dllearner/utilities/PaperStatistics.java 2007-10-11 16:17:19 UTC (rev 215) +++ trunk/src/dl-learner/org/dllearner/utilities/PaperStatistics.java 2007-10-11 18:35:03 UTC (rev 216) @@ -29,7 +29,6 @@ import org.dllearner.Config; import org.dllearner.ConfigurationManager; -import org.dllearner.Config.Algorithm; import org.dllearner.algorithms.gp.GP; import org.dllearner.core.ComponentManager; import org.dllearner.core.KnowledgeSource; @@ -215,15 +214,15 @@ LearningAlgorithm learningAlgorithm = null; if(algorithmNr==0) { - Config.algorithm = Algorithm.REFINEMENT; + // Config.algorithm = Algorithm.REFINEMENT; // Config.Refinement.heuristic = Config.Refinement.Heuristic.FLEXIBLE; Config.Refinement.horizontalExpansionFactor = 0.6; Config.Refinement.quiet = true; - Config.percentPerLengthUnit = 0.05; + // Config.percentPerLengthUnit = 0.05; // learningAlgorithm = new ROLearner(learningProblem); // learningAlgorithm = cm.learningAlgorithm(ROLearner.class, learningProblem); } else if(algorithmNr==1) { - Config.algorithm = Algorithm.GP; + // Config.algorithm = Algorithm.GP; Config.GP.algorithmType = GP.AlgorithmType.GENERATIONAL; Config.GP.selectionType = GP.SelectionType.RANK_SELECTION; Config.GP.generations = 50; @@ -235,15 +234,15 @@ Config.GP.mutationProbability = 0.02; Config.GP.crossoverProbability = 0.8; Config.GP.hillClimbingProbability = 0; - Config.percentPerLengthUnit = 0.005; + // Config.percentPerLengthUnit = 0.005; // give GP a chance to find the long solution of the // uncle problem - if(exampleNr==3 || exampleNr==5 || exampleNr == 6) - Config.percentPerLengthUnit = 0.002; + // if(exampleNr==3 || exampleNr==5 || exampleNr == 6) + // Config.percentPerLengthUnit = 0.002; // learningAlgorithm = new GP(learningProblem); learningAlgorithm = cm.learningAlgorithm(GP.class, learningProblem, rs); } else if(algorithmNr==2) { - Config.algorithm = Algorithm.HYBRID_GP; + // Config.algorithm = Algorithm.HYBRID_GP; Config.GP.algorithmType = GP.AlgorithmType.GENERATIONAL; Config.GP.selectionType = GP.SelectionType.RANK_SELECTION; Config.GP.generations = 50; @@ -255,9 +254,9 @@ Config.GP.mutationProbability = 0.02; Config.GP.crossoverProbability = 0.2; Config.GP.hillClimbingProbability = 0; - Config.percentPerLengthUnit = 0.005; - if(exampleNr == 3 || exampleNr==5 || exampleNr==6) - Config.percentPerLengthUnit = 0.002; + // Config.percentPerLengthUnit = 0.005; + // if(exampleNr == 3 || exampleNr==5 || exampleNr==6) +// Config.percentPerLengthUnit = 0.002; // learningAlgorithm = new GP(learningProblem); learningAlgorithm = cm.learningAlgorithm(GP.class, learningProblem, rs); } @@ -439,28 +438,28 @@ cm.applyConfigEntry(learningProblem, "negativeExamples", null); if (j == 0) { - Config.algorithm = Algorithm.HYBRID_GP; + // Config.algorithm = Algorithm.HYBRID_GP; Config.GP.numberOfIndividuals = i + 1; Config.GP.refinementProbability = 0.85; Config.GP.mutationProbability = 0.02; Config.GP.crossoverProbability = 0.05; Config.GP.hillClimbingProbability = 0; } else if (j == 1) { - Config.algorithm = Algorithm.HYBRID_GP; + // Config.algorithm = Algorithm.HYBRID_GP; Config.GP.numberOfIndividuals = i + 1; Config.GP.refinementProbability = 0.4; Config.GP.mutationProbability = 0.02; Config.GP.crossoverProbability = 0.4; Config.GP.hillClimbingProbability = 0; } else if (j == 2) { - Config.algorithm = Algorithm.GP; + // Config.algorithm = Algorithm.GP; Config.GP.numberOfIndividuals = i + 1; Config.GP.refinementProbability = 0; Config.GP.mutationProbability = 0.02; Config.GP.crossoverProbability = 0.8; Config.GP.hillClimbingProbability = 0; } else if (j == 3) { - Config.algorithm = Algorithm.HYBRID_GP; + // Config.algorithm = Algorithm.HYBRID_GP; Config.GP.numberOfIndividuals = i + 1; Config.GP.refinementProbability = 0.7; Config.GP.mutationProbability = 0.02; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-11 16:17:23
|
Revision: 215 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=215&view=rev Author: jenslehmann Date: 2007-10-11 09:17:19 -0700 (Thu, 11 Oct 2007) Log Message: ----------- - (re-)enabled heuristic choosing for refinement operator approach (lexicographic standard heuristic and flexible heuristic) Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/Config.java trunk/src/dl-learner/org/dllearner/ConfigurationManager.java trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java trunk/src/dl-learner/org/dllearner/core/StringConfigOption.java Modified: trunk/src/dl-learner/org/dllearner/Config.java =================================================================== --- trunk/src/dl-learner/org/dllearner/Config.java 2007-10-11 13:45:35 UTC (rev 214) +++ trunk/src/dl-learner/org/dllearner/Config.java 2007-10-11 16:17:19 UTC (rev 215) @@ -141,12 +141,8 @@ // public static File searchTreeFile = new File("searchTree.txt"); - public enum Heuristic { - LEXICOGRAPHIC, FLEXIBLE - }; + // public static Heuristic heuristic = Heuristic.LEXICOGRAPHIC; - public static Heuristic heuristic = Heuristic.LEXICOGRAPHIC; - // multi instance check => es wird versucht mehrere instance checks pro // Anfrage auf einmal an den Reasoner zu schicken; Vorteil bei DIG: // weniger Kommunikation; Nachteil: es müssen alle instanceChecks Modified: trunk/src/dl-learner/org/dllearner/ConfigurationManager.java =================================================================== --- trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-11 13:45:35 UTC (rev 214) +++ trunk/src/dl-learner/org/dllearner/ConfigurationManager.java 2007-10-11 16:17:19 UTC (rev 215) @@ -415,7 +415,7 @@ else if (option.equals("refinement.horizontalExpansionFactor")) Config.Refinement.horizontalExpansionFactor = value; else if (option.equals("percentPerLengthUnit")) - Config.percentPerLengthUnit = value; + ; // Config.percentPerLengthUnit = value; } private void applyStringOptions(String option, String value) { @@ -488,10 +488,10 @@ } else if (option.equals("gp.adc")) { Config.GP.adc = Datastructures.strToBool(value); } else if (option.equals("refinement.heuristic")) { - if(value.equals("lexicographic")) - Config.Refinement.heuristic = Config.Refinement.Heuristic.LEXICOGRAPHIC; - else - Config.Refinement.heuristic = Config.Refinement.Heuristic.FLEXIBLE; +// if(value.equals("lexicographic")) +// Config.Refinement.heuristic = Config.Refinement.Heuristic.LEXICOGRAPHIC; +// else +// Config.Refinement.heuristic = Config.Refinement.Heuristic.FLEXIBLE; } else if (option.equals("refinement.quiet")) Config.Refinement.quiet = Datastructures.strToBool(value); else if (option.equals("refinement.writeSearchTree")) Modified: trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java =================================================================== --- trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-11 13:45:35 UTC (rev 214) +++ trunk/src/dl-learner/org/dllearner/algorithms/refinement/ROLearner.java 2007-10-11 16:17:19 UTC (rev 215) @@ -33,10 +33,13 @@ public class ROLearner extends LearningAlgorithm { + public enum Heuristic { LEXICOGRAPHIC, FLEXIBLE } + // configuration options private boolean writeSearchTree; private File searchTreeFile; private static String defaultSearchTreeFile = "log/searchTree.txt"; + private Heuristic heuristic = Heuristic.LEXICOGRAPHIC; private boolean stop = false; @@ -123,105 +126,12 @@ this.learningProblem = learningProblem; this.rs = rs; - // rs.getR - // this.learningProblem2 = learningProblem2; operator = new RhoDown(learningProblem); - // Heuristik je nach Konfiguration einstellen - if(Config.Refinement.heuristic == Config.Refinement.Heuristic.LEXICOGRAPHIC) - nodeComparator = new NodeComparator(); - else - nodeComparator = new NodeComparator2(learningProblem.getNegativeExamples().size()); - // candidate sets entsprechend der gewählten Heuristik initialisieren candidates = new TreeSet<Node>(nodeComparator); // newCandidates = new TreeSet<Node>(nodeComparator); - - // System.out.println("==="); - - - // short concept test - // Concept c = DLLearner.parseConcept("((male OR (male OR EXISTS hasChild.TOP)) AND male)"); - // c = ConceptTransformation.transformToMultiClean(c); - // System.out.println("parsed: " + c); - // Concept c2 = ConceptTransformation.getShortConcept(c, conceptComparator); - // ConceptTransformation.cleanConcept(c); - // System.out.println("old: " + c); - // System.out.println("new: " + c2); - // System.exit(0); - - // Subsumption-Test - // Concept superConcept = DLLearner.parseConcept("BOTTOM"); - // Concept subConcept = DLLearner.parseConcept("TOP"); - // Concept subConcept = DLLearner.parseConcept("(male AND TOP)"); - - // boolean result = learningProblem.getReasoningService().subsumes(superConcept, subConcept); - // System.out.println(result); - // System.exit(0); - - // Set<Concept> superConcepts = new HashSet<Concept>(); - // superConcepts.add(c1); - // superConcepts.add(c2); - // Set<Concept> result = learningProblem.getReasoningService().subsumes(superConcepts, subConcept); - // System.out.println(result); - // System.exit(0); - - // boolean result = learningProblem.getReasoningService().subsumes(c1, c2); - // System.out.println(c1 + " subsumes " + c2 + ": " +result); - // System.exit(0); - - // Subsumption-Hierarchie-Test - // Concept c = DLLearner.parseConcept("top"); - // System.out.println(learningProblem.getReasoningService().getMoreGeneralConcepts(c)); - // System.exit(0); - - // Zerlegungstest - - /* - int length = 10; - - System.out.println("length " + length); - long startTime = System.nanoTime(); - List<List<Integer>> combos2 = ((RhoDown)operator).getCombos(length); - long duration = System.nanoTime() - startTime; - for(List<Integer> combo : combos2) { - System.out.println(combo); - } - - System.out.println("--"); - startTime = System.nanoTime(); - RhoDown.summen(length,length,"",0); - long duration2 = System.nanoTime() - startTime; - System.out.println("--"); - - System.out.println("duration 1: " + Helper.prettyPrintNanoSeconds(duration)); - System.out.println("duration 2: " + Helper.prettyPrintNanoSeconds(duration2)); - - System.exit(0); - */ - - - // Refinement-Test - /* - // RhoDown rho = new RhoDown(learningProblem); - Concept concept = DLLearner.parseConcept("male"); - concept = ConceptTransformation.transformToMulti(concept); - - Set<Concept> refinements = operator.refine(concept, 3, null); - - - System.out.println("=== testing refinements of " + concept + " ==="); - // rho.computeTopRefinements(5); - // for(Concept c : rho.topRefinementsCumulative.get(5)) { - // for(Concept c : rho.m.get(3)) { - for(Concept c : refinements) { - System.out.println(c); - } - */ - - - // start(); } public static Collection<Class<? extends LearningProblem>> supportedLearningProblems() { @@ -234,6 +144,9 @@ Collection<ConfigOption<?>> options = new LinkedList<ConfigOption<?>>(); options.add(new BooleanConfigOption("writeSearchTree", "specifies whether to write a search tree", false)); options.add(new StringConfigOption("searchTreeFile","file to use for the search tree", defaultSearchTreeFile)); + StringConfigOption heuristicOption = new StringConfigOption("heuristic", "specifiy the heuristic to use", "lexicographic"); + heuristicOption.setAllowedValues(new String[] {"lexicographic", "flexible"}); + options.add(heuristicOption); return options; } @@ -247,6 +160,13 @@ writeSearchTree = (Boolean) entry.getValue(); else if(name.equals("searchTreeFile")) searchTreeFile = new File((String)entry.getValue()); + else if(name.equals("heuristic")) { + String value = (String) entry.getValue(); + if(value.equals("lexicographic")) + heuristic = Heuristic.LEXICOGRAPHIC; + else + heuristic = Heuristic.FLEXIBLE; + } } /* (non-Javadoc) @@ -257,6 +177,12 @@ if(searchTreeFile == null) searchTreeFile = new File(defaultSearchTreeFile); + // adjust heuristic + if(heuristic == Heuristic.LEXICOGRAPHIC) + nodeComparator = new NodeComparator(); + else + nodeComparator = new NodeComparator2(learningProblem.getNegativeExamples().size()); + // TODO: this needs to be changed Helper.autoDetectConceptsAndRoles(rs); // prepare subsumption and role hierarchies, because they are needed @@ -896,6 +822,4 @@ stop = true; } - - } Modified: trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-11 13:45:35 UTC (rev 214) +++ trunk/src/dl-learner/org/dllearner/core/CommonConfigOptions.java 2007-10-11 16:17:19 UTC (rev 215) @@ -31,4 +31,11 @@ return verbosityOption; } + public static DoubleConfigOption getPercentPerLenghtUnitOption(double defaultValue) { + DoubleConfigOption option = new DoubleConfigOption("percentPerLenghtUnit", "describes the reduction in classification accuracy in percent one is willing to accept for reducing the length of the concept by one", defaultValue); + option.setLowerLimit(0.0); + option.setUpperLimit(1.0); + return option; + } + } Modified: trunk/src/dl-learner/org/dllearner/core/StringConfigOption.java =================================================================== --- trunk/src/dl-learner/org/dllearner/core/StringConfigOption.java 2007-10-11 13:45:35 UTC (rev 214) +++ trunk/src/dl-learner/org/dllearner/core/StringConfigOption.java 2007-10-11 16:17:19 UTC (rev 215) @@ -19,6 +19,7 @@ */ package org.dllearner.core; +import java.util.Arrays; import java.util.Set; import java.util.TreeSet; @@ -66,6 +67,10 @@ this.allowedValues = allowedValues; } + public void setAllowedValues(String[] allowedValues) { + this.allowedValues = new TreeSet<String>(Arrays.asList(allowedValues)); + } + /* (non-Javadoc) * @see org.dllearner.core.ConfigOption#checkType(java.lang.Object) */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2007-10-11 13:45:42
|
Revision: 214 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=214&view=rev Author: sknappe Date: 2007-10-11 06:45:35 -0700 (Thu, 11 Oct 2007) Log Message: ----------- applyConfigEntry changed to work with different datatypes Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-10 16:45:22 UTC (rev 213) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-11 13:45:35 UTC (rev 214) @@ -262,7 +262,31 @@ } @WebMethod - public void applyConfigEntry(int sessionID, int componentID, String optionName, Object value) throws ClientNotKnownException, UnknownComponentException { + public void applyConfigEntryInt(int sessionID, int componentID, String optionName, Integer value) throws ClientNotKnownException, UnknownComponentException + { + applyConfigEntry(sessionID, componentID,optionName,value); + } + + @WebMethod + public void applyConfigEntryString(int sessionID, int componentID, String optionName, String value) throws ClientNotKnownException, UnknownComponentException + { + applyConfigEntry(sessionID, componentID,optionName,value); + } + + @WebMethod + public void applyConfigEntryStringArray(int sessionID, int componentID, String optionName, String[] value) throws ClientNotKnownException, UnknownComponentException + { + Set<String> stringSet = new TreeSet<String>(Arrays.asList(value)); + applyConfigEntry(sessionID, componentID,optionName,stringSet); + } + + @WebMethod + public void applyConfigEntryBoolean(int sessionID, int componentID, String optionName, Boolean value) throws ClientNotKnownException, UnknownComponentException + { + applyConfigEntry(sessionID, componentID,optionName,value); + } + + private void applyConfigEntry(int sessionID, int componentID, String optionName, Object value) throws ClientNotKnownException, UnknownComponentException { State state = getState(sessionID); Component component = state.getComponent(componentID); cm.applyConfigEntry(component, optionName, value); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-10 16:45:23
|
Revision: 213 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=213&view=rev Author: jenslehmann Date: 2007-10-10 09:45:22 -0700 (Wed, 10 Oct 2007) Log Message: ----------- - implemented threaded execution of learning algorithms in web service (i.e. non-blocking method for starting the algorithm) => see demo in testnew.php - example reasoning method for web service implemented Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java trunk/src/dl-learner/org/dllearner/server/State.java trunk/src/php-client/testnew.php Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-10 13:16:25 UTC (rev 212) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-10 16:45:22 UTC (rev 213) @@ -37,6 +37,7 @@ import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; import org.dllearner.core.ReasonerComponent; +import org.dllearner.core.dl.AtomicConcept; import org.dllearner.kb.OWLFile; import org.dllearner.kb.SparqlEndpoint; import org.dllearner.learningproblems.PosNegDefinitionLP; @@ -184,6 +185,14 @@ state.getLearningAlgorithm().init(); } + /** + * Starts the learning algorithm and returns the best concept found. This + * method will block until learning is completed. + * + * @param id Session ID. + * @return The best solution found. + * @throws ClientNotKnownException + */ @WebMethod public String learn(int id) throws ClientNotKnownException { State state = getState(id); @@ -191,7 +200,45 @@ return state.getLearningAlgorithm().getBestSolution().toString(); } + /** + * Starts the learning algorithm and returns immediately. The learning + * algorithm is executed in its own thread and can be queried and + * controlled using other Web Service methods. + * + * @param id Session ID. + * @throws ClientNotKnownException + */ + @WebMethod + public void learnThreaded(int id) throws ClientNotKnownException { + final State state = getState(id); + Thread learningThread = new Thread() { + @Override + public void run() { + state.setAlgorithmRunning(true); + state.getLearningAlgorithm().start(); + state.setAlgorithmRunning(false); + } + }; + learningThread.start(); + } + @WebMethod + public String getCurrentlyBestConcept(int id) throws ClientNotKnownException { + State state = getState(id); + return state.getLearningAlgorithm().getBestSolution().toString(); + } + + @WebMethod + public boolean isAlgorithmRunning(int id) throws ClientNotKnownException { + return getState(id).isAlgorithmRunning(); + } + + /** + * Stops the learning algorithm smoothly. + * @param id + * @throws ClientNotKnownException + */ + @WebMethod public void stop(int id) throws ClientNotKnownException { getState(id).getLearningAlgorithm().stop(); } @@ -225,4 +272,17 @@ // reasoning and querying methods // //////////////////////////////////// + @WebMethod + public String[] getAtomicConcepts(int id) throws ClientNotKnownException { + Set<AtomicConcept> atomicConcepts = getState(id).getReasoningService().getAtomicConcepts(); + // convert to String-Array + String[] result = new String[atomicConcepts.size()]; + int i=0; + for(AtomicConcept ac : atomicConcepts) { + result[i] = ac.getName(); + i++; + } + return result; + } + } Modified: trunk/src/dl-learner/org/dllearner/server/State.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-10 13:16:25 UTC (rev 212) +++ trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-10 16:45:22 UTC (rev 213) @@ -59,6 +59,8 @@ private Random rand=new Random(); + private boolean isAlgorithmRunning = false; + private int generateComponentID(Component component) { int id; do { @@ -68,6 +70,20 @@ return id; } + /** + * @return the isAlgorithmRunning + */ + public boolean isAlgorithmRunning() { + return isAlgorithmRunning; + } + + /** + * @param isAlgorithmRunning the isAlgorithmRunning to set + */ + public void setAlgorithmRunning(boolean isAlgorithmRunning) { + this.isAlgorithmRunning = isAlgorithmRunning; + } + // public Component getComponent(Class<? extends Component> componentClass) throws UnknownComponentException { // if(learningProblem.getClass().equals(componentClass)) // return learningProblem; Modified: trunk/src/php-client/testnew.php =================================================================== --- trunk/src/php-client/testnew.php 2007-10-10 13:16:25 UTC (rev 212) +++ trunk/src/php-client/testnew.php 2007-10-10 16:45:22 UTC (rev 213) @@ -37,11 +37,40 @@ $init = $learn_start - $start; echo 'components initialised in '.$init.' seconds<br />'; -$concept = $client->learn($id); +$threaded = true; -$learn = microtime(true) - $learn_start; -echo 'concept learned in '.$learn.' seconds<br />'; +if($threaded == false) { -echo 'result: '.$concept; + $concept = $client->learn($id); + + $learn = microtime(true) - $learn_start; + echo 'concept learned in '.$learn.' seconds<br />'; + + echo 'result: '.$concept; + +} else { + $client->learnThreaded($id); + + $i = 1; + $sleeptime = 1; + + do { + // sleep a while + sleep($sleeptime); + + // see what we have learned so far + $concept=$client->getCurrentlyBestConcept($id); + $running=$client->isAlgorithmRunning($id); + + $seconds = $i * $sleeptime; + + echo 'result after '.$seconds.' seconds of sleep: '.$concept.'<br />'; + + $i++; + } while($running); + + echo 'algorithm finished'; +} + ?> \ 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: <sk...@us...> - 2007-10-10 13:16:27
|
Revision: 212 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=212&view=rev Author: sknappe Date: 2007-10-10 06:16:25 -0700 (Wed, 10 Oct 2007) Log Message: ----------- Removed Paths: ------------- trunk/examples/sparql.conf Deleted: trunk/examples/sparql.conf =================================================================== --- trunk/examples/sparql.conf 2007-10-10 12:56:51 UTC (rev 211) +++ trunk/examples/sparql.conf 2007-10-10 13:16:25 UTC (rev 212) @@ -1,45 +0,0 @@ -/** - * Father Example - * - * possible solution: - * male AND EXISTS hasChild.TOP - * - * Copyright (C) 2007, Jens Lehmann - */ - -/** settings **/ -// reasoner settings -reasoner = dig; -//digReasonerURL = "http://localhost:8081"; -//useRetrievalForClassification = true; -//refinement.useDIGMultiInstanceChecks = twoChecks; - -// algorithm settings -algorithm = refinement; -//refinement.horizontalExpansionFactor = 0.5; -//refinement.quiet = false; - -// search tree protocol -// refinement.writeSearchTree = false; -// refinement.searchTreeFile = "log/searchTree.txt"; - -// control output -cli.checkSatisfiability = true; -cli.showIndividuals = false; -cli.showConcepts = false; -cli.showRoles = true; -cli.showSubsumptionHierarchy = false; - -// SPARQL options -sparql.numberOfRecursions = 2; -sparql.instances = {"http://dbpedia.org/resource/Pythagoras","http://dbpedia.org/resource/Socrates"}; -sparql.filterMode = 0; -sparql.predList = {}; -sparql.objList = {}; -sparql.classList = {}; - -import("http://dbpedia.openlinksw.com","SPARQL"); - -/** examples **/ -+"http://dbpedia.org/resource/Pythagoras" --"http://dbpedia.org/resource/Socrates" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2007-10-10 12:56:53
|
Revision: 211 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=211&view=rev Author: sknappe Date: 2007-10-10 05:56:51 -0700 (Wed, 10 Oct 2007) Log Message: ----------- deleted unnecessary imports Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java Modified: trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java 2007-10-10 12:37:50 UTC (rev 210) +++ trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java 2007-10-10 12:56:51 UTC (rev 211) @@ -26,14 +26,12 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; -import java.net.InetAddress; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; -import org.dllearner.utilities.Files; /** * This class collects the ontology from dbpedia, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2007-10-10 12:37:55
|
Revision: 210 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=210&view=rev Author: sknappe Date: 2007-10-10 05:37:50 -0700 (Wed, 10 Oct 2007) Log Message: ----------- adjustet example to work with new code Modified Paths: -------------- trunk/examples/dbpedia/sparql.conf Modified: trunk/examples/dbpedia/sparql.conf =================================================================== --- trunk/examples/dbpedia/sparql.conf 2007-10-10 12:37:11 UTC (rev 209) +++ trunk/examples/dbpedia/sparql.conf 2007-10-10 12:37:50 UTC (rev 210) @@ -40,7 +40,7 @@ sparql.format = "KB"; sparql.dumpToFile = false; -import("http://dbpedia.openlinksw.com","SPARQL"); +import("http://dbpedia.openlinksw.com:8890/sparql","SPARQL"); /** examples **/ +"http://dbpedia.org/resource/Pythagoras" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2007-10-10 12:37:17
|
Revision: 209 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=209&view=rev Author: sknappe Date: 2007-10-10 05:37:11 -0700 (Wed, 10 Oct 2007) Log Message: ----------- Renamed classes to begin with Sparqle and deleted SimpleHttpRequest Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/kb/SparqlCache.java trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java trunk/src/dl-learner/org/dllearner/kb/SparqlQueryMaker.java Removed Paths: ------------- trunk/src/dl-learner/org/dllearner/kb/Cache.java trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java trunk/src/dl-learner/org/dllearner/kb/QueryMaker.java trunk/src/dl-learner/org/dllearner/kb/SimpleHTTPRequest.java Deleted: trunk/src/dl-learner/org/dllearner/kb/Cache.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/Cache.java 2007-10-10 12:28:02 UTC (rev 208) +++ trunk/src/dl-learner/org/dllearner/kb/Cache.java 2007-10-10 12:37:11 UTC (rev 209) @@ -1,210 +0,0 @@ -/** - * Copyright (C) 2007, Sebastian Hellmann - * - * 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.kb; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.net.URLEncoder; -/** - * - * This is a primitive cache. - * The objects of this class can be either the cache itself or just on entry in the cache - * - * the cache remembers: a timestamp, the original sparql-query, the result - * key is the subject http://dbpedia.org/resource/Angela_Merkel which is first urlencoded - * and so serves as the hash for the filename. - * Cache validates if timestamp too old and Sparql-Query the same - * before returning the SPARQL xml-result - * - * @author Sebastian Hellmann - * - */ -public class Cache implements Serializable{ - - - final static long serialVersionUID=104; - transient String basedir=""; - transient String fileending=".cache"; - long timestamp; - String content=""; - long daysoffreshness=15; - long multiplier=24*60*60*1000;//h m s ms - String sparqlquery=""; - - - /** - * Constructor for the cache itself. - * Called once at the beginning - * - * @param path Where the base path to the cache is - */ - public Cache(String path){ - this.basedir=path+File.separator; - if(!new File(path).exists()) - {System.out.println(new File(path).mkdir());;} - - } - -// - /** - * Constructor for single cache object(one entry) - * - * @param content the sparql xml result - * @param sparql the sparql query - */ - public Cache(String content, String sparql){ - this.content=content; - this.sparqlquery=sparql; - this.timestamp=System.currentTimeMillis(); - } - - - - /** - * use only on the cache object describing the cache itself - * - * @param key the individual - * @param sparql the sparql query - * @return the cached sparql result or null - */ - public String get(String key, String sparql){ - //System.out.println("get From "+key); - String ret=null; - try{ - Cache c =readFromFile(makeFilename(key)) ; - if(c==null)return null; - //System.out.println(" file found"); - if(!c.checkFreshness())return null; - //System.out.println("fresh"); - if(!c.validate(sparql))return null; - //System.out.println("valid"); - ret=c.content; - }catch (Exception e) {e.printStackTrace();} - return ret; - } - - /** - * - * constructor for single cache object(one entry) - * - * @param key the individual - * @param content the sparql result - * @param sparql the sparql query - */ - public void put(String key, String content, String sparql){ - //System.out.println("put into "+key); - Cache c=new Cache(content,sparql); - putIntoFile(makeFilename(key), c); - } - - - /** - * to normalize the filenames - * - * @param key - * @return - */ - String makeFilename(String key){ - String ret=""; - try{ - ret=basedir+URLEncoder.encode(key, "UTF-8")+fileending; - }catch (Exception e) {e.printStackTrace();} - return ret; - } - - /** - * how old is the result - * @return - */ - boolean checkFreshness(){ - if((System.currentTimeMillis()-this.timestamp)<=(daysoffreshness*multiplier)) - //fresh - return true; - else return false; - } - - - /** - * some sparql query - * @param sparql - * @return - */ - boolean validate(String sparql){ - if(this.sparqlquery.equals(sparql)) - //valid - return true; - else return false; - } - - /** - * makes a new file if none exists - * @param Filename - */ - public void checkFile(String Filename){ - if(!new File(Filename).exists()){ - try{ - new File(Filename).createNewFile(); - }catch (Exception e) {e.printStackTrace();} - - } - - } - - /** - * internal saving function - * puts a cache object into a file - * - * @param Filename - * @param content - */ - public void putIntoFile(String Filename,Cache content){ - try{ - //FileWriter fw=new FileWriter(new File(Filename),true); - FileOutputStream fos = new FileOutputStream( Filename , false ); - ObjectOutputStream o = new ObjectOutputStream( fos ); - o.writeObject( content ); - fos.flush(); - fos.close(); - }catch (Exception e) {System.out.println("Not in cache creating: "+Filename);} - } - - /** - * internal retrieval function - * - * @param Filename - * @return one entry object - */ - public Cache readFromFile(String Filename){ - Cache content=null; - try{ - FileInputStream fos = new FileInputStream( Filename ); - ObjectInputStream o = new ObjectInputStream( fos ); - content=(Cache)o.readObject(); - //FileReader fr=new FileReader(new File(Filename,"r")); - //BufferedReader br=new BufferedReader(fr); - }catch (Exception e) {} - return content; - - } -} Deleted: trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java 2007-10-10 12:28:02 UTC (rev 208) +++ trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java 2007-10-10 12:37:11 UTC (rev 209) @@ -1,422 +0,0 @@ -/** - * Copyright (C) 2007, Sebastian Hellmann - * - * 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.kb; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.URL; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; - -import org.dllearner.utilities.Files; - -/** - * This class collects the ontology from dbpedia, - * everything is saved in hashsets, so the doublettes are taken care of - * - * - * @author Sebastian Hellmann - * - */ -public class OntologyCollector { - - boolean print_flag=false; - SimpleHTTPRequest s; - QueryMaker q; - Cache c; - URL url; - SparqlFilter sf; - String[] subjectList; - int numberOfRecursions; - HashSet<String> properties; - HashSet<String> classes; - HashSet<String> instances; - HashSet<String> triples; - String format; - static final char value[]={13,10}; - static final String cut=new String(value); - - // some namespaces - String subclass="http://www.w3.org/2000/01/rdf-schema#subClassOf"; - String type="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; - String objectProperty="http://www.w3.org/2002/07/owl#ObjectProperty"; - String classns="http://www.w3.org/2002/07/owl#Class"; - String thing="http://www.w3.org/2002/07/owl#Thing"; - - - String[] defaultClasses={ - "http://dbpedia.org/class/yago", - "http://dbpedia.org/resource/Category:", - "http://dbpedia.org/resource/Template:", - "http://www.w3.org/2004/02/skos/core", - "http://dbpedia.org/class/"}; //TODO FEHLER hier fehlt yago - - - /** - * - * - * @param subjectList - * @param numberOfRecursions - * @param filterMode - * @param FilterPredList - * @param FilterObjList - * @param defClasses - */ - public OntologyCollector(String[] subjectList,int numberOfRecursions, - int filterMode, String[] FilterPredList,String[] FilterObjList,String[] defClasses, String format, URL url){ - this.subjectList=subjectList; - this.numberOfRecursions=numberOfRecursions; - this.format=format; - this.s=new SimpleHTTPRequest(); - this.q=new QueryMaker(); - this.c=new Cache("cache"); - if(defClasses!=null && defClasses.length>0 ){ - this.defaultClasses=defClasses; - } - - try{ - this.sf=new SparqlFilter(filterMode,FilterPredList,FilterObjList); - this.url=url; - this.properties=new HashSet<String>(); - this.classes=new HashSet<String>(); - this.instances=new HashSet<String>(); - this.triples=new HashSet<String>(); - }catch (Exception e) {e.printStackTrace();} - - } - /** - * first collects the ontology - * then types everything so it becomes owl-dl - * - * @return all triples in n-triple format - */ - public String collectOntology(){ - getRecursiveList(subjectList, numberOfRecursions); - finalize(); - String ret=""; - for (Iterator<String> iter = triples.iterator(); iter.hasNext();) { - ret += iter.next(); - - } - return ret; - } - - /** - * calls getRecursive for each subject in list - * @param subjects - * @param NumberofRecursions - */ - public void getRecursiveList(String[] subjects,int NumberofRecursions){ - for (int i = 0; i < subjects.length; i++) { - getRecursive(subjects[i], NumberofRecursions); - - } - - } - - /** - * gets all triples until numberofrecursion-- gets 0 - * - * @param StartingSubject - * @param NumberofRecursions - */ - public void getRecursive(String StartingSubject,int NumberofRecursions){ - System.out.print("SparqlModul: Depth: "+NumberofRecursions+" @ "+StartingSubject+" "); - if(NumberofRecursions<=0) - { return; - } - else {NumberofRecursions--;} - //System.out.println(NumberofRecursions); - try{ - - String sparql=q.makeQueryFilter(StartingSubject,this.sf); - p(sparql); - p("*******************"); - // checks cache - String FromCache=c.get(StartingSubject, sparql); - String xml; - // if not in cache get it from dbpedia - if(FromCache==null){ - xml=sendAndReceive(sparql); - c.put(StartingSubject, xml, sparql); - System.out.print("\n"); - } - else{ - xml=FromCache; - System.out.println("FROM CACHE"); - } - p(xml); - p("***********************"); - // get new Subjects - String[] newSubjects=processResult(StartingSubject,xml); - - for (int i = 0; (i < newSubjects.length)&& NumberofRecursions!=0; i++) { - getRecursive(newSubjects[i], NumberofRecursions); - } - - //System.out.println(xml); - }catch (Exception e) {e.printStackTrace();} - - } - - /** - * process the sparql result xml in a simple manner - * - * - * @param subject - * @param xml - * @return list of new individuals - */ - public String[] processResult(String subject,String xml){ - //TODO if result is empty, catch exceptions - String one="<binding name=\"predicate\"><uri>"; - String two="<binding name=\"object\"><uri>"; - String end="</uri></binding>"; - String predtmp=""; - String objtmp=""; - ArrayList<String> al=new ArrayList<String>(); - - while(xml.indexOf(one)!=-1){ - //get pred - xml=xml.substring(xml.indexOf(one)+one.length()); - predtmp=xml.substring(0,xml.indexOf(end)); - //getobj - xml=xml.substring(xml.indexOf(two)+two.length()); - objtmp=xml.substring(0,xml.indexOf(end)); - - // writes the triples and resources in the hashsets - // also fills the arraylist al - processTriples(subject, predtmp, objtmp,al); - //System.out.println(al.size()); - - } - - // convert al to list - Object[] o=al.toArray(); - String[] ret=new String[o.length]; - for (int i = 0; i < o.length; i++) { - ret[i]=(String)o[i]; - } - return ret; - //return (String[])al.toArray(); - //System.out.println(xml); - } - - - - /** - * - * writes the triples and resources in the hashsets - * also fills the arraylist al with new individals for further processing - * @param s - * @param p - * @param o - * @param al - */ - public void processTriples(String s,String p, String o,ArrayList<String> al){ - // the next two lines bump out some inconsistencies within dbpedia - String t="/Category"; - if(s.equals(t) || o.equals(t))return ; - - if(sf.mode==2) - { - if( o.startsWith("http://dbpedia.org/resource/Category:") - && - !p.startsWith("http://www.w3.org/2004/02/skos/core") - ) - {return;} - if(p.equals("http://www.w3.org/2004/02/skos/core#broader")){ - p=subclass; - } - else if(p.equals("http://www.w3.org/2004/02/skos/core#subject")){ - p=type; - } - else {} - } - - //save for further processing - al.add(o); - - // type classes - if(isClass(o)){ - classes.add(o); - if(isClass(s))p=subclass; - else p=type; - } - else { - instances.add(o); - this.properties.add(p); - } - - - - //maketriples - try{ - this.triples.add(makeTriples(s, p, o)); - //fw.write(makeTriples(subject, predtmp, objtmp)); - }catch (Exception e) {e.printStackTrace();} - - - return; - } -// - /** - * also makes subclass property between classes - * - * @param s - * @param p - * @param o - * @return triple in the n triple notation - */ - public String makeTriples(String s,String p, String o){ - String ret=""; - if (format.equals("N-TRIPLES")) ret="<"+s+"> <"+p+"> <"+o+">.\n"; - else if (format.equals("KB")){ - if (p.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) ret="\""+o+"\"(\""+s+"\").\n"; - else ret="\""+p+"\"(\""+s+"\",\""+o+"\").\n"; - } - return ret; - } - - /** - * decides if an object is treated as a class - * - * @param obj - * @return true if obj is in the defaultClassesList - */ - public boolean isClass(String obj){ - - boolean retval=false; - for (String defclass : defaultClasses) { - if(obj.contains(defclass))retval=true; - } - return retval; - } - - - /** - * @see java.lang.Object#finalize() - */ - @Override - public void finalize(){ - typeProperties(); - typeClasses(); - typeInstances(); - } - - public void typeProperties(){ - String rdfns="http://www.w3.org/1999/02/22-rdf-syntax-ns"; - String owlns="http://www.w3.org/2002/07/owl"; - Iterator<String> it=properties.iterator(); - String current=""; - while (it.hasNext()){ - try{ - current=it.next(); - if(current.equals(subclass))continue; - if(current.contains(rdfns)||current.contains(owlns)){/*DO NOTHING*/} - else {this.triples.add(makeTriples(current,type,objectProperty));} - }catch (Exception e) {} - - } - } - public void typeClasses(){ - Iterator<String> it=classes.iterator(); - String current=""; - while (it.hasNext()){ - try{ - current=it.next(); - this.triples.add(makeTriples(current,type,classns)); - }catch (Exception e) {} - } - } - public void typeInstances(){ - Iterator<String> it=instances.iterator(); - String current=""; - while (it.hasNext()){ - try{ - current=it.next(); - this.triples.add(makeTriples(current,type,thing)); - }catch (Exception e) {} - } - } - - /** - * debug print turn on print_flag - * @param s - */ - public void p(String s){ - if(print_flag) - System.out.println(s); - } - - private String sendAndReceive(String sparql) { - StringBuilder answer = new StringBuilder(); - - // String an Sparql-Endpoint schicken - HttpURLConnection connection; - - try { - connection = (HttpURLConnection) url.openConnection(); - connection.setDoOutput(true); - - connection.addRequestProperty("Host", "dbpedia.openlinksw.com"); - connection.addRequestProperty("Connection","close"); - connection.addRequestProperty("Accept","text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); - connection.addRequestProperty("Accept-Language","de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"); - connection.addRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"); - connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 Web-Sniffer/1.0.24"); - - OutputStream os = connection.getOutputStream(); - OutputStreamWriter osw = new OutputStreamWriter(os); - osw.write("default-graph-uri=http%3A%2F%2Fdbpedia.org&query=" + - URLEncoder.encode(sparql, "UTF-8")+ - "&format=application%2Fsparql-results%2Bxml"); - osw.close(); - - // receive answer - InputStream is = connection.getInputStream(); - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - - String line; - do { - line = br.readLine(); - if(line!=null) - answer.append(line); - } while (line != null); - - br.close(); - - } catch (IOException e) { - System.out.println("Communication problem with Sparql Server."); - System.exit(0); - } - - return answer.toString(); - } -} Deleted: trunk/src/dl-learner/org/dllearner/kb/QueryMaker.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/QueryMaker.java 2007-10-10 12:28:02 UTC (rev 208) +++ trunk/src/dl-learner/org/dllearner/kb/QueryMaker.java 2007-10-10 12:37:11 UTC (rev 209) @@ -1,123 +0,0 @@ -/** - * Copyright (C) 2007, Sebastian Hellmann - * - * 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.kb; - -/** - * - * This class produces sparql queries - * - * @author Sebastian Hellmann - * - */ -public class QueryMaker { - //Good - /*public static String owl ="http://www.w3.org/2002/07/owl#"; - public static String xsd="http://www.w3.org/2001/XMLSchema#"; - public static String rdfs="http://www.w3.org/2000/01/rdf-schema#"; - public static String rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"; - public static String base="http://dbpedia.org/resource/"; - public static String dbpedia2="http://dbpedia.org/property/"; - public static String dbpedia="http://dbpedia.org/"; - - - //BAD - public static String skos="http://www.w3.org/2004/02/skos/core#"; - public static String foaf="http://xmlns.com/foaf/0.1/"; - public static String dc="http://purl.org/dc/elements/1.1/"; - public static String foreign="http://dbpedia.org/property/wikipage-"; - public static String sameAs="http://www.w3.org/2002/07/owl#sameAs"; - public static String reference="http://dbpedia.org/property/reference";*/ - - int tempyago=0; - - /** - * reads all the options and makes the sparql query accordingly - * @param subject - * @param sf special object encapsulating all options - * @return sparql query - */ - public String makeQueryFilter(String subject, SparqlFilter sf){ - - - String Filter=""; - if(!sf.useLiterals)Filter+="!isLiteral(?object))"; - for (String p : sf.getPredFilter()) { - Filter+="\n" + filterPredicate(p); - } - for (String o : sf.getObjFilter()) { - Filter+="\n" + filterObject(o); - } - - - String ret= - "SELECT * WHERE { \n" + - "<"+ - subject+ - - "> ?predicate ?object.\n" + - "FILTER( \n" + - "(" +Filter+").}"; - //System.out.println(ret); - return ret; - } - - - /*public String makeQueryDefault(String subject){ - String ret= - "SELECT * WHERE { \n" + - "<"+ - subject+ - - "> ?predicate ?object.\n" + - "FILTER( \n" + - "(!isLiteral(?object))" + - "\n" + filterPredicate(skos)+ - //"\n" + filterObject(skos)+ - "\n" + filterPredicate(foaf)+ - "\n" + filterObject(foaf)+ - "\n" + filterPredicate(foreign)+ - "\n" + filterPredicate(sameAs)+ - "\n" + filterPredicate(reference)+ - ")." + - " }"; - - //System.out.println(ret); - return ret; -}*/ - - /** - * add a new object filter - * (objects are filtered out of sparql result) - * @param ns namespace - * @return - */ - public String filterObject(String ns){ - return "&&( !regex((?object), '"+ns+"') )"; - } - /** - * add a new object filter - * (objects are filtered out of sparql result) - * @param ns namespace - * * @return - */ - public String filterPredicate(String ns){ - return "&&( !regex(str(?predicate), '"+ns+"') )"; - } -} Deleted: trunk/src/dl-learner/org/dllearner/kb/SimpleHTTPRequest.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/SimpleHTTPRequest.java 2007-10-10 12:28:02 UTC (rev 208) +++ trunk/src/dl-learner/org/dllearner/kb/SimpleHTTPRequest.java 2007-10-10 12:37:11 UTC (rev 209) @@ -1,126 +0,0 @@ -/** - * Copyright (C) 2007, Sebastian Hellmann - * - * 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.kb; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetAddress; -import java.net.Socket; -import java.net.URLEncoder; - - - -/** - * - * This class makes a simple http request - * the dbpedia url is hardcoded - * - * @author Sebastian Hellmann - * - * - */ -public class SimpleHTTPRequest { - static final char value[]={13,10}; - static final String cut=new String(value); - - - - - public String sendAndReceive(InetAddress ia, int port, String sparql){ - String retval=""; - // - - byte resp[]=null; - - try{ - Socket SparqlServer=new Socket(ia,port); - String request=makeHeader(sparql); - // send request - (SparqlServer.getOutputStream()).write(request.getBytes()); - - //get Response - resp=readBuffer(new BufferedInputStream(SparqlServer.getInputStream())); - retval=new String(resp); - retval=subtractResponseHeader(retval); - //retval="||"+retval; - - SparqlServer.close(); - - - - } - catch(Exception e){e.printStackTrace();} - //System.out.println("got it"); - return retval; - - }//down - - public static byte[] readBuffer(InputStream IS) - throws IOException{ - byte buffer[] = new byte[0xffff]; - int nbytes=0; - byte resp[]=new byte[0]; - while ((nbytes=IS.read(buffer))!=-1) { - byte tmp[]=new byte[resp.length+nbytes]; - int i=0; - for (;i<resp.length;i++){ - tmp[i]=resp[i]; - } - for(int a=0;a<nbytes;a++,i++){ - tmp[i]=buffer[a]; - } - resp=tmp; - } - return resp; - } - - public String subtractResponseHeader(String in){ - //System.out.println(in.indexOf(cut+""+cut)); - return in.substring(in.indexOf(cut+""+cut)+4); - - - } - - public String makeHeader(String query){ - - - String RequestHeader=""; - try{ - - RequestHeader="GET /sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=" + - //"SELECT%20%2A%20WHERE%20%7B%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FAristotle%3E%20%3Fa%20%3Fb%20%7D%20" + - URLEncoder.encode(query, "UTF-8")+ - //query+// URLencode - "&format=application%2Fsparql-results%2Bxml HTTP/1.1"+cut+ - "Host: dbpedia.openlinksw.com"+cut+ - "Connection: close"+cut+ - //"Accept-Encoding: gzip"+cut+ - "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"+cut+ - "Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"+cut+ - "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"+cut+ - "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 Web-Sniffer/1.0.24"+cut+ - cut; - }catch (Exception e) {e.printStackTrace();} - return RequestHeader; - - } - -} Copied: trunk/src/dl-learner/org/dllearner/kb/SparqlCache.java (from rev 205, trunk/src/dl-learner/org/dllearner/kb/Cache.java) =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/SparqlCache.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/kb/SparqlCache.java 2007-10-10 12:37:11 UTC (rev 209) @@ -0,0 +1,210 @@ +/** + * Copyright (C) 2007, Sebastian Hellmann + * + * 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.kb; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.net.URLEncoder; +/** + * + * This is a primitive cache. + * The objects of this class can be either the cache itself or just on entry in the cache + * + * the cache remembers: a timestamp, the original sparql-query, the result + * key is the subject http://dbpedia.org/resource/Angela_Merkel which is first urlencoded + * and so serves as the hash for the filename. + * Cache validates if timestamp too old and Sparql-Query the same + * before returning the SPARQL xml-result + * + * @author Sebastian Hellmann + * + */ +public class SparqlCache implements Serializable{ + + + final static long serialVersionUID=104; + transient String basedir=""; + transient String fileending=".cache"; + long timestamp; + String content=""; + long daysoffreshness=15; + long multiplier=24*60*60*1000;//h m s ms + String sparqlquery=""; + + + /** + * Constructor for the cache itself. + * Called once at the beginning + * + * @param path Where the base path to the cache is + */ + public SparqlCache(String path){ + this.basedir=path+File.separator; + if(!new File(path).exists()) + {System.out.println(new File(path).mkdir());;} + + } + +// + /** + * Constructor for single cache object(one entry) + * + * @param content the sparql xml result + * @param sparql the sparql query + */ + public SparqlCache(String content, String sparql){ + this.content=content; + this.sparqlquery=sparql; + this.timestamp=System.currentTimeMillis(); + } + + + + /** + * use only on the cache object describing the cache itself + * + * @param key the individual + * @param sparql the sparql query + * @return the cached sparql result or null + */ + public String get(String key, String sparql){ + //System.out.println("get From "+key); + String ret=null; + try{ + SparqlCache c =readFromFile(makeFilename(key)) ; + if(c==null)return null; + //System.out.println(" file found"); + if(!c.checkFreshness())return null; + //System.out.println("fresh"); + if(!c.validate(sparql))return null; + //System.out.println("valid"); + ret=c.content; + }catch (Exception e) {e.printStackTrace();} + return ret; + } + + /** + * + * constructor for single cache object(one entry) + * + * @param key the individual + * @param content the sparql result + * @param sparql the sparql query + */ + public void put(String key, String content, String sparql){ + //System.out.println("put into "+key); + SparqlCache c=new SparqlCache(content,sparql); + putIntoFile(makeFilename(key), c); + } + + + /** + * to normalize the filenames + * + * @param key + * @return + */ + String makeFilename(String key){ + String ret=""; + try{ + ret=basedir+URLEncoder.encode(key, "UTF-8")+fileending; + }catch (Exception e) {e.printStackTrace();} + return ret; + } + + /** + * how old is the result + * @return + */ + boolean checkFreshness(){ + if((System.currentTimeMillis()-this.timestamp)<=(daysoffreshness*multiplier)) + //fresh + return true; + else return false; + } + + + /** + * some sparql query + * @param sparql + * @return + */ + boolean validate(String sparql){ + if(this.sparqlquery.equals(sparql)) + //valid + return true; + else return false; + } + + /** + * makes a new file if none exists + * @param Filename + */ + public void checkFile(String Filename){ + if(!new File(Filename).exists()){ + try{ + new File(Filename).createNewFile(); + }catch (Exception e) {e.printStackTrace();} + + } + + } + + /** + * internal saving function + * puts a cache object into a file + * + * @param Filename + * @param content + */ + public void putIntoFile(String Filename,SparqlCache content){ + try{ + //FileWriter fw=new FileWriter(new File(Filename),true); + FileOutputStream fos = new FileOutputStream( Filename , false ); + ObjectOutputStream o = new ObjectOutputStream( fos ); + o.writeObject( content ); + fos.flush(); + fos.close(); + }catch (Exception e) {System.out.println("Not in cache creating: "+Filename);} + } + + /** + * internal retrieval function + * + * @param Filename + * @return one entry object + */ + public SparqlCache readFromFile(String Filename){ + SparqlCache content=null; + try{ + FileInputStream fos = new FileInputStream( Filename ); + ObjectInputStream o = new ObjectInputStream( fos ); + content=(SparqlCache)o.readObject(); + //FileReader fr=new FileReader(new File(Filename,"r")); + //BufferedReader br=new BufferedReader(fr); + }catch (Exception e) {} + return content; + + } +} Modified: trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java 2007-10-10 12:28:02 UTC (rev 208) +++ trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java 2007-10-10 12:37:11 UTC (rev 209) @@ -124,7 +124,7 @@ public void init() { System.out.println("SparqlModul: Collecting Ontology"); String[] a=new String[0]; - OntologyCollector oc=new OntologyCollector(instances.toArray(a), numberOfRecursions, + SparqlOntologyCollector oc=new SparqlOntologyCollector(instances.toArray(a), numberOfRecursions, filterMode, Datastructures.setToArray(predList),Datastructures.setToArray( objList),Datastructures.setToArray(classList),format,url); String ont=oc.collectOntology(); Copied: trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java (from rev 208, trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java) =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/kb/SparqlOntologyCollector.java 2007-10-10 12:37:11 UTC (rev 209) @@ -0,0 +1,420 @@ +/** + * Copyright (C) 2007, Sebastian Hellmann + * + * 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.kb; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.URL; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; + +import org.dllearner.utilities.Files; + +/** + * This class collects the ontology from dbpedia, + * everything is saved in hashsets, so the doublettes are taken care of + * + * + * @author Sebastian Hellmann + * + */ +public class SparqlOntologyCollector { + + boolean print_flag=false; + SparqlQueryMaker q; + SparqlCache c; + URL url; + SparqlFilter sf; + String[] subjectList; + int numberOfRecursions; + HashSet<String> properties; + HashSet<String> classes; + HashSet<String> instances; + HashSet<String> triples; + String format; + static final char value[]={13,10}; + static final String cut=new String(value); + + // some namespaces + String subclass="http://www.w3.org/2000/01/rdf-schema#subClassOf"; + String type="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; + String objectProperty="http://www.w3.org/2002/07/owl#ObjectProperty"; + String classns="http://www.w3.org/2002/07/owl#Class"; + String thing="http://www.w3.org/2002/07/owl#Thing"; + + + String[] defaultClasses={ + "http://dbpedia.org/class/yago", + "http://dbpedia.org/resource/Category:", + "http://dbpedia.org/resource/Template:", + "http://www.w3.org/2004/02/skos/core", + "http://dbpedia.org/class/"}; //TODO FEHLER hier fehlt yago + + + /** + * + * + * @param subjectList + * @param numberOfRecursions + * @param filterMode + * @param FilterPredList + * @param FilterObjList + * @param defClasses + */ + public SparqlOntologyCollector(String[] subjectList,int numberOfRecursions, + int filterMode, String[] FilterPredList,String[] FilterObjList,String[] defClasses, String format, URL url){ + this.subjectList=subjectList; + this.numberOfRecursions=numberOfRecursions; + this.format=format; + this.q=new SparqlQueryMaker(); + this.c=new SparqlCache("cache"); + if(defClasses!=null && defClasses.length>0 ){ + this.defaultClasses=defClasses; + } + + try{ + this.sf=new SparqlFilter(filterMode,FilterPredList,FilterObjList); + this.url=url; + this.properties=new HashSet<String>(); + this.classes=new HashSet<String>(); + this.instances=new HashSet<String>(); + this.triples=new HashSet<String>(); + }catch (Exception e) {e.printStackTrace();} + + } + /** + * first collects the ontology + * then types everything so it becomes owl-dl + * + * @return all triples in n-triple format + */ + public String collectOntology(){ + getRecursiveList(subjectList, numberOfRecursions); + finalize(); + String ret=""; + for (Iterator<String> iter = triples.iterator(); iter.hasNext();) { + ret += iter.next(); + + } + return ret; + } + + /** + * calls getRecursive for each subject in list + * @param subjects + * @param NumberofRecursions + */ + public void getRecursiveList(String[] subjects,int NumberofRecursions){ + for (int i = 0; i < subjects.length; i++) { + getRecursive(subjects[i], NumberofRecursions); + + } + + } + + /** + * gets all triples until numberofrecursion-- gets 0 + * + * @param StartingSubject + * @param NumberofRecursions + */ + public void getRecursive(String StartingSubject,int NumberofRecursions){ + System.out.print("SparqlModul: Depth: "+NumberofRecursions+" @ "+StartingSubject+" "); + if(NumberofRecursions<=0) + { return; + } + else {NumberofRecursions--;} + //System.out.println(NumberofRecursions); + try{ + + String sparql=q.makeQueryFilter(StartingSubject,this.sf); + p(sparql); + p("*******************"); + // checks cache + String FromCache=c.get(StartingSubject, sparql); + String xml; + // if not in cache get it from dbpedia + if(FromCache==null){ + xml=sendAndReceive(sparql); + c.put(StartingSubject, xml, sparql); + System.out.print("\n"); + } + else{ + xml=FromCache; + System.out.println("FROM CACHE"); + } + p(xml); + p("***********************"); + // get new Subjects + String[] newSubjects=processResult(StartingSubject,xml); + + for (int i = 0; (i < newSubjects.length)&& NumberofRecursions!=0; i++) { + getRecursive(newSubjects[i], NumberofRecursions); + } + + //System.out.println(xml); + }catch (Exception e) {e.printStackTrace();} + + } + + /** + * process the sparql result xml in a simple manner + * + * + * @param subject + * @param xml + * @return list of new individuals + */ + public String[] processResult(String subject,String xml){ + //TODO if result is empty, catch exceptions + String one="<binding name=\"predicate\"><uri>"; + String two="<binding name=\"object\"><uri>"; + String end="</uri></binding>"; + String predtmp=""; + String objtmp=""; + ArrayList<String> al=new ArrayList<String>(); + + while(xml.indexOf(one)!=-1){ + //get pred + xml=xml.substring(xml.indexOf(one)+one.length()); + predtmp=xml.substring(0,xml.indexOf(end)); + //getobj + xml=xml.substring(xml.indexOf(two)+two.length()); + objtmp=xml.substring(0,xml.indexOf(end)); + + // writes the triples and resources in the hashsets + // also fills the arraylist al + processTriples(subject, predtmp, objtmp,al); + //System.out.println(al.size()); + + } + + // convert al to list + Object[] o=al.toArray(); + String[] ret=new String[o.length]; + for (int i = 0; i < o.length; i++) { + ret[i]=(String)o[i]; + } + return ret; + //return (String[])al.toArray(); + //System.out.println(xml); + } + + + + /** + * + * writes the triples and resources in the hashsets + * also fills the arraylist al with new individals for further processing + * @param s + * @param p + * @param o + * @param al + */ + public void processTriples(String s,String p, String o,ArrayList<String> al){ + // the next two lines bump out some inconsistencies within dbpedia + String t="/Category"; + if(s.equals(t) || o.equals(t))return ; + + if(sf.mode==2) + { + if( o.startsWith("http://dbpedia.org/resource/Category:") + && + !p.startsWith("http://www.w3.org/2004/02/skos/core") + ) + {return;} + if(p.equals("http://www.w3.org/2004/02/skos/core#broader")){ + p=subclass; + } + else if(p.equals("http://www.w3.org/2004/02/skos/core#subject")){ + p=type; + } + else {} + } + + //save for further processing + al.add(o); + + // type classes + if(isClass(o)){ + classes.add(o); + if(isClass(s))p=subclass; + else p=type; + } + else { + instances.add(o); + this.properties.add(p); + } + + + + //maketriples + try{ + this.triples.add(makeTriples(s, p, o)); + //fw.write(makeTriples(subject, predtmp, objtmp)); + }catch (Exception e) {e.printStackTrace();} + + + return; + } +// + /** + * also makes subclass property between classes + * + * @param s + * @param p + * @param o + * @return triple in the n triple notation + */ + public String makeTriples(String s,String p, String o){ + String ret=""; + if (format.equals("N-TRIPLES")) ret="<"+s+"> <"+p+"> <"+o+">.\n"; + else if (format.equals("KB")){ + if (p.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) ret="\""+o+"\"(\""+s+"\").\n"; + else ret="\""+p+"\"(\""+s+"\",\""+o+"\").\n"; + } + return ret; + } + + /** + * decides if an object is treated as a class + * + * @param obj + * @return true if obj is in the defaultClassesList + */ + public boolean isClass(String obj){ + + boolean retval=false; + for (String defclass : defaultClasses) { + if(obj.contains(defclass))retval=true; + } + return retval; + } + + + /** + * @see java.lang.Object#finalize() + */ + @Override + public void finalize(){ + typeProperties(); + typeClasses(); + typeInstances(); + } + + public void typeProperties(){ + String rdfns="http://www.w3.org/1999/02/22-rdf-syntax-ns"; + String owlns="http://www.w3.org/2002/07/owl"; + Iterator<String> it=properties.iterator(); + String current=""; + while (it.hasNext()){ + try{ + current=it.next(); + if(current.equals(subclass))continue; + if(current.contains(rdfns)||current.contains(owlns)){/*DO NOTHING*/} + else {this.triples.add(makeTriples(current,type,objectProperty));} + }catch (Exception e) {} + + } + } + public void typeClasses(){ + Iterator<String> it=classes.iterator(); + String current=""; + while (it.hasNext()){ + try{ + current=it.next(); + this.triples.add(makeTriples(current,type,classns)); + }catch (Exception e) {} + } + } + public void typeInstances(){ + Iterator<String> it=instances.iterator(); + String current=""; + while (it.hasNext()){ + try{ + current=it.next(); + this.triples.add(makeTriples(current,type,thing)); + }catch (Exception e) {} + } + } + + /** + * debug print turn on print_flag + * @param s + */ + public void p(String s){ + if(print_flag) + System.out.println(s); + } + + private String sendAndReceive(String sparql) { + StringBuilder answer = new StringBuilder(); + + // String an Sparql-Endpoint schicken + HttpURLConnection connection; + + try { + connection = (HttpURLConnection) url.openConnection(); + connection.setDoOutput(true); + + connection.addRequestProperty("Host", "dbpedia.openlinksw.com"); + connection.addRequestProperty("Connection","close"); + connection.addRequestProperty("Accept","text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); + connection.addRequestProperty("Accept-Language","de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"); + connection.addRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"); + connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 Web-Sniffer/1.0.24"); + + OutputStream os = connection.getOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(os); + osw.write("default-graph-uri=http%3A%2F%2Fdbpedia.org&query=" + + URLEncoder.encode(sparql, "UTF-8")+ + "&format=application%2Fsparql-results%2Bxml"); + osw.close(); + + // receive answer + InputStream is = connection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String line; + do { + line = br.readLine(); + if(line!=null) + answer.append(line); + } while (line != null); + + br.close(); + + } catch (IOException e) { + System.out.println("Communication problem with Sparql Server."); + System.exit(0); + } + + return answer.toString(); + } +} Copied: trunk/src/dl-learner/org/dllearner/kb/SparqlQueryMaker.java (from rev 205, trunk/src/dl-learner/org/dllearner/kb/QueryMaker.java) =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/SparqlQueryMaker.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/kb/SparqlQueryMaker.java 2007-10-10 12:37:11 UTC (rev 209) @@ -0,0 +1,123 @@ +/** + * Copyright (C) 2007, Sebastian Hellmann + * + * 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.kb; + +/** + * + * This class produces sparql queries + * + * @author Sebastian Hellmann + * + */ +public class SparqlQueryMaker { + //Good + /*public static String owl ="http://www.w3.org/2002/07/owl#"; + public static String xsd="http://www.w3.org/2001/XMLSchema#"; + public static String rdfs="http://www.w3.org/2000/01/rdf-schema#"; + public static String rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + public static String base="http://dbpedia.org/resource/"; + public static String dbpedia2="http://dbpedia.org/property/"; + public static String dbpedia="http://dbpedia.org/"; + + + //BAD + public static String skos="http://www.w3.org/2004/02/skos/core#"; + public static String foaf="http://xmlns.com/foaf/0.1/"; + public static String dc="http://purl.org/dc/elements/1.1/"; + public static String foreign="http://dbpedia.org/property/wikipage-"; + public static String sameAs="http://www.w3.org/2002/07/owl#sameAs"; + public static String reference="http://dbpedia.org/property/reference";*/ + + int tempyago=0; + + /** + * reads all the options and makes the sparql query accordingly + * @param subject + * @param sf special object encapsulating all options + * @return sparql query + */ + public String makeQueryFilter(String subject, SparqlFilter sf){ + + + String Filter=""; + if(!sf.useLiterals)Filter+="!isLiteral(?object))"; + for (String p : sf.getPredFilter()) { + Filter+="\n" + filterPredicate(p); + } + for (String o : sf.getObjFilter()) { + Filter+="\n" + filterObject(o); + } + + + String ret= + "SELECT * WHERE { \n" + + "<"+ + subject+ + + "> ?predicate ?object.\n" + + "FILTER( \n" + + "(" +Filter+").}"; + //System.out.println(ret); + return ret; + } + + + /*public String makeQueryDefault(String subject){ + String ret= + "SELECT * WHERE { \n" + + "<"+ + subject+ + + "> ?predicate ?object.\n" + + "FILTER( \n" + + "(!isLiteral(?object))" + + "\n" + filterPredicate(skos)+ + //"\n" + filterObject(skos)+ + "\n" + filterPredicate(foaf)+ + "\n" + filterObject(foaf)+ + "\n" + filterPredicate(foreign)+ + "\n" + filterPredicate(sameAs)+ + "\n" + filterPredicate(reference)+ + ")." + + " }"; + + //System.out.println(ret); + return ret; +}*/ + + /** + * add a new object filter + * (objects are filtered out of sparql result) + * @param ns namespace + * @return + */ + public String filterObject(String ns){ + return "&&( !regex((?object), '"+ns+"') )"; + } + /** + * add a new object filter + * (objects are filtered out of sparql result) + * @param ns namespace + * * @return + */ + public String filterPredicate(String ns){ + return "&&( !regex(str(?predicate), '"+ns+"') )"; + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2007-10-10 12:28:04
|
Revision: 208 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=208&view=rev Author: sknappe Date: 2007-10-10 05:28:02 -0700 (Wed, 10 Oct 2007) Log Message: ----------- connection to sparql-endpoint is now made without SimpleHTTPRequest but with HttpURLConnection Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java Modified: trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java 2007-10-10 11:22:58 UTC (rev 207) +++ trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java 2007-10-10 12:28:02 UTC (rev 208) @@ -19,12 +19,22 @@ */ package org.dllearner.kb; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; +import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; +import org.dllearner.utilities.Files; + /** * This class collects the ontology from dbpedia, * everything is saved in hashsets, so the doublettes are taken care of @@ -39,7 +49,7 @@ SimpleHTTPRequest s; QueryMaker q; Cache c; - InetAddress ia; + URL url; SparqlFilter sf; String[] subjectList; int numberOfRecursions; @@ -48,6 +58,8 @@ HashSet<String> instances; HashSet<String> triples; String format; + static final char value[]={13,10}; + static final String cut=new String(value); // some namespaces String subclass="http://www.w3.org/2000/01/rdf-schema#subClassOf"; @@ -88,14 +100,12 @@ } try{ - this.sf=new SparqlFilter(filterMode,FilterPredList,FilterObjList); - this.ia=InetAddress.getByName(url.getHost()); - //this.fw=new FileWriter(new File(System.currentTimeMillis()+".nt"),true); - this.properties=new HashSet<String>(); - this.classes=new HashSet<String>(); - this.instances=new HashSet<String>(); - this.triples=new HashSet<String>(); - //this.all=new HashSet<String>(); + this.sf=new SparqlFilter(filterMode,FilterPredList,FilterObjList); + this.url=url; + this.properties=new HashSet<String>(); + this.classes=new HashSet<String>(); + this.instances=new HashSet<String>(); + this.triples=new HashSet<String>(); }catch (Exception e) {e.printStackTrace();} } @@ -152,7 +162,7 @@ String xml; // if not in cache get it from dbpedia if(FromCache==null){ - xml=s.sendAndReceive(ia, 8890, sparql); + xml=sendAndReceive(sparql); c.put(StartingSubject, xml, sparql); System.out.print("\n"); } @@ -364,5 +374,49 @@ System.out.println(s); } - + private String sendAndReceive(String sparql) { + StringBuilder answer = new StringBuilder(); + + // String an Sparql-Endpoint schicken + HttpURLConnection connection; + + try { + connection = (HttpURLConnection) url.openConnection(); + connection.setDoOutput(true); + + connection.addRequestProperty("Host", "dbpedia.openlinksw.com"); + connection.addRequestProperty("Connection","close"); + connection.addRequestProperty("Accept","text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); + connection.addRequestProperty("Accept-Language","de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"); + connection.addRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"); + connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 Web-Sniffer/1.0.24"); + + OutputStream os = connection.getOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(os); + osw.write("default-graph-uri=http%3A%2F%2Fdbpedia.org&query=" + + URLEncoder.encode(sparql, "UTF-8")+ + "&format=application%2Fsparql-results%2Bxml"); + osw.close(); + + // receive answer + InputStream is = connection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String line; + do { + line = br.readLine(); + if(line!=null) + answer.append(line); + } while (line != null); + + br.close(); + + } catch (IOException e) { + System.out.println("Communication problem with Sparql Server."); + System.exit(0); + } + + return answer.toString(); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-10 11:23:04
|
Revision: 207 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=207&view=rev Author: jenslehmann Date: 2007-10-10 04:22:58 -0700 (Wed, 10 Oct 2007) Log Message: ----------- - web service: returns IDs for the components in set and add methods -> these can be used to refer to components later on - web service: added generic method to configure components Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java trunk/src/dl-learner/org/dllearner/server/State.java trunk/src/php-client/testnew.php Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-10 09:26:44 UTC (rev 206) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-10 11:22:58 UTC (rev 207) @@ -20,7 +20,6 @@ package org.dllearner.server; import java.util.Arrays; -import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Set; @@ -32,6 +31,7 @@ import javax.jws.soap.SOAPBinding; import org.dllearner.algorithms.refinement.ROLearner; +import org.dllearner.core.Component; import org.dllearner.core.ComponentManager; import org.dllearner.core.KnowledgeSource; import org.dllearner.core.LearningAlgorithm; @@ -54,10 +54,25 @@ @SOAPBinding(style = SOAPBinding.Style.RPC) public class DLLearnerWSNew { - private Map<Long, State> clients = new TreeMap<Long,State>(); + private Map<Integer, State> clients = new TreeMap<Integer,State>(); private Random rand=new Random(); private static ComponentManager cm = ComponentManager.getInstance(); + // defines the components, which are accessible for the web service + private static Map<String,Class<? extends KnowledgeSource>> knowledgeSourceMapping = new TreeMap<String,Class<? extends KnowledgeSource>>(); + private static Map<String,Class<? extends ReasonerComponent>> reasonerMapping = new TreeMap<String,Class<? extends ReasonerComponent>>(); + private static Map<String,Class<? extends LearningProblem>> learningProblemMapping = new TreeMap<String,Class<? extends LearningProblem>>(); + private static Map<String,Class<? extends LearningAlgorithm>> learningAlgorithmMapping = new TreeMap<String,Class<? extends LearningAlgorithm>>(); + + public DLLearnerWSNew() { + knowledgeSourceMapping.put("owlfile", OWLFile.class); + knowledgeSourceMapping.put("sparql", SparqlEndpoint.class); + reasonerMapping.put("dig", DIGReasoner.class); + learningProblemMapping.put("posNegDefinition", PosNegDefinitionLP.class); + learningProblemMapping.put("posNegInclusion", PosNegInclusionLP.class); + learningAlgorithmMapping.put("refinement", ROLearner.class); + } + /** * Generates a unique ID for the client and initialises a session. * Using the ID the client can call the other web service methods. @@ -66,36 +81,51 @@ * @return A session ID. */ @WebMethod - public long generateID() { - long id; + public int generateID() { + int id; do { - id = rand.nextLong(); + id = rand.nextInt(); } while(clients.containsKey(id)); clients.put(id, new State()); return id; } // returns session state or throws client not known exception - private State getState(long id) throws ClientNotKnownException { + private State getState(int id) throws ClientNotKnownException { State state = clients.get(id); if(state==null) throw new ClientNotKnownException(id); return state; } + // returns the class which is referred to by the string + private Class<? extends Component> getComponent(String component) throws UnknownComponentException { + if(knowledgeSourceMapping.containsKey(component)) + return knowledgeSourceMapping.get(component); + else if(reasonerMapping.containsKey(component)) + return reasonerMapping.get(component); + else if(learningProblemMapping.containsKey(component)) + return learningProblemMapping.get(component); + else if(learningAlgorithmMapping.containsKey(component)) + return learningAlgorithmMapping.get(component); + else + throw new UnknownComponentException(component); + } + /////////////////////////////////////// // methods for basic component setup // /////////////////////////////////////// + /** + * Adds a knowledge source. + * + * @return An identifier for the component. + */ @WebMethod - public boolean addKnowledgeSource(long id, String component, String url) throws ClientNotKnownException, UnknownComponentException { + public int addKnowledgeSource(int id, String component, String url) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); - Class<? extends KnowledgeSource> ksClass; - if(component.equals("sparql")) - ksClass = SparqlEndpoint.class; - else if(component.equals("owlfile")) - ksClass = OWLFile.class; - else + Class<? extends KnowledgeSource> ksClass = knowledgeSourceMapping.get(component); + if(ksClass == null) throw new UnknownComponentException(component); KnowledgeSource ks = cm.knowledgeSource(ksClass); cm.applyConfigEntry(ks, "url", url); @@ -103,17 +133,15 @@ } @WebMethod - public boolean removeKnowledgeSource(long id, String url) throws ClientNotKnownException { - return getState(id).removeKnowledgeSource(url); + public void removeKnowledgeSource(int id, int componentID) throws ClientNotKnownException { + getState(id).removeKnowledgeSource(componentID); } @WebMethod - public void setReasoner(long id, String component) throws ClientNotKnownException, UnknownComponentException { + public void setReasoner(int id, String component) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); - Class<? extends ReasonerComponent> rcClass; - if(component.equals("dig")) - rcClass = DIGReasoner.class; - else + Class<? extends ReasonerComponent> rcClass = reasonerMapping.get(component); + if(rcClass == null) throw new UnknownComponentException(component); ReasonerComponent rc = cm.reasoner(rcClass, state.getKnowledgeSources()); @@ -121,14 +149,10 @@ } @WebMethod - public void setLearningProblem(long id, String component) throws ClientNotKnownException, UnknownComponentException { + public void setLearningProblem(int id, String component) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); - Class<? extends LearningProblem> lpClass; - if(component.equals("posNegDefinition")) - lpClass = PosNegDefinitionLP.class; - else if(component.equals("posNegInclusion")) - lpClass = PosNegInclusionLP.class; - else + Class<? extends LearningProblem> lpClass = learningProblemMapping.get(component); + if(lpClass == null) throw new UnknownComponentException(component); LearningProblem lp = cm.learningProblem(lpClass, state.getReasoningService()); @@ -136,12 +160,10 @@ } @WebMethod - public void setLearningAlgorithm(long id, String component) throws ClientNotKnownException, UnknownComponentException { + public void setLearningAlgorithm(int id, String component) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); - Class<? extends LearningAlgorithm> laClass; - if(component.equals("refinement")) - laClass = ROLearner.class; - else + Class<? extends LearningAlgorithm> laClass = learningAlgorithmMapping.get(component); + if(laClass == null) throw new UnknownComponentException(component); LearningAlgorithm la = cm.learningAlgorithm(laClass, state.getLearningProblem(), state.getReasoningService()); @@ -153,7 +175,7 @@ * @param id Session ID. */ @WebMethod - public void init(long id) throws ClientNotKnownException { + public void init(int id) throws ClientNotKnownException { State state = getState(id); for(KnowledgeSource ks : state.getKnowledgeSources()) ks.init(); @@ -163,32 +185,44 @@ } @WebMethod - public String learn(long id) throws ClientNotKnownException { + public String learn(int id) throws ClientNotKnownException { State state = getState(id); state.getLearningAlgorithm().start(); return state.getLearningAlgorithm().getBestSolution().toString(); } + @WebMethod + public void stop(int id) throws ClientNotKnownException { + getState(id).getLearningAlgorithm().stop(); + } + ///////////////////////////////////////// // methods for component configuration // ///////////////////////////////////////// @WebMethod - public void setPositiveExamples(long id, String[] positiveExamples) throws ClientNotKnownException { + public void setPositiveExamples(int id, String[] positiveExamples) throws ClientNotKnownException { State state = getState(id); Set<String> posExamples = new TreeSet<String>(Arrays.asList(positiveExamples)); cm.applyConfigEntry(state.getLearningProblem(), "positiveExamples", posExamples); } @WebMethod - public void setNegativeExamples(long id, String[] negativeExamples) throws ClientNotKnownException { + public void setNegativeExamples(int id, String[] negativeExamples) throws ClientNotKnownException { State state = getState(id); Set<String> negExamples = new TreeSet<String>(Arrays.asList(negativeExamples)); cm.applyConfigEntry(state.getLearningProblem(), "negativeExamples", negExamples); } + @WebMethod + public void applyConfigEntry(int sessionID, int componentID, String optionName, Object value) throws ClientNotKnownException, UnknownComponentException { + State state = getState(sessionID); + Component component = state.getComponent(componentID); + cm.applyConfigEntry(component, optionName, value); + } + //////////////////////////////////// // reasoning and querying methods // //////////////////////////////////// - + } Modified: trunk/src/dl-learner/org/dllearner/server/State.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-10 09:26:44 UTC (rev 206) +++ trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-10 11:22:58 UTC (rev 207) @@ -19,10 +19,14 @@ */ package org.dllearner.server; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.Map; +import java.util.Random; import java.util.Set; +import org.dllearner.core.Component; import org.dllearner.core.KnowledgeSource; import org.dllearner.core.LearningAlgorithm; import org.dllearner.core.LearningProblem; @@ -39,6 +43,11 @@ */ public class State { + // stores the mapping between component IDs and component + // (note that this allows us to keep all references to components even + // if they are note used anymore e.g. a deleted knowledge source) + private Map<Integer,Component> componentIDs = new HashMap<Integer,Component>(); + private Set<KnowledgeSource> knowledgeSources = new HashSet<KnowledgeSource>(); private LearningProblem learningProblem; @@ -48,30 +57,37 @@ private LearningAlgorithm learningAlgorithm; - /** - * @return the knowledgeSource - */ - public Set<KnowledgeSource> getKnowledgeSources() { - return knowledgeSources; + private Random rand=new Random(); + + private int generateComponentID(Component component) { + int id; + do { + id = rand.nextInt(); + } while(componentIDs.keySet().contains(id)); + componentIDs.put(id, component); + return id; } + +// public Component getComponent(Class<? extends Component> componentClass) throws UnknownComponentException { +// if(learningProblem.getClass().equals(componentClass)) +// return learningProblem; +// else if(learningAlgorithm.getClass().equals(componentClass)) +// return learningAlgorithm; +// else if(reasonerComponent.getClass().equals(componentClass)) +// return reasonerComponent; +// else if(KnowledgeSource.class.isAssignableFrom(componentClass)) { +// +// +// for(KnowledgeSource ks : knowledgeSources) { +// if(ks.getClass().equals(componentClass)) +// return ks; +// } +// throw new UnknownComponentException(componentClass.getName()); +// } else +// throw new UnknownComponentException(componentClass.getName()); +// } /** - * @param knowledgeSources the knowledgeSource to set - */ - public void setKnowledgeSources(Set<KnowledgeSource> knowledgeSources) { - this.knowledgeSources = knowledgeSources; - } - - /** - * @param e - * @return - * @see java.util.Set#add(java.lang.Object) - */ - public boolean addKnowledgeSource(KnowledgeSource ks) { - return knowledgeSources.add(ks); - } - - /** * Removes a knowledge source with the given URL (independant of its type). * @param url URL of the OWL file or SPARQL Endpoint. * @return True if a knowledge source was deleted, false otherwise. @@ -99,8 +115,9 @@ /** * @param learningProblem the learningProblem to set */ - public void setLearningProblem(LearningProblem learningProblem) { + public int setLearningProblem(LearningProblem learningProblem) { this.learningProblem = learningProblem; + return generateComponentID(learningProblem); } /** @@ -116,9 +133,10 @@ * * @param reasonerComponent the reasonerComponent to set */ - public void setReasonerComponent(ReasonerComponent reasonerComponent) { + public int setReasonerComponent(ReasonerComponent reasonerComponent) { this.reasonerComponent = reasonerComponent; reasoningService = new ReasoningService(reasonerComponent); + return generateComponentID(reasonerComponent); } /** @@ -131,8 +149,9 @@ /** * @param learningAlgorithm the learningAlgorithm to set */ - public void setLearningAlgorithm(LearningAlgorithm learningAlgorithm) { + public int setLearningAlgorithm(LearningAlgorithm learningAlgorithm) { this.learningAlgorithm = learningAlgorithm; + return generateComponentID(learningAlgorithm); } /** @@ -141,5 +160,34 @@ public ReasoningService getReasoningService() { return reasoningService; } + + /** + * @param key + * @return + * @see java.util.Map#get(java.lang.Object) + */ + public Component getComponent(int id) { + return componentIDs.get(id); + } + + /** + * @param e + * @return + */ + public int addKnowledgeSource(KnowledgeSource ks) { + knowledgeSources.add(ks); + return generateComponentID(ks); + + } + + public boolean removeKnowledgeSource(int componentID) { + return knowledgeSources.remove(componentIDs.get(componentID)); + } + /** + * @return the knowledgeSources + */ + public Set<KnowledgeSource> getKnowledgeSources() { + return knowledgeSources; + } } Modified: trunk/src/php-client/testnew.php =================================================================== --- trunk/src/php-client/testnew.php 2007-10-10 09:26:44 UTC (rev 206) +++ trunk/src/php-client/testnew.php 2007-10-10 11:22:58 UTC (rev 207) @@ -22,7 +22,7 @@ $id = $client->generateID(); -$client->addKnowledgeSource($id, "owlfile", $ontology); +$ksID = $client->addKnowledgeSource($id, "owlfile", $ontology); $client->setReasoner($id, "dig"); $client->setLearningProblem($id, "posNegDefinition"); $client->setPositiveExamples($id, $posExamples); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-10 09:26:50
|
Revision: 206 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=206&view=rev Author: jenslehmann Date: 2007-10-10 02:26:44 -0700 (Wed, 10 Oct 2007) Log Message: ----------- ID generation test Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-10 09:01:57 UTC (rev 205) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-10 09:26:44 UTC (rev 206) @@ -24,6 +24,7 @@ import java.util.Map; import java.util.Random; import java.util.Set; +import java.util.TreeMap; import java.util.TreeSet; import javax.jws.WebMethod; @@ -53,7 +54,7 @@ @SOAPBinding(style = SOAPBinding.Style.RPC) public class DLLearnerWSNew { - private Map<Long, State> clients = new HashMap<Long,State>(); + private Map<Long, State> clients = new TreeMap<Long,State>(); private Random rand=new Random(); private static ComponentManager cm = ComponentManager.getInstance(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <sk...@us...> - 2007-10-10 09:01:59
|
Revision: 205 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=205&view=rev Author: sknappe Date: 2007-10-10 02:01:57 -0700 (Wed, 10 Oct 2007) Log Message: ----------- option url is now used Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java Modified: trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java 2007-10-09 15:52:15 UTC (rev 204) +++ trunk/src/dl-learner/org/dllearner/kb/OntologyCollector.java 2007-10-10 09:01:57 UTC (rev 205) @@ -20,6 +20,7 @@ package org.dllearner.kb; import java.net.InetAddress; +import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -75,7 +76,7 @@ * @param defClasses */ public OntologyCollector(String[] subjectList,int numberOfRecursions, - int filterMode, String[] FilterPredList,String[] FilterObjList,String[] defClasses, String format){ + int filterMode, String[] FilterPredList,String[] FilterObjList,String[] defClasses, String format, URL url){ this.subjectList=subjectList; this.numberOfRecursions=numberOfRecursions; this.format=format; @@ -88,7 +89,7 @@ try{ this.sf=new SparqlFilter(filterMode,FilterPredList,FilterObjList); - this.ia=InetAddress.getByName("dbpedia.openlinksw.com"); + this.ia=InetAddress.getByName(url.getHost()); //this.fw=new FileWriter(new File(System.currentTimeMillis()+".nt"),true); this.properties=new HashSet<String>(); this.classes=new HashSet<String>(); Modified: trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java =================================================================== --- trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java 2007-10-09 15:52:15 UTC (rev 204) +++ trunk/src/dl-learner/org/dllearner/kb/SparqlEndpoint.java 2007-10-10 09:01:57 UTC (rev 205) @@ -125,7 +125,7 @@ System.out.println("SparqlModul: Collecting Ontology"); String[] a=new String[0]; OntologyCollector oc=new OntologyCollector(instances.toArray(a), numberOfRecursions, - filterMode, Datastructures.setToArray(predList),Datastructures.setToArray( objList),Datastructures.setToArray(classList),format); + filterMode, Datastructures.setToArray(predList),Datastructures.setToArray( objList),Datastructures.setToArray(classList),format,url); String ont=oc.collectOntology(); if (format.equals("N-TRIPLES")||dumpToFile){ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jen...@us...> - 2007-10-09 15:52:21
|
Revision: 204 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=204&view=rev Author: jenslehmann Date: 2007-10-09 08:52:15 -0700 (Tue, 09 Oct 2007) Log Message: ----------- - extended new DL-Learner web service - first working PHP example for a basic learning task Modified Paths: -------------- trunk/build.xml trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java trunk/src/dl-learner/org/dllearner/server/State.java trunk/src/dl-learner/org/dllearner/server/jaxws/ClientNotKnownExceptionBean.java trunk/src/php-client/testnew.php Added Paths: ----------- trunk/src/dl-learner/org/dllearner/server/jaxws/UnknownComponentExceptionBean.java Modified: trunk/build.xml =================================================================== --- trunk/build.xml 2007-10-09 14:06:57 UTC (rev 203) +++ trunk/build.xml 2007-10-09 15:52:15 UTC (rev 204) @@ -165,7 +165,7 @@ <arg value="-cp"/> <arg value="${wsgenpath}"/> <!--<arg value=".;../../classes;../../library/dig1.1-xmlbeans.jar;../../library/kaon2.jar;../../library/xbean.jar;../../library/owlapi/;../../library/owlapi/antlr-runtime-3.0.jar;../../library/owlapi/commons-lang-2.2.jar;../../library/owlapi/owlapi-api.jar;../../library/owlapi/owlapi-apibinding.jar;../../library/owlapi/owlapi-change.jar;../../library/owlapi/owlapi-debugging.jar;../../library/owlapi/owlapi-dig1_1.jar;../../library/owlapi/owlapi-functionalparser.jar;../../library/owlapi/owlapi-functionalrenderer.jar;../../library/owlapi/owlapi-impl.jar;../../library/owlapi/owlapi-krssparser.jar;../../library/owlapi/owlapi-mansyntaxparser.jar;../../library/owlapi/owlapi-mansyntaxrenderer.jar;../../library/owlapi/owlapi-metrics.jar;../../library/owlapi/owlapi-oboparser.jar;../../library/owlapi/owlapi-owlxmlparser.jar;../../library/owlapi/owlapi-owlxmlrenderer.jar;../../library/owlapi/owlapi-rdfapi.jar;../../library/owlapi/owlapi-rdfxmlparser.jar;../../library/owlapi/owlapi-rdfxmlrenderer.jar;../../library/owlapi/owlapi-util.jar"/>--> - <arg value="org.dllearner.server.DLLearnerWS"/> + <arg value="org.dllearner.server.DLLearnerWSNew"/> </exec> </target> Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-09 14:06:57 UTC (rev 203) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-09 15:52:15 UTC (rev 204) @@ -19,8 +19,12 @@ */ package org.dllearner.server; +import java.util.Arrays; import java.util.HashMap; +import java.util.Map; import java.util.Random; +import java.util.Set; +import java.util.TreeSet; import javax.jws.WebMethod; import javax.jws.WebService; @@ -49,9 +53,9 @@ @SOAPBinding(style = SOAPBinding.Style.RPC) public class DLLearnerWSNew { - private HashMap<Long, State> clients; + private Map<Long, State> clients = new HashMap<Long,State>(); private Random rand=new Random(); - private ComponentManager cm = ComponentManager.getInstance(); + private static ComponentManager cm = ComponentManager.getInstance(); /** * Generates a unique ID for the client and initialises a session. @@ -66,6 +70,7 @@ do { id = rand.nextLong(); } while(clients.containsKey(id)); + clients.put(id, new State()); return id; } @@ -77,14 +82,20 @@ return state; } + /////////////////////////////////////// + // methods for basic component setup // + /////////////////////////////////////// + @WebMethod - public boolean addKnowledgeSource(long id, String component, String url) throws ClientNotKnownException { + public boolean addKnowledgeSource(long id, String component, String url) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); Class<? extends KnowledgeSource> ksClass; if(component.equals("sparql")) ksClass = SparqlEndpoint.class; + else if(component.equals("owlfile")) + ksClass = OWLFile.class; else - ksClass = OWLFile.class; + throw new UnknownComponentException(component); KnowledgeSource ks = cm.knowledgeSource(ksClass); cm.applyConfigEntry(ks, "url", url); return state.addKnowledgeSource(ks); @@ -136,4 +147,47 @@ state.setLearningAlgorithm(la); } + /** + * Initialise all components. + * @param id Session ID. + */ + @WebMethod + public void init(long id) throws ClientNotKnownException { + State state = getState(id); + for(KnowledgeSource ks : state.getKnowledgeSources()) + ks.init(); + state.getReasonerComponent().init(); + state.getLearningProblem().init(); + state.getLearningAlgorithm().init(); + } + + @WebMethod + public String learn(long id) throws ClientNotKnownException { + State state = getState(id); + state.getLearningAlgorithm().start(); + return state.getLearningAlgorithm().getBestSolution().toString(); + } + + ///////////////////////////////////////// + // methods for component configuration // + ///////////////////////////////////////// + + @WebMethod + public void setPositiveExamples(long id, String[] positiveExamples) throws ClientNotKnownException { + State state = getState(id); + Set<String> posExamples = new TreeSet<String>(Arrays.asList(positiveExamples)); + cm.applyConfigEntry(state.getLearningProblem(), "positiveExamples", posExamples); + } + + @WebMethod + public void setNegativeExamples(long id, String[] negativeExamples) throws ClientNotKnownException { + State state = getState(id); + Set<String> negExamples = new TreeSet<String>(Arrays.asList(negativeExamples)); + cm.applyConfigEntry(state.getLearningProblem(), "negativeExamples", negExamples); + } + + //////////////////////////////////// + // reasoning and querying methods // + //////////////////////////////////// + } Modified: trunk/src/dl-learner/org/dllearner/server/State.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-09 14:06:57 UTC (rev 203) +++ trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-09 15:52:15 UTC (rev 204) @@ -19,6 +19,7 @@ */ package org.dllearner.server; +import java.util.HashSet; import java.util.Iterator; import java.util.Set; @@ -38,7 +39,7 @@ */ public class State { - private Set<KnowledgeSource> knowledgeSources; + private Set<KnowledgeSource> knowledgeSources = new HashSet<KnowledgeSource>(); private LearningProblem learningProblem; Modified: trunk/src/dl-learner/org/dllearner/server/jaxws/ClientNotKnownExceptionBean.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/jaxws/ClientNotKnownExceptionBean.java 2007-10-09 14:06:57 UTC (rev 203) +++ trunk/src/dl-learner/org/dllearner/server/jaxws/ClientNotKnownExceptionBean.java 2007-10-09 15:52:15 UTC (rev 204) @@ -1,63 +1,41 @@ - -package org.dllearner.server.jaxws; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - * This class was generated by the JAXWS SI. - * JAX-WS RI 2.0_02-b08-fcs - * Generated source version: 2.0_02 - * - */ -@XmlRootElement(name = "ClientNotKnownException", namespace = "http://server.dllearner.org/") -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "ClientNotKnownException", namespace = "http://server.dllearner.org/", propOrder = { - "detail", - "message" -}) -public class ClientNotKnownExceptionBean { - - private String detail; - private String message; - - /** - * - * @return - * returns String - */ - public String getDetail() { - return this.detail; - } - - /** - * - * @param detail - * the value for the detail property - */ - public void setDetail(String detail) { - this.detail = detail; - } - - /** - * - * @return - * returns String - */ - public String getMessage() { - return this.message; - } - - /** - * - * @param message - * the value for the message property - */ - public void setMessage(String message) { - this.message = message; - } - -} + +package org.dllearner.server.jaxws; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * This class was generated by the JAXWS SI. + * JAX-WS RI 2.0_02-b08-fcs + * Generated source version: 2.0_02 + * + */ +@XmlRootElement(name = "ClientNotKnownException", namespace = "http://server.dllearner.org/") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ClientNotKnownException", namespace = "http://server.dllearner.org/") +public class ClientNotKnownExceptionBean { + + private String message; + + /** + * + * @return + * returns String + */ + public String getMessage() { + return this.message; + } + + /** + * + * @param message + * the value for the message property + */ + public void setMessage(String message) { + this.message = message; + } + +} Added: trunk/src/dl-learner/org/dllearner/server/jaxws/UnknownComponentExceptionBean.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/jaxws/UnknownComponentExceptionBean.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/server/jaxws/UnknownComponentExceptionBean.java 2007-10-09 15:52:15 UTC (rev 204) @@ -0,0 +1,41 @@ + +package org.dllearner.server.jaxws; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * This class was generated by the JAXWS SI. + * JAX-WS RI 2.0_02-b08-fcs + * Generated source version: 2.0_02 + * + */ +@XmlRootElement(name = "UnknownComponentException", namespace = "http://server.dllearner.org/") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "UnknownComponentException", namespace = "http://server.dllearner.org/") +public class UnknownComponentExceptionBean { + + private String message; + + /** + * + * @return + * returns String + */ + public String getMessage() { + return this.message; + } + + /** + * + * @param message + * the value for the message property + */ + public void setMessage(String message) { + this.message = message; + } + +} Modified: trunk/src/php-client/testnew.php =================================================================== --- trunk/src/php-client/testnew.php 2007-10-09 14:06:57 UTC (rev 203) +++ trunk/src/php-client/testnew.php 2007-10-09 15:52:15 UTC (rev 204) @@ -5,18 +5,43 @@ ini_set("soap.wsdl_cache_enabled","0"); $wsdluri="http://localhost:8181/services?wsdl"; +$ontology="file:/home/jl/promotion/dl-learner-svn/trunk/examples/father.owl"; +$posExamples = array('http://example.com/father#stefan', + 'http://example.com/father#markus', + 'http://example.com/father#martin'); +$negExamples = array('http://example.com/father#heinz', + 'http://example.com/father#anna', + 'http://example.com/father#michelle'); + // always update WSDL LearnerClient::loadWSDLfiles($wsdluri); // test web service $client = new SoapClient("main.wsdl"); -$test = $client->hello(); -echo $test; +$id = $client->generateID(); -$stringar = array('blub','blab'); -$ret = $client->test($stringar); -print_r($ret); +$client->addKnowledgeSource($id, "owlfile", $ontology); +$client->setReasoner($id, "dig"); +$client->setLearningProblem($id, "posNegDefinition"); +$client->setPositiveExamples($id, $posExamples); +$client->setNegativeExamples($id, $negExamples); +$client->setLearningAlgorithm($id, "refinement"); +$start = microtime(true); + +$client->init($id); + +$learn_start = microtime(true); +$init = $learn_start - $start; +echo 'components initialised in '.$init.' seconds<br />'; + +$concept = $client->learn($id); + +$learn = microtime(true) - $learn_start; +echo 'concept learned in '.$learn.' seconds<br />'; + +echo 'result: '.$concept; + ?> \ 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...> - 2007-10-09 14:07:00
|
Revision: 203 http://dl-learner.svn.sourceforge.net/dl-learner/?rev=203&view=rev Author: jenslehmann Date: 2007-10-09 07:06:57 -0700 (Tue, 09 Oct 2007) Log Message: ----------- finished basic component creation in web service Modified Paths: -------------- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java trunk/src/dl-learner/org/dllearner/server/State.java Added Paths: ----------- trunk/src/dl-learner/org/dllearner/server/UnknownComponentException.java Modified: trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-09 09:26:31 UTC (rev 202) +++ trunk/src/dl-learner/org/dllearner/server/DLLearnerWSNew.java 2007-10-09 14:06:57 UTC (rev 203) @@ -26,10 +26,17 @@ import javax.jws.WebService; import javax.jws.soap.SOAPBinding; +import org.dllearner.algorithms.refinement.ROLearner; 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.kb.OWLFile; import org.dllearner.kb.SparqlEndpoint; +import org.dllearner.learningproblems.PosNegDefinitionLP; +import org.dllearner.learningproblems.PosNegInclusionLP; +import org.dllearner.reasoning.DIGReasoner; /** * DL-Learner web service interface. @@ -71,22 +78,62 @@ } @WebMethod - public void addKnowledgeSource(long id, String type, String url) throws ClientNotKnownException { + public boolean addKnowledgeSource(long id, String component, String url) throws ClientNotKnownException { State state = getState(id); Class<? extends KnowledgeSource> ksClass; - if(type.equals("sparql")) + if(component.equals("sparql")) ksClass = SparqlEndpoint.class; else ksClass = OWLFile.class; KnowledgeSource ks = cm.knowledgeSource(ksClass); cm.applyConfigEntry(ks, "url", url); - state.addKnowledgeSource(ks); + return state.addKnowledgeSource(ks); } @WebMethod - public void setLearningAlgorithm(long id, String algorithm) throws ClientNotKnownException { + public boolean removeKnowledgeSource(long id, String url) throws ClientNotKnownException { + return getState(id).removeKnowledgeSource(url); + } + + @WebMethod + public void setReasoner(long id, String component) throws ClientNotKnownException, UnknownComponentException { State state = getState(id); - // ... + Class<? extends ReasonerComponent> rcClass; + if(component.equals("dig")) + rcClass = DIGReasoner.class; + else + throw new UnknownComponentException(component); + + ReasonerComponent rc = cm.reasoner(rcClass, state.getKnowledgeSources()); + state.setReasonerComponent(rc); } + @WebMethod + public void setLearningProblem(long id, String component) throws ClientNotKnownException, UnknownComponentException { + State state = getState(id); + Class<? extends LearningProblem> lpClass; + if(component.equals("posNegDefinition")) + lpClass = PosNegDefinitionLP.class; + else if(component.equals("posNegInclusion")) + lpClass = PosNegInclusionLP.class; + else + throw new UnknownComponentException(component); + + LearningProblem lp = cm.learningProblem(lpClass, state.getReasoningService()); + state.setLearningProblem(lp); + } + + @WebMethod + public void setLearningAlgorithm(long id, String component) throws ClientNotKnownException, UnknownComponentException { + State state = getState(id); + Class<? extends LearningAlgorithm> laClass; + if(component.equals("refinement")) + laClass = ROLearner.class; + else + throw new UnknownComponentException(component); + + LearningAlgorithm la = cm.learningAlgorithm(laClass, state.getLearningProblem(), state.getReasoningService()); + state.setLearningAlgorithm(la); + } + } Modified: trunk/src/dl-learner/org/dllearner/server/State.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-09 09:26:31 UTC (rev 202) +++ trunk/src/dl-learner/org/dllearner/server/State.java 2007-10-09 14:06:57 UTC (rev 203) @@ -19,12 +19,16 @@ */ package org.dllearner.server; +import java.util.Iterator; import java.util.Set; 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.kb.OWLFile; +import org.dllearner.kb.SparqlEndpoint; /** * Stores the state of a DL-Learner client session. @@ -34,26 +38,27 @@ */ public class State { - private Set<KnowledgeSource> knowledgeSource; + private Set<KnowledgeSource> knowledgeSources; private LearningProblem learningProblem; private ReasonerComponent reasonerComponent; + private ReasoningService reasoningService; private LearningAlgorithm learningAlgorithm; /** * @return the knowledgeSource */ - public Set<KnowledgeSource> getKnowledgeSource() { - return knowledgeSource; + public Set<KnowledgeSource> getKnowledgeSources() { + return knowledgeSources; } /** - * @param knowledgeSource the knowledgeSource to set + * @param knowledgeSources the knowledgeSource to set */ - public void setKnowledgeSource(Set<KnowledgeSource> knowledgeSource) { - this.knowledgeSource = knowledgeSource; + public void setKnowledgeSources(Set<KnowledgeSource> knowledgeSources) { + this.knowledgeSources = knowledgeSources; } /** @@ -62,16 +67,25 @@ * @see java.util.Set#add(java.lang.Object) */ public boolean addKnowledgeSource(KnowledgeSource ks) { - return knowledgeSource.add(ks); + return knowledgeSources.add(ks); } /** - * @param o - * @return - * @see java.util.Set#remove(java.lang.Object) + * Removes a knowledge source with the given URL (independant of its type). + * @param url URL of the OWL file or SPARQL Endpoint. + * @return True if a knowledge source was deleted, false otherwise. */ - public boolean removeKnowledgeSource(KnowledgeSource ks) { - return knowledgeSource.remove(ks); + public boolean removeKnowledgeSource(String url) { + Iterator<KnowledgeSource> it = knowledgeSources.iterator(); + while(it.hasNext()) { + KnowledgeSource source = it.next(); + if((source instanceof OWLFile && ((OWLFile)source).getURL().toString().equals(url)) + || (source instanceof SparqlEndpoint && ((SparqlEndpoint)source).getURL().toString().equals(url)) ) { + it.remove(); + return true; + } + } + return false; } /** @@ -96,10 +110,14 @@ } /** + * Sets the reasoner component and creates the corresponding + * <code>ReasoningService</code> instance. + * * @param reasonerComponent the reasonerComponent to set */ public void setReasonerComponent(ReasonerComponent reasonerComponent) { this.reasonerComponent = reasonerComponent; + reasoningService = new ReasoningService(reasonerComponent); } /** @@ -115,5 +133,12 @@ public void setLearningAlgorithm(LearningAlgorithm learningAlgorithm) { this.learningAlgorithm = learningAlgorithm; } + + /** + * @return the reasoningService + */ + public ReasoningService getReasoningService() { + return reasoningService; + } } Added: trunk/src/dl-learner/org/dllearner/server/UnknownComponentException.java =================================================================== --- trunk/src/dl-learner/org/dllearner/server/UnknownComponentException.java (rev 0) +++ trunk/src/dl-learner/org/dllearner/server/UnknownComponentException.java 2007-10-09 14:06:57 UTC (rev 203) @@ -0,0 +1,34 @@ +/** + * Copyright (C) 2007, 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.server; + +/** + * @author Jens Lehmann + * + */ +public class UnknownComponentException extends Exception { + + private static final long serialVersionUID = -8736552102773724529L; + + public UnknownComponentException(String component) { + super("Component " + component + " no known in this context."); + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |