Skip to content

Answer keys

Every exercise answer and quiz answer in the curriculum, on one page, for instructors. Learners working through a module can open the answer under each exercise and question instead.

This page is built from the modules by scripts/generate_answer_keys.py, and a test checks that it matches them. The code here is the same as in the modules, where the tests run it and check its output.

Module 1: What DDI metadata is, and why a graph

Exercises

Exercise 1 (O2, O5).

from pathlib import Path

import ddigraph

for name in ("lfs_correspondence.xml", "reusable_fragments.xml", "cdi_valid_minimal.xml"):
    path = Path("tests/fixtures") / name
    print(name, ddigraph.detect(path))
lfs_correspondence.xml cdi
reusable_fragments.xml codebook
cdi_valid_minimal.xml cdi

lfs_correspondence.xml holds no questions at all. It maps the survey's age groups and education levels to other groupings. Its root is a CDI <Wrapper>, so it is CDI. The other two are small test files, each made odd on purpose. reusable_fragments.xml sounds like a Lifecycle file, but its root element is <codeBook>. cdi_valid_minimal.xml holds nothing but its root, <DDICDIModels>. That is not <Wrapper>, but it is in the CDI namespace, and that is enough. detect reads the root element, never the name.

Exercise 2 (O4).

grep -n -A 4 "<d:Instrument " tests/fixtures/lfs_lifecycle.xml
9:    <d:Instrument isUniversallyUnique="true">
10-      <r:URN>urn:ddi:example.nso:lfs-instrument:1</r:URN><r:Agency>example.nso</r:Agency><r:ID>lfs-instrument</r:ID><r:Version>1</r:Version>
11-      <d:InstrumentName><r:String xml:lang="en">LFS questionnaire</r:String></d:InstrumentName>
12-      <r:Label><r:Content xml:lang="en">Labour Force Survey questionnaire, 2025</r:Content></r:Label>
13-      <d:ControlConstructReference><r:Agency>example.nso</r:Agency><r:ID>lfs-main</r:ID><r:Version>1</r:Version><r:TypeOfObject>Sequence</r:TypeOfObject></d:ControlConstructReference>

The reference on line 13 sits inside the Instrument, so the answer is urn:ddi:example.nso:lfs-main:1, a Sequence: the main sequence. It holds six more references. The first five lead to the questions SEX, AGE, REGION, EDUC and WORK. The sixth leads to a choice, "Worked last week?". A person who worked is asked HOURS, and anyone else the job search questions, LOOK and AVAIL. Following one reference after another is walking a path in the graph.

Exercise 3 (O3).

grep -n -e 'fileDscr ID' -e 'varQnty' -e '<var ID' -e 'fileid' tests/fixtures/lfs_codebook.xml
34:  <fileDscr ID="F1">
38:      <dimensns><varQnty>7</varQnty></dimensns>
43:    <var ID="V1" name="SEX" intrvl="discrete">
44:      <location fileid="F1"/>
52:    <var ID="V2" name="AGE" intrvl="contin">
53:      <location fileid="F1"/>
60:    <var ID="V3" name="AGEGRP" intrvl="discrete">
61:      <location fileid="F1"/>
73:    <var ID="V4" name="REGION" intrvl="discrete">
74:      <location fileid="F1"/>
85:    <var ID="V5" name="EDUC" intrvl="discrete">
86:      <location fileid="F1"/>
97:    <var ID="V6" name="ILOSTAT" intrvl="discrete">
98:      <location fileid="F1"/>
107:    <var ID="V7" name="HOURS" intrvl="contin">
108:      <location fileid="F1"/>

Seven edges, from (V1)-[:IN_FILE]->(F1) to (V7)-[:IN_FILE]->(F1). The data file's own description agrees: <varQnty>7</varQnty> says it holds seven variables. In a table you would keep a file column and join on it. In a graph the link is an edge you can follow, in either direction.

Quiz

Question 1 (O1): A data file has a column EDUC that holds the values 1 to 5. What do you need before you can use it?

B. The numbers mean nothing until the metadata says what was asked and what each code stands for. The data type (D) tells you the values are whole numbers, not what they mean.

Question 2 (O2): A file's root element is <FragmentInstance>. Which flavor is it?

C. <FragmentInstance> is the root of a DDI-L file. You do not need to load it: the root element is enough, which is all ddigraph detect reads.

Question 3 (O3): Why does a question such as 'which variables trace back to this code list?' suit a graph better than tables?

B. The path's length depends on how deeply things nest, so a fixed chain of joins does not fit. A pattern such as [*1..5] follows as many edges as it takes. A is tempting, but speed is not the point: the question becomes easy to write.

Question 4 (O4): A reference holds Agency example.nso, ID cl-sex and Version 1. Which URN does it name?

C. A DDI URN is urn:ddi: then the agency, the ID and the version, in that order. D drops the version, but two versions of one object are two different objects.

Question 5 (O5): You rename lfs_lifecycle.xml to codebook.xml, then run ddigraph detect codebook.xml. What does it print?

B. detect reads the root element, <FragmentInstance>, and ignores the file's name. Renaming a file does not change what is inside it.

Question 6 (O2, O3): Which flavor writes its links as explicit reference elements, each with an agency, an ID and a version?

B. A DDI-L reference, such as <r:CodeListReference>, names its target by agency, ID and version. Codebook links things with IDs that are unique only inside the file, and CDI uses its own identifiers and association elements.

Module 2: Set up your environment

Exercises

Exercise 1 (O1, O3).

import sys

import ddigraph

print(sys.version_info >= (3, 12))
print(ddigraph.__version__)
True
0.6.0

sys.version_info compares as a tuple, so (3, 14, 0) >= (3, 12) is True. A version number at all shows that this Python can import ddigraph.

Exercise 2 (O2, O3).

cd tests
ddigraph detect tests/fixtures/lfs_codebook.xml 2>&1 || echo "exit code $?"
cd ..
ddigraph detect tests/fixtures/lfs_codebook.xml
usage: ddigraph detect [-h] [--json] xml_path
ddigraph detect: error: argument xml_path: DDI XML path must reference a readable file: tests/fixtures/lfs_codebook.xml
exit code 2
Format: codebook
File: .../tests/fixtures/lfs_codebook.xml

A relative path starts from the current folder. From inside tests, tests/fixtures/... points at tests/tests/fixtures/..., which does not exist. Going back to the root fixes it.

Exercise 3 (O4, O5).

For Docker, start the server and set the variables (Bash shown):

docker run -d --name neo4j -p 7474:7474 -p 7687:7687 -e NEO4J_AUTH=neo4j/password neo4j:5
export DDIGRAPH_NEO4J_URI=bolt://localhost:7687
export DDIGRAPH_NEO4J_USER=neo4j
export DDIGRAPH_NEO4J_PASSWORD=password

Wait a few seconds for Neo4j to start, then run:

from neo4j import GraphDatabase

from ddigraph.config import Settings

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    driver.verify_connectivity()
print("Connected as", settings.neo4j_user)
Connected as neo4j

Settings() reads the same variables, and the same .env file, as every ddigraph command. So if this connects, ddigraph load will too. With Aura, the user name is the one in its file.

Quiz

Question 1 (O1): Module 6 checks graphs with SHACL. Which command installs what it needs?

B. An extra goes in square brackets after the package name, and the quotes stop the shell from reading the brackets. C installs an unrelated package called shacl. A gives the base package, which has no SHACL validator.

Question 2 (O2): You run ddigraph detect tests/fixtures/lfs_codebook.xml from your home folder and get 'must reference a readable file'. What is wrong?

C. A relative path starts from the current folder. Run cd to the repository root first. A is tempting, but then the shell would say command not found, before ddigraph could check the file.

Question 3 (O3): ddigraph version prints command not found, yet you installed ddigraph an hour ago. What is the most likely cause?

B. A new terminal starts outside the virtual environment, so it cannot find the ddigraph command. Run the activate line again, or use uv run ddigraph version. ddigraph needs no server to print its version (C).

Question 4 (O4): The shell has DDIGRAPH_NEO4J_URI=bolt://localhost:7687, and the .env file has DDIGRAPH_NEO4J_URI=neo4j+s://abc.databases.neo4j.io. Which server does ddigraph load use?

A. An environment variable beats the .env file. To use Aura, unset the variable in that terminal, or close it and open a new one.

Question 5 (O5): Neo4j runs in Docker with -p 7474:7474 -p 7687:7687. Which address do you open in a web browser to type Cypher?

C. Port 7474 serves Neo4j Browser over HTTP. Port 7687 speaks Bolt, the protocol that ddigraph and the driver use, so A is the value of DDIGRAPH_NEO4J_URI, not a web page. Port 5432 is PostgreSQL.

Module 3: Look before you load

Exercises

Exercise 1 (O1, O2).

ddigraph preview tests/fixtures/lfs_cdi.xml
Preview: .../tests/fixtures/lfs_cdi.xml
Nodes: 91   Relationships: 92

Node types
  CDICategory          21
  CDICode              21
  CDIGenericEntity     21
  CDIInstanceVariable  7
  CDIValueDomain       7
  CDICodeList          5
  CDIConcept           5
  CDIAgent             1
  CDIConceptSystem     1
  CDIUnitType          1
  Dataset              1

Relationships
  (CDICode)-[:DENOTES]->(CDICategory)  21
  (CDICode)-[:USES]->(CDIGenericEntity)  21
  (CDICodeList)-[:HAS_CODE]->(CDICode)  21
  (CDIInstanceVariable)-[:MEASURES]->(CDIUnitType)  7
  (CDIInstanceVariable)-[:TAKES_SUBSTANTIVE_VALUES_FROM]->(CDIValueDomain)  7
  (CDICodeList)-[:IS_DEFINED_BY]->(CDIConcept)  5
  (CDIConceptSystem)-[:HAS_CONCEPT]->(CDIConcept)  5
  (CDIValueDomain)-[:TAKES_VALUES_FROM]->(CDICodeList)  5

Ninety-one nodes and 92 edges. Every type but Dataset starts with CDI. Names such as Category and CodeList exist in all three flavors, with different properties. The prefix keeps the CDI ones apart when files of several flavors share one database. Dataset is the one type every flavor shares.

Exercise 2 (O3).

ddigraph preview tests/fixtures/lfs_lifecycle.xml --limit 1 --dataset-id labour | grep "urn:"
echo ---
ddigraph preview tests/fixtures/lfs_codebook.xml --limit 1 --dataset-id labour | grep "urn:"
  urn:ddi:example.nso:cat-sex-1:1
  urn:ddi:example.nso:code-sex-1:1
  urn:ddi:example.nso:cl-sex:1
  urn:ddi:example.nso:concept-demography:1
  urn:ddigraph:scoped:labour:%3Adataset
  urn:ddi:example.nso:if-worked:1
  urn:ddi:example.nso:lfs-instrument:1
  urn:ddi:example.nso:qc-sex:1
  urn:ddi:example.nso:q-sex:1
  urn:ddi:example.nso:lfs-main:1
  urn:ddi:example.nso:universe-persons15:1
  urn:ddi:example.nso:var-sex:1
---
  urn:ddigraph:derived:cfd6b2969cc9f54d953e837240eeec3d:category:c04b7030b05ced156755d5f7e375b022:0
  urn:ddigraph:derived:0aa2a9376f4048929fe16e931eaa2f04:citation:9949242b7f8e236a740cdd4b36ae63b9:0
  urn:ddigraph:derived:cfd6b2969cc9f54d953e837240eeec3d:concept:1972aebb3b80351bec83fc6df89fbb8a:0
  urn:ddigraph:derived:f000f1dbd579a3510e520b5dd8d6bbcb:contributor:a1258669715688a503cf56c4274deeda:0
  urn:ddigraph:derived:ac5d626b8d530c78737d23e437d01867:coverage:b007c5636b03dee51f45ac605a92494b:0
  urn:ddigraph:derived:510c526a246f6f31ecdc069865e430ba:generic_identifiable:8a4ce13234bd7a06b8ea56c369c7d090:0
  urn:ddigraph:derived:ac5d626b8d530c78737d23e437d01867:data_collection_event:48d30e45f186bb9d98c5dce67e73a195:0
  urn:ddigraph:scoped:labour:F1
  urn:ddigraph:scoped:labour:%3Adataset
  urn:ddigraph:derived:6851a35bb4a06b58440f4f458741fc01:document_description:963cb4fdd0eca98bfc997d4dd858ca62:0
  urn:ddigraph:derived:510c526a246f6f31ecdc069865e430ba:organization:02eb7cc011d19a938711c5fd105ec8c5:0
  urn:ddigraph:scoped:labour:Q-SEX
  urn:ddigraph:derived:6851a35bb4a06b58440f4f458741fc01:study:b895ca2be27fdbf6f1c5180e3dbccb81:0
  urn:ddigraph:scoped:labour:UNIV-PERSONS15
  urn:ddigraph:scoped:labour:V1

The DDI-L nodes keep their DDI URNs, which are the same in every dataset. Only their Dataset node takes the new ID. The Codebook file has no DDI URNs. An element with an ID, such as the variable V1 or the data file F1, gets a scoped identity, which takes labour. An element with no ID, such as a category, gets a derived identity, built from the key of the node that holds it. That key takes the dataset ID too, so every identity in the Codebook file changes.

Exercise 3 (O4).

ddigraph preview tests/fixtures/lfs_correspondence.xml --format mermaid -o correspondence.mmd
head -n 3 correspondence.mmd
Wrote correspondence.mmd
graph LR
    CDIGenericEntity["CDIGenericEntity<br/>19"]
    CDICategory["CDICategory<br/>17"]

-o sends any format to a file. The boxes come largest first, as in the text preview: this file has 19 generic entities. Seventeen hold the code of an education level, such as 5A in ISCED 1997 or 6 in ISCED 2011. The other two are the two sets of levels themselves.

Exercise 4 (O1, O4).

import ddigraph

print(ddigraph.preview("tests/fixtures/lfs_cdi.xml", format="mermaid"))
graph LR
    CDICategory["CDICategory<br/>21"]
    CDICode["CDICode<br/>21"]
    CDIGenericEntity["CDIGenericEntity<br/>21"]
    CDIInstanceVariable["CDIInstanceVariable<br/>7"]
    CDIValueDomain["CDIValueDomain<br/>7"]
    CDICodeList["CDICodeList<br/>5"]
    CDIConcept["CDIConcept<br/>5"]
    CDIAgent["CDIAgent<br/>1"]
    CDIConceptSystem["CDIConceptSystem<br/>1"]
    CDIUnitType["CDIUnitType<br/>1"]
    Dataset["Dataset<br/>1"]
    CDICode -->|DENOTES 21| CDICategory
    CDICode -->|USES 21| CDIGenericEntity
    CDICodeList -->|HAS_CODE 21| CDICode
    CDIInstanceVariable -->|MEASURES 7| CDIUnitType
    CDIInstanceVariable -->|TAKES_SUBSTANTIVE_VALUES_FROM 7| CDIValueDomain
    CDICodeList -->|IS_DEFINED_BY 5| CDIConcept
    CDIConceptSystem -->|HAS_CONCEPT 5| CDIConcept
    CDIValueDomain -->|TAKES_VALUES_FROM 5| CDICodeList

ddigraph.preview() takes the same format and limit as the command, and returns the text instead of printing it, so a script can save it or put it in a report.

Quiz

Question 1 (O1): Why does ddigraph preview count nodes by type instead of drawing every node?

B. Grouping by type keeps the answer on one screen, whatever the file's size. C is wrong: --limit prints identities, so the preview reads them. And the preview reads the whole file either way (D).

Question 2 (O2): A preview shows (Instrument)-[:HAS_CONSTRUCT]->(Sequence) and (QuestionItem)-[:USES_CODELIST]->(CodeList). Which flavor is the file?

B. An instrument whose constructs lead to questions and code lists is the questionnaire flow of a DDI-L file. A CDI file's type names would start with CDI, and in a Codebook file the edges start at variables.

Question 3 (O1): You load a file, and Neo4j holds an IN_DATASET edge for every node. The preview of the same file counts none. Why?

B. The edge belongs to the load. C is tempting, but the preview does show edges into the Dataset node, such as (Study)-[:DESCRIBES]->(Dataset).

Question 4 (O3): ddigraph preview tests/fixtures/lfs_codebook.xml --limit 2 prints urn:ddigraph:scoped:lfs_codebook:V1. What is lfs_codebook?

B. A Codebook ID such as V1 is unique only inside its file, so its identity is scoped to a dataset. --dataset-id sets another one. An agency (A) belongs to a DDI URN, which starts with urn:ddi:.

Question 5 (O4): You want to email a preview to a manager who works offline and has no ddigraph. Which command fits best?

C. The HTML page is one file that opens in any browser, with no internet and no JavaScript. Mermaid (B) needs a viewer that can draw it, such as GitHub.

Module 4: Nodes, edges and identity

Exercises

Exercise 1 (O1, O2).

import collections

from ddigraph import iter_graph

nodes = collections.Counter()
edges = collections.Counter()
for chunk in iter_graph("tests/fixtures/lfs_codebook.xml"):
    nodes.update(node.label for node in chunk.nodes)
    edges.update(edge.type for edge in chunk.relationships)

print(sum(nodes.values()), "nodes,", sum(edges.values()), "relationships")
for label, count in nodes.most_common(5):
    print(f"  {label:24} {count}")
80 nodes, 48 relationships
  DDIGenericIdentifiable   26
  Category                 21
  Variable                 7
  Concept                  7
  Question                 5

These are the counts ddigraph preview gave in Module 3. The previewer counts the same stream; your code has the same access it does. Types with equal counts come in the order the file first meets them: here the variable SEX comes before its concept.

Exercise 2 (O3).

import collections

from ddigraph import ir, urn

kinds = collections.Counter()
consistent = True
for chunk in ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="lfs_2025q3"):
    for node in chunk.nodes:
        kinds[type(node.identity).__name__] += 1
        text = urn.text(node.identity)
        consistent = consistent and urn.key(node.identity) == node.key
        consistent = consistent and urn.parse(text) == node.identity
print(sorted(kinds.items()))
print(consistent)
[('Derived', 65), ('Scoped', 15)]
True

A Codebook file has no DDI URNs: an element with an ID is scoped to the dataset, and one without is derived from its parent. Fourteen nodes come from an element with an ID: the 7 variables, the 5 questions, the data file F1 and the study's universe. The fifteenth scoped identity is the Dataset node. The 65 others, such as the 21 categories, come from elements with no ID. The key is always the hash of the text form, and the text form always reads back.

Exercise 3 (O4).

from ddigraph import iter_graph, urn

names = {}
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        names[node.key] = urn.text(node.identity)
    for edge in chunk.relationships:
        if edge.type == "CONTAINS" and names[edge.start] == "urn:ddi:example.nso:cl-ilo:1":
            print(edge.ordinal, names[edge.start], "->", names[edge.end], edge.resolution)
0 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-1:1 None
1 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-2:1 None
2 urn:ddi:example.nso:cl-ilo:1 -> urn:ddi:example.nso:code-ilo-3:1 None

