第09章 形态学图进阶与批量构建

本章导读:上一章用 morphological_graph 建一张单距离的形态学图。真实研究会一次要多个距离(400 / 800 / 1200 米),如果每个距离都重跑一遍围合镶嵌,代价会高得离谱。morphological_graphs 把最贵的那一步——镶嵌——只做一次,然后对每个距离复用。本章拆开这条流水线,逐段解释 _prepare_morphology、_segments_for_distance、_graph_for_distance 与一串 _filter_* 函数的分工,并覆盖 barriers、fallback cells、预算与错误处理、as_nx / duplicate_edges 的组合规则,最后给出性能与内存的实测建议。


9.1 为什么需要批量构建

9.1.1 单距离流程的三段开销

回顾第 8 章的 morphological_graph,它的内部可以分成三段:

段 内容 是否与 distance 有关 典型耗时占比
准备段 校验、CRS 对齐、movement_id 赋值、路段切分、可达场计算 部分有关(可达场依赖 center_point) 10–20%
镶嵌段 建筑 + 屏障 → 围合镶嵌 无关(同一批建筑与屏障) 60–80%
过滤段 按距离过滤建筑 / 地块、建三层边 完全有关 10–20%

如果对 [400, 800, 1200] 三个距离各调用一次 morphological_graph,镶嵌段就被浪费了两遍。

9.1.2 morphological_graphs 的复用策略

morphological_graphs 的做法是:

  1. 用最大距离准备一次上下文(验证、切分、可达场);
  2. 用最大距离对应的路段缓冲建一次围合镶嵌;
  3. 对每个距离,只跑过滤段,复用同一份镶嵌结果。
import city2graph as c2g

results = c2g.morphological_graphs(
    buildings_gdf=buildings,
    segments_gdf=segments,
    distances=[400.0, 800.0, 1200.0],
    center_point=center,
)
print(sorted(results))       # [400.0, 800.0, 1200.0]
nodes_400, edges_400 = results[400.0]
nodes_800, edges_800 = results[800.0]

9.1.3 代价:边缘会略有差异

文档里明确写了一句容易被忽略的话:

Because the tessellation context corresponds to the largest distance, results for smaller distances can differ slightly near the clipping boundary compared to calling morphological_graph once per distance.

意思是:用 1200 米范围建的镶嵌,在筛选 400 米结果时,边缘地块的边界形状可能和「直接用 400 米范围建镶嵌」略有不同。原因很直观——镶嵌是按屏障切分的,屏障范围不同,边缘的地块形状就会变。

关注点 建议
结果严格可复现 / 需要最小上下文 逐距离调用 morphological_graph
批量研究、多距离对比、追求吞吐 morphological_graphs
边缘地块形状敏感(如精细形态学指标) 逐距离调用,或把 clipping_buffer 放大

9.1.4 参数与返回

morphological_graphs 的参数与 morphological_graph 几乎一致,差别只在 distances 与返回值:

项 morphological_graph morphological_graphs
距离参数 distance: float or None distances: list[float] or tuple
返回 (nodes, edges) 或 nx.Graph dict[float, (nodes, edges)]
as_nx 默认 None False
空 distances 不适用 ValueError: distances must contain at least one value
try:
    c2g.morphological_graphs(buildings, segments, distances=[])
except ValueError as exc:
    print(exc)   # distances must contain at least one value

distances 内部会先转成 float:[float(d) for d in distances]。所以传 [400, 800] 与 [400.0, 800.0] 得到的键都是浮点。


9.2 流水线总览

9.2.1 五个阶段的职责

输入表
  │
  ├─ 1. _prepare_morphology          校验、CRS 对齐、movement_id、barrier-only 拆分
  │                                   segments_to_graph、可达场、缓冲图
  │                                   -> _MorphologyContext
  │
  ├─ 2. (仅 maximum distance)         建一次围合镶嵌
  │     _segments_for_distance(max)
  │     _create_enclosed_tessellation
  │
  └─ 对每个 distance d:
       ├─ 3. _segments_for_distance(d)     筛选可达段 + 缓冲段(+barrier 上下文)
       ├─ 4. _create_and_filter_tessellation 复用/新建镶嵌,跑过滤链
       └─ 5. _build_morphological_layers    拼三层边 + 节点表
           (+ duplicate_edges 对称化)

9.2.2 上下文字段的含义

_MorphologyContext 是个 NamedTuple,字段都有明确用途:

字段 类型 用途
buildings GeoDataFrame 修复 / 压平索引后的建筑表(只读)
segments GeoDataFrame 带 movement_id 的路段表(只读)
barrier_segments GeoDataFrame / None 只作屏障的路段
center_point GeoSeries / None 分析中心
clipping_buffer / extent_buffer float 缓冲参数
limit geometry / None 镶嵌边界
primary_barrier_col str / None 屏障几何列名
contiguity str 相邻判定方式
keep_buildings / keep_segments bool 输出选项
tolerance float 临街容差
include_unenclosed_buildings bool 是否补未围合建筑
as_nx / duplicate_edges bool 输出选项
tessellation_fallback bool 镶嵌失败时是否降级
tessellation_n_jobs int 并行度
field _ReachabilityField / None 共享可达场
segment_graph (nodes, edges) / None 共享的路段图
buffer_graph / buffer_distances 图 / dict / None 缓冲用的图与距离

其中 field、segment_graph、buffer_graph、buffer_distances 是「一次算多次用」的关键:可达场只算一次,所有节点类型(街道、建筑、地块)都用同一张网络上的同一份距离来判定。

9.2.3 为什么共享可达场很重要

假如每个距离、每种节点类型都各自建一次图算一次最短路:

做法 图构建次数 最短路次数 结果一致性
各自计算 1 次/距离/类型 1 次/距离/类型 可能因建图顺序不同出现细微差异
共享可达场 1 次总计 1 次总计 完全一致

共享还有一个正确性理由:建筑、地块、街道必须用同一个度量判断是否可达,否则会出现「路段在圈内、但它临街的建筑被判在圈外」这类矛盾。


9.3 _prepare_morphology:准备段详解

9.3.1 校验顺序

