Está en la página 1de 53

Tópicos Especiales:

Programación de la
1
Web Semántica
Postgrado en Computación
Taniana Rodríguez
Semestre A2016
Abril-2016
2 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
3 Evaluación

Tareas . 10%
Artículo de investigación de
estado del arte. 20%
Proyecto práctico y artículo 70%
4 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
Unidad 1. Sección 1.
Introducción a la
5
Web Semántica
6 WWW Actual 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
Cómo puede un agente o reconocer el significado y sacar conclusiones e
computador entender esta inferir nueve conocimiento utilizando el contexto y
Web? entender el conocimiento relacionado
 Información recuperada por los motores de
búsquedas
Enlaces  Es un gran repositorio de información

Contenido no estructurado

Imágenes
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
7 Agentes o Computadores entender
la Web?
Nombre

Universidad de los Andes


Cosa ….
Ubicación
ULA ….
Estado Mérida

Nucleó Mérida

José Pérez Trabaja


en
Trabaja con Juan
Jose
15/10/94 Tener un lenguaje que permita
especificar recursos y sus relaciones
 Lenguaje sea procesado por el
Mérida Trabaja computador
en Consultar los datos mediante s
aplicaciones o agentes
 Lenguaje de consulta que sea
procesable por el computador
8 ¿Qué es la Web Semántica?

“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”

“El primer paso es colocar los datos en la


Web de un modo que las máquinas Tim Beners-Lee
puedan entenderlos naturalmente o
convertirlos a esa forma. Esto crea lo que
yo llamo la Web Semántica: una red de Linked data es otro
datos que pueden ser procesados nombre para la red de
directa o indirectamente por máquinas” datos
9 ¿Qué es la Web Semántica?
Web Semántica

Definición

Origen Componentes Características

 Expresividad
 LD  Inferencia
 Teoría de Grafo WS Herramientas WS
 Integración
 Unicidad
 Declaración  Frameworks
 Lenguajes  IDE
 Ontologías  Razonadores
 Instancias  KB

Fuente: [John Hebeler, Matthew Fisher, Ryan Blace, Andrew Perez-Lopez, Mike Dean. Semantic
Web Programming]
10 Comparación de WWW y WS

Características WWW WS
Componente Contenido no Declaraciones formales
fundamental estructurado
Audiencia Humanos Aplicaciones
Enlaces Indica ubicación Indica ubicación y
significado
Vocabulario Instrucciones Semántica y lógica
Formateada
Lógica Informal/No estándar Lógica descriptiva

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


Perez-Lopez, Mike Dean. Semantic Web Programming]
11 Arquitectura de la Semántica
Se basa en dos puntos fundamentales
 La descripción del significado
 La manipulación automática de
estas descripciones

Semántica Web

Esta compuesta por


Instancias
Inferencias
Ontologías

Lenguajes
XML SPARQL

RDF RDF-S OWL

 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
12 Visión de la Infraestructura
de la Web

