sparql template: a transformation language for ... - hal-inria

25
ISSN 0249-6399 ISRN INRIA/RR--8514--FR+ENG RESEARCH REPORT N° 8514 April 2014 Project-Teams Wimmics SPARQL Template: A Transformation Language for RDF Olivier Corby, Catherine Faron-Zucker, Fabien Gandon

Upload: khangminh22

Post on 20-Mar-2023

0 views

Category:

Documents


0 download

TRANSCRIPT

ISS

N0

24

9-6

39

9IS

RN

INR

IA/R

R--

85

14

--F

R+

EN

G

RESEARCH

REPORT

N° 8514April 2014

Project-Teams Wimmics

SPARQL Template: A

Transformation

Language for RDF

Olivier Corby, Catherine Faron-Zucker, Fabien Gandon

RESEARCH CENTRE

SOPHIA ANTIPOLIS – MÉDITERRANÉE

2004 route des Lucioles - BP 93

06902 Sophia Antipolis Cedex

SPARQL Template: A Transformation

Language for RDF

Olivier Corby∗, Catherine Faron-Zucker†, Fabien Gandon ‡

Project-Teams Wimmics

Research Report n➦ 8514 — April 2014 — 22 pages

Abstract: RDF can be viewed as a meta-model to represent on the Web other languages andmodels, and in particular their abstract graph structure. The general research question addressedin this document is How to transform RDF into other languages and, in particular, how to generatethe concrete syntax of expressions of a given language from their RDF representation. We show howSPARQL can be used as a generic RDF transformation rule language, independant from the outputlanguage. We define an RDF transformer as a set of transformation rules processed by a generictransformation rule engine. We present a lightweight syntactic extension to SPARQL in order tofacilitate the writing of transformation rules and an implementation of a generic transformationrule engine. We show the feasability of our approach with several RDF transformers we havedefined for various output languages.

Key-words: Semantic Web, SPARQL Template, RDF, Transformation, Pretty-Printing

∗ Inria, I3S† Univ. Nice Sophia Antipolis, CNRS, I3S, UMR 7271‡ Inria, I3S

SPARQL Template: A Transformation

Language for RDF

Resume : RDF peut etre considere comme un meta modele pour representersur le Web d’autres languages ou modeles et particulierement leur structureabstraite sous forme de graphe. Ce document traite la question de recherchesuivante : Comment transformer un enonce RDF dans un autre langage et,en particulier, comment engendrer la syntaxe concrete d’enonces d’un langagerepresente en RDF (par exemple de OWL/RDF vers la syntaxe fonctionnelle deOWL).

Nous montrons comment SPARQL peut etre utilise comme un langage generi-que de regles de transformations, independant du format de sortie. Nous definis-sons une operation de transformation de RDF comme un ensemble de regles detransformation dediees, interpretees par un moteur de transformation generique.

Nous presentons une extension syntaxique de SPARQL, qui facilite l’ecrituredes regles de transformation, et une implementation de moteur de transfor-mation generique. Enfin nous montrons la faisabilite de notre approche enpresentant plusieurs transformation RDF realisees pour differents langages.

Mots-cles : Web semantique, SPARQL Template, RDF, Transformation,Pretty-Printing

SPARQL Template: A Transformation Language for RDF 3

1 Introduction

The read-write Web is now providing us with a world-wide blackboard where ahybrid society of users and software agents exchange digital inscriptions. Hu-mans and machines can share this giant clip-board to push and pull data on aglobal scale. The RDF standard [7] provides us with a general purpose graph-oriented data model recommended by the W3C. It is provided with severalsyntaxes (XML, Turtle, JSON-LD, TriG, N-Triples, N-Quads, RDFa) to rep-resent and interchange data on the Web. While the potential of a world-wideSemantic Web of linked data and linked data schemas is now widely recognized,we believe that a special case of data holds a very special potential that has notbeen fully acknowledge yet: data encoding formal languages.

In mathematics, computer science, and other domains, many formal lan-guages are created to capture information in symbolic representations con-strained by rules. In computer science, formal languages have been used forinstance to define programming languages, query languages, data models andformats, knowledge formalisms, inference rules, etc.

For instance in the domain of the Semantic Web alone, OWL 2 [12] is pro-vided with several syntaxes, among which the Functional syntax, the Manchestersyntax used in several ontology editors and RDF/XML and RDF/Turtle; theRule Interchange Format (RIF) [14] is provided with several syntaxes amongwhich a verbose XML syntax, two compact syntaxes for RIF-BLD and RIF-PRD and an RDF syntax; SPARQL Inference Notation (SPIN) is a W3C mem-ber submission [11] to represent SPARQL rules in RDF, to facilitate storageand maintenance.

