Tag Archive for 'rdf'

Validating RDF Data by Evaluating RDF/Clojure Code

I recently started to investigate different ways to serialize RDF triples using Clojure code 1 2 3. I had at least two goals in mind: first, ending up with an RDF serialization format that is valid Clojure code and that could easily be manipulated using core Clojure functions. The second goal was to be able to “execute” the code to validate the data according to the semantics of the ontologies used to define the data.

This blog post focuses on showing how the second goal can be implemented.

Before doing so, let’s take some time to explore what the sayings of ‘Code as Data' and ‘Data as Code' may mean in that context.

Code as Data, Data as Code

What is Code as Data? It means that the program code you write is also data that can be manipulated by a program. In other words, the code you are writing can be used as input [to a macro], which can then be transformed and then evaluated. The code is considered to be data to be manipulated by a macro system to output executable code. The code itself becomes data that can be manipulated with some internal mechanism in the language. But the result of these manipulations is still executable code.

What is Data as Code? It means that you can use a programming language’s code to embed (serialize) data. It means that you can specify your own sublanguage (DSL), translate it into code (using macros) and execute the resulting code.

The initial goal of a RDF/Clojure serialization is to specify a way to write RDF triples (data) as Clojure (code). That code is data that can be manipulated by macros to produce executable code. The evaluation of the resulting code is the validation of the data structures (the graph defined by the triples) according to the semantics defined in the ontologies. This means that validating the graph may also occur by evaluating the resulting code (and running the functions).

Ontology Creation

In my previous blog posts about serializing RDF data as Clojure code, I noted that the properties, classes and datatypes that I was referring to in those blog posts were to be defined elsewhere in the Clojure application and that I would cover it in another blog post. Here it is.

All of the ontology properties, classes and datatypes that we are using to serialize the RDF data are defined as Clojure code. They can be defined in a library, directly in your application’s code or even as data that gets emitted by a web service endpoint that you evaluate at runtime (for data that has not yet been evaluated).

In the tests I am doing, I define RDF properties as Clojure functions; the RDF classes and datatypes are normal records that comply with the same RDF serialization rules as defined for the instance records.

Some users may wonder: why is everything defined as a map but not the properties? Though each property’s RDF description is available as a map, we use it as Clojure meta-data for that function. We consider that properties are functions and not a map. As you will see below, these functions are used to validate the RDF data serialized in Clojure code. That is the reason why they are represented as Clojure functions and not as maps like everything else.

Someone could easily leverage the RDF/Clojure serialization without worrying about the ontologies. He could get the triples that describes the records without worrying about the semantics of the data as represented by the ontologies. However, if that same person would like to reason over the data that is presented to him — if he wants to make sure the data is valid and coherent –then he will require the ontologies descriptions.

Now let’s see how these ontologies are being generated.

Creating OWL Classes

As I said above, an OWL class is nothing but another record. It is described using the same rules as previously defined4. However, it is described using the OWL language and refers to a specific semantic. Creating such a class is really easy. We just have to follow the semantics of the OWL language, and the rules of RDF/Clojure serialization. For example, take this example that creates a simple FOAF person class:

(def foaf:+person
  "The class of all the persons."
  {#'uri "http://xmlns.com/foaf/0.1/Person"
   #'rdf:type #'owl:+class
   #'rdfs:label "Person"
   #'rdfs:comment "The class of all the persons."})

As you can see, we are describing the class the same way we were defining normal instance records. However, we are doing it using the OWL language.

Creating OWL Datatypes

Datatypes are also serialized like normal RDF/Clojure records; that is, just like classes. However, since the datatypes are fairly static in the way we define them, I created a simple macro called gen-datatype that can be used to generate datatypes:

(defmacro gen-datatype
  "Create a new datatype that represents a OWL datatype class.
   [name] is the name of the datatype to create.
   Optional parameters are:
     [:uri] this is the URI of the datatype to create
     [:base] this is the URI of base XSD datatype of this new datatype
     [:pattern] this is a regex pattern to use to use to validate that
                a given string represent a value that belongs to that datatype
     [:docstring] the docstring to use when creating this datatype"

  [name & {:keys [uri base pattern docstring]}]
  `(def ~name
     ~(str docstring)
     (merge {#'rdf:type "http://www.w3.org/TR/rdf-schema#Datatype"}
            (if ~uri {#'rdf.core/uri ~uri})<br />
            (if ~pattern {#'xsp:pattern ~pattern})
            (if ~base {#'xsp:base ~base}))))

You can use this macro like this:

(gen-datatype *full-us-phone-number
              :uri "http://purl.org/ontology/foo#phone-number"
              :pattern "^[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}$"
              :base "http://www.w3.org/2001/XMLSchema#string"
              :docstring "Datatype representing a phone US phone number")

And it will generate a datatype like this:

{#'ontologies.core/xsp:base "http://www.w3.org/2001/XMLSchema#string"
 #'ontologies.core/xsp:pattern "^[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}$"
 #'rdf.core/uri "http://purl.org/ontology/foo#phone-number"
 #'ontologies.core/rdf:type "http://www.w3.org/TR/rdf-schema#Datatype"}

What this datatype defines is a class of literals that represents the full version of an US phone number. I will explain how such a datatype is used to validate RDF data records below.

Creating OWL Properties

Properties are different from classes and datatypes. They are represented as functions in the RDF/Clojure serialization. I created another simple macro called gen-property to generate these OWL properties:

(defmacro gen-property
  "Create a new property that represents a OWL property.
     [name] is the name of the property/function to create. This is the name that will be
            used in your Clojure code.
     [:uri] this is the URI of the property to create
     [:description] this is the description of the property to create
     [:domain] this is the domain of the URI to create. The domain is represented by one or multiple
               classes that represent that domain. If there is more than one class that represent the domain
               you can specify the ^intersection-of or the ^union-of meta-data to specify if the classes
               should be interpreted as a union or an intersection of the set of classes.
     [:range] this is the range of the URI to create. The range is represented by one or multiple
               classes that represent that range. If there is more than one class that represent the range
               you can specify the ^intersection-of or the ^union-of meta-data to specify if the classes
               should be interpreted as a union or an intersection of the set of classes.
     [:sub-class-of] one or multiple classes that are super-classes of this class
     [:equivalent-property] one or multiple classes that are equivalent classes of this class
     [:is-object-property] true if the property being created is an object property
     [:is-datatype-property] true if the property being created is a datatype property
     [:is-annotation-property] true if the property being created is an annotation property
     [:cardinality] cardinality of the property"

  [name &amp; {:keys [uri
                  label
                  description
                  domain
                  range
                  sub-property-of
                  equivalent-property
                  is-object-property
                  is-datatype-property
                  is-annotation-property
                  cardinality]}]
  (let [vals (gensym "label-")
        docstring (if description
                    (str description ".\n [" vals "] is the preferred label to specify.")
                    (str ""))
        type (if is-object-property
               #'owl:+object-property
               (if is-annotation-property
                 #'owl:+annotation-property
                 #'owl:+datatype-property))
        metadata (merge (if uri {#'rdf.core/uri uri})
                        (if type {#'rdf:type type})
                        (if label {#'iron:pref-label label})
                        (if description {#'iron:description description})
                        (if range {#'rdfs:range range})
                        (if domain {#'rdfs:domain domain})
                        (if cardinality {#'owl:cardinality cardinality}))]
     `(defn ~(with-meta name metadata)
        ~(str docstring)
        [~vals]
        (rdf.property/validate-property #'~name ~vals))))

Note that this macro currently only accommodates a subset of the OWL language. For example, there is no way to use the macro to specify cardinality, etc. I only created what was required for writing this blog post.

You can then use this macro to create new properties like this:

(gen-property foo:phone
              :is-datatype-property true
              :label "phone number"
              :uri "http://purl.org/ontology/foo#phone"
              :range *full-us-phone-number
              :domain #'owl:+thing
              :cardinality 1)

(gen-property foo:knows
              :is-object-property true
              :label "a person that knows another person"
              :uri "http://purl.org/ontology/foo#knows"
              :range #'umbel.ref/umbel-rc:+person
              :domain #'umbel.ref/umbel-rc:+person)

Some other Classes, Datatypes and Properties

So, here is the list of classes, datatypes and properties that will be used later in this blog post for demonstrating how validation occurs in such a framework:

(in-ns 'rdf.core)
(defn uri
  [s]
  (try
    (URI. #^String s)
    (catch Exception e
      (throw (IllegalStateException. (str "Invalid URI: \"" s "\""))))))

(defn datatype
  [s]
  (if (var? s)
    (if (not= (get @s #'ontologies.core/rdf:type) "http://www.w3.org/TR/rdf-schema#Datatype")
      (throw (IllegalStateException. (str "Provided value for datatype is not a datatype: \"" s "\""))))
    (throw (IllegalStateException. (str "Provided value for datatype is not a datatype: \"" s "\"")))))

(in-ns 'ontologies.core)

(gen-property iron:pref-label
              :uri "http://purl.org/ontology/iron#prefLabel"
              :label "Preferred label"
              :description "Preferred label for describing a resource"
              :domain #'owl:+thing
              :range #'rdfs:*literal
              :is-datatype-property true)

(def owl:+thing
  "The class of OWL individuals."
  {#'uri "http://www.w3.org/2002/07/owl#Thing"
   #'rdf:type #'rdfs:+class
   #'rdfs:label "Thing"
   #'rdfs:comment "The class of OWL individuals."})

(gen-datatype xsd:*string
              :uri "http://www.w3.org/2001/XMLSchema#string"
              :docstring "Datatypes that represents all the XSD strings")

Concluding with Ontologies

Ontologies are easy to write in RDF/Clojure. There is a simple set of macros that can be used to help create the ontology classes, properties and datatypes. However, in the future I am anticipating to create a library that would use the OWLAPI to take any OWL ontology and to serialize it using these rules. The output could be Clojure code like this, or JAR libraries. Additionally, some investigation will be done to use more Clojure idiomatic projects like Phil Lord’s Tawny-OWL project.

RDF Data Instantiation Using Clojure Code

Now that we have the classes, datatypes and properties defined in our Clojure application, we can start defining data records like this:

(def valid-record (r {uri "http://foo-bar.com/test/"
                      rdf:type owl:+thing
                      foo:phone ["1-421-353-9057"]
                      iron:pref-label {value "Test cardinality validation"
                                       lang "en"
                                       datatype xsd:*string}}))

Data Validation

Now that we have all of the ontologies defined in our Clojure application, we can start to define records. Let’s start with a record called valid-record that describes something with a phone number and a preferred label. The data is there and available to you. Now, what if I would like to do a bit more than this, what if I would like to validate it?

Validating such a record is as easy as evaluating it. What does that mean? It means that each value of the map that describes the record will be evaluated by Clojure. Since each key refers to a function, then evaluating each value means that we evaluate the function and use the value as specified by the description of the record. Then we iterate over the whole map to validate all of the triples.

To perform this kind of process, we can create a validate-resource function that looks like:

(defn validate-resource [resource]
  (doseq [[property value] resource]
    (do (println (str "validating resource property: " property))
    (if (fn? @property)
      (@property value)))))

You can use it like this:

(validate-resource valid-record)

If no exceptions are thrown, then the record is considered valid according to the ontology specifications. Easy, no? Now let’s take a look at how this works.

If you check the gen-property macro, you will notice that every time a function is evaluated, the #'rdf.property/validate-property function is called. What this function does is to perform the validation of the property given the specified value(s). The validation is done according to the description of the property in the ontology specification. Such a validate-property looks like:

(defn validate-property
  "Validate that the values of the property are valid according to the description of that property
   [property] should be the reference to the function, like #'foo-phone
   [values] are the actual values of that property"

  [property values]
  (do
    (validate-owl-cardinality property values)
    (validate-rdfs-range property values)))

So what it does is to run a series of other functions to validate different characteristics of a property. For this blog post, we demonstrate how the following characteristics are being validated:

  1. Cardinality of a property
  2. URI validation
  3. Datatype validation
  4. Range validation when the range is a class.

Cardinality Validation

Validating the cardinality of a property means that we check if the number of values of a given property is as specified in the ontology. In this example, we validate the exact cardinality of a property. It could be extended to validate the maximum and minimum cardinalities as well.

The function that validates the cardinality is the validate-owl-cardinality function that is defined as:

(defn validate-owl-cardinality
  [property values]
  (doseq [[meta-key meta-val] (seq (meta property))]
    ; Only validate if there is a owl/cardinality property defined in the metadata
    (if (= meta-key #'ontologies.core/owl:cardinality)
      ; If the value is a string, a var or a map, we check if the cardinality is 1
      (if (or (string? values) (map? values) (var? values))
        (if (not= meta-val 1)
          (throw (IllegalStateException.
                  (format "CARDINALITY VALIDATION ERROR: property %s has 1 values and was expecting %d values" property meta-val))))
        ; If the value is an array, we validate the expected cardinality
        (if (not= (count values) meta-val )
          (throw (IllegalStateException.
                  (format "CARDINALITY VALIDATION ERROR: property %s has %d values and was expecting %d values" property (count values) meta-val))))))))

For each property, it checks to see if the owl:cardinality property is defined. If it is, then it makes sure that the number of values for that property is valid according to what is defined in the ontology. If there is a mismatch, then the validation function will throw an exception and the validation process will stop.

Here is an example of a record that has a cardinality validation error as defined by the property (see the description of the property below):

(def card-validation-test (r {uri "http://foo-bar.com/test/"
                              rdf:type owl:+thing
                              foo:phone ["1-421-353-9057" "(1)-(412)-342-3246"]
                              iron:pref-label {value "Test cardinality validation"
                                               lang "en"
                                               datatype xsd:*string}}))
user> (validate-resource card-validation-test)
IllegalStateException CARDINALITY VALIDATION ERROR: property #'dataset-test.core/foo:phone has 2 values and was expecting 1 values  rdf.property/validate-owl-cardinality (property.clj:36)

URI Validation

Everything you define in RDF/Clojure has a URI. However, not every string is a valid URI. All of the URIs you may define can be validated as well. When you define a URI, you use the #'rdf.core/uri function to specify the URI. That function is defined as:

(defn uri
  [s]
  (try
    (URI. #^String s)
    (catch Exception e
      (throw (IllegalStateException. (str "Invalid URI: \"" s "\""))))))

As you can see, we are using the java.net.URI function to validate the URI you are defining for your records/classes/properties/datatypes. If you make a mistake when writing a URI, then a validation error will be thrown and the validation process will stop.

Here is an example of a record that has an invalid URI:

(def uri-validation-test (r {uri "-http://foo-bar.com/test/"
                             rdf:type owl:+thing
                             foo:phone "1-421-353-9057"
                             iron:pref-label {value "Test URI validation"
                                              lang "en"
                                              datatype xsd:*string}}))
user> (validate-resource uri-validation-test)
IllegalStateException Invalid URI: "-http://foo-bar.com/test/"  rdf.core/uri (core.clj:16)

Datatype Validation

In OWL, a datatype property is used to refer to literal values that belong to classes of literals (datatypes classes). A datatype class is a class that represents all the literals that belong to that class of literal values as defined by the datatype. For example, the *full-us-phone-number datatype we described above defines the class of all the literals that are full US phone numbers.

Validating the value of a property according to its datatype means that we make sure that the literal value(s) belong to that datatype. Most of the time, people will use the XSD datatypes. If custom datatypes are created, then they will be based on one of the XSD datatypes, and a regex pattern will be defined to specify how the literal should be constructed.

(defn validate-rdfs-range
  [property values]
  (do
    ; If the value is a map, then validate the "value", "lang" and "datatype" assertions
    (if (map? values)
      (validate-map-properties values))
    (doseq [[meta-key ranges] (seq (meta property))]
      ; make sure a range is defined for this property
      (if (= meta-key #'ontologies.core/rdfs:range)
        (let [ranges (if (vector? ranges)
                       ranges
                       ^:intersection-of [ranges])]
          (if (true? (:intersection-of (meta ranges)))
            ; consider that all the values of the range is a intersection-of
            (doseq [range ranges]<br />
              (if (is-datatype-property? property)
                ; we are checking the range of a datatype property
                ; @TODO here we have to change that portion to call a function that will do the validation
                ;       according to the existing XSD types, or any custom datatype based on these core
                ;       XSD datatypes. Just like the DVT (Dataset Validation Tool)
                ;
                ;       For now, we simply test using a datatype that has a pattern defined.
                (let [pattern (get range #'ontologies.core/xsp:pattern)]
                  (if pattern
                    ; a validation pattern has been defined for this value
                    (if (vector? values)
                      ; Validate all the values of the property according to this Datatype
                      (doseq [v values]
                        (validate-range-pattern v pattern ranges))
                      ; Validate the value according to the datatype
                      (validate-range-pattern values pattern ranges))))
                ; we are checking the range of an object property
                (if (vector? values)
                  (doseq [v values]
                    (validate-range-object v range property))
                  (validate-range-object values range property))))
            ; consider that all the values of the range is an union-of
            (println "@TODO Ranges union validation")))))))

(defn- validate-range-pattern
  [v pattern range]
  (if (string? v)
    (if (nil? (re-seq (java.util.regex.Pattern/compile pattern) v))
      (throw (IllegalStateException.
              (format "Value \"%s\" invalid according to the definition of the datatype \"%s\""  v range))))
    (if (and (map? v) (nil? (validate-map-properties v)))
      (if (nil? (re-seq (java.util.regex.Pattern/compile pattern) (get v 'value)))
        (throw (IllegalStateException.
                (format "Value \"%s\" invalid according to the definition of the datatype \"%s\""  v range)))))))

(defn- validate-map-properties
  [m]
  (doseq [[p v] m]
        (if (fn? @p)
          (@p v))))

What this function does is to validate the range of a property. It checks what kind of values that exist for the input property according to the RDF/Clojure specification (is it a string, a map, an array, a var, etc.?). Then it checks if the property is an object property or a datatype property. If it is a datatype property, then it checks if a range has been defined for it. If it does, then it validates the value(s) according to the datatype defined in the range of the property.

Here is an example of a few records that have different datatype validation errors:

(def datatype-validation-test (r {uri "http://foo-bar.com/test/"
                                  rdf:type owl:+thing
                                  foo:phone "1-421-353-90573"
                                  iron:pref-label {value "Test cardinality validation"
                                                   lang "en"
                                                   datatype xsd:*string}}))
(def datatype-validation-test-2 (r {uri "http://foo-bar.com/test/"
                                  rdf:type owl:+thing
                                  foo:phone "1-421-353-9057"
                                  iron:pref-label {value "Test datatype validation"
                                                   lang "en"
                                                   datatype "not-a-datatype"}}))

(def xsd:*string-not-a-datatype)

(def datatype-validation-test-3 (r {uri "http://foo-bar.com/test/"
                                    rdf:type owl:+thing
                                    foo:phone "1-421-353-9057"
                                    iron:pref-label {value "Test datatype validation"
                                                     lang "en"
                                                     datatype xsd:*string-not-a-datatype}}))

(def datatype-validation-test-4 (r {uri "http://foo-bar.com/test/"
                                    rdf:type owl:+thing
                                    foo:phone [{value "1-421-353-9057"
                                                datatype xsd:<em>string-not-a-datatype}]
                                    iron:pref-label {value "Test datatype validation"
                                                     lang "en"
                                                     datatype xsd:</em>string}}))
user> (validate-resource datatype-validation-test)
IllegalStateException Value "1-421-353-90573" invalid according to the definition of the datatype "[{#'ontologies.core/xsp:pattern "^[0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4}$", #'rdf.core/uri "http://purl.org/ontology/foo#phone-number", #'ontologies.core/rdf:type "http://www.w3.org/TR/rdf-schema#Datatype"}]"  rdf.property/validate-range-pattern (property.clj:150)

user> (validate-resource datatype-validation-test-2)
IllegalStateException Provided value for datatype is not a datatype: "not-a-datatype"  rdf.core/datatype (core.clj:31)

user> (validate-resource datatype-validation-test-3)
IllegalStateException Provided value for datatype is not a datatype: "#'dataset-test.core/xsd:*string-not-a-datatype"  rdf.core/datatype (core.clj:30)

user> (validate-resource datatype-validation-test-4)
IllegalStateException Provided value for datatype is not a datatype: "#'dataset-test.core/xsd:*string-not-a-datatype"  rdf.core/datatype (core.clj:30)

As you can see, the validate-rdfs-range is incomplete regarding datatype validation. I am still updating this function to make sure that we validate all the existing XSD datatypes. Then we have to better validate the custom datatypes to make sure that we consider their xsp:base type, etc. The code that should be created is similar to the one I created for the Data Validation Tool (which is written in PHP).

Range validation when the range is a class

Finally, let’s shows how the range of an object property can be validated. Validating the range of an object property means that we make sure that the record referenced by the object property belongs to the class of the range of the property.

For example, consider a property foo:knows that has a range that specifies that all the values of foo:knows needs to belong to the class umbel-rc:+person. This means that all of the values defined for the foo:knows property for any record needs to refer to a record that is of type umbel-rc:+person. If it is not the case, then there is a validation error.

Here is an example of a record where the foo:knows property is not properly used:

(def wrench (r {uri "http://foo-bar.com/test/bob"
               rdf:type umbel.ref/umbel-rc:+product
               iron:pref-label "The biggest wrench ever"}))

(def object-range-validation-test (r {uri "http://foo-bar.com/test/bob"
                                      rdf:type umbel.ref/umbel-rc:+person
                                      foo:knows wrench
                                      iron:pref-label {value "Test object range validation"
                                                       lang "en"
                                                       datatype xsd:*string}}))

Remember we defined the foo:knows property with the range of umbel-rc:+person. However, in the example, the reference is to a wrench record that is of type umbel-rc:+product. Thus, we get a validation error:

user> (validate-resource object-range-validation-test)
IllegalStateException The resource "http://umbel.org/umbel/rc/Product" referenced by the property "#'dataset-test.core/foo:knows" does not belong to the class "#'umbel.ref/umbel-rc:+person" as defined by the range of the property  rdf.property/validate-range-object (property.clj:142)

The function that validates the ranges of the object properties is defined as:

(defn- validate-range-object
  [r range property]
  (do (println range)
  (let [r (if (var? r)
            (deref r)
            (if (map? r)
              (r)
              (if (string? r)
                ; @TODO get the resource's description from a dataset index
                ({}))))
        uri (get (deref (get r #'ontologies.core/rdf:type)) #'rdf.core/uri)
        uri-ending (do (println uri) (if (> (.lastIndexOf uri "/") -1)
                     (subs uri (inc (.lastIndexOf uri "/")))
                     (str "")))
        super-classes (try
                        (read-string (:body (clj-http.client/get (str "http://umbel.org/ws/super-classes/" uri-ending)
                                                                 {:headers {"Accept" "application/clojure"}
                                                                  :throw-exceptions false})))
                        (catch Exception e
                          (eval nil)))
        range-uri (get @range #'rdf.core/uri)]
    (if-not (some #{range-uri} super-classes)
      (throw (IllegalStateException. (str "The resource \"" uri "\" referenced by the property \"" property "\" does not belong to the class \"" range "\" as defined by the range of the property" )))))))

Normally, this kind validation should be done using the descriptions of the loaded ontologies. However, for the benefit of this blog post, I used a different way to perform this validation. I purposefully used some UMBEL Reference Concepts as the type of the records I described. Then the object range validation function leverages the UMBEL super-classes web service endpoint to check get the super-classes of a given class.

So what this function does is to check the type of the record(s) referenced by the foo:knows property. Then it checks the type of these record(s). What needs to be validated is whether the type(s) of the referenced record is the same, or is included, in the class defined in the range of the foo:knows property.

In our example, the range is #'umbel-rc:+person. This means that the foo:knows property can only refer to umbel-rc:+person records. In the example where we have a validation error, the type of the wrench record is umbel-rc:+product. What the validation function does is to get the list of all the super classes of the umbel-rc:+product class, and check if it is a sub-class of the umbel-rc:+person class. In this case, it is not, thus an error is thrown.

What is interesting with this example is the UMBEL super-classes web service endpoint does return the list of super classes as Clojure code. Then we use the read-string function to evaluate the list before manipulating it as if it was part of the application’s code.

Conclusion

What is elegant with this kind RDF/Clojure serialization is that the validation of RDF data is the same as evaluating the underlying code (Data as Code). If the data is invalid, then exceptions are thrown and the validation process aborts.

One thing that I yet have to investigate with such a RDF/Clojure serialization is how the semantics of the properties, classes and datatypes could be embedded into the RDF/Clojure records such that we end up with stateful RDF records that embed their own semantic at a specific point in time. This leverage would mean that even if an ontology changes in the future, the records will still be valid according to the original ontology that was used to describe them at a specific point in time (when they got written, when they got emitted by a web service endpoint, etc.).

Also, as some of my readers pointed out with my previous blog post about this subject, the fact that I use vars to serialize the RDF triples means that the serialization won’t produce valid ClojureScript code since vars doesn’t exists in ClojureScript. Paul Gearon was proposing to use keywords as the key instead of vars. Then to get the same effect as with the vars, to use a lookup index to call the functions. This avenue will be investigated as well and should be the topic of a future blog post about this RDF/Clojure serialization.

New UMBEL Web Services

umbel_logo_260_160I am happy to announce the immediate availability of a brand new UMBEL website and a new set of eight UMBEL web services.

UMBEL (Upper Mapping and Binding Exchange Layer) is a general reference structure of 28,000 concepts, which provides a scaffolding to link and interoperate other datasets and domain vocabularies. This project is now six years old.

I would recommend that your read Mike’s blog post about this new release if you want more background information about UMBEL and to have a better understanding of how it can help you integrate, manage, publish and reason over your data.

In this blog post, I will focus on the technical aspects of this new web site and the new set of web service endpoints.

Toward a Better Web Experience

The Web is changing fast. Techniques for developing web sites are constantly and quickly evolving. People uses all kind of devices with different sizes of screens to consume Web content. Websites are more and more responsive by their clever architecture design, and their simpler user interfaces. This is the kind of website we wanted to create for the new UMBEL website.

Clojure Web Service Endpoints at the Core

The core of the new UMBEL website are the new web services. As soon as you are performing a search, or looking at the description of a reference concept or a super type, your browser is making a series of asynchronous queries to the UMBEL web service endpoints.

The average query time is about 60 milliseconds for any of the web service query. This means that a web page is fully loaded within 300 to 500 milliseconds where most of the time is spent downloading the web files (the JavaScript, CSS, HTML and image files) and not querying the web service endpoints. Bearing in mind that the website currently run on a small server with a single core and 1.8G of RAM, these are really good performance figures.

We are initially releasing 8 web service endpoints (with more to follow). They have been created to help developers quickly start using the reference structure without having to download and deploy the entire structure on their own infrastructure. The 8 web services are:

  1. Search concept
  2. Get concept
  3. Get super type
  4. Get narrower concepts
  5. Get broader concepts
  6. Get sub-classes
  7. Get super-classes
  8. Degree

All these web services are calculating the results at runtime. For example, if you want to find the degree between two reference concepts, then the degree is calculated at runtime. It is the same for all the web services that does inferencing like the Get narrower concepts or Get broader concepts web service endpoints.

What we did to get these excellent performance measures is to use Clojure as the programming language and framework to develop the new web service endpoints. Then we define the UMBEL structure as Clojure code.

Each web service endpoint is comprised of simple pure functions that perform calculations on the UMBEL graph of 28 000 nodes. None of the functions are more than 30 lines of code (per endpoint) which greatly simplifies their creation, debugging, maintenance and optimization. Then we use contributed libraries such as Ring and Compojure to manage the creation of the web service endpoints, and Clucy/Lucene for the search engine.

The web services can easily be scaled horizontally since everything is self contained in a single WAR file that can be deployed on new servers in a few clicks. Then the new servers can participate into a cluster of UMBEL web service servers.

Another advantage of using this technology stack for creating the UMBEL web service endpoints is that UMBEL is not just a reference structure nor a set of web service endpoints. It is also a programming API that could be used in any Clojure or Java applications. The UMBEL reference structure, along with all the functions that uses it will be available as a JAR file. That way, UMBEL become portable. It could be used as a library in any JVM application without requiring it to send queries to external web services, or to create complex stacks to deploy and use the UMBEL reference structure in different applications.

Bootstrap as the HTML/CSS/JavaScript Framework

The previous UMBEL website was using Drupal 6. For the ones that were using it, it was sometimes clunky, less responsive and more heavy weight. The problem is that we were not requiring a full CMS system for developing a simple UMBEL website that is only informational.

We wanted a responsive experience for the UMBEL user. We wanted to have the fastest experience possible and we wanted to have this experience on any kind of device: desktop computers, tables, mobile phones, etc.

This is why we choose to develop the new UMBEL website using Twitter’s Bootstrap HTML, CSS and JavaScript framework. This is a framework that anybody can use to quickly create simple, beautiful and modern websites. It uses a grid system to create responsive user interfaces on any kind of device (screen size). That way, UMBEL users have the same kind of experience whether they are using a normal desktop screen, a tablet of their mobile phone.

This choice enabled us to create a simple, modern, nice looking and responsive website for UMBEL.

Introduction to the UMBEL Web Services

Now let’s take the time to introduce each of the UMBEL web service endpoint. The first thing to know is that the UMBEL web service endpoints are free to use, have no usage limits and there is no throttling.

Search Concept Web Service

The Search Web service is used to find UMBEL reference concepts that match a search string. This is the primary tool for finding available concepts in the reference structure. It supports the Lucene query syntax and search queries can be constrained on different fields like the preferred label, alternative labels, descriptions and URI.

Get Concept Web Service

The Get Concept Web service is used to get the full description of a UMBEL Reference Concept. By querying this Web service endpoint, you will get the preferred label, all the alternative labels (namely, the items in the semset), the sub/super classes of the concept, the broader/narrower concepts and the description of that concept.

This is the Web service endpoint that should be used to get the direct relationships with any other reference concept.

Reference concepts descriptions are available as N-Triples, RDF+XML, structJSON or Clojure code.

Get Super Type Web Service

The Get Super Type Web service is used to get the full description of a UMBEL Super Type. By querying this Web service endpoint, you will get the preferred label, all of the alternative labels, the description, and the disjoint super types of a target super type.

Get Narrower Concept Web Service

The Get Narrower Concept Web service is used to get the list of all the narrower concepts of a given reference concept. This processing is done by inference, which means that if A -> B -> C are narrower concepts, then the narrower concepts of A are both B and C, which is what will be returned by the endpoint.

Get Broader Concept Web Service

The Get Broader Concept Web service is used to get the list of all the broader concepts for a given reference concept. This processing is done by inference, which means that if A -> B -> C are broader concepts, then the broader concepts of C are both A and B, which is thus what will be returned by the endpoint.

The broader reference concepts do not include the super type as their top concept (use the Get Super-Class-Of web service endpoint for that).

Get Sub Classes Web Service

The Get Sub Classes Web service is used to get the list of all the sub classes of a given reference concept. This processing is done by inference, which means that if A -> B -> C are sub classes, then the sub classes of A are both B and C, which is what will be returned by the endpoint.

Get Super Classes Web Service

The Get Super Classes Web service is used to get the list of all the super classes of a given reference concept. This processing is done by inference, which means that if A -> B -> C are super classes, then the super classes of C are both A and B, which is what will be returned by the endpoint.

The super classes do include the super types as their top concept (use the Get Super-Class-Of web service endpoint for that).

Degree Web Service

The Degree Web service is used to get the degree (measure of distance) between two UMBEL reference concepts by following the path of a transitive property.

Conclusion

This new website along with these new web service endpoints are still using the UMBEL reference structure version 1.05. However, in the coming month or two, a new version of the reference structure should be released. The structure itself won’t change much except the introduction of a few new reference concepts. But new mechanisms (mostly related to attributes) will be introduced. It will also come with a brand new mapping with external data schemas and data sources such as Schema.org, Wikipedia, etc.

On my side, I will start writing more about UMBEL. New web service endpoints will be released over time. The API available to use, manage and leverage the structure will constantly expand.

On the other side, I will write about how the UMBEL reference structure can be used, how it can be leveraged to integrate data sources, to expend search queries, etc.

Revision of Serializing RDF Data as Clojure Code Specification

In my previous blog post RDF Code: Serializing RDF Data as Clojure Code I did outline a first version of what a RDF serialization could look like if it would be serialized using Clojure code. However, after working with this proposal for two weeks, I found a few issues with the initial assumptions that I made that turned out to be bad design decisions in terms of Clojure code.

This blog post will discuss these issues, and I will update the initial set of rules that I defined in my previous blog post. Going forward, I will use the current rules as the way to serialize RDF data as Clojure code.

What Was Wrong

After two weeks of using the previous set of serializations rules and developing all kind of functions that uses that codes in the context of UMBEL graph traversal and analysis I found the following issues:

  1. Keys and values should be Vars
  2. Ontologies should all be in the same namespace (and not in different namespaces)
  3. The prefix/entity separator for the RDF resources should be a colon and not a slash

These are the three serialization rules that changed after working with the previous version of the proposal. Now, let’s see what caused these changes to occur.

Keys and Values as Vars

The major change is that when we serialize RDF data as Clojure map structures, the keys, and values that are not strings, should be Vars.

There are three things that I didn’t properly evaluated when I first outlined the specification:

  1. The immutable nature of the Clojure data structures
  2. The dependency between ontologies
  3. The non-cyclical namespaces dependency rule imposed by Clojure

In the previous proposal, every RDF property were Clojure functions and they were also the keys of the Clojure maps that were used to serialize the RDF resources. That was working well. However, there was a side effect to this decision: everything was fine until the function’s internal ID changed.

The issue here is that when we work with Clojure maps, we are working with immutable data structures. This means that even if I create a RDF record like this:

(def mike {uri "http://foo.com/datasets/people/mike"
           rdf/type foaf/+person
           iron/pref-label "Mike"
           foaf/knows ["http://foo.com/datasets/people/fred"]})

And that somehow, in the compilation process the RDF ontology file get re-compiled, then the internal ID of the rdf/type property (function) will change. That means that if I create another record like this:

(def mike-2 {uri "http://foo.com/datasets/people/mike"
             rdf/type foaf/+person
             iron/pref-label "Mike"
             foaf/knows ["http://foo.com/datasets/people/fred"]})

that uses the same rdf/type function, then these two records would refer to different rdf/type functions since it changed between the time I created the mike and the mike-2 resources. That may not look like an issue since both functions does exactly the same thing. However, this is an issue since for multiple tasks to manipulate and query RDF data rely on comparing these keys (so, these functions). That means that unexpected behaviors can happen and may even looks like random.

The issue here was that we were not referring to the Var that point to the function, but the function itself. By using the Var as the keys and values of the map, then we fix this inconsistency issue. What happens is that all the immutable data structure we are creating are referring to the Var which point to the function. That way, when we evaluate the Var, we will get reference to the same function whatever when it got created (before or after the creation of mike and/or mike-2). Here is what the mike records looks like with this modification:

(def mike {#'uri "http://foo.com/datasets/people/mike"
           #'rdf/type #'foaf:+person
           #'iron/pref-label "Mike"
           #'foaf/knows ["http://foo.com/datasets/people/fred"]})

We use the #' macro reader to specify that we use the Var as the key and values of the map and not the actual functions or other values referenced by that Var.

The second and third issues I mentioned are tightly related. In a RDF & OWL world, there are multiple examples of ontologies that re-use external ontologies to describe their own semantic. There are cases where an ontology A use classes and properties from an ontology B and where the ontology B use classes and properties from an ontology A. They cross-use each other. Such usage cycles exists in RDF & OWL and are not that uncommon neither.

The problem with that is that at first, I was considering that each OWL ontologies that were to be defined as Clojure code would be in their own Clojure namespace. However, if you are a Clojure coder, you can envision the issue that is coming: if two ontologies cross-use each other, then it means that you have to create a namespace dependency cycles in your Clojure code… and you know that this is not possible because this is restricted by the compiler. This means that everything works fine until this happens.

To overcome that issue, we have to consider that all the ontologies belong to the same namespace (like clojure.core). However, in my next blog post that will focus on these ontologies description I will show how we can split the ontologies in multiple files while keeping them in the same namespace.

Now that we should have all the ontologies in the same namespace, and that we cannot use the namespaced symbols of Clojure anymore, I made the decision to use the more conventional way to write namespaced properties and classes in other RDF serializations which is to delimit the ontology’s prefix with a colon like that:

(def mike {#'uri "http://foo.com/datasets/people/mike"
           #'rdf:type #'foaf:+person
           #'iron:pref-label "Mike"
           #'foaf:knows ["http://foo.com/datasets/people/fred"]})

Revision of the RDF Code Rules

Now let’s revise the set of rules that I defined in the previous blog post:

  1. A RDF resource is defined as a Clojure map where:
    1. Every key is a Var that point to a function
    2. Every value is a:
      1. string
        1. A string is considered a literal if the key is a owl:DatatypeProperty
        2. A string is considered a URI if the key is a owl:ObjectProperty
      2. map
        1. A map represent a literal if the value key is present
        2. A map represent a reference to another resource if the uri key is present
        3. A map is invalid if it doesn’t have a uri nor a value key
      3. vector
        1. A vector refer to multiple values. Values of a vector can be stringsmaps, symbols or Vars
      4. symbol
        1. A symbol can be created to simplify the serialization. However, these symbols have to reference a string or a var object
      5. var
        1. A var reference another entity

In addition to these rules, there are some more specific rules such as:

  1. The value of a uri key is always a string
  2. If the #’rdf:type key is not defined for a resource, then the resource is considered to be of type #’owl:+thing (since everything is at least an instance of the owl:Thing class in OWL)

Finally, there are two additional classes and datatypes creation conventions:

  1. The name of the classes starts with a + sign, like: #’owl:+thing
  2. The name of the datatypes starts with a * sign, like: #’xsd:*string

As you can see, the rules that govern the serialization of RDF data as Clojure code are minimal and should be simple to understand for someone who is used to Clojure code and that tried to write a few resource examples using this format. Now, let’s apply these rules with a series of examples.

Note 1: in the examples of this blog post, I am referring to Vars like #’uri, #’value, #’lang, #’datatype, etc. To make the rules simpler to read and understand, consider that these Vars are defined in the user‘s namespace. However, they are vars that are defined in the rdf.core namespace that will be made publicly available later.

Note 2: All the properties and classes resource Vars have been defined in the same namespace. They should be included with :require or :use like (:use [ontologies.core]) from the ns function of the Clojure source code file that define this RDF resource. We will discuss about these namespaces in a subsequent blog post.

Revision of Serializing RDF Code in N-Triples

The serialize-ntriples function got modified to comply with the new set of rules:

(declare serialize-ntriples-map-value serialize-ntriples-string-value is-datatype-property?)

(defn serialize-ntriples
  [resource]
  (let [n3 (atom "")
        iri (get resource #'rdf.core/uri)]
    (doseq [[property prop-vals] resource]
      (let [property-uri (get (meta property) #'rdf.core/uri)]
        ; Don't do anything with the "uri" key
        (if (not= property #'rdf.core/uri)
          (if (vector? prop-vals)
            ; Here the value is a vector of maps or values
            (doseq [v prop-vals]
              (let [val (if (var? v) @v v)]
                (if (map? val)
                  ; The value of the vector is a map
                  (reset! n3 (str @n3 (serialize-ntriples-map-value val iri property-uri)))
                  (if (string? val)
                    ; The value of the vector is a string
                    (reset! n3 (str @n3 (serialize-ntriples-string-value val iri property-uri property)))))))
            (let [vals (if (var? prop-vals) @prop-vals prop-vals)]
              (if (map? vals)
                ; The value of the property is a map
                (reset! n3 (str @n3 (serialize-ntriples-map-value vals iri property-uri)))
                (if (string? vals)
                  ; The value of the property is some kind of literal
                  (reset! n3 (str @n3 (serialize-ntriples-string-value vals iri property-uri property))))))))))
    @n3))

(defn- serialize-ntriples-map-value
  [m iri property-uri]
  (if (not (nil? (get m #'rdf.core/uri)))
    ; The value is a reference to another resource
    (format "&lt;%s> &lt;%s> &lt;%s> .\n" iri property-uri (get m #'rdf.core/uri))
    (if (not (nil? (get m #'rdf.core/value)))
      ; The value is some kind of literal
      (let [value (get m #'rdf.core/value)
            lang (if (get m #'rdf.core/lang) (str "@" (get m #'rdf.core/lang)) "")
            datatype (if (get m #'rdf.core/datatype) (str "^^&lt;" (get (deref (get m #'rdf.core/datatype)) #'rdf.core/uri) ">") "")]
        (format "&lt;%s> &lt;%s> \"\"\"%s\"\"\"%s%s .\n" iri property-uri value lang datatype))
      (if (string? m)
        ; The value of the sector is some kind of literal
        (format "&lt;%s> &lt;%s> \"\"\"%s\"\"\" .\n" iri property-uri m)))))

(defn- serialize-ntriples-string-value
  [s iri property-uri property]
  ; The value of the vector is a string
  (if (true? (is-datatype-property? property))
    ; The property referring to this value is a owl:DatatypeProperty
    (format "&lt;%s> &lt;%s> \"\"\"%s\"\"\" .\n" iri property-uri s)
    ; The property referring to this value is a owl:ObjectProperty
    (format "&lt;%s> &lt;%s> &lt;%s> .\n" iri property-uri s)))

(defn is-datatype-property?
  [property]
  (if (= (-> property
             meta
             (get #'ontologies.core/rdf:type)
             deref
             (get #'rdf.core/uri))
         (-> #'ontologies.core/owl:+datatype-property
             deref
             (get #'rdf.core/uri)))
    (eval true)
    (eval false)))

Serializing a RDF Resource

Now let’s serialize a new RDF resource using the new set of rules:

(def fred {#'uri "http://foo.com/datasets/people/fred"
           #'rdf:type [#'foaf:+person #'owl:+thing]
           #'iron:pref-label "Fred"
           #'iron:alt-label {#'value "Frederick"
                             #'lang "en"}
           #'foaf:skypeID {#'value "frederick.giasson"
                           #'datatype #'xsd/*string}
           #'foaf:knows [{#'uri "http://foo.com/datasets/people/bob"}
                         mike
                         "http://foo.com/datasets/people/teo"]})

One drawback with these new rules (even if essential) is that they complexify the writing of the RDF resources because of the (heavy) usage of the #' macro.

However, on the other hand, they may looks like more familiar to people used to RDF serializations because of the usage of the colon instead of the slash to split the ontology prefix with the ending of the URI.

What we have above, is how the RDF data is represented in Clojure. However, there is a possibility to make this serialization less compact by creating a macro that would change the input map and automatically inject the usage of the #' reader macro into the map structures that define the RDF resources.

Here is the r macro (“r” stands for Resource) that does exactly this:

(defmacro r
  [form]
  (-> (walk/postwalk
       (fn [x]
         (if (and (symbol? x) (-> x
                                  eval
                                  string?
                                  not))
           `(var ~x)
           x))
       form)))

Then you can use it to define all the RDF resources you want to create:

(def fred (r {uri "http://foo.com/datasets/people/fred"
               rdf:type [foaf:+person owl:+thing]
               iron:pref-label "Fred"
               iron:alt-label {value "Frederick"
                               lang "en"}
               foaf:skypeID {value "frederick.giasson"
                             datatype  xsd/*string}
               foaf:knows [{uri "http://foo.com/datasets/people/bob"}
                            mike
                            "http://foo.com/datasets/people/teo"]})

That structure is equivalent to the other one because the r macro will add the #' reader macro calls to change the input map before creating the resource’s Var.

By using the r macro, we can see that the serialization is made much simpler, and that at the end, it is more natural to people used to other RDF serializations.

Conclusion

I used the initial specification in the context of creating a new series of web services for the UMBEL project. This heavy usage of this kind of RDF data leaded to discover the issues I covered in this blog post. Now that these issues are resolved, I am confident that we can move forward in the series of blog posts that covers how (and why!) using Clojure code to serialize RDF data.

The next blog post will cover how to manage the ontologies used to instantiate these RDF resources.




This blog is a regularly updated collection of my thoughts, tips, tricks and ideas about my semantic Web researches and related software development.


RSS Twitter LinkedIN


Follow

Get every new post on this blog delivered to your Inbox.

Join 66 other followers:

Or subscribe to the RSS feed by clicking on the counter:




RSS Twitter LinkedIN