第17章 流动性与OD矩阵建图

邻接图从几何形状推导连接关系,回答”空间上谁挨着谁”。但城市里还有另一类关系,它的证据不在几何里,而在一张表里:从 A 区搬到 B 区的人口数、从 A 站到 B 站的通勤量、从 A 点骑到 B 点的共享单车订单数。这类数据叫起点—讫点数据(origin-destination data,简称 OD 数据),它是交通规划、人口迁移研究、通勤分析、共享出行研究的基础素材。

od_matrix_to_graph 把 OD 数据接进了 City2Graph 的图体系。它的输入不再是面几何之间的关系,而是一张”谁流向谁、流了多少”的表;它的输出仍然是 (nodes_gdf, edges_gdf) 二元组,因此可以与邻接图、交通图、元路径图无缝拼接。本章从 OD 数据的基本形态讲起,把两种输入模式(边表与邻接矩阵)、七个关键参数、内部聚合口径、返回结构逐层拆开,最后用一个英格兰与威尔士 MSOA 迁移数据的完整案例收尾。


17.1 本章导读

17.1.1 学习目标

能力 说明
认出两种输入形态 边表(edgelist)与邻接矩阵(adjacency matrix)的表达差异与适用场景
掌握参数契约 source_col、target_col、weight_cols、threshold_col、zone_id_col 的联动约束
理解聚合口径 重复流量合并、互惠流量合并、阈值的”先合并后筛选”语义
读懂返回结构 节点索引与 zone ID 的对齐、边表 MultiIndex、边几何的构造方式
处理真实数据 普查 OD 表的列名映射、异常 ID 过滤、坐标系选择
排查常见错误 邻接矩阵非方阵、权重列缺失、多权重未指定阈值列等报错的定位

17.1.2 为什么 OD 数据要变成图

OD 数据本质上已经在描述一个有向加权图:每一行 (origin, destination, flow) 就是一条边。既然如此,为什么还要”转成图”?

因为直接操作 DataFrame 做网络分析很笨拙。你需要自己处理:

  • 邻接结构:把 (u,v) 对列表转成邻接表或稀疏矩阵,供最短路、中心性、社区发现使用。
  • 节点属性:把区县几何、名称、人口等属性挂到节点上,供可视化和空间统计使用。
  • 几何表示:画一张流量地图,需要把每条流量画成一条线。
  • 格式互通:转 NetworkX 做图算法,转 PyTorch Geometric 做图神经网络。

od_matrix_to_graph 把这四件事一次做完,输出与 City2Graph 其他建图函数完全同构的结果。这是”以 GeoDataFrame 为一等公民”的设计哲学(第 4 章)在流动性数据上的体现。


17.2 概念原理:OD 数据的三种形态

17.2.1 形态一:长表(long format / edge list)

最直观的表达,每行一条流量:

origin destination trips
甲区 乙区 120
甲区 丙区 45
乙区 甲区 98

优点:稀疏友好(只存非零项)、可携带任意多个属性列、易于增量追加。 缺点:看不出”全量矩阵”的结构,做矩阵运算前要先 pivot。

17.2.2 形态二:宽表(wide format / adjacency matrix)

行列都是区域,单元格是流量:

  甲区 乙区 丙区
甲区 0 120 45
乙区 98 0 12
丙区 7 3 0

优点:矩阵运算直接可用、视觉上能看出流向格局、对称性一目了然。 缺点:稠密存储(N² 单元格)、不适合 N 上万的场景。

17.2.3 形态三:NumPy 数组

就是宽表的裸数组形式,没有行列标签:

import numpy as np

A = np.array([
    [0, 120, 45],
    [98, 0, 12],
    [7, 3, 0],
])

优点:内存紧凑、计算快。 缺点:标签丢了,只能约定”行列顺序与 zones_gdf 的行顺序一致”。这个约定极易出错,所以 od_matrix_to_graph 在收到 ndarray 时会主动发一条警告提醒你。

17.2.4 三种形态与函数参数的对应

输入形态 matrix_type od_data 类型 关键参数
长表 "edgelist" pd.DataFrame source_col、target_col、weight_cols
宽表 "adjacency" pd.DataFrame 行列标签须与 zone ID 一致
数组 "adjacency" np.ndarray 顺序须与 zones_gdf 一致

注意 matrix_type 的默认值是 "edgelist",这是有意为之:长表更常见,也更不容易出错。

17.2.5 有向与无向:两种叙事

OD 数据天生有向(甲→乙 与 乙→甲 是两回事)。但很多分析场景需要把它当无向网络看:

场景 推荐 理由
通勤流向、人口迁移 有向(directed=True) 净流向本身是研究对象
城市间联系强度 无向(directed=False) 关心”联系多紧密”而非方向
社区发现 无向 多数社区算法假设无向
距离衰减模型 有向 需区分单向吸引

directed=False 时,函数会把 (u,v) 与 (v,u) 的流量相加合并成一条无向边。这个”先合并”的语义直接影响阈值的筛选结果,是本章最容易误解的地方(见 17.4.4)。


17.3 API 详解:od_matrix_to_graph

17.3.1 函数签名

city2graph.mobility.od_matrix_to_graph(
    od_data: pandas.DataFrame | numpy.ndarray,
    zones_gdf: geopandas.GeoDataFrame,
    zone_id_col: str | None = None,
    *,
    matrix_type: Literal["edgelist", "adjacency"] = "edgelist",
    source_col: str = "source",
    target_col: str = "target",
    weight_cols: list[str] | None = None,
    threshold: float | None = None,
    threshold_col: str | None = None,
    include_self_loops: bool = False,
    compute_edge_geometry: bool = True,
    directed: bool = True,
    as_nx: bool | None = None,
) -> tuple[geopandas.GeoDataFrame, geopandas.GeoDataFrame] | networkx.Graph | networkx.DiGraph

参数表展开:

参数 类型 默认值 含义
od_data DataFrame / ndarray 必填 OD 数据本体
zones_gdf GeoDataFrame 必填 区域几何,必须含唯一标识
zone_id_col str / None None 区域 ID 所在列名;为 None 时用索引
matrix_type str "edgelist" 输入解释方式:"edgelist" 或 "adjacency"
source_col str "source" 长表中起点列名
target_col str "target" 长表中讫点列名
weight_cols list[str] / None None 要保留的权重列;长表必填
threshold float / None None 最小流量阈值(含等于)
threshold_col str / None None 多权重列时指定用哪一列做阈值筛选与主权重
include_self_loops bool False 是否保留 source == target 的记录
compute_edge_geometry bool True 是否生成质心间的 LineString
directed bool True 有向图还是无向图(无向会合并互惠流量)
as_nx bool / None None 已弃用,建议用 gdf_to_nx

17.3.2 参数联动规则

这几个参数不是独立的,有几条硬约束由校验函数 _validate_od_inputs 强制:

规则一:长表必须给 weight_cols

if not weight_cols:
    msg = "weight_cols must be provided (at least one weight column) for edgelist input"
    raise ValueError(msg)

即使是”一列流量”,也必须显式写出列名。这是为了避免”猜错列”的静默错误。

规则二:多权重必须指定 threshold_col

if len(weight_cols) > 1 and (threshold_col is None or threshold_col not in weight_cols):
    msg = "When multiple weight_cols are provided a valid threshold_col must be specified"
    raise ValueError(msg)

为什么?因为阈值只能作用在一列上。若给了 ["trips", "cost"] 两列,函数无法自行判断”用 trips 筛还是用 cost 筛”。

规则三:如果权重列里有 "weight",它必须是主列

if "weight" in weight_cols and _resolve_primary(weight_cols, threshold_col) != "weight":
    msg = (
        "When weight_cols contains 'weight', threshold_col must be 'weight'; "
        "rename the input weight column to use a different primary weight"
    )
    raise ValueError(msg)

原因是输出边表里 weight 是规范列名(canonical column),函数会把主权重列的值写进 weight。如果输入里已经有个叫 weight 的列但主列是别的,就会发生覆盖。解决办法:把输入列改名(比如 flow),或者让 weight 当主列。

规则四:邻接矩阵必须是方阵,且行列标签完全一致

checks = [
    (od_data.shape[0] == od_data.shape[1], "Adjacency DataFrame must be square"),
    (od_data.index.equals(od_data.columns), "Adjacency DataFrame index and columns must match exactly"),
    (od_data.index.is_unique and od_data.columns.is_unique, "Adjacency DataFrame index and columns must be unique"),
]

