Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions Assignment4/Vasyl_Hryhoriev_24C015/task06.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# -*- coding: utf-8 -*-
"""Task06_2025.ipynb

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/drive/1GKS6qAm9T4y76LWtB8ZP-ToTFBSDENE_

**Task 06: Modifying RDF(s)**
"""

#!pip install rdflib
import urllib.request
url = 'https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/refs/heads/master/Assignment4/course_materials/python/validation.py'
urllib.request.urlretrieve(url, 'validation.py')
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/master/Assignment4/course_materials"

"""Import RDFLib main methods"""

from rdflib import Graph, Namespace, Literal, XSD
from rdflib.namespace import RDF, RDFS
from validation import Report
g = Graph()
g.namespace_manager.bind('ns', Namespace("http://somewhere#"), override=False)
r = Report()

"""Create a new class named Researcher"""

ns = Namespace("http://mydomain.org#")
g.add((ns.Researcher, RDF.type, RDFS.Class))
for s, p, o in g:
print(s,p,o)

"""**Task 6.0: Create new prefixes for "ontology" and "person" as shown in slide 14 of the Slidedeck 01a.RDF(s)-SPARQL shown in class.**"""

ontology = Namespace("http://oeg.fi.upm.es/def/people#")
person = Namespace("http://oeg.fi.upm.es/resource/person/")
g.namespace_manager.bind('ontology', ontology, override=False)
g.namespace_manager.bind('person', person, override=False)

"""**TASK 6.1: Reproduce the taxonomy of classes shown in slide 34 in class (all the classes under "Vocabulario", Slidedeck: 01a.RDF(s)-SPARQL). Add labels for each of them as they are in the diagram (exactly) with no language tags. Remember adding the correct datatype (xsd:String) when appropriate**

"""
g.add((ontology.Person, RDFS.label, Literal("Person", datatype=XSD.string)))
g.add((ontology.Professor, RDFS.label, Literal("Professor", datatype=XSD.string)))
g.add((ontology.FullProfessor, RDFS.label, Literal("FullProfessor", datatype=XSD.string)))
g.add((ontology.AssociateProfessor, RDFS.label, Literal("AssociateProfessor", datatype=XSD.string)))
g.add((ontology.InterimAssociateProfessor, RDFS.label, Literal("InterimAssociateProfessor", datatype=XSD.string)))

g.add((ontology.Person, RDF.type, RDFS.Class))
g.add((ontology.Professor, RDFS.subClassOf, ontology.Person))
g.add((ontology.FullProfessor, RDFS.subClassOf, ontology.Professor))
g.add((ontology.AssociateProfessor, RDFS.subClassOf, ontology.Professor))
g.add((ontology.InterimAssociateProfessor, RDFS.subClassOf, ontology.AssociateProfessor))

# Visualize the results
for s, p, o in g:
print(s,p,o)

# Validation. Do not remove
r.validate_task_06_01(g)

"""**TASK 6.2: Add the 3 properties shown in slide 36. Add labels for each of them (exactly as they are in the slide, with no language tags), and their corresponding domains and ranges using RDFS. Remember adding the correct datatype (xsd:String) when appropriate. If a property has no range, make it a literal (string)**"""

g.add((ontology.hasColleague, RDFS.label, Literal("hasColleague", datatype=XSD.string)))
g.add((ontology.hasName, RDFS.label, Literal("hasName", datatype=XSD.string)))
g.add((ontology.hasHomePage, RDFS.label, Literal("hasHomePage", datatype=XSD.string)))

g.add((ontology.hasColleague, RDF.type, RDF.Property))
g.add((ontology.hasColleague, RDFS.domain, ontology.Person))
g.add((ontology.hasColleague, RDFS.range, ontology.Person))

g.add((ontology.hasName, RDF.type, RDF.Property))
g.add((ontology.hasName, RDFS.domain, ontology.Person))
g.add((ontology.hasName, RDFS.range, RDFS.Literal))

g.add((ontology.hasHomePage, RDF.type, RDF.Property))
g.add((ontology.hasHomePage, RDFS.domain, ontology.FullProfessor))
g.add((ontology.hasHomePage, RDFS.range, RDFS.Literal))
# Visualize the results
for s, p, o in g:
print(s,p,o)
# Visualize the results
for s, p, o in g:
print(s,p,o)

# Validation. Do not remove
r.validate_task_06_02(g)

"""**TASK 6.3: Create the individuals shown in slide 36 under "Datos". Link them with the same relationships shown in the diagram."**"""

g.add((person.Oscar, RDF.type, ontology.AssociateProfessor))
g.add((person.Asun, RDF.type, ontology.FullProfessor))
g.add((person.Raul, RDF.type, ontology.InterimAssociateProfessor))
g.add((person.Oscar, RDFS.label, Literal("Oscar", datatype=XSD.string)))
g.add((person.Asun, RDFS.label, Literal("Asun", datatype=XSD.string)))
g.add((person.Raul, RDFS.label, Literal("Raul", datatype=XSD.string)))

