Module 16: Capstone projects¶
Learning objectives
By the end of this module, you can:
- O1. Plan a ddigraph pipeline for a file: the steps in order, what each step proves, and what you will hand in.
- O2. Check a file before you load it, with a preview, an XSD validation and a dry run, and explain each result.
- O3. Load the graph into the backend you use, and follow the paths your track needs: variables, code lists or correspondences.
- O4. Export the graph as linked data and check it, with SHACL and with a SPARQL query on published terms (DISCO, SKOS, XKOS).
- O5. Write a short quality report, and defend two design choices against the options you rejected.
Prerequisites: Modules 1–15, up to Give a model tools over the graph
Time: 60 min self-paced / 80 min instructor-led.
Needs: No server for the DuckDB and Oxigraph tabs. The Neo4j tabs need Neo4j 5, and the Gremlin tabs a Gremlin Server; Module 2 starts both.
New in this module: nothing new. You combine ddigraph preview, validate, load and export, iter_graph, the lenses and the backends of earlier modules.
How the capstone works¶
You have learned each tool on its own. Now you put them together on one file, from the first look to a report that someone else can trust.
Pick the track that matches your work. Each track takes one file through the same five steps: plan, check, load and explore, prove, and report. The tracks differ in the file and in the paths you follow. All three files describe the course's sample survey, the Labour Force Survey of the third quarter of 2025.
| Track | For | File | What you follow | Modules to review |
|---|---|---|---|---|
| A | Data archives | tests/fixtures/lfs_codebook.xml |
Variables, their questions, categories and concepts | 3, 5, 6, 7 |
| B | Survey teams | tests/fixtures/lfs_lifecycle.xml, plus a variable you add |
Questions to variables to code lists | 4, 6, 8, 9 |
| C | Classification teams | tests/fixtures/lfs_correspondence.xml |
Correspondences between classifications (XKOS) | 8, 9, 10 |
Each track's "load and explore" step has a sample solution on four
backends: Neo4j, Gremlin, DuckDB and Oxigraph. Pick the tab
of the backend you use. Each tab loads the file under its own dataset ID,
m16-codebook, m16-survey or m16-cdi, and prints the same result. It is
one graph, whatever stores it.
If you are not sure which track to pick, take Track A. It needs the fewest steps.
Plan your project¶
(O1) Write a plan before any code. A plan is a short table: one row per
step, the command or function you will use, and what the step proves. It is
your first deliverable, and it saves time, because most capstone mistakes
come from steps taken in the wrong order. For example, a load with
--replace before anyone has checked the file.
Here are three rows of a plan for Track A:
| Step | Command or function | What it proves |
|---|---|---|
| Look | ddigraph preview |
The file holds the variables we expect |
| Check | ddigraph validate, ddigraph load --dry-run |
Whether it is valid DDI, and what a load would write |
| Load | ddigraph load --replace, or a lens |
The graph is in the backend, once |
Under the table, write two notes:
- Deliverables: what you will hand in. Each track lists its own.
- Two design choices you will defend at the end. For example: recover or strict parsing, which backend, or which checks go in the report.
Exercises¶
Scenario
Your national statistics office is moving the metadata of its Labour Force Survey into a graph. Three teams each send one file: the archive, the survey team and the classification team. You are on one of those teams. Your file has to come out the other side checked, loaded, explored and reported on, so that the next person can trust it without starting again.
Track A: A Codebook archive¶
Brief. The archive holds tests/fixtures/lfs_codebook.xml, the Labour
Force Survey as a DDI Codebook: a study, a data file and seven variables.
Before the archive publishes it in a catalogue, the curator asks for a
report: is the file valid, what does the graph hold, which variables lack a
question, categories or a concept, and does every coded variable have a
full set of categories?
Deliverables. Your plan; the output of each check; the variables table from your backend; a quality report in Markdown.
Exercise 1 (O1, O2). Write the first two rows of your plan. Then look at the file and check it: its flavor, the size of its graph, its XSD and SHACL results, and what a dry run would write.
Expected output:
Format: codebook
Nodes: 80 Relationships: 48
Result: valid
Shapes result: conforms
Ingestion complete: dataset_id=m16-codebook, nodes_written=80, relationships_written=48, stubs=0, references=41, resolved=41, unresolved=0, conflicts=0
Answer
| Step | Command | What it proves |
|---|---|---|
| Look | ddigraph detect, ddigraph preview |
It is a Codebook, and how big its graph is |
| Check | ddigraph validate --shapes, ddigraph load --dry-run |
It passes the XSD and the shapes, and what a load would write |
ddigraph detect tests/fixtures/lfs_codebook.xml | sed -n 1p
ddigraph preview tests/fixtures/lfs_codebook.xml 2> /dev/null | sed -n 2p
ddigraph validate tests/fixtures/lfs_codebook.xml --shapes > checks.txt 2> /dev/null || echo "Check failed: exit $?"
grep "Result\|result" checks.txt
ddigraph load tests/fixtures/lfs_codebook.xml --dataset-id m16-codebook --dry-run 2> /dev/null | tail -n 1
Format: codebook
Nodes: 80 Relationships: 48
Result: valid
Shapes result: conforms
Ingestion complete: dataset_id=m16-codebook, nodes_written=80, relationships_written=48, stubs=0, references=41, resolved=41, unresolved=0, conflicts=0
The file passes the XSD and ddigraph's shapes, and the dry run finds no conflict and no unresolved reference: all 41 references find their end. A valid file can still miss content that its users need, so the next two exercises look inside.
Exercise 2 (O3). Load the file into your backend as the dataset
m16-codebook. For each variable, print its ID and name, whether it has a
question text, and how many categories (USES_CATEGORY) and concepts
(USES_CONCEPT) it has.
Expected output:
Loaded: 80 nodes, 48 relationships
V1 SEX: asked=True, categories=2, concepts=1
V2 AGE: asked=True, categories=0, concepts=1
V3 AGEGRP: asked=False, categories=6, concepts=1
V4 REGION: asked=True, categories=5, concepts=1
V5 EDUC: asked=True, categories=5, concepts=1
V6 ILOSTAT: asked=False, categories=3, concepts=1
V7 HOURS: asked=True, categories=0, concepts=1
Answer
Cypher, through the neo4j driver. The last lines purge the dataset, so the
example leaves your database as it found it. Leave them out to keep the data.
import os
from neo4j import GraphDatabase
import ddigraph
from ddigraph.lens.neo4j import Neo4jLens
result = ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m16-codebook", replace=True)
print("Loaded:", result.nodes_written, "nodes,", result.relationships_written, "relationships")
VARIABLES = """
MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
RETURN v.ddi_id AS id, v.name AS name, v.question_text IS NOT NULL AS asked,
COUNT { (v)-[:USES_CATEGORY]->() } AS categories,
COUNT { (v)-[:USES_CONCEPT]->() } AS concepts
ORDER BY id
"""
driver = GraphDatabase.driver(
os.environ["DDIGRAPH_NEO4J_URI"],
auth=(os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"]),
)
records, _, _ = driver.execute_query(VARIABLES, dataset="m16-codebook")
for row in records:
print(
f"{row['id']} {row['name']}: asked={row['asked']}, categories={row['categories']}, concepts={row['concepts']}"
)
Neo4jLens(driver).purge("m16-codebook") # clean up: remove the capstone's dataset
driver.close()
Loaded: 80 nodes, 48 relationships
V1 SEX: asked=True, categories=2, concepts=1
V2 AGE: asked=True, categories=0, concepts=1
V3 AGEGRP: asked=False, categories=6, concepts=1
V4 REGION: asked=True, categories=5, concepts=1
V5 EDUC: asked=True, categories=5, concepts=1
V6 ILOSTAT: asked=False, categories=3, concepts=1
V7 HOURS: asked=True, categories=0, concepts=1
A Gremlin traversal. Gremlin stores the label property as ddi_label,
since some servers keep label for themselves. The last lines drop the
vertices that only this dataset holds.
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from ddigraph.backends.gremlin import write_gremlin
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
result = write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="m16-codebook")
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
rows = (
g.V()
.has("Dataset", "dataset_id", "m16-codebook")
.in_("IN_DATASET")
.hasLabel("Variable")
.order()
.by("ddi_id")
.project("id", "name", "asked", "categories", "concepts")
.by("ddi_id")
.by("name")
.by(__.properties("question_text").count())
.by(__.out("USES_CATEGORY").count())
.by(__.out("USES_CONCEPT").count())
.to_list()
)
for row in rows:
print(
f"{row['id']} {row['name']}: asked={row['asked'] > 0}, categories={row['categories']}, concepts={row['concepts']}"
)
# Clean up: drop the vertices only this dataset holds, then its Dataset vertex
dataset = g.V().has("Dataset", "dataset_id", "m16-codebook")
dataset.in_("IN_DATASET").where(__.out("IN_DATASET").count().is_(1)).drop().iterate()
g.V().has("Dataset", "dataset_id", "m16-codebook").drop().iterate()
connection.close()
Loaded: 80 nodes, 48 relationships
V1 SEX: asked=True, categories=2, concepts=1
V2 AGE: asked=True, categories=0, concepts=1
V3 AGEGRP: asked=False, categories=6, concepts=1
V4 REGION: asked=True, categories=5, concepts=1
V5 EDUC: asked=True, categories=5, concepts=1
V6 ILOSTAT: asked=False, categories=3, concepts=1
V7 HOURS: asked=True, categories=0, concepts=1
SQL over the SQL lens's tables, in a DuckDB database in memory.
import duckdb
from ddigraph import ir
from ddigraph.lens.sql import SQLLens
connection = duckdb.connect() # a database in memory
lens = SQLLens(connection)
result = lens.write(
ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m16-codebook"),
dataset_id="m16-codebook",
)
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
VARIABLES = """
SELECT ddi_id.string_value AS id, name.string_value AS name, asked.key IS NOT NULL AS asked,
(SELECT count(*) FROM ddigraph_relationships AS r
WHERE r.start_key = m.key AND r.type = 'USES_CATEGORY') AS categories,
(SELECT count(*) FROM ddigraph_relationships AS r
WHERE r.start_key = m.key AND r.type = 'USES_CONCEPT') AS concepts
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor AND l.type_label = 'Variable'
LEFT JOIN ddigraph_properties AS ddi_id ON ddi_id.key = m.key AND ddi_id.name = 'ddi_id'
LEFT JOIN ddigraph_properties AS name ON name.key = m.key AND name.name = 'name'
LEFT JOIN ddigraph_properties AS asked ON asked.key = m.key AND asked.name = 'question_text'
WHERE m.dataset = ?
ORDER BY id
"""
for id_, name, asked, categories, concepts in connection.execute(
VARIABLES, ["m16-codebook"]
).fetchall():
print(f"{id_} {name}: asked={asked}, categories={categories}, concepts={concepts}")
Loaded: 80 nodes, 48 relationships
V1 SEX: asked=True, categories=2, concepts=1
V2 AGE: asked=True, categories=0, concepts=1
V3 AGEGRP: asked=False, categories=6, concepts=1
V4 REGION: asked=True, categories=5, concepts=1
V5 EDUC: asked=True, categories=5, concepts=1
V6 ILOSTAT: asked=False, categories=3, concepts=1
V7 HOURS: asked=True, categories=0, concepts=1
SPARQL over the RDF lens's graph, in an Oxigraph store in memory.
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens() # a store in memory
result = lens.write(
ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m16-codebook"),
dataset_id="m16-codebook",
)
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
VARIABLES = """
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX disco: <http://rdf-vocabulary.ddialliance.org/discovery#>
SELECT ?id ?name ?asked (COUNT(DISTINCT ?category) AS ?categories) (COUNT(DISTINCT ?concept) AS ?concepts)
WHERE {
?membership a ddigraph:Membership ; ddigraph:dataset "m16-codebook" ; ddigraph:member ?v .
?v a ddigraph:Variable ; ddigraph:ddiId ?id ; ddigraph:name ?name .
BIND(EXISTS { ?v disco:questionText ?text } AS ?asked)
OPTIONAL { ?v ddigraph:usesCategory ?category }
OPTIONAL { ?v ddigraph:usesConcept ?concept }
}
GROUP BY ?id ?name ?asked
ORDER BY ?id
"""
for row in lens.store.query(VARIABLES):
asked = row["asked"].value == "true"
print(
f"{row['id'].value} {row['name'].value}: asked={asked}, categories={row['categories'].value}, concepts={row['concepts'].value}"
)
Loaded: 80 nodes, 48 relationships
V1 SEX: asked=True, categories=2, concepts=1
V2 AGE: asked=True, categories=0, concepts=1
V3 AGEGRP: asked=False, categories=6, concepts=1
V4 REGION: asked=True, categories=5, concepts=1
V5 EDUC: asked=True, categories=5, concepts=1
V6 ILOSTAT: asked=False, categories=3, concepts=1
V7 HOURS: asked=True, categories=0, concepts=1
Four query languages, one answer: each backend holds the same graph.
The query reads the variables through their membership in
m16-codebook, so data that other datasets hold never gets in.
Exercise 3 (O5). Write the quality report for the curator. Use the XSD
result, the counts of a dry run (ddigraph.load(..., dry_run=True)) and the
graph itself. List the variables that have no question, no categories or no
concept, and the coded variables with fewer than two categories.
Expected output:
# Quality report: lfs_codebook.xml
- XSD: valid, 0 issue(s)
- Graph: 80 nodes, 48 relationships
- References: 41, resolved 41, unresolved {}
- Conflicts: 0
- Variables: 7
- Variables with no question: Text(value='AGEGRP', lang=None), Text(value='ILOSTAT', lang=None)
- Variables with no categories: Text(value='AGE', lang=None), Text(value='HOURS', lang=None)
- Variables with no concept: none
- Coded variables with fewer than 2 categories: none
Answer
import ddigraph
from ddigraph import iter_graph
from ddigraph.validation import validate
path = "tests/fixtures/lfs_codebook.xml"
xsd = validate(path)
load = ddigraph.load(path, dataset_id="m16-codebook", dry_run=True)
variables, edges = {}, []
for chunk in iter_graph(path):
for node in chunk.nodes:
if node.label == "Variable":
variables[node.key] = node
for edge in chunk.relationships:
edges.append((edge.start, edge.type))
def count(key, rel_type):
"""How many `rel_type` edges start at the node `key`."""
return edges.count((key, rel_type))
def names(test):
"""The name of each variable that passes a test, or 'none'."""
found = [str(node.properties["name"]) for key, node in variables.items() if test(key)]
return ", ".join(found) or "none"
report = [
"# Quality report: lfs_codebook.xml",
"",
f"- XSD: {'valid' if xsd.valid else 'invalid'}, {len(xsd.issues)} issue(s)",
f"- Graph: {load.nodes_written} nodes, {load.relationships_written} relationships",
f"- References: {load.references}, resolved {load.resolved}, unresolved {dict(load.unresolved)}",
f"- Conflicts: {len(load.conflicts)}",
f"- Variables: {len(variables)}",
f"- Variables with no question: {names(lambda key: 'question_text' not in variables[key].properties)}",
f"- Variables with no categories: {names(lambda key: count(key, 'USES_CATEGORY') == 0)}",
f"- Variables with no concept: {names(lambda key: count(key, 'USES_CONCEPT') == 0)}",
f"- Coded variables with fewer than 2 categories: {names(lambda key: count(key, 'USES_CATEGORY') == 1)}",
]
print("\n".join(report))
# Quality report: lfs_codebook.xml
- XSD: valid, 0 issue(s)
- Graph: 80 nodes, 48 relationships
- References: 41, resolved 41, unresolved {}
- Conflicts: 0
- Variables: 7
- Variables with no question: Text(value='AGEGRP', lang=None), Text(value='ILOSTAT', lang=None)
- Variables with no categories: Text(value='AGE', lang=None), Text(value='HOURS', lang=None)
- Variables with no concept: none
- Coded variables with fewer than 2 categories: none
A dry run needs no database, so the report runs anywhere. Each line
is a fact the curator can act on. AGEGRP and ILOSTAT have no
question because they are derived: the codebook says how, in each
variable's <derivation>. ddigraph does not read that text into the
graph, so the curator checks it in the file. AGE and HOURS have no
categories because they are numbers, ages and hours. The report asks,
it does not decide.
The last line guards the code lists. A coded variable with one category tells the data user nothing, since every person would get the same code. A variable with none may be a number, as here, or may have lost its code list.
Track B: A Lifecycle survey¶
Brief. The survey team keeps its questionnaire as a DDI-Lifecycle
FragmentInstance, tests/fixtures/lfs_lifecycle.xml: 8 questions, 6 code
lists and 7 variables. The variable ILOSTAT, labour force status, is
derived from the answers to three questions, WORK, LOOK and AVAIL.
Users also want the answer to WORK on its own: did the person work last
week? So the team adds the variable WORK, which comes from the question
WORK and takes its values from the code list Yes or no. You check the
new file, trace each coded variable back to its questions and its answers,
and publish the result as linked data that passes SHACL.
Deliverables. Your plan; the checks; the trace from your backend; the Turtle export with its SHACL result; a SPARQL query on published terms.
Exercise 4 (O1, O2). Write the new variable as a fragment, save the
survey as survey-plus.xml, and check it. Show the variables' edges in the
preview, the XSD result, and a dry run with --resolve fail, which refuses
the file if a reference has no end.
Expected output:
Variable 8
(Variable)-[:REFERENCES_QUESTION]->(QuestionItem) 10
(Variable)-[:IN_UNIVERSE]->(Universe) 8
(Variable)-[:USES_CONCEPT]->(Concept) 8
(Variable)-[:USES_CODELIST]->(CodeList) 6
Result: valid
Ingestion complete: dataset_id=m16-survey, nodes_written=88, relationships_written=112, stubs=0, references=89, resolved=89, unresolved=0, conflicts=0
Answer
| Step | Command | What it proves |
|---|---|---|
| Build | a short Python script | The variable is a fragment with four references |
| Look | ddigraph preview |
The survey now has 8 variables, with their edges |
| Check | ddigraph validate, ddigraph load --dry-run --resolve fail |
It passes the XSD, and every reference ends at a node |
python - <<'PY'
from pathlib import Path
# The new variable WORK: the answer to the question WORK, coded with the Yes or no list
VARIABLE = """<Fragment><l:Variable isUniversallyUnique="true">
<r:URN>urn:ddi:example.nso:var-work:1</r:URN>
<r:Agency>example.nso</r:Agency><r:ID>var-work</r:ID><r:Version>1</r:Version>
<l:VariableName><r:String xml:lang="en">WORK</r:String></l:VariableName>
<r:Label><r:Content xml:lang="en">Worked last week</r:Content></r:Label>
<r:UniverseReference><r:URN>urn:ddi:example.nso:universe-persons15:1</r:URN><r:TypeOfObject>Universe</r:TypeOfObject></r:UniverseReference>
<r:ConceptReference><r:URN>urn:ddi:example.nso:concept-labour:1</r:URN><r:TypeOfObject>Concept</r:TypeOfObject></r:ConceptReference>
<r:QuestionReference><r:URN>urn:ddi:example.nso:q-work:1</r:URN><r:TypeOfObject>QuestionItem</r:TypeOfObject></r:QuestionReference>
<l:VariableRepresentation><r:CodeRepresentation><r:CodeListReference><r:URN>urn:ddi:example.nso:cl-yesno:1</r:URN>
<r:TypeOfObject>CodeList</r:TypeOfObject></r:CodeListReference></r:CodeRepresentation></l:VariableRepresentation>
</l:Variable></Fragment>"""
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
Path("survey-plus.xml").write_text(text.replace("</FragmentInstance>", VARIABLE + "</FragmentInstance>"), encoding="utf-8")
PY
ddigraph preview survey-plus.xml 2> /dev/null | grep "Variable"
ddigraph validate survey-plus.xml > xsd.txt 2> /dev/null || echo "XSD check: exit $?"
grep "^Result" xsd.txt
ddigraph load survey-plus.xml --dataset-id m16-survey --dry-run --resolve fail 2> /dev/null | tail -n 1
Variable 8
(Variable)-[:REFERENCES_QUESTION]->(QuestionItem) 10
(Variable)-[:IN_UNIVERSE]->(Universe) 8
(Variable)-[:USES_CONCEPT]->(Concept) 8
(Variable)-[:USES_CODELIST]->(CodeList) 6
Result: valid
Ingestion complete: dataset_id=m16-survey, nodes_written=88, relationships_written=112, stubs=0, references=89, resolved=89, unresolved=0, conflicts=0
Each reference names its target by URN and by TypeOfObject. DDI 3.3
requires TypeOfObject, and ddigraph needs it to see a reference at
all: leave it out and the edge is silently missing. The variable's
elements also come in the order the XSD sets: name, label, universe,
concept, question, then representation. The file stays valid, and
--resolve fail passes, so all 89 references find their end.
Exercise 5 (O3). Load survey-plus.xml into your backend as the dataset
m16-survey. For each variable that has a code list, print its name, the
questions it comes from, its code list, and its answers in the order of
their codes. Follow the code list path of Module 9, which works whether the
codes have IDs or not.
Expected output:
Loaded: 88 nodes, 112 relationships
AGEGRP: AGE -> Age group -> 15-24, 25-34, 35-44, 45-54, 55-64, 65 and over
EDUC: EDUC -> Highest level of education -> Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
ILOSTAT: AVAIL, LOOK, WORK -> Labour force status (ILO) -> Employed, Unemployed, Not in the labour force
REGION: REGION -> Region -> Capital region, North, South, East, West
SEX: SEX -> Sex -> Male, Female
WORK: WORK -> Yes or no -> Yes, No
Answer
Cypher, through the neo4j driver. The last lines purge the dataset, so the
example leaves your database as it found it. Leave them out to keep the data.
import os
from pathlib import Path
from neo4j import GraphDatabase
import ddigraph
from ddigraph.lens.neo4j import Neo4jLens
# The new variable WORK: the answer to the question WORK, coded with the Yes or no list
VARIABLE = """<Fragment><l:Variable isUniversallyUnique="true">
<r:URN>urn:ddi:example.nso:var-work:1</r:URN>
<r:Agency>example.nso</r:Agency><r:ID>var-work</r:ID><r:Version>1</r:Version>
<l:VariableName><r:String xml:lang="en">WORK</r:String></l:VariableName>
<r:Label><r:Content xml:lang="en">Worked last week</r:Content></r:Label>
<r:UniverseReference><r:URN>urn:ddi:example.nso:universe-persons15:1</r:URN><r:TypeOfObject>Universe</r:TypeOfObject></r:UniverseReference>
<r:ConceptReference><r:URN>urn:ddi:example.nso:concept-labour:1</r:URN><r:TypeOfObject>Concept</r:TypeOfObject></r:ConceptReference>
<r:QuestionReference><r:URN>urn:ddi:example.nso:q-work:1</r:URN><r:TypeOfObject>QuestionItem</r:TypeOfObject></r:QuestionReference>
<l:VariableRepresentation><r:CodeRepresentation><r:CodeListReference><r:URN>urn:ddi:example.nso:cl-yesno:1</r:URN>
<r:TypeOfObject>CodeList</r:TypeOfObject></r:CodeListReference></r:CodeRepresentation></l:VariableRepresentation>
</l:Variable></Fragment>"""
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
Path("survey-plus.xml").write_text(
text.replace("</FragmentInstance>", VARIABLE + "</FragmentInstance>"), encoding="utf-8"
)
result = ddigraph.load("survey-plus.xml", dataset_id="m16-survey", replace=True)
print("Loaded:", result.nodes_written, "nodes,", result.relationships_written, "relationships")
TRACE = """
MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
MATCH (v)-[:USES_CODELIST]->(cl:CodeList)-[:CONTAINS*0..1]->(code)-[:HAS_CATEGORY]->(cat:Category)
WITH v, cl, cat ORDER BY code.value
WITH v, cl, collect(cat.label) AS answers
MATCH (v)-[:REFERENCES_QUESTION]->(q:QuestionItem)
WITH v, cl, answers, q ORDER BY q.name
RETURN v.name AS variable, collect(q.name) AS questions, cl.label AS code_list, answers
ORDER BY variable
"""
driver = GraphDatabase.driver(
os.environ["DDIGRAPH_NEO4J_URI"],
auth=(os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"]),
)
records, _, _ = driver.execute_query(TRACE, dataset="m16-survey")
for row in records:
print(
f"{row['variable']}: {', '.join(row['questions'])} -> {row['code_list']} -> {', '.join(row['answers'])}"
)
Neo4jLens(driver).purge("m16-survey") # clean up: remove the capstone's dataset
driver.close()
Loaded: 88 nodes, 112 relationships
AGEGRP: AGE -> Age group -> 15-24, 25-34, 35-44, 45-54, 55-64, 65 and over
EDUC: EDUC -> Highest level of education -> Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
ILOSTAT: AVAIL, LOOK, WORK -> Labour force status (ILO) -> Employed, Unemployed, Not in the labour force
REGION: REGION -> Region -> Capital region, North, South, East, West
SEX: SEX -> Sex -> Male, Female
WORK: WORK -> Yes or no -> Yes, No
A Gremlin traversal. Gremlin stores the label property as ddi_label,
since some servers keep label for themselves. The last lines drop the
vertices that only this dataset holds.
from pathlib import Path
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from ddigraph.backends.gremlin import write_gremlin
# The new variable WORK: the answer to the question WORK, coded with the Yes or no list
VARIABLE = """<Fragment><l:Variable isUniversallyUnique="true">
<r:URN>urn:ddi:example.nso:var-work:1</r:URN>
<r:Agency>example.nso</r:Agency><r:ID>var-work</r:ID><r:Version>1</r:Version>
<l:VariableName><r:String xml:lang="en">WORK</r:String></l:VariableName>
<r:Label><r:Content xml:lang="en">Worked last week</r:Content></r:Label>
<r:UniverseReference><r:URN>urn:ddi:example.nso:universe-persons15:1</r:URN><r:TypeOfObject>Universe</r:TypeOfObject></r:UniverseReference>
<r:ConceptReference><r:URN>urn:ddi:example.nso:concept-labour:1</r:URN><r:TypeOfObject>Concept</r:TypeOfObject></r:ConceptReference>
<r:QuestionReference><r:URN>urn:ddi:example.nso:q-work:1</r:URN><r:TypeOfObject>QuestionItem</r:TypeOfObject></r:QuestionReference>
<l:VariableRepresentation><r:CodeRepresentation><r:CodeListReference><r:URN>urn:ddi:example.nso:cl-yesno:1</r:URN>
<r:TypeOfObject>CodeList</r:TypeOfObject></r:CodeListReference></r:CodeRepresentation></l:VariableRepresentation>
</l:Variable></Fragment>"""
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
Path("survey-plus.xml").write_text(
text.replace("</FragmentInstance>", VARIABLE + "</FragmentInstance>"), encoding="utf-8"
)
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
result = write_gremlin(g, "survey-plus.xml", dataset_id="m16-survey")
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
rows = (
g.V()
.has("Dataset", "dataset_id", "m16-survey")
.in_("IN_DATASET")
.hasLabel("Variable")
.where(__.out("USES_CODELIST"))
.order()
.by("name")
.project("variable", "questions", "code_list", "answers")
.by("name")
.by(__.out("REFERENCES_QUESTION").values("name").order().fold())
.by(__.out("USES_CODELIST").values("ddi_label"))
.by(
__.out("USES_CODELIST")
.union(__.identity(), __.out("CONTAINS"))
.order()
.by(__.coalesce(__.values("value"), __.constant("")))
.out("HAS_CATEGORY")
.values("ddi_label")
.fold()
)
.to_list()
)
for row in rows:
print(
f"{row['variable']}: {', '.join(row['questions'])} -> {row['code_list']} -> {', '.join(row['answers'])}"
)
# Clean up: drop the vertices only this dataset holds, then its Dataset vertex
dataset = g.V().has("Dataset", "dataset_id", "m16-survey")
dataset.in_("IN_DATASET").where(__.out("IN_DATASET").count().is_(1)).drop().iterate()
g.V().has("Dataset", "dataset_id", "m16-survey").drop().iterate()
connection.close()
Loaded: 88 nodes, 112 relationships
AGEGRP: AGE -> Age group -> 15-24, 25-34, 35-44, 45-54, 55-64, 65 and over
EDUC: EDUC -> Highest level of education -> Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
ILOSTAT: AVAIL, LOOK, WORK -> Labour force status (ILO) -> Employed, Unemployed, Not in the labour force
REGION: REGION -> Region -> Capital region, North, South, East, West
SEX: SEX -> Sex -> Male, Female
WORK: WORK -> Yes or no -> Yes, No
SQL over the SQL lens's tables, in a DuckDB database in memory.
from pathlib import Path
import duckdb
from ddigraph import ir
from ddigraph.lens.sql import SQLLens
# The new variable WORK: the answer to the question WORK, coded with the Yes or no list
VARIABLE = """<Fragment><l:Variable isUniversallyUnique="true">
<r:URN>urn:ddi:example.nso:var-work:1</r:URN>
<r:Agency>example.nso</r:Agency><r:ID>var-work</r:ID><r:Version>1</r:Version>
<l:VariableName><r:String xml:lang="en">WORK</r:String></l:VariableName>
<r:Label><r:Content xml:lang="en">Worked last week</r:Content></r:Label>
<r:UniverseReference><r:URN>urn:ddi:example.nso:universe-persons15:1</r:URN><r:TypeOfObject>Universe</r:TypeOfObject></r:UniverseReference>
<r:ConceptReference><r:URN>urn:ddi:example.nso:concept-labour:1</r:URN><r:TypeOfObject>Concept</r:TypeOfObject></r:ConceptReference>
<r:QuestionReference><r:URN>urn:ddi:example.nso:q-work:1</r:URN><r:TypeOfObject>QuestionItem</r:TypeOfObject></r:QuestionReference>
<l:VariableRepresentation><r:CodeRepresentation><r:CodeListReference><r:URN>urn:ddi:example.nso:cl-yesno:1</r:URN>
<r:TypeOfObject>CodeList</r:TypeOfObject></r:CodeListReference></r:CodeRepresentation></l:VariableRepresentation>
</l:Variable></Fragment>"""
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
Path("survey-plus.xml").write_text(
text.replace("</FragmentInstance>", VARIABLE + "</FragmentInstance>"), encoding="utf-8"
)
connection = duckdb.connect() # a database in memory
lens = SQLLens(connection)
result = lens.write(ir.parse("survey-plus.xml", dataset_id="m16-survey"), dataset_id="m16-survey")
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
TRACE = """
SELECT vn.string_value AS variable,
(SELECT string_agg(qn.string_value, ', ' ORDER BY qn.string_value)
FROM ddigraph_relationships AS rq
JOIN ddigraph_properties AS qn ON qn.key = rq.end_key AND qn.name = 'name'
WHERE rq.start_key = m.key AND rq.type = 'REFERENCES_QUESTION') AS questions,
cl.string_value AS code_list,
string_agg(cat.string_value, ', ' ORDER BY cv.string_value) AS answers
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor AND l.type_label = 'Variable'
JOIN ddigraph_properties AS vn ON vn.key = m.key AND vn.name = 'name'
JOIN ddigraph_relationships AS rl ON rl.start_key = m.key AND rl.type = 'USES_CODELIST'
JOIN ddigraph_properties AS cl ON cl.key = rl.end_key AND cl.name = 'label'
JOIN ddigraph_relationships AS hc ON hc.type = 'HAS_CATEGORY' AND (
hc.start_key = rl.end_key
OR hc.start_key IN (SELECT end_key FROM ddigraph_relationships
WHERE start_key = rl.end_key AND type = 'CONTAINS'))
LEFT JOIN ddigraph_properties AS cv ON cv.key = hc.start_key AND cv.name = 'value'
JOIN ddigraph_properties AS cat ON cat.key = hc.end_key AND cat.name = 'label'
WHERE m.dataset = ?
GROUP BY m.key, vn.string_value, cl.string_value
ORDER BY variable
"""
for variable, questions, code_list, answers in connection.execute(TRACE, ["m16-survey"]).fetchall():
print(f"{variable}: {questions} -> {code_list} -> {answers}")
Loaded: 88 nodes, 112 relationships
AGEGRP: AGE -> Age group -> 15-24, 25-34, 35-44, 45-54, 55-64, 65 and over
EDUC: EDUC -> Highest level of education -> Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
ILOSTAT: AVAIL, LOOK, WORK -> Labour force status (ILO) -> Employed, Unemployed, Not in the labour force
REGION: REGION -> Region -> Capital region, North, South, East, West
SEX: SEX -> Sex -> Male, Female
WORK: WORK -> Yes or no -> Yes, No
SPARQL over the RDF lens's graph, in an Oxigraph store in memory. The query returns one row per question and answer; Python groups them.
from pathlib import Path
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
# The new variable WORK: the answer to the question WORK, coded with the Yes or no list
VARIABLE = """<Fragment><l:Variable isUniversallyUnique="true">
<r:URN>urn:ddi:example.nso:var-work:1</r:URN>
<r:Agency>example.nso</r:Agency><r:ID>var-work</r:ID><r:Version>1</r:Version>
<l:VariableName><r:String xml:lang="en">WORK</r:String></l:VariableName>
<r:Label><r:Content xml:lang="en">Worked last week</r:Content></r:Label>
<r:UniverseReference><r:URN>urn:ddi:example.nso:universe-persons15:1</r:URN><r:TypeOfObject>Universe</r:TypeOfObject></r:UniverseReference>
<r:ConceptReference><r:URN>urn:ddi:example.nso:concept-labour:1</r:URN><r:TypeOfObject>Concept</r:TypeOfObject></r:ConceptReference>
<r:QuestionReference><r:URN>urn:ddi:example.nso:q-work:1</r:URN><r:TypeOfObject>QuestionItem</r:TypeOfObject></r:QuestionReference>
<l:VariableRepresentation><r:CodeRepresentation><r:CodeListReference><r:URN>urn:ddi:example.nso:cl-yesno:1</r:URN>
<r:TypeOfObject>CodeList</r:TypeOfObject></r:CodeListReference></r:CodeRepresentation></l:VariableRepresentation>
</l:Variable></Fragment>"""
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
Path("survey-plus.xml").write_text(
text.replace("</FragmentInstance>", VARIABLE + "</FragmentInstance>"), encoding="utf-8"
)
lens = OxigraphLens() # a store in memory
result = lens.write(ir.parse("survey-plus.xml", dataset_id="m16-survey"), dataset_id="m16-survey")
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
TRACE = """
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?variable ?question ?codeList ?answer
WHERE {
?membership a ddigraph:Membership ; ddigraph:dataset "m16-survey" ; ddigraph:member ?v .
?v a ddigraph:Variable ; ddigraph:name ?variable ;
ddigraph:referencesQuestion/ddigraph:name ?question ;
ddigraph:usesCodelist ?list .
?list skos:prefLabel ?codeList ;
ddigraph:contains? ?code .
?code ddigraph:hasCategory/skos:prefLabel ?answer .
OPTIONAL { ?code ddigraph:value ?value }
}
ORDER BY ?variable ?question ?value
"""
trace = {}
for row in lens.store.query(TRACE):
entry = trace.setdefault(row["variable"].value, ([], row["codeList"].value, []))
questions, _code_list, answers = entry
for found, value in ((questions, row["question"].value), (answers, row["answer"].value)):
if value not in found:
found.append(value)
for variable, (questions, code_list, answers) in sorted(trace.items()):
print(f"{variable}: {', '.join(questions)} -> {code_list} -> {', '.join(answers)}")
Loaded: 88 nodes, 112 relationships
AGEGRP: AGE -> Age group -> 15-24, 25-34, 35-44, 45-54, 55-64, 65 and over
EDUC: EDUC -> Highest level of education -> Primary or less (ISCED 0-1), Lower secondary (ISCED 2), Upper secondary (ISCED 3), Post-secondary non-tertiary (ISCED 4), Tertiary (ISCED 5-8)
ILOSTAT: AVAIL, LOOK, WORK -> Labour force status (ILO) -> Employed, Unemployed, Not in the labour force
REGION: REGION -> Region -> Capital region, North, South, East, West
SEX: SEX -> Sex -> Male, Female
WORK: WORK -> Yes or no -> Yes, No
Each tab follows the same edges: REFERENCES_QUESTION to the
questions, then USES_CODELIST, CONTAINS zero or one time and
HAS_CATEGORY to the answers. Cypher writes the optional step as
[:CONTAINS*0..1], Gremlin as a union with identity(), SQL as an
OR, and SPARQL as the path ddigraph:contains?. A store keeps no
order of its own, so each tab sorts the answers by the value of their
code.
The trace answers the question users ask most about this survey: where
does ILOSTAT come from? From three questions, AVAIL, LOOK and
WORK, whose answers are Yes or No. The new variable WORK shares
their code list.
The ILOSTAT part of the same graph in three viewers: pick a tab. Each
circle is a node, coloured by its type, as the legend under the picture
says. Each arrow is a relationship, named by its type. Click a picture to
see it full size.
This picture uses Browser's hierarchical layout, which draws the trace from the top down. Pick it with the layout button at the bottom right of the result.
Gremlin Server has no viewer of its own. This picture is from the open-source gremlin-visualizer, which draws what this traversal returns, in colours of its own:
g.V().has('Dataset','dataset_id','m16-survey').in('IN_DATASET').has('Variable','name','ILOSTAT').union(identity(), out('REFERENCES_QUESTION'), out('USES_CODELIST'), out('REFERENCES_QUESTION').out('USES_CODELIST')).dedup().union(identity(), out('CONTAINS'), out('CONTAINS').out('HAS_CATEGORY')).dedup()
The viewer's physics is turned off here, and each node sits where it is in the NetworkX tab. You could do the same by dragging the nodes.
Exercise 6 (O4). Export survey-plus.xml as Turtle, and check the export
against the lifecycle SHACL shapes. Then query the graph with published
terms only, DISCO and SKOS, so that any linked-data tool could run the
query: each variable, its code list and its number of answers. End with the
code lists that have fewer than two answers.
Expected output:
Triples: 2150
Shapes: lifecycle (2150 triples)
Shapes result: conforms
Age group: Age group, 6 answers
Highest level of education: Highest level of education, 5 answers
Labour force status (ILO): Labour force status (ILO), 3 answers
Region of residence: Region, 5 answers
Sex of the person: Sex, 2 answers
Worked last week: Yes or no, 2 answers
Code lists with fewer than 2 answers: none
Answer
The export and its check, on the command line:
python - <<'PY'
from pathlib import Path
# The new variable WORK: the answer to the question WORK, coded with the Yes or no list
VARIABLE = """<Fragment><l:Variable isUniversallyUnique="true">
<r:URN>urn:ddi:example.nso:var-work:1</r:URN>
<r:Agency>example.nso</r:Agency><r:ID>var-work</r:ID><r:Version>1</r:Version>
<l:VariableName><r:String xml:lang="en">WORK</r:String></l:VariableName>
<r:Label><r:Content xml:lang="en">Worked last week</r:Content></r:Label>
<r:UniverseReference><r:URN>urn:ddi:example.nso:universe-persons15:1</r:URN><r:TypeOfObject>Universe</r:TypeOfObject></r:UniverseReference>
<r:ConceptReference><r:URN>urn:ddi:example.nso:concept-labour:1</r:URN><r:TypeOfObject>Concept</r:TypeOfObject></r:ConceptReference>
<r:QuestionReference><r:URN>urn:ddi:example.nso:q-work:1</r:URN><r:TypeOfObject>QuestionItem</r:TypeOfObject></r:QuestionReference>
<l:VariableRepresentation><r:CodeRepresentation><r:CodeListReference><r:URN>urn:ddi:example.nso:cl-yesno:1</r:URN>
<r:TypeOfObject>CodeList</r:TypeOfObject></r:CodeListReference></r:CodeRepresentation></l:VariableRepresentation>
</l:Variable></Fragment>"""
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
Path("survey-plus.xml").write_text(text.replace("</FragmentInstance>", VARIABLE + "</FragmentInstance>"), encoding="utf-8")
PY
ddigraph export survey-plus.xml --format turtle -o survey.ttl --dataset-id m16-survey 2> /dev/null | tail -n 1
ddigraph validate survey.ttl --flavor lifecycle 2> /dev/null | tail -n 2
Triples: 2150
Shapes: lifecycle (2150 triples)
Shapes result: conforms
The query on published terms, in Python with rdflib:
from pathlib import Path
from ddigraph import iter_graph
from ddigraph.rdf.writer import build_graph
# The new variable WORK: the answer to the question WORK, coded with the Yes or no list
VARIABLE = """<Fragment><l:Variable isUniversallyUnique="true">
<r:URN>urn:ddi:example.nso:var-work:1</r:URN>
<r:Agency>example.nso</r:Agency><r:ID>var-work</r:ID><r:Version>1</r:Version>
<l:VariableName><r:String xml:lang="en">WORK</r:String></l:VariableName>
<r:Label><r:Content xml:lang="en">Worked last week</r:Content></r:Label>
<r:UniverseReference><r:URN>urn:ddi:example.nso:universe-persons15:1</r:URN><r:TypeOfObject>Universe</r:TypeOfObject></r:UniverseReference>
<r:ConceptReference><r:URN>urn:ddi:example.nso:concept-labour:1</r:URN><r:TypeOfObject>Concept</r:TypeOfObject></r:ConceptReference>
<r:QuestionReference><r:URN>urn:ddi:example.nso:q-work:1</r:URN><r:TypeOfObject>QuestionItem</r:TypeOfObject></r:QuestionReference>
<l:VariableRepresentation><r:CodeRepresentation><r:CodeListReference><r:URN>urn:ddi:example.nso:cl-yesno:1</r:URN>
<r:TypeOfObject>CodeList</r:TypeOfObject></r:CodeListReference></r:CodeRepresentation></l:VariableRepresentation>
</l:Variable></Fragment>"""
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
Path("survey-plus.xml").write_text(
text.replace("</FragmentInstance>", VARIABLE + "</FragmentInstance>"), encoding="utf-8"
)
graph = build_graph(iter_graph("survey-plus.xml", dataset_id="m16-survey"))
query = """
PREFIX disco: <http://rdf-vocabulary.ddialliance.org/discovery#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?variable ?list (COUNT(?answer) AS ?answers) WHERE {
?v a disco:Variable ; rdfs:label ?variable ; disco:responseDomain ?scheme .
?scheme a skos:ConceptScheme ; skos:prefLabel ?list .
?concept skos:inScheme ?scheme ; skos:prefLabel ?answer .
}
GROUP BY ?variable ?list
ORDER BY ?variable
"""
short = []
for row in graph.query(query):
print(f"{row.variable}: {row.list}, {row.answers} answers")
if int(row.answers) < 2:
short.append(str(row.list))
print("Code lists with fewer than 2 answers:", ", ".join(short) or "none")
Age group: Age group, 6 answers
Highest level of education: Highest level of education, 5 answers
Labour force status (ILO): Labour force status (ILO), 3 answers
Region of residence: Region, 5 answers
Sex of the person: Sex, 2 answers
Worked last week: Yes or no, 2 answers
Code lists with fewer than 2 answers: none
SHACL checks that the graph has the shape ddigraph promises. The query
shows that a stranger's tool can read it: disco:responseDomain links
the variable to its code list, a skos:ConceptScheme, and each answer
is a skos:Concept in that scheme. The last line is the check of a
full code list, run on published terms: no code list has fewer than
two answers. A code list with one answer cannot tell people apart.
Track C: A CDI dataset¶
Brief. The classification team publishes how two of the survey's
classifications map to others. The six age groups of the survey map to the
four broad age groups that labour market tables use. The levels of ISCED
1997 map to those of ISCED 2011, the change that labour force surveys made
in 2014. The file, tests/fixtures/lfs_correspondence.xml, holds both
correspondences as DDI-CDI. You check it, list each pair that a
correspondence links, and publish the result as XKOS that passes SHACL.
Deliverables. Your plan; the checks; the pairs from your backend; the XKOS queries and the SHACL result; a three-line report.
Exercise 7 (O1, O2). Write the first rows of your plan. Then check the
file: its XSD and SHACL results, the size of its graph and its concept
maps, and a dry run with --resolve fail.
Expected output:
Result: valid
Shapes result: conforms
Nodes: 85 Relationships: 130
(CDICorrespondenceTable)-[:HAS_CONCEPT_MAP]->(CDIConceptMap) 9
(CDIConceptSystemCorrespondence)-[:HAS_CONCEPT_MAP]->(CDIConceptMap) 6
Ingestion complete: dataset_id=m16-cdi, nodes_written=85, relationships_written=130, stubs=0, references=130, resolved=130, unresolved=0, conflicts=0
Answer
| Step | Command | What it proves |
|---|---|---|
| Check | ddigraph validate --shapes |
It passes the XSD and the CDI shapes |
| Look | ddigraph preview |
The size of the graph, and how many concept maps each correspondence holds |
| Dry run | ddigraph load --dry-run --resolve fail |
All 130 references find their end |
ddigraph validate tests/fixtures/lfs_correspondence.xml --shapes > checks.txt 2> /dev/null || echo "Check failed: exit $?"
grep "Result\|result" checks.txt
ddigraph preview tests/fixtures/lfs_correspondence.xml 2> /dev/null | grep "^Nodes\|HAS_CONCEPT_MAP"
ddigraph load tests/fixtures/lfs_correspondence.xml --dataset-id m16-cdi --dry-run --resolve fail 2> /dev/null | tail -n 1
Result: valid
Shapes result: conforms
Nodes: 85 Relationships: 130
(CDICorrespondenceTable)-[:HAS_CONCEPT_MAP]->(CDIConceptMap) 9
(CDIConceptSystemCorrespondence)-[:HAS_CONCEPT_MAP]->(CDIConceptMap) 6
Ingestion complete: dataset_id=m16-cdi, nodes_written=85, relationships_written=130, stubs=0, references=130, resolved=130, unresolved=0, conflicts=0
The file passes both checks, and every reference resolves. The preview shows the two kinds of correspondence: a correspondence table with 9 concept maps, for ISCED, and a concept system correspondence with 6, for the age groups.
Exercise 8 (O3). Load the file into your backend as the dataset
m16-cdi. For each correspondence, print its label (or its ID when it has
none) and each pair that its concept maps link, from source to target.
Expected output:
Loaded: 85 nodes, 130 relationships
LFS age groups to broad age groups: 15-24 -> 15-24
LFS age groups to broad age groups: 25-34 -> 25-54
LFS age groups to broad age groups: 35-44 -> 25-54
LFS age groups to broad age groups: 45-54 -> 25-54
LFS age groups to broad age groups: 55-64 -> 55-64
LFS age groups to broad age groups: 65 and over -> 65 and over
isced1997-2011: 0 Pre-primary -> 0 Early childhood education
isced1997-2011: 1 Primary -> 1 Primary
isced1997-2011: 2 Lower secondary -> 2 Lower secondary
isced1997-2011: 3 Upper secondary -> 3 Upper secondary
isced1997-2011: 4 Post-secondary non-tertiary -> 4 Post-secondary non-tertiary
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 6 Bachelor's or equivalent
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 7 Master's or equivalent
isced1997-2011: 5B Tertiary, practical (first stage) -> 5 Short-cycle tertiary
isced1997-2011: 6 Advanced research (second stage of tertiary) -> 8 Doctoral or equivalent
Answer
Cypher, through the neo4j driver. The last lines purge the dataset, so the
example leaves your database as it found it. Leave them out to keep the data.
import os
from neo4j import GraphDatabase
import ddigraph
from ddigraph.lens.neo4j import Neo4jLens
result = ddigraph.load("tests/fixtures/lfs_correspondence.xml", dataset_id="m16-cdi", replace=True)
print("Loaded:", result.nodes_written, "nodes,", result.relationships_written, "relationships")
PAIRS = """
MATCH (c)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
WHERE c:CDICorrespondenceTable OR c:CDIConceptSystemCorrespondence
MATCH (c)-[:HAS_CONCEPT_MAP]->(map:CDIConceptMap)
MATCH (map)-[:HAS_SOURCE]->(source)
MATCH (map)-[:HAS_TARGET]->(target)
RETURN coalesce(c.label, c.ddi_id) AS correspondence, source.label AS source, target.label AS target
ORDER BY correspondence, source, target
"""
driver = GraphDatabase.driver(
os.environ["DDIGRAPH_NEO4J_URI"],
auth=(os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"]),
)
records, _, _ = driver.execute_query(PAIRS, dataset="m16-cdi")
for row in records:
print(f"{row['correspondence']}: {row['source']} -> {row['target']}")
Neo4jLens(driver).purge("m16-cdi") # clean up: remove the capstone's dataset
driver.close()
Loaded: 85 nodes, 130 relationships
LFS age groups to broad age groups: 15-24 -> 15-24
LFS age groups to broad age groups: 25-34 -> 25-54
LFS age groups to broad age groups: 35-44 -> 25-54
LFS age groups to broad age groups: 45-54 -> 25-54
LFS age groups to broad age groups: 55-64 -> 55-64
LFS age groups to broad age groups: 65 and over -> 65 and over
isced1997-2011: 0 Pre-primary -> 0 Early childhood education
isced1997-2011: 1 Primary -> 1 Primary
isced1997-2011: 2 Lower secondary -> 2 Lower secondary
isced1997-2011: 3 Upper secondary -> 3 Upper secondary
isced1997-2011: 4 Post-secondary non-tertiary -> 4 Post-secondary non-tertiary
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 6 Bachelor's or equivalent
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 7 Master's or equivalent
isced1997-2011: 5B Tertiary, practical (first stage) -> 5 Short-cycle tertiary
isced1997-2011: 6 Advanced research (second stage of tertiary) -> 8 Doctoral or equivalent
A Gremlin traversal. Gremlin stores the label property as ddi_label,
since some servers keep label for themselves. The last lines drop the
vertices that only this dataset holds.
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from ddigraph.backends.gremlin import write_gremlin
connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
result = write_gremlin(g, "tests/fixtures/lfs_correspondence.xml", dataset_id="m16-cdi")
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
rows = (
g.V()
.has("Dataset", "dataset_id", "m16-cdi")
.in_("IN_DATASET")
.hasLabel("CDICorrespondenceTable", "CDIConceptSystemCorrespondence")
.as_("c")
.out("HAS_CONCEPT_MAP")
.project("correspondence", "source", "target")
.by(__.select("c").coalesce(__.values("ddi_label"), __.values("ddi_id")))
.by(__.out("HAS_SOURCE").values("ddi_label"))
.by(__.out("HAS_TARGET").values("ddi_label"))
.to_list()
)
for row in sorted(rows, key=lambda row: (row["correspondence"], row["source"], row["target"])):
print(f"{row['correspondence']}: {row['source']} -> {row['target']}")
# Clean up: drop the vertices only this dataset holds, then its Dataset vertex
dataset = g.V().has("Dataset", "dataset_id", "m16-cdi")
dataset.in_("IN_DATASET").where(__.out("IN_DATASET").count().is_(1)).drop().iterate()
g.V().has("Dataset", "dataset_id", "m16-cdi").drop().iterate()
connection.close()
Loaded: 85 nodes, 130 relationships
LFS age groups to broad age groups: 15-24 -> 15-24
LFS age groups to broad age groups: 25-34 -> 25-54
LFS age groups to broad age groups: 35-44 -> 25-54
LFS age groups to broad age groups: 45-54 -> 25-54
LFS age groups to broad age groups: 55-64 -> 55-64
LFS age groups to broad age groups: 65 and over -> 65 and over
isced1997-2011: 0 Pre-primary -> 0 Early childhood education
isced1997-2011: 1 Primary -> 1 Primary
isced1997-2011: 2 Lower secondary -> 2 Lower secondary
isced1997-2011: 3 Upper secondary -> 3 Upper secondary
isced1997-2011: 4 Post-secondary non-tertiary -> 4 Post-secondary non-tertiary
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 6 Bachelor's or equivalent
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 7 Master's or equivalent
isced1997-2011: 5B Tertiary, practical (first stage) -> 5 Short-cycle tertiary
isced1997-2011: 6 Advanced research (second stage of tertiary) -> 8 Doctoral or equivalent
SQL over the SQL lens's tables, in a DuckDB database in memory.
import duckdb
from ddigraph import ir
from ddigraph.lens.sql import SQLLens
connection = duckdb.connect() # a database in memory
lens = SQLLens(connection)
result = lens.write(
ir.parse("tests/fixtures/lfs_correspondence.xml", dataset_id="m16-cdi"), dataset_id="m16-cdi"
)
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
PAIRS = """
SELECT coalesce(cl.string_value, ci.string_value) AS correspondence,
sl.string_value AS source, tl.string_value AS target
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
AND l.type_label IN ('CDICorrespondenceTable', 'CDIConceptSystemCorrespondence')
LEFT JOIN ddigraph_properties AS cl ON cl.key = m.key AND cl.name = 'label'
LEFT JOIN ddigraph_properties AS ci ON ci.key = m.key AND ci.name = 'ddi_id'
JOIN ddigraph_relationships AS hm ON hm.start_key = m.key AND hm.type = 'HAS_CONCEPT_MAP'
JOIN ddigraph_relationships AS hs ON hs.start_key = hm.end_key AND hs.type = 'HAS_SOURCE'
JOIN ddigraph_relationships AS ht ON ht.start_key = hm.end_key AND ht.type = 'HAS_TARGET'
JOIN ddigraph_properties AS sl ON sl.key = hs.end_key AND sl.name = 'label'
JOIN ddigraph_properties AS tl ON tl.key = ht.end_key AND tl.name = 'label'
WHERE m.dataset = ?
ORDER BY correspondence, source, target
"""
for correspondence, source, target in connection.execute(PAIRS, ["m16-cdi"]).fetchall():
print(f"{correspondence}: {source} -> {target}")
Loaded: 85 nodes, 130 relationships
LFS age groups to broad age groups: 15-24 -> 15-24
LFS age groups to broad age groups: 25-34 -> 25-54
LFS age groups to broad age groups: 35-44 -> 25-54
LFS age groups to broad age groups: 45-54 -> 25-54
LFS age groups to broad age groups: 55-64 -> 55-64
LFS age groups to broad age groups: 65 and over -> 65 and over
isced1997-2011: 0 Pre-primary -> 0 Early childhood education
isced1997-2011: 1 Primary -> 1 Primary
isced1997-2011: 2 Lower secondary -> 2 Lower secondary
isced1997-2011: 3 Upper secondary -> 3 Upper secondary
isced1997-2011: 4 Post-secondary non-tertiary -> 4 Post-secondary non-tertiary
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 6 Bachelor's or equivalent
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 7 Master's or equivalent
isced1997-2011: 5B Tertiary, practical (first stage) -> 5 Short-cycle tertiary
isced1997-2011: 6 Advanced research (second stage of tertiary) -> 8 Doctoral or equivalent
SPARQL over the RDF lens's graph, in an Oxigraph store in memory.
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
lens = OxigraphLens() # a store in memory
result = lens.write(
ir.parse("tests/fixtures/lfs_correspondence.xml", dataset_id="m16-cdi"), dataset_id="m16-cdi"
)
print("Loaded:", result.nodes, "nodes,", result.relationships, "relationships")
PAIRS = """
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?correspondence ?source ?target
WHERE {
?membership a ddigraph:Membership ; ddigraph:dataset "m16-cdi" ; ddigraph:member ?c .
{ ?c a ddigraph:CDICorrespondenceTable } UNION { ?c a ddigraph:CDIConceptSystemCorrespondence }
?c ddigraph:ddiId ?id ; ddigraph:hasConceptMap ?map .
OPTIONAL { ?c rdfs:label ?label }
?map ddigraph:hasSource/skos:prefLabel ?source ; ddigraph:hasTarget/skos:prefLabel ?target .
BIND(STR(COALESCE(?label, ?id)) AS ?correspondence)
}
ORDER BY ?correspondence ?source ?target
"""
for row in lens.store.query(PAIRS):
print(f"{row['correspondence'].value}: {row['source'].value} -> {row['target'].value}")
Loaded: 85 nodes, 130 relationships
LFS age groups to broad age groups: 15-24 -> 15-24
LFS age groups to broad age groups: 25-34 -> 25-54
LFS age groups to broad age groups: 35-44 -> 25-54
LFS age groups to broad age groups: 45-54 -> 25-54
LFS age groups to broad age groups: 55-64 -> 55-64
LFS age groups to broad age groups: 65 and over -> 65 and over
isced1997-2011: 0 Pre-primary -> 0 Early childhood education
isced1997-2011: 1 Primary -> 1 Primary
isced1997-2011: 2 Lower secondary -> 2 Lower secondary
isced1997-2011: 3 Upper secondary -> 3 Upper secondary
isced1997-2011: 4 Post-secondary non-tertiary -> 4 Post-secondary non-tertiary
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 6 Bachelor's or equivalent
isced1997-2011: 5A Tertiary, theory-based (first stage) -> 7 Master's or equivalent
isced1997-2011: 5B Tertiary, practical (first stage) -> 5 Short-cycle tertiary
isced1997-2011: 6 Advanced research (second stage of tertiary) -> 8 Doctoral or equivalent
DDI-CDI has two kinds of correspondence, a correspondence table and a
concept system correspondence. Both hold concept maps by
HAS_CONCEPT_MAP, so one query covers both. The age maps link
concepts, and the ISCED maps link the categories that the levels
denote, so the query does not name the type of the ends. The
correspondence table has no label, so the query falls back to its ID.
The pairs show the two shapes a change can take. Three age groups
merge into 25-54, and level 5A splits into Bachelor's and
Master's. A user who compares ISCED 1997 data with ISCED 2011 data
must know about the split: one old level cannot be put back into one
new one.
Exercise 9 (O4, O5). Export the file as Turtle and check it against the CDI SHACL shapes. Then use XKOS and SKOS terms only to count the correspondences and their concept pairs, and to find any concept map that lacks a source or a target. Write the three lines of your report from the results.
Expected output:
Triples: 2215
Shapes: cdi (2215 triples)
Shapes result: conforms
Correspondences: 2, concept pairs: 15
Concept maps missing an end: 0
Answer
The export and its check:
ddigraph export tests/fixtures/lfs_correspondence.xml --format turtle -o cdi.ttl --dataset-id m16-cdi 2> /dev/null | tail -n 1
ddigraph validate cdi.ttl --flavor cdi 2> /dev/null | tail -n 2
Triples: 2215
Shapes: cdi (2215 triples)
Shapes result: conforms
The XKOS queries:
from ddigraph import iter_graph
from ddigraph.rdf.writer import build_graph
graph = build_graph(iter_graph("tests/fixtures/lfs_correspondence.xml", dataset_id="m16-cdi"))
# XKOS and SKOS terms only: any tool that reads XKOS can run these
PAIRS = """
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX xkos: <http://rdf-vocabulary.ddialliance.org/xkos#>
SELECT (COUNT(DISTINCT ?correspondence) AS ?correspondences) (COUNT(?map) AS ?pairs) WHERE {
?correspondence a xkos:Correspondence ; xkos:madeOf ?map .
?map xkos:sourceConcept/skos:prefLabel ?source ; xkos:targetConcept/skos:prefLabel ?target .
}
"""
INCOMPLETE = """
PREFIX xkos: <http://rdf-vocabulary.ddialliance.org/xkos#>
SELECT (COUNT(?map) AS ?missing) WHERE {
?map a xkos:ConceptAssociation .
FILTER NOT EXISTS { ?map xkos:sourceConcept ?source ; xkos:targetConcept ?target }
}
"""
for row in graph.query(PAIRS):
print(f"Correspondences: {row.correspondences}, concept pairs: {row.pairs}")
for row in graph.query(INCOMPLETE):
print(f"Concept maps missing an end: {row.missing}")
Correspondences: 2, concept pairs: 15
Concept maps missing an end: 0
A report from these results:
- The file passes the XSD and the CDI shapes, and all 130 references resolve.
- The XKOS export passes the CDI shapes, and holds 2 correspondences with 15 concept pairs.
- No concept map lacks a source or a target, so each old age group
and each ISCED 1997 level can be traced to its new group or level.
Level
5Amaps to two levels, which users must know.
Present your project¶
(O5) Finish with a five-minute presentation to your group, or a one-page note if you work alone. Keep to this order:
- The file and its readers (30 seconds): what the file holds, and who will use the graph.
- The plan (1 minute): your table of steps.
- The proof (1 minute): run your check and your explore step live, on your backend.
- Two design choices (2 minutes): for each, what you chose, the option you rejected, and why.
- One thing you would change next time (30 seconds).
Choices worth defending:
- Recover or strict parsing for this file (Module 13).
- Which backend, and why it suits the people who will query the graph.
- Whether an XSD failure stops the load, or goes in the report.
--resolve exactorfail, and what each does to a reference with no end.- Which checks the report runs, and which it leaves to a person.
Rubric¶
Score your own work, or a partner's. The maximum is 100 points.
| Criteria | Objective | Modules | Points |
|---|---|---|---|
| A plan, written before the code, with each step, its command and what it proves | O1 | 3, 12 | 15 |
| The checks run in the right order, before any load, and each result is explained | O2 | 3, 6, 13 | 20 |
| The graph is loaded under the track's own dataset ID, and the explore step gives the expected rows | O3 | 5, 7, 10 | 20 |
| Tracks B and C: the export passes SHACL, and a query on published terms reads it. Track A: the report reads the graph itself, not only the counts | O4 | 6, 8, 9 | 15 |
| A quality report that states facts a reader can act on | O5 | 6, 11 | 15 |
| A five-minute presentation that defends two design choices against the options rejected | O5 | All | 15 |
Scoring guide:
- 90–100: You can take a DDI file from a first look to a trusted graph on your backend, and explain each step.
- 70–89: Good. Review the modules beside the rows where you lost points.
- 50–69: Redo the exercises of the modules beside your weakest rows, then try the track again.
- Below 50: Start again with Track A, one step at a time.
Quiz¶
Question 1 (O1): Why does the plan put the checks before the load?
A. Because a load cannot run on a file that fails the XSD.
B. Because a check costs nothing to undo, and a load with --replace purges the dataset first.
C. Because the checks are faster.
D. Because ddigraph refuses to load a file that was never previewed.
Answer
B. A dry run and a validation change nothing. A load writes, and
with --replace it purges the old dataset first. A is the tempting
one, but it is false: ddigraph load checks the XSD only when you
pass --validate, as Module 6 explains.
That is why the report must say whether the file is valid.
Question 2 (O2): A partner's file fails the XSD, yet ddigraph loads it. What should the report do?
A. Leave the XSD out: the load worked.
B. Refuse the file: an invalid file has no graph.
C. State the XSD result and its first issue, next to what the graph holds, so the reader can judge both.
D. Fix the file in the graph.
Answer
C. Validity and content are separate facts, and a reader needs both. A hides a real problem. B throws away a usable graph: a file can fail the XSD because of its style, such as IDs written as attributes, while no data is missing.
Question 3 (O3): Your Gremlin traversal prints no labels, while the Neo4j query does. What is the likely cause?
A. The Gremlin load failed.
B. Gremlin stores the label property as ddi_label, so values("label") finds nothing.
C. Gremlin has no labels at all.
D. The dataset ID is wrong.
Answer
B. Some Gremlin servers keep label for the vertex's own label,
so ddigraph writes the DDI label as ddi_label. A and D would give
no rows at all, not rows with empty labels.
Question 4 (O4): Why query the export with DISCO, SKOS and XKOS terms, and not only ddigraph's own?
A. Because ddigraph's terms are not in the export.
B. Because tools that know nothing of ddigraph read the published terms, so the query proves that others can use your data.
C. Because SHACL needs them.
D. Because SPARQL refuses other prefixes.
Answer
B. The export carries both: the published class or property for
any tool, and ddigraph's own so that ddigraph can read it back. A is
false: the ddigraph: terms are there too. A query on the published
terms is what a partner would write.
Question 5 (O5): A colleague says your report should simply say \"the file is fine\". What is wrong with that?
A. Nothing: a short report is a good report.
B. It gives the reader nothing to check or act on: no counts, no failing checks, no list of what is missing.
C. It is too informal for a catalogue.
D. Reports must be in Markdown.
Answer
B. A good report states facts with their source: the XSD result, the counts, the conflicts, and the items that lack something. Then the reader can trust it, or check it. C is about tone; the real problem is that there is nothing to verify.
Check yourself¶
- I can plan a ddigraph pipeline for a file, with each step, what it proves and what I will hand in. (O1)
- I can check a file before I load it, with a preview, an XSD validation and a dry run, and explain each result. (O2)
- I can load the graph into my backend and follow the paths my track needs. (O3)
- I can export the graph as linked data and check it with SHACL and with a query on published terms. (O4)
- I can write a short quality report, and defend two design choices against the options I rejected. (O5)


