Search in sources :

Example 21 with OWLOntologyManager

use of org.semanticweb.owlapi.model.OWLOntologyManager 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 22 with OWLOntologyManager

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

the class ClerezzaOntologyProvider method toOWLOntology.

/**
 * @param graphName
 * @param forceMerge
 *            if set to false, the selected import management policy will be applied.
 * @return
 * @throws OWLOntologyCreationException
 */
protected OWLOntology toOWLOntology(IRI graphName, boolean forceMerge) throws OWLOntologyCreationException {
    log.debug("Exporting graph to OWLOntology");
    log.debug(" -- ImmutableGraph name : {}", graphName);
    OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
    // Never try to import
    mgr.addIRIMapper(new PhonyIRIMapper(Collections.<org.semanticweb.owlapi.model.IRI>emptySet()));
    Set<OWLOntologyID> loaded = new HashSet<OWLOntologyID>();
    Graph graph = store.getGraph(graphName);
    IRI ontologyId = null;
    // Get the id of this ontology.
    Iterator<Triple> itt = graph.filter(null, RDF.type, OWL.Ontology);
    if (itt.hasNext()) {
        BlankNodeOrIRI nl = itt.next().getSubject();
        if (nl instanceof IRI)
            ontologyId = (IRI) nl;
    }
    List<OWLOntologyID> revImps = new Stack<OWLOntologyID>();
    List<OWLOntologyID> lvl1 = new Stack<OWLOntologyID>();
    fillImportsReverse(keymap.getReverseMapping(graphName), revImps, lvl1);
    // If not set to merge (either by policy of by force), adopt the set import policy.
    if (!forceMerge && !ImportManagementPolicy.MERGE.equals(getImportManagementPolicy())) {
        OWLOntology o = OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(graph, mgr);
        // TODO make it not flat.
        // Examining the reverse imports stack will flatten all imports.
        List<OWLOntologyChange> changes = new ArrayList<OWLOntologyChange>();
        OWLDataFactory df = OWLManager.getOWLDataFactory();
        List<OWLOntologyID> listToUse;
        switch(getImportManagementPolicy()) {
            case FLATTEN:
                listToUse = revImps;
                break;
            case PRESERVE:
                listToUse = lvl1;
                break;
            default:
                listToUse = lvl1;
                break;
        }
        for (OWLOntologyID ref : listToUse) if (!loaded.contains(ref) && !ref.equals(keymap.getReverseMapping(graphName))) {
            changes.add(new AddImport(o, df.getOWLImportsDeclaration(ref.getOntologyIRI())));
            loaded.add(ref);
        }
        o.getOWLOntologyManager().applyChanges(changes);
        return o;
    } else {
        // If there is just the root ontology, convert it straight away.
        if (revImps.size() == 1 && revImps.contains(graphName)) {
            OWLOntology o = OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(graph, mgr);
            return o;
        }
        // FIXME when there's more than one ontology, this way of merging them seems inefficient...
        Graph tempGraph = new IndexedGraph();
        // The set of triples that will be excluded from the merge
        Set<Triple> exclusions = new HashSet<Triple>();
        // Examine all reverse imports
        for (OWLOntologyID ref : revImps) if (!loaded.contains(ref)) {
            // Get the triples
            Graph imported = // store.getTriples(ref);
            getStoredOntology(getKey(ref), Graph.class, false);
            // For each owl:Ontology
            Iterator<Triple> remove = imported.filter(null, RDF.type, OWL.Ontology);
            while (remove.hasNext()) {
                BlankNodeOrIRI subj = remove.next().getSubject();
                /*
                         * If it's not the root ontology, trash all its triples. If the root ontology is
                         * anonymous, all ontology annotations are to be trashed without distinction.
                         */
                if (ontologyId == null || !subj.equals(ontologyId)) {
                    Iterator<Triple> it = imported.filter(subj, null, null);
                    while (it.hasNext()) {
                        Triple t = it.next();
                        exclusions.add(t);
                    }
                }
            }
            Iterator<Triple> it = imported.iterator();
            while (it.hasNext()) {
                Triple t = it.next();
                if (!exclusions.contains(t))
                    tempGraph.add(t);
            }
            loaded.add(ref);
        }
        // online.
        return OWLAPIToClerezzaConverter.clerezzaGraphToOWLOntology(tempGraph, mgr);
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) ArrayList(java.util.ArrayList) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) AddImport(org.semanticweb.owlapi.model.AddImport) Stack(java.util.Stack) Triple(org.apache.clerezza.commons.rdf.Triple) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) OWLOntologyChange(org.semanticweb.owlapi.model.OWLOntologyChange) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) PhonyIRIMapper(org.apache.stanbol.commons.owl.PhonyIRIMapper) Iterator(java.util.Iterator) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLDataFactory(org.semanticweb.owlapi.model.OWLDataFactory) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) HashSet(java.util.HashSet)

