Henriette's Notes

Home » Semantic technologies (Page 2)

Category Archives: Semantic technologies

Getting started with Ontotext GraphDB and RDF4J

In this post I will explain how to quickly get started with the free version of Ontotext GraphDB and RDF4J. Ontotext GraphDB is an RDF datastore and RDF4J is a Java framework for accessing RDF datastores (not just GraphDB). I will explain

  1. how to install and start GraphDB, as well as how to use the workbench to add a repository, and
  2. how to do SPARQL queries against GraphDB using RDF4J.

Install and start GraphDB and create a Repository

To gain access to the free version of GraphDB you have to email Ontotext. They will respond with an email with links to a desktop and stand-alone server version of GraphDB. You want to download the stand-alone server version. This is a graphdb-free-VERSION-dist.zip file, that you can extract somewhere on your filesystem, which I will refer to here as $GRAPHDB_ROOT. To start GraphDB, go to $GRAPHDB_ROOT/bin and run ./graphdb.

To access the workbench you can go to http://localhost:7200. To create a new repository, in the left-hand side menu navigate to Setup>Repositories. Click the Create new repository button. For our simple example we will use PersonData as an Repository ID. The rest of the settings we leave as-is. At the bottom of the page you can press the Create button.

Accessing a GraphDB Repository using RDF4J

To access our PersonData repository we will use RDF4J. Since GraphDB is based on the RDF4J libraries, we only need to include the GraphDB dependencies since these already include RDF4J. Thus, in our pom.xml file we only need to add the following:

 <dependency>
   <groupId>com.ontotext.graphdb</groupId>
   <artifactId>graphdb-free-runtime</artifactId>
   <version>8.5.0</version>
 </dependency>

In our example Java code we first insert some RDF data and then do a query based on the added data. For inserting data we start a transaction and commit it, or, if it fails we do a rollback. For querying the data we iterate through the TupleQueryResult, retrieving values for the binding variables we are interested in (i.e. name in this case). In line with the TupleQueryResult documentation, we close the TupleQueryResult once we are done.

package org.graphdb.rdf4j.tutorial;
package org.graphdb.rdf4j.tutorial;

import org.eclipse.rdf4j.model.impl.SimpleLiteral;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.TupleQuery;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.query.Update;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.http.HTTPRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

public class SimpleInsertQueryExample {
  private static Logger logger = 
    LoggerFactory.getLogger(SimpleInsertQueryExample.class);
  // Why This Failure marker
  private static final Marker WTF_MARKER = 
    MarkerFactory.getMarker("WTF");
  
  // GraphDB 
  private static final String GRAPHDB_SERVER = 
    "http://localhost:7200/";
  private static final String REPOSITORY_ID = "PersonData";

  private static String strInsert;
  private static String strQuery;
  
  static {
    strInsert = 
        "INSERT DATA {"
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/birthDate> \"1906-12-09\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/birthPlace> <http://dbpedia.org/resource/New_York_City> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/deathDate> \"1992-01-01\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://dbpedia.org/ontology/deathPlace> <http://dbpedia.org/resource/Arlington_County,_Virginia> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://purl.org/dc/terms/description> \"American computer scientist and United States Navy officer.\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Person> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/gender> \"female\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/givenName> \"Grace\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/name> \"Grace Hopper\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> <http://xmlns.com/foaf/0.1/surname> \"Hopper\" ."        
         + "}";
    
    strQuery = 
        "SELECT ?name FROM DEFAULT WHERE {" +
        "?s <http://xmlns.com/foaf/0.1/name> ?name .}";
  }  
  
  private static RepositoryConnection getRepositoryConnection() {
    Repository repository = new HTTPRepository(
      GRAPHDB_SERVER, REPOSITORY_ID);
    repository.initialize();
    RepositoryConnection repositoryConnection = 
      repository.getConnection();
    return repositoryConnection;
  }
  
