第11章 场所图与移动图

城市形态(urban morphology)研究把城市空间拆成两种基本成分:供人停留、承载建筑的场所空间(place space),以及供人穿行的移动空间(movement space)。City2Graph 的形态学模块围绕这一对概念组织代码,其中的 place_to_place_graph、place_to_movement_graph 与 movement_to_movement_graph 分别负责场所之间的邻接、场所与移动网络之间的界面,以及移动段之间的拓扑连通。本章从这两种对象的语义出发,逐层拆开三个函数的参数、内部策略与输出结构,最后给出一个”用 POI 与街道互相建图”的完整例子。


11.1 本章导读

11.1.1 为什么要区分场所与移动

如果把城市抽象成一张图,最容易犯的错误是把所有要素塞进同一个节点集合:POI、建筑轮廓、道路中心线、地块边界混在一起,边的含义随之含糊。City2Graph 的做法沿用了空间句法(space syntax)与形态学网络(morphological network)研究的传统:

概念 英文 典型几何 City2Graph 中的节点类型 标识列
场所空间 place space Polygon / MultiPolygon place place_id
移动空间 movement space LineString movement movement_id
  • 场所空间回答”这里是什么”:建筑轮廓、地块、镶嵌单元(tessellation cell)、POI 缓冲区都可以充当场所。它的几何是面,节点通常取其质心(centroid)参与距离计算。
  • 移动空间回答”怎么过去”:街道段、步行道、轨道线。它的几何是线,节点同样取质心,但语义上是”这条通道”。

把两者分开带来三个直接好处:其一,异构图(heterogeneous graph)里节点类型天然清晰,导出到 PyTorch Geometric 时可以直接映射为不同 node_type;其二,三类关系可以分别建模——同类型内部是邻接,跨类型是界面;其三,筛选、剪枝、可达性计算可以只作用在移动层上,不影响场所层的完整性。

11.1.2 三个函数的分工

morphology.py
├── place_to_place_graph()          # 场所 ↔ 场所:面邻接(Queen / Rook)
├── place_to_movement_graph()       # 场所 ↔ 移动:面线相接(dwithin + 最近回退)
├── movement_to_movement_graph()    # 移动 ↔ 移动:线线拓扑(对偶图)
└── morphological_graph()           # 三者组合而成的完整异构图

三个函数共享同一套输出约定:默认返回 (nodes_gdf, edges_gdf) 二元组,边表的索引是一个两级的 MultiIndex,列为 weight 与 geometry(place_to_movement_graph 是特例,其边表没有 weight 列)。as_nx=True 时改为返回 networkx 图对象,不过该参数在 0.4 之后的版本里已被标记为废弃(deprecated)。

版本提示:三个函数的 as_nx 参数都会触发 DeprecationWarning,官方建议先用默认模式拿到 GeoDataFrame,再调用 city2graph.gdf_to_nx() 转图。本章仍会讲解 as_nx 的行为,因为它解释了内部图结构与列名,但新代码应优先使用 gdf_to_nx。


11.2 place 与 movement 两类对象的语义

11.2.1 场所(place)的构造来源

在 City2Graph 的完整流程里,场所一般来自 create_tessellation 生成的镶嵌单元。镶嵌单元的 tess_id 会被重命名为 place_id(见 morphology._create_and_filter_tessellation 中的 rename(columns={"tess_id": _PLACE_ID_COL}))。除此之外,只要你提供的面数据带有 place_id 列,就可以直接当作场所使用:

来源 几何 place_id 生成方式 适用场景
封闭镶嵌(enclosed tessellation) Polygon tess_id 重命名 城市形态标准做法
形态学镶嵌(morphological tessellation) Polygon tessellation.index 缺少街道障碍时
建筑轮廓回退单元 Polygon fallback_<index> 镶嵌失败时
行政区 / 普查区 Polygon 自定义 宏观尺度统计
POI 缓冲区 Polygon 自定义 没有地块数据时的近似

无论来源如何,place_gdf 必须满足两件事:几何是面,存在 place_id 列且取值唯一。后者尤其重要,因为 place_to_place_graph 内部会用 place_gdf.drop_duplicates(subset=[_PLACE_ID_COL]) 去重——如果同一个 place_id 对应多个几何,只有第一行会被保留。

11.2.2 移动(movement)的构造来源

移动层的标准来源是街道段。morphological_graph 会把 segments_gdf 的索引直接当作 movement_id(文档字符串写作 “The ‘movement_id’ for street segments is taken directly from the index of segments_gdf“)。因此推荐在传入前先把索引设好:

import geopandas as gpd

# 假设 streets 从 GeoJSON 读入
streets = gpd.read_file("streets.geojson")
streets = streets.to_crs(epsg=27700)                 # 投影到米制 CRS
streets["movement_id"] = streets.index.astype(str)   # 显式生成 ID 列

place_to_movement_graph 要求 movement_gdf 含有 movement_id 列;而 movement_to_movement_graph 允许缺省该列——缺失时它会自动创建 _edge_id:

if "movement_id" in movement_gdf_copy.columns:
    edge_id_col = "movement_id"
else:
    edge_id_col = "_edge_id"
    movement_gdf_copy[edge_id_col] = [str(idx) for idx in movement_gdf_copy.index]

11.2.3 三种关系类型的命名约定

在 morphological_graph 汇总时,边类型键是三元组 (源类型, 关系名, 目标类型):

边类型键 含义 生成函数 方向性
("place", "touched_to", "place") 镶嵌单元共享边界 place_to_place_graph 无向(可对称化)
("movement", "connected_to", "movement") 街道段共享端点 movement_to_movement_graph 无向(对偶图)
("place", "faced_to", "movement") 场所有临街界面 place_to_movement_graph 有向(place → movement)

记住这三个字符串,后续导出到 gdf_to_pyg 时它们会直接变成 edge_type;写错一个词,异构图就会多出一种孤立的边类型。


11.3 place_to_place_graph:场所之间的邻接

11.3.1 函数签名

place_to_place_graph(
    place_gdf: gpd.GeoDataFrame,
    group_col: str | None = None,
    contiguity: str = "queen",
    as_nx: bool | None = None,
    duplicate_edges: bool = False,
) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame] | nx.Graph

11.3.2 参数详解

参数 类型 默认值 说明
place_gdf GeoDataFrame 必填 场所面数据,必须含 place_id 列;空表也允许(返回类型正确的空结果)
group_col str 或 None None 分组列名。只有同组内的相邻单元才会连边;为 None 时所有单元视为同一组,并统一写入 group = 0
contiguity str "queen" 邻接判定方式,只能是 "queen" 或 "rook"
as_nx bool 或 None None 已废弃;为真时返回 networkx 图
duplicate_edges bool False 为真时边表同时包含 (u, v) 与 (v, u),行数约翻倍;与 as_nx=True 互斥

11.3.3 Queen 与 Rook 的差异

两种邻接规则来自棋盘:Queen 走法允许斜向,Rook 只允许横竖。