The ordinal keeps the list's order, 0 to 2: employed, unemployed, not in the labour force. It holds whatever order the edges arrive in. The resolution is None, because the codes are written inside the code list: no reference had to find them. Each code's edge to its category comes from a reference, and is exact. The dictionary is filled from each chunk's nodes before its edges are read, so every end is already in it.

Exercise 4 (O4, O5).

from ddigraph import iter_graph, urn

names = {}
for chunk in iter_graph("tests/fixtures/ir_cdi_valid.xml", resolve="latest-declared"):
    for node in chunk.nodes:
        names[node.key] = urn.text(node.identity)
        if node.unresolved is not None:
            print("stub", names[node.key], node.unresolved)
    for edge in chunk.relationships:
        if edge.type == "DENOTES":
            print(names[edge.start], "->", names[edge.end], edge.resolution)
stub urn:ddi:example.org:code-3:1 not_in_file
urn:ddi:example.org:code-1:1 -> urn:ddi:example.org:cat-employed:1 exact
urn:ddi:example.org:code-2:1 -> urn:ddi:example.org:cat-unemployed:1.10 latest-declared

The stub for cat-unemployed:2.0 is gone. With latest-declared, a reference to a version the file lacks takes the highest version of the same agency and ID that the file has, here 1.10, and the edge says so in its resolution. code-3 is not in the file at any version, so it stays a stub.

Quiz

Question 1 (O2): Which field of a node tells you the file and line it came from?

C. provenance holds the source file, the flavor and the line. The identity (A) says which object the node is, not where it was read.

Question 2 (O3): Two Codebook files, for two quarters of the Labour Force Survey, both have a variable with the ID V1. You read them as the datasets lfs_2025q2 and lfs_2025q3. How many V1 nodes do you get?

B. Their identities are urn:ddigraph:scoped:lfs_2025q2:V1 and urn:ddigraph:scoped:lfs_2025q3:V1, so their keys differ. Codebook files often reuse IDs such as V1, for the same variable or for a different one, and nothing in the file says which. A would be right for a DDI URN, which is the same in every dataset.

Question 3 (O3): A colleague keys nodes on ddi_id alone, to save time. What goes wrong?

C. Part of an identity is not unique: versions, agencies and datasets can share an ID. The merge is silent, which is why it is dangerous. node.key comes from the whole identity.

Question 4 (O4): Your code reads a chunk's edges first, then its nodes. What can happen?

B. The stream promises that an edge comes after both of its ends, in its own chunk or an earlier one. If you read the edges first, the ends in the same chunk are not in your dictionary yet. Handle the nodes first.

Question 5 (O5): A question references a code list that lives in another file. What does ddigraph do?

C. The stub keeps the link and the identity the reference gave. A is tempting, but dropping the edge would lose the fact that the question uses a code list at all.

Question 6 (O1): Why can iter_graph read a 65 MB file without holding the whole graph in memory?

B. The stream is a generator of chunks. Your code keeps only what it needs, such as a label for each key. A is wrong: ddigraph reads the whole file, because an edge can point at an object later in the file.

Module 5: Ask the graph questions in memory

Exercises

Exercise 1 (O1, O2).

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, edge, node, prop, run

lens = MemoryLens()
lens.write(ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="survey"), dataset_id="survey")

query = Query(
    match=[node("q", "QuestionItem"), node("l", "CodeList"), edge("q", "USES_CODELIST", "l")],
    returns=[prop("q", "name"), prop("q", "question_text"), prop("l", "label")],
    order_by=[asc(prop("q", "name"))],
)
for name, text, code_list in run(query, lens):
    print(name, "|", text.value, "|", code_list.value)
Text(value='AVAIL', lang='en') | If you found a job, could you start within the next two weeks? | Yes or no
Text(value='EDUC', lang='en') | What is the highest level of education you have completed? | Highest level of education
Text(value='LOOK', lang='en') | In the last four weeks, did you look for work? | Yes or no
Text(value='REGION', lang='en') | In which region do you live? | Region
Text(value='SEX', lang='en') | What is your sex? | Sex
Text(value='WORK', lang='en') | Last week, did you do any work for pay or profit, even for one hour? | Yes or no

name is a plain string, so it prints as it is. question_text and label are texts, so the code prints their .value. AGE and HOURS are missing: their answer is a number, not a code. Three questions share the list "Yes or no". DDI-L defines it once, and each question points at it.

Exercise 2 (O3).

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, asc, compare, evaluate, missing, node, not_, prop

lens = MemoryLens()
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
)

not_sex = Query(
    match=[node("v", "Variable")],
    where=not_(compare(prop("v", "question_text"), "==", "What is your sex?")),
    returns=[prop("v", "name")],
    order_by=[asc(prop("v", "name"))],
)
print("not SEX:", [name for (name,) in evaluate(not_sex, lens)])

no_text = Query(
    match=[node("v", "Variable")],
    where=missing(prop("v", "question_text")),
    returns=[prop("v", "name")],
    order_by=[asc(prop("v", "name"))],
)
print("no question text:", [name for (name,) in evaluate(no_text, lens)])
not SEX: [Text(value='AGE', lang=None), Text(value='EDUC', lang=None), Text(value='HOURS', lang=None), Text(value='REGION', lang=None)]
no question text: [Text(value='AGEGRP', lang=None), Text(value='ILOSTAT', lang=None)]

The first filter loses AGEGRP and ILOSTAT, the two derived variables. They have no question text, so "question text == 'What is your sex?'" is unknown for them. not_ of unknown is still unknown, and an unknown row is dropped. missing is never unknown. To list every variable but SEX, filter on a property every variable has: compare(prop("v", "name"), "!=", "SEX").

Exercise 3 (O4).

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, count, edge, evaluate, node

lens = MemoryLens()
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="cdi"), dataset_id="cdi")

for label in ("CDICodeList", "CDICode", "CDICategory"):
    [(total,)] = evaluate(Query(match=[node("n", label)], returns=[count()]), lens)
    print(f"{label:11} {total}")

denotes = Query(
    match=[node("x", "CDICode"), node("c", "CDICategory"), edge("x", "DENOTES", "c")],
    returns=[count()],
)
[(total,)] = evaluate(denotes, lens)
print(f"{'DENOTES':11} {total}")
CDICodeList 5
CDICode     21
CDICategory 21
DENOTES     21

Each code denotes one category, so the last three counts agree. A count that did not match would point at a code with no category, or at a stub, as in Module 4. There are 5 code lists for 7 variables, because AGE and HOURS are numbers.

Exercise 4 (O5).

from collections import Counter

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, edge, evaluate, key, node, prop

lens = MemoryLens()
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="cdi"), dataset_id="cdi")

query = Query(
    match=[
        node("l", "CDICodeList"),
        node("x", "CDICode"),
        node("c", "CDICategory"),
        edge("l", "HAS_CODE", "x"),
        edge("x", "DENOTES", "c"),
    ],
    returns=[prop("l", "name"), key("c")],
)
sizes = Counter(name.value for name, _category in evaluate(query, lens))
for name, size in sorted(sizes.items(), key=lambda item: (-item[1], item[0])):
    print(f"{name}: {size}")
Age group: 6
Highest level of education: 5
Region: 5
Labour force status (ILO): 3
Sex: 2

The pattern is the DDI 3.3 shape with CDI names: the codes sit between the list and its categories. A CDI name is a plain string, so it needs no .value. The DDI-L file has one list more, "Yes or no". It serves the questions WORK, LOOK and AVAIL, and DDI-CDI 1.0 holds no questions.

Quiz

Question 1 (O1): What does lens.write(chunks, dataset_id='codebook') return?

B. The counts let you check a load at once, as in section 1: 80 nodes and 48 edges, as the preview said. Rows (A) come from evaluate or run.

Question 2 (O2): A query matches node('q', 'QuestionItem'), node('v', 'Variable') and edge('q', 'REFERENCES_QUESTION', 'v'). It returns no rows. Why?

B. An edge pattern follows the direction of the IR. A is tempting, but a misspelled type would raise a ValueError when you build the query, not return an empty list.

Question 3 (O3): Why does not_(compare(prop('v', 'question_text'), '==', 'What is your sex?')) skip AGEGRP and ILOSTAT?

B. This is SQL's rule, and every engine follows it. The two derived variables have no question text. To find them, use missing(prop('v', 'question_text')), which is never unknown.

Question 4 (O4): Query(match=[node('n', 'Variable')], returns=[prop('n', 'label'), count()]) raises a ValueError. Why?

A. The message says count(*) is returned alone. To count by some value, run one count query per value, or return the rows and count them in Python with collections.Counter.

Question 5 (O5): You ask a DDI 3.3 file for (CodeList)-[:HAS_CATEGORY]->(Category) and get no rows, yet its code lists have categories. Why?

B. Ask through the codes too, as section 7 does. Only a code with no ID, as in DDI 3.1, leaves the edge on its code list.

Question 6 (O2): When does ddigraph notice that you wrote node('q', 'QuestionItm')?

C. The Query checks each name against ddigraph's model and raises a ValueError with the nearest valid name. A is what would happen in a hand-written loop, which is the reason for the check.

Module 6: Prove it is right: XSD and SHACL

Exercises

Exercise 1 (O1, O5).

ddigraph validate tests/fixtures/cdi_sample.xml || echo "exit code $?"
ddigraph export tests/fixtures/cdi_sample.xml --format turtle -o cdi.ttl
ddigraph validate cdi.ttl --flavor cdi
File:   .../tests/fixtures/cdi_sample.xml
Flavor: cdi
Schema: .../schemas/ddi-cdi/xml-schema/ddi-cdi.xsd
Result: invalid (1 issue(s))
  line 10: Element '{http://ddi-cdi/1.0}Wrapper': No matching global declaration available for the validation root.
exit code 1
Wrote cdi.ttl
Format: turtle
Nodes: 9  Relationships: 3
Triples: 149
File:   .../cdi.ttl
Shapes: cdi (149 triples)
Shapes result: conforms

They disagree: the XSD says no, SHACL says yes. The file declares the namespace http://ddi-cdi/1.0, which is not the one the published schema uses, so the schema has nothing to match its root element. The reader does not mind, and builds a correct graph. A disagreement like this points at the input file, not at what you built from it.

Exercise 2 (O2).

from pathlib import Path

from ddigraph.validation import validate

for path in sorted(Path("tests/fixtures").glob("*.xml")):
    result = validate(path, max_issues=1)
    print(path.name, "valid" if result.valid else "invalid")
cdi_correspondence.xml invalid
cdi_inherited_endpoints.xml invalid
cdi_sample.xml invalid
cdi_valid_minimal.xml valid
codebook_sample.xml invalid
fragment_instance.xml invalid
ir_cdi_valid.xml valid
lfs_cdi.xml valid
lfs_codebook.xml valid
lfs_correspondence.xml valid
lfs_lifecycle.xml valid
reusable_fragments.xml invalid

max_issues=1 stops counting after the first issue: to sort files into valid and invalid, one is enough. The four survey files pass, and so do two CDI test files. The other test files fail on purpose, as section 2 said.

Exercise 3 (O3).

import rdflib

import ddigraph
from ddigraph.validation import validate_shapes

ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
data = rdflib.Graph().parse("survey.ttl", format="turtle")
code_list = rdflib.URIRef("urn:ddi:example.nso:cl-education:1")
data.remove((code_list, rdflib.OWL.versionInfo, None))
data.serialize("broken.ttl", format="turtle")

result = validate_shapes("broken.ttl", flavor="lifecycle")
print("conforms:", result.valid, "results:", result.total)
for issue in result.issues:
    print(issue.focus_node, issue.constraint)
conforms: False results: 1
urn:ddi:example.nso:cl-education:1 OrConstraintComponent

A required property is written as an "or": the node must have the version, or be a stub with an unresolvedReason. This node is neither, so the "or" fails. The full message lists both choices.

Exercise 4 (O4).

import ddigraph
from ddigraph.validation import validate_shapes

ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")

for flavor in ("codebook", "lifecycle"):
    result = validate_shapes("survey.ttl", flavor=flavor)
    print(f"{flavor:10} conforms={result.valid} results={result.total}")
codebook   conforms=False results=51
lifecycle  conforms=True results=0

Trust the Lifecycle result: it uses the file's own flavor. The Codebook shapes expect a dataset_id on each Category, CodeList, Concept, QuestionItem, Universe and Variable, because Codebook IDs are scoped to a dataset. A DDI-L node has a URN instead. So the wrong flavor raises 51 false alarms, one for each node of those six types: 23 categories, 6 code lists, 5 concepts, 8 questions, 2 universes and 7 variables.

Quiz

Question 1 (O1): In a build script, ddigraph validate survey.xml finds two issues. What happens next?

B. The exit code is 1 for an invalid file and 0 for a valid one, which is all a build step needs. The command never changes the file (C).

Question 2 (O5): A partner's file has a typo in an element name, <r:Agnecy>. Which check catches it?

A. A wrong element is a question about the XML, so the schema answers it. B is tempting, but SHACL sees only the graph, never the XML, so it cannot point at the element that was misspelled.

Question 3 (O5): A bug in a converter writes a node with no ddigraph:key. Which check catches it?

B. The source file can be perfect while the graph is wrong. Only a check on the graph sees what the converter made.

Question 4 (O1): Why does ddigraph load not check the XSD unless you pass --validate?

B. You choose when to be strict. The schemas do ship with ddigraph (C): ddigraph validate uses them.

Question 5 (O4): A Codebook export passes with no --flavor, and fails with --flavor lifecycle. What should you conclude?

B. The Lifecycle shapes expect an agency, an ID and a version that Codebook nodes need not have. With no flavor, a shared type passes if it matches any flavor's shape, which is looser (D). The file's own flavor gives the right check.

Question 6 (O3): What does ddigraph shapes -o shapes.ttl --flavor lifecycle write?

B. The shapes are a graph themselves. Pass them to pyshacl, or to another SHACL tool, to check an export. C is what ddigraph export writes.

Question 7 (O2): validate(path, max_issues=1) returns one issue. Does the file have only one problem?

B. max_issues caps the list. Use max_issues=0 to keep them all. A file with an issue is invalid (D): result.valid is False.

Module 7: Your first graph database: Neo4j

Exercises

Exercise 1 (O1, O2).

ddigraph bootstrap
ddigraph bootstrap
ddigraph load tests/fixtures/lfs_lifecycle.xml --dataset-id m07-survey --replace
ddigraph load tests/fixtures/lfs_lifecycle.xml --dataset-id m07-survey --replace
Schema ensured for database 'neo4j'
Schema ensured for database 'neo4j'
Pre-ingestion: connecting to Neo4j at ... (database 'neo4j'); credentials from ...; dry-run/validate-only is OFF; format: lifecycle
Ingestion complete: dataset_id=m07-survey, nodes_written=87, relationships_written=108, stubs=0, references=85, resolved=85, unresolved=0, conflicts=0
Pre-ingestion: connecting to Neo4j at ... (database 'neo4j'); credentials from ...; dry-run/validate-only is OFF; format: lifecycle
Ingestion complete: dataset_id=m07-survey, nodes_written=87, relationships_written=108, stubs=0, references=85, resolved=85, unresolved=0, conflicts=0

Nothing changes. The schema statements are IF NOT EXISTS, and --replace empties the dataset before each load, so the second load writes the same graph again. Both commands are safe to repeat.

Exercise 2 (O3, O5).

In Browser:

MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: 'm07-survey'})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)-[c:CONTAINS*0..1]->()-[h:HAS_CATEGORY]->(cat:Category)
RETURN q.name AS question, cl.label AS code_list, cat.label AS category
ORDER BY question, coalesce(c[0].ordinal, h.ordinal)

From Python:

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

ddigraph.load("tests/fixtures/lfs_lifecycle.xml", dataset_id="m07-survey", replace=True)

query = """
MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
MATCH (q)-[:USES_CODELIST]->(cl:CodeList)-[c:CONTAINS*0..1]->()-[h:HAS_CATEGORY]->(cat:Category)
RETURN q.name AS question, cl.label AS code_list, cat.label AS category
ORDER BY question, coalesce(c[0].ordinal, h.ordinal)
"""
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _summary, _keys = driver.execute_query(
        query, dataset="m07-survey", database_=settings.neo4j_database
    )
for record in records:
    print(record["question"], "|", record["code_list"], "|", record["category"])
AVAIL | Yes or no | Yes
AVAIL | Yes or no | No
EDUC | Highest level of education | Primary or less (ISCED 0-1)
EDUC | Highest level of education | Lower secondary (ISCED 2)
EDUC | Highest level of education | Upper secondary (ISCED 3)
EDUC | Highest level of education | Post-secondary non-tertiary (ISCED 4)
EDUC | Highest level of education | Tertiary (ISCED 5-8)
LOOK | Yes or no | Yes
LOOK | Yes or no | No
REGION | Region | Capital region
REGION | Region | North
REGION | Region | South
REGION | Region | East
REGION | Region | West
SEX | Sex | Male
SEX | Sex | Female
WORK | Yes or no | Yes
WORK | Yes or no | No

The first MATCH keeps the query to m07-survey. The *0..1 reads the categories whether they hang off the codes or off the code list, and the coalesce of the two ordinals keeps their order, as section 4 explained. Sort by h.ordinal alone, and the categories of each list come in no set order, since each code's HAS_CATEGORY edge has the ordinal 0. AGE and HOURS are not listed: their answer is a number.

Exercise 3 (O4).

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m07-codebook", replace=True)

query = """
MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
OPTIONAL MATCH (v)-[:IN_UNIVERSE]->(u:Universe)
RETURN v.name AS variable, u.label AS universe
ORDER BY v.ddi_id
"""
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _summary, _keys = driver.execute_query(
        query, dataset="m07-codebook", database_=settings.neo4j_database
    )
for record in records:
    print(record["variable"], record["universe"])
SEX None
AGE None
AGEGRP None
REGION None
EDUC None
ILOSTAT None
HOURS Employed persons aged 15 and over

A Codebook variable states a universe only where it narrows the study's, "Persons aged 15 and over living in private households". Only HOURS does: only employed people are asked about their hours. OPTIONAL MATCH keeps the other six and gives None for them. A plain MATCH would drop those rows. The ORDER BY uses ddi_id, V1 to V7, which follows the file.

Exercise 4 (O5).

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings
from ddigraph.lens.neo4j import Neo4jLens

waves = ("m07-wave1", "m07-wave2")
for wave in waves:
    ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id=wave, replace=True)

query = """
MATCH (v:Variable {name: 'SEX'})-[:IN_DATASET]->(d:Dataset)
WHERE d.dataset_id IN $waves
RETURN d.dataset_id AS dataset, v.identity AS identity
ORDER BY dataset
"""
settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _summary, _keys = driver.execute_query(
        query, waves=list(waves), database_=settings.neo4j_database
    )
    for record in records:
        print(record["dataset"], record["identity"])
    lens = Neo4jLens(driver, database=settings.neo4j_database)
    for wave in waves:
        print(wave, "removed:", lens.purge(wave), "nodes")
    for dataset in ("m07-codebook", "m07-survey"):
        lens.purge(dataset)
    records, _summary, _keys = driver.execute_query(
        "MATCH (d:Dataset) WHERE d.dataset_id STARTS WITH 'm07-' RETURN count(d) AS left",
        database_=settings.neo4j_database,
    )