  private static void insert(
    RepositoryConnection repositoryConnection) {
    
    repositoryConnection.begin();    
    Update updateOperation = repositoryConnection
      .prepareUpdate(QueryLanguage.SPARQL, strInsert);
    updateOperation.execute();
    
    try {
      repositoryConnection.commit();
    } catch (Exception e) {
      if (repositoryConnection.isActive())
        repositoryConnection.rollback();
    }
  }

  private static void query(
    RepositoryConnection repositoryConnection) {
    
    TupleQuery tupleQuery = repositoryConnection
      .prepareTupleQuery(QueryLanguage.SPARQL, strQuery);
    TupleQueryResult result = null;
    try {
      result = tupleQuery.evaluate();
      while (result.hasNext()) {
        BindingSet bindingSet = result.next();

        SimpleLiteral name = 
          (SimpleLiteral)bindingSet.getValue("name");
        logger.trace("name = " + name.stringValue());
      }
    }
    catch (QueryEvaluationException qee) {
      logger.error(WTF_MARKER, 
        qee.getStackTrace().toString(), qee);
    } finally {
      result.close();
    }    
  }  
  
  public static void main(String[] args) {
    RepositoryConnection repositoryConnection = null;
    try {   
      repositoryConnection = getRepositoryConnection();
      
      insert(repositoryConnection);
      query(repositoryConnection);      
      
    } catch (Throwable t) {
      logger.error(WTF_MARKER, t.getMessage(), t);
    } finally {
      repositoryConnection.close();
    }
  }  
}

Conclusion

In this brief post I gave a quick example of how you can setup a simple GraphDB repository and query it using SPARQL. You can find sample code on github.

A Common Misconception regarding OWL Properties

A misconception w.r.t. OWL properties that I come across from time-to-time is that people mistakenly think that properties express relations between classes rather than relations between individuals. In this post

  1. I explain how this misconception fails,
  2. I explain what is the meaning of OWL properties, and
  3. I explain how you can model relations between classes if that is really what you want to do.

Throughout this post I will refer to object properties only, even though what I say applies to data properties as well, except of course that object properties relate objects to objects whereas data properties relate objects to data type values.

As an example ontology I will use the following:

Class: Employer
Class: Employee

ObjectProperty: employs
   Domain: Employer
   Range: Employee

How thinking that Properties express Relations between Classes fails

Thinking that properties express relations between classes fails in two different ways:

  1. The first way in which the expectations of users fail under this misconception is that their assumption is that domain and range axioms behave as constraints. That is if we extend our Employer ontology with something nonsensical like
    Class: Cheese
    Class: Fridge
    
    Individual: companyFridge 
        Types: Fridge
        
    Individual: blueCheese
       Types: Cheese
       Facts: employs companyFridge
    

    the reasoner will indicate that our ontology is inconsistent because the individual blueCheese is not of type Employer and neither is the individual companyFridge an instance of Employee. However, this is not the case. This ontology is in fact consistent because domain and range axioms do not behave as constraints.

  2. The other way in which the assumption of users is shattered is that they tend to think that domain and range axioms mean that in our Employer ontology it means that instances of the Employer class must necessarily be linked via the employs property to an instance (or instances?) of Employee. Thus, the expectation is that if we have an instance Employer that is not linked to an instance of Employee via the employs property, the reasoner should give an inconsistency. Again, this is wrong. This ontology will still be consistent.

The Real Meaning of OWL Object Properties

The OWL specification is very explicit about the meaning of object properties. It states:

Object properties connect pairs of individuals.

So what is the meaning of domain and range axioms then? Domain and range axioms are not constraints to be checked, but rather they are axioms from which the reasoner can make inferences. What domain and range axioms state is that whenever two instances are linked via the employs property, for example, it means that the first instance is of type Employer and the second instance is of type Employee. Thus, in our cheese and fridge example, no matter how silly it is, the reasoner will infer that blueCheese is an instance of Employer and companyFridge is an instance of Employee.

Finally, the underlying mathematical formalization of object properties themselves does not enable linking of pairs of classes. An OWL object r is represented as a role r in description logics. Stating that the role r has the domain C and the range D, where C and D are concepts, is achieved through the following axioms:

DomainRangeAxiom whereTopis the set representing the application domain. An object property r between instances a and b is expressed as a role assertion
RoleAssertion in description logics. Note that this assertion contains no information regarding description logic concepts (i.e. classes in OWL).

If you really, really want to have a Link between Classes

So if you really, really want to express a relation between classes, how can this be done? For our Employer ontology we can state the following:

Class: Employer
   SubClassOf: employs some Employee

This states that the Employer class is a subclass of the class consisting of the instances that are linked to at least 1 instance of the Employee class. If we now have an instance of Employer that is not linked via employs to an instance of Employee, the reasoner will find that our ontology is inconsistent. To state that acme is an employer without employees, we state it as follows:

Individual: acme
   Types: Employer
   Facts: employs max 0 Employee

Conclusion

In this post I explained that object properties link individuals (not classes!) and that thinking otherwise can lead to various errors when designing an ontology.

Understanding OWL Universal Property Restrictions

In my previous post I explained existential property restrictions. In this post I want to deal with universal property restrictions. In designing ontologies existential property restrictions tend to be used more often than universal property restrictions. However, beginners in ontology design tend to prefer universal property restrictions, which can lead to inconsistencies that can be very difficult to debug, even for experienced ontology designers [1, 2].

We again start with a very simple ontolgy:

ObjectProperty: owns
        
Class: Cat
  SubClassOf: Pet
    
Class: Dog
  SubClassOf: Pet
    
Class: Person
  DisjointWith: Pet
        
Class: Pet
  DisjointUnionOf: Cat, Dog
  DisjointWith: Person

We will use this ontology as basis for explaining universal property restrictions. We assume we want to extend this ontology with a DogLover class to represent persons owning only dogs. In this post:

  1. I will introduce the DogLover class which I will define as Class: DogLover EquivalentTo: owns only Dog,
  2. I will show you how this definition can lead to inconsistencies that can be difficult to debug, and
  3. I will explain how we can fix this error.

Class: DogLover EquivalentTo: owns only Dog

Let us start out by defining the DogLover class as

Class: DogLover
  EquivalentTo: owns only Dog

We can run the reasoner to ensure that our ontology is currently consistent. We can test our ontology by adding a aDogOnlyOwner individual owning a Dog.

Individual: aDog
  Types: Dog

Individual: aDogOnlyOwner
  Facts: owns aDog

If we run the reasoner it will not infer that aDogOnlyOwner is a DogLover, reason being that due to the open world assumption the reasoner has no information from which it can derive that aDogOnlyOwner owns only dogs. We can try and fix this by stating that

Individual: aDogOnlyOwner
  Types: owns max 0 Cat

Again the reasoner will not infer that aDogOnlyOwner owns only dogs. This is because it still allows for the possibility that aDogOnlyOwner can own, say a house. To exclude all other options we have to define aDogOnlyOwner as follows:

Individual: aDogOnlyOwner
  Types: owns max 0 (not Dog)

which enforces that aDogOnlyOwner owns nothing besides dogs. The reasoner will now infer that aDogOnlyOwner is a DogLover. We can also test that individuals of type DogLover cannot own cats, for example:

Individual: aCat
  Types: Cat

Individual: aDogLover
  Types: DogLover
  Facts: owns aCat

If we run the reasoner, it will give an inconsistency. As I said in my previous post, it is always a good idea to review the explanations for an inconsistency, even when you expect an inconsistency, as seen in Figure 1. It states that the inconsistency is due to

  1. aDogLover owning a cat (aDogLover owns aCat),
  2. a cat is not a dog (Pet DisjointUnionOf Cat, Dog),
  3. an individual that loves dogs owns only dogs (DogLover EquivalentTo owns only Dog),
  4. the aDogLover individual is of type DogLover (aDogLover Type DogLover), and
  5. the aCat individual is of type Cat (aCat Type Cat).
ExplanationForDogLoverWithCat

Figure 1

At this point you may think our definition of DogLover is exactly what we need, but it contains a rather serious flaw.