g.add((person.Oscar, person.hasColleague, person.Asun))
g.add((person.Oscar, person.hasName, Literal("Oscar", datatype=XSD.string)))

g.add((person.Asun, person.hasColleague, person.Raul))
g.add((person.Asun, person.hasHomePage, Literal("http://www.oeg-upm.net/", datatype=XSD.string)))

# Visualize the results
for s, p, o in g:
print(s,p,o)
# Visualize the results
for s, p, o in g:
print(s,p,o)

r.validate_task_06_03(g)

"""**TASK 6.4: Add to the individual person:Oscar the email address, given and family names. Use the properties already included in example 4 to describe Jane and John (https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/master/Assignment4/course_materials/rdf/example4.rdf). Do not import the namespaces, add them manually**

"""
VCARD = Namespace("http://www.w3.org/2001/vcard-rdf/3.0/")
FOAF = Namespace("http://xmlns.com/foaf/0.1/")

g.namespace_manager.bind('vcard', VCARD, override=False)
g.namespace_manager.bind('foaf', FOAF, override=False)

g.add((person.Oscar, VCARD.Given, Literal("Oscar", datatype=XSD.string)))
g.add((person.Oscar, VCARD.Family, Literal("Corcho", datatype=XSD.string)))
g.add((person.Oscar, FOAF.email, Literal("ocorcho@fi.upm.es", datatype=XSD.string)))

# Visualize the results
for s, p, o in g:
print(s,p,o)
# Visualize the results
for s, p, o in g:
print(s,p,o)

# Validation. Do not remove
r.validate_task_06_04(g)
r.save_report("_Task_06")
161 changes: 161 additions & 0 deletions Assignment4/Vasyl_Hryhoriev_24C015/task07.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# -*- coding: utf-8 -*-
"""Task07_2025.ipynb

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/drive/13zP7djRTBeG5tsTNq-mV-TGtIeDmqV7W

**Task 07: Querying RDF(s)**
"""

#!pip install rdflib
import urllib.request
url = 'https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/refs/heads/master/Assignment4/course_materials/python/validation.py'
urllib.request.urlretrieve(url, 'validation.py')
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/master/Assignment4/course_materials"

from validation import Report

"""First let's read the RDF file"""

from rdflib import Graph, Namespace, Literal
from rdflib.namespace import RDF, RDFS
# Do not change the name of the variables
g = Graph()
g.namespace_manager.bind('ns', Namespace("http://somewhere#"), override=False)
g.parse(github_storage+"/rdf/data06.ttl", format="TTL")
report = Report()

"""**TASK 7.1a: For all classes, list each classURI. If the class belogs to another class, then list its superclass.**
**Do the exercise in RDFLib returning a list of Tuples: (class, superclass) called "result". If a class does not have a super class, then return None as the superclass**
"""
# Visualize the results
result = [] #list of tuples
for s, p, o in g.triples((None, RDF.type, RDFS.Class)):
superclass = g.value(s, RDFS.subClassOf, None)
result.append((s, superclass if superclass is not None else None))
for r in result:
print(r)

## Validation: Do not remove
report.validate_07_1a(result)

"""**TASK 7.1b: Repeat the same exercise in SPARQL, returning the variables ?c (class) and ?sc (superclass)**"""

query = """
SELECT ?c ?sc
WHERE {
?c rdf:type rdfs:Class.
OPTIONAL{?c rdfs:subClassOf ?sc.}
}
"""

for r in g.query(query):
print(r.c, r.sc)

## Validation: Do not remove
report.validate_07_1b(query,g)

"""**TASK 7.2a: List all individuals of "Person" with RDFLib (remember the subClasses). Return the individual URIs in a list called "individuals"**

"""

ns = Namespace("http://oeg.fi.upm.es/def/people#")

# variable to return
individuals = []
clases = [ns.Person]
for c,p,o in g.triples((None,RDFS.subClassOf, ns.Person)):
clases.append(c)
for sub,p,o in g.triples((None, RDFS.subClassOf, c)):
clases.append(sub)
for subsub,p,o in g.triples((None, RDFS.subClassOf, sub)):
clases.append(subsub)

for clase in clases:
for s,p,o in g.triples((None, RDF.type, clase)):
individuals.append(s)

# visualize results
for i in individuals:
print(i)

# validation. Do not remove
report.validate_07_02a(individuals)

"""**TASK 7.2b: Repeat the same exercise in SPARQL, returning the individual URIs in a variable ?ind**"""

query = """
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX ns: <http://oeg.fi.upm.es/def/people#>

SELECT DISTINCT ?ind
WHERE {
?ind rdf:type ?class .
?class rdfs:subClassOf* ns:Person .
}
"""

for r in g.query(query):
print(r.ind)
# Visualize the results

## Validation: Do not remove
report.validate_07_02b(g, query)

"""**TASK 7.3: List the name and type of those who know Rocky (in SPARQL only). Use name and type as variables in the query**"""