print("m07 datasets left:", records[0]["left"])
m07-wave1 urn:ddigraph:scoped:m07-wave1:V1
m07-wave2 urn:ddigraph:scoped:m07-wave2:V1
m07-wave1 removed: 80 nodes
m07-wave2 removed: 80 nodes
m07 datasets left: 0

A Codebook ID, here V1, is scoped to its dataset, so the same file loaded twice gives two separate graphs. Without the IN_DATASET anchor, a query for SEX would mix both waves, and any other dataset's SEX too. Each purge removes its wave's 79 members and its Dataset node. The last purges remove the datasets of the earlier exercises.

Quiz

Question 1 (O1): What does ddigraph bootstrap create?

B. One schema serves every flavor, and running it again changes nothing. It writes no data (D): that is what ddigraph load does.

Question 2 (O2): You delete a variable from a file, then reload it with ddigraph load and the same --dataset-id, without --replace. What happens to the deleted variable in Neo4j?

B. A load writes what the file holds; it does not look for what is gone. --replace empties the dataset first, so the database matches the file again.

Question 3 (O5): MATCH (v:Variable) RETURN count(v) returns 42, but your file has 7 variables. Why?

B. Start from the dataset: MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: 'm07-codebook'}). A is tempting, but the key constraint makes a second copy of a node impossible.

Question 4 (O3): Why does the code list query use -[:CONTAINS*0..1]->() before -[:HAS_CATEGORY]->?

B. Zero CONTAINS edges covers the DDI 3.1 shape, and one covers the shape with codes. C is wrong: in a DDI 3.1 file the edge starts at the code list.

Question 5 (O4): Why pass dataset='m07-codebook' to execute_query, rather than pasting the name into the query text?

B. Values from users or files belong in parameters. A is wrong: the Browser queries above hold strings. The database is a driver option, database_ (D).

Question 6 (O2): A load reports conflicts=3. What does that mean?

B. The survey's files load with conflicts=0, as a clean file should. A file where two elements share an ID reports them. Stubs (D) are counted by stubs, and other datasets never cause conflicts (A).

Module 8: Linked data: RDF out and back in

Exercises

Exercise 1 (O1).

import json

import ddigraph

result = ddigraph.export("tests/fixtures/lfs_cdi.xml", "cdi.jsonld", format="jsonld")
print(result.nodes, "nodes,", result.relationships, "relationships,", result.triples, "triples")

with open("cdi.jsonld", encoding="utf-8") as handle:
    objects = json.load(handle)
print(len(objects), "JSON-LD objects")
91 nodes, 92 relationships, 1995 triples
273 JSON-LD objects

Each subject is one object: the 91 nodes, the 90 memberships (the Dataset node has none), and the 92 statements, one per relationship.

Exercise 2 (O2).

import rdflib

import ddigraph
from ddigraph.rdf.vocabulary import DDIGRAPH

ddigraph.export("tests/fixtures/lfs_codebook.xml", "codebook.ttl", format="turtle")
graph = rdflib.Graph().parse("codebook.ttl")

types = {str(kind) for kind in graph.objects(None, rdflib.RDF.type)}
project = {kind for kind in types if kind.startswith(DDIGRAPH)}
print(len(types), "types,", len(project), "of them ddigraph types")
26 types, 16 of them ddigraph types

Most types are ddigraph: ones, since DISCO has only 16 classes. Two of them, ddigraph:Membership and ddigraph:Dataset, belong to the export itself. The 10 published types cover what other people search for: the study, its variables, questions, universes and data file, and the categories and concepts as skos:Concept. One of them is rdf:Statement, for the edges.

Exercise 3 (O3).

import rdflib

import ddigraph

ddigraph.export("tests/fixtures/lfs_codebook.xml", "codebook.ttl", format="turtle")
graph = rdflib.Graph().parse("codebook.ttl")