第二条用的是 .equals(),不只是”集合相同”,连顺序都必须一致。这一点很容易踩:df.pivot() 出来的矩阵有时列顺序与行顺序不同,需要 reindex(index=..., columns=...) 对齐。

规则五:ndarray 尺寸必须等于区域数

if od_data.shape[0] != len(zones_gdf):
    msg = "Adjacency ndarray size must match number of zones in zones_gdf"
    raise ValueError(msg)

同时会发一条警告:

Assuming ndarray row/column ordering matches zones_gdf order (requirement 5.7); ndarray rows=...

这条警告是在提醒你:函数无法验证顺序,只能相信你。

17.3.3 区域表的要求

zones_gdf 的要求由 _validate_zones_gdf 强制:

要求 违反时的异常
必须是 gpd.GeoDataFrame TypeError: zones_gdf must be a GeoDataFrame
若给了 zone_id_col,该列必须存在 ValueError: zone_id_col 'x' not found in zones_gdf columns
ID 不得为空 ValueError: zone_id_col contains null values
ID 必须唯一 ValueError: zone_id_col values must be unique

另有 CRS 相关的警告(不是错误):

GeoDataProcessor.warn_crs_issues(
    zones_gdf,
    missing_message="zones_gdf has no CRS set; outputs will have undefined CRS (requirement 3.1)",
    geographic_message="Geographic CRS detected; distance/length measures may be inaccurate (requirement 3.5)",
)

也就是说:没有 CRS 只会警告,不会中断;但如果后续要做距离计算,结果不可信。

17.3.4 返回结构

GeoDataFrame 模式(默认)

返回 (nodes_gdf, edges_gdf)。

节点表:

  • 索引:如果 zone_id_col 给了,索引就是该列的值(列本身保留,因为用的是 set_index(zone_id_col, drop=False))。
  • 列:zones_gdf 的全部列(含几何)。
  • CRS:与 zones_gdf 一致。
  • 行数等于 len(zones_gdf),与 OD 表里出现了多少区域无关。没有流量的区域也会作为孤立节点保留。

边表:

  • 索引:MultiIndex[(source, target)]。
  • 列:weight(主权重)、其他 weight_cols(按给定顺序)、geometry。
  • CRS:与 zones_gdf 一致。

举个具体例子。输入长表:

source  target  flow
A       B       5
B       A       3

directed=True(默认)时输出两行边:(A,B) weight=5 flow=5 与 (B,A) weight=3 flow=3。

directed=False 时输出一行边:(A,B) weight=8 flow=8(顺序按字符串比较,A < B)。

NetworkX 模式

as_nx=True 返回 nx.DiGraph(有向)或 nx.Graph(无向)。同样已弃用,推荐:

nodes, edges = c2g.od_matrix_to_graph(...)
G = c2g.gdf_to_nx(nodes, edges, directed=True, keep_geom=True)

17.4 内部流程:从原始 OD 到空间图

17.4.1 主流程五步

    # 1. 校验
_validate_od_inputs(od_data, zones_gdf, zone_id_col=zone_id_col, matrix_type=matrix_type, ...)

    # 2. 规范化为统一的长表(canonical edgelist)
edge_df = _build_canonical_edgelist(od_data, zones_gdf, ...)

    # 3. 空间装配:节点表 + 边表 + 边几何
nodes_gdf, edges_gdf = _assemble_od_frames(edge_df, zones_gdf, zone_id_col=zone_id_col, compute_edge_geometry=compute_edge_geometry)

    # 4. 输出选择
if not as_nx:
    return nodes_gdf, edges_gdf
G = gdf_to_nx(nodes=nodes_gdf, edges=edges_gdf, keep_geom=compute_edge_geometry, directed=directed)
return G

这个设计的关键是第 2 步:无论输入是长表、宽表还是数组,都先归一化成同一种”规范长表”(列名为 source、target、weight 加额外权重列)。后续所有逻辑只面对一种形态,代码复杂度大幅下降。

17.4.2 长表的处理链

matrix_type="edgelist" 时调用两次:

aligned = _align_edgelist_zones(od_data, zones_gdf=zones_gdf, zone_id_col=zone_id_col,
                               source_col=source_col, target_col=target_col)
edge_df = _normalize_edgelist(aligned, source_col=source_col, target_col=target_col,
                              weight_cols=weight_cols or [], threshold=threshold,
                              directed=directed, threshold_col=threshold_col,
                              include_self_loops=include_self_loops)

第一步:_align_edgelist_zones

按区域表过滤:只要起点或讫点不在 zones_gdf 的 ID 集合里,整行丢弃。

这一步非常重要,因为真实 OD 表几乎总有”外部区域”:普查数据里有”不适用”代码(如英国的 -8)、有境外地区、有已撤销的行政区。不过滤的话下游会拿到指向不存在节点的边。

注意这个函数不做聚合——重复的 (source, target) 行会保留到下一步。

第二步:_normalize_edgelist

这是整个模块最复杂的函数,做的事按顺序是:

序号 操作 源码要点
1 权重列强制转数值 _coerce_weight_columns,无法解析的变 NaN 并填 0
2 负数检查 负权重只警告不报错
3 去自环 include_self_loops=False 时丢弃 source == target
4 确定主权重列 单列就是它;多列用 threshold_col
5 丢弃全零行 仅当 threshold is None or threshold > 0 时执行
6 无向化 directed=False 时把 (u,v)、(v,u) 端点规范化
7 聚合 按 (source, target) 分组求和所有权重列
8 阈值筛选 对主权重列应用 >= threshold(或 > 0)
9 规范列名 重命名为 source、target、weight

最终返回的列顺序固定为:

cols = ["source", "target", "weight", *remaining_weights]

其中 remaining_weights 是 weight_cols 里除 "weight" 外的列。

17.4.3 无向化的端点规范化

directed=False 时,必须保证 (A,B) 与 (B,A) 变成同一个键。函数用 _canonicalize_undirected_endpoints 做这件事,规则是按字符串比较:较小的 ID 做 source,较大的做 target。

这里有个精妙之处:如果两个不同的 ID 的字符串形式相同(比如整数 1 和字符串 "1"),直接转字符串排序会产生”碰撞”。源码用 _can_have_string_label_collision 检测这种情况并特殊处理,保证不同 ID 不会被误合并。这属于边缘情况,但如果你的 ID 列是 object 类型混了 int 和 str,就会触发。

实践建议:把 ID 列统一成字符串(astype(str)),既避免碰撞,又避免 sorted 的 TypeError。

17.4.4 阈值的准确语义

这是最容易被误解的部分。手册里写”threshold:最小流量阈值(含等于)”,但完整语义要分情况:

情况 筛选条件 何时应用
threshold=None weight > 0 聚合后
threshold > 0 weight >= threshold 聚合后
threshold = 0 weight >= 0,保留 0 值边 聚合后
threshold < 0 weight >= threshold,包含 0 与负值 聚合后

关键点:先聚合、后筛选。这保证了 directed=False 时阈值作用在”双向流量之和”上,而不是先各自筛选再相加。

举例说明差异。假设 (A,B)=3、(B,A)=4,阈值设为 5:

  • 若”先筛后合”:(3 < 5 丢弃, 4 < 5 丢弃) → 结果无边。
  • 若”先合后筛”:(3+4=7 ≥ 5) → 结果有一条边,权重 7。

City2Graph 采用后者。对于”城市间联系强度”这类分析,这个语义更合理:单向看都很弱,但双向加起来说明联系确实存在。

threshold=0 的陷阱:在邻接矩阵模式下它会保留所有零值单元格,产生 O(N²) 条边。源码注释里明确警告了这一点:

When matrix_type='adjacency' and threshold <= 0 (for example, threshold=0),
zero-valued cells are also retained as edges, which produces a dense graph
of O(N²) edges for large matrices.

对一个 7000 区的矩阵,那就是 4900 万条边。慎用。

17.4.5 邻接矩阵的处理链

matrix_type="adjacency" 且输入是 DataFrame 时:

adj = _align_adjacency_zones(od_data, zones_gdf=zones_gdf, zone_id_col=zone_id_col)
edge_df = _adjacency_to_edgelist(adj, include_self_loops=include_self_loops,
                                 threshold=threshold, directed=directed)

_align_adjacency_zones 只保留”矩阵标签 ∩ 区域 ID”的重叠部分,缺失的两侧都发警告:

缺失方向 警告文案 后果
区域有、矩阵无 N zone IDs in zones_gdf not present in adjacency; they will be isolated nodes 这些区域成为孤立节点
矩阵有、区域无 N labels in adjacency not present in zones_gdf; related edges will be dropped 这些流量边被丢弃
完全没有交集 ValueError: No overlapping zone IDs between adjacency matrix and zones_gdf 直接报错