https://www.w3.org/
13 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)

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
14 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
15 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
16 Ejemplo de Linked Data

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
17 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”
18 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
Unidad 1. Sección 2.
Introducción a la
19
programación de la
Web Semántica
20 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. Sem
Web Programming]
21 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
22 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)
23 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
24 Almacenamiento de RDF

 Oracle 11g (http://www.oracle.com): Soporte para RDF y


reglas en Oracle Database. También soporta un
subconjunto de OWL, transacciones y seguridad
 OWLIM (https://www.w3.org/2001/sw/wiki/Owlim): Esto es un
código abierto, almacenamiento RDF en Java y soporta
inferencia usando RDFS y un subconjunto OWL
 Parliament (http://parliament.semwebcentral.org) :
implementación en C++ para el almacenamiento RDF
25 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.
26 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.
27 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
Ambiente de Desarrollo para la Web
28
Semántica
Editor de Ontología I.D:E

Clases Instancias Proyecto Código

Ontologías Consola

Jar
D.I.G.

Razonador Framework Web Semántica

Motor de búsqueda

Almacenamiento

Administrador de
Ontologías

Razonador

Motor de reglas
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” .

29 Ejemplo 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 > .

swp2:Statement
swp2:Ontology

swp2:Reasoner
foaf:Person
foaf:knows
foaf:knows
foaf:knows
rdf:type

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

“Semantic” foaf:depiction “Web”



foaf:name foaf:nick
<http://semwebprogramming.org/senweb.jpg> “…”

“Webby”
“Semantic Web”
30 Continuación del ejemplo
swp2:Reasoner rdf:type foaf:Person .
swp2:Reasoner foaf:seeAlso
<http://reasoner.com > .
foaf:Person swp2:Reasoner foaf:mbox
<mailto:reason@hotmail.com> .
swp2:Reasoner foaf:name “Ican Reason” .

rdf:type
“Ican Reason”
swp2:Statement
foaf:name

swp2:Ontology
swp2:Reasoner
foaf:knows
foaf:knows
foaf:knows
rdf:type
foaf:mailto
foaf:seeAls foaf:homepage
o swp2:me
<mailto:reason@hotmail.com> <http://semwebprogramming.org>
foaf:givenname
<http://reasoner.com> foaf:family_name

“Semantic” foaf:depiction “Web”


<http://semwebprogramming.org/senweb.jpg> foaf:name
foaf:nick “…”

“Webby”
“Semantic Web”
31 Continuación del Ejemplo
swp2:Statement rdf:type foaf:Person .
swp2:Statement foaf:seeAlso <http://statament.com > .
swp2:Statement foaf:mbox foaf:Person
<mailto:mstatement@gmail.com> .
swp2:Statement foaf:name “Makea Statament” . rdf:type “Makea Statament”

foaf:name
rdf:type
“Ican Reason”
swp2:Statement
foaf:name
foaf:mailto
swp2:Ontology
foaf:knows
swp2:Reasoner foaf:seeAlso <mailto:mstatement@gmail.com>
foaf:knows
foaf:knows <http://statament.com>
rdf:type
foaf:mailto
foaf:seeAlso foaf:homepage
swp2:me
<mailto:reason@hotmail.com> <http://semwebprogramming.org>
foaf:givenname
<http://reasoner.com> foaf:family_name

“Semantic” foaf:depiction “Web”


<http://semwebprogramming.org/senweb.jpg> foaf:name
foaf:nick “…”

“Webby”
“Semantic Web”
32 Continuación del Ejemplo
swp2:Ontology rdf:type foaf:Person .
swp2:Ontology foaf:seeAlso <http://ont.com > .
swp2:Ontology foaf:mbox foaf:Person
<mailto:ont@gmail.com> . “Makea
swp2:Ontology foaf:name “I. M. Ontology” . Statament”
rdf:type
rdf:type foaf:name
rdf:type
“Ican Reason” “I. M. Ontolgy”
swp2:Statement
foaf:name foaf:name
rdf:type foaf:mailto
foaf:seeAlso swp2:Ontology
foaf:knows
swp2:Reasoner foaf:seeAlso <mailto:mstatement@gmail.com>
<http://ont.com> foaf:knows
foaf:mailto
<http://statament.com>
<mailto:ont@gmail.com>
foaf:knows
foaf:mailto
foaf:seeAlso foaf:homepage
swp2:me
<mailto:reason@hotmail.com> <http://semwebprogramming.org>
foaf:givenname
<http://reasoner.com> foaf:family_name

“Semantic” foaf:depiction “Web”


<http://semwebprogramming.org/senweb.jpg> foaf:name
foaf:nick “…”

“Webby”
“Semantic Web”
swp2:me rdf:type foaf:Person .
swp2:me foaf:depiction <http://semwebprogramming.org/senweb.jpg >.
swp2:me foaf:family_name “Web” .

Consulta 1
swp2:me foaf:givenname “Semantic” .
33 swp2:me foaf:homepage <http://semwebprogramming.org >.
swp2:me foaf:knows “Reasoner” .
swp2:me foaf:knows “Statement” .
swp2:me foaf:knows “Ontology” .
select DISTINCT ?name swp2:me foaf:name “Semantic Web” .
swp2:me foaf:nick “Webby” .
where{ swp2:me foaf:phone “<tel:410-679-8999>” .
swp2:me foaf:name swp2:me foaf:schoolInfoHomepage <http://www.web.edu > .
swp2:me foaf:title “Dr.” .
?name swp2:me foaf:workInfoHomepage
} <http://semwebprogramming.com/dataweb.html> .
swp2:me foaf:workplaceHomepage <http://semwebprogramming.com > .

swp2:Ontology swp2:Statement

swp2:Reasoner
foaf:Person
foaf:name
foaf:knows
foaf:knows swp2:me ?name
foaf:knows
rdf:type

foaf:homepag
swp2:me e swp2:me
<http://semwebprogramming.org>
foaf:givenname
foaf:family_name

“Semantic” foaf:depiction “Web” foaf:name



<http://semwebprogramming.org/senweb.jpg foaf:name foaf:nick
> “…”

“Webby”
“Semantic
“Semantic Web”
Web”
34 Función ejecutar la consulta
static String defaultNameSpace = "http://org.semwebprogramming/chapter2/swp2#";
Model _friends = null;
Model schema = null;
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();}
}
35 Ejecutar la consulta 1
private void populateFOAFFriends(){
_friends = ModelFactory.createOntologyModel();
InputStream inFoafInstance = Cargar la ontología
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); Consulta
//add the query string
}

