Skip to content

Module 18: NetworkX

Learning objectives

By the end of this module, you can:

  • O1. Build a NetworkX graph of a DDI file with to_networkx, and say what its node IDs, node attributes and edge keys hold.
  • O2. Find the most connected nodes of a graph with degree and centrality.
  • O3. Find the shortest path between a question and a category, and say when the direction of the edges matters.
  • O4. Split a graph into its connected components, and merge several files into one graph.
  • O5. Write a graph to GraphML or JSON, with lists flattened by ddigraph.backends.flatten, and read it back.

Prerequisites: Module 5

Time: 40 min self-paced / 55 min instructor-led.

Needs: No server. The networkx extra (pip install "ddigraph[networkx]").

New in this module: ddigraph.backends.networkx.to_networkx, MultiDiGraph, node_labels, memberships, G.degree(), nx.betweenness_centrality, nx.shortest_path, nx.weakly_connected_components, ddigraph.backends.flatten, nx.write_graphml, nx.node_link_data


1. A DDI file as a NetworkX graph

NetworkX is a Python library for graphs. It keeps the whole graph in memory and ships hundreds of graph algorithms. It needs no server. That makes it a good place to ask questions about the shape of your metadata: which items are hubs, what connects to what, and what stands alone.

to_networkx reads a DDI file of any flavor, or an RDF file ddigraph wrote, and gives back a graph. This module uses the sample survey: a fictional Labour Force Survey, third quarter 2025. Its DDI-L file holds the questionnaire, 8 questions, 6 code lists and 7 variables. This block reads it, and prints its code lists:

from ddigraph.backends.networkx import to_networkx

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

print(type(G).__name__, G.number_of_nodes(), "nodes", G.number_of_edges(), "edges")
for key, data in G.nodes(data=True):
    if "CodeList" in data["node_labels"]:
        print(key, data["node_labels"], data.get("label"))

Expected output:

MultiDiGraph 87 nodes 108 edges
5f70c70dcb831d4a26fc857c4c7d42af ['CodeList'] Sex
c4988e70d6d3687387beaa1ab7d3c9f3 ['CodeList'] Age group
79d801998adc1f3de0eda1d626f575ca ['CodeList'] Yes or no
8e45f3f395a79ac85290e379a4a17279 ['CodeList'] Labour force status (ILO)
200467fe66fc08cd6fa31010255e680c ['CodeList'] Region
32e6091748601d687612b60f3a3cd989 ['CodeList'] Highest level of education

The survey has a code list for each set of answers it offers. Each node's ID in NetworkX is its key: the 32 hex characters that name it in every backend. The graph is a MultiDiGraph:

  • Di for directed: each edge goes one way, as each DDI reference does.
  • Multi because two nodes can be joined by more than one edge, of different types.

2. What the nodes and edges hold

Each node carries attributes: a dictionary of values. Each edge has a key that tells it apart from other edges between the same two nodes, and attributes of its own. This block prints the attributes of the question WORK, then each edge that touches its code list, Yes or no:

from ddigraph.backends.networkx import to_networkx

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


def name(node):
    # A short, readable name for a node: its type, then its name, label or value
    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()


question = next(n for n in G if name(n) == "QuestionItem WORK")
for attribute, value in G.nodes[question].items():
    print(f"{attribute}: {value}")
print()
code_list = next(n for n in G if name(n) == "CodeList Yes or no")
edges = [
    *G.in_edges(code_list, keys=True, data=True),
    *G.out_edges(code_list, keys=True, data=True),
]
for start, end, (rel_type, ordinal), data in edges:
    print(f"{name(start)} -{rel_type}-> {name(end)}  ordinal={ordinal} {data}")

Expected output:

node_labels: ['QuestionItem']
identity: urn:ddi:example.nso:q-work:1
ddi_id: q-work
agency: example.nso
version: 1
urn: urn:ddi:example.nso:q-work:1
name: WORK
name_lang: en
question_text: Last week, did you do any work for pay or profit, even for one hour?
question_text_lang: en
response_type: code
memberships: {'lfs_lifecycle': Provenance(source='tests/fixtures/lfs_lifecycle.xml', flavor='lifecycle', line=147)}

QuestionItem LOOK -USES_CODELIST-> CodeList Yes or no  ordinal=None {'resolution': 'exact'}
QuestionItem WORK -USES_CODELIST-> CodeList Yes or no  ordinal=None {'resolution': 'exact'}
QuestionItem AVAIL -USES_CODELIST-> CodeList Yes or no  ordinal=None {'resolution': 'exact'}
CodeList Yes or no -CONTAINS-> Code 1  ordinal=0 {}
CodeList Yes or no -CONTAINS-> Code 2  ordinal=1 {}