然后把矩阵转成边表。转换用 NumPy 向量化实现,核心是构造一个布尔掩码:

mask = (arr > 0) if threshold is None else (arr >= threshold)
if not include_self_loops:
    np.fill_diagonal(mask, val=False)

无向模式下不走”全矩阵展平再 groupby”,而是直接在上三角计算互惠和,源码注释称之为”bounded row batches”的优化,避免稠密矩阵展平成边表时的内存爆炸。这对大矩阵很重要:7000×7000 的矩阵若展平成 4900 万行 DataFrame,光内存就是几个 GB。

17.4.6 边几何的构造

compute_edge_geometry=True(默认)时,每条边生成一条连接两个区域质心的 LineString。实现要点(_create_edge_geometries):

  1. 质心只算一次:GeoDataProcessor.compute_centroids(zones_gdf) 对全部区域批量算质心。
  2. 过滤无质心的区域:None 或空几何的质心不参与映射。
  3. 用 get_indexer 做批量查找:比逐行 .loc 快几个数量级。
  4. 找不到的边丢弃并警告:
warnings.warn(
    f"Dropping {n_missing} edges with unknown zone IDs or missing centroid(s) (requirement 3.6)",
    UserWarning,
    stacklevel=2,
)
  1. 用 shapely.linestrings 一次性批量构造:
line_coords = np.empty((len(src_idx), 2, 2), dtype=np.float64)
line_coords[:, 0, :] = valid_coords[src_idx]
line_coords[:, 1, :] = valid_coords[tgt_idx]
geom = gpd.GeoSeries(linestrings(line_coords), crs=zones_gdf.crs)

这个 (N, 2, 2) 数组的形状值得记一下:N 条线,每条 2 个点,每点 2 个坐标。这是 Shapely 2.0 批量 API 的标准输入格式。

compute_edge_geometry=False 时会返回一个 geometry 列全为 None 的 GeoDataFrame——结构仍然完整,只是没有几何。


17.5 完整示例一:长表建图

17.5.1 构造 4×4 网格区域

import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from shapely.geometry import box

import city2graph as c2g

    # 4x4 的 1 度方格(用 4326 只为方便演示,真实分析请投影)
cells, zone_ids = [], []
for i in range(4):      # 行(y 方向)
    for j in range(4):  # 列(x 方向)
        cells.append(box(j, i, j + 1, i + 1))
        zone_ids.append(f"G{j}{i}")

zones_gdf = gpd.GeoDataFrame({"zone_id": zone_ids}, geometry=cells, crs="EPSG:4326")
print(f"{len(zones_gdf)} 个区域")
print(zones_gdf.head(3))
16 个区域
  zone_id                                           geometry
0     G00  POLYGON ((1 0, 1 1, 0 1, 0 0, 1 0))
1     G10  POLYGON ((2 0, 2 1, 1 1, 1 0, 2 0))
2     G20  POLYGON ((3 0, 3 1, 2 1, 2 0, 3 0))

17.5.2 单权重长表

E = pd.DataFrame({
    "source": ["G00", "G00", "G10", "G01", "G22", "G23", "G12"],
    "target": ["G10", "G01", "G11", "G11", "G32", "G33", "G22"],
    "flow":   [5,     2,     3,     7,     4,     6,     5],
})

nodes_gdf1, edges_gdf1 = c2g.od_matrix_to_graph(
    E, zones_gdf, zone_id_col="zone_id",
    matrix_type="edgelist",
    source_col="source", target_col="target",
    weight_cols=["flow"],
    threshold=None,           # 只丢零值
    include_self_loops=False,
    compute_edge_geometry=True,
    directed=True,
 )

print(f"节点 {len(nodes_gdf1)},边 {len(edges_gdf1)}")
print(edges_gdf1.head())
节点 16,边 7
                  weight  flow                                           geometry
source target
G00    G01          2.0   2.0  LINESTRING (0.5 0.5, 0.5 1.5)
       G10          5.0   5.0  LINESTRING (0.5 0.5, 1.5 0.5)
G01    G11          7.0   7.0  LINESTRING (0.5 1.5, 1.5 1.5)
G10    G11          3.0   3.0  LINESTRING (1.5 0.5, 1.5 1.5)
G12    G22          5.0   5.0  LINESTRING (1.5 2.5, 2.5 2.5)

几个观察:节点 16 个(全部区域),边 7 条(OD 表有 7 行)。weight 与 flow 数值相同——因为 flow 是唯一权重列,它既是主权重也是规范 weight。

17.5.3 可视化

ax = zones_gdf.boundary.plot(color="#2E86AB", alpha=0.8, linewidth=0.8, figsize=(8, 8))
c2g.plot_graph(
    nodes=nodes_gdf1.set_geometry(nodes_gdf1.centroid),
    edges=edges_gdf1,
    ax=ax,
    bgcolor="#f8f9fa",
    node_color="#2E86AB",
    node_alpha=0.8,
    markersize=20,
    edge_color="#E67E22",
    edge_linewidth=np.log1p(edges_gdf1["weight"]) * 1.2,
)
plt.title("4x4 网格上的有向 OD 图")
plt.axis("equal")
plt.axis("off")
plt.show()

set_geometry(nodes_gdf1.centroid) 这一步是必要的:节点几何是面,plot_graph 画点更清晰,所以临时换成质心(不改变原对象)。

17.5.4 重复流量如何合并

假设 OD 表里同一个 (source, target) 出现多次——这在分时段、分出行目的的数据里很常见:

E_dup = pd.DataFrame({
    "source": ["G00", "G00", "G00", "G10"],
    "target": ["G10", "G10", "G11", "G11"],
    "flow":   [2,     3,     1,     4],
})

_, edges_dup = c2g.od_matrix_to_graph(
    E_dup, zones_gdf, zone_id_col="zone_id",
    weight_cols=["flow"], directed=True,
)
print(edges_dup)
                  weight  flow
source target
G00    G10          5.0   5.0
       G11          1.0   1.0
G10    G11          4.0   4.0

两个 G00→G10 的 2 和 3 被合并成 5。这是 _aggregate_edgelist 里一次 groupby([source, target]).sum() 的结果。


17.6 完整示例二:多权重与无向合并

17.6.1 构造互惠流量 + 双权重

E2 = pd.DataFrame({
    "source": ["G00", "G10", "G01", "G11", "G22", "G32", "G23", "G33"],
    "target": ["G10", "G00", "G11", "G01", "G32", "G22", "G33", "G23"],
    "trips":  [5,     1,     7,     2,     4,     3,     8,     2],
    "cost":   [10,    2,     12,    3,     7,     4,     15,    3],
})

这里有 4 对互惠边:(G00,G10)/(G10,G00)、(G01,G11)/(G11,G01)、(G22,G32)/(G32,G22)、(G23,G33)/(G33,G23)。

17.6.2 无向 + 多权重 + 阈值

nodes_gdf2, edges_gdf2 = c2g.od_matrix_to_graph(
    E2, zones_gdf, zone_id_col="zone_id",
    matrix_type="edgelist",
    source_col="source", target_col="target",
    weight_cols=["trips", "cost"],
    threshold=3, threshold_col="trips",
    include_self_loops=False,
    compute_edge_geometry=True,
    directed=False,   # 无向:合并互惠流量
 )

print(edges_gdf2)
                  weight  trips  cost
source target
G00    G10          6.0    6.0   12.0
G01    G11          9.0    9.0   15.0
G22    G32          7.0    7.0   11.0
G23    G33         10.0   10.0   18.0

逐个验证:

边 trips 合并 cost 合并 阈值 3 筛 trips
G00–G10 5+1=6 10+2=12 6 ≥ 3 保留
G01–G11 7+2=9 12+3=15 9 ≥ 3 保留
G22–G32 4+3=7 7+4=11 7 ≥ 3 保留
G23–G33 8+2=10 15+3=18 10 ≥ 3 保留

四条边全部保留,且所有权重列都做了求和(不只是主列)。这一点很重要:cost 也变成 12、15、11、18,而不是原值。

17.6.3 端点顺序的规范化

注意输出里所有边的 source 都小于 target(字符串比较:"G00" < "G10" 等)。这是 _canonicalize_undirected_endpoints 的作用。

如果换成 directed=True,同样输入会得到 8 条边,没有合并,端点顺序也保持原样。

17.6.4 阈值的不同结果演示

把阈值提高到 8:

_, edges_hi = c2g.od_matrix_to_graph(
    E2, zones_gdf, zone_id_col="zone_id",
    weight_cols=["trips", "cost"],
    threshold=8, threshold_col="trips",
    directed=False,
)
print(edges_hi[["weight", "trips"]])
                  weight  trips
source target
G01    G11          9.0    9.0
G23    G33         10.0   10.0

只剩两条。注意 G00–G10 的 trips 是 6 < 8 被丢掉了——如果阈值是在合并前应用的,5 和 1 都会被丢,结果同样没有这条边。这里”先合后筛”的差别看不出来。真正能看出差别的例子是阈值 4:

边 单向值 合并值 阈值 4 先合后筛 阈值 4 先筛后合
G00–G10 5, 1 6 保留(6≥4) 保留(5≥4)
G01–G11 7, 2 9 保留 保留
G22–G32 4, 3 7 保留(7≥4) 保留(4≥4)
G23–G33 8, 2 10 保留 保留

这个例子里差别不明显。构造一个反例:(A,B)=3、(B,A)=3,阈值 5:

策略 结果
先合后筛 3+3=6 ≥ 5,保留
先筛后合 3 < 5 且 3 < 5,全丢

City2Graph 采用先合后筛,所以边会被保留。这个语义对于”联系强度”分析是合理的,对于”只要强单向流”的分析则可能过宽——那时应该用 directed=True。


17.7 完整示例三:邻接矩阵 Input

17.7.1 从长表构造矩阵

ids = zones_gdf["zone_id"]
A = pd.DataFrame(0.0, index=ids, columns=ids)

A.loc["G00", "G10"] = 5
A.loc["G00", "G01"] = 2
A.loc["G10", "G11"] = 3
A.loc["G01", "G11"] = 7
A.loc["G22", "G32"] = 4
A.loc["G23", "G33"] = 6
A.loc["G12", "G22"] = 5

nodes_gdf3, edges_gdf3 = c2g.od_matrix_to_graph(
    A, zones_gdf, zone_id_col="zone_id",
    matrix_type="adjacency",
    include_self_loops=False,
    threshold=None,
    directed=True,
)
print(f"边 {len(edges_gdf3)}")
print(edges_gdf3)
边 7
                  weight                                          geometry
source target
G00    G01          2.0  LINESTRING (0.5 0.5, 0.5 1.5)
       G10          5.0  LINESTRING (0.5 0.5, 1.5 0.5)
G01    G11          7.0  LINESTRING (0.5 1.5, 1.5 1.5)
G10    G11          3.0  LINESTRING (1.5 0.5, 1.5 1.5)
G12    G22          5.0  LINESTRING (1.5 2.5, 2.5 2.5)
G22    G32          4.0  LINESTRING (2.5 1.5, 2.5 0.5)
G23    G33          6.0  LINESTRING (2.5 2.5, 2.5 3.5)

结果与 17.5.2 节的长表示例基本一致(细节差异来自数据不同),说明两种输入模式在语义上等价。

17.7.2 NumPy 数组模式

A_arr = A.to_numpy()
nodes_gdf4, edges_gdf4 = c2g.od_matrix_to_graph(
    A_arr, zones_gdf, zone_id_col="zone_id",
    matrix_type="adjacency",
    directed=True,
)
print(f"边 {len(edges_gdf4)}")

运行时会看到警告:

UserWarning: Assuming ndarray row/column ordering matches zones_gdf order (requirement 5.7); ndarray rows=16

这条警告是设计上的”安全带”。如果你的 zones_gdf 顺序和数组顺序不一致,结果会全错但不报错。所以用数组前务必确认排序:

assert A_arr.shape[0] == len(zones_gdf)
assert (A.index == zones_gdf["zone_id"]).all()   # 构造时确认过

17.7.3 矩阵与区域不完全重叠

    # 部分重叠:去掉两个区域
zones_subset = zones_gdf.iloc[:14]   # 少 2 个

nodes_part, edges_part = c2g.od_matrix_to_graph(
    A, zones_subset, zone_id_col="zone_id",
    matrix_type="adjacency",
    directed=True,
)
print(f"节点 {len(nodes_part)},边 {len(edges_part)}")

会看到警告:

UserWarning: 2 zone IDs in zones_gdf not present in adjacency; they will be isolated nodes
UserWarning: 2 labels in adjacency not present in zones_gdf; related edges will be dropped

注意第一个警告的措辞与实际不符:这两行代码里 zones_subset 只有 14 行,矩阵有 16 个标签,所以是”矩阵有、区域无”的情况——但因为 _align_adjacency_zones 会先算交集再分别报告两侧差集,实际行为是对的,只是提示文字中”zones_gdf not present in adjacency”这一句要按方向理解。


17.8 综合案例:英格兰与威尔士 MSOA 迁移网络

17.8.1 数据背景

英国 2021 年人口普查发布了 MSOA(Middle layer Super Output Area,中层超级输出区)级别的迁移 OD 表,记录”一年前住在某地、现在住在另一地”的人数。MSOA 在英格兰与威尔士共约 7200 个,是研究城市尺度人口流动的标准空间单元。

数据来源:

数据 提供方 用途
ODMG01EW(OD 迁移表) Nomis / ONS 流量
MSOA 2021 边界 ONS Open Geography 区域几何

典型的 OD 表列名很长,需要映射到函数参数:

原始列名 含义 映射到
Migrant MSOA one year ago code 一年前居住地代码 source_col
Middle layer Super Output Areas code 现居住地代码 target_col
Count 人数 weight_cols
(边界表)MSOA21CD 区域代码 zone_id_col

17.8.2 完整流程

import geopandas as gpd
import pandas as pd
import city2graph as c2g

    # 1. 读入数据
zones_msoa = gpd.read_file("MSOA_2021_EW_BGC.gpkg")
od_table = pd.read_csv("ODMG01EW_MSOA.csv")

print(f"区域 {len(zones_msoa)} 个,CRS = {zones_msoa.crs}")
print(f"OD 记录 {len(od_table)} 条")

    # 2. 投影到英国国家格网(单位:米)
zones_msoa = zones_msoa.to_crs(27700)

    # 3. 建图(无向,把迁移看作双向联系)
source_col = "Migrant MSOA one year ago code"
target_col = "Middle layer Super Output Areas code"
weight_col = "Count"
zone_id_col = "MSOA21CD"

od_nodes, od_edges = c2g.od_matrix_to_graph(
    od_table, zones_msoa, zone_id_col=zone_id_col,
    matrix_type="edgelist",
    source_col=source_col, target_col=target_col,
    weight_cols=[weight_col],
    threshold=None,
    include_self_loops=False,
    compute_edge_geometry=True,
    directed=False,
)
print(f"节点 {len(od_nodes)},边 {len(od_edges)}")

参考输出(数据版本不同会有差异):

区域 7264 个,CRS = EPSG:27700
OD 记录 537000 条
节点 7264,边 1228547

160 万行的 OD 表建出 120 万条边,这个规模说明为什么需要 directed=False:有向的话边数会翻倍到 240 万,内存和后续算法都吃不消。

17.8.3 关键细节:负代码过滤

普查 OD 表里有一种特殊值:-8,表示”不适用”(比如一年前住在国外的人)。这些行会被 _align_edgelist_zones 自动过滤掉,因为 -8 不在 zones_msoa[zone_id_col] 里。

但要注意:过滤是静默的,不会警告。所以建议自己先检查一下丢了多少:

valid_ids = set(zones_msoa[zone_id_col])
n_before = len(od_table)
n_after = od_table[od_table[source_col].isin(valid_ids) & od_table[target_col].isin(valid_ids)].shape[0]
print(f"过滤掉 {n_before - n_after} 行({(n_before - n_after) / n_before:.1%})")

    # 看看被丢弃的来源都有什么
dropped_src = od_table.loc[~od_table[source_col].isin(valid_ids), source_col].value_counts()
print(dropped_src.head())

17.8.4 网络分析:度中心性

import networkx as nx

G = c2g.gdf_to_nx(od_nodes, od_edges)

degree_centrality = nx.degree_centrality(G)
nx.set_node_attributes(G, degree_centrality, "degree_centrality")

od_nodes, od_edges = c2g.nx_to_gdf(G)
print(od_nodes[["MSOA21NM", "degree_centrality"]].sort_values("degree_centrality", ascending=False).head())
                        MSOA21NM  degree_centrality
MSOA21CD
E02000001        City of London 001           0.116205
E02000003   Barking and Dagenham 002           0.061683
E02000005   Barking and Dagenham 004           0.055349

City of London 的度中心性显著高于其他区域,反映它作为就业中心吸引大量通勤与迁移。