A Serious Flaw

To keep our ontology as simple as possible for this section, please remove any
individuals you may have added to your ontology, but leave the DogLover class as we have defined it in the previous section. Just to ensure that our ontology is consistent, you can run the reasoner to confirm that it is consistent. What we now want to do is to infer that when an individual owns something, that individual is a person. The way we can achieve this is by defining the domain for the owns property:

ObectProperty: owns
  Domain: Person

Now, this looks like a rather innocent change, but when you run the reasoner again you will find that Pet, Cat and Dog are all equivalent to owl:Nothing while Person is equivalent to owl:Thing. An explanation for why Pet is equivalent to owl:Nothing is given in Figure 2.

ExplanationForPetEquivalentToNothing

Figure 2

The explanation given in Figure 2 can be difficult to understand. Indeed, research has shown that there are explanations that are difficult to understand even for experienced ontology designers [1, 2]. In cases where it is hard to understand explanations, using laconic explanations can be helpful. Laconic justifications aim to remove subexpressions from axioms that do not contribute to explaining an entailment or inconsistency [1, 2]. Ticking the “Display laconic explanation” displays the laconic explanation in Figure 3.

LaconicExplanationForPetEquivalentToNothing

Figure 3

The main difference between the explanations in Figures 2 and 3 are

DogLover EquivalentTo owns only Dog

versus

owns only owl:Nothing SubClassOf DogLover

Where does owns only owl:nothing SubClassOf DogLover come from? Recall that A EquivalentTo B is just syntactical sugar for the two axioms A SubClassOf B and B SubClassOf A. What this explanation is saying is that there is a problem with the owns only Dog SubClassOf DogLover part of our axiom (there is no problem with the DogLover SubClassOf owns only Dog part of our axiom). Furthermore, it states that Dog is inferred to be equivalent to owl:Nothing. For this we need to understand the meaning of owns only Dog better.

OwnsOnlyDog

Figure 4

In Figure 4 I give an example domain where I make the assumption that for all individuals all ownership information is specified explicitly. Thus, individuals with no ownership links own nothing and individuals with ownership links own only what is specified and nothing else. The owns only Dog class includes all individuals that are known to own nothing besides dogs. However, a confusing aspect of the semantics of universal restrictions is that it also includes those individuals that owns nothing. To confirm this for yourself you can use the following ontology (from which I removed the domain restriction for the moment). This ontology will infer that anIndividualOwningNothing is of type DogLover.

ObjectProperty: owns
        
Class: Cat
  SubClassOf: Pet
    
Class: Dog
  SubClassOf: Pet
    
Class: Person
  DisjointWith: Pet
        
Class: Pet
  DisjointUnionOf: Cat, Dog
  DisjointWith: Person
  
Class: DogLover
  SubClassOf: Person
  owns only Dog SubClassOf: DogLover
  
Individual: anIndividualOwningNothing
  Types: owns only (not owl:Thing)

We are now ready to explain why Pet is equivalent to owl:Nothing:

  1. owns Domain Person states that whenever an individual owns something, that individual is a Person.
  2. owns only Pet SubClassOf DogLover includes saying that when an individual owns nothing at all, that individual is a DogLover.
  3. Since DogLover is a subclass of Person it means Person now includes individuals that owns something and individuals that owns nothing, which means Person is equivalent to owl:Thing.
  4. Person and Pet are disjoint, hence Pet must be equivalent to owl:Nothing.

Conclusion

So how do we fix our ontology? Simple, we enforce that for someone to be a DogLover, they must own at least 1 dog and nothing else but dogs.

Class: DogLover
  EquivalentTo: owns some Dog and owns only Dog

The example ontologies of this post can be found in github.

Bibliography

[1] M. Horridge, Justification Based Explanation in Ontologies, Ph.D. Thesis, University of Manchester, 2011.

[2] M. Horridge, S. Bail, B. Parsia, and U. Sattler, Toward Cognitive Support for OWL Justifications., Knowl.-Based Syst. 53 (2013), 66–79.