Skip to content

Module 9: Code lists and classifications: SKOS and XKOS

Learning objectives

By the end of this module, you can:

  • O1. Describe how a code list, its codes and its categories form a graph in each DDI flavor, and why a DDI 3.2 or 3.3 code is a node of its own.
  • O2. Find a code list's categories whether or not its codes have IDs, with the CONTAINS*0..1 then HAS_CATEGORY path, in Python and in Cypher.
  • O3. Query the SKOS form of a code list (skos:ConceptScheme, skos:Concept, skos:inScheme, skos:notation), and link its categories to a published classification.
  • O4. Read the XKOS form of a classification in tests/fixtures/lfs_correspondence.xml: its correspondences, their concept pairs, and its levels.

Prerequisites: Module 8

Time: 45 min self-paced / 60 min instructor-led.

Needs: No server. The rdf extra; the DuckDB and Oxigraph tabs of section 4 also need the duckdb and oxigraph extras. The Neo4j tab of section 4 uses the server from Module 7.

New in this module: Code, Category, CONTAINS*0..1, skos:ConceptScheme, skos:Concept, skos:inScheme, skos:notation, skos:exactMatch, xkos:Correspondence, xkos:madeOf, xkos:sourceConcept, xkos:targetConcept, xkos:ClassificationLevel, build_graph


1. Code lists, codes and categories

A survey question often has a fixed set of answers. DDI describes them in three parts:

  • A category is the meaning of an answer, such as "Employed".
  • A code is the value a data file stores for it, such as 1. A code points to its category.
  • A code list is the ordered set of codes that a question or a variable uses. It holds every possible answer: the Labour force status (ILO) list has three, Employed, Unemployed and Not in the labour force.

So the same category, "Yes", can have the code 1 in one code list and Y in another. That is why DDI keeps codes and categories apart.

DDI-Lifecycle writes a code list once and lets many questions use it. In the sample survey, tests/fixtures/lfs_lifecycle.xml, the Yes or no list serves three questions: WORK, LOOK and AVAIL. DDI-Codebook has no such reuse. Each variable lists its own categories, so two Yes or no variables would each repeat "Yes" and "No".

Each DDI flavor puts these parts into the graph its own way:

Flavor Path from the list to its answers
DDI-Lifecycle 3.1 style, a code with no ID CodeList -HAS_CATEGORY-> Category
DDI-Lifecycle 3.2 and 3.3, a code with an ID CodeList -CONTAINS-> Code -HAS_CATEGORY-> Category, and the code value is the code's value property
DDI-Codebook No list: Variable -USES_CATEGORY-> Category, and the code value is the category's code property
DDI-CDI CDICodeList -HAS_CODE-> CDICode -DENOTES-> CDICategory; the value is on the notation the code USES

In Module 4 you saw the rule behind the second row: an element with an identity of its own is a node. DDI 3.2 and 3.3 give each Code an ID, so the code is a node. Its code list CONTAINS it, in order, and the code holds the HAS_CATEGORY edge. A code with no ID is only a part of its code list, so the edge starts at the CodeList.

A code node also keeps its value, such as 1, as its value property. The value sits on the code, not on the category, because one category can have a different code in each list.

2. See the two DDI-L shapes

tests/fixtures/lfs_lifecycle.xml is written in the DDI 3.3 style: each code has an ID. Older files look different. A data archive often keeps its own copy of a survey's metadata, under its own agency, and an older tool may write it in the DDI 3.1 style, with codes that have no ID.

This example makes such a copy. It changes the agency, so the copy's URNs differ from the original's. Then re.sub removes the four elements that give each code its identity: its URN, agency, ID and version. Last, it counts the code list edges of both files:

import re
from collections import Counter
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, shapes = {}, Counter()
    for chunk in iter_graph(path):
        for node in chunk.nodes:
            labels[node.key] = node.label
        for edge in chunk.relationships:
            if edge.type in ("CONTAINS", "HAS_CATEGORY"):
                shapes[f"{labels[edge.start]} -{edge.type}-> {labels[edge.end]}"] += 1
    print(path)
    for shape, count in shapes.items():
        print(f"  {count} x {shape}")