public static void main(String[] args) throws


IOException {
HolaWebSemantica hello = new Programa principal
HolaWebSemantica();

//Load my FOAF friends


System.out.println("Load my FOAF Friends");
hello.populateFOAFFriends(); Load my FOAF Friends
Say Hello to Myself
Salida
// Say Hello to myself Hello to Semantic Web
System.out.println("\nSay Hello to Myself");
hello.mySelf(hello._friends);
}
36 Consulta 2 ?name
“Ican Reason”

foaf:name
foaf:name
“I. M. Ontolgy”

foaf:name
foaf:knows swp2:me

select DISTINCT ?myname ?name swp2:me ?friends

where{ foaf:name
swp2:me foaf:knows ?friend
?friend foaf:name ?name foaf:Person “Makea Statament”
}
“Makea Statament”
rdf:type
rdf:type foaf:name
rdf:type
“Ican Reason”
“I. M. Ontolgy” swp2:Statement
foaf:name foaf:name
rdf:type foaf:mailto
foaf:seeAlso swp2:Ontology
foaf:knows
swp2:Reasoner foaf:seeAlso <mailto:mstatement@gmail.com>
<http://ont.com> foaf:knows
foaf:mailto
<http://statament.com>
<mailto:ont@gmail.com>
foaf:knows
foaf:mailto
foaf:seeAlso foaf:homepag
<mailto:reason@hotmail.co swp2:me e
<http://semwebprogramming.org>
m>
foaf:givenname
<http://reasoner.com> foaf:family_name

“Semantic” foaf:depiction “Web”


<http://semwebprogramming.org/senweb.jpg> foaf:name
foaf:nick “…”

“Webby”
“Semantic Web”
37 Ejecutar Consulta 2