rows = graph.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 ?concept WHERE {
  ?v a disco:Variable ;
     rdfs:label ?variable ;
     disco:concept ?c .
  ?c skos:prefLabel ?concept .
}
ORDER BY ?variable
""")
for variable, concept in rows:
    print(variable, "->", concept)
Age group -> Demographic characteristics
Age in completed years -> Demographic characteristics
Highest level of education -> Educational attainment
Labour force status (ILO) -> Labour market status
Region of residence -> Place of residence
Sex of the person -> Demographic characteristics
Usual weekly hours in the main job -> Working time

A Codebook concept is a skos:Concept, so its label is skos:prefLabel. A variable has no SKOS class, so its label is rdfs:label. The edge USES_CONCEPT is written as disco:concept. "Demographic characteristics" comes three times, and it is three concepts, not one: DDI-Codebook writes the concept inside each variable. In DDI-L, the three variables point to one concept.

Exercise 4 (O4).

import ddigraph
from ddigraph import iter_graph
from ddigraph.conform import canonical
from ddigraph.rdf.reader import read_graph

ddigraph.export("tests/fixtures/lfs_cdi.xml", "cdi.jsonld", format="jsonld")

back = canonical(read_graph("cdi.jsonld"))
original = canonical(iter_graph("tests/fixtures/lfs_cdi.xml"))
print("same graph:", back == original)

labels = sorted({node.label for chunk in read_graph("cdi.jsonld") for node in chunk.nodes})
print(labels)
same graph: True
['CDIAgent', 'CDICategory', 'CDICode', 'CDICodeList', 'CDIConcept', 'CDIConceptSystem', 'CDIGenericEntity', 'CDIInstanceVariable', 'CDIUnitType', 'CDIValueDomain', 'Dataset']

The JSON-LD file holds the same nodes, with the same keys, properties and provenance, and the same relationships, in order. read_graph knows the format from the .jsonld extension.

Quiz

Question 1 (O1): An export of the sample survey reports 87 nodes and over 2,000 triples. Why are there so many more triples than nodes?

B. A node with ten properties and two types is already twelve triples. Each membership and each statement adds a few more. A is tempting, but a node is written once: its edges are triples about it, not copies of it. The vocabularies themselves are not copied in.

Question 2 (O2): A colleague wants smaller files and proposes to write only the published rdf:type. What breaks?

C. The match to published classes is many to one, so the published type alone loses the DDI type. A is true for other tools, which is why it is tempting, but the round trip of section 8 needs the ddigraph: class. Queries on disco:Question would still work.

Question 3 (O3): You want the categories of a code list in their order. Which part of the export holds that order?

B. A set of triples has no order, so the order of lines in a file means nothing (A). The statement of each edge carries its ordinal. D is tempting, since a later line often means a later category, but a category can be defined anywhere in the file, far from its code list. C would put "Female" before "Male", whatever the list says.

Question 4 (O3): Which SPARQL pattern finds the categories of the code list ?scheme in a SKOS tool?

C. SKOS puts the link on the member. B is the graph's direction, which is tempting, but it would say the scheme is inside the category. skos:member belongs to skos:Collection, not to a concept scheme. D works in ddigraph's own terms, but a SKOS tool does not know them.

Question 5 (O4): You run read_graph on a Turtle file of SKOS concepts that another tool published. What happens?

B. read_graph reads only what ddigraph wrote, and never guesses an identity. D sounds friendly, but a half-read graph would be worse than an error. To use someone else's RDF, query it with rdflib beside your export.

Question 6 (O4): You run ddigraph load out.ttl. Which dataset do the nodes join?

B. The export writes the Dataset node and a membership per node, so the file knows its dataset. A is how a DDI XML file gets its default ID, which is why it is tempting. That is why section 9 names the dataset when it exports.

Module 9: Code lists and classifications: SKOS and XKOS

Exercises

Exercise 1 (O1).

from ddigraph import iter_graph

nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_cdi.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    edges.extend(chunk.relationships)


def ends(start, kind):
    return [nodes[edge.end] for edge in edges if edge.start == start and edge.type == kind]


for code_list in nodes.values():
    if code_list.properties.get("name") != "Labour force status (ILO)":
        continue
    for code in ends(code_list.key, "HAS_CODE"):
        (notation,) = ends(code.key, "USES")
        (category,) = ends(code.key, "DENOTES")
        print(
            code_list.properties["name"],
            "-HAS_CODE->",
            f"code {notation.properties['value']}",
            "-DENOTES->",
            category.properties["name"],
        )

DDI-CDI always makes the code a node: it has an identifier, and its value sits on the notation it USES. The edge names differ from DDI-L, but the idea is the same: list, code, category. The list has its three codes, in their order.

Exercise 2 (O2).

import re
from pathlib import Path

from ddigraph import iter_graph

text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
text = text.replace("example.nso", "example.archive")
text = re.sub(r'<l:Code isUniversallyUnique="true">\s*<r:URN>.*?</r:Version>', "<l:Code>", text)
Path("archive.xml").write_text(text, encoding="utf-8")

for path in ("tests/fixtures/lfs_lifecycle.xml", "archive.xml"):
    labels, edges = {}, []
    for chunk in iter_graph(path):
        for node in chunk.nodes:
            labels[node.key] = node.label
        edges.extend(chunk.relationships)
    lists = {key for key, label in labels.items() if label == "CodeList"}
    steps = lists | {edge.end for edge in edges if edge.type == "CONTAINS" and edge.start in lists}
    direct = sum(edge.type == "HAS_CATEGORY" and edge.start in lists for edge in edges)
    found = sum(edge.type == "HAS_CATEGORY" and edge.start in steps for edge in edges)
    print(f"{path}: direct {direct}, with CONTAINS*0..1 {found}")
tests/fixtures/lfs_lifecycle.xml: direct 0, with CONTAINS*0..1 23
archive.xml: direct 23, with CONTAINS*0..1 23

steps holds the code lists and the codes they contain: the zero-step and the one-step starts. The direct edge misses all 23 categories of the DDI 3.3 file, and no error tells you. A count like this one is a cheap check to run on every new file.

Exercise 3 (O3).

from ddigraph import iter_graph
from ddigraph.rdf.writer import build_graph

graph = build_graph(iter_graph("tests/fixtures/lfs_codebook.xml"))
rows = graph.query("""
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?code ?label WHERE {
  ?variable ddigraph:name "ILOSTAT" ;
            ddigraph:usesCategory ?category .
  ?category skos:prefLabel ?label ;
            skos:notation ?code .
}
ORDER BY ?code
""")
for row in rows:
    print(row.code, row.label)
1 Employed
2 Unemployed
3 Not in the labour force

A Codebook category keeps its code value (catValu) as its code property, which SKOS writes as skos:notation. USES_CATEGORY has no published term, so it stays ddigraph:usesCategory. A DDI-L category has no notation: in DDI-L, the value belongs to the code, as its value property, not to the category.

Exercise 4 (O3).

from ddigraph import iter_graph
from ddigraph.rdf.writer import build_graph

PUBLISHED = """
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix isced: <https://example.org/isced2011/> .
isced:levels a skos:ConceptScheme ; skos:prefLabel "ISCED 2011 levels of education"@en .
isced:0 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "0" ; skos:prefLabel "Early childhood education"@en .
isced:1 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "1" ; skos:prefLabel "Primary education"@en .
isced:2 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "2" ; skos:prefLabel "Lower secondary education"@en .
isced:3 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "3" ; skos:prefLabel "Upper secondary education"@en .
isced:4 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "4" ; skos:prefLabel "Post-secondary non-tertiary education"@en .
isced:5 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "5" ; skos:prefLabel "Short-cycle tertiary education"@en .
isced:6 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "6" ; skos:prefLabel "Bachelor's or equivalent level"@en .
isced:7 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "7" ; skos:prefLabel "Master's or equivalent level"@en .
isced:8 a skos:Concept ; skos:inScheme isced:levels ; skos:notation "8" ; skos:prefLabel "Doctoral or equivalent level"@en .
"""

graph = build_graph(iter_graph("tests/fixtures/lfs_lifecycle.xml"))
graph.parse(data=PUBLISHED, format="turtle")

links = graph.query("""
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
CONSTRUCT { ?category skos:exactMatch ?level }
WHERE {
  ?category a skos:Concept ; skos:prefLabel ?label .
  ?level skos:inScheme <https://example.org/isced2011/levels> ; skos:notation ?code .
  FILTER (CONTAINS(STR(?label), CONCAT("(ISCED ", ?code, ")")))
}
""")
for category, match, level in sorted(links):
    graph.add((category, match, level))
    print(category, "exactMatch", level)
urn:ddi:example.nso:cat-education-2:1 exactMatch https://example.org/isced2011/2
urn:ddi:example.nso:cat-education-3:1 exactMatch https://example.org/isced2011/3
urn:ddi:example.nso:cat-education-4:1 exactMatch https://example.org/isced2011/4

ddigraph writes no skos:exactMatch: linking is your decision, so you build it. Lower secondary, Upper secondary and Post-secondary non-tertiary each match one level. "Primary or less (ISCED 0-1)" and "Tertiary (ISCED 5-8)" cover several levels, so they are not exact matches, and the filter skips them. SKOS has skos:narrowMatch for them: "Tertiary" is broader than level 6. That link is a judgement too, so a person should make it.

Exercise 5 (O4).

from ddigraph import iter_graph
from ddigraph.rdf.writer import build_graph

graph = build_graph(iter_graph("tests/fixtures/lfs_correspondence.xml"))
rows = graph.query("""
PREFIX xkos: <http://rdf-vocabulary.ddialliance.org/xkos#>
SELECT ?correspondence (COUNT(?map) AS ?maps) WHERE {
  ?correspondence a xkos:Correspondence ; xkos:madeOf ?map .
}
GROUP BY ?correspondence
ORDER BY ?correspondence
""")
for row in rows:
    print(row.correspondence, row.maps)
urn:ddi:example.nso:age-lfs-broad:1 6
urn:ddi:example.nso:isced1997-2011:1 9

The first is a concept system correspondence: one concept map per age group. The second is a correspondence table with nine maps for eight ISCED 1997 levels, since 5A maps twice. Both kinds hold their maps with HAS_CONCEPT_MAP, so both are xkos:madeOf them.

Quiz

Question 1 (O1): Why is a code in a DDI 3.3 code list a node of its own, while a code in a DDI 3.1 code list is not?

B. Identity decides it, as in Module 4. C is tempting, since a code does hold a value, but so does a DDI 3.1 code, and it stays part of its code list. A is wrong: a code with no ID is not a node.

Question 2 (O2): MATCH (cl:CodeList)-[:HAS_CATEGORY]->(cat) RETURN cat.label returns no rows on a DDI 3.3 file that has code lists. What is the most likely reason?

C. Use (cl:CodeList)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat). B is tempting when a query returns nothing, but a stub would still be matched. D would follow chains of categories, which do not exist.

Question 3 (O3): In the SKOS form of a DDI 3.3 code list, which node is the skos:Concept in the scheme?

B. A DDI-L code gets no SKOS class. Its category is the concept, and it carries the label. A is tempting because the code is the node next to the list in the graph, but SKOS skips it. The ddigraph:contains and ddigraph:hasCategory triples keep the code for anyone who needs it.

Question 4 (O3): You want to tell a partner that your category means the same as an item of their published classification. What does ddigraph give you?

B. Saying two things mean the same is a judgement, so ddigraph does not guess it. D is tempting, but external references are written as one rdf:List under ddigraph:externalReferences, because a reference is not a claim of sameness.

Question 5 (O4): In lfs_correspondence.xml, the ISCED correspondence table has a HAS_SOURCE edge and each concept map has one too. Which become xkos:sourceConcept?

C. xkos:sourceConcept must point at a concept. The table's source is a level, "ISCED 1997 levels", so it keeps only ddigraph:hasSource. A is tempting because the edge type is the same, but the published term depends on where the edge starts.

Question 6 (O4): A tool reads your export and asks for the xkos:depth of each level. What should you tell it?

B. ddigraph maps the level's class, not the rest of the XKOS level model. A is what a full XKOS export would offer, which is why it is tempting. The SKOS and XKOS page lists what is not mapped.

Module 10: One query, many engines

Exercises

Exercise 1 (O1, O2).

import duckdb

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, compare, edge, node, prop, run

query = Query(
    match=[node("q", "QuestionItem"), node("l", "CodeList"), edge("q", "USES_CODELIST", "l")],
    returns=[prop("q", "name")],
    where=compare(prop("l", "label"), "==", "Yes or no"),
    order_by=[asc(prop("q", "name"))],
)

results = []
for lens in (MemoryLens(), SQLLens(duckdb.connect()), OxigraphLens()):
    lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="survey"), dataset_id="survey"
    )
    rows = run(query, lens)
    print(type(lens).__name__, rows)
    results.append(rows)
print("same:", all(rows == results[0] for rows in results))
MemoryLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
SQLLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
OxigraphLens [(Text(value='AVAIL', lang='en'),), (Text(value='LOOK', lang='en'),), (Text(value='WORK', lang='en'),)]
same: True

The code that writes and queries does not change from one lens to the next. Only the lens's constructor does. A text property such as label compares with a plain string: the filter reads its value, not its language. The three questions share one code list, so a change to that list reaches all three.

Exercise 2 (O3).

from ddigraph.query import Query, compare, node, prop, to_cypher, to_sparql, to_sql

query = Query(
    match=[node("q", "QuestionItem")],
    returns=[prop("q", "name")],
    where=compare(prop("q", "name"), "==", "WORK"),
)
sql, sql_parameters = to_sql(query, "postgres")
_cypher, cypher_parameters = to_cypher(query)
print(sql_parameters, cypher_parameters, '"WORK"' in to_sparql(query))
print(sql)
['WORK'] {'p0': 'WORK'} True
WITH RECURSIVE v0 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'QuestionItem')
)
SELECT p0.string_value AS c0, p0.language AS c1
FROM (
  SELECT n0.key AS n0
  FROM v0 AS n0
) AS m
LEFT JOIN ddigraph_properties AS p0
  ON p0.key = m.n0 AND p0.name = 'name'
WHERE (p0.string_value COLLATE "C" = $1)

SQL and Cypher keep every literal out of the text, as a parameter. So a value from a user can never change the query itself. SPARQL writes the literal in, escaped. On PostgreSQL, COLLATE "C" makes the comparison go by code point, as on the other engines.

Exercise 3 (O4).

import duckdb

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, compare, missing, node, or_, prop, run

text = prop("v", "question_text")
hours_question = "How many hours a week do you usually work in your main job?"
query = Query(
    match=[node("v", "Variable")],
    returns=[prop("v", "name")],
    where=or_(missing(text), compare(text, "!=", hours_question)),
    order_by=[asc(prop("v", "name"))],
)
for lens in (MemoryLens(), SQLLens(duckdb.connect()), OxigraphLens()):
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
    )
    print(run(query, lens))
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]
[(Text(value='AGE', lang=None),), (Text(value='AGEGRP', lang=None),), (Text(value='EDUC', lang=None),), (Text(value='ILOSTAT', lang=None),), (Text(value='REGION', lang=None),), (Text(value='SEX', lang=None),)]

compare(text, "!=", ...) alone would drop AGEGRP and ILOSTAT, whose question text is missing: the filter is unknown there. missing(text) is never unknown, so or_ keeps them.

Exercise 4 (O4).

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens
from ddigraph.lens.networkx import NetworkXLens
from ddigraph.query import Query, count, node, run

query = Query(match=[node("v", "Variable")], returns=[count()])

nx_lens = NetworkXLens()
nx_lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="codebook"), dataset_id="codebook"
)
try:
    run(query, nx_lens)
except TypeError as error:
    print("TypeError:", error)

memory = MemoryLens()
memory.write(nx_lens.read(dataset_id="codebook"), dataset_id="codebook")
print(run(query, memory))
TypeError: Cannot run a query on a NetworkXLens
[(7,)]

NetworkX and pandas are stores for analysis, not query engines. Every lens reads back the same stream, so moving a dataset from one lens to another is one write of the other's read. The count is the survey's seven variables.

Quiz

Question 1 (O1): You misspell a property, prop('v', 'lable'). When do you find out?

C. A query is checked against the model as it is built. B is what a Cypher typo would do in Neo4j, which is why it is tempting: an unknown property there is quietly null. That is the mistake the typed query prevents.

Question 2 (O2): Which call runs a query on an in-memory DuckDB database?

B. run needs a lens, which knows its tables. A is tempting, but a bare connection has no ddigraph_ tables until a lens makes them, and run does not take one. evaluate works on a MemoryLens only. to_sql gives the text and runs nothing.

Question 3 (O3): to_cypher(query) returns a pair. What is the second item?

B. Every literal is a parameter, so a value can never change the query's text. A is tempting because the text starts with CYPHER 5, but the version is the function's second argument, not part of what it returns.

Question 4 (O4): A query filters with not_(compare(prop('v', 'question_text'), '==', 'What is your sex?')). The derived variable ILOSTAT has no question_text. Is it in the result?

B. A missing value is unknown, as in SQL. A is the everyday reading, which is why it is tempting. C would be true without ddigraph.query: the shared rule is what makes every engine agree. Add missing(...) with or_ to keep such rows.

Question 5 (O4): Why does Query(..., limit=10) need an order_by over every returned term?

B. Each engine may return rows in any order before the limit. Only a full order makes "the first 10" mean the same rows everywhere. A is false: SQL accepts a bare LIMIT, and that is exactly the problem.

Question 6 (O4): You keep a graph in a PandasLens and want to run a ddigraph.query on it. What do you do?

C. pandas, like NetworkX, is not a query target, so run raises TypeError. But every lens reads back the same stream, so a copy is one write. B is tempting, but the SQL reads the SQL lens's tables, not your DataFrames.

Module 11: Reload, history and differences

Exercises

Exercise 1 (O1).

ddigraph store add tests/fixtures/lfs_lifecycle.xml --dataset-id lfs-lifecycle --store agency-store
ddigraph store add tests/fixtures/lfs_cdi.xml --dataset-id lfs-cdi --store agency-store
ddigraph store list --store agency-store
Generation 1 of dataset 'lfs-lifecycle': 87 nodes, 108 relationships
Generation 1 of dataset 'lfs-cdi': 91 nodes, 92 relationships
lfs-cdi: HEAD 1, 1 generations
lfs-lifecycle: HEAD 1, 1 generations

Each dataset has its own folder and its own HEAD, so one store holds many files of any flavor, here the same survey in two of them. store list sorts the datasets by ID.

Exercise 2 (O2).

cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
first=$(ddigraph store show lfs | python -c "import json, sys; print(json.load(sys.stdin)['created'])")
python - <<'EOF'
from pathlib import Path

path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace("<labl>West</labl></catgry>", "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>")
text = text.replace("usually work in your main job?", "usually work in your main job, including overtime?")
path.write_text(text, encoding="utf-8")
EOF
ddigraph store add lfs.xml > /dev/null
cat > label.py <<'EOF'
import json
import sys

graph = json.load(sys.stdin)
for node in graph["nodes"]:
    if node["properties"].get("ddi_id") == "Q-HOURS":
        print(sys.argv[1], node["properties"]["label"]["value"])
EOF
ddigraph store show lfs --as-of "$first" --json | python label.py then:
ddigraph store show lfs --json | python label.py now:
then: How many hours a week do you usually work in your main job?
now: How many hours a week do you usually work in your main job, including overtime?

Generation 1 never changes, so --as-of reads the graph exactly as it was when it was written. In the JSON, a text property is an object with its value and its lang.

Exercise 3 (O3).

cp tests/fixtures/lfs_codebook.xml lfs.xml
ddigraph store add lfs.xml > /dev/null
cp lfs.xml renamed.xml
ddigraph store add renamed.xml --dataset-id lfs
ddigraph store diff lfs 1 2
Generation 2 of dataset 'lfs': 80 nodes, 48 relationships
Nodes: 0 added, 0 removed, 80 changed
Relationships: 0 added, 0 removed

Every node is changed, though no value is. Each node's provenance holds the file's path, and the path changed. So keep a dataset's file at one path, or expect a diff that lists every node.

Exercise 4 (O4).

import shutil
from pathlib import Path

from ddigraph import ir
from ddigraph.store import Store

shutil.copyfile("tests/fixtures/lfs_codebook.xml", "lfs.xml")
store = Store("ddigraph-store")
store.write("lfs", ir.parse("lfs.xml", dataset_id="lfs"), memory_limit=64 * 2**20)

path = Path("lfs.xml")
text = path.read_text(encoding="utf-8")
text = text.replace(
    "<labl>West</labl></catgry>",
    "<labl>West</labl></catgry><catgry><catValu>6</catValu><labl>Central</labl></catgry>",
)
text = text.replace(
    "usually work in your main job?", "usually work in your main job, including overtime?"
)
path.write_text(text, encoding="utf-8")
store.write("lfs", ir.parse("lfs.xml", dataset_id="lfs"), memory_limit=64 * 2**20)

print("HEAD", store.head("lfs"))
for generation in store.generations("lfs"):
    print(f"generation {generation.number}: {generation.nodes.rows} nodes")

delta = store.diff("lfs", 1, 2)
print("added:", [node.properties["label"].value for node in delta.added])
print("changed:", [node.label for node in delta.changed])

for change, row in store.changes("lfs", since=1):
    print(change, type(row).__name__)
HEAD 2
generation 1: 80 nodes
generation 2: 81 nodes
added: ['Central']
changed: ['Variable', 'Question']
added Node
changed Node
changed Node
added_relationship Relationship

Store.write takes any graph stream, here from ir.parse, and a memory limit for its sort. diff gives the whole delta at once; changes streams it as (change, row) pairs, each row an IR Node or Relationship, in the order a database applies them.

Quiz

Question 1 (O1): You add a new version of a file to the store. What happens to the generation before it?

B. A generation never changes once written, and old ones stay until store gc removes them. C is tempting because it is what a plain load does to Neo4j, but the store keeps each version whole.

Question 2 (O2): A manifest's created is 2026-03-02T09:15:00Z, but the survey describes 2025. What does created record?

C. It is transaction time. A and B are tempting because they are dates about the metadata, but the store never reads them: DDI keeps those in its own versions and dates.

Question 3 (O2): You run store show lfs --as-of 2026-03-01T12:00:00. Generation 1 was created at 09:00 UTC that day and generation 2 at 15:00 UTC. Which do you get?

A. --as-of gives the generation that was HEAD at that time. D is tempting, but a time with no offset is always read as UTC, whatever your computer's time zone.

Question 4 (O3): You add a blank line at the top of a DDI file and add it to the store again. What does store diff report?

B. The key does not change, so nothing is removed or added (C). But provenance holds the line, so the nodes that moved are changed. A is what you might expect, which is why section 4 edits the file without adding lines.

Question 5 (O3): A reference moves from the second place to the first in an ordered list. How does the diff show it?

B. A relationship is known by its start, type, end and ordinal, so a new ordinal makes a new relationship. A is tempting, but a relationship is never "changed", only removed and added.

Question 6 (O4): A program has applied the rows of store changes lfs --since 3 --json. Which --since should it pass next time?

C. The last line names the generation the rows lead to, which may be more than one step past 3. B assumes one new generation per run, which is often wrong. D works but sends the whole graph every time.

Module 12: Build your own pipeline and lens

Exercises

Exercise 1 (O1).

import collections

from ddigraph import iter_graph

for path in (
    "tests/fixtures/lfs_lifecycle.xml",
    "tests/fixtures/lfs_codebook.xml",
    "tests/fixtures/lfs_cdi.xml",
):
    labels = {}
    shapes = collections.defaultdict(set)
    for chunk in iter_graph(path):
        for node in chunk.nodes:
            labels[node.key] = node.label
        for edge in chunk.relationships:
            shapes[labels[edge.start]].add(f"-{edge.type}->")
            shapes[labels[edge.end]].add(f"<-{edge.type}-")

    print(f"--- {path}")
    for label in sorted(shapes)[:4]:
        print(f"  {label}: {', '.join(sorted(shapes[label]))}")
--- tests/fixtures/lfs_lifecycle.xml
  Category: <-HAS_CATEGORY-
  Code: -HAS_CATEGORY->, <-CONTAINS-
  CodeList: -CONTAINS->, <-USES_CODELIST-
  Concept: <-USES_CONCEPT-
--- tests/fixtures/lfs_codebook.xml
  Category: <-USES_CATEGORY-
  Citation: -DESCRIBES->
  Concept: <-USES_CONCEPT-
  Contributor: -CONTRIBUTES_TO->
--- tests/fixtures/lfs_cdi.xml
  CDICategory: <-DENOTES-
  CDICode: -DENOTES->, -USES->, <-HAS_CODE-
  CDICodeList: -HAS_CODE->, -IS_DEFINED_BY->, <-TAKES_VALUES_FROM-
  CDIConcept: <-HAS_CONCEPT-, <-IS_DEFINED_BY-

One loop, three flavors, no branching on which is which. The label of an edge's end is always known when the edge arrives, because of rule 2. iter_graph gives the Codebook file its default dataset ID.

Exercise 2 (O2).

from ddigraph import ir
from ddigraph.lens.networkx import NetworkXLens

lens = NetworkXLens()
for quarter in ("lfs-2025q3", "lfs-2025q4"):
    result = lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id=quarter), dataset_id=quarter
    )
    print(quarter, result.nodes, "nodes written;", lens.graph.number_of_nodes(), "in the graph")

question = lens.graph.nodes["bf1edd4946eed1c2ce250123ecb48b53"]
print("question in:", sorted(question["memberships"]))
print("purged:", lens.purge("lfs-2025q4"), "node")
print(lens.graph.number_of_nodes(), "nodes;", "question in:", sorted(question["memberships"]))
lfs-2025q3 87 nodes written; 87 in the graph
lfs-2025q4 87 nodes written; 88 in the graph
question in: ['lfs-2025q3', 'lfs-2025q4']
purged: 1 node
87 nodes; question in: ['lfs-2025q3']

The 86 DDI objects have the same keys in both quarters, so the lens keeps one of each, held by both datasets. Only the Dataset node is new. A purge deletes only what no other dataset holds: here, the lfs-2025q4 Dataset node. That is the lens rule called isolation.

Exercise 3 (O3).

from pathlib import Path

import msgspec

from ddigraph import ir
from ddigraph.conform import canonical
from ddigraph.ir.model import Node, Relationship
from ddigraph.lens import Lens, WriteResult
from ddigraph.lens.memory import chunked


class JsonLinesLens:
    """Each dataset in a file of its own, with one JSON line per node or relationship."""

    def __init__(self, folder):
        self.folder = Path(folder)
        self.folder.mkdir(exist_ok=True)

    def ddl(self):
        return []

    def write(self, chunks, *, dataset_id, dry_run=False):
        result = WriteResult(dry_run=dry_run)
        lines = []
        for chunk in chunks:
            for node in chunk.nodes:
                lines.append(b"N" + msgspec.json.encode(node))
                result.nodes += 1
            for edge in chunk.relationships:
                lines.append(b"R" + msgspec.json.encode(edge))
                result.relationships += 1
        if not dry_run:
            (self.folder / f"{dataset_id}.jsonl").write_bytes(b"\n".join(lines) + b"\n")
        return result

    def purge(self, dataset_id):
        path = self.folder / f"{dataset_id}.jsonl"
        if not path.exists():
            return 0
        count = sum(line.startswith(b"N") for line in path.read_bytes().splitlines())
        path.unlink()
        return count

    def read(self, *, dataset_id=None):
        names = (
            [dataset_id]
            if dataset_id
            else sorted(path.stem for path in self.folder.glob("*.jsonl"))
        )
        for name in names:
            nodes, edges = [], []
            for line in (self.folder / f"{name}.jsonl").read_bytes().splitlines():
                if line.startswith(b"N"):
                    nodes.append(msgspec.json.decode(line[1:], type=Node))
                else:
                    edges.append(msgspec.json.decode(line[1:], type=Relationship))
            yield from chunked(nodes, edges)


lens = JsonLinesLens("graphs")
print("a Lens:", isinstance(lens, Lens))
print(
    lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="lfs-cdi"), dataset_id="lfs-cdi")
)
print(sorted(path.name for path in Path("graphs").iterdir()))
same = canonical(lens.read(dataset_id="lfs-cdi")) == canonical(
    ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="lfs-cdi")
)
print("same graph:", same)
print("purged:", lens.purge("lfs-cdi"), "nodes")
a Lens: True
WriteResult(nodes=91, relationships=92, stubs=0, dry_run=False)
['lfs-cdi.jsonl']
same graph: True
purged: 91 nodes

The IR types are msgspec structs, so they encode and decode with no code of your own, and the identity, the provenance and each Text survive. Each line starts with N or R, so read knows which type to decode. A file per dataset makes purge one unlink.

Exercise 4 (O4).

from pathlib import Path

import ddigraph
from ddigraph import iter_graph
from ddigraph.rdf.reader import read_graph

RDF = {".ttl", ".jsonld", ".nt", ".rdf"}


def graph(path):
    """Read a DDI file, or an RDF file that ddigraph wrote, as the graph stream."""
    return read_graph(path) if Path(path).suffix in RDF else iter_graph(path)


ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "lfs.jsonld", format="jsonld")
ddigraph.export("tests/fixtures/lfs_cdi.xml", "lfs_cdi.ttl", format="turtle")
for path in ("tests/fixtures/lfs_lifecycle.xml", "lfs.jsonld", "lfs_cdi.ttl"):
    nodes = relationships = 0
    for chunk in graph(path):
        nodes += len(chunk.nodes)
        relationships += len(chunk.relationships)
    print(f"{path}: {nodes} nodes, {relationships} relationships")
tests/fixtures/lfs_lifecycle.xml: 87 nodes, 108 relationships
lfs.jsonld: 87 nodes, 108 relationships
lfs_cdi.ttl: 91 nodes, 92 relationships

Both readers give the same kind of stream, so the rest of the pipeline never knows where the graph came from. The JSON-LD file gives back the graph of the XML it came from. read_graph accepts both RDF files because ddigraph wrote them.

Quiz

Question 1 (O1): Why can a target write each chunk's edges right after its nodes, with no second pass?

B. That is rule 2 of the stream. D is how some databases behave, which makes it tempting, but it would create empty nodes and hide real errors. C is false: a chunk holds a number of nodes, not a fragment.

Question 2 (O1): A pipeline keys nodes on node.properties['ddi_id']. It loads two agencies' files and finds fewer nodes than expected, with no error. Why?

B. An ID is unique only with its agency and version. A is true of the Dataset node, which is why it is tempting, but it would raise a KeyError, not lose nodes quietly. Always key on node.key.

Question 3 (O2): You write the same file twice through a lens, under the same dataset ID. What changes the second time?

B. A lens writes nodes by key, so a reload changes nothing. D is what ddigraph load --replace does on purpose, which is why it is tempting, but a lens's write never purges.

Question 4 (O3): Which of these makes a class a ddigraph.lens.Lens?

B. Lens is a protocol: a class with those four methods is one, and isinstance checks the methods. A is how many libraries work, hence the temptation, but no base class is needed. There is no register function.

Question 5 (O3): Your lens passes isinstance(lens, Lens). What is the most important test still to run?

B. isinstance checks only that the methods exist, not what they do. A lens that loses a property or an edge still passes it. The PutGet test catches that, whatever the order the lens reads in.

Question 6 (O4): You give read_graph a Turtle export that holds two datasets. What must you add?

B. read_graph reads one dataset at a time. ddigraph.rdf.reader.datasets(graph) lists the ones an rdflib graph holds. A is not needed: the format comes from the extension. C is tempting, but a stream holds one dataset.

Module 13: Big, broken and untrusted files

Exercises

Exercise 1 (O1).

from pathlib import Path

from lxml import etree

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def question(path, **options):
    """Return the text of the HOURS question that ddigraph reads from a DDI-L file."""
    for chunk in iter_graph(path, **options):
        for node in chunk.nodes:
            if node.properties.get("ddi_id") == "q-hours":
                text = node.properties["question_text"]
                return text.value if isinstance(text, Text) else text


text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
old = "How many hours a week"
Path("hand-edited.xml").write_text(
    text.replace(old, "How many paid & unpaid hours a week"), encoding="utf-8"
)
print("Recovered:", repr(question("hand-edited.xml")))
try:
    question("hand-edited.xml", recover=False)
except etree.XMLSyntaxError as error:
    print("Strict:", error.msg)

Path("fixed.xml").write_text(
    text.replace(old, "How many paid &amp; unpaid hours a week"), encoding="utf-8"
)
print("Fixed:", repr(question("fixed.xml", recover=False)))
Recovered: 'How many paid  unpaid hours a week do you usually work in your main job?'
Strict: xmlParseEntityRef: no name, line 161, column 75
Fixed: 'How many paid & unpaid hours a week do you usually work in your main job?'

The recovering read loses the & without stopping. The strict read names the line, so you can fix the file at its source, where the fix belongs.

Exercise 2 (O2).

from pathlib import Path

from ddigraph import iter_graph

text = Path("tests/fixtures/lfs_cdi.xml").read_text(encoding="utf-8")
root = '<Wrapper xmlns="http://ddialliance.org/Specification/DDI-CDI/1.0/XMLSchema/">'
deep = "<extra>" * 260 + "</extra>" * 260
Path("deep-cdi.xml").write_text(text.replace(root, root + deep), encoding="utf-8")

try:
    list(iter_graph("deep-cdi.xml"))
except ValueError as error:
    print("Refused:", type(error).__name__)
nodes = sum(len(chunk.nodes) for chunk in iter_graph("deep-cdi.xml", huge_tree=True))
print("With huge_tree:", nodes, "nodes")
Refused: XMLLimitError
With huge_tree: 91 nodes

No. On a service that takes uploads, the next deep file may come from an attacker. Lift the limit for one trusted file, in one command, with DDIGRAPH_XML_HUGE_TREE=true or --tune xml_huge_tree=true, and keep it off everywhere else.

Exercise 3 (O3).

from pathlib import Path

from ddigraph import iter_graph
from ddigraph.utils.parsing import XMLLimitError

text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
body = text.split("\n", 1)[1]  # the file without its XML declaration

leak = '<!DOCTYPE FragmentInstance [<!ENTITY secret SYSTEM "file:///etc/passwd">]>\n'
leak += body.replace("What is your sex?", "&secret;")
Path("leak.xml").write_text(leak, encoding="utf-8")
for chunk in iter_graph("leak.xml"):
    for node in chunk.nodes:
        if node.properties.get("ddi_id") == "q-sex":
            print("Question text:", node.properties.get("question_text"))

entities = ['<!ENTITY e0 "ha">']
for n in range(1, 10):
    ten_copies = f"&e{n - 1};" * 10
    entities.append(f'<!ENTITY e{n} "{ten_copies}">')
bomb = "<!DOCTYPE FragmentInstance [" + "".join(entities) + "]>\n"
bomb += body.replace('"en">What is your sex?', '"&e9;">What is your sex?')
Path("bomb.xml").write_text(bomb, encoding="utf-8")
try:
    list(iter_graph("bomb.xml", huge_tree=True))
except XMLLimitError:
    print("Bomb refused, even with huge_tree: True")
Question text: None
Bomb refused, even with huge_tree: True

The external entity is never read, so the question has no text at all. The bomb is refused at any setting, because no trusted file needs it.

Exercise 4 (O4, O5).

from pathlib import Path

from ddigraph import iter_graph

text = Path("tests/fixtures/lfs_cdi.xml").read_text(encoding="utf-8")
start, end = text.index("<Organization>"), text.index("</Wrapper>")
version_1 = "<versionIdentifier>1</versionIdentifier>"
versions = "".join(
    text[start:end].replace(version_1, f"<versionIdentifier>{n}</versionIdentifier>")
    for n in range(1, 41)
)
# newline="\n" writes the same bytes on Windows, so the size is the same
Path("all-versions.xml").write_text(
    text[:start] + versions + text[end:], encoding="utf-8", newline="\n"
)

size = Path("all-versions.xml").stat().st_size
print(f"Size: {size / 2**20:.1f} MB")
chunks = nodes = 0
for chunk in iter_graph("all-versions.xml", chunk_size=300):
    chunks += 1
    nodes += len(chunk.nodes)
print("Chunks:", chunks, "- nodes:", nodes)

# A DDI-CDI file counts 8 times its size against the memory limit
for name, limit_mb in (("Default limit", 256), ("--memory-limit 16", 16)):
    print(f"{name}:", "rust" if size * 8 <= limit_mb * 2**20 else "lxml")
Size: 2.7 MB
Chunks: 25 - nodes: 3601
Default limit: rust
--memory-limit 16: lxml

Each version is a new object for ddigraph, since the version is part of its identity: 40 copies of 90 objects, and the Dataset node. The file counts as about 22 MB for the rust engine. That fits 256 MB easily, but not 16 MB, so auto would read it with lxml there. Either way, you get the same graph: only the speed and the memory change.

Quiz

Question 1 (O1): A recovering load of a hand-edited file finishes with no error. What do you know about its graph?

B. Recovering reads past an error by guessing, as the dropped & in Highest level of education training showed. A is the tempting one: the load finishes, so it looks fixed, but libxml2 cannot know what the author meant. Read the Recovered DDI XML parse error warnings, or load with --strict-parsing.

Question 2 (O2): A file from your own survey team fails with an XMLLimitError about depth. What do you do?

C. The limit guards against hostile files, and this one is yours. A works, but it opens every later upload to a depth bomb. B is wrong: the rust engine keeps the same limits and raises the same XMLLimitError. D throws away real content.

Question 3 (O3): Why does huge_tree not let an entity bomb through?

B. A bomb is well-formed XML, so A is wrong. Its danger is the expansion itself. huge_tree exists for big honest files, and an honest file never needs that expansion, so the limit on it stays.

Question 4 (O4): The compiled engine is installed. Which engine does auto pick for a 10 MB Codebook file with the default memory limit?

B. auto checks the engine's memory peak, the file's size times 64 for Codebook, against the limit. A is tempting: installed and faster are both true, but the peak does not fit. Raise the limit with --memory-limit 1024, and auto would pick rust.

Question 5 (O5): You stream a 2 GB file with chunk_size=500. When does your code get the first chunk?

B. ddigraph must see every element before it can settle each key and reference, so it reads the whole file first, sorting within the memory limit. A is the tempting picture of streaming, but it would give edges to nodes not yet known. D is wrong: past the limit, the sort uses temporary files.

Question 6 (O1, O4): You load a file with one bare & in it, with --engine rust. What happens?

B. The rust engine never recovers, whatever recover says. C is what auto does, not rust: only auto falls back to lxml for a file the engine refuses.

Module 14: Ground a language model in the graph

Exercises

Exercise 1 (O2).

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_codebook.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def linked(key, rel_type):
    """Return the nodes that `key` reaches by one `rel_type` edge."""
    return [nodes[end] for start, kind, end in edges if start == key and kind == rel_type]


lines = ["The codebook has these variables. Do not invent variables that are not listed."]
for key, node in nodes.items():
    if node.label != "Variable":
        continue
    line = f"- {plain(node.properties['name'])}: {plain(node.properties['label'])}"
    if "question_text" in node.properties:
        line += f'; asks "{plain(node.properties["question_text"])}"'
    if answers := linked(key, "USES_CATEGORY"):
        codes = [f"{c.properties['code']} = {plain(c.properties['label'])}" for c in answers]
        line += f"; answers: {', '.join(codes)}"
    if concepts := linked(key, "USES_CONCEPT"):
        line += f"; concept: {', '.join(plain(c.properties['label']) for c in concepts)}"
    lines.append(line)
print("\n".join(lines))
The codebook has these variables. Do not invent variables that are not listed.
- SEX: Sex of the person; asks "What is your sex?"; answers: 1 = Male, 2 = Female; concept: Demographic characteristics
- AGE: Age in completed years; asks "What was your age on your last birthday?"; concept: Demographic characteristics
- AGEGRP: Age group; answers: 1 = 15-24, 2 = 25-34, 3 = 35-44, 4 = 45-54, 5 = 55-64, 6 = 65 and over; concept: Demographic characteristics
- REGION: Region of residence; asks "In which region do you live?"; answers: 1 = Capital region, 2 = North, 3 = South, 4 = East, 5 = West; concept: Place of residence
- EDUC: Highest level of education; asks "What is the highest level of education you have completed?"; answers: 1 = Primary or less (ISCED 0-1), 2 = Lower secondary (ISCED 2), 3 = Upper secondary (ISCED 3), 4 = Post-secondary non-tertiary (ISCED 4), 5 = Tertiary (ISCED 5-8); concept: Educational attainment
- ILOSTAT: Labour force status (ILO); answers: 1 = Employed, 2 = Unemployed, 3 = Not in the labour force; concept: Labour market status
- HOURS: Usual weekly hours in the main job; asks "How many hours a week do you usually work in your main job?"; concept: Working time

One line per variable, built from its edges, says more than a list of every node. Each line also holds what a data user needs to read the data file: the code behind each answer. AGE and HOURS have no answers line, because they are numbers, not codes. AGEGRP and ILOSTAT have no question, because they are derived from other variables. The pack says so by leaving the line out, not by inventing.

Exercise 2 (O3).

from ddigraph import iter_graph, urn
from ddigraph.ir.model import Text

STOP_WORDS = {"what", "which", "does", "mean", "where", "from", "have", "this", "that", "with"}


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


def name_of(node):
    """Name a node by its name and label, or by its URN when it has neither."""
    name = plain(node.properties.get("name"))
    label = plain(node.properties.get("label"))
    if name and label and name != label:
        return f'{name} "{label}"'
    return name or label or urn.text(node.identity)


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        if node.label != "Dataset":
            nodes[node.key] = node
    for edge in chunk.relationships:
        if edge.start in nodes:
            edges.append((edge.start, edge.type, edge.end))


def relevant(question, limit=10):
    """Return the keys of the nodes whose text shares a topic word with the question."""
    words = {word.lower().strip("?.,") for word in question.split() if len(word) > 3}
    words -= STOP_WORDS
    hits = []
    for key, node in nodes.items():
        haystack = " ".join(
            plain(value) for value in node.properties.values() if isinstance(value, (str, Text))
        ).lower()
        score = sum(1 for word in words if word in haystack)
        if score:
            hits.append((score, key))
    hits.sort(key=lambda item: -item[0])
    return [key for _score, key in hits[:limit]]


hits = relevant("What does ILOSTAT mean and where does it come from?")
for start, rel_type, end in edges:
    if start in hits or end in hits:
        print(
            f"- {nodes[start].label} {name_of(nodes[start])} --{rel_type}--> "
            f"{nodes[end].label} {name_of(nodes[end])}"
        )
- Variable ILOSTAT "Labour force status (ILO)" --IN_UNIVERSE--> Universe Persons aged 15 and over living in private households
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem LOOK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem WORK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem AVAIL
- Variable ILOSTAT "Labour force status (ILO)" --USES_CODELIST--> CodeList Labour force status (ILO)
- Variable ILOSTAT "Labour force status (ILO)" --USES_CONCEPT--> Concept Labour market status

The only hit now is ILOSTAT, and its neighbours bring what the user asked: the three questions it comes from, its code list, its concept and its universe. The lines about other questions are gone, because no hit touches them. A better score made a smaller and more useful pack.

Exercise 3 (O4).

from types import SimpleNamespace


def ask(client, pack, question):
    """Ask a question about the survey; return the text blocks of the reply."""
    response = client.beta.messages.create(
        model="claude-opus-5-5",
        max_tokens=16000,
        betas=["server-side-fallback-2026-07-01"],
        fallbacks="default",
        system=(
            "Answer questions about this survey using only the structure below. "
            "If the answer is not there, say so rather than guessing.\n\n" + pack
        ),
        messages=[{"role": "user", "content": question}],
    )
    return "".join(block.text for block in response.content if block.type == "text")


class StandInMessages:
    """Records the request, and replies as the API can: thinking first, then text."""

    def create(self, **request):
        self.request = request
        return SimpleNamespace(
            content=[
                SimpleNamespace(type="thinking", thinking=""),
                SimpleNamespace(type="text", text="WORK, LOOK and AVAIL use the Yes or no list."),
            ]
        )


client = SimpleNamespace(beta=SimpleNamespace(messages=StandInMessages()))
pack = "\n".join(
    [
        "- QuestionItem WORK --USES_CODELIST--> CodeList Yes or no",
        "- QuestionItem LOOK --USES_CODELIST--> CodeList Yes or no",
        "- QuestionItem AVAIL --USES_CODELIST--> CodeList Yes or no",
    ]
)
answer = ask(client, pack, "Which questions use the Yes or no list?")

sent = client.beta.messages.request
print("Model:", sent["model"])
print("System ends with:", sent["system"].splitlines()[-1])
print("Answer:", answer)
Model: claude-opus-5-5
System ends with: - QuestionItem AVAIL --USES_CODELIST--> CodeList Yes or no
Answer: WORK, LOOK and AVAIL use the Yes or no list.

response.content[0] here is the thinking block, which has no text. Reading by block.type skips it. With a real key, pass anthropic.Anthropic() as client, and nothing else changes.

Exercise 4 (O2).

from ddigraph import iter_graph, urn
from ddigraph.ir.model import Text

WIRING = {"Sequence", "QuestionConstruct", "IfThenElse"}
FLOW = {"HAS_CONSTRUCT", "THEN", "ELSE"}


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


def name_of(node):
    """Name a node by its name and label, or by its URN when it has neither."""
    name = plain(node.properties.get("name"))
    label = plain(node.properties.get("label"))
    if name and label and name != label:
        return f'{name} "{label}"'
    return name or label or urn.text(node.identity)


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        if node.label != "Dataset":
            nodes[node.key] = node
    for edge in chunk.relationships:
        if edge.start in nodes:
            edges.append((edge.start, edge.type, edge.end))


def questions_under(key):
    """Follow the flow (HAS_CONSTRUCT, THEN, ELSE) down to the questions."""
    found = []
    for start, rel_type, end in edges:
        if start == key and rel_type in FLOW:
            found += questions_under(end)
        elif start == key and rel_type == "REFERENCES_QUESTION":
            found.append(end)
    return found


items = {key: node for key, node in nodes.items() if node.label not in WIRING}
lines = ["The survey contains these items. Do not invent items that are not listed."]
for key, node in sorted(items.items(), key=lambda item: item[1].label):
    text = node.properties.get("question_text")
    lines.append(f"- {node.label}: {name_of(node)}" + (f' — asks "{plain(text)}"' if text else ""))

lines.append("")
lines.append("Links between them:")
for start, rel_type, end in edges:
    if start in items and end in items:
        lines.append(
            f"- {nodes[start].label} {name_of(nodes[start])} --{rel_type}--> "
            f"{nodes[end].label} {name_of(nodes[end])}"
        )
for key, node in items.items():
    if node.label == "Instrument":
        for question in questions_under(key):
            lines.append(
                f"- Instrument {name_of(node)} --ASKS--> QuestionItem {name_of(nodes[question])}"
            )

pack = "\n".join(lines)
for line in lines:
    if "--ASKS-->" in line:
        print(line)
print(len(pack), "characters")
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem SEX
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem AGE
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem REGION
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem EDUC
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem WORK
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem LOOK
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem AVAIL
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem HOURS
11225 characters

The pack keeps every fact a reader asks about, and it is smaller: 11,225 characters instead of 12,264. Every line costs money on every request, so a line that nobody asks about never earns its cost. ASKS is a name made up for the pack, not a relationship type of the graph: the model needs a clear word, not the schema.

One fact is lost, though: the routing. HOURS is asked only of people who worked last week, and LOOK and AVAIL only of people who did not. The universe of the variable HOURS, "Employed persons aged 15 and over", still says part of it. If your users ask who answers which question, keep the IfThenElse and its label in the pack.

Quiz

Question 1 (O1): Why is a plausible but ungrounded answer about a survey worse than no answer?

B. A model that has read many surveys writes answer options that look right. That is the danger: a wrong answer that looks wrong gets caught, a plausible one does not. A is too strong: the model is often close, which is exactly why its errors slip through.

Question 2 (O2): Your pack lists every node of a survey, but no edges. Which question can it not answer?

B. Which code list a question uses is a link between two nodes, USES_CODELIST. A list of nodes shows that the question and the code list exist, but not that one uses the other. The other three ask about a single node, so the list alone answers them.

Question 3 (O3): Keyword retrieval returns the variable ILOSTAT for the question \"Where does ILOSTAT come from?\". Why add its neighbours before you send it?

B. The answer, the questions WORK, LOOK and AVAIL, is in the nodes one edge from the variable, and no word of the question matches them. One step along the edges brings them in. D overstates it: neighbours complete a hit, they do not replace it.

Question 4 (O4): Your code prints response.content[0].text. It worked yesterday and fails today with an AttributeError. What is the likely cause?

B. response.content is a list of blocks of several types, and the first one is not always text. Loop over the blocks and keep those whose type is "text". D is the tempting picture, but content is a list, never a string.

Question 5 (O4): Why does the system prompt say \"If the answer is not there, say so rather than guessing\"?

B. The pack limits what the model should use, and this sentence says what to do at that limit. A is wrong: the API never checks your pack. D mixes it up with fallbacks="default", which is about a model that declines a request.

Module 15: Give a model tools over the graph

Exercises

Exercise 1 (O1, O2).

import json

from ddigraph import iter_graph
from ddigraph.ir.model import Text

CONCEPT_TOOL = {
    "name": "find_questions_about",
    "description": (
        "Find the variables, and the questions behind them, that measure a "
        "concept. Call this when the user asks which questions or variables "
        "cover a topic or concept."
    ),
    "input_schema": {
        "type": "object",
        "properties": {"concept": {"type": "string", "description": "The concept name."}},
        "required": ["concept"],
    },
}


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_codebook.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def find_questions_about(concept: str) -> dict:
    """The tool's implementation: the variables that use a concept."""
    found = []
    matched = False
    for start, rel_type, end in edges:
        if rel_type != "USES_CONCEPT":
            continue
        if concept.lower() != plain(nodes[end].properties.get("label", "")).lower():
            continue
        matched = True
        variable = nodes[start]
        found.append(
            {
                "variable": plain(variable.properties.get("name")),
                "question": plain(variable.properties.get("question_text")),
            }
        )
    if not matched:
        return {"error": f"No concept matching {concept!r}"}
    return {"concept": concept, "variables": found}


