Search in sources :

Example 1 with SWRLRule

use of org.semanticweb.owlapi.model.SWRLRule 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;
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) Recipe(org.apache.stanbol.rules.base.api.Recipe) NoSuchRecipeException(org.apache.stanbol.rules.base.api.NoSuchRecipeException) UnavailableRuleObjectException(org.apache.stanbol.rules.base.api.UnavailableRuleObjectException) IOException(java.io.IOException) RecipeConstructionException(org.apache.stanbol.rules.base.api.RecipeConstructionException) UnsupportedTypeForExportException(org.apache.stanbol.rules.base.api.UnsupportedTypeForExportException) Iterator(java.util.Iterator) SWRLRule(org.semanticweb.owlapi.model.SWRLRule) SWRLRule(org.semanticweb.owlapi.model.SWRLRule) Rule(com.hp.hpl.jena.reasoner.rulesys.Rule) RuleAtomCallExeption(org.apache.stanbol.rules.base.api.RuleAtomCallExeption) RuleAdapter(org.apache.stanbol.rules.base.api.RuleAdapter)

Example 2 with SWRLRule

use of org.semanticweb.owlapi.model.SWRLRule 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;
}
Also used : JenaReasoningService(org.apache.stanbol.reasoners.jena.JenaReasoningService) Statement(com.hp.hpl.jena.rdf.model.Statement) ArrayList(java.util.ArrayList) OWLApiReasoningService(org.apache.stanbol.reasoners.owlapi.OWLApiReasoningService) ReasoningServiceException(org.apache.stanbol.reasoners.servicesapi.ReasoningServiceException) ReasoningServiceInputProvider(org.apache.stanbol.reasoners.servicesapi.ReasoningServiceInputProvider) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) Model(com.hp.hpl.jena.rdf.model.Model) Iterator(java.util.Iterator) SWRLRule(org.semanticweb.owlapi.model.SWRLRule) ArrayList(java.util.ArrayList) List(java.util.List) SWRLRule(org.semanticweb.owlapi.model.SWRLRule) Rule(com.hp.hpl.jena.reasoner.rulesys.Rule) OWLAxiom(org.semanticweb.owlapi.model.OWLAxiom)

Example 3 with SWRLRule

use of org.semanticweb.owlapi.model.SWRLRule in project stanbol by apache.

the class SWRLAdapter method adaptRecipeTo.

@SuppressWarnings("unchecked")
@Override
protected <T> T adaptRecipeTo(Recipe recipe, Class<T> type) throws RuleAtomCallExeption, UnsupportedTypeForExportException, UnavailableRuleObjectException {
    List<SWRLRule> swrlRules = null;
    if (type == SWRLRule.class) {
        RuleList ruleList = recipe.getRuleList();
        swrlRules = new ArrayList<SWRLRule>();
        if (ruleList != null && !ruleList.isEmpty()) {
            Iterator<Rule> ruleIterator = ruleList.iterator();
            while (ruleIterator.hasNext()) {
                Rule rule = ruleIterator.next();
                swrlRules.add(adaptRuleTo(rule, SWRLRule.class));
            }
        }
    } else {
        throw new UnsupportedTypeForExportException("The SPARQL Export Provider does not support the selected serialization : " + type.getCanonicalName());
    }
    return (T) swrlRules;
}
Also used : RuleList(org.apache.stanbol.rules.base.api.util.RuleList) UnsupportedTypeForExportException(org.apache.stanbol.rules.base.api.UnsupportedTypeForExportException) SWRLRule(org.semanticweb.owlapi.model.SWRLRule) Rule(org.apache.stanbol.rules.base.api.Rule) SWRLRule(org.semanticweb.owlapi.model.SWRLRule)

Example 4 with SWRLRule

use of org.semanticweb.owlapi.model.SWRLRule in project stanbol by apache.

the class AbstractOWLApiReasoningService method isConsistent.

/**
     * Only check consistency.
     * 
     * Subclasses may want to change how.
     * 
     * @param ontology
     * @param rules
     * @return
     * @throws ReasoningServiceException
     */
@Override
public boolean isConsistent(OWLOntology ontology, List<SWRLRule> rules) throws ReasoningServiceException {
    log.debug("Create a input ontology to merge rules in.");
    OWLOntology input;
    try {
        OWLOntologyManager manager = createOWLOntologyManager();
        input = manager.createOntology();
        Set<SWRLRule> ruleSet = new HashSet<SWRLRule>();
        ruleSet.addAll(rules);
        manager.addAxioms(input, ruleSet);
        input = manager.getOntology(input.getOntologyID());
        log.debug("Created ontology: {}", input);
        return getReasoner(ontology).isConsistent();
    } catch (OWLOntologyCreationException e) {
        log.error("An error have been thrown while attempting to create ontology. Message was: {}", e.getLocalizedMessage());
        // TODO Add explanation of this exception
        throw new ReasoningServiceException();
    }
}
Also used : ReasoningServiceException(org.apache.stanbol.reasoners.servicesapi.ReasoningServiceException) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) SWRLRule(org.semanticweb.owlapi.model.SWRLRule) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) HashSet(java.util.HashSet)

Example 5 with SWRLRule

use of org.semanticweb.owlapi.model.SWRLRule in project stanbol by apache.

the class HermitReasoningServiceTest method testClassifyWithRules.