query = """
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX ns: <http://oeg.fi.upm.es/def/people#>

SELECT ?name ?type
WHERE {
?x ns:knows ns:Rocky .
?x rdf:type ?type .
?x rdfs:label ?name
}
"""
# Visualize the results
for r in g.query(query):
print(r.name, r.type)

## Validation: Do not remove
report.validate_07_03(g, query)

"""**Task 7.4: List the name of those entities who have a colleague with a dog, or that have a collegue who has a colleague who has a dog (in SPARQL). Return the results in a variable called name**"""

query = """
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX ns: <http://oeg.fi.upm.es/def/people#>

SELECT DISTINCT ?name
WHERE {
{
?x ns:hasColleague ?c .
?c ns:ownsPet ?p .
?p rdf:type ns:Animal .
}
UNION
{
?x ns:hasColleague ?c1 .
?c1 ns:hasColleague ?c2 .
?c2 ns:ownsPet ?p .
?p rdf:type ns:Animal .
}
?x rdfs:label ?name .
}
"""

for r in g.query(query):
print(r.name)

# Visualize the results

## Validation: Do not remove
report.validate_07_04(g,query)
report.save_report("_Task_07")
46 changes: 46 additions & 0 deletions Assignment4/Vasyl_Hryhoriev_24C015/task08.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
"""Task08.ipynb

Automatically generated by Colab.
**Task 08: Completing missing data**
"""

#!pip install rdflib
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2021-2022/master/Assignment4/course_materials"

from rdflib import Graph, Namespace, Literal, URIRef
g1 = Graph()
g2 = Graph()
g1.parse(github_storage+"/rdf/data01.rdf", format="xml")
g2.parse(github_storage+"/rdf/data02.rdf", format="xml")

"""Tarea: lista todos los elementos de la clase Person en el primer grafo (data01.rdf) y completa los campos (given name, family name y email) que puedan faltar con los datos del segundo grafo (data02.rdf). Puedes usar consultas SPARQL o iterar el grafo, o ambas cosas."""
RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#")
DATA = Namespace("http://data.org#")
VCARD = Namespace("http://www.w3.org/2001/vcard-rdf/3.0#")

personas = []
for s,p,o in g1.triples((None, RDF.type, DATA.Person)):
print(s)
personas.append(s)

for persona in personas:
given = g2.value(persona, VCARD.Given)
family = g2.value(persona, VCARD.Family)
email = g2.value(persona, VCARD.EMAIL)
if given:
g1.add((persona, VCARD.Given, given))
if family:
g1.add((persona, VCARD.Family, family))
if email:
g1.add((persona, VCARD.EMAIL, email))

####Visualización de g1
for persona in personas:
for s,p,o in g1.triples((persona, VCARD.Given, None)):
print(s,p,o)
for s,p,o in g1.triples((persona, VCARD.Family, None)):
print(s,p,o)
for s,p,o in g1.triples((persona, VCARD.EMAIL,None)):
print(s,p,o)
49 changes: 49 additions & 0 deletions Assignment4/Vasyl_Hryhoriev_24C015/task09.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
"""Task09.ipynb
Automatically generated by Colab.
**Task 09: Data linking**
"""

#!pip install rdflib
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2021-2022/master/Assignment4/course_materials/"

from rdflib import Graph, Namespace, Literal, URIRef
g1 = Graph()
g2 = Graph()
g3 = Graph()
g1.parse(github_storage+"rdf/data03.rdf", format="xml")
g2.parse(github_storage+"rdf/data04.rdf", format="xml")

"""Busca individuos en los dos grafos y enlázalos mediante la propiedad OWL:sameAs, inserta estas coincidencias en g3. Consideramos dos individuos iguales si tienen el mismo apodo y nombre de familia. Ten en cuenta que las URI no tienen por qué ser iguales para un mismo individuo en los dos grafos."""

OWL = Namespace("http://www.w3.org/2002/07/owl#")
VCARD = Namespace("http://www.w3.org/2001/vcard-rdf/3.0#")
RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#")
DATA3 = Namespace("http://data.three.org#")
DATA4 = Namespace("http://data.four.org#")

individuos1=[]
for s,p,o in g1.triples((None, RDF.type, DATA3.Person)):
print(s)
individuos1.append(s)

individuos2=[]
for s,p,o in g2.triples((None, RDF.type, DATA4.Person)):
print(s)
individuos2.append(s)

for i1 in individuos1:
nombre1 = g1.value(i1, VCARD.Given, None)
apellido1 = g1.value(i1, VCARD.Family, None)
if nombre1 and apellido1:
for i2 in individuos2:
nombre2 = g2.value(i2, VCARD.Given, None)
apellido2 = g2.value(i2, VCARD.Family, None)
if nombre2 and apellido2:
if (str(nombre1) == str(nombre2)) and (str(apellido1) == str(apellido2)):
g3.add((i1, OWL.sameAs, i2))

####Visualización de g3
for s,p,o in g3.triples((None, None, None)):
print(s,p,o)
Loading