What each part means:

  • node_labels is the node's types, as a sorted list. Most nodes have one. It is not called label, because most DDI items have a label of their own: the readable one.
  • identity is the identity as text, and the other attributes are the node's properties, the same ones Neo4j holds.
  • memberships maps each dataset that holds the node to where it came from: the file, the flavor and the line. The dataset ID is the file's name without its extension.
  • An edge key is the pair (type, ordinal). The ordinal is the edge's place in an ordered list, from 0, or None. The code list holds its codes in order, so its two CONTAINS edges have 0 and 1. Because the key is fixed, loading the same file twice does not double any edge.
  • resolution says how a reference found its end, here exact. A code sits inside its code list in the file, with no reference, so a CONTAINS edge has none.

Three questions point at one code list: WORK, LOOK and AVAIL share Yes or no. Notice what is missing: there is no IN_DATASET edge. In Neo4j, each node points at its Dataset node. Here, a node's datasets are in its memberships attribute instead. The NetworkX backend page lists every attribute.

Put these parts to work on a question: which concept does each variable use? Ask it of the same survey's DDI-Codebook file. In NetworkX, walk the edges and keep each USES_CONCEPT edge that starts at a variable. The pandas tab asks the same of the three tables of Module 19. Pick a tab, and the site remembers it for every code box.

from ddigraph.backends.networkx import to_networkx

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

rows = [
    (G.nodes[start]["name"], G.nodes[end]["label"])
    for start, end, (rel_type, _ordinal) in G.edges(keys=True)
    if rel_type == "USES_CONCEPT" and "Variable" in G.nodes[start]["node_labels"]
]
for variable, concept in sorted(rows):
    print(variable, "|", concept)
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

The edge key holds the type, and each end's attributes hold its name or label. No join is needed: an edge already knows its two nodes.

from ddigraph.backends.pandas import to_dataframes

frames = to_dataframes("tests/fixtures/lfs_codebook.xml")
variables = frames.of("Variable")[["key", "name"]].rename(columns={"name": "variable"})
concepts = frames.of("Concept")[["key", "label"]].rename(columns={"label": "concept"})
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")
    .sort_values("variable")
)
for row in table.itertuples():
    print(row.variable, "|", row.concept)
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

A table holds rows, not links. So each step along an edge is a merge: the relationship's start to the variable's key, and its end to the concept's.

Both tabs print the same seven rows, and so would the Neo4j recipe in Module 17. It is one graph, whatever holds it.

3. Hubs: degree and centrality

The degree of a node is the number of edges that touch it. In a directed graph, it splits into in-degree (edges that arrive) and out-degree (edges that leave). A node with a high degree is a hub: many things hang off it.

Betweenness centrality asks another question: how often does a node sit on the shortest path between two other nodes? A node with a high score is a bridge. Remove it, and parts of the graph drift apart. The score runs from 0 to 1.

This block names each node by its type and its name or label, then ranks them three ways:

import networkx as nx

from ddigraph.backends.networkx import to_networkx

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


def name(node):
    # A short, readable name for a node: its type, then its name or label
    data = G.nodes[node]
    return f"{data['node_labels'][0]} {data.get('name') or data.get('label') or ''}".strip()


print("Most links:")
for node, degree in sorted(G.degree(), key=lambda pair: (-pair[1], name(pair[0])))[:4]:
    print(f"  {degree}  {name(node)}  (in {G.in_degree(node)}, out {G.out_degree(node)})")

print("Most used code lists:")
code_lists = [n for n, data in G.nodes(data=True) if "CodeList" in data["node_labels"]]
for node in sorted(code_lists, key=lambda n: (-G.in_degree(n), name(n)))[:3]:
    users = sorted(name(start) for start, _ in G.in_edges(node))
    print(f"  {G.in_degree(node)}  {name(node)}: {', '.join(users)}")

print("Betweenness, ignoring direction:")
scores = nx.betweenness_centrality(G.to_undirected())
for node, score in sorted(scores.items(), key=lambda pair: (-pair[1], name(pair[0])))[:4]:
    print(f"  {score:.3f}  {name(node)}")

Expected output:

Most links:
  7  CodeList Age group  (in 1, out 6)
  7  CodeList Highest level of education  (in 2, out 5)
  7  CodeList Region  (in 2, out 5)
  7  Sequence Main sequence  (in 1, out 6)
