Skip to main content

Directed, Weighted, and Multigraphs

Graph type is part of the measurement model. An undirected simple graph stores at most one edge per unordered node pair. A directed graph distinguishes u → v from v → u. A multigraph additionally preserves parallel edges, while attributes such as weight carry declared measurements.

Prerequisites​

Complete graphs as a data model. You should already have written the fixture's node identity and edge identity rules.

Learning goals​

  • Select Graph, DiGraph, MultiGraph, or MultiDiGraph from data semantics.
  • Preserve repeated events with stable edge keys.
  • State a parallel-edge aggregation rule before converting to a simple graph or matrix.
  • Decide whether self-loops are valid observations and how each statistic treats them.

Four choices, not four interchangeable containers​

NetworkX classDirectedParallel edges
Graphnono
DiGraphyesno
MultiGraphnoyes
MultiDiGraphyesyes

The fixture contains two distinct events from Ada to Ben, reciprocal events between Dia and Eli, and Eli's self-loop. A MultiDiGraph preserves all of them. Calling add_edge("ada", "ben") twice on a DiGraph would update one edge instead of retaining two event identities.

Weight also needs semantics. Here it is positive interaction intensity, so summing parallel weights answers “total recorded intensity.” If weights were distances, probabilities, signed ratings, or capacities, summing could be nonsensical. This batch uses the explicit parallel-edge aggregation rule “sum positive intensity weights” only when a simple representation is required.

Worked example​

import csv
from pathlib import Path

import networkx as nx

fixture = Path("tests/fixtures/graph-data-science")
graph = nx.MultiDiGraph()
with (fixture / "interaction-nodes.csv").open(encoding="utf-8") as handle:
graph.add_nodes_from(row["node_id"] for row in csv.DictReader(handle))
with (fixture / "interaction-relationships.csv").open(encoding="utf-8") as handle:
for row in csv.DictReader(handle):
if row["record_status"] == "valid":
graph.add_edge(
row["source"],
row["target"],
key=row["relationship_id"],
weight=int(row["weight"]),
interaction_type=row["interaction_type"],
)

parallel = graph.get_edge_data("ada", "ben")
aggregate_weight = sum(attributes["weight"] for attributes in parallel.values())
self_loops = sorted(nx.selfloop_edges(graph, keys=True))
print(f"parallel_ada_ben={len(parallel)} aggregate_weight={aggregate_weight}")
print(f"self_loops={self_loops}")

Expected output:

parallel_ada_ben=2 aggregate_weight=3
self_loops=[('eli', 'eli', 'r08')]

The edge key is the event's identity. The ordered endpoints are not enough because two valid Ada-to-Ben events share them.

Limitations​

  • Collapsing direction can create paths that never existed in the directed graph.
  • Counting multigraph degree counts edge multiplicity; counting distinct neighbors answers another question.
  • A large weight need not mean closeness. Shortest-path code often interprets weight as cost, which reverses an intensity interpretation.
  • Self-loops can be valid, erroneous, or irrelevant depending on the generating process. Removing them silently changes degree and matrix diagonals.

Practice​

For an airline route, payment transfer, co-authorship, and web-link dataset, choose a graph class and define the weight. For each, say whether repeated records should remain separate or be aggregated.

Next steps​

Next, compare edge lists, adjacency matrices, and sparse storage while keeping these semantics visible.

Primary sources​

Checked 2026-10-18: NetworkX, graph types reference; NetworkX, MultiDiGraph reference; NetworkX, selfloop_edges.