规则 判定 边数 典型效果
"queen" 共享任意边界,含单个顶点接触 更多 镶嵌单元几乎总能连成一片
"rook" 仅共享边(正长度线段) 更少 只在尖角相接的单元不连边

City2Graph 把这项工作交给 libpysal 的空间权重矩阵:

ids = list(gdf.index)
if contiguity.lower() == "queen":
    return libpysal.weights.Queen.from_dataframe(gdf, ids=ids)
return libpysal.weights.Rook.from_dataframe(gdf, ids=ids)

随后把邻接字典转成去重后的无向边集合:

return list(
    {tuple(sorted((src, nbr))) for src, nbrs in weights.neighbors.items() for nbr in nbrs}
)

11.3.4 group_col 的作用与 enclosure_index

在封闭镶嵌(enclosed tessellation)里,enclosure_index 标记每个单元属于哪个”封闭街区”。街道作为屏障把城市切成若干互不相连的街区,跨越街区的单元虽然几何上邻接,但被街道隔开,不应直接连边。因此 morphological_graph 内部固定用 group_col="enclosure_index":

group_col_for_priv_priv: str | None = "enclosure_index"
if group_col_for_priv_priv not in tessellation.columns:
    ...
    group_col_for_priv_priv = None

_format_place_edges 的实现说明了过滤逻辑:

if group_col:
    id_to_group = gdf_unique.set_index(_PLACE_ID_COL)[group_col]
    edges_gdf[group_col] = edges_gdf["from_place_id"].map(id_to_group)
    to_group = edges_gdf["to_place_id"].map(id_to_group)
    edges_gdf = edges_gdf[edges_gdf[group_col] == to_group].copy()
else:
    edges_gdf["group"] = 0

注意最后一行:group_col=None 时列名就叫 group,而不是 enclosure_index。如果你的下游代码要按组查询,必须区分这两种情况。

11.3.5 输出结构

import city2graph as c2g

nodes, edges = c2g.place_to_place_graph(tessellation_gdf, group_col="enclosure_index")

print(nodes.columns.tolist())
# ['geometry', 'enclosure_index', 'place_id', ...]

print(edges.columns.tolist())
# ['from_place_id', 'to_place_id', 'enclosure_index', 'geometry']

print(edges.index.name)
# None —— 注意:place_to_place_graph 的边表是 RangeIndex

这一点常被误解:place_to_place_graph 的边表已经 reset_index() 并用 from_place_id/to_place_id 两列承载端点,不是 MultiIndex。但 morphological_graph 在汇总时又会调用 _set_edge_index 把这两列设回 MultiIndex。两种形态各有用途:

场景 用哪种形态 原因
单函数直接分析 列形态 便于 merge、筛选、导出
汇总成异构图 MultiIndex 形态 与 gdf_to_nx、nx_to_gdf 的约定一致
邻域查询 edges.xs(id) MultiIndex 形态 需要 duplicate_edges=True 才能双向查全

11.3.6 空表与边界情况

place_to_place_graph 对退化输入有明确行为:

输入情况 行为
place_gdf 为空 返回 (place_gdf, 空边表),空边表含 from_place_id/to_place_id 与分组列
去重后少于 2 个单元 同上,返回空边表
libpysal 未产生任何邻接 同上
缺少 place_id 列(非空表) 抛 ValueError: Expected ID column 'place_id' not found in place_gdf.
contiguity 非法 抛 ValueError: contiguity must be either 'queen' or 'rook'
group_col 不存在 抛 ValueError: group_col '...' not found in place_gdf columns
duplicate_edges=True 且 as_nx=True 抛 ValueError(无向图无法容纳互逆边)

空边表的构造由 _return_empty_place_edges 完成,它保证列结构与非空时一致:

group_cols = [group_col] if group_col else ["group"]
empty_edges = GeoDataProcessor.create_empty_edges_gdf(
    place_gdf.crs, "from_place_id", "to_place_id", group_cols,
)

11.3.7 最小可运行示例

import geopandas as gpd
from shapely.geometry import Polygon
import city2graph as c2g

# 三个相邻方块,同属一个 "街区"
polys = [
    Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]),
    Polygon([(1, 0), (2, 0), (2, 1), (1, 1)]),
    Polygon([(2, 0), (3, 0), (3, 1), (2, 1)]),
]
places = gpd.GeoDataFrame(
    {"place_id": ["p0", "p1", "p2"], "enclosure_index": [0, 0, 0]},
    geometry=polys,
    crs="EPSG:3857",
)

nodes, edges = c2g.place_to_place_graph(places, group_col="enclosure_index")
print(len(nodes), len(edges))
# 3 2      —— 链状 p0-p1、p1-p2

print(edges[["from_place_id", "to_place_id"]])
#   from_place_id to_place_id
# 0            p0          p1
# 1            p1          p2

若把第三个方块挪到第二个方块的正上方(y 从 1 到 2),则 p1 与 p2 只共用一个顶点:

polys[2] = Polygon([(1, 1), (2, 1), (2, 2), (1, 2)])
places = gpd.GeoDataFrame(
    {"place_id": ["p0", "p1", "p2"], "enclosure_index": [0, 0, 0]},
    geometry=polys, crs="EPSG:3857",
)
_, queen_edges = c2g.place_to_place_graph(places, contiguity="queen")
_, rook_edges = c2g.place_to_place_graph(places, contiguity="rook")
print(len(queen_edges), len(rook_edges))
# 2 1      —— queen 认为共点是邻接,rook 不认

11.4 place_to_movement_graph:场所与移动的界面

11.4.1 函数签名

place_to_movement_graph(
    place_gdf: gpd.GeoDataFrame,
    movement_gdf: gpd.GeoDataFrame,
    primary_barrier_col: str | None = None,
    tolerance: float = 1e-6,
    as_nx: bool | None = None,
    max_connection_distance: float = math.inf,
    duplicate_edges: bool = False,
) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame] | nx.Graph

11.4.2 参数详解

参数 类型 默认值 说明
place_gdf GeoDataFrame 必填 场所面数据,需含 place_id 列
movement_gdf GeoDataFrame 必填 移动线数据,需含 movement_id 列
primary_barrier_col str 或 None None 备用几何列名。存在时用它替代主几何参与”邻近查询”,但不改变移动节点本身
tolerance float 1e-6 dwithin 谓词的距离阈值,单位与 CRS 一致
as_nx bool 或 None None 已废弃
max_connection_distance float math.inf 最近邻回退连接的距离上限,只作用于回退边
duplicate_edges bool False 生成互逆行;反向行的 place_id 列装的是 movement id

11.4.3 连接策略:dwithin + 最近邻回退

主查询用的是空间索引的 dwithin 谓词,而不是先做 buffer 再做相交:

movement_indices, place_indices = place_gdf.sindex.query(
    query_geometry,
    predicate="dwithin",
    distance=tolerance,
)

这种写法避免了为每条街道生成缓冲区几何(buffer geometry)的开销,在几十万条街道上差别非常明显。返回的两个索引数组按位置配对,直接组装成 DataFrame 后 drop_duplicates()。

