Why OWLReasoner.getSubclasses(...) returns http://www.w3.org/2002/07/owl#Nothing? - owl

Here is a piece of my ontology subclasses request, using JAVA-7 and owlapi library:
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import org.semanticweb.owlapi.reasoner.ConsoleProgressMonitor;
import org.semanticweb.owlapi.reasoner.OWLReasonerConfiguration;
...
...
OWLReasonerFactory reasonerFactory = new StructuralReasonerFactory();
ConsoleProgressMonitor progressMonitor = new ConsoleProgressMonitor();
OWLReasonerConfiguration config = new SimpleConfiguration(myconfiguration);
OWLReasoner reasoner = reasonerFactory.createReasoner(myontology, config);
Set<OWLClass> subclasses = reasoner.getSubClasses(myClazz, true).getFlattened();
Here is my question:
Why does the subclasses, what OWLReasoner.getSubClasses(...) method returns, contains all the subclasses of myClazz, but always also adds the OWLClass with URI http://www.w3.org/2002/07/owl#Nothing? I have defined nowhere this class.
Thanks in advance.

owl:Nothing is the class defined to be subclass of all classes in OWL, so it's included as subclass of all satisfiable classes (it is equivalent to all unsatisfiable classes).
To skip it during iterations, Node has a getEntitiesMinusBottom() method that will skip owl:Nothing.
At w3.org owl semantics, you can find more info about the owl:Nothing class: https://www.w3.org/TR/2004/REC-owl-semantics-20040210/#owl_Nothing

Related

Check OWL Class

Suppose the range of an object property is defined through a class expression. I want to know whether a particular instance of the class can be used in the range of the object property. Is it possible to use the OWL API and check if a particular class is subsumed by this class expression ?
OWLAPI cannot provide a complete answer for this - an OWLReasoner implementation is necessary for complete results.
Given an implementation of OWLReasoner, to check entailment you can either list all the subclasses of a class expression and check if the class you're interested in appears in the response, or ask the reasoner if your class of interest is a subclass, i.e.,
OWLDataFactory df = ...
OWLClassExpression ce = ...
OWLClass c = ...
OWLReasoner r = ...
OWLAxiom ax = df.getOWLObjectSubClassOf(c, ce);
boolean cIsSubclassOfCE = r.isEntailed(ax);

Datastore query without model class

