Adjacency, degree, and incidence matrices: theory and implementation
Environment
Python 3.14.6, NumPy 2.4.6, SciPy 1.18.1, NetworkX 3.7, Matplotlib 3.11.2 (Jupyter Notebook).
This article is a rewrite of a post from around 2021, with calculations performed in the environment described above.
Overview
This article belongs to the “Graph basics and matrix representations” chapter of Graph Theory and Practice. It covers adjacency matrices for relationships between vertices, degree matrices for vertex degrees, and incidence matrices for relationships between vertices and edges. We connect their definitions to calculations on the same graph using NumPy and NetworkX, including directed and weighted graphs and isolated vertices.
Setup
Run the cells in order. Round values to three significant figures only for display.
Check the environment, import libraries, and configure plots
from pathlib import Path
from pprint import pprint
import platform
import numpy as np
import scipy
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.ticker import MaxNLocator
from IPython.display import Math, SVG, display
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
print("仮想環境: wa-src(3.14.6)")
print(f"Python: {platform.python_version()}")
print(f"OS: {platform.system()} / {platform.machine()}")
for module in (np, scipy, nx, matplotlib):
print(f"{module.__name__}: {module.__version__}")
# 浮動小数点数だけを有効数字3桁にそろえる。整数はそのまま表示する。
def number(value):
if isinstance(value, (int, np.integer)) or value == 0:
return str(int(value))
return format(float(value), "#.3g")
np.set_printoptions(formatter={"float_kind": number}, linewidth=88)
# ノートブックのフォルダ、またはリポジトリのルートから実行する。
notebook_dir = Path.cwd()
if (notebook_dir / "series/graph-theory/102/102_nb.ipynb").exists():
notebook_dir = notebook_dir / "series/graph-theory/102"
figure_dir = notebook_dir / "102_nb_files"
figure_dir.mkdir(parents=True, exist_ok=True)
# 日本語フォントがある環境では、それを使用する。
available_fonts = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ("Hiragino Sans", "Noto Sans CJK JP", "IPAexGothic", "YuGothic"):
if candidate in available_fonts:
plt.rcParams["font.family"] = [candidate, "DejaVu Sans"]
break
plt.rcParams.update({"font.size": 11, "axes.unicode_minus": False,
"svg.fonttype": "path", "svg.hashsalt": "graph-102"})
仮想環境: wa-src(3.14.6)
Python: 3.14.6
OS: Darwin / arm64
numpy: 2.4.6
scipy: 1.18.1
networkx: 3.7
matplotlib: 3.11.2
The following helpers format output. Arrays use pprint() and equations use display(). The \(...\) delimiters are passed to LaTeX output. Markdown uses $...$ for inline equations and $$...$$ for display equations.
def show_matrix(symbol, values):
"""配列をLaTeXの行列として表示する。1次元配列は列ベクトルにする。"""
values = np.asarray(values)
if values.ndim == 1:
values = values[:, None]
body = r" \\\\ ".join(" & ".join(number(v) for v in row) for row in values)
display(Math(symbol + r"=\begin{bmatrix}" + body + r"\end{bmatrix}"))
def save_figure(fig, name):
"""SVGを保存し、同じ内容を出力欄に埋め込む。"""
path = figure_dir / name
fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})
plt.close(fig)
display(SVG(filename=str(path)))
def matrix_plot(ax, values, title, row_labels, column_labels):
"""各成分の値を添えた行列のヒートマップを描く。"""
values = np.asarray(values)
scale = max(float(np.abs(values).max()), 1)
signed = bool((values < 0).any())
ax.imshow(values, cmap="RdBu_r" if signed else "Blues",
vmin=-scale if signed else 0, vmax=scale)
for (i, j), value in np.ndenumerate(values):
color = "white" if abs(value) > 0.600 * scale else "black"
ax.text(j, i, number(value), ha="center", va="center", color=color)
ax.set_xticks(range(len(column_labels)), column_labels)
ax.set_yticks(range(len(row_labels)), row_labels)
ax.set_title(title, pad=12)
ax.set_xlabel("列")
ax.set_ylabel("行")
def draw_graph(ax, graph, positions, edge_labels=None):
"""頂点の位置を固定し、図どうしを比較できるようにする。"""
nx.draw_networkx(graph, positions, ax=ax, node_color="#dcecf6",
edgecolors="#244c66", node_size=800, width=2,
labels={v: f"$v_{v}$" for v in graph.nodes},
arrows=graph.is_directed(),
**({"arrowsize": 22} if graph.is_directed() else {}))
if edge_labels:
nx.draw_networkx_edge_labels(graph, positions, ax=ax,
edge_labels=edge_labels, font_size=11)
ax.margins(0.200)
ax.set_axis_off()
1. Fix the vertex and edge orders
Start with an undirected graph $G=(V,E)$ without self-loops or parallel edges.
$$ \begin{aligned} V&=\{v_1,v_2,v_3,v_4,v_5\},\quad E=\{e_1,e_2,e_3,e_4\},\\ e_1&=\{v_1,v_2\},\quad e_2=\{v_1,v_3\},\\ e_3&=\{v_2,v_3\},\quad e_4=\{v_3,v_4\}. \end{aligned} $$
There are $n=5$ vertices and $m=4$ edges. Vertex $v_5$ is isolated. Fix the vertex order as $(v_1,v_2,v_3,v_4,v_5)$ and the edge order as $(e_1,e_2,e_3,e_4)$. Check these orders before comparing matrices: changing the order changes the positions of the entries.
2. The adjacency matrix
Define the entries of the adjacency matrix $\mathbf{A}\in\mathbb{R}^{n\times n}$ as follows.
$$ a_{ij}=\begin{cases} 1 & \{v_i,v_j\}\in E,\\ 0 & \text{otherwise}. \end{cases} $$
In the first row, $v_1$ is connected to $v_2,v_3$, so only those columns are 1. Since the graph is undirected, $a_{ij}=a_{ji}$; since it has no self-loops, $a_{ii}=0$. The fifth row and column are all 0 because they correspond to the isolated vertex.
First construct the matrix manually from the edge list and compare it with NetworkX. The nodelist argument of to_numpy_array
specifies the row and column order.
nodes = [1, 2, 3, 4, 5]
edges = [(1, 2), (1, 3), (2, 3), (3, 4)]
index = {node: i for i, node in enumerate(nodes)}
vertex_labels = [f"$v_{v}$" for v in nodes]
edge_labels = [f"$e_{k}$" for k in range(1, len(edges) + 1)]
positions = {1: (0, 1), 2: (0, -1), 3: (2, 0), 4: (4, 0), 5: (4, 2)}
graph = nx.Graph()
graph.add_nodes_from(nodes) # 辺の追加だけでは孤立頂点v5が抜ける。
graph.add_edges_from(edges)
A = np.zeros((len(nodes), len(nodes)), dtype=int)
for u, v in edges:
i, j = index[u], index[v]
A[i, j] = A[j, i] = 1
A_nx = nx.to_numpy_array(graph, nodelist=nodes, weight=None, dtype=int)
np.testing.assert_array_equal(A, A_nx)
show_matrix(r"\mathbf{A}", A)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
draw_graph(axes[0], graph, positions, dict(zip(edges, edge_labels)))
axes[0].set_title("図1 無向グラフと孤立頂点")
matrix_plot(axes[1], A, r"隣接行列 $\mathbf{A}$", vertex_labels, vertex_labels)
save_figure(fig, "01_graph_adjacency.svg")
$$ \displaystyle \mathbf{A}=\begin{bmatrix}0 & 1 & 1 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 \\ 1 & 1 & 0 & 1 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$
$$ \displaystyle \mathbf{A}^{\mathsf{T}}=\mathbf{A} $$
What does a product of adjacency matrices count?
The definition of matrix multiplication gives the following sum for an entry of $\mathbf{A}^2$.
$$ (\mathbf{A}^2)_{ij}=\sum_{k=1}^{n}a_{ik}a_{kj}. $$
The product $a_{ik}a_{kj}=1$ equals 1 when the two-edge walk $v_i\to v_k\to v_j$ exists. For example,
$$ \begin{aligned} (\mathbf{A}^2)_{14} &=a_{11}a_{14}+a_{12}a_{24}+a_{13}a_{34}+a_{14}a_{44}+a_{15}a_{54}\\ &=0\cdot0+1\cdot0+1\cdot1+0\cdot0+0\cdot0=1,\\ (\mathbf{A}^2)_{11} &=0\cdot0+1\cdot1+1\cdot1+0\cdot0+0\cdot0=2. \end{aligned} $$
The first value corresponds to $v_1\to v_3\to v_4$, and the second to $v_1\to v_2\to v_1$ and $v_1\to v_3\to v_1$. In general, $(\mathbf{A}^{\ell})_{ij}$ counts walks of length $\ell$. Walks may repeat vertices and edges, so this is not a count of simple paths. In the code, @ is matrix multiplication; A * A multiplies corresponding entries.
A2 = A @ A
show_matrix(r"\mathbf{A}^{2}", A2)
pprint({"v1からv4への長さ2の歩道数": int(A2[0, 3]),
"v1からv1への長さ2の歩道数": int(A2[0, 0])})
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
draw_graph(axes[0], graph, positions)
nx.draw_networkx_edges(graph, positions, ax=axes[0], edgelist=[(1, 3), (3, 4)],
edge_color="#c34f22", width=4)
axes[0].set_title(r"図2 $v_1 \to v_3 \to v_4$")
matrix_plot(axes[1], A2, r"$\mathbf{A}^{2}$:長さ2の歩道数", vertex_labels, vertex_labels)
save_figure(fig, "02_walks.svg")
$$ \displaystyle \mathbf{A}^{2}=\begin{bmatrix}2 & 1 & 1 & 1 & 0 \\ 1 & 2 & 1 & 1 & 0 \\ 1 & 1 & 3 & 0 & 0 \\ 1 & 1 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ {‘v1からv1への長さ2の歩道数’: 2, ‘v1からv4への長さ2の歩道数’: 1}
3. The degree vector and degree matrix
The degree of vertex $v_i$, denoted $d_i$, is the number of incident edges. Sum row $i$ of the adjacency matrix to obtain it.
$$ \begin{aligned} d_i&=\sum_{j=1}^{n}a_{ij},\\ d_1&=0+1+1+0+0=2,\quad d_2=1+0+1+0+0=2,\\ d_3&=1+1+0+1+0=3,\quad d_4=0+0+1+0+0=1,\quad d_5=0. \end{aligned} $$
With $\mathbf{1}$ denoting the all-ones column vector, the degree vector is $\mathbf{d}=\mathbf{A}\mathbf{1}$. The degree matrix $\mathbf{D}$ has $d_i$ on its diagonal and 0 elsewhere.
Every edge contributes one to each endpoint’s degree, so the degree sum is twice the number of edges. Here, $2+2+3+1+0=8=2\cdot4$. Also, $(\mathbf{A}^2)_{ii}=\sum_k a_{ik}a_{ki}=\sum_k a_{ik}^2=\sum_k a_{ik}=d_i$, agreeing with the diagonal entries in the preceding section.
d = A.sum(axis=1)
D = np.diag(d)
show_matrix(r"\mathbf{d}", d)
show_matrix(r"\mathbf{D}", D)
pprint({"次数の和": int(d.sum()), "辺数の2倍": 2 * graph.number_of_edges()})
np.testing.assert_array_equal(np.diag(A2), d)
assert int(d.sum()) == 2 * len(edges)
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
axes[0].bar(vertex_labels, d, color="#4e88aa")
axes[0].set(title="図3 各頂点の次数", ylabel="次数")
axes[0].yaxis.set_major_locator(MaxNLocator(integer=True))
for i, value in enumerate(d):
axes[0].text(i, value, str(int(value)), ha="center", va="bottom")
axes[0].set_ylim(0, 4)
matrix_plot(axes[1], D, r"次数行列 $\mathbf{D}$", vertex_labels, vertex_labels)
save_figure(fig, "03_degree.svg")
$$ \displaystyle \mathbf{d}=\begin{bmatrix}2 \\ 2 \\ 3 \\ 1 \\ 0\end{bmatrix} $$ $$ \displaystyle \mathbf{D}=\begin{bmatrix}2 & 0 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 & 0 \\ 0 & 0 & 3 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ {‘次数の和’: 8, ‘辺数の2倍’: 8}
$$ \displaystyle \mathbf{d}=\mathbf{A}\mathbf{1},\qquad \mathbf{D}=\operatorname{diag}(d_1,\ldots,d_n) $$
4. Incidence matrices connect vertices to edges
Unsigned incidence matrix
Rows of an incidence matrix represent vertices and columns represent edges. For the unsigned incidence matrix $\mathbf{C}\in\mathbb{R}^{n\times m}$, set the entry to 1 when vertex $v_i$ is an endpoint of edge $e_k$: $c_{ik}=1$. Otherwise, set $c_{ik}=0$. There are no self-loops, so each column contains two 1s.
Signed incidence matrix
Temporarily orient the edges as $e_1:v_1\to v_2$, $e_2:v_1\to v_3$, $e_3:v_2\to v_3$, and $e_4:v_3\to v_4$. These directions are only for calculation and do not change the original undirected graph. Define the signed incidence matrix $\mathbf{B}\in\mathbb{R}^{n\times m}$ by
$$ b_{ik}=\begin{cases} -1 & v_i\text{ is the tail of }e_k,\\ +1 & v_i\text{ is the head of }e_k,\\ 0 & \text{otherwise} \end{cases} $$
For example, column 2 represents $e_2:v_1\to v_3$ and is therefore $(-1,0,1,0,0)^{\mathsf{T}}$. Every column sums to 0. Sign and transpose conventions differ across references, so check the meaning of each axis and sign. We use the convention of NetworkX’s incidence_matrix
.
C = np.zeros((len(nodes), len(edges)), dtype=int)
B = np.zeros_like(C)
for k, (tail, head) in enumerate(edges):
i, j = index[tail], index[head]
C[i, k] = C[j, k] = 1
B[i, k], B[j, k] = -1, 1
# nodelistとedgelistの両方を渡し、行・列の順序を固定する。
for oriented, expected in ((False, C), (True, B)):
actual = nx.incidence_matrix(graph, nodelist=nodes, edgelist=edges,
oriented=oriented, weight=None, dtype=int)
np.testing.assert_array_equal(actual.toarray(), expected)
show_matrix(r"\mathbf{C}", C)
show_matrix(r"\mathbf{B}", B)
pprint({"Cの列和": C.sum(axis=0), "Bの列和": B.sum(axis=0)})
oriented_graph = nx.DiGraph()
oriented_graph.add_nodes_from(nodes)
oriented_graph.add_edges_from(edges)
fig, axes = plt.subplots(1, 3, figsize=(14, 4), layout="constrained")
draw_graph(axes[0], oriented_graph, positions, dict(zip(edges, edge_labels)))
axes[0].set_title("図4 計算用に向きを付けた辺")
matrix_plot(axes[1], C, r"符号なし $\mathbf{C}$", vertex_labels, edge_labels)
matrix_plot(axes[2], B, r"符号付き $\mathbf{B}$", vertex_labels, edge_labels)
save_figure(fig, "04_incidence.svg")
$$ \displaystyle \mathbf{C}=\begin{bmatrix}1 & 1 & 0 & 0 \\ 1 & 0 & 1 & 0 \\ 0 & 1 & 1 & 1 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0\end{bmatrix} $$ $$ \displaystyle \mathbf{B}=\begin{bmatrix}-1 & -1 & 0 & 0 \\ 1 & 0 & -1 & 0 \\ 0 & 1 & 1 & -1 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 0 & 0\end{bmatrix} $$ {‘Bの列和’: array([0, 0, 0, 0]), ‘Cの列和’: array([2, 2, 2, 2])}
Vertex differences and flows along edges
Let the vertex values be the column vector $\mathbf{x}=(1,2,4,7,0)^{\mathsf{T}}$. Then $\mathbf{B}^{\mathsf{T}}\mathbf{x}$ gives “target value minus source value” for each edge.
$$ \mathbf{B}^{\mathsf{T}}\mathbf{x} =\begin{bmatrix}-x_1+x_2\\-x_1+x_3\\-x_2+x_3\\-x_3+x_4\end{bmatrix} =\begin{bmatrix}-1+2\\-1+4\\-2+4\\-4+7\end{bmatrix} =\begin{bmatrix}1\\3\\2\\3\end{bmatrix}. $$
Conversely, if $\mathbf{f}=(2,1,3,4)^{\mathsf{T}}$ is the flow along the chosen edge directions, $\mathbf{B}\mathbf{f}$ gives “inflow minus outflow” at each vertex.
$$ \mathbf{B}\mathbf{f} =\begin{bmatrix}-f_1-f_2\\f_1-f_3\\f_2+f_3-f_4\\f_4\\0\end{bmatrix} =\begin{bmatrix}-2-1\\2-3\\1+3-4\\4\\0\end{bmatrix} =\begin{bmatrix}-3\\-1\\0\\4\\0\end{bmatrix}. $$
The sum over all vertices is $-3-1+0+4+0=0$. Each edge contributes the same amount to outflow at one endpoint and inflow at the other.
x = np.array([1, 2, 4, 7, 0])
f = np.array([2, 1, 3, 4])
edge_difference = B.T @ x
net_inflow = B @ f
pprint({"辺ごとの値の差": edge_difference, "頂点ごとの正味流入": net_inflow})
assert int(net_inflow.sum()) == 0
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
axes[0].bar(edge_labels, edge_difference, color="#4e88aa")
axes[0].set(title=r"図5 $\mathbf{B}^{\mathsf{T}}\mathbf{x}$", ylabel="終点 − 始点")
axes[1].bar(vertex_labels, net_inflow, color="#b66640")
axes[1].axhline(0, color="black", linewidth=1)
axes[1].set(title=r"$\mathbf{B}\mathbf{f}$", ylabel="流入量 − 流出量")
for ax in axes:
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
save_figure(fig, "05_difference_flow.svg")
{'辺ごとの値の差': array([1, 3, 2, 3]), '頂点ごとの正味流入': array([-3, -1, 0, 4, 0])}
5. Relationships among the three matrices
Consider $(\mathbf{C}\mathbf{C}^{\mathsf{T}})_{ij}=\sum_k c_{ik}c_{jk}$. When $i=j$, it counts incident edges and equals $d_i$. When $i\ne j$, it is 1 exactly when an edge joins the two vertices, so it equals $a_{ij}$.
For $\mathbf{B}\mathbf{B}^{\mathsf{T}}$, the diagonal entry is likewise $\sum_k b_{ik}^2=d_i$. The signs at opposite endpoints differ, giving off-diagonal entries $-a_{ij}$. Specifically,
$$ \begin{aligned} (\mathbf{B}\mathbf{B}^{\mathsf{T}})_{11}&=(-1)^2+(-1)^2+0^2+0^2=2,\\ (\mathbf{B}\mathbf{B}^{\mathsf{T}})_{12}&=(-1)\cdot1+(-1)\cdot0+0\cdot(-1)+0\cdot0=-1,\\ (\mathbf{B}\mathbf{B}^{\mathsf{T}})_{14}&=(-1)\cdot0+(-1)\cdot0+0\cdot0+0\cdot1=0. \end{aligned} $$
Thus $\mathbf{C}\mathbf{C}^{\mathsf{T}}=\mathbf{D}+\mathbf{A}$ and $\mathbf{B}\mathbf{B}^{\mathsf{T}}=\mathbf{D}-\mathbf{A}$. The latter is the graph Laplacian $\mathbf{L}$. Here we establish this relationship without developing its further properties.
Reversing an edge changes the sign of its entire column in $\mathbf{B}$. If that column is $\mathbf{b}_k$, its contribution to the product remains $(-\mathbf{b}_k)(-\mathbf{b}_k)^{\mathsf{T}}=\mathbf{b}_k\mathbf{b}_k^{\mathsf{T}}$. Therefore $\mathbf{B}\mathbf{B}^{\mathsf{T}}$ does not depend on these temporary orientations.
np.testing.assert_array_equal(C @ C.T, D + A)
np.testing.assert_array_equal(B @ B.T, D - A)
B_reversed = B.copy()
B_reversed[:, 0] *= -1 # e1だけを逆向きにする。
np.testing.assert_array_equal(B_reversed @ B_reversed.T, B @ B.T)
print("2つの恒等式と、辺の向きを変えた場合の不変性を確認した。")
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
matrix_plot(axes[0], C @ C.T, r"図6 $\mathbf{C}\mathbf{C}^{\mathsf{T}}=\mathbf{D}+\mathbf{A}$",
vertex_labels, vertex_labels)
matrix_plot(axes[1], B @ B.T, r"$\mathbf{B}\mathbf{B}^{\mathsf{T}}=\mathbf{D}-\mathbf{A}$",
vertex_labels, vertex_labels)
save_figure(fig, "06_matrix_relations.svg")
2つの恒等式と、辺の向きを変えた場合の不変性を確認した。
$$ \displaystyle \mathbf{C}\mathbf{C}^{\mathsf{T}}=\mathbf{D}+\mathbf{A},\qquad \mathbf{B}\mathbf{B}^{\mathsf{T}}=\mathbf{D}-\mathbf{A}=\mathbf{L} $$
6. Separate out-degree and in-degree for directed graphs
Here, the arrows in Figure 4 represent actual edge directions. When $v_i\to v_j$ exists, set $a_{ij}=1$. Rows indicate sources and columns indicate targets, and generally $\mathbf{A}_{\mathrm{dir}}^{\mathsf{T}}\ne\mathbf{A}_{\mathrm{dir}}$. Row sums give out-degrees and column sums give in-degrees.
$$ \begin{aligned} \mathbf{d}_{\mathrm{out}}&=\mathbf{A}_{\mathrm{dir}}\mathbf{1} =(2,1,1,0,0)^{\mathsf{T}},\\ \mathbf{d}_{\mathrm{in}}&=\mathbf{A}_{\mathrm{dir}}^{\mathsf{T}}\mathbf{1} =(0,1,2,1,0)^{\mathsf{T}}. \end{aligned} $$
For example, vertex $v_3$ has out-degree $a_{31}+a_{32}+a_{33}+a_{34}+a_{35}=0+0+0+1+0=1$ and in-degree $a_{13}+a_{23}+a_{33}+a_{43}+a_{53}=1+1+0+0+0=2$. The corresponding diagonal matrices are $\mathbf{D}_{\mathrm{out}}$ and $\mathbf{D}_{\mathrm{in}}$. Both the total out-degree and the total in-degree equal the edge count $m$.
The signed incidence matrix definition still applies. However, $\mathbf{B}\mathbf{B}^{\mathsf{T}}$ is unchanged by edge reversal, so it does not retain all the information in a directed graph. In general it differs from $\mathbf{D}_{\mathrm{out}}-\mathbf{A}_{\mathrm{dir}}$.
A_dir = nx.to_numpy_array(oriented_graph, nodelist=nodes, weight=None, dtype=int)
d_out = A_dir.sum(axis=1) # 行を足す。
d_in = A_dir.sum(axis=0) # 列を足す。
D_out, D_in = np.diag(d_out), np.diag(d_in)
show_matrix(r"\mathbf{A}_{\mathrm{dir}}", A_dir)
show_matrix(r"\mathbf{D}_{\mathrm{out}}", D_out)
show_matrix(r"\mathbf{D}_{\mathrm{in}}", D_in)
pprint({"出次数": d_out, "入次数": d_in})
np.testing.assert_array_equal(d_out, [oriented_graph.out_degree(v) for v in nodes])
np.testing.assert_array_equal(d_in, [oriented_graph.in_degree(v) for v in nodes])
assert int(d_out.sum()) == int(d_in.sum()) == len(edges)
fig, axes = plt.subplots(1, 3, figsize=(14, 4), layout="constrained")
draw_graph(axes[0], oriented_graph, positions)
axes[0].set_title("図7 有向グラフ")
matrix_plot(axes[1], A_dir, r"$\mathbf{A}_{\mathrm{dir}}$", vertex_labels, vertex_labels)
locations = np.arange(len(nodes))
axes[2].bar(locations - 0.200, d_out, width=0.400, label="出次数", color="#4e88aa")
axes[2].bar(locations + 0.200, d_in, width=0.400, label="入次数", color="#b66640")
axes[2].set_xticks(locations, vertex_labels)
axes[2].set_title("行和と列和")
axes[2].set_ylabel("次数")
axes[2].yaxis.set_major_locator(MaxNLocator(integer=True))
axes[2].legend()
save_figure(fig, "07_directed.svg")
$$ \displaystyle \mathbf{A}_{\mathrm{dir}}=\begin{bmatrix}0 & 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ $$ \displaystyle \mathbf{D}_{\mathrm{out}}=\begin{bmatrix}2 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ $$ \displaystyle \mathbf{D}_{\mathrm{in}}=\begin{bmatrix}0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 2 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ {‘入次数’: array([0, 1, 2, 1, 0]), ‘出次数’: array([2, 1, 1, 0, 0])}
7. Weighted graphs
Assign weights $w_1=0.500$, $w_2=1.50$, $w_3=2.00$, and $w_4=1.00$ to the original undirected edges, in order. The weighted adjacency matrix $\mathbf{A}_w$ uses weights instead of 1s at edge positions. The sum $s_i=\sum_j(\mathbf{A}_w)_{ij}$ is the weighted degree, distinct from the degree that counts edges.
$$ \begin{aligned} s_1&=0.500+1.50=2.00,\quad s_2=0.500+2.00=2.50,\\ s_3&=1.50+2.00+1.00=4.50,\quad s_4=1.00,\quad s_5=0. \end{aligned} $$
Let $\mathbf{D}_w=\operatorname{diag}(s_1,\ldots,s_n)$ be the weighted degree matrix and $\mathbf{W}=\operatorname{diag}(w_1,\ldots,w_m)$ the diagonal matrix of edge weights. Keep $\mathbf{B}$ as the unweighted matrix with entries $-1,0,1$. Then
$$ \mathbf{B}\mathbf{W}\mathbf{B}^{\mathsf{T}} =\sum_{k=1}^{m}w_k\mathbf{b}_k\mathbf{b}_k^{\mathsf{T}} =\mathbf{D}_w-\mathbf{A}_w. $$
A diagonal entry sums the incident edge weights, while an off-diagonal entry is the negative of the corresponding edge weight. For row 1, the diagonal entry is $(-1)^2\cdot0.500+(-1)^2\cdot1.50=2.00$ and the entry in column 2 is $(-1)\cdot0.500\cdot1=-0.500$.
Note that incidence_matrix(..., weight="weight")
returns entries $\pm w_k$ in the matrix $\mathbf{B}_w=\mathbf{B}\mathbf{W}$. Direct multiplication gives $\mathbf{B}_w\mathbf{B}_w^{\mathsf{T}}=\mathbf{B}\mathbf{W}^2\mathbf{B}^{\mathsf{T}}$, which squares the weights. For example, its first diagonal entry becomes $0.500^2+1.50^2=2.50$. Instead, calculate $\mathbf{B}\mathbf{W}\mathbf{B}^{\mathsf{T}}$ or multiply each column by $\sqrt{w_k}$. The latter gives a real-valued representation when weights are nonnegative.
weights = np.array([0.500, 1.50, 2.00, 1.00])
weighted_graph = graph.copy()
for (u, v), weight in zip(edges, weights):
weighted_graph[u][v]["weight"] = float(weight)
A_w = nx.to_numpy_array(weighted_graph, nodelist=nodes, weight="weight")
strength = A_w.sum(axis=1)
D_w = np.diag(strength)
W = np.diag(weights)
L_w = B @ W @ B.T
np.testing.assert_allclose(L_w, D_w - A_w)
# 平方根を列ごとに掛けた場合も、同じ行列が得られる。
B_sqrt = B * np.sqrt(weights)[None, :]
np.testing.assert_allclose(B_sqrt @ B_sqrt.T, L_w)
B_weighted = nx.incidence_matrix(weighted_graph, nodelist=nodes, edgelist=edges,
oriented=True, weight="weight").toarray()
np.testing.assert_allclose(B_weighted, B @ W)
assert not np.allclose(B_weighted @ B_weighted.T, L_w)
show_matrix(r"\mathbf{D}_w", D_w)
pprint({"通常の次数": d, "重み付き次数": strength})
pprint({"重みを二乗した場合の第1対角成分":
number((B_weighted @ B_weighted.T)[0, 0])})
fig, axes = plt.subplots(1, 3, figsize=(14, 4), layout="constrained")
draw_graph(axes[0], weighted_graph, positions,
{edge: number(weight) for edge, weight in zip(edges, weights)})
axes[0].set_title("図8 辺の重み")
matrix_plot(axes[1], A_w, r"$\mathbf{A}_w$", vertex_labels, vertex_labels)
matrix_plot(axes[2], L_w, r"$\mathbf{B}\mathbf{W}\mathbf{B}^{\mathsf{T}}$", vertex_labels, vertex_labels)
save_figure(fig, "08_weighted.svg")
$$ \displaystyle \mathbf{D}_w=\begin{bmatrix}2.00 & 0 & 0 & 0 & 0 \\ 0 & 2.50 & 0 & 0 & 0 \\ 0 & 0 & 4.50 & 0 & 0 \\ 0 & 0 & 0 & 1.00 & 0 \\ 0 & 0 & 0 & 0 & 0\end{bmatrix} $$ {‘通常の次数’: array([2, 2, 3, 1, 0]), ‘重み付き次数’: array([2.00, 2.50, 4.50, 1.00, 0])} {‘重みを二乗した場合の第1対角成分’: ‘2.50’}
$$ \displaystyle \mathbf{B}\mathbf{W}\mathbf{B}^{\mathsf{T}}=\mathbf{D}_w-\mathbf{A}_w $$
8. Check ordering and assumptions
If $\mathbf{P}$ permutes the vertices, then $\mathbf{A}^{\prime}=\mathbf{P}\mathbf{A}\mathbf{P}^{\mathsf{T}}$ and $\mathbf{D}^{\prime}=\mathbf{P}\mathbf{D}\mathbf{P}^{\mathsf{T}}$. For an incidence matrix with fixed edge order, $\mathbf{B}^{\prime}=\mathbf{P}\mathbf{B}$. Reordering the vertices to $v_3$ followed by $v_1,v_2,v_4,v_5$ changes the matrix representation but not the graph itself.
new_nodes = [3, 1, 2, 4, 5]
permutation = [index[v] for v in new_nodes]
P = np.eye(len(nodes), dtype=int)[permutation]
A_new = nx.to_numpy_array(graph, nodelist=new_nodes, weight=None, dtype=int)
np.testing.assert_array_equal(A_new, P @ A @ P.T)
np.testing.assert_array_equal(np.diag(A_new.sum(axis=1)), P @ D @ P.T)
B_new = nx.incidence_matrix(graph, nodelist=new_nodes, edgelist=edges,
oriented=True, weight=None, dtype=int).toarray()
np.testing.assert_array_equal(B_new, P @ B)
show_matrix(r"\mathbf{P}", P)
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
matrix_plot(axes[0], A, "図9 元の頂点順", vertex_labels, vertex_labels)
new_labels = [f"$v_{v}$" for v in new_nodes]
matrix_plot(axes[1], A_new, "頂点を並べ替えた行列", new_labels, new_labels)
save_figure(fig, "09_vertex_order.svg")
$$ \displaystyle \mathbf{P}=\begin{bmatrix}0 & 0 & 1 & 0 & 0 \\ 1 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 1\end{bmatrix} $$
The simple identities above assumed no self-loops. NetworkX puts a self-loop’s weight on the adjacency matrix diagonal once, but counts the loop twice in an undirected degree. Therefore the adjacency row sum and the usual degree do not agree unchanged when self-loops are present. Check the self-loop convention .
For parallel edges, also choose an aggregation rule, such as storing the edge count or the sum of weights in the adjacency matrix. The $0,1$ definition here does not apply unchanged. The next article, “Sparse matrices for large graphs and their computational cost,” covers sparse representations.
Conclusion
We constructed adjacency, degree, and incidence matrices from the same graph, then used Python to verify their entries and relationships.
Adjacency matrices describe vertex connections, degree matrices describe incident edge counts, and incidence matrices match vertices to edges. Separate out-degree from in-degree in directed graphs, and edge counts from weight sums in weighted graphs. Before implementing a model, fix the vertex and edge orders, incidence signs, and self-loop convention.