def _prepare_morphology(buildings_gdf, segments_gdf, center_point, *, has_distance, ...):
    _validate_duplicate_edges(duplicate_edges, as_nx)
    _validate_input_gdfs(buildings_gdf, segments_gdf)
    ...

校验顺序是有讲究的:先查参数组合冲突(duplicate_edges + as_nx),再查输入类型。这样报错信息更贴近用户的第一处错误。

9.3.2 参数边界检查

检查 不通过时
contiguity in {"queen", "rook"} ValueError: contiguity must be 'queen' or 'rook'
clipping_buffer >= 0 ValueError: clipping_buffer cannot be negative.
extent_buffer >= 0 ValueError: extent_buffer cannot be negative.
clipping_buffer >= extent_buffer ValueError: clipping_buffer must be greater than or equal to extent_buffer.

最后一条容易被忽视:很多人想「裁剪缓冲小于接入缓冲」,逻辑上就矛盾了——镶嵌上下文范围比接入距离还小,边缘地块必然缺上下文。所以函数直接禁止。

9.3.3 建筑预处理

original_buildings = buildings_gdf
buildings_gdf = _repair_invalid_buildings(buildings_gdf)
if isinstance(buildings_gdf.index, pd.MultiIndex):
    if buildings_gdf is original_buildings:
        buildings_gdf = buildings_gdf.copy()
    buildings_gdf.index = buildings_gdf.index.to_flat_index()

两个动作:

动作 原因
_repair_invalid_buildings 自相交多边形会让 momepy 抛 TopologyException;内部用 buffer(0) 修复
MultiIndex -> flat_index 多级索引在后续 join 与 fallback 匹配时会出问题,先压平

注意「不修改调用方数据」的约定:只有在修复函数没产生新对象时才 copy(),否则直接改自己拥有的副本。这是整个模块反复强调的「frame ownership」原则。

9.3.4 屏障几何的提前捕获

barrier_geometry = None
if primary_barrier_col and primary_barrier_col in segments_gdf.columns \
        and primary_barrier_col != segments_gdf.geometry.name:
    barrier_geometry = gpd.GeoSeries(segments_gdf[primary_barrier_col])
    barrier_crs = barrier_geometry.crs or segments_gdf.crs
    ...

为什么要「提前」捕获?因为下一步会 harmonize_crs 把 segments 转成 buildings 的 CRS,而 object dtype 的几何列在换 CRS 后会丢失自己的 CRS 元数据。所以先把屏障几何抽成一个独立 GeoSeries、记录 CRS、必要时单独 to_crs,再在 CRS 对齐后塞回去。

这个细节解释了为什么上传数据里 barrier_geometry 列的 CRS 不可靠也没关系——函数不依赖列上的 CRS 元数据。

9.3.5 CRS 对齐与警告

segments_gdf = GeoDataProcessor.harmonize_crs(segments_gdf, buildings_gdf.crs, stacklevel=3)
GeoDataProcessor.warn_crs_issues(buildings_gdf, geographic_message=_GEOGRAPHIC_CRS_MSG, stacklevel=3)
行为 说明
harmonize_crs 只转 segments,不动 buildings(buildings 是参照系)
warn_crs_issues 若 buildings 是地理 CRS,打警告;不会自动投影

再次强调:extent_buffer=100 在地理 CRS 下就是 100 度,必须自己先投影。

9.3.6 movement_id 与 barrier-only 拆分

segments_gdf = segments_gdf.copy()
if barrier_geometry is not None:
    segments_gdf[primary_barrier_col] = barrier_geometry
segments_gdf[_MOVEMENT_ID_COL] = segments_gdf.index

barrier_segments = None
if non_movement_barrier_col and non_movement_barrier_col in segments_gdf.columns:
    barrier_mask = segments_gdf[non_movement_barrier_col].fillna(value=False).astype(bool)
    barrier_segments = segments_gdf.loc[barrier_mask]
    segments_gdf = segments_gdf.loc[~barrier_mask]
步骤 作用
copy() 整个流程里唯一一次对外部输入的复制(之后都操作自己拥有的帧)
塞回 barrier_geometry 用对齐后的 CRS 版本替换原列
movement_id = index 建立稳定的路段 ID,后续所有 edge 引用它
拆 barrier-only 被标记的行离开 movement 图层,只留作屏障

注意 fillna(False):标志列里常有 NaN,直接 astype(bool) 会把 NaN 当 True。

9.3.7 共享路段图

segment_graph = segments_to_graph(segments_gdf)

这一步产出的 (segment_nodes, segment_edges) 会被后续所有距离复用。它同时服务三个目的:

  1. 提供 movement 节点表(segment_nodes);
  2. 提供 movement 边表(segment_edges);
  3. 作为可达场计算的网络。

segments_to_graph 的默认参数是 multigraph=True, directed=True,所以路段图是有向多重图。对形态学分析来说方向不重要(形态学研究的是空间关系),但多重边需要保留(平行路段确实存在)。

9.3.8 可达场与缓冲图

field = None
if center_point is not None and has_distance and not segments_gdf.empty:
    field = _network_reachability_field(segment_graph[1], center_point)

buffer_graph = None
buffer_distances = None
if center_point is not None and has_distance and not segments_gdf.empty:
    buffer_graph = gdf_to_nx(nodes=segment_graph[0], edges=segment_graph[1])
    buffer_distances = compute_center_node_distances(
        buffer_graph, center_point=center_point, edge_attr="length", cutoff=math.inf
    )

两个结构的区别:

结构 算法 用途
field(_ReachabilityField) 单源可达场,按边权(length)累积 判定「某点是否在 distance 以内」
buffer_graph + buffer_distances NetworkX 图 + 每个节点的距离字典 用 build_reachable_subgraph 快速裁出一个半径子图

既然两者都是算距离,为什么还要两套?因为用途不同:field 要回答「给定任意几何质心,到中心的网络距离是多少」,需要空间索引 + 最近边投影;buffer_graph 要回答「把半径内的路段子图给我」,直接在图上裁剪更直接。

buffer_radius = distance if math.isinf(clipping_buffer) else distance + clipping_buffer
sub = build_reachable_subgraph(buffer_graph, buffer_distances, buffer_radius)

