53
Tópicos Especiales: Programación de la Web Semántica Postgrado en Computación Taniana Rodríguez Semestre A2016 Abril-2016 1

Introducción a la programación de la Web Semántica

Embed Size (px)

Citation preview

Tópicos Especiales:

Programación de la

Web Semántica Postgrado en Computación

Taniana Rodríguez

Semestre A2016

Abril-2016

1

Contenido del Curso

Unidad 1. Introducción a la programación

de la Web Semántica

Unidad 2. Modelado Información

Unidad 3. Construyendo Aplicaciones

para la Web Semántica

2

Evaluación

Tareas . 10%

Artículo de investigación de

estado del arte. 20%

Proyecto práctico y artículo 70%

3

Bibliografía

Parte del material de este curso está basado en el siguiente libro,

John Hebeler, Matthew Fisher, Rayn Blace and Andrew Perez-Lopez. “Semantic Web Programming” 2009 Wiley Publishing, Inc

Asimismo, se recomienda como bibliografía complementaria los siguientes

Toby Segaran, Colin Evans, and Jamie Taylor. Programming the Semantic Web. 2009 O’REILLY.

Bob DuCharme. “Learning SPARQL. Querying and Updating with SPARQL 1.1.” 2013. O’REILLY. Second Edition

Dean Allemang. James Hendler. “Semantic Web for the Working Ontologist. Modeling in RDF, RDFS and OWL.” 2008 Morgan Kaufmann publications.

Griogoris Antoniou and Frank van Harmelen. “A Semantic Web Primer.” Second edition. 2008. The MIT’Press

4

Unidad 1. Sección 1.

Introducción a la

Web Semántica 5

WWW Actual

Contenido no estructurado

Enlaces

Web Es un conjunto de documentos Información esta expresada en Lenguaje Natural. Falta de estructura semántica La información es Interpretado por los humanos Se asume que los usuarios finales pueden

reconocer el significado y sacar conclusiones e inferir nueve conocimiento utilizando el contexto y entender el conocimiento relacionado

Información recuperada por los motores de búsquedas

Es un gran repositorio de información

Desafíos de la Web Heterogénea. La presentación

de los datos son presentados en forma diferentes

Masiva. Gran cantidad de información

Cambia rápido Hecha por humanos

Cómo puede un agente o computador entender esta Web?

Imágenes

6

Agentes o Computadores entender

la Web?

Cosa

Nombre

Ubicación

Estado

….

Jose

José Pérez

15/10/94

Mérida

Juan Trabaja con

ULA

Universidad de los Andes

Mérida

Nucleó Mérida

….

Trabaja

en

Trabaja

en

Tener un lenguaje que permita especificar recursos y sus relaciones

Lenguaje sea procesado por el computador

Consultar los datos mediante s aplicaciones o agentes

Lenguaje de consulta que sea procesable por el computador

7

¿Qué es la Web Semántica?

“El primer paso es colocar los datos en la Web de un modo que las máquinas

puedan entenderlos naturalmente o

convertirlos a esa forma. Esto crea lo que

yo llamo la Web Semántica: una red de datos que pueden ser procesados

directa o indirectamente por máquinas”

Tim Beners-Lee

“La Web Semántica es una extensión

de la Web en la cual la información se

da mediante un significado bien

definido, lo que facilita que los

ordenadores y la gente trabajen en

cooperación”

Linked data es otro

nombre para la red de

datos

8

¿Qué es la Web Semántica?

Web Semántica

Definición

Origen Componentes Características

LD Teoría de Grafo WS Herramientas WS

Declaración Lenguajes Ontologías Instancias

Frameworks IDE Razonadores KB

Expresividad Inferencia Integración Unicidad

Fuente: [John Hebeler, Matthew Fisher, Ryan Blace, Andrew Perez-Lopez, Mike Dean. Semantic Web Programming]

9

Comparación de WWW y WS

Características WWW WS

Componente

fundamental

Contenido no

estructurado

Declaraciones formales

Audiencia Humanos Aplicaciones

Enlaces Indica ubicación Indica ubicación y

significado

Vocabulario Instrucciones

Formateada

Semántica y lógica

Lógica Informal/No estándar Lógica descriptiva

Fuente: [John Hebeler, Matthew Fisher, Ryan Blace, Andrew

Perez-Lopez, Mike Dean. Semantic Web Programming]

10

Arquitectura de la Semántica

Semántica Web

Inferencias Ontologías

Lenguajes

Instancias