问题在于:并非所有场所都贴着街道。封闭镶嵌的回退单元可能直接是建筑轮廓(见第 12 章),它可能完全不接触任何街道线。如果只留主查询,这些单元在 faced_to 层里就成了孤立节点。为此代码加了第二段逻辑 _connect_unmatched_place_to_nearest_movement:

  1. 计算 connected_place_ids,找出未被主查询覆盖的场所;
  2. 用移动几何的 sindex.nearest 找最近的一条移动段;
  3. 若给出有限的 max_connection_distance,计算两者实际距离,超过上限的配对丢弃;
  4. 把保留下来的回退边并入结果并再次 drop_duplicates()。

关键代码:

place_nearest_indices, movement_nearest_indices = movement_query.sindex.nearest(
    unmatched_place.geometry,
    return_all=False,
)

return_all=False 保证每个未匹配场所只取一条最近边。而距离截断部分:

if not math.isinf(max_distance):
    matched_place = unmatched_place.geometry.to_numpy()[place_nearest_indices]
    matched_movement = movement_query.to_numpy()[movement_nearest_indices]
    gaps = gpd.GeoSeries(matched_place, crs=movement_gdf.crs).distance(
        gpd.GeoSeries(matched_movement, crs=movement_gdf.crs),
        align=False,
    )
    within = (gaps <= max_distance).to_numpy()
    place_nearest_indices = place_nearest_indices[within]
    movement_nearest_indices = movement_nearest_indices[within]

为什么默认是 math.inf? 因为回退连接的语义是”补一条临街边”,不设上限会让一条远端街道与孤岛单元之间拉出长长的星形边(star-shaped edge),污染图的可视化与中心性指标。生产环境建议显式给值,通常取建筑进深量级(20–100 m)。

11.4.4 CRS 与几何转换

_place_to_movement_edges 的开头有一段容易被忽略的处理:

movement_crs = movement_gdf.crs
movement_gdf = GeoDataProcessor.harmonize_crs(movement_gdf, place_gdf.crs, stacklevel=3)
GeoDataProcessor.warn_crs_issues(place_gdf, geographic_message=_GEOGRAPHIC_CRS_MSG, stacklevel=3)
  • harmonize_crs 会把移动层重投影到场所层的 CRS(注意会先记下原始的 movement_crs,因为 GeoDataFrame.to_crs 只变换活动几何列);
  • warn_crs_issues 在检测到地理坐标系(经纬度)时发出警告,提示距离参数按米解释但 .centroid 结果不可靠。

若 primary_barrier_col 指向的列自带 CRS 且与场所层不一致,代码会先 set_crs 再 to_crs:

if barrier_crs is not None and place_gdf.crs is not None and barrier_crs != place_gdf.crs:
    if query_geometry.crs is None:
        query_geometry = query_geometry.set_crs(barrier_crs)
    query_geometry = query_geometry.to_crs(place_gdf.crs)

实践建议:不要依赖自动转换,传参前统一 to_crs 到投影坐标系(如 EPSG:3857、EPSG:32633、EPSG:27700),否则 tolerance=1e-6 在经纬度下几乎等于零距离,一条边都连不上。

11.4.5 输出结构

nodes, edges = c2g.place_to_movement_graph(place_gdf, movement_gdf)

print(nodes.columns.tolist())
# 场所列 + 移动列拼接,索引被重置为 RangeIndex
print(edges.columns.tolist())
# ['place_id', 'movement_id', 'geometry']

注意三点:

  1. 节点表是 pd.concat([place_gdf, movement_gdf], ignore_index=True),即索引被重置。场所与移动的属性列会并集对齐,缺失处为 NaN。如果后续要按 ID 关联,请用 place_id/movement_id 列而不是索引。
  2. 边表没有 weight 列——这是与其它邻近函数最大的区别。若要权重,需要自己按几何长度或其它指标补算。
  3. 边几何是”场所质心 → 移动质心”的 LineString,见 _create_place_movement_edges。它只是可视化用的连线,不等于真实的临街距离。
# 自行补充几何长度作为权重
import numpy as np
edges["length"] = edges.geometry.length
print(edges["length"].describe())

11.4.6 duplicate_edges 的列语义陷阱

duplicate_edges=True 时,函数对 ("place_id", "movement_id") 做对称化:

if duplicate_edges:
    edges_gdf = _symmetrize_edge_columns(edges_gdf, "place_id", "movement_id")

反向行的两个列值互换,因此在反向行里 place_id 列装的是 movement id。文档字符串明确写了这一点:

Note that on reverse rows the ‘place_id’ column holds a movement id and vice versa, because the endpoints are swapped.

如果下游要用这两列做 groupby 或 merge,请先加上方向标记列:

edges["direction"] = "forward"
rev = edges.rename(columns={"place_id": "movement_id", "movement_id": "place_id"})

11.4.7 空结果处理

输入情况 行为
场所或移动为空 返回空边表(含 place_id、movement_id 与几何列)
缺少 place_id ValueError: Expected ID column 'place_id' not found in place_gdf.
缺少 movement_id ValueError: Expected ID column 'movement_id' not found in movement_gdf.
两者都不为空但无任何相接 边表为空;上游 morphological_graph 会打印 No place to movement connections found

空边表的几何列 CRS 取自 place_gdf.crs,这保证 edges_gdf.plot() 不会因 CRS 缺失报错。

11.5 movement_to_movement_graph:移动段之间的拓扑连通

11.5.1 函数签名

movement_to_movement_graph(
    movement_gdf: gpd.GeoDataFrame,
    as_nx: bool | None = None,
    duplicate_edges: bool = False,
) -> tuple[gpd.GeoDataFrame, gpd.GeoDataFrame] | nx.Graph

参数极少,因为内部完全复用了 segments_to_graph + dual_graph 这条链路。

11.5.2 实现链路

segment_nodes, segment_edges = segments_to_graph(movement_gdf_copy)
_, dual_edges = dual_graph(
    (segment_nodes, segment_edges),
    edge_id_col=edge_id_col,
    keep_original_geom=True,
)
if isinstance(dual_edges.index, pd.MultiIndex):
    dual_edges.index.names = ["from_movement_id", "to_movement_id"]
dual_edges = dual_edges.reset_index()

分三步理解:

  1. 原始图(primal graph):segments_to_graph 把每条 LineString 拆成端点节点与边,得到”路口—街道”图。
  2. 对偶图(dual graph):dual_graph 把原始图的边变成节点、把原始图的节点变成边。于是每条街道段成为对偶图的一个节点,两条共享同一个路口的街道段之间连一条边。
  3. 改名与展平:MultiIndex 的两个层级重命名为 from_movement_id/to_movement_id,再 reset_index() 变成普通列。

这正是空间句法中”对偶图”的标准定义:街道段为节点、交点为边。它比原始图更适合做街道中心性分析,因为”一条街”在对偶图里才是一个可度量的对象。

11.5.3 输出结构

列名 类型 说明
from_movement_id 与 movement_id 同类型 源街道段 ID
to_movement_id 与 movement_id 同类型 目标街道段 ID
geometry LineString 两段质心之间的连线