Expected output:

tests/fixtures/lfs_lifecycle.xml
  23 x CodeList -CONTAINS-> Code
  23 x Code -HAS_CATEGORY-> Category
archive.xml
  23 x CodeList -HAS_CATEGORY-> Category

The six code lists hold 23 codes in all. In the original, each code is a node, between its list and its category. In the copy, the codes are gone from the graph, and each list points straight at its categories. A query that follows CodeList -HAS_CATEGORY-> finds all 23 categories in the copy and none in the original. Most files made today look like the original.

3. One path for both shapes

The fix is to allow zero or one CONTAINS step before HAS_CATEGORY. Zero steps start at the code list itself. One step starts at each of its codes. This function does that on the graph stream:

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


def categories(path):
    """Map each code list's label to the labels of its categories."""
    nodes, edges = {}, []
    for chunk in iter_graph(path):
        for node in chunk.nodes:
            nodes[node.key] = node
        edges.extend(chunk.relationships)

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

    found = {}
    for key, node in nodes.items():
        if node.label == "CodeList":
            steps = [key, *ends(key, "CONTAINS")]  # zero steps, then one step
            found[node.properties["label"].value] = [
                nodes[category].properties["label"].value
                for step in steps
                for category in ends(step, "HAS_CATEGORY")
            ]
    return found


survey = categories("tests/fixtures/lfs_lifecycle.xml")
for code_list, answers in survey.items():
    print(f"{code_list}: {', '.join(answers)}")
print("Same for archive.xml:", categories("archive.xml") == survey)

Expected output:

Sex: Male, Female
Age group: 15-24, 25-34, 35-44, 45-54, 55-64, 65 and over
Yes or no: Yes, No
Labour force status (ILO): Employed, Unemployed, Not in the labour force
Region: Capital region, North, South, East, West
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)
Same for archive.xml: True

Both files give the same answer, and each code list comes whole, in its own order. The steps list is the whole idea: the code list, then each code it contains.

4. The same path on every backend

The idea is the same on every backend: start at the code list or at one of its codes, then follow HAS_CATEGORY. Each tab below writes both files, as the datasets m09-survey and m09-archive, and lists each code list's categories. Each tab sorts the labels, so that all tabs print them in the same order. Pick your backend: every tab prints the same lines, because it is one graph. The Neo4j tab needs the server and the DDIGRAPH_NEO4J_* variables you set in Module 2.

The Python walk of section 3, on a lens that holds both files:

import re
from pathlib import Path

from ddigraph import ir
from ddigraph.lens.memory import MemoryLens

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

lens = MemoryLens()
for path, dataset in (
    ("tests/fixtures/lfs_lifecycle.xml", "m09-survey"),
    ("archive.xml", "m09-archive"),
):
    lens.write(ir.parse(path, dataset_id=dataset), dataset_id=dataset)

nodes, edges = {}, []
for chunk in lens.read():
    for node in chunk.nodes:
        nodes[node.key] = node
    edges.extend(chunk.relationships)


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


found = {}
for key, node in nodes.items():
    if node.label == "CodeList":
        steps = [key, *ends(key, "CONTAINS")]  # zero steps, then one step
        found[node.properties["urn"]] = sorted(
            nodes[cat].properties["label"].value
            for step in steps
            for cat in ends(step, "HAS_CATEGORY")
        )
for code_list in sorted(found):
    print(code_list, found[code_list])
urn:ddi:example.archive:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.archive:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.archive:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.archive:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.archive:cl-sex:1 ['Female', 'Male']
urn:ddi:example.archive:cl-yesno:1 ['No', 'Yes']
urn:ddi:example.nso:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.nso:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.nso:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.nso:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.nso:cl-sex:1 ['Female', 'Male']
urn:ddi:example.nso:cl-yesno:1 ['No', 'Yes']

[:CONTAINS*0..1] means zero or one CONTAINS edge. The empty node () is the code list itself, or one of its codes. The tab purges its two datasets at the end:

import os
import re
from pathlib import Path