private void populateFOAFFriends(){


_friends = ModelFactory.createOntologyModel();
InputStream inFoafInstance = Cargar la ontología
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);
}
Consulta
public static void main(String[] args) throws
IOException {
HolaWebSemantica hello = new
HolaWebSemantica(); Programa principal
//Load my FOAF friends Say Hello to my FOAF Friends
hello.populateFOAFFriends(); Hello to Makea Statement
Hello to Ican Reason Salida
// Say Hello to my FOAF Friends Hello to I. M. Ontology
System.out.println("\nSay Hello to my FOAF
Friends");
hello.myFriends(hello._friends);
}
38 Agregar otra fuente de información
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” .

People:Individual Instancia
“Mr. OWL”
rdf:type
rdf:type people:hasName

people:Individual_7

rdf:type Esquema
people:Individual_6
people:hasfriends

people:hasNam people:hasfriends
e people:Individual
people:hasfriends
“Web O. Data”

people:Individual_5 people:hasName

people:hasName

“Sem Web”

Amigos adicionales desde diferente fuente, con vocabulario diferente


39 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(); Say Hello to Myself
Hello to Semantic Web
//Load my FOAF friends
hello.populateFOAFFriends(); Say Hello to my FOAF Friends
Hello to Makea Statement
// Say Hello to my FOAF Friends Hello to Ican Reason
System.out.println("\nSay Hello to my FOAF Friends"); Hello to I. M. Ontology
hello.myFriends(hello._friends);
add my new friends
//Add my new friends
System.out.println("\nadd my new friends"); Say hello to all my friends - hey the new
hello.populateNewFriends(); ones are missing!
Hello to Makea Statement
//Say hello to my friends - hey my new ones are missing? Hello to Ican Reason
System.out.println("\nSay hello to all my friends - hey the Hello to I. M. Ontology
new ones are missing!");
hello.myFriends(hello._friends);
}
40 Esquemas

Esquema Esquema
foaf:knows
people:hasfriends

foaf:Person
people:Individual

foaf:mbox
foaf:Name
people:hasName
41 ¿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(); Say Hello to Myself
Hello to Semantic Web
//Load my FOAF friends
hello.populateFOAFFriends(); Say Hello to my FOAF Friends
Hello to Makea Statement
// Say Hello to my FOAF Friends Hello to Ican Reason
System.out.println("\nSay Hello to my FOAF Friends"); Hello to I. M. Ontology
hello.myFriends(hello._friends);
add my new friends
//Add my new friends
System.out.println("\nadd my new friends"); Say hello to all my friends - hey the new ones are
hello.populateNewFriends(); missing!
Hello to Makea Statement
//Say hello to my friends - hey my new ones are Hello to Ican Reason
missing? Hello to I. M. Ontology
System.out.println("\nSay hello to all my friends - hey
the new ones are missing!");
hello.myFriends(hello._friends);
}
42 Agregando el nuevo Esquema
private void populateFOAFSchema() throws IOException{
InputStream inFoaf2;
try (InputStream inFoaf = FileManager.get().open("Ontologies/foaf.rdf")) { Sigue sin mostrar los
inFoaf2 = FileManager.get().open("Ontologies/foaf.rdf");
schema = ModelFactory.createOntologyModel();
amigos adicionales
schema.read(inFoaf, defaultNameSpace); ¿Por qué?
_friends.read(inFoaf2, defaultNameSpace); Say Hello to Myself
} Hello to Semantic Web
inFoaf2.close();
} Say Hello to my FOAF Friends
public static void main(String[] args) throws IOException { Hello to Makea Statement
//Add my new friends Hello to Ican Reason
System.out.println("\nadd my new friends"); Hello to I. M. Ontology
hello.populateNewFriends();
//Say hello to my friends - hey my new ones are missing? add my new friends
System.out.println("\nSay hello to all my friends - hey the
new ones are missing!"); Say hello to all my friends - hey the new ones are
hello.myFriends(hello._friends); missing!
// Add the ontologies Hello to Makea Statement
System.out.println("\nAdd the Ontologies"); Hello to Ican Reason
hello.populateFOAFSchema(); Hello to I. M. Ontology
hello.populateNewFriendsSchema();
//See if the ontologies help identify my new friends? Add the Ontologies
Nope!
System.out.println("\nSee if the ontologies help to say See if the ontologies help to say hello to all my
hello to all my friends - Nope!"); friends - Nope!
hello.myFriends(hello._friends); Hello to Makea Statement
} Hello to Ican Reason
Hello to I. M. Ontology
43 Alineando

Esquema Esquema
foaf:knows
people:hasfriends

foaf:Person
people:Individual

foaf:mbox
foaf:Name
people:hasName

people:Individual owl:equivalenteClass foaf:Person .


people:hasName owl:equivalentProperty foaf:Name.
people:hasfriends rdfs:subPropertyOf foaf:Knows .
44 Alineando
people:Individual owl:equivalenteClass foaf:Person .
people:hasName owl:equivalentProperty foaf:Name.
people:hasfriends rdfs:subPropertyOf foaf:Knows .

rdfs:supPropertyOf

foaf:knows
people:hasfriends

owl:equivalenteClass
foaf:Person
people:Individual

owl:equivalenteProperty
foaf:mbox foaf:Name
rdf:type people:hasName
rdf:type

owl:sameAs
swp2:me
people:Individual_5

people:hasName

foaf:name
“Sem Web”

“Semantic Web”
45 Función de Alineación
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);
}
46
Alineando
Sigue sin mostrar los
amigos adicionales
public static void main(String[] args) throws IOException {
HolaWebSemantica hello = new HolaWebSemantica(); ¿Por qué?
//Add my new friends
System.out.println("\nadd my new friends");
hello.populateNewFriends();
add my new friends
//Say hello to my friends - hey my new ones are
missing?
Say hello to all my friends - hey the new ones are
System.out.println("\nSay hello to all my friends - hey the
missing!
new ones are missing!");
Hello to Makea Statement
hello.myFriends(hello._friends);
Hello to Ican Reason
// Add the ontologies
Hello to I. M. Ontology
System.out.println("\nAdd the Ontologies");
hello.populateFOAFSchema();
Add the Ontologies
hello.populateNewFriendsSchema();
//See if the ontologies help identify my new friends?
See if the ontologies help to say hello to all my
Nope!
friends - Nope!
System.out.println("\nSee if the ontologies help to say
Hello to Makea Statement
hello to all my friends - Nope!");
Hello to Ican Reason
hello.myFriends(hello._friends);
Hello to I. M. Ontology
//Align the ontologies to bind my friends together
Ok, lets add alignment statements for the two
System.out.println("\nOk, lets add alignment statements
ontologies.
for the two ontologies.");
hello.addAlignment();
Try again - Hello to all my friends - nope still not
all!
//Now say hello to my friends - nope still no new friends!
Hello to Makea Statement
System.out.println("\nTry again - Hello to all my friends -
Hello to Ican Reason
nope still not all!");
Hello to I. M. Ontology
hello.myFriends(hello._friends);
}
47 Invocando el razonador
private void bindReasoner(){
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
reasoner = reasoner.bindSchema(schema);
inferredFriends = ModelFactory.createInfModel(reasoner, _friends);
}
Add the Ontologies
public static void main(String[] args) throws
IOException { See if the ontologies help to say hello to all my
HolaWebSemantica hello = new friends - Nope!
HolaWebSemantica(); Hello to Makea Statement
……… Hello to Ican Reason
//Align the ontologies to bind my friends Hello to I. M. Ontology
together Ok, lets add alignment statements for the two
System.out.println("\nOk, lets add alignment ontologies.
statements for the two ontologies.");
hello.addAlignment(); Try again - Hello to all my friends - nope still not
all!
//Now say hello to my friends - nope still no new Hello to Makea Statement
friends! Hello to Ican Reason
System.out.println("\nTry again - Hello to all my Hello to I. M. Ontology
friends - nope still not all!");
hello.myFriends(hello._friends); Run a Reasoner
//Run reasoner to align the instances Finally- Hello to all my friends!
System.out.println("\nRun a Reasoner"); Hello to I. M. Ontology
hello.bindReasoner(); Hello to Ican Reason
System.out.println("\fFinally- Hello to all my Hello to Makea Statement
friends!"); Hello to Mr. Owl
hello.myFriends(hello.inferredFriends); Hello to Web O. Data
}
48 Definiendo restricción
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);
}
49 Ejecutando la restricción
Add the Ontologies

public static void main(String[] args) throws See if the ontologies help to say hello to all my
IOException { friends - Nope!
HolaWebSemantica hello = new Hello to Makea Statement
HolaWebSemantica(); Hello to Ican Reason
……… Hello to I. M. Ontology
//Align the ontologies to bind my friends Ok, lets add alignment statements for the two
together ontologies.
System.out.println("\nOk, lets add alignment
statements for the two ontologies."); Try again - Hello to all my friends - nope still not
hello.addAlignment(); all!
Hello to Makea Statement
//Now say hello to my friends - nope still no new Hello to Ican Reason
friends! Hello to I. M. Ontology
System.out.println("\nTry again - Hello to all my
friends - nope still not all!"); Run a Reasoner
hello.myFriends(hello._friends); Finally- Hello to all my friends!
//Run reasoner to align the instances Hello to I. M. Ontology
System.out.println("\nRun a Reasoner"); Hello to Ican Reason
hello.bindReasoner(); Hello to Makea Statement
System.out.println("\fFinally- Hello to all my Hello to Mr. Owl
friends!"); Hello to Web O. Data
hello.myFriends(hello.inferredFriends);
System.out.println("\nEstablishing a restriction Establishing a restriction to just get email friends
to just get email friends"); Hello to Makea Statement
hello.setRestriction(hello.inferredFriends); Hello to Ican Reason
hello.myEmailFriends(hello.inferredFriends); Hello to I. M. Ontology
}
50 Definiendo reglas

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);
}
51 Definiendo reglas
public static void main(String[] args) throws
IOException {
HolaWebSemantica hello = new
HolaWebSemantica();
……… Run a Reasoner
//Now say hello to my friends - nope still no new Finally- Hello to all my friends!
friends! Hello to I. M. Ontology
System.out.println("\nTry again - Hello to all my Hello to Ican Reason
friends - nope still not all!"); Hello to Makea Statement
hello.myFriends(hello._friends); Hello to Mr. Owl
//Run reasoner to align the instances Hello to Web O. Data
System.out.println("\nRun a Reasoner");
hello.bindReasoner(); Establishing a restriction to just get email friends
System.out.println("\fFinally- Hello to all my Hello to Makea Statement
friends!"); Hello to Ican Reason
hello.myFriends(hello.inferredFriends); Hello to I. M. Ontology
System.out.println("\nEstablishing a restriction
to just get email friends"); Say hello to my gmail friends only
hello.setRestriction(hello.inferredFriends); Hello to Makea Statement
hello.myEmailFriends(hello.inferredFriends); Hello to I. M. Ontology
System.out.println("\nSay hello to my gmail
friends only");
hello.runJenaRule(hello.inferredFriends);
hello.myGmailFriends(hello.inferredFriends);
}
52

Porque el Señor da la sabiduría;


conocimiento y ciencia brotan de sus
labios. - Proverbios 2:6
53 Bibliografía

 Web Semántica: la aplicaciones actuales (Consultado


en marzo de 2016 http://es.ccm.net/faq/7082-web-
semantica-las-aplicaciones-actuales)
 John Hebeler, Matthew Fisher, Ryan Blace, Andrew
Perez-Lopez, Mike Dean. Semantic Web Programming
 Guía Breve de Linked Data. (Consultado en marzo de
2016 )

También podría gustarte