Example 23 with OWLOntologyManager

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

the class AbstractOntologyCollectorImpl method exportToOWLOntology.

/**
 * This method has no conversion calls, to it can be invoked by subclasses that wish to modify it
 * afterwards.
 *
 * FIXME not merging yet FIXME not including imported ontologies unless they are merged *before* storage.
 *
 * @param merge
 * @return
 */
protected OWLOntology exportToOWLOntology(boolean merge, org.semanticweb.owlapi.model.IRI prefix) {
    long before = System.currentTimeMillis();
    // Create a new ontology
    OWLOntology root;
    OWLOntologyManager ontologyManager = OWLManager.createOWLOntologyManager();
    org.semanticweb.owlapi.model.IRI iri = org.semanticweb.owlapi.model.IRI.create(prefix + _id);
    try {
        root = ontologyManager.createOntology(iri);
    } catch (OWLOntologyAlreadyExistsException e) {
        // It should be impossible, but just in case.
        ontologyManager.removeOntology(ontologyManager.getOntology(iri));
        try {
            root = ontologyManager.createOntology(iri);
        } catch (OWLOntologyAlreadyExistsException e1) {
            root = ontologyManager.getOntology(iri);
        } catch (OWLOntologyCreationException e1) {
            log.error("Failed to assemble root ontology for scope " + iri, e);
            root = null;
        }
    } catch (OWLOntologyCreationException e) {
        log.error("Failed to assemble root ontology for scope " + _id, e);
        root = null;
    }
    // Add the import declarations for directly managed ontologies.
    if (root != null) {
        if (merge) {
            final Set<OWLOntology> set = new HashSet<OWLOntology>();
            log.debug("Merging {} with its imports.", root);
            set.add(root);
            for (OWLOntologyID ontologyId : managedOntologies) {
                log.debug("Merging {} with {}.", ontologyId, root);
                set.add(getOntology(ontologyId, OWLOntology.class, true));
            }
            OWLOntologySetProvider provider = new OWLOntologySetProvider() {

                @Override
                public Set<OWLOntology> getOntologies() {
                    return set;
                }
            };
            OWLOntologyMerger merger = new OWLOntologyMerger(provider);
            try {
                root = merger.createMergedOntology(OWLManager.createOWLOntologyManager(), iri);
            } catch (OWLOntologyCreationException e) {
                log.error("Failed to merge imports for ontology " + iri, e);
                root = null;
            }
        } else {
            // Add the import declarations for directly managed ontologies.
            List<OWLOntologyChange> changes = new LinkedList<OWLOntologyChange>();
            OWLDataFactory df = ontologyManager.getOWLDataFactory();
            String base = prefix + getID();
            for (int i = 0; i < backwardPathLength; i++) base = URIUtils.upOne(URI.create(base)).toString();
            base += "/";
            // The key set of managedOntologies contains the ontology IRIs, not their storage keys.
            for (OWLOntologyID ontologyId : managedOntologies) {
                // XXX some day the versionIRI will be the only physical reference for the ontology
                org.semanticweb.owlapi.model.IRI physIRI = org.semanticweb.owlapi.model.IRI.create(base + OntologyUtils.encode(ontologyId));
                changes.add(new AddImport(root, df.getOWLImportsDeclaration(physIRI)));
            }
            ontologyManager.applyChanges(changes);
        }
    }
    log.debug("OWL export of {} completed in {} ms.", getID(), System.currentTimeMillis() - before);
    return root;
}
Also used : OWLOntologyMerger(org.semanticweb.owlapi.util.OWLOntologyMerger) AddImport(org.semanticweb.owlapi.model.AddImport) OWLOntologyAlreadyExistsException(org.semanticweb.owlapi.model.OWLOntologyAlreadyExistsException) LinkedList(java.util.LinkedList) OWLOntologySetProvider(org.semanticweb.owlapi.model.OWLOntologySetProvider) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntologyChange(org.semanticweb.owlapi.model.OWLOntologyChange) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLDataFactory(org.semanticweb.owlapi.model.OWLDataFactory) HashSet(java.util.HashSet)

