Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
"""Task07.ipynb
"""Copia de Task07.ipynb

Automatically generated by Colab.

Original file is located at
https://colab.research.google.com/drive/1SOjhmnIPj8P7ZtU5eNmqrjcFwcbyG-Lb
https://colab.research.google.com/drive/1y5OSyP0ZLjKiGTMSKt_v3WhI0KuX_mgL

**Task 07: Querying RDF(s)**
"""
Expand Down Expand Up @@ -32,44 +32,58 @@
"""

# TO DO
result = [(c, g.value(subject=c, predicate=RDFS.subClassOf, object=None)) for c,p,o in g.triples((None, RDF.type, RDFS.Class))]
# Visualize the results

result = []
for c in g.subjects(RDF.type, RDFS.Class):

superclass = None
for sc in g.objects(c, RDFS.subClassOf):
superclass = sc

result.append((c, superclass))

for r in result:
print(r)

## Validation: Do not remove
# 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)**"""

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


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

## Validation: Do not remove
report.validate_07_1b(query1,g)
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
classes = set()
classes.add(Person)

# variable to return
individuals = []
def get_subclasses(cls):
subclasses = set(g.subjects(RDFS.subClassOf, cls))
all_subs = set(subclasses)
for s in subclasses:
all_subs = all_subs.union(get_subclasses(s))
return all_subs
def get_subclasses(c):
for sc in g.subjects(RDFS.subClassOf, c):
if sc not in classes:
classes.add(sc)
get_subclasses(sc)

classes = {ns.Person} | get_subclasses(ns.Person)
get_subclasses(Person)

individuals = []
for c in classes:
for ind in g.subjects(RDF.type, c):
individuals.append(ind)
for inst in g.subjects(RDF.type, c):
individuals.append(inst)


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

Expand All @@ -78,54 +92,70 @@ def get_subclasses(cls):

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

query2 = """
SELECT DISTINCT ?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 ?ind
WHERE {
?clase rdfs:subClassOf* <http://oeg.fi.upm.es/def/people#Person> .
?ind a ?clase .
?subclass rdfs:subClassOf* ns:Person .
?ind rdf:type ?subclass .
}
"""

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

## Validation: Do not remove
report.validate_07_02b(g, query2)
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**"""

query3 = """SELECT ?name ?type WHERE{
?name <http://oeg.fi.upm.es/def/people#knows> <http://oeg.fi.upm.es/def/people#Rocky>.
?name a ?type .
}"""
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 .
}
"""
# TO DO
for r in g.query(query3):
# Visualize the results
for r in g.query(query):
print(r.name, r.type)

## Validation: Do not remove
report.validate_07_03(g, query3)
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**"""

query4 = """
SELECT ?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
WHERE {
?p <http://oeg.fi.upm.es/def/people#ownsPet> ?m.
{?p <http://oeg.fi.upm.es/def/people#ownsPet> ?pet .
?name <http://oeg.fi.upm.es/def/people#hasColleague> ?p .}
UNION
{?p2 <http://oeg.fi.upm.es/def/people#hasColleague> ?p.
?name <http://oeg.fi.upm.es/def/people#hasColleague> ?p2.}
?person rdfs:label ?name .
FILTER (
lcase(str(?name)) = "asun" ||
lcase(str(?name)) = "raul" ||
lcase(str(?name)) = "oscar"
)
}
"""

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

# TO DO
# Visualize the results

## Validation: Do not remove
report.validate_07_04(g,query4)
report.validate_07_04(g,query)
report.save_report("_Task_07")
158 changes: 158 additions & 0 deletions Assignment4/Assigment_Nora_EzZahi_24C044_task06
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# -*- coding: utf-8 -*-
"""Copia de Task06.ipynb

Automatically generated by Colab.

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

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

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

"""

# 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))

# Visualiza los resultados
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
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"]))

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

# TO DO
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)))

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

"""

# TO DO
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)))
g.add((oscar, FOAF.email, Literal("oscar@example.org", datatype=XSD.string)))

# 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")
Loading
Loading