The Web is already used to exchange code and other representations offormal languages, but most of the time as documents. Just like the SemanticWeb proposes to make data more accessible to machines by going beyond theinitial documentary metaphor of the Web, we consider that the Web of data canbe applied to formal language representations. These languages, their alphabets,their rules, their syntaxes and the expressions they produce can also be seen asjust a special type of data. As such they can become the subject of data modelsand representations in other languages and, in particular in our case, of Webformalisms to exchange and even translate and transform them on a world-widescale.

We propose to consider what happens when RDF is viewed and used asa meta-model to represent on the Web other languages and models, and inparticular their abstract graph structure. We consider that RDF can then beviewed as a pivot abstract language to represent the Abstract Syntax Trees(AST) of expressions of other languages. To do so requires then the ability toexport and import expressions between the targeted formal languages and theirRDF representation. In this paper we address the latter problem of pretty-printing RDF data, i.e. generating the concrete syntax of expressions of a givenlanguage from their RDF representation.

More generally, the research question addressed in this paper is How totransform RDF into other languages? We answer three sub-questions: (1) How

RR n➦ 8514

4 O. Corby & C. Faron-Zucker & F. Gandon

to write declarative transformation rules from RDF to other languages? (2) Howto make the approach generic, i.e the rule language independant from the outputlanguage? and (3) Can SPARQL be used as a transformation rule language?

We show how SPARQL [9] can be used as a generic transformation rulelanguage for RDF, independant from the output languages. We define a trans-former as a set of transformation rules processed by a generic transformationrule engine. We present a lightweight syntactic extension to SPARQL in or-der to facilitate the writing of transformation rules and an implementation of ageneric rule engine.

In section 2 we present existing transformation languages for Web languages.In section 3 we present a generic approach for writing RDF transformers, basedon SPARQL as a transformation rule language. In section 4 we present thetemplate syntactic extension to SPARQL facilitating the writing of RDF trans-formation rules. In section 5 we present our generic transformation rule engine.In section 6 we show the feasability of our approach with several RDF trans-formers we have defined for various output languages.

2 Related Work

Many specific languages have been designed to transform trees, among whichPPML [15] was a pionner rule-based language for programming languages. Itwas designed in the context of the Centaur [3] programming environment.

XSLT [10] is another rule-based language for transforming XML trees. AnXPath expression identifies the subtrees (their roots) for which the templateapplies, and the content of the template describes the text to be pretty-printed.Let us note that XSLT could be used to process and display RDF/XML data.For instance the following example is one of the XSLT rules (called templates)which could be used to pretty-print RDF triples into an HTML table row.

<xsl:template

match=’rdf:Description[@rdf:about]’>