Most used code lists:
  3  CodeList Yes or no: QuestionItem AVAIL, QuestionItem LOOK, QuestionItem WORK
  2  CodeList Highest level of education: QuestionItem EDUC, Variable EDUC
  2  CodeList Region: QuestionItem REGION, Variable REGION
Betweenness, ignoring direction:
  0.531  Universe Persons aged 15 and over living in private households
  0.317  Variable ILOSTAT
  0.272  Variable AGEGRP
  0.259  CodeList Age group

Degree counts every edge, so the longest code lists come first: Age group has six codes, and Region and Highest level of education have five each. Their size makes them hubs, not their use. In-degree tells you about use. Only questions and variables point at a code list, so its in-degree counts its users. Yes or no comes first: WORK, LOOK and AVAIL share it.

Betweenness finds the bridges. The universe of persons aged 15 and over comes first: six of the seven variables point at it, so many paths between them run through it. ILOSTAT is next: it joins the three questions it comes from to its own code list.

The sort key puts the highest first, and breaks ties by name, so the order is the same on every run. Betweenness ran on G.to_undirected(), a copy with no arrows. On the directed graph, few paths exist at all, since most edges point away from the questionnaire and the variables.

nx.pagerank gives another kind of score, but it needs SciPy, which the networkx extra does not install.

4. Paths between a question and a category

A path is a chain of edges from one node to another. The shortest path uses the fewest edges. In the DDI-L file, the arrows lead from the questionnaire down to the categories. Which way does the questionnaire reach the answer Yes?

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")
path = nx.shortest_path(G, questionnaire, yes)
for node in path:
    print(name(node))
print(len(path) - 1, "steps")

Expected output:

Instrument LFS questionnaire
Sequence Main sequence
QuestionConstruct WORK
QuestionItem WORK
CodeList Yes or no
Code 1
Category Yes
6 steps

That is the questionnaire's flow, in one call: the main sequence, the question WORK, its code list and its first code. LOOK and AVAIL use Yes or no too, but they sit deeper, in the job search branch, so their paths are longer.

Now try a category of a derived variable. Unemployed is a category of ILOSTAT, the labour force status. The survey never asks it: ILOSTAT is worked out from WORK, LOOK and AVAIL.

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")
unemployed = next(n for n in G if name(n) == "Category Unemployed")
print("directed:", nx.has_path(G, questionnaire, unemployed))
undirected = G.to_undirected(as_view=True)
for path in nx.all_shortest_paths(undirected, questionnaire, unemployed):
    print(" - ".join(name(n) for n in path))

Expected output:

directed: False
Instrument LFS questionnaire - Sequence Main sequence - QuestionConstruct WORK - QuestionItem WORK - Variable ILOSTAT - CodeList Labour force status (ILO) - Code 2 - Category Unemployed

No arrow path joins them. A variable points at its questions, not the other way, so no arrow leads from the questionnaire to ILOSTAT. Ignore the direction, and a path appears: through the question WORK, and the variable derived from it.

to_undirected(as_view=True) gives a view with no arrows, without copying the graph. all_shortest_paths lists every path of the shortest length: here only one. So direction matters. With arrows, a path follows the references as DDI wrote them. Without them, it tells you how two items are related at all, even through a variable that points the other way.

A connected component is a group of nodes that paths join, with no path to the rest. In a directed graph, a weakly connected component ignores the direction of the edges. Components show the islands of a file. The DDI-Codebook file has a few:

from collections import Counter

import networkx as nx

from ddigraph.backends.networkx import to_networkx

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

components = sorted(nx.weakly_connected_components(G), key=len, reverse=True)
print(len(components), "components")
for component in components:
    if len(component) > 1:
        types = sorted({G.nodes[n]["node_labels"][0] for n in component})
        print(len(component), "nodes:", ", ".join(types))
alone = Counter(G.nodes[n]["node_labels"][0] for c in components if len(c) == 1 for n in c)
print(sum(alone.values()), "nodes link to nothing:", dict(sorted(alone.items())))

Expected output:

32 components
42 nodes: Category, Concept, DataFile, Question, Universe, Variable
8 nodes: Citation, Contributor, Coverage, Dataset, Organization, Study
30 nodes link to nothing: {'DDIGenericIdentifiable': 26, 'DataCollectionEvent': 2, 'DocumentDescription': 1, 'Universe': 1}

The big island holds the seven variables and what they use. They all sit in one data file, so paths join them all. The study, its citations and its producer form a second island, around the Dataset node. And 30 nodes link to nothing. Most are structure elements, such as each variable's location. They still belong to the dataset, through their memberships, but no reference reaches them.