I recently encountered a situation where one might want to run a datastore query which includes a kind, but the class of the corresponding model is not available (e.g. if it's defined in a module that hasn't been imported yet).
I couldn't find any out-of-the-box way to do this using the google.appengine.ext.db package, so I ended up using the google.appengine.api.datastore.Query class from the low-level datastore API.
This worked fine for my needs (my query only needed to count the number of results, without returning any model instances), but I was wondering if anyone knows of a better solution.
Another approach I've tried (which also worked) was subclassing db.GqlQuery to bypass its constructor. This might not be the cleanest solution, but if anyone is interested, here is the code:
import logging
from google.appengine.ext import db, gql
class ClasslessGqlQuery(db.GqlQuery):
"""
This subclass of :class:`db.GqlQuery` uses a modified version of ``db.GqlQuery``'s constructor to suppress any
:class:`db.KindError` that might be raised by ``db.class_for_kind(kindName)``.
This allows using the functionality :class:`db.GqlQuery` without requiring that a Model class for the query's kind
be available in the local environment, which could happen if a module defining that class hasn't been imported yet.
In that case, no validation of the Model's properties will be performed (will not check whether they're not indexed),
but otherwise, this class should work the same as :class:`db.GqlQuery`.
"""
def __init__(self, query_string, *args, **kwds):
"""
**NOTE**: this is a modified version of :class:`db.GqlQuery`'s constructor, suppressing any :class:`db.KindError`s
that might be raised by ``db.class_for_kind(kindName)``.
In that case, no validation of the Model's properties will be performed (will not check whether they're not indexed),
but otherwise, this class should work the same as :class:`db.GqlQuery`.
Args:
query_string: Properly formatted GQL query string.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
Raises:
PropertyError if the query filters or sorts on a property that's not indexed.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
namespace = None
if isinstance(app, tuple):
if len(app) != 2:
raise db.BadArgumentError('_app must have 2 values if type is tuple.')
app, namespace = app
self._proto_query = gql.GQL(query_string, _app=app, namespace=namespace)
kind = self._proto_query._kind
model_class = None
try:
if kind is not None:
model_class = db.class_for_kind(kind)
except db.KindError, e:
logging.warning("%s on %s without a model class", self.__class__.__name__, kind, exc_info=True)
super(db.GqlQuery, self).__init__(model_class)
if model_class is not None:
for property, unused in (self._proto_query.filters().keys() +
self._proto_query.orderings()):
if property in model_class._unindexed_properties:
raise db.PropertyError('Property \'%s\' is not indexed' % property)
self.bind(*args, **kwds)
(also available as a gist)
You could create a temporary class just to do the query. If you use an Expando model, the properties of the class don't need to match what is actually in the datastore.
class KindName(ndb.Expando):
pass
You could then do:
KindName.query()
If you need to filter on specific properties, then I suspect you'll have to add them to the temporary class.

Solve inconsistencies in an OWL ontology

(Thanks of the comments, I am updating my code and question. Maybe it will be useful for others.)
Update
I am doing several edit processes in one ontology, at the end, I realized my ontology is inconsistent. Now I should get rid of all the unsatisfiable classes.
I searched a lot, but there is no code to solve the inconsistencies.
Follow the approach of this paper and the library of Matthew Horridge and this, still I am struggling with this issue.
I update my code and question, this is my solution. Is there any more suggestion for it?
What I am doing to solve the inconsistencies:
Run a reasoner to find unsatisfiable classes
From the all unsatisfiable classes, only find the root-unsatisfiable-classes
Find explanation axioms for them
Rank them and select the axioms which should be deleted (or rewrite) by the user
In my below code (using other existing solutions), I only need to implement rank function (the left open issue in inconsistency resolver).
For example, for my ontology, it has 25 unsatisfiable classes, which only 2 of them are the root of inconsistencies. These 2 root-classes, has 11 axioms (which I get them by getExplanations)
import java.io.File;
import java.util.Iterator;
import java.util.Set;
import org.semanticweb.owl.explanation.impl.rootderived.CompleteRootDerivedReasoner;
import org.semanticweb.owl.explanation.impl.rootderived.StructuralRootDerivedReasoner;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import com.clarkparsia.owlapi.explanation.BlackBoxExplanation;
import com.clarkparsia.owlapi.explanation.HSTExplanationGenerator;
import com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory;
public class InconsistencyTest {
public static void main(String areg[]) throws Exception {
File fileM = new File("address\\to\\my\\ontology\\myOnt.owl");
OWLOntologyManager tempManager = OWLManager.createOWLOntologyManager();
OWLOntology ont = tempManager.loadOntologyFromOntologyDocument(fileM);
// run an reasoner
OWLReasonerFactory reasonerFactory = new PelletReasonerFactory();
OWLReasoner reasoner = reasonerFactory.createNonBufferingReasoner(ont);
if (reasoner.isConsistent()) {
// an ontology can be consistent, but have unsatisfiable classes.
if (reasoner.getUnsatisfiableClasses().getEntitiesMinusBottom().size() > 0) {
// means: an ontology is consistent but unsatisfiable!
System.out.println("The ontology FAILED satisfiability test with Pellet reasoner. \n Unsatisfiable classes detected: "
+ reasoner.getUnsatisfiableClasses().getEntitiesMinusBottom().size());
// This line return all unsatisfibaleClasses, but I do not need it
// Iterator<OWLClass> aList=reasoner.getUnsatisfiableClasses().getEntitiesMinusBottom().iterator();
// get root of unstaisfiableClasses, and get their explanations
BlackBoxExplanation bb = new BlackBoxExplanation(ont, reasonerFactory, reasoner);
HSTExplanationGenerator multExplanator = new HSTExplanationGenerator(bb);
CompleteRootDerivedReasoner rdr = new CompleteRootDerivedReasoner(tempManager, reasoner, reasonerFactory);
for (OWLClass cls : rdr.getRootUnsatisfiableClasses()) {
System.out.println("**** ROOT! " + cls);
int maxEntailment = 5;
Set<Set<OWLAxiom>> exSet = multExplanator.getExplanations(cls, maxEntailment);
OWLAxiom deletedAxiom = rankAxiom(exSet);
//return these axioms to user to delete or rewrite them
}
} else {
System.out.println("The ontology PASSED the consistency test.");
}
} else {
System.out.println("The ontology FAILED the consistency test, please review the Axioms or debug using Protege");
}
reasoner.dispose();
}
Do I follow everything correct? Is there any suggestion for rank the axioms?
Very Thanks

Importing Individuals from a text file into an OWL Ontology (Protege)

I basically have a large file of a few thousand names each on a new line in .txt. I am using Protege to build my ontology and I want a quicker way to insert these names as Individuals into the concept 'Person' in my Ontology. is there anyway that this can be done using Protege or the OWL API as clicking the add button in protege and typing/copying each name then adding it to the 'Person' concept will take some time.
Thanks for any suggestions.
If using the OWL API, there is an example of how to do just this in the examples provided in the documentation:
public void shouldAddClassAssertion() throws OWLOntologyCreationException,
OWLOntologyStorageException {
// For more information on classes and instances see the OWL 2 Primer
// http://www.w3.org/TR/2009/REC-owl2-primer-20091027/#Classes_and_Instances
// In order to say that an individual is an instance of a class (in an
// ontology), we can add a ClassAssertion to the ontology. For example,
// suppose we wanted to specify that :Mary is an instance of the class
// :Person. First we need to obtain the individual :Mary and the class
// :Person Create an ontology manager to work with
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLDataFactory dataFactory = manager.getOWLDataFactory();
// The IRIs used here are taken from the OWL 2 Primer
String base = "http://example.com/owl/families/";
PrefixManager pm = new DefaultPrefixManager(base);
// Get the reference to the :Person class (the full IRI will be
// <http://example.com/owl/families/Person>)
OWLClass person = dataFactory.getOWLClass(":Person", pm);
// Get the reference to the :Mary class (the full IRI will be
// <http://example.com/owl/families/Mary>)
OWLNamedIndividual mary = dataFactory
.getOWLNamedIndividual(":Mary", pm);
// Now create a ClassAssertion to specify that :Mary is an instance of
// :Person
OWLClassAssertionAxiom classAssertion = dataFactory
.getOWLClassAssertionAxiom(person, mary);
// We need to add the class assertion to the ontology that we want
// specify that :Mary is a :Person
OWLOntology ontology = manager.createOntology(IRI.create(base));
// Add the class assertion
manager.addAxiom(ontology, classAssertion);
// Dump the ontology to stdout
manager.saveOntology(ontology, new StreamDocumentTarget(
new ByteArrayOutputStream()));
}

Find owlSubClasses of a class using the ROWLEX API?

I have a given ontology, on which I like to reason. I use the ROWLEX API for .NET.
How can I find all owlSubClasses of a class?
ROWLEX is not a reasoner. It has some functionality of a reasoner implemented - it is very necessary for the C# class generation - but its API is not designed for that. However, there is still hope, just not the most elegant solution.
I assume, that you have an ontology and you generated .NET classes from that using OwlGrinder.exe. Therefore by default, you have two associated .NET classes generated for each corresponding OWL class in the ontology: one light class and one full class. We are going to use the light classes only. We simply iterate through ALL .NET classes and filter out if is a subclass. That is it.
string baseClassUri = "http://myontology/2012/10#mybaseclass";
Assembly asm = GetMyAssemblyGeneratedByOwlGrinder();
Type[] subClasses = (from type in asm.GetTypes()
where type.IsSubclassOf(typeof(NC3A.SI.Rowlex.OwlThing))
// selecting subclasses only
let attributes = type.GetCustomAttributes(typeof(NC3A.SI.Rowlex.SubClassOfAttribute), false)
from attr in attributes
let subClassAttr = attr as NC3A.SI.Rowlex.SubClassOfAttribute
where subClassAttr.TypeUri == baseClassUri
// selecting light classes only
let lightAttributes = type.GetCustomAttributes(typeof(NC3A.SI.Rowlex.LightVersionAttribute), false)
from lightAttr in lightAttributes
let lightAttr_ = lightAttr as NC3A.SI.Rowlex.LightVersionAttribute
where lightAttr_.LightVersion == true
select type).ToArray();
I did not try the code, it may be buggy. But it does show the idea. Each generated class have a bunch of attributes added. These include their base classes in the SubClassOfAttribute and whether they are light classes or full classes using the LightVersionAttribute. You can filter out the classes you are interested in based on these attributes.

Resources