from neo4j import GraphDatabase

from ddigraph import ir
from ddigraph.lens.neo4j import Neo4jLens

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

QUERY = """
MATCH (cl:CodeList)-[:IN_DATASET]->(d:Dataset)
WHERE d.dataset_id IN ['m09-survey', 'm09-archive']
MATCH (cl)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat:Category)
RETURN cl.urn AS code_list, collect(cat.label) AS categories
ORDER BY code_list
"""
auth = (os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"])
with GraphDatabase.driver(os.environ["DDIGRAPH_NEO4J_URI"], auth=auth) as driver:
    lens = Neo4jLens(driver)
    for path, dataset in (
        ("tests/fixtures/lfs_lifecycle.xml", "m09-survey"),
        ("archive.xml", "m09-archive"),
    ):
        lens.purge(dataset)
        lens.write(ir.parse(path, dataset_id=dataset), dataset_id=dataset)
    records, _, _ = driver.execute_query(QUERY)
    for record in records:
        print(record["code_list"], sorted(record["categories"]))
    for dataset in ("m09-survey", "m09-archive"):
        lens.purge(dataset)
urn:ddi:example.archive:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.archive:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.archive:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.archive:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.archive:cl-sex:1 ['Female', 'Male']
urn:ddi:example.archive:cl-yesno:1 ['No', 'Yes']
urn:ddi:example.nso:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.nso:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.nso:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.nso:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.nso:cl-sex:1 ['Female', 'Male']
urn:ddi:example.nso:cl-yesno:1 ['No', 'Yes']

The SQL lens's tables hold the same graph. A WITH clause lists the steps: each code list itself, then each code it CONTAINS. A label that several flavors share, such as CodeList, has one row per flavor in ddigraph_labels, so take DISTINCT keys:

import re
from pathlib import Path

import duckdb

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

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

lens = SQLLens(duckdb.connect())
for path, dataset in (
    ("tests/fixtures/lfs_lifecycle.xml", "m09-survey"),
    ("archive.xml", "m09-archive"),
):
    lens.write(ir.parse(path, dataset_id=dataset), dataset_id=dataset)

SQL = """
WITH lists (key) AS (
    SELECT DISTINCT key FROM ddigraph_labels WHERE type_label = 'CodeList'
),
steps (list, step) AS (
    SELECT key, key FROM lists
    UNION ALL
    SELECT r.start_key, r.end_key
    FROM ddigraph_relationships AS r
    JOIN lists ON lists.key = r.start_key
    WHERE r.type = 'CONTAINS'
)
SELECT urn.string_value, list(label.string_value ORDER BY label.string_value)
FROM steps
JOIN ddigraph_relationships AS h ON h.start_key = steps.step AND h.type = 'HAS_CATEGORY'
JOIN ddigraph_properties AS urn ON urn.key = steps.list AND urn.name = 'urn'
JOIN ddigraph_properties AS label ON label.key = h.end_key AND label.name = 'label'
GROUP BY urn.string_value
ORDER BY urn.string_value
"""
for code_list, labels in lens.fetch(SQL):
    print(code_list, labels)
urn:ddi:example.archive:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.archive:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.archive:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.archive:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.archive:cl-sex:1 ['Female', 'Male']
urn:ddi:example.archive:cl-yesno:1 ['No', 'Yes']
urn:ddi:example.nso:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.nso:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.nso:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.nso:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.nso:cl-sex:1 ['Female', 'Male']
urn:ddi:example.nso:cl-yesno:1 ['No', 'Yes']

In SPARQL, ? after a predicate means zero or one: ddigraph:contains?/ddigraph:hasCategory is the same path:

import re
from pathlib import Path

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

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

lens = OxigraphLens()
for path, dataset in (
    ("tests/fixtures/lfs_lifecycle.xml", "m09-survey"),
    ("archive.xml", "m09-archive"),
):
    lens.write(ir.parse(path, dataset_id=dataset), dataset_id=dataset)

SPARQL = """
PREFIX ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?list (GROUP_CONCAT(?label; separator="|") AS ?labels) WHERE {
  ?list a ddigraph:CodeList ;
        ddigraph:contains?/ddigraph:hasCategory/skos:prefLabel ?label .
}
GROUP BY ?list
ORDER BY ?list
"""
for row in lens.store.query(SPARQL):
    print(row["list"].value, sorted(row["labels"].value.split("|")))
urn:ddi:example.archive:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.archive:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.archive:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.archive:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.archive:cl-sex:1 ['Female', 'Male']
urn:ddi:example.archive:cl-yesno:1 ['No', 'Yes']
urn:ddi:example.nso:cl-agegroup:1 ['15-24', '25-34', '35-44', '45-54', '55-64', '65 and over']
urn:ddi:example.nso:cl-education:1 ['Lower secondary (ISCED 2)', 'Post-secondary non-tertiary (ISCED 4)', 'Primary or less (ISCED 0-1)', 'Tertiary (ISCED 5-8)', 'Upper secondary (ISCED 3)']
urn:ddi:example.nso:cl-ilo:1 ['Employed', 'Not in the labour force', 'Unemployed']
urn:ddi:example.nso:cl-region:1 ['Capital region', 'East', 'North', 'South', 'West']
urn:ddi:example.nso:cl-sex:1 ['Female', 'Male']
urn:ddi:example.nso:cl-yesno:1 ['No', 'Yes']

In Cypher, always write the path this way:

MATCH (cl:CodeList)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat:Category)
RETURN cl.label AS code_list, collect(cat.label) AS categories