<xsl:for-each select=’./*’>

<tr>

<td>

<xsl:value-of select=’../@rdf:about’/>

</td>

<td>

<xsl:value-of select=’name()’/>

</td>

<td>

<xsl:call-template name="value">

<xsl:with-param name=’v’ select=’.’/>

</xsl:call-template>

</td>

</tr>

Inria

SPARQL Template: A Transformation Language for RDF 5

</xsl:for-each>

</xsl:template>

However RDF/XML syntax is too versatile and less and less used and, most ofall, writing XSLT templates for it would be very complex considering the manypotential serialization of an RDF statement and the transformation rules woulddepend on the concrete XML syntax of RDF instead of its semantics.

We have identified a few other specific transformation languages designed forthe Semantic Web. Fresnel [2] is an RDF vocabulary for specifying in RDF whichdata contained in an RDF graph should be displayed and how. Fresnel’s twofoundational concepts are lenses and formats. Lenses specify which propertiesof an RDF resource are displayed and how these properties are ordered; formatsspecify how resources and properties are rendered. The following example is aFresnel RDF graph describing a presentation format for RDF data on persons:a lense specifies that for each person, her name, mbox and picture should bedisplayed and a format specifies how to display her name.

PersonLens a fresnel:Lens ;

fresnel:classLensDomain foaf:Person ;

fresnel:showProperties

( foaf:name

foaf:mbox

foaf:depiction ).

:nameFormat a fresnel:Format ;

fresnel:label "Name" ;

fresnel:propertyFormatDomain foaf:name .

Xenon [13] is another ontology for specifying in RDF how RDF resourcesshould be presented to the user. It reuses many of the key ideas of XSLT, amongwhich templates, and defines a so-called RDF Stylesheet language. Contrary toFresnel formats, Xenon templates are tied to a specific display paradigm andan XHTML-like output format.

OWL-PL [4] is an extension of XSLT for transforming RDF/OWL intoXHTML. It provides an adaptation of XSLT processing of XML trees to RDFgraphs. In particular, it matches properties of resources instead of XML nodesthrough XPath. Like Xenon, OWL-PL is tied to its output format: XHTML.

[1] addresses the problem of generating XML from RDF data with an ex-tended SPARQL query. A SPARQL query is given a template of XML docu-ment where variables are fed with the query results. The SPARQL construct

clause is overloaded to refer to an XML template with reference to SPARQLquery variables that are bound by a standard where clause. Here again, thesolution is specific to one output format, in this case XML.

In the following, we present a generic approach for writing RDF transformersfor any output language, as opposed to the above presented works constrainedby specific output languages. We propose a generic transformation rule languagebased on SPARQL and a generic transformation rule engine enabling to write

RR n➦ 8514

6 O. Corby & C. Faron-Zucker & F. Gandon

specific transformers for RDF: a special-purpose RDF transformer for a specificoutput language is declaratively defined as a specific set of transformation ruleswhich can be processed by our generic rule engine.

3 SPARQL as a Transformation Rule Language

Generally speaking, a transformation rule consists in a condition part specifyingstatements to be transformed and a presentation part specifying the output forthe statements matching the condition.

We propose to use the SPARQL language as a transformation rule languagefor RDF. We consider the select-where query form, with a where clause asthe condition part of a rule, enabling to select nodes in the RDF graph to betransformed, and a select clause as the presentation part of the rule enablingto define the display of the selected nodes.

The where clause of a transformation rule is any standard SPARQL graphpattern. Therefore, anything that can be represented in RDF can be trans-formed by such rules. For instance, let us consider the expressions in bothFunctional and RDF/Turtle syntaxes of a OWL 2 statement which defines theclass of parents as equivalent to the class of individuals that are linked to aperson by the hasChild property.

EquivalentClasses(

ex:Parent

ObjectSomeValuesFrom (

ex:hasChild

ex:Person ) )

ex:Parent a owl:Class ;

owl:equivalentClass

[ a owl:Restriction ;

owl:onProperty ex:hasChild ;

owl:someValuesFrom ex:Person ]

To pretty-print the above RDF statement into the corresponding Functionalstatement, the following where clause matches the restriction expression andenables to select the values of properties owl:onProperty and owl:allValuesFrom

and bind them to variables ?p and ?c1.

where { ?in a owl:Restriction ;

owl:onProperty ?p ;

owl:someValuesFrom ?c .

}

1The actual pretty-print rule distinguishes between datatype and object properties; it isgiven in section 6.3.

Inria

SPARQL Template: A Transformation Language for RDF 7

The select clause of a transformation rule produces an output result byusing the values bound to the variables of the where clause (or their display),combined with additional text. This is done by using the SPARQL concat

function and an extension function we defined to recursively call transformationrules on the bound values: st:apply-templates is a recursive function whichtakes an RDF term as argument (we call it the focus node) and returns theresult of the appropriate transformation rule applied to this node. For instance,here is the select clause of the pretty-print rule for the OWL restriction in ourrunning example.

prefix st: <http://ns.inria.fr/sparql-template/>

select

(st:apply-templates(?p) as ?pp)

(st:apply-templates(?c) as ?pc)

(concat("ObjectSomeValuesFrom(",

?pp, " ", ?pc, ")") as ?out)

Variables ?pp and ?pc are the transformation results for variables ?p and ?c.The pretty-printing of the Restriction statement as a whole is the concatenationof appropriate text and the values bound to variables ?pp and ?pc. It is returnedby the select clause as the value of variable ?out.

By convention, the focus node of a transformation rule (in the where clause)is denoted by ?in and the transformation result (in the select clause) is de-noted by ?out. Thus, the result of the st:apply-templates function with thevalue bound to ?in as argument is the value bound to ?out and the transformeris the implementation of st:apply-templates. This is detailed in section 5.

By analogy with XSLT templates, we call templates our SPARQL select-

where transformation rules. In the next section, we present a syntax for writingtemplates.

4 Extension of SPARQL with the template-where

Query Form

SPARQL Template is a lightweight syntactic extension to SPARQL we definedto facilitate the writing of transformation rules. It consists in a template-where query form which has some similarity with the construct-where

query form but generates text (in any format) instead of RDF triples.

4.1 Template Definition

SPARQL Template defines and uses the namespace shown below:

prefix st: <http://ns.inria.fr/sparql-template/>

Here is the syntax of the template extension, based on SPARQL 1.1 QueryLanguage grammar2. Prologue defines base and prefixes, PrimaryExpression

2http://www.w3.org/TR/sparql11-query/

RR n➦ 8514

8 O. Corby & C. Faron-Zucker & F. Gandon

is a constant, a variable, a function call or a bracketed expression.

Template ::= Prologue

’template’ (iri VarList ?) ? ’{’

(PrimaryExpression | Group) *

( Separator ) ?

’}’

WhereClause

SolutionModifier

ValuesClause

VarList ::= ’(’ Var + ’)’

Group ::= ’group’ (’distinct’) ? ’{’

PrimaryExpression *

( Separator ) ?

’}’

Separator ::=

’;’ ’separator’ ’=’ Separator

4.2 Template Compiling

Compiling a template keeps the where clause, the solution modifiers andthe values clause of the template unchanged. Only the template clause ismodified which is syntactic sugar for st:apply-templates() and (concat ()

as ?out). Here is the compiling scheme of a template clause into a stan-dard select clause. Basically, a recursive tr function replaces variables V byst:apply-templates(V) and it concatenates terms in a concat() (1-4). Otherexpressions are left as is (5-6).

(1) tr(template(List l)) -> select (concat(tr(l)) as ?out)

(2) tr(List l) -> List(tr(e)) for all e in l

(3) tr(Group(List l)) -> group_concat(tr(l))

(4) tr(Variable v) -> coalesce(st:apply-templates(v), "")

(5) tr(Literal d) -> d

(6) tr(Exp f) -> f

For instance, the following template:

template {

"ObjectAllValuesFrom(" ?p " " ?c ")"

}

where {

?in a owl:Restriction ;

owl:onProperty ?p ;

owl:allValuesFrom ?c .

}

Inria

SPARQL Template: A Transformation Language for RDF 9

is compiled into the following standard select-where query:

select

(coalesce(st:apply-templates(?p), "") as ?_v1)

(coalesce(st:apply-templates(?c), "") as ?_v2)

(concat(

"ObjectAllValuesFrom(", ?_v1, " ", ?_v2, ")")

as ?out)

where {

?in a owl:Restriction ;

owl:onProperty ?p ;

owl:allValuesFrom ?c .

}

Variables are compiled into coalesce(st:apply-templates(var), "") in or-der to facilitate the writing of templates with optional or union patterns wherevariables may be unbound. Hence, for unbound variables, the empty string isreturned in the pretty-print stream.

4.3 Transformation Functions in the template Clause

SPARQL functions can be used in the template clause, e.g. xsd:string(term)returns the string value of its argument. In addition, we defined a set of spe-cific transformation functions that can be used in the template clause of atransformation rule:

❼ st:apply-templates(term) calls the transformer on a focus node andexecutes one template.

❼ st:apply-templates-with(uri, term) calls the specified transformeron a focus node and executes one template. The uri argument is theURI of the document that defines the templates.

❼ st:apply-all-templates(term) calls the transformer on a focus nodeand executes all templates; it returns the concatenation of the results.

❼ st:call-template(name, term) calls a template by its name on a focusnode, it can have several node arguments.

❼ st:call-template-with(uri, name, term) calls a template by its name,on a focus node with a specified transformer.

❼ st:turtle(term) returns the Turtle form of an RDF term.

❼ st:uri(term) returns the Turtle form of its argument if it is a URI; elsecalls st:apply-templates.

For instance, the following template:

RR n➦ 8514

10 O. Corby & C. Faron-Zucker & F. Gandon

template {

"list: " group { ?exp }

}

where {

?in rdf:rest*/rdf:first ?exp

}