RDF RDF-S OWL

SPARQL XML

Esta compuesta por

Se basa en dos puntos fundamentales

La descripción del significado

La manipulación automática de estas descripciones

La descripción del significado se articula con Semántica MetaDatos Ontologías

La manipulación se efectúa mediante Lógica Motores de inferencias

11

Visión de la Infraestructura

de la Web

12

https://www.w3.org/

Linked Data “Los Datos Enlazados es la forma que tiene la Web

Semántica de vincular los distintos datos que están

distribuidos en la Web”

(http://www.w3c.es/Divulgacion/GuiasBreves/LinkedD

ata)

13

Describe la forma de

exponer, compartir y

conectar piezas de

datos, información y

conocimiento a través

de la Web

Permite construir la

Web de Datos

Open Data

Open Data es una forma de publicar datos de

organizaciones públicas y privadas, en formatos que

sean reutilizables por personas e instituciones

Según Wikipedia: Open Data es una filosofía que

persigue que determinados datos estén disponibles de

forma libre a todo el mundo, sin restricciones de

copuright, patetes u otros mecanismos de control

14

Las cinco estrellas de Open

Linked Data

Una estrella: ofrece los datos en cualquier formato.

Dos estrellas: entregar los datos de manera estructurada

Tres estrellas: entregar los datos en un formato que no sea propietario

Cuatro estrellas: usar URI para identificar cosas y propiedades, de manera que se pueda apuntar a los datos.

Cinco estrellas: vincular sus datos con los de otras personas, dotándolos de contexto

15

Ejemplo de Linked Data 16

BBC utiliza tecnologías semánticas basadas en los

principios de Linked Data:

BBC Music -> Música

BBC Programmes -> Programas

BBC Wildlife Finger -> Fauna Salvaje

Aplicaciones de la Web

Semántica

Los campos de aplicaciones de la Web Semántica son utilizados en diferentes dominios

Las redes sociales, los blogs y las plataformas comunitarias (por ejemplo: Flickr, Facebook)

La búsqueda o la clasificación bibliográfica o documental

La búsqueda de información en Internet o Intranet

La búsqueda de información en la empresa.

La industria, la investigación u el desarrollo especialmente en los dominios de tecnologías

Comercio/Comercio electrónico: especialmente mediante la ontología “GoodRelation”

17

En resumen la Web Semántica

Se basa en dos puntos fundamentales

La descripción del significado

La manipulación automática de estas descripciones

Dos grandes disciplinas contribuyen a la Web Semántica

Teoría de grafos, que es el corazón de la Web Semántica, el cual

representa los conceptos y sus relaciones.

Lógica Descriptiva, el cual es el formalismo basados en lógica para la

representación del conocimiento, es decir describe al dominio en función

de conceptos, Relaciones e individuos

La Web Semántica ofrece una nueva manera de crear y compartir

información.

Las definiciones de declaraciones, permite al proceso de información realizar

inferencias y validación

18

Unidad 1. Sección 2.

Introducción a la

programación de la

Web Semántica 19

Framework de la Web

Semántica

Framework de la Web Semántica

Almacenamiento

Acceso

Inferencia

Fuente: [John Hebeler, Matthew Fisher, Ryan Blace, Andrew Perez-Lopez, Mike Dean. Semantic Web Programming]

20

Frameworks Web Semántica

Hay varios Framework para la Web Semántica pero los más usados son:

Jena Semantic Web Framework (http://jena.apache.org/) para

Java. Posee una interfaz SPARQL, APIs de RDF y OWL, soporta

inferencia, tiene múltiple almacenamiento y mecanismo de

razonamiento y también permite la integración de otros

mecanismos de razonamiento

Sesame Semantic Web Framework y servidor (http://rdf4j.org/).

Posee una interfaz SPARQL y una interfaz servidor HTTP. Posee

multiple almacenamiento y mecanismo de razonamiento y tambien

permite la integración de otros mecanismos de razonamiento

Otros Frameworks son los siguientes:

OWL API (http://owlapi.sourceforge.net/) para Java. Posee API OWL

que es contruido sobre el formato funcional de OWL 2 y contiene

una interfaz común interfaz para mecanismos de razonamiento

21

Frameworks Web Semántica

Otros Frameworks son los siguientes:

4Suite (http://4suite.org/) es un código abierto de XML y RDF, las

librerías de procesamiento para PYTHON.

RAP RDF API (http://wifo5-03.informatik.uni-

mannheim.de/bizer/rdfapi/). Es un códico abierto de API RDF y

un software para almacenar, consultar, y manipular RDF en PHP

Redland (http://librdf.org/). Colección de librerias de RDF para C.

con interfaz para otros lenguajes. Posee API RDF. Parser y una

interfaz de consultas

LinqToRDF (https://code.google.com/archive/p/linqtordf/) para

.NET construido sobre el Microsoft Language-Integrated Query

(LINQ)

22

Almacenamiento de RDF

AllegroGraph(http://franz.com/agraph/allegrograph): esta

disponible para implementación java y Lisp y posee una interfaz

SPARQL y razonamiento basado en RDFS

Mulgara (http://www.mulgara.org ): Esto es un código abierto,

almacenamiento RDF en Java con un procesador de consulta

SPARQL

OpenLink Virtouso (https://www.w3.org/wiki/VirtuosoUniversalServer)

Posee código abierto y una versión comercial de basado RDB para

el almacenamiento RDF. Posee SPARQL dentro SQL como método

de consulta de datos RDF

23

Motores de Razonamiento

FaCT++ (http://owl.man.ac.uk/factplusplus ): C++

que soporta un subconjunto OWL DL

Hermit (http://www.hermit-reasoner.com ): es un

razonador OWL. Se puede integrar en Protégé y

aplicaciones Java usando el OWL API

KAON2 (http://kaon2.semanticweb.org) : Java para

realizar razonamiento en ontologías OWL DL.

25

Motores de Razonamiento

Pellet (https://www.w3.org/2001/sw/wiki/Pellet) : es un

razonador en Java que soporta OWL DL, OWL

incluyendo OW2.

RacerPro (http://franz.com/agraph/racer): es un

razonador comercial que soporta un gran subconjunto

OWL DL.

Vampire (http://kaon2.semanticweb.org) : es un

razonador comercial, para realizar razonamiento en

ontologías OWL DL.

26

Jena Semantic Web Framework

Este Framework proporciona un entorno de

programación para RDF, RDFS y OWL, SPARQL e

incluye un motor de inferencia basado en reglas.

Esta compuesto por:

Una API RDF y OWL que permite crear y poblar

modelos RDF.

Leer y escribir RDF en formato RDF/XML, N3 y

N-Triples.

Un motor de persistencia en memoria y disco.

Consultar modelos usando tanto el lenguaje

propietario RDQL como SPARQL

Razonar sobre ontologías bien a través de

motores de reglas o razonamiento OWL

27

Ambiente de Desarrollo para la Web

Semántica Editor de Ontología

Clases

Instancias

Ontologías

Proyecto

Código

Consola

I.D:E

Razonador Framework Web Semántica

Motor de búsqueda

Almacenamiento

Administrador de

Ontologías

Razonador

Motor de reglas

D.I.G

.

Jar

28

swp2:me rdf:type foaf:Person .

swp2:me foaf:depiction <http://semwebprogramming.org/senweb.jpg >.

swp2:me foaf:family_name “Web” .

swp2:me foaf:givenname “Semantic” .

swp2:me foaf:homepage <http://semwebprogramming.org >.

swp2:me foaf:knows “Reasoner” .

swp2:me foaf:knows “Statement” .

swp2:me foaf:knows “Ontology” .

swp2:me foaf:name “Semantic Web” .

swp2:me foaf:nick “Webby” .

swp2:me foaf:phone “<tel:410-679-8999>” .

swp2:me foaf:schoolInfoHomepage <http://www.web.edu > .

swp2:me foaf:title “Dr.” .

swp2:me foaf:workInfoHomepage

<http://semwebprogramming.com/dataweb.html> .

swp2:me foaf:workplaceHomepage <http://semwebprogramming.com > .

Ejemplo

foaf:Person

swp2:me

rdf:type

<http://semwebprogramming.org/senweb.jpg>

foaf:depiction “Web”

foaf:family_name

“Semantic”

foaf:givenname

<http://semwebprogramming.org>

foaf:homepage

swp2:Reasoner

swp2:Statement swp2:Ontology

foaf:knows foaf:knows

foaf:knows

“Semantic Web”

foaf:name

“Webby”

foaf:nick “…”

29

Continuación del ejemplo

foaf:Person

swp2:Reasoner rdf:type foaf:Person .

swp2:Reasoner foaf:seeAlso

<http://reasoner.com > .

swp2:Reasoner foaf:mbox

<mailto:[email protected]> .

swp2:Reasoner foaf:name “Ican Reason” .

swp2:me

rdf:type

<http://semwebprogramming.org/senweb.jpg>

foaf:depiction “Web”

foaf:family_name

“Semantic”

foaf:givenname

<http://semwebprogramming.org>

foaf:homepage

swp2:Reasoner

swp2:Statement

swp2:Ontology

foaf:knows foaf:knows

foaf:knows

“Semantic Web”

foaf:name

“Webby”

foaf:nick “…”

rdf:type

<http://reasoner.com>

foaf:seeAls

o <mailto:[email protected]>

foaf:mailto

“Ican Reason”

foaf:name

30

Continuación del Ejemplo

foaf:Person

swp2:Statement rdf:type foaf:Person .

swp2:Statement foaf:seeAlso <http://statament.com > .

swp2:Statement foaf:mbox

<mailto:[email protected]> .

swp2:Statement foaf:name “Makea Statament” .

swp2:me

rdf:type

<http://semwebprogramming.org/senweb.jpg>

foaf:depiction “Web”

foaf:family_name

“Semantic”

foaf:givenname

<http://semwebprogramming.org>

foaf:homepage

swp2:Reasoner

swp2:Statement

swp2:Ontology

foaf:knows foaf:knows

foaf:knows

“Semantic Web”

foaf:name

“Webby”

foaf:nick “…”

rdf:type

<http://reasoner.com>

foaf:seeAlso

<mailto:[email protected]>

foaf:mailto

“Ican Reason”

foaf:name

“Makea Statament”

foaf:name

rdf:type

<http://statament.com>

foaf:seeAlso <mailto:[email protected]>

foaf:mailto

31

foaf:Person

swp2:Ontology rdf:type foaf:Person .

swp2:Ontology foaf:seeAlso <http://ont.com > .

swp2:Ontology foaf:mbox

<mailto:[email protected]> .

swp2:Ontology foaf:name “I. M. Ontology” .

swp2:me

rdf:type

<http://semwebprogramming.org/senweb.jpg>

foaf:depiction “Web”

foaf:family_name

“Semantic”

foaf:givenname

<http://semwebprogramming.org>

foaf:homepage

swp2:Reasoner

swp2:Statement

swp2:Ontology

foaf:knows

foaf:knows

foaf:knows

“Semantic Web”

foaf:name

“Webby”

foaf:nick “…”

rdf:type

<http://reasoner.com>

foaf:seeAlso

<mailto:[email protected]>

foaf:mailto

“Ican Reason”

foaf:name

“Makea

Statament”

foaf:name rdf:type

<http://statament.com>

foaf:seeAlso <mailto:[email protected]>

foaf:mailto

rdf:type

“I. M. Ontolgy”

foaf:name

<http://ont.com>

foaf:seeAlso

<mailto:[email protected]>

foaf:mailto

Continuación del Ejemplo 32

swp2:me rdf:type foaf:Person .

swp2:me foaf:depiction <http://semwebprogramming.org/senweb.jpg >.

swp2:me foaf:family_name “Web” .

swp2:me foaf:givenname “Semantic” .

swp2:me foaf:homepage <http://semwebprogramming.org >.

swp2:me foaf:knows “Reasoner” .

swp2:me foaf:knows “Statement” .

swp2:me foaf:knows “Ontology” .

swp2:me foaf:name “Semantic Web” .

swp2:me foaf:nick “Webby” .

swp2:me foaf:phone “<tel:410-679-8999>” .

swp2:me foaf:schoolInfoHomepage <http://www.web.edu > .

swp2:me foaf:title “Dr.” .

swp2:me foaf:workInfoHomepage

<http://semwebprogramming.com/dataweb.html> .

swp2:me foaf:workplaceHomepage <http://semwebprogramming.com > .

Consulta 1

foaf:Person

swp2:me

rdf:type

<http://semwebprogramming.org/senweb.jpg

>

foaf:depiction “Web”

foaf:family_name

“Semantic”

foaf:givenname

<http://semwebprogramming.org>

foaf:homepag

e

swp2:Reasoner

swp2:Statement swp2:Ontology

foaf:knows foaf:knows

foaf:knows

“Semantic

Web”

foaf:name

“Webby”

foaf:nick “…”

select DISTINCT ?name

where{ swp2:me foaf:name ?name }

swp2:me

“Semantic Web”

foaf:name

swp2:me

foaf:name

?name

33

private void runQuery(String queryRequest, Model model){

StringBuffer queryStr = new StringBuffer();

// Establish Prefixes

//Set default Name space first

queryStr.append("PREFIX people" + ": <" + defaultNameSpace + "> ");

queryStr.append("PREFIX rdfs" + ": <" + "http://www.w3.org/2000/01/rdf-schema#" + "> ");

queryStr.append("PREFIX rdf" + ": <" + "http://www.w3.org/1999/02/22-rdf-syntax-ns#" + "> ");

queryStr.append("PREFIX foaf" + ": <" + "http://xmlns.com/foaf/0.1/" + "> ");

//Now add query

queryStr.append(queryRequest);

Query query = QueryFactory.create(queryStr.toString());

QueryExecution qexec = QueryExecutionFactory.create(query, model);

try {

ResultSet response = qexec.execSelect();

while( response.hasNext()){

QuerySolution soln = response.nextSolution();

RDFNode name = soln.get("?name");

if( name != null ){

System.out.println( "Hello to " + name.toString() );

}

else

System.out.println("No Friends found!");

}

} finally { qexec.close();}

}

static String defaultNameSpace = "http://org.semwebprogramming/chapter2/swp2#";

Model _friends = null;

Model schema = null;

Función ejecutar la consulta 34

Ejecutar la consulta 1

private void populateFOAFFriends(){

_friends = ModelFactory.createOntologyModel();

InputStream inFoafInstance =

FileManager.get().open("Ontologies/FOAFFriends.rdf");

_friends.read(inFoafInstance,defaultNameSpace);

}

private void mySelf(Model model){

runQuery(" select DISTINCT ?name where{ people:me foaf:name ?name }", model);

//add the query string

}

public static void main(String[] args) throws

IOException {

HolaWebSemantica hello = new

HolaWebSemantica();

//Load my FOAF friends

System.out.println("Load my FOAF Friends");

hello.populateFOAFFriends();

// Say Hello to myself

System.out.println("\nSay Hello to Myself");

hello.mySelf(hello._friends);

}

Cargar la ontología

Consulta

Programa principal

Load my FOAF Friends

Say Hello to Myself

Hello to Semantic Web

Salida

35

rdf:type

foaf:Person

swp2:me

rdf:type

<http://semwebprogramming.org/senweb.jpg>

foaf:depiction “Web”

foaf:family_name

“Semantic”

foaf:givenname

<http://semwebprogramming.org>

foaf:homepag

e

swp2:Reasoner

swp2:Statement

swp2:Ontology

foaf:knows

foaf:knows

foaf:knows

“Semantic Web”

foaf:name

“Webby”

foaf:nick “…”

rdf:type

<http://reasoner.com>

foaf:seeAlso

<mailto:[email protected]

m>

foaf:mailto

“Ican Reason”

foaf:name

“Makea Statament”

foaf:name

<http://statament.com>

foaf:seeAlso <mailto:[email protected]>

foaf:mailto

rdf:type

“I. M. Ontolgy”

foaf:name

<http://ont.com>

foaf:seeAlso

<mailto:[email protected]>

foaf:mailto

select DISTINCT ?myname ?name

where{

swp2:me foaf:knows ?friend

?friend foaf:name ?name

}

foaf:name

swp2:me

foaf:knows

?friends

?name

swp2:me

“Makea Statament”

foaf:name

“Ican Reason”

foaf:name

“I. M. Ontolgy”

foaf:name Consulta 2 36

Ejecutar Consulta 2

private void populateFOAFFriends(){

_friends = ModelFactory.createOntologyModel();

InputStream inFoafInstance =

FileManager.get().open("Ontologies/FOAFFriends.rdf");

_friends.read(inFoafInstance,defaultNameSpace);

}

private void myFriends(Model model){

runQuery(" select DISTINCT ?myname ?name where{ people:me foaf:knows ?friend. ?friend foaf:name

?name } ", model);

}

public static void main(String[] args) throws

IOException {

HolaWebSemantica hello = new

HolaWebSemantica();

//Load my FOAF friends

hello.populateFOAFFriends();

// Say Hello to my FOAF Friends

System.out.println("\nSay Hello to my FOAF

Friends");

hello.myFriends(hello._friends);

}

Cargar la ontología

Consulta

Programa principal

Say Hello to my FOAF Friends

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Salida

37

people:Individual_5 rdf:type people:Individual .

people:Individual_5 people:hasName “Sem Web”.

people:Individual_5 people:hasfriends Individual_6 .

people:Individual_5 people:hasfriends Individual_7.

people:Individual_6 people:hasfName “Web O. Data” .

people:Individual_7 people:hasfName “Mr. OWL” .

Amigos adicionales desde diferente fuente, con vocabulario diferente

people:Individual

people:hasfriends

people:hasName

people:hasName

People:Individual

people:Individual_5

rdf:type

people:Individual_7

people:Individual_6

people:hasfriends

people:hasfriends

“Sem Web”

people:hasName

“Mr. OWL”

rdf:type rdf:type

“Web O. Data”

people:hasNam

e

Instancia

Esquema

Agregar otra fuente de información 38

Agregar nuevos amigos private void populateNewFriendsSchema() throws IOException {

InputStream inFoafInstance = FileManager.get().open("Ontologies/additionalFriendsSchema.owl");

_friends.read(inFoafInstance,defaultNameSpace);

inFoafInstance.close();

}

public static void main(String[] args) throws IOException {

HolaWebSemantica hello = new HolaWebSemantica();

//Load my FOAF friends

hello.populateFOAFFriends();

// Say Hello to my FOAF Friends

System.out.println("\nSay Hello to my FOAF Friends");

hello.myFriends(hello._friends);

//Add my new friends

System.out.println("\nadd my new friends");

hello.populateNewFriends();

//Say hello to my friends - hey my new ones are missing?

System.out.println("\nSay hello to all my friends - hey the

new ones are missing!");

hello.myFriends(hello._friends);

}

Say Hello to Myself

Hello to Semantic Web

Say Hello to my FOAF Friends

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

add my new friends

Say hello to all my friends - hey the new

ones are missing!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

39

Esquemas

people:Individual

people:hasfriends

people:hasName

Esquema

foaf:Person

foaf:knows

foaf:Name

Esquema

foaf:mbox

40

¿Porque no se muestra los

amigos adicionales? private void populateNewFriendsSchema() throws IOException {

InputStream inFoafInstance = FileManager.get().open("Ontologies/additionalFriendsSchema.owl");

_friends.read(inFoafInstance,defaultNameSpace);

inFoafInstance.close();

}

public static void main(String[] args) throws IOException {

HolaWebSemantica hello = new

HolaWebSemantica();

//Load my FOAF friends

hello.populateFOAFFriends();

// Say Hello to my FOAF Friends

System.out.println("\nSay Hello to my FOAF Friends");

hello.myFriends(hello._friends);

//Add my new friends

System.out.println("\nadd my new friends");

hello.populateNewFriends();

//Say hello to my friends - hey my new ones are

missing?

System.out.println("\nSay hello to all my friends - hey

the new ones are missing!");

hello.myFriends(hello._friends);

}

Say Hello to Myself

Hello to Semantic Web

Say Hello to my FOAF Friends

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

add my new friends

Say hello to all my friends - hey the new ones are

missing!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

41

private void populateFOAFSchema() throws IOException{

InputStream inFoaf2;

try (InputStream inFoaf = FileManager.get().open("Ontologies/foaf.rdf")) {

inFoaf2 = FileManager.get().open("Ontologies/foaf.rdf");

schema = ModelFactory.createOntologyModel();

schema.read(inFoaf, defaultNameSpace);

_friends.read(inFoaf2, defaultNameSpace);

}

inFoaf2.close();

}

public static void main(String[] args) throws IOException {

//Add my new friends

System.out.println("\nadd my new friends");

hello.populateNewFriends();

//Say hello to my friends - hey my new ones are missing?

System.out.println("\nSay hello to all my friends - hey the

new ones are missing!");

hello.myFriends(hello._friends);

// Add the ontologies

System.out.println("\nAdd the Ontologies");

hello.populateFOAFSchema();

hello.populateNewFriendsSchema();

//See if the ontologies help identify my new friends?

Nope!

System.out.println("\nSee if the ontologies help to say

hello to all my friends - Nope!");

hello.myFriends(hello._friends);

}

Say Hello to Myself

Hello to Semantic Web

Say Hello to my FOAF Friends

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

add my new friends

Say hello to all my friends - hey the new ones are

missing!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Add the Ontologies

See if the ontologies help to say hello to all my

friends - Nope!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Agregando el nuevo Esquema

Sigue sin mostrar los

amigos adicionales

¿Por qué?

42

Alineando

people:Individual owl:equivalenteClass foaf:Person .

people:hasName owl:equivalentProperty foaf:Name.

people:hasfriends rdfs:subPropertyOf foaf:Knows .

43

people:Individual

people:hasfriends

people:hasName

Esquema

foaf:Person

foaf:knows

foaf:Name

Esquema

foaf:mbox

Alineando

people:Individual

people:hasfriends

people:hasName

foaf:Person

foaf:knows

foaf:Name foaf:mbox

people:Individual owl:equivalenteClass foaf:Person .

people:hasName owl:equivalentProperty foaf:Name.

people:hasfriends rdfs:subPropertyOf foaf:Knows .

rdfs:supPropertyOf

owl:equivalenteClass

owl:equivalenteProperty

people:Individual_5

“Sem Web”

people:hasName

rdf:type

swp2:me

“Semantic Web”

foaf:name

rdf:type

owl:sameAs

44

private void addAlignment(){

// State that :individual is equivalentClass of foaf:Person

Resource resource = schema.createResource(defaultNameSpace + "Individual");

Property prop = schema.createProperty("http://www.w3.org/2002/07/owl#equivalentClass");

Resource obj = schema.createResource("http://xmlns.com/foaf/0.1/Person");

schema.add(resource,prop,obj);

//State that :hasName is an equivalentProperty of foaf:name

resource = schema.createResource(defaultNameSpace + "hasName");

//prop = schema.createProperty("http://www.w3.org/2000/01/rdf-schema#subPropertyOf");

prop = schema.createProperty("http://www.w3.org/2002/07/owl#equivalentProperty");

obj = schema.createResource("http://xmlns.com/foaf/0.1/name");

schema.add(resource,prop,obj);

//State that :hasFriend is a subproperty of foaf:knows

resource = schema.createResource(defaultNameSpace + "hasFriend");

prop = schema.createProperty("http://www.w3.org/2000/01/rdf-schema#subPropertyOf");

obj = schema.createResource("http://xmlns.com/foaf/0.1/knows");

schema.add(resource,prop,obj);

//State that sem web is the same person as Semantic Web

resource =

schema.createResource("http://org.semwebprogramming/chapter2/people#me");

prop = schema.createProperty("http://www.w3.org/2002/07/owl#sameAs");

obj =

schema.createResource("http://org.semwebprogramming/chapter2/people#Individual_5");

schema.add(resource,prop,obj);

}

Función de Alineación 45

public static void main(String[] args) throws IOException {

HolaWebSemantica hello = new HolaWebSemantica();

//Add my new friends

System.out.println("\nadd my new friends");

hello.populateNewFriends();

//Say hello to my friends - hey my new ones are

missing?

System.out.println("\nSay hello to all my friends - hey the

new ones are missing!");

hello.myFriends(hello._friends);

// Add the ontologies

System.out.println("\nAdd the Ontologies");

hello.populateFOAFSchema();

hello.populateNewFriendsSchema();

//See if the ontologies help identify my new friends?

Nope!

System.out.println("\nSee if the ontologies help to say

hello to all my friends - Nope!");

hello.myFriends(hello._friends);

//Align the ontologies to bind my friends together

System.out.println("\nOk, lets add alignment statements

for the two ontologies."); hello.addAlignment();

//Now say hello to my friends - nope still no new friends!

System.out.println("\nTry again - Hello to all my friends -

nope still not all!");

hello.myFriends(hello._friends);

}

add my new friends

Say hello to all my friends - hey the new ones are

missing!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Add the Ontologies

See if the ontologies help to say hello to all my

friends - Nope!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Ok, lets add alignment statements for the two

ontologies.

Try again - Hello to all my friends - nope still not

all!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Sigue sin mostrar los

amigos adicionales

¿Por qué?

Alineando 46

private void bindReasoner(){

Reasoner reasoner = ReasonerRegistry.getOWLReasoner();

reasoner = reasoner.bindSchema(schema);

inferredFriends = ModelFactory.createInfModel(reasoner, _friends);

}

public static void main(String[] args) throws

IOException {

HolaWebSemantica hello = new

HolaWebSemantica();

………

//Align the ontologies to bind my friends

together

System.out.println("\nOk, lets add alignment

statements for the two ontologies.");

hello.addAlignment();

//Now say hello to my friends - nope still no new

friends!

System.out.println("\nTry again - Hello to all my

friends - nope still not all!");

hello.myFriends(hello._friends);

//Run reasoner to align the instances

System.out.println("\nRun a Reasoner");

hello.bindReasoner();

System.out.println("\fFinally- Hello to all my

friends!");

hello.myFriends(hello.inferredFriends);

}

Add the Ontologies

See if the ontologies help to say hello to all my

friends - Nope!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Ok, lets add alignment statements for the two

ontologies.

Try again - Hello to all my friends - nope still not

all!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Run a Reasoner

Finally- Hello to all my friends!

Hello to I. M. Ontology

Hello to Ican Reason

Hello to Makea Statement

Hello to Mr. Owl

Hello to Web O. Data

Invocando el razonador 47

people:EmailPerson

rdf:type owl:Class ;

rdfs:subClassOf foaf:person;

owl:equivalentClass

[ rdf:type owl:Restriction; owl:minCardinality “ 1 “ ᶺᶺxsd:nonNegativeInteger;

owl:onProperty foaf:mbox

] .

public void setRestriction(Model model) throws IOException{

// Load restriction - if entered in model with reasoner, reasoner sets entailments

InputStream inResInstance = FileManager.get().open("Ontologies/restriction.owl");

model.read(inResInstance,defaultNameSpace);

inResInstance.close();

}

public void myGmailFriends(Model model){

runQuery(" select DISTINCT ?name where{ ?sub rdf:type people:GmailPerson. ?sub foaf:name

?name } ", model);

}

Definiendo restricción 48

public static void main(String[] args) throws

IOException {

HolaWebSemantica hello = new

HolaWebSemantica();

………

//Align the ontologies to bind my friends

together

System.out.println("\nOk, lets add alignment

statements for the two ontologies.");

hello.addAlignment();

//Now say hello to my friends - nope still no new

friends!

System.out.println("\nTry again - Hello to all my

friends - nope still not all!");

hello.myFriends(hello._friends);

//Run reasoner to align the instances

System.out.println("\nRun a Reasoner");

hello.bindReasoner();

System.out.println("\fFinally- Hello to all my

friends!");

hello.myFriends(hello.inferredFriends);

System.out.println("\nEstablishing a restriction

to just get email friends");

hello.setRestriction(hello.inferredFriends);

hello.myEmailFriends(hello.inferredFriends);

}

Add the Ontologies

See if the ontologies help to say hello to all my

friends - Nope!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Ok, lets add alignment statements for the two

ontologies.

Try again - Hello to all my friends - nope still not

all!

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Run a Reasoner

Finally- Hello to all my friends!

Hello to I. M. Ontology

Hello to Ican Reason

Hello to Makea Statement

Hello to Mr. Owl

Hello to Web O. Data

Establishing a restriction to just get email friends

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Ejecutando la restricción 49

private void runJenaRule(Model model){

String rules = "[emailChange: (?person <http://xmlns.com/foaf/0.1/mbox> ?email),

strConcat(?email, ?lit),

regex( ?lit, '(.*@gmail.com)') ->

(?person <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>

<http://org.semwebprogramming/chapter2/people#GmailPerson>)]";

Reasoner ruleReasoner = new GenericRuleReasoner(Rule.parseRules(rules));

ruleReasoner = ruleReasoner.bindSchema(schema);

inferredFriends = ModelFactory.createInfModel(ruleReasoner, model);

}

Definiendo reglas 50

public static void main(String[] args) throws

IOException {

HolaWebSemantica hello = new

HolaWebSemantica();

………

//Now say hello to my friends - nope still no new

friends!

System.out.println("\nTry again - Hello to all my

friends - nope still not all!");

hello.myFriends(hello._friends);

//Run reasoner to align the instances

System.out.println("\nRun a Reasoner");

hello.bindReasoner();

System.out.println("\fFinally- Hello to all my

friends!");

hello.myFriends(hello.inferredFriends);

System.out.println("\nEstablishing a restriction

to just get email friends");

hello.setRestriction(hello.inferredFriends);

hello.myEmailFriends(hello.inferredFriends);

System.out.println("\nSay hello to my gmail

friends only");

hello.runJenaRule(hello.inferredFriends);

hello.myGmailFriends(hello.inferredFriends);

}

Run a Reasoner

Finally- Hello to all my friends!

Hello to I. M. Ontology

Hello to Ican Reason

Hello to Makea Statement

Hello to Mr. Owl

Hello to Web O. Data

Establishing a restriction to just get email friends

Hello to Makea Statement

Hello to Ican Reason

Hello to I. M. Ontology

Say hello to my gmail friends only

Hello to Makea Statement

Hello to I. M. Ontology

Definiendo reglas 51

Porque el Señor da la sabiduría;

conocimiento y ciencia brotan de sus

labios. - Proverbios 2:6

52