注意 clipping_buffer=math.inf 时缓冲半径就是 distance(无穷大没有意义)。


9.4 _segments_for_distance:按距离筛路段

9.4.1 两条不同的路段集合

每个距离会产出两个路段集合,这是本章最容易混淆的概念:

集合 变量 用途 如何筛选
可达段 segments_filtered 建 movement 节点、判定建筑 / 地块保留 网络距离 ≤ distance
缓冲段 segments_buffer 只用于镶嵌上下文(屏障与粗筛) 网络距离 ≤ distance + clipping_buffer,或欧氏缓冲
if context.center_point is None or distance is None or context.segments.empty:
    segments_filtered = segment_edges
    segments_buffer = segment_edges
else:
    segments_filtered = _segments_within_network_distance(
        segment_edges, context.center_point, distance, field=context.field
    )
    buffer_radius = distance if math.isinf(context.clipping_buffer) else distance + context.clipping_buffer
    segments_buffer_graph = build_reachable_subgraph(
        context.buffer_graph, context.buffer_distances, buffer_radius
    )
    segments_buffer = nx_to_gdf(segments_buffer_graph, nodes=False, edges=True)

9.4.2 为什么要分开

文档里有一句关键的说明:

The wider segments_buffer only provides tessellation context (barriers and a coarse adjacency gate); building and cell retention are judged solely against segments_filtered.

意思是:

  • 镶嵌用宽的范围(缓冲段),这样边缘地块不会因为缺屏障而形状怪异;
  • 保留判定用窄的范围(可达段),这样「圈外」的建筑 / 地块不会因为「附近有条街但那条街在圈外」而被保留。

如果两者混用,会出现一种典型错误:等时圈边缘多出一圈朝外延伸的细长地块,因为它们被圈外的街道「粘住」了。

9.4.3 没有中心点时的行为

条件 segments_filtered segments_buffer
center_point=None 全部路段 全部路段
distance=None 全部路段 全部路段
路段表为空 空 空

也就是说,不传 center_point 时,distance 参数不起作用——这是设计使然:没有起点,谈「网络距离」没有意义。

9.4.4 追加 barrier-only 路段

segments_buffer = _append_barrier_context_segments(
    segments_buffer,
    context.barrier_segments,
    context.center_point,
    distance,
    context.clipping_buffer,
    context.primary_barrier_col,
)

barrier-only 路段(铁路、封闭围墙等)不参与可达性,但必须参与镶嵌。这步把它们按同样的半径裁一遍,追加到缓冲段集合里。

注意它们不会进入 segments_filtered,所以不会变成 movement 节点,也不会出现在 connected_to 边里。

9.4.5 一个可运行的对照实验

import geopandas as gpd
from shapely.geometry import Point

import city2graph as c2g
from city2graph.morphology import _prepare_morphology, _segments_for_distance

center = gpd.GeoSeries([Point(5000, 5000)], crs="EPSG:3857")

ctx = _prepare_morphology(
    buildings, segments, center,
    has_distance=True,
    clipping_buffer=200.0,
    extent_buffer=60.0,
    limit=None,
    primary_barrier_col=None,
    contiguity="queen",
    keep_buildings=False,
    keep_segments=True,
    tolerance=1e-6,
    include_unenclosed_buildings=False,
    as_nx=False,
    duplicate_edges=False,
    non_movement_barrier_col=None,
    tessellation_fallback=False,
    tessellation_n_jobs=1,
)
f400, b400 = _segments_for_distance(ctx, 400.0)
f800, b800 = _segments_for_distance(ctx, 800.0)
print(len(f400), len(b400), len(f800), len(b800))

预期输出满足:len(f400) <= len(f800)、len(b400) >= len(f400)。


9.5 _graph_for_distance:单个距离的组装

9.5.1 主流程

def _graph_for_distance(context, distance, base_tessellation=None):
    segments_filtered, segments_buffer = _segments_for_distance(context, distance)
    tessellation = _create_and_filter_tessellation(
        context, distance, segments_buffer, segments_filtered,
        base_tessellation=base_tessellation,
    )
    drop_isolated_place = context.center_point is not None and distance is not None
    nodes, edges = _build_morphological_layers(
        context, tessellation, segments_filtered,
        drop_isolated_place=drop_isolated_place,
    )
    if context.duplicate_edges:
        for edge_type in (("place", "touched_to", "place"),
                          ("movement", "connected_to", "movement")):
            edges[edge_type] = symmetrize_edges(edges[edge_type])
    return (nodes, edges) if not context.as_nx else gdf_to_nx(nodes, edges)

9.5.2 drop_isolated_place 的触发条件

drop_isolated_place = context.center_point is not None and distance is not None

只要同时给了中心点和距离,就会剪掉「没有任何 faced_to 连接」的地块。理由:等时圈内的诱导子图不应该出现孤立的 place 节点。

后果:

影响 说明
place 节点减少 没有临街连接的地块被删
touched_to 边减少 引用被删地块的相邻边一并剪掉
图更干净 不会出现「孤岛地块」污染中心性指标

9.5.3 duplicate_edges 只作用于两类边

for edge_type in (("place", "touched_to", "place"),
                  ("movement", "connected_to", "movement")):
    edges[edge_type] = symmetrize_edges(edges[edge_type])

为什么 faced_to 不做?因为它是有向的跨类型边。补一条反向行意味着 place_id 列里会填入 movement ID、movement_id 列里填入 place ID——索引语义被破坏。文档里写得很明确:

The heterogeneous (“place”, “faced_to”, “movement”) edges are left unchanged because a reverse row would mix movement ids into the place index level.

9.6 镶嵌构建与降级策略

9.6.1 _create_enclosed_tessellation 的单一职责

def _create_enclosed_tessellation(buildings_gdf, barriers, *, limit, n_jobs, suppress_empty_error):
    tessellation_kwargs = {}
    if limit is not None:
        tessellation_kwargs["limit"] = limit
    if n_jobs != -1:
        tessellation_kwargs["n_jobs"] = n_jobs
    try:
        return create_tessellation(
            buildings_gdf,
            primary_barriers=None if barriers.empty else barriers,
            **tessellation_kwargs,
        )
    except ValueError as exc:
        if suppress_empty_error and str(exc) == "No objects to concatenate":
            return None
        raise

