Check OWL Class - owl

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);

Related

How to analyze a complex class axiom using OWL API

I read the OWL API documentation, most of the examples are about create class axioms and add them to the ontology. Now, I need to retrieve the restriction of a class, and extract the elements in the restriction.
For example, in the pizza.owl, ChessePizza class is defined by the restriction: "Pizza and (hasTopping some CheeseTopping)". I can use the "getEquivalentClassesAxioms" function to get the whole axiom. But I want to know the details of this axiom, such as the object properties (hasTopping) and classes (CheeseTopping) used in this axiom. Is there any method to extract the elements of a axiom?
The best approach to, for example, extract the property for all existential restrictions, is to write an OWLObjectVisitor.
In a visitor, you implement a visit(OWL... o) for each class that the visitor knows about. For an axiom that defines A equivalentTo p some Q, the visitor would look something like:
OWLObjectVisitor v = new OWLObjectVisitor() {
public void visit(OWLEquivalentClassesAxiom ax) {
// this is an example of recursive visit
ax.classExpressions().forEach(c->c.accept(v));
}
public void visit(OWLObjectSomeValuesFrom ce) {
OWLObjectPropertyExpression p = ce.getProperty();
// here you can do what you need with the property.
}
};
axiom.accept(v);

OWL: How to refer to property holder's properties?

This is a question about OWL (Web Ontology Language). There might be some mistakes of terms as I am a very beginner.
I want to represent a painting activity as a Painting class.
Painting has a property TargetSurface whose range is a Surface class:
Surface has properties SurfaceColor (range: Color), etc.
Painting has a property TargetColor whose range is a Color class.
Now I want to represent the objective of painting as a property of Painting. It would be something like: a property Painting.Objective has a range that is an instance of Change class (let's say, Change1), which involves properties Change1.What = TargetSurface.SurfaceColor and Change1.ToWhat = TargetColor.
My question is that Objective is referring to properties of Painting (Painting is a holder of Objective; referred properties are Painting.TargetSurface.SurfaceColor and Painting.TargetColor). How can we represent this in OWL? An ugly solution would be representing the properties of Change1 as xsd:string; Change1.What = "parent.TargetSurface.SurfaceColor" and Change1.ToWhat = "parent.TargetColor". Are there better solutions?
Note that Painting.TargetSurface and Painting.TargetColor will be referred to in other properties of Painting. So making an instance Change2 which directly refers to Painting.TargetSurface.SurfaceColor and Painting.TargetColor would not be a good idea.
Many thanks!
You can do this with "punning" in OWL2. Punning takes advantage of the fact that properties are objects too. We do something similar when modeling property attributes. We can use the property in the subject position of a triple when specifying the domain attribute, e.g. TargetSurface rdfs:range Surface. You can similarly specify rdf:Property in the object position of the rdfs:range assertion for your What property. An example assertion could be Change1 What TargetColor where Change1 is your individual change of the painting, What is the property and TargetColor is the property that is changed (which is used here as the object of the triple).
From the answer of #Jess, a solution came up to my mind.
We prepare two general classes. Holder class (properties Context, HeldVia) refers to a class that holds a class Context as a property HeldVia. Ref class (properties A, B) refers to a class that is held by A as a property B (i.e. like an A.B operator).
Then we can represent Painting.Objective as follows. An informative representation would be:
Painting.Objective = Change1
Change1.What = Ref(Ref(Holder(Change1,Objective),TargetSurface),SurfaceColor)
Change1.ToWhat = Ref(Holder(Change1,Objective),TargetColor)
Note that Holder(Change1,Objective) refers to Painting since Painting is holding Change1 as an Objective property.
More formally, the above would be represented as:
Painting.Objective = Change1
Holder1.Context = Change1
Holder1.HeldVia = Objective
Ref1.A = Holder1
Ref1.B = TargetSurface
Ref2.A = Ref1
Ref2.B = SurfaceColor
Ref3.A = Holder1
Ref3.B = TargetColor
Change1.What = Ref2
Change1.ToWhat = Ref3

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()));
}

How do I handle objects that are part of a Model object’s state, but don’t need separate db-level support?