private void testClassifyWithRules(String testID, String rulesID, String testExpectedID) {
    log.info("Testing the task CLASSIFY with rules");
    OWLOntologyManager manager = TestData.manager;
    // We prepare the input ontology
    try {
        OWLOntology testOntology = manager.createOntology();
        OWLOntologyID testOntologyID = testOntology.getOntologyID();
        log.debug("Created test ontology with ID: {}", testOntologyID);
        OWLImportsDeclaration importTest = TestData.factory.getOWLImportsDeclaration(IRI.create(testID));
        manager.applyChange(new AddImport(testOntology, importTest));
        Set<SWRLRule> rules = manager.getOntology(IRI.create(rulesID)).getAxioms(AxiomType.SWRL_RULE);
        // Maybe we want to see the list of rules
        if (log.isDebugEnabled()) {
            log.debug("List of {} rules: ", rules.size());
            TestUtils.debug(rules, log);
        }
        log.debug("We add the rules to the ontology");
        manager.addAxioms(manager.getOntology(testOntologyID), rules);
        // Maybe we want to see what is in before
        if (log.isDebugEnabled())
            log.debug("Content of the input is:");
        TestUtils.debug(manager.getOntology(testOntologyID), log);
        // Now we test the method
        log.debug("Running HermiT");
        Set<OWLAxiom> inferred = this.theinstance.runTask(ReasoningService.Tasks.CLASSIFY, manager.getOntology(testOntologyID));
        // Maybe we want to see the inferred axiom list
        if (log.isDebugEnabled()) {
            log.debug("{} inferred axioms:", inferred.size());
            TestUtils.debug(inferred, log);
        }
        Set<OWLLogicalAxiom> expectedAxioms = manager.getOntology(IRI.create(testExpectedID)).getLogicalAxioms();
        Set<OWLAxiom> missing = new HashSet<OWLAxiom>();
        for (OWLAxiom expected : expectedAxioms) {
            // We consider here only two kind of axioms
            if (expected instanceof OWLSubClassOfAxiom || expected instanceof OWLClassAssertionAxiom) {
                if (!inferred.contains(expected)) {
                    log.error("missing expected axiom: {}", expected);
                    missing.add(expected);
                }
            }
        }
        assertTrue(missing.isEmpty());
        // We want to remove the ontology from the manager
        manager.removeOntology(testOntology);
    } catch (OWLOntologyCreationException e) {
        log.error("An {} have been thrown while creating the input ontology for test", e.getClass());
        assertTrue(false);
    } catch (ReasoningServiceException e) {
        log.error("An {} have been thrown while executing the reasoning", e.getClass());
        assertTrue(false);
    } catch (InconsistentInputException e) {
        log.error("An {} have been thrown while executing the reasoning", e.getClass());
        assertTrue(false);
    } catch (UnsupportedTaskException e) {
        log.error("An {} have been thrown while executing the reasoning", e.getClass());
        assertTrue(false);
    }
}
Also used : OWLLogicalAxiom(org.semanticweb.owlapi.model.OWLLogicalAxiom) OWLImportsDeclaration(org.semanticweb.owlapi.model.OWLImportsDeclaration) InconsistentInputException(org.apache.stanbol.reasoners.servicesapi.InconsistentInputException) AddImport(org.semanticweb.owlapi.model.AddImport) UnsupportedTaskException(org.apache.stanbol.reasoners.servicesapi.UnsupportedTaskException) ReasoningServiceException(org.apache.stanbol.reasoners.servicesapi.ReasoningServiceException) OWLSubClassOfAxiom(org.semanticweb.owlapi.model.OWLSubClassOfAxiom) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) SWRLRule(org.semanticweb.owlapi.model.SWRLRule) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLAxiom(org.semanticweb.owlapi.model.OWLAxiom) OWLClassAssertionAxiom(org.semanticweb.owlapi.model.OWLClassAssertionAxiom) HashSet(java.util.HashSet)

Aggregations

SWRLRule (org.semanticweb.owlapi.model.SWRLRule)8 HashSet (java.util.HashSet)4 ReasoningServiceException (org.apache.stanbol.reasoners.servicesapi.ReasoningServiceException)4 OWLAxiom (org.semanticweb.owlapi.model.OWLAxiom)4 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)4 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)4 OWLOntologyManager (org.semanticweb.owlapi.model.OWLOntologyManager)4 UnsupportedTypeForExportException (org.apache.stanbol.rules.base.api.UnsupportedTypeForExportException)3 Rule (com.hp.hpl.jena.reasoner.rulesys.Rule)2 Iterator (java.util.Iterator)2 List (java.util.List)2 InconsistentInputException (org.apache.stanbol.reasoners.servicesapi.InconsistentInputException)2 UnsupportedTaskException (org.apache.stanbol.reasoners.servicesapi.UnsupportedTaskException)2 RuleAtomCallExeption (org.apache.stanbol.rules.base.api.RuleAtomCallExeption)2 UnavailableRuleObjectException (org.apache.stanbol.rules.base.api.UnavailableRuleObjectException)2 AddImport (org.semanticweb.owlapi.model.AddImport)2 OWLImportsDeclaration (org.semanticweb.owlapi.model.OWLImportsDeclaration)2 OWLLogicalAxiom (org.semanticweb.owlapi.model.OWLLogicalAxiom)2 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)2 Model (com.hp.hpl.jena.rdf.model.Model)1