(cl:CodeList)-[:HAS_CATEGORY]->(cat) looks right and works on old files, but it silently misses every category of a DDI 3.3 file. The relationship model explains the rule.

To see the path in Neo4j Browser, load the sample survey with ddigraph load tests/fixtures/lfs_lifecycle.xml --dataset-id m09-survey. Then run this query. It draws the Yes or no code list, its two codes and its two categories, and the three questions that use the list:

MATCH p = (q:QuestionItem)-[:USES_CODELIST]->(cl:CodeList {urn: 'urn:ddi:example.nso:cl-yesno:1'})-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat:Category)
RETURN p

The same graph in three viewers: pick a tab. Each circle is a node, coloured by its type, as the legend under the picture says. Each arrow is a relationship, named by its type. Three questions, WORK, LOOK and AVAIL, point to one code list: DDI-L writes the list once. Click a picture to see it full size.

Neo4j Browser showing the code list Yes or no, its two codes, its categories Yes and No, and the questions WORK, LOOK and AVAIL that use it

gremlin-visualizer showing the code list Yes or no, its two codes, its categories Yes and No, and the questions WORK, LOOK and AVAIL that use it, from Gremlin Server

Gremlin Server has no viewer of its own. This picture is from the open-source gremlin-visualizer, which draws what this traversal returns, in colours of its own:

g.V().has('CodeList','urn','urn:ddi:example.nso:cl-yesno:1').union(identity(), out('CONTAINS'), out('HAS_CATEGORY'), out('CONTAINS').out('HAS_CATEGORY'), in('USES_CODELIST').hasLabel('QuestionItem')).dedup()

The viewer's physics is turned off here, and each node sits where it is in the NetworkX tab. You could do the same by dragging the nodes.

The code list Yes or no, its two codes, its categories Yes and No, and the questions WORK, LOOK and AVAIL that use it, drawn by NetworkX and matplotlib

NetworkX has no viewer either. This picture is drawn with networkx.draw_networkx and matplotlib, from the graph to_networkx gives.

5. Code lists as SKOS

Module 8 showed that the RDF export uses published terms. For code lists, those terms come from SKOS:

  • a code list, code scheme or category scheme is a skos:ConceptScheme;
  • a category is a skos:Concept;
  • the category is skos:inScheme its code list, even when a code sits between the two;
  • a label is skos:prefLabel, and a Codebook category's code is its skos:notation.

A DDI-L Code gets no SKOS class. Its category is the concept: the category carries the label. The code's value stays ddigraph:value. build_graph, from ddigraph.rdf.writer, gives the RDF graph of a stream in memory, with no file. This query uses SKOS terms only. It counts the concepts of each scheme, and gives the same answer for both shapes:

import re
from pathlib import Path

from ddigraph import iter_graph
from ddigraph.rdf.writer import build_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")

QUERY = """
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?list (COUNT(?concept) AS ?answers) WHERE {
  ?scheme a skos:ConceptScheme ; skos:prefLabel ?list .
  ?concept a skos:Concept ; skos:inScheme ?scheme .
}
GROUP BY ?list
ORDER BY ?list
"""
for path in ("tests/fixtures/lfs_lifecycle.xml", "archive.xml"):
    graph = build_graph(iter_graph(path))
    print(path)
    print("  " + ", ".join(f"{row.list} {row.answers}" for row in graph.query(QUERY)))

Expected output:

tests/fixtures/lfs_lifecycle.xml
  Age group 6, Highest level of education 5, Labour force status (ILO) 3, Region 5, Sex 2, Yes or no 2
archive.xml
  Age group 6, Highest level of education 5, Labour force status (ILO) 3, Region 5, Sex 2, Yes or no 2

SKOS hides the code. That is what a SKOS tool wants: a scheme and its concepts. The ddigraph:contains and ddigraph:hasCategory triples are still there, in the graph's direction, for anyone who needs the codes.

In DDI-CDI the code is a node with a value, and it is the code that is skos:inScheme its code list. The category it DENOTES is a skos:Concept. So a SKOS query on a CDI code list goes through the code: ?code skos:inScheme ?scheme ; ddigraph:denotes ?category.

6. Classifications and correspondences: XKOS

A statistical classification, such as a classification of industries, occupations or levels of education, is a code list with more structure. It has levels, such as sections and divisions. A new version often comes with a correspondence: a table that says which item of the old version maps to which item of the new one.

XKOS extends SKOS for these. ddigraph writes:

  • xkos:Correspondence for a correspondence table, and for a DDI-CDI concept system correspondence;
  • xkos:ConceptAssociation for each concept map, the row that pairs a source concept with a target concept;
  • xkos:madeOf from the correspondence to each of its concept maps;
  • xkos:sourceConcept and xkos:targetConcept from each concept map.