is compiled into the following standard SPARQL select-where query:

select

(coalesce(st:apply-templates(?exp), "") as ?res)

(group_concat(?res) as ?p)

(concat("list: ", ?p) as ?out)

where {

?in rdf:rest*/rdf:first ?exp

}

5 A SPARQL Template Processor as a Generic

RDF Transformer

As stated in section 3 the RDF transformer is the st:apply-templates ex-tension function. It is implemented together with the template extension toSPARQL in the Corese Semantic Web Factory3 [6, 5] .

Given an RDF graph with a focus node to be transformed and a list oftemplates, the st:apply-templates function successively tries to apply them tothe focus node until one of them succeeds. A template succeeds if the matchingof the where clause succeeds, i.e. returns a result. Here is the core pseudocodeof st:apply-templates.

(01) Node st:apply-templates(Node node){

(02) for (Query q : getTemplates()){

(03) Mappings map = eval(q, IN, node);

(04) Node res = map.getResult(OUT);

(05) if (res != null) return res;

(06) }

(07) return node;

(08) }

Templates are selected (02) and tried (03) one by one until one of them returnsa result (04-05). In other words, a template is searched whose where clausematches the RDF graph with the binding of the focus node. If no template isfound, the focus node itself is returned (07).

Recursive calls to st:apply-templates implements the AST recursive traver-sal with successive focus nodes: eval (03) runs templates that recursively callthe st:apply-templates function.

3http://wimmics.inria.fr/corese

Inria

SPARQL Template: A Transformation Language for RDF 11

In addition to this pseudocode, the transformer checks loops in case the RDFgraph is not a tree but a cyclic graph. It keeps track of the templates appliedto nodes in order to avoid applying the same template on the same node twice.If no fresh template exists for a focus node, the transformer returns its stringvalue.

5.1 Dynamic Variable Binding

When matching the where clause of a template with the RDF graph, theSPARQL query evaluator is called with a binding of variable in (?in in thewhere clause) with the focus node to be transformed. When processing tem-plates, the SPARQL interpreter must then be able to perfom dynamic bindingto transmit the focus node. This dynamic value binding can be implementedin SPARQL with an extension function st:getFocusNode() that retrieves thefocus node from the environment and a SPARQL bind clause to bind it to the?in variable in the where clause:

bind(st:getFocusNode() as ?in)

It can be generalized to named templates with arguments:

template st:rec(?x) {

}

where {

bind(st:getFocusNode(’x’) as ?x)

}

5.2 Template Selection

Named templates are processed explicitly by a call to the st:call-template()function. For instance, the following template calls the st:interunion tem-plate.

template {

"SubClassOf("

if (bound(?z),

st:call-template(st:interunion, ?in), st:uri(?in))

" " st:uri(?y) ")"

}

where {

?in rdfs:subClassOf ?y

optional {

{?in owl:intersectionOf ?z} union

{?in owl:unionOf ?z}}

}

RR n➦ 8514

12 O. Corby & C. Faron-Zucker & F. Gandon

Given a focus node, the template processor considers the first template thatmatches this node. Hence, the result of the transformation of the focus node isthe result of this template. It is possible to specify an order between templatesusing an explicit priority. For this purpose we introduce a pragma extensionto the syntax:

template {}

where {}

pragma { st:template st:priority 1 }

In some cases, it is worth writing several templates for a type of focus node,in particular when the node holds different graph patterns that should be trans-formed according to different presentation rules. Executing several templateson the focus node is done by calling the st:apply-all-templates() functionin the template clause. The result of the transformation is the concatenationof the results of the successful templates, possibly with a user-defined separator.

template {

st:apply-all-templates(?in

; separator = "\n")

}

where {...}

A transformer can be used to transform a whole RDF graph. For this pur-pose, the st:apply-templates-with(uri) function can be called without focusnode. The transformer must then determine a focus node as there is no dis-tinguished root node in a graph. In this case, if there is a st:start namedtemplate, it is executed first. Otherwise, the first template that succeeds is thestarting point of the transformer.

5.3 Recursive Templates

By combining recursive calls of named templates and if patterns, our trans-former is able to perform computations. For instance, the following two tem-plates enable to generate the development of n! (the first one calling the secondone).

template {

?n "! = " st:call-template(st:rec, ?n)

}

where {

?in a m:Factorial ; m:args(?n)

}

template st:rec(?x) {

if (?x = 1, 1, concat(?x, " . ",

st:call-template(st:rec, ?x - 1)))

}

where { }

Inria

SPARQL Template: A Transformation Language for RDF 13

5.4 Managing Several Transformation Results

In the general case, a template may return several results, like any standardselect-where query. In that case, the transformer automatically concatenatesthese results. Let Q be the select-where query resulting from the compilationof a template T. Let M be the multiset of solution mappings that is the finalresult of the evaluation of Q. The result of the evaluation of T is computed byapplying an additional group concat aggregate on variable ?out on multiset Mas shown below, where scalarvals is a separator that may be user-defined.

Aggregation((?out), group_concat, scalarvals, M)

As a result, the values of the ?out variable of the final results are concatenated,after SPARQL processing of eventual aggregates and solution modifiers.

An explicit call to the group concat function in the template clause canalso be done to specify how to aggregate transformation results. For instance,the following template displays authors and their documents (separated by thespace default separator in the explicit call to group concat), grouped by authors(separated by the specified line break separator in the implicit final call togroup concat):

template {

"author: " ?a "\n"

"books: " group_concat(?b)

; separator = "\n"

}

where {

?in ex:member ?a

?a ex:author ?b

}

group by ?a

order by ?a

6 Validation with Several Specific RDF Trans-

formers

In our approach of RDF transformation based on SPARQL templates with aSPARQL external function st:apply-templates, the transformer, i.e. the tem-plate processor is completely generic: it applies to any RDF data or any lan-guage provided with an RDF syntax. What is specific to each output languageor format is the set of transformation rules defined for it.

We have written several SPARQL template bases available online4 whichvalidate both SPARQL Template and our generic transformer approach.

4ftp://ftp-sop.inria.fr/wimmics/soft/pprint

RR n➦ 8514

14 O. Corby & C. Faron-Zucker & F. Gandon

6.1 RDF-to-RDF Transformer

The following single SPARQL template enables to output RDF data in Turtlesyntax.

template {

st:uri(?x) "\n"

group { st:uri(?p) " " st:turtle(?y)

; separator = ";\n" } "."

; separator = " \n\n"

}

where { ?x ?p ?y }

group by ?x

In a similar way, it is easy to write a transformer for each of RDF syntaxes.

6.2 RDF-to-HTML and RDF-to-CSV Transformer

We implemented a generic transformer from RDF to HTML which generates aHTML table with properties in lines and resources in columns. The content of acell is the value(s) of a given property for a given resource. Here is the templatethat generates the HTML code for the cells containing RDF triple values:

template st:line {

"<td>"

group {

if (?o = st:null, "",

if (isURI(?o),

st:call-template(st:href, ?o),

replace(

replace(st:turtle(?o), "&", "&amp;"),

"<", "&lt;")))

}

"</td>"

}

