use of com.hp.hpl.jena.reasoner.rulesys.Rule in project stanbol by apache.
the class RecipeInputProvider method getInput.
@SuppressWarnings("unchecked")
@Override
public <T> Iterator<T> getInput(Class<T> type) throws IOException {
ReasoningProvider reasoningProvider = null;
if (type.isAssignableFrom(SWRLRule.class)) {
reasoningProvider = ReasoningProvider.OWL2;
} else if (type.isAssignableFrom(Rule.class)) {
reasoningProvider = ReasoningProvider.Jena;
} else {
log.error("Cannot adapt to this type {}", type.getCanonicalName());
throw new UnsupportedOperationException("Cannot adapt to " + type.getCanonicalName());
}
switch(reasoningProvider) {
case OWL2:
List<SWRLRule> rules = null;
if (recipeId != null) {
long start = System.currentTimeMillis();
log.info("[start] Prepare rules for OWLApi ");
// If recipe exists, return it as a list of SWRL rules
rules = new ArrayList<SWRLRule>();
try {
Recipe recipe = null;
synchronized (store) {
try {
recipe = store.getRecipe(new IRI(recipeId));
} catch (RecipeConstructionException e) {
log.error("An error occurred while generating the recipe.", e);
}
}
log.debug("Recipe is: {}", recipe);
/*
* We ask to the adapter manager to get the right adapter in order to transform
* recipes into SWRLRule objects.
*/
RuleAdapter adapter;
try {
adapter = adapterManager.getAdapter(recipe, SWRLRule.class);
rules = (List<SWRLRule>) adapter.adaptTo(recipe, SWRLRule.class);
} catch (UnavailableRuleObjectException e) {
log.error(e.getMessage(), e);
} catch (RuleAtomCallExeption e) {
log.error(e.getMessage(), e);
} catch (UnsupportedTypeForExportException e) {
log.error(e.getMessage(), e);
}
/*
RuleList ruleList = recipe.getRuleList();
log.debug("RuleList is: {}",ruleList);
for(org.apache.stanbol.rules.base.api.Rule r : ruleList ){
SWRLRule swrl = r.toSWRL(OWLManager.getOWLDataFactory());
log.debug("Prepared rule: {}",swrl);
rules.add(swrl);
}*/
} catch (NoSuchRecipeException e) {
log.error("Recipe {} does not exists", recipeId);
throw new IOException(e);
}
long end = System.currentTimeMillis();
log.info("[end] Prepared {} rules for OWLApi in {} ms.", rules.size(), (end - start));
}
if (rules == null) {
log.error("No rules have been loaded");
throw new IOException("No rules loaded");
}
final Iterator<SWRLRule> iterator = Collections.unmodifiableList(rules).iterator();
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return (T) iterator.next();
}
@Override
public void remove() {
log.error("Cannot remove items from this iterator. This may be cused by an error in the program");
throw new UnsupportedOperationException("Cannot remove items from this iterator");
}
};
case Jena:
List<Rule> jenaRules = null;
if (recipeId != null) {
long start = System.currentTimeMillis();
log.info("[start] Prepare rules for Jena ");
try {
Recipe recipe = null;
synchronized (store) {
try {
recipe = store.getRecipe(new IRI(recipeId));
} catch (RecipeConstructionException e) {
log.error("An error occurred while generating the recipe.", e);
}
}
if (recipe != null) {
log.debug("Recipe is: {}", recipe);
/*
* We ask to the adapter manager to get the right adapter in order to transform
* recipes into Jena Rule objects.
*/
RuleAdapter adapter;
try {
adapter = adapterManager.getAdapter(recipe, Rule.class);
jenaRules = (List<Rule>) adapter.adaptTo(recipe, Rule.class);
} catch (UnavailableRuleObjectException e) {
log.error(e.getMessage(), e);
} catch (RuleAtomCallExeption e) {
log.error(e.getMessage(), e);
} catch (UnsupportedTypeForExportException e) {
log.error(e.getMessage(), e);
}
}
//jenaRules = recipe.toJenaRules();
} catch (NoSuchRecipeException e) {
log.error("Recipe {} does not exists", recipeId);
throw new IOException(e);
}
long end = System.currentTimeMillis();
log.info("[end] Prepared {} rules for Jena in {} ms.", jenaRules.size(), (end - start));
}
if (jenaRules == null) {
log.error("No rules have been loaded");
throw new IOException("No rules loaded");
}
final Iterator<Rule> jRiterator = Collections.unmodifiableList(jenaRules).iterator();
return new Iterator<T>() {
@Override
public boolean hasNext() {
return jRiterator.hasNext();
}
@Override
public T next() {
return (T) jRiterator.next();
}
@Override
public void remove() {
log.error("Cannot remove items from this iterator. This may be cused by an error in the program");
throw new UnsupportedOperationException("Cannot remove items from this iterator");
}
};
default:
return null;
}
}
use of com.hp.hpl.jena.reasoner.rulesys.Rule in project stanbol by apache.
the class ReasoningServiceExecutor method execute.
/**
* General method for execution, delegates to specific implementations.
*
* @param task
* @param service
* @param targetGraphID
* @param parameters
* @return
* @throws ReasoningServiceException
* @throws UnsupportedTaskException
* @throws InconsistentInputException
*/
private ReasoningServiceResult<?> execute(String task, ReasoningService<?, ?, ?> service, String targetGraphID, Map<String, List<String>> parameters) throws ReasoningServiceException, UnsupportedTaskException, InconsistentInputException {
long start = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
log.debug("[start] Execution: {}", service.getClass().getCanonicalName());
log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
log.debug("-----------------------------------------------------");
log.debug("execute()");
log.debug(" > task: {}", task);
log.debug(" > service: {}", service.getClass().getCanonicalName());
log.debug(" > target: {}", targetGraphID);
log.debug(" > parameters:");
for (Entry<String, List<String>> e : parameters.entrySet()) {
log.debug(" >> {}: {}", e.getKey());
for (String v : e.getValue()) {
log.debug(" >>> value: {}", v);
}
}
log.debug(" > input providers:");
for (ReasoningServiceInputProvider p : inmgr.getProviders()) {
log.debug(" >> {}", p.getClass().getCanonicalName());
}
log.debug("-----------------------------------------------------");
}
ReasoningServiceResult<?> result = null;
/**
* TODO Switch this into the ReasoningService implementation
*/
if (service instanceof JenaReasoningService) {
Model input = ModelFactory.createDefaultModel();
synchronized (inmgr) {
Iterator<Statement> statements = inmgr.getInputData(Statement.class);
while (statements.hasNext()) {
input.add(statements.next());
}
}
List<Rule> rules = null;
synchronized (inmgr) {
Iterator<Rule> rulesI = inmgr.getInputData(Rule.class);
while (rulesI.hasNext()) {
Rule o = rulesI.next();
log.debug("Rule: {}", o);
if (rules == null) {
rules = new ArrayList<Rule>();
}
rules.add(o);
}
}
if (log.isDebugEnabled()) {
log.debug("Input size is {} statements", input.listStatements().toSet().size());
}
result = executeJenaReasoningService(task, (JenaReasoningService) service, input, rules, targetGraphID, true, parameters);
} else if (service instanceof OWLApiReasoningService) {
OWLOntology input;
try {
input = OWLManager.createOWLOntologyManager().createOntology();
} catch (OWLOntologyCreationException e) {
throw new ReasoningServiceException(e);
}
synchronized (inmgr) {
Iterator<OWLAxiom> statements = inmgr.getInputData(OWLAxiom.class);
while (statements.hasNext()) {
input.getOWLOntologyManager().addAxiom(input, statements.next());
}
}
// FIXME Please check if this is really necessary!!!
input = input.getOWLOntologyManager().getOntology(input.getOntologyID());
List<SWRLRule> rules = null;
synchronized (inmgr) {
Iterator<SWRLRule> rulesI = inmgr.getInputData(SWRLRule.class);
while (rulesI.hasNext()) {
if (rules == null) {
rules = new ArrayList<SWRLRule>();
}
rules.add(rulesI.next());
}
}
if (log.isDebugEnabled()) {
log.debug("Input size is {} statements", input.getAxiomCount());
}
result = executeOWLApiReasoningService(task, (OWLApiReasoningService) service, input, rules, targetGraphID, true, parameters);
} else
throw new UnsupportedOperationException("Service implementation not supported!");
if (log.isDebugEnabled()) {
log.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
long end = System.currentTimeMillis();
log.debug("[end] In time: {}ms", (end - start));
log.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
}
return result;
}
use of com.hp.hpl.jena.reasoner.rulesys.Rule in project stanbol by apache.
the class TestUtils method parseRuleStringAsFile.
/**
* This utility gets a jena rules file content string and parse it to return
* a List of Rule objects
*
* @param source
* @return
*/
public static List<Rule> parseRuleStringAsFile(String source) {
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(source.getBytes())));
Rule.Parser parser = Rule.rulesParserFromReader(br);
List<Rule> rules = Rule.parseRules(parser);
return rules;
}
use of com.hp.hpl.jena.reasoner.rulesys.Rule in project stanbol by apache.
the class JenaReasoningServiceTest method testRunWithRules.
/**
* Tests the run(Model,List<Rule>) method of a service
*
* @param service
*/
private void testRunWithRules(JenaReasoningService service) {
// Prepare the rule set
String source = "" + "\n@prefix foaf: <" + TestData.FOAF_NS + ">." + "\n@prefix ex: <" + TestData.TEST_NS + ">." + "\n[rule1: (?a foaf:knows ?b) (?a foaf:workplaceHomepage ?w) (?b foaf:workplaceHomepage ?w) -> (?a ex:collegueOf ?b)] " + "\n[rule2: (?b foaf:knows ?a) -> (?a foaf:knows ?b)] " + "\n[rule3: (?a ex:collegueOf ?b) -> (?b ex:collegueOf ?a)] ";
// log.info("This is the ruleset: \n {}", source);
List<Rule> rules = TestUtils.parseRuleStringAsFile(source);
log.info("Loaded {} rules", rules.size());
// Clean data
TestData.alexdma.removeProperties();
TestData.enridaga.removeProperties();
Resource wphomepage = TestData.model.createResource("http://stlab.istc.cnr.it");
// Prepare data
TestData.alexdma.addProperty(TestData.foaf_knows, TestData.enridaga);
TestData.alexdma.addProperty(TestData.foaf_workplaceHomepage, wphomepage);
TestData.enridaga.addProperty(TestData.foaf_workplaceHomepage, wphomepage);
// Setup input for the reasoner
Model input = ModelFactory.createUnion(TestData.enridaga.getModel(), TestData.alexdma.getModel());
input = ModelFactory.createUnion(input, TestData.foaf);
// Run the method
Set<Statement> inferred = service.run(input, rules).listStatements().toSet();
// Expected statements
Property collegueOf = TestData.model.createProperty(TestData.TEST_NS + "collegueOf");
Set<Statement> expected = new HashSet<Statement>();
expected.add(TestData.model.createStatement(TestData.alexdma, collegueOf, TestData.enridaga));
expected.add(TestData.model.createStatement(TestData.enridaga, collegueOf, TestData.alexdma));
log.info("All the expected statements must be in the inferred output");
Set<Statement> notInOutput = TestUtils.expectedStatementsCheck(inferred, expected);
log.info("Are all expected statements in the inferred set (true)? {}", notInOutput.isEmpty());
if (!notInOutput.isEmpty()) {
for (Statement bad : notInOutput) {
log.error("The following statement is not included in the reasoner output: {}", bad);
}
}
assertTrue(notInOutput.isEmpty());
// Clean data
TestData.alexdma.removeProperties();
TestData.enridaga.removeProperties();
}
use of com.hp.hpl.jena.reasoner.rulesys.Rule in project stanbol by apache.
the class JenaReasoningServiceTest method testClassifyWithRule.
/**
* Tests the classify(Model data, List<Rule> rules) method
*/
private void testClassifyWithRule(JenaReasoningService service) {
log.info("Testing {}", service.getClass());
// Prepare the rule set
String source = "" + "\n@prefix rdf: <" + RDF.getURI() + ">." + "\n@prefix foaf: <" + TestData.FOAF_NS + ">." + "\n@prefix ex: <" + TestData.TEST_NS + ">." + "\n[rule: (?a foaf:workplaceHomepage ?w) (?w rdf:type ex:SWResearchLab) -> (?a rdf:type ex:SWResearcher)] ";
// log.info("This is the ruleset: \n {}", source);
List<Rule> rules = TestUtils.parseRuleStringAsFile(source);
log.info("Loaded {} rules", rules.size());
// Clean data
TestData.alexdma.removeProperties();
TestData.enridaga.removeProperties();
Resource wphomepage = TestData.model.createResource("http://stlab.istc.cnr.it");
Resource swResearchLab = TestData.model.createResource(TestData.TEST_NS + "SWResearchLab");
// Prepare data
TestData.alexdma.addProperty(TestData.foaf_workplaceHomepage, wphomepage);
TestData.enridaga.addProperty(TestData.foaf_workplaceHomepage, wphomepage);
wphomepage.addProperty(RDF.type, swResearchLab);
// Setup input for the reasoner
Model input = ModelFactory.createUnion(TestData.enridaga.getModel(), TestData.alexdma.getModel());
input = ModelFactory.createUnion(input, wphomepage.getModel());
input = ModelFactory.createUnion(input, TestData.foaf);
try {
// Run the method
Set<Statement> inferred = service.runTask(ReasoningService.Tasks.CLASSIFY, input, rules, false, null);
// Expected statements
Resource swResearcher = TestData.model.createResource(TestData.TEST_NS + "SWResearcher");
Set<Statement> expected = new HashSet<Statement>();
expected.add(TestData.model.createStatement(TestData.alexdma, RDF.type, swResearcher));
expected.add(TestData.model.createStatement(TestData.enridaga, RDF.type, swResearcher));
log.info("All the expected statements must be in the inferred output");
Set<Statement> notInOutput = TestUtils.expectedStatementsCheck(inferred, expected);
log.info("Are all expected statements in the inferred set (true)? {}", notInOutput.isEmpty());
if (!notInOutput.isEmpty()) {
for (Statement bad : notInOutput) {
log.error("The following statement is not included in the reasoner output: {}", bad);
}
}
assertTrue(notInOutput.isEmpty());
// There must be only rdf:type output
boolean onlyRdf = true;
for (Statement stat : inferred) {
// Here we want only rdf:type statements
if (!stat.getPredicate().equals(RDF.type)) {
log.error("This statement is not rdf:type: {}", stat);
}
if (!stat.getPredicate().equals(RDF.type)) {
onlyRdf = false;
}
}
log.info("Check for statements to be rdf:type only (true): {}", onlyRdf);
assertTrue(onlyRdf);
} catch (ReasoningServiceException e) {
log.error("Error thrown: {}", e);
assertTrue(false);
} catch (InconsistentInputException e) {
log.error("Error thrown: {}", e);
assertTrue(false);
} catch (UnsupportedTaskException e) {
log.error("Error thrown: {}", e);
assertTrue(false);
}
// Clean data
TestData.alexdma.removeProperties();
TestData.enridaga.removeProperties();
}
Aggregations