与 place_to_place_graph 一样,边表是 RangeIndex 加两个端点列,汇总进 morphological_graph 时才转成 MultiIndex。

11.5.4 端点匹配的几何前提

segments_to_graph 依赖端点坐标完全相等来识别路口。真实数据里常见两类问题:

  • 相邻街道端点相差几厘米(采集误差);
  • 立交桥上下两层在平面上相交但实际不连通。

第一种问题靠预吸附解决:

import geopandas as gpd
from shapely import set_precision

# 把坐标吸附到 1 米网格,消除微小偏移
streets["geometry"] = set_precision(streets.geometry, grid_size=1.0)

更彻底的做法是先用 shapely.ops.snap 或 OSMnx 的 consolidate_intersections。第二种问题则要靠 primary_barrier_col 或数据本身的层级字段排除——立交桥不应连边。

11.5.5 空表与退化输入

if movement_gdf.empty or len(movement_gdf) < 2:
    empty_edges = GeoDataProcessor.create_empty_edges_gdf(
        movement_gdf.crs, "from_movement_id", "to_movement_id"
    )
    return (movement_gdf, empty_edges) if not as_nx else gdf_to_nx(...)

单条街道不会产生任何对偶边(没有相邻段),所以直接短路返回。此时仍返回原 movement_gdf 作为节点表,节点数与输入行数一致。


11.6 CRS 投影与距离单位

11.6.1 必须使用投影坐标系

三个函数都涉及距离,因此对 CRS 有硬性要求。判断方法:

if gdf.crs is None:
    raise ValueError("请先设置 CRS")
if gdf.crs.is_geographic:
    print("警告:地理坐标系,距离参数按度解释")
    gdf = gdf.to_crs(epsg=3857)

place_to_place_graph 本身不涉及距离阈值(邻接由拓扑判定),但它的边几何与权重在 contiguity_graph 里会用到距离。place_to_movement_graph 的 tolerance 与 max_connection_distance、movement_to_movement_graph 的端点匹配,都必须在米制下才可解释。

11.6.2 常用投影选择

区域 推荐 EPSG 单位 备注
全球 / Web 地图 3857 米 Web Mercator,高纬度严重变形,仅作近似
中国全境 4490 度 CGCS2000,不能直接算距离
中国分带 4547–4554 米 CGCS2000 3 度带高斯投影
英国 27700 米 British National Grid
日本 6677 米 JGD2011 平面直角坐标系
UTM 通用 32601–32660 米 北半球;南半球用 32701–32760

11.6.3 投影不一致时的自动处理

place_to_movement_graph 会自动把移动层重投影到场所层的 CRS,但这是有代价的隐式行为:

  1. 大表重投影耗时;
  2. 重投影后的几何与原图层不再逐点相等,若下游还要用原坐标会出错;
  3. place_to_place_graph 和 movement_to_movement_graph 不会自动重投影。

统一做法是在入口处集中检查:

import geopandas as gpd

def ensure_metric_crs(*gdfs, epsg=27700):
    out = []
    for g in gdfs:
        if g.crs is None:
            raise ValueError("输入缺少 CRS")
        out.append(g if g.crs.to_epsg() == epsg else g.to_crs(epsg=epsg))
    return out

places, streets = ensure_metric_crs(places, streets)

11.7 as_nx 与输出模式的取舍

11.7.1 三种输出对应关系

as_nx duplicate_edges 返回 节点 边
False False (nodes_gdf, edges_gdf) GeoDataFrame GeoDataFrame,每对只一条
False True (nodes_gdf, edges_gdf) GeoDataFrame GeoDataFrame,双向两条
True 必须 False nx.Graph 带 pos 等属性 带 weight、geometry

11.7.2 为什么 as_nx 被判为废弃

三个函数都用同一段代码处理:

if as_nx is not None:
    warnings.warn(
        "`as_nx` is deprecated and will be removed in a future release. "
        "Use `gdf_to_nx()` on the returned GeoDataFrames instead to "
        "obtain a NetworkX graph.",
        DeprecationWarning,
        stacklevel=2,
    )

原因在于职责分离:图转换(GeoDataFrame ↔ NetworkX)是 utils.conversion 模块的事,建图函数只需要产出规范化的 GeoDataFrame。这也带来一个好处——你可以先对 GeoDataFrame 做筛选、投影、加列,再决定是否转图;而 as_nx=True 时这些操作只能在 NetworkX 侧做,属性处理麻烦得多。

11.7.3 迁移写法

# 旧写法(会告警)
G = c2g.place_to_place_graph(tess, as_nx=True)

# 新写法
nodes, edges = c2g.place_to_place_graph(tess)
G = c2g.gdf_to_nx(nodes=nodes, edges=edges)

对异构图(三个函数组合后的结果),gdf_to_nx 接受字典:

G = c2g.gdf_to_nx(nodes=nodes_dict, edges=edges_dict, directed=True)

11.8 完整例子:POI 与街道互相建图

下面这个例子不依赖 City2Graph 的镶嵌功能,直接用 OSMnx 抓取 POI 与街道,演示三类图如何拼成一张异构图。

11.8.1 数据准备

import warnings
warnings.filterwarnings("ignore")

import geopandas as gpd
import networkx as nx
import numpy as np
import osmnx as ox

import city2graph as c2g

# 1) 抓取东京塔周边 1 km 的餐馆 POI
poi_tags = {"amenity": ["restaurant", "cafe"]}
poi_gdf = ox.features_from_point(
    (35.658514, 139.70133),
    tags=poi_tags,
    dist=1000,
)
poi_gdf = poi_gdf[poi_gdf.index.get_level_values("element") == "node"].copy()
poi_gdf = poi_gdf.to_crs(epsg=6677)

# 2) 抓取街道网络
G_streets = ox.graph_from_point((35.658514, 139.70133), dist=1000)
streets = c2g.nx_to_gdf(G_streets, nodes=False, edges=True)
streets = streets.to_crs(epsg=6677)

print(f"POI: {len(poi_gdf)}, 街道段: {len(streets)}")

11.8.2 把 POI 变成场所

POI 是点,而场所图要求面。最简单的做法是缓冲区:

# 每个 POI 缓冲 40 m 作为"场所",并生成唯一 place_id
places = poi_gdf.copy()
places["geometry"] = places.geometry.buffer(40)
places["place_id"] = "poi_" + places.index.astype(str)
places = places.set_geometry("geometry")

print(places.crs, len(places))

如果你有真实地块数据,用 create_tessellation 得到镶嵌单元再重命名 tess_id 为 place_id 更严谨(见第 12 章)。

11.8.3 三类图分别构建

# (a) 场所 ↔ 场所:POI 缓冲区之间的 Queen 邻接
place_nodes, place_edges = c2g.place_to_place_graph(
    places,
    contiguity="queen",
)
print("place->place 边数:", len(place_edges))

# (b) 移动 ↔ 移动:街道段对偶图
streets = streets.copy()
streets["movement_id"] = streets.index.astype(str)
movement_nodes, movement_edges = c2g.movement_to_movement_graph(streets)
print("movement->movement 边数:", len(movement_edges))

