Chapter 6 — Assignment Project: A Knowledge Graph for Course Advising
Overview¶
A computer science department keeps its course catalogue and its students’ records in separate spreadsheets. Advisors spend hours answering the same questions: Which courses can this student take next? Who has already passed Machine Learning? Why would this course suit me? The department asks you to turn the spreadsheets into a knowledge graph, answer those questions with SPARQL, audit the data for errors, and propose explained course suggestions.
Data (generated in the notebook; the students are simulated):
CATALOGUE: 24 courses with title, department, prerequisites and topics;RECORDS: 300 students and the courses they have passed.
The spreadsheets were typed by hand over many years: they contain mistakes, which Part C asks you to find.
| Part | Task | Points |
|---|---|---|
| A | Build the knowledge graph | 20 |
| B | Answer advising questions with SPARQL | 30 |
| C | Audit the data quality | 25 |
| D | Explained suggestions | 10 |
| E | Report for the department | 15 |
import re
import numpy as np
import pandas as pd
from collections import Counter, defaultdict
from rdflib import Graph, Namespace, Literal, RDF, RDFS
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
CATALOGUE = [ # code, title, department, prerequisites, topics
('CS101', 'Programming 1', 'CS', [], ['programming']),
('CS102', 'Programming 2', 'CS', ['CS101'], ['programming']),
('CS201', 'Data Structures', 'CS', ['CS102'], ['programming', 'theory']),
('CS202', 'Discrete Mathematics', 'CS', [], ['math', 'theory']),
('CS210', 'Computer Organisation', 'CS', ['CS102'], ['systems']),
('CS220', 'Databases', 'CS', ['CS201'], ['data']),
('CS230', 'Web Development', 'CS', ['CS102'], ['web', 'programming']),
('CS301', 'Algorithms', 'CS', ['CS201', 'CS202'], ['theory']),
('CS310', 'Operating Systems', 'CS', ['CS201', 'CS210'], ['systems']),
('CS320', 'Data Mining', 'CS', ['CS220', 'MA201'], ['data', 'AI']),
('CS330', 'Computer Networks', 'CS', ['CS210'], ['systems', 'web']),
('CS340', 'Artificial Intelligence', 'CS', ['CS301', 'MA201'], ['AI']),
('CS350', 'Information Security', 'CS', ['CS330'], ['security', 'systems']),
('CS360', 'Machine Learning', 'CS', ['CS340', 'MA210'], ['AI', 'data']),
('CS361', 'Machine learning ', 'CS', ['CS340', 'MA210'], ['AI', 'data']),
('CS370', 'Cloud Computing', 'CS', ['CS310', 'CS330'], ['systems', 'web']),
('CS380', 'Natural Language Processing', 'CS', ['CS360', 'CS390'], ['AI']),
('CS390', 'Computer Vision', 'CS', ['CS380'], ['AI']),
('CS395', 'Cryptography', 'CS', ['CS301', 'MA201'], ['security', 'math']),
('CS399', 'Professional Ethics', 'CS', [], []),
('MA101', 'Calculus 1', 'MATH', [], ['math']),
('MA102', 'Calculus 2', 'MATH', ['MA101'], ['math']),
('MA201', 'Probability and Statistics', 'MATH', ['MA101'], ['math', 'data']),
('MA210', 'Linear Algebra', 'MATH', ['MA101'], ['math']),
]
def simulate_records(n=300, seed=42):
"""Simulated students: a common core, then electives chosen partly by a hidden interest."""
prereqs = {c: p for c, _, _, p, _ in CATALOGUE if c not in ('CS361', 'CS380', 'CS390')}
prereqs.update({'CS380': ['CS360'], 'CS390': ['CS360']})
topics = {c: t for c, _, _, _, t in CATALOGUE}
core = ['CS101', 'MA101', 'CS102', 'CS202', 'MA201', 'MA210', 'CS201']
rng, records = np.random.default_rng(seed), []
for i in range(n):
interest = ['AI', 'data', 'systems', 'security', 'web', 'theory'][rng.integers(6)]
done = list(core)
for _ in range(rng.integers(3, 8)):
options = [c for c in prereqs if c not in done and all(p in done for p in prereqs[c])]
w = np.array([5.0 if interest in topics[c] else 1.0 for c in options])
done.append(options[rng.choice(len(options), p=w / w.sum())])
records.append((f'S{i + 1:03d}', done))
records[16][1].append('CS380') # a typing error: passed without its prerequisite
records[41][1].remove('CS102') # a lost line: CS102 missing from a record
return records
RECORDS = simulate_records()
print(len(CATALOGUE), 'courses;', len(RECORDS), 'students; first record:', RECORDS[0])Part A — Build the Knowledge Graph (20 points)¶
A1 (checked). Complete build_graph(catalogue, records), returning an rdflib Graph with the namespace ex: <http://example.org/> and:
for each course:
ex:CODE a ex:Course,rdfs:label "Title",ex:department ex:DEPT, oneex:prerequisite ex:OTHERper prerequisite, oneex:topic ex:TOPICper topic;for each student:
ex:SID a ex:Student, and oneex:passed ex:CODEper course passed.
Use the title exactly as written (do not clean it yet: Part C is about finding such problems).
EX = Namespace('http://example.org/')
def build_graph(catalogue, records):
raise NotImplementedError # TODOdef _expected_size():
return sum(3 + len(p) + len(t) for _, _, _, p, t in CATALOGUE) + sum(1 + len(set(d)) for _, d in RECORDS)
check('A1: the number of triples', lambda: len(build_graph(CATALOGUE, RECORDS)) == _expected_size())
check('A1: types, labels and prerequisites', lambda: (lambda g: (EX.CS340, RDF.type, EX.Course) in g and (EX.CS340, EX.prerequisite, EX.CS301) in g and (EX.S001, RDF.type, EX.Student) in g and str(g.value(EX.CS340, RDFS.label)) == 'Artificial Intelligence')(build_graph(CATALOGUE, RECORDS)))
g = build_graph(CATALOGUE, RECORDS)
PREFIX = 'PREFIX ex: <http://example.org/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> '
def sparql(q):
return [tuple(str(v).replace('http://example.org/', '') for v in row) for row in g.query(PREFIX + q)]
print(len(g), 'triples')Part B — Advising Questions (30 points)¶
Write each query as a SPARQL string. The check cells compare your answers with a plain-Python computation.
B1 (checked). Every course with the number of students who passed it, most passed first (GROUP BY, COUNT, ORDER BY).
B2 (checked). For student S001: the courses they can take now, i.e. not yet passed and with every prerequisite passed. (Hint: FILTER NOT EXISTS { ?course ex:prerequisite ?p . FILTER NOT EXISTS { ex:S001 ex:passed ?p } }.)
B3 (checked). Every course that CS360 depends on, directly or indirectly (a property path).
B4. Which students have passed every course with the topic security? (Hint: a double FILTER NOT EXISTS again.)
B1 = 'TODO'
B2 = 'TODO'
B3 = 'TODO'
B4 = 'TODO'_passed = {sid: set(d) for sid, d in RECORDS}
_pre = {c: p for c, _, _, p, _ in CATALOGUE}
def _closure(c, seen=None):
seen = set() if seen is None else seen
for p in _pre[c]:
if p not in seen:
seen.add(p); _closure(p, seen)
return seen
check('B1: counts', lambda: dict((c, int(n)) for c, n in sparql(B1)) == dict(Counter(c for d in _passed.values() for c in d)))
check('B1: ordered by count', lambda: [int(n) for _, n in sparql(B1)] == sorted([int(n) for _, n in sparql(B1)], reverse=True))
check('B2: what S001 can take now', lambda: [c for (c,) in sparql(B2)] == sorted(c for c in _pre if c not in _passed['S001'] and all(p in _passed['S001'] for p in _pre[c])))
check('B3: everything CS360 depends on', lambda: {c for (c,) in sparql(B3)} == _closure('CS360'))
print('B4:', [s for (s,) in sparql(B4)][:10], '...', len(sparql(B4)), 'students')Part C — Audit the Data Quality (25 points)¶
C1 (checked). A prerequisite cycle makes courses impossible to take. Complete find_cycles(prereqs) (a dict course → list of prerequisites), returning the set of courses that lie on a cycle (a course that is, directly or indirectly, its own prerequisite).
def find_cycles(prereqs):
raise NotImplementedError # TODOcheck('C1: a toy example', lambda: find_cycles({'A': ['B'], 'B': ['C'], 'C': ['A'], 'D': ['A'], 'E': []}) == {'A', 'B', 'C'})
print('courses on a cycle in the catalogue:', sorted(find_cycles(_pre)))C2 (checked). Write a SPARQL query C2 listing every (student, course) pair where the student passed the course without having passed one of its prerequisites (DISTINCT).
C2 = 'TODO'_violations = sorted({(s, c) for s, d in _passed.items() for c in d for p in _pre[c] if p not in d})
check('C2: the prerequisite violations', lambda: sparql(C2) == _violations)
print(sparql(C2))C3. Find duplicate courses: different codes whose titles are the same after normalising (lower case, extra spaces removed). Then list the courses with no topic, and say whether that is an error under the open-world assumption.
# TODOC4. Summarise your audit in a table: each problem, how you found it, how many records it affects, and the fix you propose (which record should change, or who should be asked).
Your audit table:
Part D — Explained Suggestions (10 points)¶
Complete the cell below: for a student, rank the courses they can take now (B2) by how many of their passed electives share a topic with the course (ignore the common core: CS101, MA101, CS102, CS202, MA201, MA210, CS201), and print, for the top 3, an explanation path in the graph such as S001 —passed→ CS220 —topic→ data ←topic— CS320. Run it for S001 and S100.
CORE = {'CS101', 'MA101', 'CS102', 'CS202', 'MA201', 'MA210', 'CS201'}
TOPICS = {c: set(t) for c, _, _, _, t in CATALOGUE}
def suggest(sid, k=3):
raise NotImplementedError # TODO
for sid in ['S001', 'S100']:
print(sid, 'passed electives:', sorted(c for c in _passed[sid] if c not in CORE))
suggest(sid)Part E — Report for the Department (15 points)¶
Write 250–350 words for the head of department:
What the knowledge graph contains and why it is more useful than the two spreadsheets.
Three advising questions it now answers instantly (with an example answer each).
The data problems your audit found, and what the department must decide or correct.
How the explained suggestions could be used, and what they must not be used for.
Your report:
Grading Rubric¶
| Part | Full marks if… |
|---|---|
| A (20) | the graph is built correctly (checked) |
| B (30) | the three checked queries are correct; B4 answered |
| C (25) | cycle detection and violations correct (checked); duplicates and missing topics found; a clear audit table with fixes |
| D (10) | suggestions ranked as specified, each with a readable path explanation |
| E (15) | clear for the department; accurate; problems and responsibilities stated |