Skip to content

Commit b64f8d8

Browse files
2 parents af53bc3 + c3f1f43 commit b64f8d8

55 files changed

Lines changed: 119786 additions & 38083 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Assignment1/DatasetDescriptions.csv

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
Your name; Your GitHub user; Dataset name; Dataset URL; Dataset brief description
2+
Alberto Barreiro Tasende; albertobarreiro1; Contaminación acústica. Estaciones de medida; https://datos.madrid.es/egob/catalogo/211346-0-estaciones-acusticas.dcat; Red fija de 31 estaciones de medición de ruido ambiental en Madrid, con su localización geográfica, altitud y fecha de alta. El sistema SIVCA monitoriza el ruido en la ciudad para evaluar el impacto acústico.
23
Daniel Arias Suárez Mangurrineiro; Flora Urbana de Madrid; https://datos.madrid.es/egob/catalogo/300607-0-flora-mapas.dcat; Registros de especies vegetales distribuidas en los distritos de Madrid desde el año 1758 a 2020.
34
Kleart Laci Dreshaj; kleartlaci; Ruido ambiental en la ciudad de Madrid: niveles de ruido por estaciones; https://datos.madrid.es/egob/catalogo/210227-2-ruido-mensual.rdf; Dataset que recoge los niveles mensuales de ruido ambiental registrados en las diferentes estaciones de medición de la ciudad de Madrid.
45
Pablo Grano de oro Sevillano; pablogranodeoro; Mapa Estratégico del Ruido 2021 en Madrid.; https://servpub.madrid.es/IDEAM_WBGEOPORTAL/dcat?id=470b89af-5d64-41d3-8bdb-2fe6badd0364; Refleja los niveles de ruido provocados por el tráfico rodado en Madrid correspondientes a 2021. Los metadatos de este conjunto de datos están en formato RDF.
@@ -15,3 +16,4 @@ Rodrigo Nieto Rodríguez; Rodrix505; Puntos limpios fijos; https://datos.madrid.
1516
Yi Chen Chen; yichenchen2006; Principales parques y jardines municipales; https://datos.madrid.es/sites/v/index.jsp?vgnextoid=dc758935dde13410VgnVCM2000000c205a0aRCRD&vgnextchannel=374512b9ace9f310VgnVCM100000171f5a0aRCRD; Madrid ofrece un patrimonio verde de excepcional extensión y diversidad (más de 6.000 hectáreas, que suponen más de 18 metros cuadrados de parques y zonas verdes públicas por habitante de la ciudad).
1617
Carolina Simal;carol-2406;Arbolado en parques y zonas verdes de Madrid;https://datos.madrid.es/egob/catalogo/300264-81-Arbolado-parques-historico.csv;Número de arboles por parque de Madrid de cada especie.
1718
Luca Alvarez; lucaam06; Bomberos. Parques de bomberos; https://datos.madrid.es/egob/catalogo/211642-0-bomberos-parques.rdf; En este conjunto de datos, puede encontrar la relación de los trece parques de bomberos existentes en la ciudad de Madrid.
19+
Carla Jiménez Arganda; carlajimenezarganda; Zonas verdes de Madrid: zonas estanciales y ajardinadas; https://datos.madrid.es/egob/catalogo/300226-0-zonas-verdes-estanciales.rdf; Localización, características y tipologías de las zonas verdes estanciales y ajardinadas de Madrid.
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
#%% [markdown]
2+
# **Task 06: Modifying RDF(s)**
3+
4+
# %%
5+
6+
7+
# %%
8+
#%pip install rdflib
9+
import urllib.request
10+
url = 'https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/refs/heads/master/Assignment4/course_materials/python/validation.py'
11+
urllib.request.urlretrieve(url, 'validation.py')
12+
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/master/Assignment4/course_materials"
13+
14+
# %% [markdown]
15+
# Import RDFLib main methods
16+
17+
# %%
18+
from rdflib import Graph, Namespace, Literal, XSD
19+
from rdflib.namespace import RDF, RDFS
20+
from validation import Report
21+
g = Graph()
22+
g.namespace_manager.bind('ns', Namespace("http://somewhere#"), override=False)
23+
r = Report()
24+
25+
# %% [markdown]
26+
# Create a new class named Researcher
27+
28+
# %%
29+
ns = Namespace("http://mydomain.org#")
30+
g.add((ns.Researcher, RDF.type, RDFS.Class))
31+
for s, p, o in g:
32+
print(s,p,o)
33+
34+
# %% [markdown]
35+
# **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.**
36+
37+
# %%
38+
person = Namespace("http://oeg-upm.net/people#")
39+
ontology = Namespace("http://oeg-upm.net/ontology#")
40+
41+
g.bind('person', person)
42+
g.bind('ontology', ontology)
43+
44+
# %% [markdown]
45+
# **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**
46+
#
47+
48+
# %%
49+
people = Namespace("http://oeg.fi.upm.es/def/people#")
50+
g.bind("people", people)
51+
52+
53+
person = people.Person
54+
professor = people.Professor
55+
associate = people.AssociateProfessor
56+
interim = people.InterimAssociateProfessor
57+
full = people.FullProfessor
58+
59+
g.add((person, RDF.type, RDFS.Class))
60+
g.add((person, RDFS.label, Literal("Person", datatype=XSD.string)))
61+
62+
g.add((professor, RDF.type, RDFS.Class))
63+
g.add((professor, RDFS.label, Literal("Professor", datatype=XSD.string)))
64+
g.add((professor, RDFS.subClassOf, person))
65+
66+
g.add((associate, RDF.type, RDFS.Class))
67+
g.add((associate, RDFS.label, Literal("AssociateProfessor", datatype=XSD.string)))
68+
g.add((associate, RDFS.subClassOf, professor))
69+
70+
g.add((interim, RDF.type, RDFS.Class))
71+
g.add((interim, RDFS.label, Literal("InterimAssociateProfessor", datatype=XSD.string)))
72+
g.add((interim, RDFS.subClassOf, associate))
73+
74+
g.add((full, RDF.type, RDFS.Class))
75+
g.add((full, RDFS.label, Literal("FullProfessor", datatype=XSD.string)))
76+
g.add((full, RDFS.subClassOf, professor))
77+
78+
79+
# Visualize the results
80+
for s, p, o in g:
81+
print(s,p,o)
82+
83+
# %%
84+
# Validation. Do not remove
85+
r.validate_task_06_01(g)
86+
87+
# %% [markdown]
88+
# **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)**
89+
90+
# %%
91+
hasName = people.hasName
92+
hasColleague = people.hasColleague
93+
hasHomePage = people.hasHomePage
94+
95+
g.add((hasName, RDF.type, RDF.Property))
96+
g.add((hasName, RDFS.label, Literal("hasName", datatype=XSD.string)))
97+
g.add((hasName, RDFS.domain, person))
98+
g.add((hasName, RDFS.range, RDFS.Literal))
99+
100+
g.add((hasColleague, RDF.type, RDFS.subPropertyOf))
101+
g.add((hasColleague, RDFS.label, Literal("hasColleague", datatype=XSD.string)))
102+
g.add((hasColleague, RDFS.domain, person))
103+
g.add((hasColleague, RDFS.range, person))
104+
105+
g.add((hasHomePage, RDF.type, RDFS.subPropertyOf))
106+
g.add((hasHomePage, RDFS.label, Literal("hasHomePage", datatype=XSD.string)))
107+
g.add((hasHomePage, RDFS.domain, full))
108+
g.add((hasHomePage, RDFS.range, RDFS.Literal))
109+
110+
for s, p, o in g:
111+
print(s,p,o)
112+
113+
# %%
114+
# Validation. Do not remove
115+
r.validate_task_06_02(g)
116+
117+
# %% [markdown]
118+
# **TASK 6.3: Create the individuals shown in slide 36 under "Datos". Link them with the same relationships shown in the diagram."**
119+
120+
# %%
121+
indiv = Namespace("http://oeg.fi.upm.es/resource/person/")
122+
123+
oscar = indiv.Oscar
124+
asun = indiv.Asun
125+
raul = indiv.Raul
126+
g.add((oscar, RDF.type, full))
127+
g.add((oscar, RDFS.label, Literal("Oscar", datatype=XSD.string)))
128+
g.add((oscar, hasColleague, indiv.Asun))
129+
g.add((oscar, hasName, Literal("Oscar García", datatype=XSD.string)))
130+
131+
g.add((asun, RDF.type, full))
132+
g.add((asun, RDFS.label, Literal("Asun", datatype=XSD.string)))
133+
g.add((asun, hasColleague, oscar))
134+
g.add((asun, hasHomePage, Literal("https://www.oeg-upm.net/", datatype=XSD.string)))
135+
136+
g.add((raul, RDFS.label, Literal("Raul", datatype=XSD.string)))
137+
g.add((raul, RDF.type, interim))
138+
139+
# Visualize the results
140+
for s, p, o in g:
141+
print(s,p,o)
142+
143+
# %%
144+
r.validate_task_06_03(g)
145+
146+
# %% [markdown]
147+
# **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**
148+
#
149+
150+
# %%
151+
vcard = Namespace("http://www.w3.org/2001/vcard-rdf/3.0/")
152+
foaf = Namespace("http://xmlns.com/foaf/0.1/")
153+
154+
g.add((oscar, vcard.Given, Literal("Oscar", datatype=XSD.string)))
155+
g.add((oscar, vcard.Family, Literal("García", datatype=XSD.string)))
156+
g.add((oscar, foaf.email, Literal("ocorcho@fi.upm.es", datatype=XSD.string)))
157+
for s, p, o in g:
158+
print(s,p,o)
159+
160+
# %%
161+
# Validation. Do not remove
162+
r.validate_task_06_04(g)
163+
r.save_report("_Task_06")
164+
165+
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
# %% [markdown]
2+
# **Task 07: Querying RDF(s)**
3+
4+
# %%
5+
#!pip install rdflib
6+
import urllib.request
7+
url = 'https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/refs/heads/master/Assignment4/course_materials/python/validation.py'
8+
urllib.request.urlretrieve(url, 'validation.py')
9+
github_storage = "https://raw.githubusercontent.com/FacultadInformatica-LinkedData/Curso2025-2026/master/Assignment4/course_materials"
10+
11+
# %%
12+
from validation import Report
13+
14+
# %% [markdown]
15+
# First let's read the RDF file
16+
17+
# %%
18+
from rdflib import Graph, Namespace, Literal
19+
from rdflib.namespace import RDF, RDFS
20+
# Do not change the name of the variables
21+
g = Graph()
22+
g.namespace_manager.bind('ns', Namespace("http://somewhere#"), override=False)
23+
g.parse(github_storage+"/rdf/data06.ttl", format="TTL")
24+
report = Report()
25+
26+
# %% [markdown]
27+
# **TASK 7.1a: For all classes, list each classURI. If the class belogs to another class, then list its superclass.**
28+
# **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**
29+
30+
# %%
31+
result = []
32+
for cls in g.subjects(RDF.type, RDFS.Class):
33+
superclasses = list(g.objects(cls, RDFS.subClassOf))
34+
if superclasses:
35+
for sup in superclasses:
36+
result.append((str(cls), str(sup)))
37+
else:
38+
result.append((str(cls), None))
39+
for r in result:
40+
print(r)
41+
42+
# %%
43+
## Validation: Do not remove
44+
report.validate_07_1a(result)
45+
46+
# %% [markdown]
47+
# **TASK 7.1b: Repeat the same exercise in SPARQL, returning the variables ?c (class) and ?sc (superclass)**
48+
49+
# %%
50+
query = """
51+
SELECT ?c ?sc
52+
WHERE {
53+
?c rdf:type rdfs:Class .
54+
OPTIONAL { ?c rdfs:subClassOf ?sc . }
55+
}
56+
"""
57+
58+
for r in g.query(query):
59+
print(r.c, r.sc)
60+
61+
62+
# %%
63+
## Validation: Do not remove
64+
report.validate_07_1b(query,g)
65+
66+
# %% [markdown]
67+
# **TASK 7.2a: List all individuals of "Person" with RDFLib (remember the subClasses). Return the individual URIs in a list called "individuals"**
68+
#
69+
70+
# %%
71+
people = Namespace("http://oeg.fi.upm.es/def/people#")
72+
73+
def is_subclass_of_person(c):
74+
if c == people.Person:
75+
return True
76+
for _, _, sup in g.triples((c, RDFS.subClassOf, None)):
77+
if is_subclass_of_person(sup):
78+
return True
79+
return False
80+
81+
individuals = []
82+
vistos = set()
83+
84+
for s, p, o in g.triples((None, RDF.type, None)):
85+
if o == people.Person or is_subclass_of_person(o):
86+
if s not in vistos:
87+
vistos.add(s)
88+
individuals.append(s)
89+
90+
for i in individuals:
91+
print(i)
92+
93+
# %%
94+
# validation. Do not remove
95+
report.validate_07_02a(individuals)
96+
97+
# %% [markdown]
98+
# **TASK 7.2b: Repeat the same exercise in SPARQL, returning the individual URIs in a variable ?ind**
99+
100+
# %%
101+
102+
query = """
103+
PREFIX people: <http://oeg.fi.upm.es/def/people#>
104+
SELECT DISTINCT ?ind
105+
WHERE {
106+
?ind rdf:type ?c .
107+
?c rdfs:subClassOf* people:Person .
108+
}
109+
"""
110+
for r in g.query(query):
111+
print(r.ind)
112+
# Visualize the results
113+
114+
# %%
115+
## Validation: Do not remove
116+
report.validate_07_02b(g, query)
117+
118+
# %% [markdown]
119+
# **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**
120+
121+
# %%
122+
123+
query = """
124+
PREFIX people: <http://oeg.fi.upm.es/def/people#>
125+
SELECT ?name ?type
126+
where{
127+
?x people:knows people:Rocky .
128+
?x rdfs:label ?name .
129+
?x a ?type .
130+
}
131+
"""
132+
# Visualize the results
133+
for r in g.query(query):
134+
print(r.name, r.type)
135+
136+
# %%
137+
## Validation: Do not remove
138+
report.validate_07_03(g, query)
139+
140+
# %% [markdown]
141+
# **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**
142+
143+
# %%
144+
query = """
145+
PREFIX people: <http://oeg.fi.upm.es/def/people#>
146+
SELECT DISTINCT ?name WHERE {
147+
?x rdfs:label ?name .
148+
{
149+
?x people:hasColleague ?colleague .
150+
?z people:ownsPet ?pet .
151+
} UNION {
152+
?x people:hasColleague ?colleague1 .
153+
?y people:hasColleague ?colleague2 .
154+
?z people:ownsPet ?pet .
155+
}
156+
}
157+
"""
158+
159+
for r in g.query(query):
160+
print(r.name)
161+
162+
# TO DO
163+
# Visualize the results
164+
165+
# %%
166+
## Validation: Do not remove
167+
report.validate_07_04(g,query)
168+
report.save_report("_Task_07")
169+
170+

0 commit comments

Comments
 (0)