tests/fixtures/lfs_correspondence.xml holds one correspondence of each kind. The first maps the survey's six age groups to the four broad age groups that labour market tables often use. The second maps the levels of ISCED 1997, the old International Standard Classification of Education, to those of ISCED 2011. European labour force surveys made that change in 2014. This query lists the pairs, with XKOS and SKOS terms only:

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 skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX xkos: <http://rdf-vocabulary.ddialliance.org/xkos#>
SELECT ?correspondence ?source ?target WHERE {
  ?correspondence a xkos:Correspondence ;
                  xkos:madeOf ?map .
  ?map xkos:sourceConcept/skos:prefLabel ?source ;
       xkos:targetConcept/skos:prefLabel ?target .
}
ORDER BY ?correspondence ?source
""")
for row in rows:
    print(f"{row.correspondence}: {row.source} -> {row.target}")

Expected output:

urn:ddi:example.nso:age-lfs-broad:1: 15-24 -> 15-24
urn:ddi:example.nso:age-lfs-broad:1: 25-34 -> 25-54
urn:ddi:example.nso:age-lfs-broad:1: 35-44 -> 25-54
urn:ddi:example.nso:age-lfs-broad:1: 45-54 -> 25-54
urn:ddi:example.nso:age-lfs-broad:1: 55-64 -> 55-64
urn:ddi:example.nso:age-lfs-broad:1: 65 and over -> 65 and over
urn:ddi:example.nso:isced1997-2011:1: 0 Pre-primary -> 0 Early childhood education
urn:ddi:example.nso:isced1997-2011:1: 1 Primary -> 1 Primary
urn:ddi:example.nso:isced1997-2011:1: 2 Lower secondary -> 2 Lower secondary
urn:ddi:example.nso:isced1997-2011:1: 3 Upper secondary -> 3 Upper secondary
urn:ddi:example.nso:isced1997-2011:1: 4 Post-secondary non-tertiary -> 4 Post-secondary non-tertiary
urn:ddi:example.nso:isced1997-2011:1: 5A Tertiary, theory-based (first stage) -> 6 Bachelor's or equivalent
urn:ddi:example.nso:isced1997-2011:1: 5A Tertiary, theory-based (first stage) -> 7 Master's or equivalent
urn:ddi:example.nso:isced1997-2011:1: 5B Tertiary, practical (first stage) -> 5 Short-cycle tertiary
urn:ddi:example.nso:isced1997-2011:1: 6 Advanced research (second stage of tertiary) -> 8 Doctoral or equivalent

a/b in SPARQL is a property path: follow a, then b. Here it goes from the concept map to the concept, then to its label.

A correspondence is not always one to one. Three age groups merge into one broad group, 25-54. And one ISCED 1997 level, 5A, splits into two ISCED 2011 levels: 6, Bachelor's, and 7, Master's. So a query must expect one source with several targets, and one target with several sources.

7. Levels

XKOS calls a level of a classification an xkos:ClassificationLevel. ddigraph gives that class to a DDI-L ClassificationLevel, a Codebook CategoryGroup and a ConceptGroup.

The sample Codebook file has no category group, so this example adds one to a copy. In the variable AGEGRP, it groups three age groups into 25-54, the prime working age that labour market tables use. A <catgryGrp> names its categories by their IDs, so the copy gives those three categories an ID first:

from pathlib import Path

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

text = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
for code, label in (("2", "25-34"), ("3", "35-44"), ("4", "45-54")):
    text = text.replace(
        f"<catgry><catValu>{code}</catValu><labl>{label}</labl>",
        f'<catgry ID="AGEGRP-{code}"><catValu>{code}</catValu><labl>{label}</labl>',
    )
text = text.replace(
    "<labl>Age group</labl>",
    '<labl>Age group</labl><catgryGrp catgry="AGEGRP-2 AGEGRP-3 AGEGRP-4"><labl>25-54</labl></catgryGrp>',
)
Path("grouped.xml").write_text(text, encoding="utf-8")

graph = build_graph(iter_graph("grouped.xml"))
rows = graph.query("""
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#>
PREFIX xkos: <http://rdf-vocabulary.ddialliance.org/xkos#>
SELECT ?level ?member WHERE {
  ?group a xkos:ClassificationLevel ;
         rdfs:label ?level ;
         ddigraph:groups/skos:prefLabel ?member .
}
ORDER BY ?member
""")
for row in rows:
    print(row.level, "->", row.member)

Expected output:

25-54 -> 25-34
25-54 -> 35-44
25-54 -> 45-54

The level's label is rdfs:label, not skos:prefLabel, because a level is not a SKOS concept. Its members are reached with the ddigraph:groups edge: ddigraph writes no xkos:levels, xkos:depth or xkos:classifiedUnder.

The ISCED correspondence table in lfs_correspondence.xml also names a source level and a target level. DDI-CDI 1.0 has a Level class, but ddigraph reads it as a CDIGenericEntity whose entity_type is Level. So it keeps only ddigraph: terms, and the table reaches it with ddigraph:hasSource and ddigraph:hasTarget, not with XKOS terms:

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 ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?table ?source ?target WHERE {
  ?table a ddigraph:CDICorrespondenceTable ;
         ddigraph:hasSource/rdfs:label ?source ;
         ddigraph:hasTarget/rdfs:label ?target .
}
""")
for row in rows:
    print(f"{row.table}: {row.source} -> {row.target}")

Expected output:

urn:ddi:example.nso:isced1997-2011:1: ISCED 1997 levels -> ISCED 2011 levels

This is why a concept map's HAS_SOURCE is xkos:sourceConcept, while a correspondence table's is not: the table's source is a level, not a concept. The SKOS and XKOS page has the full mapping, and what it leaves out.


Exercises

Scenario

Your agency keeps the ISCED 2011 levels of education as SKOS. A partner sends you the Labour Force Survey's metadata in DDI-L and DDI-CDI. You must check that each code list's answers can be found, whatever the file's style, and link them to the published levels.