# (c) 场所 ↔ 移动:POI 缓冲区与街道的界面
pm_nodes, pm_edges = c2g.place_to_movement_graph(
    places,
    streets,
    tolerance=1e-6,
    max_connection_distance=60.0,   # 最近邻回退上限,防止长星形边
)
print("place->movement 边数:", len(pm_edges))

11.8.4 拼成异构图

# 统一节点表:place 与 movement 分别保留自己的索引
nodes_dict = {
    "place": place_nodes.set_index("place_id"),
    "movement": movement_nodes.set_index("movement_id"),
}

# 统一边表:把两列端点设为 MultiIndex
def to_multiindex(edges, from_col, to_col):
    return edges.set_index([from_col, to_col])

edges_dict = {
    ("place", "touched_to", "place"): to_multiindex(
        place_edges, "from_place_id", "to_place_id"
    ),
    ("movement", "connected_to", "movement"): to_multiindex(
        movement_edges, "from_movement_id", "to_movement_id"
    ),
    ("place", "faced_to", "movement"): to_multiindex(
        pm_edges.drop_duplicates(subset=["place_id", "movement_id"]),
        "place_id", "movement_id",
    ),
}

G = c2g.gdf_to_nx(nodes=nodes_dict, edges=edges_dict, directed=True)
print(G)
# MultiDiGraph with N nodes and M edges
print(G.graph.get("is_hetero"), G.graph.get("crs"))

11.8.5 检查结果

# 孤立场所节点(没有任何临街边)
faced_to = edges_dict[("place", "faced_to", "movement")]
connected = set(faced_to.index.get_level_values(0))
isolated = [p for p in nodes_dict["place"].index if p not in connected]
print("孤立场所数:", len(isolated))

# 各边类型的平均几何长度
for key, e in edges_dict.items():
    if len(e) == 0:
        continue
    print(key, len(e), round(float(e.geometry.length.mean()), 2))

11.8.6 用 NetworkX 做简单分析

import pandas as pd

# 场所层的度中心性(只看 touched_to 子图)
G_place = nx.Graph()
G_place.add_nodes_from(nodes_dict["place"].index)
G_place.add_edges_from(edges_dict[("place", "touched_to", "place")].index)
degree = nx.degree_centrality(G_place)

rank = (
    pd.Series(degree, name="degree_centrality")
    .sort_values(ascending=False)
    .head(10)
)
print(rank)

这个例子展示了三类图的分工:touched_to 描述 POI 聚集区之间的相邻关系,connected_to 描述街道的拓扑连通,faced_to 把两者桥接起来。若要走通”从某个 POI 出发沿街道走”,路径必须跨越 faced_to 边;这正是异构图相对单层图的价值。


11.9 注意事项与常见错误

11.9.1 错误速查表

现象 可能原因 修复
ValueError: Expected ID column 'place_id' not found 场所表未生成 ID places["place_id"] = ...
ValueError: Expected ID column 'movement_id' not found 街道表未生成 ID streets["movement_id"] = ...
place->movement 边数为 0 CRS 是经纬度,tolerance=1e-6 等于 0 米 先 to_crs 到米制
出现超长星形边 max_connection_distance 为默认 inf 显式设成 20–100 m
duplicate_edges=True 报错 同时传了 as_nx=True 二选一
反向行的 place_id 里是街道 ID duplicate_edges 的互换语义 加 direction 列区分
对偶图边数异常多 街道端点未吸附,同一路口被识别为多个 set_precision 或 consolidate_intersections
libpysal 警告 Weights matrix contains islands 存在完全孤立的镶嵌单元 正常现象,孤立单元无邻接边
place_to_place_graph 边数与预期不符 用了 group_col 且跨组边被过滤 去掉 group_col 或检查分组列取值

11.9.2 几何有效性

libpysal 与 shapely 都会在遇到自相交面时出错或给出错误邻接。建模前统一修复:

invalid = ~places.geometry.is_valid
if invalid.any():
    print(f"修复 {invalid.sum()} 个无效面")
    places.loc[invalid, places.geometry.name] = places.loc[invalid].geometry.buffer(0)

注意 buffer(0) 可能把自相交面变成 MultiPolygon,甚至变成空几何。修复后要再检查一次:

places = places[~places.geometry.is_empty & places.geometry.notna()]

11.9.3 索引唯一性

place_to_place_graph 会 drop_duplicates(subset=[place_id]),但 place_to_movement_graph 不会对场所去重。若属性连接(attribute join)导致场所表出现重复 place_id,faced_to 边会出现重复行。入口处自查:

dup = places["place_id"].duplicated().sum()
if dup:
    places = places.drop_duplicates(subset=["place_id"])

11.9.4 与 morphological_graph 的关系

如果你要的是完整形态学图,不要手工调这三个函数——直接调 morphological_graph(buildings_gdf, segments_gdf),它内部会:

  1. 用建筑与街道生成镶嵌(第 12 章);
  2. 按 distance 与 extent_buffer 做可达性筛选;
  3. 调这三个函数建三层边;
  4. 组装成 nodes = {"place": ..., "movement": ...} 与 edges = {(类型, 关系, 类型): ...}。

手工调用适合两类场景:一是没有建筑数据,只有 POI 与街道;二是需要对某一层单独替换算法(例如用自定义邻接代替 Queen 邻接)。

11.9.5 性能提示

数据规模 主要瓶颈 建议
场所 < 1 万 libpysal 邻接 直接跑
场所 1–10 万 place_to_place_graph 的 libpysal 构建 确保几何有效、使用 rook 可减少边数
移动 > 10 万 segments_to_graph 的端点匹配 先按行政区裁剪,或分块处理
场所 × 移动 都很大 dwithin 查询 先用 sindex 粗筛包围盒、再精算

place_to_movement_graph 的主查询走空间索引,复杂度接近 O(n log m);回退连接对未匹配场所做 nearest,最坏是 O(k log m)(k 为未匹配数)。真正昂贵的是 movement_to_movement_graph——它要先把所有街道段拆成端点图,端点数量级是段数的两倍。


11.10 典型工作流与选型建议

11.10.1 工作流 A:只有 POI 与街道

这是最容易上手的一类数据条件——没有建筑轮廓,也没有地块边界,但手上有 POI 点与街道线。此时场所层只能由 POI 派生:

POI 点 → 缓冲区 / Voronoi → place 面 → place_to_place_graph
街道线 → movement 线 → movement_to_movement_graph
两者 → place_to_movement_graph → 异构图

三个环节各有陷阱。缓冲区半径要一致,否则 POI 密集处会产生大量重叠面,Queen 邻接会给出虚假的”全连接”。Voronoi 划分更适合密度均匀的 POI 集,但对边界点会产生无限延伸的单元,必须用研究区范围裁剪。街道线则要求端点吸附干净,否则对偶图会碎成许多小片段,度中心性失去意义。

11.10.2 工作流 B:有建筑与街道

