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

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/github/davidgarciiapoli/Curso2025-2026-DataScience/blob/master/Assignment4/course_materials/notebooks/Task06.ipynb

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

from rdflib import Graph, Namespace

# Crear el grafo
g = Graph()

# Crear los namespaces
ontology = Namespace("http://example.org/ontology/")
person = Namespace("http://example.org/person/")

# Asociar los prefijos al grafo
g.bind("ontology", ontology)
g.bind("person", person)

"""**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 = Graph()
person = Namespace("http://oeg.fi.upm.es/def/people#")


g.bind("person", person)
for cls in ["Person", "Professor", "FullProfessor", "AssociateProfessor", "InterimAssociateProfessor"]:
g.add((person[cls], RDF.type, RDFS.Class))

hierarchy = {
"Professor": "Person",
"FullProfessor": "Professor",
"AssociateProfessor": "Professor",
"InterimAssociateProfessor": "AssociateProfessor"
}
for subclass, superclass in hierarchy.items():
g.add((person[subclass], RDFS.subClassOf, person[superclass]))


labels = [
("Person", "Person"),
("Professor", "Professor"),
("FullProfessor", "FullProfessor"),
("AssociateProfessor", "AssociateProfessor"),
("InterimAssociateProfessor", "InterimAssociateProfessor")
]
for cls, lbl in labels:
g.add((person[cls], RDFS.label, Literal(lbl, datatype=XSD.string)))


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((person.hasHomePage, RDF.type, RDF.Property))
g.add((person.hasName, RDF.type, RDF.Property))
g.add((person.hasColleague, RDF.type, RDF.Property))

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

g.add((person.hasHomePage, RDFS.domain, person.FullProfessor))
g.add((person.hasName, RDFS.domain, person.Person))
g.add((person.hasColleague, RDFS.domain, person.Person))

g.add((person.hasHomePage, RDFS.range, RDFS.Literal))
g.add((person.hasName, RDFS.range, RDFS.Literal))
g.add((person.hasColleague, RDFS.range, person.Person))

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

data = Namespace("http://oeg.fi.upm.es/resource/person/")


g.add((data.Raul, RDF.type, person.InterimAssociateProfessor))
g.add((data.Raul, RDFS.label, Literal("Raul", datatype=XSD.string)))

g.add((data.Asun, RDF.type, person.FullProfessor))
g.add((data.Asun, RDFS.label, Literal("Asun", datatype=XSD.string)))
g.add((data.Asun, person.hasHomePage, Literal("http://www.oeg-upm.net/")))

g.add((data.Oscar, RDF.type, person.AssociateProfessor))
g.add((data.Oscar, RDFS.label, Literal("Oscar", datatype=XSD.string)))
g.add((data.Oscar, person.hasName, Literal("Óscar Corcho García")))


g.add((data.Asun, person.hasColleague, data.Raul))
g.add((data.Oscar, person.hasColleague, data.Asun))


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

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

g.namespace_manager.bind('foaf', foaf)
g.namespace_manager.bind('vcard', vcard)

g.add((data.Oscar, vcard.Given, Literal("Oscar", datatype=XSD.string)))
g.add((data.Oscar, vcard.Family, Literal("Corcho García", datatype=XSD.string)))
g.add((data.Oscar, foaf.email, Literal("ocorcho@fi.upm.es", 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")
148 changes: 148 additions & 0 deletions Assignment4/David_Garcia_23C056/task07.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
# -*- coding: utf-8 -*-
"""Task07.ipynb

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/github/davidgarciiapoli/Curso2025-2026-DataScience/blob/master/Assignment4/course_materials/notebooks/Task07.ipynb

**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 = [] #list of tuples
for c in g.subjects(RDF.type, RDFS.Class):
superclass = None
for sclass in g.objects(c, RDFS.subClassOf):
superclass = sclass
result.append((c, superclass))
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#")


individuals = []
def get_all_subclasses(cls):
subclasses = set()
for sub in g.subjects(RDFS.subClassOf, cls):
subclasses.add(sub)
subclasses.update(get_all_subclasses(sub))
return subclasses


all_classes = {ns.Person} | get_all_subclasses(ns.Person)


for cls in all_classes:
for ind in g.subjects(RDF.type, cls):
individuals.append(ind)
# visualize results
for i in individuals:
print(i)

query = """
SELECT ?ind
WHERE {
?ind rdf:type/rdfs:subClassOf* <http://oeg.fi.upm.es/def/people#Person> .
}
"""

# Ejecutar consulta
for r in g.query(query):
print(r.ind)

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

## 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 ns: <http://oeg.fi.upm.es/def/people#>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
select ?name ?type WHERE{
?name ns:knows ns:Rocky.
?name 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 people: <http://oeg.fi.upm.es/def/people#>
SELECT DISTINCT ?name WHERE {
?person rdfs:label ?name .
{
?person people:hasColleague ?colleague1 .
?colleague1 people:ownsPet ?pet1 .
} UNION {
?person people:hasColleague ?colleague1 .
?colleague1 people:hasColleague ?colleague2 .
?colleague2 people:ownsPet ?pet2 .
}
}
"""

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

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