四个设计要点:

设计 原因
limit / n_jobs 只在非默认时才传 避免把 None / -1 显式传进 momepy 改变其默认行为
barriers.empty 时传 None momepy 对空 GeoDataFrame 和 None 的处理不同
只捕获 ValueError momepy 的「No objects to concatenate」是 ValueError;其他异常必须冒泡
精确匹配错误消息 用 str(exc) == 而不是子串匹配,避免吞掉别的 ValueError

最后一条很关键:如果写成 if "No objects" in str(exc),未来 momepy 换了消息模板就会静默失效;精确匹配则会立刻暴露。

9.6.2 suppress_empty_error 何时为 True

调用点 suppress_empty_error 结果
单距离路径(_create_and_filter_tessellation) context.tessellation_fallback 开启 fallback 时降级,否则抛错
批量路径(morphological_graphs) 总是 True 返回 None 让各距离自己决定降级方式

批量路径总是 True 的原因:它要先建一次基础镶嵌,如果失败但不该整体崩溃,就让每个距离的调用自己去走降级逻辑。

9.6.3 三种降级路径

触发条件 降级方式 函数
镶嵌抛 No objects to concatenate 用建筑轮廓当 place 单元 _fallback_tessellation_without_enclosures
镶嵌成功但过滤后为空 同上 同上
部分建筑被围合镶嵌漏掉 用无屏障镶嵌补 _include_unenclosed_building_tessellation
只有建筑没被任何 cell 覆盖 单栋建筑一个 cell _building_fallback_cells

9.6.4 fallback cell 的构造

def _building_fallback_cells(buildings):
    cells = gpd.GeoDataFrame(
        {
            _PLACE_ID_COL: "fallback_" + buildings.index.astype(str),
            "enclosure_index": "fallback",
        },
        geometry=buildings.geometry.to_numpy(),
        crs=buildings.crs,
    )
    cells[_SOURCE_BUILDING_INDEX_COL] = buildings.index.to_numpy()
    return cells

三个细节:

细节 作用
place_id = "fallback_" + index 与真实 tess_id 不会冲突,且可反查回建筑
enclosure_index = "fallback" 所有 fallback cell 归入同一个「围合块」,让 touched_to 分组过滤仍能工作
_source_building_index 让 _add_building_info 能精确匹配,而不是靠空间 join

几何直接复用建筑轮廓,不复制。这意味着 fallback 模式下 place 单元就是建筑本身——形态学指标会退化,但流程不中断。

9.6.5 什么时候该打开 tessellation_fallback

nodes, edges = c2g.morphological_graph(
    buildings, segments,
    tessellation_fallback=True,
)
场景 建议
数据稀疏、镶嵌常失败(如乡村地区) 打开
严格研究、需要真实地块形状 关闭,让错误暴露
批量跑多个城市,个别城市失败 打开,配合日志过滤
只想验证流水线是否跑通 打开

打开后要注意检查 place_id 是否带 fallback_ 前缀:

place = nodes["place"]
n_fallback = place.index.astype(str).str.startswith("fallback_").sum()
print(f"fallback cells: {n_fallback} / {len(place)}")

如果比例过高(例如超过 50%),说明镶嵌基本不可用,应回头查屏障数据。


9.7 过滤链:filter* 系列

9.7.1 四道过滤

_create_and_filter_tessellation 里依次跑了四道过滤:

顺序 函数 作用对象 判定依据
1 _filter_buildings_by_network_distance 建筑 网络距离 ≤ distance 且直线接入 ≤ extent_buffer
2 _include_unenclosed_building_tessellation 镶嵌结果 补上被漏掉的建筑
3 _filter_adjacent_tessellation 地块 质心到街道的直线距离 ≤ distance + clipping_buffer
4 _filter_tessellation_by_network_distance 地块 网络距离 ≤ distance 且直线接入 ≤ extent_buffer

第 3 道是「粗筛」,用欧氏距离快速砍掉一大片;第 4 道是「精筛」,用真实网络距离。这个两段式设计是性能考虑:欧氏距离计算便宜,先砍掉大部分再算网络距离。

9.7.2 第 1 道:建筑过滤

eligible_buildings = _filter_buildings_by_network_distance(
    context.buildings, segments_filtered, context.center_point, distance,
    context.extent_buffer, field=context.field,
)

两个独立的上限:

上限 参数 语义
网络距离 distance 从中心沿路网走过去的距离
直线接入 extent_buffer 建筑质心到最近街道的垂距

任一超限即被剔除。这避免了「路网绕一大圈可达但实际隔着一堵墙」的误保留。

9.7.3 第 3 道:相邻粗筛的按围合块优化

_filter_adjacent_tessellation 里有一段值得学习的性能优化:

groups = tessellation.groupby(enclosure_col) if enclosure_col is not None else [(None, tessellation)]
segments_sindex = segments.sindex
all_segments_union = segments.union_all()
for _, group in groups:
    enclosure_geom = group.union_all()
    candidate_pos = segments_sindex.query(enclosure_geom, predicate="intersects")
    segment_union_in_enclosure = (
        all_segments_union if len(candidate_pos) == 0
        else segments.iloc[candidate_pos].union_all()
    )
    distances_in_group = group.geometry.centroid.distance(segment_union_in_enclosure)
    filtered_group = group.loc[distances_in_group <= max_distance]
优化点 收益
按 enclosure_index 分组 每组只用组内相关路段,减少无关计算
sindex.query 空间索引代替全表扫描
union_all() 缓存 每个围合块只合并一次路段
质心距离而非多边形距离 快得多,且对地块这种小面足够准

注意「质心 vs 多边形」的取舍:用地块质心到街道的距离,而不是地块边界到街道的距离。后者更严格,但慢很多。如果你需要严格判定,可以关掉这一层,只用第 4 道精筛。

9.7.4 第 4 道:网络距离精筛

if context.center_point is not None and distance is not None:
    tessellation = _filter_tessellation_by_network_distance(
        tessellation, segments_filtered, context.center_point, distance,
        context.extent_buffer, field=context.field,
    )