print(CONCEPT_TOOL["name"])
print(json.dumps(find_questions_about("demographic characteristics"), indent=2))
print(json.dumps(find_questions_about("health")))
find_questions_about
{
  "concept": "demographic characteristics",
  "variables": [
    {
      "variable": "AGEGRP",
      "question": null
    },
    {
      "variable": "AGE",
      "question": "What was your age on your last birthday?"
    },
    {
      "variable": "SEX",
      "question": "What is your sex?"
    }
  ]
}
{"error": "No concept matching 'health'"}

AGEGRP has no question: it is derived from AGE. The tool says null, and the model can say so, rather than invent a question. The survey has no health questions, so the second call returns an error.

The tool loops over every USES_CONCEPT edge, and it does not stop at the first concept that matches. That matters here. DDI-Codebook repeats the concept's text in each variable, so this graph holds three "Demographic characteristics" nodes, one for each of SEX, AGE and AGEGRP. A tool that stopped at the first one would find SEX alone.

Keep it a separate tool rather than a mode of get_answer_options. The model chooses by reading descriptions, and "returns answer options or questions, depending on which argument you pass" describes nothing well. Two tools with clear edges beat one tool with a mode flag.

Exercise 2 (O3).

import json
from types import SimpleNamespace

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def follow(start, rel_type):
    """Every node reachable from `start` by one `rel_type` edge."""
    return [end for s, t, end in edges if s == start and t == rel_type]


def get_answer_options(question: str) -> dict:
    """The tool's implementation. Its return value goes back to the model."""
    for key, node in nodes.items():
        if node.label != "QuestionItem":
            continue
        text = plain(node.properties.get("question_text", ""))
        if question.lower() not in text.lower():
            continue
        options = []
        for code_list in follow(key, "USES_CODELIST"):
            for owner in [code_list, *follow(code_list, "CONTAINS")]:
                for category in follow(owner, "HAS_CATEGORY"):
                    options.append(plain(nodes[category].properties.get("label")))
        return {"question": text, "options": options}
    return {"error": f"No question matching {question!r}"}


TOOLS = {"get_answer_options": get_answer_options}
reply = [
    SimpleNamespace(
        type="tool_use", id="toolu_01", name="get_answer_options", input={"question": "education"}
    ),
    SimpleNamespace(
        type="tool_use", id="toolu_02", name="get_answer_options", input={"question": "income"}
    ),
]

