Skip to content

Commit 233f8f2

Browse files
authored
Merge pull request #54 from irenesanchezsanz/master
Assigment 4 - Irene Sánchez Sanz
2 parents a15262a + 15fb4f7 commit 233f8f2

3 files changed

Lines changed: 580 additions & 0 deletions

File tree

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
# -*- coding: utf-8 -*-
2+
"""Task06.ipynb
3+
4+
Automatically generated by Colab.
5+
6+
Original file is located at
7+
https://colab.research.google.com/drive/1X0FBFPAmKdYdKq6WNdQwUv5CADcN3Raf
8+
9+
**Task 06: Modifying RDF(s)**
10+
"""
11+
12+
#!pip install rdflib
13+
import urllib.request
14+
url = 'https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/refs/heads/master/Assignment4/course_materials/python/validation.py'
15+
urllib.request.urlretrieve(url, 'validation.py')
16+
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/master/Assignment4/course_materials"
17+
18+
"""Import RDFLib main methods"""
19+
20+
from rdflib import Graph, Namespace, Literal, XSD
21+
from rdflib.namespace import RDF, RDFS
22+
from validation import Report
23+
g = Graph()
24+
r = Report()
25+
26+
"""Create a new class named Researcher"""
27+
28+
ns = Namespace("http://mydomain.org#")
29+
g.add((ns.Researcher, RDF.type, RDFS.Class))
30+
for s, p, o in g:
31+
print(s,p,o)
32+
33+
"""**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.**
34+
35+
> Añadir blockquote
36+
37+
38+
"""
39+
40+
# this task is validated in the next step
41+
ONT = Namespace("http://oeg.fi.upm.es/def/people#")
42+
PER = Namespace("http://oeg.fi.upm.es/resource/person/")
43+
44+
g.namespace_manager.bind('ontology', ONT, override=False)
45+
g.namespace_manager.bind('person', PER, override=False)
46+
47+
g.namespace_manager.bind('ns', Namespace("http://somewhere#"), override=False)
48+
ns = Namespace("http://mydomain.org#")
49+
g.add((ns.Researcher, RDF.type, RDFS.Class))
50+
51+
"""**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**
52+
53+
"""
54+
55+
# TO DO
56+
# Visualize the results
57+
58+
classes = {
59+
ONT.Person: "Person",
60+
ONT.Professor: "Professor",
61+
ONT.AssociateProfessor: "AssociateProfessor",
62+
ONT.InterimAssociateProfessor: "InterimAssociateProfessor",
63+
ONT.FullProfessor: "FullProfessor",
64+
}
65+
66+
for c_uri, label in classes.items():
67+
g.add((c_uri, RDF.type, RDFS.Class))
68+
g.add((c_uri, RDFS.label, Literal(label, datatype=XSD.string)))
69+
70+
g.add((ONT.Professor, RDFS.subClassOf, ONT.Person))
71+
g.add((ONT.AssociateProfessor, RDFS.subClassOf, ONT.Professor))
72+
g.add((ONT.InterimAssociateProfessor, RDFS.subClassOf, ONT.AssociateProfessor))
73+
g.add((ONT.FullProfessor, RDFS.subClassOf, ONT.Professor))
74+
for s, p, o in g:
75+
print(s, p, o)
76+
77+
# Validation. Do not remove
78+
r.validate_task_06_01(g)
79+
80+
"""**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)**"""
81+
82+
# TO DO
83+
# Visualize the results
84+
props = {
85+
ONT.hasColleague: {
86+
"label": "hasColleague",
87+
"domain": ONT.Person,
88+
"range": ONT.Person,
89+
},
90+
ONT.hasName: {
91+
"label": "hasName",
92+
"domain": ONT.Person,
93+
"range": RDFS.Literal,
94+
},
95+
ONT.hasHomePage: {
96+
"label": "hasHomePage",
97+
"domain": ONT.FullProfessor,
98+
"range": RDFS.Literal,
99+
},
100+
}
101+
102+
for p_uri, meta in props.items():
103+
g.add((p_uri, RDF.type, RDF.Property))
104+
g.add((p_uri, RDFS.label, Literal(meta["label"], datatype=XSD.string)))
105+
g.add((p_uri, RDFS.domain, meta["domain"]))
106+
g.add((p_uri, RDFS.range, meta["range"]))
107+
for s, p, o in g:
108+
print(s,p,o)
109+
110+
# Validation. Do not remove
111+
r.validate_task_06_02(g)
112+
113+
"""**TASK 6.3: Create the individuals shown in slide 36 under "Datos". Link them with the same relationships shown in the diagram."**"""
114+
115+
# TO DO
116+
# Visualize the results
117+
oscar = PER["Oscar"]
118+
asun = PER["Asun"]
119+
raul = PER["Raul"]
120+
121+
g.add((oscar, RDF.type, ONT.Person))
122+
g.add((asun, RDF.type, ONT.FullProfessor))
123+
g.add((raul, RDF.type, ONT.AssociateProfessor))
124+
125+
126+
g.add((oscar, RDFS.label, Literal("Oscar", datatype=XSD.string)))
127+
g.add((asun, RDFS.label, Literal("Asun", datatype=XSD.string)))
128+
g.add((raul, RDFS.label, Literal("Raul", datatype=XSD.string)))
129+
130+
131+
g.add((oscar, ONT.hasName, Literal("Oscar", datatype=XSD.string)))
132+
g.add((oscar, ONT.hasColleague, asun))
133+
134+
135+
g.add((asun, ONT.hasColleague, oscar))
136+
g.add((asun, ONT.hasHomePage, Literal("https://example.org/asun", datatype=XSD.string)))
137+
138+
139+
140+
for s, p, o in g:
141+
print(s,p,o)
142+
143+
r.validate_task_06_03(g)
144+
145+
"""**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**
146+
147+
"""
148+
149+
# TO DO
150+
# Visualize the results
151+
from validation import VCARD, FOAF
152+
153+
g.add((oscar, VCARD.Given, Literal("Oscar", datatype=XSD.string)))
154+
g.add((oscar, VCARD.Family, Literal("Corcho", datatype=XSD.string))) # family name example
155+
g.add((oscar, FOAF.email, Literal("oscar@example.org", datatype=XSD.string)))
156+
for s, p, o in g:
157+
print(s,p,o)
158+
159+
# Validation. Do not remove
160+
r.validate_task_06_04(g)
161+
r.save_report("_Task_06")
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
# -*- coding: utf-8 -*-
2+
"""Task07.ipynb
3+
4+
Automatically generated by Colab.
5+
6+
Original file is located at
7+
https://colab.research.google.com/drive/1PtX_z2vUt1J2bQxZNDZXJ_GUcfZO2VtC
8+
9+
**Task 07: Querying RDF(s)**
10+
"""
11+
12+
#!pip install rdflib
13+
import urllib.request
14+
url = 'https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/refs/heads/master/Assignment4/course_materials/python/validation.py'
15+
urllib.request.urlretrieve(url, 'validation.py')
16+
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/master/Assignment4/course_materials"
17+
18+
from validation import Report
19+
20+
"""First let's read the RDF file"""
21+
22+
from rdflib import Graph, Namespace, Literal
23+
from rdflib.namespace import RDF, RDFS
24+
# Do not change the name of the variables
25+
g = Graph()
26+
g.namespace_manager.bind('ns', Namespace("http://somewhere#"), override=False)
27+
g.parse(github_storage+"/rdf/data06.ttl", format="TTL")
28+
report = Report()
29+
30+
"""**TASK 7.1a: For all classes, list each classURI. If the class belogs to another class, then list its superclass.**
31+
**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**
32+
"""
33+
34+
# TO DO
35+
# Visualize the results
36+
result = []
37+
38+
39+
for c in g.subjects(RDF.type, RDFS.Class):
40+
superclasses = list(g.objects(c, RDFS.subClassOf))
41+
42+
if superclasses:
43+
for sc in superclasses:
44+
result.append((c, sc))
45+
else:
46+
result.append((c, None))
47+
#list of tuples
48+
for r in result:
49+
print(r)
50+
51+
## Validation: Do not remove
52+
report.validate_07_1a(result)
53+
54+
"""**TASK 7.1b: Repeat the same exercise in SPARQL, returning the variables ?c (class) and ?sc (superclass)**"""
55+
56+
query = """
57+
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
58+
SELECT DISTINCT ?c ?sc
59+
WHERE {
60+
?c a rdfs:Class .
61+
OPTIONAL { ?c rdfs:subClassOf ?sc }
62+
}
63+
"""
64+
for r in g.query(query):
65+
print(r.c, r.sc)
66+
67+
## Validation: Do not remove
68+
report.validate_07_1b(query,g)
69+
70+
"""**TASK 7.2a: List all individuals of "Person" with RDFLib (remember the subClasses). Return the individual URIs in a list called "individuals"**
71+
72+
"""
73+
74+
ns = Namespace("http://oeg.fi.upm.es/def/people#")
75+
76+
person = ns.Person
77+
all_person_classes = {person}
78+
changed = True
79+
while changed:
80+
changed = False
81+
for sub, sup in g.subject_objects(RDFS.subClassOf):
82+
if sup in all_person_classes and sub not in all_person_classes:
83+
all_person_classes.add(sub)
84+
changed = True
85+
86+
individuals_set = set()
87+
for ind, _, cls in g.triples((None, RDF.type, None)):
88+
if cls in all_person_classes:
89+
individuals_set.add(ind)
90+
91+
individuals = list(individuals_set)
92+
93+
# Visualización
94+
for i in individuals:
95+
print(i)
96+
97+
# validation. Do not remove
98+
report.validate_07_02a(individuals)
99+
100+
"""**TASK 7.2b: Repeat the same exercise in SPARQL, returning the individual URIs in a variable ?ind**"""
101+
102+
query = """PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
103+
PREFIX people: <http://oeg.fi.upm.es/def/people#>
104+
SELECT ?ind WHERE {
105+
?ind a ?t .
106+
?t rdfs:subClassOf* people:Person .
107+
}
108+
"""
109+
110+
for r in g.query(query):
111+
print(r.ind)
112+
# Visualize the results
113+
114+
## Validation: Do not remove
115+
report.validate_07_02b(g, query)
116+
117+
"""**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**"""
118+
119+
query = """
120+
PREFIX people: <http://oeg.fi.upm.es/def/people#>
121+
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
122+
123+
SELECT ?name ?type
124+
WHERE {
125+
?person people:knows people:Rocky .
126+
?person rdfs:label ?name .
127+
?person rdf:type ?type .
128+
}
129+
"""
130+
131+
for r in g.query(query):
132+
print(r.name, r.type)
133+
134+
## Validation: Do not remove
135+
report.validate_07_03(g, query)
136+
137+
"""**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**"""
138+
139+
query = """
140+
PREFIX people: <http://oeg.fi.upm.es/def/people#>
141+
SELECT DISTINCT ?name WHERE {
142+
?person rdfs:label ?name .
143+
{
144+
?person people:hasColleague ?colleague1 .
145+
?colleague1 people:ownsPet ?pet1 .
146+
} UNION {
147+
?person people:hasColleague ?colleague1 .
148+
?colleague1 people:hasColleague ?colleague2 .
149+
?colleague2 people:ownsPet ?pet2 .
150+
}
151+
}
152+
"""
153+
for r in g.query(query):
154+
print(r.name)
155+
156+
# TO DO
157+
# Visualize the results
158+
159+
## Validation: Do not remove
160+
report.validate_07_04(g,query)
161+
report.save_report("_Task_07")

0 commit comments

Comments
 (0)