17.8.5 加权度:总流量

度中心性只看”连了多少边”,不看流量大小。要看流量规模得算加权度:

weighted_degree = dict(G.degree(weight="weight"))
od_nodes["total_migration"] = od_nodes.index.map(weighted_degree).fillna(0)

top = od_nodes.nlargest(10, "total_migration")[["MSOA21NM", "total_migration"]]
print(top)

这个指标能识别”人口吸引中心”,比度中心性更有解释力。

17.8.6 只画强流量

170 万条边画出来是一团黑。筛选阈值:

strong_edges = od_edges[od_edges["weight"] >= 10]
print(f"强流量边 {len(strong_edges)} 条(占 {len(strong_edges)/len(od_edges):.2%})")

ax = zones_msoa.centroid.plot(figsize=(10, 14), markersize=0.5, color="#cccccc")
c2g.plot_graph(
    nodes=zones_msoa.centroid,
    edges=strong_edges,
    ax=ax,
    edge_alpha=strong_edges["weight"].rank(pct=True),
)
plt.axis("off")
plt.show()

注意这里用 edges_gdf["weight"] 而不是原始 Count 列——两者数值相同,但 weight 是规范列名,写起来更通用。

17.8.7 按流量分位数着色

percentiles = strong_edges["weight"].rank(pct=True)
c2g.plot_graph(nodes=zones_msoa.centroid, edges=strong_edges, edge_alpha=percentiles)

用分位数而不是绝对值做透明度,可以让”弱但非零”的流量也可见,避免视觉被少数极强流量主导。


17.9 注意事项与常见错误

17.9.1 错误对照表

报错信息 原因 解决
TypeError: zones_gdf must be a GeoDataFrame 传了 DataFrame gpd.GeoDataFrame(df, geometry=...)
ValueError: zone_id_col 'x' not found 列名拼错 检查列名
ValueError: zone_id_col values must be unique ID 有重复 drop_duplicates
ValueError: zone_id_col contains null values ID 有空值 dropna(subset=[id_col])
ValueError: weight_cols must be provided 长表没给权重列 加 weight_cols=["flow"]
ValueError: weight_cols contain columns not present 列名拼错 检查实际列名
ValueError: When multiple weight_cols are provided a valid threshold_col must be specified 多列未指定主列 加 threshold_col
ValueError: threshold_col not in weight_cols 主列不在权重列里 修正 threshold_col
ValueError: When weight_cols contains 'weight'... 输入有 weight 列但主列是别的 重命名输入列
ValueError: Adjacency DataFrame must be square 矩阵非方阵 检查 pivot 是否正确
ValueError: Adjacency DataFrame index and columns must match exactly 行列标签不同或顺序不同 reindex(index=ids, columns=ids)
ValueError: Adjacency ndarray size must match number of zones 数组尺寸 ≠ 区域数 检查数组构造
ValueError: No overlapping zone IDs between adjacency matrix and zones_gdf 标签完全对不上 检查 ID 类型(int vs str)
ValueError: threshold must be numeric (int or float) 阈值传了字符串 转 float
ValueError: matrix_type must be 'edgelist' or 'adjacency' 拼错 检查拼写
TypeError: For matrix_type='edgelist', od_data must be a pandas DataFrame 长表模式传了数组 转 DataFrame
TypeError: For matrix_type='adjacency', od_data must be a pandas DataFrame or numpy ndarray 邻接模式传了列表 转 DataFrame 或 ndarray

17.9.2 ID 类型不一致:最阴的错误

    # 常见坑:OD 表里是字符串,区域表里是整数
print(od_table["source"].dtype)      # object (str)
print(zones_gdf["zone_id"].dtype)    # int64

结果是所有行都被 _align_edgelist_zones 过滤掉,得到空边表但无报错。

节点 7264,边 0

看到边数为 0 先查这个。修复:

zones_gdf["zone_id"] = zones_gdf["zone_id"].astype(str)
od_table["source"] = od_table["source"].astype(str)
od_table["target"] = od_table["target"].astype(str)

17.9.3 空结果的判断

边表为空时不报错,返回列名正确的空 GeoDataFrame(_empty_edgeframe 保证列结构)。所以:

nodes, edges = c2g.od_matrix_to_graph(...)
if edges.empty:
    print("警告:没有生成任何边,检查过滤条件与 ID 对齐")

17.9.4 负权重

函数只警告不报错:

warnings.warn(
    f"Column '{col}' contains negative weights; keeping values (requirement 5.6)",
    UserWarning,
    stacklevel=2,
)

负流量在物理上没意义,但有时数据里用负数表示”净流出”。这种情况下需要注意:聚合求和后可能出现负数,阈值为 None 时(> 0)负边会被丢弃。

17.9.5 自环的处理

默认 include_self_loops=False,会丢弃 source == target 的行。这在迁移数据分析里是必须的:区内迁移(同一 MSOA 内搬家)通常不是研究对象,保留会造成大量自环边。

但如果你想分析”区内流动性强度”,可以设 True:

_, edges_self = c2g.od_matrix_to_graph(od_table, zones_gdf, zone_id_col="zone_id",
                                       weight_cols=["Count"], include_self_loops=True, directed=True)
self_loops = edges_self[edges_self.index.get_level_values(0) == edges_self.index.get_level_values(1)]
print(f"自环边 {len(self_loops)} 条")

17.9.6 性能与内存

数据规模 长表建图耗时 内存峰值 备注
1 万行 亚秒级 几十 MB  
100 万行 数秒 数百 MB  
500 万行 十几秒 1–2 GB  
邻接矩阵 7000×7000 数秒 与边数正相关 用 threshold 控制边数

优化建议:

  1. 先过滤再建图:在 DataFrame 上先按流量筛一遍,减少 _normalize_edgelist 的工作量。
  2. compute_edge_geometry=False:不需要画图时关掉几何构造,能省大量时间与内存。
  3. 邻接矩阵优先用 threshold > 0:避免 O(N²) 边。
  4. 大矩阵用稀疏格式:od_matrix_to_graph 不接受 scipy.sparse,但可以自己转成 COO 再构造长表。
from scipy.sparse import coo_matrix

sp = coo_matrix(A_arr)
edges_sparse = pd.DataFrame({
    "source": zones_gdf["zone_id"].to_numpy()[sp.row],
    "target": zones_gdf["zone_id"].to_numpy()[sp.col],
    "flow": sp.data,
})
nodes, edges = c2g.od_matrix_to_graph(edges_sparse, zones_gdf, zone_id_col="zone_id", weight_cols=["flow"])

17.10 OD 图的三种下游用法

17.10.1 转 PyTorch Geometric 做图学习

from city2graph import gdf_to_pyg

data = gdf_to_pyg(nodes=od_nodes, edges=od_edges)
print(data)
print(f"节点特征 {data.x.shape},边索引 {data.edge_index.shape}")

注意:gdf_to_pyg 只接受同构图(单一节点类型)。OD 图天生同构,可以直接转。异构图(如同时有区域与设施)需要第 7 章的异构转换接口。

17.10.2 与邻接图叠加成多层图

OD 图(流动性)与邻接图(空间邻接)是同一批节点的两层关系。这种”多层网络”是城市分析的常见形态:

    # 第 16 章:空间邻接
adj_nodes, adj_edges = c2g.contiguity_graph(zones_msoa, "queen")

    # OD 边加一个关系标记
od_edges = od_edges.assign(relation="migration")

    # 合并成一个边表(注意列对齐)
import pandas as pd
combined = pd.concat([
    adj_edges.assign(relation="contiguity"),
    od_edges.assign(relation="migration"),
])

这种”同一节点集、多种关系”的结构在 City2Graph 里用异构图表达更规范(见第 8 章与第 22 章元路径)。

17.10.3 空间滞后与引力模型

OD 图是空间交互模型(spatial interaction model)的输入。经典的引力模型:

    # 简化示例:流量 ~ 人口积 / 距离平方
od_edges = od_edges.reset_index()
od_edges = od_edges.merge(od_nodes[["MSOA21CD", "pop"]], left_on="source", right_on="MSOA21CD")
od_edges = od_edges.merge(od_nodes[["MSOA21CD", "pop"]], left_on="target", right_on="MSOA21CD", suffixes=("_src", "_dst"))
od_edges["distance_m"] = od_edges.geometry.length

od_edges["expected"] = od_edges["pop_src"] * od_edges["pop_dst"] / (od_edges["distance_m"] ** 2)
print(od_edges[["weight", "expected", "distance_m"]].describe())