results = []
for block in reply:
    if block.type == "tool_use":
        output = TOOLS[block.name](**block.input)
        results.append(
            {
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": json.dumps(output),
                "is_error": "error" in output,
            }
        )
turns = [{"role": "user", "content": results}]

print("Turns to send:", len(turns))
for result in turns[0]["content"]:
    print(result["tool_use_id"], f"is_error={result['is_error']}")
Turns to send: 1
toolu_01 is_error=False
toolu_02 is_error=True

All the results of one reply go back in a single user turn. Splitting them over several turns teaches the model to stop asking for tools in parallel. is_error keeps the failed lookup from reading as a fact.

Exercise 3 (O2).

import re
from pathlib import Path

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


# A code in the DDI 3.1 style: no URN, agency, ID or version of its own
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
old_style = re.sub(
    r'<l:Code isUniversallyUnique="true">\s*<r:URN>.*?</r:Version>', "<l:Code>", text
)
Path("old-codes.xml").write_text(old_style, encoding="utf-8")

nodes, edges = {}, []
for chunk in iter_graph("old-codes.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def follow(start, rel_type):
    """Every node reachable from `start` by one `rel_type` edge."""
    return [end for s, t, end in edges if s == start and t == rel_type]


code_list = next(
    key
    for key, node in nodes.items()
    if node.label == "CodeList" and plain(node.properties["label"]) == "Yes or no"
)
through_codes = [
    plain(nodes[c].properties["label"])
    for code in follow(code_list, "CONTAINS")
    for c in follow(code, "HAS_CATEGORY")
]
zero_or_one = [
    plain(nodes[c].properties["label"])
    for owner in [code_list, *follow(code_list, "CONTAINS")]
    for c in follow(owner, "HAS_CATEGORY")
]
print("Through the codes:", through_codes)
print("CONTAINS zero or one time:", zero_or_one)
Through the codes: []
CONTAINS zero or one time: ['Yes', 'No']

With no ID, a code is not a node of its own, so the category hangs off the code list, and the walk through the codes finds nothing. Worse, a tool built on it would return {"options": []}, which the model reads as "no answers". Following CONTAINS zero or one time covers both shapes. The copy also fails the DDI 3.3 XSD, which requires an ID on each code: it stands in for an older file, not for a valid 3.3 one.

Exercise 4 (O4).

import json
from pathlib import Path

from ddigraph import iter_graph
from ddigraph.ir.model import Text

variables = "".join(
    f'<var ID="v{n}" name="Q{n}"><labl>Question {n}</labl>'
    "<catgry><catValu>1</catValu><labl>Yes</labl></catgry>"
    "<catgry><catValu>2</catValu><labl>No</labl></catgry></var>"
    for n in range(1, 3001)
)
Path("big.xml").write_text(
    f"<codeBook><dataDscr>{variables}</dataDscr></codeBook>", encoding="utf-8"
)


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, answers = {}, {}
for chunk in iter_graph("big.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        if edge.type == "USES_CATEGORY":
            answers.setdefault(edge.start, []).append(plain(nodes[edge.end].properties["label"]))

lines = ["The codebook has these variables. Do not invent variables that are not listed."]
for key, options in answers.items():
    lines.append(f"- {plain(nodes[key].properties['label'])}: {', '.join(options)}")
pack = "\n".join(lines)

first = next(iter(answers))
result = json.dumps(
    {"variable": plain(nodes[first].properties["label"]), "options": answers[first]}
)

print("Full pack:", len(pack), "characters, about", len(pack) // 4, "tokens per request")
print("One tool result:", len(result), "characters")
print("Tool calls for the cost of one pack:", len(pack) // len(result))
Full pack: 73971 characters, about 18492 tokens per request
One tool result: 55 characters
Tool calls for the cost of one pack: 1344

For this catalogue, a tool wins by far: one full pack costs as much as more than a thousand lookups, and you pay for it on every request. For the one questionnaire of Module 14, a pack is still a fair choice: about 3,000 tokens, in one request, with no round trip. Measure before you choose, and keep a one-line pack that tells the model what the tools can find.

Quiz

Question 1 (O1): Why is the description the most important part of a tool definition?

B. The model chooses tools by their descriptions. A description that says only what the function does leaves the model guessing when to use it. D is the input schema's job, not the description's.

Question 2 (O2): Your tool finds no question matching the user's words. Why return an error rather than {\"options\": []}?

B. An empty result is a claim about the survey. An error is a claim about the lookup, which is the truth here. C is wrong: the API does not rerun your tools; the model may choose to call again.

Question 3 (O3): You send a tool_result whose tool_use_id does not match the id of the call. What goes wrong?

B. tool_use_id is how a result finds its call, and every tool_use block needs its result. A is the tempting shortcut: with two calls in one reply, order alone could swap two answers.

Question 4 (O3): After the first reply, you append only the reply's text to messages, then send the tool_result. Why does the next request fail?

B. Append the whole response.content. The tool_use block in it is what the tool_result answers. D sounds plausible, but you do send tools on every request anyway; the missing piece is the call.

Question 5 (O4): A survey team asks a fixed set of five questions about one small instrument, every day. Pack or tool?

B. A small graph and known questions are the case a pack fits best: one round trip, nothing to call. A tool earns its extra round trip when the graph is large or the questions are open. C is the mistake Module 14 began with.

Module 16: Capstone projects

Exercises

Exercise 1 (O1, O2).

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

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

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.

Exercise 4 (O1, O2).

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

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.

Exercise 6 (O4).

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.

Exercise 7 (O1, O2).

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

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

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:

  1. The file passes the XSD and the CDI shapes, and all 130 references resolve.
  2. The XKOS export passes the CDI shapes, and holds 2 correspondences with 15 concept pairs.
  3. 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 5A maps to two levels, which users must know.

Quiz

Question 1 (O1): Why does the plan put the checks before the load?

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?

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?

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?

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?

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.

Module 17: Neo4j in depth

Exercises

Exercise 1 (O1, O2).

from pathlib import Path

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings

ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m17-codebook", replace=True)
survey = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
survey = survey.replace("example.nso", "m17.example.nso")
Path("m17-survey.xml").write_text(survey, encoding="utf-8")
ddigraph.load("m17-survey.xml", dataset_id="m17-survey", replace=True)

CODEBOOK = """
MATCH (v:Variable {dataset_id: 'm17-codebook'})
OPTIONAL MATCH (v)-[:IN_UNIVERSE]->(u:Universe)
RETURN v.name AS variable, u.label AS universe
ORDER BY variable
"""
LIFECYCLE = """
MATCH (v:Variable)-[:IN_DATASET]->(:Dataset {dataset_id: 'm17-survey'})
OPTIONAL MATCH (v)-[:IN_UNIVERSE]->(u:Universe)
RETURN v.name AS variable, u.label AS universe
ORDER BY variable
"""

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    for title, query in [("Codebook:", CODEBOOK), ("DDI-L:", LIFECYCLE)]:
        print(title)
        for record in driver.execute_query(query).records:
            print(" | ".join(str(value) for value in record.values()))
Codebook:
AGE | None
AGEGRP | None
EDUC | None
HOURS | Employed persons aged 15 and over
ILOSTAT | None
REGION | None
SEX | None
DDI-L:
AGE | Persons aged 15 and over living in private households
AGEGRP | Persons aged 15 and over living in private households
EDUC | Persons aged 15 and over living in private households
HOURS | Employed persons aged 15 and over
ILOSTAT | Persons aged 15 and over living in private households
REGION | Persons aged 15 and over living in private households
SEX | Persons aged 15 and over living in private households

In the Codebook file, only HOURS has an IN_UNIVERSE edge. A Codebook variable states a universe only where it narrows the study's. The other six take the study's universe, persons aged 15 and over living in private households. That universe is a node too, but no edge reaches it, so a query cannot follow one. In DDI-L, each variable refers to its universe, so the query finds all seven. The dataset_id index makes the first MATCH one lookup. The OPTIONAL MATCH keeps a variable that has no universe.

Exercise 2 (O3).

cp tests/fixtures/lfs_codebook.xml m17-edit-store.xml
ddigraph load m17-edit-store.xml --store my-store | tail -n 1
sed 's|<labl>Tertiary (ISCED 5-8)</labl></catgry>|&<catgry missing="Y"><catValu>9</catValu><labl>Not stated</labl></catgry>|' \
    tests/fixtures/lfs_codebook.xml > m17-edit-store.xml
ddigraph load m17-edit-store.xml --store my-store | tail -n 1
ddigraph repair m17-edit-store --store my-store --dry-run
Store: generation=1, delta_from=None, nodes_removed=0, relationships_removed=0
Store: generation=2, delta_from=1, nodes_removed=0, relationships_removed=0
Dataset 'm17-edit-store' against generation 2: 0 buckets differed; would write nodes: 0 added, 0 removed, 0 changed; relationships: 0 added, 0 removed

In sed, & stands for the text it matched, so the new category goes right after Tertiary, on the same line. No other node moves. missing="Y" marks a code for a missing answer. The second load is a delta from generation 1: it wrote only the new category and its edge from EDUC. Neo4j then holds HEAD, so the dry run finds no bucket to fix.

Exercise 3 (O4).

import csv
from collections import Counter

from ddigraph import export

export("tests/fixtures/lfs_codebook.xml", "codebook-import", format="neo4j-import")

with open("codebook-import/relationships.csv", newline="", encoding="utf-8") as f:
    types = Counter(row[":TYPE"] for row in csv.DictReader(f))
for name, count in sorted(types.items(), key=lambda item: (-item[1], item[0])):
    print(name, count)
print("total", sum(types.values()))
IN_DATASET 79
USES_CATEGORY 21
IN_FILE 7
USES_CONCEPT 7
ASKED_AS 5
DESCRIBES 3
ASSOCIATED_WITH 2
CONTRIBUTES_TO 1
COVERS 1
IN_UNIVERSE 1
total 127

Each of the 80 nodes but the Dataset node has an IN_DATASET row, so 79. The other 48 are the file's own edges, the 48 the export reported: 21 from the variables to their categories, 7 to the data file, and so on. neo4j-admin imports exactly these rows.

Exercise 4 (O5).

mkdir -p aura-test && cd aura-test
printf 'NEO4J_URI=neo4j+s://abcd1234.databases.neo4j.io\nNEO4J_USERNAME=neo4j\nNEO4J_PASSWORD=change-me\n' > .env
unset DDIGRAPH_NEO4J_URI
python -c "from ddigraph.config import Settings; print(Settings().neo4j_uri)"
DDIGRAPH_NEO4J_URI=bolt://localhost:7687 python -c "from ddigraph.config import Settings; print(Settings().neo4j_uri)"
neo4j+s://abcd1234.databases.neo4j.io
bolt://localhost:7687

A DDIGRAPH_ variable wins over the bare NEO4J_ names of the .env file. A stale variable in your shell can point ddigraph at the wrong server.

Quiz

Question 1 (O1): Why does ddigraph bootstrap put a uniqueness constraint on key?

B. A load runs MERGE on key for every node. The constraint stops duplicates, and the index behind it makes each lookup fast. A is tempting, but two datasets may share a node: it then has an IN_DATASET edge to each.

Question 2 (O1): A search with WHERE q.question_text CONTAINS 'work' is slow on a large catalogue. Why?

C. ddigraph indexes keys, IDs, URNs and short typed properties, not free text. For text search, make a full-text index yourself. Then remember that bootstrap --drop-legacy would drop it.

Question 3 (O2): On a DDI 3.3 file, MATCH (cl:CodeList)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat) finds the categories. Why not write (cl:CodeList)-[:HAS_CATEGORY]->(cat)?

B. The shortcut finds nothing when codes have IDs. *0..1 also covers a code with no ID, as in DDI 3.1, where the edge starts at the code list. So C is wrong: the shorter pattern misses most files.

Question 4 (O2): You load questions.xml. Its questions use the Yes or no code list, which lives in common-codes.xml. What does Neo4j hold for that code list before you load common-codes.xml?

D. The edge is kept and ends at a stub. Loading common-codes.xml later fills the stub in place, so the edge needs no rewrite. A is what you might expect from a strict parser, but ddigraph keeps the reference.

Question 5 (O3): You deleted a variable from a file and reloaded it with a plain ddigraph load (no --store, no --replace). What happens to the variable in Neo4j?

A. Only --replace, which purges first, or a load through the store, which sends the delta, removes what the file dropped. The store's delta also removes it in one small write, not a whole reload.

Question 6 (O3): ddigraph repair DATASET --dry-run reports 3 buckets differed. What does it compare?

B. Repair reads the store, not the file. It hashes the same buckets on both sides, so it only reads the few that differ. D is store diff, which never looks at Neo4j.

Question 7 (O4): Why does a bulk import on Community Edition use a blue/green switch?

B. You import green while blue serves, set green as the default database, and restart. Blue stays on disk for a rollback. D is backwards: Aura gives you no neo4j-admin at all.

Question 8 (O5): Your folder holds Aura's .env file, but ddigraph load still connects to bolt://localhost:7687. What is the likely cause?

C. ddigraph reads NEO4J_URI and the other bare names, but a DDIGRAPH_ variable wins. Unset it. B is wrong: the neo4j+s:// scheme already turns TLS on.

Module 18: NetworkX

Exercises

Exercise 1 (O1).

from collections import Counter

from ddigraph.backends.networkx import to_networkx

G = to_networkx("tests/fixtures/lfs_cdi.xml")

nodes = Counter(label for _, data in G.nodes(data=True) for label in data["node_labels"])
edges = Counter(rel_type for _, _, (rel_type, _ordinal) in G.edges(keys=True))
for label, count in sorted(nodes.items()):
    print(f"{label}: {count}")
for rel_type, count in sorted(edges.items()):
    print(f"{rel_type}: {count}")
CDIAgent: 1
CDICategory: 21
CDICode: 21
CDICodeList: 5
CDIConcept: 5
CDIConceptSystem: 1
CDIGenericEntity: 21
CDIInstanceVariable: 7
CDIUnitType: 1
CDIValueDomain: 7
Dataset: 1
DENOTES: 21
HAS_CODE: 21
HAS_CONCEPT: 5
IS_DEFINED_BY: 5
MEASURES: 7
TAKES_SUBSTANTIVE_VALUES_FROM: 7
TAKES_VALUES_FROM: 5
USES: 21

Each node's types are in node_labels, and each edge's type is the first half of its key. There are 7 variables and 7 value domains, but only 5 code lists: AGE and HOURS take a number, so their value domains need no code list. That is why TAKES_VALUES_FROM counts 5, not 7.

Exercise 2 (O2).

from ddigraph.backends.networkx import to_networkx

G = to_networkx("tests/fixtures/lfs_correspondence.xml")

for node, degree in sorted(G.degree(), key=lambda pair: (-pair[1], pair[0])):
    if degree >= 5:
        data = G.nodes[node]
        print(degree, data["node_labels"][0], data["identity"])
13 CDICorrespondenceTable urn:ddi:example.nso:isced1997-2011:1
11 CDIStatisticalClassification urn:ddi:example.nso:isced2011:1
10 CDIStatisticalClassification urn:ddi:example.nso:isced1997:1
10 CDIGenericEntity urn:ddi:example.nso:isced2011-levels:1
9 CDIGenericEntity urn:ddi:example.nso:isced1997-levels:1
8 CDIConceptSystemCorrespondence urn:ddi:example.nso:age-lfs-broad:1
7 CDIConceptSystem urn:ddi:example.nso:age-lfs:1
5 CDIConceptSystem urn:ddi:example.nso:age-broad:1

A correspondence table is a hub by design: it links two classifications and holds the maps between them. Here it holds 9 maps from ISCED 1997 to ISCED 2011: one for each level, and two for 5A, which maps to both 6 and 7. Each classification is a hub too, since it holds all its levels.

Exercise 3 (O3).

import networkx as nx

from ddigraph.backends.networkx import to_networkx

G = to_networkx("tests/fixtures/lfs_lifecycle.xml")


def name(node):
    data = G.nodes[node]
    text = data.get("name") or data.get("label") or data.get("value") or ""
    return f"{data['node_labels'][0]} {text}".strip()


questionnaire = next(n for n in G if name(n) == "Instrument LFS questionnaire")
yes = next(n for n in G if name(n) == "Category Yes")
print(nx.has_path(G, yes, questionnaire))
path = nx.shortest_path(G.reverse(), yes, questionnaire)
print(" <- ".join(name(n) for n in path))
False
Category Yes <- Code 1 <- CodeList Yes or no <- QuestionItem WORK <- QuestionConstruct WORK <- Sequence Main sequence <- Instrument LFS questionnaire

DDI references point down, from the questionnaire towards the categories. To answer "which questions offer the answer Yes?", walk the edges backwards: G.reverse() gives a graph with every arrow turned round.

Exercise 4 (O4).

import networkx as nx

from ddigraph import export
from ddigraph.backends.networkx import to_networkx

export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl")  # Turtle is the default

G = to_networkx("tests/fixtures/lfs_lifecycle.xml")
G = to_networkx("survey.ttl", graph=G)

components = nx.number_weakly_connected_components(G)
print(
    f"{G.number_of_nodes()} nodes, {G.number_of_edges()} edges, "
    f"weakly connected components: {components}"
)
87 nodes, 108 edges, weakly connected components: 1

The RDF export keeps each node's key, and holds the same dataset, so every node and edge merges with its twin. The whole survey is one component: the questionnaire leads to the questions, and every variable, code list, concept and universe hangs off a question or a variable.

Exercise 5 (O5).

from collections import Counter

import networkx as nx

from ddigraph.backends import flatten
from ddigraph.backends.networkx import to_networkx

G = to_networkx("tests/fixtures/lfs_correspondence.xml")

flat = nx.MultiDiGraph()
for node, data in G.nodes(data=True):
    kept = {k: flatten(v) for k, v in data.items() if k not in ("memberships", "provenance")}
    flat.add_node(node, **kept)
for start, end, (rel_type, ordinal), data in G.edges(keys=True, data=True):
    order = {} if ordinal is None else {"ordinal": ordinal}
    flat.add_edge(start, end, type=rel_type, **order, **data)
nx.write_graphml(flat, "correspondence.graphml")

back = nx.read_graphml("correspondence.graphml", force_multigraph=True)
for rel_type, count in sorted(Counter(d["type"] for _, _, d in back.edges(data=True)).items()):
    print(rel_type, count)
DENOTES 17
GROUPS 17
HAS_CLASSIFICATION_ITEM 17
HAS_CONCEPT 10
HAS_CONCEPT_MAP 15
HAS_SOURCE 16
HAS_TARGET 16
IS_SUCCESSOR_OF 1
MAPS 2
MAPS_TO 2
USES 17

The type attribute is the first half of the old edge key. Without the copy, write_graphml would fail on the first list it met.

Quiz

Question 1 (O1): In the graph to_networkx returns, what is a node's ID?

C. ddigraph uses the node's key everywhere, so a NetworkX ID matches the key in Neo4j or pandas. B is tempting, but many nodes have no URN: a Codebook node, for one. The URN is in the urn attribute when there is one.

Question 2 (O1): Why does a node's dataset appear in its memberships attribute, and not as an IN_DATASET edge?

B. Membership is data about the node, so it sits on the node. This is also why many Codebook nodes form components of one: nothing but their dataset links to them.

Question 3 (O2): Which node is likely to have the highest betweenness centrality in a survey's graph?

A. Betweenness counts how often a node lies on the shortest paths between others. In the sample survey, the universe of persons aged 15 and over comes first. D is tempting, since every node belongs to the dataset, but membership is not an edge here. In the DDI-L file, the Dataset node only links to the questionnaire.

Question 4 (O3): In the survey's DDI-L file, nx.has_path(G, questionnaire, unemployed) is False, but the undirected view finds a path. Why?

B. Each edge goes one way. A path along the arrows must follow the references as written. The undirected view answers a looser question: are the two related at all?

Question 5 (O4): You load the same file twice into one graph, under two dataset IDs. The survey's DDI-L file gives 88 nodes; its Codebook file gives 160. Why the difference?

B. Nodes merge by key, and the key comes from the identity. The only new DDI-L node is the second Dataset node.

Question 6 (O5): nx.write_graphml(G, ...) fails on the graph to_networkx returns. What do you do?

D. GraphML only stores plain values. A is wrong twice: json.dump cannot take a graph, and node-link JSON still needs msgspec.to_builtins for the memberships.

Module 19: pandas

Exercises

Exercise 1 (O1, O2).

from ddigraph.backends.pandas import to_dataframes

frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
variables = frames.of("Variable")[["key", "name"]]

placed = variables.merge(frames.memberships, on="key").sort_values("line")
print(placed[["name", "dataset_id", "flavor", "line"]].to_string(index=False))
   name   dataset_id   flavor line
    SEX lfs_codebook codebook   43
    AGE lfs_codebook codebook   52
 AGEGRP lfs_codebook codebook   60
 REGION lfs_codebook codebook   73
   EDUC lfs_codebook codebook   85
ILOSTAT lfs_codebook codebook   97
  HOURS lfs_codebook codebook  107

Both tables have a key column, so on="key" joins them. Where a node comes from is in memberships, not in nodes, since one node can come from several files. The line is where the variable starts in the file, so sorting on it gives the file's order.

Exercise 2 (O3).

from ddigraph.backends.pandas import to_dataframes

frames = to_dataframes("tests/fixtures/lfs_cdi.xml")
rels = frames.relationships
nodes = frames.nodes[["key", "name", "value"]]


def edges(rel_type, start, end):
    # The edges of one type, with their ends named
    found = rels[rels["type"] == rel_type]
    return found[["start", "end"]].rename(columns={"start": start, "end": end})


lists = frames.of("CDICodeList")
ilo = lists.loc[lists["name"] == "Labour force status (ILO)", ["key"]]
table = (
    ilo.merge(edges("HAS_CODE", "key", "code"), on="key")
    .merge(edges("USES", "code", "notation"), on="code")
    .merge(edges("DENOTES", "code", "category"), on="code")
    .merge(nodes[["key", "value"]], left_on="notation", right_on="key")
    .merge(nodes[["key", "name"]], left_on="category", right_on="key")
    .sort_values("value")
)
print(table[["value", "name"]].to_string(index=False))
value                    name
    1                Employed
    2              Unemployed
    3 Not in the labour force

Four merges walk the path: the list to its codes, each code to its notation and to its category, then the two ends to the nodes that hold the value and the name. The table starts from one row, the code list, so it keeps only that list's codes. The three categories cover everyone aged 15 and over: each person is in exactly one.

Exercise 3 (O3, O4).

from pathlib import Path

from ddigraph.backends.pandas import to_dataframes

frames = to_dataframes("tests/fixtures/lfs_lifecycle.xml")
variables = frames.of("Variable")[["key", "name", "label"]]
concepts = frames.of("Concept")[["key", "label"]]
uses = frames.relationships[frames.relationships["type"] == "USES_CONCEPT"]

table = (
    uses.merge(variables, left_on="start", right_on="key")
    .merge(concepts, left_on="end", right_on="key", suffixes=("", "_concept"))
    .sort_values("name")
)
table[["name", "label", "label_concept"]].to_csv("variables.csv", index=False)
print(Path("variables.csv").read_text(encoding="utf-8"), end="")
name,label,label_concept
AGE,Age in completed years,Demographic characteristics
AGEGRP,Age group,Demographic characteristics
EDUC,Highest level of education,Educational attainment
HOURS,Usual weekly hours in the main job,Working time
ILOSTAT,Labour force status (ILO),Labour market status
REGION,Region of residence,Place of residence
SEX,Sex of the person,Demographic characteristics

In DDI-Lifecycle, questions use concepts too. The merge with variables keeps only the edges that start at a variable. Three variables share the one concept node "Demographic characteristics". Keeping only the columns a reader needs makes a table someone can check by eye. The keys stay out: they join the tables, but mean nothing to a person.

Quiz

Question 1 (O1): Why does to_dataframes give three tables instead of one?

B. A graph does not fit in one rectangle. The three tables join on key, start and end, so you rebuild any view you need with merge.

Question 2 (O1): Why does the type count call explode() before value_counts()?

A. Without it, pandas would count each whole list as one value, so a node with two types would count as a type of its own. Most nodes have one type, which makes this easy to miss.

Question 3 (O2): frames.of("Variable") keeps the column question_text, but AGEGRP and ILOSTAT have no question. Why is it kept?

C. of() drops a column only when it is empty for all the rows of the type. So frames.of("Variable") has 8 columns, not 20, and still keeps question_text. The two derived variables show None in it.

Question 4 (O3): You merge the variables with the ASKED_AS edges, and AGEGRP and ILOSTAT disappear from the result. What happened?

B. merge is an inner join by default. A left join keeps every row of the left table, and fills the cells it cannot match with NaN.

Question 5 (O4): You write frames.nodes to CSV as it is, and the node_labels column holds text like ['Variable']. What should you do?

D. A CSV cell holds one value. pandas writes a list as its Python text, which another tool cannot split reliably. Joined with |, it reads back as a plain string, and splits again with .str.split("|").

Question 6 (O4): to_excel fails with "Missing optional dependency 'openpyxl'". What is the fix?

B. pandas writes .xlsx files through openpyxl. A renamed CSV file is not a workbook: Excel would warn, and the sheets would be lost.

Module 20: SQL with DuckDB and PostgreSQL

Exercises

Exercise 1 (O1).

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import TABLES, SQLLens

connection = duckdb.connect()
lens = SQLLens(connection)
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="m20-cdi"), dataset_id="m20-cdi")
for table in TABLES:
    (count,) = connection.execute(f"SELECT count(*) FROM {table}").fetchone()
    print(f"{table}: {count}")
ddigraph_nodes: 91
ddigraph_labels: 181
ddigraph_properties: 493
ddigraph_relationships: 92
ddigraph_relationship_properties: 0
ddigraph_memberships: 90

91 nodes, but 90 memberships: the Dataset node keeps its own provenance and has no membership. Several CDI labels exist in more than one flavor, so there are more label rows than nodes.

Exercise 2 (O2).

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)