Exercise 1 (O1). In tests/fixtures/lfs_cdi.xml, start at the code list named "Labour force status (ILO)". Follow each HAS_CODE edge to a code. From each code, follow USES to its notation, which holds the value, and DENOTES to its category. Print the list's name, the code's value and the category's name.

Expected output:


Answer
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). A colleague's script finds categories through a direct CodeList -HAS_CATEGORY-> edge only. It worked on the archive's copy. For tests/fixtures/lfs_lifecycle.xml and the archive.xml copy of section 2, count the categories that the direct edge finds, and those that the CONTAINS*0..1 path finds.

Expected output:

tests/fixtures/lfs_lifecycle.xml: direct 0, with CONTAINS*0..1 23
archive.xml: direct 23, with CONTAINS*0..1 23
Answer
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). Build the RDF graph of tests/fixtures/lfs_codebook.xml with build_graph. For the variable ILOSTAT, list each category it uses (ddigraph:usesCategory), with its skos:notation and its label, sorted by notation.

Expected output:

1 Employed
2 Unemployed
3 Not in the labour force
Answer
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). Your agency's ISCED 2011 levels are the SKOS graph below. The addresses are made up for this course: UNESCO publishes ISCED 2011, but not at these addresses. Add the graph to the RDF graph of tests/fixtures/lfs_lifecycle.xml. Then use a SPARQL CONSTRUCT to add a skos:exactMatch from each category whose label names one ISCED level, such as "(ISCED 2)", to that level. Print each link, sorted.

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

Expected output:

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
Answer
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). In the RDF graph of tests/fixtures/lfs_correspondence.xml, count the concept maps of each xkos:Correspondence. Use COUNT and GROUP BY.

Expected output:

urn:ddi:example.nso:age-lfs-broad:1 6
urn:ddi:example.nso:isced1997-2011:1 9
Answer
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?

A. ddigraph makes a node for every XML element.

B. A DDI 3.3 code has an ID of its own, and an element with an identity of its own is a node.

C. DDI 3.3 codes always hold a value, and values need nodes.

D. The --flavor lifecycle option makes codes into nodes.

Answer

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?

A. The file was loaded without --replace.

B. The categories are stubs.

C. Each code has an ID, so the HAS_CATEGORY edge starts at the Code, one CONTAINS step below the code list.

D. Neo4j needs HAS_CATEGORY* with a star.

Answer

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?

A. The Code, with the category as its label.

B. The Category, which is skos:inScheme the code list.

C. Both the code and the category, each in the scheme.

D. Neither: SKOS cannot describe a code list with codes.

Answer

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?

A. A skos:exactMatch triple, written by the export when the labels match.

B. Nothing for the link itself: you add skos:exactMatch yourself, for example with a SPARQL CONSTRUCT.

C. A MATCHES relationship in Neo4j.

D. The external_references property, written as skos:exactMatch.

Answer

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?

A. Both.

B. Only the table's, since the table is the correspondence.

C. Only the concept maps', since only their source is a concept; the table's source is a level.

D. Neither: XKOS has no source term.

Answer

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?

A. Read xkos:depth on each xkos:ClassificationLevel.

B. ddigraph writes no xkos:depth, xkos:levels or xkos:classifiedUnder; a level's members are reached with ddigraph:groups or other ddigraph: edges.

C. Count the skos:inScheme steps from the top.

D. Depth is the ddigraph:ordinal of the level.

Answer

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.


Check yourself

  • I can describe how a code list, its codes and its categories form a graph in each DDI flavor, and why a DDI 3.2 or 3.3 code is a node of its own. (O1)
  • I can find a code list's categories whether or not its codes have IDs, with the CONTAINS*0..1 then HAS_CATEGORY path, in Python and in Cypher. (O2)
  • I can query the SKOS form of a code list, and link its categories to a published classification. (O3)
  • I can read the XKOS form of a classification: its correspondences, their concept pairs, and its levels. (O4)

Next: Module 10: One query, many engines