In my Google App Engine app I have model objects that need to be stored. These objects are parameterized by various policy objects. For example, my Event class has a Privacy policy object which determines who can see, update, etc. There are various subclasses of PrivacyPolicy that behave differently. The Event consults its PrivacyPolicy object at various points.
class PrivacyPolicy(db.Model):
def can_see(self, event, user):
pass
class OwnerOnlyPolicy(PrivacyPolicy):
def can_see(self, event, user):
return user == event.owner
class GroupOnlyPolicy(PrivacyPolicy):
def can_see(self, event, user):
for grp in event.owner.groups()
if grp.is_member(user):
return True
return False
class OnlyCertainUsersPolicy(PrivacyPolicy):
def __init__(self, others):
self.others = others
def can_see(self, event, user):
return user in others
I could make my Event class use a ReferenceProperty to the PrivacyPolicy:
class Event(db.Model):
privacy: db.ReferenceProperty(PrivacyPolicy)
#…
The reason I don’t like this is that the one-to-one relationship means that nobody every queries for the policy object, there is no need to maintain the back-reference from the policy to its Event object, and in no other way is PrivacyPolicy an independent db-level object. It is functionally equivalent to an IntegerProperty, in that it is part of the Event object’s state, it’s just an object instead of a number — specifically it’s an object that can have zero state or lots of state, unknown to the Event type.
I can’t find anyone talking about how to approach such a situation. Is there a tool/approach I don’t know about? Do I just suck it up and use a reference property and the hell with the overhead?
If the only other way to handle this is a custom Property type, any advice about how to approach it would be welcome. My first thought is to use a TextProperty to store the string rep of the policy object (policy), decode it when needed, caching the result, and having any change to the policy object invalidate the cache and update the string rep.
You're overcomplicating by trying to store this in the datastore. This belongs in code rather than in the datastore.
The least complicated way would be:
class Event(db.Model):
privacy = db.IntegerProperty()
def can_see(self, user):
if self.privacy == PRIVACY_OWNER_ONLY:
return user == event.owner
else if self.privacy == PRIVACY_GROUP:
for grp in self.owner.groups()
if grp.is_member(user):
return True
return False
Sometimes all it takes is to think of the right approach. The solution is to introduce a new kind of property that uses pickle to store and retrieve values, such as that described in https://groups.google.com/forum/?fromgroups#!topic/google-appengine/bwMD0ZfRnJg
I wanted something slightly more sophisticated, because pickle isn’t always the answer, and anyway documentation is nice, so here is my ObjectReference type:
import pickle
from google.appengine.ext import db
class ObjectProperty(db.Property):
def __init__(self, object_type=None, verbose_name=None, to_store=pickle.dumps, from_store=pickle.loads, **kwds):
"""Initializes this Property with all the given options
All args are passed to the superclass. The ones used specifically by this class are described here. For
all other args, see base class method documentation for details.
Args:
object_type: If not None, all values assigned to the property must be either instances of this type or None
to_store: A function to use to convert a property value to a storable str representation. The default is
to use pickle.dumps()
from_store: A function to use to convert a storable str representation to a property value. The default is
to use pickle.loads()
"""
if object_type and not isinstance(object_type, type):
raise TypeError('object_type should be a type object')
kwds['indexed'] = False # It never makes sense to index pickled data
super(ObjectProperty, self).__init__(verbose_name, **kwds)
self.to_store = to_store
self.from_store = from_store
self.object_type = object_type
def get_value_for_datastore(self, model_instance):
"""Get value from property to send to datastore.
We retrieve the value of the attribute and return the result of invoking the to_store function on it
See base class method documentation for details.
"""
value = getattr(model_instance, self.name, None)
return self.to_store(value)
def make_value_from_datastore(self, rep):
"""Get value from datastore to assign to the property.
We take the value passed, convert it to str() and return the result of invoking the from_store function
on it. The Property class assigns this returned value to the property.
See base class method documentation for details.
"""
# It passes us a unicode, even though I returned a str, so this is required
rep = str(rep)
return self.from_store(rep)
def validate(self, value):
"""Validate reference.
Returns:
A valid value.
Raises:
BadValueError for the following reasons:
- Object not of correct type.
"""
value = super(ObjectProperty, self).validate(value)
if value is not None and not isinstance(value, self.object_type):
raise db.KindError('Property %s must be of type %s' % (self.name, self.object_type))
return value

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