CATEGORIES = """
SELECT code.string_value, category.string_value
FROM ddigraph_properties AS variable
JOIN ddigraph_relationships AS r ON r.start_key = variable.key AND r.type = 'USES_CATEGORY'
JOIN ddigraph_properties AS code ON code.key = r.end_key AND code.name = 'code'
JOIN ddigraph_properties AS category ON category.key = r.end_key AND category.name = 'label'
WHERE variable.name = 'name' AND variable.string_value = $1
ORDER BY r.ordinal
"""
for code, label in lens.fetch(CATEGORIES, ["AGEGRP"]):
    print(code, label)
1 15-24
2 25-34
3 35-44
4 45-54
5 55-64
6 65 and over

USES_CATEGORY is an ordered edge, so its ordinal gives the categories' order. A Codebook category keeps its code in the property code, so one more join brings it. The name is a parameter, so the same query serves any variable: try ILOSTAT.

Exercise 3 (O3).

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

connection = duckdb.connect()
lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)

connection.execute("CREATE TABLE stewards (concept VARCHAR, steward VARCHAR)")
connection.execute(
    "INSERT INTO stewards VALUES ('Demographic characteristics', 'Demography team'),"
    " ('Educational attainment', 'Education team'),"
    " ('Labour market status', 'Labour team'), ('Working time', 'Labour team')"
)

OWNERS = """
SELECT variable.string_value, concept.string_value, coalesce(s.steward, 'nobody')
FROM ddigraph_relationships AS r
JOIN ddigraph_properties AS variable ON variable.key = r.start_key AND variable.name = 'name'
JOIN ddigraph_properties AS concept ON concept.key = r.end_key AND concept.name = 'label'
LEFT JOIN stewards AS s ON s.concept = concept.string_value
WHERE r.type = 'USES_CONCEPT'
ORDER BY 1
"""
for row in lens.fetch(OWNERS):
    print(*row, sep=" | ")
AGE | Demographic characteristics | Demography team
AGEGRP | Demographic characteristics | Demography team
EDUC | Educational attainment | Education team
HOURS | Working time | Labour team
ILOSTAT | Labour market status | Labour team
REGION | Place of residence | nobody
SEX | Demographic characteristics | Demography team

The LEFT JOIN keeps REGION, whose concept has no steward yet, and coalesce fills the gap. The join runs inside the database: no data leaves it.

Exercise 4 (O4).

import psycopg

from ddigraph import ir
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, count, node, run

query = Query(match=[node("n")], returns=[count()], dataset_id="m20-survey")

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m20-survey"),
        dataset_id="m20-survey",
    )
    print("before:", run(query, lens))
    lens.purge("m20-survey")
    print("after:", run(query, lens))
before: [(87,)]
after: [(0,)]

A node pattern with no label matches any node, and dataset_id= keeps the members of the dataset and its Dataset node: 87 in all. After the purge, nothing of m20-survey is left in the shared database.

Exercise 5 (O5).

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

connection = duckdb.connect()
connection.execute("INSTALL duckpgq FROM community")
connection.execute("LOAD duckpgq")
lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m20-survey"),
    dataset_id="m20-survey",
)
lens.property_graph()

PATH = """
SELECT code_list.string_value, code.string_value, category.string_value
FROM GRAPH_TABLE (ddigraph_graph
  MATCH (q:ddigraph_node WHERE q.key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'QuestionItem'))
        -[u:ddigraph_relationship WHERE u.type = 'USES_CODELIST']->(l:ddigraph_node)
        -[s:ddigraph_relationship WHERE s.type = 'CONTAINS']->(k:ddigraph_node)
        -[h:ddigraph_relationship WHERE h.type = 'HAS_CATEGORY']->(c:ddigraph_node)
  COLUMNS (q.key AS q, l.key AS l, k.key AS k, c.key AS c)
) g
JOIN ddigraph_properties AS question ON question.key = g.q AND question.name = 'name'
JOIN ddigraph_properties AS code_list ON code_list.key = g.l AND code_list.name = 'label'
JOIN ddigraph_properties AS code ON code.key = g.k AND code.name = 'value'
JOIN ddigraph_properties AS category ON category.key = g.c AND category.name = 'label'
WHERE question.string_value = 'EDUC'
ORDER BY code.string_value
"""
for row in connection.execute(PATH).fetchall():
    print(*row, sep=" | ")
Highest level of education | 1 | Primary or less (ISCED 0-1)
Highest level of education | 2 | Lower secondary (ISCED 2)
Highest level of education | 3 | Upper secondary (ISCED 3)
Highest level of education | 4 | Post-secondary non-tertiary (ISCED 4)
Highest level of education | 5 | Tertiary (ISCED 5-8)

The three edges are one pattern in MATCH, as in Cypher. Each edge's type is a column of the edge, so a WHERE inside the brackets picks it. The variable EDUC uses the same code list as the question, so without the QuestionItem test each row would come twice. In DDI-Lifecycle each code has an ID of its own, so the path needs the CONTAINS step between the list and its categories.

Quiz

Question 1 (O1): Why does the lens keep one row per property in ddigraph_properties, with a column per type, and not one JSON column per node?

B. JSON would not keep every type: PostgreSQL's jsonb stores a number as a decimal, so a float could come back as an integer. A and D are false: both databases hold JSON well.

Question 2 (O1): The Codebook file of the survey has 80 nodes but 158 rows in ddigraph_labels. Why?

C. A join on the key alone would give a variable three times. Joining ddigraph_memberships to ddigraph_labels on key and flavor gives each membership the one label its dataset reads.

Question 3 (O2): Why pass a value to lens.fetch as $1, with a list, rather than paste it into the SQL text?

A. A value such as O'Brien would end a pasted string early. With a parameter, the database never reads the value as SQL. C is false: Exercise 3's query has no parameter at all.

Question 4 (O3): You add your own table answered to the database, then reload the DDI file with lens.write. What happens to answered?

B. The lens only writes its own six tables, and in them, only what the mapping spec owns. Your own property rows and columns stay too.

Question 5 (O4): Several people use the same PostgreSQL database. Which habit keeps your work from touching theirs?

B. The tables are shared, but each row belongs to a dataset. A purge removes only what no other dataset holds. A would delete everyone's data.

Question 6 (O5): lens.property_graph() returns False on a DuckDB connection. What is the likely cause?

D. Without duckpgq, property_graph() returns False and run falls back to plain SQL, with the same rows. B is backwards: PostgreSQL has no duckpgq, so there it always returns False.

Module 21: RDF and SPARQL with Oxigraph

Exercises

Exercise 1 (O1, O2).

python - <<'PY'
from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens

lens = OxigraphLens("m21-cdi-store")
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="m21-cdi"), dataset_id="m21-cdi")
PY
python - <<'PY'
from ddigraph.lens.oxigraph import OxigraphLens

lens = OxigraphLens("m21-cdi-store")
rows = lens.store.query("""
    PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
    SELECT ?class (COUNT(?node) AS ?n)
    WHERE {
        ?node a ?class .
        FILTER(STRSTARTS(STR(?class), STR(ddigraph:)))
        FILTER(?class != ddigraph:Membership)
    }
    GROUP BY ?class
    ORDER BY DESC(?n) ?class
""")
for row in rows:
    print(row["class"].value.removeprefix("https://pbisson44.github.io/ddigraph/ns/1.0/"), row["n"].value)
PY
CDICategory 21
CDICode 21
CDIGenericEntity 21
CDIInstanceVariable 7
CDIValueDomain 7
CDICodeList 5
CDIConcept 5
CDIAgent 1
CDIConceptSystem 1
CDIUnitType 1
Dataset 1

The second run finds the triples because the store lives in the folder. Every node carries its ddigraph class, so one GROUP BY counts them. The filter drops the ddigraph:Membership records, which say which dataset holds each node but are not nodes themselves. The counts read like the survey: 21 codes, each with its category and its notation, the generic entity that holds the code's value; 7 variables, each with its value domain; 5 code lists.

Exercise 2 (O2).

from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.query import Query, asc, edge, node, prop, run

lens = OxigraphLens()
lens.write(
    ir.parse("tests/fixtures/lfs_correspondence.xml", dataset_id="m21-isced"),
    dataset_id="m21-isced",
)

query = Query(
    match=[
        node("map", "CDIConceptMap"),
        node("source", "CDICategory"),
        node("target", "CDICategory"),
        edge("map", "HAS_SOURCE", "source"),
        edge("map", "HAS_TARGET", "target"),
    ],
    returns=[prop("source", "name"), prop("target", "name")],
    order_by=[asc(prop("source", "name")), asc(prop("target", "name"))],
)
for row in run(query, lens):
    print(row)
(Text(value='0 Pre-primary', lang=None), Text(value='0 Early childhood education', lang=None))
(Text(value='1 Primary', lang=None), Text(value='1 Primary', lang=None))
(Text(value='2 Lower secondary', lang=None), Text(value='2 Lower secondary', lang=None))
(Text(value='3 Upper secondary', lang=None), Text(value='3 Upper secondary', lang=None))
(Text(value='4 Post-secondary non-tertiary', lang=None), Text(value='4 Post-secondary non-tertiary', lang=None))
(Text(value='5A Tertiary, theory-based (first stage)', lang=None), Text(value="6 Bachelor's or equivalent", lang=None))
(Text(value='5A Tertiary, theory-based (first stage)', lang=None), Text(value="7 Master's or equivalent", lang=None))
(Text(value='5B Tertiary, practical (first stage)', lang=None), Text(value='5 Short-cycle tertiary', lang=None))
(Text(value='6 Advanced research (second stage of tertiary)', lang=None), Text(value='8 Doctoral or equivalent', lang=None))

Two edge patterns start from the same map: one to its source, one to its target. run writes the SPARQL for you, with one rdf:Statement pattern per edge. Level 5A gives two rows: ISCED 2011 split it into Bachelor's and Master's. The file's other correspondence maps age groups, which are concepts, not categories, so the labels in node() leave it out. The export also writes each map with XKOS terms, xkos:sourceConcept and xkos:targetConcept, for tools that read XKOS.

Exercise 3 (O3).

ddigraph export tests/fixtures/lfs_lifecycle.xml --format turtle -o survey.ttl > /dev/null
python - <<'PY'
import rdflib

name = rdflib.URIRef("https://pbisson44.github.io/ddigraph/ns/1.0/name")
graph = rdflib.Graph().parse("survey.ttl", format="turtle")
graph.add((rdflib.URIRef("urn:ddi:example.nso:q-hours:1"), name, rdflib.Literal("USUAL_HOURS", lang="en")))
graph.serialize("broken.ttl", format="turtle")
PY
ddigraph validate broken.ttl --flavor lifecycle || echo "exit code: $?"
File:   .../broken.ttl
Shapes: lifecycle (2107 triples)
Shapes result: does not conform (1 result(s))
  urn:ddi:example.nso:q-hours:1 https://pbisson44.github.io/ddigraph/ns/1.0/name: More than one String shares the same Language
exit code: 1

A shape allows one value per language for a text, and the question now has two English names. ddigraph validate exits with 1 when the file does not conform, so a script or a CI job can stop on it.

Exercise 4 (O5).

from pathlib import Path

from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens

xml = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
english = '<r:Content xml:lang="en">Employed</r:Content>'
for tag in ["fr", "FR-ca", "zh-hant-tw", "en-a"]:
    labelled = f'<r:Content xml:lang="{tag}">Employed</r:Content>'
    Path("tagged.xml").write_text(xml.replace(english, labelled))
    lens = OxigraphLens()
    try:
        lens.write(ir.parse("tagged.xml", dataset_id="m21-tags"), dataset_id="m21-tags")
    except ValueError:
        print(tag, "-> ValueError")
        continue
    for chunk in lens.read(dataset_id="m21-tags"):
        for node in chunk.nodes:
            if node.label == "Category" and node.properties["label"].value == "Employed":
                print(tag, "->", node.properties["label"].lang)