这是 City2Graph 设计的标准路径。场所层由 create_tessellation 生成,保证单元互不重叠且覆盖整个研究区;街道既是移动层,也是镶嵌的屏障。此时不要手工调三个函数,直接调 morphological_graph:

import city2graph as c2g

nodes, edges = c2g.morphological_graph(
    buildings_gdf=buildings,
    segments_gdf=streets,
    contiguity="queen",
    keep_buildings=True,
    keep_segments=True,
)

place_nodes = nodes["place"]
movement_nodes = nodes["movement"]
touched = edges[("place", "touched_to", "place")]
connected = edges[("movement", "connected_to", "movement")]
faced = edges[("place", "faced_to", "movement")]

这条路径的额外收益是:morphological_graph 会做可达性筛选、建筑信息回填、孤立节点剪枝,这些逻辑单独调用三个函数时都得自己写。

11.10.3 工作流 C:跨尺度拼接

把行政区作为场所层、把街道作为移动层,可以构造”宏观—微观”双层图:

# 行政区 → 场所(大尺度)
ward_nodes, ward_edges = c2g.place_to_place_graph(
    wards.rename(columns={"GSS_CODE": "place_id"}),
    contiguity="queen",
)

# 街道 → 移动(小尺度)
street_nodes, street_edges = c2g.movement_to_movement_graph(streets)

# 行政区与街道的界面
ward_places = wards.rename(columns={"GSS_CODE": "place_id"})
node_all, edge_all = c2g.place_to_movement_graph(ward_places, streets)

注意 ```place_to_movement_graph` 返回的节点表是两者拼接后的结果,索引被重置,因此要把两层的 ID 列显式保留下来再合并。

11.10.4 选型对照表

条件 推荐路径 理由
有完整建筑轮廓 + 街道 morphological_graph 内置镶嵌与筛选,输出即异构图
只有 POI + 街道 手工调三个函数 无需镶嵌,POI 缓冲区即可当场所
需要多距离等时圈 morphological_graphs 一次镶嵌、多次出图,效率高
需要街道中心性分析 movement_to_movement_graph 对偶图才是”街道为节点”的正确表示
需要空间权重矩阵 contiguity_graph(第 16 章) 输出与 libpysal 兼容的邻接

11.10.5 数据结构一致性检查清单

把三个函数的输出拼进一张异构图之前,逐项确认:

检查项 期望 检查方式
节点索引类型 一致(同为 str 或同为 int) nodes_dict["place"].index.dtype
节点索引唯一 无重复 index.is_unique
边表端点列存在 与节点索引同名 edges.index.names
边表端点可解析 全部存在于节点索引 差集为空
CRS 一致 三个 GeoDataFrame 同 CRS gdf.crs == crs
空边表 有列、有 CRS、零行 len(edges) == 0 and edges.crs is not None

前四项最容易出错。尤其是”边表端点可解析”:place_to_movement_graph 的节点表被 ignore_index 重置过,若你把节点表直接设为异构图节点来源,而边表用的是原始索引,就会出现大量悬空边。做法是先给节点表重新生成稳定 ID 列,再以该列建索引。


11.11 深入理解:圈层、邻接与形态学指标

11.11.1 place_to_place 边与”街区”概念

地域邻接(regional adjacency)在空间分析里通常指行政单元共享边界。City2Graph 把它推广到镶嵌单元,并用 group_col 引入”街区”这一中间层次:

街区 A: [单元 a1, a2, a3]
街区 B: [单元 b1, b2]
               ── 街道(屏障)──

a3 与 b1 在几何上只隔一条街,Queen 规则会判定相邻。但街道是屏障而非连接,这条边在语义上应当被剔除——这正是 group_col="enclosure_index" 的作用。这个设计对应了形态学中的”封闭街区(enclosure)”概念:街道围合出的地块集合。

如果研究目的是研究跨街区渗透(例如步行可达性),可以去掉 group_col,保留跨街区的邻接边;此时建议同时把街道宽度作为边权重,让窄街的连接强度更高。

11.11.2 faced_to 边的方向性

("place", "faced_to", "movement") 是从场所指向移动的有向边。为何要定方向?因为临街关系天然不对称:

  • 一个场所可以同时面对多条街道(转角地块);
  • 一条街道可以被多个场所借用(沿街立面);
  • 但”场所属于哪条街”是从场所出发的属性。

有向表示允许下游做两类完全不同的事:从场所出发统计”临街面数量”(度数即转角数),或从街道出发统计”服务了多少地块”(入度即沿街强度)。若转成无向,这两种语义会被混为一谈。

11.11.3 movement_to_movement 与街道网络分析

对偶图是街道网络分析(street network analysis)的经典表示。它把”一条街”作为分析单元,从而可以直接计算:

指标 计算方式 含义
度(degree) 对偶图中相邻街道数 该街道与其他街道的衔接数
介数(betweenness) 对偶图最短路径经过次数 该街道在城市通行中的中介作用
接近中心性(closeness) 到其他街道平均最短路径的倒数 该街道的相对可达性
整合度(integration) 空间句法中的标准化接近度 街道在网络中的可达层级

注意:对偶图的边不加权时,介数等价于”经过的街道数”;若把原始段长度作为权重,介数则反映”经过的距离”。两种口径都常用,但要写清在论文里。

11.11.4 三层边对形态学指标的贡献

边类型 直接支撑的指标 典型应用
touched_to 场所邻接密度、地块破碎度 城市肌理紧凑度
connected_to 街道连通度、环路指数 路网冗余度、步行友好度
faced_to 临街率、街道界面密度 沿街商业活力、街道围合感

临街率(street frontage ratio)的算法很直观:以场所为分母、以存在 faced_to 边的场所为分子:

total_places = len(place_nodes)
faced_places = faced.index.get_level_values(0).nunique()
frontage_ratio = faced_places / total_places
print(f"临街率: {frontage_ratio:.2%}")

这个指标在 0.6–0.9 之间通常说明镶嵌与街道匹配良好;低于 0.5 往往意味着 max_connection_distance 设得太小,或者建筑离街过远(郊区、大型封闭社区)。

11.11.5 与 contiguity_graph 的关系

place_to_place_graph 在实现上直接调用了 contiguity_graph:

_, edges_gdf = contiguity_graph(gdf_indexed, contiguity=contiguity)

两者的差别在于接口定位:

维度 place_to_place_graph contiguity_graph
面向对象 场所(place_id) 任意面要素
group 过滤 支持 不支持
端点列命名 from_place_id/to_place_id MultiIndex
距离度量 不涉及 支持 euclidean/manhattan/network
典型用途 形态学图 空间权重、区域分析

如果你需要”跨街区的邻接 + 网络距离权重”,应当直接用 contiguity_graph(详见第 16 章),而不是 place_to_place_graph。


11.12 常见问题(FAQ)

11.12.1 为什么 place_to_place_graph 的边表没有 MultiIndex?

因为它面向”直接看边”的场景:两列端点值配合 from_place_id/to_place_id 的语义比 MultiIndex 更直观,导出到 CSV、GeoJSON 或数据库时也更省事。只有汇总到 morphological_graph 的异构边字典时,才统一转成 MultiIndex——异构图的约定是”索引用元组表示端点”。如果你要把两份输出合并,先把列形态的端点列改名对齐:

import pandas as pd

p2p = edges_place.copy()
p2p.index = pd.MultiIndex.from_arrays(
    [p2p.pop("from_place_id"), p2p.pop("to_place_id")],
    names=["source", "target"],
)

11.12.2 为什么 place_to_movement_graph 的边没有 weight?

因为临街关系(frontage)的”权重”没有统一定义。它可以是几何距离、可以是共享界面的长度、也可以是场所临街面的数量——三者量纲完全不同。City2Graph 选择不预设默认值,把权重决策留给使用者。常见三种补法:

权重定义 计算方式 语义
质心距离 edges.geometry.length 场所与街道的粗略距离
界面长度 场所面与街道缓冲区的交集长度 真实临街面长度
二值 恒为 1 只关心是否临街

界面长度的写法:

# 街道缓冲 0.5 m 后与场所求交,取交集长度
buffer = streets.copy()
buffer["geometry"] = buffer.geometry.buffer(0.5)
joined = gpd.overlay(
    places[["place_id", "geometry"]],
    buffer[["movement_id", "geometry"]],
    how="intersection",
)
joined["frontage_len"] = joined.geometry.length
frontage = joined.groupby(["place_id", "movement_id"])["frontage_len"].sum()

11.12.3 镶嵌单元为什么会出现 place_id 冲突?

tess_id 的生成规则是 f"{enclosure_index}_{index}"(见 create_tessellation 末尾)。如果镶嵌被多次调用并合并,或者对同一个镶嵌做了重采样(例如 explode 多部件),可能出现重复。检测方式:

dup = tess["place_id"][tess["place_id"].duplicated()].unique()
print("冲突 ID:", dup[:10], "数量:", len(dup))

修复方式是给重复项加后缀,而不是直接删除——删除会让对应的建筑失去场所单元。

11.12.4 为什么 movement_to_movement_graph 的边数远多于预期?

常见三个原因,按出现频率排序:

  1. 端点未吸附:同一条街被拆成多段,每段两端各生成一个节点,导致对偶图碎化。检查方法:统计原始街道图的节点数,若接近 2 × 段数,说明几乎没有共享端点。
  2. 道路图层包含重复几何:同一路段以不同 movement_id 出现两次,对偶图会出现自环式重复边。用 drop_duplicates(subset=["geometry"]) 或按属性去重。
  3. 立交与隧道:平面上相交但实际不连通的线被判定为共享端点。需要按层级(layer、tunnel、bridge)字段先过滤。

11.12.5 三层图里的孤立节点应不应该删?

取决于分析目标:

目标 处理方式
计算整体连通性 保留,孤立点本身是结论(该地块不临街)
训练图神经网络 删除,孤立点不参与消息传递,只会引入全零嵌入
可视化 保留但用不同颜色标出
计算临街率 保留,孤立点是分子分母的一部分

morphological_graph 的 drop_isolated_place 参数(内部使用)会在应用可达性预算时自动删除没有 faced_to 边的场所;不带 distance 调用时不删除。

11.12.6 能否把异构图直接喂给 PyTorch Geometric?

可以。gdf_to_pyg 接受 (nodes_dict, edges_dict):

data = c2g.gdf_to_pyg(
    nodes=nodes,
    edges=edges,
    node_feature_cols=["height", "floors"],
    edge_feature_cols=["weight"],
)
print(data)
# HeteroData(
#   place={x=[...], pos=[...]},
#   movement={x=[...], pos=[...]},
#   (place, touched_to, place)={edge_index=[2, ...], weight=[...]},
#   ...
# )

细节见第 7 章。要点:节点特征列必须在每层都是数值型,边特征列只在相应边类型里查找。


11.13 参数速查表

11.13.1 三个函数的参数对照

参数 place_to_place place_to_movement movement_to_movement
place_gdf 必填 必填 —
movement_gdf — 必填 必填
group_col 可选 — —
contiguity 可选 — —
primary_barrier_col — 可选 —
tolerance — 可选 —
max_connection_distance — 可选 —
as_nx 可选(废弃) 可选(废弃) 可选(废弃)
duplicate_edges 可选 可选 可选

11.13.2 常用参数取值建议

参数 建议值 适用条件
tolerance 1e-6(默认) 数据已精确相接
tolerance 0.5 ~ 2.0 数据有几何误差,需容差连接
max_connection_distance 20 ~ 100 城市街区尺度,建筑进深量级
max_connection_distance math.inf 需要强制连通,接受长边
contiguity "queen" 默认,邻接更完整
contiguity "rook" 需要严格共边判定
group_col "enclosure_index" 封闭镶嵌,需按街区隔离
duplicate_edges False 默认
duplicate_edges True 需要双向邻域查询

11.13.3 输出列名速查

函数 节点列 边列 边索引
place_to_place_graph 原列 + place_id from_place_id, to_place_id, 分组列, geometry RangeIndex
place_to_movement_graph 两层列并集 + 重置索引 place_id, movement_id, geometry RangeIndex
movement_to_movement_graph 原列 + 可选 movement_id from_movement_id, to_movement_id, geometry RangeIndex

11.14 延伸练习与延伸阅读

11.14.1 练习一:可视化三类边的分布

把三类边分别画在三个子图上,观察它们在空间上的差异:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 3, figsize=(18, 6))

place_nodes.plot(ax=axes[0], color="#f2f2f2", edgecolor="#cccccc", linewidth=0.2)
place_edges.plot(ax=axes[0], color="#1f77b4", linewidth=0.6)
axes[0].set_title("touched_to")
axes[0].set_axis_off()

movement_nodes.plot(ax=axes[1], color="#f2f2f2")
movement_edges.plot(ax=axes[1], color="#d62728", linewidth=1.2)
axes[1].set_title("connected_to")
axes[1].set_axis_off()

place_nodes.plot(ax=axes[2], color="#f2f2f2", linewidth=0.2)
pm_edges.plot(ax=axes[2], color="#2ca02c", linewidth=0.4, alpha=0.5)
axes[2].set_title("faced_to")
axes[2].set_axis_off()

plt.tight_layout()
plt.show()

观察要点:touched_to 边应基本沿街区内部网格分布;connected_to 边应贴合街道走向;faced_to 边应垂直于街道、指向最近街道。若第三张图出现大量同方向的超长边,说明回退连接没有设上限。

11.14.2 练习二:比较 Queen 与 Rook 的边数差

results = []
for rule in ("queen", "rook"):
    _, e = c2g.place_to_place_graph(places, contiguity=rule)
    results.append({"rule": rule, "edges": len(e), "mean_len": float(e.geometry.length.mean())})

import pandas as pd
print(pd.DataFrame(results))

在规则网格状的镶嵌上两者差异很小;在不规则镶嵌(建筑形态复杂)上,Queen 通常比 Rook 多出 10%–30% 的边。

11.14.3 练习三:给 faced_to 边加权重