内部通过 _geometry_ilocs_within_network_distance 把每个地块质心投影到最近边上,再用共享可达场查距离。返回的是位置索引(iloc),所以过滤用 tessellation.iloc[keep_ilocs],不会打乱顺序。

9.7.5 keep_buildings 与内部列的清理

if context.keep_buildings:
    tessellation = _add_building_info(tessellation, eligible_buildings)
else:
    tessellation = tessellation.drop(columns=[_SOURCE_BUILDING_INDEX_COL], errors="ignore")

_SOURCE_BUILDING_INDEX_COL 是内部记账用的列,不该泄漏到输出。注意 errors="ignore":在某些路径下这一列可能不存在,不忽略会报错。


9.8 barriers:屏障的完整语义

9.8.1 三层含义

「barrier」在形态学图里有三个不同层面,很容易混:

层面 参数 影响
几何替换 primary_barrier_col 用哪条几何切分空间
是否移动空间 non_movement_barrier_col 该行是否成为 movement 节点
镶嵌上下文 _append_barrier_context_segments 屏障段是否进入缓冲段集合

9.8.2 _prepare_barriers 的稳健性处理

if geom_col and geom_col in segments.columns and geom_col != "geometry":
    barrier_series = gpd.GeoSeries(segments[geom_col], index=segments.index)
    if segments.crs is not None:
        if barrier_series.crs is None:
            barrier_series = barrier_series.set_crs(segments.crs)
        ...
情况 处理
列是 object dtype 用 gpd.GeoSeries 强制转成几何
列没有 CRS 继承主几何的 CRS
列 CRS 与主几何不同 to_crs 对齐
某行屏障几何为 None / 空 该行被丢弃(不参与屏障,但仍留在 movement 图层)

最后一条对应真实场景:桥、隧道的 barrier_geometry 可能为空。这类段照样是 movement 节点,只是不用它的几何去切空间。

9.8.3 barrier-only 段的半径裁剪

_append_barrier_context_segments 会把 barrier-only 段按 distance + clipping_buffer 的半径裁一遍再追加。裁剪依据是网络距离还是欧氏距离,取决于是否给了 center_point:

条件 裁剪方式
有 center_point + distance 网络距离(借用可达场)
没给 全部保留

这保证了「圈外的屏障不会因为离得近就混进来」——虽然屏障的目的是切分空间,但圈外的屏障对圈内镶嵌没有意义,保留只会拖慢。

9.8.4 一个完整的 barrier 配置示例

import city2graph as c2g

segments_processed = c2g.process_overture_segments(
    segments_gdf=segments,
    connectors_gdf=connectors,
    get_barriers=True,
)

segments_processed["barrier_only"] = segments_processed["subtype"].isin(["rail"])

nodes, edges = c2g.morphological_graph(
    buildings_gdf=buildings,
    segments_gdf=segments_processed,
    primary_barrier_col="barrier_geometry",
    non_movement_barrier_col="barrier_only",
    extent_buffer=60.0,
)

mv = nodes["movement"]
print("movement 里还有铁路吗:", mv["subtype"].eq("rail").any())   # False

9.9 预算与错误处理

9.9.1 预算参数的相互作用

参数组合 行为
center_point=None 不看 distance,全部数据参与
center_point 给了、distance=None 同样全部参与(无预算)
两者都给 启用网络预算 + 缓冲半径 = distance + clipping_buffer
clipping_buffer=inf 缓冲半径退化为 distance

9.9.2 三种「空结果」及处理

空的东西 检查点 处理
空路段图 segments_to_graph 返回空 后续过滤全部跳过,得到空 place / movement 图层
空镶嵌 _create_enclosed_tessellation 返回 None 或空 有 fallback 则降级,否则报错或返回空
空 faced_to _build_morphological_layers 里检测 打 warning,但继续返回

第三种最容易被忽视:faced_to 为空时函数只打一条日志,不抛错。所以拿到结果后一定要检查边数:

if len(edges[("place", "faced_to", "movement")]) == 0:
    print("警告:没有任何临街连接,检查 tolerance / extent_buffer / 街道数据")

9.9.3 异常一览

异常 触发条件 可恢复性
TypeError 输入不是 GeoDataFrame 不可恢复,改数据
ValueError: contiguity must be... 参数值错 改参数
ValueError: clipping_buffer... 参数关系错 改参数
ValueError: duplicate_edges... 参数冲突 改参数
ValueError: No objects to concatenate 镶嵌失败 用 tessellation_fallback=True
momepy 的 TopologyException 建筑几何坏 内部已修复,仍有则手工 make_valid
MemoryError 数据过大 裁剪范围 / 降采样

9.9.4 批量跑多城市时的容错模板

import warnings
from pathlib import Path

import geopandas as gpd
import pandas as pd

import city2graph as c2g

rows = []
for city_dir in sorted(Path("./cities").iterdir()):
    if not city_dir.is_dir():
        continue
    try:
        b = gpd.read_file(city_dir / "buildings.gpkg").to_crs(27700)
        s = gpd.read_file(city_dir / "segments.gpkg").to_crs(27700)
        res = c2g.morphological_graphs(
            b, s, distances=[400.0, 800.0],
            extent_buffer=60.0,
            tessellation_fallback=True,
            tessellation_n_jobs=1,
        )
        for d, (nodes, edges) in res.items():
            rows.append({
                "city": city_dir.name,
                "distance": d,
                "place": len(nodes["place"]),
                "movement": len(nodes["movement"]),
                "faced_to": len(edges[("place", "faced_to", "movement")]),
            })
    except Exception as exc:
        warnings.warn(f"{city_dir.name} 失败: {exc}")
        rows.append({"city": city_dir.name, "distance": None, "place": 0,
                     "movement": 0, "faced_to": 0, "error": str(exc)})

print(pd.DataFrame(rows))

要点:tessellation_n_jobs=1 避免外层循环与内层并行叠加;tessellation_fallback=True 让个别城市失败后仍能产出结果;except Exception 记录而不是崩溃。


9.10 多距离结果的对比分析

9.10.1 规模随距离的变化

res = c2g.morphological_graphs(
    buildings, segments, distances=[200.0, 400.0, 800.0, 1600.0],
    center_point=center, extent_buffer=60.0,
)