fr -> fr
FR-ca -> fr-CA
zh-hant-tw -> zh-Hant-TW
en-a -> ValueError

Oxigraph keeps each tag in lower case, and the lens gives it back in the recommended case: a two-letter region in upper case, a four-letter script in title case. en-a is allowed by DDI but is not valid BCP 47, so Oxigraph refuses it and the write changes nothing.

Exercise 5 (O3, O4).

import pyshacl
from pyoxigraph import DefaultGraph, RdfFormat

from ddigraph import ir
from ddigraph.lens.oxigraph import OxigraphLens
from ddigraph.lens.rdf import RDFLens
from ddigraph.rdf.reader import read_graph
from ddigraph.rdf.shacl import shapes_graph

datasets = {
    "m21-codebook": ("tests/fixtures/lfs_codebook.xml", "codebook"),
    "m21-survey": ("tests/fixtures/lfs_lifecycle.xml", "lifecycle"),
}
lens = OxigraphLens()
for dataset_id, (path, _flavor) in datasets.items():
    lens.write(ir.parse(path, dataset_id=dataset_id), dataset_id=dataset_id)
lens.store.dump("both.ttl", RdfFormat.TURTLE, from_graph=DefaultGraph())

for dataset_id, (_path, flavor) in datasets.items():
    chunks = list(read_graph("both.ttl", dataset_id=dataset_id))
    one = RDFLens()
    one.write(chunks, dataset_id=dataset_id)
    conforms, _results, _text = pyshacl.validate(one.graph, shacl_graph=shapes_graph(flavor=flavor))
    print(dataset_id, sum(len(chunk.nodes) for chunk in chunks), conforms)
m21-codebook 80 True
m21-survey 87 True

A file mixes flavors, but each dataset has one. Reading the datasets apart lets you check each with the full shapes of its flavor, which is stricter than the all-flavor shapes a mixed file would need.

Quiz

Question 1 (O1): A notebook has the folder store m21-store open in a lens. You run a script that opens the same folder. What happens?

B. A folder store is open in one place at a time. The lock protects the files from two writers. A looks reasonable, since a database often gives each reader a snapshot, but Oxigraph refuses the second opening outright. Close the notebook's lens, or end its kernel, before the script runs.

Question 2 (O2): Why does the SPARQL from to_sparql match a relationship through its rdf:Statement, not through the plain ddigraph:usesConcept triple?

C. A plain triple is a fact: it appears once, however many relationships say it. Two USES_CONCEPT relationships between the same two nodes would be one triple but two statements, and two rows in Neo4j. A is tempting, but the export writes both: the plain triple for other tools, and the statement so ddigraph can count and order the relationships.

Question 3 (O3): One Turtle file holds a Codebook dataset and a DDI-L dataset. ddigraph validate both.ttl --flavor lifecycle reports more than 100 results, though each dataset conforms on its own. Why?

B. A shape targets a ddigraph class, such as ddigraph:Concept, whatever dataset the node is in. With --flavor lifecycle, the Codebook concepts must meet the DDI-L rules, and they do not. Check each dataset on its own, as in Exercise 5, or leave out --flavor, which accepts either flavor's shape but checks less. D is wrong: the same file conforms without --flavor.

Question 4 (O4): Reading both.ttl with read_graph raises ValueError and names two datasets. What is the fix?

B. read_graph gives one dataset's stream, the way ir.parse gives one file's. When a file holds several, you name one. A does nothing here: the format comes from the .ttl extension. D would break the file, since the membership records say which dataset holds each node.

Question 5 (O5): You write a label tagged EN-gb to an Oxigraph store. What does SPARQL's LANG() give in the store, and what does lens.read give?

C. Oxigraph keeps every tag in lower case, and SPARQL sees what is stored. The lens rewrites the tag in the case BCP 47 recommends when it reads. D is wrong: case does not make a tag invalid. An rdflib lens would give A.

Question 6 (O1): Your Oxigraph store holds two million triples, and each lens.write now takes minutes. What is the better way to add a large file?

B. Each lens call copies the whole default graph into memory, so its time grows with the store, not with the file. Oxigraph's own loader adds the triples without that copy. A changes how the file is read, not the copy. C fails, since the folder is locked while a lens has it open.

Module 22: Gremlin

Exercises

Exercise 1 (O1, O3).

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 gremlin_python.process.traversal import P

from ddigraph.backends.gremlin import write_gremlin


def drop_dataset(g, dataset_id):
    """Drop a dataset's vertices, but keep those another dataset also holds."""
    shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
    g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
    g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()


connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-cdi")
print(write_gremlin(g, "tests/fixtures/lfs_cdi.xml", dataset_id="m22-cdi"))

members = g.V().has("Dataset", "dataset_id", "m22-cdi").in_("IN_DATASET")
print("with ddi_label:", members.has_label("CDICategory").has("ddi_label").count().next())
members = g.V().has("Dataset", "dataset_id", "m22-cdi").in_("IN_DATASET")
print("with label:", members.has_label("CDICategory").has("label").count().next())
connection.close()
GremlinResult(nodes=91, relationships=92, memberships=90, skipped=0)
with ddi_label: 21
with label: 0

Ninety-one vertices, the Dataset vertex among them, and 90 memberships, one for every other vertex. has with a name alone keeps the vertices that have that property. All 21 categories, from Male to Not in the labour force, have a ddi_label, and none has a label: the writer renamed it. A traversal runs only once, so the script builds it again for the second question.

Exercise 2 (O4).

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 gremlin_python.process.traversal import P

from ddigraph.backends.gremlin import write_gremlin


def drop_dataset(g, dataset_id):
    """Drop a dataset's vertices, but keep those another dataset also holds."""
    shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
    g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
    g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()


connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-cdi")
write_gremlin(g, "tests/fixtures/lfs_cdi.xml", dataset_id="m22-cdi")

codes = (
    g.V()
    .has("Dataset", "dataset_id", "m22-cdi")
    .in_("IN_DATASET")
    .has("CDICodeList", "name", "Labour force status (ILO)")
    .as_("list")
    .out("HAS_CODE")
    .as_("code")
    .out("DENOTES")
    .as_("category")
    .select("list", "code", "category")
    .by("name")
    .by(__.out("USES").values("value"))
    .by("name")
)
for row in sorted(codes.to_list(), key=lambda row: row["code"]):
    print(f"{row['list']}: {row['code']} -> {row['category']}")
connection.close()
Labour force status (ILO): 1 -> Employed
Labour force status (ILO): 2 -> Unemployed
Labour force status (ILO): 3 -> Not in the labour force

as_ names a step, and select gathers the named steps into one result. Each by says what to show for each name, in order: a property, or a traversal, such as the step to the notation for the code's value. These HAS_CODE edges carry no ordinal, so Python sorts the rows by code. In DDI-CDI the codes are always vertices, so there is one path only.

Exercise 3 (O4).

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 gremlin_python.process.traversal import P

from ddigraph.backends.gremlin import write_gremlin


def drop_dataset(g, dataset_id):
    """Drop a dataset's vertices, but keep those another dataset also holds."""
    shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
    g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
    g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()


connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-codebook")
write_gremlin(g, "tests/fixtures/lfs_codebook.xml", dataset_id="m22-codebook")

categories = (
    g.V()
    .has("Variable", "name", "AGEGRP")
    .has("dataset_id", "m22-codebook")
    .out_e("USES_CATEGORY")
    .order()
    .by("ordinal")
    .project("ordinal", "category")
    .by("ordinal")
    .by(__.in_v().values("ddi_label"))
)
for row in categories.to_list():
    print(row["ordinal"], row["category"])
connection.close()
0 15-24
1 25-34
2 35-44
3 45-54
4 55-64
5 65 and over

As in Section 5, out_e stops on the edges instead of walking past them, so you can sort by an edge property. in_v then steps to the vertex each edge points at. Here project reads one value from the edge and one from the category it points at.

Exercise 4 (O2, O4).

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 gremlin_python.process.traversal import P

from ddigraph import ir
from ddigraph.backends.gremlin import write_gremlin
from ddigraph.lens.memory import MemoryLens
from ddigraph.query import Query, count, node, run


def drop_dataset(g, dataset_id):
    """Drop a dataset's vertices, but keep those another dataset also holds."""
    shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
    g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
    g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()


path = "tests/fixtures/lfs_codebook.xml"
lens = MemoryLens()
lens.write(ir.parse(path, dataset_id="m22-codebook"), dataset_id="m22-codebook")
[(variables,)] = run(Query(match=[node("v", "Variable")], returns=[count()]), lens)
print("file, ddigraph.query:", variables)

connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
drop_dataset(g, "m22-codebook")
write_gremlin(g, path, dataset_id="m22-codebook")
members = g.V().has("Dataset", "dataset_id", "m22-codebook").in_("IN_DATASET")
print("Gremlin, traversal:", members.has_label("Variable").count().next())
connection.close()
file, ddigraph.query: 7
Gremlin, traversal: 7

ddigraph.query cannot run on Gremlin, so it runs on the file, which stays the source. The traversal asks Gremlin the same question in its own language. When the two agree, the write is complete.

Exercise 5 (O5).

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 gremlin_python.process.traversal import P

from ddigraph.backends.gremlin import write_gremlin


def drop_dataset(g, dataset_id):
    """Drop a dataset's vertices, but keep those another dataset also holds."""
    shared = __.out("IN_DATASET").has("dataset_id", P.neq(dataset_id))
    g.V().has("Dataset", "dataset_id", dataset_id).in_("IN_DATASET").not_(shared).drop().iterate()
    g.V().has("Dataset", "dataset_id", dataset_id).drop().iterate()


connection = DriverRemoteConnection("ws://localhost:8182/gremlin", "g")
g = traversal().with_(connection)
for dataset_id in ("m22-cdi-a", "m22-cdi-b"):
    drop_dataset(g, dataset_id)
    write_gremlin(g, "tests/fixtures/lfs_cdi.xml", dataset_id=dataset_id)

members = g.V().has("Dataset", "dataset_id", "m22-cdi-a").in_("IN_DATASET")
print("members of m22-cdi-a:", members.count().next())
members = g.V().has("Dataset", "dataset_id", "m22-cdi-a").in_("IN_DATASET")
shared = members.where(__.out("IN_DATASET").has("dataset_id", "m22-cdi-b")).count().next()
print("shared by both:", shared)

drop_dataset(g, "m22-cdi-b")
members = g.V().has("Dataset", "dataset_id", "m22-cdi-a").in_("IN_DATASET")
print("members of m22-cdi-a after the drop:", members.count().next())
connection.close()
members of m22-cdi-a: 90
shared by both: 90
members of m22-cdi-a after the drop: 90

Every node of this file has a URN, made of its agency, ID and version. So each one is a single vertex that both datasets hold. Dropping m22-cdi-b removes only its Dataset vertex, with its edges, and leaves m22-cdi-a whole. The survey's Codebook file would share nothing, since a Codebook ID is scoped to its dataset.

Quiz

Question 1 (O2): You pass a Gremlin traversal source to ddigraph.query.run. What happens?

B. ddigraph only writes to Gremlin. A is tempting, since run writes Cypher, SPARQL and SQL, but Gremlin is not among them. C would need a reader, which does not exist. Run the query on the file in memory, or on another lens, and write your own traversal for Gremlin.

Question 2 (O3): You load the same DDI-L file into the same dataset twice. What is in the graph after the second load?

B. Each vertex is found by its key, and each edge by its two ends, type and ordinal. The write creates one only when it is missing. C is the usual trap of a write that upserts vertices but always adds edges; write_gremlin upserts both.

Question 3 (O3): Why does a DDI node's label property arrive in Gremlin as ddi_label?

A. In TinkerPop, every vertex already has a label: its type, such as Variable. A property with the same name confuses some databases. C is wrong: only label is renamed, while name and question_text keep their names. The language goes in ddi_label_lang, so D is wrong too.

Question 4 (O3): A Codebook variable's external_references holds two URNs. What does its vertex hold?

C. Gremlin databases store lists, or several values in one property, in different ways. Some do not allow them at all. One string works everywhere. A is what a multi-property would give, and that is exactly what ddigraph avoids.

Question 5 (O4): Why does the code-list traversal use union, with one path through HAS_CATEGORY alone and one through CONTAINS, then HAS_CATEGORY?

B. DDI 3.2 and 3.3 give each code an ID, so the path is code list, code, category. DDI 3.1 codes have none, so the edge starts at the code list. One code list takes one path or the other, so A does not happen. C reverses the edge.

Question 6 (O5): You drop every vertex with an IN_DATASET edge to your Dataset vertex, without the not_ filter. Another team loaded the same DDI-L file as their own dataset. What breaks?

B. A URN gives the same key in every dataset, so both datasets hold one shared vertex. A is the tempting mistake: it would be true for Codebook IDs, which are scoped to their dataset, but not for URNs. Gremlin drops a vertex with all its edges, so D does not happen either.

Module 23: Serve the graph: HTTP and Arrow Flight

Exercises

Exercise 1 (O1).

# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done

# The draft of Section 3: its question texts say en_CA, where XML wants en-CA
sed 's/<d:Text xml:lang="en">/<d:Text xml:lang="en_CA">/' tests/fixtures/lfs_lifecycle.xml > draft.xml
for path in tests/fixtures/lfs_codebook.xml tests/fixtures/lfs_lifecycle.xml tests/fixtures/lfs_cdi.xml draft.xml; do
  curl -s -F "file=@$path" "$URL/validate?max_issues=0" -o result.json
  python -c 'import json, sys; r = json.load(open("result.json")); print(sys.argv[1], r["flavor"], r["valid"], len(r["issues"]))' "$path"
done
tests/fixtures/lfs_codebook.xml codebook True 0
tests/fixtures/lfs_lifecycle.xml lifecycle True 0
tests/fixtures/lfs_cdi.xml cdi True 0
draft.xml lifecycle False 8

max_issues=0 asks for every issue. Each answer has status 200, valid or not, so the script reads valid. The server picked the right schema for each flavor, as ddigraph validate would. The draft has 8 issues, one for each question text: a designer fixes them all by writing en-CA, or en.

Exercise 2 (O2, O3).

export DDIGRAPH_API_TOKEN="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"
export DDIGRAPH_API_PUBLIC_READS=true
# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done
AUTH="Authorization: Bearer $DDIGRAPH_API_TOKEN"
FILE=file=@tests/fixtures/lfs_cdi.xml

echo "detect, no token: $(curl -s -o /dev/null -w '%{http_code}' -F "$FILE" "$URL/detect")"
echo "load, no token: $(curl -s -o /dev/null -w '%{http_code}' -F "$FILE" "$URL/load?dry_run=true")"
echo "load, token: $(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" -F "$FILE" "$URL/load?dataset_id=m23-cdi&dry_run=true")"
echo "jobs/unknown, token: $(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" "$URL/jobs/unknown")"
detect, no token: 200
load, no token: 401
load, token: 202
jobs/unknown, token: 404

Public reads open the read endpoints only. /load still needs the token, so the request without it gets 401, not 403: writes are on, but this client did not prove it may use them. The server answers 404 for a job it does not know.

Exercise 3 (O4).

import duckdb
import pyarrow.ipc

import ddigraph

ddigraph.export("tests/fixtures/lfs_cdi.xml", "m23-cdi-arrow", format="arrow", dataset_id="m23-cdi")
nodes = pyarrow.ipc.open_file("m23-cdi-arrow/nodes.arrow").read_all()
rows = duckdb.sql(
    "SELECT node_label, count(*) FROM nodes GROUP BY node_label ORDER BY node_label LIMIT 3"
)
for row in rows.fetchall():
    print(row)
('CDIAgent', 1)
('CDICategory', 21)
('CDICode', 21)

The agent is the National Statistics Office. The 21 codes of the survey's 5 code lists each denote one of its 21 categories. ddigraph.export is the Python form of ddigraph export. DuckDB finds the table through the Python variable nodes, and reads the Arrow columns in place, with no copy and no conversion.

Exercise 4 (O4, O5).

import pyarrow.flight as flight
import pyarrow.ipc

import ddigraph
from ddigraph import ir
from ddigraph.flight import server, ticket
from ddigraph.store import Store

path = "tests/fixtures/lfs_codebook.xml"
store = Store("m23-store")
store.write("m23-codebook", ir.parse(path, dataset_id="m23-codebook"), memory_limit=2**26)
running = server(store, port=0)
client = flight.connect(f"grpc://127.0.0.1:{running.port}")
served = client.do_get(flight.Ticket(ticket("m23-codebook", None, "nodes"))).read_all()
running.shutdown()

ddigraph.export(path, "m23-arrow", format="arrow", dataset_id="m23-codebook")
exported = pyarrow.ipc.open_file("m23-arrow/nodes.arrow").read_all()
print(served.num_rows, "rows over Flight,", exported.num_rows, "rows in the file")
print("equal:", served.equals(exported))
80 rows over Flight, 80 rows in the file
equal: True

A part read whole is the table the export writes for the same graph, row for row and type for type. So a client can switch from files to Flight, or back, without changing how it reads the tables.

Quiz

Question 1 (O1): You send an invalid DDI file to /validate. What do you get back?

C. The check worked; its answer is "not valid". So the server answers 200, and the result says valid: false. A is tempting, but 400 means the request itself was wrong, such as XML that does not parse at all. A script must read valid, not the status.

Question 2 (O2): No DDIGRAPH_API_TOKEN is set. A client sends POST /load with a valid file. What happens?

B. With no token, there is no way to tell who may write, so the server turns /load, /bootstrap and /jobs off. 401 (C) is the answer when a token is set and the client sent none or the wrong one. A would let anyone who reaches the server write to your database.

Question 3 (O3): A client sends a 500 MB file, and DDIGRAPH_API_MAX_UPLOAD_MB is 100. When does it get its 413?

B. The server reads the Content-Length header first, and refuses a body that is too large before reading it. That keeps big files off its disk. A client that states no size is cut off once the body passes the limit. A would let a client fill the disk before being refused.

Question 4 (O3): Your server sits behind a proxy, and every client gets 429 far too soon. Why?

B. ddigraph serve ignores X-Forwarded-For, since any client can write that header. Behind a proxy, all clients share the proxy's one limit. Run uvicorn yourself with --proxy-headers and the proxy's address in --forwarded-allow-ips to count them apart. C is wrong: /health never counts.

Question 5 (O4): A client asks /export?format=arrow. What happens, and why?

B. arrow, csv and neo4j-import each write a folder, and /export answers with one file. For tables over the network, Flight is the tool: it streams both parts, in Arrow. A would lose the relationships.

Question 6 (O5): Why do the tickets of a flight name HEAD's number, such as generation 1, instead of null?

B. You read the two parts with two do_get calls. If HEAD moved in between, null would give you nodes of one generation and relationships of another. A is wrong: you can send null yourself, and it reads HEAD as it is at that moment. A ticket is no secret either: Flight checks no client, which is why it listens on 127.0.0.1 alone.