Example 24 with OWLOntologyManager

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

the class ScopeImpl method exportToOWLOntology.

/**
 * Get an OWL API {@link OWLOntology} representation of the scope.
 *
 * @param merge
 *            if true the core and custom spaces will be recursively merged with the scope ontology,
 *            otherwise owl:imports statements will be added.
 * @return the OWL representation of the scope.
 */
protected OWLOntology exportToOWLOntology(boolean merge, org.semanticweb.owlapi.model.IRI universalPrefix) {
    // if (merge) throw new UnsupportedOperationException(
    // "Ontology merging only implemented for managed ontologies, not for collectors. "
    // + "Please set merge parameter to false.");
    // Create an ontology manager on the fly. We don't really need a permanent one.
    OWLOntologyManager mgr = OWLManager.createOWLOntologyManager();
    OWLDataFactory df = mgr.getOWLDataFactory();
    OWLOntology ont = null;
    try {
        if (merge) {
            final Set<OWLOntology> set = new HashSet<OWLOntology>();
            log.debug("Merging custom space of {}.", getID());
            set.add(this.getCustomSpace().export(OWLOntology.class, merge));
            log.debug("Merging core space of {}.", getID());
            set.add(this.getCoreSpace().export(OWLOntology.class, merge));
            OWLOntologySetProvider provider = new OWLOntologySetProvider() {

                @Override
                public Set<OWLOntology> getOntologies() {
                    return set;
                }
            };
            OWLOntologyMerger merger = new OWLOntologyMerger(provider);
            try {
                ont = merger.createMergedOntology(OWLManager.createOWLOntologyManager(), org.semanticweb.owlapi.model.IRI.create(getDefaultNamespace() + getID()));
            } catch (OWLOntologyCreationException e) {
                log.error("Failed to merge imports for ontology.", e);
                ont = null;
            }
        } else {
            // The root ontology ID is in the form [namespace][scopeId]
            ont = mgr.createOntology(org.semanticweb.owlapi.model.IRI.create(universalPrefix + getID()));
            List<OWLOntologyChange> additions = new LinkedList<OWLOntologyChange>();
            // Add the import statement for the custom space, if existing and not empty
            OntologySpace spc = getCustomSpace();
            if (spc != null && spc.listManagedOntologies().size() > 0) {
                org.semanticweb.owlapi.model.IRI spaceIri = org.semanticweb.owlapi.model.IRI.create(universalPrefix + spc.getID());
                additions.add(new AddImport(ont, df.getOWLImportsDeclaration(spaceIri)));
            }
            // Add the import statement for the core space, if existing and not empty
            spc = getCoreSpace();
            if (spc != null && spc.listManagedOntologies().size() > 0) {
                org.semanticweb.owlapi.model.IRI spaceIri = org.semanticweb.owlapi.model.IRI.create(universalPrefix + spc.getID());
                additions.add(new AddImport(ont, df.getOWLImportsDeclaration(spaceIri)));
            }
            mgr.applyChanges(additions);
        }
    } catch (OWLOntologyCreationException e) {
        log.error("Failed to generate an OWL form of scope " + getID(), e);
        ont = null;
    }
    return ont;
}
Also used : OWLOntologyMerger(org.semanticweb.owlapi.util.OWLOntologyMerger) AddImport(org.semanticweb.owlapi.model.AddImport) LinkedList(java.util.LinkedList) OWLOntologySetProvider(org.semanticweb.owlapi.model.OWLOntologySetProvider) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OWLOntologyChange(org.semanticweb.owlapi.model.OWLOntologyChange) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OntologySpace(org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) OWLDataFactory(org.semanticweb.owlapi.model.OWLDataFactory) HashSet(java.util.HashSet)