stats = []
for d, (nodes, edges) in sorted(res.items()):
    stats.append({
        "distance": d,
        "place": len(nodes["place"]),
        "movement": len(nodes["movement"]),
        "touched_to": len(edges[("place", "touched_to", "place")]),
        "connected_to": len(edges[("movement", "connected_to", "movement")]),
        "faced_to": len(edges[("place", "faced_to", "movement")]),
    })
import pandas as pd
print(pd.DataFrame(stats))

预期规律:

指标 随距离增长 原因
movement 近似线性 路段条数大致与半径成正比(二维网络)
place 近似平方 地块是二维分布,面积与半径平方成正比
connected_to 近似线性 与路段数同阶
faced_to 近似线性 每条路段临街若干地块,比例稳定

如果 place 的增长明显快于平方,可能是因为大距离下镶嵌把更多小地块切开;如果慢于平方,可能是边缘大量地块被过滤掉了。

9.10.2 稳定性检查

import networkx as nx
import city2graph as c2g

for d, (nodes, edges) in sorted(res.items()):
    G = c2g.gdf_to_nx(nodes, edges, directed=False)
    comps = sorted(nx.connected_components(G), key=len, reverse=True)
    print(d, "components:", len(comps), "largest:", len(comps[0]) if comps else 0)

健康的形态学图应当有 1 个明显主导的连通分量,其余是少量小孤岛。如果第二大分量占比超过 10%,说明街道网络在圈内被切断了,要查平面交叉处的端点匹配。

9.10.3 用同一份镶嵌做多距离的好处

除了省时间,还有一致性收益:不同距离的结果共享同一批地块边界,做「同一地块在 400 米与 800 米下的指标变化」这类纵向对比才有意义。若每个距离单独镶嵌,地块 ID 与形状都会变,根本没法配对。


9.11 as_nx 与 duplicate_edges 在批量模式下的行为

9.11.1 as_nx 的默认值差异

函数 as_nx 默认
morphological_graph None
morphological_graphs False

morphological_graphs 的默认是显式 False(而非 None),所以不传时不会触发 DeprecationWarning。这算是对批量场景的一个小照顾——批量调用通常不需要图对象。

res = c2g.morphological_graphs(b, s, [400.0], as_nx=True)
G = res[400.0]
print(type(G).__name__)   # Graph

9.11.2 duplicate_edges 在批量下的处理

批量模式下,duplicate_edges 是在每个距离的 _graph_for_distance 末尾执行的,所以每个距离的边表都带反向行:

res = c2g.morphological_graphs(b, s, [400.0, 800.0], duplicate_edges=True)
for d, (nodes, edges) in res.items():
    touched = edges[("place", "touched_to", "place")]
    print(d, len(touched))

仍然受 as_nx 互斥约束:传 as_nx=True + duplicate_edges=True 会在参数校验阶段抛错。

9.11.3 内存提醒

duplicate_edges=True 且距离列表很长时,内存会快速上升——每个距离都保存一份带反向行的完整边表。如果只需要最终某个距离,考虑逐个算而不是批量。


9.12 性能与内存

9.12.1 批量 vs 逐个:实测对比

import time

import city2graph as c2g

distances = [400.0, 800.0, 1200.0]

t0 = time.perf_counter()
batch = c2g.morphological_graphs(buildings, segments, distances=distances, center_point=center)
t_batch = time.perf_counter() - t0

t0 = time.perf_counter()
single = {
    d: c2g.morphological_graph(buildings, segments, center_point=center, distance=d)
    for d in distances
}
t_single = time.perf_counter() - t0

print(f"batch={t_batch:.1f}s  single={t_single:.1f}s  speedup={t_single / t_batch:.2f}x")

经验值:

距离个数 批量相对逐一的加速
2 1.3–1.6×
3 1.8–2.2×
5 2.5–3.5×

加速比趋近于「距离个数」,但达不到,因为过滤段本身也占时间。

9.12.2 内存峰值

批量模式的内存峰值大致是「一份镶嵌 + 一个距离的完整图层」,再乘以距离个数(因为 dict 里保存了每个距离的结果)。压缩办法:

import gc

res = c2g.morphological_graphs(buildings, segments, [400.0, 800.0, 1200.0])

summary = {}
for d, (nodes, edges) in res.items():
    summary[d] = {
        "place": len(nodes["place"]),
        "movement": len(nodes["movement"]),
        "faced_to": len(edges[("place", "faced_to", "movement")]),
    }
res = None
gc.collect()
print(summary)

9.12.3 镶嵌并行的嵌套陷阱

批量模式下,morphological_graphs 内部只建一次镶嵌,所以 tessellation_n_jobs 的影响被摊薄。但如果外层自己还有并行(例如 joblib 跑多个城市),务必把 tessellation_n_jobs=1:

from joblib import Parallel, delayed

def build_one(city_dir):
    b = gpd.read_file(city_dir / "buildings.gpkg")
    s = gpd.read_file(city_dir / "segments.gpkg")
    return c2g.morphological_graphs(b, s, [400.0, 800.0], tessellation_n_jobs=1)

results = Parallel(n_jobs=4)(delayed(build_one)(p) for p in city_dirs)

嵌套并行的典型后果是线程数爆炸(4 × n_jobs)导致上下文切换开销超过收益。

9.12.4 只算需要的距离

批量模式最省时的用法不是「一次算很多距离」,而是「一次算你真正需要的两三个距离」。经验上:

研究目的 推荐距离
街区尺度形态学 200 / 400
社区尺度 400 / 800
城区尺度 800 / 1600

距离间隔太小(如 390 / 400 / 410)没有意义,地块分布不会显著变化,只是浪费计算。


9.12.5 分块并行:把距离与空间切分组合起来

当研究范围覆盖整座城市、距离列表又长时,单机串行的瓶颈会落在镶嵌上。一个可行策略是按空间分块,块内共享上下文:

import geopandas as gpd
from shapely.geometry import box

import city2graph as c2g

def tiles(bbox, step):
    minx, miny, maxx, maxy = bbox
    x = minx
    while x < maxx:
        y = miny
        while y < maxy:
            yield box(x, y, x + step, y + step)
            y += step
        x += step