One of them is worth a look: a Universe. The big island holds the universe of HOURS, employed persons aged 15 and over, since HOURS points at it. The lone one is the study's universe, persons aged 15 and over living in private households. Six variables belong to it, but a Codebook variable names a universe only when it narrows the study's. So no edge reaches it. On a real codebook, this is a quick way to find items nothing uses.

6. Several files in one graph

Pass graph= to add a file to a graph you already have. Nodes that two files share, by key, become one node, with a membership for each dataset. Which nodes are shared depends on their identity, as Module 4 explained.

The survey runs every quarter. When the questionnaire does not change, the next quarter uses the same metadata. This block loads each file twice, as the third and the fourth quarter:

from collections import Counter

from ddigraph.backends.networkx import to_networkx

G = to_networkx("tests/fixtures/lfs_lifecycle.xml", dataset_id="lfs-2025q3")
G = to_networkx("tests/fixtures/lfs_lifecycle.xml", dataset_id="lfs-2025q4", graph=G)
print("DDI-L twice:", G.number_of_nodes(), "nodes,", G.number_of_edges(), "edges")
held_by = Counter(
    ", ".join(sorted(data.get("memberships", {})) or [data["dataset_id"]])
    for _, data in G.nodes(data=True)
)
for datasets, count in sorted(held_by.items()):
    print(f"  {count} held by {datasets}")

C = to_networkx("tests/fixtures/lfs_codebook.xml", dataset_id="lfs-2025q3")
C = to_networkx("tests/fixtures/lfs_codebook.xml", dataset_id="lfs-2025q4", graph=C)
print("Codebook twice:", C.number_of_nodes(), "nodes,", C.number_of_edges(), "edges")

Expected output:

DDI-L twice: 88 nodes, 109 edges
  1 held by lfs-2025q3
  86 held by lfs-2025q3, lfs-2025q4
  1 held by lfs-2025q4
Codebook twice: 160 nodes, 96 edges

The DDI-L objects have URNs, so the second load finds the same 86 nodes and adds a membership to each. Only the second Dataset node, and its HAS_ENTRY_POINT edge, are new. A Dataset node keeps a dataset_id instead of memberships. The Codebook IDs only mean something inside one file, so its nodes are scoped to their dataset: the second load doubles the graph. When two files give a shared node different values, the second one wins.

7. Save the graph: GraphML and JSON

GraphML is an XML format for graphs that tools such as Gephi, yEd and Cytoscape open. It stores only plain values: text, numbers and booleans. But node_labels is a list, memberships holds records, and an edge key is a pair. So write a copy first:

  • ddigraph.backends.flatten joins a list into one string with |, and passes any other value through;
  • the memberships and provenance records stay out;
  • each edge key becomes two attributes, type and ordinal.
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_lifecycle.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, "survey.graphml")

back = nx.read_graphml("survey.graphml", force_multigraph=True)
print(back.number_of_nodes(), "nodes,", back.number_of_edges(), "edges")
question = next(
    n
    for n, data in back.nodes(data=True)
    if data["node_labels"] == "QuestionItem" and data["name"] == "WORK"
)
print(back.nodes[question]["question_text"])
print(Counter(data["type"] for _, _, data in back.edges(data=True)).most_common(3))

Expected output:

87 nodes, 108 edges
Last week, did you do any work for pay or profit, even for one hour?
[('CONTAINS', 23), ('HAS_CATEGORY', 23), ('REFERENCES_QUESTION', 17)]

After the round trip, node_labels is the string QuestionItem, not a list. Split it on | if a node has more than one type.

Node-link JSON keeps lists as lists. A membership is a Provenance record, which json cannot write alone, so pass msgspec.to_builtins as the fallback. JSON has no tuples, though: each edge key comes back as a list, and NetworkX refuses a list as a key. Turn the keys back into tuples before you rebuild the graph:

import json

import msgspec
import networkx as nx

from ddigraph.backends.networkx import to_networkx

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

with open("survey.json", "w", encoding="utf-8") as f:
    json.dump(nx.node_link_data(G, edges="edges"), f, indent=2, default=msgspec.to_builtins)

with open("survey.json", encoding="utf-8") as f:
    data = json.load(f)
print(data["edges"][1])
for edge in data["edges"]:
    edge["key"] = tuple(edge["key"])  # JSON turned each (type, ordinal) key into a list