where {

{select distinct ?p where {?s ?p ?v}

order by ?p}

{?in ?p ?o} union {bind(st:null as ?o)}

}

group by ?p

order by ?p

With a simple adaptation, it is easy to write as well a transformer to output aCSV table representing an RDF graph.

Inria

SPARQL Template: A Transformation Language for RDF 15

6.3 OWL 2 Pretty-Printer

We wrote a pretty-printer generating OWL 2 expressions in functional syn-tax from OWL 2 expressions in RDF syntax as a set of 48 SPARQL tem-plates. Among them, here are the two templates enabling to pretty-print theOWL/RDF statements presented in section 3 in OWL 2 Functional syntax.

template {

if (bound(?t), "DatatypeDefinition",

"EquivalentClasses") "("

if (bound(?z),

st:call-template(st:interunion, ?in),

st:uri(?in))

" " st:uri(?y) ")"

}

where {

?in owl:equivalentClass ?y

optional {{?in owl:intersectionOf ?z}

union {?in owl:unionOf ?z}}

optional { ?y a ?t .

filter(?t = rdfs:Datatype)}

}

template {

if (bound(?t1) || bound(?t2),

"DataSomeValuesFrom",

"ObjectSomeValuesFrom")

"(" st:uri(?p) " " st:uri(?z) ")"

}

where {

?in owl:someValuesFrom ?z ;

owl:onProperty ?p .

optional {?z a ?t1 .

filter(?t1 = rdfs:Datatype)}

optional {?p a ?t2 .

filter(?t2 = owl:DatatypeProperty)}

}

We validated it on the OWL 2 Primer complete sample ontology5 containing350 RDF triples. To validate the result of the pretty-printer, we loaded theoutput produced in OWL Functional syntax into Protege and did a completecycle of pretty print (save to RDF/XML, load and pretty print again) andwe checked that the results were equivalent. Let us note that the results areequivalent and not identical because some statements are not printed in thesame order, due to the fact that Protege does not save RDF/XML statements

5http://www.w3.org/TR/owl2-primer

RR n➦ 8514

16 O. Corby & C. Faron-Zucker & F. Gandon

exactly in the same order and hence blank nodes are not allocated in the sameorder.

We tested this OWL/RDF transformer on several real world ontologies,among which a subset of the Galen ontology. The RDF graph representingit contains 33080 triples, the size of the result is 0.56 MB, the number of tem-plate calls is 291476 and the (average) pretty-print time is 1.75 seconds.

6.4 SPIN Pretty-Printer

SPIN provides an RDF syntax for SPARQL queries. Here is an example of aSPARQL query in SPIN syntax:

[] a sp:Select ;

sp:resultVariables (_:b1 _:b2) ;

sp:where (

[ sp:subject _:b1 ;

sp:predicate foaf:name ;

sp:object _:b2 ]

[a sp:ne ;

sp:arg1 _:b2 ;

sp:arg2 "James"]) .

_:b1 sp:varName "x"^^xsd:string .

_:b2 sp:varName "name"^^xsd:string .

The result of the transformation in SPARQL concrete syntax is shown below:

select ?x ?name

where {

?x foaf:name ?name .

filter(?name != "James")

}

We defined a pretty-printer for SPIN (SPARQL 1.1 Query & Update) asa set of 62 SPARQL templates. It generates SPARQL 1.1 queries in concretesyntax from RDF SPIN data. Here are some key templates of our pretty-printer.

template {

"construct "

if (bound(?temp),

concat("{", ?temp, "}", "\n"), "")

"where {" ?where "}"

}

where {

?in a sp:Construct ; sp:where ?where

optional { ?in sp:templates ?temp }

}

Inria

SPARQL Template: A Transformation Language for RDF 17

template {

st:uri(?x) " " st:uri(?p) " " st:uri(?y) "."

}

where {

?in sp:subject ?x ;

sp:predicate ?p ;

sp:object ?y

}

We tested our SPIN pretty-printer with success on 444 queries from the W3CSPARQL 1.1 Query & Update test cases. We compiled in SPIN the SPARQLqueries in concrete syntax in the W3C test cases. Then we converted this RDFdata back into SPARQL queries in concrete syntax with our SPIN pretty-printer.

6.5 SQL Pretty-Printer

We proposed an RDF syntax for SQL queries similar to the RDF syntax ofSPARQL queries in SPIN in [8]. Here is an extract of an RDF AST for a SQLselect statement:

@prefix sql: <http://ns.inria.fr/ast/sql#>

[] a sql:Query ;

sql:args (

[a sql:Select ;

sql:args (

[a sql:Column ;

sql:label "Customers.CustomerName"]

[a sql:Column ;

sql:label "Orders.OrderID"] ) ]

... )

We have implemented a SQL pretty-printer from SQL AST in RDF to SQLconcrete syntax. Here is a template outputing the select statement of a SQLquery from its RDF AST:

prefix sql:<http://ns.inria.fr/ast/sql#>

template {

"select "

st:call-template(sql:comma, ?select)

}

where {

?in a sql:Select ; sql:args ?select

}

6.6 RDF-to-Latex Transformer

We made an experiment with mathematical expressions represented in RDF.We defined an RDF AST for mathematical expressions and we wrote a set

RR n➦ 8514

18 O. Corby & C. Faron-Zucker & F. Gandon

of SPARQL templates to transform it into Latex. Here is an example of amathematical expression that we encoded in RDF:

[a m:Integral ;

m:from 0 ; m:to m:pi ;

m:args (

[a m:Integral ;

m:from 0 ; m:to m:pi ;

m:args(

[a m:Plus ; m:args(

[a m:Mult ; m:args(3

[a m:Mult ; m:args([m:name "x"]

[m:name "y"])] )]

[a m:Plus ; m:args(

[a m:Mult ; m:args(2 [m:name "x"] )]

1

)]

)]

) ;

m:var [m:name "x"]] ) ;

m:var [m:name "y"] ]

Here is the Latex format generated by our transformer:

\int_{y=0}^{\pi}\,\int_{x=0}^{\pi}\,

(3 \, x \, y + 2 \, x + 1)\,dx\,dy

And here is the final output produced by a standard Latex compiler:

∫π

y=0

∫π

x=0

(3 x y + 2 x + 1) dx dy

The following templates are involved in the transformation of the above example.Here is a template to pretty-print an integral:

template {

"\\int_{" ?v "=" ?fr "}^{" ?to "}\\, "

if (bound(?p), "(", "")

?e

if (bound(?p), ")", "")

"\\,"

"d" ?v

}

where {

?in a m:Integral ; m:args (?e) ;

m:var ?v ;

m:from ?fr ; m:to ?to

Inria

SPARQL Template: A Transformation Language for RDF 19

optional {

?e a ?p .

filter(?p = m:Plus) }

}

And here is a template to pretty-print a term:

template {

?f " " ?t " " ?r }

where {

?in a ?t ; m:args(?f ?r)

}

values ?t {

m:Plus m:Minus m:Mult

m:Eq m:Lt m:Le m:Ne m:Gt m:Ge

}

6.7 OWL2RL-to-SPARQL Transformer

We made an experiment on the transformation of OWL 2 RL statements intoSPARQL construct-where queries expressing rules. For instance, here is atemplate that translates a OWL 2 property chain axiom into a SPARQL rulewith a property path expression generated on-the-fly.

template {

"construct {?x " st:turtle(?in) " ?y } \n"

"where {"

"?x "

group { st:turtle(?e) ; separator = "/" }

" ?y }"

}

where {

?in owl:propertyChain ?l .

?l rdf:rest*/rdf:first ?e

}

Given the following property chain axiom:

ex:hasUncle owl:propertyChain

(ex:hasFather ex:hasBrother)

the above template generates the following SPARQL rule:

construct { ?x ex:hasUncle ?y }

where { ?x ex:hasFather/ex:hasBrother ?y }

RR n➦ 8514

20 O. Corby & C. Faron-Zucker & F. Gandon

6.8 Discussion

The applications of our work are many and varied. A first family of appli-cations deals with the presentation of RDF data into specific syntaxes (Turtle,RDF/XML, RDF/JSON, TriG, N-Triples, N-Quads, RDFa) or presentation for-mats (HTML table or any other format answering specific needs). As a result,we are able to answer all the application scenarii adressed in the related work.

A second family of applications deals with the translation of RDF intoother languages: RDF-to-CSV, RDF-to-Conceptual Graphs, RDF-to-Kif, etc.but also the translation X-to-Y of other languages with RDF syntaxes (e.g.OWL2RL-to-SPARQL).

A third family of applications deals with the pretty-print of statements ofa given language stored in RDF syntax: OWL, SPARQL, SQL, or any otherspecial purpose language with an RDF syntax. For instance, when queryingan OWL ontology represented in its RDF syntax, SPARQL queries can callthe OWL 2 pretty-printer in their select clause to present their results in theFunctional syntax. For instance, the following query retrieves specific classes ofthe ontology and displays them in Functional syntax in the result:

select (st:apply-templates-with(st:owl, ?x) as ?t)

where {

?x a owl:Class ;

rdfs:subClassOf* f:Human

}

In a variant of this application scenario, the RDF expression of the statementsof some language is embedded into heterogenous RDF data. In that case, thepretty-printer for the RDF AST of this specific language just handles a subsetof the whole RDF data.

Note that the transformation engine can also be used in a filter clause inorder to perform string text matching:

select *

where {

?x a owl:Class

filter(contains(st:apply-templates-with(st:owl, ?x),

"intersection"))

}

7 Conclusion and On-going Work