这个例子要说明的是:od_matrix_to_graph 输出的边几何(质心连线)本身就能当距离用,不必再回查区域表。


17.11 小结

17.11.1 核心要点

主题 要点
输入形态 长表(edgelist)、宽表(adjacency DataFrame)、数组(adjacency ndarray)三种
长表要求 必须给 weight_cols;多列时必须给 threshold_col;输入含 weight 列时它必须是主列
宽表要求 方阵、行列标签完全一致(含顺序)、标签唯一
数组要求 尺寸等于区域数,顺序须与区域表一致(函数只能警告不能验证)
聚合语义 先按 (source,target) 聚合求和,再应用阈值
无向语义 directed=False 时互惠流量先相加再筛阈值,端点按字符串排序规范化
阈值语义 None 时丢 0;> 0 时 >=;= 0 时保留 0 值边(大矩阵慎用)
自环 默认丢弃,include_self_loops=True 保留
返回结构 节点表索引 = zone ID;边表 MultiIndex[(source,target)],列含 weight + 各权重列 + geometry
几何 默认质心连线;compute_edge_geometry=False 时列为 None
弃用项 as_nx 已弃用,改用 gdf_to_nx

17.11.2 参数选择速查

我的数据情况 推荐配置
一张 source/target/count 的 CSV matrix_type="edgelist", weight_cols=["count"]
多列属性(流量 + 成本) weight_cols=["trips","cost"], threshold_col="trips"
只要强联系 加 threshold=10(先用分位数定阈值)
分析城市间联系强度 directed=False
分析净流向 directed=True,再算 in - out
只要网络结构不要几何 compute_edge_geometry=False
大数据不想爆内存 先预过滤,或 compute_edge_geometry=False

17.11.3 下一章预告

第 18 章进入公共交通领域。OD 数据回答”人从哪到哪”,而 GTFS(General Transit Feed Specification)回答”车怎么跑”——路线、站点、班次、时刻。City2Graph 把 GTFS 的 zip 包直接读进 DuckDB,让你用 SQL 与 pandas 混合查询它。这一章的难点从”参数联动”转向”数据模型理解”:GTFS 是一组互相关联的文本表,不理解表间关系就无法正确建图。


17.12 延伸练习

  1. 阈值敏感性分析:对同一份 OD 数据,取 10 个不同阈值(从 0 到最大流量的 90 分位),画出”边数—阈值”曲线与”最大连通分量规模—阈值”曲线,观察网络结构随阈值崩塌的过程。

  2. 有向 vs 无向对比:同一份数据分别用 directed=True/False 建图,比较边数、平均度、度分布形状,并计算”净流量”(in_degree - out_degree)最高的 10 个区域。

  3. 逆距离加权:把边权 weight 改为 weight / distance^2,重新做 PageRank,观察排名变化。这实际上是在手工实现一个引力模型的变体。

  4. 多权重一致性:构造一份 trips 与 cost 不完全相关的数据,分别用两列做 threshold_col,比较保留边集的差异,思考”阈值列选择”如何改变结论。

  5. 稀疏矩阵接入:用 scipy.sparse 构造一个 5000×5000 的稀疏邻接矩阵(非零率 0.1%),对比”直接传 ndarray”与”转成 COO 再转长表”两种做法的内存与耗时。


17.13 进阶:OD 网络的统计特性

17.13.1 迁移网络的典型形态

真实的 OD 网络(尤其是人口迁移与通勤)有三个几乎所有城市都成立的统计特征。认识它们有助于判断数据是否被正确处理。

特征一:重尾度分布

大多数区域的度很小(只与少数几处有流量),少数中心和枢纽的度极大。这在直方图上表现为长尾:

import numpy as np
import pandas as pd

degree_df = pd.DataFrame({
    "node": od_nodes.index,
    "in_degree": [G.in_degree(n) for n in od_nodes.index],
    "out_degree": [G.out_degree(n) for n in od_nodes.index],
    "weighted_in": [sum(d["weight"] for _, _, d in G.in_edges(n, data=True)) for n in od_nodes.index],
    "weighted_out": [sum(d["weight"] for _, _, d in G.out_edges(n, data=True)) for n in od_nodes.index],
})
print(degree_df[["in_degree", "out_degree"]].describe(percentiles=[0.5, 0.9, 0.99]))

若 99 分位与中位数相差 10 倍以上,说明分布重尾显著,用均值描述”典型区域”会误导。

特征二:流向不对称

A→B 与 B→A 的流量通常不相等,且差额有系统性方向(郊区→市中心多、反向少)。合并成无向边会掩盖这个信息,所以”净流量”分析必须用 directed=True:

_, edges_dir = c2g.od_matrix_to_graph(
    od_table, zones_gdf, zone_id_col="MSOA21CD",
    weight_cols=["Count"], directed=True,
)
net = edges_dir.reset_index()
net["signed"] = np.where(net["source"] < net["target"], net["weight"], -net["weight"])
net_flow = net.groupby(["source", "target"] if False else [net[["source", "target"]].min(axis=1)])["signed"].sum()
print(net_flow.head())

更直接的写法是把有向边表转成”净流量表”:

edges_dir = edges_dir.reset_index()
pairs = edges_dir.assign(
    a=np.minimum(edges_dir["source"], edges_dir["target"]),
    b=np.maximum(edges_dir["source"], edges_dir["target"]),
)
net = pairs.groupby(["a", "b"]).apply(
    lambda g: g.loc[g["source"] == g["a"], "weight"].sum()
              - g.loc[g["source"] == g["b"], "weight"].sum(),
    include_groups=False,
).rename("net_flow").reset_index()
print(net.nlargest(10, "net_flow"))

特征三:距离衰减

流量随距离单调下降,这是引力模型的基础。检验方法:

edges_wd = edges_dir.copy()
    # 边几何长度(注意 CRS 必须是投影坐标)
edges_wd["dist_km"] = edges_wd.geometry.length / 1000
bins = pd.qcut(edges_wd["dist_km"], q=20, duplicates="drop")
decay = edges_wd.groupby(bins, observed=True)["weight"].agg(["mean", "median", "count"])
print(decay)

如果 mean 随距离不是单调下降,先怀疑两点:坐标系是经纬度(长度单位是度)、或者数据里存在大量”远距离但高流量”的特殊流(如大学生返乡)。

17.13.2 为什么 OD 图不适合直接做社区发现

把迁移网络丢进 Louvain 或 Leiden,会得到”地理上聚成一团”的社区——但这通常是空间自相关的副产品,不是真实的”功能区”。

原因:OD 流量与距离强负相关,所以地理上邻近的区域天然有更多边。社区检测会优先切分空间上远离的组,得到的结果基本复刻画的分区。

要做有意义的社区检测,需要去除距离效应:

    # 方案一:用"超出预期的流量"作为边权
edges_wd["expected"] = (
    edges_wd["weight"].mean() * np.exp(-edges_wd["dist_km"] / 10)
)
edges_wd["residual"] = edges_wd["weight"] / edges_wd["expected"]

    # 方案二:只保留长距离流量
long_edges = edges_wd[edges_wd["dist_km"] > 20]

    # 方案三:用行标准化后的流量(消除区域规模差异)
edges_wd["share"] = edges_wd["weight"] / edges_wd.groupby("source")["weight"].transform("sum")

这三种处理对应三种研究问题:方案一看”哪里联系异常紧密”,方案二看”跨城联系”,方案三看”流出去向的偏好”。

17.13.3 空间交互模型:把 OD 图当作回归数据

经典引力模型的估计形式:

T_ij = k * (P_i^α * P_j^β) / d_ij^γ

取对数后变成线性回归:

ln(T_ij) = ln(k) + α·ln(P_i) + β·ln(P_j) - γ·ln(d_ij)

用 OD 边表直接构造回归数据:

import numpy as np
import statsmodels.api as sm

reg = edges_dir.copy()
reg = reg[reg["weight"] > 0]                 # 对数要求正值
reg["dist_km"] = reg.geometry.length / 1000
reg = reg[reg["dist_km"] > 0]

pop = od_nodes["pop"].astype(float)
reg["ln_pop_src"] = np.log(reg["source"].map(pop))
reg["ln_pop_dst"] = np.log(reg["target"].map(pop))
reg["ln_dist"] = np.log(reg["dist_km"])
reg["ln_flow"] = np.log(reg["weight"].astype(float))

X = sm.add_constant(reg[["ln_pop_src", "ln_pop_dst", "ln_dist"]])
model = sm.OLS(reg["ln_flow"], X, missing="drop").fit()
print(model.params)
print(f"R² = {model.rsquared:.3f}")

