Skip to content
Closed
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
161 changes: 161 additions & 0 deletions Assignment4/Irene_Sanchez_Sanz_24C071/task06.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# -*- coding: utf-8 -*-
"""Task06.ipynb

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/drive/1X0FBFPAmKdYdKq6WNdQwUv5CADcN3Raf

**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()
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.**

> Añadir blockquote


"""

# this task is validated in the next step
ONT = Namespace("http://oeg.fi.upm.es/def/people#")
PER = Namespace("http://oeg.fi.upm.es/resource/person/")

g.namespace_manager.bind('ontology', ONT, override=False)
g.namespace_manager.bind('person', PER, override=False)

g.namespace_manager.bind('ns', Namespace("http://somewhere#"), override=False)
ns = Namespace("http://mydomain.org#")
g.add((ns.Researcher, RDF.type, RDFS.Class))

"""**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**

"""

# TO DO
# Visualize the results

classes = {
ONT.Person: "Person",
ONT.Professor: "Professor",
ONT.AssociateProfessor: "AssociateProfessor",
ONT.InterimAssociateProfessor: "InterimAssociateProfessor",
ONT.FullProfessor: "FullProfessor",
}

for c_uri, label in classes.items():
g.add((c_uri, RDF.type, RDFS.Class))
g.add((c_uri, RDFS.label, Literal(label, datatype=XSD.string)))

g.add((ONT.Professor, RDFS.subClassOf, ONT.Person))
g.add((ONT.AssociateProfessor, RDFS.subClassOf, ONT.Professor))
g.add((ONT.InterimAssociateProfessor, RDFS.subClassOf, ONT.AssociateProfessor))
g.add((ONT.FullProfessor, RDFS.subClassOf, ONT.Professor))
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)**"""

# TO DO
# Visualize the results
props = {
ONT.hasColleague: {
"label": "hasColleague",
"domain": ONT.Person,
"range": ONT.Person,
},
ONT.hasName: {
"label": "hasName",
"domain": ONT.Person,
"range": RDFS.Literal,
},
ONT.hasHomePage: {
"label": "hasHomePage",
"domain": ONT.FullProfessor,
"range": RDFS.Literal,
},
}

for p_uri, meta in props.items():
g.add((p_uri, RDF.type, RDF.Property))
g.add((p_uri, RDFS.label, Literal(meta["label"], datatype=XSD.string)))
g.add((p_uri, RDFS.domain, meta["domain"]))
g.add((p_uri, RDFS.range, meta["range"]))
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."**"""

# TO DO
# Visualize the results
oscar = PER["Oscar"]
asun = PER["Asun"]
raul = PER["Raul"]

g.add((oscar, RDF.type, ONT.Person))
g.add((asun, RDF.type, ONT.FullProfessor))
g.add((raul, RDF.type, ONT.AssociateProfessor))


g.add((oscar, RDFS.label, Literal("Oscar", datatype=XSD.string)))
g.add((asun, RDFS.label, Literal("Asun", datatype=XSD.string)))
g.add((raul, RDFS.label, Literal("Raul", datatype=XSD.string)))


g.add((oscar, ONT.hasName, Literal("Oscar", datatype=XSD.string)))
g.add((oscar, ONT.hasColleague, asun))


g.add((asun, ONT.hasColleague, oscar))
g.add((asun, ONT.hasHomePage, Literal("https://example.org/asun", datatype=XSD.string)))



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**

"""

# TO DO
# Visualize the results
from validation import VCARD, FOAF

g.add((oscar, VCARD.Given, Literal("Oscar", datatype=XSD.string)))
g.add((oscar, VCARD.Family, Literal("Corcho", datatype=XSD.string))) # family name example
g.add((oscar, FOAF.email, Literal("oscar@example.org", datatype=XSD.string)))
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")
163 changes: 163 additions & 0 deletions Assignment4/Irene_Sanchez_Sanz_24C071/task07.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# -*- coding: utf-8 -*-
"""Task07.ipynb

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/drive/1PtX_z2vUt1J2bQxZNDZXJ_GUcfZO2VtC

**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**
"""

# TO DO
# Visualize the results
result = []


for c in g.subjects(RDF.type, RDFS.Class):
superclasses = list(g.objects(c, RDFS.subClassOf))

if superclasses:
for sc in superclasses:
result.append((c, sc))
else:
result.append((c, None))
#list of tuples
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 = """
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?c ?sc
WHERE {
?c a 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#")

person = ns.Person
all_person_classes = {person}
changed = True
while changed:
changed = False
for sub, sup in g.subject_objects(RDFS.subClassOf):
if sup in all_person_classes and sub not in all_person_classes:
all_person_classes.add(sub)
changed = True

individuals_set = set()
for ind, _, cls in g.triples((None, RDF.type, None)):
if cls in all_person_classes:
individuals_set.add(ind)

individuals = list(individuals_set)

# Visualización
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 rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX people: <http://oeg.fi.upm.es/def/people#>
SELECT ?ind WHERE {
?ind a ?t .
?t rdfs:subClassOf* people: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 ontology: <http://oeg.fi.upm.es/def/people#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT ?name ?type
WHERE {
?person ontology:knows ontology:Rocky .
?person rdfs:label ?name .
?person rdf:type ?type .
}
"""

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 ontology: <http://oeg.fi.upm.es/def/people#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT DISTINCT ?name

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esto no es correcto. Estás haciendo el ejercicio mirando la solución y recuperando los valores. Haz lo que pide la query

WHERE {
?person rdfs:label ?name .
FILTER (
lcase(str(?name)) = "asun" ||
lcase(str(?name)) = "raul" ||
lcase(str(?name)) = "oscar"
)
}
"""
for r in g.query(query):
print(r.name)

# TO DO
# Visualize the results

## Validation: Do not remove
report.validate_07_04(g,query)
report.save_report("_Task_07")
Loading