back = nx.node_link_graph(data, edges="edges")
print(back.number_of_nodes(), "nodes,", back.number_of_edges(), "edges")
print(sorted(back.edges(keys=True))[0][2])

Expected output:

{'resolution': 'exact', 'source': '35d76b9592b9df076ff269bb05b02318', 'target': '2d6807716f4e860c96841165a2572976', 'key': ['HAS_CONSTRUCT', 0]}
87 nodes, 108 edges
('REFERENCES_QUESTION', None)

matplotlib can draw a graph too, but this course does not install it. For a picture of the graph, open the GraphML file in Gephi or yEd, or see the drawing examples on the NetworkX backend page.


Exercises

Scenario

Your institute is moving its Labour Force Survey to DDI-CDI. Before anyone loads a database, your manager wants to know what the CDI files hold and how their parts connect.

Exercise 1 (O1). Build the graph of tests/fixtures/lfs_cdi.xml, the survey in DDI-CDI. Print how many nodes it has of each type, then how many edges of each type. Read the edge types from the edge keys.

Expected output:

CDIAgent: 1
...
TAKES_SUBSTANTIVE_VALUES_FROM: 7
TAKES_VALUES_FROM: 5
USES: 21
Answer
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). In tests/fixtures/lfs_correspondence.xml, which nodes have a degree of 5 or more? Print each one's degree, type and identity, highest degree first. Break ties by key, so the order is the same on every run.

Expected output:

13 CDICorrespondenceTable urn:ddi:example.nso:isced1997-2011:1
11 CDIStatisticalClassification urn:ddi:example.nso:isced2011:1
...
Answer
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). In the DDI-L file, is there a directed path from the category Yes back up to the questionnaire? Print the answer. Then reverse every edge with G.reverse(), and print the shortest path from the category to the questionnaire.

Expected output:

False
Category Yes <- Code 1 <- CodeList Yes or no <- QuestionItem WORK <- ... <- Instrument LFS questionnaire
Answer
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). Export tests/fixtures/lfs_lifecycle.xml to Turtle with ddigraph.export. Build one graph from the XML file, then add the Turtle file to it. Print the node and edge counts, and the number of weakly connected components.

Expected output:

87 nodes, 108 edges, weakly connected components: 1
Answer
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). Write the graph of tests/fixtures/lfs_correspondence.xml to correspondence.graphml, with lists flattened. Read it back, and print how many edges it has of each type.

Expected output:

DENOTES 17
...
USES 17
Answer
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?

A. Its DDI ID, such as q-work.

B. Its URN, such as urn:ddi:example.nso:q-work:1.

C. Its key: 32 hex characters, the same in every backend.

D. A number NetworkX gives each node in turn.

Answer

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?

A. NetworkX cannot store edges to a Dataset node.

B. The NetworkX lens keeps each node's datasets, with the file and line, as an attribute. Edges are only the references the file makes.

C. The node belongs to no dataset in NetworkX.

D. IN_DATASET only exists in Codebook files.

Answer

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. A node that sits on many shortest paths between other nodes, such as a universe that most variables share.

B. The node with the longest label.

C. A node that links to nothing.

D. Always the Dataset node.

Answer

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?

A. The DDI-L file is broken.

B. Unemployed is a category of ILOSTAT, a derived variable. A variable points at its questions, so no arrow leads from the questionnaire to it. Ignoring the arrows, the path runs through the question WORK and the variable.

C. has_path only works on DDI-Codebook files.

D. The category is a stub.

Answer

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?

A. The Codebook file is read twice; the DDI-L file only once.

B. DDI-L objects have URNs, which name the same node in every dataset. Codebook IDs only mean something in one file, so each dataset gets its own nodes.

C. NetworkX drops duplicate DDI-L nodes but not Codebook ones.

D. The second Codebook load failed half way.

Answer

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?

A. Write it to JSON with json.dump(G).

B. Remove every node that has a list.

C. Install matplotlib.

D. Write a copy with plain values: flatten each list with ddigraph.backends.flatten, leave out memberships, and split each edge key into type and ordinal.

Answer

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.


Check yourself

  • I can build a NetworkX graph of a DDI file with to_networkx, and say what its node IDs, node attributes and edge keys hold. (O1)
  • I can find the most connected nodes of a graph with degree and centrality. (O2)
  • I can find the shortest path between a question and a category, and say when the direction of the edges matters. (O3)
  • I can split a graph into its connected components, and merge several files into one graph. (O4)
  • I can write a graph to GraphML or JSON, with lists flattened, and read it back. (O5)

Next: Module 19: pandas