Example 25 with OWLOntologyManager

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

the class TestOntologyReconciliation method anonymousFromURLWithCustomKeys.

/*
     * If an anonymous ontology is loaded from a URL and at least one override is provided, the first override
     * should be the primary key, while everything else, including the URL, should be an alias for that key.
     */
@Test
public void anonymousFromURLWithCustomKeys() throws Exception {
    OWLOntologyID myKey = new OWLOntologyID(IRI.create("nameless"), IRI.create(getClass().getCanonicalName() + "#anonymousFromURLWithCustomKeys()"));
    OWLOntologyID alias = new OWLOntologyID(IRI.create("nameless"), IRI.create(getClass().getCanonicalName() + "#anonymousFromURLWithCustomKeys().alias"));
    URL url = getClass().getResource(location_nameless);
    OWLOntologyManager onMgr = OWLManager.createOWLOntologyManager();
    OWLOntology o1 = onMgr.loadOntologyFromOntologyDocument(IRI.create(url));
    assertTrue(o1.isAnonymous());
    OWLOntologyID key = ontologyProvider.loadInStore(IRI.create(url), RDF_XML, false, Origin.create(myKey), Origin.create(alias));
    assertNotNull(key);
    assertFalse(key.isAnonymous());
    assertEquals(myKey, key);
    log.info("Anonymous ontology loaded with non-anonymous public key {} (submitted)", key);
    // should have 2 aliases: the physical location and the submitted alias.
    assertEquals(2, ontologyProvider.listAliases(key).size());
    for (OWLOntologyID al : ontologyProvider.listAliases(key)) {
        assertFalse(al.isAnonymous());
        log.info("Named alias detected {}", al);
    }
    // Now retrieve using the alias...
    OWLOntology o2 = ontologyProvider.getStoredOntology(alias, OWLOntology.class, false);
    assertTrue(o2.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(o1.getAxioms(), o2.getAxioms());
    // ... and using the physical IRI
    o2 = ontologyProvider.getStoredOntology(new OWLOntologyID(IRI.create(url)), OWLOntology.class, false);
    assertTrue(o2.isAnonymous());
    // Cannot equal OWLOntology objects
    assertEquals(o1.getAxioms(), o2.getAxioms());
}
Also used : OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) OWLOntology(org.semanticweb.owlapi.model.OWLOntology) OWLOntologyManager(org.semanticweb.owlapi.model.OWLOntologyManager) URL(java.net.URL) Test(org.junit.Test)

Aggregations

OWLOntologyManager (org.semanticweb.owlapi.model.OWLOntologyManager)82 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)52 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)41 OWLDataFactory (org.semanticweb.owlapi.model.OWLDataFactory)23 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)21 OWLAxiom (org.semanticweb.owlapi.model.OWLAxiom)17 HashSet (java.util.HashSet)13 IRI (org.semanticweb.owlapi.model.IRI)13 AddImport (org.semanticweb.owlapi.model.AddImport)12 OWLClass (org.semanticweb.owlapi.model.OWLClass)12 Test (org.junit.Test)11 ReasoningServiceException (org.apache.stanbol.reasoners.servicesapi.ReasoningServiceException)10 OWLObjectProperty (org.semanticweb.owlapi.model.OWLObjectProperty)10 OntModel (com.hp.hpl.jena.ontology.OntModel)9 InputStream (java.io.InputStream)9 OWLDataProperty (org.semanticweb.owlapi.model.OWLDataProperty)9 OWLOntologyStorageException (org.semanticweb.owlapi.model.OWLOntologyStorageException)9 ArrayList (java.util.ArrayList)8 InconsistentInputException (org.apache.stanbol.reasoners.servicesapi.InconsistentInputException)8 OWLOntologyChange (org.semanticweb.owlapi.model.OWLOntologyChange)8