results = []
for tile in tiles(buildings.total_bounds, 2000):
    b = buildings[buildings.intersects(tile)]
    s = segments[segments.intersects(tile)]
    if b.empty or s.empty:
        continue
    center = gpd.GeoSeries([tile.centroid], crs=buildings.crs)
    res = c2g.morphological_graphs(
        b, s, distances=[400.0, 800.0],
        center_point=center, clipping_buffer=200.0, tessellation_n_jobs=1,
    )
    results.append((tile, res))
print("块数:", len(results))

分块的代价是边界不连续:相邻块分别镶嵌,边界处的地块会被切开。补偿办法是让相邻块重叠一个 clipping_buffer 的宽度,并在合并结果时按中心点去重:

| 做法 | 效果 | | — | — | | 块间无重叠 | 边界处地块被切断,指标偏低 | | 重叠一个 clipping_buffer | 边界地块有完整上下文,可只保留块中心附近的单元 | | 只保留质心落在块内的单元 | 保证每个地块只归属一个块 |

def keep_core_cells(nodes, tile):
    place = nodes["place"]
    inside = place.geometry.within(tile)
    return {**nodes, "place": place.loc[inside]}

9.13 完整实战:利物浦多尺度形态学

import geopandas as gpd
import pandas as pd
from shapely import Point

import city2graph as c2g

c2g.load_overture_data(
    place_name="Liverpool, UK",
    types=["building", "segment", "connector"],
    output_dir="./data/overture",
    prefix="liv_",
)
buildings = gpd.read_file("./data/overture/liv_building.geojson").to_crs(27700)
segments = gpd.read_file("./data/overture/liv_segment.geojson").to_crs(27700)
connectors = gpd.read_file("./data/overture/liv_connector.geojson").to_crs(27700)

segments_p = c2g.process_overture_segments(
    segments_gdf=segments,
    connectors_gdf=connectors,
    get_barriers=True,
)

center = gpd.GeoSeries([Point(-2.9879, 53.4062)], crs="EPSG:4326").to_crs(27700)

res = c2g.morphological_graphs(
    buildings_gdf=buildings,
    segments_gdf=segments_p,
    distances=[400.0, 800.0, 1200.0],
    center_point=center,
    clipping_buffer=200.0,
    extent_buffer=60.0,
    primary_barrier_col="barrier_geometry",
    contiguity="queen",
    keep_buildings=True,
    tessellation_fallback=True,
)

rows = []
for d, (nodes, edges) in sorted(res.items()):
    place = nodes["place"]
    area = place["tessellation_geometry"].area
    rows.append({
        "distance": d,
        "place": len(place),
        "movement": len(nodes["movement"]),
        "touched": len(edges[("place", "touched_to", "place")]),
        "connected": len(edges[("movement", "connected_to", "movement")]),
        "faced": len(edges[("place", "faced_to", "movement")]),
        "cell_median_m2": round(area.median(), 1),
        "fallback_ratio": round(
            place.index.astype(str).str.startswith("fallback_").mean(), 3
        ),
    })

print(pd.DataFrame(rows).to_string(index=False))

9.13.1 输出解读

列 健康范围 异常含义
place 随距离增长 不增长:中心点周围无建筑或全被过滤
movement 随距离增长 不增长:街道数据缺失
touched 与 place 同阶 远小于 place:地块过于分散
connected 约为 movement 的 1.5 倍 为 0:街道段端点不匹配
faced 约为 place 的 1~2 倍 远小于 place:tolerance 太小
cell_median_m2 城区 100–2000 过大:屏障不全;过小:建筑过密
fallback_ratio 小于 0.05 过高:镶嵌失效

9.13.2 导出为 PyG

nodes_800, edges_800 = res[800.0]
nodes_800["place"]["cell_area"] = nodes_800["place"]["tessellation_geometry"].area

data_800 = c2g.gdf_to_pyg(
    nodes_800, edges_800,
    node_feature_cols={"place": ["cell_area"], "movement": ["length"]},
)
print(data_800.node_types)
print(data_800.edge_types)

9.14 日志、诊断与可复现性

9.14.1 该打开哪些日志

形态学模块用的是标准库 logging,模块级 logger 名字是 city2graph.morphology。默认情况下 warning 以上会打印到 stderr,info 级别需要自己配置:

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("city2graph.morphology")
logger.setLevel(logging.DEBUG)

排查时值得关注的日志点:

日志点 级别 含义
Column 'enclosure_index' not found warning 镶嵌结果缺分组列,相邻边不做围合内过滤
No place to movement connections found warning faced_to 完全为空,检查 tolerance
Removed N geometries with invalid types warning 输入几何被过滤,行数变少
Graph has no edges(经 validate_nx) error 转图时发现空边表
镶嵌异常栈 exception momepy 内部错误,通常是几何问题

9.14.2 一个可复用的诊断函数

import logging

import pandas as pd

logger = logging.getLogger("city2graph.morphology")

def diagnose(res, building_count=None, segment_count=None):
    rows = []
    for d, item in sorted(res.items()):
        if isinstance(item, tuple):
            nodes, edges = item
        else:
            continue
        place = nodes.get("place")
        mv = nodes.get("movement")
        faced = edges.get(("place", "faced_to", "movement"))
        row = {
            "distance": d,
            "place": len(place) if place is not None else 0,
            "movement": len(mv) if mv is not None else 0,
            "faced_to": len(faced) if faced is not None else 0,
        }
        if place is not None and not place.empty:
            area = place["tessellation_geometry"].area
            row["cell_median"] = round(float(area.median()), 1)
            row["fallback"] = float(
                place.index.astype(str).str.startswith("fallback_").mean()
            )
            row["faced_per_place"] = row["faced_to"] / max(row["place"], 1)
        rows.append(row)
        logger.info("distance=%s place=%d movement=%d", d, row["place"], row["movement"])
    df = pd.DataFrame(rows).sort_values("distance")
    print(df.to_string(index=False))
    return df

判读规则:

指标 判据 处置
faced_per_place 小于 0.5 放大 tolerance 或 extent_buffer
fallback 大于 0.2 检查屏障数据
cell_median 大于 5000 屏障不全,地块没切开
cell_median 小于 20 建筑过密或数据异常
movement 为 0 — 街道数据缺失或全被过滤

9.14.3 可复现性清单

同样的输入在不同机器上跑出不同结果,通常来自四处:

来源 控制方法
镶嵌并行度 固定 tessellation_n_jobs=1
依赖版本 锁 momepy / geopandas / shapely 版本
输入行顺序 建图前 sort_index()
CRS 转换路径 统一在入口处一次 to_crs,不要在流程中间来回转
import geopandas as gpd

def freeze_inputs(buildings, segments):
    b = buildings.sort_index().to_crs(27700)
    s = segments.sort_index().to_crs(27700)
    return b, s

b_frozen, s_frozen = freeze_inputs(buildings, segments_raw)
res_a = c2g.morphological_graphs(b_frozen, s_frozen, [400.0, 800.0], tessellation_n_jobs=1)
res_b = c2g.morphological_graphs(b_frozen, s_frozen, [400.0, 800.0], tessellation_n_jobs=1)
print("place 数一致:", len(res_a[400.0][0]["place"]) == len(res_b[400.0][0]["place"]))

9.14.4 把结果固化成快照

研究项目里建议把每个距离的关键统计量落盘,方便回归对比:

import json
from pathlib import Path

snapshot = {}
for d, (nodes, edges) in c2g.morphological_graphs(b_frozen, s_frozen, [400.0]).items():
    snapshot[str(d)] = {
        "place": len(nodes["place"]),
        "movement": len(nodes["movement"]),
        "faced_to": len(edges[("place", "faced_to", "movement")]),
        "cell_area_median": float(nodes["place"]["tessellation_geometry"].area.median()),
    }

Path("snapshots").mkdir(exist_ok=True)
Path("snapshots/morphology_400.json").write_text(
    json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8"
)

这样下次换数据或升级依赖后,一条 diff 就能看出指标有没有漂移。


9.14.5 最小可复现脚本

把一个距离的完整构建写成可重跑的函数,是排查问题最快的办法:

from pathlib import Path

import geopandas as gpd

import city2graph as c2g


def run_one(distance, data_dir="./data/overture", crs=27700):
    buildings = gpd.read_file(Path(data_dir) / "liv_building.geojson").to_crs(crs)
    segments = gpd.read_file(Path(data_dir) / "liv_segment.geojson").to_crs(crs)
    connectors = gpd.read_file(Path(data_dir) / "liv_connector.geojson").to_crs(crs)

    processed = c2g.process_overture_segments(
        segments_gdf=segments, connectors_gdf=connectors, get_barriers=True
    )
    return c2g.morphological_graph(
        buildings_gdf=buildings,
        segments_gdf=processed,
        distance=distance,
        extent_buffer=60.0,
        primary_barrier_col="barrier_geometry",
        tessellation_n_jobs=1,
    )


nodes_a, edges_a = run_one(800.0)
nodes_b, edges_b = run_one(800.0)
print(len(nodes_a["place"]) == len(nodes_b["place"]))   # True:结果可复现

固定 tessellation_n_jobs=1、固定输入排序、固定 CRS,就能把「同一代码不同结果」的问题压缩到依赖版本这一项上。


9.15 常见错误与排查

现象 原因 修复
distances 为空报错 传了 [] 至少给一个距离
各距离结果完全相同 忘了传 center_point 补中心点
小距离结果反而比大距离大 混淆了 distance 与 clipping_buffer 检查参数顺序
批量比逐个还慢 只有 2 个距离 / 镶嵌不是瓶颈 改为逐个或减少距离数
内存爆掉 duplicate_edges=True × 多距离 关掉反向行或逐个算
fallback 比例很高 屏障数据缺失或几何错误 检查 barrier_geometry
边缘地块形状怪异 clipping_buffer 太小 放大到 extent_buffer 的 2–3 倍
各距离的 place_id 无法对齐 每个距离单独镶嵌 确认没被逐个调用覆盖
as_nx 警告刷屏 显式传了 as_nx 改用 gdf_to_nx

9.16 小结

  • morphological_graphs 的核心是「一次镶嵌、多距离复用」,代价是边缘地块形状与逐距离调用略有差异。
  • 流水线分五段:_prepare_morphology(共享上下文)→ 一次镶嵌 → _segments_for_distance(按距离筛段)→ _create_and_filter_tessellation(四道过滤)→ _build_morphological_layers(拼三层边)。
  • _prepare_morphology 只复制一次外部输入,之后全流程操作自己拥有的帧;CRS 以 buildings 为参照,segments 被对齐。
  • 共享 field(可达场)、segment_graph(路段图)、buffer_graph(缓冲图)是批量性能的来源,也是「所有节点类型用同一度量」的正确性保证。
  • 可达段与缓冲段分工明确:缓冲段只用于镶嵌上下文,保留判定只看可达段。
  • 三种降级:include_unenclosed_buildings(补漏)、tessellation_fallback(整体失败)、_building_fallback_cells(单栋兜底)。
  • barrier 有三个层面:几何替换、是否移动空间、镶嵌上下文;primary_barrier_col 与 non_movement_barrier_col 正交。
  • duplicate_edges 只对称化同类型无向边,faced_to 永不补反向行;批量模式下每个距离各自对称化。
  • 性能上,批量对 3 个距离通常有 2 倍左右加速;嵌套并行时务必 tessellation_n_jobs=1。

练习

  1. 用同一份数据分别调用 morphological_graphs([400, 800]) 与两次 morphological_graph,比较 place 数差异并解释边缘效应。
  2. 把 clipping_buffer 从 100 改到 500,观察 400 米结果的 place 数变化。
  3. 打开 tessellation_fallback=True,构造一个屏障几何全部为空的场景,检查 fallback 比例。
  4. 用 non_movement_barrier_col 把铁路标为只作屏障,比较 movement 数与 place 数变化。

下一章从「面 + 线」转到纯线性的街道网络:segments_to_graph 如何把物理路段展开成有向边、oneway_col 的取值表、directed 与 connectivity 的配合,以及它与 OSMnx graph_from_gdf 的差异。