In this article we proposed to consider that RDF can be used as a meta-modelto represent on the Web other languages and their abstract graph structure.Among the research questions that derive from this proposal we addressed theproblem of transforming RDF into other languages in particular to translate,transform or export these expressions to many other formats. We specified

Inria

SPARQL Template: A Transformation Language for RDF 21

a generic and domain independent extension to support SPARQL Templatesformalizing the transformation rules. Being based on SPARQL, the templatelanguage inherits its expressivity and its extension mechanisms. This specifi-cation and the algorithms we described have been implemented and tested ina generic transformation rule engine part of the Corese Semantic Web Factoryplatform [6, 5]. This means all these results are part of the open-source plat-form Corese. We demonstrated the feasibility and genericity of our approachby providing several transformations including: RDF-to-RDF syntaxes, OWL2, SPIN, HTML, SQL, Latex. We now intend to augment the number of trans-formations available by writing rules for other formats and domains. We alsoconsider special applications of this generic transformation mechanism includingfor instance anonymizing dumps or rewriting heuristics for optimization.

Acknowledgment

We thank Abdoul Macina and Corentin Follenfant for their work on the SQL-to-RDF compiler and the RDF-to-SQL pretty-printer.

References

[1] Faisal Alkhateeb and Sebastien Laborie. Towards Extending and UsingSPARQL for Modular Document Generation. In Proc. of the 8th ACMSymposium on Document Engineering, pages 164–172, Sao Paulo, Bresil,September 2008. ACM Press.

[2] Christian Bizer, Ryan Lee, and Emmanuel Pietriga. Fresnel - A Browser-Independent Presentation Vocabulary for RDF. In Second InternationalWorkshop on Interaction Design and the Semantic Web @ ISWC’05, Gal-way, Ireland, November 2005.

[3] Patrick Borras, Dominique Clement, Thierry Despeyroux, Janet Incerpi,Gilles Kahn, Bernard Lang, and Valerie Pascual. Centaur: the system. InProc. SIGSOFT, 3rd Annual Symposium on Software Development Envi-ronments, Boston, USA, 1988.

[4] Matt Brophy and Jeff Heflin. OWL-PL: A Presentation Language for Dis-playing Semantic Data on the Web. Technical report, Department of Com-puter Science and Engineering, Lehigh University, 2009.

[5] Olivier Corby and Catherine Faron-Zucker. The KGRAM Abstract Ma-chine for Knowledge Graph Querying. In IEEE/WIC/ACM InternationalConference, Toronto, Canada, September 2010.

[6] Olivier Corby, Alban Gaignard, Catherine Faron-Zucker, and Johan Mon-tagnat. KGRAM Versatile Data Graphs Querying and Inference Engine.In Proc. IEEE/WIC/ACM International Conference on Web Intelligence,Macau, December 2012.

RR n➦ 8514

22 O. Corby & C. Faron-Zucker & F. Gandon

[7] Richard Cyganiak, David Wood, and Markus Lanthaler. RDF1.1 Concepts and Abstract Syntax. Recommendation, W3C, 2014.http://www.w3.org/TR/rdf11-concepts/.

[8] Corentin Follenfant, Olivier Corby, Fabien Gandon, and David Trastour.RDF Modelling and SPARQL Processing of SQL Abstract Syntax Trees. InProgramming the Semantic Web, ISWC Workshop, Boston, USA, Novem-ber 2012.

[9] Steve Harris and Andy Seaborne. SPARQL 1.1 Query Language. Recom-mendation, W3C, 2013. http://www.w3.org/TR/sparql11-query/.

[10] Michael Kay. XSL Transformations (XSLT) Version 2.0. Recommendation,W3C, 2007. http://www.w3.org/TR/xslt20/.

[11] Holger Knublauch. SPIN - SPARQL Syntax. Member Submission,W3C, 2011. http://www.w3.org/Submission/2011/SUBM-spin-sparql-20110222/.

[12] Peter F. Patel-Schneider and Boris Motik. OWL 2 Web Ontology LanguageMapping to RDF Graphs (Second Edition). Recommendation, W3C, 2012.http://www.w3.org/TR/owl-mapping-to-rdf/.

[13] Dennis Quan. Xenon: An RDF Stylesheet Ontology. In Proc. WWW, 2005.

[14] Axel Polleres Sandro Hawke. RIF In RDF. Working Group Note, W3C,2012. http://www.w3.org/TR/rif-in-rdf/.

[15] Laurent Thery. A Table-Driven Compiler for Pretty Print-ing Specifications. Technical Report RT 0288, Inria, 2003.http://hal.inria.fr/docs/00/06/98/91/PDF/RT-0288.pdf.

Inria

RESEARCH CENTRE

SOPHIA ANTIPOLIS – MÉDITERRANÉE

2004 route des Lucioles - BP 93

06902 Sophia Antipolis Cedex

Publisher

Inria

Domaine de Voluceau - Rocquencourt

BP 105 - 78153 Le Chesnay Cedex

inria.fr

ISSN 0249-6399