隣接行列・次数行列・接続行列の理論と実装
実行環境
Python 3.14.6、NumPy 2.4.6、SciPy 1.18.1、NetworkX 3.7、Matplotlib 3.11.2(Jupyter Notebook)。
本記事は2021年頃の記事をリライトし、上記の環境で計算したものである。
概要
本記事は『グラフの理論と実践』の「グラフの基礎と行列表現」に属する。頂点どうしの関係を表す隣接行列、各頂点の次数を並べる次数行列、頂点と辺の関係を表す接続行列を扱う。同じグラフで定義と計算を対応させ、NumPyとNetworkXで実装する。有向グラフ、重み付きグラフ、孤立頂点も確認する。
計算の準備
コードは上から順に実行する。数値は表示時だけ有効数字3桁に整える。
実行環境の確認・ライブラリの読み込み・描画設定
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
以下は表示用の共通関数である。配列の文字出力には pprint()、数式には display() を使う。重要式の \(...\) はLaTeX出力に渡す。Markdown本文では、インライン数式を $...$、独立した数式を $$...$$ で記述する。
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. 頂点と辺の順序を決める
自己ループと多重辺を持たない無向グラフ $G=(V,E)$ から始める。
$$ \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} $$
頂点数は $n=5$、辺数は $m=4$ である。$v_5$ は辺を持たない孤立頂点である。行列の頂点順を $(v_1,v_2,v_3,v_4,v_5)$、辺順を $(e_1,e_2,e_3,e_4)$ に固定する。行列を比較するときは、まずこの順序を確認する。順序を変えるだけで成分の位置が変わるためである。
2. 隣接行列
隣接行列 $\mathbf{A}\in\mathbb{R}^{n\times n}$ の成分を次で定義する。
$$ a_{ij}=\begin{cases} 1 & \{v_i,v_j\}\in E,\\ 0 & \text{otherwise}. \end{cases} $$
第1行では $v_1$ とつながる $v_2,v_3$ の列だけが1になる。無向グラフなので $a_{ij}=a_{ji}$、自己ループがないので $a_{ii}=0$ である。孤立頂点に対応する第5行と第5列はすべて0となる。
まず辺の一覧から手で行列を作り、NetworkXの結果と比較する。to_numpy_array
の nodelist は行と列の順序を指定する引数である。
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} $$
隣接行列の積は何を数えるか
行列積の定義から、$\mathbf{A}^2$ の成分は次の和になる。
$$ (\mathbf{A}^2)_{ij}=\sum_{k=1}^{n}a_{ik}a_{kj}. $$
$a_{ik}a_{kj}=1$ となるのは、$v_i\to v_k\to v_j$ と2本の辺で移動できる場合である。例えば、
$$ \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} $$
前者は $v_1\to v_3\to v_4$、後者は $v_1\to v_2\to v_1$ と $v_1\to v_3\to v_1$ に対応する。一般に $(\mathbf{A}^{\ell})_{ij}$ は長さ $\ell$ の歩道の数である。歩道は頂点や辺を繰り返してよく、単純路の数とは異なる。コードでは行列積を @ で書く。A * A は成分ごとの積である。
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. 次数ベクトルと次数行列
頂点 $v_i$ の次数 $d_i$ は、その頂点に接続する辺の数である。隣接行列の第 $i$ 行を足せばよい。
$$ \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} $$
全成分が1の列ベクトルを $\mathbf{1}$ とすると、次数ベクトルは $\mathbf{d}=\mathbf{A}\mathbf{1}$ となる。次数行列 $\mathbf{D}$ は $d_i$ を対角成分に持ち、非対角成分を0とする行列である。
各辺は両端の次数に1ずつ加わるため、次数の和は辺数の2倍になる。この例では $2+2+3+1+0=8=2\cdot4$ である。また、$(\mathbf{A}^2)_{ii}=\sum_k a_{ik}a_{ki}=\sum_k a_{ik}^2=\sum_k a_{ik}=d_i$ となり、前節の対角成分とも一致する。
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. 接続行列は頂点と辺を対応させる
符号なし接続行列
接続行列では行が頂点、列が辺に対応する。符号なし接続行列 $\mathbf{C}\in\mathbb{R}^{n\times m}$ を、頂点 $v_i$ が辺 $e_k$ の端点なら $c_{ik}=1$、それ以外なら $c_{ik}=0$ と定義する。自己ループがないので、各列には1が2個ある。
符号付き接続行列
各辺に $e_1:v_1\to v_2$、$e_2:v_1\to v_3$、$e_3:v_2\to v_3$、$e_4:v_3\to v_4$ という向きを仮に付ける。これは計算のための向きであり、元の無向グラフの意味は変わらない。符号付き接続行列 $\mathbf{B}\in\mathbb{R}^{n\times m}$ は、
$$ 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} $$
とする。例えば第2列は $e_2:v_1\to v_3$ を表すので、$(-1,0,1,0,0)^{\mathsf{T}}$ となる。各列の和は0である。文献によって符号や転置の規約が異なるため、行・列の意味と符号を確認する必要がある。ここでは NetworkXの 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])}
頂点の値の差と、辺を流れる量
頂点の値を列ベクトル $\mathbf{x}=(1,2,4,7,0)^{\mathsf{T}}$ とする。$\mathbf{B}^{\mathsf{T}}\mathbf{x}$ は、各辺の「終点の値−始点の値」である。
$$ \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}. $$
逆に、辺の向きに沿う流量を $\mathbf{f}=(2,1,3,4)^{\mathsf{T}}$ とすると、$\mathbf{B}\mathbf{f}$ は各頂点の「流入量−流出量」となる。
$$ \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}. $$
全頂点で足すと $-3-1+0+4+0=0$ である。各辺が一方の流出と他方の流入に同じ量だけ寄与するためである。
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. 3種類の行列の関係
$(\mathbf{C}\mathbf{C}^{\mathsf{T}})_{ij}=\sum_k c_{ik}c_{jk}$ を考える。$i=j$ では接続する辺の数を数えるので $d_i$ となる。$i\ne j$ では、両頂点を端点に持つ辺がある場合だけ1となるため $a_{ij}$ になる。
$\mathbf{B}\mathbf{B}^{\mathsf{T}}$ でも対角成分は $\sum_k b_{ik}^2=d_i$ である。一方、辺の両端の符号は反対なので、非対角成分は $-a_{ij}$ となる。具体的には、
$$ \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} $$
よって $\mathbf{C}\mathbf{C}^{\mathsf{T}}=\mathbf{D}+\mathbf{A}$、$\mathbf{B}\mathbf{B}^{\mathsf{T}}=\mathbf{D}-\mathbf{A}$ である。後者はグラフラプラシアン $\mathbf{L}$ と呼ばれる。ここではこの関係までを確認する。
辺の向きを逆にすると、$\mathbf{B}$ の対応する列全体の符号が変わる。列ベクトルを $\mathbf{b}_k$ と書けば、積への寄与は $(-\mathbf{b}_k)(-\mathbf{b}_k)^{\mathsf{T}}=\mathbf{b}_k\mathbf{b}_k^{\mathsf{T}}$ のままである。したがって $\mathbf{B}\mathbf{B}^{\mathsf{T}}$ は計算用の向きに依存しない。
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. 有向グラフでは出次数と入次数を分ける
ここでは図4の矢印を実際の辺の向きとする。$v_i\to v_j$ があるとき $a_{ij}=1$ と定義する。行が出発点、列が到着点であり、一般には $\mathbf{A}_{\mathrm{dir}}^{\mathsf{T}}\ne\mathbf{A}_{\mathrm{dir}}$ である。行和は出次数、列和は入次数になる。
$$ \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} $$
例えば $v_3$ の出次数は $a_{31}+a_{32}+a_{33}+a_{34}+a_{35}=0+0+0+1+0=1$、入次数は $a_{13}+a_{23}+a_{33}+a_{43}+a_{53}=1+1+0+0+0=2$ である。それぞれを対角に並べた行列を $\mathbf{D}_{\mathrm{out}}$、$\mathbf{D}_{\mathrm{in}}$ とする。出次数の総和と入次数の総和は、どちらも辺数 $m$ に等しい。
符号付き接続行列の定義はそのまま使える。ただし $\mathbf{B}\mathbf{B}^{\mathsf{T}}$ は向きを反転しても変わらないため、有向グラフの情報をすべて保持する行列ではない。一般に $\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. 重み付きグラフ
元の無向グラフの辺に、順に $w_1=0.500$、$w_2=1.50$、$w_3=2.00$、$w_4=1.00$ を与える。重み付き隣接行列 $\mathbf{A}_w$ では、辺がある位置に1の代わりに重みを入れる。重みの総和 $s_i=\sum_j(\mathbf{A}_w)_{ij}$ は重み付き次数であり、辺の本数を数える次数とは区別する。
$$ \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} $$
重み付き次数行列を $\mathbf{D}_w=\operatorname{diag}(s_1,\ldots,s_n)$、辺の重みの対角行列を $\mathbf{W}=\operatorname{diag}(w_1,\ldots,w_m)$ とする。$\mathbf{B}$ は重みを含まない $-1,0,1$ の行列のまま使う。このとき、
$$ \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. $$
対角成分には接続する辺の重みが足され、非対角成分にはその辺の重みの負値が入る。例えば第1行について、対角成分は $(-1)^2\cdot0.500+(-1)^2\cdot1.50=2.00$、第2列の成分は $(-1)\cdot0.500\cdot1=-0.500$ となる。
注意点は incidence_matrix(..., weight="weight")
が $\pm w_k$ を入れた行列 $\mathbf{B}_w=\mathbf{B}\mathbf{W}$ を返すことである。この行列をそのまま掛けると $\mathbf{B}_w\mathbf{B}_w^{\mathsf{T}}=\mathbf{B}\mathbf{W}^2\mathbf{B}^{\mathsf{T}}$ となり、重みが二乗される。例えば第1対角成分は $0.500^2+1.50^2=2.50$ となってしまう。$\mathbf{B}\mathbf{W}\mathbf{B}^{\mathsf{T}}$ と計算するか、列を $\sqrt{w_k}$ 倍した行列を使う。後者は非負の重みで使える実数表現である。
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. 行列の順序と適用範囲を確認する
頂点の並べ替えを表す置換行列を $\mathbf{P}$ とすると、$\mathbf{A}^{\prime}=\mathbf{P}\mathbf{A}\mathbf{P}^{\mathsf{T}}$、$\mathbf{D}^{\prime}=\mathbf{P}\mathbf{D}\mathbf{P}^{\mathsf{T}}$ となる。接続行列では、辺順を固定した場合は $\mathbf{B}^{\prime}=\mathbf{P}\mathbf{B}$ である。第1行を $v_3$、続いて $v_1,v_2,v_4,v_5$ の順に変えても、グラフ自体は同じである。
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} $$
ここまでの単純な恒等式は、自己ループを除くという前提で導いた。NetworkXの隣接行列では自己ループの重みを対角成分に1回入れるが、無向グラフの次数ではループを2回数える。したがって自己ループがある場合、隣接行列の行和と通常の次数はそのままでは一致しない。自己ループの規約 を確認する必要がある。
多重辺を使う場合は、隣接行列に辺の本数または重みの合計を入れるなど、集約方法も決める。本記事の $0,1$ の定義をそのまま適用する対象ではない。大規模なグラフを疎行列で保持する方法は、次の記事「疎行列による大規模グラフの表現と計算量」で扱う。
結論
この記事では、隣接行列・次数行列・接続行列を同じグラフから構成し、成分の意味と行列間の関係をPythonで確認した。
隣接行列は頂点間の接続、次数行列は各頂点に集まる辺の数、接続行列は頂点と辺の対応を表す。有向グラフでは出次数と入次数を分け、重み付きグラフでは辺の本数と重みの総和を区別する。実装では頂点・辺の順序、接続行列の符号、自己ループの扱いを先に固定することが必要である。