系数解读:ln_dist 的系数就是 -γ(距离弹性),其绝对值反映”距离摩擦”强度。大城市的 γ 通常较小(长距离通勤更多),小城市较大。

注意 c2g.od_matrix_to_graph 输出的边几何是质心直线,所以 geometry.length 是直线距离,不是路网距离。做严谨的引力模型应该用路网距离或通勤时间。


17.14 进阶:参数组合的完整矩阵

17.14.1 五种输入 × 两种方向的输出

import pandas as pd
import geopandas as gpd
from shapely.geometry import box
import city2graph as c2g

    # 构造 3 个区域,2 条流量
zones = gpd.GeoDataFrame(
    {"zid": ["A", "B", "C"]},
    geometry=[box(0, 0, 1, 1), box(1, 0, 2, 1), box(0, 1, 1, 2)],
    crs="EPSG:3857",
)

edge_list = pd.DataFrame({"s": ["A", "B"], "t": ["B", "A"], "w": [5, 3]})
adj_df = pd.DataFrame([[0, 5, 0], [3, 0, 0], [0, 0, 0]],
                      index=["A", "B", "C"], columns=["A", "B", "C"])
adj_arr = adj_df.to_numpy()

cases = []
for name, data, kwargs in [
    ("edgelist", edge_list, dict(source_col="s", target_col="t", weight_cols=["w"], matrix_type="edgelist")),
    ("adjacency-df", adj_df, dict(matrix_type="adjacency")),
    ("adjacency-arr", adj_arr, dict(matrix_type="adjacency")),
]:
    for directed in (True, False):
        _, e = c2g.od_matrix_to_graph(data, zones, zone_id_col="zid", directed=directed, **kwargs)
        cases.append({"input": name, "directed": directed, "n_edges": len(e),
                      "total_weight": float(e["weight"].sum()) if len(e) else 0.0})
print(pd.DataFrame(cases).to_string(index=False))

预期结果:

input directed n_edges total_weight
edgelist True 2 8.0
edgelist False 1 8.0
adjacency-df True 2 8.0
adjacency-df False 1 8.0
adjacency-arr True 2 8.0
adjacency-arr False 1 8.0

三种输入在有向时都得到 2 条边、总权重 8;无向时都合并成 1 条边、总权重 8。这个”总权重守恒”是检验实现是否正确的好指标:合并只改变边的数量,不改变流量总和。

17.14.2 阈值的组合矩阵

固定数据,扫描阈值的不同取值:

import numpy as np

scan = []
for th in [None, 0, 1, 3, 4, 5, 6, 10]:
    _, e = c2g.od_matrix_to_graph(
        edge_list, zones, zone_id_col="zid",
        source_col="s", target_col="t", weight_cols=["w"],
        directed=False, threshold=th,
    )
    scan.append({"threshold": th, "edges": len(e), "sum": float(e["weight"].sum()) if len(e) else 0.0})
print(pd.DataFrame(scan).to_string(index=False))

这里 (A,B) 与 (B,A) 合计 8,所以:

threshold 保留条件 edges
None 合并值 > 0 1(8 > 0)
0 >= 0 1
1–8 >= 阈值 1(8 >= 阈值)
10 >= 10 0

把数据改成 3 与 3(合计 6)再扫一遍,就能看到 threshold=5 时”先合后筛”保留了边、”先筛后合”会丢弃的差别。这种小数据扫描是验证自己对语义理解是否正确的有效手段。

17.14.3 多权重列的完整行为

E3 = pd.DataFrame({
    "s": ["A", "B", "C"],
    "t": ["B", "A", "A"],
    "trips": [4, 2, 6],
    "cost": [10, 5, 20],
    "dist": [1.2, 1.1, 2.4],
})

_, e3 = c2g.od_matrix_to_graph(
    E3, zones, zone_id_col="zid",
    source_col="s", target_col="t",
    weight_cols=["trips", "cost", "dist"],
    threshold_col="trips", threshold=5,
    directed=False,
)
print(e3)

预期:

                 weight  trips  cost  dist
source target
A      B       6.0    6.0   15.0   2.3
A      C       6.0    6.0   20.0   2.4

验证要点:

  1. weight 等于 trips(因为 threshold_col="trips" 决定了主列)。
  2. trips、cost、dist 全部做了求和,不只是主列。
  3. A–B 的 trips 是 4+2=6 ≥ 5,保留。
  4. A–C 是 6 ≥ 5,保留。
  5. 列顺序是 weight 在最前,其后按 weight_cols 给定顺序。

这个例子把”多权重聚合”的完整语义展示清楚了。实际数据里 cost 往往与 trips 正相关但不是线性关系,聚合后两者可能不一致——这正是需要记录”用哪一列做阈值”的原因。

17.14.4 空结果的各种成因

cases = {
    "全部低于阈值": dict(threshold=100),
    "全部是自环": dict(include_self_loops=False),
    "ID 不匹配": dict(),
}
for label, kw in cases.items():
    data = edge_list if label != "全部是自环" else pd.DataFrame({"s": ["A"], "t": ["A"], "w": [5]})
    if label == "ID 匹配失败":
        data = pd.DataFrame({"s": ["X"], "t": ["Y"], "w": [5]})
    _, e = c2g.od_matrix_to_graph(data, zones, zone_id_col="zid",
                                  source_col="s", target_col="t", weight_cols=["w"], **kw)
    print(f"{label}: {len(e)} 条边, 列={e.columns.tolist()}")

空结果统一返回 columns=["source", "target", "weight"](多权重时再加额外列)的空 GeoDataFrame。这个稳定性让下游代码不必写特判,但也意味着看到 0 条边时不会收到任何警告——所以建议每次建图后打印边数并和预期对照。


17.15 进阶:把 OD 图嵌入更大分析流程

17.15.1 与人口属性结合:人均迁移强度

原始流量受区域规模影响。归一化后才能比较”迁移倾向”:

od_nodes["pop"] = od_nodes["pop"].astype(float)
total_out = od_edges.reset_index().groupby("source")["weight"].sum()
od_nodes["total_out"] = od_nodes.index.map(total_out).fillna(0.0)
od_nodes["out_rate"] = od_nodes["total_out"] / od_nodes["pop"]

print(od_nodes.nlargest(10, "out_rate")[["MSOA21NM", "pop", "total_out", "out_rate"]])

out_rate 高但人口少的区域,往往是”过渡型社区”(学生区、租赁市场活跃区)。

17.15.2 与邻接图做对比分析

把”迁移联系”与”空间邻接”两张图叠在一起,能识别”跨边界流动”:

adj_nodes, adj_edges = c2g.contiguity_graph(zones_gdf.set_index("MSOA21CD"), "queen")

adj_pairs = set(adj_edges.index)
od_pairs = set(od_edges.index)

cross_boundary = od_pairs - adj_pairs
print(f"迁移边 {len(od_pairs)},其中 {len(cross_boundary)} 条跨越非相邻区域({len(cross_boundary)/len(od_pairs):.1%})")

这个比例是”通勤圈范围”的粗指标:如果 80% 的迁移发生在相邻区域之间,说明人口流动高度本地化;如果比例低,说明存在强力的中心吸引(如大城市就业中心)。

17.15.3 输出到 GNN 管道

from city2graph import gdf_to_pyg

    # 节点特征:把有用的数值列整理成矩阵
feature_cols = ["pop", "total_out", "out_rate"]
X = od_nodes[feature_cols].fillna(0.0).to_numpy(dtype="float32")

data = gdf_to_pyg(nodes=od_nodes, edges=od_edges)
print(f"节点特征 {data.x.shape},边 {data.edge_index.shape}")

    # 归一化节点特征
from sklearn.preprocessing import StandardScaler
data.x = __import__("torch").tensor(StandardScaler().fit_transform(X), dtype=__import__("torch").float32)

注意 gdf_to_pyg 默认会把数值列当特征,文本列(如区域名)需要先剔除,否则会报错。稳妥做法是自己控制特征列。

17.15.4 与其他章节的数据契约对照

上游产出 本函数能否直接消费 说明
Cricket/普查 OD 表 能 需列名映射
travel_summary_graph 的边表 不能直接 它是已聚合图,不需要再建
get_od_pairs 的输出 部分能 需先用 groupby(["orig_stop_id","dest_stop_id"]) 聚合
county_business_patterns 类数据 能 任意 source/target/weight 结构
邻接矩阵 CSV 能 pd.read_csv(index_col=0) 后直接传