用界面长度替换质心距离,观察权重分布的变化:

# 界面长度法(对每条 faced_to 边,计算场所与街道缓冲的交集长度)
buf = streets.copy()
buf["geometry"] = buf.geometry.buffer(1.0)
inter = gpd.overlay(
    places[["place_id", "geometry"]],
    buf[["movement_id", "geometry"]],
    how="intersection",
)
inter["frontage"] = inter.geometry.length
frontage = inter.groupby(["place_id", "movement_id"])["frontage"].sum()

pm = pm_edges.copy()
pm["frontage"] = pm.set_index(["place_id", "movement_id"]).index.map(frontage)
pm["frontage"] = pm["frontage"].fillna(0.0)
print(pm["frontage"].describe())

大多数回退边的界面长度会是 0(因为场所根本不接触街道缓冲区),这提示你:回退边只是”补连通”,不应参与临街强度统计。

11.14.4 延伸阅读

主题 文献 / 资料 与本章的关系
空间句法 Hillier, B. & Hanson, J. The Social Logic of Space (1984) 对偶图与整合度的理论源头
形态学网络 Serra, M. et al. 关于 morphological tessellation 的系列论文 create_tessellation 的方法论基础
对偶图构造 Porta, S. et al. The Network Analysis of Urban Streets (2006) movement_to_movement_graph 的参照
libpysal 空间权重 Rey, S. & Anselin, L. libpysal 文档 place_to_place_graph 的底层
临街面与街道界面 城市设计领域的 street frontage 研究 faced_to 边的指标解释

11.14.5 与其他章节的衔接

想知道 去看
镶嵌单元怎么生成 第 12 章
邻近图的 KNN / Delaunay 第 13 章
概率图与最小生成树 第 14 章
多层图桥接与节点分组 第 15 章
领接图与空间权重 第 16 章
GeoDataFrame 与 NetworkX 互转 第 6 章
导出到 PyTorch Geometric 第 7 章

11.15 本章要点回顾

11.15.1 概念层面的三个判断

判断一段代码是否用对了本章的 API,可以问三个问题。第一个问题:手里的数据是面还是线,有没有稳定的 ID 列?面必须有 place_id,线必须有 movement_id(或允许函数自动生成)。第二个问题:三类关系是否都需要?如果只研究街道本身,movement_to_movement_graph 就够了,不必强行拉上场所层;如果只研究地块肌理,place_to_place_graph 足矣,faced_to 反而会引入街道噪声。第三个问题:投影单位是不是米?凡是涉及 tolerance、max_connection_distance 的参数,在经纬度下都没有意义。

11.15.2 实现层面的四个细节

  • place_to_place_graph 内部先按 place_id 去重再调 libpysal,重复 ID 会静默丢弃行;
  • place_to_movement_graph 的节点表被 ignore_index 重置,边表却仍用原始 ID,两者混用会产生悬空边;
  • movement_to_movement_graph 的成败取决于端点是否精确共点,坐标吸附是前置工序;
  • 三个函数的 as_nx 都已废弃,正确姿势是 gdf_to_nx。

11.15.3 排错时的思考顺序

遇到”边数不对”或”图断开”,先看数据结构再看算法:ID 列是否存在、索引是否唯一、端点是否能对上、CRS 是否投影、分组列取值是否一致。这五项检查完,问题通常已经定位到某一行数据上。算法本身(Queen/Rook、dwithin、对偶图)很少出错,出错的多是输入。


11.16 设计取舍的再讨论

11.16.1 为什么用质心而不是原始几何

三个建图函数都把节点几何取成质心。这个选择在面数据上意味着丢掉形状信息,在长条状单元上尤其明显:一个狭长的地块,其质心可能落在相邻地块的范围内,导致邻接与临街判断出现偏差。

City2Graph 仍然选择质心,理由是后续的图算法都基于点坐标。NetworkX 的路径计算、PyTorch Geometric 的位置编码、可视化的散点绘制,都要求节点是一个点。若保留面几何,所有下游代码都要处理”非点节点”这一情况,复杂度大幅上升。

代价通过额外列弥补:形态学图把原始面存在 tessellation_geometry 列,原始线存在 segment_geometry 列。需要真实几何时从这些列取回,不需要时忽略。这是一种”默认简单、按需复杂”的设计。

若质心偏差不可接受,应当在传入前自行构造代表点。例如用 shapely 的 representative_point 取面内一点,或者按业务规则指定(零售分析取入口点,住宅分析取单元中心)。注意代表点必须在面内,否则空间连接会出错。

11.16.2 为什么空表返回空结构而不是报错

空数据在真实项目中极为常见:某个行政区没有公交站,某个网格没有 POI,某个时间段没有出行记录。如果每个函数在空输入时抛异常,调用方就要写大量 try 与 if,代码很快变得难以维护。

City2Graph 的选择是让空输入返回列结构与类型正确的空结果。这带来一个隐含约定:调用方可以无条件地遍历结果,不必先判断非空。只有在”缺少必需 ID 列”这类配置错误时才抛异常,因为那是代码问题而非数据问题。

这个约定对批量处理尤其有价值。你可以对所有单元循环调用建图函数,收集所有结果,最后统一过滤空表,而不必先在循环里判断数据量。

11.16.3 参数默认值的用意

三个函数的默认值都偏向”最安全”而非”最有用”:contiguity 默认 queen(更多边,不会漏掉邻接),max_connection_distance 默认无穷(不丢边),as_nx 默认假(返回便于检查的 GeoDataFrame)。

这种保守默认的好处是初次使用不容易得到”看起来缺了什么”的结果,代价是生产环境必须显式收紧参数。经验是:先用默认值跑通,看清边数与分布,再按业务语义把阈值收紧。不要一开始就设置严格的阈值,否则很难区分”数据里确实没有”与”参数把边过滤掉了”。


11.17 小结

本章围绕 City2Graph 形态学模块的三个基础函数展开:

  • 语义层:place 是面,movement 是线;place_id 与 movement_id 是两层节点的唯一标识,前者常由 tess_id 重命名而来,后者默认取街道表索引。
  • place_to_place_graph:基于 libpysal 的 Queen/Rook 邻接,group_col 可把邻接限制在同组内,duplicate_edges 产出互逆行;输出边表带 from_place_id/to_place_id 两列。
  • place_to_movement_graph:主查询用 dwithin 空间索引谓词,未匹配的场所通过 sindex.nearest 回退连接,max_connection_distance 限制回退边长度;输出边表只有 place_id/movement_id/geometry,没有 weight 列。
  • movement_to_movement_graph:先 segments_to_graph 建原始图,再 dual_graph 取对偶图,得到”街道段为节点、路口为边”的结构;端点吸附质量直接决定结果正确性。
  • 工程约定:as_nx 已废弃,改用 gdf_to_nx;距离参数必须在投影坐标系下解释;空表一律返回类型正确的空结果而不是抛异常。

下一章进入场所空间的生成环节:如何用 create_tessellation 从建筑与街道得到镶嵌单元,以及镶嵌失败时 City2Graph 的回退阶梯。