第二行值得展开:交通图的边表本身已经是 (from_stop_id, to_stop_id, travel_time_sec, frequency),若你想用”频次”当流量再建一张 OD 图,会得到一张结构相同但边权不同的图——这没有意义。OD 建图的适用场景是原始流量数据,不是已聚合的图结构。

17.16 实战:三类常见数据源的适配

17.16.1 普查迁移表(英国 ODMG 风格)

特征:列名很长、含负代码表示”不适用”、区域数量上万、单日快照。

适配要点:

import pandas as pd
import city2graph as c2g

    # 1. 读入并检查特殊值
od_raw = pd.read_csv("ODMG01EW_MSOA.csv")
print(od_raw.iloc[:, 0].value_counts().head())   # 看是否含 -8 之类

    # 2. 显式过滤"不适用"行(比依赖内部过滤更可控)
valid = set(zones_gdf["MSOA21CD"])
od_clean = od_raw[
    od_raw["Migrant MSOA one year ago code"].isin(valid)
    & od_raw["Middle layer Super Output Areas code"].isin(valid)
].copy()
print(f"{len(od_raw)} -> {len(od_clean)} 行")

    # 3. 建图
nodes, edges = c2g.od_matrix_to_graph(
    od_clean, zones_gdf, zone_id_col="MSOA21CD",
    source_col="Migrant MSOA one year ago code",
    target_col="Middle layer Super Output Areas code",
    weight_cols=["Count"],
    directed=False,
)

先自己过滤的好处是知道丢了多少。若依赖内部过滤,你拿到的只是一张变小的表,不知道原因。

17.16.2 通勤流矩阵(CSV 邻接矩阵)

特征:行列都是区域名、值是对称或近似对称的通勤人数、可能带行列合计。

这类数据要注意去掉”合计行/列”:

commute = pd.read_csv("commute_matrix.csv", index_col=0)
print(commute.shape)

    # 去掉合计行与合计列(常见命名)
total_labels = ["Total", "合计", "Total residents", "All"]
commute = commute.drop(index=[i for i in commute.index if i in total_labels], errors="ignore")
commute = commute.drop(columns=[c for c in commute.columns if c in total_labels], errors="ignore")

    # 确保方阵且行列一致
assert commute.shape[0] == commute.shape[1]
commute = commute.reindex(index=commute.index, columns=commute.index)

nodes, edges = c2g.od_matrix_to_graph(
    commute, zones_gdf, zone_id_col="zone_name",
    matrix_type="adjacency", directed=True,
)

如果行列标签顺序不一致,reindex 是必须的——函数会用 .equals() 检查”完全一致”,不只是集合相同。

17.16.3 共享单车 OD 记录

特征:数据量巨大(百万到千万级)、每次骑行一条记录、需要先聚合。

直接传原始记录不可行(每行都是唯一起点终点组合,聚合后也没意义)。正确做法是先在 pandas 里聚合:

trips = pd.read_parquet("bike_trips_2025.parquet")
print(f"原始骑行记录 {len(trips)} 条")

    # 按起终点聚合
od_agg = (
    trips.groupby(["start_station_id", "end_station_id"], as_index=False)
    .agg(trips=("trip_id", "size"), median_duration=("duration_min", "median"))
)

    # 过滤:少于 50 次的组合视为噪声
od_agg = od_agg[od_agg["trips"] >= 50]
print(f"聚合后 {len(od_agg)} 个站对")

nodes, edges = c2g.od_matrix_to_graph(
    od_agg, stations_gdf, zone_id_col="station_id",
    source_col="start_station_id", target_col="end_station_id",
    weight_cols=["trips", "median_duration"],
    threshold_col="trips", threshold=50,
    directed=False,
)

这里有个设计选择:什么时候在 pandas 里预聚合,什么时候交给 od_matrix_to_graph?

情况 建议
同一对 OD 有大量重复行 可以交给函数(它内部会 groupby.sum())
需要 median 等非求和聚合 必须自己先聚合
需要多阶段过滤(如先按时间窗) 自己先过滤
需要控制内存 自己先聚合再传

关键限制:od_matrix_to_graph 对重复行的聚合方式是求和,无法做中位数、最大値等其他聚合。所以只要你要的聚合不是求和,就必须在外部完成。

17.16.4 数据源适配的通用清单

| 检查项 | 为什么 | |——–|——–| | ID 类型统一(都用 str) | 避免静默空结果 | | ID 无空值、无重复 | 函数会报错或产生歧义 | | 特殊代码(-8、-9、Unknown)已处理 | 内部过滤会静默丢弃 | | 行列顺序对齐 | 邻接矩阵用 .equals() 严格检查 | | 区域集合与 OD 集合的交集已确认 | 交集为空会抛错 | | 权重非负(或已理解负值含义) | 负值只警告不报错 | | 聚合口径明确(求和/中位数/最大值) | 函数只支持求和 | —

17.17 本章与后续章节的数据契约

17.17.1 输出对象的三条不变式

od_matrix_to_graph 的输出遵守三条不变式,任何下游代码都可以依赖:

不变式 含义 违反后果
节点集等于区域集 len(nodes) == len(zones_gdf) 下游 join 会丢行
边索引是 (source, target) 两层 MultiIndex reset_index() 才能取列
weight 列一定存在 即使 weight_cols 为空(仅邻接模式) 下游统一按 weight 取值

第一条最容易被忽视。即使 OD 表里只出现 100 个区域之间的流量,节点表仍然是全部 7264 个区域。这对下游是好事(保证空间完整性),但如果你忘了这一点,可能会误以为”图和 OD 表规模一致”。

17.17.2 与第 22 章元路径的接口

OD 图与邻接图是同一批节点上的两层关系。把它们组合成多层网络,是元路径分析的典型输入:

    # 层一:空间邻接
adj_nodes, adj_edges = c2g.contiguity_graph(zones_gdf.set_index("MSOA21CD"), "queen")

    # 层二:人口迁移
od_nodes2, od_edges2 = c2g.od_matrix_to_graph(
    od_table, zones_gdf, zone_id_col="MSOA21CD",
    weight_cols=["Count"], directed=False,
)

    # 异构图:两类边,同一节点集
hetero_nodes = {"msoa": od_nodes2}
hetero_edges = {
    ("msoa", "is_adjacent_to", "msoa"): adj_edges,
    ("msoa", "has_migration_with", "msoa"): od_edges2,
}

注意 adj_edges 与 od_edges2 的索引都是两层 (source, target),但边类型不同。元路径函数通过字典键区分它们。

17.17.3 与第 23 章网络距离的接口

OD 图的边权是流量,不是距离。想算”迁移距离衰减”需要把质心直线距离算出来:

edges_with_dist = od_edges.reset_index()
edges_with_dist["dist_m"] = edges_with_dist.geometry.length
print(edges_with_dist[["weight", "dist_m"]].describe())

前提是区域已经投影(米制)。若在经纬度上,length 的单位是度,必须换算或用 geopy 的测地线距离。

17.17.4 与第 27 章 GNN 的接口

OD 图的边权是连续值,转 PyG 时通常需要决定”当边权还是当边特征”:

用法 做法
当边权(影响消息传递强度) 保留在 edge_weight
当边特征(输入到边分类器) 用 edge_attr 传矩阵
忽略(只看拓扑) 转成二值 1

gdf_to_pyg 的默认行为是把数值列当边特征。这个区别在训练时影响很大——边权参与归一化会改变梯度尺度。

17.17.5 一个完整的最小管道

把本章所有要点压缩成一个可复用的函数:

def build_mobility_graph(zones, od_table, *, zone_col, src_col, tgt_col,
                         weight_col, directed=False, threshold=None):
    """从 OD 表构建流动性图,并附上基础统计。"""
    nodes, edges = c2g.od_matrix_to_graph(
        od_table, zones, zone_id_col=zone_col,
        source_col=src_col, target_col=tgt_col,
        weight_cols=[weight_col], directed=directed, threshold=threshold,
    )
    stats = {
        "n_nodes": len(nodes),
        "n_edges": len(edges),
        "total_flow": float(edges["weight"].sum()) if len(edges) else 0.0,
        "isolated_nodes": len(nodes) - len(
            set(edges.index.get_level_values(0)) | set(edges.index.get_level_values(1))
        ) if len(edges) else len(nodes),
    }
    return nodes, edges, stats


nodes, edges, stats = build_mobility_graph(
    zones_gdf, od_table, zone_col="MSOA21CD",
    src_col="Migrant MSOA one year ago code",
    tgt_col="Middle layer Super Output Areas code",
    weight_col="Count", directed=False,
)
print(stats)

这个函数把”建图 + 统计”封装成一次调用,适合在多个数据源上重复使用。